Files
brain-of-reese/app/core/security_headers.py
T
ducoterra bef24e05e2
Build and Push Containers / build-and-push-app (push) Successful in 1m54s
Build and Push Containers / build-and-push-db (push) Failing after 13s
phase: 123_chat_image_questions
All gates green. Verification complete.

**Phase 123 — final verification pass (all 4 tasks already in `complete/`)**

- Verified the full implementation is in the working tree: `app/api/chat_images.py` (upload/serve pair), `ChatRequest.image`/`ChatMessage.image` (path-validated, omitted-when-None), toggle-off + stale-file hinted error frames, `build_user_content` multimodal build at both sites (chat.py deflected branch + `run_agent`), config-gated composer attach/preview/upload-then-send, restore + shared rendering, CSP `img-src 'self' data:` carve-out, mock-LLM capture buffer.
- `uv run pytest` → **2796 passed**, exit 0 (unit + integration).
- `uv run pytest --cov=app --cov-report=term-missing` → **TOTAL 99%** (29/4615 missed; phase-123 modules 99–100%).
- `uv run pytest tests/e2e/test_chat_image_questions.py -v --no-cov` → **5 passed** in isolation.
- `uv run ruff check . && uv run pyright` → clean (0 errors).

**Completion criteria:** (1) attach→send→multimodal text+image to the model, bubble/reload/shared all render it, saved chat stores the PATH with `"base64" not in json.dumps(stored)` — **verified** (E2E tests 1–4 + integration round-trip); (2) `BOR_IMAGES=false` — control hidden, exact hinted error frame, zero model calls / no query_log row — **verified** (E2E test 5 + integration); (3) text-only byte-identical (`content` stays a plain `str`) — **verified** (unit + integration); (4) all gates green — **verified**; (5) commit + phase move — left to the harness per pipeline rules (no `git add`/`commit` run).

No defects found; no live-infrastructure changes (repo + local dev DB only). **Next pending phase: none** — 123 is the last phase in `todo/`.
2026-09-25 05:19:18 -04:00

116 lines
5.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), extended
#: by phase 123's ``img-src`` carve-out (see below).
#: ``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).
#
#: Phase 123 (chat image questions, owner-confirmed 2026-09-24) added
#: the one scoped relaxation the design requires: ``img-src 'self'
#: data:``. The question-image composer renders the picked file as a
#: ``data:`` URL — the PREVIEW thumbnail (before the send-time upload
#: there is no served path yet) and the LIVE user bubble (the data URL
#: needs no fetch) — and ``default-src 'self'`` alone blocks ``data:``
#: images in every real browser (the phase-123 E2E caught it: the
#: bubble degraded to the "image unavailable" line). The carve-out is
#: ``img-src`` ONLY: ``data:`` never becomes a source for scripts,
#: styles, or fetches (those keep the strict ``default-src 'self'``
#: inheritance), and the bytes are the user's OWN locally-picked file
#: (no exfiltration vector — an ``<img>`` cannot read them back).
#: Restored / shared bubbles render from the served path (``'self'``),
#: so the ``data:`` allowance exists for the two pre-upload/first-paint
#: surfaces only.
CSP = (
"default-src 'self'; base-uri 'none'; frame-ancestors 'none'; "
"img-src 'self' data:"
)
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) —
EXCEPT when an inner layer has already set one: the phase-91
(task 05) pre-paint theme tag is an inline ``<style>`` that the
A1 policy would block in the browser, so the caching middleware
publishes, on themed HTML pages only, the A1 string with
``style-src 'self' 'sha256-<tag-content-hash>'`` appended (the
current theme is the only inline style ever permitted — no
``'unsafe-inline'``). A pre-existing CSP is that inner layer's
deliberate one and is preserved; every other response (including
every untagged page) gets the plain A1 string.
* ``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)
# Phase 91 (task 05): preserve a CSP an inner layer set
# (the caching middleware's theme-extended policy — see
# the class docstring); the A1 string covers every
# response without one.
if "content-security-policy" not in headers:
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)