Skip to content

fix(symfony): emit a csp nonce on the swagger ui scripts#8310

Open
soyuka wants to merge 1 commit into
api-platform:4.3from
soyuka:fix/swagger-csp-nonce-8142-impl
Open

fix(symfony): emit a csp nonce on the swagger ui scripts#8310
soyuka wants to merge 1 commit into
api-platform:4.3from
soyuka:fix/swagger-csp-nonce-8142-impl

Conversation

@soyuka

@soyuka soyuka commented Jun 16, 2026

Copy link
Copy Markdown
Member

Summary

Under a Content Security Policy such as script-src 'self' 'strict-dynamic', the bundled SwaggerUI <script> tags were blocked because they carried no nonce. They now receive one, reusing existing mechanisms with no new config key:

  • a _csp_nonce request attribute (set by a proxy/middleware) takes precedence;
  • otherwise the nelmio csp_nonce('script') Twig function is used when available;
  • absent both, output is unchanged (no nonce attribute) so plain installs are unaffected.

The csp_nonce() call lives in an include()'d child template (csp-nonce.html.twig) because a literal csp_nonce() in the main template would throw a Twig SyntaxError at parse time when the function is not registered — a runtime {% if %} guard does not prevent parse-time failure.

Reproduction

Visiting /api with a strict CSP blocked the SwaggerUI scripts (no nonce emitted).

Test plan

  • New SwaggerUiCspNonceTest (4 cases): request-attribute nonce, csp_nonce() nonce, request-attr precedence over the function, and no-mechanism → no nonce attribute.
  • DocumentationActionTest regression green (9/9).
  • PHPStan + php-cs-fixer clean on changed files.

Fixes #8142

Under a CSP like "script-src 'self' 'strict-dynamic'" the bundled SwaggerUI
scripts were blocked because they carried no nonce. Emit one, reusing existing
mechanisms with no new config key: a `_csp_nonce` request attribute takes
precedence, otherwise the nelmio `csp_nonce('script')` Twig function is used
when available; absent both, output is unchanged.

The csp_nonce() call lives in an included child template so Twig does not fail
at parse time when the function is not registered.

Fixes api-platform#8142
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant