# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """The two checks that make a loopback bind actually mean loopback. Binding to 127.0.0.1 stops the network. It does not stop the browser already running on this machine, and this app writes ``.env`` -- the file that decides which groups the bot answers in and who may add it to one. Two attacks reach a loopback port from an ordinary web page, and both are cheap to close: - **Form CSRF.** A page on any site can POST a cross-origin ``
`` to 127.0.0.1 without reading the reply. A form can only send ``application/x-www-form-urlencoded``, ``multipart/form-data`` or ``text/plain``, so requiring ``application/json`` on every mutating request refuses it outright, with no token and no session to keep. - **DNS rebinding.** A hostname the attacker controls is re-pointed at 127.0.0.1 after the page loads, which makes the browser treat this app as same-origin. The rebound request still carries the attacker's hostname in ``Host``, so requiring a loopback ``Host`` refuses that too. Roughly forty lines instead of authentication, which is the right trade for something started by hand, used for a few minutes and stopped again. """ from __future__ import annotations from typing import TYPE_CHECKING, Final from fastapi import FastAPI, Request, Response, status from fastapi.responses import JSONResponse if TYPE_CHECKING: from collections.abc import Awaitable, Callable # GET and HEAD do not change anything, and requiring a content type on them # would break every ordinary navigation to the page itself. MUTATING: Final = frozenset({"POST", "PUT", "PATCH", "DELETE"}) JSON_TYPE: Final = "application/json" LOOPBACK_HOSTS: Final = ("127.0.0.1", "localhost", "[::1]") def allowed_host(host: str, port: int) -> bool: """Whether a Host header names this app on this machine. Args: host: The request's Host header, possibly with a port. port: The port this app is serving on. Returns: True for a loopback name, with either the right port or none. """ if not host: # HTTP/1.1 requires it. Something that omits it is not a browser # doing anything ordinary, so it does not get the benefit of the doubt. return False name, _, given = host.rpartition(":") if not name: name, given = host, "" return name in LOOPBACK_HOSTS and given in {"", str(port)} def install(app: FastAPI, port: int) -> None: """Add both checks to one app, in front of every route. Args: app: The FastAPI application to guard. port: The port it will be served on. """ @app.middleware("http") async def check( request: Request, call_next: Callable[[Request], Awaitable[Response]] ) -> Response: if not allowed_host(request.headers.get("host", ""), port): return JSONResponse( {"status": "refused", "reason": "this page is only served on loopback"}, status_code=status.HTTP_421_MISDIRECTED_REQUEST, ) if request.method in MUTATING: declared = request.headers.get("content-type", "").split(";")[0].strip() if declared != JSON_TYPE: return JSONResponse( {"status": "refused", "reason": f"{JSON_TYPE} is required"}, status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, ) return await call_next(request)