Passed
Push — master ( 1722f6...6db377 )
by Adrien
13:35
created

EventCompleter::removeSensitiveData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 10
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Log;
6
7
use Ecodev\Felix\Model\CurrentUser;
8
use Laminas\Log\Processor\ProcessorInterface;
9
10
class EventCompleter implements ProcessorInterface
11
{
12 5
    public function __construct(private readonly string $baseUrl)
13
    {
14 5
    }
15
16
    /**
17
     * Complete a log event with extra data, including stacktrace and any global stuff relevant to the app.
18
     */
19 4
    public function process(array $event): array
20
    {
21 4
        $envData = $this->getEnvData();
22 4
        $event = array_merge($event, $envData);
23
24
        // If we are logging PHP errors, then we include all known information in message
25 4
        if ($event['extra']['errno'] ?? false) {
26 1
            $event['message'] .= "\nStacktrace:\n" . $this->getStacktrace();
27
        }
28
29
        // Security hide clear text password
30 4
        unset($event['extra']['password']);
31
32 4
        return $event;
33
    }
34
35
    /**
36
     * Retrieve dynamic information from environment to be logged.
37
     */
38 4
    private function getEnvData(): array
39
    {
40 4
        $user = CurrentUser::get();
41
42 4
        if (PHP_SAPI === 'cli') {
43
            global $argv;
44 4
            $ip = !empty(getenv('REMOTE_ADDR')) ? getenv('REMOTE_ADDR') : 'script';
45 4
            $url = implode(' ', $argv);
46 4
            $referer = '';
47
        } else {
48
            $ip = $_SERVER['REMOTE_ADDR'] ?? '';
49
            $url = $this->baseUrl . $_SERVER['REQUEST_URI'];
50
            $referer = $_SERVER['HTTP_REFERER'] ?? '';
51
        }
52
53 4
        $request = $_REQUEST;
54 4
        $request = $this->redactSensitiveData($request);
55
56 4
        $envData = [
57 4
            'creator_id' => $user?->getId(),
58 4
            'login' => $user?->getLogin(),
59 4
            'url' => $url,
60 4
            'referer' => $referer,
61 4
            'request' => json_encode($request, JSON_PRETTY_PRINT),
62 4
            'ip' => $ip,
63 4
        ];
64
65 4
        return $envData;
66
    }
67
68
    /**
69
     * Redact sensitive values from the entire data structure.
70
     */
71 4
    private function redactSensitiveData(array $request): array
72
    {
73 4
        foreach ($request as $key => &$value) {
74 2
            if (in_array($key, [
75 2
                'password',
76 2
                'passwordConfirmation',
77 2
                'password_rep',
78 2
                'cpass',
79 2
                'npass1',
80 2
                'npass2',
81 2
                'password',
82 2
            ], true)) {
83 1
                $value = '***REDACTED***';
84 2
            } elseif (is_array($value)) {
85 1
                $value = $this->redactSensitiveData($value);
86
            }
87
        }
88
89 4
        return $request;
90
    }
91
92
    /**
93
     * Returns the backtrace excluding the most recent calls to this function, so we only get the interesting parts.
94
     */
95 1
    private function getStacktrace(): string
96
    {
97 1
        ob_start();
98 1
        @debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
99 1
        $trace = ob_get_contents();
100 1
        ob_end_clean();
101
102 1
        if ($trace === false) {
103
            return 'Could not get stacktrace';
104
        }
105
106
        // Remove first items from backtrace as it's this function and previous logging functions which is not interesting
107 1
        $shortenTrace = preg_replace('/^#[0-4]\s+[^\n]*\n/m', '', $trace);
108
109 1
        if ($shortenTrace === null) {
110
            return $trace;
111
        }
112
113
        // Renumber backtrace items.
114 1
        $renumberedTrace = preg_replace_callback('/^#(\d+)/m', fn ($matches) => '#' . ((int) $matches[1] - 5), $shortenTrace);
115
116 1
        if ($renumberedTrace === null) {
117
            return $shortenTrace;
118
        }
119
120 1
        return $renumberedTrace;
121
    }
122
}
123