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

82 lines
3.0 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Reading and writing ``.env`` from the page.
Three refusals, in order, and the order matters. A key that may not be
written is refused before anything is parsed, so a read-only key cannot be
smuggled past by making the rest of the file invalid. Then the whole
candidate file is validated by the function startup uses. Only then is
anything written, so a rejected edit leaves the file byte-identical.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel
from signal_bot.groups import ConfigError
from signal_bot.manage import envfile, envkeys
from signal_bot.manage.routes_status import live_groups
if TYPE_CHECKING:
from signal_bot.manage.deps import ManageDeps
class EnvUpdate(BaseModel):
"""The keys the form changed, and what to set them to."""
values: dict[str, str]
def router(deps: ManageDeps) -> APIRouter:
"""The two ``.env`` endpoints.
Args:
deps: The running app's configuration and the path it may edit.
Returns:
A router to include in the management app.
"""
api = APIRouter(prefix="/api")
@api.get("/env")
async def read() -> dict[str, Any]:
"""Every key the page shows, and whether groups can be edited now."""
text = deps.env_path.read_text(encoding="utf-8")
groups = await live_groups(deps)
return {
"keys": envkeys.settings(text),
# False turns the two group fields read-only in the form rather
# than letting them be written blind. See envkeys.NEEDS_GROUPS.
"groups_known": bool(groups),
"needs_groups": list(envkeys.NEEDS_GROUPS),
}
@api.put("/env")
async def write(update: EnvUpdate) -> dict[str, Any]:
"""Validate an edit against startup's own rules, then write it."""
groups = await live_groups(deps)
refused = envkeys.refuse(update.values, groups_known=bool(groups))
if refused is not None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"{refused} is not editable from this page",
)
text = deps.env_path.read_text(encoding="utf-8")
try:
envkeys.validate(text, update.values)
except ConfigError as error:
# load_config's own message: the page shows what the journal
# would have shown at the next restart, before that restart.
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(error)
) from error
envfile.write(deps.env_path, update.values)
# The running process loaded the old values and will keep using them.
# Saying so is the whole of the contract; restarting is the
# operator's to do, from the terminal they started this page in.
return {"status": "written", "restart_required": True}
return api