signal-bot/signal_bot/manage/routes_album.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

115 lines
4.2 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The photo tagger, absorbed.
These are ``tool/tagger.py``'s seven routes, moved here so they are inside
the coverage gate rather than beside it -- which is the reason an
unconditional ImportError once sat in that file through two releases. The
behaviour is unchanged, deliberately: ``Album`` already deals in ``KeyError``
and ``ConfigError`` so routes can translate them, and the media route is
still indexed by integer.
That last one is not a style choice. A filename supplied by a client is a
path, and this directory holds private photographs.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from fastapi import APIRouter, HTTPException, status
from fastapi.responses import FileResponse
from signal_bot.groups import ConfigError
from signal_bot.manage.routes_status import live_groups
from signal_bot.pack import MEDIA_DIR
if TYPE_CHECKING:
from signal_bot.manage.deps import ManageDeps
def roster(api: APIRouter, deps: ManageDeps) -> None:
"""The two endpoints that write people.json.
Split from :func:`router` along the seam that matters: everything here
can refuse, and a refusal has to reach the page rather than the next
restart.
Args:
api: The router to register on.
deps: The running app's album.
"""
@api.post("/setup")
async def setup(payload: dict[str, Any]) -> dict[str, str]:
"""Write the roster, then prove the bot could load it."""
try:
deps.album.setup(
list(payload.get("groups", [])),
list(payload.get("people", [])),
list(payload.get("combos", [])),
)
except ConfigError as error:
# Straight into the page: a manifest the bot would refuse should
# be fixed here, in the form, not found at the next restart.
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(error)
) from error
return {"status": "ok"}
@api.post("/person")
async def person(payload: dict[str, Any]) -> dict[str, str]:
"""Add one person mid-session, and return the key they were given."""
# Mid-session, not only at setup: the reason to add somebody is
# usually a photo of them already on the screen.
try:
key = deps.album.add_person([str(t) for t in payload.get("triggers", [])])
except ConfigError as error:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(error)
) from error
return {"status": "ok", "key": key}
def router(deps: ManageDeps) -> APIRouter:
"""Every album endpoint the page needs.
Args:
deps: The running app's album and HTTP client.
Returns:
A router to include in the management app.
"""
api = APIRouter(prefix="/api/album")
roster(api, deps)
@api.get("/state")
async def state() -> dict[str, Any]:
"""Everything the tagging view draws itself from."""
return {**deps.album.state(), "known_groups": await live_groups(deps)}
@api.post("/tag")
async def tag(payload: dict[str, Any]) -> dict[str, str]:
"""Record who is in one file."""
try:
deps.album.tag(str(payload["file"]), [str(key) for key in payload.get("keys", [])])
except KeyError as error:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(error)) from error
return {"status": "ok"}
@api.get("/summary")
async def summary() -> dict[str, list[str]]:
"""What each command would answer with, and what is still untagged."""
return {"lines": deps.album.summary()}
@api.get("/media/{index}")
async def media(index: int) -> FileResponse:
"""One item, by position in the album."""
# By index, never by a name the page sends back: a filename from a
# client is a path, and portraits.path_for exists for the same reason.
files = deps.album.files
if not 0 <= index < len(files):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such item")
return FileResponse(deps.album.directory / MEDIA_DIR / files[index])
return api