# Changelog

All notable changes to **securityheaders-tester** are documented in this file.
Format: [Keep a Changelog](https://keepachangelog.com/).

## [Unreleased]

### Changed

- **RATE-001 — local rate-limit escape hatch**: `BT_RATE_LIMIT` env in
  `config.rs` — `off`/`0` lifts every AbuseGuard budget (per-IP/UA/target/
  global), a number sets the per-IP budget (handy to reproduce a 429 fast).
  Compiled **only into debug builds** (`#[cfg(debug_assertions)]`): release
  binaries get an empty stub, so production can never run unlimited by
  touching an env var. Local Makefile targets (`up`, `up-template`,
  `watch-server`) default it to `off` — override with
  `make up BT_RATE_LIMIT=30`.

### Security

- **RECUR-001 — self-check guard**: `contract::guard_self_target()` rejects a
  target that is *this service's own host* with `400 {"error":"self_target",
  "retry":"never"}` **before** any outbound fetch — wired on the API route, the
  recognized-consumer channel and the web route. Configured by `BT_SELF_HOSTS`
  (comma-separated own hosts; empty = guard inert) with `BT_ALLOW_SELF_CHECK=1`
  as the local opt-out. Sibling `*.btoven.net` hosts stay fetchable — the fleet
  checks each other for dogfooding and public examples (decision 2026-11-15).
- **SSRF-001 (MCP/FEEDBACK §B9)**: `contract::guard_target()` is now wired on
  every outbound route — RFC1918/loopback/link-local/metadata targets are
  rejected with `400 private_target` before the fetch.

### Fixed

- **OOM-001 — shared-cache L2 slots**: the single-flight map is capped at
  4 096 slots with idle-slot purge, so a flood of distinct URLs can no longer
  grow `l2` without bound; past the cap a key runs without a local slot (it
  loses local dedup, never memory) and the Redis single-flight still covers
  the real fetch.
- **OOM-003 — rate-limiter ceilings**: `windows` (65 536) and `bans` (16 384)
  get hard caps with batch eviction of the least-recently-active 10%, so a
  distributed flood of UA/target keys can no longer grow the maps until OOM.
  Bans reuse the grouped window material (one IPv6 ban covers a /64).
- **OOM — cache `key_fifo`**: an entry evicted under the write-lock now also
  leaves `key_fifo`, so `sweep()` can no longer stall on an orphaned key.

### Changed

- **Shared theme**: the landing now uses the shared `theme.css`/`theme.js`
  primitives (TEMPLATE-001/003) from `index.hbs`; the local styles were removed
  in favour of them.
- **RUNBOOK**: new *Secret rotation* section for `BTOVEN_TRUST_TOKEN`
  (TRUST-004/TRUST-005) — receiver-first / emitter-last order with
  `*_PREVIOUS` dual-accept for zero-downtime rotation.

## [0.4.3] — 2026-11-14

### Added

- **Failed-trust gate (TRUST-003 hardening)**: invalid `X-BTOVEN-Trust`
  attempts on `/api/consumer/lookup` get their own limiter — after
  `TRUST_FAIL_MAX` (5) failures per client inside a 5-minute window the next
  one flips from `400` to `429` + `Retry-After`. The VALID token is checked
  first, so a legitimate consumer can never be locked out. Client keys are
  log-safe tokens (`trust:<8-hex>`, FNV-1a of the forwarded address) — raw
  IPs never reach logs. (Wiring + tests: consumer gate in `routes.rs`,
  integration test flipping 400→429.)
- **Zero-downtime rotation (TRUST-005)**: `trust_token_valid` also accepts
  `BTOVEN_TRUST_TOKEN_PREVIOUS` during a rotation window — set previous,
  update current, then drop previous (emitter switches in between).
- **Per-project ban ladder (TRUST-003 escalation)**: sustained abuse of the
  consumer budget no longer just re-429s per call — after 3 consecutive
  exhausted windows the CONSUMER itself is banned on a wider ladder
  (10m → 1h → 6h), escalating on reincidence and forgetting old grudges
  after a long silence. The ban IS the wide rate limit for the project.

### Fixed

- `profile.rs` test: removed a trailing `|| true` that made the
  protocol-relative-origin assertion vacuous (clippy deny-by-default).
- **README**: configuration table now lists only env vars the code reads
  (`PORT`, `LANDING_CACHE_MAX_AGE`, `BTOVEN_TRUST_TOKEN`) and documents the
  real, fixed rate limits (REFACTOR-001) — `BIND_*`/`RATE_LIMIT_*` were
  never read by anything.

## [0.4.2] — 2026-11-14

### Added

- **Consumer channel — TRUST-001 (option A)**: `GET /api/consumer/lookup`,
  the recognized-consumer variant of `/api/lookup` for BTOVEN's own services.
  Requires `X-BTOVEN-Trust` (shared secret from env `BTOVEN_TRUST_TOKEN`,
  constant-time content comparison) + `X-BTOVEN-Consumer` (canonical
  transparency signature), runs on its own **600/h per-consumer budget**
  (new `consumer.rs`, path exempt from the shared guard in `config.rs` — the
  public route's limits are untouched), and returns the exact same stamped
  payload. Unit tests cover token matching, budget/rollover/eviction and
  per-consumer isolation. Documented in `llms.txt` ("Consumer channel").

### Changed

- **Initiator chain in the User-Agent (TRUST-001)**: when a check runs on
  behalf of another BTOVEN product, `fetch_on_behalf_of` appends that
  product's canonical signature to ours — e.g.
  `BTOVEN-SecurityHeaders/1.0 (+…) BTOVEN-AdBlock/1.0 (+…)` — so third-party
  logs can attribute the request responsibly. Suffixes are sanitized
  (printable ASCII, ≤256 chars; invalid → declaration dropped), covered by
  tests. `get_security`/`get_security_cached` now thread
  `consumer: Option<&str>` (initiator-agnostic results → shared cache still
  valid across consumers).

## [0.4.1] — 2026-11-14

### Changed

- **User-Agent (UA-001)**: outbound fetches now carry the canonical transparency
  signature `BTOVEN-SecurityHeaders/1.0 (+https://btoven.net/transparency/securityheaders)`
  — format `BTOVEN-<Service>/<version> (+<stable URL>)` per the registry at
  btoven.net/transparency — replacing `securityheaders/<version> (<host>)`. The
  `USER_AGENT_URL` env override is gone: the signature is fixed and registered.

## [0.4.0] — 2026-10-30

### Added (round 10 — MCP consumer contract, `MCP/FEEDBACK.md` §B)

- **Canonical `GET /health` (B1)**: `{status, version, commit, schema_version,
  engine, contract_version, polarity}`. `commit` comes from `GIT_COMMIT`
  (exported by the Makefile, passed as `ARG` by the Dockerfile) — `unknown`
  when the build had no sha.
- **Identity on every JSON response (B2)**: `/api/lookup` stamps
  `contract_version` and `polarity` when they are absent; the `ApiResult`'s own
  `schema_version` and `engine` are **never overwritten** (they stay at v2 and
  `securityheaders/0.4.0`).
- **Polarity (B4)**: `polarity.absence_means = "pass"` over
  `errors`/`issues`, on top of the per-header `negative` flag the engine already
  had.
- **Error envelope (B3)**: the `400`s of `/api/lookup` move from plain text to
  `{error, message, retry, retry_after_s?, contract_version}`; the abuse-guard
  `429` adds `retry_after_s` + `retry` (keeping `retry_after_secs` as a
  deprecated alias) and still sends the `Retry-After` header.
- **Privacy (B5/B11)**: `llms.txt` documents the contract, privacy (no query
  persistence) and acceptable use; the invalid cache-key warning no longer
  writes the URL, only its length.
- `server/src/contract.rs` shared with the eight testers (audit06
  `shared_identical` group, drift 8/8) plus `config::API_META`.
- **Verification pending** (`CONTRACT-002`): this session did not build — run
  `cargo build && cargo clippy -- -D warnings && cargo test` before shipping.

### Changed (round 10)

- Version **0.3.0 → 0.4.0 (source)**. Production still serves 0.2.0: close
  the gap with `DEPLOY-003` — the same *deploy-drift* we already documented in
  `MCP/FEEDBACK.md` §A2.

## [0.3.0] — 2026-10-24

### Changed (round 9 — profiling cap + always-visible CSP hygiene)

- Body profiling cap **256KB → 333KB** (`MAX_PROFILE_BODY`), covering heavier
  pages; all docs/notices updated.
- **`csp_hygiene` is now a first-class API field** — the CHECK is always
  exposed when a CSP + profiled body exist, not only when the purge advisory
  fires: `applicable`, `allowed_hosts`, `observed_hosts`, `unused_hosts`,
  `status` (not-applicable | clean | purge-recommended). UI panel, AI export
  and CLI show it too; the CSP-HYGIENE advisory still fires only on
  purge-recommended.
- Bare `*` in a CSP is no longer parsed as a host grant (facade CSPs are
  classify_csp's job — hygiene reports clean with zero host grants).

### Fixed (round 8 — payment-popup false positive + leftover i18n)

- **COOP payment-popup detector now requires concrete evidence** (bug reported
  against pgp.btoven.net: a static PGP tool flagged for "payment popups" just
  for one `target="_blank"` Wikipedia link). Evidence is now:
  1. a payment gateway referenced by an actual `<script src>`, `<form action>`
     or a loaded origin (Stripe, PayPal, MercadoPago, Braintree, Adyen, … with
     label-boundary host matching — `square` never matches `squarespace`), or
  2. `window.open` in JS **plus** a cross-origin `<script src>` (genuine
     OAuth/checkout popup flows that need `window.opener`).
  Plain `target="_blank"` links, the word "checkout" in text and local-only
  `window.open` dialogs no longer trigger the same-origin-allow-popups advice.
- Fixed 10 remaining Spanish strings that escaped every sweep ("presente",
  "CSP presente y efectiva") — automated sweep with expanded adjective list
  now reports 0 leftovers.

### Added (round 7 — CSP hygiene)

- **CSP-HYGIENE advisory (severity `medium`, new level)**: diffs the origins
  allowed by the site's CSP header against the origins the fetched page really
  loads (`src`/`href`/`action`) → concrete purge list of permissive origins
  with no detected use. Wildcards count as used when an observed host falls
  under them; own-site hosts are excluded; keywords/schemes skipped. Honest
  caveat included: best-effort against the fetched HTML (first 256KB) — verify
  runtime usage before removing (e.g. payment SDKs loaded on demand).

### Fixed (round 6 — dogfooding feedback, memory #569)

- `/api/lookup` **never returns a null body**: unreachable or non-2xx targets
  get the result object (score 0 + errors) like the web route — crashed
  consumers doing `.get()` on null (`fallback.btoven.net` 503 case).
- Missing headers are no longer duplicated: `issues[]` is canonical (with
  severity); `errors[]` keeps validation messages only. OpenAPI description +
  llms.txt updated accordingly.
- `headers[].negative` (new, additive): `true` for x-powered-by so consumers
  count absence as PASS — never "missing". CLI now renders ✅ for an absent
  negative header (was ❌).
- Comparability documented (score 66 vs 68 without breakdown): compare only
  with matching `engine` + `schema_version`; `make check` diff workflow.

### Changed (round 5 — smarter CSP suggestions)

- Custom CSP values are now minimal and readable: each observed origin appears
  **once, in the directive where it was actually used** (per-resource origin
  tracking: script/style/img/frame/form), ordered **own domains first,
  third-party last**. No more blanket 5-origins × 4-directives walls.
- Compatibility directives: `form-action` includes observed external
  (payment/auth) form targets; `frame-src` for observed embeds; `connect-src`
  mirrors script hosts; `font-src` only guesses fonts.gstatic.com when Google
  Fonts was actually observed.
- Static-landing suggestions now include observed CDN assets (previously
  ignored them → suggestion would break the page if enforced).
- Single-label wording: `CSP broken: …` / `Existing CSP is broken: …` — removed
  double prefixes ("Existing CSP: Broken CSP:") and a leftover untranslated
  "CSP rota" string.
- Reports cleaner: issues carry short recommendations (exact values live ONLY
  in the roadmap), AI export no longer repeats the full CSP suggestion, and the
  roadmap is labeled as a custom suggestion to validate before enforcement.

### Added (round 4 — schema identity, replicable checks, shared list)

- **Schema/engine identity**: `schema_version: 2` (single source: securityheaders
  crate `SCHEMA_VERSION`) and `engine: "securityheaders/<version>"` on every
  result (API + CLI). Bump the constant on structural changes; quote the engine
  to replicate a check later. Footer shows the current version.
- **Replicable checks**: `securityheaders-cli --json` / `make check URL=x`
  emits stable JSON (identity + full result) for diffing scores across engine
  versions: `make check URL=example.com > before.json`.
- **Shared tracker list** (canonical source: adblock-tester): embedded at
  compile time from `securityheaders/data/trackers.txt`; Dockerfile refreshes it
  on every image build from
  `https://adblock.btoven.net/static/lists/trackers.txt` (falls back to the
  committed snapshot); `make fetch-trackers` for local refresh. No runtime
  dependency. Published as L0KL resource `trackers-list` (adblock-tester).

### Added (round 3 — security + privacy as first-class axes)

- **Dual grades as the headline**: `Security: A–F` (from the score:
  ≥90 A, ≥80 B, ≥65 C, ≥50 D) + `Privacy: A–F` (third-party origins +
  2×trackers: ≤1 A, 2–3 B, 4–6 C, 7–9 D, ≥10 F). The 0-100 stays in the
  API/breakdown; "fewer externals is always better" is now measured.
- **Tracker/analytics detection** (curated offline catalog in `profile.rs`):
  GA, GTM, Clarity, Meta Pixel, Hotjar, Segment, Mixpanel, Google Ads,
  Matomo, Microsoft/LinkedIn/TikTok ads, FullStory, New Relic, Yandex.
- **Privacy Surface panel**: grade chip, origin list, tracker chips, guidance.
- **Self-host roadmap steps** (`third-party-assets`, tag `privacy`, 0 pts,
  ordered after scored steps): shrink the CSP allow-list, cut supply-chain and
  data-sharing exposure; `csp_advice.self_host_targets` carries the targets.
- Large CSP allow-list warning (>5 origins) in `csp_advice.note`.
- Issue recommendations reframed security + privacy (CSP, referrer,
  permissions, cache).

### Added (round 2 — score expression)

- Score context: the number never travels alone — badge and reports show
  `Headers: passed/applicable · Critical: N · After roadmap: X/100`
  (`applicable`, `passed`, `critical`, `projected` in `score_breakdown`).
- Roadmap steps carry their score gain (`points`) and are **ordered by score
  impact** (biggest gain first), with `After roadmap` projection.
- Full English sweep: all remaining Spanish strings translated (roadmap
  actions/values, HSTS notes, Makefile output); automated detector passes clean.

### Changed

- L0KL-aligned Makefile lifecycle: `serve` / `up` / `down` / `test` / `deploy`
  (default `PORT=29829`, the L0KL reservation) + commands declared in
  `l0kl.json` and synced via `audit06 l0kl commands-sync`.

### Added

- **Profile-aware scoring (SCORE-002)** — the score now measures compliance
  against the header set *expected* for the page's profile instead of a generic
  checklist:
  - Page profiling from the served HTML (same request, capped 256KB,
    `text/html` only): `static-landing`, `app-legacy`, `app-moderna`, `cms`,
    `unknown`. Opt out with `?no_profile=1`.
  - Per-profile weighted sets; headers reasonable to omit become **contextual**
    and do not count against the score (e.g. COOP/COEP on legacy apps).
  - `score_breakdown`: per-header points, status
    (`pass|weak|missing|fail|contextual`) and cause; `deliberate_omissions[]`.
  - `roadmap`: ordered improvements with the exact header value for each step.
  - CSP intelligence: facade/broken detection (`default-src *`,
    `unsafe-eval`+`unsafe-inline` without nonce), feasibility analysis, and a
    concrete suggested CSP built from the page's observed third-party origins;
    Report-Only first when inline JS is present (`csp_advice`).
  - COOP payment risk → recommends `same-origin-allow-popups`;
    COEP marked "not viable yet" listing the cross-origin domains that must
    send `CORP` first.
  - Cache-Control sensitivity: session/login pages → `no-store`;
    public pages → short `max-age` + revalidation.
- **Issue severities**: `issues[]` now carries `severity`
  (`critical | recommended | contextual`), derived from the score breakdown.
- **Generic advisory engine** (`advisories.rs`): curated offline catalog
  (baked into the binary, no network) matched against versions leaked in
  `X-Powered-By`/`Server`:
  - PHP2Shell (CVE-2026-109618 / CVE-2026-109619) — PHP 5.4–8.5, fixed at
    8.2.35 / 8.3.36 / 8.4.27 / 8.5.12 (EOL branches stay critical)
  - Apache path traversal & RCE (CVE-2021-41773 / CVE-2021-42013) — 2.4.49–2.4.50
  - Apache HTTP/2 rapid reset (CVE-2023-44487) — < 2.4.60
- **Subdomain hints** for HSTS `includeSubDomains` viability: referenced
  same-site subdomains (`source: "html"`, zero extra traffic); active probe
  behind `?probe=subdomains` opt-in (HEAD, max 5, 2s each, `source: "probe"`).
- **cargo-audit (informative)**: `make audit` target + CI job `audit-deps`
  with `allow_failure: true` — surfaces RustSec advisories without blocking.
- **L0KL integration**: `l0kl.json` service descriptor + `PORT` env override
  (default 7070 unchanged) for a local instance on L0KL-reserved port 29829.

### Changed

- API is **backward compatible** — only fields added: `page_profile`,
  `score_breakdown`, `roadmap`, `csp_advice`, `subdomains`, `issues[].severity`.
- `FetchOptions` defaults: profiling ON, probe OFF (single outbound request).
- UI: profile tag next to score, Roadmap panel, Score Breakdown table,
  severity column in Issues, AI-report export includes profile/roadmap/severity.
- CLI prints profile, roadmap and score breakdown.
- `llms.txt` documents the new fields and query parameters.

### Fixed

- `FetchOptions::default()` derived `profile: false`, silently disabling
  profiling on the default lookup path — now an explicit `Default` with
  `profile: true`.
- Advisory `fixed_in` floors compare by `(major, minor, patch)` — previously a
  `(major, patch)` floor could mark EOL branches (e.g. PHP 8.1) as patched.

## Earlier history

See `git log` — releases prior to 2026-10-24 predate this changelog.
