CSP Builder — Go source
Build a Content-Security-Policy header interactively. Toggle directives, add sources, see the assembled header in real time — with a security score that flags unsafe sources.
This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package cspbuilder ports src/lib/csp-builder.ts (dual source: the web lib is
// TypeScript, the CLI lib is Go — kept in lock-step). Pure Content-Security-
// Policy logic: no I/O, deterministic, never panics. A CSP is modeled as an
// ordered map of directive -> source list; BuildCSP assembles the map into the
// header string (directives in catalog order, then unknown directives in
// insertion order), ParseCSP reads a header back into the map — leniently, so a
// pasted real-world header always yields something editable. The table-driven
// tests in csp_builder_test.go share vectors with src/lib/csp-builder.test.ts
// so the two implementations are held to the same contract.
package cspbuilder
import (
"regexp"
"strings"
)
// DirectiveKind is how a directive takes its value: a source list, a single
// URL, or a bare flag.
type DirectiveKind string
const (
KindSources DirectiveKind = "sources"
KindURL DirectiveKind = "url"
KindFlag DirectiveKind = "flag"
)
// DirectiveRisk is how much exposure the directive controls.
type DirectiveRisk string
const (
RiskLow DirectiveRisk = "low"
RiskMedium DirectiveRisk = "medium"
RiskHigh DirectiveRisk = "high"
)
// DirectiveInfo is one entry of the built-in directive catalog.
type DirectiveInfo struct {
Name string
Kind DirectiveKind
Description string
Risk DirectiveRisk
DefaultSources []string // sources inserted when the directive is enabled in the UI
}
// CSPDirectives is the catalog, in canonical build/display order. Mirrors
// CSP_DIRECTIVES in src/lib/csp-builder.ts.
var CSPDirectives = []DirectiveInfo{
{
Name: "default-src",
Kind: KindSources,
Description: "Fallback for every fetch directive you do not set explicitly. " +
"Set this first, then tighten individual directives.",
Risk: RiskMedium,
DefaultSources: []string{"'self'"},
},
{
Name: "script-src",
Kind: KindSources,
Description: "Where scripts may load from. The single most important XSS " +
"control - keep it as tight as you can.",
Risk: RiskHigh,
DefaultSources: []string{"'self'"},
},
{
Name: "style-src",
Kind: KindSources,
Description: "Where stylesheets may load from. Also gates inline style attributes.",
Risk: RiskMedium,
DefaultSources: []string{"'self'"},
},
{
Name: "img-src",
Kind: KindSources,
Description: "Where images and favicons may load from.",
Risk: RiskLow,
DefaultSources: []string{"'self'"},
},
{
Name: "connect-src",
Kind: KindSources,
Description: "Which URLs scripts may connect to (fetch, XHR, WebSocket). " +
"Your data-exfiltration boundary.",
Risk: RiskMedium,
DefaultSources: []string{"'self'"},
},
{
Name: "font-src",
Kind: KindSources,
Description: "Where web fonts may load from.",
Risk: RiskLow,
DefaultSources: []string{"'self'"},
},
{
Name: "frame-src",
Kind: KindSources,
Description: "Which URLs may be embedded as child browsing contexts (iframe, frame).",
Risk: RiskLow,
DefaultSources: []string{"'self'"},
},
{
Name: "media-src",
Kind: KindSources,
Description: "Where audio and video may load from.",
Risk: RiskLow,
DefaultSources: []string{"'self'"},
},
{
Name: "object-src",
Kind: KindSources,
Description: "Where plugin content (object, embed, applet) may load from. " +
"Almost always should be 'none'.",
Risk: RiskHigh,
DefaultSources: []string{"'none'"},
},
{
Name: "base-uri",
Kind: KindSources,
Description: "Which URLs may set the document base. Restrict to 'self' to " +
"block <base> hijacking of relative URLs.",
Risk: RiskHigh,
DefaultSources: []string{"'self'"},
},
{
Name: "form-action",
Kind: KindSources,
Description: "Where forms may submit to. Does not fall back to default-src.",
Risk: RiskMedium,
DefaultSources: []string{"'self'"},
},
{
Name: "frame-ancestors",
Kind: KindSources,
Description: "Which parents may embed this page (clickjacking control). " +
"Ignored inside a <meta> tag - header delivery only.",
Risk: RiskMedium,
DefaultSources: []string{"'self'"},
},
{
Name: "report-uri",
Kind: KindURL,
Description: "URL where the browser posts violation reports. Pair with a report collector.",
Risk: RiskLow,
DefaultSources: nil,
},
{
Name: "upgrade-insecure-requests",
Kind: KindFlag,
Description: "Tells the browser to rewrite http:// subresource requests to https://.",
Risk: RiskLow,
DefaultSources: nil,
},
{
Name: "block-all-mixed-content",
Kind: KindFlag,
Description: "Blocks loading of any http:// subresource on an https:// page.",
Risk: RiskLow,
DefaultSources: nil,
},
}
// CommonSources are the source presets offered in the UI when adding a source
// to a directive. Mirrors COMMON_SOURCES.
var CommonSources = []string{
"'self'",
"'none'",
"'unsafe-inline'",
"'unsafe-eval'",
"'strict-dynamic'",
"data:",
"blob:",
"https:",
}
// flagDirectives are the directives that take no value - emitted as a bare name.
var flagDirectives = func() map[string]bool {
m := map[string]bool{}
for _, d := range CSPDirectives {
if d.Kind == KindFlag {
m[d.Name] = true
}
}
return m
}()
// knownDirectives are the catalog names, for ordering during build.
var knownDirectives = func() map[string]bool {
m := map[string]bool{}
for _, d := range CSPDirectives {
m[d.Name] = true
}
return m
}()
// CSPDirectiveMap is a policy: directive name (lowercase) -> enabled source
// list; a present key means the directive is enabled. It is an ordered map:
// Keys() reports insertion order, which BuildCSP relies on to emit unknown
// directives deterministically — the Go counterpart of TS Record key order.
// The zero value is an empty, usable policy.
type CSPDirectiveMap struct {
keys []string
values map[string][]string
}
// NewCSPDirectiveMap returns an empty policy.
func NewCSPDirectiveMap() *CSPDirectiveMap {
return &CSPDirectiveMap{values: map[string][]string{}}
}
// Set stores sources under name. An existing key keeps its original position;
// a new key is appended in insertion order.
func (m *CSPDirectiveMap) Set(name string, sources []string) {
if m.values == nil {
m.values = map[string][]string{}
}
if _, ok := m.values[name]; !ok {
m.keys = append(m.keys, name)
}
m.values[name] = sources
}
// Get returns the source list for name and whether the key is present.
// A present key with an empty list (e.g. a flag directive) returns
// (empty, true) — the TS twin distinguishes undefined from [].
func (m *CSPDirectiveMap) Get(name string) ([]string, bool) {
sources, ok := m.values[name]
return sources, ok
}
// Has reports whether name is present (enabled).
func (m *CSPDirectiveMap) Has(name string) bool {
_, ok := m.values[name]
return ok
}
// Keys returns the directive names in insertion order.
func (m *CSPDirectiveMap) Keys() []string {
return append([]string(nil), m.keys...)
}
// Len returns the number of directives in the policy.
func (m *CSPDirectiveMap) Len() int {
return len(m.keys)
}
// BuildCSP assembles a policy map into the Content-Security-Policy header
// value. Known directives emit in catalog order, unknown directives after them
// in insertion order. Flag directives emit as a bare name; source/url
// directives with an empty list are omitted (a valueless directive is invalid
// CSP). An empty map yields an empty string.
func BuildCSP(directives *CSPDirectiveMap) string {
var parts []string
emit := func(name string) {
sources, ok := mget(directives, name)
if !ok {
return
}
if flagDirectives[name] {
parts = append(parts, name)
return
}
if len(sources) == 0 {
return
}
parts = append(parts, name+" "+strings.Join(sources, " "))
}
for _, d := range CSPDirectives {
emit(d.Name)
}
for _, name := range directives.Keys() {
if !knownDirectives[name] {
emit(name)
}
}
return strings.Join(parts, "; ")
}
// mget reads name from directives, tolerating a nil map pointer like the TS
// emit closure reading directives[name] of a possibly-absent key.
func mget(m *CSPDirectiveMap, name string) ([]string, bool) {
if m == nil {
return nil, false
}
return m.Get(name)
}
var (
// Leading "Content-Security-Policy:" label on a pasted full header line.
cspLabel = regexp.MustCompile(`(?i)^content-security-policy[ \t]*:`)
// Any run of whitespace, for token splitting.
whitespace = regexp.MustCompile(`\s+`)
)
// ParseCSP parses a CSP header value back into a policy map. Lenient: splits
// on semicolons and whitespace, lowercases directive names, ignores empty
// tokens, and strips an optional leading Content-Security-Policy: label so a
// pasted full header line works. Duplicate directives keep only the first
// occurrence (matching how browsers honor them). Garbage in, empty policy out.
func ParseCSP(header string) *CSPDirectiveMap {
out := NewCSPDirectiveMap()
text := strings.TrimSpace(header)
if cspLabel.MatchString(text) {
text = text[strings.Index(text, ":")+1:]
}
for _, token := range strings.Split(text, ";") {
words := whitespace.Split(strings.TrimSpace(token), -1)
words = dropEmpty(words)
if len(words) == 0 {
continue
}
name := strings.ToLower(words[0])
if out.Has(name) {
continue
}
out.Set(name, words[1:])
}
return out
}
// dropEmpty removes empty strings produced by splitting on leading/trailing
// whitespace runs — the Go counterpart of TS .filter(Boolean).
func dropEmpty(words []string) []string {
kept := words[:0]
for _, w := range words {
if w != "" {
kept = append(kept, w)
}
}
return kept
}
// riskySources are the sources treated as security-weakening, compared
// case-insensitively. Mirrors RISKY_SOURCES.
var riskySources = map[string]bool{
"'unsafe-inline'": true,
"'unsafe-eval'": true,
"data:": true,
"http:": true,
"*": true,
}
// IsRiskySource reports whether a source weakens the policy: 'unsafe-inline',
// 'unsafe-eval', 'data:', 'http:', the bare wildcard '*', or any insecure
// http:// URL. 'self', 'none', 'strict-dynamic', 'blob:', 'https:' and https
// URLs are fine.
func IsRiskySource(source string) bool {
s := strings.ToLower(strings.TrimSpace(source))
return riskySources[s] || strings.HasPrefix(s, "http://")
}
// riskExplanations are short human explanations for each risky source.
// Mirrors RISK_EXPLANATIONS.
var riskExplanations = map[string]string{
"'unsafe-inline'": "Allows inline <script>/<style> and event handlers - " +
"defeats most of CSP's XSS protection.",
"'unsafe-eval'": "Allows eval() and similar code execution - weakens XSS protection.",
"*": "Allows every origin - effectively no restriction for this directive.",
"data:": "data: URIs can carry arbitrary payloads and are same-origin - " +
"attackers can smuggle content through them.",
"http:": "Allows insecure origins - a network attacker can inject or tamper with subresources.",
}
// RiskExplanation returns the explanation for any risky source, falling back
// to the generic insecure-origin text.
func RiskExplanation(source string) string {
key := strings.ToLower(strings.TrimSpace(source))
if exp, ok := riskExplanations[key]; ok {
return exp
}
return "Insecure http:// URL - traffic can be tampered with in transit."
}
// CspIssue is one policy problem: either policy-wide (Directive == "") or a
// risky source. Source is nil for policy-wide issues (TS null).
type CspIssue struct {
Directive string // directive the issue belongs to; "" for policy-wide issues
Source *string // the offending source, or nil for policy-wide issues
Message string
}
// ValidateCSP lints a policy: warns when default-src is missing (unset
// directives fall back to the browser's allow-everything default) and flags
// every risky source.
func ValidateCSP(directives *CSPDirectiveMap) []CspIssue {
var issues []CspIssue
if !directives.Has("default-src") {
issues = append(issues, CspIssue{
Directive: "",
Source: nil,
Message: "No default-src - every directive you don't set explicitly " +
"falls back to the browser's permissive default.",
})
}
for _, name := range directives.Keys() {
sources, _ := directives.Get(name)
for _, src := range sources {
if IsRiskySource(src) {
s := src
issues = append(issues, CspIssue{
Directive: name,
Source: &s,
Message: name + ": " + src + " weakens this policy - " + RiskExplanation(src),
})
}
}
}
return issues
}
// scorePenalties is the score penalty per risky source (case-insensitive key).
// Mirrors SCORE_PENALTIES.
var scorePenalties = map[string]int{
"'unsafe-inline'": 20,
"'unsafe-eval'": 15,
"*": 20,
"data:": 10,
"http:": 10,
}
// SecurityScore returns the security score, 0-100. Starts at 100; each risky
// source subtracts its penalty (insecure http:// URLs subtract 10), and a
// missing default-src subtracts 10. Clamped to 0-100. Deterministic.
func SecurityScore(directives *CSPDirectiveMap) int {
score := 100
if !directives.Has("default-src") {
score -= 10
}
for _, name := range directives.Keys() {
sources, _ := directives.Get(name)
for _, src := range sources {
s := strings.ToLower(strings.TrimSpace(src))
penalty, ok := scorePenalties[s]
if !ok {
penalty = 0
if strings.HasPrefix(s, "http://") {
penalty = 10
}
}
score -= penalty
}
}
if score < 0 {
return 0
}
if score > 100 {
return 100
}
return score
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →