Skip to content

Security Headers Analyzer — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! security-headers — HTTP response-header analysis and grading.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `security-headers` tool, ported from
//! src/lib/security-headers.ts (the canonical TypeScript implementation).
//!
//! Why this file exists: the analyzer is pure string work, so the exact logic
//! behind the web tool runs with zero dependencies. The TypeScript lib leans
//! on regex; std Rust has none, so the handful of patterns (`max-age=`,
//! `;includeSubDomains`, `'unsafe-inline'`, `default-src`) become small
//! hand-rolled scanners. Grades, explanations, weighted score, and the fix
//! list match the lib exactly; catalog blurbs are omitted for brevity.
//!
//! display source — part of CosmoDev's polyglot tool pages.

use std::collections::HashMap;

/// One security header as analyzed: the parsed value plus its grade and
/// guidance. `value` is `None` when the header is absent. Grades are "A"
/// (best practice), "B" (present but weak), "C" (missing or dangerous) and
/// "F" (actively harmful).
#[derive(Debug, Clone)]
pub struct ParsedHeader {
    pub name: String,
    pub value: Option<String>,
    pub grade: &'static str,
    pub explanation: String,
    pub recommendation: String,
}

/// The full analysis result: per-header rows, the overall grade, and fix list.
#[derive(Debug, Clone)]
pub struct HeaderAnalysis {
    pub headers: Vec<ParsedHeader>,
    pub grade: &'static str,
    pub score: u32, // 0-100 weighted average of per-header grade points
    pub recommendations: Vec<String>,
}

/// One year in seconds - the minimum HSTS max-age worth calling strong.
const ONE_YEAR: u64 = 31_536_000;

/// The "best practice met" recommendation shared by every grade-A verdict.
const BEST: &str = "Best practice met - nothing to change.";

const REFERRER_STRICT: &[&str] = &[
    "no-referrer",
    "same-origin",
    "strict-origin",
    "strict-origin-when-cross-origin",
];
const REFERRER_WEAK: &[&str] = &["origin", "origin-when-cross-origin", "no-referrer-when-downgrade"];

/// ASCII whitespace, the `\s` of the TS lib's regexes narrowed to what real
/// HTTP responses contain (SP / HTAB / CR / LF / FF / VT).
fn is_ws(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\r' | b'\n' | 0x0B | 0x0C)
}

/// Case-insensitive substring test - the role `/'x'/i.test(v)` plays in the TS lib.
fn contains_ci(hay: &str, needle: &str) -> bool {
    hay.to_lowercase().contains(&needle.to_lowercase())
}

/// Emulate the regex `max-age\s*=\s*(\d+)` (case-insensitive): try every
/// "max-age" occurrence, and return the first one followed by optional
/// whitespace, `=`, optional whitespace, and at least one ASCII digit.
fn find_max_age(value: &str) -> Option<u64> {
    let lower = value.to_lowercase();
    let bytes = lower.as_bytes();
    let mut from = 0usize;
    while let Some(rel) = lower[from..].find("max-age") {
        let mut i = from + rel + "max-age".len();
        while i < bytes.len() && is_ws(bytes[i]) {
            i += 1;
        }
        if i < bytes.len() && bytes[i] == b'=' {
            i += 1;
            while i < bytes.len() && is_ws(bytes[i]) {
                i += 1;
            }
            let start = i;
            while i < bytes.len() && bytes[i].is_ascii_digit() {
                i += 1;
            }
            if i > start {
                // Saturating fold so absurdly long digit runs still grade "A".
                let mut n: u64 = 0;
                for &b in &bytes[start..i] {
                    n = n.saturating_mul(10).saturating_add((b - b'0') as u64);
                }
                return Some(n);
            }
        }
        from += rel + 1; // regex backtracking: try the next occurrence
    }
    None
}

/// Emulate `;\s*<directive>` (case-insensitive): a semicolon, optional
/// whitespace, then the directive - e.g. `; includeSubDomains`.
fn has_folded_directive(value: &str, directive: &str) -> bool {
    let lower = value.to_lowercase();
    let needle = directive.to_lowercase();
    let bytes = lower.as_bytes();
    let mut from = 0usize;
    while let Some(rel) = lower[from..].find(';') {
        let mut i = from + rel + 1;
        while i < bytes.len() && is_ws(bytes[i]) {
            i += 1;
        }
        if lower[i..].starts_with(&needle) {
            return true;
        }
        from += rel + 1;
    }
    false
}

/// Emulate `(^|\s)default-src\s` (case-insensitive): the directive bounded by
/// whitespace (or the string edges) on both sides.
fn has_default_src(value: &str) -> bool {
    let lower = value.to_lowercase();
    let bytes = lower.as_bytes();
    let mut from = 0usize;
    while let Some(rel) = lower[from..].find("default-src") {
        let start = from + rel;
        let end = start + "default-src".len();
        if (start == 0 || is_ws(bytes[start - 1])) && end < bytes.len() && is_ws(bytes[end]) {
            return true;
        }
        from = start + 1;
    }
    false
}

/// Parse a raw header block into a lowercased-name map. Lines are
/// `name: value`; the `HTTP/1.1 200 OK` status line and any line without a
/// colon are ignored. A line starting with whitespace continues the previous
/// header (RFC 7230 obs-fold); a repeated name joins its values with ", ".
pub fn parse_headers(raw: &str) -> HashMap<String, String> {
    let mut headers: HashMap<String, String> = HashMap::new();
    let mut last_name: Option<String> = None;
    for line in raw.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)) {
        if line.starts_with(is_ws_char) {
            // Folded continuation - append to the previous header, if any.
            if let Some(name) = &last_name {
                let folded = format!("{} {}", headers.get(name).map(String::as_str).unwrap_or(""), line.trim());
                headers.insert(name.clone(), folded.trim().to_string());
            }
            continue;
        }
        let colon = match line.find(':') {
            Some(i) => i,
            None => continue, // status line, blank line, or junk
        };
        let name = line[..colon].trim().to_lowercase();
        if name.is_empty() {
            continue;
        }
        let value = line[colon + 1..].trim();
        let joined = match headers.get(&name) {
            Some(prev) => format!("{prev}, {value}"),
            None => value.to_string(),
        };
        headers.insert(name.clone(), joined);
        last_name = Some(name);
    }
    headers
}

/// `char::is_whitespace`, matching JS `\s` closely (see go.go's note).
fn is_ws_char(c: char) -> bool {
    c.is_whitespace()
}

/// The verdict every grader returns: (grade, explanation, recommendation).
type Grading = (&'static str, String, String);
type Grader = fn(Option<&str>) -> Grading;

fn grade_hsts(value: Option<&str>) -> Grading {
    let Some(v) = value else {
        return ("C", "Missing - the browser accepts plain HTTP, so the first visit (and SSL-strip attacks) can downgrade the connection.".into(), "Add: strict-transport-security: max-age=31536000; includeSubDomains; preload".into());
    };
    let max_age = match find_max_age(v) {
        None => {
            return ("B", format!("Present but malformed - no readable max-age directive ({v})."), "Use: strict-transport-security: max-age=31536000; includeSubDomains".into());
        }
        Some(0) => {
            return ("F", "max-age=0 actively deletes the HSTS policy - the site opts out of HTTPS-only enforcement.".into(), "Raise max-age to at least 31536000 (one year).".into());
        }
        Some(n) => n,
    };
    let subs = has_folded_directive(v, "includesubdomains");
    if max_age < ONE_YEAR {
        let extra = if subs { " and includeSubDomains" } else { "" };
        return ("B", format!("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.".into());
    }
    if !subs {
        return ("B", "Strong max-age (>= 1 year), but includeSubDomains is missing - subdomains stay downgradable.".into(), "Append ; includeSubDomains once every subdomain serves HTTPS.".into());
    }
    let tail = if has_folded_directive(v, "preload") {
        " + preload - eligible for the browser preload list."
    } else {
        ". Add preload to join the browser preload list."
    };
    ("A", format!("Strong: max-age >= 1 year + includeSubDomains{tail}"), BEST.into())
}

fn grade_csp(value: Option<&str>) -> Grading {
    let Some(v) = value else {
        return ("C", "Missing - no restriction on where scripts and resources load from, so injected markup runs at full power.".into(), "Add a policy, e.g.: content-security-policy: default-src 'none'; script-src 'self'; ...".into());
    };
    let inline = contains_ci(v, "'unsafe-inline'");
    let evaluates = contains_ci(v, "'unsafe-eval'");
    if inline && 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.".into(), "Remove 'unsafe-inline' and 'unsafe-eval'; use nonces or hashes for inline scripts.".into());
    }
    if inline || evaluates {
        let culprit = if inline { "'unsafe-inline'" } else { "'unsafe-eval'" };
        return ("B", format!("Present but weak - {culprit} punches a hole through the anti-XSS guarantee."), format!("Remove {culprit}; use nonces or hashes for legitimate inline code."));
    }
    if !has_default_src(v) {
        return ("B", "Present with no default-src - resource types not listed explicitly fall back to the browser permissive default.".into(), "Start the policy with default-src 'none' or 'self', then allow what you need.".into());
    }
    ("A", "Strong - a default-src fallback with no unsafe-inline / unsafe-eval escape hatches.".into(), BEST.into())
}

fn grade_frame_options(value: Option<&str>) -> Grading {
    let Some(v) = value else {
        return ("C", "Missing - any site can embed this page in an iframe and overlay it (clickjacking).".into(), "Add: x-frame-options: DENY (or SAMEORIGIN if you embed yourself)".into());
    };
    let u = v.trim().to_uppercase();
    if u == "DENY" || u == "SAMEORIGIN" {
        return ("A", format!("Strong - {u} blocks framing by other origins."), BEST.into());
    }
    if u.starts_with("ALLOW-FROM") {
        return ("B", "ALLOW-FROM is deprecated and modern browsers ignore it - the page is effectively frameable.".into(), "Replace with a CSP frame-ancestors directive (x-frame-options: DENY as fallback).".into());
    }
    ("B", format!("Unrecognized value ({v}) - browsers ignore it, leaving the page frameable."), "Use DENY or SAMEORIGIN.".into())
}

fn grade_content_type_options(value: Option<&str>) -> Grading {
    let Some(v) = value else {
        return ("C", "Missing - browsers may sniff uploaded content into executable types.".into(), "Add: x-content-type-options: nosniff".into());
    };
    if v.trim().to_lowercase() == "nosniff" {
        return ("A", "Strong - MIME sniffing is off; the declared Content-Type is final.".into(), BEST.into());
    }
    ("B", format!("Present but the value ({v}) is not nosniff, so browsers ignore the header."), "Send exactly: x-content-type-options: nosniff".into())
}

fn grade_referrer_policy(value: Option<&str>) -> Grading {
    let Some(v) = value else {
        return ("C", "Missing - older browsers default to leaking the full URL to whatever site the user navigates to.".into(), "Add: referrer-policy: strict-origin-when-cross-origin (or no-referrer)".into());
    };
    let p = v.trim().to_lowercase();
    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.".into(), "Use strict-origin-when-cross-origin or no-referrer instead.".into());
    }
    if REFERRER_STRICT.contains(&p.as_str()) {
        return ("A", format!("Strong - {p} leaks at most the origin cross-origin."), BEST.into());
    }
    if REFERRER_WEAK.contains(&p.as_str()) {
        return ("B", format!("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.".into());
    }
    ("B", format!("Unrecognized value ({v}) - browsers fall back to their default policy."), "Use one of the standard directives, e.g. strict-origin-when-cross-origin.".into())
}

fn grade_permissions_policy(value: Option<&str>) -> Grading {
    let Some(v) = value else {
        return ("C", "Missing - powerful features (camera, geolocation, payment...) default to the browser policy, not yours.".into(), "Add: permissions-policy: camera=(), microphone=(), geolocation=()".into());
    };
    // value.replace(/\s+/g, '').toLowerCase()
    let p: String = v.chars().filter(|c| !c.is_whitespace()).collect();
    if p.is_empty() {
        return ("B", "Present but empty - no feature is restricted, so it declares nothing.".into(), "List the features to switch off, e.g. camera=(), microphone=().".into());
    }
    let p = p.to_lowercase();
    if p == "*" || p.contains("=*") {
        return ("B", "Present but permissive - a =* wildcard re-allows the listed feature(s) everywhere.".into(), "Use an empty allowlist () or a specific origin instead of *.".into());
    }
    ("A", "Strong - the policy restricts at least one powerful feature.".into(), BEST.into())
}

fn grade_xss_protection(value: Option<&str>) -> Grading {
    let Some(v) = value else {
        return ("A", "Correctly omitted - the header is deprecated; modern browsers removed the XSS Auditor it drove.".into(), "Nothing to change - rely on Content-Security-Policy instead.".into());
    };
    let t = v.trim();
    if t == "0" || t.starts_with("0;") {
        return ("A", "Explicitly disabled ('0') - the right call for a deprecated header old browsers still honor.".into(), "Nothing to change - or remove the header entirely.".into());
    }
    if t.starts_with('1') {
        return ("B", "Deprecated - '1; mode=block' is ignored by modern browsers and the old Auditor had cross-site leaks of its own.".into(), "Send '0' or drop the header; use Content-Security-Policy for XSS defense.".into());
    }
    ("B", format!("Present with an unrecognized value ({v}) - remove the deprecated header."), "Send '0' or drop the header entirely.".into())
}

fn grade_coop(value: Option<&str>) -> Grading {
    let Some(v) = value else {
        return ("C", "Missing - pages that open or are opened by other origins share a browsing context with them.".into(), "Add: cross-origin-opener-policy: same-origin".into());
    };
    match v.trim().to_lowercase().as_str() {
        "same-origin" => ("A", "Strong - the window handle is isolated from cross-origin openers.".into(), BEST.into()),
        "same-origin-allow-popups" => ("B", "Partially isolated - popups you open keep a reference to this window.".into(), "Use same-origin unless you genuinely need cross-origin popup handles.".into()),
        "unsafe-none" => ("B", "Explicit opt-out - unsafe-none restores the shared browsing context COOP exists to cut.".into(), "Use same-origin unless a documented integration requires shared handles.".into()),
        _ => ("B", format!("Unrecognized value ({v}) - browsers treat it as no COOP."), "Use same-origin.".into()),
    }
}

/// Grade points used for the weighted overall score.
fn grade_points(grade: &str) -> f64 {
    match grade {
        "A" => 100.0,
        "B" => 70.0,
        "C" => 40.0,
        _ => 0.0, // "F"
    }
}

/// Map a weighted 0-100 score to the overall A/B/C/F grade.
fn overall_grade(score: u32) -> &'static str {
    if score >= 90 {
        "A"
    } else if score >= 70 {
        "B"
    } else if score >= 45 {
        "C"
    } else {
        "F"
    }
}

/// The 8 graded headers with their score weight and grader, in display order.
/// Catalog descriptions live in src/lib/security-headers.ts.
const SECURITY_HEADERS: &[(&str, f64, Grader)] = &[
    ("Strict-Transport-Security", 1.5, grade_hsts),
    ("Content-Security-Policy", 2.0, grade_csp),
    ("X-Frame-Options", 1.0, grade_frame_options),
    ("X-Content-Type-Options", 1.0, grade_content_type_options),
    ("Referrer-Policy", 1.0, grade_referrer_policy),
    ("Permissions-Policy", 1.0, grade_permissions_policy),
    ("X-XSS-Protection", 0.5, grade_xss_protection),
    ("Cross-Origin-Opener-Policy", 1.0, grade_coop),
];

/// Analyze a raw HTTP response-header block. Every catalog header gets a
/// `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.
pub fn analyze_headers(raw: &str) -> HeaderAnalysis {
    let parsed = parse_headers(raw);
    let mut headers = Vec::new();
    let mut weighted = 0.0f64;
    for (name, weight, grader) in SECURITY_HEADERS {
        let value = parsed.get(&name.to_lowercase()).map(String::as_str);
        let (grade, explanation, recommendation) = grader(value);
        weighted += grade_points(grade) * weight;
        headers.push(ParsedHeader {
            name: (*name).to_string(),
            value: value.map(str::to_string),
            grade,
            explanation,
            recommendation,
        });
    }
    let total: f64 = SECURITY_HEADERS.iter().map(|(_, w, _)| w).sum();
    // Math.round(x) === floor(x + 0.5) for the non-negative totals here.
    let score = (weighted / total + 0.5).floor() as u32;
    let recommendations: Vec<String> = headers
        .iter()
        .filter(|h| h.grade != "A")
        .map(|h| h.recommendation.clone())
        .collect();
    HeaderAnalysis {
        headers,
        grade: overall_grade(score),
        score,
        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 →