Skip to content

CSP Builder — Python 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 Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""csp-builder — Content-Security-Policy assembly, parsing, linting and scoring.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `csp-builder` tool, ported from
src/lib/csp-builder.ts (the canonical TypeScript implementation).

A policy is a plain dict of directive name -> source list; Python dicts
preserve insertion order, which is exactly what the TS Record relies on for
unknown-directive ordering in ``build_csp``. Parse is lenient by design so a
pasted real-world header always yields something editable — nothing raises.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import re

Policy = dict[str, list[str]]

# The directive catalog, in canonical build/display order: (name, kind) pairs.
# kind is "sources", "url" or "flag"; flags emit as a bare name. Descriptions,
# risk labels and default sources are UI metadata, omitted here.
_CATALOG: tuple[tuple[str, str], ...] = (
    ("default-src", "sources"), ("script-src", "sources"), ("style-src", "sources"),
    ("img-src", "sources"), ("connect-src", "sources"), ("font-src", "sources"),
    ("frame-src", "sources"), ("media-src", "sources"), ("object-src", "sources"),
    ("base-uri", "sources"), ("form-action", "sources"), ("frame-ancestors", "sources"),
    ("report-uri", "url"), ("upgrade-insecure-requests", "flag"),
    ("block-all-mixed-content", "flag"),
)

_FLAGS = frozenset(name for name, kind in _CATALOG if kind == "flag")
_KNOWN = frozenset(name for name, _ in _CATALOG)


def build_csp(directives: Policy) -> str:
    """Assemble a policy map into the ``Content-Security-Policy`` header value.

    Known directives emit in catalog order, unknown ones 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.
    """
    parts: list[str] = []

    def emit(name: str) -> None:
        sources = directives.get(name)
        if sources is None:
            return
        if name in _FLAGS:
            parts.append(name)
        elif sources:
            parts.append(f"{name} {' '.join(sources)}")

    for name, _ in _CATALOG:
        emit(name)
    for name in directives:
        if name not in _KNOWN:
            emit(name)
    return "; ".join(parts)


def parse_csp(header: str) -> Policy:
    """Parse 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). Never raises;
    garbage in, ``{}`` out.
    """
    text = header.strip()
    if re.match(r"^content-security-policy\s*:", text, re.IGNORECASE):
        text = text[text.index(":") + 1:]
    out: Policy = {}
    for token in text.split(";"):
        words = token.split()  # str.split() == trim + split(/\s+/), empties dropped
        if not words:
            continue
        name = words[0].lower()
        if name not in out:
            out[name] = words[1:]
    return out


# Sources treated as security-weakening, compared case-insensitively.
_RISKY_SOURCES = frozenset({"'unsafe-inline'", "'unsafe-eval'", "data:", "http:", "*"})


def is_risky_source(source: str) -> bool:
    """True when 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.
    """
    s = source.strip().lower()
    return s in _RISKY_SOURCES or s.startswith("http://")


# Short human explanation for each risky source (tooltip text in the UI).
_RISK_EXPLANATIONS = {
    "'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.",
}
_GENERIC_EXPLANATION = "Insecure http:// URL - traffic can be tampered with in transit."


def risk_explanation(source: str) -> str:
    """Explanation for any risky source; falls back to the generic text."""
    return _RISK_EXPLANATIONS.get(source.strip().lower(), _GENERIC_EXPLANATION)


def validate_csp(directives: Policy) -> list[dict[str, object]]:
    """Lint a policy: warn when default-src is missing (unset directives fall
    back to the browser's allow-everything default) and flag every risky
    source. Each issue is a dict with ``directive`` ("" for policy-wide),
    ``source`` (None for policy-wide) and ``message``.
    """
    issues: list[dict[str, object]] = []
    if "default-src" not in directives:
        issues.append({
            "directive": "",
            "source": None,
            "message": "No default-src - every directive you don't set explicitly falls back to the browser's permissive default.",
        })
    for name, sources in directives.items():
        for src in sources:
            if is_risky_source(src):
                issues.append({
                    "directive": name,
                    "source": src,
                    "message": f"{name}: {src} weakens this policy - {risk_explanation(src)}",
                })
    return issues


# Score penalty per risky source (case-insensitive key).
_SCORE_PENALTIES = {"'unsafe-inline'": 20, "'unsafe-eval'": 15, "*": 20, "data:": 10, "http:": 10}


def security_score(directives: Policy) -> int:
    """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.
    """
    score = 100
    if "default-src" not in directives:
        score -= 10
    for sources in directives.values():
        for src in sources:
            s = src.strip().lower()
            score -= _SCORE_PENALTIES.get(s, 10 if s.startswith("http://") else 0)
    return max(0, min(100, 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 →