Performance Monitoring and Metrics

Performance Monitoring and Metrics

Continuous monitoring helps identify and address performance issues:

// CSP Performance Monitor
class CSPPerformanceMonitor {
  constructor() {
    this.metrics = this.initializeMetrics();
    this.thresholds = this.defineThresholds();
  }
  
  initializeMetrics() {
    return {
      realUserMetrics: `
        // Real User Monitoring for CSP
        (function() {
          const cspRUM = {
            metrics: {
              headerParseTime: 0,
              policyEvaluations: 0,
              violations: 0,
              blockedResources: 0,
              totalOverhead: 0
            },
            
            init() {
              this.measureHeaderParsing();
              this.trackViolations();
              this.measurePerformanceImpact();
              this.reportMetrics();
            },
            
            measureHeaderParsing() {
              // Estimate CSP header parsing time
              const entries = performance.getEntriesByType('navigation');
              if (entries.length > 0) {
                const nav = entries[0];
                // CSP parsing happens during responseEnd
                this.metrics.headerParseTime = nav.responseEnd - nav.responseStart;
              }
            },
            
            trackViolations() {
              document.addEventListener('securitypolicyviolation', (e) => {
                this.metrics.violations++;
                
                // Measure violation processing time
                const start = performance.now();
                // Violation handling
                const processingTime = performance.now() - start;
                
                this.metrics.totalOverhead += processingTime;
              });
            },
            
            measurePerformanceImpact() {
              // Compare with and without CSP
              const observer = new PerformanceObserver((list) => {
                for (const entry of list.getEntries()) {
                  if (entry.entryType === 'measure' && entry.name.includes('csp')) {
                    this.metrics.totalOverhead += entry.duration;
                  }
                }
              });
              
              observer.observe({ entryTypes: ['measure', 'navigation'] });
            },
            
            reportMetrics() {
              // Send metrics after page load
              window.addEventListener('load', () => {
                setTimeout(() => {
                  this.sendMetrics({
                    ...this.metrics,
                    pageLoadTime: performance.timing.loadEventEnd - performance.timing.navigationStart,
                    cspOverheadPercentage: (this.metrics.totalOverhead / (performance.timing.loadEventEnd - performance.timing.navigationStart)) * 100
                  });
                }, 1000);
              });
            },
            
            sendMetrics(data) {
              // Send to analytics endpoint
              if (navigator.sendBeacon) {
                navigator.sendBeacon('/api/csp-performance', JSON.stringify(data));
              }
            }
          };
          
          cspRUM.init();
        })();
      `,
      
      syntheticMonitoring: `
        // Synthetic monitoring for CSP performance
        class CSPSyntheticMonitor {
          async runPerformanceTest(url, cspPolicy) {
            const puppeteer = require('puppeteer');
            const browser = await puppeteer.launch();
            
            try {
              // Test without CSP
              const baselineMetrics = await this.measurePageLoad(browser, url, null);
              
              // Test with CSP
              const cspMetrics = await this.measurePageLoad(browser, url, cspPolicy);
              
              // Calculate impact
              const impact = {
                loadTimeIncrease: cspMetrics.loadTime - baselineMetrics.loadTime,
                percentageIncrease: ((cspMetrics.loadTime - baselineMetrics.loadTime) / baselineMetrics.loadTime) * 100,
                additionalRequests: cspMetrics.requests - baselineMetrics.requests,
                blockedResources: cspMetrics.blockedResources
              };
              
              return {
                baseline: baselineMetrics,
                withCSP: cspMetrics,
                impact: impact,
                recommendation: this.generateRecommendation(impact)
              };
            } finally {
              await browser.close();
            }
          }
          
          async measurePageLoad(browser, url, cspPolicy) {
            const page = await browser.newPage();
            
            if (cspPolicy) {
              await page.setExtraHTTPHeaders({
                'Content-Security-Policy': cspPolicy
              });
            }
            
            const metrics = {
              loadTime: 0,
              requests: 0,
              blockedResources: 0
            };
            
            page.on('request', () => metrics.requests++);
            page.on('requestfailed', request => {
              if (request.failure().errorText.includes('Content Security Policy')) {
                metrics.blockedResources++;
              }
            });
            
            const start = Date.now();
            await page.goto(url, { waitUntil: 'networkidle2' });
            metrics.loadTime = Date.now() - start;
            
            return metrics;
          }
        }
      `
    };
  }
  
  defineThresholds() {
    return {
      acceptable: {
        parseTime: 5, // ms
        overheadPercentage: 2, // %
        violationsPerPageLoad: 0
      },
      warning: {
        parseTime: 10,
        overheadPercentage: 5,
        violationsPerPageLoad: 1
      },
      critical: {
        parseTime: 20,
        overheadPercentage: 10,
        violationsPerPageLoad: 5
      }
    };
  }
}

CSP performance optimization requires a holistic approach that considers header size, parsing complexity, resource loading patterns, and caching strategies. By implementing the optimization techniques outlined in this guide and maintaining continuous monitoring, organizations can deploy robust CSP policies that enhance security without compromising user experience. Remember that performance optimization is an iterative process—regularly review metrics, test optimizations, and adjust strategies based on real-world performance data. The goal is to achieve the strongest possible security posture while maintaining the fast, responsive web experience users expect.## CSP Directives Explained - Full Reference Guide

Content Security Policy directives form the backbone of any CSP implementation, each controlling a specific type of resource or browser behavior. Understanding these directives and their interactions is crucial for creating effective security policies that protect against attacks while maintaining application functionality. This comprehensive reference guide explores every CSP directive, their use cases, and practical implementation strategies.