From c1d34f30dfc6add0fd2aa326f617ed6c0f2a769d Mon Sep 17 00:00:00 2001 From: roxblnfk Date: Mon, 23 Nov 2026 16:22:58 +0400 Subject: [PATCH 1/2] feat(csp): receive browser CSP and Reporting API reports, show them in the web UI and over MCP As buggregator/server 2.14 does, Trap takes a POST with `application/csp-report` or `application/reports+json` on any path, or any POST to `/csp` and `/csp/{project}`, reads both formats into one report shape and answers 204. The CSP reports page of the web UI shows them, the console prints a block per report, and the MCP event tools list, filter (`report_type`, `directive`, `blocked`, `disposition`, `page`, `source_file`) and read them. A request marked for another module is left to it; a body over 1 MiB gets 413, one that is no report 400. `trap test` sends a report of each format. Chrome delivers Reporting API reports to another origin only after a CORS preflight, so an OPTIONS to `/csp` paths is answered for any origin; it is not an origin check. docs/csp.md and the skill's csp reference set up a Report-Only policy for plain PHP, Laravel and Symfony. Assisted-By: Claude Opus 5.5 --- README.md | 4 +- docs/README.md | 1 + docs/agent-skills.md | 2 +- docs/cli.md | 2 + docs/csp.md | 111 +++++++++ docs/http-dump.md | 3 +- docs/mcp.md | 21 +- docs/web-ui.md | 11 +- resources/payloads/csp.json | 58 +++++ skills/trap/SKILL.md | 3 +- skills/trap/references/csp.md | 47 ++++ skills/trap/references/mcp.md | 19 +- src/Module/Csp/Console/Renderer.php | 94 +++++++ src/Module/Csp/Frame.php | 70 ++++++ src/Module/Csp/Frontend/Mapper.php | 35 +++ src/Module/Csp/Http/CspTrap.php | 139 +++++++++++ src/Module/Csp/Mcp/CspView.php | 103 ++++++++ src/Module/Csp/Module.php | 64 +++++ src/Module/Csp/Report.php | 230 ++++++++++++++++++ src/Module/Frontend/EventQuery.php | 16 +- src/Module/Frontend/Http/StaticFiles.php | 2 +- src/Server/Application/Module/Modules.php | 2 + src/Server/Command/Test.php | 22 ++ tests/Acceptance/ServerTest.php | 9 +- .../Unit/Module/Console/ConsoleSenderTest.php | 2 + .../Module/Console/RendererSupportTest.php | 4 + .../Unit/Module/Csp/Console/RendererTest.php | 53 ++++ tests/Unit/Module/Csp/FrameTest.php | 42 ++++ tests/Unit/Module/Csp/Http/CspTrapTest.php | 146 +++++++++++ tests/Unit/Module/Csp/Mcp/CspViewTest.php | 70 ++++++ tests/Unit/Module/Csp/ReportTest.php | 132 ++++++++++ tests/Unit/Module/Frontend/EventQueryTest.php | 13 + .../Module/Frontend/Http/StaticFilesTest.php | 2 + tests/Unit/Module/Frontend/ServiceTest.php | 2 +- .../Mcp/Tool/EventFilterArgumentsTest.php | 2 +- tests/Unit/Module/Mcp/Tool/ListEventsTest.php | 1 + .../Server/Application/Module/ModulesTest.php | 2 + tests/Unit/Server/Command/TestTest.php | 2 +- tests/Unit/Server/Proto/FrameTypesTest.php | 3 + tools/structarmed/structarmed.php | 3 +- 40 files changed, 1517 insertions(+), 30 deletions(-) create mode 100644 docs/csp.md create mode 100644 resources/payloads/csp.json create mode 100644 skills/trap/references/csp.md create mode 100644 src/Module/Csp/Console/Renderer.php create mode 100644 src/Module/Csp/Frame.php create mode 100644 src/Module/Csp/Frontend/Mapper.php create mode 100644 src/Module/Csp/Http/CspTrap.php create mode 100644 src/Module/Csp/Mcp/CspView.php create mode 100644 src/Module/Csp/Module.php create mode 100644 src/Module/Csp/Report.php create mode 100644 tests/Unit/Module/Csp/Console/RendererTest.php create mode 100644 tests/Unit/Module/Csp/FrameTest.php create mode 100644 tests/Unit/Module/Csp/Http/CspTrapTest.php create mode 100644 tests/Unit/Module/Csp/Mcp/CspViewTest.php create mode 100644 tests/Unit/Module/Csp/ReportTest.php diff --git a/README.md b/README.md index 93a537fd..95e7a6ab 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,7 @@ The ports below are the defaults of the clients. | Ray | host `127.0.0.1`, port `8000` in `ray.php` | [Ray](docs/ray.md) | | HTTP dumps | any HTTP request, e.g. `http://127.0.0.1:8000/webhook` | [HTTP dumps](docs/http-dump.md) | | OpenTelemetry (OTLP) | `OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318` | [OpenTelemetry](docs/opentelemetry.md) | +| CSP and Reporting API | `report-uri http://127.0.0.1:8000/csp/my-app` in the policy | [CSP reports](docs/csp.md) | | Profiles | `trap()::profile()`, `POST /api/profiler/*`, a watched directory | [Profiling](docs/profiling.md), [receiving](docs/profiles.md), [SPX](docs/spx.md) | | Xdebug step debugging | `--xdebug`, `xdebug.client_port=9003`, the IDE moved to `9004` | [Xdebug debugger](docs/xdebug.md) | | Xdebug function traces | `POST` with `X-Buggregator-Event: xdebug-trace`, a watched directory | [Xdebug traces](docs/xdebug-traces.md) | @@ -232,7 +233,8 @@ All the options and variables: [CLI](docs/cli.md) and [Configuration](docs/confi - [Functions](docs/functions.md) - [Profiling code](docs/profiling.md) and [receiving profiles](docs/profiles.md), [SPX](docs/spx.md) - Integrations: [var-dumper](docs/var-dumper.md), [Monolog](docs/monolog.md), [Sentry](docs/sentry.md), - [SMTP](docs/smtp.md), [Ray](docs/ray.md), [HTTP dumps](docs/http-dump.md), [OpenTelemetry](docs/opentelemetry.md) + [SMTP](docs/smtp.md), [Ray](docs/ray.md), [HTTP dumps](docs/http-dump.md), [OpenTelemetry](docs/opentelemetry.md), + [CSP reports](docs/csp.md) - [Senders](docs/senders.md) - [Web UI](docs/web-ui.md) - [MCP server](docs/mcp.md) diff --git a/docs/README.md b/docs/README.md index 3598a477..72cb582c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -21,6 +21,7 @@ - [Ray](ray.md) - payloads of Ray clients. - [HTTP dumps](http-dump.md) - any other HTTP request. - [OpenTelemetry](opentelemetry.md) - traces over OTLP/HTTP. +- [CSP reports](csp.md) - Content Security Policy violations and Reporting API reports of browsers. - [Receiving profiles](profiles.md) - XHProf, Xdebug, Speedscope, pprof and SPX over HTTP or from a directory. - [SPX](spx.md) - SPX full reports: directory, HTTP and profiling from code. - [Xdebug traces](xdebug-traces.md) - Xdebug function traces over HTTP or from a directory: the call tree. diff --git a/docs/agent-skills.md b/docs/agent-skills.md index 09f42624..296c97e6 100644 --- a/docs/agent-skills.md +++ b/docs/agent-skills.md @@ -21,7 +21,7 @@ The agent loads the skill when it debugs or profiles code at runtime, reads what The references of the skill cover dumps and logs, profiling and Xdebug function traces, step debugging with the [Xdebug debugger](xdebug.md), long-running workers, pointing Sentry, Monolog, Ray, a mailer or OpenTelemetry at Trap, -and the server setup. +fixing a Content Security Policy with the [CSP reports](csp.md) of a Report-Only policy, and the server setup. ## Install with Composer diff --git a/docs/cli.md b/docs/cli.md index bea05198..1a3a93fc 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -68,6 +68,8 @@ page of the [web UI](web-ui.md), Sentry pages included: trace with database, cache and HTTP spans, logs and trace metrics; - an [OpenTelemetry](opentelemetry.md) trace across two services, with logs and metrics of each type; - a Sentry error with logs of a second project, `billing`; +- [CSP reports](csp.md) of each format: a `report-uri` violation, and a Reporting API batch of a violation and a + deprecation; - an image as binary data. The times of the logs, traces and metrics are those of the run, so the period filters of the UI show them. diff --git a/docs/csp.md b/docs/csp.md new file mode 100644 index 00000000..21d0536d --- /dev/null +++ b/docs/csp.md @@ -0,0 +1,111 @@ +# CSP reports + +Trap receives the security reports browsers send: Content Security Policy violations and the other reports of the +Reporting API, such as `deprecation`, `intervention`, `crash` and `network-error`. Point a policy of your +application at Trap, open its pages, and every resource the policy would block shows up in the console, on the +CSP reports page of the [web UI](web-ui.md) and in the [MCP tools](mcp.md#csp-reports). + +Your application only sends a header: there is no client to install. Use `Content-Security-Policy-Report-Only` while +you debug a policy: the browser reports what the policy would block and blocks nothing. + +## Receive reports + +Send the reports to `/csp` or `/csp/{project}` on an HTTP port of Trap, `8000` by default: + +```text +http://127.0.0.1:8000/csp/my-app +``` + +Trap takes a report from a `POST`: + +- with the `application/csp-report` content type, of the `report-uri` directive, to any path; +- with the `application/reports+json` content type, of the `report-to` directive, to any path; +- to `/csp` or `/csp/{project}` with any content type: a JSON list is read as `reports+json`, an object as + `csp-report`. + +So an existing report URL of your application works too when its host and port point at Trap. A request marked for +another kind of event, with the `X-Buggregator-Event` header or the user of Basic authorization, is left to it. + +The project of the reports is the `{project}` of the path, else the password of the `csp` user of Basic +authorization (`http://csp:my-app@127.0.0.1:8000/`), else the `X-Buggregator-Project` header, else `default`. + +Trap answers a report with `204` and an empty body, a body that is not a report with `400`, and a body larger than +1 MiB with `413`. An `OPTIONS` request to `/csp` or `/csp/{project}` gets a CORS preflight answer for any origin: +Chrome sends Reporting API reports to another origin only after one. + +## Set up the policy + +The samples send the policy only in development: take it out of the application when you are done. + +### `report-uri` + +`report-uri` sends a `csp-report` right away, one request per violation, from HTTP and HTTPS pages alike. + +```php +if (getenv('APP_ENV') === 'dev') { + header("Content-Security-Policy-Report-Only: default-src 'self'; report-uri http://127.0.0.1:8000/csp/my-app"); +} +``` + +### `report-to` and `Reporting-Endpoints` + +`report-to` names an endpoint of the `Reporting-Endpoints` header and sends `reports+json`. The endpoint named +`default` also gets the other reports of the page: deprecations, interventions, crashes. + +```php +if (getenv('APP_ENV') === 'dev') { + header('Reporting-Endpoints: trap="https://127.0.0.1:8000/csp/my-app", default="https://127.0.0.1:8000/csp/my-app"'); + header("Content-Security-Policy-Report-Only: default-src 'self'; report-to trap; report-uri https://127.0.0.1:8000/csp/my-app"); +} +``` + +- Chrome sends Reporting API reports only from an HTTPS page to an HTTPS endpoint, so the endpoint is `https://`: + Trap takes TLS on the same port, and the browser must trust its certificate, see [TLS](tls.md#certificate). +- A browser that knows `report-to` ignores `report-uri` in the same policy; keep both for the other browsers. +- The browser batches the reports and sends them with a delay of up to a minute. Keep the page open meanwhile. +- Send the reports of another origin to `/csp` or `/csp/{project}`: only these paths answer the preflight. + +### Laravel + +[spatie/laravel-csp](https://github.com/spatie/laravel-csp) adds `report-uri` from `report_uri` of +`config/csp.php`, which reads `CSP_REPORT_URI`. Set it in the `.env` of development: + +```dotenv +CSP_REPORT_URI=http://127.0.0.1:8000/csp/my-app +``` + +Put the policy you debug into the report-only one: `report_only_presets` in version 3 of the package, +`report_only_policy` in version 2. + +### Symfony + +[NelmioSecurityBundle](https://github.com/nelmio/NelmioSecurityBundle) sends the `report` policy as +`Content-Security-Policy-Report-Only`: + +```yaml +# config/packages/nelmio_security.yaml +when@dev: + nelmio_security: + csp: + report: + default-src: ['self'] + report-uri: ['http://127.0.0.1:8000/csp/my-app'] +``` + +## HTTPS pages + +An HTTPS page sends no report to an `http://` URL of a host other than `127.0.0.1` or `localhost`: the browser +blocks it as mixed content. When Trap runs on another host, for example in Docker, report to `https://` on its +port, with a certificate the browser trusts: see [TLS](tls.md#certificate). + +## What Trap shows + +The console prints a block per report: what was blocked or reported, the report type, the page, the directive, what +was blocked, the disposition (`enforce`: blocked; `report`: Report-Only, not blocked), the source file with its line +and column, the code sample, the message of a report of another type, the policy and the user agent. + +One request is one event of the `csp` type: a `report-uri` request carries one report, a `report-to` batch may +carry several. The web UI lists the events on its CSP reports page; the [MCP tools](mcp.md#csp-reports) list, +filter and read them. + +`vendor/bin/trap test` sends a report of each format. diff --git a/docs/http-dump.md b/docs/http-dump.md index fcf9f6cb..4612236e 100644 --- a/docs/http-dump.md +++ b/docs/http-dump.md @@ -20,7 +20,8 @@ which posts to `/_debug/bar`. That request is dumped and answered with `200`. ## Notes -- The requests of Sentry, Ray, the profilers and OpenTelemetry go to their modules and are not dumped. +- The requests of Sentry, Ray, the profilers, OpenTelemetry and [CSP reports](csp.md) go to their modules and are + not dumped. - When the [web UI](web-ui.md) runs on the same port, it answers `/`, the paths of its files, e.g. `/favicon.ico`, its `/api/...` routes, e.g. `/api/events`, and a browser opening a page of the UI, e.g. `/smtp`: see [Port](web-ui.md#port). diff --git a/docs/mcp.md b/docs/mcp.md index e82442a1..cd8d2af0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17,8 +17,9 @@ Other clients take the same URL with the `http` (Streamable HTTP) transport type ## Tools -The tools read the events Trap has caught, the Sentry and OpenTelemetry [traces](#traces) it has received, Sentry -[user feedback](#user-feedback), and the call trees of [Xdebug traces](#xdebug-traces). The events are the ones the [web UI](web-ui.md) shows, kept with +The tools read the events Trap has caught, [CSP reports](#csp-reports) among them, the Sentry and OpenTelemetry +[traces](#traces) it has received, Sentry [user feedback](#user-feedback), and the call trees of +[Xdebug traces](#xdebug-traces). The events are the ones the [web UI](web-ui.md) shows, kept with `--mcp` alone too. An event deleted in the UI is gone for the agent. An event the agent deletes is gone from the UI on its next load; a page already open keeps showing it. @@ -63,7 +64,7 @@ the agent deletes is gone from the UI on its next load; a page already open keep | Argument | Matches | | --------- | -------------------------------------------------------------------------------------------------------------------------------- | -| `type` | One event type or a list: `var-dump`, `smtp`, `monolog`, `ray`, `sentry`, `profiler`, `http-dump`, `xdebug-trace` | +| `type` | One event type or a list: `var-dump`, `smtp`, `monolog`, `ray`, `sentry`, `profiler`, `http-dump`, `xdebug-trace`, `csp` | | `project` | One project or a list; events sent without a project belong to `default` | | `from` | Events caught at this time or later: ISO 8601 (UTC without an offset) or a duration back from now: `30s`, `5m`, `2h`, `1d`, `1w` | | `to` | Events caught at this time or earlier, in the same forms | @@ -119,6 +120,7 @@ seconds. Trap catches events and answers other requests meanwhile, and a call st | `http-dump` | `method`, `path`, `host` | | `ray` | `payload_type`, `exception`, `label`, `color` | | `profiler` | `name` (the application or the file), `format` | +| `csp` | `report_type`, `directive`, `blocked`, `disposition`, `page`, `source_file` (of each report of the request) | An `xdebug-trace` event has no fields: its summary starts with the URL or the name of the trace, so `search` finds it. The `list_events` description lists the fields too. Examples: @@ -342,6 +344,19 @@ dropped. Clearing the Sentry pages of the web UI drops their traces for the tool ID of that error for `get_event`, null when Trap no longer has it or the feedback is about no error. - `limit` is 20 by default, 100 at most; `total` counts all the matching entries. +### CSP reports + +The browser [security reports](csp.md) are `csp` events, one per request of the browser, which may carry several +reports. The summary is the first report and its page, as `script-src-elem blocked https://cdn.example.com/x.js on +https://localhost:8080/checkout (+1 more)`. `get_event` gives a block per report: the title, then the report type, +the page, the directive, what was blocked, the disposition (`enforce`, blocked; `report`, Report-Only, not blocked), +the source file with its line and column, the code sample, the message and ID of a report of another type, the +policy and the user agent. A field of the report the browser left empty is left out. + +- The CSP violations of the last 5 minutes: `{"type": "csp", "from": "5m", "where": {"report_type": "csp-violation"}, + "include": "text"}`. +- What a page has blocked: `{"type": "csp", "where": {"page": "*/checkout*", "disposition": "enforce"}}`. + ### Profiles The [profiles](profiles.md) are `profiler` events. `get_event` gives one as the console prints it; these tools let diff --git a/docs/web-ui.md b/docs/web-ui.md index 88d2a87a..f694a65e 100644 --- a/docs/web-ui.md +++ b/docs/web-ui.md @@ -31,7 +31,8 @@ On a shared port the UI takes only its own requests, and the others stay [HTTP d such endpoint. Open the UI from Trap itself: it sends no CORS headers, so a frontend served from another origin, such as a dev -server of buggregator/frontend, can't call its API. An `OPTIONS` request is an HTTP dump like any other. +server of buggregator/frontend, can't call its API. An `OPTIONS` request is an HTTP dump like any other, but the +preflight of a [CSP report](csp.md) to `/csp`. The UI asks for no password or token, the [MCP token](mcp.md#security) included: anyone who reaches its port sees the caught events. Trap warns at startup when the port listens on a host other than a loopback one. @@ -43,8 +44,8 @@ vendor/bin/trap --ui=8080 -s ## What it shows -Dumps, Monolog logs, Sentry events, emails, Ray payloads, HTTP dumps, profiles and -[Xdebug traces](xdebug-traces.md) with their call tree. +Dumps, Monolog logs, Sentry events, emails, Ray payloads, HTTP dumps, profiles, +[Xdebug traces](xdebug-traces.md) with their call tree, and [CSP reports](csp.md) on the CSP reports page. The UI keeps the last 200 events; `/trap/events/@maxEvents` in [`trap.xml`](configuration.md#trapxml) changes it. A pinned event is pushed out last: only when all the kept events are pinned. A clear keeps the pinned events when @@ -59,8 +60,8 @@ sessions and steps through the ones Trap drives, and its setup guide shows the d The UI has pages for features of the Buggregator Server that Trap has not: metrics, the mock server, updates. They show no data, and the menu of the mock server stays while HTTP dumps are on: hide it in Settings › Menu. -Other features of the server stay hidden, as Trap answers 404 to their endpoints: the Broadcast and CSP reports -pages, the Crons and Queues tabs of the Sentry section, the +Other features of the server stay hidden, as Trap answers 404 to their endpoints: the Broadcast page, the Crons +and Queues tabs of the Sentry section, the «Send to inbox» button of an email (Settings › Email relay says the server can't send email), the other versions of an email and its invite card, sign-in and the audit log. A Ray pause shows its state in the tab whose button released it; another tab keeps its buttons. diff --git a/resources/payloads/csp.json b/resources/payloads/csp.json new file mode 100644 index 00000000..3f835feb --- /dev/null +++ b/resources/payloads/csp.json @@ -0,0 +1,58 @@ +[ + { + "content_type": "application/csp-report", + "body": { + "csp-report": { + "document-uri": "http://localhost:8080/checkout", + "referrer": "http://localhost:8080/cart", + "violated-directive": "script-src-elem", + "effective-directive": "script-src-elem", + "original-policy": "default-src 'self'; script-src 'self' 'nonce-r4nd0m'; report-uri http://127.0.0.1:8000/csp", + "disposition": "report", + "blocked-uri": "https://cdn.payments.example/widget.js", + "line-number": 42, + "column-number": 9, + "source-file": "http://localhost:8080/checkout", + "status-code": 200, + "script-sample": "" + } + } + }, + { + "content_type": "application/reports+json", + "body": [ + { + "age": 1530, + "body": { + "blockedURL": "inline", + "columnNumber": 17, + "disposition": "enforce", + "documentURL": "http://localhost:8080/profile", + "effectiveDirective": "script-src-elem", + "lineNumber": 88, + "originalPolicy": "script-src 'self'; report-to trap", + "referrer": "", + "sample": "document.getElementById('avatar').onclick", + "sourceFile": "http://localhost:8080/profile", + "statusCode": 200 + }, + "type": "csp-violation", + "url": "http://localhost:8080/profile", + "user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" + }, + { + "age": 920, + "body": { + "columnNumber": 5, + "id": "UnloadHandler", + "lineNumber": 12, + "message": "Unload event listeners are deprecated and will be removed.", + "sourceFile": "http://localhost:8080/assets/app.js" + }, + "type": "deprecation", + "url": "http://localhost:8080/profile", + "user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" + } + ] + } +] diff --git a/skills/trap/SKILL.md b/skills/trap/SKILL.md index ded1a112..c9d41ce7 100644 --- a/skills/trap/SKILL.md +++ b/skills/trap/SKILL.md @@ -1,6 +1,6 @@ --- name: trap -description: Debug or profile a running PHP application through Buggregator Trap and its MCP tools. Use when reading what the application sent at runtime (dumps, logs, exceptions, mails, requests, traces, profiles), pointing it at Trap, stepping through PHP code with Xdebug, calling Trap MCP tools such as `list_events`, or when code calls trap(), tr() or td(). +description: Debug or profile a running PHP application through Buggregator Trap and its MCP tools. Use when reading what the application sent at runtime (dumps, logs, exceptions, mails, requests, traces, profiles, CSP violations), pointing it at Trap, stepping through PHP code with Xdebug, calling Trap MCP tools such as `list_events`, or when code calls trap(), tr() or td(). --- # Trap @@ -46,6 +46,7 @@ the agent reads back through Trap's MCP tools. | [xdebug.md](references/xdebug.md) | Stopping at a line or an exception and stepping through PHP code: `--xdebug`, breakpoints, variables, `xdebug_*` tools | | [workers.md](references/workers.md) | Debugging RoadRunner, Swoole, FrankenPHP, Octane or queue workers: reloads, volume, memory leaks | | [integrations.md](references/integrations.md) | Pointing Sentry, Monolog, Ray, a mailer, OTel or VarDumper at Trap, a `4xx` they get; a scenario's output; tying logs to a trace | +| [csp.md](references/csp.md) | Fixing a Content Security Policy: a Report-Only policy that reports to Trap, reading the violations, browser reports | | [server.md](references/server.md) | Installing, starting Trap, its ports, the web UI, TLS, an application in Docker or on another host, the token, limits, `trap.xml` | Edge cases beyond these are in the full documentation: . diff --git a/skills/trap/references/csp.md b/skills/trap/references/csp.md new file mode 100644 index 00000000..feba0394 --- /dev/null +++ b/skills/trap/references/csp.md @@ -0,0 +1,47 @@ +# CSP reports + +Browsers report what a Content Security Policy blocks, and Trap catches the reports as `csp` events: one event per +request of the browser, holding one report (`report-uri`) or a batch (`report-to`). The application only sends a +header. The full reference: . + +## Fix a policy + +1. **Add a Report-Only policy** in the dev config of the application, pointing at Trap: + `Content-Security-Policy-Report-Only: ; report-uri http://127.0.0.1:8000/csp/`. + Report-Only blocks nothing, so the page keeps working while it reports. Done when a response of the page carries + the header: check with `curl -sI `. +2. **Open the page**: take a `cursor` with `list_events` `{"order": "newest", "limit": 1}`, then open the page in a + browser you drive (Playwright, a headless Chrome), or ask the user to open it and click through the parts to + check. +3. **Read the violations**: `list_events` with `{"since": "", "type": "csp", "include": "text"}`. The text + gives a block per report: the page, the directive, what was blocked (a URL, or `inline`, `eval`), the + disposition, the source file with line and column, the code sample. Done when every violation is either fixed + in the code (a nonce or hash, a moved script, a source added to the policy) or reported to the user as intended. +4. **Check again**: reload, wait with `wait_for_events` `{"since": "", "type": "csp", "timeout": 10}`; + done when `timed_out: true` comes back with no events. +5. **Remove the debug config** with the rest of step 5 of the skill: the Report-Only header and its `report-uri`. + Keep only the policy changes the user wants. + +## Setting the header + +- Plain PHP: `header("Content-Security-Policy-Report-Only: default-src 'self'; report-uri http://127.0.0.1:8000/csp/my-app");` +- Laravel, `spatie/laravel-csp`: `CSP_REPORT_URI=http://127.0.0.1:8000/csp/my-app` in `.env`; the policy under test in + `report_only_presets` (v3) or `report_only_policy` (v2) of `config/csp.php`. +- Symfony, NelmioSecurityBundle: `nelmio_security.csp.report` is the Report-Only policy; add + `report-uri: ['http://127.0.0.1:8000/csp/my-app']` to it under `when@dev`. + +## Gotchas + +- Any `POST` with `application/csp-report` or `application/reports+json` is caught on any path, so an existing + report URL works when its host and port point at Trap. The project is the `` of `/csp/`, else + the password of the Basic user `csp`, else `X-Buggregator-Project`, else `default`. A request with + `X-Buggregator-Event` or a Basic user of another type goes to that module. +- `report-to` with `Reporting-Endpoints` (`reports+json`) is slower and stricter: Chrome sends it only from an HTTPS + page to an `https://` endpoint the browser trusts (Trap takes TLS on the same port, see + [server.md](server.md#tls)), batches with a delay of up to a minute, and needs the endpoint on `/csp` or + `/csp/` for another origin. Prefer `report-uri` to debug: it reports at once from HTTP pages too. +- An HTTPS page can't report to `http://` on a host other than `127.0.0.1` or `localhost`: mixed content. For + Trap in Docker or on another host use `https://`. +- Filter with `where`: `report_type` (`csp-violation`, `deprecation`, `intervention`…), `directive`, `blocked`, + `disposition` (`enforce` blocked it, `report` only reported), `page`, `source_file`. +- Trap answers a report `204`; a body that is no report gets `400`, one over 1 MiB `413`. diff --git a/skills/trap/references/mcp.md b/skills/trap/references/mcp.md index bc9f74de..e0d1218d 100644 --- a/skills/trap/references/mcp.md +++ b/skills/trap/references/mcp.md @@ -41,7 +41,7 @@ The argument schema of each tool is in its `inputSchema` (`mcp.php tools ` | ----------------- | ----------------------------------------------------------------------------------------------- | | `list_events` | The events changed after `since`, oldest first; with `order: newest` the latest ones | | `wait_for_events` | Waits until `count` events (1 by default) match, up to `timeout` seconds (30, at most 50) | -| `get_event` | One event as plain text: the full dump, log record, exception, mail, request | +| `get_event` | One event as plain text: the full dump, log record, exception, mail, request, CSP report | | `delete_event` | Deletes events by `id` or `ids` | | `clear_events` | Deletes the events matching a filter, or all; pinned ones stay unless `include_pinned: true` | | `list_traces` | Sentry and OpenTelemetry traces; filters by project, source, service, name, duration, errors | @@ -70,14 +70,14 @@ The argument schema of each tool is in its `inputSchema` (`mcp.php tools ` `list_events`, `wait_for_events` and `clear_events` take the same filter; an event matches all the arguments given. -| Argument | Matches | -| --------- | ------------------------------------------------------------------------------------------------------------ | -| `type` | One or a list of `var-dump`, `monolog`, `sentry`, `smtp`, `http-dump`, `ray`, `profiler`, `xdebug-trace` | -| `project` | One or a list; events sent without a project belong to `default` | -| `from` | Caught at this time or later: ISO 8601 in UTC, or back from now in lower case: `30s`, `5m`, `2h`, `1d`, `1w` | -| `to` | Caught at this time or earlier, in the same forms | -| `search` | Text in the summary or the text of the event, in any case; `regex: true` makes it a PCRE pattern | -| `where` | Fields of the event, below | +| Argument | Matches | +| --------- | --------------------------------------------------------------------------------------------------------------- | +| `type` | One or a list of `var-dump`, `monolog`, `sentry`, `smtp`, `http-dump`, `ray`, `profiler`, `xdebug-trace`, `csp` | +| `project` | One or a list; events sent without a project belong to `default` | +| `from` | Caught at this time or later: ISO 8601 in UTC, or back from now in lower case: `30s`, `5m`, `2h`, `1d`, `1w` | +| `to` | Caught at this time or earlier, in the same forms | +| `search` | Text in the summary or the text of the event, in any case; `regex: true` makes it a PCRE pattern | +| `where` | Fields of the event, below | | Type | Fields | | ----------- | --------------------------------------------------------------------------------------------------------------- | @@ -88,6 +88,7 @@ The argument schema of each tool is in its `inputSchema` (`mcp.php tools ` | `http-dump` | `method`, `path`, `host` | | `ray` | `payload_type`, `exception`, `label`, `color` | | `profiler` | `name`, `format` | +| `csp` | `report_type`, `directive`, `blocked`, `disposition`, `page`, `source_file`, see [csp.md](csp.md) | A `where` string matches the whole value in any case, with `*` for any characters; a list matches any of its values. A field no type has fails the call. An `xdebug-trace` has no fields: `search` finds it by its URL or name. diff --git a/src/Module/Csp/Console/Renderer.php b/src/Module/Csp/Console/Renderer.php new file mode 100644 index 00000000..ceef57a5 --- /dev/null +++ b/src/Module/Csp/Console/Renderer.php @@ -0,0 +1,94 @@ + + * + * @psalm-import-type CspReport from Report + * + * @internal + */ +final class Renderer implements RendererInterface +{ + /** + * A one-line title of a report: `script-src-elem blocked https://cdn.test/x.js`, or `deprecation: `. + * + * @param CspReport $report + */ + public static function title(array $report): string + { + if (Report::isViolation($report)) { + $directive = $report['directive'] ?? 'CSP'; + $blocked = $report['blocked'] ?? ''; + + return $blocked === '' ? "$directive violation" : "$directive blocked $blocked"; + } + + $type = $report['type'] === '' ? 'report' : $report['type']; + + return isset($report['message']) ? "$type: {$report['message']}" : $type; + } + + #[\Override] + public function isSupport(Frame $frame): bool + { + return $frame instanceof CspFrame; + } + + #[\Override] + public function render(OutputInterface $output, Frame $frame): void + { + \assert($frame instanceof CspFrame); + + Common::renderHeader1($output, 'CSP', $frame->format, ...($frame->project === null ? [] : ['cyan' => $frame->project])); + Common::renderMetadata($output, ['Time' => $frame->time]); + + foreach ($frame->reports as $report) { + self::renderReport($output, $report); + } + } + + /** + * @param CspReport $report + */ + private static function renderReport(OutputInterface $output, array $report): void + { + Common::renderHeader2($output, OutputFormatter::escape(self::title($report))); + + $disposition = $report['disposition'] ?? ''; + $metadata = [ + 'Type' => $report['type'], + 'Page' => $report['url'], + 'Directive' => $report['directive'] ?? '', + 'Blocked' => $report['blocked'] ?? '', + 'Disposition' => match ($disposition) { + 'enforce' => 'enforce (blocked)', + 'report' => 'report (Report-Only: not blocked)', + default => $disposition, + }, + 'Source' => Report::source($report), + 'Sample' => $report['sample'] ?? '', + 'Message' => $report['message'] ?? '', + 'ID' => $report['id'] ?? '', + 'Policy' => $report['policy'] ?? '', + 'User agent' => $report['user_agent'] ?? '', + ]; + Common::renderMetadata($output, \array_map( + OutputFormatter::escape(...), + \array_filter($metadata, static fn(string $value): bool => $value !== ''), + )); + } +} diff --git a/src/Module/Csp/Frame.php b/src/Module/Csp/Frame.php new file mode 100644 index 00000000..28e545f5 --- /dev/null +++ b/src/Module/Csp/Frame.php @@ -0,0 +1,70 @@ + $reports + * @param non-empty-string|null $project Null for the default project. + */ + public function __construct( + public readonly string $format, + public readonly array $reports, + public readonly ?string $project = null, + \DateTimeImmutable $time = new \DateTimeImmutable(), + ) { + parent::__construct(self::TYPE, $time); + } + + /** + * @throws \JsonException + * @throws \InvalidArgumentException When the JSON is not a frame of reports. + */ + #[\Override] + public static function fromString(string $payload, \DateTimeImmutable $time): static + { + $data = Json::decode($payload); + $format = \is_array($data) ? $data['format'] ?? null : null; + $reports = \is_array($data) ? $data['reports'] ?? null : null; + \in_array($format, [Report::FORMAT_CSP, Report::FORMAT_REPORTS], true) + && \is_array($reports) && \array_is_list($reports) && $reports !== [] + or throw new \InvalidArgumentException('A CSP frame must have a format and reports.'); + \assert(\is_array($data)); + + /** @var mixed $project */ + $project = $data['project'] ?? null; + + return new self( + $format, + \array_map(Report::restore(...), $reports), + \is_string($project) && $project !== '' ? $project : null, + $time, + ); + } + + /** + * @throws \JsonException + */ + public function __toString(): string + { + return Json::encode(['format' => $this->format, 'reports' => $this->reports, 'project' => $this->project]); + } +} diff --git a/src/Module/Csp/Frontend/Mapper.php b/src/Module/Csp/Frontend/Mapper.php new file mode 100644 index 00000000..121c0cf1 --- /dev/null +++ b/src/Module/Csp/Frontend/Mapper.php @@ -0,0 +1,35 @@ + $frame->format, 'reports' => $frame->reports], + timestamp: (float) $frame->time->format('U.u'), + project: $frame->project, + ); + } +} diff --git a/src/Module/Csp/Http/CspTrap.php b/src/Module/Csp/Http/CspTrap.php new file mode 100644 index 00000000..10656bcb --- /dev/null +++ b/src/Module/Csp/Http/CspTrap.php @@ -0,0 +1,139 @@ +getUri()->getPath(); + $ownPath = $path === '/csp' || \str_starts_with($path, '/csp/'); + if ($ownPath && $request->getMethod() === 'OPTIONS') { + return self::preflight(); + } + + $format = Report::formatOf($request->getHeaderLine('Content-Type')); + if ($request->getMethod() !== 'POST' || self::markedForOther($request) || $format === null && !$ownPath) { + return $next($request); + } + + $size = $request->getBody()->getSize(); + if ($size === null || $size > self::MAX_BODY_SIZE) { + return $this->reject(413, 'the body is larger than 1 MiB.'); + } + + try { + [$format, $reports] = Report::parse($format, (string) $request->getBody()); + } catch (\InvalidArgumentException $e) { + return $this->reject(400, \lcfirst($e->getMessage())); + } + + /** @var mixed $time */ + $time = $request->getAttribute('begin_at'); + \Fiber::suspend(new Frame( + $format, + $reports, + self::project($request), + $time instanceof \DateTimeImmutable ? $time : new \DateTimeImmutable(), + )); + + return new Response(204, ['Access-Control-Allow-Origin' => '*']); + } + + /** + * Chrome delivers Reporting API reports to another origin only after a CORS preflight succeeds, + * and drops them otherwise. + */ + private static function preflight(): ResponseInterface + { + return new Response(204, [ + 'Access-Control-Allow-Origin' => '*', + 'Access-Control-Allow-Methods' => 'POST', + 'Access-Control-Allow-Headers' => 'Content-Type', + 'Access-Control-Max-Age' => '86400', + ]); + } + + private static function markedForOther(ServerRequestInterface $request): bool + { + $event = \strtolower(\trim($request->getHeaderLine('X-Buggregator-Event'))); + $user = self::basicAuth($request)[0]; + + return $event !== '' && $event !== Frame::TYPE || $user !== '' && $user !== Frame::TYPE; + } + + /** + * @return non-empty-string|null + */ + private static function project(ServerRequestInterface $request): ?string + { + $path = $request->getUri()->getPath(); + $project = \str_starts_with($path, '/csp/') ? \trim(\rawurldecode(\substr($path, 5)), '/ ') : ''; + if ($project === '') { + [$user, $password] = self::basicAuth($request); + $project = $user === Frame::TYPE ? $password : ''; + } + $project === '' and $project = \trim($request->getHeaderLine('X-Buggregator-Project')); + + return $project === '' ? null : $project; + } + + /** + * A URL like `http://csp:shop@host/` comes as Basic authorization. + * + * @return array{string, string} The user and the password; empty strings without Basic authorization. + */ + private static function basicAuth(ServerRequestInterface $request): array + { + $header = $request->getHeaderLine('Authorization'); + $credentials = \strncasecmp($header, 'Basic ', 6) === 0 + ? \base64_decode(\trim(\substr($header, 6)), true) + : false; + if ($credentials === false) { + return ['', '']; + } + + $parts = \explode(':', $credentials, 2); + + return [\strtolower($parts[0]), $parts[1] ?? '']; + } + + private function reject(int $status, string $reason): ResponseInterface + { + $this->logger?->warning('CSP: report rejected with %d: %s', $status, $reason); + + return new Response($status); + } +} diff --git a/src/Module/Csp/Mcp/CspView.php b/src/Module/Csp/Mcp/CspView.php new file mode 100644 index 00000000..3dda14b5 --- /dev/null +++ b/src/Module/Csp/Mcp/CspView.php @@ -0,0 +1,103 @@ + 1 and $summary .= \sprintf(' (+%d more)', \count($reports) - 1); + + $summary = PayloadSummary::shorten($summary); + + return $summary === '' ? null : $summary; + } + + #[\Override] + public function text(Record $record): ?string + { + return null; + } + + #[\Override] + public function fieldNames(): array + { + return [Mapper::TYPE => self::FIELDS]; + } + + #[\Override] + public function fields(Event $event): ?array + { + $reports = self::reports($event); + if ($reports === null) { + return null; + } + + $values = static function (string $key) use ($reports): array { + $values = []; + foreach ($reports as $report) { + /** @var mixed $value */ + $value = $report[$key] ?? null; + \is_string($value) && $value !== '' && !\in_array($value, $values, true) and $values[] = $value; + } + + return $values; + }; + + return [ + 'report_type' => $values('type'), + 'directive' => $values('directive'), + 'blocked' => $values('blocked'), + 'disposition' => $values('disposition'), + 'page' => $values('url'), + 'source_file' => $values('source_file'), + ]; + } + + /** + * @return list|null Null for an event of another type. + */ + private static function reports(Event $event): ?array + { + $payload = $event->payload; + /** @var mixed $reports */ + $reports = \is_array($payload) ? $payload['reports'] ?? null : null; + if ($event->type !== Mapper::TYPE || !\is_array($reports)) { + return null; + } + + return \array_values(\array_map(Report::restore(...), $reports)); + } +} diff --git a/src/Module/Csp/Module.php b/src/Module/Csp/Module.php new file mode 100644 index 00000000..42c65151 --- /dev/null +++ b/src/Module/Csp/Module.php @@ -0,0 +1,64 @@ + Frame::class]; + } + + #[\Override] + public function renderers(): array + { + return [Renderer::class]; + } + + #[\Override] + public function eventMappers(): array + { + return [Frame::class => Mapper::class]; + } + + #[\Override] + public function eventTypes(): array + { + return [Mapper::TYPE]; + } + + #[\Override] + public function eventViews(): array + { + return [CspView::class]; + } +} diff --git a/src/Module/Csp/Report.php b/src/Module/Csp/Report.php new file mode 100644 index 00000000..a15f5127 --- /dev/null +++ b/src/Module/Csp/Report.php @@ -0,0 +1,230 @@ + self::FORMAT_CSP, + 'application/reports+json' => self::FORMAT_REPORTS, + default => null, + }; + } + + /** + * @param self::FORMAT_*|null $format Null to guess by the body: a list is `reports+json`, an object `csp-report`. + * + * @return array{self::FORMAT_*, non-empty-list} + * + * @throws \InvalidArgumentException When the body is not a document of the format. + */ + public static function parse(?string $format, string $body): array + { + $format ??= \str_starts_with(\ltrim($body), '[') ? self::FORMAT_REPORTS : self::FORMAT_CSP; + + try { + /** @var mixed $data */ + $data = Json::finite(Json::decode($body)); + } catch (\JsonException $e) { + throw new \InvalidArgumentException("Not a $format document: {$e->getMessage()}", previous: $e); + } + + return [$format, $format === self::FORMAT_CSP ? [self::cspReport($data)] : self::reports($data)]; + } + + /** + * A report as {@see parse()} made it, from its JSON: the frames come back from files and other Trap servers. + * + * @return CspReport + */ + public static function restore(mixed $report): array + { + \is_array($report) or $report = []; + /** @var mixed $body */ + $body = $report['body'] ?? null; + + return self::make( + [ + 'type' => $report['type'] ?? null, + 'url' => $report['url'] ?? null, + 'user_agent' => $report['user_agent'] ?? null, + 'directive' => $report['directive'] ?? null, + 'blocked' => $report['blocked'] ?? null, + 'disposition' => $report['disposition'] ?? null, + 'source_file' => $report['source_file'] ?? null, + 'line' => $report['line'] ?? null, + 'column' => $report['column'] ?? null, + 'sample' => $report['sample'] ?? null, + 'policy' => $report['policy'] ?? null, + 'message' => $report['message'] ?? null, + 'id' => $report['id'] ?? null, + ], + \is_array($body) ? $body : [], + ); + } + + /** + * Whether the report is a CSP violation, of either format. + * + * @param CspReport $report + */ + public static function isViolation(array $report): bool + { + return $report['type'] === self::TYPE_CSP_VIOLATION || isset($report['directive']); + } + + /** + * The file of the report with its line and column, as `file:line:column`. + * + * @param CspReport $report + */ + public static function source(array $report): string + { + $file = $report['source_file'] ?? ''; + if ($file === '') { + return ''; + } + + $position = \implode(':', \array_filter([$report['line'] ?? 0, $report['column'] ?? 0])); + + return $position === '' ? $file : "$file:$position"; + } + + /** + * @return CspReport + */ + private static function cspReport(mixed $data): array + { + /** @var mixed $report */ + $report = \is_array($data) ? $data['csp-report'] ?? null : null; + \is_array($report) && $report !== [] && !\array_is_list($report) + or throw new \InvalidArgumentException('Not a csp-report document: no `csp-report` object.'); + + /** @var mixed $directive */ + $directive = $report['effective-directive'] ?? null; + if (!\is_string($directive) || $directive === '') { + /** @var mixed $directive */ + $directive = $report['violated-directive'] ?? null; + } + + return self::make([ + 'type' => self::TYPE_CSP_VIOLATION, + 'url' => $report['document-uri'] ?? null, + 'directive' => $directive, + 'blocked' => $report['blocked-uri'] ?? null, + 'disposition' => $report['disposition'] ?? null, + 'source_file' => $report['source-file'] ?? null, + 'line' => $report['line-number'] ?? null, + 'column' => $report['column-number'] ?? null, + 'sample' => $report['script-sample'] ?? null, + 'policy' => $report['original-policy'] ?? null, + ], $report); + } + + /** + * @return non-empty-list + */ + private static function reports(mixed $data): array + { + \is_array($data) && \array_is_list($data) + or throw new \InvalidArgumentException('Not a reports+json document: no list of reports.'); + $data === [] and throw new \InvalidArgumentException('Not a reports+json document: the list of reports is empty.'); + + $reports = []; + /** @var mixed $item */ + foreach ($data as $item) { + \is_array($item) && !\array_is_list($item) + or throw new \InvalidArgumentException('Not a reports+json document: a report is not an object.'); + + /** @var mixed $body */ + $body = $item['body'] ?? null; + $body = \is_array($body) ? $body : []; + $reports[] = self::make([ + 'type' => $item['type'] ?? null, + 'url' => $item['url'] ?? null, + 'user_agent' => $item['user_agent'] ?? null, + 'directive' => $body['effectiveDirective'] ?? null, + 'blocked' => $body['blockedURL'] ?? null, + 'disposition' => $body['disposition'] ?? null, + 'source_file' => $body['sourceFile'] ?? null, + 'line' => $body['lineNumber'] ?? null, + 'column' => $body['columnNumber'] ?? null, + 'sample' => $body['sample'] ?? null, + 'policy' => $body['originalPolicy'] ?? null, + 'message' => $body['message'] ?? null, + 'id' => $body['id'] ?? null, + ], $body); + } + + return $reports; + } + + /** + * @param array $fields A field of a wrong type counts as empty. + * + * @return CspReport + */ + private static function make(array $fields, array $body): array + { + $report = ['type' => '', 'url' => '']; + /** @var mixed $value */ + foreach ($fields as $name => $value) { + if (\in_array($name, ['line', 'column'], true)) { + $value = \is_int($value) || \is_string($value) && \ctype_digit($value) ? (int) $value : 0; + $value > 0 and $report[$name] = $value; + continue; + } + + $value = \is_string($value) ? $value : ''; + ($value !== '' || isset($report[$name])) and $report[$name] = $value; + } + // An empty body is an object, as the browser sent it + $report['body'] = $body === [] ? new \stdClass() : $body; + + /** @var CspReport */ + return $report; + } +} diff --git a/src/Module/Frontend/EventQuery.php b/src/Module/Frontend/EventQuery.php index 650c7ad4..be46ded8 100644 --- a/src/Module/Frontend/EventQuery.php +++ b/src/Module/Frontend/EventQuery.php @@ -306,7 +306,8 @@ private static function lower(string $text): string /** * What the search finds an event by: the `message` and `channel` of its payload and the keys and values of * its `context` and `extra`, as a Monolog record has them. A Sentry event has a `message` and `extra` too; - * an event without these fields matches no search. + * an event without these fields matches no search. Security reports are found by their type, page, + * directive, blocked resource, file and message. */ private static function searchText(Event $event): string { @@ -316,6 +317,19 @@ private static function searchText(Event $event): string } $parts = []; + if ($event->type === 'csp') { + /** @var mixed $report */ + foreach (\is_array($payload['reports'] ?? null) ? $payload['reports'] : [] as $report) { + foreach (['type', 'url', 'directive', 'blocked', 'source_file', 'message'] as $key) { + /** @var mixed $value */ + $value = \is_array($report) ? $report[$key] ?? null : null; + \is_string($value) and $parts[] = $value; + } + } + + return self::lower(\implode("\n", $parts)); + } + foreach (['message', 'channel'] as $key) { \is_scalar($payload[$key] ?? null) and $parts[] = (string) $payload[$key]; } diff --git a/src/Module/Frontend/Http/StaticFiles.php b/src/Module/Frontend/Http/StaticFiles.php index 480e937d..10b75421 100644 --- a/src/Module/Frontend/Http/StaticFiles.php +++ b/src/Module/Frontend/Http/StaticFiles.php @@ -25,7 +25,7 @@ final class StaticFiles implements Middleware /** * Event types of the UI build: its `/{type}` and `/{type}/{id}` pages. */ - private const UI_EVENT_TYPES = 'var-dump|smtp|sentry|profiler|monolog|inspector|http-dump|ray|sms' + private const UI_EVENT_TYPES = 'var-dump|smtp|sentry|profiler|monolog|inspector|http-dump|ray|sms|csp' . '|sentry-trace|sentry-log|xdebug-trace'; /** diff --git a/src/Server/Application/Module/Modules.php b/src/Server/Application/Module/Modules.php index 57243977..4c34b8cd 100644 --- a/src/Server/Application/Module/Modules.php +++ b/src/Server/Application/Module/Modules.php @@ -24,6 +24,7 @@ final class Modules * * Channels go first: a source module that takes a sender name is then the one reported. * The MCP module goes before the source modules: its token guard answers before any of them keeps a request. + * The CSP reports go after the other sources: they take a POST of their content type on any path. * The HTTP dump goes last: its middleware ends the HTTP pipeline. */ private const LIST = [ @@ -41,6 +42,7 @@ final class Modules \Buggregator\Trap\Module\XDebugTrace\Module::class, \Buggregator\Trap\Module\XDebug\Module::class, \Buggregator\Trap\Module\Tracing\Module::class, + \Buggregator\Trap\Module\Csp\Module::class, \Buggregator\Trap\Module\HttpDump\Module::class, ]; diff --git a/src/Server/Command/Test.php b/src/Server/Command/Test.php index c8d89b6f..399fbc33 100644 --- a/src/Server/Command/Test.php +++ b/src/Server/Command/Test.php @@ -72,6 +72,7 @@ protected function execute( $this->httpDump(); $this->sentry(); $this->openTelemetry(); + $this->csp(); \usleep(100_000); $this->sendContent('logo.png'); @@ -318,6 +319,27 @@ private function openTelemetry(): void }); } + /** + * Security reports of a browser, a request of each format: a CSP violation of `report-uri`, and + * a Reporting API batch of `report-to` with a CSP violation and a deprecation. + */ + private function csp(): void + { + $this->attempt('CSP reports', function (): void { + /** @var mixed $request */ + foreach (self::template('csp.json') as $request) { + /** @var mixed $type */ + $type = \is_object($request) ? $request->content_type ?? null : null; + \is_string($type) or throw new \RuntimeException('A CSP request must have a content type and a body.'); + \assert(\is_object($request)); + $this->http('POST', '/csp', [ + 'Content-Type' => $type, + 'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + ], self::json($request->body ?? null)); + } + }); + } + private function dump(): void { $_SERVER['VAR_DUMPER_FORMAT'] = 'server'; diff --git a/tests/Acceptance/ServerTest.php b/tests/Acceptance/ServerTest.php index 79d7cd58..4d578ecf 100644 --- a/tests/Acceptance/ServerTest.php +++ b/tests/Acceptance/ServerTest.php @@ -820,7 +820,7 @@ public function testMailsOfTestCommandAreCaptured(): void /** * One run of `trap test` gives every page of the web UI data: each event type of the feed, the Sentry - * traces, logs, metrics and user feedback, and a second project. + * traces, logs, metrics and user feedback, the CSP reports of both formats, and a second project. */ public function testTestCommandFillsEveryPageOfTheUi(): void { @@ -833,11 +833,14 @@ public function testTestCommandFillsEveryPageOfTheUi(): void $types = TrapProcess::waitFor(function (): ?array { [, , $body] = TrapProcess::http($this->uiPort, 'GET', '/api/events'); $types = \array_unique(\array_column(self::json($body)['data'], 'type')); - return \count($types) >= 8 ? $types : null; + return \count($types) >= 9 ? $types : null; }, 'events of every type in the web UI'); Assert::array($types)->sameElementsAs([ - 'profiler', 'xdebug-trace', 'var-dump', 'smtp', 'monolog', 'ray', 'http-dump', 'sentry', + 'profiler', 'xdebug-trace', 'var-dump', 'smtp', 'monolog', 'ray', 'http-dump', 'sentry', 'csp', ]); + [, , $csp] = TrapProcess::http($this->uiPort, 'GET', '/api/events?type=csp'); + Assert::array(\array_column(\array_column(self::json($csp)['data'], 'payload'), 'format')) + ->sameElementsAs(['csp-report', 'reports+json']); [, , $projects] = TrapProcess::http($this->uiPort, 'GET', '/api/projects'); Assert::same(\array_column(self::json($projects)['data'], 'key'), ['default', 'billing']); diff --git a/tests/Unit/Module/Console/ConsoleSenderTest.php b/tests/Unit/Module/Console/ConsoleSenderTest.php index 90d3e437..a24adb3d 100644 --- a/tests/Unit/Module/Console/ConsoleSenderTest.php +++ b/tests/Unit/Module/Console/ConsoleSenderTest.php @@ -7,6 +7,7 @@ use Buggregator\Trap\Module\Console\ConsoleSender; use Buggregator\Trap\Module\Console\FrameHandler; use Buggregator\Trap\Module\Console\Renderer; +use Buggregator\Trap\Module\Csp\Console\Renderer as CspRenderer; use Buggregator\Trap\Module\HttpDump\Console\Renderer as HttpDumpRenderer; use Buggregator\Trap\Module\Mailer\Console\Renderer as MailerRenderer; use Buggregator\Trap\Module\Monolog\Console\Renderer as MonologRenderer; @@ -44,6 +45,7 @@ public function testModuleRenderersInListOrderThenChannelOnesWithPlainLast(): vo XDebugTraceRenderer::class, TracingRenderer::class, SignalRenderer::class, + CspRenderer::class, HttpDumpRenderer::class, Renderer\Binary::class, Renderer\Plain::class, diff --git a/tests/Unit/Module/Console/RendererSupportTest.php b/tests/Unit/Module/Console/RendererSupportTest.php index 01a42720..3374e830 100644 --- a/tests/Unit/Module/Console/RendererSupportTest.php +++ b/tests/Unit/Module/Console/RendererSupportTest.php @@ -5,6 +5,8 @@ namespace Buggregator\Trap\Tests\Unit\Module\Console; use Buggregator\Trap\Module\Console\Renderer; +use Buggregator\Trap\Module\Csp\Console\Renderer as CspRenderer; +use Buggregator\Trap\Module\Csp\Frame as CspFrame; use Buggregator\Trap\Module\HttpDump\Console\Renderer as HttpDumpRenderer; use Buggregator\Trap\Module\HttpDump\Frame as HttpFrame; use Buggregator\Trap\Module\Mailer\Console\Renderer as MailerRenderer; @@ -49,6 +51,7 @@ public static function renderersDataProvider(): iterable yield 'monolog' => [new MonologRenderer(), ['monolog']]; yield 'smtp' => [new MailerRenderer(), ['smtp']]; yield 'ray' => [new RayRenderer(), ['ray']]; + yield 'csp' => [new CspRenderer(), ['csp']]; yield 'http' => [new HttpDumpRenderer(), ['http']]; yield 'profiler' => [new ProfilerRenderer(), ['profiler']]; yield 'binary' => [new Renderer\Binary(), ['binary']]; @@ -88,6 +91,7 @@ private static function frames(): array 'monolog' => new MonologFrame(['message' => 'hello']), 'smtp' => new MailerFrame(MailerMessage::create(['FROM' => ['']], ['Subject' => 'Hi'])), 'ray' => new RayFrame('a1', []), + 'csp' => new CspFrame('csp-report', [['type' => 'csp-violation', 'url' => '', 'body' => []]]), 'http' => new HttpFrame(new ServerRequest('GET', 'http://localhost/')), 'profiler' => new ProfilerFrame(Payload::new(PayloadType::XHProf, static fn(): Profile => new Profile())), 'binary' => new Frame\Binary(Stream::create('binary')), diff --git a/tests/Unit/Module/Csp/Console/RendererTest.php b/tests/Unit/Module/Csp/Console/RendererTest.php new file mode 100644 index 00000000..4e1150b3 --- /dev/null +++ b/tests/Unit/Module/Csp/Console/RendererTest.php @@ -0,0 +1,53 @@ +render($output, new Frame($format, $reports, 'shop')); + $text = (string) \preg_replace('/ +/', ' ', $output->fetch()); + + Assert::string($text) + ->contains('CSP reports+json shop') + ->contains('# script-src-elem blocked inline') + ->contains('Page: https://shop.test/') + ->contains('Directive: script-src-elem') + ->contains('Disposition: enforce (blocked)') + ->contains('Source: https://shop.test/:121:39') + ->contains('Sample: console.log(1)') + ->contains("# deprecation: 'window.webkitStorageInfo' is deprecated.") + ->contains('ID: PrefixedStorageInfo') + ->contains('Source: https://shop.test/app.js:2:5'); + } + + public function testEscapesMarkupOfReport(): void + { + [$format, $reports] = Report::parse(null, '{"csp-report":{"document-uri":"http://a/x","blocked-uri":"","disposition":"report"}}'); + $output = new BufferedOutput(); + + (new Renderer())->render($output, new Frame($format, $reports)); + + Assert::string($output->fetch()) + ->contains('http://a/x') + ->contains('CSP blocked ') + ->contains('report (Report-Only: not blocked)'); + } +} diff --git a/tests/Unit/Module/Csp/FrameTest.php b/tests/Unit/Module/Csp/FrameTest.php new file mode 100644 index 00000000..7a1a04b4 --- /dev/null +++ b/tests/Unit/Module/Csp/FrameTest.php @@ -0,0 +1,42 @@ +format, Report::FORMAT_REPORTS); + Assert::same($restored->reports, $reports); + Assert::same($restored->project, 'shop'); + Assert::same($restored->type, 'csp'); + } + + #[DataSet(['{}'], 'no fields')] + #[DataSet(['{"format":"json","reports":[{}]}'], 'unknown format')] + #[DataSet(['{"format":"csp-report","reports":[]}'], 'no reports')] + public function testRejectsOtherJson(string $json): void + { + Expect::exception(\InvalidArgumentException::class); + + Frame::fromString($json, new \DateTimeImmutable()); + } +} diff --git a/tests/Unit/Module/Csp/Http/CspTrapTest.php b/tests/Unit/Module/Csp/Http/CspTrapTest.php new file mode 100644 index 00000000..dabb943e --- /dev/null +++ b/tests/Unit/Module/Csp/Http/CspTrapTest.php @@ -0,0 +1,146 @@ + $contentType], $body))->withAttribute('begin_at', $time); + + [$response, $frames] = self::handle($request); + + Assert::same($response->getStatusCode(), 204); + Assert::same((string) $response->getBody(), ''); + Assert::count($frames, 1); + Assert::same($frames[0]->format, $format); + Assert::same($frames[0]->time, $time); + } + + #[DataSet(['GET', '/csp', 'application/csp-report', []], 'GET')] + #[DataSet(['POST', '/api/x', 'application/json', []], 'other JSON elsewhere')] + #[DataSet(['POST', '/cspx', 'application/json', []], 'a path that only starts with csp')] + #[DataSet(['POST', '/csp', 'application/csp-report', ['X-Buggregator-Event' => 'http-dump']], 'marked for HTTP dumps')] + #[DataSet(['POST', '/csp', 'application/csp-report', ['X-Buggregator-Event' => 'sentry']], 'marked for Sentry')] + #[DataSet(['POST', '/csp', 'application/csp-report', ['Authorization' => 'Basic aHR0cC1kdW1wOg==']], 'Basic user http-dump')] + public function testLeavesOtherRequests(string $method, string $path, string $contentType, array $headers): void + { + [$response, $frames] = self::handle(new ServerRequest($method, $path, ['Content-Type' => $contentType] + $headers, ReportTest::CSP_REPORT)); + + Assert::same($response->getStatusCode(), 404); + Assert::same($frames, []); + } + + #[DataSet([['X-Buggregator-Event' => 'CSP']], 'header')] + #[DataSet([['Authorization' => 'Basic Y3NwOg==']], 'Basic user')] + public function testTakesRequestMarkedForCsp(array $headers): void + { + [, $frames] = self::handle(new ServerRequest('POST', '/', ['Content-Type' => 'application/csp-report'] + $headers, ReportTest::CSP_REPORT)); + + Assert::count($frames, 1); + } + + #[DataSet(['/csp', [], null], 'none')] + #[DataSet(['/csp', ['X-Buggregator-Project' => ' shop '], 'shop'], 'header')] + #[DataSet(['/some/report', ['X-Buggregator-Project' => 'shop'], 'shop'], 'header on any path')] + #[DataSet(['/csp/billing', ['X-Buggregator-Project' => 'shop'], 'billing'], 'path over header')] + #[DataSet(['/csp/my%20app/', [], 'my app'], 'decoded path')] + #[DataSet(['/csp', ['Authorization' => 'Basic Y3NwOnNob3A=', 'X-Buggregator-Project' => 'other'], 'shop'], 'Basic password over header')] + #[DataSet(['/csp/billing', ['Authorization' => 'Basic Y3NwOnNob3A='], 'billing'], 'path over Basic password')] + public function testProject(string $path, array $headers, ?string $project): void + { + [, $frames] = self::handle(new ServerRequest('POST', $path, ['Content-Type' => 'application/csp-report'] + $headers, ReportTest::CSP_REPORT)); + + Assert::count($frames, 1); + Assert::same($frames[0]->project, $project); + } + + #[DataSet(['{"x":1}'], 'no report')] + #[DataSet(['[]'], 'empty list')] + #[DataSet(['not json'], 'not JSON')] + public function testRejectsMalformedReport(string $body): void + { + $output = new BufferedOutput(); + + [$response, $frames] = self::handle(new ServerRequest('POST', '/csp', [], $body), new Logger($output)); + + Assert::same($response->getStatusCode(), 400); + Assert::same($frames, []); + Assert::string($output->fetch())->contains('CSP: report rejected with 400'); + } + + public function testRejectsLargeBody(): void + { + $body = '{"csp-report":{"script-sample":"' . \str_repeat('a', CspTrap::MAX_BODY_SIZE) . '"}}'; + + [$response, $frames] = self::handle(new ServerRequest('POST', '/csp', ['Content-Type' => 'application/csp-report'], $body)); + + Assert::same($response->getStatusCode(), 413); + Assert::same($frames, []); + } + + /** + * Chrome sends Reporting API reports to another origin only after a preflight. + */ + public function testAnswersPreflightOfReportPaths(): void + { + $request = new ServerRequest('OPTIONS', '/csp/shop', [ + 'Origin' => 'https://localhost:8443', + 'Access-Control-Request-Method' => 'POST', + 'Access-Control-Request-Headers' => 'content-type', + ]); + + [$response, $frames] = self::handle($request); + [$other] = self::handle(new ServerRequest('OPTIONS', '/api/x')); + + Assert::same($response->getStatusCode(), 204); + Assert::same($response->getHeaderLine('Access-Control-Allow-Origin'), '*'); + Assert::same($response->getHeaderLine('Access-Control-Allow-Methods'), 'POST'); + Assert::same($response->getHeaderLine('Access-Control-Allow-Headers'), 'Content-Type'); + Assert::same($frames, []); + Assert::same($other->getStatusCode(), 404); + } + + /** + * Runs the middleware the way the HTTP pipeline does: in a fiber that suspends with frames. + * + * @return array{ResponseInterface, list} + */ + private static function handle(ServerRequestInterface $request, ?Logger $logger = null): array + { + $trap = new CspTrap($logger); + $frames = []; + $fiber = new \Fiber(static fn(): ResponseInterface => $trap->handle($request, static fn(): Response => new Response(404))); + $got = $fiber->start(); + while (!$fiber->isTerminated()) { + $got instanceof Frame and $frames[] = $got; + $got = $fiber->resume(); + } + + return [$fiber->getReturn(), $frames]; + } +} diff --git a/tests/Unit/Module/Csp/Mcp/CspViewTest.php b/tests/Unit/Module/Csp/Mcp/CspViewTest.php new file mode 100644 index 00000000..e3fd24c3 --- /dev/null +++ b/tests/Unit/Module/Csp/Mcp/CspViewTest.php @@ -0,0 +1,70 @@ +type, 'csp'); + Assert::same($event->projectKey(), 'shop'); + Assert::same( + \json_decode(\json_encode($event, \JSON_THROW_ON_ERROR), true)['payload']['reports'][0]['blocked'] ?? null, + 'https://cdn.evil.test/x.js', + ); + } + + public function testSummaryNamesFirstReportAndPage(): void + { + $view = new CspView(); + + Assert::same( + $view->summary(self::event(ReportTest::CSP_REPORT)), + 'script-src-elem blocked https://cdn.evil.test/x.js on https://shop.test/cart', + ); + Assert::same( + $view->summary(self::event(ReportTest::REPORTS)), + 'script-src-elem blocked inline on https://shop.test/ (+1 more)', + ); + Assert::null($view->summary(new Event('a1', 'monolog', ['message' => 'x'], 1.0))); + } + + public function testFieldsOfAllReports(): void + { + $fields = (new CspView())->fields(self::event(ReportTest::REPORTS)); + + Assert::same($fields, [ + 'report_type' => ['csp-violation', 'deprecation'], + 'directive' => ['script-src-elem'], + 'blocked' => ['inline'], + 'disposition' => ['enforce'], + 'page' => ['https://shop.test/'], + 'source_file' => ['https://shop.test/', 'https://shop.test/app.js'], + ]); + Assert::same(\array_keys((new CspView())->fieldNames()), ['csp']); + } + + private static function event(string $body, ?string $project = null): Event + { + [$format, $reports] = Report::parse(null, $body); + + return (new Mapper())->map(new Frame($format, $reports, $project)); + } +} diff --git a/tests/Unit/Module/Csp/ReportTest.php b/tests/Unit/Module/Csp/ReportTest.php new file mode 100644 index 00000000..20c03d1e --- /dev/null +++ b/tests/Unit/Module/Csp/ReportTest.php @@ -0,0 +1,132 @@ + 'csp-violation', + 'url' => 'https://shop.test/cart', + 'directive' => 'script-src-elem', + 'blocked' => 'https://cdn.evil.test/x.js', + 'disposition' => 'enforce', + 'source_file' => 'https://shop.test/cart', + 'line' => 12, + 'column' => 7, + 'policy' => "default-src 'self'; report-uri /csp", + ]); + Assert::same($reports[0]['body']['status-code'] ?? null, 200); + } + + public function testViolatedDirectiveStandsInForEffectiveOne(): void + { + [, $reports] = Report::parse(null, '{"csp-report":{"document-uri":"http://a/","violated-directive":"img-src","blocked-uri":"data"}}'); + + Assert::same($reports[0]['directive'] ?? null, 'img-src'); + } + + public function testReadsReportingApiBatch(): void + { + [$format, $reports] = Report::parse(Report::FORMAT_REPORTS, self::REPORTS); + + Assert::same($format, Report::FORMAT_REPORTS); + Assert::count($reports, 2); + [$violation, $deprecation] = $reports; + Assert::same($violation['blocked'] ?? null, 'inline'); + Assert::same($violation['sample'] ?? null, 'console.log(1)'); + Assert::same($violation['line'] ?? null, 121); + Assert::same($violation['user_agent'] ?? null, 'Mozilla/5.0 Chrome/131'); + Assert::same($deprecation['type'], 'deprecation'); + Assert::same($deprecation['id'] ?? null, 'PrefixedStorageInfo'); + Assert::same($deprecation['message'] ?? null, "'window.webkitStorageInfo' is deprecated."); + Assert::same($deprecation['source_file'] ?? null, 'https://shop.test/app.js'); + Assert::false(isset($deprecation['directive'])); + } + + #[DataSet([self::CSP_REPORT, Report::FORMAT_CSP], 'object')] + #[DataSet([" \n" . self::REPORTS, Report::FORMAT_REPORTS], 'list')] + public function testGuessesFormatByBody(string $body, string $format): void + { + Assert::same(Report::parse(null, $body)[0], $format); + } + + #[DataSet([Report::FORMAT_CSP, '{"x":1}'], 'no csp-report')] + #[DataSet([Report::FORMAT_CSP, '{"csp-report":[]}'], 'empty csp-report')] + #[DataSet([Report::FORMAT_REPORTS, '[]'], 'empty list')] + #[DataSet([Report::FORMAT_REPORTS, '{"type":"deprecation"}'], 'object')] + #[DataSet([Report::FORMAT_REPORTS, '[1]'], 'not an object')] + #[DataSet([null, 'not json'], 'not json')] + public function testRejectsOtherDocuments(?string $format, string $body): void + { + Expect::exception(\InvalidArgumentException::class); + + Report::parse($format, $body); + } + + public function testEmptyBodyStaysObject(): void + { + [, $reports] = Report::parse(null, '[{"type":"crash","url":"http://a/","body":{}}]'); + + Assert::same(\json_encode($reports[0]), '{"type":"crash","url":"http:\/\/a\/","body":{}}'); + } + + public function testFieldsOfWrongTypesAreLeftOut(): void + { + [, $reports] = Report::parse(null, '[{"type":"csp-violation","url":7,"body":{"lineNumber":"12","columnNumber":-1,"blockedURL":["x"],"statusCode":1e999}}]'); + + $report = $reports[0]; + unset($report['body']); + Assert::same($report, ['type' => 'csp-violation', 'url' => '', 'line' => 12]); + Assert::string(\json_encode($reports, \JSON_THROW_ON_ERROR))->contains('"statusCode":"Infinity"'); + } + + public function testRestoresReport(): void + { + [, $reports] = Report::parse(null, self::REPORTS); + + $restored = \array_map(Report::restore(...), \json_decode(\json_encode($reports, \JSON_THROW_ON_ERROR), true)); + + Assert::same($restored, $reports); + } + + public function testSourceHasLineAndColumn(): void + { + Assert::same(Report::source(['type' => '', 'url' => '', 'source_file' => 'a.js', 'line' => 3, 'column' => 4, 'body' => []]), 'a.js:3:4'); + Assert::same(Report::source(['type' => '', 'url' => '', 'source_file' => 'a.js', 'body' => []]), 'a.js'); + Assert::same(Report::source(['type' => '', 'url' => '', 'line' => 3, 'body' => []]), ''); + } +} diff --git a/tests/Unit/Module/Frontend/EventQueryTest.php b/tests/Unit/Module/Frontend/EventQueryTest.php index bb1ddf97..94163d61 100644 --- a/tests/Unit/Module/Frontend/EventQueryTest.php +++ b/tests/Unit/Module/Frontend/EventQueryTest.php @@ -70,6 +70,19 @@ public function testSearchFoldsTheCaseOfAnyLetter(): void Assert::same(self::uuids(EventQuery::fromQueryString('q=' . \urlencode('ОШИБКА'))->select($events)), ['a']); } + public function testSearchFindsSecurityReportsByTheirFields(): void + { + $events = [new Event('c', 'csp', ['format' => 'reports+json', 'reports' => [ + ['type' => 'csp-violation', 'url' => 'https://shop.test/', 'directive' => 'script-src-elem', 'blocked' => 'https://cdn.test/x.js', 'body' => []], + ['type' => 'deprecation', 'url' => 'https://shop.test/', 'message' => 'Unload is deprecated', 'body' => []], + ]], 1.0)]; + + foreach (['cdn.test', 'SCRIPT-SRC', 'unload', 'deprecation'] as $q) { + Assert::same(self::uuids(EventQuery::fromQueryString('q=' . \urlencode($q))->select($events)), ['c'], $q); + } + Assert::same(self::uuids(EventQuery::fromQueryString('q=nothing')->select($events)), []); + } + public function testWindowCountsFromNow(): void { Assert::null(EventQuery::since(null)); diff --git a/tests/Unit/Module/Frontend/Http/StaticFilesTest.php b/tests/Unit/Module/Frontend/Http/StaticFilesTest.php index e22488a7..1b748877 100644 --- a/tests/Unit/Module/Frontend/Http/StaticFilesTest.php +++ b/tests/Unit/Module/Frontend/Http/StaticFilesTest.php @@ -64,6 +64,8 @@ public function testEarlyHintsPreloadStylesInCorsModeOfTheirTags(): void #[DataSet(['/smtp'])] #[DataSet(['/smtp/0198c2d4-7a54-7b81-9b8e-3cf7c6c3a6b1'])] #[DataSet(['/http-dump/0198c2d4-7a54-7b81-9b8e-3cf7c6c3a6b1'])] + #[DataSet(['/csp'])] + #[DataSet(['/csp/0198c2d4-7a54-7b81-9b8e-3cf7c6c3a6b1'])] #[DataSet(['/sentry/traces/4bf92f3577b34da6a3ce929d0e0e4736'])] #[DataSet(['/profiler/compare'])] #[DataSet(['/settings'])] diff --git a/tests/Unit/Module/Frontend/ServiceTest.php b/tests/Unit/Module/Frontend/ServiceTest.php index 316d8871..33363156 100644 --- a/tests/Unit/Module/Frontend/ServiceTest.php +++ b/tests/Unit/Module/Frontend/ServiceTest.php @@ -220,7 +220,7 @@ public function testSettingsListEventTypesOfTrap(): void Assert::same( self::json($service->settings())['events'], - ['var-dump', 'smtp', 'monolog', 'ray', 'sentry', 'profiler', 'xdebug-trace', 'http-dump'], + ['var-dump', 'smtp', 'monolog', 'ray', 'sentry', 'profiler', 'xdebug-trace', 'csp', 'http-dump'], ); } diff --git a/tests/Unit/Module/Mcp/Tool/EventFilterArgumentsTest.php b/tests/Unit/Module/Mcp/Tool/EventFilterArgumentsTest.php index 9a8141e8..1114f6da 100644 --- a/tests/Unit/Module/Mcp/Tool/EventFilterArgumentsTest.php +++ b/tests/Unit/Module/Mcp/Tool/EventFilterArgumentsTest.php @@ -125,7 +125,7 @@ public function testSchemaListsTheFieldsOfTheModules(): void Assert::same(\array_keys($schema), ['type', 'project', 'from', 'to', 'search', 'regex', 'where']); Assert::string($filters->fieldsHelp()) - ->startsWith('sentry: level, exception, environment, release, transaction, server_name, status; profiler: name, format; var-dump: label, value_type, language, file; monolog: level, channel; ') + ->startsWith('sentry: level, exception, environment, release, transaction, server_name, status; profiler: name, format; csp: report_type, directive, blocked, disposition, page, source_file; var-dump: label, value_type, language, file; monolog: level, channel; ') ->contains('smtp: subject, from, to, cc, bcc') ->contains('http-dump: method, path, host'); Assert::string($schema['where']['description'])->contains($filters->fieldsHelp()); diff --git a/tests/Unit/Module/Mcp/Tool/ListEventsTest.php b/tests/Unit/Module/Mcp/Tool/ListEventsTest.php index b694db0d..35ce119f 100644 --- a/tests/Unit/Module/Mcp/Tool/ListEventsTest.php +++ b/tests/Unit/Module/Mcp/Tool/ListEventsTest.php @@ -217,6 +217,7 @@ public function testSchemaListsKnownTypes(): void 'sentry', 'profiler', 'xdebug-trace', + 'csp', 'http-dump', ]); Assert::same($schema['properties']['limit']['maximum'], ListEvents::MAX_LIMIT); diff --git a/tests/Unit/Server/Application/Module/ModulesTest.php b/tests/Unit/Server/Application/Module/ModulesTest.php index 65f58a1c..65a1600f 100644 --- a/tests/Unit/Server/Application/Module/ModulesTest.php +++ b/tests/Unit/Server/Application/Module/ModulesTest.php @@ -4,6 +4,7 @@ namespace Buggregator\Trap\Tests\Unit\Server\Application\Module; +use Buggregator\Trap\Module\Csp\Http\CspTrap; use Buggregator\Trap\Module\HttpDump\Http\DebugPage; use Buggregator\Trap\Module\HttpDump\Http\Dump; use Buggregator\Trap\Module\Mailer\Traffic\Dispatcher as MailerDispatcher; @@ -122,6 +123,7 @@ public function testServerModulesProvideInOrder(): void SPXTrap::class, TraceTrap::class, OtlpTrap::class, + CspTrap::class, DebugPage::class, Dump::class, ], diff --git a/tests/Unit/Server/Command/TestTest.php b/tests/Unit/Server/Command/TestTest.php index c5bb1ee6..dacb0b83 100644 --- a/tests/Unit/Server/Command/TestTest.php +++ b/tests/Unit/Server/Command/TestTest.php @@ -37,7 +37,7 @@ public static function payloadFiles(): iterable public static function templates(): iterable { - foreach (['monolog', 'ray', 'sentry-checkout', 'sentry-billing', 'otlp-traces', 'otlp-logs', 'otlp-metrics'] as $name) { + foreach (['monolog', 'ray', 'sentry-checkout', 'sentry-billing', 'otlp-traces', 'otlp-logs', 'otlp-metrics', 'csp'] as $name) { yield $name => ["$name.json"]; } } diff --git a/tests/Unit/Server/Proto/FrameTypesTest.php b/tests/Unit/Server/Proto/FrameTypesTest.php index 992f35f8..47bbeb00 100644 --- a/tests/Unit/Server/Proto/FrameTypesTest.php +++ b/tests/Unit/Server/Proto/FrameTypesTest.php @@ -4,6 +4,7 @@ namespace Buggregator\Trap\Tests\Unit\Server\Proto; +use Buggregator\Trap\Module\Csp\Frame as CspFrame; use Buggregator\Trap\Module\HttpDump\Frame as HttpFrame; use Buggregator\Trap\Module\HttpDump\Module as HttpDumpModule; use Buggregator\Trap\Module\Mailer\Frame as MailerFrame; @@ -54,6 +55,7 @@ public static function framesDataProvider(): iterable yield [new ProfilerFrame(Payload::new(PayloadType::XHProf, static fn(): Profile => new Profile())), 'profiler']; yield [new OtlpTraces([]), 'otlp']; yield [new RayFrame('a1', []), 'ray']; + yield [new CspFrame('csp-report', [['type' => 'csp-violation', 'url' => '', 'body' => []]]), 'csp']; } #[DataProvider('framesDataProvider')] @@ -76,6 +78,7 @@ public function testMapsDecodableTypesToFrameClasses(): void Assert::same($types->classOf('profiler'), ProfilerFrame::class); Assert::same($types->classOf('otlp'), TracingFrame::class); Assert::same($types->classOf('ray'), RayFrame::class); + Assert::same($types->classOf('csp'), CspFrame::class); } public function testDoesNotDecodeBinaryFrames(): void diff --git a/tools/structarmed/structarmed.php b/tools/structarmed/structarmed.php index a99a3c85..d7377615 100644 --- a/tools/structarmed/structarmed.php +++ b/tools/structarmed/structarmed.php @@ -5,7 +5,7 @@ use Boundwize\StructArmed\Architecture; $root = \dirname(__DIR__, 2); -$sources = ['HttpDump', 'Mailer', 'Monolog', 'Profiler', 'Ray', 'Sentry', 'Tracing', 'VarDumper', 'XDebug', 'XDebugTrace']; +$sources = ['Csp', 'HttpDump', 'Mailer', 'Monolog', 'Profiler', 'Ray', 'Sentry', 'Tracing', 'VarDumper', 'XDebug', 'XDebugTrace']; $channels = ['Console', 'Files', 'Frontend', 'Mcp', 'Remote']; $architecture = Architecture::define() @@ -39,6 +39,7 @@ // The single place that names the module manifests: the module list. ->skipClassViolation('Buggregator\Trap\Server\Application\Module\Modules', [ 'Buggregator\Trap\Module\Console\Module', + 'Buggregator\Trap\Module\Csp\Module', 'Buggregator\Trap\Module\Files\Module', 'Buggregator\Trap\Module\Frontend\Module', 'Buggregator\Trap\Module\HttpDump\Module', From 2a9060df726259ff8ed83ee1cf5d868ab33b9c6d Mon Sep 17 00:00:00 2001 From: roxblnfk Date: Mon, 23 Nov 2026 17:48:06 +0400 Subject: [PATCH 2/2] fix(csp): take a request marked `csp` on any path and with any content type fix(csp): escape the project in the console header feat(csp): show the failure of `network-error` and the reason of `crash` reports docs(csp): name the project of browser reports in the path; Network Error Logging As buggregator/server does, `X-Buggregator-Event: csp` or the Basic user `csp` marks a report whatever its path and type; the header goes before the Basic user. A project with markup, such as `/csp/%3Cerror%3Ered`, made the console print nothing. A browser sends no userinfo credentials and adds no headers to a report, so the docs and the skill name the project in `/csp/{project}` and leave Basic and `X-Buggregator-Project` to proxies and other clients. Assisted-By: Claude Opus 5.5 --- docs/csp.md | 20 ++++++++- docs/mcp.md | 1 + docs/web-ui.md | 4 +- skills/trap/references/csp.md | 13 ++++-- src/Module/Csp/Console/Renderer.php | 45 ++++++++++++++++++- src/Module/Csp/Http/CspTrap.php | 20 ++++++--- .../Unit/Module/Csp/Console/RendererTest.php | 34 ++++++++++++++ tests/Unit/Module/Csp/Http/CspTrapTest.php | 14 ++++-- 8 files changed, 131 insertions(+), 20 deletions(-) diff --git a/docs/csp.md b/docs/csp.md index 21d0536d..3bfe89bd 100644 --- a/docs/csp.md +++ b/docs/csp.md @@ -21,16 +21,21 @@ Trap takes a report from a `POST`: - with the `application/csp-report` content type, of the `report-uri` directive, to any path; - with the `application/reports+json` content type, of the `report-to` directive, to any path; - to `/csp` or `/csp/{project}` with any content type: a JSON list is read as `reports+json`, an object as - `csp-report`. + `csp-report`; +- marked `csp` with the `X-Buggregator-Event` header or the user of Basic authorization, to any path with any + content type. So an existing report URL of your application works too when its host and port point at Trap. A request marked for another kind of event, with the `X-Buggregator-Event` header or the user of Basic authorization, is left to it. The project of the reports is the `{project}` of the path, else the password of the `csp` user of Basic authorization (`http://csp:my-app@127.0.0.1:8000/`), else the `X-Buggregator-Project` header, else `default`. +A browser sends no credentials from the userinfo of a report URL and adds no headers of yours, so for browsers the +project works only as `/csp/{project}`. Basic authorization and the header are for a proxy or another client that +forwards the reports. Trap answers a report with `204` and an empty body, a body that is not a report with `400`, and a body larger than -1 MiB with `413`. An `OPTIONS` request to `/csp` or `/csp/{project}` gets a CORS preflight answer for any origin: +1 MiB with `413`. Any `OPTIONS` request to `/csp` or `/csp/...` gets a CORS preflight answer for any origin: Chrome sends Reporting API reports to another origin only after one. ## Set up the policy @@ -65,6 +70,17 @@ if (getenv('APP_ENV') === 'dev') { - The browser batches the reports and sends them with a delay of up to a minute. Keep the page open meanwhile. - Send the reports of another origin to `/csp` or `/csp/{project}`: only these paths answer the preflight. +`network-error` reports come from Network Error Logging, which a `NEL` header turns on. It names a group of the +older `Report-To` header: Chrome takes the endpoints of Network Error Logging from it, not from `Reporting-Endpoints`. + +```php +header('Report-To: {"group": "trap", "max_age": 3600, "endpoints": [{"url": "https://127.0.0.1:8000/csp/my-app"}]}'); +header('NEL: {"report_to": "trap", "max_age": 3600, "failure_fraction": 1.0}'); +``` + +The console and the MCP text show the failure of a `network-error` report (its `type`, such as `tcp.refused`), the +phase, the HTTP status, the elapsed time and the server IP, and the reason of a `crash` report. + ### Laravel [spatie/laravel-csp](https://github.com/spatie/laravel-csp) adds `report-uri` from `report_uri` of diff --git a/docs/mcp.md b/docs/mcp.md index cd8d2af0..65fdd334 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -351,6 +351,7 @@ reports. The summary is the first report and its page, as `script-src-elem block https://localhost:8080/checkout (+1 more)`. `get_event` gives a block per report: the title, then the report type, the page, the directive, what was blocked, the disposition (`enforce`, blocked; `report`, Report-Only, not blocked), the source file with its line and column, the code sample, the message and ID of a report of another type, the +failure, phase, status, elapsed time and server IP of a `network-error` report, the reason of a `crash`, the policy and the user agent. A field of the report the browser left empty is left out. - The CSP violations of the last 5 minutes: `{"type": "csp", "from": "5m", "where": {"report_type": "csp-violation"}, diff --git a/docs/web-ui.md b/docs/web-ui.md index f694a65e..aafcff5b 100644 --- a/docs/web-ui.md +++ b/docs/web-ui.md @@ -31,8 +31,8 @@ On a shared port the UI takes only its own requests, and the others stay [HTTP d such endpoint. Open the UI from Trap itself: it sends no CORS headers, so a frontend served from another origin, such as a dev -server of buggregator/frontend, can't call its API. An `OPTIONS` request is an HTTP dump like any other, but the -preflight of a [CSP report](csp.md) to `/csp`. +server of buggregator/frontend, can't call its API. An `OPTIONS` request is an HTTP dump like any other, but one to +`/csp` or `/csp/...`: it gets the CORS preflight answer [CSP reports](csp.md) need. The UI asks for no password or token, the [MCP token](mcp.md#security) included: anyone who reaches its port sees the caught events. Trap warns at startup when the port listens on a host other than a loopback one. diff --git a/skills/trap/references/csp.md b/skills/trap/references/csp.md index feba0394..901e76a3 100644 --- a/skills/trap/references/csp.md +++ b/skills/trap/references/csp.md @@ -33,9 +33,11 @@ header. The full reference: ` of `/csp/`, else - the password of the Basic user `csp`, else `X-Buggregator-Project`, else `default`. A request with - `X-Buggregator-Event` or a Basic user of another type goes to that module. + report URL works when its host and port point at Trap. So is one marked `X-Buggregator-Event: csp` or with the + Basic user `csp`, whatever its path and type; one marked for another type goes to that module. +- Name the project in the path, `/csp/`: a browser sends no userinfo credentials and adds no headers to a + report. The password of the Basic user `csp`, then `X-Buggregator-Project`, name it for a proxy or another client + that forwards reports; without any, the project is `default`. - `report-to` with `Reporting-Endpoints` (`reports+json`) is slower and stricter: Chrome sends it only from an HTTPS page to an `https://` endpoint the browser trusts (Trap takes TLS on the same port, see [server.md](server.md#tls)), batches with a delay of up to a minute, and needs the endpoint on `/csp` or @@ -44,4 +46,7 @@ header. The full reference: format, ...($frame->project === null ? [] : ['cyan' => $frame->project])); + Common::renderHeader1( + $output, + 'CSP', + $frame->format, + ...($frame->project === null ? [] : ['cyan' => OutputFormatter::escape($frame->project)]), + ); Common::renderMetadata($output, ['Time' => $frame->time]); foreach ($frame->reports as $report) { @@ -61,6 +68,39 @@ public function render(OutputInterface $output, Frame $frame): void } } + /** + * What the body of a report of a type without fields of its own tells: the failure of a `network-error` + * report of Network Error Logging, the reason of a `crash`. + * + * @param CspReport $report + * + * @return array Label => value. + */ + private static function bodyFacts(array $report): array + { + $body = (array) $report['body']; + $text = static function (string $key) use ($body): string { + /** @var mixed $value */ + $value = $body[$key] ?? null; + + return \is_string($value) || \is_int($value) || \is_float($value) ? (string) $value : ''; + }; + + $facts = match ($report['type']) { + 'network-error' => [ + 'Error' => $text('type'), + 'Phase' => $text('phase'), + 'Status' => $text('status_code') === '0' ? '' : $text('status_code'), + 'Elapsed' => $text('elapsed_time') === '' ? '' : $text('elapsed_time') . ' ms', + 'Server IP' => $text('server_ip'), + ], + 'crash' => ['Reason' => $text('reason')], + default => [], + }; + + return \array_filter($facts, static fn(string $value): bool => $value !== ''); + } + /** * @param CspReport $report */ @@ -83,6 +123,7 @@ private static function renderReport(OutputInterface $output, array $report): vo 'Sample' => $report['sample'] ?? '', 'Message' => $report['message'] ?? '', 'ID' => $report['id'] ?? '', + ...self::bodyFacts($report), 'Policy' => $report['policy'] ?? '', 'User agent' => $report['user_agent'] ?? '', ]; diff --git a/src/Module/Csp/Http/CspTrap.php b/src/Module/Csp/Http/CspTrap.php index 10656bcb..0a383ec8 100644 --- a/src/Module/Csp/Http/CspTrap.php +++ b/src/Module/Csp/Http/CspTrap.php @@ -16,8 +16,8 @@ * Receives browser security reports, as buggregator/server does: a POST to any path with the * `application/csp-report` or `application/reports+json` content type, or a POST to `/csp` or `/csp/{project}`. * - * A request marked for another module, with `X-Buggregator-Event` or the user of Basic authorization, is left - * to it. The project is the `{project}` of the path, else the password of the Basic user `csp`, else + * A request marked with `X-Buggregator-Event` or the user of Basic authorization is taken when marked `csp`, + * whatever its path and content type, and left to the other module otherwise. The project is the `{project}` of the path, else the password of the Basic user `csp`, else * the `X-Buggregator-Project` header. * * A report is answered with 204: browsers read nothing from the answer. An `OPTIONS` preflight to `/csp` @@ -45,7 +45,11 @@ public function handle(ServerRequestInterface $request, callable $next): Respons } $format = Report::formatOf($request->getHeaderLine('Content-Type')); - if ($request->getMethod() !== 'POST' || self::markedForOther($request) || $format === null && !$ownPath) { + $marked = self::markedType($request); + if ($request->getMethod() !== 'POST' + || $marked !== '' && $marked !== Frame::TYPE + || $marked === '' && $format === null && !$ownPath + ) { return $next($request); } @@ -86,12 +90,16 @@ private static function preflight(): ResponseInterface ]); } - private static function markedForOther(ServerRequestInterface $request): bool + /** + * The event type the client marked the request with: `X-Buggregator-Event`, else the user of Basic authorization. + * + * @return string Empty for an unmarked request. + */ + private static function markedType(ServerRequestInterface $request): string { $event = \strtolower(\trim($request->getHeaderLine('X-Buggregator-Event'))); - $user = self::basicAuth($request)[0]; - return $event !== '' && $event !== Frame::TYPE || $user !== '' && $user !== Frame::TYPE; + return $event === '' ? self::basicAuth($request)[0] : $event; } /** diff --git a/tests/Unit/Module/Csp/Console/RendererTest.php b/tests/Unit/Module/Csp/Console/RendererTest.php index 4e1150b3..607ccee0 100644 --- a/tests/Unit/Module/Csp/Console/RendererTest.php +++ b/tests/Unit/Module/Csp/Console/RendererTest.php @@ -38,6 +38,40 @@ public function testRendersBlockPerReport(): void ->contains('Source: https://shop.test/app.js:2:5'); } + /** + * An unclosed tag in the project, as `/csp/%3Cerror%3Ered` gives, swallowed the whole output. + */ + public function testEscapesMarkupOfProject(): void + { + [$format, $reports] = Report::parse(null, ReportTest::CSP_REPORT); + $output = new BufferedOutput(); + + (new Renderer())->render($output, new Frame($format, $reports, 'red')); + + Assert::string($output->fetch()) + ->contains('red') + ->contains('script-src-elem blocked https://cdn.evil.test/x.js'); + } + + public function testShowsBodyOfNetworkErrorAndCrash(): void + { + [$format, $reports] = Report::parse(null, '[{"type":"network-error","url":"https://shop.test/","body":{"elapsed_time":48,"method":"GET","phase":"connection","protocol":"http/1.1","referrer":"","sampling_fraction":1,"server_ip":"203.0.113.7","status_code":0,"type":"tcp.refused"}},{"type":"crash","url":"https://shop.test/","body":{"reason":"oom"}}]'); + $output = new BufferedOutput(); + + (new Renderer())->render($output, new Frame($format, $reports)); + $text = (string) \preg_replace('/ +/', ' ', $output->fetch()); + + Assert::string($text) + ->contains('# network-error: tcp.refused') + ->contains('Error: tcp.refused') + ->contains('Phase: connection') + ->contains('Elapsed: 48 ms') + ->contains('Server IP: 203.0.113.7') + ->notContains('Status:') + ->contains('# crash: oom') + ->contains('Reason: oom'); + } + public function testEscapesMarkupOfReport(): void { [$format, $reports] = Report::parse(null, '{"csp-report":{"document-uri":"http://a/x","blocked-uri":"","disposition":"report"}}'); diff --git a/tests/Unit/Module/Csp/Http/CspTrapTest.php b/tests/Unit/Module/Csp/Http/CspTrapTest.php index dabb943e..3b742508 100644 --- a/tests/Unit/Module/Csp/Http/CspTrapTest.php +++ b/tests/Unit/Module/Csp/Http/CspTrapTest.php @@ -55,12 +55,18 @@ public function testLeavesOtherRequests(string $method, string $path, string $co Assert::same($frames, []); } - #[DataSet([['X-Buggregator-Event' => 'CSP']], 'header')] - #[DataSet([['Authorization' => 'Basic Y3NwOg==']], 'Basic user')] - public function testTakesRequestMarkedForCsp(array $headers): void + #[DataSet([['X-Buggregator-Event' => 'CSP'], 'application/csp-report'], 'header')] + #[DataSet([['Authorization' => 'Basic Y3NwOg=='], 'application/csp-report'], 'Basic user')] + #[DataSet([['X-Buggregator-Event' => 'csp'], 'application/json'], 'header, another type')] + #[DataSet([['Authorization' => 'Basic Y3NwOnNob3A='], ''], 'Basic user, no type')] + #[DataSet([['X-Buggregator-Event' => 'csp', 'Authorization' => 'Basic dXNlcjpzM2NyM3Q='], 'text/plain'], 'header over a Basic user')] + public function testTakesRequestMarkedForCspOnAnyPath(array $headers, string $contentType): void { - [, $frames] = self::handle(new ServerRequest('POST', '/', ['Content-Type' => 'application/csp-report'] + $headers, ReportTest::CSP_REPORT)); + $request = new ServerRequest('POST', '/other', ['Content-Type' => $contentType] + $headers, ReportTest::CSP_REPORT); + [$response, $frames] = self::handle($request); + + Assert::same($response->getStatusCode(), 204); Assert::count($frames, 1); }