All verification is complete — this pass needed no code changes. Final report: **Phase 91 — Admin Theme tab: final verification pass (all 6 tasks already in `complete/`)** - Verified pre-paint theming end-to-end: `ui_settings` store + resolver, admin `GET/PUT /api/ui-settings`, `CachingMiddleware` inline-`<style id="bor-theme">` injection before `</head>` (incl. `/shared/<token>` prefix branch, unit-pinned), CSP sha256 exemption for the inline tag, Theme tab shell + `theme.js` editor, CSS-file theming fully retired. - No defects found; zero changes made — working tree left exactly as the task executors left it. - Tests: `uv run pytest --cov=app` → 1841 passed, 0 failed (TOTAL coverage **99%**; theming/ui_settings/caching all 100%); `uv run pytest tests/e2e/test_admin_theme_tab.py -v --no-cov` → **5 passed** in isolation. - Lint/types: `uv run ruff check .` → All checks passed; `uv run pyright` → 0 errors, 0 warnings. - Criteria: (1) unset deployment byte-identical, no `#bor-theme` anywhere — ✓ (unit no-op test + E2E reset byte-compare); `rg "BOR_THEME|themes/"` → single hit is the permitted doc-history comment in `frontend/index.html`. (2) admin-only gate + 403s for anonymous and token users — ✓ (E2E test 3). (3) saved theme inline before `</head>` on every page incl. `/shared/<token>`, computed `--brand` on first paint for admin + anonymous — ✓ (E2E test 2 + unit). (4) reset → byte-identical; 5 contrast pairs warn <4.5:1, non-blocking — ✓ (E2E tests 4–5). (5) suite green, >90% coverage, lint clean — ✓. (6) commit deferred to harness per rules. - Notable: `.agents/PLAN.md` is absent from the repo — the phase overview's Design section was used as the binding spec; no deviation resulted. - Next pending phase: **none** — 91 is the last phase in `todo/`.
155 lines
6.8 KiB
Python
155 lines
6.8 KiB
Python
"""Integration: the phase-82 security-header contract against the REAL app.
|
|
|
|
Phase 82 (audit SEC-04) adds a header-only, pure-ASGI middleware
|
|
(``app/core/security_headers.py``) registered OUTERMOST in
|
|
``app/main.py`` (last ``add_middleware`` — after
|
|
``configure_caching``), so every response this process serves — pages,
|
|
API JSON, static assets, even the static catch-all's 404s — carries:
|
|
|
|
* ``Content-Security-Policy`` — the exact A1 string (``default-src 'self';
|
|
base-uri 'none'; frame-ancestors 'none'`` → clickjacking closed, no
|
|
inline anything because the No-CDN frontend has none);
|
|
* ``X-Frame-Options: DENY`` — the legacy no-framing fallback;
|
|
* ``X-Content-Type-Options: nosniff`` — the MIME-confusion belt.
|
|
|
|
This suite pins those three on the four response shapes the browser
|
|
actually sees — a page (``/``), an API response (``/api/health``), a
|
|
static asset (``/assets/styles.css``), and a 404
|
|
(``/definitely-not-a-page`` — the outermost-position proof: the 404 is
|
|
built deep inside the static catch-all, yet the headers are still on
|
|
it) — against the real ``app.main:app`` with the real static mount on
|
|
the real ``frontend/`` tree (no mocks, same client as
|
|
``tests/integration/test_caching_revalidation.py`` via the shared
|
|
``client`` fixture). It also pins that the two middlewares coexist: the
|
|
CSP middleware is header-only, so the phase-33/54 ``?v=<token>``
|
|
rewrite from ``CachingMiddleware`` still runs under it (the last
|
|
regression below). The SSE chat stream's byte-identity is pinned by the
|
|
unit streaming test and the chat E2E suites (the tripwires).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import httpx
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import text
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core import theming
|
|
from app.core.security_headers import CSP
|
|
from app.models import UiSettings
|
|
|
|
#: The exact owner-approved A1 policy string (phase 82). The constant is
|
|
#: the single source of truth; the unit suite additionally pins that the
|
|
#: constant itself equals this literal.
|
|
_EXPECTED = {
|
|
"content-security-policy": CSP,
|
|
"x-frame-options": "DENY",
|
|
"x-content-type-options": "nosniff",
|
|
}
|
|
|
|
|
|
def _assert_security_headers(response: httpx.Response) -> None:
|
|
"""All three phase-82 headers present with the exact values (the
|
|
httpx header lookup is case-insensitive)."""
|
|
path = response.request.url.path
|
|
for name, value in _EXPECTED.items():
|
|
assert response.headers.get(name) == value, (
|
|
f"{path}: {name} must be {value!r}, "
|
|
f"got {response.headers.get(name)!r}"
|
|
)
|
|
|
|
|
|
def test_page_carries_all_three_headers(client: TestClient, db: Session) -> None:
|
|
"""``GET /`` (the shell page) — 200 + all three headers, CSP exactly
|
|
the A1 string. The ``ui_settings`` row is cleared first (phase 91,
|
|
task 05: a themed page carries the A1 string EXTENDED with the
|
|
style-src hash — the plain-A1 pin is the UNTHAMED page's
|
|
contract, and the dev database must not leak a theme into it)."""
|
|
db.execute(text("DELETE FROM ui_settings"))
|
|
db.commit()
|
|
response = client.get("/")
|
|
assert response.status_code == 200
|
|
_assert_security_headers(response)
|
|
assert response.headers["content-security-policy"] == (
|
|
"default-src 'self'; base-uri 'none'; frame-ancestors 'none'"
|
|
)
|
|
|
|
|
|
def test_api_health_carries_all_three_headers(client: TestClient) -> None:
|
|
"""``GET /api/health`` (an API JSON response) — 200 + all three
|
|
headers."""
|
|
response = client.get("/api/health")
|
|
assert response.status_code == 200
|
|
_assert_security_headers(response)
|
|
|
|
|
|
def test_static_asset_carries_all_three_headers(client: TestClient) -> None:
|
|
"""``GET /assets/styles.css`` (the static mount) — 200 + all three
|
|
headers (the nosniff belt guards exactly this surface)."""
|
|
response = client.get("/assets/styles.css")
|
|
assert response.status_code == 200
|
|
_assert_security_headers(response)
|
|
|
|
|
|
def test_static_catchall_404_carries_all_three_headers(client: TestClient) -> None:
|
|
"""``GET /definitely-not-a-page`` — 404 from the static catch-all,
|
|
built deep inside the app, yet all three headers ride on it: the
|
|
outermost-position proof (a response the middleware cannot see
|
|
unless it wraps everything)."""
|
|
response = client.get("/definitely-not-a-page")
|
|
assert response.status_code == 404
|
|
_assert_security_headers(response)
|
|
|
|
|
|
def test_caching_rewrite_still_runs_under_headers_middleware(client: TestClient) -> None:
|
|
"""Coexistence pin: the header middleware is header-only (it never
|
|
drains or rewrites a body), so the phase-33/54 ``CachingMiddleware``
|
|
``?v=<token>`` asset rewrite on the same page must still run — the
|
|
served HTML still carries at least one ``?v=`` reference."""
|
|
response = client.get("/")
|
|
assert response.status_code == 200
|
|
assert response.text.count("?v=") >= 1, (
|
|
"the ?v=<token> asset rewrite no longer runs — the outermost "
|
|
"security-header middleware altered or swallowed the body"
|
|
)
|
|
|
|
|
|
def test_themed_page_carries_a1_plus_style_src_theme_hash(
|
|
client: TestClient, db: Session
|
|
) -> None:
|
|
"""Phase 91 (task 05, defect fix): the A1 CSP would BLOCK the
|
|
inline ``<style id="bor-theme">`` pre-paint tag in every real
|
|
browser (``style-src`` falls back to ``default-src 'self'``) — so a
|
|
THemed HTML page carries the A1 string EXTENDED with
|
|
``style-src 'self' 'sha256-<hash>'``, the CSP3 hash of the exact
|
|
tag content: the current theme is the only inline style ever
|
|
permitted, no blanket ``'unsafe-inline'``, a different palette is
|
|
still blocked. The unthemed page keeps the plain A1 string (no
|
|
exemption for a tag that is not served). Pinned against the real
|
|
app (the unit suite pins the two middleware halves in isolation).
|
|
"""
|
|
db.execute(text("DELETE FROM ui_settings"))
|
|
db.commit()
|
|
try:
|
|
db.add(UiSettings(id=1, brand="#818cf8"))
|
|
db.commit()
|
|
colors = dict(theming.BUILTIN_COLORS)
|
|
colors["brand"] = "#818cf8"
|
|
tag = theming.theme_style_tag(colors)
|
|
response = client.get("/")
|
|
assert response.status_code == 200
|
|
assert tag in response.text # the themed page serves the tag
|
|
assert response.headers["content-security-policy"] == (
|
|
f"{CSP}; style-src 'self' '{theming.theme_csp_hash(tag)}'"
|
|
)
|
|
assert "unsafe-inline" not in response.headers["content-security-policy"]
|
|
# The other two phase-82 headers ride along, unchanged.
|
|
assert response.headers["x-frame-options"] == "DENY"
|
|
assert response.headers["x-content-type-options"] == "nosniff"
|
|
finally:
|
|
db.execute(text("DELETE FROM ui_settings"))
|
|
db.commit()
|
|
# The UNthemed page after the row is gone: plain A1, no tag.
|
|
response = client.get("/")
|
|
assert response.headers["content-security-policy"] == CSP
|
|
assert "bor-theme" not in response.text
|