Add helper for safely appending nonce/hash sources

Created on 23 December 2023, 6 months ago
Updated 5 June 2024, 21 days ago

Problem/Motivation

In order to safely add a nonce or hash to a directive, modules need to:

  • copy sources from any fallback directives
  • For hashes, initialize the other subdirective so that a hash value from the base directive doesn't apply (either through the other directive not existing on the final policy, or the value from the base directive later being copied)
  • check whether another module has already added 'unsafe-inline' but not another nonce or hash source
    • if 'unsafe-inline' is not present or is disabled (by an existing nonce or hash; or 'strict-dynamic'): append the nonce or hash
    • if 'unsafe-inline' is required by another module: authorize the necessary sources in another way - it's presumed 'unsafe-inline' is already present, but other modules (e.g. google_tag) may need to add additional external domains for dynamically loaded scripts
  • Modify the base directive with the same value for older browsers that don't support *-elem and *-attr

Enable conditional/alternate directive values Active could either supersede this, or be used as the underlying method for implementing the source fallback functionality.

Proposed resolution

Create a PolicyHelper service with methods for altering a Csp object

  • appendNonce(Csp $policy, string $directive, $fallback = null, string $value = null) : bool
    If $value is not provided, retrieve the nonce from the csp.nonce service.
    Add a nonce to {$directive}-src-elem if possible (and the corresponding base directive. It is not necessary to alter the -attr directive since nonces can't be applied to attributes).
    If the nonce is not appended, add $fallback to the directives instead.
  • appendHash(Csp $policy, string $directive, string $type = 'elem', $fallback = null, string $value): bool
    Initialize the base directive and other subdirective.
    Add the provided hash to {$directive}-src-{$type} and {$directive}-src if possible.
    If the hash is not added, add the $fallback value.
  • requireUnsafeInline(Csp $policy, string $directive, string $type): void
    Ensure that the other subdirective does not fall back to the base directive.
    Require 'unsafe-inline' for a directive (and its base directive) by ensuring that any hashes or nonces are removed.
    Note: if this method is required, it should be called early in the policy alter event so that other modules can correctly add any needed fallback values.

Remaining tasks

User interface changes

n/a

API changes

New service

Data model changes

n/a

Feature request
Status

Fixed

Version

1.0

Component

Code

Created by

🇨🇦Canada gapple

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.69.0 2024