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

103 lines
3.9 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""What the bot currently is: alive or not, in which groups, configured how.
All three reads degrade rather than fail. The management page is most useful
exactly when something is down, so a page that cannot render because the
container is unreachable would be missing at the only moment it was wanted.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import httpx
from fastapi import APIRouter
if TYPE_CHECKING:
from signal_bot.manage.deps import ManageDeps
# Enough to recognise the number, not enough to be the number. The page runs
# on the operator's own machine, but this repository has leaked a phone number
# into a public place once already and the fix was to delete the repository.
VISIBLE_DIGITS = 4
async def live_groups(deps: ManageDeps) -> list[dict[str, str]]:
"""The groups this account is in, so an id is picked and never typed.
Lifted from ``tool/tagger.py``, where it existed for the same reason: a
group id is 44 characters of base64 and retyping one is how you end up
scoping the bot to a group that does not exist.
Args:
deps: The running app's configuration and shared HTTP client.
Returns:
Every group with an id, or empty when the container cannot be
reached. Empty is a real answer -- see ``envkeys.refuse``, which
turns it into "group settings are read-only right now".
"""
try:
response = await deps.client.get(deps.config.groups_url, timeout=5.0)
response.raise_for_status()
listing = response.json()
except httpx.HTTPError, ValueError:
# No container, no network, or something that is not JSON at the
# other end. None of them stop the rest of the page working.
return []
return [
{"id": str(entry.get("id", "")), "name": str(entry.get("name", ""))}
for entry in listing
if entry.get("id")
]
def router(deps: ManageDeps) -> APIRouter:
"""The three read-only status endpoints.
Args:
deps: The running app's configuration, client and album.
Returns:
A router to include in the management app.
"""
api = APIRouter(prefix="/api")
@api.get("/status")
async def status() -> dict[str, Any]:
"""Whether the bot answers, and what it says about itself."""
try:
response = await deps.client.get(f"{deps.bot_url}/healthz", timeout=5.0)
body = response.json()
except httpx.HTTPError, ValueError:
# The bot being down is the single most important thing this
# page can tell you, so it is a state and never an error.
return {"reachable": False, "bot": {}}
return {"reachable": True, "bot": body}
@api.get("/groups")
async def groups() -> dict[str, list[dict[str, str]]]:
"""The live group listing, or empty when the container is unreachable."""
return {"groups": await live_groups(deps)}
@api.get("/config")
async def config() -> dict[str, Any]:
"""The resolved configuration, as the running bot sees it."""
settings = deps.config
return {
"phone_number": f"…{settings.phone_number[-VISIBLE_DIGITS:]}",
"is_pinned": settings.is_pinned,
"group_ids": list(settings.group_ids),
"trusted_inviters_count": len(settings.trusted_inviters),
"api_base_url": settings.api_base_url,
"database_path": settings.database_path,
"photo_pack_dirs": [str(path) for path in settings.photo_pack_dirs],
"report_at": f"{settings.report_hour:02d}:{settings.report_minute:02d}",
"cooldown_seconds": settings.cooldown_seconds,
"silence_seconds": settings.silence_seconds,
"log_level": settings.log_level,
"bind": f"{settings.bind_host}:{settings.bind_port}",
}
return api