diff --git a/app/Config/Exceptions.php b/app/Config/Exceptions.php index 4e3396346b80..445a6ce3a624 100644 --- a/app/Config/Exceptions.php +++ b/app/Config/Exceptions.php @@ -58,6 +58,19 @@ class Exceptions extends BaseConfig */ public array $sensitiveDataInTrace = []; + /** + * Query, form, and cookie names whose values may be shown in the detailed HTML error page. + * + * Built-in and configured redaction rules still apply to allowed values. + * + * @var array{ + * query?: list, + * form?: list, + * cookies?: list + * } + */ + public array $diagnosticValues = []; + /** * -------------------------------------------------------------------------- * WHETHER TO THROW AN EXCEPTION ON DEPRECATED ERRORS diff --git a/app/Config/Kint.php b/app/Config/Kint.php index 931ad47f5fe4..775f3218e311 100644 --- a/app/Config/Kint.php +++ b/app/Config/Kint.php @@ -33,6 +33,22 @@ class Kint public bool $displayCalledFrom = true; public bool $expanded = false; + /** + * Editor URL template using %f for the absolute filename and %l for the line. + * Leave null to use the Xdebug setting. + * + * Common templates: + * - VS Code: 'vscode://file%f:%l' + * - Cursor: 'cursor://file%f:%l' + * - PhpStorm: 'phpstorm://open?file=%f&line=%l' + * - IntelliJ IDEA: 'idea://open?file=%f&line=%l' + * - Sublime Text: 'subl://open?url=file://%f&line=%l' + * - TextMate: 'txmt://open?url=file://%f&line=%l' + * + * @var non-empty-string|null + */ + public ?string $fileLinkFormat = null; + /* |-------------------------------------------------------------------------- | RichRenderer Settings diff --git a/app/Views/errors/cli/error_exception.php b/app/Views/errors/cli/error_exception.php index 5621cb186185..898137d54832 100644 --- a/app/Views/errors/cli/error_exception.php +++ b/app/Views/errors/cli/error_exception.php @@ -1,65 +1,14 @@ getFile()) . ':' . $exception->getLine(), 'green')); -CLI::newLine(); - -$last = $exception; - -while ($prevException = $last->getPrevious()) { - $last = $prevException; - - CLI::write(' Caused by:'); - CLI::write(' [' . $prevException::class . ']', 'red'); - CLI::write(' ' . $prevException->getMessage()); - CLI::write(' at ' . CLI::color(clean_path($prevException->getFile()) . ':' . $prevException->getLine(), 'green')); - CLI::newLine(); -} - -// The backtrace -if ((defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE) || CLI::getOutput()->isVerbose()) { - $backtraces = $last->getTrace(); - - if ($backtraces) { - CLI::write('Backtrace:', 'green'); - } - - foreach ($backtraces as $i => $error) { - $padFile = ' '; // 4 spaces - $padClass = ' '; // 7 spaces - $c = str_pad($i + 1, 3, ' ', STR_PAD_LEFT); +declare(strict_types=1); - if (isset($error['file'])) { - $filepath = clean_path($error['file']) . ':' . $error['line']; - - CLI::write($c . $padFile . CLI::color($filepath, 'yellow')); - } else { - CLI::write($c . $padFile . CLI::color('[internal function]', 'yellow')); - } - - $function = ''; - - if (isset($error['class'])) { - $type = ($error['type'] === '->') ? '()' . $error['type'] : $error['type']; - $function .= $padClass . $error['class'] . $type . $error['function']; - } elseif (! isset($error['class']) && isset($error['function'])) { - $function .= $padClass . $error['function']; - } - - $args = implode(', ', array_map(static fn ($value): string => match (true) { - is_object($value) => 'Object(' . $value::class . ')', - is_array($value) => $value !== [] ? '[...]' : '[]', - $value === null => 'null', // return the lowercased version - default => var_export($value, true), - }, array_values($error['args'] ?? []))); - - $function .= '(' . $args . ')'; - - CLI::write($function); - CLI::newLine(); - } -} +use CodeIgniter\CLI\CLI; +use CodeIgniter\Debug\ConsoleExceptionRenderer; +use Config\Exceptions; + +/** + * @var Exceptions $config + * @var Throwable $exception + * @var string $message + */ +ConsoleExceptionRenderer::render($exception, $message, CLI::getOutput(), $config->sensitiveDataInTrace); diff --git a/app/Views/errors/html/debug.css b/app/Views/errors/html/debug.css index 2072418db1bd..b8539a420221 100644 --- a/app/Views/errors/html/debug.css +++ b/app/Views/errors/html/debug.css @@ -46,16 +46,9 @@ p.lead { .header .container { padding: 1rem; } -.header-title { - align-items: flex-start; - display: flex; - gap: 1rem; - justify-content: space-between; -} .header h1 { font-size: 2.5rem; font-weight: 500; - min-width: 0; } .header p { font-size: 1.2rem; @@ -72,58 +65,8 @@ p.lead { display: inline; } -.error-report { - flex: 0 0 auto; - margin-top: 0.35rem; -} - -.error-report-button { - align-items: center; - background: rgba(255,255,255,0.35); - border: 1px solid rgba(0,0,0,0.14); - border-radius: 5px; - box-sizing: border-box; - color: var(--main-text-color); - cursor: pointer; - display: inline-flex; - font-size: 0.82rem; - font-weight: 500; - gap: 0.35rem; - height: 1.875rem; - justify-content: center; - line-height: 1; - padding: 0 0.65rem; - transition: background-color 160ms ease-in-out, border-color 160ms ease-in-out, color 160ms ease-in-out, box-shadow 160ms ease-in-out; - white-space: nowrap; - width: 7.15rem; -} - -.error-report-button:hover { - background: rgba(255,255,255,0.6); - border-color: rgba(0,0,0,0.22); - color: var(--dark-text-color); - box-shadow: 0 1px 2px rgba(0,0,0,0.04); -} - -.error-report-button:focus-visible { - border-color: rgba(0,0,0,0.35); - outline: 0; - box-shadow: 0 0 0 2px rgba(220,72,20,0.16); -} - -.error-report-button:active { - background: rgba(255,255,255,0.75); -} - -.error-report-icon { - flex: 0 0 auto; - height: 0.72rem; - width: 0.72rem; -} - .environment { background: var(--brand-primary-color); - box-sizing: border-box; color: var(--main-bg-color); text-align: center; padding: calc(4px + 0.2083vw); @@ -132,26 +75,6 @@ p.lead { position: fixed; } -@media (max-width: 40rem) { - .header { - margin-top: 0; - } - - .header p { - font-size: 1.1rem; - line-height: 1.45; - margin-top: 0.35rem; - overflow-wrap: anywhere; - } - - .environment { - font-size: 0.9rem; - line-height: 1.25; - padding: 0.45rem 0.75rem; - position: static; - } -} - .source { background: #343434; color: var(--light-text-color); diff --git a/app/Views/errors/html/debug.js b/app/Views/errors/html/debug.js index 78b85a026ef7..99199cac872c 100644 --- a/app/Views/errors/html/debug.js +++ b/app/Views/errors/html/debug.js @@ -114,29 +114,3 @@ function toggle(elem) return false; } - -function copyErrorReport(reportId, button) -{ - if (! navigator.clipboard || ! window.isSecureContext) - { - return false; - } - - var report = document.getElementById(reportId); - navigator.clipboard.writeText(report.value).then(function () { - showCopiedButton(button); - }); - - return false; -} - -function showCopiedButton(button) -{ - button.defaultHtml = button.defaultHtml || button.innerHTML; - button.innerHTML = 'Copied!'; - - window.clearTimeout(button.copyResetTimer); - button.copyResetTimer = window.setTimeout(function () { - button.innerHTML = button.defaultHtml; - }, 1500); -} diff --git a/app/Views/errors/html/error_exception.php b/app/Views/errors/html/error_exception.php index eec30a3037dd..c9d7839d7826 100644 --- a/app/Views/errors/html/error_exception.php +++ b/app/Views/errors/html/error_exception.php @@ -1,462 +1,521 @@ > $trace + */ +$exceptionChain = (new Inspector($exception))->chain(); +$showBacktrace = defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE; +$reasonPhrase = $response->getStatusCode() === $code ? $response->getReasonPhrase() : ''; + +$requestPath = sprintf('/%s', ltrim($request->getPath(), '/')); +$requestUrl = $requestPath; +$uri = $request->getUri(); + +if ($uri->getHost() !== '') { + $requestUrl = URI::createURIString( + $uri->getScheme(), + $uri->getPort() === null ? $uri->getHost() : sprintf('%s:%d', $uri->getHost(), $uri->getPort()), + $requestPath, + ); +} + +$userAgent = $this->redactDiagnosticData(['User-Agent' => $request->getUserAgent()->getAgentString()], caseInsensitive: true)['User-Agent']; + +$serverContext = [ + 'Environment' => ENVIRONMENT, + 'CodeIgniter' => CodeIgniter::CI_VERSION, + 'PHP' => PHP_VERSION, + 'SAPI' => PHP_SAPI, + 'Platform' => PHP_OS_FAMILY, + 'Time' => date('Y-m-d H:i:s e'), +]; +helper('number'); +$memoryUsage = number_to_size(memory_get_usage(true), 2); + +$linkToFile = static function (?string $path, ?int $line = null, bool $compact = false): string { + if ($path === null || $path === '') { + return '[PHP internal code]'; + } + + $relative = Backtrace::relativePath($path); + $basename = basename($relative); + $location = sprintf('%s%s', esc(substr($relative, 0, strlen($relative) - strlen($basename))), esc($basename)); + $resolved = realpath($path); + + if ($resolved !== false && is_file($resolved)) { + $normalized = is_windows() ? str_replace('\\', '/', $resolved) : $resolved; + $encoded = implode('/', array_map(rawurlencode(...), explode('/', $normalized))); + $encoded = preg_replace('/^([a-z])%3A/i', '/$1:', $encoded); + + $editorUrl = $line !== null && class_exists(AbstractRenderer::class) + ? AbstractRenderer::getFileLink($encoded, $line) + : null; + $url = $editorUrl === null || $editorUrl === '' ? sprintf('file://%s', $encoded) : $editorUrl; + $location = sprintf('%s', esc($url, 'attr'), $location); + } + + if ($line === null) { + return $location; + } + + return sprintf($compact ? '%s:%d' : 'in %s (line %d)', $location, $line); +}; + +$throwSite = $linkToFile($file, $line); +$stackHeading = $showBacktrace ? 'Stack trace' : 'Exceptions'; +$heading = $message === '' ? $title : $message; +$stack = []; +$sourcePanels = []; +$snippets = []; +$snippetLimit = 16; +$frameLimit = 20; +$causeLimit = 10; +$hiddenCauses = max(0, count($exceptionChain) - $causeLimit); +$rootCause = $exceptionChain[array_key_last($exceptionChain)]; + +foreach (array_slice($exceptionChain, 0, $causeLimit) as $causeIndex => $cause) { + if ($showBacktrace) { + $causeTrace = Frames::fromException($cause, $cause === $rootCause ? $trace : null); + $hiddenFrames = max(0, count($causeTrace) - $frameLimit); + $frames = $causeTrace->take($frameLimit); + } else { + $location = Frame::sourceLocation($cause->getFile(), $cause->getLine()); + $hiddenFrames = 0; + $frames = [new Frame('', $location['file'], $location['line'] ?? null)]; + } + + $stackFrames = []; + + foreach ($frames as $frameIndex => $frame) { + $frameId = sprintf('frame-%02d%02d', $causeIndex, $frameIndex); + $path = $frame->file ?? ''; + $origin = match (true) { + str_starts_with($path, APPPATH) => 'Application', + str_starts_with($path, SYSTEMPATH) => 'Framework', + str_starts_with($path, FCPATH) => 'Front controller', + defined('TESTPATH') && str_starts_with($path, TESTPATH) => 'Application tests', + defined('VENDORPATH') && str_starts_with($path, VENDORPATH) => 'Vendor', + default => 'Root', + }; + + $stackFrames[] = [ + 'id' => $frameId, + 'call' => $showBacktrace ? $frame->call() : 'Exception thrown', + 'location' => $linkToFile($frame->file, $frame->line, compact: true), + 'origin' => $origin, + ]; + + $snippetKey = sprintf('%s:%d', $path, $frame->line ?? 0); + + if ( + $frame->file !== null + && $frame->line !== null + && ! isset($snippets[$snippetKey]) + // Limit source I/O even when an exception carries a deep trace. + && count($snippets) < $snippetLimit + ) { + $snippets[$snippetKey] = CodeSnippet::get($frame->file, $frame->line); + } -$errorId = uniqid('error', true); -$copyableErrorReportId = $errorId . 'copyableErrorReport'; + $sourcePanels[$frameId] = [ + 'location' => $linkToFile($frame->file, $frame->line), + 'origin' => $origin, + 'line' => $frame->line, + 'source' => $snippets[$snippetKey] ?? [], + 'arguments' => $showBacktrace ? $this->previewDiagnosticArguments($frame) : [], + ]; + } + + $stack[] = [ + 'cause' => $causeIndex > 0 ? $cause : null, + 'frames' => $stackFrames, + 'hiddenFrames' => $hiddenFrames, + ]; +} + +$superglobals = service('superglobals'); +$router = service('router'); + +foreach (['SERVER_SOFTWARE', 'SERVER_PROTOCOL', 'SERVER_NAME', 'SERVER_PORT', 'REQUEST_SCHEME', 'GATEWAY_INTERFACE', 'SCRIPT_NAME', 'REQUEST_TIME'] as $key) { + $value = $superglobals->server($key); + + if (is_string($value) || is_int($value)) { + $serverContext[$key] = (string) $value; + } +} + +$constants = array_keys(get_defined_constants(true)['user'] ?? []); +sort($constants, SORT_STRING); + +$requestContext = [ + 'Method' => $request->getMethod(), + 'Path' => $requestPath, + 'URL' => $requestUrl, + 'Protocol' => sprintf('HTTP/%s', $request->getProtocolVersion()), +]; + +if ($router instanceof Router) { + $matchedRoute = $router->getMatchedRoute(); + + if ($matchedRoute !== null) { + $requestContext['Route'] = sprintf('/%s', ltrim($matchedRoute[0], '/')); + } +} + +$requestContext['Secure'] = $request->isSecure() ? 'Yes' : 'No'; +$requestContext['User agent'] = $userAgent; + +$responseContext = ['Status' => sprintf('%d %s', $code, $reasonPhrase)]; + +$memoryLimit = ini_parse_quantity(ini_get('memory_limit')); +$memoryContext = [ + 'Current usage' => $memoryUsage, + 'Peak usage' => number_to_size(memory_get_peak_usage(true), 2), + 'Memory limit' => $memoryLimit === -1 ? 'Unlimited' : number_to_size($memoryLimit, 2), +]; + +$headerContext = function (MessageInterface $message): array { + $rows = []; + + // Show header values for debugging and mask credential headers by name. + $sensitiveHeaders = [ + 'authorization', 'proxy-authorization', 'cookie', 'cookie2', 'set-cookie', 'set-cookie2', 'api-key', + 'x-api-key', 'x-auth-token', 'x-csrf-token', 'x-xsrf-token', + ]; + + foreach ($message->headers() as $name => $headers) { + $headers = $headers instanceof Header ? [$headers] : $headers; + $rows[$name] = implode(', ', array_map(static fn (Header $header): string => $header->getValueLine(), $headers)); + } + + return $this->redactDiagnosticData($rows, $sensitiveHeaders, caseInsensitive: true); +}; + +$sensitiveFields = ['password', 'password_confirmation', 'token', 'access_token', 'refresh_token', 'secret', 'client_secret', 'api_key']; +$sensitiveCookies = [config('Session')->cookieName, sprintf('%s%s', config('Cookie')->prefix, config('Security')->cookieName)]; +$requestDetails = array_filter([ + 'Headers' => $headerContext($request), + 'Query fields' => $this->diagnosticFields($superglobals->getGetArray(), 'query', $sensitiveFields), + 'Form fields' => $this->diagnosticFields($superglobals->getPostArray(), 'form', $sensitiveFields), + 'Cookies' => $this->diagnosticFields($superglobals->getCookieArray(), 'cookies', [...$sensitiveFields, ...$sensitiveCookies]), +]); +$responseHeaders = $headerContext($response); + +// Use the same markup for each field list, including the collapsed data. +$renderContext = static function (array $rows): void { + ?> +
+ $value) : ?> +
+
+ +
+ - + + - - <?= esc($title) ?> - - + <?= esc($message) ?> + - - - -
-
- Displayed at — - PHP: — - CodeIgniter: -- - Environment: -
-
-
-

getCode() ? ' #' . $exception->getCode() : '') ?>

-
- - -
+ +
+
+ + + + CodeIgniter + +
+ PHP · +
-

- getMessage())) ?> - getMessage())) ?>" - rel="noreferrer" target="_blank">search → -

-
- - -
-

at line

- - -
- -
- -
- -
- getPrevious()) { - $last = $prevException; - ?> - -
-    Caused by:
-    getCode() ? ' #' . $prevException->getCode() : '') ?>
-
-    getMessage())) ?>
-    getMessage())) ?>"
-       rel="noreferrer" target="_blank">search →
-    getFile()) . ':' . $prevException->getLine()) ?>
-    
- - -
- - -
- - - -
- - -
- -
    - $row) : ?> - -
  1. -

    - - - - - {PHP internal code} - - - - -   —   - - - ( arguments ) -

    - - - getParameters(); - } - - foreach ($row['args'] as $key => $value) : ?> - - - - - - -
    name : "#{$key}") ?>
    -
    - - () - - - - -   —   () - -

    - - - -
    - -
    - -
  2. - - -
- -
- - -
- - - -

$

- - - - - - - - - - $value) : ?> - - - - - - -
KeyValue
- - - -
- -
- - - - - - -

Constants

- - - - - - - - - - $value) : ?> - - - - - - -
KeyValue
- - - -
- -
- -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PathgetUri()) ?>
HTTP MethodgetMethod()) ?>
IP AddressgetIPAddress()) ?>
Is AJAX Request?isAJAX() ? 'yes' : 'no' ?>
Is CLI Request?isCLI() ? 'yes' : 'no' ?>
Is Secure Request?isSecure() ? 'yes' : 'no' ?>
User AgentgetUserAgent()->getAgentString()) ?>
- - - - - - - - -

$

- - - - - - - - - - $value) : ?> - - - - - - -
KeyValue
- - - -
- -
- - - - - -
- No $_GET, $_POST, or $_COOKIE Information to show. -
- - - - headers(); ?> - - -

Headers

- - - - - - - - - - $value) : ?> - - - - - - -
HeaderValue
- getValueLine(), 'html'); - } else { - foreach ($value as $i => $header) { - echo ' ('. $i+1 . ') ' . esc($header->getValueLine(), 'html'); - } - } - ?> -
- - + + +
+
+ +
- - setStatusCode($responseStatusCode === false || $responseStatusCode === 0 ? $code : $responseStatusCode); - ?> -
- - - - - -
Response StatusgetStatusCode() . ' - ' . $response->getReasonPhrase()) ?>
- - headers(); ?> - -

Headers

- - - - - - - - - - $value) : ?> - - - - - - -
HeaderValue
- getHeaderLine($name), 'html'); - } else { - foreach ($value as $i => $header) { - echo ' ('. $i+1 . ') ' . esc($header->getValueLine(), 'html'); +
+
+
+

+ $cause, 'frames' => $frames, 'hiddenFrames' => $hiddenFrames]) : ?> + +
+ + Caused by + + getMessage()) ?> + + + +
    + $frameId, 'call' => $call, 'location' => $location, 'origin' => $origin]) : ?> +
  1. + aria-current="location"> + + + +
  2. + +
+ + 0) : ?> +

+ hidden

+ + + +
+ + + + 0) : ?> +

+ hidden

+ +
+ +
+ ['location' => $location, 'origin' => $origin, 'line' => $sourceLine, 'source' => $source, 'arguments' => $arguments]) : ?> +
+
+

+ +
+ + +

Source preview unavailable.

+ +
 $highlightedLine) {
+                                        $lineClass = $number === $sourceLine ? ' current-line' : '';
+
+                                        printf(
+                                            "%d%s\n",
+                                            $lineClass,
+                                            $number,
+                                            $highlightedLine,
+                                        );
                                     }
-                                }
-                                ?>
-                                
- - -
- - -
- - -
    - -
  1. - -
-
- - -
- - - - - - - - - - - - - - - - -
Memory Usage
Peak Memory Usage:
Memory Limit:
- + ?> + + + +
+ Arguments +
+ $value) : ?> +
+
+ +
+
+ + + +
-
+
+

Diagnostics

+ +
+ Request + + $rows) : ?> +
+ + +
+ +
+ +
+ Response + + +
+ Headers + +
+ +
+ +
+ Server + + +
+ Constants () +
    + +
  • + +
+
+ +
+ +
+ Files () +
    + +
  1. + +
+
+ +
+ Memory + +
+
+ +
+
+ Error report + + +
+
+
+ + diff --git a/app/Views/errors/html/error_report.php b/app/Views/errors/html/error_report.php index 5927c4720d3a..b2e86d98795b 100644 --- a/app/Views/errors/html/error_report.php +++ b/app/Views/errors/html/error_report.php @@ -1,127 +1,151 @@ setStatusCode($code); - -$report = [ - '# ' . $reportTitle, - '', - '## Exception', - '', - '- Type: ' . $type, - '- Status Code: ' . $code, - '- Status: ' . $reportResponse->getReasonPhrase(), - $messageLines ? '- Message:' : '- Message: ' . $reportMessage, -]; - -if ($messageLines) { - $report[] = ''; - $report[] = '```text'; - $report[] = $reportMessage; - $report[] = '```'; + +/** + * @var string $message Exception message before newline normalization. + * @var string $title The exception class shown in the report heading. + * @var string $file The exception's source path before stripping the project root. + * @var int|null $line + * @var int $code + * @var string $reasonPhrase + * @var array $serverContext + * @var string $memoryUsage + * @var IncomingRequest $request + * @var string $requestPath + * @var string $requestUrl + * @var string $userAgent + * @var list $exceptionChain + * @var Throwable $rootCause + * @var bool $showBacktrace + */ +$normalizedMessage = trim(str_replace(["\r\n", "\r"], "\n", $message)); +$markdownTitle = $normalizedMessage === '' ? $title : sprintf('[%s] %s', $title, $normalizedMessage); + +$markdown = sprintf( + <<<'EOT' + # %s + + ## Exception + + - Source: %s + - Status: HTTP %d %s + + ## Environment + + - PHP: %s + - CodeIgniter: %s + - Environment: %s + - SAPI: %s + - Time: %s + - Memory Usage: %s + + EOT, + $markdownTitle, + Backtrace::location($file, $line), + $code, + $reasonPhrase, + $serverContext['PHP'], + $serverContext['CodeIgniter'], + $serverContext['Environment'], + $serverContext['SAPI'], + $serverContext['Time'], + $memoryUsage, +); + +$markdown .= sprintf( + <<<'EOT' + + ## Request + + - Method: %s + - Path: %s + - URL: %s + - User Agent: %s + + EOT, + $request->getMethod(), + $requestPath, + $requestUrl, + $userAgent, +); + +$causes = array_slice($exceptionChain, 1); + +if ($causes !== []) { + $markdown .= sprintf( + <<<'EOT' + + ## Previous Exceptions + + - %s + + EOT, + implode("\n- ", array_map( + static fn (Throwable $e): string => sprintf( + "[%s] %s\n %s", + $e::class, + $e->getMessage(), + Backtrace::location($e->getFile(), $e->getLine()), + ), + $causes, + )), + ); } -$report[] = ''; -$report[] = '## Environment'; -$report[] = ''; -$report[] = '- PHP: ' . PHP_VERSION; -$report[] = '- CodeIgniter: ' . CodeIgniter::CI_VERSION; -$report[] = '- Environment: ' . ENVIRONMENT; -$report[] = '- SAPI: ' . PHP_SAPI; -$report[] = '- Time: ' . date('Y-m-d H:i:s e'); -$report[] = '- Memory Usage: ' . number_format(memory_get_usage(true) / 1024 / 1024, 2) . ' MB'; - -$reportRequest = service('request'); - -if ($reportRequest instanceof IncomingRequest) { - $reportPath = '/' . ltrim($reportRequest->getPath(), '/'); - $reportUri = $reportRequest->getUri(); - $reportUrl = $reportPath; - - if ($reportUri->getHost() !== '') { - $reportUrl = URI::createURIString( - $reportUri->getScheme(), - $reportUri->getHost() . ($reportUri->getPort() === null ? '' : ':' . $reportUri->getPort()), - $reportPath, +$sourceLocation = Frame::sourceLocation($rootCause->getFile(), $rootCause->getLine()); +$excerptLine = $sourceLocation['line'] ?? null; +$excerpt = CodeSnippet::get($sourceLocation['file'], $excerptLine, highlight: false); + +if ($excerpt !== []) { + $excerptLines = []; + $lineWidth = strlen((string) array_key_last($excerpt)); + + foreach ($excerpt as $number => $text) { + $excerptLines[] = sprintf( + '%s %*d | %s', + $number === $excerptLine ? '>' : ' ', + $lineWidth, + $number, + mb_scrub($text, 'UTF-8'), ); } - $report[] = ''; - $report[] = '## Request'; - $report[] = ''; - $report[] = '- Method: ' . $reportRequest->getMethod(); - $report[] = '- Path: ' . $reportPath; - $report[] = '- URL: ' . $reportUrl; - $report[] = '- User Agent: ' . $reportRequest->getUserAgent()->getAgentString(); -} - -$report[] = ''; -$report[] = '## Source'; -$report[] = ''; -$report[] = '`' . clean_path($file) . ':' . $line . '`'; - -if (is_file($file) && is_readable($file)) { - $sourceLines = file($file, FILE_IGNORE_NEW_LINES); - - if ($sourceLines !== false) { - $startLine = max($line - 5, 1); - $endLine = min($line + 5, count($sourceLines)); - - $report[] = ''; - $report[] = '```php'; + $markdown .= sprintf( + <<<'EOT' - for ($sourceLine = $startLine; $sourceLine <= $endLine; $sourceLine++) { - $report[] = sprintf( - '%s%4d %s', - $sourceLine === $line ? '>' : ' ', - $sourceLine, - $sourceLines[$sourceLine - 1], - ); - } + ## Source Excerpt - $report[] = '```'; - } -} - -$previousException = $exception->getPrevious(); - -if ($previousException instanceof Throwable) { - $report[] = ''; - $report[] = '## Previous Exceptions'; + %s - while ($previousException instanceof Throwable) { - $report[] = '* ' . $previousException::class . ' - ' . $previousException->getMessage(); - $report[] = ' ' . clean_path($previousException->getFile()) . ':' . $previousException->getLine(); + ```php + %s + ``` - $previousException = $previousException->getPrevious(); - } + EOT, + Backtrace::location($sourceLocation['file'], $excerptLine), + implode("\n", $excerptLines), + ); } -if ($trace !== []) { - $report[] = ''; - $report[] = '## Stack Trace'; - $report[] = ''; - $report[] = '```text'; - - foreach (array_slice($trace, 0, 50) as $reportIndex => $reportRow) { - $reportLocation = isset($reportRow['file'], $reportRow['line']) - ? clean_path($reportRow['file']) . ':' . $reportRow['line'] - : '{PHP internal code}'; - $reportCall = ($reportRow['class'] ?? '') . ($reportRow['type'] ?? '') . ($reportRow['function'] ?? ''); +if ($showBacktrace) { + $markdown .= sprintf( + <<<'EOT' - $report[] = $reportIndex . ' ' . $reportLocation . ($reportCall === '' ? '' : ' ' . $reportCall . '()'); - } + ## Stack Trace - $report[] = '```'; + ```text + %s + ``` + EOT, + implode("\n", Backtrace::lines(Frames::fromException($rootCause), includeArguments: false)), + ); } -echo esc(implode("\n", $report)) . "\n"; +printf("%s\n", esc(trim($markdown))); diff --git a/app/Views/errors/html/exception.css b/app/Views/errors/html/exception.css new file mode 100644 index 000000000000..78f05abc164c --- /dev/null +++ b/app/Views/errors/html/exception.css @@ -0,0 +1,523 @@ +:root { + color-scheme: light; + --page: #fff; + --ink: #222; + --row-line: #ededed; + --row-hover: #f6f6f6; + --button-line: #bcbcbc; + --button-hover: #fcf4ef; + --muted: #555; + --line: #d8d8d8; + --surface: #ededee; + --accent: #dd4814; + --code-font: Menlo, Monaco, Consolas, "Courier New", monospace; +} + +:root[data-theme="dark"] { + color-scheme: dark; + --page: #1f1f1f; + --ink: #efefef; + --muted: #bcbcbc; + --line: #4a4a4a; + --surface: #303030; + --row-line: #3a3a3a; + --row-hover: #292929; + --button-line: #686868; + --button-hover: #42312b; + --accent: #ff8b61; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme]) { + color-scheme: dark; + --page: #1f1f1f; + --ink: #efefef; + --muted: #bcbcbc; + --line: #4a4a4a; + --surface: #303030; + --row-line: #3a3a3a; + --row-hover: #292929; + --button-line: #686868; + --button-hover: #42312b; + --accent: #ff8b61; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + background: var(--page); + color: var(--ink); + font: 1rem/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; +} + +a { color: inherit; } + +.editor-link { + text-decoration: underline; + text-underline-offset: .16em; +} + +.editor-link:hover { text-decoration-thickness: 2px; } + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.container { + width: min(75rem, calc(100% - 2rem)); + margin-inline: auto; +} + +.environment { + border-top: 3px solid var(--accent); + background: #252525; + color: #fff; +} + +.environment-inner { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: .35rem 1rem; +} + +.environment-inner { min-height: 2.75rem; } + +.framework { + display: inline-flex; + align-items: center; + gap: .5rem; + font-size: .875rem; + font-weight: 600; +} + +.framework svg { + width: .8rem; + height: 1.1rem; +} + +.runtime { + color: #dfdfdf; + font-size: .8125rem; +} + +.environment-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: .35rem .75rem; +} + +.theme-toggle { + width: 2rem; + height: 2rem; + padding: .4rem; + border: 0; + border-radius: 3px; + background: transparent; + color: inherit; + cursor: pointer; +} + +.theme-toggle svg { + display: block; + width: 100%; + height: 100%; +} + +.theme-toggle[aria-pressed="false"] .theme-sun, +.theme-toggle[aria-pressed="true"] .theme-moon { + display: none; +} + +.theme-toggle:hover, .theme-toggle[aria-pressed="true"] { + background: #424242; +} + +.exception-summary { + padding: 1.25rem 0 1.4rem; + border-bottom: 1px solid var(--line); + background: var(--surface); +} + +.summary-meta { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: start; + gap: .35rem 1rem; +} + +.http-status { + text-align: right; +} + +.exception-type, .http-status, .throw-site { + margin: 0; + font: .8125rem/1.55 var(--code-font); + overflow-wrap: anywhere; +} + +.exception-type { font-weight: 600; } +.throw-site { + grid-column: 1 / -1; + color: var(--muted); +} + +h1 { + margin: 0; + font-size: clamp(1.5rem, 3vw, 2.25rem); + font-weight: 500; + line-height: 1.25; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.copy-button { + display: inline-flex; + align-items: center; + justify-content: center; + justify-self: end; + gap: .35rem; + min-width: 7rem; + padding: .25rem .65rem; + border: 1px solid var(--button-line); + border-radius: 3px; + background: var(--page); + font-size: .8125rem; + text-decoration: none; + white-space: nowrap; +} + +.copy-button:hover { + border-color: var(--accent); + background: var(--button-hover); +} + +.copy-icon { width: .85rem; height: .85rem; } +.copy-icon-check { opacity: 0; } +.copy-button.is-copied .copy-icon-sheets { opacity: 0; } +.copy-button.is-copied .copy-icon-check { opacity: 1; } + +@media (prefers-reduced-motion: no-preference) { + .copy-button.is-copied .copy-icon-check { + stroke-dasharray: 1; + animation: draw-copy-check .25s ease-out; + } +} + +@keyframes draw-copy-check { + from { stroke-dashoffset: 1; } + to { stroke-dashoffset: 0; } +} + +.exception-layout { + display: grid; + grid-template-columns: minmax(15rem, 1fr) minmax(0, 2fr); + margin-top: 1.25rem; + align-items: start; +} + +.stack { + overflow-y: auto; + border: 1px solid var(--line); +} + +.stack h2, .source-heading { + margin: 0; + padding: .55rem .75rem; + border-bottom: 1px solid var(--line); + background: var(--surface); +} + +.stack h2 { + position: sticky; + top: 0; + font-size: .875rem; + font-weight: 600; +} + +.frames { + margin: 0; + padding: 0; + list-style: none; +} + +.frame-link { + display: block; + padding: .5rem .75rem 0; + text-decoration: none; + overflow-wrap: anywhere; +} + +.frame-link:focus-visible { outline-offset: -2px; } + +.frames li + li { border-top: 1px solid var(--row-line); } +.frames li:hover { background: var(--row-hover); } + +.stack-overflow { + margin: 0; + padding: .5rem .75rem; + border-top: 1px solid var(--row-line); + color: var(--muted); + font-size: .8125rem; +} + +.frame-link[aria-current], .frame-link[aria-current] + .frame-location { background: var(--surface); } + +.frame-call, .frame-location, .source-heading h2 { + display: block; + font: .8125rem/1.45 var(--code-font); +} + +.frame-link[data-origin="Application"] .frame-call { font-weight: 600; } + +.frame-location { + padding: .125rem .75rem .5rem; + color: var(--muted); + font-size: .75rem; + overflow-wrap: anywhere; +} + +.frame-link[data-origin="Framework"] .frame-call, +.frame-link[data-origin="Vendor"] .frame-call { + color: var(--muted); + font-weight: 400; +} + +.cause { border-top: 1px solid var(--line); } + +.cause summary { + padding: .5rem .75rem; + background: var(--row-hover); + cursor: pointer; + font-size: .8125rem; + overflow-wrap: anywhere; +} + +.cause-message { + display: block; + color: var(--muted); +} + +.source-panel { + display: flex; + flex-direction: column; + height: 23rem; + border: 1px solid var(--line); + border-inline-start: 0; + scroll-margin-top: 1rem; +} + +@supports selector(:has(*)) { + .source-panel:not(:first-child):not(:target), + .source-panels:has(> .source-panel:target) > .source-panel:first-child:not(:target) { + display: none; + } + + .exception-layout:has(.source-panel:target:not(:first-child)) :is(.frame-link[href="#frame-0000"], .frame-link[href="#frame-0000"] + .frame-location) { + background: transparent; + } +} + +.source-heading { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: baseline; + gap: .125rem .75rem; + overflow-wrap: anywhere; +} + +.source-heading h2 { + margin: 0; +} + +.source-heading span, .source-unavailable { + color: var(--muted); + font-size: .8125rem; +} + +.source-unavailable { margin: .75rem; } + +.source-panel:focus-visible, .source-code:focus-visible { + outline-color: #767676; + outline-offset: -2px; +} + +.source-code { + flex: 1; + min-height: 0; + margin: 0; + padding: .5rem 0; + overflow: auto; + background: #343434; + color: #e0e0e0; + font: .8125rem/1.6 var(--code-font); + tab-size: 4; +} + +.frame-arguments { + max-height: 8rem; + overflow: auto; + border-top: 1px solid var(--line); + font-size: .8125rem; +} + +.frame-arguments summary { + padding: .4rem .75rem; + cursor: pointer; +} + +.argument-value { + margin: 0; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.source-code code { + display: table; + min-width: 100%; + font: inherit; +} + +.source-line { display: table-row; } + +.source-line > span { + display: table-cell; + padding-inline: .7rem; +} + +.line-number { + width: 1%; + color: #bcbcbc; + text-align: right; + user-select: none; +} + +.current-line { + background: #252525; + color: #fff; +} + +.current-line .line-number { color: #fff; } + +.source-code .php-keyword { color: #f1ce61; } +.source-code .php-string { color: #a4b77e; } +.source-code .php-comment { + color: #a3a7a9; + font-style: italic; +} + +.exception-footer { + margin: .9rem 0 1.5rem; + color: var(--muted); + font-size: .875rem; +} + +.exception-footer summary { cursor: pointer; } + +.exception-footer label { + display: block; + margin: .7rem 0 .3rem; +} + +.exception-footer textarea { + width: 100%; + padding: .75rem; + border: 1px solid var(--line); + color: var(--ink); + font: .8125rem/1.5 var(--code-font); + resize: vertical; +} + +@media (width > 48rem) { + .exception-layout { align-items: stretch; } + + /* Let the selected source determine the row height. */ + .stack { contain: size; } +} + +@media (max-width: 48rem) { + .container { width: calc(100% - 1.5rem); } + .exception-layout { grid-template-columns: minmax(0, 1fr); } + .stack { max-height: 15rem; } + .source-panel { + border-top: 0; + border-inline-start: 1px solid var(--line); + } +} + +@media (max-width: 32rem) { + .summary-meta { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } +} + +.diagnostics { + margin-top: 1.25rem; + border: 1px solid var(--line); + font-size: .875rem; +} + +.diagnostics h2 { + margin: 0; + padding: .55rem .75rem; + border-bottom: 1px solid var(--line); + background: var(--surface); + font-size: .875rem; + font-weight: 600; +} + +.diagnostic-section + .diagnostic-section { + border-top: 1px solid var(--line); +} + +.diagnostic-section > summary, .diagnostic-fields > summary { + padding: .4rem .75rem; + cursor: pointer; +} + +.diagnostic-section > summary { font-weight: 600; } + +.diagnostic-fields { + margin: 0 .75rem .35rem; + border-inline-start: 2px solid var(--line); +} + +.diagnostic-fields > summary { + color: var(--muted); +} + +.diagnostic-values { + display: grid; + grid-template-columns: minmax(10rem, max-content) minmax(10rem, 1fr); + gap: .15rem .75rem; + margin: 0; + padding: .2rem .75rem .6rem; + overflow-x: auto; +} + +.diagnostic-values dt { white-space: nowrap; } + +.diagnostic-values dd { + margin: 0; + overflow-wrap: anywhere; +} + +.diagnostic-values code, .diagnostic-files code { + font: .8125rem/1.45 var(--code-font); +} + +.diagnostic-files { + max-height: 20rem; + margin: 0; + padding: .25rem .75rem .6rem 2.75rem; + overflow: auto; + overflow-wrap: anywhere; +} + +@media (max-width: 48rem) { + .diagnostic-values { grid-template-columns: max-content minmax(8rem, 1fr); } +} diff --git a/docs/changelogs/v4.8.0.md b/docs/changelogs/v4.8.0.md index e397ab146b2f..d9d1ffa189d0 100644 --- a/docs/changelogs/v4.8.0.md +++ b/docs/changelogs/v4.8.0.md @@ -293,7 +293,7 @@ Release Date: Unreleased ### Debug -- Added a **Copy Details** button to detailed HTML exception pages. +- Refreshed the HTML and CLI exception views with source previews and shareable reports, updated log trace formatting, and removed arguments from API traces. See [Detailed Exception Responses](../installation/upgrade_480.md#detailed-exception-responses). ### Model diff --git a/docs/general/errors.md b/docs/general/errors.md index 74d1be6330bd..f2628c6f1cee 100644 --- a/docs/general/errors.md +++ b/docs/general/errors.md @@ -82,7 +82,7 @@ You can change your environment by setting the `CI_ENVIRONMENT` variable. See [S Disabling error reporting DOES NOT stop logs from being written if there are errors. !!! warning "Warning" - Note that your settings from the **.env** file are added to `$_SERVER` and `$_ENV`. As a side effect, this means that if the detailed error report is displayed, **your secure credentials are publicly exposed**. + Keep `display_errors` disabled on public deployments. Detailed error reports can expose credentials through exception messages, source excerpts, and diagnostic values. ### Logging Exceptions @@ -344,6 +344,29 @@ If there is no view file corresponding to the HTTP status code, **production.php !!! note "Note" If `display_errors` is on in the PHP ini settings, **error_exception.php** is selected and a detailed error report is displayed. +The detailed HTML view shows the exception, its causes, and the source location. When `SHOW_DEBUG_BACKTRACE` is enabled, select a stack frame to inspect its location and available source. **Copy Details** generates a Markdown report with source locations and a short excerpt from the first frame if its source is available. The report lists stack frames when backtraces are enabled. It omits trace arguments, request headers, query strings, and session data. Review the exception messages, request path, and source excerpt before sharing the report. + +The error page shows paths relative to the project when possible. Set `Config\Kint::$fileLinkFormat` to an editor URL template such as `vscode://file%f:%l`, or override it in `.env` with `kint.fileLinkFormat = 'vscode://file%f:%l'`. Kint substitutes the absolute filename for `%f` and the line number for `%l`. The error page and Debug Toolbar share this setting. When it is `null`, Kint uses `xdebug.file_link_format` if configured. The error page uses `file://` when there is no editor format or line number. + +Common editor templates: + +- VS Code: `vscode://file%f:%l` +- Cursor: `cursor://file%f:%l` +- PhpStorm: `phpstorm://open?file=%f&line=%l` +- IntelliJ IDEA: `idea://open?file=%f&line=%l` +- Sublime Text: `subl://open?url=file://%f&line=%l` +- TextMate: `txmt://open?url=file://%f&line=%l` + +The **Diagnostics** section shows request and response metadata, common server fields, framework versions, defined constant names, included files, and memory usage. Both header lists show values by default and mask credential headers such as `Authorization`, `API-Key`, `Cookie`, and `Set-Cookie`. Add application-specific header names to `Config\Exceptions::$sensitiveDataInTrace` to mask those values as well. Header names are matched case-insensitively. + +Query, form, and cookie values stay masked by default. Add specific field names under `query`, `form`, or `cookies` in `Config\Exceptions::$diagnosticValues` to show their values. Common credential fields, configured session and CSRF cookies, and fields matched by `Config\Exceptions::$sensitiveDataInTrace` stay masked. + +When the CLI shows a backtrace, a short source excerpt appears below the exception message and location. A `>` marks the exception's throw site when the source is available. + +When PHP captures arguments in exception traces, select a stack frame and expand **Arguments** to inspect the values passed to the named function. The HTML and CLI views and backtrace logs show array keys and values up to size and depth limits and mark circular references. Object arguments show their class name. The copied report omits argument values. + +The HTML and CLI views and backtrace logs mask sensitive arguments by parameter name, position, or value when the value contains a URL with embedded credentials or a `password=` pair. Add application-specific parameter names or positions to `Config\Exceptions::$sensitiveDataInTrace`. Detailed API error responses include frame metadata when `SHOW_DEBUG_BACKTRACE` is enabled and always omit trace arguments. + You should customize all of the error views in the **app/Views/errors/html** folder for your site. You can also create error views for specific HTTP status codes. For example, if you want to create an error view for "400 Bad Request", add **error_400.php**. diff --git a/docs/guides/first-app/index.md b/docs/guides/first-app/index.md index c0588294d3fe..debde6863c71 100644 --- a/docs/guides/first-app/index.md +++ b/docs/guides/first-app/index.md @@ -87,8 +87,8 @@ In addition to this, CodeIgniter has some helpful error pages when you hit excep There are a couple of things to note here: -1. Hovering over the red header at the top reveals a **search** link that will open up DuckDuckGo.com in a new tab and search for the exception. -2. Clicking the **arguments** link on any line in the Backtrace will expand a list of the arguments that were passed into that function call. +1. Select a frame in the **Stack trace** to inspect its source code. +2. Expand **Arguments** below the source when PHP captured arguments for the selected frame. Everything else should be clear when you see it. diff --git a/docs/images/error.png b/docs/images/error.png index 14fac852d48f..aff5562d3284 100644 Binary files a/docs/images/error.png and b/docs/images/error.png differ diff --git a/docs/installation/upgrade_480.md b/docs/installation/upgrade_480.md index 6a8b725e24b2..1cbd53b7aa40 100644 --- a/docs/installation/upgrade_480.md +++ b/docs/installation/upgrade_480.md @@ -126,6 +126,16 @@ Config classes that override `getEnvValue()` or `initEnvValue()` keep the previo `RouteCollection` no longer applies `esc(strip_tags())` to namespace, controller, and method values, including custom controllers passed to `resource()` and `presenter()`. Applications relying on HTML tags being stripped or special characters being HTML-encoded must preprocess these values before passing them to the router. Values originating from untrusted sources should be restricted to an explicit allowlist of permitted handlers. +### Detailed Exception Responses + +Detailed API error responses keep the `trace` field. It is empty when `SHOW_DEBUG_BACKTRACE` is disabled. When enabled, each frame contains call and source metadata. Remove any dependency on the former `args` field in API clients. + +After a fatal shutdown error, the log retains the previous exception's trace with argument values omitted. The rendered error includes that trace only when `SHOW_DEBUG_BACKTRACE` is enabled. + +The detailed HTML error page masks known credential headers in requests and responses. Add custom sensitive header names to `Config\Exceptions::$sensitiveDataInTrace`. Query, form, and cookie values require an entry in `Config\Exceptions::$diagnosticValues`. See [Error Reporting](../general/errors.md#error-reporting). + +CLI error output and logs now show bounded array previews. Formatted traces display instance calls as `Class()->method()`. Diagnostic fields and trace arguments use `[redacted]` for masked values. Update any snapshots or scripts that expect the previous call syntax, asterisks for masked values, or `[...]` for every nonempty trace argument array. + ## Breaking Enhancements ### Log Handler Interface @@ -157,12 +167,18 @@ The following files received significant changes (including deprecations or visu #### Config +- **app/Config/Exceptions.php** + - Added `$diagnosticValues` to choose which query, form, and cookie values the detailed HTML error page shows. + - **app/Config/Filters.php** - Added a new filter named `requestid` that adds a unique request ID to each request in the application's context. - **app/Config/Generators.php** - `Config\Generators::$views` added entries for `make:request`, `make:test`, and `make:transformer`, and dropped the stale `session:migration` entry. +- **app/Config/Kint.php** + - Added `$fileLinkFormat` to configure editor links in the Debug Toolbar and detailed error page. It defaults to `null`, so existing Xdebug link settings continue to apply. + - **app/Config/Logger.php** - `Config\Logger::$handlers` added a new key `stopChainOnFailure` to the `FileHandler` and `ErrorlogHandler` settings. @@ -183,17 +199,14 @@ The following files received significant changes (including deprecations or visu - **app/Views/errors/cli/error_exception.php** - Shows the backtrace also when the command runs with `-v`. -- **app/Views/errors/html/debug.css** - - Added styles for the **Copy Details** button. - -- **app/Views/errors/html/debug.js** - - Added clipboard handling for the **Copy Details** button. +- **app/Views/errors/html/error_exception.php** + - Refreshed the detailed HTML exception page with selectable stack frames and request, response, server, file, and memory diagnostics. Merge this view together with **exception.css** and **error_report.php** to adopt the new layout. -- **app/Views/errors/html/error_exception.php** - - Added a **Copy Details** button to detailed HTML exception pages. +- **app/Views/errors/html/exception.css** + - Added styles for the detailed HTML exception page. - **app/Views/errors/html/error_report.php** - - Added a Markdown error report partial used by the **Copy Details** button. + - Added a Markdown error report partial used by **Copy Details**. It includes an excerpt from the first frame if its source is available and lists stack frame names when backtraces are enabled. ### All Changes diff --git a/phpstan.dist.neon b/phpstan.dist.neon index cae51ff7d5c0..f422e9de531f 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -9,6 +9,8 @@ parameters: level: 6 bootstrapFiles: - phpstan-bootstrap.php + dynamicConstantNames: + - SHOW_DEBUG_BACKTRACE paths: - admin/starter/tests - app diff --git a/system/Autoloader/Autoloader.php b/system/Autoloader/Autoloader.php index 3f4bf2231b43..3212441a2874 100644 --- a/system/Autoloader/Autoloader.php +++ b/system/Autoloader/Autoloader.php @@ -23,6 +23,7 @@ use Config\Kint as KintConfig; use Config\Modules; use Kint\Kint; +use Kint\Renderer\AbstractRenderer; use Kint\Renderer\CliRenderer; use Kint\Renderer\RichRenderer; @@ -492,6 +493,13 @@ private function configureKint(): void Kint::$display_called_from = $config->displayCalledFrom; Kint::$expanded = $config->expanded; + // @phpstan-ignore function.alreadyNarrowedType + $fileLinkFormat = property_exists($config, 'fileLinkFormat') ? $config->fileLinkFormat : null; + + if (is_string($fileLinkFormat)) { + AbstractRenderer::$file_link_format = $fileLinkFormat; + } + if (isset($config->plugins) && is_array($config->plugins)) { Kint::$plugins = $config->plugins; } diff --git a/system/Common.php b/system/Common.php index 01d8507e3764..4875e0c0eac3 100644 --- a/system/Common.php +++ b/system/Common.php @@ -21,6 +21,8 @@ use CodeIgniter\Cookie\Exceptions\CookieException; use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\ConnectionInterface; +use CodeIgniter\Debug\Backtrace; +use CodeIgniter\Debug\Inspection\Frames; use CodeIgniter\Debug\Timer; use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\Exceptions\RuntimeException; @@ -39,6 +41,7 @@ use Config\App; use Config\Database; use Config\DocTypes; +use Config\Exceptions as ExceptionsConfig; use Config\Logger; use Config\Services; use Config\View; @@ -955,7 +958,7 @@ function remove_invisible_characters(string $str, bool $urlEncoded = true): stri if (! function_exists('render_backtrace')) { /** - * Renders a backtrace in a nice string format. + * Renders a raw PHP trace from the supplied starting location, when available. * * @param list * }> $backtrace + * @param list|null $sensitiveKeys */ - function render_backtrace(array $backtrace): string + function render_backtrace(array $backtrace, ?string $file = null, ?int $line = null, ?array $sensitiveKeys = null): string { - $backtraces = []; + $sensitiveKeys ??= config(ExceptionsConfig::class)->sensitiveDataInTrace; - foreach ($backtrace as $index => $trace) { - $frame = $trace + ['file' => '[internal function]', 'line' => 0, 'class' => '', 'type' => '', 'args' => []]; - - if ($frame['file'] !== '[internal function]') { - $frame['file'] = sprintf('%s(%s)', $frame['file'], $frame['line']); - } - - unset($frame['line']); - $idx = $index; - $idx = str_pad((string) ++$idx, 2, ' ', STR_PAD_LEFT); - - $args = implode(', ', array_map(static fn ($value): string => match (true) { - is_object($value) => sprintf('Object(%s)', $value::class), - is_array($value) => $value !== [] ? '[...]' : '[]', - $value === null => 'null', - is_resource($value) => sprintf('resource (%s)', get_resource_type($value)), - default => var_export($value, true), - }, $frame['args'])); - - $backtraces[] = sprintf( - '%s %s: %s%s%s(%s)', - $idx, - clean_path($frame['file']), - $frame['class'], - $frame['type'], - $frame['function'], - $args, - ); - } - - return implode("\n", $backtraces); + return implode("\n", Backtrace::lines( + Frames::fromTrace($backtrace, $file, $line), + sensitiveKeys: $sensitiveKeys, + )); } } diff --git a/system/Database/MySQLi/Connection.php b/system/Database/MySQLi/Connection.php index f3fe8076889d..b0bdf2f763f9 100644 --- a/system/Database/MySQLi/Connection.php +++ b/system/Database/MySQLi/Connection.php @@ -389,7 +389,7 @@ protected function execute(string $sql) 'message' => $e->getMessage(), 'exFile' => clean_path($e->getFile()), 'exLine' => $e->getLine(), - 'trace' => render_backtrace($e->getTrace()), + 'trace' => render_backtrace($e->getTrace(), $e->getFile(), $e->getLine()), ]); if ($e->getCode() === 1213 && $this->transDepth > 0) { diff --git a/system/Database/OCI8/Connection.php b/system/Database/OCI8/Connection.php index af6a32d40621..d8d1599278c4 100644 --- a/system/Database/OCI8/Connection.php +++ b/system/Database/OCI8/Connection.php @@ -321,7 +321,7 @@ protected function execute(string $sql) 'message' => $e->getMessage(), 'exFile' => clean_path($e->getFile()), 'exLine' => $e->getLine(), - 'trace' => render_backtrace($trace), + 'trace' => render_backtrace($trace, $e->getFile(), $e->getLine()), ]); $error = $this->error(); diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index e6ae70140dff..9d307e5b9055 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -291,7 +291,7 @@ protected function execute(string $sql) 'message' => $e->getMessage(), 'exFile' => clean_path($e->getFile()), 'exLine' => $e->getLine(), - 'trace' => render_backtrace($trace), + 'trace' => render_backtrace($trace, $e->getFile(), $e->getLine()), ]); $exception = new DatabaseException($e->getMessage(), 0, $e); @@ -332,15 +332,17 @@ protected function execute(string $sql) $message = (string) pg_result_error($failedResult); $trace = debug_backtrace(); $first = array_shift($trace); + $file = $first['file'] ?? null; + $line = $first['line'] ?? null; $this->lastFailedResult = $failedResult; // Log only the first line; pg_result_error() appends "LINE N: ..." context. log_message('error', "{message}\nin {exFile} on line {exLine}.\n{trace}", [ 'message' => explode("\n", $message)[0], - 'exFile' => clean_path($first['file']), - 'exLine' => $first['line'], - 'trace' => render_backtrace($trace), + 'exFile' => $file === null ? '[internal function]' : clean_path($file), + 'exLine' => $line ?? 0, + 'trace' => render_backtrace($trace, $file, $line), ]); $exception = $this->createDatabaseException($message, $sqlstate); @@ -366,12 +368,14 @@ private function handleConnectionError(): false $message = pg_last_error($this->connID); $trace = debug_backtrace(); $first = array_shift($trace); + $file = $first['file'] ?? null; + $line = $first['line'] ?? null; log_message('error', "{message}\nin {exFile} on line {exLine}.\n{trace}", [ 'message' => $message, - 'exFile' => clean_path($first['file']), - 'exLine' => $first['line'], - 'trace' => render_backtrace($trace), + 'exFile' => $file === null ? '[internal function]' : clean_path($file), + 'exLine' => $line ?? 0, + 'trace' => render_backtrace($trace, $file, $line), ]); $exception = new DatabaseException($message); diff --git a/system/Database/SQLSRV/Connection.php b/system/Database/SQLSRV/Connection.php index ccc17f49073a..337302136de4 100644 --- a/system/Database/SQLSRV/Connection.php +++ b/system/Database/SQLSRV/Connection.php @@ -597,13 +597,15 @@ protected function execute(string $sql) if ($stmt === false) { $trace = debug_backtrace(); $first = array_shift($trace); + $file = $first['file'] ?? null; + $line = $first['line'] ?? null; $message = $this->getAllErrorMessages(); log_message('error', "{message}\nin {exFile} on line {exLine}.\n{trace}", [ 'message' => $message, - 'exFile' => clean_path($first['file']), - 'exLine' => $first['line'], - 'trace' => render_backtrace($trace), + 'exFile' => $file === null ? '[internal function]' : clean_path($file), + 'exLine' => $line ?? 0, + 'trace' => render_backtrace($trace, $file, $line), ]); $error = $this->error(); diff --git a/system/Database/SQLite3/Connection.php b/system/Database/SQLite3/Connection.php index 97033eecb9b3..4d3c415db8fc 100644 --- a/system/Database/SQLite3/Connection.php +++ b/system/Database/SQLite3/Connection.php @@ -227,7 +227,7 @@ protected function execute(string $sql) 'message' => $e->getMessage(), 'exFile' => clean_path($e->getFile()), 'exLine' => $e->getLine(), - 'trace' => render_backtrace($e->getTrace()), + 'trace' => render_backtrace($e->getTrace(), $e->getFile(), $e->getLine()), ]); $error = $this->error(); diff --git a/system/Debug/Backtrace.php b/system/Debug/Backtrace.php new file mode 100644 index 000000000000..06a538d61cad --- /dev/null +++ b/system/Debug/Backtrace.php @@ -0,0 +1,359 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug; + +use CodeIgniter\Debug\Inspection\Frame; +use CodeIgniter\Debug\Inspection\Frames; +use ReflectionException; +use ReflectionFunction; +use ReflectionMethod; +use ReflectionParameter; +use ReflectionReference; +use SensitiveParameterValue; + +/** + * Formats backtraces for display and logging. + * + * @internal + */ +final class Backtrace +{ + /** + * Display text for a masked value. + */ + public const REDACTED_TEXT = '[redacted]'; + + /** + * Maximum arguments shown per call. + */ + private const MAX_ARGUMENTS = 20; + + /** + * Maximum items shown per array. + */ + private const MAX_ARRAY_ITEMS = 8; + + /** + * Maximum array nesting expanded in an argument. + */ + private const MAX_ARRAY_DEPTH = 3; + + /** + * Total values visited per argument, including nested items. + */ + private const MAX_ARGUMENT_VALUES = 32; + + /** + * Byte limit for a formatted scalar before the ellipsis. + */ + private const MAX_VALUE_BYTES = 500; + + /** + * Parameter names and array keys masked by default. + */ + private const SENSITIVE_ARGUMENTS = [ + 'password', + 'password_confirmation', + 'token', + 'access_token', + 'refresh_token', + 'secret', + 'client_secret', + 'apikey', + 'api_key', + 'dsn', + 'authorization', + 'proxy-authorization', + 'cookie', + 'set-cookie', + 'x-api-key', + 'x-auth-token', + 'x-csrf-token', + 'x-xsrf-token', + 'http_authorization', + 'http_proxy_authorization', + 'http_cookie', + 'php_auth_pw', + ]; + + /** + * Format a call with bounded, redacted arguments. + * + * @param list $sensitiveKeys + */ + public static function call(Frame $frame, array $sensitiveKeys = []): string + { + $arguments = self::formatArguments($frame, $sensitiveKeys, multiline: false); + $hidden = count($frame->arguments) - count($arguments); + + if ($hidden > 0) { + $arguments[] = sprintf('… +%d more', $hidden); + } + + return $frame->call(implode(', ', $arguments)); + } + + /** + * Format frames as numbered plain-text lines for logs and reports. + * + * @param list $sensitiveKeys + * + * @return list + */ + public static function lines(Frames $trace, bool $includeArguments = true, array $sensitiveKeys = []): array + { + $lines = []; + + foreach ($trace as $index => $frame) { + $lines[] = sprintf( + '%2d %s %s', + $index + 1, + $includeArguments ? self::call($frame, $sensitiveKeys) : $frame->call(), + self::location($frame->file, $frame->line), + ); + } + + return $lines; + } + + /** + * Strip the project root from paths inside the project. + */ + public static function relativePath(string $file): string + { + return str_starts_with($file, ROOTPATH) ? substr($file, strlen(ROOTPATH)) : $file; + } + + /** + * Format a source location for logs and reports or as path:line for terminal links. + */ + public static function location(?string $file, ?int $line, bool $cli = false): string + { + if ($file === null || $file === '') { + return '[internal function]'; + } + + $source = Frame::sourceLocation($file, $line); + $path = self::relativePath($source['file']); + $line = $source['line'] ?? null; + + if ($cli) { + return $line === null ? $path : sprintf('%s:%d', $path, $line); + } + + return $line === null ? sprintf('in %s', $path) : sprintf('in %s (line %d)', $path, $line); + } + + /** + * Format a bounded, redacted preview keyed by parameter name or position. + * + * @param list $sensitiveKeys + * + * @return array + */ + public static function argumentPreview(Frame $frame, array $sensitiveKeys = []): array + { + return self::formatArguments($frame, $sensitiveKeys, multiline: true); + } + + /** + * @param list $sensitiveKeys + * + * @return array + */ + private static function formatArguments(Frame $frame, array $sensitiveKeys, bool $multiline): array + { + if ($frame->arguments === []) { + return []; + } + + $keys = [...self::SENSITIVE_ARGUMENTS, ...array_map(strtolower(...), $sensitiveKeys)]; + $parameters = self::parameters($frame); + $formatted = []; + + foreach (array_slice($frame->arguments, 0, self::MAX_ARGUMENTS, true) as $index => $value) { + $name = $parameters[$index] ?? null; + $path = self::argumentName($parameters, $index); + $remaining = self::MAX_ARGUMENT_VALUES; + $reference = ReflectionReference::fromArrayElement($frame->arguments, $index)?->getId(); + + $formatted[$name?->getName() ?? $index] = self::formatValue( + $value, + $keys, + $path, + (string) $index, + $multiline, + $remaining, + $reference, + ); + } + + return $formatted; + } + + /** + * @param list $sensitiveKeys + * @param array $ancestors + */ + private static function formatValue( + mixed $value, + array $sensitiveKeys, + string $path, + string $position, + bool $multiline, + int &$remaining, + ?string $reference, + int $depth = 0, + array $ancestors = [], + ): string { + $remaining--; + + if (self::isSensitiveArgument($value, $sensitiveKeys, $path, $position)) { + return self::REDACTED_TEXT; + } + + if (! is_array($value)) { + return self::formatScalar($value, $multiline); + } + + if ($value === []) { + return '[]'; + } + + if ($reference !== null) { + if (isset($ancestors[$reference])) { + return '*RECURSION*'; + } + + $ancestors[$reference] = true; + } + + if ($depth >= self::MAX_ARRAY_DEPTH) { + return '[...]'; + } + + $rows = []; + $list = array_is_list($value); + $indent = $multiline ? str_repeat(' ', $depth + 1) : ''; + + foreach (array_slice($value, 0, self::MAX_ARRAY_ITEMS, true) as $key => $item) { + if ($remaining === 0) { + break; + } + + $formatted = self::formatValue( + $item, + $sensitiveKeys, + sprintf('%s/%s', $path, $key), + sprintf('%s/%s', $position, $key), + $multiline, + $remaining, + ReflectionReference::fromArrayElement($value, $key)?->getId(), + $depth + 1, + $ancestors, + ); + $row = $list ? $formatted : sprintf('%s => %s', self::formatScalar($key, $multiline), $formatted); + $rows[] = $multiline ? sprintf('%s%s,', $indent, $row) : $row; + } + + $hidden = count($value) - count($rows); + + if ($hidden > 0) { + $rows[] = sprintf('%s… +%d more', $indent, $hidden); + } + + if (! $multiline) { + return sprintf('[%s]', implode(', ', $rows)); + } + + return sprintf("[\n%s\n%s]", implode("\n", $rows), str_repeat(' ', $depth)); + } + + /** + * @return list + */ + private static function parameters(Frame $frame): array + { + try { + $reflection = $frame->class !== null + ? new ReflectionMethod($frame->class, $frame->function) + : new ReflectionFunction($frame->function); + + return $reflection->getParameters(); + } catch (ReflectionException) { + return []; + } + } + + /** + * @param list $parameters + */ + private static function argumentName(array $parameters, int|string $index): string + { + $parameter = $parameters[$index] ?? null; + $last = $parameters === [] ? null : $parameters[array_key_last($parameters)]; + + return $parameter?->getName() ?? ($last?->isVariadic() ? $last->getName() : (string) $index); + } + + /** + * @param list $keys + */ + private static function isSensitiveArgument(mixed $value, array $keys, string $path, string $position): bool + { + if ($value instanceof SensitiveParameterValue) { + return true; + } + + $path = sprintf('/%s', strtolower($path)); + $position = sprintf('/%s', strtolower($position)); + + foreach ($keys as $key) { + $suffix = sprintf('/%s', $key); + + if (str_ends_with($path, $suffix) || str_ends_with($position, $suffix)) { + return true; + } + } + + return is_string($value) && preg_match( + '~(?:^|\s)[a-z][a-z0-9+.-]*://[^\s/@]+:[^\s/@]*@|(?:^|[;\s:])(?:password|passwd|pwd)\s*=~i', + $value, + ) === 1; + } + + private static function formatScalar(mixed $value, bool $multiline): string + { + $truncated = is_string($value) && strlen($value) > self::MAX_VALUE_BYTES; + + if ($truncated) { + $value = mb_strcut($value, 0, self::MAX_VALUE_BYTES, 'UTF-8'); + } + + $text = match (true) { + is_object($value) => sprintf('Object(%s)', $value::class), + $value === null => 'null', + is_resource($value) => sprintf('resource (%s)', get_resource_type($value)), + default => var_export($value, true), + }; + + if (! $multiline) { + $text = addcslashes($text, "\0..\37\177"); + } + + return $truncated || strlen($text) > self::MAX_VALUE_BYTES + ? sprintf('%s…', mb_strcut($text, 0, self::MAX_VALUE_BYTES, 'UTF-8')) + : $text; + } +} diff --git a/system/Debug/BaseExceptionHandler.php b/system/Debug/BaseExceptionHandler.php index 70a60f5f997e..3b12fd5bb6e0 100644 --- a/system/Debug/BaseExceptionHandler.php +++ b/system/Debug/BaseExceptionHandler.php @@ -13,7 +13,10 @@ namespace CodeIgniter\Debug; +use CodeIgniter\Debug\Inspection\Frame; +use CodeIgniter\Debug\Inspection\Inspector; use Config\Exceptions as ExceptionsConfig; +use ReflectionReference; use Throwable; /** @@ -62,27 +65,29 @@ public function __construct(ExceptionsConfig $config) */ protected function collectVars(Throwable $exception, int $statusCode): array { - // Get the first exception. - $firstException = $exception; - - while (($prevException = $firstException->getPrevious()) instanceof Throwable) { - $firstException = $prevException; - } - - $trace = $firstException->getTrace(); + $trace = (new Inspector($exception))->rootCause()->getTrace(); if ($this->config->sensitiveDataInTrace !== []) { $trace = $this->maskSensitiveData($trace, $this->config->sensitiveDataInTrace); } + return $this->collectExceptionDetails($exception, $statusCode) + ['trace' => $trace]; + } + + /** + * @return array{title: string, type: string, code: int, message: string, file: string, line: int} + */ + protected function collectExceptionDetails(Throwable $exception, int $statusCode): array + { + $location = Frame::sourceLocation($exception->getFile(), $exception->getLine()); + return [ 'title' => $exception::class, 'type' => $exception::class, 'code' => $statusCode, 'message' => $exception->getMessage(), - 'file' => $exception->getFile(), - 'line' => $exception->getLine(), - 'trace' => $trace, + 'file' => $location['file'], + 'line' => $location['line'] ?? $exception->getLine(), ]; } @@ -97,43 +102,116 @@ protected function collectVars(Throwable $exception, int $statusCode): array protected function maskSensitiveData(array $trace, array $keysToMask, string $path = ''): array { foreach ($trace as $i => $line) { - $trace[$i]['args'] = $this->maskData($line['args'], $keysToMask, $path); + if (isset($line['args'])) { + $trace[$i]['args'] = $this->maskData($line['args'], $keysToMask, $path); + } } return $trace; } + /** + * Apply configured trace redaction rules to an array shown by an error view. + * + * @param array $data + * @param list $additionalKeys + * + * @return array + */ + protected function redactDiagnosticData(array $data, array $additionalKeys = [], bool $caseInsensitive = false): array + { + $keys = [...$this->config->sensitiveDataInTrace, ...$additionalKeys]; + + if ($caseInsensitive) { + $keys = array_map(strtolower(...), $keys); + + foreach ($data as $name => $value) { + $data[$name] = in_array(strtolower((string) $name), $keys, true) ? Backtrace::REDACTED_TEXT : $value; + } + + return $data; + } + + return $this->maskData($data, $keys); + } + + /** + * @param array $data + * @param list $sensitiveKeys + * + * @return array + */ + protected function diagnosticFields(array $data, string $section, array $sensitiveKeys = []): array + { + $allowed = $this->config->diagnosticValues[$section] ?? []; + + foreach (array_keys($data) as $name) { + if (! in_array((string) $name, $allowed, true)) { + $data[$name] = Backtrace::REDACTED_TEXT; + } + } + + return $this->redactDiagnosticData($data, $sensitiveKeys); + } + + /** + * @return array + */ + protected function previewDiagnosticArguments(Frame $frame): array + { + return Backtrace::argumentPreview($frame, $this->config->sensitiveDataInTrace); + } + /** * @param array|object $args * @param list $keysToMask + * @param array $ancestors * * @return array|object */ - private function maskData(mixed $args, array $keysToMask, string $path = ''): mixed + private function maskData(mixed $args, array $keysToMask, string $path = '', array $ancestors = []): mixed { + if (is_object($args)) { + $id = spl_object_id($args); + + if (isset($ancestors[$id])) { + return $args; + } + + $ancestors[$id] = true; + } + foreach ($keysToMask as $key) { $explode = explode('/', $key); $index = end($explode); if (str_starts_with(strrev($path . '/' . $index), strrev($key))) { if (is_array($args) && array_key_exists($index, $args)) { - $args[$index] = '******************'; + $args[$index] = Backtrace::REDACTED_TEXT; } elseif ( is_object($args) && property_exists($args, $index) && isset($args->{$index}) && is_scalar($args->{$index}) ) { - $args->{$index} = '******************'; + $args->{$index} = Backtrace::REDACTED_TEXT; } } } if (is_array($args)) { foreach ($args as $pathKey => $subarray) { - $args[$pathKey] = $this->maskData($subarray, $keysToMask, $path . '/' . $pathKey); + $reference = ReflectionReference::fromArrayElement($args, $pathKey)?->getId(); + + if ($reference !== null && isset($ancestors[$reference])) { + continue; + } + + $branch = $reference === null ? $ancestors : $ancestors + [$reference => true]; + + $args[$pathKey] = $this->maskData($subarray, $keysToMask, $path . '/' . $pathKey, $branch); } } elseif (is_object($args)) { foreach ($args as $pathKey => $subarray) { - $args->{$pathKey} = $this->maskData($subarray, $keysToMask, $path . '/' . $pathKey); + $args->{$pathKey} = $this->maskData($subarray, $keysToMask, $path . '/' . $pathKey, $ancestors); } } @@ -143,8 +221,6 @@ private function maskData(mixed $args, array $keysToMask, string $path = ''): mi /** * Describes memory usage in real-world units. Intended for use * with memory_get_usage, etc. - * - * @used-by app/Views/errors/html/error_exception.php */ protected static function describeMemory(int $bytes): string { @@ -156,8 +232,6 @@ protected static function describeMemory(int $bytes): string /** * Creates a syntax-highlighted version of a PHP file. * - * @used-by app/Views/errors/html/error_exception.php - * * @return bool|string */ protected static function highlightFile(string $file, int $lineNumber, int $lines = 15) @@ -238,6 +312,16 @@ protected static function highlightFile(string $file, int $lineNumber, int $line * @param string|null $viewFile */ protected function render(Throwable $exception, int $statusCode, $viewFile = null): void + { + $this->renderWithViewData($exception, $statusCode, $viewFile, []); + } + + /** + * Render an error view with additional variables supplied by the handler. + * + * @param array $viewData + */ + protected function renderWithViewData(Throwable $exception, int $statusCode, ?string $viewFile, array $viewData): void { if ($viewFile === null) { echo 'The error view file was not specified. Cannot display error view.'; @@ -251,8 +335,8 @@ protected function render(Throwable $exception, int $statusCode, $viewFile = nul exit(1); } - echo (function () use ($exception, $statusCode, $viewFile): string { - $vars = $this->collectVars($exception, $statusCode); + echo (function () use ($exception, $statusCode, $viewFile, $viewData): string { + $vars = $this->collectVars($exception, $statusCode) + ['config' => $this->config] + $viewData; extract($vars, EXTR_SKIP); // CLI error views output to STDERR/STDOUT, so ob_start() does not work. diff --git a/system/Debug/ConsoleExceptionRenderer.php b/system/Debug/ConsoleExceptionRenderer.php new file mode 100644 index 000000000000..e0d47faa25fd --- /dev/null +++ b/system/Debug/ConsoleExceptionRenderer.php @@ -0,0 +1,158 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug; + +use CodeIgniter\CLI\Output; +use CodeIgniter\Debug\Inspection\CodeSnippet; +use CodeIgniter\Debug\Inspection\Frame; +use CodeIgniter\Debug\Inspection\Frames; +use CodeIgniter\Debug\Inspection\Inspector; +use Throwable; + +/** + * Writes exception details to the terminal. + * + * @internal + */ +final class ConsoleExceptionRenderer +{ + /** + * Snippet prefix width excluding the line number digits. + */ + private const SNIPPET_PREFIX_WIDTH = 7; + + /** + * Maximum indent for calls below their numbered locations. + */ + private const BACKTRACE_CALL_INDENT = 7; + + /** + * Render the exception, source excerpt, causes, and enabled backtrace. + * + * @param list $sensitiveKeys + */ + public static function render(Throwable $exception, string $message, Output $output, array $sensitiveKeys = []): void + { + $showBacktrace = (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE) || $output->isVerbose(); + + self::writeSummary($exception, $message, $output); + self::writeSnippet($exception->getFile(), $exception->getLine(), $output); + $output->deferNewLine(); + + $chain = (new Inspector($exception))->chain(); + self::writeCauses(array_slice($chain, 1), $output); + + if ($showBacktrace) { + self::writeBacktrace($chain[array_key_last($chain)], $output, $sensitiveKeys); + } + } + + private static function writeSummary(Throwable $exception, string $message, Output $output): void + { + $output->write(sprintf('[%s]', $exception::class), 'light_gray', 'red'); + $output->write($message); + + $location = Backtrace::location($exception->getFile(), $exception->getLine(), cli: true); + $output->write(sprintf('in %s', $output->color($location, 'green'))); + } + + /** + * Write a terminal-width source excerpt at the exception's throw site. + */ + private static function writeSnippet(string $file, int $line, Output $output): void + { + $location = Frame::sourceLocation($file, $line); + + $line = $location['line'] ?? $line; + $lines = CodeSnippet::get($location['file'], $line, highlight: false); + + if ($lines === []) { + return; + } + + $digits = strlen((string) array_key_last($lines)); + $width = $output->getTerminal()->getWidth() - $digits - self::SNIPPET_PREFIX_WIDTH; + + if ($width < 1) { + return; + } + + $output->deferNewLine(); + + foreach ($lines as $number => $text) { + $current = $number === $line; + $source = addcslashes(str_replace("\t", ' ', $text), "\0..\37\177"); + $output->write(sprintf( + ' %s %*d | %s', + $current ? '>' : ' ', + $digits, + $number, + mb_strimwidth($source, 0, $width, '…', 'UTF-8'), + ), $current ? 'yellow' : ''); + } + } + + /** + * @param list $causes + */ + private static function writeCauses(array $causes, Output $output): void + { + foreach ($causes as $cause) { + $output->write(' Caused by:'); + $output->write(sprintf(' %s', $output->color(sprintf('[%s]', $cause::class), 'light_gray', 'red'))); + $output->write(sprintf(' %s', $cause->getMessage())); + $location = Backtrace::location($cause->getFile(), $cause->getLine(), cli: true); + $output->write(sprintf(' in %s', $output->color($location, 'green'))); + $output->deferNewLine(); + } + } + + /** + * Write the numbered trace with calls wrapped to the terminal width. + * + * @param list $sensitiveKeys + */ + private static function writeBacktrace(Throwable $rootCause, Output $output, array $sensitiveKeys): void + { + $trace = Frames::fromException($rootCause); + + $output->write('Backtrace:', 'green'); + + $columns = max(1, $output->getTerminal()->getWidth()); + $padding = min(self::BACKTRACE_CALL_INDENT, max(0, $columns - 2)); + $indent = str_repeat(' ', $padding); + $width = $columns - $padding; + + foreach ($trace as $index => $frame) { + $location = Backtrace::location($frame->file, $frame->line, cli: true); + $output->write(sprintf('%3d %s', $index + 1, $output->color($location, 'yellow'))); + + $call = Backtrace::call($frame, $sensitiveKeys); + + foreach (explode(PHP_EOL, $output->wrap($call, $width)) as $line) { + // The standard wrapper leaves words wider than a line intact. + while (mb_strwidth($line, 'UTF-8') > $width) { + $part = mb_strimwidth($line, 0, $width, '', 'UTF-8'); + $part = $part === '' ? mb_substr($line, 0, 1, 'UTF-8') : $part; + $output->write($indent . $part); + $line = substr($line, strlen($part)); + } + + $output->write($indent . $line); + } + + $output->deferNewLine(); + } + } +} diff --git a/system/Debug/ExceptionHandler.php b/system/Debug/ExceptionHandler.php index 6e4491209ac0..e5cd47e37dd7 100644 --- a/system/Debug/ExceptionHandler.php +++ b/system/Debug/ExceptionHandler.php @@ -13,10 +13,11 @@ namespace CodeIgniter\Debug; -use Closure; use CodeIgniter\API\ResponseTrait; use CodeIgniter\Boot; use CodeIgniter\CLI\CLI; +use CodeIgniter\Debug\Inspection\Frames; +use CodeIgniter\Debug\Inspection\Inspector; use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\HTTP\CLIRequest; use CodeIgniter\HTTP\Exceptions\HTTPException; @@ -84,15 +85,9 @@ public function handle( if (! str_contains($request->getHeaderLine('accept'), 'text/html')) { // If display_errors is enabled, shows the error details. $data = $this->isDisplayErrorsEnabled() - ? $this->collectVars($exception, $statusCode) + ? $this->collectExceptionDetails($exception, $statusCode) + ['trace' => $this->apiTrace($exception)] : ''; - // Sanitize data to remove non-JSON-serializable values (resources, closures) - // before formatting for API responses (JSON, XML, etc.) - if ($data !== '') { - $data = $this->sanitizeData($data); - } - $this->respond($data, $statusCode)->send(); if ($this->shouldExit()) { @@ -125,7 +120,10 @@ public function handle( // Displays the HTML or CLI error code. if ($request instanceof IncomingRequest) { - $this->render($exception, $statusCode, $viewFile); + $this->renderWithViewData($exception, $statusCode, $viewFile, [ + 'request' => $this->request, + 'response' => $this->response, + ]); } else { CLI::redirectToStderr(fn () => $this->render($exception, $statusCode, $viewFile)); } @@ -192,51 +190,22 @@ private function isDisplayErrorsEnabled(): bool } /** - * Sanitizes data to remove non-JSON-serializable values like resources and closures. - * This is necessary for API responses that need to be JSON/XML encoded. + * Return only scalar frame metadata suitable for serialization. * - * @param array $seen Used internally to prevent infinite recursion + * @return list */ - private function sanitizeData(mixed $data, array &$seen = []): mixed + private function apiTrace(Throwable $exception): array { - $type = gettype($data); - - switch ($type) { - case 'resource': - case 'resource (closed)': - return '[Resource #' . (int) $data . ']'; - - case 'array': - $result = []; - - foreach ($data as $key => $value) { - $result[$key] = $this->sanitizeData($value, $seen); - } - - return $result; - - case 'object': - $oid = spl_object_id($data); - if (isset($seen[$oid])) { - return '[' . $data::class . ' Object *RECURSION*]'; - } - $seen[$oid] = true; - - if ($data instanceof Closure) { - return '[Closure]'; - } - - $result = []; - - foreach ((array) $data as $key => $value) { - $cleanKey = preg_replace('/^\x00.*\x00/', '', (string) $key); - $result[$cleanKey] = $this->sanitizeData($value, $seen); - } + if (! defined('SHOW_DEBUG_BACKTRACE') || ! SHOW_DEBUG_BACKTRACE) { + return []; + } - return $result; + $trace = []; - default: - return $data; + foreach (Frames::fromException((new Inspector($exception))->rootCause()) as $frame) { + $trace[] = $frame->metadata(); } + + return $trace; } } diff --git a/system/Debug/Exceptions.php b/system/Debug/Exceptions.php index 72151988148d..343322c7dfa6 100644 --- a/system/Debug/Exceptions.php +++ b/system/Debug/Exceptions.php @@ -14,6 +14,8 @@ namespace CodeIgniter\Debug; use CodeIgniter\API\ResponseTrait; +use CodeIgniter\Debug\Inspection\Frames; +use CodeIgniter\Debug\Inspection\Inspector; use CodeIgniter\Exceptions\HasExitCodeInterface; use CodeIgniter\Exceptions\HTTPExceptionInterface; use CodeIgniter\HTTP\CLIRequest; @@ -93,21 +95,26 @@ public function exceptionHandler(Throwable $exception) 'routeInfo' => sprintf('[Method: %s, Route: %s]', $this->request->getMethod(), $uri), 'exFile' => clean_path($exception->getFile()), // {file} refers to THIS file 'exLine' => $exception->getLine(), // {line} refers to THIS line - 'trace' => render_backtrace($exception->getTrace()), + 'trace' => render_backtrace( + $exception->getTrace(), + $exception->getFile(), + $exception->getLine(), + $this->config->sensitiveDataInTrace, + ), ]); - // Get the first exception. - $firstException = $exception; - - while (($prevException = $firstException->getPrevious()) instanceof Throwable) { - $firstException = $prevException; - + foreach (array_slice((new Inspector($exception))->chain(), 1) as $prevException) { log_message('critical', "[Caused by] {exClass}: {message}\nin {exFile} on line {exLine}.\n{trace}", [ 'exClass' => $prevException::class, 'message' => $prevException->getMessage(), 'exFile' => clean_path($prevException->getFile()), // {file} refers to THIS file 'exLine' => $prevException->getLine(), // {line} refers to THIS line - 'trace' => render_backtrace($prevException->getTrace()), + 'trace' => render_backtrace( + $prevException->getTrace(), + $prevException->getFile(), + $prevException->getLine(), + $this->config->sensitiveDataInTrace, + ), ]); } } @@ -174,16 +181,27 @@ public function shutdownHandler() ['type' => $type, 'message' => $message, 'file' => $file, 'line' => $line] = $error; - if ($this->exceptionCaughtByExceptionHandler instanceof Throwable) { - $message .= "\n【Previous Exception】\n" - . $this->exceptionCaughtByExceptionHandler::class . "\n" - . $this->exceptionCaughtByExceptionHandler->getMessage() . "\n" - . $this->exceptionCaughtByExceptionHandler->getTraceAsString(); + if (! in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE], true)) { + return; } - if (in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE], true)) { - $this->exceptionHandler(new ErrorException($message, 0, $type, $file, $line)); + if ($this->exceptionCaughtByExceptionHandler instanceof Throwable) { + $previous = $this->exceptionCaughtByExceptionHandler; + $details = sprintf("【Previous Exception】\n%s\n%s", $previous::class, $previous->getMessage()); + $message .= "\n" . $details; + + if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE) { + $message .= "\n" . implode("\n", Backtrace::lines(Frames::fromException($previous), includeArguments: false)); + } elseif ($this->config->log && ! in_array(ResponseInterface::HTTP_INTERNAL_SERVER_ERROR, $this->config->ignoreCodes, true)) { + // Keep the previous trace in the log when the rendered error hides backtraces. + log_message('critical', "{details}\n{trace}", [ + 'details' => $details, + 'trace' => implode("\n", Backtrace::lines(Frames::fromException($previous), includeArguments: false)), + ]); + } } + + $this->exceptionHandler(new ErrorException($message, 0, $type, $file, $line)); } /** @@ -251,7 +269,7 @@ private function handleDeprecationError(string $message, ?string $file = null, ? 'message' => $message, 'errFile' => clean_path($file ?? ''), 'errLine' => $line ?? 0, - 'trace' => render_backtrace($trace), + 'trace' => render_backtrace($trace, $file, $line, $this->config->sensitiveDataInTrace), ], ); diff --git a/system/Debug/Inspection/CodeSnippet.php b/system/Debug/Inspection/CodeSnippet.php new file mode 100644 index 000000000000..7d0e624ebf3d --- /dev/null +++ b/system/Debug/Inspection/CodeSnippet.php @@ -0,0 +1,176 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug\Inspection; + +use SplFileObject; +use Throwable; + +/** + * Reads bounded PHP source excerpts. + * + * @internal + */ +final class CodeSnippet +{ + /** + * Lines of context on each side of the selected line in HTML. + */ + private const CONTEXT_LINES = 7; + + /** + * Lines of context on each side of the selected line in plain text. + */ + private const PLAIN_CONTEXT_LINES = 3; + + /** + * Largest source file eligible for a snippet, in bytes. + */ + private const MAX_FILE_SIZE = 1_048_576; + + /** + * Source bytes shown per line before adding an ellipsis. + */ + private const MAX_LINE_BYTES = 1_000; + + /** + * Read a source excerpt around the requested line as escaped HTML or plain text, keyed by one-based line number. + * + * @return array + */ + public static function get(?string $file, ?int $line, bool $highlight = true): array + { + if ($file === null || $line === null || $line < 1) { + return []; + } + + try { + // Resolve a local file before opening it and only show PHP source. + $path = realpath($file); + + if ($path === false || strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'php' || ! is_file($path)) { + return []; + } + + $source = new SplFileObject($path, 'rb'); + + if ($source->getSize() > self::MAX_FILE_SIZE) { + return []; + } + + // Read one extra byte to detect growth after the size check. + $contents = $source->fread(self::MAX_FILE_SIZE + 1); + + if ($contents === false || strlen($contents) > self::MAX_FILE_SIZE) { + return []; + } + + return $highlight ? self::highlight($contents, $line) : self::plain($contents, $line); + } catch (Throwable) { + return []; // Source is optional, including when a file has moved or become unreadable. + } + } + + /** + * @return array + */ + private static function plain(string $contents, int $line): array + { + $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $contents)); + + if ($line > count($lines)) { + return []; + } + + $start = max(1, $line - self::PLAIN_CONTEXT_LINES); + $end = min(count($lines), $line + self::PLAIN_CONTEXT_LINES); + + $excerpt = []; + + for ($number = $start; $number <= $end; $number++) { + $text = $lines[$number - 1]; + + $excerpt[$number] = strlen($text) > self::MAX_LINE_BYTES + ? mb_strcut($text, 0, self::MAX_LINE_BYTES, 'UTF-8') . '…' + : $text; + } + + return $excerpt; + } + + /** + * Highlight the requested lines using the full file's token context. + * + * @return array + */ + private static function highlight(string $contents, int $line): array + { + $start = max(1, $line - self::CONTEXT_LINES); + $end = $line + self::CONTEXT_LINES; + + $current = 1; + $bytes = 0; + $lines = []; + + foreach (token_get_all(str_replace(["\r\n", "\r"], "\n", $contents)) as $token) { + $text = is_array($token) ? $token[1] : $token; + $class = match (is_array($token) ? $token[0] : null) { + T_COMMENT, T_DOC_COMMENT => 'comment', + T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE => 'string', + T_INLINE_HTML, T_STRING, T_VARIABLE, T_WHITESPACE, + T_LNUMBER, T_DNUMBER, T_NAME_QUALIFIED, + T_NAME_FULLY_QUALIFIED, T_NAME_RELATIVE => '', + default => 'keyword', + }; + + foreach (explode("\n", $text) as $index => $part) { + if ($index > 0) { + $current++; + $bytes = 0; + } + + if ($current > $end) { + return $lines; + } + + if ($current < $start) { + continue; + } + + $lines[$current] ??= ''; + $remaining = self::MAX_LINE_BYTES - $bytes; + + if ($part === '' || $remaining < 0) { + continue; + } + + $length = strlen($part); + $slice = esc(mb_strcut($part, 0, $remaining, 'UTF-8')); + + if ($slice !== '') { + $lines[$current] .= $class === '' + ? $slice + : sprintf('%s', $class, $slice); + } + + if ($length > $remaining) { + $lines[$current] .= '…'; + } + + $bytes += $length; + } + } + + return isset($lines[$line]) ? $lines : []; + } +} diff --git a/system/Debug/Inspection/Frame.php b/system/Debug/Inspection/Frame.php new file mode 100644 index 000000000000..5fc80c395154 --- /dev/null +++ b/system/Debug/Inspection/Frame.php @@ -0,0 +1,77 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug\Inspection; + +/** + * A stack frame with its call and source location. + * + * @internal + */ +final readonly class Frame +{ + /** + * Store a call with its source location and captured arguments. + * + * @param array $arguments + */ + public function __construct( + public string $function, + public ?string $file = null, + public ?int $line = null, + public ?string $class = null, + public ?string $type = null, + public array $arguments = [], + ) { + } + + /** + * Render the call with preformatted arguments. + */ + public function call(string $arguments = ''): string + { + $type = $this->type === '->' ? '()->' : ($this->type ?? ''); + + return sprintf('%s%s%s(%s)', $this->class ?? '', $type, $this->function, $arguments); + } + + /** + * Export the available call and source metadata for API responses. + * + * @return array{file?: string, line?: int, class?: string, type?: string, function: string} + */ + public function metadata(): array + { + return array_filter([ + 'file' => $this->file, + 'line' => $this->line, + 'function' => $this->function, + 'class' => $this->class, + 'type' => $this->type, + ], static fn (int|string|null $value): bool => $value !== null); + } + + /** + * Resolve nested eval locations to the outer eval call in the source file. + * + * @return array{file: string, line?: int} + */ + public static function sourceLocation(string $file, ?int $line): array + { + if (preg_match('/^(.+?)\((\d+)\)(?: : eval\(\)\x27d code(?:\(\d+\))?)+$/D', $file, $parts) === 1) { + return ['file' => $parts[1], 'line' => (int) $parts[2]]; + } + + return $line === null ? ['file' => $file] : ['file' => $file, 'line' => $line]; + } +} diff --git a/system/Debug/Inspection/Frames.php b/system/Debug/Inspection/Frames.php new file mode 100644 index 000000000000..fae20c9d4e8e --- /dev/null +++ b/system/Debug/Inspection/Frames.php @@ -0,0 +1,126 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug\Inspection; + +use ArrayIterator; +use Countable; +use IteratorAggregate; +use Override; +use Throwable; +use Traversable; + +/** + * An ordered collection of normalized stack frames. + * + * @internal + * + * @implements IteratorAggregate + */ +final readonly class Frames implements Countable, IteratorAggregate +{ + /** + * Store normalized frames in trace order. + * + * @param list $frames + */ + public function __construct(private array $frames) + { + } + + /** + * Normalize a trace using the exception's throw site. + * + * @param list + * }>|null $trace + */ + public static function fromException(Throwable $exception, ?array $trace = null): self + { + return self::fromTrace($trace ?? $exception->getTrace(), $exception->getFile(), $exception->getLine()); + } + + /** + * Pair each raw call with the location inside that call. + * + * @param list}> $trace + */ + public static function fromTrace(array $trace, ?string $file = null, ?int $line = null): self + { + if ($trace === [] && $file === null) { + return new self([]); + } + + $location = $file === null ? [] : Frame::sourceLocation($file, $line); + $frames = []; + + foreach ($trace as $row) { + $function = $row['function']; + + if (str_starts_with($function, '{closure:') || str_ends_with($function, '\{closure}')) { + $function = '{closure}'; + } + + $frames[] = new Frame( + $function, + $location['file'] ?? null, + $location['line'] ?? null, + $row['class'] ?? null, + $row['type'] ?? null, + $row['args'] ?? [], + ); + + $location = isset($row['file']) ? Frame::sourceLocation($row['file'], $row['line'] ?? null) : []; + } + + // Use the final call site for the entry frame PHP omits. + $frames[] = new Frame('{main}', $location['file'] ?? null, $location['line'] ?? null); + + return new self($frames); + } + + /** + * Count all frames before applying a display limit. + */ + #[Override] + public function count(): int + { + return count($this->frames); + } + + /** + * Iterate from the innermost call to the entry point. + * + * @return Traversable + */ + #[Override] + public function getIterator(): Traversable + { + return new ArrayIterator($this->frames); + } + + /** + * Return the leading frames up to the display limit. + * + * @return list + */ + public function take(int $limit): array + { + return array_slice($this->frames, 0, $limit); + } +} diff --git a/system/Debug/Inspection/Inspector.php b/system/Debug/Inspection/Inspector.php new file mode 100644 index 000000000000..921fadd0e32e --- /dev/null +++ b/system/Debug/Inspection/Inspector.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug\Inspection; + +use Throwable; + +/** + * Walks an exception's chain of causes. + * + * @internal + */ +final readonly class Inspector +{ + /** + * Start inspection from the reported exception. + */ + public function __construct(private Throwable $exception) + { + } + + /** + * List the reported exception and its causes in order. + * + * @return list + */ + public function chain(): array + { + $chain = []; + + for ($exception = $this->exception; $exception instanceof Throwable; $exception = $exception->getPrevious()) { + $chain[] = $exception; + } + + return $chain; + } + + /** + * Return the deepest cause, or the reported exception when it has none. + */ + public function rootCause(): Throwable + { + $chain = $this->chain(); + + return $chain[array_key_last($chain)]; + } +} diff --git a/tests/system/CommonFunctionsTest.php b/tests/system/CommonFunctionsTest.php index 28bad7a6bab5..61afc916366a 100644 --- a/tests/system/CommonFunctionsTest.php +++ b/tests/system/CommonFunctionsTest.php @@ -35,6 +35,7 @@ use Config\App; use Config\Cookie; use Config\DocTypes; +use Config\Exceptions as ExceptionsConfig; use Config\Logger; use Config\Modules; use Config\Routing; @@ -872,11 +873,35 @@ public function testIsWindowsUsingMock(): void public function testRenderBacktrace(): void { - $trace = (new RuntimeException('Test exception'))->getTrace(); - $renders = explode("\n", render_backtrace($trace)); + $trace = [ + ['file' => ROOTPATH . 'caller.php', 'line' => 20, 'class' => 'Connection', 'type' => '->', 'function' => 'query'], + ['file' => ROOTPATH . 'entry.php', 'line' => 30, 'function' => 'caller', 'args' => [42]], + ]; + + $this->assertSame([ + ' 1 Connection()->query() [internal function]', + ' 2 caller(42) in caller.php (line 20)', + ' 3 {main}() in entry.php (line 30)', + ], explode("\n", render_backtrace($trace))); + $this->assertStringStartsWith( + " 1 Connection()->query() in connection.php (line 10)\n", + render_backtrace($trace, ROOTPATH . 'connection.php', 10), + ); + } + + public function testRenderBacktraceRedactsArgumentsUsingTheSharedExceptionConfig(): void + { + $config = config(ExceptionsConfig::class); + $saved = $config->sensitiveDataInTrace; + + $config->sensitiveDataInTrace = ['needle']; + + try { + $trace = [['function' => 'str_contains', 'args' => ['visible', 'redacted']]]; - foreach ($renders as $render) { - $this->assertMatchesRegularExpression('/^\s*\d* .+(?:\(\d+\))?: \S+(?:(?:\->|::)\S+)?\(.*\)$/', $render); + $this->assertStringContainsString("str_contains('visible', [redacted])", render_backtrace($trace)); + } finally { + $config->sensitiveDataInTrace = $saved; } } diff --git a/tests/system/Database/Live/ExecuteLogMessageFormatTest.php b/tests/system/Database/Live/ExecuteLogMessageFormatTest.php index 265ca976e1fa..a46d9535bd1a 100644 --- a/tests/system/Database/Live/ExecuteLogMessageFormatTest.php +++ b/tests/system/Database/Live/ExecuteLogMessageFormatTest.php @@ -66,9 +66,13 @@ public function testLogMessageWhenExecuteFailsShowFullStructuredBacktrace(): voi } $this->assertMatchesRegularExpression('/^in \S+ on line \d+\.$/', array_shift($messageFromLogs)); + $this->assertNotEmpty($messageFromLogs); - foreach ($messageFromLogs as $line) { - $this->assertMatchesRegularExpression('/^\s*\d* .+(?:\(\d+\))?: \S+(?:(?:\->|::)\S+)?\(.*\)$/', $line); + foreach ($messageFromLogs as $index => $line) { + $this->assertMatchesRegularExpression( + sprintf('/^%2d \S+\(.*\) (?:in .+ \(line \d+\)|\[internal function\])$/', $index + 1), + $line, + ); } } } diff --git a/tests/system/Debug/BacktraceTest.php b/tests/system/Debug/BacktraceTest.php new file mode 100644 index 000000000000..33441181387a --- /dev/null +++ b/tests/system/Debug/BacktraceTest.php @@ -0,0 +1,186 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug; + +use CodeIgniter\Debug\Inspection\Frame; +use CodeIgniter\Debug\Inspection\Frames; +use CodeIgniter\Test\CIUnitTestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\UsesClass; +use SensitiveParameterValue; +use stdClass; + +/** + * @internal + */ +#[CoversClass(Backtrace::class)] +#[Group('Others')] +#[UsesClass(Frame::class)] +#[UsesClass(Frames::class)] +final class BacktraceTest extends CIUnitTestCase +{ + public function testFormatsAnEvalSourceLocationForTextAndCli(): void + { + $eval = sprintf("%s(17) : eval()'d code(3) : eval()'d code", ROOTPATH . 'app/Example.php'); + + $this->assertSame('app/Example.php:17', Backtrace::location($eval, 2, cli: true)); + $this->assertSame('in app/Example.php (line 17)', Backtrace::location($eval, 2)); + } + + public function testFormatsArraysInlineAndSummarizesObjectsAndResources(): void + { + $resource = fopen('php://memory', 'rb'); + + try { + $file = ROOTPATH . 'app/Example.php'; + $trace = new Frames([ + new Frame('run', $file, 42, 'Example', '->', [ + new stdClass(), ['a' => 1, 'b' => [true]], [], null, $resource, 'value', + ]), + ]); + + $this->assertSame([ + " 1 Example()->run(Object(stdClass), ['a' => 1, 'b' => [true]], [], null, resource (stream), 'value') in app/Example.php (line 42)", + ], Backtrace::lines($trace)); + } finally { + fclose($resource); + } + } + + public function testFormatsRelativeAndInternalFramesWithoutArguments(): void + { + $trace = new Frames([ + new Frame('run', ROOTPATH . 'app/Example.php', 42, arguments: ['secret']), + new Frame('array_map'), + ]); + + $this->assertSame([ + ' 1 run() in app/Example.php (line 42)', + ' 2 array_map() [internal function]', + ], Backtrace::lines($trace, includeArguments: false)); + } + + public function testLocationPreservesExternalPathsAndHandlesMissingLocation(): void + { + $external = dirname(rtrim(ROOTPATH, '\\/')) . DIRECTORY_SEPARATOR . 'external.php'; + + $this->assertSame('in ' . $external, Backtrace::location($external, null)); + $this->assertSame($external, Backtrace::location($external, null, cli: true)); + $this->assertSame('[internal function]', Backtrace::location(null, 12)); + $this->assertSame('[internal function]', Backtrace::location('', 12, cli: true)); + $this->assertSame([], Backtrace::lines(new Frames([]))); + } + + public function testArgumentPreviewUsesNamesAndSummarizesObjects(): void + { + $preview = Backtrace::argumentPreview(new Frame('array_map', arguments: [ + (object) ['privateValue' => 'secret'], ['hidden'], new SensitiveParameterValue('secret'), + ])); + + $this->assertSame(['callback' => 'Object(stdClass)', 'array' => "[\n 'hidden',\n]", 'arrays' => '[redacted]'], $preview); + } + + public function testArgumentPreviewLimitsArraysAndMasksNestedFields(): void + { + $preview = Backtrace::argumentPreview(new Frame('{closure}', arguments: [ + range(1, 10), ['account' => ['pin' => 'private value', 'nested' => ['deeper' => ['value' => 'too deep']]]], + ]), ['account/pin']); + + $this->assertStringContainsString('… +2 more', $preview[0]); + $this->assertStringContainsString("'pin' => [redacted]", $preview[1]); + $this->assertStringContainsString("'deeper' => [...]", $preview[1]); + $this->assertStringNotContainsString('private value', $preview[1]); + $this->assertStringNotContainsString('too deep', $preview[1]); + } + + public function testArgumentPreviewMasksPositionalPathsAndCredentialDsnValues(): void + { + $preview = Backtrace::argumentPreview(new Frame('{closure}', arguments: [ + 'positional secret', ['private' => 'nested secret', 'public' => 'visible'], 'mysql://user:pass@host', + ]), ['0', '1/private']); + + $this->assertSame([ + '[redacted]', + "[\n 'private' => [redacted],\n 'public' => 'visible',\n]", + '[redacted]', + ], $preview); + } + + public function testArgumentPreviewTruncatesAtUtf8Boundaries(): void + { + $prefix = str_repeat('x', 498); + $preview = Backtrace::argumentPreview(new Frame('{closure}', arguments: [$prefix . 'é'])); + + $this->assertSame(["'" . $prefix . '…'], $preview); + } + + public function testInlineFormattingRedactsNestedValuesAndDetectsOnlyAncestorReferences(): void + { + $shared = ['label' => 'visible', 'pin' => 'hidden']; + $cycle = ['left' => &$shared, 'right' => &$shared]; + $cycle['self'] = &$cycle; + + $frame = new Frame('work', arguments: [&$cycle]); + $trace = new Frames([$frame]); + $line = Backtrace::lines($trace, sensitiveKeys: ['pin'])[0]; + + $this->assertSame( + " 1 work(['left' => ['label' => 'visible', 'pin' => [redacted]], 'right' => ['label' => 'visible', 'pin' => [redacted]], 'self' => *RECURSION*]) [internal function]", + $line, + ); + $this->assertStringContainsString("'self' => *RECURSION*", Backtrace::argumentPreview($frame, ['pin'])[0]); + $this->assertSame('hidden', $shared['pin']); + } + + public function testArrayFormattingBoundsTheTotalValuesAcrossNestedBranches(): void + { + $items = array_fill(0, 8, array_fill(0, 8, 'entry')); + $frame = new Frame('work', arguments: [$items]); + $line = Backtrace::lines(new Frames([$frame]))[0]; + + $this->assertStringContainsString('… +', $line); + $this->assertLessThan(32, substr_count($line, "'entry'")); + } + + public function testInlineArraysRedactCredentialHeadersAndKeepEachFrameOnOneLine(): void + { + $frame = new Frame('work', arguments: [['Authorization' => 'hidden', 'note' => "first\nsecond"]]); + + $this->assertSame( + " 1 work(['Authorization' => [redacted], 'note' => 'first\\nsecond']) [internal function]", + Backtrace::lines(new Frames([$frame]))[0], + ); + } + + public function testArgumentPreviewOfFrameWithoutParametersRaisesNoDeprecation(): void + { + $errors = []; + + set_error_handler(static function (int $severity, string $message) use (&$errors): bool { + $errors[] = $message; + + return true; + }); + + try { + $preview = Backtrace::argumentPreview(new Frame('require_once', arguments: ['/path/to/file.php'])); + } finally { + restore_error_handler(); + } + + $this->assertSame([], $errors); + $this->assertSame(["'/path/to/file.php'"], $preview); + } +} diff --git a/tests/system/Debug/ConsoleExceptionRendererTest.php b/tests/system/Debug/ConsoleExceptionRendererTest.php new file mode 100644 index 000000000000..f585d568f281 --- /dev/null +++ b/tests/system/Debug/ConsoleExceptionRendererTest.php @@ -0,0 +1,100 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug; + +use CodeIgniter\CLI\Output; +use CodeIgniter\CLI\Terminal; +use CodeIgniter\CLI\Verbosity; +use CodeIgniter\Debug\Inspection\CodeSnippet; +use CodeIgniter\Debug\Inspection\Frame; +use CodeIgniter\Debug\Inspection\Frames; +use CodeIgniter\Debug\Inspection\Inspector; +use CodeIgniter\Test\CIUnitTestCase; +use CodeIgniter\Test\IniTestTrait; +use CodeIgniter\Test\Mock\MockInputOutput; +use ErrorException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\UsesClass; + +/** + * @internal + */ +#[CoversClass(ConsoleExceptionRenderer::class)] +#[Group('Others')] +#[UsesClass(Backtrace::class)] +#[UsesClass(CodeSnippet::class)] +#[UsesClass(Frame::class)] +#[UsesClass(Frames::class)] +#[UsesClass(Inspector::class)] +final class ConsoleExceptionRendererTest extends CIUnitTestCase +{ + use IniTestTrait; + + public function testCliWrapsArgumentsToTheTerminalWidth(): void + { + $terminal = $this->createStub(Terminal::class); + $terminal->method('getWidth')->willReturn(25); + $terminal->method('hasColorSupport')->willReturn(false); + + $this->backupIniValues(['zend.exception_ignore_args']); + ini_set('zend.exception_ignore_args', '0'); + + $io = new MockInputOutput(); + $output = new Output($io, $terminal); + $output->setVerbosity(Verbosity::Verbose); + + $argument = str_repeat('界', 20); + $exception = $this->runWithArgument($argument); + + ConsoleExceptionRenderer::render($exception, 'Wrapped argument', $output); + + $trace = strstr($io->getOutput(), ' 1 test.php:12' . PHP_EOL); + $this->assertNotFalse($trace); + $firstFrame = strstr($trace, PHP_EOL . PHP_EOL, true); + $this->assertNotFalse($firstFrame); + $lines = array_slice(explode(PHP_EOL, $firstFrame), 1); + $this->assertGreaterThan(1, count($lines)); + + foreach ($lines as $line) { + $this->assertStringStartsWith(' ', $line); + $this->assertLessThanOrEqual(25, mb_strwidth($line, 'UTF-8')); + } + + $this->assertSame(sprintf("%s()->runWithArgument('%s')", self::class, $argument), implode('', array_map(static fn (string $line): string => substr($line, 7), $lines))); + } + + public function testCliSourceExcerptMarksTheRequestedLine(): void + { + $terminal = $this->createStub(Terminal::class); + $terminal->method('getWidth')->willReturn(80); + $terminal->method('hasColorSupport')->willReturn(false); + $io = new MockInputOutput(); + + $exception = new ErrorException('Missing controller', filename: SUPPORTPATH . 'Controllers/Hello.php', line: 16); + + ConsoleExceptionRenderer::render($exception, 'Missing controller', new Output($io, $terminal)); + + $output = $io->getOutput(); + $this->assertStringContainsString(' > 16 | use CodeIgniter\Controller;' . PHP_EOL, $output); + $this->assertStringContainsString(' 18 | class Hello extends Controller' . PHP_EOL, $output); + $this->assertStringNotContainsString(' | return', $output); + $this->assertSame(1, substr_count($output, ' > ')); + } + + private function runWithArgument(string $argument): ErrorException + { + return new ErrorException($argument, filename: ROOTPATH . 'test.php', line: 12); + } +} diff --git a/tests/system/Debug/ExceptionHandlerTest.php b/tests/system/Debug/ExceptionHandlerTest.php index 13db117abdc7..eb30884d1fb6 100644 --- a/tests/system/Debug/ExceptionHandlerTest.php +++ b/tests/system/Debug/ExceptionHandlerTest.php @@ -14,23 +14,30 @@ namespace CodeIgniter\Debug; use App\Controllers\Home; +use CodeIgniter\Debug\Inspection\CodeSnippet; +use CodeIgniter\Debug\Inspection\Frames; use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\Exceptions\RuntimeException; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\Response; +use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\SiteURI; use CodeIgniter\HTTP\UserAgent; use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\Filters\CITestStreamFilter; use CodeIgniter\Test\IniTestTrait; use CodeIgniter\Test\StreamFilterTrait; +use CodeIgniter\Test\TestLogger; use Config\App; use Config\Exceptions as ExceptionsConfig; use Config\Services; +use Kint\Renderer\AbstractRenderer; use Override; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; -use stdClass; +use ReflectionProperty; +use SensitiveParameter; +use SensitiveParameterValue; /** * @internal @@ -125,30 +132,207 @@ public function testCopyErrorReportIncludesPreviousExceptions(): void $report = $this->extractCopyableErrorReport($this->renderHtmlException($exception)); $this->assertStringContainsString('## Previous Exceptions', $report); - $this->assertStringContainsString('* CodeIgniter\Exceptions\RuntimeException - Root cause.', $report); + $this->assertStringContainsString('- [CodeIgniter\Exceptions\RuntimeException] Root cause.', $report); + $this->assertStringContainsString('()->testCopyErrorReportIncludesPreviousExceptions()', $report); } public function testCopyErrorReportOmitsSensitiveRequestDataAndTraceArgs(): void { - $exception = $this->createExceptionWithSensitiveTraceArgument(); + $this->backupIniValues(['zend.exception_ignore_args']); + ini_set('zend.exception_ignore_args', '0'); + + $argument = bin2hex(random_bytes(12)); + $cookie = bin2hex(random_bytes(12)); + $post = bin2hex(random_bytes(12)); + $exception = $this->forwardSensitiveTraceArgument(password: $argument); service('superglobals') - ->setCookie('debug_cookie', 'cookie-secret') - ->setPost('debug_post', 'post-secret'); + ->setCookie(config('Session')->cookieName, $cookie) + ->setPost('password', $post); try { - $report = $this->extractCopyableErrorReport($this->renderHtmlException($exception)); + $this->assertSame($argument, $exception->getTrace()[0]['args'][0]); + + $output = $this->renderHtmlException($exception); + $report = $this->extractCopyableErrorReport($output); - $this->assertStringNotContainsString('secret-token', $report); - $this->assertStringNotContainsString('cookie-secret', $report); - $this->assertStringNotContainsString('post-secret', $report); + $this->assertStringContainsString('Arguments', $output); + $this->assertStringNotContainsString($argument, $output); + $this->assertStringNotContainsString($argument, $report); + $this->assertStringNotContainsString($cookie, $output); + $this->assertStringNotContainsString($post, $output); $this->assertStringNotContainsString('$_COOKIE', $report); $this->assertStringNotContainsString('$_POST', $report); } finally { - service('superglobals')->unsetCookie('debug_cookie')->unsetPost('debug_post'); + $this->restoreIniValues(); + service('superglobals')->unsetCookie(config('Session')->cookieName)->unsetPost('password'); + } + } + + public function testArgumentPreviewMatchesTheNamedFunction(): void + { + $this->backupIniValues(['zend.exception_ignore_args']); + ini_set('zend.exception_ignore_args', '0'); + + try { + $argument = bin2hex(random_bytes(12)); + $exception = $this->createExceptionForArgumentPreview($argument); + $output = $this->renderHtmlException($exception); + + $this->assertSame(1, preg_match('#]+id="frame-0001".*?#s', $output, $panel)); + $this->assertStringContainsString('
$sample
', $panel[0]); + $this->assertStringContainsString($argument, $panel[0]); + $this->assertStringNotContainsString('
$inner
', $panel[0]); + + $this->assertSame(1, preg_match('#]+id="frame-0000".*?#s', $output, $firstPanel)); + $this->assertStringContainsString('
$inner
', $firstPanel[0]); + $this->assertStringContainsString('value passed to the inner call', $firstPanel[0]); + } finally { + $this->restoreIniValues(); + } + } + + public function testDetailedHtmlRendersRecursiveArgumentsWithRedactionConfigured(): void + { + $this->backupIniValues(['zend.exception_ignore_args']); + ini_set('zend.exception_ignore_args', '0'); + + $config = new ExceptionsConfig(); + $config->sensitiveDataInTrace = ['pin']; + $this->handler = new ExceptionHandler($config); + $secret = bin2hex(random_bytes(12)); + $argument = ['pin' => $secret]; + $argument['self'] = &$argument; + + try { + $error = (static fn (array $data): RuntimeException => new RuntimeException('Recursive trace test.'))($argument); + $output = $this->renderHtmlException($error); + + $this->assertStringContainsString('*RECURSION*', $output); + $this->assertStringNotContainsString($secret, $output); + } finally { + $this->restoreIniValues(); } } + #[DataProvider('provideWebErrorRespectsDisabledBacktraces')] + public function testWebErrorRespectsDisabledBacktraces(string $accept): void + { + $homePath = var_export(HOMEPATH, true); + $bootstrap = var_export(SYSTEMPATH . 'util_bootstrap.php', true); + $mediaType = var_export($accept, true); + $sourceFile = var_export(SUPPORTPATH . 'Controllers/Hello.php', true); + + $code = <<setValue(null, true); + + function createExceptionWithHiddenTrace(): RuntimeException + { + \$exception = new RuntimeException('Hidden trace regression test.'); + (new ReflectionProperty(Exception::class, 'file'))->setValue(\$exception, {$sourceFile}); + (new ReflectionProperty(Exception::class, 'line'))->setValue(\$exception, 16); + + return \$exception; + } + + \$request = service('incomingrequest', null, false); + \$request->setHeader('accept', {$mediaType}); + (new ExceptionHandler(new ExceptionsConfig()))->handle( + createExceptionWithHiddenTrace(), + \$request, + service('response'), + 500, + EXIT_ERROR, + ); + PHP; + + $cmd = sprintf('%s -r %s 2>&1', escapeshellarg(PHP_BINARY), escapeshellarg($code)); + exec($cmd, $lines, $status); + $output = implode(PHP_EOL, $lines); + + $this->assertSame(0, $status, $output); + $this->assertStringContainsString('Hidden trace regression test.', $output); + $this->assertStringNotContainsString('createExceptionWithHiddenTrace', $output); + + if ($accept === 'text/html') { + $report = $this->extractCopyableErrorReport($output); + $this->assertStringNotContainsString('## Stack Trace', $report); + $this->assertStringContainsString('## Source Excerpt', $report); + $this->assertStringContainsString('> 16 | use CodeIgniter\Controller;', $report); + } else { + $this->assertSame([], json_decode($output, true, flags: JSON_THROW_ON_ERROR)['trace']); + } + } + + /** + * @return iterable + */ + public static function provideWebErrorRespectsDisabledBacktraces(): iterable + { + yield 'HTML' => ['text/html']; + + yield 'JSON' => ['application/json']; + } + + #[DataProvider('provideApiTraceContainsFrameMetadataWithoutArguments')] + public function testApiTraceContainsFrameMetadataWithoutArguments(string $format): void + { + $this->backupIniValues(['zend.exception_ignore_args']); + ini_set('zend.exception_ignore_args', '0'); + + try { + $secret = bin2hex(random_bytes(12)); + $public = bin2hex(random_bytes(12)); + $error = $this->exceptionWithApiArguments($secret, $public); + + $accept = sprintf('application/%s', $format); + $request = service('incomingrequest', null, false); + $request->setHeader('Accept', $accept); + $response = new Response(); + $response->pretend(); + (new ReflectionProperty($this->handler, 'format'))->setValue($this->handler, $format); + + ob_start(); + + try { + $this->handler->handle($error, $request, $response, 500, EXIT_ERROR); + $body = ob_get_contents(); + } finally { + ob_end_clean(); + } + + $this->assertStringContainsString($accept, $response->getHeaderLine('Content-Type')); + $this->assertIsString($body); + $this->assertStringContainsString('exceptionWithApiArguments', $body); + $this->assertStringContainsString('function', $body); + $this->assertStringNotContainsString('args', $body); + $this->assertStringNotContainsString($secret, $body); + $this->assertStringNotContainsString($public, $body); + } finally { + $this->restoreIniValues(); + } + } + + /** + * @return iterable + */ + public static function provideApiTraceContainsFrameMetadataWithoutArguments(): iterable + { + yield 'JSON' => ['json']; + + yield 'XML' => ['xml']; + } + public function testCopyErrorReportOmitsQueryStringFromUrl(): void { $config = new App(); @@ -193,6 +377,9 @@ public function testHandleWebPageNotFoundExceptionDoNotAcceptHTML(): void $this->assertSame(PageNotFoundException::class, $json->type); $this->assertSame(404, $json->code); $this->assertSame('Controller or its method is not found: Foo::bar', $json->message); + $this->assertSame($exception->getFile(), $json->trace[0]->file); + $this->assertSame($exception->getLine(), $json->trace[0]->line); + $this->assertSame('forControllerNotFound', $json->trace[0]->function); } public function testHandleWebPageNotFoundExceptionAcceptHTML(): void @@ -218,11 +405,317 @@ public function testHandleWebRuntimeExceptionAcceptHTMLIncludesCopyErrorReport() $report = $this->extractCopyableErrorReport($output); $this->assertStringContainsString('Copy Details', $output); - $this->assertStringContainsString('# Something went wrong.', $report); + $this->assertStringContainsString('# [CodeIgniter\Exceptions\RuntimeException] Something went wrong.', $report); - foreach (['## Exception', '## Environment', '## Request', '## Source', '## Stack Trace'] as $section) { + foreach (['## Exception', '## Environment', '## Request', '## Stack Trace'] as $section) { $this->assertStringContainsString($section, $report); } + + $this->assertStringContainsString('- Source: in ' . Backtrace::relativePath(__FILE__) . ' (line ', $report); + } + + public function testDetailedHtmlLinksToSourceForEachException(): void + { + $cause = new RuntimeException('Root cause.'); + $output = $this->renderHtmlException(new RuntimeException('Top level.', 0, $cause)); + + $this->assertStringContainsString('href="#frame-0000"', $output); + $this->assertStringContainsString('id="frame-0000"', $output); + $this->assertStringContainsString('href="#frame-0100"', $output); + $this->assertStringContainsString('id="frame-0100"', $output); + $this->assertStringContainsString('class="source-line current-line"', $output); + $this->assertStringNotContainsString('class="stack-overflow"', $output); + $report = $this->extractCopyableErrorReport($output); + $this->assertSame(1, substr_count($report, '## Source Excerpt')); + $this->assertStringContainsString("\n```php\n", $report); + $this->assertStringContainsString(sprintf('> %d |', $cause->getLine()), $report); + $this->assertStringNotContainsString(sprintf('> %d |', $cause->getLine() + 1), $report); + } + + public function testDetailedHtmlCountsHiddenFramesForEachTruncatedTrace(): void + { + $cause = $this->exceptionWithTraceDepth(25); + $exception = $this->exceptionWithTraceDepth(30, $cause); + $output = $this->renderHtmlException($exception); + + $this->assertStringContainsString('id="frame-0019"', $output); + $this->assertStringContainsString('id="frame-0119"', $output); + $this->assertStringContainsString('class="stack-overflow">+' . (count($exception->getTrace()) - 19) . ' hidden frames', $output); + $this->assertStringContainsString('class="stack-overflow">+' . (count($cause->getTrace()) - 19) . ' hidden frames', $output); + $this->assertStringNotContainsString('id="frame-0020"', $output); + } + + public function testDetailedHtmlCountsHiddenExceptions(): void + { + $exception = new RuntimeException('Root cause.'); + + for ($index = 0; $index < 10; $index++) { + $exception = new RuntimeException('Wrapper.', previous: $exception); + } + + $output = $this->renderHtmlException($exception); + + $this->assertStringContainsString('id="frame-0900"', $output); + $this->assertStringContainsString('class="stack-overflow">+1 hidden exception

', $output); + } + + public function testDetailedHtmlLinksToTheFullSourcePath(): void + { + $exception = new RuntimeException('Editor link test.'); + $format = AbstractRenderer::$file_link_format; + AbstractRenderer::$file_link_format = null; + + try { + $output = $this->renderHtmlException($exception); + } finally { + AbstractRenderer::$file_link_format = $format; + } + + $this->assertSame(1, preg_match('#

in #', $output, $link)); + + $path = str_replace('\\', '/', realpath(__FILE__)); + $url = html_entity_decode($link[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'); + + $this->assertSame('file:///' . ltrim($path, '/'), rawurldecode($url)); + $this->assertStringContainsString('ExceptionHandlerTest.php (line ' . $exception->getLine() . ')', $output); + $this->assertMatchesRegularExpression('#.*ExceptionHandlerTest\.php:' . $exception->getLine() . '#', $output); + } + + public function testDetailedHtmlUsesKintEditorLinkFormat(): void + { + $exception = new RuntimeException('Configured editor link test.'); + $format = AbstractRenderer::$file_link_format; + AbstractRenderer::$file_link_format = 'vscode://file%f:%l'; + + try { + $output = $this->renderHtmlException($exception); + } finally { + AbstractRenderer::$file_link_format = $format; + } + + $this->assertSame(1, preg_match('#

in #', $output, $link)); + $url = html_entity_decode($link[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'); + $path = str_replace('\\', '/', realpath(__FILE__)); + + $this->assertSame(sprintf('vscode://file/%s:%d', ltrim($path, '/'), $exception->getLine()), rawurldecode($url)); + } + + public function testSourceSnippetHighlightsPhpAndEscapesSource(): void + { + $file = SUPPORTPATH . 'Controllers/Hello.php'; + $lines = CodeSnippet::get($file, 22); + + $this->assertStringContainsString('return', $lines[22]); + $this->assertStringContainsString(''Hello'', $lines[22]); + $this->assertStringContainsString('', CodeSnippet::get($file, 8)[8]); + $this->assertStringContainsString('<?php', CodeSnippet::get($file, 1)[1]); + } + + public function testDetailedHtmlShowsDiagnosticsWithMaskedValues(): void + { + $config = new ExceptionsConfig(); + $config->sensitiveDataInTrace = ['filter/internal', 'x-internal-key']; + $config->diagnosticValues = ['query' => ['filter']]; + $this->handler = new ExceptionHandler($config); + + $secret = bin2hex(random_bytes(12)); + $request = service('incomingrequest', null, false); + $request->setHeader('Authorization', 'Bearer ' . $secret); + $request->setHeader('API-Key', $secret); + $request->setHeader('X-Internal-Key', $secret); + $request->setHeader('X-Request-ID', 'example-request-id'); + Services::injectMock('request', $request); + service('response')->setHeader('Set-Cookie', 'session=' . $secret); + service('response')->setHeader('X-INTERNAL-KEY', $secret); + service('superglobals')->setGet('filter', ['page' => 'example-page', 'internal' => $secret]); + + try { + $output = $this->renderHtmlException(new RuntimeException('Diagnostics test.')); + + foreach (['Diagnostics', 'Request', 'Response', 'Server', 'Files (', 'Memory', '500 Internal Server Error', 'example-request-id', 'example-page'] as $label) { + $this->assertStringContainsString($label, $output); + } + + foreach (['Authorization', 'API-Key', 'Set-Cookie', 'X-Internal-Key', 'X-INTERNAL-KEY'] as $name) { + $this->assertMatchesRegularExpression('#

' . $name . '
\\s*
\\[redacted\\]
#', $output); + } + + $this->assertStringNotContainsString($secret, $output); + $this->assertStringNotContainsString('Authorization', $this->extractCopyableErrorReport($output)); + } finally { + service('superglobals')->unsetGet('filter'); + $this->resetServices(); + } + } + + public function testDetailedHtmlShowsHeaderValuesAndMasksOtherFieldsByDefault(): void + { + $secret = bin2hex(random_bytes(12)); + $request = service('incomingrequest', null, false); + $response = service('response', null, false); + $request->setHeader('Content-Type', 'multipart/form-data; boundary=fixture'); + $request->setHeader('Content-Length', '128'); + $request->setHeader('Origin', 'https://example.test'); + $request->setHeader('X-Application-Mode', 'preview'); + $response->setHeader('Content-Type', 'text/plain; charset=UTF-8'); + $response->setHeader('Content-Length', '256'); + $response->removeHeader('Cache-Control'); + $response->setHeader('Cache-Control', 'no-store'); + $superglobals = service('superglobals'); + $superglobals->setGet('query-key', $secret)->setPost('form-key', $secret)->setCookie('custom-session', $secret); + + try { + $output = $this->renderHtmlException(new RuntimeException('Diagnostics defaults test.'), $request, $response); + + $this->assertMatchesRegularExpression('#
Content-Type
\s*
multipart/form-data; boundary=fixture
#', $output); + $this->assertMatchesRegularExpression('#
Content-Type
\s*
text/plain; charset=UTF-8
#', $output); + $this->assertMatchesRegularExpression('#
Content-Length
\s*
128
#', $output); + $this->assertMatchesRegularExpression('#
Content-Length
\s*
256
#', $output); + $this->assertMatchesRegularExpression('#
Origin
\s*
https://example\.test
#', $output); + $this->assertMatchesRegularExpression('#
Cache-Control
\s*
no-store
#', $output); + $this->assertMatchesRegularExpression('#
X-Application-Mode
\s*
preview
#', $output); + + foreach (['query-key', 'form-key', 'custom-session'] as $name) { + $this->assertMatchesRegularExpression('#
' . $name . '
\s*
\[redacted\]
#', $output); + } + + $this->assertStringNotContainsString($secret, $output); + } finally { + $superglobals->unsetGet('query-key')->unsetPost('form-key')->unsetCookie('custom-session'); + } + } + + public function testDetailedHtmlMasksExplicitlySensitiveCommonHeaders(): void + { + $config = new ExceptionsConfig(); + $config->sensitiveDataInTrace = ['content-type']; + $this->handler = new ExceptionHandler($config); + + $type = sprintf('application/vnd.%s+json', bin2hex(random_bytes(8))); + $request = service('incomingrequest', null, false); + $request->setHeader('Content-Type', $type); + + $output = $this->renderHtmlException(new RuntimeException('Header validation test.'), $request); + + $this->assertMatchesRegularExpression('#
Content-Type
\s*
\[redacted\]
#', $output); + $this->assertStringNotContainsString($type, $output); + } + + public function testDetailedHtmlUsesTheRequestAndResponsePassedToTheHandler(): void + { + $config = new App(); + $request = new IncomingRequest($config, new SiteURI($config, '/actual-request'), null, new UserAgent()); + $request->setHeader('X-Request-ID', 'actual-request-id'); + + $response = service('response', null, false); + $response->setHeader('X-Response-ID', 'actual-response-id'); + $response->setHeader('Content-Type', 'text/css; charset=UTF-8'); + + $output = $this->renderHtmlException(new RuntimeException('Request and response test.'), $request, $response); + + $this->assertStringContainsString('actual-request-id', $output); + $this->assertStringContainsString('actual-response-id', $output); + $this->assertStringContainsString('
text/css; charset=UTF-8
', $output); + $this->assertStringContainsString('HTTP 500 Internal Server Error', $output); + $this->assertStringContainsString('- Path: /actual-request', $this->extractCopyableErrorReport($output)); + } + + public function testServerDiagnosticsOnlyIncludeAllowlistedFields(): void + { + $superglobals = service('superglobals'); + $original = $superglobals->getServerArray(); + $secret = bin2hex(random_bytes(12)); + + $superglobals->setServer('SERVER_SOFTWARE', 'Example Server'); + $superglobals->setServer('APPLICATION_SECRET', $secret); + + try { + $output = $this->renderHtmlException(new RuntimeException('Server diagnostics test.')); + + $this->assertStringContainsString('
SERVER_SOFTWARE
', $output); + $this->assertStringContainsString('Example Server', $output); + $this->assertStringNotContainsString($secret, $output); + $this->assertStringContainsString('Constants (', $output); + $this->assertStringContainsString('
  • EXIT_SUCCESS
  • ', $output); + $this->assertStringContainsString('
  • COMPOSER_PATH
  • ', $output); + } finally { + $superglobals->setServerArray($original); + } + } + + public function testConstantsShowNamesWithoutValues(): void + { + $suffix = bin2hex(random_bytes(5)); + $secret = bin2hex(random_bytes(12)); + $key = sprintf('DB_PASS_%s', $suffix); + $custom = sprintf('DEMO_CUSTOM_%s', $suffix); + + define($key, $secret); + define($custom, ['value' => $secret]); + + $output = $this->renderHtmlException(new RuntimeException('Constants diagnostics test.')); + + $this->assertStringContainsString(sprintf('
  • %s
  • ', $key), $output); + $this->assertStringContainsString(sprintf('
  • %s
  • ', $custom), $output); + $this->assertStringNotContainsString($secret, $output); + } + + public function testDetailedHtmlShowsUnlimitedMemoryLimit(): void + { + $this->backupIniValues(['memory_limit']); + ini_set('memory_limit', '-1'); + + try { + $output = $this->renderHtmlException(new RuntimeException('Memory diagnostics test.')); + + $this->assertMatchesRegularExpression('#
    Memory limit
    \s*
    Unlimited
    #', $output); + } finally { + $this->restoreIniValues(); + } + } + + public function testDetailedHtmlShowsUserAgentInRequestSummary(): void + { + service('superglobals')->setServer('HTTP_USER_AGENT', 'ExampleBrowser/1.0'); + + try { + $output = $this->renderHtmlException(new RuntimeException('Request summary test.')); + + $this->assertMatchesRegularExpression('#
    User agent
    \s*
    ExampleBrowser/1\.0
    #', $output); + $this->assertStringContainsString('- User Agent: ExampleBrowser/1.0', $this->extractCopyableErrorReport($output)); + } finally { + service('superglobals')->unsetServer('HTTP_USER_AGENT'); + } + } + + public function testConfiguredUserAgentRedactionAlsoAppliesToCopyDetails(): void + { + $config = new ExceptionsConfig(); + $config->sensitiveDataInTrace = ['User-Agent']; + $this->handler = new ExceptionHandler($config); + + $agent = bin2hex(random_bytes(12)); + service('superglobals')->setServer('HTTP_USER_AGENT', $agent); + + try { + $output = $this->renderHtmlException(new RuntimeException('Request summary test.')); + + $this->assertStringNotContainsString($agent, $output); + $this->assertStringContainsString('- User Agent: [redacted]', $this->extractCopyableErrorReport($output)); + } finally { + service('superglobals')->unsetServer('HTTP_USER_AGENT'); + } + } + + public function testBacktraceCanRenderInternalCallsWithoutArguments(): void + { + $exception = array_map($this->createExceptionWithSensitiveTraceArgument(...), ['private value'])[0]; + $frames = Frames::fromTrace($exception->getTrace()); + $rendered = implode("\n", Backtrace::lines($frames, includeArguments: false)); + + $this->assertNull($frames->take(1)[0]->file); + $this->assertStringContainsString(self::class . '()->createExceptionWithSensitiveTraceArgument() [internal function]', $rendered); + $this->assertStringNotContainsString('private value', $rendered); } public function testHandleWebRuntimeExceptionEscapesCopyErrorReport(): void @@ -266,10 +759,51 @@ public function testHandleCLIExceptionWritesToStderr(): void CITestStreamFilter::removeOutputFilter(); - $this->handler->handle(new RuntimeException('Something broke.'), $request, $response, 500, EXIT_ERROR); + $cause = new RuntimeException('Root cause.'); + $exception = new RuntimeException('Something broke.', 0, $cause); + $this->handler->handle($exception, $request, $response, 500, EXIT_ERROR); $this->assertStringContainsString('[' . RuntimeException::class . ']', $this->getStreamFilterBuffer()); $this->assertStringContainsString('Something broke.', $this->getStreamFilterBuffer()); + $this->assertStringContainsString('Caused by:', $this->getStreamFilterBuffer()); + $this->assertStringContainsString('Root cause.', $this->getStreamFilterBuffer()); + $this->assertStringContainsString('Backtrace:', $this->getStreamFilterBuffer()); + $this->assertMatchesRegularExpression( + sprintf('#Something broke\..*?> %d \|.*?Caused by:.*?Backtrace:#s', $exception->getLine()), + $this->getStreamFilterBuffer(), + ); + $this->assertSame(1, substr_count($this->getStreamFilterBuffer(), ' > ')); + } + + public function testCliAndLogsRedactConfiguredArgumentsAndDsns(): void + { + $this->backupIniValues(['zend.exception_ignore_args']); + ini_set('zend.exception_ignore_args', '0'); + + $config = new ExceptionsConfig(); + $config->sensitiveDataInTrace = ['credential']; + $this->handler = new ExceptionHandler($config); + $secret = bin2hex(random_bytes(12)); + $dsn = sprintf('host=localhost password=%s', bin2hex(random_bytes(12))); + $request = service('clirequest', null, false); + Services::injectMock('request', $request); + CITestStreamFilter::removeOutputFilter(); + + try { + $error = $this->exceptionWithCliArguments($secret, $dsn, 'trace-visible'); + (new Exceptions($config))->exceptionHandler($error); + + $this->assertLogContains('critical', "exceptionWithCliArguments([redacted], [redacted], 'trace-visible')"); + $this->assertFalse(TestLogger::didLog('critical', $secret, false)); + $this->assertFalse(TestLogger::didLog('critical', $dsn, false)); + + $output = str_replace([' ', PHP_EOL], '', $this->getStreamFilterBuffer()); + $this->assertStringContainsString("exceptionWithCliArguments([redacted],[redacted],'trace-visible')", $output); + $this->assertStringNotContainsString($secret, $output); + $this->assertStringNotContainsString(str_replace(' ', '', $dsn), $output); + } finally { + $this->restoreIniValues(); + } } /** @@ -384,10 +918,10 @@ public function testMaskSensitiveData(): void $newTrace = $maskSensitiveData($trace, $keysToMask, $path); - $this->assertSame(['password' => '******************'], (array) $newTrace[0]['args'][0]); - $this->assertSame(['password' => '******************'], $newTrace[0]['args'][1]->default); - $this->assertSame(['password' => '******************'], $newTrace[0]['args'][2]); - $this->assertSame(['password' => '******************'], $newTrace[0]['args'][3]['default']); + $this->assertSame(['password' => '[redacted]'], (array) $newTrace[0]['args'][0]); + $this->assertSame(['password' => '[redacted]'], $newTrace[0]['args'][1]->default); + $this->assertSame(['password' => '[redacted]'], $newTrace[0]['args'][2]); + $this->assertSame(['password' => '[redacted]'], $newTrace[0]['args'][3]['default']); } public function testMaskSensitiveDataTraceDataKey(): void @@ -420,6 +954,14 @@ public function testMaskSensitiveDataTraceDataKey(): void $this->assertSame('/var/www/CodeIgniter4/app/Controllers/Home.php', $newTrace[0]['file']); } + public function testMaskSensitiveDataLeavesFramesWithoutArgumentsIntact(): void + { + $maskSensitiveData = self::getPrivateMethodInvoker($this->handler, 'maskSensitiveData'); + $trace = [['function' => 'run']]; + + $this->assertSame($trace, $maskSensitiveData($trace, ['password'])); + } + public function testHighlightFile(): void { $this->backupIniValues([ @@ -436,130 +978,55 @@ public function testHighlightFile(): void $this->restoreIniValues(); } - public function testSanitizeDataWithResource(): void + private function exceptionWithApiArguments(#[SensitiveParameter] string $credential, string $public): RuntimeException { - $sanitizeData = self::getPrivateMethodInvoker($this->handler, 'sanitizeData'); - - // Create a resource (file handle) - $resource = fopen('php://memory', 'rb'); - $result = $sanitizeData($resource); + $exception = new RuntimeException('API error response test.'); + [$sensitive, $visible] = $exception->getTrace()[0]['args']; - $this->assertIsString($result); - $this->assertStringStartsWith('[Resource #', $result); - $this->assertStringEndsWith(']', $result); + $this->assertInstanceOf(SensitiveParameterValue::class, $sensitive); + $this->assertSame($credential, $sensitive->getValue()); + $this->assertSame($public, $visible); - fclose($resource); + return $exception; } - public function testSanitizeDataWithClosure(): void + private function exceptionWithCliArguments(string $credential, string $connection, string $label): RuntimeException { - $sanitizeData = self::getPrivateMethodInvoker($this->handler, 'sanitizeData'); + $exception = new RuntimeException('CLI error output test.'); + $this->assertSame([$credential, $connection, $label], $exception->getTrace()[0]['args']); - $closure = static fn (): string => 'test'; - $result = $sanitizeData($closure); - - $this->assertSame('[Closure]', $result); + return $exception; } - public function testSanitizeDataWithCircularReference(): void + private function exceptionWithTraceDepth(int $depth, ?RuntimeException $previous = null): RuntimeException { - $sanitizeData = self::getPrivateMethodInvoker($this->handler, 'sanitizeData'); - - // Create an object with circular reference - $obj = new stdClass(); - $obj->self = $obj; - - $result = $sanitizeData($obj); - - $this->assertIsArray($result); - $this->assertArrayHasKey('self', $result); - $this->assertStringContainsString('*RECURSION*', (string) $result['self']); - $this->assertStringContainsString('stdClass', (string) $result['self']); + return $depth === 0 + ? new RuntimeException('Deep trace.', previous: $previous) + : $this->exceptionWithTraceDepth($depth - 1, $previous); } - public function testSanitizeDataWithArrayContainingResource(): void + private function createExceptionForArgumentPreview(string $sample): RuntimeException { - $sanitizeData = self::getPrivateMethodInvoker($this->handler, 'sanitizeData'); - - $resource = fopen('php://memory', 'rb'); - $data = [ - 'string' => 'test', - 'number' => 123, - 'resource' => $resource, - ]; + $exception = $this->createExceptionWithPreviewInnerArgument('value passed to the inner call'); + $this->assertSame([$sample], $exception->getTrace()[1]['args']); - $result = $sanitizeData($data); - - $this->assertIsArray($result); - $this->assertSame('test', $result['string']); - $this->assertSame(123, $result['number']); - $this->assertIsString($result['resource']); - $this->assertStringStartsWith('[Resource #', $result['resource']); - - fclose($resource); + return $exception; } - public function testSanitizeDataWithObjectContainingResource(): void + private function createExceptionWithPreviewInnerArgument(string $inner): RuntimeException { - $sanitizeData = self::getPrivateMethodInvoker($this->handler, 'sanitizeData'); - - $resource = fopen('php://memory', 'rb'); - - $obj = new stdClass(); - $obj->name = 'test'; - $obj->connID = $resource; - $obj->database = 'mydb'; + $exception = new RuntimeException('Argument preview test.'); + $this->assertSame([$inner], $exception->getTrace()[0]['args']); - $result = $sanitizeData($obj); - - $this->assertIsArray($result); - $this->assertSame('test', $result['name']); - $this->assertSame('mydb', $result['database']); - $this->assertIsString($result['connID']); - $this->assertStringStartsWith('[Resource #', $result['connID']); - - fclose($resource); + return $exception; } - public function testSanitizeDataWithNestedObjects(): void + private function forwardSensitiveTraceArgument(string $password): RuntimeException { - $sanitizeData = self::getPrivateMethodInvoker($this->handler, 'sanitizeData'); - - $resource = fopen('php://memory', 'rb'); - - $inner = new stdClass(); - $inner->connID = $resource; - $inner->host = 'localhost'; - - $outer = new stdClass(); - $outer->db = $inner; - $outer->cache = 'file'; - - $result = $sanitizeData($outer); - - $this->assertIsArray($result); - $this->assertSame('file', $result['cache']); - $this->assertIsArray($result['db']); - $this->assertSame('localhost', $result['db']['host']); - $this->assertIsString($result['db']['connID']); - $this->assertStringStartsWith('[Resource #', $result['db']['connID']); - - fclose($resource); - } - - public function testSanitizeDataWithScalars(): void - { - $sanitizeData = self::getPrivateMethodInvoker($this->handler, 'sanitizeData'); - - $this->assertSame('string', $sanitizeData('string')); - $this->assertSame(123, $sanitizeData(123)); - $this->assertEqualsWithDelta(45.67, $sanitizeData(45.67), PHP_FLOAT_EPSILON); - $this->assertTrue($sanitizeData(true)); - $this->assertFalse($sanitizeData(false)); - $this->assertNull($sanitizeData(null)); + return $this->createExceptionWithSensitiveTraceArgument($password); } - private function createExceptionWithSensitiveTraceArgument(): RuntimeException + private function createExceptionWithSensitiveTraceArgument(string $password): RuntimeException { return new RuntimeException('Trace argument test.'); } @@ -571,22 +1038,20 @@ private function extractCopyableErrorReport(string $output): string return html_entity_decode($matches[0], ENT_QUOTES | ENT_HTML5, 'UTF-8'); } - private function renderHtmlException(RuntimeException $exception): string + private function renderHtmlException(RuntimeException $exception, ?IncomingRequest $request = null, ?ResponseInterface $response = null): string { - $this->backupIniValues([ - 'highlight.comment', 'highlight.default', 'highlight.html', 'highlight.keyword', 'highlight.string', - ]); - - $render = self::getPrivateMethodInvoker($this->handler, 'render'); + $request ??= service('request'); + $response ??= service('response'); + $request->setHeader('Accept', 'text/html'); ob_start(); try { - $render($exception, 500, APPPATH . 'Views/errors/html/error_exception.php'); + $this->handler->handle($exception, $request, $response, 500, EXIT_ERROR); - return ob_get_clean(); + return ob_get_contents(); } finally { - $this->restoreIniValues(); + ob_end_clean(); } } } diff --git a/tests/system/Debug/ExceptionsTest.php b/tests/system/Debug/ExceptionsTest.php index ed58a8b1e8e6..4cbffa4ca5fc 100644 --- a/tests/system/Debug/ExceptionsTest.php +++ b/tests/system/Debug/ExceptionsTest.php @@ -154,6 +154,52 @@ public function testDetermineCodes(): void $this->assertSame([403, EXIT_CONFIG], $determineCodes(HoneypotException::isBot())); } + public function testShutdownLogsPreviousTraceWhenDisplayBacktracesAreDisabled(): void + { + $homePath = var_export(HOMEPATH, true); + $bootstrap = var_export(SYSTEMPATH . 'util_bootstrap.php', true); + + $code = <<setValue(service('exceptions'), \$previous); + + register_shutdown_function(static function (): void { + echo TestLogger::didLog('critical', 'shutdownPreviousFrame()', false) ? 'PREVIOUS TRACE LOGGED' : 'PREVIOUS TRACE MISSING'; + echo TestLogger::didLog('critical', 'previous-argument-marker', false) ? 'ARGUMENT LOGGED' : ''; + }); + + causeFatalRedeclaration(); + causeFatalRedeclaration(); + PHP; + + $command = sprintf('%s -d zend.exception_ignore_args=0 -r %s 2>&1', escapeshellarg(PHP_BINARY), escapeshellarg($code)); + exec($command, $lines, $status); + $output = implode(PHP_EOL, $lines); + + $this->assertSame(255, $status, $output); + $this->assertStringContainsString('PREVIOUS TRACE LOGGED', $output); + $this->assertStringNotContainsString('ARGUMENT LOGGED', $output); + $this->assertStringNotContainsString('shutdownPreviousFrame()', $output); + } + public function testResetForWorkerModeClearsPreviousRequestState(): void { $this->setPrivateProperty($this->exception, 'exceptionCaughtByExceptionHandler', new RuntimeException('Previous request')); diff --git a/tests/system/Debug/Inspection/CodeSnippetTest.php b/tests/system/Debug/Inspection/CodeSnippetTest.php new file mode 100644 index 000000000000..ea3674600a45 --- /dev/null +++ b/tests/system/Debug/Inspection/CodeSnippetTest.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug\Inspection; + +use CodeIgniter\Test\CIUnitTestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; + +/** + * @internal + */ +#[CoversClass(CodeSnippet::class)] +#[Group('Others')] +final class CodeSnippetTest extends CIUnitTestCase +{ + public function testLimitsTheSnippetAndRetainsMultilineTokenContext(): void + { + $source = "\r\n", 18) . "*/\r\nreturn 'done';"; + + $this->withSource($source, function (string $file): void { + $lines = CodeSnippet::get($file, 12); + + $this->assertSame(range(5, 19), array_keys($lines)); + $this->assertSame('<tag>', $lines[5]); + $this->assertSame([], CodeSnippet::get($file, 100)); + }); + } + + public function testPlainExcerptKeepsSourceTextAndLimitsContext(): void + { + $source = "\r\n", 9); + + $this->withSource($source, function (string $file): void { + $lines = CodeSnippet::get($file, 6, highlight: false); + + $this->assertSame(array_fill(3, 7, '// '), $lines); + $this->assertSame([], CodeSnippet::get($file, 100, highlight: false)); + }); + } + + public function testTruncatesLongLines(): void + { + $this->withSource("assertSame('//' . str_repeat('x', 998) . '…', strip_tags($lines[2])); + }); + } + + public function testTruncatesAtUtf8BoundariesAcrossTokens(): void + { + $prefix = 'echo "' . str_repeat('x', 993); + + $this->withSource(sprintf("assertSame($prefix . '…', html_entity_decode(strip_tags($lines[2]), ENT_QUOTES, 'UTF-8')); + $this->assertSame('return 2;', strip_tags($lines[3])); + }); + } + + public function testSkipsOversizedFilesAndInvalidLocations(): void + { + $this->withSource(str_repeat('x', 1_048_577), function (string $file): void { + $this->assertSame([], CodeSnippet::get($file, 1)); + }); + + $this->assertSame([], CodeSnippet::get(__FILE__, 0)); + $this->assertSame([], CodeSnippet::get(__FILE__, null)); + $this->assertSame([], CodeSnippet::get(null, 1)); + $this->assertSame([], CodeSnippet::get(__FILE__ . '.missing.php', 1)); + } + + /** + * @param callable(string): void $test + */ + private function withSource(string $source, callable $test): void + { + $file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'ci-snippet-' . bin2hex(random_bytes(8)) . '.php'; + + try { + file_put_contents($file, $source); + $test($file); + } finally { + unlink($file); + } + } +} diff --git a/tests/system/Debug/Inspection/FrameTest.php b/tests/system/Debug/Inspection/FrameTest.php new file mode 100644 index 000000000000..86ccda2a6d97 --- /dev/null +++ b/tests/system/Debug/Inspection/FrameTest.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug\Inspection; + +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * @internal + */ +#[CoversClass(Frame::class)] +#[Group('Others')] +final class FrameTest extends TestCase +{ + public function testFormatsFunctionStaticAndInstanceCalls(): void + { + $function = new Frame('run'); + $static = new Frame('run', class: 'Example', type: '::'); + $instance = new Frame('run', class: 'Example', type: '->'); + + $this->assertSame('run()', $function->call()); + $this->assertSame('Example::run(42)', $static->call('42')); + $this->assertSame('Example()->run(42)', $instance->call('42')); + } + + public function testMetadataOmitsArgumentsAndMissingFields(): void + { + $frame = new Frame('run', '/example/file.php', arguments: ['private value']); + + $this->assertSame(['file' => '/example/file.php', 'function' => 'run'], $frame->metadata()); + } + + public function testResolvesSourceLocationWithoutALine(): void + { + $this->assertSame(['file' => '/example/file.php'], Frame::sourceLocation('/example/file.php', null)); + } + + public function testResolvesNestedEvalToTheOuterSourceLocation(): void + { + $file = "/example/file.php(17) : eval()'d code(3) : eval()'d code"; + + $this->assertSame(['file' => '/example/file.php', 'line' => 17], Frame::sourceLocation($file, 2)); + } +} diff --git a/tests/system/Debug/Inspection/FramesTest.php b/tests/system/Debug/Inspection/FramesTest.php new file mode 100644 index 000000000000..9a814940785d --- /dev/null +++ b/tests/system/Debug/Inspection/FramesTest.php @@ -0,0 +1,107 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug\Inspection; + +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\UsesClass; +use PHPUnit\Framework\TestCase; +use RuntimeException; + +/** + * @internal + */ +#[CoversClass(Frames::class)] +#[Group('Others')] +#[UsesClass(Frame::class)] +final class FramesTest extends TestCase +{ + public function testNormalizesClosureNamesAndNestedEvalLocations(): void + { + $exception = new RuntimeException('Example'); + $file = ROOTPATH . 'app/Example.php'; + $eval = sprintf("%s(17) : eval()'d code(3) : eval()'d code", $file); + $frames = Frames::fromException($exception, [ + ['file' => $eval, 'line' => 2, 'class' => 'Example', 'type' => '::', 'function' => '{closure:Example::run():13}'], + ['function' => 'eval'], + ['function' => 'App\{closure}'], + ])->take(3); + + $this->assertSame('{closure}', $frames[0]->function); + $this->assertSame('Example', $frames[0]->class); + $this->assertSame($file, $frames[1]->file); + $this->assertSame(17, $frames[1]->line); + $this->assertSame('{closure}', $frames[2]->function); + } + + public function testNormalizesThrowSiteAndKeepsArgumentsWithTheirCall(): void + { + $exception = new RuntimeException('Example'); + + $frames = Frames::fromException($exception, [ + [ + 'file' => '/example/Caller.php', + 'line' => 17, + 'class' => 'Example', + 'type' => '->', + 'function' => 'fail', + 'args' => ['masked'], + ], + ['function' => 'array_map'], + ]); + $this->assertCount(3, $frames); + + [$first, $caller, $main] = $frames->take(3); + + $this->assertSame([ + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + 'function' => 'fail', + 'class' => 'Example', + 'type' => '->', + ], $first->metadata()); + $this->assertSame(['masked'], $first->arguments); + $this->assertSame(['file' => '/example/Caller.php', 'line' => 17, 'function' => 'array_map'], $caller->metadata()); + $this->assertSame(['function' => '{main}'], $main->metadata()); + $this->assertSame([$first, $caller, $main], iterator_to_array($frames)); + $this->assertSame([$first, $caller], $frames->take(2)); + } + + public function testFromExceptionUsesTheCapturedTraceByDefault(): void + { + $capture = static fn (): RuntimeException => new RuntimeException('Example'); + $exception = $capture(); + $frame = Frames::fromException($exception)->take(1)[0]; + + $this->assertSame('{closure}', $frame->function); + $this->assertSame($exception->getFile(), $frame->file); + $this->assertSame($exception->getLine(), $frame->line); + } + + public function testEmptyTraceWithoutAStartingLocationHasNoFrames(): void + { + $frames = Frames::fromTrace([]); + + $this->assertCount(0, $frames); + $this->assertSame([], iterator_to_array($frames)); + } + + public function testEmptyTraceWithAStartingLocationHasAnEntryFrame(): void + { + $frames = Frames::fromTrace([], '/example/index.php', 42); + + $this->assertCount(1, $frames); + $this->assertSame(['file' => '/example/index.php', 'line' => 42, 'function' => '{main}'], $frames->take(1)[0]->metadata()); + } +} diff --git a/tests/system/Debug/Inspection/InspectorTest.php b/tests/system/Debug/Inspection/InspectorTest.php new file mode 100644 index 000000000000..b89e3245f3df --- /dev/null +++ b/tests/system/Debug/Inspection/InspectorTest.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Debug\Inspection; + +use CodeIgniter\Test\CIUnitTestCase; +use LogicException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use RuntimeException; +use TypeError; + +/** + * @internal + */ +#[CoversClass(Inspector::class)] +#[Group('Others')] +final class InspectorTest extends CIUnitTestCase +{ + public function testChainPreservesOrderAndThrowableIdentity(): void + { + $root = new TypeError('Root cause'); + $middle = new LogicException('Intermediate exception', previous: $root); + $outer = new RuntimeException('Reported exception', previous: $middle); + $inspector = new Inspector($outer); + + $this->assertSame([$outer, $middle, $root], $inspector->chain()); + $this->assertSame($root, $inspector->rootCause()); + } + + public function testUnchainedExceptionIsItsOwnRootCause(): void + { + $exception = new RuntimeException('Single exception'); + $inspector = new Inspector($exception); + + $this->assertSame([$exception], $inspector->chain()); + $this->assertSame($exception, $inspector->rootCause()); + } +}