Put nosniff, X-Frame-Options: DENY and Referrer-Policy: same-origin on every HTTP answer through the boilerplate's Hardening middleware, outermost and leaving the socket alone, name the API tokens in the Account page's lede, and reach the open test app as 127.0.0.1, since auth now answers 421 to any other Host

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-10-27 11:51:21 +01:00
1 parent 244e57ac29
commit 14793f4707
4 files changed
+144 -6

No files matched your search

+47 -4
View File
@@ -4,8 +4,9 @@
uv run uvicorn app.main:app --reload uv run uvicorn app.main:app --reload
`create_app()` is the whole of the wiring, and the order in it is the point: `create_app()` is the whole of the wiring, and the order in it is the point:
config and store, the door, the queue, the pages. Everything before the queue config and store, the door, the queue, the pages, and around all of them the
is something the queue needs; everything after it is something that enqueues. hardening headers. Everything before the queue is something the queue needs;
everything after it is something that enqueues.
""" """
from __future__ import annotations from __future__ import annotations
@@ -17,7 +18,9 @@ from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from starlette.datastructures import MutableHeaders
from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.types import ASGIApp, Message, Receive, Scope, Send
import auth import auth
from app import jobs from app import jobs
@@ -33,6 +36,39 @@ log = logging.getLogger(__name__)
#: data gets `{"detail": ...}`; a browser that asked for a page gets one. #: data gets `{"detail": ...}`; a browser that asked for a page gets one.
API_PREFIXES = ("/api", "/ws", "/_jobs", "/_auth", "/static", "/health") API_PREFIXES = ("/api", "/ws", "/_jobs", "/_auth", "/static", "/health")
#: On every HTTP answer, the door's refusals and the error pages included. No
#: CSP yet: the templates carry inline scripts and styles, which would need a
#: nonce or a hash each.
HARDENING = {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "same-origin",
}
class Hardening:
"""`HARDENING` on every response that does not set the header itself.
Pure ASGI rather than `BaseHTTPMiddleware`, so a streamed answer and the
socket 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 harden(message: Message) -> None:
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
for name, value in HARDENING.items():
headers.setdefault(name, value)
await send(message)
await self.app(scope, receive, harden)
def create_app(config: Config | None = None) -> FastAPI: def create_app(config: Config | None = None) -> FastAPI:
"""Build the application. A test passes its own config; nobody else does.""" """Build the application. A test passes its own config; nobody else does."""
@@ -59,8 +95,12 @@ def create_app(config: Config | None = None) -> FastAPI:
# The door, first, because it is the door. The middleware covers every # The door, first, because it is the door. The middleware covers every
# route whenever it was added, `/ws/jobs` included; written first, nobody # route whenever it was added, `/ws/jobs` included; written first, nobody
# has to work that out. `auto` locks unless the bind address is loopback. # has to work that out. `auto` locks unless the bind address is loopback,
# Auth's tables are the `auth_*` ones in the same file. # and an app it leaves open answers 421 to a request that names any host
# but a loopback one or comes through a proxy. Auth's tables are the
# `auth_*` ones in the same file, `auth_tokens` for the API tokens among
# them. No `session_only=`: no route here hands out or replaces the
# database as a file.
auth.connect(app, auth.AuthStore(config.database), config.auth, auth.connect(app, auth.AuthStore(config.database), config.auth,
host=config.server.host, open=("/static/",), host=config.server.host, open=("/static/",),
stylesheet="/static/app.css") stylesheet="/static/app.css")
@@ -84,6 +124,9 @@ def create_app(config: Config | None = None) -> FastAPI:
--wait` waits on this, so it has to prove the database answers.""" --wait` waits on this, so it has to prove the database answers."""
return {"ok": True, "open_roles": sum(store.open_role_counts().values())} return {"ok": True, "open_roles": sum(store.open_role_counts().values())}
# Last, so outermost: around the door and the error pages.
app.add_middleware(Hardening)
@app.exception_handler(StarletteHTTPException) @app.exception_handler(StarletteHTTPException)
async def errors(request: Request, exc: StarletteHTTPException) -> Any: async def errors(request: Request, exc: StarletteHTTPException) -> Any:
"""JSON for a caller, a page for a browser. One shape for every API """JSON for a caller, a page for a browser. One shape for every API
+1 -1
View File
@@ -3,7 +3,7 @@
{% block content %} {% block content %}
<h1>Account</h1> <h1>Account</h1>
<p class="lede">The one password, the devices signed in with it, and the passkeys that sign in without it.</p> <p class="lede">The one password, the devices signed in with it, the passkeys that sign in without it, and the API tokens a script sends instead.</p>
<section class="card"> <section class="card">
{# As in Sources' Runs: the element and its script belong to {# As in Sources' Runs: the element and its script belong to
+93
View File
@@ -0,0 +1,93 @@
"""The three hardening headers `app.main.Hardening` puts on every HTTP answer:
a page, an API answer, the error handler's answers and the door's own
refusals, since it sits outside all of them. The socket's handshake is not an
HTTP answer and passes through untouched."""
from __future__ import annotations
from collections.abc import Iterator
from pathlib import Path
import pytest
from fastapi import FastAPI, Response
from fastapi.testclient import TestClient
from httpx import Headers
from app.config import Config, ServerConfig
from app.main import HARDENING, create_app
@pytest.fixture
def app(tmp_path: Path) -> FastAPI:
return create_app(Config(server=ServerConfig(host="127.0.0.1", port=0),
database=tmp_path / "roledesk.db"))
@pytest.fixture
def client(app: FastAPI) -> Iterator[TestClient]:
"""Reached as 127.0.0.1: an app open on loopback answers 421 to any
other `Host`."""
with TestClient(app, base_url="http://127.0.0.1") as c:
yield c
def hardened(headers: Headers) -> None:
for name, value in HARDENING.items():
assert headers.get(name) == value, name
def test_a_page_carries_the_three_headers(client: TestClient) -> None:
answer = client.get("/settings/account")
assert answer.status_code == 200
hardened(answer.headers)
def test_an_api_answer_carries_them(client: TestClient) -> None:
answer = client.get("/api/account")
assert answer.status_code == 200
assert answer.headers["content-type"].startswith("application/json")
hardened(answer.headers)
def test_an_error_answer_carries_them(client: TestClient) -> None:
"""The JSON error and the error page both come from the exception handler,
inside the middleware."""
missing = client.get("/api/no-such-thing")
assert missing.status_code == 404
assert "detail" in missing.json()
hardened(missing.headers)
page = client.get("/no-such-page")
assert page.status_code == 404
assert page.headers["content-type"].startswith("text/html")
hardened(page.headers)
def test_the_doors_refusal_carries_them(app: FastAPI) -> None:
"""auth's 421 for a host that is not loopback is answered by its
middleware, which `Hardening` wraps."""
with TestClient(app, base_url="http://rebound.example") as stranger:
refused = stranger.get("/")
assert refused.status_code == 421
hardened(refused.headers)
def test_a_header_the_route_sets_is_kept(app: FastAPI, client: TestClient) -> None:
@app.get("/api/framed")
def framed() -> Response:
return Response("{}", media_type="application/json",
headers={"X-Frame-Options": "SAMEORIGIN"})
answer = client.get("/api/framed")
assert answer.headers["x-frame-options"] == "SAMEORIGIN"
assert answer.headers["x-content-type-options"] == "nosniff"
def test_the_socket_handshake_is_left_alone(client: TestClient) -> None:
"""TestClient names `testserver` on a socket whatever its `base_url`, so
the handshake names the loopback host itself."""
with client.websocket_connect("/ws/jobs", headers={"host": "127.0.0.1"}) as socket:
accepted = {bytes(name).decode().lower()
for name, _ in (socket.extra_headers or [])}
assert socket.receive_json()["type"] == "jobs"
assert not accepted & {name.lower() for name in HARDENING}
+3 -1
View File
@@ -41,7 +41,9 @@ def store(app: FastAPI) -> Store:
@pytest.fixture @pytest.fixture
def client(app: FastAPI) -> Iterator[TestClient]: def client(app: FastAPI) -> Iterator[TestClient]:
with TestClient(app) as c: """Reached as 127.0.0.1, the name a browser uses: an app open on loopback
answers 421 to any other `Host`, TestClient's `testserver` included."""
with TestClient(app, base_url="http://127.0.0.1") as c:
yield c yield c