signal-bot/signal_bot/manage/envkeys.py
Krzysztof kuhy Rudnicki bdd20654bf feat: the .env layer the management page will write through
envfile.py edits the file in place, line by line: only the KEY= line of a
key that actually changed is replaced, so the paragraph explaining why
GROUP_IDS is empty survives an edit made in a browser. A regenerated file
would be correct and would still lose most of what that file is for.
Temp-then-replace with the mode reapplied before the swap, because .env
holds the account number and is edited from a tab that can be closed
mid-save.

envkeys.py is the policy, as data. Nothing here re-implements validation:
load_config(candidate, use_dotenv=False) is what startup runs, so an edit
this bot would refuse at boot is refused at the form instead, with the
journal's own message.

Read-only is wider than "the phone number". API_BASE_URL repoints every
outgoing message and attachment fetch at the next restart, which is worse
than changing the number; DATABASE_PATH orphans the history; PHOTO_PACK_DIR
cannot be validated at all, because _photo_pack_dirs() reads os.environ
directly rather than the mapping it is handed -- deliberately, since that is
what keeps the suite away from a real album.

GROUP_IDS and SELFTEST_GROUPS are editable but refused while no group
listing has been read. parse_group_ids only checks syntax; startup also
requires the group to be one the bot actually joined, so writing one blind
with the container down turns a scoping mistake into a unit that will not
start.

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

107 lines
3.6 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Which ``.env`` keys a browser may write, and what makes an edit valid.
The tables are the whole policy and they are data, so "can the page change
this?" has one answer and it is greppable. Validation is deliberately not
re-implemented here: :func:`signal_bot.config_env.load_config` is what
startup runs, so handing it the candidate mapping means an edit this bot
would refuse at boot is refused at the form instead -- and an edit it accepts
here is one it will accept there.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Final
from signal_bot.config_env import load_config
from signal_bot.manage import envfile
if TYPE_CHECKING:
from collections.abc import Mapping
# Everything the page may write. The read-only remainder is still shown --
# "what is this bot configured with" is the first question the page answers --
# but PHONE_NUMBER, DATABASE_PATH, PHOTO_PACK_DIR and the bind address all
# name things outside the file, and changing them from a form would leave the
# container, the database or the album pointing somewhere that does not exist.
EDITABLE: Final = (
"GROUP_IDS",
"TRUSTED_INVITERS",
"SELFTEST_GROUPS",
"COOLDOWN_SECONDS",
"REPORT_HOUR",
"REPORT_MINUTE",
"SILENCE_SECONDS",
"LOG_LEVEL",
)
# Shown, never written.
READ_ONLY: Final = (
"PHONE_NUMBER",
"API_BASE_URL",
"DATABASE_PATH",
"PHOTO_PACK_DIR",
"BIND_HOST",
"BIND_PORT",
)
# Two of the editable keys name groups, and a group id is only meaningful
# against a listing that was actually read. With the container down the
# picker has nothing to offer, and a free-text fallback would let a
# syntactically valid write name a group the next startup rejects -- turning
# a scoping mistake into a failed unit. So these are refused in that state.
NEEDS_GROUPS: Final = ("GROUP_IDS", "SELFTEST_GROUPS")
def settings(text: str) -> list[dict[str, str | bool]]:
"""Every key the page shows, with whether it may be edited.
Args:
text: The current ``.env`` contents.
Returns:
One entry per known key, editable ones first, each carrying the
current value -- empty when the key is absent, which is how ``.env``
spells "use the default".
"""
values = envfile.parse(text)
return [
{"key": key, "value": values.get(key, ""), "editable": key in EDITABLE}
for key in (*EDITABLE, *READ_ONLY)
]
def refuse(changes: Mapping[str, str], *, groups_known: bool) -> str | None:
"""The first key that may not be written right now, or None.
Args:
changes: The edited keys and their new values.
groups_known: Whether a group listing was actually read. With the
container down it was not, and a group id checked only for syntax
can name a group the next startup rejects -- which turns a scoping
mistake into a unit that will not start.
Returns:
The offending key, or None when every change is allowed.
"""
for key in changes:
if key not in EDITABLE:
return key
if key in NEEDS_GROUPS and not groups_known:
return key
return None
def validate(text: str, changes: Mapping[str, str]) -> None:
"""Prove the bot could start on the edited file.
Args:
text: The current ``.env`` contents.
changes: The edited keys and their new values.
Raises:
ConfigError: The result is something ``load_config`` refuses. The
message is the one startup would print, verbatim.
"""
load_config(envfile.candidate(text, changes), use_dotenv=False)