CSP Testing Best Practices

CSP Testing Best Practices

Effective CSP testing requires systematic approaches and proper tooling:

// CSP Test Suite
describe('Content Security Policy Tests', () => {
  let page;
  let violations;
  
  beforeEach(async () => {
    violations = [];
    page = await browser.newPage();
    
    // Capture CSP violations
    page.on('console', msg => {
      if (msg.type() === 'error' && msg.text().includes('Content Security Policy')) {
        violations.push(msg.text());
      }
    });
    
    // Intercept violation reports
    await page.setRequestInterception(true);
    page.on('request', request => {
      if (request.url().includes('csp-report')) {
        violations.push(JSON.parse(request.postData()));
        request.respond({ status: 204 });
      } else {
        request.continue();
      }
    });
  });
  
  test('CSP headers are present', async () => {
    const response = await page.goto('https://localhost:3000');
    const cspHeader = response.headers()['content-security-policy'];
    
    expect(cspHeader).toBeDefined();
    expect(cspHeader).toContain('default-src');
  });
  
  test('No violations on standard page load', async () => {
    await page.goto('https://localhost:3000');
    await page.waitForTimeout(2000);
    
    expect(violations).toHaveLength(0);
  });
  
  test('Inline scripts are blocked', async () => {
    await page.goto('https://localhost:3000');
    
    // Attempt to execute inline script
    const result = await page.evaluate(() => {
      try {
        const script = document.createElement('script');
        script.textContent = 'window.testVar = "inline-script-executed";';
        document.head.appendChild(script);
        return window.testVar;
      } catch (e) {
        return 'blocked';
      }
    });
    
    expect(result).not.toBe('inline-script-executed');
    expect(violations.length).toBeGreaterThan(0);
  });
  
  test('External scripts from unauthorized domains are blocked', async () => {
    await page.goto('https://localhost:3000');
    
    await page.evaluate(() => {
      const script = document.createElement('script');
      script.src = 'https://evil-site.com/malicious.js';
      document.head.appendChild(script);
    });
    
    await page.waitForTimeout(1000);
    
    const violationFound = violations.some(v => 
      v.includes('evil-site.com') || 
      (v['csp-report'] && v['csp-report']['blocked-uri'].includes('evil-site.com'))
    );
    
    expect(violationFound).toBe(true);
  });
});

Debugging and testing CSP effectively requires a combination of tools, techniques, and systematic approaches. By implementing comprehensive monitoring, automated testing, and continuous analysis, you can maintain robust CSP policies that enhance security without impacting functionality. Remember that CSP debugging is an iterative process – use the tools and techniques outlined here to progressively refine your policies based on real-world usage patterns and security requirements.## CSP Report-Only Mode - Safe Implementation Strategy

Report-Only mode represents one of Content Security Policy's most valuable features, allowing organizations to test and refine security policies without risking application functionality. This comprehensive guide explores how to leverage Report-Only mode effectively, transitioning from initial implementation to full enforcement while maintaining application stability and user experience throughout the process.