From 97d32c803dae4008be9d5d645c17dcb65ac184da Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Thu, 27 Aug 2026 20:49:16 +0200 Subject: [PATCH] Phase 6: vmbox becomes the gate for the system scripts (item 10) scripts/vmbox/harness.sh provisions a disposable Arch guest, runs the REAL install.sh in it, and adjudicates 8 cases on a host-side exit code. Plus DOCS-vmbox.md, which states what a pass does and does not mean. Covered: system-python imports, timer enabled, wake-alarm.service still `static` (an [Install] there fires the alarm at *login*), the shutdown wrapper shadowing /usr/bin/shutdown, the alarm-cache shape jq expects, a trigger tick, the inhibitor, and the re-fire path. With --window it also opens the real fullscreen Tk window and screenshots it from the host -- confirmed showing "WAKE UP!", round 1/4 and a live flash challenge. Not covered, and said plainly in the doc rather than implied away: audio (the guest has no pactl/paplay), the phone, GPU and real outputs, and anything bootloader-related (guest is BIOS, this machine is UEFI). **The VM earned its place immediately by finding two live bugs that the host could not reach and the unit suite passed straight through.** 1. The inhibitor claimed a block it did not have. Popen succeeding only means the binary launched; logind can still refuse -- the guest's polkit denies a non-interactive session outright ("Failed to inhibit: Access denied", exit 1) while the alarm cheerfully logged the power key as blocked. take_power_key_inhibitor() now waits INHIBIT_CONFIRM_SECONDS and confirms the child survived, returning None and logging the refusal otherwise. 2. An unsigned session record was written and then rejected on read. With no HMAC key on the machine (/etc/gatelock absent, as in the guest), verify_entry_hmac returns False for a *missing* key exactly as it does for a forgery -- so every session record was unreadable and item 2's power-off defence silently did not exist. An entry with no "hmac" field is now honoured with a loud warning; a present-but-wrong signature is still rejected, since that one really is tampering. Two harness traps worth recording, both hit while building it: - `vm run` reports the *VM's* verdict, not the guest command's exit code, so a guest script exiting 1 still gives rc=0. A gate built on that fails OPEN. guest_cases.sh prints ALL-CASES-PASSED only when every case passed and the harness greps for it; verified by breaking a case on purpose and watching the gate go red. - `vm share`/`vm repo` key off the path basename, so REPO_DIR must be absolute and symlink-resolved. A relative "scripts/vmbox/../.." makes rsync write into /home and fail with permissions errors that look like a guest fault. Guest checks live in real .py files beside the shell, not heredocs, so they get linted like everything else -- ruff's autofix gutted an early heredoc version (stripped the assignments AND the print) exactly as TODO-hardening warned, and only running it showed the file had stopped producing output. Also drops three stale fan references the guest install run surfaced: install.sh still announced "Fans will ramp to 100%" and README.md still described the fan ramp, three commits after item 14 deleted the feature. Splits carried: test_inhibit.py -> + test_inhibit_cleanup.py, test_alarm_session.py -> + test_alarm_session_refire.py. 455 tests pass, 100% branch coverage. Harness: 8/8 cases, exit 0. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh --- AGENTS.md | 4 + DOCS-vmbox.md | 106 ++++++++++ README.md | 8 +- install.sh | 1 - scripts/vmbox/__init__.py | 7 + scripts/vmbox/check_inhibitor.py | 72 +++++++ scripts/vmbox/check_refire.py | 38 ++++ scripts/vmbox/guest_cases.sh | 194 +++++++++++++++++ scripts/vmbox/harness.sh | 199 ++++++++++++++++++ wake_alarm/_alarm_session.py | 25 ++- wake_alarm/_constants.py | 7 + wake_alarm/_inhibit.py | 26 ++- wake_alarm/tests/test_alarm_session.py | 124 ++--------- wake_alarm/tests/test_alarm_session_refire.py | 134 ++++++++++++ wake_alarm/tests/test_inhibit.py | 130 ++++-------- wake_alarm/tests/test_inhibit_cleanup.py | 103 +++++++++ 16 files changed, 977 insertions(+), 201 deletions(-) create mode 100644 DOCS-vmbox.md create mode 100644 scripts/vmbox/__init__.py create mode 100644 scripts/vmbox/check_inhibitor.py create mode 100644 scripts/vmbox/check_refire.py create mode 100755 scripts/vmbox/guest_cases.sh create mode 100755 scripts/vmbox/harness.sh create mode 100644 wake_alarm/tests/test_alarm_session_refire.py create mode 100644 wake_alarm/tests/test_inhibit_cleanup.py diff --git a/AGENTS.md b/AGENTS.md index 4144656..b18f840 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -218,6 +218,10 @@ considering a dependency change done. - Show what the next tick would do: `python -m wake_alarm._trigger --dry-run` - Watch it live: `journalctl --user -fu wake-alarm-trigger.service` - Install for production: `bash install.sh` +- Gate the shell/system scripts: `bash scripts/vmbox/harness.sh` + (disposable Arch VM; what it covers and what it cannot is in + **`DOCS-vmbox.md`** — notably *not* audio, the phone, or the + bootloader). A sandbox pass never proves the host is fine. Note the dev venv lacks `gatelock`, so anything importing `_state` (including `_trigger`) must be run with `/usr/bin/python3`, not `.venv/bin/python`. diff --git a/DOCS-vmbox.md b/DOCS-vmbox.md new file mode 100644 index 0000000..9d3a2e8 --- /dev/null +++ b/DOCS-vmbox.md @@ -0,0 +1,106 @@ +# Testing wake_alarm in a disposable VM + +`scripts/vmbox/harness.sh` is this repo's default gate for the shell and +system pieces — `install.sh`, the systemd units, `shutdown-wrapper.sh`, the +power-key inhibitor and the re-fire path. It provisions a throwaway Arch guest +(`~/utils/vmbox`), installs this repo into it exactly the way a real machine +does, runs the cases, and returns a host-side verdict. + +```bash +bash scripts/vmbox/harness.sh # the gate +bash scripts/vmbox/harness.sh --window # also screenshot the real alarm window +bash scripts/vmbox/harness.sh --keep # leave the sandbox up to poke at +``` + +Exit codes: `0` everything passed, `1` a case failed, `2` the harness itself +could not run. + +## Why a VM at all + +Every one of these touches something a test on the host cannot safely touch: +`install.sh` writes systemd user units, a sudoers entry and +`/usr/local/bin/shutdown`; the shutdown wrapper's whole job is to hibernate the +machine; the inhibitor takes a logind lock on the power button. Getting any of +those wrong on the host is not a failed test, it is a broken machine. + +## What it actually covers + +| Case | What a pass means | +|---|---| +| `imports-from-system-python` | `wake_alarm` and `gatelock` import under `/usr/bin/python3`, the interpreter the units really use — not a venv | +| `trigger-timer-enabled` | `wake-alarm-trigger.timer` is enabled after `install.sh` | +| `alarm-service-never-auto-starts` | `wake-alarm.service` is still `static`. An `[Install]` section there fires the alarm at *login*, because `_should_run_alarm()` has no time gate | +| `shutdown-wrapper-shadows-real-shutdown` | `shutdown` resolves to `/usr/local/bin/shutdown`, ahead of `/usr/bin/shutdown` | +| `wrapper-parses-the-alarm-cache` | `jq` reads the `{"hour","minute","fetched_at"}` shape the wrapper expects — the only coupling left between it and `_sync.py`'s `_write_cache()` | +| `trigger-dry-run` | one tick reaches a decision without crashing | +| `inhibitor-never-claims-a-block-it-lacks` | see the caveat below — this is *not* "the power button was blocked" | +| `cut-short-alarm-refires` | an unfinished session record makes the trigger fire even with the catch-up window long closed | +| `alarm-window-opens` (`--window`) | the fullscreen Tk window really paints, on a real X server, verified by a host-side screenshot | + +`install.sh` itself running to completion is a precondition of all of them: if +it fails, the harness stops with exit 2 and dumps the log. + +## What it cannot cover — do not read a pass as covering these + +- **Audio.** The guest has no `pactl` and no `paplay`. Every sink, card-profile + and reactivation path — the whole of item 6 — is untestable here and was + verified directly on the host instead. +- **That the power button is actually blocked.** The guest has no physical + power button, *and* its polkit refuses an inhibit from a non-interactive ssh + session outright (`Failed to inhibit: Access denied`). So the case asserts + something narrower but still useful: that the code never *claims* a block it + did not get. `REFUSED` is a passing outcome. +- **The phone.** Nothing about the Flutter app, the sync round-trip, or the + alarm the phone rings. +- **GPU and the real display outputs.** The guest's X server is not DP-2 and + HDMI-0, so multi-monitor surface placement proves nothing here. +- **Anything bootloader-related.** The guest is BIOS/GRUB; this machine is + UEFI. A guest pass on boot-adjacent work is actively misleading — a sibling + repo's `boot-repair` passes in the guest while deleting the only bootable + kernel on a UEFI host. +- **rtcwake actually waking the machine.** `rtcwake` exists in the guest, but a + VM's RTC alarm is not the host's firmware. + +**A sandbox pass never proves the host is fine.** It is an added first step: +sandbox → report → host run. Phrase results as "passed in vmbox, not verified +on the host". + +## Guest provisioning, and why + +The stock guest image is missing exactly one thing this package needs: + +- **`tk`** — without it `import tkinter` fails with `libtk8.6.so: cannot open + shared object file` and the alarm cannot open its window at all. + +`gatelock` is not installed separately: it is a `pyproject.toml` dependency, so +`install.sh`'s `pip install -e` pulls it from its pinned tag. That is +deliberate — the harness runs the real install path rather than a hand-rolled +approximation, so a break in `install.sh` fails the gate. + +## Two traps worth knowing before editing the harness + +- **`vm run` does not propagate the guest command's exit code.** It reports the + *VM's* verdict (clean / dirty / rebooted / crashed / hung), so a guest script + exiting 1 still returns 0 on the host. A gate built on that exit code fails + *open*, which is worse than no gate. `guest_cases.sh` therefore prints + `ALL-CASES-PASSED` only when every case passed, and the harness greps for it. +- **`vm share` and `vm repo` key off the path's basename**, so the repo path + must be absolute and symlink-resolved. A relative `scripts/vmbox/../..` + makes rsync write into `/home` and fail with permission errors that look + like a guest problem. + +## Cases this VM found that the host could not + +Both were live bugs, both passed the unit suite: + +1. **The inhibitor claimed a block it did not have.** `Popen` succeeding only + means the binary launched; logind can still refuse. The alarm logged "power + key inhibited" while `systemd-inhibit` had already exited 1. + `take_power_key_inhibitor()` now waits briefly and confirms the child + survived. +2. **An unsigned session record was written and then rejected on read.** With + no HMAC key on the machine (`/etc/gatelock` absent, as in the guest), + `verify_entry_hmac` returns False, so every session record was unreadable + and the power-off defence silently did not exist. An entry with *no* `hmac` + field is now honoured with a loud warning, while a *present but wrong* + signature is still rejected — that one really is tampering. diff --git a/README.md b/README.md index 4fc3a51..729c030 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ A phone-driven wake alarm for an always-on PC. The alarm time is whatever the companion phone app last synced (via the shared `crdt_sync` transport over a private GitHub repo); a per-minute systemd user timer fires at exactly that -time, showing a fullscreen, challenge-dismissed alarm with fan ramp and -optional TP-Link Tapo P110 smart-plug control. +time, showing a fullscreen, challenge-dismissed alarm with escalating audio +and optional TP-Link Tapo P110 smart-plug control. Change the alarm on the phone at any hour and the PC follows within ~5 minutes. If the PC does happen to be powered down, a `shutdown` wrapper @@ -20,8 +20,8 @@ This installs the package + dependencies into system Python's user site-packages (the systemd units run `/usr/bin/python` directly, not a venv — see `CLAUDE.md`), installs and enables the per-minute trigger timer, the systemd-sleep resume hook, the `shutdown` wrapper that hibernates with -`rtcwake` as a fallback, the fan-ramp script, and (optionally) `python-kasa` -for smart-plug control. +`rtcwake` as a fallback, and (optionally) `python-kasa` for smart-plug +control. Reading the phone's alarm needs a GitHub token with `repo` scope, at `~/.config/wake_alarm/sync.json` as `{"token": "..."}`. If that file is diff --git a/install.sh b/install.sh index abc903e..eee6609 100755 --- a/install.sh +++ b/install.sh @@ -170,5 +170,4 @@ echo "repo-scoped GitHub token — see MIGRATION.md)." echo "Check what it resolves right now: python -m wake_alarm._sync --show" echo "If the PC is powered down instead, the shutdown wrapper hibernates with" echo "rtcwake set to the same alarm, and the sleep hook runs it on resume." -echo "Fans will ramp to 100% while the alarm is active, then restore automatically." echo "To test now: python -m wake_alarm._alarm --demo" diff --git a/scripts/vmbox/__init__.py b/scripts/vmbox/__init__.py new file mode 100644 index 0000000..5d7cfa0 --- /dev/null +++ b/scripts/vmbox/__init__.py @@ -0,0 +1,7 @@ +"""Guest-side checks for the vmbox harness. + +Not an importable part of ``wake_alarm`` -- these run *inside* a disposable +Arch guest, invoked by ``guest_cases.sh``. The package marker exists so they +are linted and type-checked like the rest of the repo instead of drifting as +loose scripts. +""" diff --git a/scripts/vmbox/check_inhibitor.py b/scripts/vmbox/check_inhibitor.py new file mode 100644 index 0000000..0e99379 --- /dev/null +++ b/scripts/vmbox/check_inhibitor.py @@ -0,0 +1,72 @@ +"""Guest-side check: does the power-key inhibitor register with logind? + +Run by ``guest_cases.sh`` inside a vmbox sandbox. Prints a single line the +shell case compares exactly, so the harness adjudicates on a string rather +than on a human reading a log. + +**What this proves and what it does not.** The guest has no physical power +button, so this shows the inhibitor is *taken* and *released* -- not that a +real press was suppressed. That distinction is stated in ``DOCS-vmbox.md`` +rather than papered over. + +The guest's polkit also refuses an inhibit from a non-interactive ssh session, +so ``REFUSED`` is an expected and passing outcome. It is what caught the real +bug: ``Popen`` succeeded while ``systemd-inhibit`` had already exited 1, and +the alarm logged the power key as blocked when it was not. +""" + +from __future__ import annotations + +import subprocess +import sys +import time + +from wake_alarm._inhibit import ( + release_power_key_inhibitor, + take_power_key_inhibitor, +) + +_SETTLE_SECONDS = 1.0 + +# Absolute, so the check cannot be pointed at a different binary by PATH -- +# and so it matches how _inhibit.py resolves the tool it actually spawns. +_SYSTEMD_INHIBIT = "/usr/bin/systemd-inhibit" + + +def _inhibitor_list() -> str: + """Return logind's current inhibitor table as text.""" + return subprocess.run( + [_SYSTEMD_INHIBIT, "--list"], + capture_output=True, + text=True, + check=False, + ).stdout + + +def main() -> None: + """Take the inhibitor, observe it, release it, observe it gone. + + Writes ``REFUSED`` when logind declined, which the harness treats as a + *pass*: the point of the case is that the code never claims a block it did + not get. + """ + process = take_power_key_inhibitor() + if process is None: + sys.stdout.write("REFUSED\n") + return + + time.sleep(_SETTLE_SECONDS) + while_held = _inhibitor_list() + release_power_key_inhibitor(process) + time.sleep(_SETTLE_SECONDS) + after_release = _inhibitor_list() + + held = "handle-power-key" in while_held and "wake-alarm" in while_held + freed = "wake-alarm" not in after_release + sys.stdout.write( + f"{'HELD' if held else 'NOT-HELD'} {'FREED' if freed else 'NOT-FREED'}\n" + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/vmbox/check_refire.py b/scripts/vmbox/check_refire.py new file mode 100644 index 0000000..e4f3137 --- /dev/null +++ b/scripts/vmbox/check_refire.py @@ -0,0 +1,38 @@ +"""Guest-side check: does a cut-short alarm re-fire on the next tick? + +Run by ``guest_cases.sh`` inside a vmbox sandbox. Prints one line -- three +decisions joined by dashes -- that the shell case compares exactly. + +This is the case a VM tests better than the host can: on the real machine the +only honest way to produce an unfinished session is to actually cut the power +mid-alarm. Here the alarm time is deliberately placed hours in the past, so +the catch-up window is closed and **only** an unfinished session can make the +trigger fire. +""" + +from __future__ import annotations + +import sys + +from wake_alarm._alarm_session import finish_session, start_session +from wake_alarm._sync import Alarm +from wake_alarm._trigger import _decide, _now + +_HOURS_AGO = 6 + + +def main() -> None: + """Print before-during-after firing decisions around a session record.""" + now = _now() + stale = Alarm((now.hour - _HOURS_AGO) % 24, 0, "remote") + + before, _ = _decide(now, stale) + start_session("wake-vmbox-harness") + during, _ = _decide(now, stale) + finish_session() + after, _ = _decide(now, stale) + sys.stdout.write(f"{before}-{during}-{after}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/vmbox/guest_cases.sh b/scripts/vmbox/guest_cases.sh new file mode 100755 index 0000000..191c303 --- /dev/null +++ b/scripts/vmbox/guest_cases.sh @@ -0,0 +1,194 @@ +#!/bin/bash + +# ============================================================================ +# wake_alarm vmbox harness — the cases that run INSIDE the guest. +# +# Kept as its own file rather than inlined into `vm run` for two reasons: the +# vmbox runner wraps its argument in `sh -c` and chokes on a multi-line +# command, and a real file gets shellcheck like every other script here. +# +# Each case prints "PASS " or "FAIL : " and the script exits +# non-zero if any failed, so the host adjudicates on an exit code rather than +# by reading prose. +# ============================================================================ + +set -uo pipefail + +readonly PY=/usr/bin/python3 +# The helper .py files ship beside this script, so each gets real linting +# and type checking instead of hiding inside a heredoc. +CASE_DIR="$(dirname "$(readlink -f "$0")")" +readonly CASE_DIR +FAILURES=0 + +pass() { + echo "PASS $1" +} + +fail() { + echo "FAIL $1: $2" + FAILURES=$((FAILURES + 1)) +} + +# --- Case: the package installs and imports from SYSTEM python --------------- +# The units run /usr/bin/python directly, never a venv, so this is the check +# that actually matters (CLAUDE.md). +case_imports() { + local name="imports-from-system-python" + if "$PY" -c "import wake_alarm, gatelock" 2>/dev/null; then + pass "$name" + else + fail "$name" "wake_alarm or gatelock missing from /usr/bin/python3" + fi +} + +# --- Case: units land in the right enablement state -------------------------- +# wake-alarm.service must stay `static`. An [Install] section there fires the +# alarm at *login* time, because _should_run_alarm() has no time gate. +case_units() { + local name state + name="trigger-timer-enabled" + state="$(systemctl --user is-enabled wake-alarm-trigger.timer 2>&1)" + if [[ "$state" == "enabled" ]]; then + pass "$name" + else + fail "$name" "expected enabled, got '$state'" + fi + + name="alarm-service-never-auto-starts" + state="$(systemctl --user is-enabled wake-alarm.service 2>&1)" + if [[ "$state" == "static" || "$state" == "disabled" ]]; then + pass "$name" + else + fail "$name" "wake-alarm.service is '$state'; it must never auto-start" + fi +} + +# --- Case: the shutdown wrapper shadows /usr/bin/shutdown -------------------- +case_shutdown_wrapper() { + local name="shutdown-wrapper-shadows-real-shutdown" + local resolved + resolved="$(command -v shutdown)" + if [[ "$resolved" == "/usr/local/bin/shutdown" ]]; then + pass "$name" + else + fail "$name" "shutdown resolves to '$resolved', not the wrapper" + fi +} + +# --- Case: the wrapper reads the alarm cache, not the network ---------------- +# It parses ~/.config/wake_alarm/alarm_cache.json with jq. The shape is the +# only coupling left between the wrapper and _sync.py's _write_cache(). +case_wrapper_reads_cache() { + local name="wrapper-parses-the-alarm-cache" + local cache="$HOME/.config/wake_alarm/alarm_cache.json" + mkdir -p "$(dirname "$cache")" + printf '{"hour": 6, "minute": 45, "fetched_at": %d}\n' "$(date +%s)" > "$cache" + if jq -e '.hour == 6 and .minute == 45' "$cache" >/dev/null 2>&1; then + pass "$name" + else + fail "$name" "jq could not read the cache shape the wrapper expects" + fi + rm -f "$cache" +} + +# --- Case: the trigger decides without crashing ------------------------------ +case_trigger_dry_run() { + local name="trigger-dry-run" + if "$PY" -m wake_alarm._trigger --dry-run 2>/dev/null | grep -q "firing"; then + pass "$name" + else + fail "$name" "--dry-run produced no decision line" + fi +} + +# --- Case: the inhibitor reports honestly ------------------------------------ +# The guest's polkit denies an inhibit from a non-interactive ssh session +# ("Failed to inhibit: Access denied", exit 1), so what is asserted here is +# NOT that the power key gets blocked -- it is that the code never *claims* +# a block it did not get. That distinction is the bug this case found: Popen +# succeeded, the alarm logged "power key inhibited", and nothing was. +# +# The two accepted outcomes are therefore "took it and released it" and +# "logind refused and we said so". A silent third state is the failure. +# See DOCS-vmbox.md for why the block itself cannot be proven in a guest. +case_inhibitor() { + local name="inhibitor-never-claims-a-block-it-lacks" + "$PY" "$CASE_DIR/check_inhibitor.py" > /tmp/inhibit_result 2>/dev/null + local result + result="$(cat /tmp/inhibit_result 2>/dev/null)" + case "$result" in + "HELD FREED"|"REFUSED") + pass "$name ($result)" + ;; + *) + fail "$name" "expected 'HELD FREED' or 'REFUSED', got '$result'" + ;; + esac +} + +# --- Case: an unfinished session re-fires -------------------------------- +# The one case a VM tests better than the host: a real poweroff mid-alarm. +# Here we assert the decision the next boot's trigger tick would make. +case_refire() { + local name="cut-short-alarm-refires" + "$PY" "$CASE_DIR/check_refire.py" > /tmp/refire_result 2>/dev/null + local result + result="$(cat /tmp/refire_result 2>/dev/null)" + if [[ "$result" == "False-True-False" ]]; then + pass "$name" + else + fail "$name" "expected False-True-False, got '$result'" + fi + rm -f "$HOME/.config/wake_alarm/alarm_session.json" +} + +# --- Case: the alarm window really opens on a real X server ------------------ +# Verified by the HOST via `vm screenshot`; this half only launches it. +case_alarm_window() { + local name="alarm-window-opens" + "$PY" -m wake_alarm._alarm --demo --trigger-now >/tmp/alarm.log 2>&1 & + local pid=$! + sleep 12 + if kill -0 "$pid" 2>/dev/null; then + pass "$name" + echo "$pid" > /tmp/alarm.pid + else + fail "$name" "the alarm exited early: $(tail -3 /tmp/alarm.log)" + fi +} + +main() { + case "${1:-all}" in + window) + # Run alone: it leaves a fullscreen window up for the host to + # screenshot, which would hide every later case's output. + case_alarm_window + ;; + all) + case_imports + case_units + case_shutdown_wrapper + case_wrapper_reads_cache + case_trigger_dry_run + case_inhibitor + case_refire + ;; + *) + echo "usage: $0 [all|window]" >&2 + exit 2 + ;; + esac + + echo "---" + if [[ $FAILURES -gt 0 ]]; then + echo "$FAILURES case(s) failed" + exit 1 + fi + # The host greps for this exact string. `vm run` reports the VM's verdict + # rather than this script's exit code, so an exit status alone would let + # the gate fail open. + echo "ALL-CASES-PASSED" +} + +main "$@" diff --git a/scripts/vmbox/harness.sh b/scripts/vmbox/harness.sh new file mode 100755 index 0000000..5ca98a8 --- /dev/null +++ b/scripts/vmbox/harness.sh @@ -0,0 +1,199 @@ +#!/bin/bash + +# ============================================================================ +# wake_alarm's default gate for shell and system scripts. +# +# Provisions a disposable Arch guest, installs this repo into it exactly the +# way production does, and runs the cases that cannot safely run on the host: +# install.sh, the systemd units, the shutdown wrapper, the power-key +# inhibitor, and the re-fire path after a cut-short alarm. +# +# What it deliberately cannot cover -- audio, the phone, real outputs, the +# bootloader -- is in DOCS-vmbox.md. Read that before trusting a pass. +# +# Usage: bash scripts/vmbox/harness.sh [--name ] [--keep] [--window] +# ============================================================================ + +set -euo pipefail + +VM_NAME="wake-alarm-harness" +KEEP=0 +RUN_WINDOW=0 +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" +readonly SCRIPT_DIR +# Absolute and symlink-resolved: `vm share` and `vm repo` both key off the +# path's basename, so a relative "scripts/vmbox/../.." resolves to the wrong +# directory in the guest and rsync writes into /home instead of the repo. +REPO_DIR="$(readlink -f "${SCRIPT_DIR}/../..")" +readonly REPO_DIR +SCRIPT_NAME="$(basename "$0")" +readonly SCRIPT_NAME + +# Packages the guest image lacks that this package genuinely needs. tk is not +# optional: without it `import tkinter` fails with a missing libtk8.6.so and +# the alarm cannot open its window. Measured on the stock guest, not guessed. +readonly GUEST_PACKAGES="tk" + +# Printed by guest_cases.sh only when every case passed. See run_cases(). +readonly GUEST_OK_SENTINEL="ALL-CASES-PASSED" + +usage() { + cat < Sandbox name (default: $VM_NAME) + --keep Leave the sandbox running afterwards, for poking at + --window Also open the real alarm window and screenshot it + -h, --help Show this help + +Exit codes: + 0 every case passed + 1 a case failed + 2 the harness could not run (vmbox missing, provisioning failed) +USAGE + exit 0 +} + +die() { + echo "Error: $*" >&2 + exit 2 +} + +step() { + echo "==> $*" +} + +validate_requirements() { + command -v vm >/dev/null 2>&1 || + die "vmbox is not installed. Run: bash ~/utils/vmbox/install.sh" + [[ -f "$REPO_DIR/install.sh" ]] || + die "cannot find install.sh; run this from the wake-alarm repo" +} + +# Bring the sandbox up from scratch. `vm new` on an existing name is an error, +# so an existing sandbox is reset instead -- that is the sub-second path and +# it guarantees a pristine starting point either way. +provision_sandbox() { + if vm list 2>/dev/null | awk '{print $1}' | grep -qx "$VM_NAME"; then + step "Resetting existing sandbox '$VM_NAME'" + vm reset "$VM_NAME" >/dev/null + else + step "Creating sandbox '$VM_NAME'" + vm new "$VM_NAME" >/dev/null + fi + + # `vm repo` copies out of the shared mount, so the share must exist first. + # A bind mount, never a symlink: 9p does not follow one. + step "Sharing the repo with the guest" + vm share "$REPO_DIR" >/dev/null + + step "Installing guest packages ($GUEST_PACKAGES)" + vm run "$VM_NAME" \ + "sudo pacman -S --noconfirm --needed $GUEST_PACKAGES" >/dev/null || + die "could not install guest packages" + + # --worktree, not a clone: the point of the gate is to test the edits in + # front of you, including the ones not committed yet. + step "Copying the working tree into the guest" + vm repo "$VM_NAME" "$REPO_DIR" --worktree >/dev/null || + die "could not copy the repo into the guest" +} + +# The real production install path, not a hand-rolled approximation: this is +# the same install.sh a machine runs, so a break in it fails the gate. +run_install() { + step "Running install.sh in the guest" + if ! vm run "$VM_NAME" 'cd ~/wake-alarm && bash install.sh' >/tmp/wa-install.log 2>&1; then + tail -20 /tmp/wa-install.log >&2 + die "install.sh failed in the guest (full log: /tmp/wa-install.log)" + fi +} + +# `vm run` reports the *VM's* verdict (clean/dirty/hung), not the command's +# exit status -- a guest script exiting 1 still gives rc=0 on the host. That +# would make this gate fail *open*, which is worse than having no gate, so the +# verdict is carried in the output as an explicit sentinel and matched here. +run_cases() { + step "Running the guest cases" + local output + output="$(vm run "$VM_NAME" \ + 'bash ~/wake-alarm/scripts/vmbox/guest_cases.sh all' 2>&1)" + echo "$output" + grep -q "$GUEST_OK_SENTINEL" <<<"$output" +} + +# The alarm's window needs a real X server, so the guest is the only place it +# can be seen at all without hijacking the host's screen. The screenshot is +# the artefact: it outlives the guest and is what a human actually checks. +run_window_case() { + step "Opening the alarm window in the guest" + local output + output="$(vm run "$VM_NAME" \ + 'bash ~/wake-alarm/scripts/vmbox/guest_cases.sh window' 2>&1)" + echo "$output" + grep -q "$GUEST_OK_SENTINEL" <<<"$output" || return 1 + local shot="/tmp/wake-alarm-window.png" + vm screenshot "$VM_NAME" "$shot" + echo "Alarm window screenshot: $shot" +} + +cleanup() { + if [[ $KEEP -eq 1 ]]; then + echo "Sandbox '$VM_NAME' left running (--keep). Poke at it with: vm ssh $VM_NAME" + return + fi + vm reset "$VM_NAME" >/dev/null 2>&1 || true +} + +main() { + validate_requirements + trap cleanup EXIT + + provision_sandbox + run_install + + local status=0 + run_cases || status=1 + if [[ $RUN_WINDOW -eq 1 ]]; then + run_window_case || status=1 + fi + + echo "============================================================" + if [[ $status -eq 0 ]]; then + echo "vmbox harness: PASSED" + echo "NOT verified on the host — see DOCS-vmbox.md for what this misses." + else + echo "vmbox harness: FAILED" + fi + echo "============================================================" + return $status +} + +while [[ $# -gt 0 ]]; do + case $1 in + --name) + VM_NAME="${2:?--name needs a sandbox name}" + shift 2 + ;; + --keep) + KEEP=1 + shift + ;; + --window) + RUN_WINDOW=1 + shift + ;; + -h|--help) + usage + ;; + *) + echo "Unknown option: $1" >&2 + exit 2 + ;; + esac +done + +main "$@" diff --git a/wake_alarm/_alarm_session.py b/wake_alarm/_alarm_session.py index 7f3948d..aeb389a 100644 --- a/wake_alarm/_alarm_session.py +++ b/wake_alarm/_alarm_session.py @@ -141,10 +141,27 @@ def load_session() -> dict[str, object] | None: return None if not isinstance(entry, dict): return None - if not verify_entry_hmac(entry): - _logger.warning("Alarm session HMAC verification failed") - return None - return entry + if verify_entry_hmac(entry): + return entry + # An entry with no "hmac" field at all was written unsigned, because no + # HMAC key was available at fire time. gatelock's verify returns False for + # that case *and* for a real forgery, and treating them alike would be a + # silent fail-open: on a machine with no key provisioned, every session + # record would be unreadable and the power-off defence would simply not + # exist. Found by running the vmbox harness, where /etc/gatelock is absent. + # + # So: unsigned is accepted with a loud warning (it is no weaker than the + # no-record state it replaces), while a *present but wrong* signature is + # still rejected outright -- that one really is tampering. + if "hmac" not in entry: + _logger.warning( + "Alarm session is unsigned (no HMAC key on this machine) — " + "honouring it, but it offers no tamper protection", + extra={"event": "session_unsigned"}, + ) + return entry + _logger.warning("Alarm session HMAC verification failed") + return None def _fired_at(entry: dict[str, object]) -> datetime | None: diff --git a/wake_alarm/_constants.py b/wake_alarm/_constants.py index cbad70b..6582fc5 100644 --- a/wake_alarm/_constants.py +++ b/wake_alarm/_constants.py @@ -132,6 +132,13 @@ INHIBIT_WHY: str = "Wake alarm is ringing and must be dismissed, not switched of # so it is never `sleep infinity`. Comfortably longer than any real alarm. INHIBIT_MAX_SECONDS: float = 7200.0 +# How long to wait for the inhibitor child to prove it survived. Popen +# succeeding only means the binary launched; logind can still refuse (polkit +# denies a non-interactive session, seen in a vmbox run: "Failed to inhibit: +# Access denied", exit 1). Still alive after this means the inhibit was +# accepted. Short enough not to delay the alarm perceptibly. +INHIBIT_CONFIRM_SECONDS: float = 0.5 + # When the failsafe silences the alarm. Audio ONLY: the lock, the typed # challenge and the workout gate all persist past this point, so waiting it # out in bed is not a way to escape the alarm. It exists so a ring nobody is diff --git a/wake_alarm/_inhibit.py b/wake_alarm/_inhibit.py index ae702c9..bf77ff3 100644 --- a/wake_alarm/_inhibit.py +++ b/wake_alarm/_inhibit.py @@ -42,6 +42,7 @@ import signal import subprocess from wake_alarm._constants import ( + INHIBIT_CONFIRM_SECONDS, INHIBIT_MAX_SECONDS, INHIBIT_WHAT, INHIBIT_WHO, @@ -150,7 +151,7 @@ def take_power_key_inhibitor() -> subprocess.Popen[bytes] | None: process = subprocess.Popen( cmd, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, + stderr=subprocess.PIPE, ) except OSError: _logger.warning( @@ -159,6 +160,29 @@ def take_power_key_inhibitor() -> subprocess.Popen[bytes] | None: extra={"event": "inhibitor_failed"}, ) return None + + # Popen succeeding only means the *binary* started. logind can still + # refuse the inhibit -- polkit denies it outright for a non-interactive + # session, which is exactly what a vmbox run turned up: systemd-inhibit + # printed "Failed to inhibit: Access denied" and exited 1 while this + # function happily reported the power key blocked. Claiming protection + # that is not there is worse than reporting none, so wait briefly and + # check the child is actually alive. + try: + process.wait(timeout=INHIBIT_CONFIRM_SECONDS) + except subprocess.TimeoutExpired: + pass # Still running after the grace period: the inhibit was accepted. + else: + stderr = b"" if process.stderr is None else process.stderr.read() + _logger.warning( + "logind refused the power-key inhibitor (rc=%d): %s — the alarm " + "rings unprotected", + process.returncode, + stderr.decode(errors="replace").strip() or "no detail", + extra={"event": "inhibitor_refused", "rc": process.returncode}, + ) + return None + _logger.warning( "Power key inhibited for up to %ds (pid %d) — a short press no longer " "kills the alarm; a ~4s firmware hold still cuts power", diff --git a/wake_alarm/tests/test_alarm_session.py b/wake_alarm/tests/test_alarm_session.py index c2340d0..415f1e0 100644 --- a/wake_alarm/tests/test_alarm_session.py +++ b/wake_alarm/tests/test_alarm_session.py @@ -2,7 +2,7 @@ from __future__ import annotations -from datetime import datetime, timedelta, timezone +from datetime import datetime import json from typing import TYPE_CHECKING @@ -16,7 +16,6 @@ from wake_alarm._alarm_session import ( load_session, should_refire, start_session, - unfinished_session_age, ) if TYPE_CHECKING: @@ -117,6 +116,27 @@ class TestLoadSession: session_file.write_text("[1, 2, 3]") assert load_session() is None + def test_an_unsigned_record_is_honoured( + self, + session_file: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + ) -> None: + """No HMAC key must not silently disable the power-off defence. + + ``verify_entry_hmac`` returns False both for a forgery *and* for a + machine with no key at all. Treating them alike meant that on such a + machine every session record was unreadable and the re-fire simply did + not happen -- found by running the vmbox harness, where /etc/gatelock + is absent. + """ + monkeypatch.setattr(_alarm_session, "compute_entry_hmac", lambda _e: None) + start_session("wake-20260827-0700") + assert "hmac" not in json.loads(session_file.read_text()) + with caplog.at_level("WARNING"): + assert should_refire() is True + assert "unsigned" in caplog.text + def test_tampered_record_is_rejected( self, session_file: Path, caplog: pytest.LogCaptureFixture ) -> None: @@ -128,103 +148,3 @@ class TestLoadSession: with caplog.at_level("WARNING"): assert load_session() is None assert "HMAC verification failed" in caplog.text - - -class TestShouldRefire: - """The decision _trigger acts on.""" - - def test_no_record_does_not_refire(self) -> None: - """The ordinary case: nothing was cut short.""" - assert should_refire() is False - - def test_ringing_record_refires(self) -> None: - """The whole point: a power-off mid-alarm rings again.""" - start_session("wake-20260827-0700") - assert should_refire() is True - - def test_finished_record_does_not_refire(self) -> None: - """A dismissed alarm stays dismissed.""" - start_session("wake-20260827-0700") - finish_session() - assert should_refire() is False - - def test_stale_record_does_not_refire( - self, caplog: pytest.LogCaptureFixture - ) -> None: - """Bounded on purpose. - - An alarm that died before dismissal leaves a record nothing will ever - clear; unbounded, this would restart the alarm every minute forever. - """ - start_session("wake-20260827-0700") - much_later = datetime.now(tz=timezone.utc).astimezone() + timedelta(days=1) - with caplog.at_level("INFO"): - assert should_refire(now=much_later) is False - assert "Ignoring an unfinished alarm session" in caplog.text - - def test_a_backward_clock_jump_still_refires( - self, caplog: pytest.LogCaptureFixture - ) -> None: - """Fails *closed*, which is the whole point of the record. - - NTP correcting after a resume moves the clock backwards, leaving the - record stamped in the future. Discarding it there would mean: alarm - fires on a fast clock, clock is corrected, and the power-off escape - quietly works again -- on a machine that hibernates nightly, i.e. the - exact scenario this record exists to close. - """ - start_session("wake-20260827-0700") - corrected = datetime.now(tz=timezone.utc).astimezone() - timedelta(minutes=5) - with caplog.at_level("INFO"): - assert should_refire(now=corrected) is True - assert "in the future" in caplog.text - - def test_a_wildly_future_record_is_ignored( - self, caplog: pytest.LogCaptureFixture - ) -> None: - """Bounded, so a broken RTC cannot create an endless re-fire.""" - start_session("wake-20260827-0700") - way_earlier = datetime.now(tz=timezone.utc).astimezone() - timedelta(hours=6) - with caplog.at_level("WARNING"): - assert should_refire(now=way_earlier) is False - assert "beyond the" in caplog.text - - def test_missing_timestamp_is_ignored( - self, - session_file: Path, - monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, - ) -> None: - """A record with no usable fired_at cannot be aged, so it is dropped.""" - monkeypatch.setattr(_alarm_session, "verify_entry_hmac", lambda _e: True) - session_file.write_text(json.dumps({"state": STATE_RINGING})) - with caplog.at_level("WARNING"): - assert unfinished_session_age() is None - assert "no usable fired_at" in caplog.text - - @pytest.mark.parametrize( - "fired_at", - [ - "not-a-timestamp", - # Naive: without an offset the elapsed-time comparison is - # meaningless, which is exactly the ambiguity this record avoids. - "2026-08-27T07:00:00", - ], - ) - def test_unusable_timestamps_are_ignored( - self, session_file: Path, monkeypatch: pytest.MonkeyPatch, fired_at: str - ) -> None: - """Neither an unparsable nor a naive timestamp can drive a re-fire.""" - monkeypatch.setattr(_alarm_session, "verify_entry_hmac", lambda _e: True) - session_file.write_text( - json.dumps({"state": STATE_RINGING, "fired_at": fired_at}) - ) - assert should_refire() is False - - def test_age_is_reported_for_a_live_session(self) -> None: - """The age helper is what makes the bound observable.""" - start_session("wake-20260827-0700") - later = datetime.now(tz=timezone.utc).astimezone() + timedelta(seconds=90) - age = unfinished_session_age(now=later) - assert age is not None - assert 89 <= age <= 92 diff --git a/wake_alarm/tests/test_alarm_session_refire.py b/wake_alarm/tests/test_alarm_session_refire.py new file mode 100644 index 0000000..a6bdecf --- /dev/null +++ b/wake_alarm/tests/test_alarm_session_refire.py @@ -0,0 +1,134 @@ +"""Tests for the re-fire decision driven by the session record. + +Split from ``test_alarm_session.py`` for the 250-line cap. The header is copied +whole: without the autouse ``session_file`` fixture these tests would read and +write the *production* record, which the next real trigger tick would act on. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import json +from typing import TYPE_CHECKING + +import pytest + +from wake_alarm import _alarm_session +from wake_alarm._alarm_session import ( + STATE_RINGING, + finish_session, + should_refire, + start_session, + unfinished_session_age, +) + +if TYPE_CHECKING: + from pathlib import Path + + +@pytest.fixture(autouse=True) +def session_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Point the record at a temporary file, never the real one.""" + path = tmp_path / "alarm_session.json" + monkeypatch.setattr(_alarm_session, "ALARM_SESSION_FILE", path) + return path + + +class TestShouldRefire: + """The decision _trigger acts on.""" + + def test_no_record_does_not_refire(self) -> None: + """The ordinary case: nothing was cut short.""" + assert should_refire() is False + + def test_ringing_record_refires(self) -> None: + """The whole point: a power-off mid-alarm rings again.""" + start_session("wake-20260827-0700") + assert should_refire() is True + + def test_finished_record_does_not_refire(self) -> None: + """A dismissed alarm stays dismissed.""" + start_session("wake-20260827-0700") + finish_session() + assert should_refire() is False + + def test_stale_record_does_not_refire( + self, caplog: pytest.LogCaptureFixture + ) -> None: + """Bounded on purpose. + + An alarm that died before dismissal leaves a record nothing will ever + clear; unbounded, this would restart the alarm every minute forever. + """ + start_session("wake-20260827-0700") + much_later = datetime.now(tz=timezone.utc).astimezone() + timedelta(days=1) + with caplog.at_level("INFO"): + assert should_refire(now=much_later) is False + assert "Ignoring an unfinished alarm session" in caplog.text + + def test_a_backward_clock_jump_still_refires( + self, caplog: pytest.LogCaptureFixture + ) -> None: + """Fails *closed*, which is the whole point of the record. + + NTP correcting after a resume moves the clock backwards, leaving the + record stamped in the future. Discarding it there would mean: alarm + fires on a fast clock, clock is corrected, and the power-off escape + quietly works again -- on a machine that hibernates nightly, i.e. the + exact scenario this record exists to close. + """ + start_session("wake-20260827-0700") + corrected = datetime.now(tz=timezone.utc).astimezone() - timedelta(minutes=5) + with caplog.at_level("INFO"): + assert should_refire(now=corrected) is True + assert "in the future" in caplog.text + + def test_a_wildly_future_record_is_ignored( + self, caplog: pytest.LogCaptureFixture + ) -> None: + """Bounded, so a broken RTC cannot create an endless re-fire.""" + start_session("wake-20260827-0700") + way_earlier = datetime.now(tz=timezone.utc).astimezone() - timedelta(hours=6) + with caplog.at_level("WARNING"): + assert should_refire(now=way_earlier) is False + assert "beyond the" in caplog.text + + def test_missing_timestamp_is_ignored( + self, + session_file: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + ) -> None: + """A record with no usable fired_at cannot be aged, so it is dropped.""" + monkeypatch.setattr(_alarm_session, "verify_entry_hmac", lambda _e: True) + session_file.write_text(json.dumps({"state": STATE_RINGING})) + with caplog.at_level("WARNING"): + assert unfinished_session_age() is None + assert "no usable fired_at" in caplog.text + + @pytest.mark.parametrize( + "fired_at", + [ + "not-a-timestamp", + # Naive: without an offset the elapsed-time comparison is + # meaningless, which is exactly the ambiguity this record avoids. + "2026-08-27T07:00:00", + ], + ) + def test_unusable_timestamps_are_ignored( + self, session_file: Path, monkeypatch: pytest.MonkeyPatch, fired_at: str + ) -> None: + """Neither an unparsable nor a naive timestamp can drive a re-fire.""" + monkeypatch.setattr(_alarm_session, "verify_entry_hmac", lambda _e: True) + session_file.write_text( + json.dumps({"state": STATE_RINGING, "fired_at": fired_at}) + ) + assert should_refire() is False + + def test_age_is_reported_for_a_live_session(self) -> None: + """The age helper is what makes the bound observable.""" + start_session("wake-20260827-0700") + later = datetime.now(tz=timezone.utc).astimezone() + timedelta(seconds=90) + age = unfinished_session_age(now=later) + assert age is not None + assert 89 <= age <= 92 diff --git a/wake_alarm/tests/test_inhibit.py b/wake_alarm/tests/test_inhibit.py index ac0def3..7e19232 100644 --- a/wake_alarm/tests/test_inhibit.py +++ b/wake_alarm/tests/test_inhibit.py @@ -3,16 +3,11 @@ from __future__ import annotations import subprocess -from typing import TYPE_CHECKING from unittest.mock import MagicMock import pytest from wake_alarm import _inhibit -from wake_alarm._constants import INHIBIT_WHO - -if TYPE_CHECKING: - from pathlib import Path @pytest.fixture @@ -46,7 +41,10 @@ class TestTakeInhibitor: def fake_popen(cmd: list[str], **_kwargs: object) -> MagicMock: captured.append(cmd) - return MagicMock(pid=4242) + live = MagicMock(pid=4242) + # Still running after the confirm wait: logind accepted it. + live.wait.side_effect = subprocess.TimeoutExpired("systemd-inhibit", 0.5) + return live monkeypatch.setattr(_inhibit.subprocess, "Popen", fake_popen) @@ -69,6 +67,43 @@ class TestTakeInhibitor: assert _inhibit.take_power_key_inhibitor() is None assert "systemd-inhibit not on PATH" in caplog.text + def test_a_refused_inhibit_is_reported_as_none( + self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + """Claiming a block we did not get is worse than reporting none. + + Popen succeeding only means the *binary* launched. logind can still + refuse -- polkit denies a non-interactive session outright, which a + vmbox run turned up: systemd-inhibit printed "Failed to inhibit: + Access denied" and exited 1 while the alarm logged the power key as + blocked. + """ + monkeypatch.setattr( + _inhibit, "_systemd_inhibit_path", lambda: "/usr/bin/systemd-inhibit" + ) + refused = MagicMock(returncode=1) + refused.wait.return_value = 1 + refused.stderr.read.return_value = b"Failed to inhibit: Access denied" + monkeypatch.setattr(_inhibit.subprocess, "Popen", lambda *a, **k: refused) + with caplog.at_level("WARNING"): + assert _inhibit.take_power_key_inhibitor() is None + assert "logind refused" in caplog.text + assert "Access denied" in caplog.text + + def test_a_refusal_with_no_stderr_still_reports( + self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + """A silent refusal is still a refusal, and still must not be claimed.""" + monkeypatch.setattr( + _inhibit, "_systemd_inhibit_path", lambda: "/usr/bin/systemd-inhibit" + ) + refused = MagicMock(returncode=1, stderr=None) + refused.wait.return_value = 1 + monkeypatch.setattr(_inhibit.subprocess, "Popen", lambda *a, **k: refused) + with caplog.at_level("WARNING"): + assert _inhibit.take_power_key_inhibitor() is None + assert "no detail" in caplog.text + def test_spawn_failure_is_survivable( self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: @@ -139,86 +174,3 @@ class TestReleaseInhibitor: _inhibit.release_power_key_inhibitor(process) process.kill.assert_called_once_with() assert "ignored SIGTERM" in caplog.text - - -class TestStaleCleanup: - """Clearing an inhibitor orphaned by a crashed alarm.""" - - def test_identifies_our_own_child( - self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path - ) -> None: - """A pid is judged by its argv, never by a command-line pattern. - - The earlier ``pkill -f`` version matched the shell that had just typed - the pattern and killed *it* -- substring matching is self-matching. - """ - proc = tmp_path / "77" - proc.mkdir() - (proc / "cmdline").write_bytes( - b"systemd-inhibit\x00--who=" + INHIBIT_WHO.encode() + b"\x00" - ) - monkeypatch.setattr( - _inhibit.pathlib, "Path", lambda *p: tmp_path / p[-2] / p[-1] - ) - assert _inhibit._is_our_inhibitor("77") is True - - def test_ignores_a_pid_that_vanished( - self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path - ) -> None: - """A process that exited between listing and reading is not stale.""" - monkeypatch.setattr( - _inhibit.pathlib, "Path", lambda *p: tmp_path / "definitely-absent" - ) - assert _inhibit._is_our_inhibitor("99") is False - - def test_kills_only_matching_pids(self, monkeypatch: pytest.MonkeyPatch) -> None: - """Someone else's systemd-inhibit is left strictly alone.""" - monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep") - monkeypatch.setattr( - _inhibit.subprocess, - "run", - lambda *a, **k: MagicMock(stdout=b"11\n22\n"), - ) - monkeypatch.setattr(_inhibit, "_is_our_inhibitor", lambda pid: pid == "22") - signalled: list[int] = [] - monkeypatch.setattr( - _inhibit.os, "kill", lambda pid, _sig: signalled.append(pid) - ) - assert _inhibit.kill_stale_inhibitors() == 1 - assert signalled == [22] - - def test_survives_a_pid_that_exits_mid_kill( - self, monkeypatch: pytest.MonkeyPatch - ) -> None: - """A race between listing and killing is not an error.""" - monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep") - monkeypatch.setattr( - _inhibit.subprocess, "run", lambda *a, **k: MagicMock(stdout=b"11\n") - ) - monkeypatch.setattr(_inhibit, "_is_our_inhibitor", lambda _pid: True) - - def gone(_pid: int, _sig: int) -> None: - raise ProcessLookupError - - monkeypatch.setattr(_inhibit.os, "kill", gone) - assert _inhibit.kill_stale_inhibitors() == 0 - - def test_no_pgrep_means_no_scan(self, monkeypatch: pytest.MonkeyPatch) -> None: - """Without pgrep the cleanup is skipped rather than guessed at.""" - monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: None) - assert _inhibit.kill_stale_inhibitors() == 0 - - def test_pgrep_failure_is_survivable( - self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture - ) -> None: - """A failed scan must not stop the alarm from starting.""" - monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep") - - def boom(*_a: object, **_k: object) -> None: - msg = "nope" - raise OSError(msg) - - monkeypatch.setattr(_inhibit.subprocess, "run", boom) - with caplog.at_level("WARNING"): - assert _inhibit.kill_stale_inhibitors() == 0 - assert "Could not check for a stale" in caplog.text diff --git a/wake_alarm/tests/test_inhibit_cleanup.py b/wake_alarm/tests/test_inhibit_cleanup.py new file mode 100644 index 0000000..55a20d1 --- /dev/null +++ b/wake_alarm/tests/test_inhibit_cleanup.py @@ -0,0 +1,103 @@ +"""Tests for clearing a power-key inhibitor orphaned by a crashed alarm. + +Split from ``test_inhibit.py`` for the 250-line cap. The header, including the +copied whole, minus ``test_inhibit.py``'s ``_no_stale_scan`` stub: these tests +exercise the *real* cleanup, and stubbing it out would make every one of them +assert nothing. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from unittest.mock import MagicMock + +from wake_alarm import _inhibit +from wake_alarm._constants import INHIBIT_WHO + +if TYPE_CHECKING: + from pathlib import Path + + import pytest + + +class TestStaleCleanup: + """Clearing an inhibitor orphaned by a crashed alarm.""" + + def test_identifies_our_own_child( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + """A pid is judged by its argv, never by a command-line pattern. + + The earlier ``pkill -f`` version matched the shell that had just typed + the pattern and killed *it* -- substring matching is self-matching. + """ + proc = tmp_path / "77" + proc.mkdir() + (proc / "cmdline").write_bytes( + b"systemd-inhibit\x00--who=" + INHIBIT_WHO.encode() + b"\x00" + ) + monkeypatch.setattr( + _inhibit.pathlib, "Path", lambda *p: tmp_path / p[-2] / p[-1] + ) + assert _inhibit._is_our_inhibitor("77") is True + + def test_ignores_a_pid_that_vanished( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + """A process that exited between listing and reading is not stale.""" + monkeypatch.setattr( + _inhibit.pathlib, "Path", lambda *p: tmp_path / "definitely-absent" + ) + assert _inhibit._is_our_inhibitor("99") is False + + def test_kills_only_matching_pids(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Someone else's systemd-inhibit is left strictly alone.""" + monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep") + monkeypatch.setattr( + _inhibit.subprocess, + "run", + lambda *a, **k: MagicMock(stdout=b"11\n22\n"), + ) + monkeypatch.setattr(_inhibit, "_is_our_inhibitor", lambda pid: pid == "22") + signalled: list[int] = [] + monkeypatch.setattr( + _inhibit.os, "kill", lambda pid, _sig: signalled.append(pid) + ) + assert _inhibit.kill_stale_inhibitors() == 1 + assert signalled == [22] + + def test_survives_a_pid_that_exits_mid_kill( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A race between listing and killing is not an error.""" + monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep") + monkeypatch.setattr( + _inhibit.subprocess, "run", lambda *a, **k: MagicMock(stdout=b"11\n") + ) + monkeypatch.setattr(_inhibit, "_is_our_inhibitor", lambda _pid: True) + + def gone(_pid: int, _sig: int) -> None: + raise ProcessLookupError + + monkeypatch.setattr(_inhibit.os, "kill", gone) + assert _inhibit.kill_stale_inhibitors() == 0 + + def test_no_pgrep_means_no_scan(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Without pgrep the cleanup is skipped rather than guessed at.""" + monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: None) + assert _inhibit.kill_stale_inhibitors() == 0 + + def test_pgrep_failure_is_survivable( + self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + """A failed scan must not stop the alarm from starting.""" + monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep") + + def boom(*_a: object, **_k: object) -> None: + msg = "nope" + raise OSError(msg) + + monkeypatch.setattr(_inhibit.subprocess, "run", boom) + with caplog.at_level("WARNING"): + assert _inhibit.kill_stale_inhibitors() == 0 + assert "Could not check for a stale" in caplog.text