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/`.
157 lines
7.0 KiB
Python
157 lines
7.0 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), extended by
|
|
the phase-123 ``img-src 'self' data:`` carve-out (the question-image
|
|
composer's data-URL preview + live bubble — see ``CSP`` in
|
|
``app/core/security_headers.py``; the ``data:`` allowance is scoped
|
|
to img-src only);
|
|
* ``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"] == CSP
|
|
|
|
|
|
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
|