Skip to content

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

// Package securityheaders is the Go twin of CosmoDev's
// src/lib/security-headers.ts (dual source: the web lib is TypeScript, the CLI
// lib is Go — kept in lock-step). Pure + deterministic, never panics. The
// table-driven tests in security_headers_test.go share vectors with
// src/lib/security-headers.test.ts so the two implementations are held to the
// same contract.
//
// It parses a raw response-header block (the "key: value" lines copied from
// DevTools' Network panel), grades each of 8 security headers A/B/C/F, and
// rolls a weighted overall score. Header names match case-insensitively,
// folded (indented) continuation lines join their parent value, and duplicate
// names join with ", ". Malformed lines and the HTTP status line are ignored.
package securityheaders

import (
	"math"
	"regexp"
	"slices"
	"strconv"
	"strings"
	"unicode"
	"unicode/utf8"
)

// Grade is a per-header grade: A best practice, B present but weak,
// C missing or dangerous, F actively harmful. Mirrors HeaderGrade in the TS lib.
type Grade string

const (
	GradeA Grade = "A"
	GradeB Grade = "B"
	GradeC Grade = "C"
	GradeF Grade = "F"
)

// ParsedHeader is one security header as analyzed: the parsed value plus its
// grade and guidance. Value is nil when the header is absent (TS: string | null).
type ParsedHeader struct {
	Name           string // canonical name, e.g. "Strict-Transport-Security"
	Value          *string // raw value as parsed; nil when the header is absent
	Grade          Grade
	Explanation    string
	Recommendation string
}

// HeaderAnalysis is the full analysis result: per-header rows, the overall
// grade, and fix list. Mirrors HeaderAnalysis in the TS lib.
type HeaderAnalysis struct {
	Headers         []ParsedHeader
	Grade           Grade
	Score           int // 0-100 weighted average of per-header grades
	Recommendations []string
}

// HeaderSpec is a catalog entry: canonical name, why the header matters, and
// its score weight. Mirrors HeaderSpec in the TS lib.
type HeaderSpec struct {
	Name        string
	Description string
	Weight      float64
}

// SecurityHeaders is the 8 security headers this analyzer grades, in display
// order. Mirrors SECURITY_HEADERS in the TS lib.
var SecurityHeaders = []HeaderSpec{
	{
		Name: "Strict-Transport-Security",
		Description: "HSTS tells the browser 'only ever reach this site over HTTPS' for max-age seconds. It defeats SSL-strip attacks, which downgrade the very first plain-HTTP visit. includeSubDomains extends the guarantee to every subdomain; preload lets the site join the browser-built HSTS preload list so even the first visit is HTTPS.",
		Weight: 1.5,
	},
	{
		Name: "Content-Security-Policy",
		Description: "CSP is the strongest anti-XSS control available in a header: it declares which sources scripts, styles, and other resources may load from. 'unsafe-inline' and 'unsafe-eval' punch holes straight through it - they re-allow inline injection and string-to-code evaluation. A default-src directive is the baseline so resource types you forgot to list inherit a restrictive fallback instead of the browser's permissive one.",
		Weight: 2,
	},
	{
		Name: "X-Frame-Options",
		Description: "Stops other sites from embedding this page in an iframe, which is the basis of clickjacking: an attacker overlays invisible UI on your framed page and harvests the victim's clicks. DENY blocks all framing; SAMEORIGIN allows only your own origin. The modern replacement is the CSP frame-ancestors directive.",
		Weight: 1,
	},
	{
		Name: "X-Content-Type-Options",
		Description: "With the value nosniff, the browser must respect the declared Content-Type instead of 'helpfully' sniffing the payload. Sniffing turns an uploaded text file into executable JavaScript when its bytes look script-shaped - the classic content-type-confusion attack.",
		Weight: 1,
	},
	{
		Name: "Referrer-Policy",
		Description: "Controls how much of the URL the browser leaks in the Referer header when the user navigates to another site. Full URLs can carry IDs, tokens, or search queries to third parties. strict-origin-when-cross-origin sends only the origin cross-origin (the browser default since 2020); no-referrer and same-origin leak even less. unsafe-url sends the full URL everywhere, including on plain-HTTP requests.",
		Weight: 1,
	},
	{
		Name: "Permissions-Policy",
		Description: "Declares which browser features (camera, microphone, geolocation, payment, USB...) the page and its embedded iframes may use. An empty allowlist - feature=() - switches the feature off entirely; an =* wildcard re-allows it everywhere, defeating the point of declaring it.",
		Weight: 1,
	},
	{
		Name: "X-XSS-Protection",
		Description: "The 2010-era XSS Auditor: browsers inspected reflected input in the page and blocked obviously injected scripts. Chrome removed it in 2019 (its heuristics introduced cross-site leaks of their own) and every modern browser now ignores it. The header is deprecated - CSP is the real defense. Sites either omit it or send '0' to switch old browsers off.",
		Weight: 0.5,
	},
	{
		Name: "Cross-Origin-Opener-Policy",
		Description: "Isolates the page's window handle from other origins. Without COOP, a site that opened your page in a popup (or was opened by it) keeps a JS reference to it, enabling some cross-window attacks and Spectre-class side channels. same-origin cuts that shared handle; unsafe-none restores the old shared browsing context.",
		Weight: 1,
	},
}

// gradePoints maps a grade to the points used for the weighted overall score.
// Mirrors GRADE_POINTS in the TS lib.
var gradePoints = map[Grade]float64{GradeA: 100, GradeB: 70, GradeC: 40, GradeF: 0}

// oneYear is one year in seconds - the minimum HSTS max-age worth calling
// strong. Mirrors ONE_YEAR in the TS lib.
const oneYear uint64 = 31536000

var (
	maxAgeRe       = regexp.MustCompile(`(?i)max-age\s*=\s*(\d+)`)
	includeSubsRe  = regexp.MustCompile(`(?i);\s*includesubdomains`)
	preloadRe      = regexp.MustCompile(`(?i);\s*preload`)
	unsafeInlineRe = regexp.MustCompile(`(?i)'unsafe-inline'`)
	unsafeEvalRe   = regexp.MustCompile(`(?i)'unsafe-eval'`)
	defaultSrcRe   = regexp.MustCompile(`(?i)(^|\s)default-src\s`)
	whitespaceRe   = regexp.MustCompile(`\s+`)
	newlineRe      = regexp.MustCompile(`\r?\n`)
)

// isFolded reports whether line begins with whitespace (RFC 7230 obs-fold
// continuation). Mirrors the /^\s/.test(line) check in the TS lib.
func isFolded(line string) bool {
	r, size := utf8.DecodeRuneInString(line)
	return size > 0 && unicode.IsSpace(r)
}

// ParseHeaders parses 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 space/tab continues the previous
// header (RFC 7230 obs-fold); a repeated name joins its values with ", ".
// It mirrors parseHeaders() in the TS lib. The TS lib also tolerates a null
// raw; the Go zero value ("") yields the same empty map.
func ParseHeaders(raw string) map[string]string {
	headers := make(map[string]string)
	lastName := ""
	for _, line := range newlineRe.Split(raw, -1) {
		if isFolded(line) {
			// Folded continuation - append to the previous header, if any.
			if lastName != "" {
				prev := headers[lastName]
				headers[lastName] = strings.TrimSpace(prev + " " + strings.TrimSpace(line))
			}
			continue
		}
		name, value, found := strings.Cut(line, ":")
		if !found {
			continue // status line, blank line, or junk
		}
		name = strings.ToLower(strings.TrimSpace(name))
		if name == "" {
			continue
		}
		value = strings.TrimSpace(value)
		if prev, ok := headers[name]; ok {
			headers[name] = prev + ", " + value
		} else {
			headers[name] = value
		}
		lastName = name
	}
	return headers
}

// --- Per-header graders: value (nil when absent) -> grade + guidance ---

// grading holds the verdict fields every grader returns; folded into
// ParsedHeader. Mirrors the Grading interface in the TS lib.
type grading struct {
	grade          Grade
	explanation    string
	recommendation string
}

// parseMaxAge converts a matched digit run to a number. Runs beyond uint64
// range clamp to the maximum, which mirrors the TS lib's Number() giving a
// huge value: both then compare >= oneYear. Never panics.
func parseMaxAge(digits string) uint64 {
	n, err := strconv.ParseUint(digits, 10, 64)
	if err != nil {
		return math.MaxUint64
	}
	return n
}

func gradeHSTS(value *string) grading {
	if value == nil {
		return grading{GradeC,
			"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 := maxAgeRe.FindStringSubmatch(*value)
	if m == nil {
		return grading{GradeB,
			"Present but malformed - no readable max-age directive (" + *value + ").",
			"Use: strict-transport-security: max-age=31536000; includeSubDomains"}
	}
	maxAge := parseMaxAge(m[1])
	if maxAge == 0 {
		return grading{GradeF,
			"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)."}
	}
	hasSubs := includeSubsRe.MatchString(*value)
	if maxAge < oneYear {
		subs := ""
		if hasSubs {
			subs = " and includeSubDomains"
		}
		return grading{GradeB,
			"Present with max-age=" + strconv.FormatUint(maxAge, 10) + "s (< 1 year)" + subs + " - a shorter window weakens the guarantee.",
			"Raise max-age to 31536000 (one year) or more."}
	}
	if !hasSubs {
		return grading{GradeB,
			"Strong max-age (>= 1 year), but includeSubDomains is missing - subdomains stay downgradable.",
			"Append ; includeSubDomains once every subdomain serves HTTPS."}
	}
	hasPreload := preloadRe.MatchString(*value)
	suffix := ". Add preload to join the browser preload list."
	if hasPreload {
		suffix = " + preload - eligible for the browser preload list."
	}
	return grading{GradeA,
		"Strong: max-age >= 1 year + includeSubDomains" + suffix,
		"Best practice met - nothing to change."}
}

func gradeCSP(value *string) grading {
	if value == nil {
		return grading{GradeC,
			"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 := unsafeInlineRe.MatchString(*value)
	evaluates := unsafeEvalRe.MatchString(*value)
	if inline && evaluates {
		return grading{GradeF,
			"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 || evaluates {
		culprit := "'unsafe-eval'"
		if inline {
			culprit = "'unsafe-inline'"
		}
		return grading{GradeB,
			"Present but weak - " + culprit + " punches a hole through the anti-XSS guarantee.",
			"Remove " + culprit + "; use nonces or hashes for legitimate inline code."}
	}
	if !defaultSrcRe.MatchString(*value) {
		return grading{GradeB,
			"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 grading{GradeA,
		"Strong - a default-src fallback with no unsafe-inline / unsafe-eval escape hatches.",
		"Best practice met - nothing to change."}
}

func gradeFrameOptions(value *string) grading {
	if value == nil {
		return grading{GradeC,
			"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)"}
	}
	v := strings.ToUpper(strings.TrimSpace(*value))
	if v == "DENY" || v == "SAMEORIGIN" {
		return grading{GradeA,
			"Strong - " + v + " blocks framing by other origins.",
			"Best practice met - nothing to change."}
	}
	if strings.HasPrefix(v, "ALLOW-FROM") {
		return grading{GradeB,
			"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 grading{GradeB,
		"Unrecognized value (" + *value + ") - browsers ignore it, leaving the page frameable.",
		"Use DENY or SAMEORIGIN."}
}

func gradeContentTypeOptions(value *string) grading {
	if value == nil {
		return grading{GradeC,
			"Missing - browsers may sniff uploaded content into executable types.",
			"Add: x-content-type-options: nosniff"}
	}
	if strings.ToLower(strings.TrimSpace(*value)) == "nosniff" {
		return grading{GradeA,
			"Strong - MIME sniffing is off; the declared Content-Type is final.",
			"Best practice met - nothing to change."}
	}
	return grading{GradeB,
		"Present but the value (" + *value + ") is not nosniff, so browsers ignore the header.",
		"Send exactly: x-content-type-options: nosniff"}
}

var referrerStrict = []string{"no-referrer", "same-origin", "strict-origin", "strict-origin-when-cross-origin"}
var referrerWeak = []string{"origin", "origin-when-cross-origin", "no-referrer-when-downgrade"}

func gradeReferrerPolicy(value *string) grading {
	if value == nil {
		return grading{GradeC,
			"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)"}
	}
	v := strings.ToLower(strings.TrimSpace(*value))
	if v == "unsafe-url" {
		return grading{GradeF,
			"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 slices.Contains(referrerStrict, v) {
		return grading{GradeA,
			"Strong - " + v + " leaks at most the origin cross-origin.",
			"Best practice met - nothing to change."}
	}
	if slices.Contains(referrerWeak, v) {
		return grading{GradeB,
			"Present but leaky - " + v + " 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 grading{GradeB,
		"Unrecognized value (" + *value + ") - browsers fall back to their default policy.",
		"Use one of the standard directives, e.g. strict-origin-when-cross-origin."}
}

func gradePermissionsPolicy(value *string) grading {
	if value == nil {
		return grading{GradeC,
			"Missing - powerful features (camera, geolocation, payment...) default to the browser policy, not yours.",
			"Add: permissions-policy: camera=(), microphone=(), geolocation=()"}
	}
	v := strings.ToLower(whitespaceRe.ReplaceAllString(*value, ""))
	if v == "" {
		return grading{GradeB,
			"Present but empty - no feature is restricted, so it declares nothing.",
			"List the features to switch off, e.g. camera=(), microphone=()."}
	}
	if v == "*" || strings.Contains(v, "=*") {
		return grading{GradeB,
			"Present but permissive - a =* wildcard re-allows the listed feature(s) everywhere.",
			"Use an empty allowlist () or a specific origin instead of *."}
	}
	return grading{GradeA,
		"Strong - the policy restricts at least one powerful feature.",
		"Best practice met - nothing to change."}
}

func gradeXSSProtection(value *string) grading {
	if value == nil {
		return grading{GradeA,
			"Correctly omitted - the header is deprecated; modern browsers removed the XSS Auditor it drove.",
			"Nothing to change - rely on Content-Security-Policy instead."}
	}
	v := strings.TrimSpace(*value)
	if v == "0" || strings.HasPrefix(v, "0;") {
		return grading{GradeA,
			"Explicitly disabled ('0') - the right call for a deprecated header old browsers still honor.",
			"Nothing to change - or remove the header entirely."}
	}
	if strings.HasPrefix(v, "1") {
		return grading{GradeB,
			"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 grading{GradeB,
		"Present with an unrecognized value (" + *value + ") - remove the deprecated header.",
		"Send '0' or drop the header entirely."}
}

func gradeCOOP(value *string) grading {
	if value == nil {
		return grading{GradeC,
			"Missing - pages that open or are opened by other origins share a browsing context with them.",
			"Add: cross-origin-opener-policy: same-origin"}
	}
	v := strings.ToLower(strings.TrimSpace(*value))
	if v == "same-origin" {
		return grading{GradeA,
			"Strong - the window handle is isolated from cross-origin openers.",
			"Best practice met - nothing to change."}
	}
	if v == "same-origin-allow-popups" {
		return grading{GradeB,
			"Partially isolated - popups you open keep a reference to this window.",
			"Use same-origin unless you genuinely need cross-origin popup handles."}
	}
	if v == "unsafe-none" {
		return grading{GradeB,
			"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 grading{GradeB,
		"Unrecognized value (" + *value + ") - browsers treat it as no COOP.",
		"Use same-origin."}
}

// graders maps every catalog name to its grader. The TS lib gets
// compile-time completeness via Record<SecurityHeaderName, ...>; here the
// catalog tests keep the table honest.
var graders = map[string]func(*string) grading{
	"Strict-Transport-Security":  gradeHSTS,
	"Content-Security-Policy":    gradeCSP,
	"X-Frame-Options":            gradeFrameOptions,
	"X-Content-Type-Options":     gradeContentTypeOptions,
	"Referrer-Policy":            gradeReferrerPolicy,
	"Permissions-Policy":         gradePermissionsPolicy,
	"X-XSS-Protection":           gradeXSSProtection,
	"Cross-Origin-Opener-Policy": gradeCOOP,
}

// overallGrade maps a weighted 0-100 score to the overall A/B/C/F grade.
// Mirrors overallGrade() in the TS lib.
func overallGrade(score int) Grade {
	switch {
	case score >= 90:
		return GradeA
	case score >= 70:
		return GradeB
	case score >= 45:
		return GradeC
	}
	return GradeF
}

// AnalyzeHeaders analyzes 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 at grade A. It mirrors analyzeHeaders() in
// the TS lib.
func AnalyzeHeaders(raw string) HeaderAnalysis {
	parsed := ParseHeaders(raw)
	headers := make([]ParsedHeader, 0, len(SecurityHeaders))
	var totalWeight, sum float64
	for _, spec := range SecurityHeaders {
		var value *string
		if v, ok := parsed[strings.ToLower(spec.Name)]; ok {
			v := v
			value = &v
		}
		g := graders[spec.Name](value)
		headers = append(headers, ParsedHeader{
			Name:           spec.Name,
			Value:          value,
			Grade:          g.grade,
			Explanation:    g.explanation,
			Recommendation: g.recommendation,
		})
		totalWeight += spec.Weight
		sum += gradePoints[g.grade] * spec.Weight
	}
	score := int(math.Round(sum / totalWeight))
	var recommendations []string
	for _, h := range headers {
		if h.Grade != GradeA {
			recommendations = append(recommendations, h.Recommendation)
		}
	}
	return HeaderAnalysis{
		Headers:         headers,
		Grade:           overallGrade(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 →