You are here

public function CspOptimizationTest::testWorkerSrcFallback in Content-Security-Policy 8

Test optimizing policy based on the worker-src fallback list.

@covers ::getHeaderValue @covers ::getDirectiveFallbackList @covers ::reduceSourceList

File

tests/src/Unit/CspOptimizationTest.php, line 83

Class

CspOptimizationTest
Test optimization of CSP directives.

Namespace

Drupal\Tests\csp\Unit

Code

public function testWorkerSrcFallback() {
  $policy = new Csp();

  // Fallback should progresses as more policies in the list are added.
  $policy
    ->setDirective('worker-src', Csp::POLICY_SELF);
  $this
    ->assertEquals("worker-src 'self'", $policy
    ->getHeaderValue());
  $policy
    ->setDirective('child-src', Csp::POLICY_SELF);
  $this
    ->assertEquals("child-src 'self'", $policy
    ->getHeaderValue());
  $policy
    ->setDirective('script-src', Csp::POLICY_SELF);
  $this
    ->assertEquals("script-src 'self'", $policy
    ->getHeaderValue());
  $policy
    ->setDirective('default-src', Csp::POLICY_SELF);
  $this
    ->assertEquals("default-src 'self'", $policy
    ->getHeaderValue());

  // A missing directive from the list should not prevent fallback.
  $policy
    ->removeDirective('child-src');
  $this
    ->assertEquals("default-src 'self'", $policy
    ->getHeaderValue());

  // Fallback should only progress to the nearest matching directive.
  // Since child-src differs from worker-src, both should be included.
  // script-src does not appear since it matches default-src.
  $policy
    ->setDirective('child-src', [
    Csp::POLICY_SELF,
    'example.com',
  ]);
  $this
    ->assertEquals("default-src 'self'; child-src 'self' example.com; worker-src 'self'", $policy
    ->getHeaderValue());

  // Fallback should only progress to the nearest matching directive.
  // worker-src now matches child-src, so it should be removed.
  $policy
    ->setDirective('worker-src', [
    Csp::POLICY_SELF,
    'example.com',
  ]);
  $this
    ->assertEquals("default-src 'self'; child-src 'self' example.com", $policy
    ->getHeaderValue());
}