Report-URI Configuration Errors

Report-URI Configuration Errors

Incorrect report-uri configuration prevents violation monitoring:

// Common Error: CSP reports not being received
// No console error, but reports aren't arriving at endpoint

// SOLUTION 1: Correct report-uri configuration
// Ensure absolute URL or correct relative path
Content-Security-Policy: 
  default-src 'self';
  report-uri /csp-violation-report; // Relative path
  report-to csp-endpoint; // Modern reporting

// SOLUTION 2: Implement proper report handling
app.post('/csp-violation-report', (req, res) => {
  // Set correct content type acceptance
  const contentType = req.headers['content-type'];
  
  if (contentType === 'application/csp-report') {
    // Traditional report-uri format
    handleCSPReport(req.body);
  } else if (contentType === 'application/reports+json') {
    // Modern Reporting API format
    req.body.forEach(report => {
      if (report.type === 'csp-violation') {
        handleCSPReport(report.body);
      }
    });
  }
  
  // Always return 204 No Content
  res.status(204).end();
});

// SOLUTION 3: Debug report-uri issues
class CSPReportDebugger {
  static validateReportUri(uri) {
    const issues = [];
    
    // Check if URI is reachable
    if (!uri) {
      issues.push('Report URI is not configured');
    } else if (uri.startsWith('//')) {
      issues.push('Protocol-relative URIs may cause issues');
    } else if (!uri.startsWith('http') && !uri.startsWith('/')) {
      issues.push('Invalid URI format');
    }
    
    return issues;
  }
  
  static testReportEndpoint(endpoint) {
    const testReport = {
      'csp-report': {
        'blocked-uri': 'https://test.example.com',
        'document-uri': 'https://example.com/test',
        'violated-directive': 'script-src'
      }
    };
    
    return fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/csp-report'
      },
      body: JSON.stringify(testReport)
    }).then(response => {
      if (response.status !== 204) {
        throw new Error(`Unexpected status: ${response.status}`);
      }
      return true;
    });
  }
}

Understanding and fixing common CSP errors requires systematic debugging and careful attention to error messages. By recognizing these patterns and applying the appropriate solutions, developers can implement robust CSP policies that enhance security without breaking functionality. Remember that CSP errors often indicate security vulnerabilities that would otherwise go unnoticed, making proper error resolution an essential part of web application security.