Content Security Policy (CSP) Directive Regex for Go
/^(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+(.+))?$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching content security policy (csp) directive, ported and verified for Go. 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 Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.
Go Implementation
// Content Security Policy (CSP) Directive
// ReDoS-safe | RegexVault — Security > Security Headers
package validation
import "regexp"
var contentSecurityPolicyCspDirectiveRe = regexp.MustCompile(`^(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+(.+))?$`)
func ValidateContentSecurityPolicyCspDirective(s string) bool {
return contentSecurityPolicyCspDirectiveRe.MatchString(s)
}
// Example
// fmt.Println(ValidateContentSecurityPolicyCspDirective("default-src 'self'")) // trueTest 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 Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. 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