Problem/Motivation

Currently, it is not very easy for a module to correctly add nessecary information to the CSP headers.

For example, if a module adds this snippet to the page:
<script>alert('Hello!');</script>

Currently, to add CSP compatibility the following code is needed (if you really want to do it right):

    $csp = $alterEvent->getPolicy();

    // Add the new directive to script-src-elem for CSP level 3.
    // First make sure that the directive is copied from its parent if it
    // doesn't have a value present.
    $csp->fallbackAwareAppendIfEnabled('script-src-elem', []);
    // We only want to add the directive if 'unsafe-inline' is not present,
    // because otherwise it will undo the 'unsafe-inline'.
    if (!in_array("'unsafe-inline'", $csp->getDirective('script-src-elem') ?? [])) {
      $csp->fallbackAwareAppendIfEnabled('script-src-elem', "'sha256-1k/RwDD3A+xnxZogLFSUWP9jGMvmdeww4OSpMKdUxn4='");
    }
    // Now, make sure that there is a script-src-attr present. If there isn't yet, the
    // value is taken from script-src by the browser, which we will also be adjusting.
    $csp->fallbackAwareAppendIfEnabled('script-src-attr', []);
    // Also add the directive to script-src for CSP level 2.
    // Exactly the same as for level 3.
    $csp->fallbackAwareAppendIfEnabled('script-src', []);
    if (!in_array("'unsafe-inline'", $csp->getDirective('script-src') ?? [])) {
      $csp->fallbackAwareAppendIfEnabled('script-src', "'sha256-1k/RwDD3A+xnxZogLFSUWP9jGMvmdeww4OSpMKdUxn4='");
    }

Proposed resolution

If the Csp class has a few helper methods that could take care of this, it is much easier for modules to add CSP compatibility.
By making different helper methods for all (relevant) directives, it can also be made clearer which directives should be used. For example, by always using script-src-elem or script-src-attr and not script-src. Documentation can be added to all methods to be clear about where they are for.

Remaining tasks

Create MR and decide on methods to create.

User interface changes

None.

API changes

New methods on the Csp class, so backwards compatible.

Data model changes

None.

Issue fork csp-3251172

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

bartlangelaan created an issue. See original summary.

bartlangelaan’s picture

Status: Active » Needs review

Please see MR !4.

We can add a lot more methods of course, but first I would like some feedback ;-)

bartlangelaan’s picture

Issue summary: View changes

Change the issue description so the usecase uses an inline script, instead of an external javascript.