From 9ad424d777609df1af1813e40043947b5563562b Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Sun, 22 Nov 2026 16:58:47 +0100 Subject: [PATCH] Verify store unblock/re-block; file failures Every store-window action now checks its result instead of trusting the commands: unblock needs no live store hosts line, no iptables chain and a reachable store (else "network down" when steamcommunity.com is down too), with one repair pass. Re-block needs every domain on a sinkhole and the store unreachable, and is not retried. A failure fails the job, names the check, and files one todo task (deduplicated by title) through the local todo MCP; re-block reports reach the web server via the new store_reports op. Job log times now show local time like the summary. Todo: 85af719b Co-Authored-By: Claude Opus 5.5 --- DOCS-ctl-socket.md | 15 ++ DOCS-web-control-api.md | 2 +- steam_backlog_enforcer/_ctl_client.py | 6 + steam_backlog_enforcer/_ctl_ops.py | 18 +- steam_backlog_enforcer/_store_verify.py | 238 ++++++++++++++++++ steam_backlog_enforcer/_store_window.py | 42 +++- steam_backlog_enforcer/_todo_filing.py | 185 ++++++++++++++ steam_backlog_enforcer/_web_privileged.py | 32 ++- steam_backlog_enforcer/_web_store_report.py | 95 +++++++ steam_backlog_enforcer/jobs/_daemon_jobs.py | 4 + steam_backlog_enforcer/main/misc.py | 12 + .../tests/_fake_todo_mcp.py | 91 +++++++ .../tests/_no_subprocess.py | 13 + .../tests/test_ctl_ops_privileged.py | 1 + .../tests/test_ctl_store_verify.py | 52 ++++ .../tests/test_store_verify.py | 196 +++++++++++++++ .../tests/test_store_window.py | 61 ++++- .../tests/test_todo_filing.py | 124 +++++++++ .../tests/test_web_store_report.py | 163 ++++++++++++ web/src/jobs/jobProgress.ts | 4 +- web/src/ui/format.test.ts | 17 +- web/src/ui/format.ts | 10 + web/vitest.config.ts | 2 + 23 files changed, 1366 insertions(+), 17 deletions(-) create mode 100644 steam_backlog_enforcer/_store_verify.py create mode 100644 steam_backlog_enforcer/_todo_filing.py create mode 100644 steam_backlog_enforcer/_web_store_report.py create mode 100644 steam_backlog_enforcer/tests/_fake_todo_mcp.py create mode 100644 steam_backlog_enforcer/tests/test_ctl_store_verify.py create mode 100644 steam_backlog_enforcer/tests/test_store_verify.py create mode 100644 steam_backlog_enforcer/tests/test_todo_filing.py create mode 100644 steam_backlog_enforcer/tests/test_web_store_report.py diff --git a/DOCS-ctl-socket.md b/DOCS-ctl-socket.md index 1fbe35e..1250d4f 100644 --- a/DOCS-ctl-socket.md +++ b/DOCS-ctl-socket.md @@ -74,6 +74,21 @@ Rate limit: 1 per 10 minutes, persisted in `/var/lib/steam-backlog-enforcer/ctl_restart.json` (root, 0600) so restarting the daemon does not reset it. +## Store checks + +`store_unblock` checks its own result (`_store_verify.py`): no live store line +in `/etc/hosts` in either family (`0.0.0.0` and `::`), the iptables store chain +gone, and `https://store.steampowered.com/` answering. A failure gets one +repair pass (unblock again, which also flushes DNS), then the op fails as +`op_failed` with `data.report = {action, check, title, body}`; `check` is the +first failing check, or `network down` when steamcommunity.com is unreachable +too. The web server (or the CLI) files the report as a todo task. + +The end-of-window re-block runs the reverse checks (every domain resolves only +to a sinkhole, the store does not answer) with no repair and no retry for that +deadline. A failure is queued in memory; `store_reports {}` hands the queue +back and clears it. The web server asks every 60 s and files each report. + ## Research game `research_game {"app_id": N}` and `research_game_revoke {}` (`_ctl_research_game.py`, diff --git a/DOCS-web-control-api.md b/DOCS-web-control-api.md index 62edc3f..d564d03 100644 --- a/DOCS-web-control-api.md +++ b/DOCS-web-control-api.md @@ -216,7 +216,7 @@ hard-codes it. Request `{"op": "", "args": {…}}`, response `{"ok": true, "data": …}` or `{"ok": false, "error": "", "message": "…"}`. - Allowlisted ops only: `ping`, `status`, `journal_tail{lines}`, - `store_unblock{minutes, phrase}`, `block_gaming{days, phrase}`, + `store_unblock{minutes, phrase}`, `store_reports{}`, `block_gaming{days, phrase}`, `gaming_unblock{phrase}`, `gaming_reset_arm{phrase}`, `gaming_reset_heartbeat{pending_id}`, `gaming_reset_commit{pending_id, phrase}`, `gaming_reset_cancel{pending_id}`, `restart{}`. There is no `stop`. diff --git a/steam_backlog_enforcer/_ctl_client.py b/steam_backlog_enforcer/_ctl_client.py index 1947266..fdbdd51 100644 --- a/steam_backlog_enforcer/_ctl_client.py +++ b/steam_backlog_enforcer/_ctl_client.py @@ -164,6 +164,12 @@ def journal_tail(lines: int = 50) -> list[str]: return [str(line) for line in cast("list[object]", data["lines"])] +def store_reports() -> list[dict[str, object]]: + """Take the daemon's queued failed re-block reports (it forgets them).""" + reports = call("store_reports").get("reports") or [] + return [r for r in cast("list[object]", reports) if isinstance(r, dict)] + + def store_unblock(minutes: int, phrase: str) -> StoreWindow: """Open the store for *minutes* (1-30); *phrase* is checked by the daemon.""" data = call( diff --git a/steam_backlog_enforcer/_ctl_ops.py b/steam_backlog_enforcer/_ctl_ops.py index 3e3a15e..0fc43e9 100644 --- a/steam_backlog_enforcer/_ctl_ops.py +++ b/steam_backlog_enforcer/_ctl_ops.py @@ -28,7 +28,12 @@ from steam_backlog_enforcer._ctl_reset import RESET_OPS from steam_backlog_enforcer._ctl_restart import RESTART_OPS, restart_available_at from steam_backlog_enforcer._fast_install_progress import fast_install_status from steam_backlog_enforcer._playtime_block import release_block -from steam_backlog_enforcer._store_window import MAX_WINDOW_MINUTES, open_store_window +from steam_backlog_enforcer._store_verify import StoreVerifyError +from steam_backlog_enforcer._store_window import ( + MAX_WINDOW_MINUTES, + open_store_window, + take_store_reports, +) from steam_backlog_enforcer._total_block import ( get_total_block_status, start_total_block, @@ -129,6 +134,11 @@ def op_store_unblock(ctx: CtlContext, args: dict[str, object]) -> dict[str, obje check_locks("unblock") try: until = open_store_window(State.load(), minutes) + except StoreVerifyError as exc: + # The web server files the report as a todo task: it runs as the + # desktop user, who owns the todo token. + data: dict[str, object] = {"report": exc.report.to_wire()} + raise CtlError(OP_FAILED, str(exc), data) from exc except RuntimeError as exc: raise CtlError(OP_FAILED, str(exc)) from exc finally: @@ -137,6 +147,11 @@ def op_store_unblock(ctx: CtlContext, args: dict[str, object]) -> dict[str, obje return {"minutes": minutes, "until": until.isoformat()} +def op_store_reports(_ctx: CtlContext, _args: dict[str, object]) -> dict[str, object]: + """Hand back (and forget) the failed end-of-window re-block reports.""" + return {"reports": take_store_reports()} + + def op_block_gaming(ctx: CtlContext, args: dict[str, object]) -> dict[str, object]: """Start a total gaming block of *days* days. There is no undo.""" days = int_arg(args, "days", 1, MAX_BLOCK_DAYS) @@ -164,6 +179,7 @@ OPS: Final[dict[str, Callable[[CtlContext, dict[str, object]], dict[str, object] "status": op_status, "journal_tail": op_journal_tail, "store_unblock": op_store_unblock, + "store_reports": op_store_reports, "block_gaming": op_block_gaming, "gaming_unblock": op_gaming_unblock, **RESET_OPS, diff --git a/steam_backlog_enforcer/_store_verify.py b/steam_backlog_enforcer/_store_verify.py new file mode 100644 index 0000000..f70b267 --- /dev/null +++ b/steam_backlog_enforcer/_store_verify.py @@ -0,0 +1,238 @@ +"""Check that a store unblock or re-block really did what it reports. + +An unblock once reported "Success" while a live ``::`` hosts line kept the +store blocked: nothing looked at the result. Every store-window action now +runs these checks and fails loudly when one does not hold. + +Unblock checks, in order (the first failing one names the failure): + hosts -- no live store line in /etc/hosts (either address family); + iptables -- the store chain is gone; + https -- ``https://store.steampowered.com/`` answers. +When only ``https`` fails and ``https://steamcommunity.com/`` fails too, the +machine is offline: the result is "network down", not an unblock failure. + +Re-block checks (the reverse): + dns -- every store domain resolves only to a sinkhole; + https -- the store does not answer. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime +import shutil +import subprocess +from typing import TYPE_CHECKING, Final + +from steam_backlog_enforcer._hosts_lines import ( + SINKHOLES, + live_store_lines, + store_lines, +) +from steam_backlog_enforcer._store_tools import IPTABLES, IPTABLES_CHAIN, SUDO +from steam_backlog_enforcer.config import BLOCKED_DOMAINS, HOSTS_FILE + +if TYPE_CHECKING: + from collections.abc import Callable + +UNBLOCK: Final = "unblock" +REBLOCK: Final = "re-block" +NETWORK_DOWN: Final = "network down" +STORE_URL: Final = "https://store.steampowered.com/" +CONTROL_URL: Final = "https://steamcommunity.com/" + +CURL: Final = shutil.which("curl") or "/usr/bin/curl" +GETENT: Final = shutil.which("getent") or "/usr/bin/getent" +JOURNALCTL: Final = shutil.which("journalctl") or "/usr/bin/journalctl" +_UNIT: Final = "steam-backlog-enforcer.service" +# curl's --max-time bounds the whole request, IPv6-then-IPv4 fallback included. +_HTTPS_SECONDS: Final = 8 +_GETENT_SECONDS: Final = 2 +_JOURNAL_SECONDS: Final = 5 +_JOURNAL_LINES: Final = 50 + + +@dataclass(frozen=True) +class Check: + """One check's outcome: its name, whether it held, and what was seen.""" + + name: str + ok: bool + detail: str + + +@dataclass +class StoreCheckReport: + """Every check of one action, plus the evidence a failure report needs.""" + + action: str + at: str + checks: list[Check] + network_down: bool = False + repaired: bool = False + evidence: dict[str, str] = field(default_factory=dict) + + @property + def ok(self) -> bool: + """Whether every check held.""" + return not self.network_down and all(c.ok for c in self.checks) + + @property + def failed_check(self) -> str | None: + """The failure: "network down", the first failed check, or None.""" + if self.network_down: + return NETWORK_DOWN + return next((c.name for c in self.checks if not c.ok), None) + + @property + def title(self) -> str: + """The todo task title for this failure.""" + return f"Store {self.action} verification failed: {self.failed_check}" + + def body(self) -> str: + """The failure report as markdown, for the todo task.""" + rows = [ + f"- {c.name}: {'ok' if c.ok else 'FAILED'} ({c.detail})" + for c in self.checks + ] + parts = [ + f"Time: {self.at}", + f"Action: {self.action}", + f"Repair pass run: {'yes' if self.repaired else 'no'}", + f"Result: {self.failed_check or 'ok'}", + "", + "## Checks", + *rows, + ] + for name, text in self.evidence.items(): + parts += ["", f"## {name}", "```", text.rstrip() or "(empty)", "```"] + return "\n".join(parts) + "\n" + + def to_wire(self) -> dict[str, object]: + """What the daemon hands the web server for filing.""" + return { + "action": self.action, + "check": self.failed_check, + "title": self.title, + "body": self.body(), + } + + +class StoreVerifyError(RuntimeError): + """A store action ran but its checks failed, even after the repair pass.""" + + def __init__(self, report: StoreCheckReport) -> None: + """Keep *report* for the caller to show and file.""" + super().__init__(f"Store {report.action} failed: {report.failed_check}") + self.report = report + + +def _run(cmd: list[str], timeout: float) -> tuple[int, str]: + """Run *cmd*; its exit code and combined output (``-1`` if it never ran).""" + try: + done = subprocess.run( + cmd, + capture_output=True, + text=True, + errors="replace", + timeout=timeout, + check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + return -1, str(exc) + return done.returncode, (done.stdout + done.stderr).strip() + + +def https_reachable(url: str) -> tuple[bool, str]: + """Whether *url* answers at all (any HTTP status counts as reachable).""" + cmd = [CURL, "-sS", "-o", "/dev/null", "-w", "%{http_code}"] + rc, out = _run([*cmd, "--max-time", str(_HTTPS_SECONDS), url], _HTTPS_SECONDS + 2) + return rc == 0, f"curl rc={rc} {out}".strip() + + +def resolve(domain: str) -> tuple[set[str], str]: + """Addresses *domain* resolves to via NSS (what curl and Steam see).""" + _rc, out = _run([GETENT, "ahosts", domain], _GETENT_SECONDS) + return {line.split()[0] for line in out.splitlines() if line.split()}, out + + +def _hosts_text() -> str: + try: + return HOSTS_FILE.read_text(encoding="utf-8") + except OSError as exc: + return f"(unreadable: {exc})" + + +def _chain_rules() -> tuple[bool, str]: + """Whether the store chain exists, and ``iptables -S`` for it.""" + rc, out = _run([SUDO, IPTABLES, "-S", IPTABLES_CHAIN], 5) + return rc == 0, out + + +def check_unblock() -> StoreCheckReport: + """Run the unblock checks once.""" + live = live_store_lines(_hosts_text()) + chain, _rules = _chain_rules() + store_ok, store_detail = https_reachable(STORE_URL) + checks = [ + Check("hosts", not live, f"{len(live)} live store line(s)"), + Check("iptables", not chain, "chain present" if chain else "chain gone"), + Check("https", store_ok, store_detail), + ] + report = StoreCheckReport(UNBLOCK, _now(), checks) + if not live and not chain and not store_ok: + report.network_down = not https_reachable(CONTROL_URL)[0] + return report + + +def check_reblock() -> StoreCheckReport: + """Run the re-block checks once.""" + leaks = {} + for domain in BLOCKED_DOMAINS: + addrs, _ = resolve(domain) + if not addrs or not addrs <= SINKHOLES: + leaks[domain] = ",".join(sorted(addrs)) or "no answer" + store_open, detail = https_reachable(STORE_URL) + leak_text = "; ".join(f"{d} -> {a}" for d, a in leaks.items()) + checks = [ + Check("dns", not leaks, leak_text or "every domain sinkholed"), + Check("https", not store_open, detail), + ] + return StoreCheckReport(REBLOCK, _now(), checks) + + +def _now() -> str: + return datetime.now().astimezone().isoformat(timespec="seconds") + + +def gather_evidence(report: StoreCheckReport) -> None: + """Attach hosts lines, the chain, getent per domain and the journal tail.""" + getent = [f"$ getent ahosts {d}\n{resolve(d)[1]}" for d in BLOCKED_DOMAINS] + journal = [JOURNALCTL, "-u", _UNIT, "-n", str(_JOURNAL_LINES), "--no-pager", "-q"] + report.evidence = { + "/etc/hosts store lines": "\n".join(store_lines(_hosts_text())), + f"iptables -S {IPTABLES_CHAIN}": _chain_rules()[1], + "getent": "\n".join(getent), + "Daemon journal (last 50 lines)": _run(journal, _JOURNAL_SECONDS)[1], + } + + +def verify( + check: Callable[[], StoreCheckReport], + repair: Callable[[], object] | None = None, +) -> StoreCheckReport: + """Run *check*; on failure run *repair* once and check again. + + The report that comes back carries the evidence when it failed. + """ + report = check() + if report.ok: + return report + if repair is not None: + repair() + report = check() + report.repaired = True + if report.ok: + return report + gather_evidence(report) + return report diff --git a/steam_backlog_enforcer/_store_window.py b/steam_backlog_enforcer/_store_window.py index b929528..0e383a5 100644 --- a/steam_backlog_enforcer/_store_window.py +++ b/steam_backlog_enforcer/_store_window.py @@ -17,8 +17,15 @@ from __future__ import annotations from datetime import UTC, datetime, timedelta import logging +import threading from typing import TYPE_CHECKING +from steam_backlog_enforcer._store_verify import ( + StoreVerifyError, + check_reblock, + check_unblock, + verify, +) from steam_backlog_enforcer.store_blocker import ( block_store, hosts_blocks_store, @@ -37,6 +44,20 @@ MAX_WINDOW_MINUTES = 30 # purpose (see module docstring); a restarted daemon re-blocks at startup anyway. _reblocked_for: set[str] = set() +# Failed re-block checks waiting for the web server to file them (it runs as +# the desktop user and asks through the ``store_reports`` socket op). The +# enforce loop appends, the control-socket thread takes: hence the lock. +_pending_reports: list[dict[str, object]] = [] +_reports_lock = threading.Lock() + + +def take_store_reports() -> list[dict[str, object]]: + """Hand back, and forget, every failed re-block report queued so far.""" + with _reports_lock: + reports = list(_pending_reports) + _pending_reports.clear() + return reports + def open_store_window(state: State, minutes: int) -> datetime: """Record a store window ending *minutes* from now and unblock at once. @@ -50,7 +71,9 @@ def open_store_window(state: State, minutes: int) -> datetime: Raises: ValueError: If *minutes* is out of range. - RuntimeError: If the store could not be unblocked right now. + StoreVerifyError: If the store is still blocked after one repair + pass. The deadline stays saved, so the window-end re-block + undoes a half-done unblock. """ if not 1 <= minutes <= MAX_WINDOW_MINUTES: msg = f"minutes must be between 1 and {MAX_WINDOW_MINUTES}, got {minutes}" @@ -58,9 +81,13 @@ def open_store_window(state: State, minutes: int) -> datetime: until = datetime.now(UTC) + timedelta(minutes=minutes) state.store_unblocked_until = until.isoformat() state.save() - if not unblock_store(): - msg = "could not unblock the store (sudo?)" - raise RuntimeError(msg) + unblock_store() + # The checks, not unblock_store's return value, decide: a "success" + # once left the store blocked by a live IPv6 hosts line. + report = verify(check_unblock, unblock_store) + if not report.ok: + logger.error("Store unblock failed its checks: %s", report.failed_check) + raise StoreVerifyError(report) return until @@ -101,3 +128,10 @@ def store_window_tick(config: Config, state: State) -> None: if config.block_store: logger.info("Store window ended at %s: re-blocking the store", until) block_store() + # No retry for this deadline even on failure (kuhy, 2026-11-22): the + # report gets filed, and a restarted daemon re-blocks at startup. + report = verify(check_reblock) + if not report.ok: + logger.error("Store re-block failed its checks: %s", report.failed_check) + with _reports_lock: + _pending_reports.append(report.to_wire()) diff --git a/steam_backlog_enforcer/_todo_filing.py b/steam_backlog_enforcer/_todo_filing.py new file mode 100644 index 0000000..9d8f940 --- /dev/null +++ b/steam_backlog_enforcer/_todo_filing.py @@ -0,0 +1,185 @@ +"""File a failed store check as a task in kuhy's todo app (local MCP server). + +Runs as the desktop user (web server or CLI), who owns the todo token; the +root daemon only builds the report. Stdlib only: a minimal MCP +streamable-HTTP client (initialize, ``Mcp-Session-Id``, ``tools/call``). + +One task per failure kind: when an open task with the same title exists, +nothing is filed or appended. Any failure to reach the server raises +:class:`FilingError`, so the caller can fail loudly instead of quietly. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import http.client +import json +import os +from pathlib import Path +import re +from typing import TYPE_CHECKING, Any, Final +from urllib.parse import urlsplit + +if TYPE_CHECKING: + from collections.abc import Mapping + +REPO: Final = "kuhyx/steam-backlog-enforcer" +DEFAULT_URL: Final = "http://127.0.0.1:8735/mcp" +_PROTOCOL: Final = "2025-03-26" +_TIMEOUT_SECONDS: Final = 10.0 +_COLUMNS: Final = 5 +_HTTP_ERROR: Final = 400 + + +class FilingError(Exception): + """The todo MCP server could not be reached or refused the call.""" + + +@dataclass(frozen=True) +class Filed: + """What filing did: ``created`` a task, or found ``existing`` open one.""" + + created: bool + task: str + + +def _settings(env: Mapping[str, str]) -> tuple[str, Path]: + """The MCP URL and token file (``SBE_TODO_MCP_URL`` / ``SBE_TODO_TOKEN_FILE``).""" + url = env.get("SBE_TODO_MCP_URL") or DEFAULT_URL + default_token = Path.home() / ".config" / "todo-mcp-client" / "token" + return url, Path(env.get("SBE_TODO_TOKEN_FILE") or default_token) + + +class _Mcp: + """One MCP session over streamable HTTP.""" + + def __init__(self, url: str, token: str) -> None: + if not url.startswith(("http://", "https://")): + msg = f"unsupported MCP url: {url}" + raise FilingError(msg) + self._url = url + self._token = token + self._session: str | None = None + self._next_id = 0 + + def _post(self, payload: dict[str, Any]) -> tuple[str, str, str | None]: + headers = { + "Authorization": f"Bearer {self._token}", + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + } + if self._session: + headers["Mcp-Session-Id"] = self._session + parts = urlsplit(self._url) + conn_type = ( + http.client.HTTPSConnection + if parts.scheme == "https" + else http.client.HTTPConnection + ) + conn = conn_type(parts.netloc, timeout=_TIMEOUT_SECONDS) + try: + conn.request("POST", parts.path or "/", json.dumps(payload), headers) + reply = conn.getresponse() + body = reply.read().decode("utf-8", "replace") + except (OSError, http.client.HTTPException) as err: + msg = f"todo MCP {self._url} unreachable: {err}" + raise FilingError(msg) from err + finally: + conn.close() + if reply.status >= _HTTP_ERROR: + msg = f"todo MCP {self._url}: HTTP {reply.status}" + raise FilingError(msg) + ctype = reply.getheader("Content-Type", "") + return ctype, body, reply.getheader("Mcp-Session-Id") + + def _rpc(self, method: str, params: dict[str, Any]) -> dict[str, Any]: + self._next_id += 1 + payload = {"jsonrpc": "2.0", "id": self._next_id, "method": method} + ctype, body, session = self._post(payload | {"params": params}) + if method == "initialize": + self._session = session + message = _parse(ctype, body) + if "error" in message: + msg = f"todo MCP {method}: {message['error']}" + raise FilingError(msg) + return message.get("result", {}) + + def call(self, tool: str, arguments: dict[str, object]) -> str: + """Call *tool*; its text, or :class:`FilingError` if it reports one.""" + if self._next_id == 0: + info = {"name": "steam-backlog-enforcer", "version": "1"} + self._rpc( + "initialize", + {"protocolVersion": _PROTOCOL, "capabilities": {}, "clientInfo": info}, + ) + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + result = self._rpc("tools/call", {"name": tool, "arguments": arguments}) + text = "\n".join( + part.get("text", "") + for part in result.get("content", []) + if part.get("type") == "text" + ) + if result.get("isError"): + msg = f"todo MCP {tool}: {text}" + raise FilingError(msg) + return text + + +def _parse(ctype: str, body: str) -> dict[str, Any]: + """The JSON-RPC message in a JSON or server-sent-events reply.""" + rows = [body] + if "text/event-stream" in ctype: + rows = [r.removeprefix("data:").strip() for r in body.splitlines()] + for raw in rows: + try: + message = json.loads(raw) + except json.JSONDecodeError: + continue + if isinstance(message, dict): + return message + msg = f"todo MCP sent an unparsable reply: {body[:80]!r}" + raise FilingError(msg) + + +def _open_task(listing: str, title: str) -> str | None: + """The id of an open task in *listing* titled exactly *title*.""" + for row in listing.splitlines(): + parts = row.split("\t") + if len(parts) >= _COLUMNS and re.sub(r"^#+\s*", "", parts[4].strip()) == title: + return parts[0] + return None + + +def file_report( + report: Mapping[str, object], env: Mapping[str, str] | None = None +) -> Filed: + """File *report* (``title`` + ``body``) unless an open task has its title. + + Raises: + FilingError: No token, the server is unreachable, or a call failed. + """ + url, token_file = _settings(os.environ if env is None else env) + try: + token = token_file.read_text(encoding="utf-8").strip() + except OSError as exc: + msg = f"no todo MCP token at {token_file}: {exc}" + raise FilingError(msg) from exc + title = str(report["title"]) + client = _Mcp(url, token) + existing = _open_task( + client.call("list_tasks", {"repo": REPO, "status": "open"}), title + ) + if existing is not None: + return Filed(created=False, task=existing) + reply = client.call( + "add_task", + { + "repo": REPO, + "title": title, + "body": str(report["body"]), + "done_check": "none", + "priority": "medium", + "new_note": True, + }, + ) + return Filed(created=True, task=reply.split("\n", 1)[0]) diff --git a/steam_backlog_enforcer/_web_privileged.py b/steam_backlog_enforcer/_web_privileged.py index aa3ef4e..48c0851 100644 --- a/steam_backlog_enforcer/_web_privileged.py +++ b/steam_backlog_enforcer/_web_privileged.py @@ -20,10 +20,12 @@ from http import HTTPStatus from typing import TYPE_CHECKING, Final from steam_backlog_enforcer import _ctl_client +from steam_backlog_enforcer._ctl_protocol import CtlError from steam_backlog_enforcer._store_window import DEFAULT_WINDOW_MINUTES from steam_backlog_enforcer._web_daemon import daemon_call, pending_action from steam_backlog_enforcer._web_errors import ApiError from steam_backlog_enforcer._web_io import Reply +from steam_backlog_enforcer._web_store_report import filing_log from steam_backlog_enforcer.jobs._daemon_jobs import ( EXIT_FAILED, EXIT_OK, @@ -37,6 +39,7 @@ if TYPE_CHECKING: from collections.abc import Callable, Mapping from steam_backlog_enforcer._command_params import ParamValue + from steam_backlog_enforcer._ctl_types import StoreWindow type Outcome = tuple[str, dict[str, object]] type Op = Callable[[Mapping[str, ParamValue], str], Outcome] @@ -55,9 +58,29 @@ def _local_hhmm(iso: str | None) -> str: return iso +class StoreCheckFailedError(ApiError): + """``op_failed`` from a store window whose checks failed, with the report.""" + + def __init__(self, message: str, report: Mapping[str, object]) -> None: + """Keep *report* so the job can file it.""" + super().__init__(message, code="op_failed") + self.report = report + + +def _open_window(minutes: int, phrase: str) -> StoreWindow: + """``store_unblock``, keeping a failed check's report on the error.""" + try: + return _ctl_client.store_unblock(minutes, phrase) + except CtlError as exc: + report = exc.data.get("report") + if isinstance(report, dict): + raise StoreCheckFailedError(exc.message, report) from None + raise + + def _store_window(minutes: int, phrase: str) -> Outcome: """Open the store for *minutes*.""" - window = daemon_call(_ctl_client.store_unblock, minutes, phrase) + window = daemon_call(_open_window, minutes, phrase) summary = ( f"Store unblocked for {window.minutes} min, until {_local_hhmm(window.until)}." ) @@ -133,7 +156,12 @@ def run_privileged( summary, data = op(params, typed) except ApiError as exc: if exc.code == "op_failed": - failed = DaemonOutcome(ok=False, summary=exc.message, exit_code=EXIT_FAILED) + log = ( + filing_log(exc.report) if isinstance(exc, StoreCheckFailedError) else () + ) + failed = DaemonOutcome( + ok=False, summary=exc.message, exit_code=EXIT_FAILED, log=log + ) record_daemon_job(command, params, created_at=created_at, outcome=failed) raise done = DaemonOutcome(ok=True, summary=summary, exit_code=EXIT_OK, data=data) diff --git a/steam_backlog_enforcer/_web_store_report.py b/steam_backlog_enforcer/_web_store_report.py new file mode 100644 index 0000000..95cf499 --- /dev/null +++ b/steam_backlog_enforcer/_web_store_report.py @@ -0,0 +1,95 @@ +"""Failed store checks as the web server sees them: job log lines and todo tasks. + +The daemon builds the report (``_store_verify``); the web server, running as +the desktop user, files it in the todo app. A failed unblock comes back on +the ``store_unblock`` call itself. A failed end-of-window re-block happens in +the daemon with nobody asking, so a background thread fetches those reports +every minute (``store_reports``) and records each as a failed job. + +The re-block job is recorded under the ``unblock`` command with +``params.phase = "re-block"``: the web UI knows only catalog commands, and a +new one would need its own icon. +""" + +from __future__ import annotations + +from datetime import datetime +import logging +import threading +from typing import TYPE_CHECKING, Final + +from steam_backlog_enforcer import _ctl_client +from steam_backlog_enforcer._ctl_protocol import CtlError, DaemonUnreachableError +from steam_backlog_enforcer._todo_filing import FilingError, file_report +from steam_backlog_enforcer.jobs._daemon_jobs import ( + EXIT_FAILED, + DaemonOutcome, + record_daemon_job, +) + +if TYPE_CHECKING: + from collections.abc import Mapping + +logger = logging.getLogger(__name__) + +POLL_SECONDS: Final = 60.0 + +type LogLines = tuple[tuple[str, str], ...] + + +def filing_log(report: Mapping[str, object]) -> LogLines: + """File *report* in the todo app; the job log lines saying what happened. + + Never raises: a filing failure becomes an ``error`` line, and the job it + lands in has already failed (non-zero exit), so nothing fails quietly. + """ + title = str(report.get("title", "?")) + try: + filed = file_report(report) + except FilingError as exc: + logger.exception("Could not file todo task %r", title) + return (("error", f"Could not file the todo task {title!r}: {exc}"),) + if filed.created: + return (("info", f"Filed todo task {title!r}: {filed.task}"),) + return (("info", f"Todo task {filed.task} is already open for {title!r}."),) + + +def record_reblock_failure(report: Mapping[str, object]) -> str: + """Record one failed re-block as a failed job, filing its task first.""" + outcome = DaemonOutcome( + ok=False, + summary=f"Store re-block failed: {report.get('check')}", + exit_code=EXIT_FAILED, + data={"check": report.get("check")}, + log=filing_log(report), + ) + created_at = datetime.now().astimezone().isoformat() + params = {"phase": "re-block"} + return record_daemon_job("unblock", params, created_at=created_at, outcome=outcome) + + +def collect_store_reports() -> int: + """Fetch the daemon's queued re-block failures and record each; the count.""" + try: + reports = _ctl_client.store_reports() + except (DaemonUnreachableError, CtlError) as exc: + logger.warning("store_reports: %s", exc) + return 0 + for report in reports: + try: + record_reblock_failure(report) + except OSError: + logger.exception("Could not record the failed re-block job") + return len(reports) + + +def start_store_report_poller(interval: float = POLL_SECONDS) -> threading.Event: + """Collect re-block reports every *interval* seconds until the event is set.""" + stop = threading.Event() + + def loop() -> None: + while not stop.wait(interval): + collect_store_reports() + + threading.Thread(target=loop, name="store-reports", daemon=True).start() + return stop diff --git a/steam_backlog_enforcer/jobs/_daemon_jobs.py b/steam_backlog_enforcer/jobs/_daemon_jobs.py index 83fcfc5..17e24b2 100644 --- a/steam_backlog_enforcer/jobs/_daemon_jobs.py +++ b/steam_backlog_enforcer/jobs/_daemon_jobs.py @@ -39,12 +39,14 @@ class DaemonOutcome: summary: One line for the job list and the ``result`` event. exit_code: ``0`` ok, ``1`` failed, ``2`` refused. data: Optional result data for the ``result`` event. + log: Extra ``(level, message)`` log lines after the summary. """ ok: bool summary: str exit_code: int data: Mapping[str, Any] | None = None + log: tuple[tuple[str, str], ...] = () def record_daemon_job( @@ -78,6 +80,8 @@ def record_daemon_job( writer.emit("state", state="queued") writer.emit("state", state="running") writer.emit("log", level="info" if ok else "error", message=summary) + for level, message in outcome.log: + writer.emit("log", level=level, message=message) result: dict[str, Any] = {"ok": ok, "summary": summary} if data is not None: result["data"] = json.loads(json.dumps(dict(data), default=str)) diff --git a/steam_backlog_enforcer/main/misc.py b/steam_backlog_enforcer/main/misc.py index 67c5174..b2bd9bd 100644 --- a/steam_backlog_enforcer/main/misc.py +++ b/steam_backlog_enforcer/main/misc.py @@ -18,6 +18,7 @@ from steam_backlog_enforcer._serve_startup import ( ensure_port_available, parse_serve_args, ) +from steam_backlog_enforcer._store_verify import StoreVerifyError from steam_backlog_enforcer._store_window import ( DEFAULT_WINDOW_MINUTES, MAX_WINDOW_MINUTES, @@ -26,6 +27,10 @@ from steam_backlog_enforcer._store_window import ( from steam_backlog_enforcer._total_block import start_total_block from steam_backlog_enforcer._web_build import build_frontend, frontend_is_stale from steam_backlog_enforcer._web_server import serve +from steam_backlog_enforcer._web_store_report import ( + filing_log, + start_store_report_poller, +) from steam_backlog_enforcer.game_install import _echo from steam_backlog_enforcer.library_hider import unhide_all_games @@ -57,6 +62,12 @@ def cmd_unblock(_config: Config, state: State, args: list[str] | None = None) -> except ValueError as exc: _echo(f"Usage: unblock [minutes] (1-{MAX_WINDOW_MINUTES}): {exc}") sys.exit(1) + except StoreVerifyError as exc: + # Runs as the desktop user, so it can file the todo task itself. + _echo(f"{exc} (the store is NOT open).") + for _level, line in filing_log(exc.report.to_wire()): + _echo(line) + sys.exit(1) except RuntimeError as exc: _echo(f"Failed to unblock: {exc}") sys.exit(1) @@ -136,6 +147,7 @@ def cmd_serve(args: list[str]) -> None: if frontend_is_stale() and not build_frontend(): sys.exit(1) ensure_port_available(host, port) + start_store_report_poller() try: serve(host, port) except OSError as exc: diff --git a/steam_backlog_enforcer/tests/_fake_todo_mcp.py b/steam_backlog_enforcer/tests/_fake_todo_mcp.py new file mode 100644 index 0000000..aa2ffe9 --- /dev/null +++ b/steam_backlog_enforcer/tests/_fake_todo_mcp.py @@ -0,0 +1,91 @@ +"""A fake todo MCP server: the list_tasks / add_task subset the filer uses. + +Speaks streamable HTTP like the real one (initialize hands out an +``Mcp-Session-Id``, replies as server-sent events) and keeps tasks in memory. +Run standalone for VM checks: ``python -m steam_backlog_enforcer.tests._fake_todo_mcp + ``; every add is also written to the dump file. +""" + +from __future__ import annotations + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import sys +import threading +from typing import Any + + +class FakeTodo(ThreadingHTTPServer): + """The server plus its task list.""" + + def __init__(self, port: int, token: str, dump: Path | None = None) -> None: + """Listen on 127.0.0.1:*port* (0 picks one).""" + super().__init__(("127.0.0.1", port), _Handler) + self.token = token + self.dump = dump + self.tasks: list[dict[str, Any]] = [] + self.calls: list[str] = [] + + @property + def url(self) -> str: + """The MCP endpoint URL.""" + return f"http://127.0.0.1:{self.server_address[1]}/mcp" + + def start(self) -> None: + """Serve in a daemon thread.""" + threading.Thread( + target=self.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True + ).start() + + def tool(self, name: str, args: dict[str, Any]) -> str: + """Answer one tool call the way the real server words it.""" + self.calls.append(name) + if name == "list_tasks": + rows = [ + f"{t['id'][:8]}\ttodo\t{t['priority']}\t{t['repo']}\t{t['title']}\tclaude" + for t in self.tasks + if t["repo"] == args.get("repo") + ] + return "\n".join(rows) or "no tasks match" + task = dict(args) | {"id": f"{len(self.tasks) + 1:08d}deadbeef"} + self.tasks.append(task) + if self.dump is not None: + self.dump.write_text(json.dumps(self.tasks, indent=2), encoding="utf-8") + return f"added {task['id']}\n{task['id'][:8]}\ttodo\tmedium\t{task['repo']}" + + +class _Handler(BaseHTTPRequestHandler): + server: FakeTodo + + def log_message(self, *_args: object) -> None: + """Stay quiet.""" + + def do_POST(self) -> None: + """One JSON-RPC message in, one SSE event out.""" + if self.headers.get("Authorization") != f"Bearer {self.server.token}": + self.send_response(401) + self.end_headers() + return + length = int(self.headers.get("Content-Length", "0")) + message = json.loads(self.rfile.read(length)) + if "id" not in message: # A notification. + self.send_response(202) + self.end_headers() + return + params = message.get("params", {}) + if message["method"] == "initialize": + result: dict[str, Any] = {"protocolVersion": params["protocolVersion"]} + else: + text = self.server.tool(params["name"], params.get("arguments", {})) + result = {"content": [{"type": "text", "text": text}]} + body = json.dumps({"jsonrpc": "2.0", "id": message["id"], "result": result}) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Mcp-Session-Id", "fake-session") + self.end_headers() + self.wfile.write(f"event: message\ndata: {body}\n\n".encode()) + + +if __name__ == "__main__": + FakeTodo(int(sys.argv[1]), sys.argv[2], Path(sys.argv[3])).serve_forever() diff --git a/steam_backlog_enforcer/tests/_no_subprocess.py b/steam_backlog_enforcer/tests/_no_subprocess.py index 6fc85cc..b14d444 100644 --- a/steam_backlog_enforcer/tests/_no_subprocess.py +++ b/steam_backlog_enforcer/tests/_no_subprocess.py @@ -6,6 +6,7 @@ Split out of ``conftest.py`` to keep every file inside the 250-line cap; from __future__ import annotations +import os from typing import TYPE_CHECKING from unittest.mock import MagicMock, patch @@ -106,5 +107,17 @@ def _block_real_subprocesses() -> Iterator[None]: "steam_backlog_enforcer._web_build.subprocess.run", noop_run, ), + # Store checks run curl, getent, iptables and journalctl; hosts edits + # run guardctl and sudo tee. + patch("steam_backlog_enforcer._store_verify.subprocess.run", noop_run), + patch("steam_backlog_enforcer._hosts_protection.subprocess.run", noop_run), + # The todo filer must never reach kuhy's real board from a test. + patch.dict( + os.environ, + { + "SBE_TODO_MCP_URL": "http://127.0.0.1:9/mcp", + "SBE_TODO_TOKEN_FILE": "/nonexistent/sbe-test-token", + }, + ), ): yield diff --git a/steam_backlog_enforcer/tests/test_ctl_ops_privileged.py b/steam_backlog_enforcer/tests/test_ctl_ops_privileged.py index aad37e5..d7e3598 100644 --- a/steam_backlog_enforcer/tests/test_ctl_ops_privileged.py +++ b/steam_backlog_enforcer/tests/test_ctl_ops_privileged.py @@ -176,6 +176,7 @@ class TestOpsTable: "status", "journal_tail", "store_unblock", + "store_reports", "block_gaming", "gaming_unblock", "gaming_reset_arm", diff --git a/steam_backlog_enforcer/tests/test_ctl_store_verify.py b/steam_backlog_enforcer/tests/test_ctl_store_verify.py new file mode 100644 index 0000000..09bd24d --- /dev/null +++ b/steam_backlog_enforcer/tests/test_ctl_store_verify.py @@ -0,0 +1,52 @@ +"""Control-socket side of the store checks: failed unblocks and re-block reports.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +from steam_backlog_enforcer import _ctl_ops +from steam_backlog_enforcer._ctl_protocol import CtlError +from steam_backlog_enforcer._store_verify import ( + Check, + StoreCheckReport, + StoreVerifyError, +) +from steam_backlog_enforcer.tests._ctl_fixtures import make_ctx + +if TYPE_CHECKING: + from collections.abc import Iterator + +_PHRASE = "unblock the store for 5 minutes" + + +@pytest.fixture(autouse=True) +def hand_back() -> Iterator[MagicMock]: + """Never chown the real state file.""" + with patch.object(_ctl_ops, "_hand_back_state_file") as fake: + yield fake + + +def test_failed_check_is_op_failed_with_report() -> None: + """A failed check is op_failed, naming the check and carrying the report.""" + report = StoreCheckReport("unblock", "t", [Check("https", ok=False, detail="x")]) + with ( + patch.object(_ctl_ops, "check_locks"), + patch.object( + _ctl_ops, "open_store_window", side_effect=StoreVerifyError(report) + ), + pytest.raises(CtlError) as caught, + ): + _ctl_ops.op_store_unblock(make_ctx(), {"minutes": 5, "phrase": _PHRASE}) + assert caught.value.code == "op_failed" + assert caught.value.message == "Store unblock failed: https" + assert caught.value.data["report"] == report.to_wire() + + +def test_store_reports_hands_back_queued_reports() -> None: + """store_reports returns what the window queued, then nothing.""" + queued = [{"title": "Store re-block verification failed: dns"}] + with patch.object(_ctl_ops, "take_store_reports", return_value=queued): + assert _ctl_ops.op_store_reports(make_ctx(), {}) == {"reports": queued} diff --git a/steam_backlog_enforcer/tests/test_store_verify.py b/steam_backlog_enforcer/tests/test_store_verify.py new file mode 100644 index 0000000..0c9a217 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_store_verify.py @@ -0,0 +1,196 @@ +"""Tests for the store unblock / re-block result checks.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +from steam_backlog_enforcer import _store_verify as sv +from steam_backlog_enforcer._store_verify import _run as run_command +from steam_backlog_enforcer.config import BLOCKED_DOMAINS + +if TYPE_CHECKING: + from collections.abc import Iterator + from pathlib import Path + +_STORE = "store.steampowered.com" +_V4 = ".".join(["0"] * 4) # The IPv4 sinkhole. + + +class FakeHost: + """Answers the commands the checks run, from settable machine state.""" + + def __init__(self, hosts: Path) -> None: + """Start as a correctly unblocked, online machine.""" + self.hosts = hosts + self.chain = False + self.reachable = {sv.STORE_URL: True, sv.CONTROL_URL: True} + self.resolves: dict[str, str] = dict.fromkeys(BLOCKED_DOMAINS, "1.2.3.4") + self.calls: list[list[str]] = [] + + def run(self, cmd: list[str], **_kw: object) -> MagicMock: + """Fake ``subprocess.run``.""" + self.calls.append(cmd) + out, rc = "", 0 + if cmd[0] == sv.CURL: + rc = 0 if self.reachable[cmd[-1]] else 7 + out = "200" if rc == 0 else "curl: (7) Failed to connect" + elif cmd[0] == sv.GETENT: + addr = self.resolves[cmd[-1]] + out = f"{addr} STREAM {cmd[-1]}\n" if addr else "" + rc = 0 if addr else 2 + elif "-S" in cmd: + rc = 0 if self.chain else 1 + out = "-N STEAM_ENFORCER\n-A STEAM_ENFORCER -d 1.2.3.4 -j DROP" + out = out if self.chain else "iptables: No chain/target/match." + elif cmd[0] == sv.JOURNALCTL: + out = "\n".join(f"journal line {i}" for i in range(50)) + return MagicMock(returncode=rc, stdout=out, stderr="") + + +@pytest.fixture(name="host") +def fixture_host(tmp_path: Path) -> Iterator[FakeHost]: + """A fake machine with an empty /etc/hosts.""" + hosts = tmp_path / "hosts" + fake = FakeHost(hosts) + hosts.write_text("127.0.0.1 localhost\n", encoding="utf-8") + with ( + patch(f"{sv.__name__}.subprocess.run", side_effect=fake.run), + patch(f"{sv.__name__}.HOSTS_FILE", hosts), + ): + yield fake + + +def _hosts(host: FakeHost, text: str) -> None: + host.hosts.write_text(text, encoding="utf-8") + + +@pytest.mark.usefixtures("host") +def test_unblock_all_checks_pass() -> None: + """A clean unblock passes and names no failed check.""" + report = sv.check_unblock() + assert report.ok + assert report.failed_check is None + + +def test_unblock_live_ipv6_line_fails_hosts(host: FakeHost) -> None: + """The bug kuhy hit: a live ``::`` line fails the hosts check.""" + _hosts(host, f"# 0.0.0.0 {_STORE}\n:: {_STORE}\n") + host.reachable[sv.STORE_URL] = False + report = sv.check_unblock() + assert not report.ok + assert report.failed_check == "hosts" + assert report.title == "Store unblock verification failed: hosts" + + +def test_unblock_chain_left_fails_iptables(host: FakeHost) -> None: + """A store chain still present fails the iptables check.""" + host.chain = True + assert sv.check_unblock().failed_check == "iptables" + + +def test_unblock_store_unreachable_fails_https(host: FakeHost) -> None: + """Store down while steamcommunity.com answers: an unblock failure.""" + host.reachable[sv.STORE_URL] = False + report = sv.check_unblock() + assert report.failed_check == "https" + assert not report.network_down + + +def test_unblock_both_unreachable_is_network_down(host: FakeHost) -> None: + """Store and steamcommunity.com both unreachable: network down.""" + host.reachable = dict.fromkeys(host.reachable, False) + report = sv.check_unblock() + assert not report.ok + assert report.failed_check == sv.NETWORK_DOWN + assert report.title == "Store unblock verification failed: network down" + + +def test_network_down_not_claimed_when_hosts_still_blocks(host: FakeHost) -> None: + """A live hosts line is named even when everything is unreachable.""" + _hosts(host, f":: {_STORE}\n") + host.reachable = dict.fromkeys(host.reachable, False) + assert sv.check_unblock().failed_check == "hosts" + + +def test_reblock_passes_when_sinkholed(host: FakeHost) -> None: + """Every domain on a sinkhole and the store unreachable: re-block ok.""" + host.resolves = {d: ("::" if i % 2 else _V4) for i, d in enumerate(BLOCKED_DOMAINS)} + host.reachable[sv.STORE_URL] = False + assert sv.check_reblock().ok + + +def test_reblock_leaking_domain_fails_dns(host: FakeHost) -> None: + """One domain resolving to a real address fails the dns check.""" + host.resolves = dict.fromkeys(BLOCKED_DOMAINS, _V4) + host.resolves[_STORE] = "23.1.1.1" + host.reachable[sv.STORE_URL] = False + report = sv.check_reblock() + assert report.failed_check == "dns" + assert _STORE in report.checks[0].detail + + +def test_reblock_store_answering_fails_https(host: FakeHost) -> None: + """Sinkholed names but the store still answers: https fails.""" + host.resolves = dict.fromkeys(BLOCKED_DOMAINS, _V4) + report = sv.check_reblock() + assert report.failed_check == "https" + assert report.title == "Store re-block verification failed: https" + + +def test_verify_repairs_once_then_passes(host: FakeHost) -> None: + """A failing check triggers one repair; a fixed machine then passes.""" + host.chain = True + + def repair() -> None: + host.chain = False + + report = sv.verify(sv.check_unblock, repair) + assert report.ok + assert report.repaired + + +def test_verify_gives_up_after_one_repair_with_evidence(host: FakeHost) -> None: + """Still failing after the repair: the report carries every evidence part.""" + _hosts(host, f"# 0.0.0.0 {_STORE}\n:: {_STORE}\n0.0.0.0 steamkarta.pl\n") + repair = MagicMock() + report = sv.verify(sv.check_unblock, repair) + repair.assert_called_once() + assert not report.ok + body = report.body() + assert "Action: unblock" in body + assert "- hosts: FAILED" in body + assert "- iptables: ok" in body + assert f":: {_STORE}" in body + assert "steamkarta" not in body + assert "iptables -S STEAM_ENFORCER" in body + assert all(f"getent ahosts {d}" in body for d in BLOCKED_DOMAINS) + assert "journal line 49" in body + wire = report.to_wire() + assert wire["title"] == "Store unblock verification failed: hosts" + assert wire["check"] == "hosts" + + +def test_verify_without_repair_checks_once(host: FakeHost) -> None: + """The re-block path has no repair: one check, then the evidence.""" + report = sv.verify(sv.check_reblock) + assert not report.ok + assert not report.repaired + curls = [c for c in host.calls if c[0] == sv.CURL] + assert len(curls) == 1 + + +def test_run_survives_missing_binary() -> None: + """A command that cannot start reports rc -1 instead of raising.""" + with patch(f"{sv.__name__}.subprocess.run", side_effect=OSError("nope")): + assert run_command(["x"], 1) == (-1, "nope") + + +def test_error_carries_report(host: FakeHost) -> None: + """StoreVerifyError keeps the report and names the check.""" + host.chain = True + err = sv.StoreVerifyError(sv.check_unblock()) + assert str(err) == "Store unblock failed: iptables" + assert err.report.failed_check == "iptables" diff --git a/steam_backlog_enforcer/tests/test_store_window.py b/steam_backlog_enforcer/tests/test_store_window.py index 0fe5e6a..db907c2 100644 --- a/steam_backlog_enforcer/tests/test_store_window.py +++ b/steam_backlog_enforcer/tests/test_store_window.py @@ -4,15 +4,21 @@ from __future__ import annotations from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pytest from steam_backlog_enforcer import _store_window +from steam_backlog_enforcer._store_verify import ( + Check, + StoreCheckReport, + StoreVerifyError, +) from steam_backlog_enforcer._store_window import ( MAX_WINDOW_MINUTES, open_store_window, store_window_tick, + take_store_reports, ) from steam_backlog_enforcer.config import Config, State @@ -25,10 +31,26 @@ PKG = "steam_backlog_enforcer._store_window" @pytest.fixture(autouse=True) def _fresh_reblock_memory() -> Iterator[None]: """Each test starts with a daemon that has re-blocked for nothing yet.""" - with patch.object(_store_window, "_reblocked_for", set()): + with ( + patch.object(_store_window, "_reblocked_for", set()), + patch.object(_store_window, "_pending_reports", []), + ): yield +def _report(action: str, *, ok: bool) -> StoreCheckReport: + return StoreCheckReport( + action, "2026-11-22T16:00:00+01:00", [Check("hosts", ok, "x")] + ) + + +@pytest.fixture(name="checks", autouse=True) +def fixture_checks() -> Iterator[MagicMock]: + """Every action's checks pass unless a test says otherwise.""" + with patch(f"{PKG}.verify", return_value=_report("unblock", ok=True)) as fake: + yield fake + + def _state_ending_in(delta: timedelta) -> State: """Return a state whose store window ends delta from now.""" return State(store_unblocked_until=(datetime.now(UTC) + delta).isoformat()) @@ -60,13 +82,18 @@ class TestOpenStoreWindow: assert until <= datetime.now(UTC) + timedelta(minutes=10) assert State.load().store_unblocked_until == until.isoformat() - def test_failed_unblock_raises(self) -> None: - """A failed unblock raises instead of claiming a window.""" + def test_failed_check_raises_and_keeps_deadline(self, checks: MagicMock) -> None: + """Checks failing after the repair raise; the deadline stays saved.""" + checks.return_value = _report("unblock", ok=False) with ( - patch(f"{PKG}.unblock_store", return_value=False), - pytest.raises(RuntimeError, match="could not unblock"), + patch(f"{PKG}.unblock_store", return_value=True) as mock_unblock, + pytest.raises(StoreVerifyError, match="unblock failed: hosts"), ): open_store_window(State(), 5) + check, repair = checks.call_args.args + assert check is _store_window.check_unblock + assert repair is mock_unblock + assert State.load().store_unblocked_until class TestStoreWindowTick: @@ -116,6 +143,28 @@ class TestStoreWindowTick: store_window_tick(Config(block_store=True), state) mock_block.assert_called_once() + def test_reblock_checked_and_failure_queued_once(self, checks: MagicMock) -> None: + """A failed re-block check queues one report and is never retried.""" + checks.return_value = _report("re-block", ok=False) + state = _state_ending_in(timedelta(seconds=-1)) + with patch(f"{PKG}.block_store") as mock_block: + store_window_tick(Config(block_store=True), state) + store_window_tick(Config(block_store=True), state) + mock_block.assert_called_once() + checks.assert_called_once_with(_store_window.check_reblock) + reports = take_store_reports() + assert [r["title"] for r in reports] == [ + "Store re-block verification failed: hosts" + ] + assert take_store_reports() == [] + + def test_reblock_passing_queues_nothing(self) -> None: + """A re-block whose checks pass leaves nothing to file.""" + state = _state_ending_in(timedelta(seconds=-1)) + with patch(f"{PKG}.block_store"): + store_window_tick(Config(block_store=True), state) + assert take_store_reports() == [] + def test_expired_window_respects_block_store_off(self) -> None: """With block_store off an expired window does not block.""" state = _state_ending_in(timedelta(seconds=-1)) diff --git a/steam_backlog_enforcer/tests/test_todo_filing.py b/steam_backlog_enforcer/tests/test_todo_filing.py new file mode 100644 index 0000000..8c2f5d7 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_todo_filing.py @@ -0,0 +1,124 @@ +"""Tests for filing failed store checks in the todo app (against a fake MCP).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from steam_backlog_enforcer._todo_filing import ( + FilingError, + _Mcp, + _parse, + _settings, + file_report, +) +from steam_backlog_enforcer.tests._fake_todo_mcp import FakeTodo + +if TYPE_CHECKING: + from collections.abc import Iterator + from pathlib import Path + +_REPORT = { + "title": "Store unblock verification failed: hosts", + "body": "Time: t\nAction: unblock\n", +} + + +@pytest.fixture(name="todo") +def fixture_todo() -> Iterator[FakeTodo]: + """A running fake todo MCP server.""" + server = FakeTodo(0, "tok") + server.start() + yield server + server.shutdown() + server.server_close() + + +_GOOD = "tok" + + +def _env(todo: FakeTodo, tmp_path: Path, secret: str = _GOOD) -> dict[str, str]: + token_file = tmp_path / "token" + token_file.write_text(f"{secret}\n", encoding="utf-8") + return {"SBE_TODO_MCP_URL": todo.url, "SBE_TODO_TOKEN_FILE": str(token_file)} + + +def test_files_one_task_with_report(todo: FakeTodo, tmp_path: Path) -> None: + """A new failure is filed once: repo, title, body, done_check none.""" + filed = file_report(_REPORT, _env(todo, tmp_path)) + assert filed.created + assert filed.task.startswith("added ") + [task] = todo.tasks + assert task["repo"] == "kuhyx/steam-backlog-enforcer" + assert task["title"] == _REPORT["title"] + assert task["body"] == _REPORT["body"] + assert task["done_check"] == "none" + assert task["priority"] == "medium" + assert task["new_note"] is True + + +def test_open_task_with_same_title_files_nothing( + todo: FakeTodo, tmp_path: Path +) -> None: + """The second identical failure finds the open task and adds nothing.""" + env = _env(todo, tmp_path) + file_report(_REPORT, env) + again = file_report(_REPORT, env) + assert not again.created + assert again.task == "00000001" + assert len(todo.tasks) == 1 + assert todo.calls == ["list_tasks", "add_task", "list_tasks"] + + +def test_other_title_is_filed(todo: FakeTodo, tmp_path: Path) -> None: + """A different check is a different task.""" + env = _env(todo, tmp_path) + file_report(_REPORT, env) + file_report(_REPORT | {"title": "Store unblock verification failed: https"}, env) + assert len(todo.tasks) == 2 + + +def test_server_down_raises(tmp_path: Path) -> None: + """No server listening is a FilingError, never a silent pass.""" + server = FakeTodo(0, "tok") + env = _env(server, tmp_path) + server.server_close() + with pytest.raises(FilingError, match="unreachable"): + file_report(_REPORT, env) + + +def test_bad_token_raises(todo: FakeTodo, tmp_path: Path) -> None: + """A rejected token is a FilingError naming the HTTP status.""" + with pytest.raises(FilingError, match="HTTP 401"): + file_report(_REPORT, _env(todo, tmp_path, "wrong")) + + +def test_missing_token_file_raises(todo: FakeTodo, tmp_path: Path) -> None: + """No token file is a FilingError.""" + env = {"SBE_TODO_MCP_URL": todo.url, "SBE_TODO_TOKEN_FILE": str(tmp_path / "x")} + with pytest.raises(FilingError, match="no todo MCP token"): + file_report(_REPORT, env) + + +def test_defaults_point_at_live_server() -> None: + """Without env the filer targets the local todo MCP and kuhy's token.""" + url, token = _settings({}) + assert url == "http://127.0.0.1:8735/mcp" + assert token.parts[-2:] == ("todo-mcp-client", "token") + + +def test_unsupported_url_raises() -> None: + """Only http(s) URLs are accepted.""" + with pytest.raises(FilingError, match="unsupported"): + _Mcp("file:///x", "t") + + +@pytest.mark.parametrize( + ("ctype", "body"), + [("application/json", "not json"), ("text/event-stream", "data: [1]")], +) +def test_unparsable_reply_raises(ctype: str, body: str) -> None: + """A reply with no JSON-RPC object in it is a FilingError.""" + with pytest.raises(FilingError, match="unparsable"): + _parse(ctype, body) diff --git a/steam_backlog_enforcer/tests/test_web_store_report.py b/steam_backlog_enforcer/tests/test_web_store_report.py new file mode 100644 index 0000000..0aa3c02 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_web_store_report.py @@ -0,0 +1,163 @@ +"""Failed store checks in the web server and CLI: failed jobs and todo tasks.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +from steam_backlog_enforcer import _web_privileged, _web_store_report +from steam_backlog_enforcer._ctl_protocol import CtlError, DaemonUnreachableError +from steam_backlog_enforcer._store_verify import ( + Check, + StoreCheckReport, + StoreVerifyError, +) +from steam_backlog_enforcer._todo_filing import Filed, FilingError +from steam_backlog_enforcer._web_errors import ApiError +from steam_backlog_enforcer.config import Config, State +from steam_backlog_enforcer.jobs import _store +from steam_backlog_enforcer.jobs._events import read_events +from steam_backlog_enforcer.jobs._view import list_jobs +from steam_backlog_enforcer.main.misc import cmd_unblock + +if TYPE_CHECKING: + from collections.abc import Iterator + +_REPORTS = "steam_backlog_enforcer._web_store_report" +_CLIENT = "steam_backlog_enforcer._web_privileged._ctl_client" +_REPORT = { + "action": "unblock", + "check": "https", + "title": "Store unblock verification failed: https", + "body": "Time: t\n", +} + + +@pytest.fixture(name="filer") +def fixture_filer() -> Iterator[MagicMock]: + """The todo filer, faked: files a new task unless told otherwise.""" + filed = Filed(created=True, task="added abc") + with patch(f"{_REPORTS}.file_report", return_value=filed) as f: + yield f + + +def _messages(job_id: str) -> list[str]: + events = read_events(_store.JOBS_DIR / job_id) + return [str(e["message"]) for e in events if e.get("type") == "log"] + + +def _failed_unblock() -> CtlError: + return CtlError("op_failed", "Store unblock failed: https", {"report": _REPORT}) + + +def test_failed_unblock_job_fails_and_files_task(filer: MagicMock) -> None: + """op_failed with a report: failed job naming the check, one task filed.""" + with ( + patch(f"{_CLIENT}.store_unblock", side_effect=_failed_unblock()), + pytest.raises(ApiError) as err, + ): + _web_privileged.run_privileged("unblock", {"minutes": 5}, "p") + assert err.value.code == "op_failed" + filer.assert_called_once_with(_REPORT) + (job,) = list_jobs() + assert (job["state"], job["exit_code"]) == ("failed", 1) + assert job["summary"] == "Store unblock failed: https" + log = _messages(str(job["id"])) + assert "Filed todo task 'Store unblock verification failed: https'" in log[1] + + +def test_already_open_task_is_logged_not_refiled(filer: MagicMock) -> None: + """A second failure says the task is already open.""" + filer.return_value = Filed(created=False, task="1234abcd") + with ( + patch(f"{_CLIENT}.store_unblock", side_effect=_failed_unblock()), + pytest.raises(ApiError), + ): + _web_privileged.run_privileged("unblock", {"minutes": 5}, "p") + (job,) = list_jobs() + assert "1234abcd is already open" in _messages(str(job["id"]))[1] + + +def test_filing_failure_is_in_the_log_and_job_is_non_zero(filer: MagicMock) -> None: + """MCP down: the job log says the task could not be filed; exit is 1.""" + filer.side_effect = FilingError("todo MCP unreachable") + with ( + patch(f"{_CLIENT}.store_unblock", side_effect=_failed_unblock()), + pytest.raises(ApiError), + ): + _web_privileged.run_privileged("unblock", {"minutes": 5}, "p") + (job,) = list_jobs() + assert job["exit_code"] == 1 + assert "Could not file the todo task" in _messages(str(job["id"]))[1] + + +def test_op_failed_without_report_files_nothing(filer: MagicMock) -> None: + """A plain op_failed (no report) is recorded and files nothing.""" + with ( + patch(f"{_CLIENT}.store_unblock", side_effect=CtlError("op_failed", "x")), + pytest.raises(ApiError), + ): + _web_privileged.run_privileged("unblock", {"minutes": 5}, "p") + filer.assert_not_called() + assert len(list_jobs()) == 1 + + +def test_collect_records_one_failed_reblock_job_per_report(filer: MagicMock) -> None: + """Each queued re-block report becomes a failed job and a filed task.""" + report = _REPORT | {"action": "re-block", "check": "dns"} + with patch(f"{_REPORTS}._ctl_client.store_reports", return_value=[report]): + assert _web_store_report.collect_store_reports() == 1 + (job,) = list_jobs() + assert job["summary"] == "Store re-block failed: dns" + assert job["state"] == "failed" + filer.assert_called_once_with(report) + + +@pytest.mark.parametrize("error", [DaemonUnreachableError("x"), CtlError("a", "b")]) +def test_collect_survives_daemon_errors(error: Exception) -> None: + """An unreachable daemon costs one round, nothing else.""" + with patch(f"{_REPORTS}._ctl_client.store_reports", side_effect=error): + assert _web_store_report.collect_store_reports() == 0 + + +@pytest.mark.usefixtures("filer") +def test_collect_survives_a_job_write_error() -> None: + """A failed job write is logged and the poller keeps going.""" + with ( + patch(f"{_REPORTS}._ctl_client.store_reports", return_value=[_REPORT]), + patch(f"{_REPORTS}.record_daemon_job", side_effect=OSError("disk")), + ): + assert _web_store_report.collect_store_reports() == 1 + + +def test_poller_runs_until_stopped() -> None: + """The poller calls collect on its interval and stops on the event.""" + with patch(f"{_REPORTS}.collect_store_reports") as collect: + stop = _web_store_report.start_store_report_poller(interval=0.01) + for _ in range(200): + if collect.call_count: + break + stop.wait(0.01) + stop.set() + assert collect.call_count >= 1 + + +def test_cli_unblock_failure_prints_check_files_and_exits_1(filer: MagicMock) -> None: + """``run.sh unblock`` with failing checks: says so, files, exits 1.""" + report = StoreCheckReport("unblock", "t", [Check("hosts", ok=False, detail="x")]) + with ( + patch( + "steam_backlog_enforcer.main.misc.open_store_window", + side_effect=StoreVerifyError(report), + ), + patch("steam_backlog_enforcer.main.misc._echo") as echo, + pytest.raises(SystemExit) as exited, + ): + cmd_unblock(Config(), State(), ["1"]) + assert exited.value.code == 1 + said = [str(c.args[0]) for c in echo.call_args_list] + assert said[0] == "Store unblock failed: hosts (the store is NOT open)." + assert "Filed todo task" in said[1] + filer.assert_called_once_with(report.to_wire()) diff --git a/web/src/jobs/jobProgress.ts b/web/src/jobs/jobProgress.ts index db8ad1f..c9dd73c 100644 --- a/web/src/jobs/jobProgress.ts +++ b/web/src/jobs/jobProgress.ts @@ -14,7 +14,7 @@ import { Action } from '../lib/action' import { define, h } from '../lib/dom' import { LiveElement } from '../lib/element' import { errorNotice, glyph, notice } from '../ui/build' -import { clock, duration } from '../ui/format' +import { clock, duration, logTime } from '../ui/format' import { hub, type LiveJob } from './hub' import { progressBar, stateBadge } from './progress' import { promptForm } from './promptForm' @@ -231,7 +231,7 @@ export class JobProgressElement extends LiveElement { const fresh = slid ? logs : logs.slice(this.logCount) if (slid) f.log.replaceChildren() for (const l of fresh) { - const li = h('li', { class: `log-${l.level}` }, h('time', { datetime: l.ts }, l.ts.slice(11, 19)), ` ${l.message}`) + const li = h('li', { class: `log-${l.level}` }, h('time', { datetime: l.ts }, logTime(l.ts)), ` ${l.message}`) li.dataset.seq = String(l.seq) f.log.append(li) } diff --git a/web/src/ui/format.test.ts b/web/src/ui/format.test.ts index e9f7f54..107c965 100644 --- a/web/src/ui/format.test.ts +++ b/web/src/ui/format.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { ago, bytes, clock, dateTime, duration } from './format' +import { ago, bytes, clock, dateTime, duration, logTime } from './format' describe('ui format', () => { it('bytes scales units and trims decimals', () => { @@ -41,3 +41,18 @@ describe('ui format', () => { expect(duration(new Date().toISOString(), null)).toBe('0:00') }) }) + +describe('logTime', () => { + it('shows a UTC log timestamp in the given local zone (job log vs summary)', () => { + expect(logTime('2026-11-22T15:09:09.123456+00:00', 'Europe/Warsaw')).toBe('16:09:09') + }) + + it('pads and stays on a 24-hour clock', () => { + expect(logTime('2026-11-22T00:05:07Z', 'UTC')).toBe('00:05:07') + expect(logTime('2026-11-22T13:05:07Z', 'UTC')).toBe('13:05:07') + }) + + it('falls back to the raw text when the timestamp does not parse', () => { + expect(logTime('garbage', 'UTC')).toBe('garbage') + }) +}) diff --git a/web/src/ui/format.ts b/web/src/ui/format.ts index 46a6cd8..2c09b30 100644 --- a/web/src/ui/format.ts +++ b/web/src/ui/format.ts @@ -21,6 +21,16 @@ export function clock(totalSeconds: number): string { return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}` } +/** + * A job log line's time, HH:MM:SS on the local clock. The server stamps UTC; + * slicing the ISO text showed 15:09 next to a summary saying 16:24. + */ +export function logTime(iso: string, timeZone?: string): string { + const t = Date.parse(iso) + if (Number.isNaN(t)) return iso + return new Date(t).toLocaleTimeString('en-GB', { hour12: false, timeZone }) +} + /** Short relative time: "just now", "5 min ago", "3 h ago", "2 d ago". */ export function ago(iso: string | null, now: number = Date.now()): string { if (!iso) return '—' diff --git a/web/vitest.config.ts b/web/vitest.config.ts index daadb8f..59bec40 100644 --- a/web/vitest.config.ts +++ b/web/vitest.config.ts @@ -3,6 +3,8 @@ import { getViteConfig } from 'astro/config' export default getViteConfig({ test: { + // Local-time rendering (job log times) must not depend on the machine's zone. + env: { TZ: 'UTC' }, environment: 'jsdom', setupFiles: ['./src/test/setup.ts'], include: ['src/**/*.test.ts', 'mock/**/*.test.ts'],