REGEXVAULTv2.0
Security/Security Headers
Verified Safe

Content Security Policy (CSP) Directive Regex for Python

/^(default-src|script-src|style-src|img-src|connect-src|font-src|object-src|media-src|frame-src|child-src|form-action|frame-ancestors|base-uri|report-uri|report-to|upgrade-insecure-requests|block-all-mixed-content|sandbox|worker-src|manifest-src|prefetch-src)(?:\s+(.+))?$/i

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching content security policy (csp) directive, ported and verified for Python. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.

Python Implementation

Python
# Content Security Policy (CSP) Directive
# ReDoS-safe | RegexVault — Security > Security Headers

import re

content_security_policy_csp_directive_pattern = re.compile(r'^(default-src|script-src|style-src|img-src|connect-src|font-src|object-src|media-src|frame-src|child-src|form-action|frame-ancestors|base-uri|report-uri|report-to|upgrade-insecure-requests|block-all-mixed-content|sandbox|worker-src|manifest-src|prefetch-src)(?:\s+(.+))?$')

def validate_content_security_policy_csp_directive(value: str) -> bool:
    return bool(content_security_policy_csp_directive_pattern.fullmatch(value))

# Example
print(validate_content_security_policy_csp_directive("default-src 'self'"))  # True

Test Cases

Matches (Valid)
Rejects (Invalid)
default-src 'self'evil-src 'self'
script-src 'self' https://cdn.example.com 'nonce-abc123'src 'self'
object-src 'none'
upgrade-insecure-requests

When to use this pattern

This pattern is drawn from the Security > Security Headers category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

'unsafe-inline' and 'unsafe-eval' negate much of CSP's protection. Prefer nonce-based CSP where a random nonce is generated per request. The CSP Evaluator tool (from Google) checks CSP policies for weaknesses.

Technical Notes

CSP source keywords: 'self' (same origin), 'none' (block all), 'unsafe-inline' (dangerous), 'unsafe-eval' (dangerous), 'nonce-{base64}' (nonce), 'sha256-{hash}' (hash). A strong CSP eliminates most XSS attack surfaces. object-src 'none' and base-uri 'self' are critical.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern