Files
brain-of-reese/app/core/security_headers.py
T
ducoterra e29d68d9f0 phase: 82_security_headers
All completion criteria verified green — no defects found, nothing to fix. Final report:

**Phase 82 (security headers) — final verification pass: all green**

- Verified prior-run implementation: `app/core/security_headers.py` (pure-ASGI, header-only, exact A1 CSP), registration in `app/main.py` after `configure_caching` (outermost), unit/integration/E2E suites.
- Deviation confirmed sound: `data:`-URI favicon (blocked by locked CSP) → static `frontend/assets/favicon.svg` in 5 templates + Containerfile `cp`; SVG element byte-identical to the old data-URI (verified programmatically); serves 200 with all three headers.
- Curl check (server booted like e2e conftest, log: `/tmp/curl_security_headers_final.log`): `/`, `/api/health`, `/assets/styles.css`, `/nope` (404) → all three headers, CSP exactly `default-src 'self'; base-uri 'none'; frame-ancestors 'none'`.
- `uv run pytest tests/unit/test_security_headers.py tests/integration/test_security_headers.py -v --no-cov` → 13 passed (incl. SSE byte-identity pin).
- `uv run pytest tests/e2e/test_security_headers.py -v --no-cov` (isolated) → 2 passed (headers + zero CSP violations + painted page).
- SSE tripwire `uv run pytest tests/e2e/test_chat_rag.py -v --no-cov` → 3 passed.
- `uv run pytest --cov=app --cov-report=term-missing` → 1665 passed, app/ 99% (>90%); `uv run ruff check . && uv run pyright` → clean (0 errors).
- `git diff --stat` limited to phase-82 files + the two documented deviations (favicon set, `tests/unit/__init__.py`); no `pyproject.toml`/`uv.lock`/JS diffs.
- Commit + phase-dir move left to the harness per pipeline rules (not executed by me).

Next pending phase: `83_chat_save_payload_limits`.
2026-09-07 23:54:41 -04:00

82 lines
3.8 KiB
Python

"""Security headers on every response (phase 82 — security audit SEC-04).
Audit basis (SEC-04, severity Medium): no response in the app carried
``Content-Security-Policy``, ``X-Frame-Options``, or
``X-Content-Type-Options``. Every page — including the admin sign-in and
the admin-only views — could be embedded in a third-party page's
iframe: a malicious LAN page could overlay the admin UI and trick the
signed-in owner into clicking Sync / Revoke / Delete-source actions
(audit PoC: ``<iframe src="http://<server>:8000/git-sources.html">``
with a benign-looking overlay). ``frame-ancestors 'none'`` (in the
CSP) plus ``X-Frame-Options: DENY`` (the legacy fallback for pre-CSP
browsers) close that clickjacking vector. The CSP itself is the
standard second line of defense against any future XSS regression —
cheap here because the frontend is No-CDN and was verified for this
phase to have **no** inline ``<style>`` blocks, **no** ``style="…"``
attributes, **no** ``onclick``/``on*`` handlers, **no** ``javascript:``
URLs, and **no** external hosts (inline ``<svg>`` elements are
CSP-legal; the two ``el.style.…`` CSSOM writes in ``app.js`` are not
CSP-blocked). If inline scripts/styles are ever introduced, re-verify
that: the policy would break the affected page loudly, and that loud
failure is the feature, not the bug.
``X-Content-Type-Options: nosniff`` is the one-line belt-and-braces
against MIME confusion on the static mount.
Why pure ASGI: this is a *header-only* middleware. It wraps ``send``
and writes the three headers on ``http.response.start`` only — it
never reads or buffers a body, so the SSE chat stream and every other
response pass through byte-identical. That is the explicit contrast
with ``app/core/caching.py``'s ``CachingMiddleware``, which
*does* buffer page bodies for the ``?v=`` rewrite. No HSTS (plain
homelab HTTP — TLS is the documented non-goal), no ``Referrer-Policy``
/ ``Permissions-Policy`` (owner decision A4: the three headers above
are the scope).
"""
from __future__ import annotations
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
#: The exact owner-approved policy (phase 82, decision A1).
#: ``default-src 'self'`` is inherited by every sub-policy that has no
#: explicit entry (``script-src``, ``style-src``, ``connect-src``, …),
#: ``base-uri 'none'`` blocks base-tag hijacking, and
#: ``frame-ancestors 'none'`` forbids any framing. No ``'unsafe-inline'``
#: (verified unnecessary — see module docstring), no ``report-uri`` /
#: ``report-to`` (no collector in the homelab — a report would just
#: vanish).
CSP = "default-src 'self'; base-uri 'none'; frame-ancestors 'none'"
class SecurityHeadersMiddleware:
"""Header-only, pure-ASGI — never reads or buffers a body (SSE-safe).
Adds exactly three headers to every HTTP response:
* ``Content-Security-Policy``: the strict same-origin policy above
(``frame-ancestors 'none'`` → clickjacking closed, SEC-04);
* ``X-Frame-Options: DENY`` — legacy no-framing fallback;
* ``X-Content-Type-Options: nosniff`` — MIME-confusion belt.
Non-HTTP scopes (websocket, lifespan) pass through untouched.
"""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
async def send_wrapper(message: Message) -> None:
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
headers["Content-Security-Policy"] = CSP
headers["X-Frame-Options"] = "DENY"
headers["X-Content-Type-Options"] = "nosniff"
await send(message)
await self.app(scope, receive, send_wrapper)