πŸ”’ Security

CSP

Content Security Policy

Content Security Policy. An HTTP header that prevents XSS attacks.

πŸ“– Detailed Explanation

CSP (Content Security Policy) is an HTTP response header that prevents XSS (Cross-Site Scripting) and data injection attacks in web browsers. It explicitly specifies the origins of resources (scripts, styles, images, fonts, etc.) that a web page can load as an allowlist.

The core principle of CSP is "whitelist-based security." By default, it blocks all inline scripts and eval(), and loads only resources from explicitly allowed origins. Even if an attacker discovers an XSS vulnerability, the execution of malicious scripts is blocked.

The main directives include default-src (default policy), script-src (script origins), style-src (style origins), img-src (image origins), and connect-src (Ajax/WebSocket origins). 'self' means the same origin, 'unsafe-inline' allows inline code (not recommended), and nonce/hash allow only specific inline scripts.

When CSP is violated, the browser blocks the resource load and prints an error to the console. By collecting violation reports with the report-uri or report-to directive, you can tighten the policy gradually.

πŸ’» Code Example

# 기본적인 CSP 헀더 μ„€μ • (Nginx)
# nginx.conf
add_header Content-Security-Policy "
  default-src 'self';
  script-src 'self' https://cdn.jsdelivr.net;
  style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
  font-src 'self' https://fonts.gstatic.com;
  img-src 'self' data: https:;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  form-action 'self';
" always;

# Next.jsμ—μ„œ CSP μ„€μ • (nonce 기반)
// next.config.js
const cspHeader = `
  default-src 'self';
  script-src 'self' 'nonce-{nonce}' 'strict-dynamic';
  style-src 'self' 'nonce-{nonce}';
  img-src 'self' blob: data:;
  font-src 'self';
  object-src 'none';
  base-uri 'self';
  form-action 'self';
  frame-ancestors 'none';
  upgrade-insecure-requests;
`;

// middleware.ts
import { NextResponse } from 'next/server';
import crypto from 'crypto';

export function middleware(request) {
  const nonce = crypto.randomBytes(16).toString('base64');
  const csp = cspHeader.replace(/{nonce}/g, nonce);

  const response = NextResponse.next();
  response.headers.set('Content-Security-Policy', csp);
  response.headers.set('x-nonce', nonce);
  return response;
}

# CSP Report-Only λͺ¨λ“œ (λ¨Όμ € ν…ŒμŠ€νŠΈ)
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report

# μœ„λ°˜ λ³΄κ³ μ„œ μˆ˜μ§‘ μ—”λ“œν¬μΈνŠΈ
// /api/csp-report.ts
export async function POST(req) {
  const report = await req.json();
  console.log('CSP Violation:', report['csp-report']);
  // 둜그 μ €μž₯ λ˜λŠ” μ•Œλ¦Ό
}

πŸ—£οΈ How It's Said in Practice

Security team: "The web vulnerability scan found that the CSP header is missing. Please add it to defend against XSS."

Frontend: "We use a lot of inline scripts, so applying it right away would probably break the site."

Senior: "Let's deploy in Report-Only mode first, collect the violation logs, and tighten it gradually."

Interviewer: "How would you defend against XSS attacks?"

Candidate: "Input validation and output encoding are the basics, and I add a second layer of defense with the CSP header. I allow only 'self' in script-src and restrict inline scripts with a nonce or hash. I start with Report-Only and tighten the policy gradually."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer: "If CSP contains 'unsafe-inline' and 'unsafe-eval', it has almost no effect in defending against XSS."

Author: "I added them because of legacy code, but I'll refactor to be nonce-based."

⚠️ Cautions

πŸ“š Learn More