diff --git a/app/main.py b/app/main.py index 07d367c..167e1c2 100644 --- a/app/main.py +++ b/app/main.py @@ -4,8 +4,9 @@ uv run uvicorn app.main:app --reload `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 -is something the queue needs; everything after it is something that enqueues. +config and store, the door, the queue, the pages, and around all of them the +hardening headers. Everything before the queue is something the queue needs; +everything after it is something that enqueues. """ from __future__ import annotations @@ -17,7 +18,9 @@ from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from fastapi.staticfiles import StaticFiles +from starlette.datastructures import MutableHeaders from starlette.exceptions import HTTPException as StarletteHTTPException +from starlette.types import ASGIApp, Message, Receive, Scope, Send import auth from app import jobs @@ -33,6 +36,39 @@ log = logging.getLogger(__name__) #: data gets `{"detail": ...}`; a browser that asked for a page gets one. 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: """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 # route whenever it was added, `/ws/jobs` included; written first, nobody - # has to work that out. `auto` locks unless the bind address is loopback. - # Auth's tables are the `auth_*` ones in the same file. + # has to work that out. `auto` locks unless the bind address is loopback, + # 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, host=config.server.host, open=("/static/",), 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.""" 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) async def errors(request: Request, exc: StarletteHTTPException) -> Any: """JSON for a caller, a page for a browser. One shape for every API diff --git a/app/templates/settings/account.html b/app/templates/settings/account.html index dfce2e1..58f51cb 100644 --- a/app/templates/settings/account.html +++ b/app/templates/settings/account.html @@ -3,7 +3,7 @@ {% block content %}

Account

-

The one password, the devices signed in with it, and the passkeys that sign in without it.

+

The one password, the devices signed in with it, the passkeys that sign in without it, and the API tokens a script sends instead.

{# As in Sources' Runs: the element and its script belong to diff --git a/tests/test_app_hardening.py b/tests/test_app_hardening.py new file mode 100644 index 0000000..6073b12 --- /dev/null +++ b/tests/test_app_hardening.py @@ -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} diff --git a/tests/test_pages.py b/tests/test_pages.py index 64d94ab..07ef778 100644 --- a/tests/test_pages.py +++ b/tests/test_pages.py @@ -41,7 +41,9 @@ def store(app: FastAPI) -> Store: @pytest.fixture 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