signal-bot/signal_bot/manage/guard.py
Krzysztof kuhy Rudnicki 0b539fc327 feat: the management backend, absorbing the tagger
A second process rather than more routes on the bot's own app. This one can
rewrite .env, and the bot's port already serves /_selftest, which posts for
real into a real group; keeping them apart means the surface that can
reconfigure the bot only listens while somebody has the page open.

The tagger's seven routes move here unchanged, out of tool/ and into the
coverage gate -- which is the reason an unconditional ImportError once sat
in tagger.py through two releases. The media route is still indexed by
integer, and that is not a style choice: a filename from a client is a path,
and the directory holds private photographs. FastAPI refuses a name with 422
before the handler runs, which the tests assert.

guard.py is the part that was not asked for. Binding to loopback stops the
network, not the browser already running on this machine, and two attacks
reach a loopback port from an ordinary web page: a cross-origin form, which
can only send urlencoded, multipart or plain text, so requiring
application/json refuses it with no token to keep; and DNS rebinding, whose
request still carries the attacker's hostname in Host. Forty lines instead
of authentication, which is the right trade for something started by hand
and stopped again a few minutes later.

assets.py branches on whether the page has been built, because StaticFiles
raises at construction on a missing directory -- mounting it unconditionally
would take the app down on a fresh clone, and in CI, where pytest never runs
pnpm build. Both branches are tested; "not built" answers with the command.

The container restart goes through signal_bot.external, wrapped in
asyncio.to_thread: it is synchronous with a 60s default, and blocking the
loop would freeze the page showing the restart.

100% branch coverage across all eleven modules, no omits, no pragmas.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01416TegJ3sa8xL5qGGgrygP
2026-08-31 14:38:24 +02:00

85 lines
3.4 KiB
Python

# 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 ``<form>`` 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)