• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

avoutic / web-framework / 45418632783

24 Nov 2026 02:47PM UTC coverage: 69.305% (-4.3%) from 73.637%
45418632783

push

github

avoutic
Mark the config_values table as deprecated

2872 of 4144 relevant lines covered (69.31%)

2.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.57
/src/Diagnostics/DebugService.php
1
<?php
2

3
/*
4
 * This file is part of WebFramework.
5
 *
6
 * (c) Avoutic <avoutic@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
namespace WebFramework\Diagnostics;
13

14
use Psr\Http\Message\ServerRequestInterface as Request;
15
use Psr\Log\LoggerInterface;
16
use Slim\Routing\RouteContext;
17
use WebFramework\Core\RuntimeEnvironment;
18
use WebFramework\Database\Database;
19
use WebFramework\Database\DatabaseProvider;
20
use WebFramework\Security\AuthenticationService;
21
use WebFramework\Support\ErrorReport;
22
use WebFramework\Support\Helpers;
23

24
/**
25
 * Class DebugService.
26
 *
27
 * Provides debugging and error reporting functionality for the application.
28
 */
29
class DebugService
30
{
31
    /** The value that replaces scrubbed content in a report */
32
    public const SCRUBBED = 'scrubbed';
33

34
    /** Request headers whose name contains one of these (case-insensitive) are scrubbed */
35
    public const DEFAULT_SCRUB_HEADERS = ['authorization', 'cookie', 'token', 'secret', 'key'];
36

37
    /** Inputs whose key contains one of these (case-insensitive) are scrubbed */
38
    public const DEFAULT_SCRUB_INPUTS = ['password', 'passwd', 'secret', 'token', 'authorization', 'code'];
39

40
    /** Server params that are reported, all others are left out */
41
    public const DEFAULT_SERVER_PARAMS = [
42
        'REQUEST_METHOD',
43
        'REQUEST_URI',
44
        'QUERY_STRING',
45
        'REQUEST_SCHEME',
46
        'SERVER_PROTOCOL',
47
        'HTTPS',
48
        'SERVER_NAME',
49
        'SERVER_PORT',
50
        'HTTP_HOST',
51
        'REMOTE_ADDR',
52
        'HTTP_X_FORWARDED_FOR',
53
        'HTTP_USER_AGENT',
54
        'HTTP_REFERER',
55
        'HTTP_ACCEPT',
56
        'HTTP_ACCEPT_LANGUAGE',
57
        'CONTENT_TYPE',
58
        'CONTENT_LENGTH',
59
        'REQUEST_TIME',
60
    ];
61

62
    /** @var array<string> */
63
    private array $scrubHeaders = self::DEFAULT_SCRUB_HEADERS;
64

65
    /** @var array<string> */
66
    private array $scrubInputs = self::DEFAULT_SCRUB_INPUTS;
67

68
    /** @var array<string> */
69
    private array $serverParams = self::DEFAULT_SERVER_PARAMS;
70

71
    /**
72
     * DebugService constructor.
73
     *
74
     * @param AuthenticationService $authenticationService Service for handling authentication
75
     * @param DatabaseProvider      $databaseProvider      Provider for database access
76
     * @param LoggerInterface       $logger                The logger
77
     * @param ReportFunction        $reportFunction        Function for reporting errors
78
     * @param RuntimeEnvironment    $runtimeEnvironment    Runtime environment information
79
     * @param null|array<string>    $scrubHeaders          Parts of header names to scrub (null for the defaults)
80
     * @param null|array<string>    $scrubInputs           Parts of input keys to scrub (null for the defaults)
81
     * @param null|array<string>    $serverParams          Server params to report (null for the defaults)
82
     */
83
    public function __construct(
6 ✔
84
        private AuthenticationService $authenticationService,
85
        private DatabaseProvider $databaseProvider,
86
        private LoggerInterface $logger,
87
        private ReportFunction $reportFunction,
88
        private RuntimeEnvironment $runtimeEnvironment,
89
        ?array $scrubHeaders = null,
90
        ?array $scrubInputs = null,
91
        ?array $serverParams = null,
92
    ) {
93
        $this->scrubHeaders = $scrubHeaders ?? self::DEFAULT_SCRUB_HEADERS;
6 ✔
94
        $this->scrubInputs = $scrubInputs ?? self::DEFAULT_SCRUB_INPUTS;
6 ✔
95
        $this->serverParams = $serverParams ?? self::DEFAULT_SERVER_PARAMS;
6 ✔
96
    }
97

98
    /**
99
     * Report an error.
100
     *
101
     * This never throws. A failure to report is logged.
102
     *
103
     * @param string       $message   The error message
104
     * @param array<mixed> $stack     The error stack trace
105
     * @param null|Request $request   The request object, if available
106
     * @param string       $errorType The type of error
107
     */
108
    public function reportError(string $message, array $stack = [], ?Request $request = null, string $errorType = 'report_error'): void
3 ✔
109
    {
110
        try
111
        {
112
            $errorReport = $this->getErrorReport($stack, $request, $errorType, $message);
3 ✔
113

114
            $this->reportFunction->report($message, $errorType, $errorReport);
3 ✔
115
        }
116
        catch (\Throwable $reportError)
2 ✔
117
        {
118
            $this->logReportFailure($reportError, $message);
2 ✔
119
        }
120
    }
121

122
    /**
123
     * Report an exception.
124
     *
125
     * This never throws. A failure to report is logged.
126
     *
127
     * @param \Throwable   $e       The Throwable object
128
     * @param null|Request $request The request object, if available
129
     */
130
    public function reportException(\Throwable $e, ?Request $request = null): void
1 ✔
131
    {
132
        try
133
        {
134
            $errorReport = $this->getThrowableReport($e, $request);
1 ✔
135

136
            $this->reportFunction->report($e->getMessage(), $e::class, $errorReport);
1 ✔
137
        }
138
        catch (\Throwable $reportError)
1 ✔
139
        {
140
            $this->logReportFailure($reportError, $e->getMessage());
1 ✔
141
        }
142
    }
143

144
    /**
145
     * Log that an error could not be reported. Reporting an error must never cause a new one.
146
     *
147
     * @param \Throwable $reportError The exception thrown while reporting
148
     * @param string     $message     The message of the error that was being reported
149
     */
150
    private function logReportFailure(\Throwable $reportError, string $message): void
3 ✔
151
    {
152
        try
153
        {
154
            $this->logger->error('Failed to report error', [
3 ✔
155
                'reason' => $reportError->getMessage(),
3 ✔
156
                'error' => $message,
3 ✔
157
            ]);
3 ✔
158
        }
159
        catch (\Throwable $loggingError)
1 ✔
160
        {
161
            // Nothing left to tell it to
162
        }
163
    }
164

165
    /**
166
     * Get a report for a Throwable.
167
     *
168
     * @param \Throwable   $e       The Throwable object
169
     * @param null|Request $request The request object, if available
170
     *
171
     * @return ErrorReport The error report
172
     */
173
    public function getThrowableReport(\Throwable $e, ?Request $request = null): ErrorReport
1 ✔
174
    {
175
        $stack = $this->filterTrace($e->getTrace());
1 ✔
176

177
        $file = $e->getFile();
1 ✔
178
        $line = $e->getLine();
1 ✔
179
        $errorType = $e::class;
1 ✔
180
        $message = $e->getMessage();
1 ✔
181

182
        return $this->getReport($file, $line, $stack, $request, $errorType, $message);
1 ✔
183
    }
184

185
    /**
186
     * Get an error report from a stack trace.
187
     *
188
     * @param array<mixed> $trace     The stack trace
189
     * @param null|Request $request   The request object, if available
190
     * @param string       $errorType The type of error
191
     * @param string       $message   The error message
192
     *
193
     * @return ErrorReport The error report
194
     */
195
    public function getErrorReport(array $trace, ?Request $request, string $errorType, string $message): ErrorReport
3 ✔
196
    {
197
        $stack = $this->filterTrace($trace);
3 ✔
198
        $stackTop = reset($stack);
3 ✔
199

200
        $file = ($stackTop) ? $stackTop['file'] : 'unknown';
3 ✔
201
        $line = ($stackTop) ? $stackTop['line'] : 0;
3 ✔
202

203
        return $this->getReport($file, $line, $stack, $request, $errorType, $message);
3 ✔
204
    }
205

206
    /**
207
     * Generate a detailed error report.
208
     *
209
     * @param string       $file          The file where the error occurred
210
     * @param int          $line          The line number where the error occurred
211
     * @param array<mixed> $filteredStack The filtered stack trace
212
     * @param null|Request $request       The request object, if available
213
     * @param string       $errorType     The type of error
214
     * @param string       $message       The error message
215
     *
216
     * @return ErrorReport The detailed error report
217
     */
218
    private function getReport(string $file, int $line, array $filteredStack, ?Request $request, string $errorType, string $message): ErrorReport
4 ✔
219
    {
220
        $report = new ErrorReport();
4 ✔
221

222
        $report->message = $message;
4 ✔
223

224
        // Retrieve request
225
        //
226
        if ($request !== null)
4 ✔
227
        {
228
            try
229
            {
230
                $routeContext = RouteContext::fromRequest($request);
1 ✔
231
                $route = $routeContext->getRoute();
×
232

233
                // Use route name as base source
234
                //
235
                if (!empty($route))
×
236
                {
237
                    $requestMethod = $request->getMethod();
×
238

239
                    $report->requestSource = $requestMethod.' '.$route->getPattern();
×
240
                }
241
            }
242
            catch (\RuntimeException $e)
1 ✔
243
            {
244
            }
245

246
            // Fallback to direct method
247
            //
248
            if ($report->requestSource === 'unknown')
1 ✔
249
            {
250
                $requestMethod = $request->getMethod();
1 ✔
251

252
                $uri = $request->getUri();
1 ✔
253

254
                $report->requestSource = $requestMethod.' '.$uri->getPath();
1 ✔
255
            }
256
        }
257

258
        $report->serverName = $this->runtimeEnvironment->getServerName();
4 ✔
259
        $report->file = $file;
4 ✔
260
        $report->line = $line;
4 ✔
261

262
        $report->errorType = Helpers::getErrorTypeString($errorType);
4 ✔
263
        $report->stack = $this->condenseStack($filteredStack);
4 ✔
264
        $report->dbError = $this->getDatabaseError($this->databaseProvider->get());
4 ✔
265
        $report->auth = $this->getAuthenticationStatus();
4 ✔
266

267
        if ($request !== null)
4 ✔
268
        {
269
            $report->inputs = $this->getInputsReport($request);
1 ✔
270

271
            $headers = $request->getHeaders();
1 ✔
272
            $report->headers = $this->scrubRequestHeaders($headers);
1 ✔
273

274
            $report->serverParams = $this->scrubServerParams($request->getServerParams());
1 ✔
275
        }
276

277
        return $report;
4 ✔
278
    }
279

280
    /**
281
     * Filter a stack trace.
282
     *
283
     * @param array<array<mixed>> $trace        The original stack trace
284
     * @param bool                $skipInternal Whether to skip internal frames
285
     * @param bool                $scrubState   Whether to scrub sensitive state information
286
     *
287
     * @return array<array<mixed>> The filtered stack trace
288
     */
289
    public function filterTrace(array $trace, bool $skipInternal = true, bool $scrubState = true): array
8 ✔
290
    {
291
        $stack = [];
8 ✔
292
        $skipping = $skipInternal;
8 ✔
293

294
        foreach ($trace as $entry)
8 ✔
295
        {
296
            if ($skipping && isset($entry['class'])
6 ✔
297
                && $entry['class'] === 'DebugService')
6 ✔
298
            {
299
                continue;
3 ✔
300
            }
301

302
            $skipping = false;
6 ✔
303

304
            if ($scrubState)
6 ✔
305
            {
306
                if (isset($entry['args']))
3 ✔
307
                {
308
                    Helpers::scrubState($entry['args']);
2 ✔
309
                }
310
            }
311

312
            $stack[] = $entry;
6 ✔
313
        }
314

315
        return $stack;
8 ✔
316
    }
317

318
    /**
319
     * Condense a stack trace into a shorter representation.
320
     *
321
     * @param array<array<mixed>> $stack The stack trace to condense
322
     *
323
     * @return array<string> The condensed stack trace
324
     */
325
    public function condenseStack(array $stack): array
5 ✔
326
    {
327
        $appDir = $this->runtimeEnvironment->getAppDir();
5 ✔
328

329
        $stackCondensed = [];
5 ✔
330

331
        foreach ($stack as $entry)
5 ✔
332
        {
333
            $file = $entry['file'] ?? 'unknown';
3 ✔
334

335
            if (str_starts_with($file, $appDir))
3 ✔
336
            {
337
                $file = substr($file, strlen($appDir));
3 ✔
338
            }
339

340
            $line = $entry['line'] ?? '-';
3 ✔
341

342
            $function = '';
3 ✔
343
            if (isset($entry['class']))
3 ✔
344
            {
345
                $pattern = '/@anonymous.*/';
3 ✔
346
                $replacement = '@anonymous';
3 ✔
347
                $class = preg_replace($pattern, $replacement, $entry['class']);
3 ✔
348
                $function .= $class.$entry['type'];
3 ✔
349
            }
350

351
            $function = $function.$entry['function'].'()';
3 ✔
352

353
            $stackCondensed[] = "{$function} ({$file}:{$line})";
3 ✔
354
        }
355

356
        return $stackCondensed;
5 ✔
357
    }
358

359
    /**
360
     * Get the last database error.
361
     *
362
     * @param null|Database $database The database object
363
     *
364
     * @return string The last database error or 'None' if no error
365
     */
366
    public function getDatabaseError(?Database $database): string
7 ✔
367
    {
368
        if ($database === null)
7 ✔
369
        {
370
            return 'Not initialized yet';
4 ✔
371
        }
372

373
        $dbError = $database->getLastError();
3 ✔
374

375
        if (strlen($dbError))
3 ✔
376
        {
377
            return $dbError;
2 ✔
378
        }
379

380
        return 'None';
1 ✔
381
    }
382

383
    /**
384
     * Get the current authentication status.
385
     *
386
     * @return null|array{user_id: int, username: string, email: string} The authentication status
387
     */
388
    public function getAuthenticationStatus(): ?array
6 ✔
389
    {
390
        if (!$this->authenticationService->isAuthenticated())
6 ✔
391
        {
392
            return null;
4 ✔
393
        }
394

395
        $user = $this->authenticationService->getAuthenticatedUser();
2 ✔
396

397
        return [
2 ✔
398
            'user_id' => $user->getId(),
2 ✔
399
            'username' => $user->getUsername(),
2 ✔
400
            'email' => $user->getEmail(),
2 ✔
401
        ];
2 ✔
402
    }
403

404
    /**
405
     * Get a report of the request inputs.
406
     *
407
     * @param Request $request The request object
408
     *
409
     * @return array<string, mixed>
410
     */
411
    public function getInputsReport(Request $request): array
7 ✔
412
    {
413
        $inputs = [];
7 ✔
414

415
        // Get the GET parameters
416
        //
417
        $getParams = $request->getQueryParams();
7 ✔
418

419
        if (count($getParams))
7 ✔
420
        {
421
            $inputs['get'] = $this->scrubInputs($getParams);
2 ✔
422
        }
423

424
        // Check if the Content-Type header indicates JSON data
425
        //
426
        $contentType = $request->getHeaderLine('Content-Type');
7 ✔
427
        $isJsonData = str_contains($contentType, 'application/json');
7 ✔
428

429
        if ($isJsonData)
7 ✔
430
        {
431
            // Get the message body as a string
432
            //
433
            $body = (string) $request->getBody();
3 ✔
434

435
            // Parse the JSON content
436
            //
437
            $jsonData = json_decode($body, true);
3 ✔
438

439
            if ($jsonData === null && json_last_error() !== JSON_ERROR_NONE)
3 ✔
440
            {
441
                // The raw body cannot be scrubbed by key, so only report its size
442
                //
443
                $inputs['json_parsing_failed'] = 'Unparseable body of '.strlen($body).' bytes';
1 ✔
444
            }
445
            else
446
            {
447
                $inputs['json_data'] = is_array($jsonData) ? $this->scrubInputs($jsonData) : $jsonData;
2 ✔
448
            }
449
        }
450

451
        // Check if parsed body data is available
452
        //
453
        $postParams = $request->getParsedBody();
7 ✔
454
        if ($postParams !== null)
7 ✔
455
        {
456
            $inputs['post'] = is_array($postParams) ? $this->scrubInputs($postParams) : self::SCRUBBED;
2 ✔
457
        }
458

459
        return $inputs;
7 ✔
460
    }
461

462
    /**
463
     * Scrub sensitive information from request headers.
464
     *
465
     * The value of a header whose name contains one of the configured parts is replaced,
466
     * so the report still shows the header was sent. Query parameters in a Referer are
467
     * scrubbed like inputs.
468
     *
469
     * @param array<array<mixed>> $headers The original headers
470
     *
471
     * @return array<array<mixed>> The scrubbed headers
472
     */
473
    public function scrubRequestHeaders(array $headers): array
3 ✔
474
    {
475
        foreach ($headers as $name => $values)
3 ✔
476
        {
477
            $name = (string) $name;
3 ✔
478

479
            if ($this->containsAny($name, $this->scrubHeaders))
3 ✔
480
            {
481
                $headers[$name] = [self::SCRUBBED];
2 ✔
482

483
                continue;
2 ✔
484
            }
485

486
            if (strtolower($name) === 'referer')
3 ✔
487
            {
488
                $headers[$name] = array_map(fn ($value) => is_string($value) ? $this->scrubUrl($value) : $value, $values);
1 ✔
489
            }
490
        }
491

492
        return $headers;
3 ✔
493
    }
494

495
    /**
496
     * Scrub sensitive information from request inputs.
497
     *
498
     * The value of an input whose key contains one of the configured parts is replaced,
499
     * at any depth, so the report still shows the input was sent.
500
     *
501
     * @param array<mixed> $inputs The original inputs
502
     *
503
     * @return array<mixed> The scrubbed inputs
504
     */
505
    public function scrubInputs(array $inputs): array
8 ✔
506
    {
507
        foreach ($inputs as $key => $value)
8 ✔
508
        {
509
            if (is_string($key) && $this->containsAny($key, $this->scrubInputs))
8 ✔
510
            {
511
                $inputs[$key] = self::SCRUBBED;
5 ✔
512
            }
513
            elseif (is_array($value))
8 ✔
514
            {
515
                $inputs[$key] = $this->scrubInputs($value);
2 ✔
516
            }
517
        }
518

519
        return $inputs;
8 ✔
520
    }
521

522
    /**
523
     * Reduce the server params to the ones that are allowed in a report.
524
     *
525
     * Server params can hold credentials and the environment of the process, under names
526
     * that cannot be known in advance. So only the configured params are kept. Query
527
     * parameters in the kept URLs are scrubbed like inputs.
528
     *
529
     * @param array<mixed> $serverParams The original server params
530
     *
531
     * @return array<mixed> The allowed server params
532
     */
533
    public function scrubServerParams(array $serverParams): array
3 ✔
534
    {
535
        $allowed = [];
3 ✔
536

537
        foreach ($serverParams as $name => $value)
3 ✔
538
        {
539
            if (!in_array($name, $this->serverParams, true))
2 ✔
540
            {
541
                continue;
2 ✔
542
            }
543

544
            if (is_string($value))
2 ✔
545
            {
546
                if ($name === 'QUERY_STRING')
2 ✔
547
                {
548
                    $value = $this->scrubQueryString($value);
1 ✔
549
                }
550
                elseif ($name === 'REQUEST_URI' || $name === 'HTTP_REFERER')
2 ✔
551
                {
552
                    $value = $this->scrubUrl($value);
1 ✔
553
                }
554
            }
555

556
            $allowed[$name] = $value;
2 ✔
557
        }
558

559
        return $allowed;
3 ✔
560
    }
561

562
    /**
563
     * Scrub the query parameters of a URL.
564
     */
565
    private function scrubUrl(string $url): string
2 ✔
566
    {
567
        $fragment = '';
2 ✔
568
        $fragmentPosition = strpos($url, '#');
2 ✔
569

570
        if ($fragmentPosition !== false)
2 ✔
571
        {
572
            $fragment = substr($url, $fragmentPosition);
1 ✔
573
            $url = substr($url, 0, $fragmentPosition);
1 ✔
574
        }
575

576
        $queryPosition = strpos($url, '?');
2 ✔
577

578
        if ($queryPosition === false)
2 ✔
579
        {
580
            return $url.$fragment;
×
581
        }
582

583
        $query = $this->scrubQueryString(substr($url, $queryPosition + 1));
2 ✔
584

585
        return substr($url, 0, $queryPosition + 1).$query.$fragment;
2 ✔
586
    }
587

588
    /**
589
     * Scrub the parameters of a query string. The string is only rewritten when it
590
     * contains something to scrub.
591
     */
592
    private function scrubQueryString(string $query): string
2 ✔
593
    {
594
        $params = [];
2 ✔
595
        parse_str($query, $params);
2 ✔
596

597
        $scrubbed = $this->scrubInputs($params);
2 ✔
598

599
        if ($scrubbed === $params)
2 ✔
600
        {
601
            return $query;
×
602
        }
603

604
        return http_build_query($scrubbed);
2 ✔
605
    }
606

607
    /**
608
     * Check if a name contains one of the given parts, ignoring case.
609
     *
610
     * @param array<string> $parts
611
     */
612
    private function containsAny(string $name, array $parts): bool
9 ✔
613
    {
614
        $name = strtolower($name);
9 ✔
615

616
        foreach ($parts as $part)
9 ✔
617
        {
618
            if ($part !== '' && str_contains($name, strtolower($part)))
9 ✔
619
            {
620
                return true;
5 ✔
621
            }
622
        }
623

624
        return false;
9 ✔
625
    }
626
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc