Search by

mulertech / csp-bundle

mulertech

Symfony bundle for Content Security Policy (CSP) header management with nonce support

Package info

github.com/mulertech/csp-bundle

Type:symfony-bundle

pkg:composer/mulertech/csp-bundle

Statistics

Installs: 525

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v3.2.0 2026-09-17 15:59 UTC

This package is auto-updated.

Last update: 2026-09-17 16:01:56 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub PHPStan Action Status Total Downloads Test Coverage

Symfony bundle for Content Security Policy (CSP) header management with named nonce support.

Installation

composer require mulertech/csp-bundle

The package is a symfony-bundle, so Flex generates a recipe for it and registers it in config/bundles.php on its own. Without Flex, add the line by hand:

return [
    // ...
    MulerTech\CspBundle\MulerTechCspBundle::class => ['all' => true],
];

Without that line the package sits in vendor/ doing nothing: no Content-Security-Policy header on responses, and csp_nonce() raises Unknown "csp_nonce" function in Twig.

Configuration

The bundle ships with secure defaults for every directive and works with no configuration file at all. Create config/packages/mulertech_csp.yaml to override what differs from those defaults:

mulertech_csp:
    directives:
        img-src:
            - "'self'"
            - "data:"
            - "https://cdn.example.com"

Full reference

Here is the complete list of available options with their default values:

mulertech_csp:
    enabled: true                    # true by default
    report_only: false               # false by default
    always_add: []                   # Origins added to ALL directives
    report:
        url: ~                       # External URL for report-uri/report-to
        route: ~                     # Symfony route name (alternative to url)
        route_params: []             # Route parameters
        chance: 100                  # 0-100, % of requests with reporting
        markers: ['report-uri', 'report-to']  # Which markers the policy advertises
    report_only_directives: []       # Candidate policy observed next to the enforced one
    directives:                      # Only override what you need
        default-src:
            - "'self'"
        script-src:
            - "'self'"
            - "nonce(main)"
        style-src:
            - "'self'"
            - "nonce(main)"
        img-src:
            - "'self'"
            - "data:"
        font-src:
            - "'self'"
        connect-src:
            - "'self'"
        media-src:
            - "'self'"
        object-src:
            - "'none'"
        frame-src:
            - "'none'"
        frame-ancestors:
            - "'none'"
        base-uri:
            - "'none'"
        form-action:
            - "'self'"
        upgrade-insecure-requests: true

Default directives

Directive Default
default-src 'self'
script-src 'self' + nonce(main)
style-src 'self' + nonce(main)
img-src 'self' data:
font-src 'self'
connect-src 'self'
media-src 'self'
object-src 'none'
frame-src 'none'
frame-ancestors 'none'
base-uri 'none'
form-action 'self'
upgrade-insecure-requests true, dropped on a local development origin (see below)

Responses that are not documents

The whole policy is sent on responses the browser renders as one of your documents, text/html and application/xhtml+xml, and on responses declaring no type at all, which the framework settles to HTML.

Everything else, an image, a PDF, a sitemap, a feed, gets a reduced policy holding frame-ancestors and sandbox alone, and no header at all when neither is configured. Opened directly, those resources are displayed inside a document the browser builds itself and styles with its own inline stylesheet, and, for an image, its own style attribute. The whole policy governs that generated document: it blocks the viewer's own styling and, where reporting is on, reports a violation on style-src-elem or style-src-attr that nothing in the application can act on. What is kept is what still describes the resource rather than the viewer around it.

A listener replacing the policy through BuildCspHeaderEvent states what it wants sent, and is applied whatever the response carries.

Local development over HTTP

upgrade-insecure-requests is left out when the page is served over plain HTTP to a loopback host: localhost, any *.localhost name, 127.0.0.0/8 or ::1. Nothing answers over HTTPS on such a development server, and Safari applies the directive to loopback hosts, unlike Chrome and Firefox: every stylesheet, script and image is requested over HTTPS and the page renders unstyled, in Safari only. The rest of the policy is sent unchanged.

The exemption reads the host, never the scheme alone, so a production site keeps the directive:

  • a site served over plain HTTP under its public name keeps it, since its visitors never reach it under a loopback name;
  • a site behind a TLS-terminating reverse proxy that is not listed in trusted_proxies keeps it as well, although the framework sees such a request as plain HTTP.

A development server reached under another name, app.test or a LAN address, is not recognised. Drop the directive for that environment only:

when@dev:
    mulertech_csp:
        directives:
            upgrade-insecure-requests: false

A policy set through BuildCspHeaderEvent is sent as the listener wrote it.

Serving a page under a nonce policy

A nonce in style-src makes the browser ignore 'unsafe-inline' entirely: the two never cohabit. Three things stop working, all of them silently, with a 200 response and a page that still renders.

A style attribute carries neither a nonce nor a usable hash. It is rewritten, not worked around. A fixed value becomes a class. A value that comes from data is better removed altogether: a choice among a closed palette gives a class the template can write, and the problem disappears. When a computed value is unavoidable, it goes into a <style nonce="…"> block with a selector by id — with one exception below.

An inline event handler (onclick, onsubmit) needs 'unsafe-inline' in script-src, which the nonce cancels. It never runs, so a delete button does nothing, or a confirmation disappears and the deletion goes through unannounced. It moves into a module served from 'self', asked for by a data- attribute.

A <style> block in an application driven by Turbo. Turbo copies the <style> elements of the page it fetches into the current document as they are, while it re-nonces <script> elements from <meta name="csp-nonce">. The block therefore arrives carrying the nonce of its own response, which the displayed document's policy refuses. The failure appears only when reaching the page through a link, never on a reload, which makes it easy to miss. Under Turbo, use the CSSOM instead: a style written by script goes through no nonce check at all.

A library that injects its own inline block reads its nonce where it expects to: Turbo, for the stylesheet of its progress bar, reads <meta name="csp-nonce">. Carry the value in the element's nonce attribute rather than in content: the browser hides a nonce attribute from the DOM while leaving it readable through the .nonce property, which Turbo queries first, whereas content leaves the value in plain sight for any script.

Named nonces

Use nonce(handle) syntax in directives to create named nonces:

mulertech_csp:
    directives:
        script-src:
            - "'self'"
            - "nonce(main)"           # For your main scripts
            - "nonce(analytics)"      # For analytics scripts

Each named nonce generates a unique 256-bit (32 bytes) cryptographically secure value, and every request gets fresh ones. Persistent runtimes (FrankenPHP worker mode, RoadRunner, Swoole) keep services alive across requests, so the generator is tagged kernel.reset: a nonce reused from one page to the next would be readable by an attacker before the injection.

always_add

Add origins to all directives automatically (except those set to 'none'):

mulertech_csp:
    always_add:
        - "https://cdn.example.com"
    directives:
        default-src:
            - "'self'"
        object-src:
            - "'none'"               # always_add is NOT merged here

Violation reporting

Report CSP violations to an external endpoint:

mulertech_csp:
    report:
        url: "https://report.example.com/csp"
        chance: 50                    # Only 50% of requests

Or use a Symfony route, resolved to an absolute URL:

mulertech_csp:
    report:
        route: "app_csp_report"
        route_params: {}

Both forms emit the same three markers: report-uri and report-to csp-endpoint inside the policy, plus a Reporting-Endpoints response header defining the csp-endpoint group. report-uri is deprecated but still the only form some browsers honour, hence the pair.

Choosing the markers

mulertech_csp:
    report:
        route: "app_csp_report"
        markers: ['report-uri']

A policy carrying report-to makes every browser that implements the Reporting API ignore report-uri entirely and queue its reports for out-of-band, batched delivery. That delivery is deferred, and browsers are free to drop it: a violation shown in the console can reach the endpoint minutes later, or never. Dropping report-to restores an immediate POST that every browser performs, which is what a migration needs to measure anything at all.

Keep both when reports are a background signal, keep report-uri alone when you need the data now. Reporting-Endpoints is only sent when report-to is among the markers, since it exists to define the group that marker names.

Collecting violations

Collection is an instrument of migration. It turns a guess about what a stricter policy would break into an inventory measured on real traffic, which is what the candidate policy below is for, and it is worth branching for the duration of a tightening.

It is not permanent monitoring. On a public site, the steady-state volume is what the visitors' own browsers inject into the page: extensions, userscript managers, in-app browsers. Those arrive as inline, eval or blob against your page's URL, they are indistinguishable from a block of yours served without a nonce, and no change on your side addresses them. The violation you can act on comes from a template serving an inline block without a nonce, and that one fires on every view of the page: a functional test asserting every inline <script> and <style> carries a nonce catches it on the branch, before a visitor meets it. Unbranch the collector once the policy is enforced and stable.

The bundle ships a collector that reads both wire formats and hands each violation to the application. Declare the route yourself:

# config/routes/mulertech_csp.yaml
mulertech_csp_report:
    path: /csp-report
    controller: MulerTech\CspBundle\Controller\CspReportController
    methods: [POST]

The bundle declares no route on its own: the endpoint is public and unauthenticated by nature, so opening it stays an explicit gesture of the application, which is also where rate limiting belongs.

Then listen to the violations and decide where they go:

use MulerTech\CspBundle\Event\CspViolationReportedEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener(event: CspViolationReportedEvent::NAME)]
class CspViolationListener
{
    public function __invoke(CspViolationReportedEvent $event): void
    {
        $report = $event->getReport();

        $this->logger->warning('CSP violation', [
            'signature' => $report->signature(),
            'directive' => $report->effectiveDirective,
            'blocked' => $report->blockedOrigin(),
            'document' => $report->documentPath(),
            'enforced' => $report->isEnforced(),
        ]);
    }
}

What the collector settles before dispatching:

  • the legacy application/csp-report object and the Reporting API list are normalised into one CspViolationReport, since a policy advertising both markers receives the same violation twice;
  • violations injected by browser extensions (chrome-extension:, moz-extension: and their kin) are dropped, as they belong to the visitor's browser and would bury the real signal, and so are those a userscript manager reports under the user-script source file;
  • a body over 64 KB answers 413, a payload that is not JSON answers 400, anything else answers 204.

CspViolationReport::signature() identifies a violation by directive, document path and blocked origin. Line and column numbers are left out on purpose: they drift with every edit of the page, and keying on them would announce the same violation as new every time. Deduplicate on the signature to notify once per distinct violation instead of once per page view.

The report carries originalPolicy as the browser sent it, which is long: disposition is the field that tells an enforced block from a candidate observation.

Report-only mode

Test your CSP policy without enforcing it:

mulertech_csp:
    report_only: true

This sets the Content-Security-Policy-Report-Only header instead of Content-Security-Policy.

Candidate policy

Observe a stricter policy on real traffic while the current one keeps protecting the site:

mulertech_csp:
    directives:
        style-src:
            - "'self'"
            - "'unsafe-inline'"
    report_only_directives:
        style-src:
            - "'self'"
            - "nonce(main)"
    report:
        route: "app_csp_report"

The response then carries two policies: Content-Security-Policy with the enforced one, and Content-Security-Policy-Report-Only with the candidate. Nothing new is blocked, and the browser reports everything the candidate would have blocked, so a policy is tightened on measurements instead of guesswork.

report_only_directives is a diff of the enforced policy rather than a policy of its own: every directive it does not mention is inherited, so the two differ only where the migration is happening. Both share the same nonces and the same endpoint, and a request sampled in by chance is sampled in for both, so the two sets of reports are always comparable.

Read disposition on the received reports to tell them apart: enforce means the resource is blocked right now, report means it would be blocked once the candidate is enforced.

Since report_only: true already sends the whole policy as report-only, it leaves nothing to compare against: combining it with report_only_directives raises a configuration error when the container compiles.

A listener that replaces the policy wholesale through BuildCspHeaderEvent leaves no configured policy to diff against, so the candidate stands down on those responses.

Directives the specification ignores in a report-only delivery, namely upgrade-insecure-requests, sandbox and block-all-mixed-content, are dropped from the candidate, and from the whole policy under report_only: true. They would change nothing there and would earn a console warning on every page load.

Usage

In Twig templates

Use the csp_nonce('handle') function with a named handle:

<script nonce="{{ csp_nonce('main') }}">
    // Your inline JavaScript
</script>

<script nonce="{{ csp_nonce('analytics') }}">
    // Analytics script
</script>

Dynamic CSP customization

Listen to the BuildCspHeaderEvent to customize CSP per-request:

use MulerTech\CspBundle\Event\BuildCspHeaderEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener(event: BuildCspHeaderEvent::NAME)]
class CspListener
{
    public function __invoke(BuildCspHeaderEvent $event): void
    {
        if ($event->getRequest()->getPathInfo() === '/admin') {
            $event->setHeaderValue("default-src 'self'; script-src 'self'");
        }
    }
}

Inject the nonce generator

use MulerTech\CspBundle\CspNonceGenerator;

class MyService
{
    public function __construct(
        private readonly CspNonceGenerator $nonceGenerator,
    ) {}

    public function getMainNonce(): string
    {
        return $this->nonceGenerator->getNonce('main');
    }
}

Upgrading from v2.x

Breaking changes

  1. style-src no longer allows inline styles
# v2.x
style-src 'self' 'unsafe-inline'

# v3.0
style-src 'self' 'nonce-...'

A policy that allows any inline style lets an injection read form values through attribute selectors and cover the page with its own interface, which is most of what a script would have done. The two forms never cohabit: a nonce makes browsers ignore 'unsafe-inline' entirely.

Every <style> element served to a browser now needs nonce="{{ csp_nonce('main') }}", and every style="..." attribute stops being applied, silently, with no server-side error. An attribute carries neither a nonce nor a usable hash, so it has to be rewritten as a class or as a rule in a nonced block.

Measure before you switch: keep the old policy enforced and put the new one under report_only_directives, then read the violations for as long as it takes to see the whole site. An application that genuinely needs inline styles opts back in explicitly:

mulertech_csp:
    directives:
        style-src:
            - "'self'"
            - "'unsafe-inline'"
  1. base-uri is 'none'

An injected <base> rewrites how every relative URL on the page resolves. Applications using a <base> tag set base-uri: ["'self'"] back.

Upgrading from v1.x

Breaking changes

  1. Directives format: Changed from scalar strings to arrays of sources
# v1.x
mulertech_csp:
    directives:
        script-src: "'self' 'nonce-{nonce}'"

# v2.0
mulertech_csp:
    directives:
        script-src:
            - "'self'"
            - "nonce(main)"
  1. Twig function: csp_nonce() now requires a handle argument
{# v1.x #}
<script nonce="{{ csp_nonce() }}">

{# v2.0 #}
<script nonce="{{ csp_nonce('main') }}">
  1. Nonce placeholder: {nonce} replaced by nonce(handle) syntax

Requirements

  • PHP >= 8.4
  • Symfony 6.4, 7.x or 8.x
  • Twig (optional, for the csp_nonce() function)
  • symfony/routing (optional, for route-based reporting)

License

MIT