Security Headers Analyzer — Python source
Paste HTTP response headers to analyze security posture. Checks CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""security-headers — HTTP response-header analysis and grading.
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `security-headers` tool, ported from
src/lib/security-headers.ts (the canonical TypeScript implementation).
Why this file exists: grading security headers is pure string work, so the
exact logic behind the web tool runs anywhere Python does — paste a DevTools
header block, get the same A/B/C/F verdicts, weighted score, and fix list.
Two mechanical substitutions: JS Math.round(x) is mirrored as floor(x + 0.5)
(Python's round() rounds half to even), and the TS lib's catalog blurbs are
omitted for brevity — every grade, explanation, and score matches the lib.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
# Grade points used for the weighted overall score.
GRADE_POINTS = {"A": 100, "B": 70, "C": 40, "F": 0}
# One year in seconds - the minimum HSTS max-age worth calling strong.
ONE_YEAR = 31_536_000
BEST = "Best practice met - nothing to change."
# The 8 graded headers with their score weights, in display order. The long
# "why it matters" blurbs live in src/lib/security-headers.ts.
SECURITY_HEADERS: list[tuple[str, float]] = [
("Strict-Transport-Security", 1.5),
("Content-Security-Policy", 2),
("X-Frame-Options", 1),
("X-Content-Type-Options", 1),
("Referrer-Policy", 1),
("Permissions-Policy", 1),
("X-XSS-Protection", 0.5),
("Cross-Origin-Opener-Policy", 1),
]
REFERRER_STRICT = ("no-referrer", "same-origin", "strict-origin", "strict-origin-when-cross-origin")
REFERRER_WEAK = ("origin", "origin-when-cross-origin", "no-referrer-when-downgrade")
@dataclass
class ParsedHeader:
"""One security header as analyzed; ``value`` is None when the header is absent."""
name: str
value: str | None
grade: str # 'A' best practice, 'B' weak, 'C' missing, 'F' actively harmful
explanation: str
recommendation: str
@dataclass
class HeaderAnalysis:
"""The full analysis: per-header rows, the overall grade, and the fix list."""
headers: list[ParsedHeader]
grade: str
score: int # 0-100 weighted average of per-header grade points
recommendations: list[str]
def parse_headers(raw: str | None) -> dict[str, str]:
"""Parse a raw header block into a lowercased-name dict.
Lines are ``name: value``; the ``HTTP/1.1 200 OK`` status line and any
line without a colon are ignored. A line starting with space/tab continues
the previous header (RFC 7230 obs-fold); a repeated name joins its values
with ", ". Never raises.
"""
headers: dict[str, str] = {}
last_name: str | None = None
for line in re.split(r"\r?\n", raw or ""):
if re.match(r"\s", line):
# Folded continuation - append to the previous header, if any.
if last_name is not None:
prev = headers.get(last_name, "")
headers[last_name] = f"{prev} {line.strip()}".strip()
continue
name, sep, value = line.partition(":")
if not sep:
continue # status line, blank line, or junk
name = name.strip().lower()
if name == "":
continue
value = value.strip()
headers[name] = f"{headers[name]}, {value}" if name in headers else value
last_name = name
return headers
# --- Per-header graders: value (None when absent) -> (grade, explanation, recommendation) ---
def _grade_hsts(v: str | None) -> tuple[str, str, str]:
if v is None:
return "C", "Missing - the browser accepts plain HTTP, so the first visit (and SSL-strip attacks) can downgrade the connection.", "Add: strict-transport-security: max-age=31536000; includeSubDomains; preload"
m = re.search(r"max-age\s*=\s*(\d+)", v, re.IGNORECASE)
if m is None:
return "B", f"Present but malformed - no readable max-age directive ({v}).", "Use: strict-transport-security: max-age=31536000; includeSubDomains"
max_age = int(m.group(1))
if max_age == 0:
return "F", "max-age=0 actively deletes the HSTS policy - the site opts out of HTTPS-only enforcement.", "Raise max-age to at least 31536000 (one year)."
subs = re.search(r";\s*includesubdomains", v, re.IGNORECASE) is not None
if max_age < ONE_YEAR:
extra = " and includeSubDomains" if subs else ""
return "B", f"Present with max-age={max_age}s (< 1 year){extra} - a shorter window weakens the guarantee.", "Raise max-age to 31536000 (one year) or more."
if not subs:
return "B", "Strong max-age (>= 1 year), but includeSubDomains is missing - subdomains stay downgradable.", "Append ; includeSubDomains once every subdomain serves HTTPS."
tail = " + preload - eligible for the browser preload list." if re.search(r";\s*preload", v, re.IGNORECASE) else ". Add preload to join the browser preload list."
return "A", f"Strong: max-age >= 1 year + includeSubDomains{tail}", BEST
def _grade_csp(v: str | None) -> tuple[str, str, str]:
if v is None:
return "C", "Missing - no restriction on where scripts and resources load from, so injected markup runs at full power.", "Add a policy, e.g.: content-security-policy: default-src 'none'; script-src 'self'; ..."
inline = re.search(r"'unsafe-inline'", v, re.IGNORECASE) is not None
evaluates = re.search(r"'unsafe-eval'", v, re.IGNORECASE) is not None
if inline and evaluates:
return "F", "Actively harmful - 'unsafe-inline' + 'unsafe-eval' together re-allow inline injection and string evaluation, gutting the policy while it still looks present.", "Remove 'unsafe-inline' and 'unsafe-eval'; use nonces or hashes for inline scripts."
if inline or evaluates:
culprit = "'unsafe-inline'" if inline else "'unsafe-eval'"
return "B", f"Present but weak - {culprit} punches a hole through the anti-XSS guarantee.", f"Remove {culprit}; use nonces or hashes for legitimate inline code."
if re.search(r"(^|\s)default-src\s", v, re.IGNORECASE) is None:
return "B", "Present with no default-src - resource types not listed explicitly fall back to the browser permissive default.", "Start the policy with default-src 'none' or 'self', then allow what you need."
return "A", "Strong - a default-src fallback with no unsafe-inline / unsafe-eval escape hatches.", BEST
def _grade_frame_options(v: str | None) -> tuple[str, str, str]:
if v is None:
return "C", "Missing - any site can embed this page in an iframe and overlay it (clickjacking).", "Add: x-frame-options: DENY (or SAMEORIGIN if you embed yourself)"
u = v.strip().upper()
if u in ("DENY", "SAMEORIGIN"):
return "A", f"Strong - {u} blocks framing by other origins.", BEST
if u.startswith("ALLOW-FROM"):
return "B", "ALLOW-FROM is deprecated and modern browsers ignore it - the page is effectively frameable.", "Replace with a CSP frame-ancestors directive (x-frame-options: DENY as fallback)."
return "B", f"Unrecognized value ({v}) - browsers ignore it, leaving the page frameable.", "Use DENY or SAMEORIGIN."
def _grade_content_type_options(v: str | None) -> tuple[str, str, str]:
if v is None:
return "C", "Missing - browsers may sniff uploaded content into executable types.", "Add: x-content-type-options: nosniff"
if v.strip().lower() == "nosniff":
return "A", "Strong - MIME sniffing is off; the declared Content-Type is final.", BEST
return "B", f"Present but the value ({v}) is not nosniff, so browsers ignore the header.", "Send exactly: x-content-type-options: nosniff"
def _grade_referrer_policy(v: str | None) -> tuple[str, str, str]:
if v is None:
return "C", "Missing - older browsers default to leaking the full URL to whatever site the user navigates to.", "Add: referrer-policy: strict-origin-when-cross-origin (or no-referrer)"
p = v.strip().lower()
if p == "unsafe-url":
return "F", "Actively harmful - unsafe-url sends the full URL (including IDs and tokens in query strings) to every destination, even on plain HTTP.", "Use strict-origin-when-cross-origin or no-referrer instead."
if p in REFERRER_STRICT:
return "A", f"Strong - {p} leaks at most the origin cross-origin.", BEST
if p in REFERRER_WEAK:
return "B", f"Present but leaky - {p} still shares the full URL in some same- or cross-origin cases.", "Tighten to strict-origin-when-cross-origin, strict-origin, same-origin, or no-referrer."
return "B", f"Unrecognized value ({v}) - browsers fall back to their default policy.", "Use one of the standard directives, e.g. strict-origin-when-cross-origin."
def _grade_permissions_policy(v: str | None) -> tuple[str, str, str]:
if v is None:
return "C", "Missing - powerful features (camera, geolocation, payment...) default to the browser policy, not yours.", "Add: permissions-policy: camera=(), microphone=(), geolocation=()"
p = re.sub(r"\s+", "", v).lower()
if p == "":
return "B", "Present but empty - no feature is restricted, so it declares nothing.", "List the features to switch off, e.g. camera=(), microphone=()."
if p == "*" or "=*" in p:
return "B", "Present but permissive - a =* wildcard re-allows the listed feature(s) everywhere.", "Use an empty allowlist () or a specific origin instead of *."
return "A", "Strong - the policy restricts at least one powerful feature.", BEST
def _grade_xss_protection(v: str | None) -> tuple[str, str, str]:
if v is None:
return "A", "Correctly omitted - the header is deprecated; modern browsers removed the XSS Auditor it drove.", "Nothing to change - rely on Content-Security-Policy instead."
t = v.strip()
if t == "0" or t.startswith("0;"):
return "A", "Explicitly disabled ('0') - the right call for a deprecated header old browsers still honor.", "Nothing to change - or remove the header entirely."
if t.startswith("1"):
return "B", "Deprecated - '1; mode=block' is ignored by modern browsers and the old Auditor had cross-site leaks of its own.", "Send '0' or drop the header; use Content-Security-Policy for XSS defense."
return "B", f"Present with an unrecognized value ({v}) - remove the deprecated header.", "Send '0' or drop the header entirely."
def _grade_coop(v: str | None) -> tuple[str, str, str]:
if v is None:
return "C", "Missing - pages that open or are opened by other origins share a browsing context with them.", "Add: cross-origin-opener-policy: same-origin"
p = v.strip().lower()
if p == "same-origin":
return "A", "Strong - the window handle is isolated from cross-origin openers.", BEST
if p == "same-origin-allow-popups":
return "B", "Partially isolated - popups you open keep a reference to this window.", "Use same-origin unless you genuinely need cross-origin popup handles."
if p == "unsafe-none":
return "B", "Explicit opt-out - unsafe-none restores the shared browsing context COOP exists to cut.", "Use same-origin unless a documented integration requires shared handles."
return "B", f"Unrecognized value ({v}) - browsers treat it as no COOP.", "Use same-origin."
# Compile-time-complete grader table: every catalog name has a grader.
GRADERS = {
"Strict-Transport-Security": _grade_hsts,
"Content-Security-Policy": _grade_csp,
"X-Frame-Options": _grade_frame_options,
"X-Content-Type-Options": _grade_content_type_options,
"Referrer-Policy": _grade_referrer_policy,
"Permissions-Policy": _grade_permissions_policy,
"X-XSS-Protection": _grade_xss_protection,
"Cross-Origin-Opener-Policy": _grade_coop,
}
def _overall_grade(score: int) -> str:
"""Map a weighted 0-100 score to the overall A/B/C/F grade."""
if score >= 90:
return "A"
if score >= 70:
return "B"
if score >= 45:
return "C"
return "F"
def analyze_headers(raw: str | None) -> HeaderAnalysis:
"""Analyze a raw HTTP response-header block.
Every catalog header gets a :class:`ParsedHeader` row (in catalog order);
the overall score is the weight-adjusted average of per-header grade
points, and recommendations list one fix per header that is not grade A.
"""
parsed = parse_headers(raw)
rows: list[tuple[ParsedHeader, float]] = []
for name, weight in SECURITY_HEADERS:
value = parsed.get(name.lower())
grade, explanation, recommendation = GRADERS[name](value)
rows.append((ParsedHeader(name=name, value=value, grade=grade, explanation=explanation, recommendation=recommendation), weight))
total_weight = sum(weight for _, weight in SECURITY_HEADERS)
# Math.round(x) === floor(x + 0.5) for the non-negative totals here.
score = int(math.floor(sum(GRADE_POINTS[row.grade] * weight for row, weight in rows) / total_weight + 0.5))
recommendations = [row.recommendation for row, _ in rows if row.grade != "A"]
return HeaderAnalysis(headers=[row for row, _ in rows], grade=_overall_grade(score), score=score, recommendations=recommendations)
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 →