Install exceptions; add-exception via daemon

install offers every approved exception that is not fully installed,
next to the allowed games. add-exception as non-root goes through the
root daemon's new add_exception op, which re-checks reason, phrase,
locks and duplicates; a file left unlocked now fails loudly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-22 22:01:31 +01:00
parent 801f387c21
commit b6f473ceec
16 changed files with 784 additions and 23 deletions

View File

@ -108,3 +108,23 @@ the file's `flags` (game-research's `recording.pid` or `research_launch.pid`,
under the user's home, launch flag at most 20 min old) names a live
`game_research_desktop` process. Deleting the file revokes it at once;
`research_game_revoke` also drops the record and logs `RESEARCH_GAME_REVOKED`.
## Exceptions
`add_exception {"app_id": N, "reason": "...", "phrase": "..."}`
(`_ctl_exception.py`). `approved_exceptions.json` is `chattr +i`, so only root
can replace it; the web job and the CLI as the desktop user both send this op.
The daemon looks the name up in the snapshot (else `AppID=<id>`, as the CLI
does), then checks in order: the reason rule (`invalid_params`), the phrase
`request exception for {game_name}` (`wrong_phrase`), the locks (`locked`), and
duplicates (`invalid_params`). It clears `+i`, writes, hands a new file back to
the config dir's owner, sets `+i` again and appends `APPROVED` to
`exception_audit.log`.
If the flag will not go back on, the entry and the audit line stay but the op
fails: `op_failed` "exception saved but file not locked". Under `sudo` the CLI
writes the file itself and fails the same way (exit 1). If the socket does not
answer, the CLI exits 1 naming `/run/steam-backlog-enforcer/ctl.sock` and the
`sudo ./run.sh add-exception` fallback. The enforce loop's own per-tick lock
stays best-effort and logs "immutable flag did not stick" once per file, not
per tick, until the flag holds again.

View File

@ -199,7 +199,7 @@ with explicit params, a `Progress` reporter and a `Prompter`.
| `gaming-unblock` | `force release playtime mounts` | daemon; if unreachable the UI shows the `sudo ./run.sh gaming-unblock` fallback |
| `abandon-pick` | `abandon {game_name}` | – |
| `pick-manual` | `lock in {game_name}` | – |
| `add-exception` | `request exception for {game_name}` | active immediately (no cooldown since de76c65); reason logged |
| `add-exception` | `request exception for {game_name}` | daemon (the file is `chattr +i`); active immediately (no cooldown since de76c65); reason logged |
| `uninstall` | `uninstall {count} games` | – |
| `reset` | `wipe all enforcer state` | automatic timestamped backup first |
| backup restore | `restore backup {id}` | – |
@ -222,7 +222,8 @@ hard-codes it.
`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`.
`gaming_reset_cancel{pending_id}`, `restart{}`,
`add_exception{app_id, reason, phrase}`. There is no `stop`.
- `status` also lists the daemon's steam-game-installer runs as
`fast_installs: [{app_id, name, phase, percent, elapsed_seconds, error}]`,
read from its log by the enforce loop; `percent` is the current depot's, or

View File

@ -49,7 +49,7 @@ def call(
args: dict[str, object] | None = None,
*,
timeout: float = _DEFAULT_TIMEOUT,
path: Path = SOCKET_PATH,
path: Path | None = None,
) -> dict[str, object]:
"""Send one request and return the response's ``data``.
@ -57,7 +57,8 @@ def call(
op: Op name.
args: Op arguments.
timeout: Seconds to wait for connect and for the reply.
path: Socket path (overridable for tests).
path: Socket path; ``None`` reads ``SOCKET_PATH`` at call time, so
the tests' redirect covers every caller.
Returns:
The ``data`` object of a successful response.
@ -66,6 +67,7 @@ def call(
DaemonUnreachableError: No daemon answered on the socket.
CtlError: The daemon refused or failed the op.
"""
path = path or SOCKET_PATH
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn.settimeout(timeout)
try:
@ -234,3 +236,11 @@ def restart() -> str | None:
data = call("restart")
until = data.get("restart_available_at")
return str(until) if until else None
def add_exception(app_id: int, reason: str, phrase: str) -> str:
"""Whitelist *app_id*; the daemon re-checks phrase, reason, locks, duplicates."""
# Outwait the tick lock: a client that gave up first would report a
# failure for an entry the daemon then writes anyway.
args = {"app_id": app_id, "reason": reason, "phrase": phrase}
return str(call("add_exception", args, timeout=_SLOW_TIMEOUT)["message"])

View File

@ -0,0 +1,73 @@
"""Control-socket op ``add_exception``: whitelist one game as root.
``approved_exceptions.json`` carries ``chattr +i``, so the unprivileged web
server and CLI cannot replace it (2026-11-22: every web add-exception died
with ``PermissionError``). The daemon writes it instead: it clears the flag,
writes, and sets it again.
The client sends only the app id, the reason and the typed phrase. The daemon
looks the name up itself (falling back to ``AppID=<id>``, as the CLI does) and
re-checks the reason, the phrase, the locks and duplicates, so talking to the
socket directly skips none of them.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Final
from steam_backlog_enforcer._ctl_context import (
check_locks,
hold_tick,
int_arg,
require_phrase,
str_arg,
)
from steam_backlog_enforcer._ctl_protocol import INVALID_PARAMS, OP_FAILED, CtlError
from steam_backlog_enforcer._snapshot import snapshot_game_name
from steam_backlog_enforcer._whitelist import validate_reason
from steam_backlog_enforcer._whitelist_locking import add_pending_exception
from steam_backlog_enforcer._whitelist_relock import (
NOT_LOCKED_MESSAGE,
ExceptionNotLockedError,
)
if TYPE_CHECKING:
from collections.abc import Callable
from steam_backlog_enforcer._ctl_context import CtlContext
logger = logging.getLogger(__name__)
_MAX_APP_ID: Final = 2**31 - 1
def op_add_exception(ctx: CtlContext, args: dict[str, object]) -> dict[str, object]:
"""Add a whitelist exception, active immediately, as ``add-exception`` does."""
app_id = int_arg(args, "app_id", 1, _MAX_APP_ID)
reason = str_arg(args, "reason")
err = validate_reason(reason)
if err is not None:
raise CtlError(INVALID_PARAMS, err)
game_name = snapshot_game_name(app_id) or f"AppID={app_id}"
require_phrase("add-exception", args.get("phrase"), game_name=game_name)
with hold_tick(ctx):
check_locks("add-exception")
try:
message = add_pending_exception(app_id, reason)
except ExceptionNotLockedError as exc:
logger.exception("Exception for %s saved, file left unlocked", app_id)
raise CtlError(OP_FAILED, NOT_LOCKED_MESSAGE) from exc
except ValueError as exc: # already approved
raise CtlError(INVALID_PARAMS, str(exc)) from exc
except OSError as exc:
raise CtlError(
OP_FAILED, f"could not write the exceptions file: {exc}"
) from exc
logger.warning("Exception approved for %s (control socket)", app_id)
return {"app_id": app_id, "game_name": game_name, "message": message}
EXCEPTION_OPS: Final[
dict[str, Callable[[CtlContext, dict[str, object]], dict[str, object]]]
] = {"add_exception": op_add_exception}

View File

@ -22,6 +22,7 @@ from steam_backlog_enforcer._ctl_context import (
int_arg,
require_phrase,
)
from steam_backlog_enforcer._ctl_exception import EXCEPTION_OPS
from steam_backlog_enforcer._ctl_protocol import OP_FAILED, CtlError
from steam_backlog_enforcer._ctl_research_game import RESEARCH_GAME_OPS
from steam_backlog_enforcer._ctl_reset import RESET_OPS
@ -185,4 +186,5 @@ OPS: Final[dict[str, Callable[[CtlContext, dict[str, object]], dict[str, object]
**RESET_OPS,
**RESTART_OPS,
**RESEARCH_GAME_OPS,
**EXCEPTION_OPS,
}

View File

@ -21,6 +21,12 @@ from steam_backlog_enforcer._whitelist import (
_FS_IOC_GETFLAGS,
validate_reason,
)
from steam_backlog_enforcer._whitelist_relock import (
NOT_LOCKED_MESSAGE,
ExceptionNotLockedError,
hand_back_to_dir_owner,
note_lock_state,
)
from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
if TYPE_CHECKING:
@ -70,25 +76,28 @@ def _immutable_flag_is(path: Path, *, immutable: bool) -> bool:
return bool(buf[0] & _FS_IMMUTABLE_FL) is immutable
def _try_set_immutable(path: Path, *, immutable: bool) -> None:
"""Silently attempt to set or clear the immutable flag on *path*.
def _try_set_immutable(path: Path, *, immutable: bool) -> bool:
"""Attempt to set or clear the immutable flag on *path*.
This is a best-effort operation — it fails silently if chattr is not
available, the process lacks the required capability, or the filesystem
does not support the flag. When the flag already holds the requested
value, no subprocess is spawned at all.
Never raises: chattr missing, the capability missing or a filesystem
without the flag all end in False. When the flag already holds the
requested value, no subprocess is spawned at all.
Args:
path: File to modify.
immutable: True to set +i, False to clear -i.
Returns:
Whether the flag now reads back as *immutable* (True for a missing
file: there is nothing to lock).
"""
if not path.exists():
return
return True
if _immutable_flag_is(path, immutable=immutable):
return
return True
chattr = shutil.which("chattr")
if chattr is None:
return
return False
flag = "+i" if immutable else "-i"
with contextlib.suppress(OSError, subprocess.TimeoutExpired):
subprocess.run(
@ -97,6 +106,12 @@ def _try_set_immutable(path: Path, *, immutable: bool) -> None:
check=False,
timeout=5,
)
return _immutable_flag_is(path, immutable=immutable)
def _relock(path: Path) -> bool:
"""Set +i on *path* again after a write; report whether it holds."""
return _try_set_immutable(path, immutable=True)
def lock_enforcement_files(config_file: Path) -> None:
@ -108,8 +123,8 @@ def lock_enforcement_files(config_file: Path) -> None:
Args:
config_file: Path to the main config.json.
"""
_try_set_immutable(config_file, immutable=True)
_try_set_immutable(APPROVED_EXCEPTIONS_FILE, immutable=True)
for path in (config_file, APPROVED_EXCEPTIONS_FILE):
note_lock_state(path, locked=_try_set_immutable(path, immutable=True))
def unlock_for_write(path: Path) -> None:
@ -139,11 +154,12 @@ def _load_approved() -> list[dict[str, object]]:
return []
def _save_approved(entries: list[dict[str, object]]) -> None:
"""Persist approved exception entries to disk."""
def _save_approved(entries: list[dict[str, object]]) -> bool:
"""Persist approved exception entries; True if the file is locked again."""
unlock_for_write(APPROVED_EXCEPTIONS_FILE)
_atomic_write(APPROVED_EXCEPTIONS_FILE, json.dumps(entries, indent=2) + "\n")
_try_set_immutable(APPROVED_EXCEPTIONS_FILE, immutable=True)
hand_back_to_dir_owner(APPROVED_EXCEPTIONS_FILE)
return _relock(APPROVED_EXCEPTIONS_FILE)
def _append_audit_log(app_id: int, reason: str, event: str) -> None:
@ -163,6 +179,7 @@ def _append_audit_log(app_id: int, reason: str, event: str) -> None:
EXCEPTION_AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
with EXCEPTION_AUDIT_LOG.open("a", encoding="utf-8") as fh:
fh.write(line)
hand_back_to_dir_owner(EXCEPTION_AUDIT_LOG)
# ──────────────────────────────────────────────────────────────
@ -185,6 +202,8 @@ def add_pending_exception(app_id: int, reason: str) -> str:
Raises:
ValueError: If the reason fails validation or the ID is already approved.
ExceptionNotLockedError: The entry was saved and audited, but the file
could not be made immutable again.
"""
err = validate_reason(reason)
if err is not None:
@ -203,8 +222,10 @@ def add_pending_exception(app_id: int, reason: str) -> str:
"approved_at": now,
}
)
_save_approved(approved)
locked = _save_approved(approved)
_append_audit_log(app_id, reason, "APPROVED")
if not locked:
raise ExceptionNotLockedError(NOT_LOCKED_MESSAGE)
return f"Exception approved for AppID {app_id}. Active immediately. Reason logged."

View File

@ -0,0 +1,62 @@
"""What happens around a write to the ``chattr +i`` exceptions file.
Split out of :mod:`steam_backlog_enforcer._whitelist_locking` to keep it under
the 250-line cap. Imports nothing from it, so either side can be loaded alone.
* A direct write that cannot set the flag again raises
:class:`ExceptionNotLockedError`: the entry is kept, but the caller must not
report success for a file anyone can now edit.
* A file root creates is handed back to the config dir's owner, or the
unprivileged CLI and web server could no longer read their own list.
* The enforce loop's per-tick lock stays best-effort, so it can never crash
the daemon; :func:`note_lock_state` logs only when a file's lock state
changes, so a flag that will not stick warns once, not every ~3 s tick.
"""
from __future__ import annotations
import contextlib
import logging
import os
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(__name__)
NOT_LOCKED_MESSAGE = "exception saved but file not locked"
# Files whose flag did not stick at the last tick (warned about already).
_unlocked: set[Path] = set()
class ExceptionNotLockedError(RuntimeError):
"""The exception was saved, but the file could not be made immutable."""
def hand_back_to_dir_owner(path: Path) -> None:
"""Give *path* to the owner of its directory if root just created it.
Must run while the file is still mutable: ``chown`` on a ``+i`` file is
refused. A missing file or a refused ``chown`` (non-root) is left alone.
"""
with contextlib.suppress(OSError):
owner = path.parent.stat()
if path.stat().st_uid != owner.st_uid:
os.chown(path, owner.st_uid, owner.st_gid)
def note_lock_state(path: Path, *, locked: bool) -> None:
"""Log *path*'s lock state, but only when it changed since the last tick."""
if not locked and path not in _unlocked:
_unlocked.add(path)
logger.warning("%s: immutable flag did not stick (chattr +i failed)", path)
elif locked and path in _unlocked:
_unlocked.discard(path)
logger.info("%s: immutable flag holds again", path)
def reset_lock_warnings() -> None:
"""Forget which files were warned about (tests)."""
_unlocked.clear()

View File

@ -6,12 +6,21 @@ its typed-phrase confirmation, to keep both files under the 250-line cap.
from __future__ import annotations
import os
import sys
from steam_backlog_enforcer import _ctl_client
from steam_backlog_enforcer._ctl_protocol import (
SOCKET_PATH,
CtlError,
DaemonUnreachableError,
)
from steam_backlog_enforcer._friction import expected_phrase
from steam_backlog_enforcer._prompter import confirm_phrase
from steam_backlog_enforcer._snapshot import snapshot_game_name
from steam_backlog_enforcer._whitelist import validate_reason
from steam_backlog_enforcer._whitelist_locking import add_pending_exception
from steam_backlog_enforcer._whitelist_relock import ExceptionNotLockedError
from steam_backlog_enforcer.game_install import _echo
_MIN_ADD_EXCEPTION_ARGS = 3
@ -26,6 +35,18 @@ _ADD_EXCEPTION_USAGE = (
)
def _add(app_id: int, reason: str, game_name: str) -> str:
"""Write the exception: in-process under sudo, else through the daemon.
The file is ``chattr +i``; only root can replace it. The phrase was
already typed and checked here; the daemon checks it again.
"""
if os.geteuid() == 0:
return add_pending_exception(app_id, reason)
phrase = expected_phrase("add-exception", game_name=game_name) or ""
return _ctl_client.add_exception(app_id, reason, phrase)
def cmd_add_exception(args: list[str]) -> None:
"""Add a whitelist exception, active immediately.
@ -71,9 +92,19 @@ def cmd_add_exception(args: list[str]) -> None:
sys.exit(1)
try:
msg = add_pending_exception(app_id, reason)
except ValueError as exc:
msg = _add(app_id, reason, game_name)
except (ValueError, ExceptionNotLockedError) as exc:
_echo(f"Error: {exc}")
sys.exit(1)
except CtlError as exc:
_echo(f"Error: {exc.message or exc.code}")
sys.exit(1)
except DaemonUnreachableError as exc:
_echo(
f"Error: the enforcer daemon did not answer on {SOCKET_PATH} ({exc}).\n"
"Start it, or write the file as root: "
f'sudo ./run.sh add-exception {app_id} --reason "..."'
)
sys.exit(1)
_echo(msg)

View File

@ -19,6 +19,7 @@ import pytest
from steam_backlog_enforcer._hltb_failures import reset_failures
from steam_backlog_enforcer._hltb_search_api import forget_hltb_search_url
from steam_backlog_enforcer._icon_ledger import LEDGER_ENV
from steam_backlog_enforcer._whitelist_relock import reset_lock_warnings
if TYPE_CHECKING:
from collections.abc import Iterator
@ -34,9 +35,14 @@ def _isolate_control_plane(
Without it a test that reaches the restart-exit marker or a job store
touches ``/var/lib/steam-backlog-enforcer`` or the real
``~/.local/state`` (and the web token lives under ``XDG_RUNTIME_DIR``).
Default arguments bound at import (``path=SOCKET_PATH``) cannot be
redirected here: tests pass an explicit path for those.
``_ctl_client.call`` reads ``SOCKET_PATH`` at call time, so a command that
asks the daemon (``add-exception`` as non-root) never reaches the live one.
The exceptions file's re-lock counts as holding: a non-root test can never
set ``+i``, and ``add_pending_exception`` now fails loudly when it is not.
``test_whitelist_relock`` covers the real ``_relock``.
"""
reset_lock_warnings()
state = tmp_path / "ctl_state"
monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path / "xdg_runtime"))
# The icon-word ledger is a committed repo file: never write the real one.
@ -52,6 +58,7 @@ def _isolate_control_plane(
patch("steam_backlog_enforcer._ctl_server.SOCKET_PATH", state / "ctl.sock"),
patch("steam_backlog_enforcer._backups.BACKUPS_DIR", tmp_path / "backups"),
patch("steam_backlog_enforcer.jobs._store.JOBS_DIR", tmp_path / "jobs"),
patch("steam_backlog_enforcer._whitelist_locking._relock", return_value=True),
):
yield

View File

@ -0,0 +1,38 @@
"""``_ctl_client.add_exception`` and the tests' socket backstop."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _ctl_client
from steam_backlog_enforcer._ctl_context import LOCK_WAIT_SECONDS
from steam_backlog_enforcer._ctl_protocol import SOCKET_PATH, DaemonUnreachableError
def test_add_exception_sends_args_and_returns_message() -> None:
"""Only id, reason and phrase go over the wire; the message comes back."""
with patch.object(
_ctl_client, "call", return_value={"app_id": 1, "message": "approved"}
) as call:
assert _ctl_client.add_exception(1, "a reason", "the phrase") == "approved"
assert call.call_args.args == (
"add_exception",
{"app_id": 1, "reason": "a reason", "phrase": "the phrase"},
)
def test_add_exception_outwaits_the_tick_lock() -> None:
"""A client that gave up while the daemon waits for the tick would report
a failure for an entry the daemon then writes."""
with patch.object(_ctl_client, "call", return_value={"message": "m"}) as call:
_ctl_client.add_exception(1, "r", "p")
assert call.call_args.kwargs["timeout"] > LOCK_WAIT_SECONDS
def test_tests_never_reach_the_live_socket() -> None:
"""conftest points the default socket away from the live daemon."""
assert vars(_ctl_client)["SOCKET_PATH"] != SOCKET_PATH
with pytest.raises(DaemonUnreachableError):
_ctl_client.ping()

View File

@ -0,0 +1,132 @@
"""The ``add_exception`` control-socket op.
The web server cannot replace the ``chattr +i`` exceptions file, so the root
daemon writes it. The daemon re-checks the phrase, the reason, the locks and
duplicates itself: a client talking straight to the socket skips nothing.
"""
from __future__ import annotations
import json
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _ctl_ops
from steam_backlog_enforcer import _whitelist_locking as wl
from steam_backlog_enforcer._ctl_protocol import (
INVALID_PARAMS,
LOCKED,
OP_FAILED,
WRONG_PHRASE,
CtlError,
)
from steam_backlog_enforcer.tests._ctl_fixtures import make_ctx
from steam_backlog_enforcer.tests._main_helpers import VALID_REASON
MOD = "steam_backlog_enforcer._ctl_exception"
APP = 588730
PHRASE = "request exception for Majotori"
def _call(**args: object) -> dict[str, object]:
full: dict[str, object] = {"app_id": APP, "reason": VALID_REASON, "phrase": PHRASE}
full.update(args)
with patch(f"{MOD}.snapshot_game_name", return_value="Majotori"):
return _ctl_ops.OPS["add_exception"](make_ctx(), full)
def _error(**args: object) -> CtlError:
with pytest.raises(CtlError) as err:
_call(**args)
return err.value
def _approved_ids() -> list[int]:
if not wl.APPROVED_EXCEPTIONS_FILE.exists():
return []
entries = json.loads(wl.APPROVED_EXCEPTIONS_FILE.read_text(encoding="utf-8"))
return [int(e["app_id"]) for e in entries]
def test_op_is_allowlisted() -> None:
"""The op is in the socket's allowlist."""
assert "add_exception" in _ctl_ops.OPS
def test_adds_the_exception() -> None:
"""Right phrase and reason: the entry is written and reported."""
data = _call()
assert data["app_id"] == APP
assert "Exception approved for AppID 588730" in str(data["message"])
assert _approved_ids() == [APP]
def test_wrong_phrase_writes_nothing() -> None:
"""A wrong phrase is refused before the file is touched."""
assert _error(phrase="wrong").code == WRONG_PHRASE
assert _approved_ids() == []
def test_phrase_names_app_id_without_snapshot_name() -> None:
"""With no snapshot name the phrase uses AppID=<id>, as the CLI does."""
args = {
"app_id": APP,
"reason": VALID_REASON,
"phrase": f"request exception for AppID={APP}",
}
with patch(f"{MOD}.snapshot_game_name", return_value=None):
_ctl_ops.OPS["add_exception"](make_ctx(), args)
assert _approved_ids() == [APP]
def test_short_reason_is_invalid_params() -> None:
"""The reason rule holds at the socket, not only in the CLI."""
err = _error(reason="too short")
assert err.code == INVALID_PARAMS
assert _approved_ids() == []
@pytest.mark.parametrize(
"args",
[{"app_id": "x"}, {"app_id": True}, {"app_id": 0}, {"reason": 5}, {"reason": ""}],
)
def test_bad_args_are_invalid_params(args: dict[str, object]) -> None:
"""Non-integer ids, bools and non-text reasons are refused."""
assert _error(**args).code == INVALID_PARAMS
def test_duplicate_is_invalid_params() -> None:
"""An id already approved is refused by the daemon."""
_call()
err = _error()
assert err.code == INVALID_PARAMS
assert "already in the approved exceptions list" in err.message
assert _approved_ids() == [APP]
def test_lock_refuses() -> None:
"""A lock the CLI honours is honoured here too."""
with patch(f"{MOD}.check_locks", side_effect=CtlError(LOCKED, "locked")):
assert _error().code == LOCKED
assert _approved_ids() == []
def test_write_failure_is_op_failed() -> None:
"""A file the daemon cannot write fails the op with the reason."""
with patch(f"{MOD}.add_pending_exception", side_effect=OSError("read-only fs")):
err = _error()
assert err.code == OP_FAILED
assert "read-only fs" in err.message
def test_relock_failure_keeps_entry_and_fails_loudly() -> None:
"""Saved but not locked again: entry and audit line stay, the op fails."""
with patch.object(wl, "_relock", return_value=False):
err = _error()
assert err.code == OP_FAILED
assert err.message == "exception saved but file not locked"
assert _approved_ids() == [APP]
assert f"APPROVED | app_id={APP}" in wl.EXCEPTION_AUDIT_LOG.read_text(
encoding="utf-8"
)

View File

@ -186,4 +186,5 @@ class TestOpsTable:
"restart",
"research_game",
"research_game_revoke",
"add_exception",
}

View File

@ -0,0 +1,111 @@
"""``add-exception`` as plain kuhy goes through the root daemon.
The exceptions file is ``chattr +i``; only root can replace it. Under sudo the
CLI still writes the file itself; everyone else asks the daemon.
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _ctl_client
from steam_backlog_enforcer._ctl_protocol import (
INVALID_PARAMS,
CtlError,
DaemonUnreachableError,
)
from steam_backlog_enforcer._whitelist_relock import ExceptionNotLockedError
from steam_backlog_enforcer.main import cmd_add_exception
from steam_backlog_enforcer.tests._main_helpers import VALID_REASON
EXC_PKG = "steam_backlog_enforcer.main.exception"
ARGS = ["440", "--reason", VALID_REASON]
PHRASE = "request exception for AppID=440"
def _run(*, euid: int) -> list[str]:
"""Run the command with the phrase typed; returns what it echoed."""
with (
patch(f"{EXC_PKG}.os.geteuid", return_value=euid),
patch("builtins.input", return_value=PHRASE),
patch(f"{EXC_PKG}._echo") as echo,
):
cmd_add_exception(ARGS)
return [str(c.args[0]) if c.args else "" for c in echo.call_args_list]
def test_plain_user_asks_the_daemon() -> None:
"""Non-root sends id, reason and phrase to the socket; no direct write."""
with (
patch.object(_ctl_client, "add_exception", return_value="ok msg") as client,
patch(f"{EXC_PKG}.add_pending_exception") as direct,
):
out = _run(euid=1000)
client.assert_called_once_with(440, VALID_REASON, PHRASE)
direct.assert_not_called()
assert out[-1] == "ok msg"
def test_root_writes_directly() -> None:
"""Under sudo the file is written in-process, as before."""
with (
patch.object(_ctl_client, "add_exception") as client,
patch(f"{EXC_PKG}.add_pending_exception", return_value="direct") as direct,
):
out = _run(euid=0)
direct.assert_called_once_with(440, VALID_REASON)
client.assert_not_called()
assert out[-1] == "direct"
def test_unreachable_message_text(capsys: pytest.CaptureFixture[str]) -> None:
"""The message names /run/steam-backlog-enforcer/ctl.sock and sudo."""
with (
patch(f"{EXC_PKG}.os.geteuid", return_value=1000),
patch("builtins.input", return_value=PHRASE),
patch.object(
_ctl_client, "add_exception", side_effect=DaemonUnreachableError("gone")
),
patch(f"{EXC_PKG}._echo", side_effect=print),
pytest.raises(SystemExit),
):
cmd_add_exception(ARGS)
out = capsys.readouterr().out
assert "/run/steam-backlog-enforcer/ctl.sock" in out
assert "sudo ./run.sh add-exception" in out
def test_daemon_refusal_exits_with_its_message(
capsys: pytest.CaptureFixture[str],
) -> None:
"""A refusal (duplicate, locked, ...) prints the daemon's text, exit 1."""
err = CtlError(
INVALID_PARAMS, "AppID 440 is already in the approved exceptions list."
)
with (
patch(f"{EXC_PKG}.os.geteuid", return_value=1000),
patch("builtins.input", return_value=PHRASE),
patch.object(_ctl_client, "add_exception", side_effect=err),
patch(f"{EXC_PKG}._echo", side_effect=print),
pytest.raises(SystemExit, match="1"),
):
cmd_add_exception(ARGS)
assert "already in the approved exceptions list" in capsys.readouterr().out
def test_root_relock_failure_exits_1(capsys: pytest.CaptureFixture[str]) -> None:
"""Under sudo a file left unlocked is an error too, not a success."""
with (
patch(f"{EXC_PKG}.os.geteuid", return_value=0),
patch("builtins.input", return_value=PHRASE),
patch(
f"{EXC_PKG}.add_pending_exception",
side_effect=ExceptionNotLockedError("exception saved but file not locked"),
),
patch(f"{EXC_PKG}._echo", side_effect=print),
pytest.raises(SystemExit, match="1"),
):
cmd_add_exception(ARGS)
assert "exception saved but file not locked" in capsys.readouterr().out

View File

@ -0,0 +1,106 @@
"""``install`` offers approved exceptions next to the allowed games.
App 3347910 was whitelisted and ``install`` still answered "All allowed games
are already installed.": the candidates came from ``allowed_games`` alone.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from steam_backlog_enforcer._prompter import use_prompter
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.main import cmd_install
from steam_backlog_enforcer.tests._fake_prompter import FakePrompter
PKG = "steam_backlog_enforcer.main.install"
EXC = 588730
NAMES = {EXC: "Majotori"}
def _assigned() -> State:
return State(current_app_id=1, current_game_name="Assigned")
def _run(
state: State,
*,
exceptions: frozenset[int],
installed: set[int],
prompter: FakePrompter | None = None,
) -> tuple[FakePrompter, MagicMock, MagicMock]:
"""Run ``cmd_install``; returns the prompter, install_game and _echo mocks."""
prompter = prompter or FakePrompter()
with (
use_prompter(prompter),
patch(f"{PKG}.get_approved_exception_ids", return_value=exceptions),
patch(f"{PKG}.snapshot_game_name", side_effect=NAMES.get),
patch(f"{PKG}.is_game_fully_installed", side_effect=installed.__contains__),
patch(f"{PKG}.install_game", return_value=True) as install,
patch(f"{PKG}.fast_install_failure", return_value=None),
patch(f"{PKG}._echo") as echo,
):
cmd_install(Config(steam_id="i"), state)
return prompter, install, echo
def _echoed(echo: MagicMock) -> list[str]:
return [str(c) for c in echo.call_args_list]
class TestInstallOffersExceptions:
"""Every approved exception that is not fully installed is a candidate."""
def test_uninstalled_exception_is_offered_next_to_allowed(self) -> None:
"""Both sources land in one prompt; picking the exception installs it."""
prompter, install, _ = _run(
_assigned(),
exceptions=frozenset({EXC}),
installed=set(),
prompter=FakePrompter(choices=[str(EXC)]),
)
assert prompter.asked[0][1] == ["1", str(EXC)]
assert install.call_args.args[:2] == (EXC, "Majotori")
def test_only_uninstalled_exception_installs_without_prompt(self) -> None:
"""Allowed game installed, one exception left: no prompt, it installs."""
prompter, install, _ = _run(
_assigned(), exceptions=frozenset({EXC}), installed={1}
)
assert prompter.asked == []
assert install.call_args.args[:2] == (EXC, "Majotori")
def test_unknown_name_falls_back_to_app_id(self) -> None:
"""An exception missing from the snapshot shows as AppID=<id>."""
_, install, _ = _run(_assigned(), exceptions=frozenset({77}), installed={1})
assert install.call_args.args[:2] == (77, "AppID=77")
def test_exception_that_is_also_allowed_is_offered_once(self) -> None:
"""The allowed entry wins; the id is not listed twice."""
prompter, install, _ = _run(
_assigned(), exceptions=frozenset({1}), installed=set()
)
assert prompter.asked == []
assert install.call_args.args[:2] == (1, "Assigned")
def test_everything_installed_keeps_the_old_message(self) -> None:
"""Allowed game and exception both installed: nothing to do."""
_, install, echo = _run(
_assigned(), exceptions=frozenset({EXC}), installed={1, EXC}
)
install.assert_not_called()
assert any(
"All allowed games are already installed." in c for c in _echoed(echo)
)
def test_no_assignment_but_an_exception_installs_it(self) -> None:
"""No allowed game is not "run scan first" while an exception exists."""
_, install, echo = _run(State(), exceptions=frozenset({EXC}), installed=set())
assert install.call_args.args[:2] == (EXC, "Majotori")
assert not any("No game currently assigned" in c for c in _echoed(echo))
def test_no_assignment_and_no_exceptions_says_scan(self) -> None:
"""Nothing from either source: the scan hint, as before."""
_, install, echo = _run(State(), exceptions=frozenset(), installed=set())
install.assert_not_called()
assert any("No game currently assigned" in c for c in _echoed(echo))

View File

@ -1,5 +1,6 @@
"""Tests for the main CLI: add-exception and block-gaming commands."""
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
@ -12,6 +13,9 @@ from steam_backlog_enforcer.tests._main_helpers import (
VALID_REASON,
)
if TYPE_CHECKING:
from collections.abc import Iterator
PKG = "steam_backlog_enforcer.main.misc"
EXC_PKG = "steam_backlog_enforcer.main.exception"
_PHRASE = "request exception for AppID=440"
@ -21,6 +25,12 @@ _BLOCK_PHRASE = "block all gaming for 14 days"
class TestCmdAddException:
"""add-exception validates arguments and the typed phrase."""
@pytest.fixture(autouse=True)
def _as_root(self) -> Iterator[None]:
"""These cover the direct write; as non-root it goes through the daemon."""
with patch(f"{EXC_PKG}.os.geteuid", return_value=0):
yield
def test_no_args_prints_usage_and_exits(self) -> None:
"""No arguments prints usage and exits 1."""
with (

View File

@ -0,0 +1,136 @@
"""Re-locking the exceptions file after a write, and saying so when it fails.
``_try_set_immutable`` used to fail silently, so a write that left the file
unlocked looked like success. A direct write now fails loudly; the enforce
loop's per-tick lock stays best-effort but warns once when the flag will not
stick.
"""
from __future__ import annotations
import logging
import os
from pathlib import Path
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _whitelist_locking as wl
from steam_backlog_enforcer import _whitelist_relock as relock_mod
# The real function: conftest swaps ``wl._relock`` for "always locked",
# since a non-root test can never set +i.
from steam_backlog_enforcer._whitelist_locking import (
_relock as real_relock,
)
from steam_backlog_enforcer._whitelist_locking import (
_try_set_immutable,
)
from steam_backlog_enforcer._whitelist_relock import (
ExceptionNotLockedError,
hand_back_to_dir_owner,
)
from steam_backlog_enforcer.tests._main_helpers import VALID_REASON
def test_add_raises_after_saving_when_not_relocked() -> None:
"""The entry and the audit line stay; the caller hears it failed."""
with (
patch.object(wl, "_relock", return_value=False),
pytest.raises(ExceptionNotLockedError, match="not locked"),
):
wl.add_pending_exception(440, VALID_REASON)
assert wl.get_approved_exception_ids() == frozenset({440})
assert "APPROVED | app_id=440" in wl.EXCEPTION_AUDIT_LOG.read_text(encoding="utf-8")
def test_real_relock_reports_flag_state(tmp_path: Path) -> None:
"""True only when the flag reads back as set after chattr."""
target = tmp_path / "f.json"
target.write_text("[]", encoding="utf-8")
with patch.object(wl, "_immutable_flag_is", return_value=True):
assert real_relock(target) is True
with (
patch("shutil.which", return_value=None),
patch.object(wl, "_immutable_flag_is", return_value=False),
):
assert real_relock(target) is False
def test_try_set_immutable_reports_missing_file_as_nothing_to_do(
tmp_path: Path,
) -> None:
"""A file that does not exist has nothing to lock."""
assert _try_set_immutable(tmp_path / "absent", immutable=True) is True
def test_hand_back_chowns_to_dir_owner(tmp_path: Path) -> None:
"""A file root just created goes back to the config dir's owner."""
target = tmp_path / "f.json"
target.write_text("[]", encoding="utf-8")
dir_stat = tmp_path.stat()
root_owned = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) # uid 0, gid 0
real_stat = Path.stat
def _stat(self: Path, *, follow_symlinks: bool = True) -> os.stat_result:
if self == target:
return root_owned
return real_stat(self, follow_symlinks=follow_symlinks)
with (
patch.object(Path, "stat", autospec=True, side_effect=_stat),
patch("os.chown") as chown,
):
hand_back_to_dir_owner(target)
chown.assert_called_once_with(target, dir_stat.st_uid, dir_stat.st_gid)
def test_hand_back_leaves_matching_owner_alone(tmp_path: Path) -> None:
"""Same owner as the dir: no chown at all."""
target = tmp_path / "f.json"
target.write_text("[]", encoding="utf-8")
with patch("os.chown") as chown:
hand_back_to_dir_owner(target)
chown.assert_not_called()
def test_hand_back_ignores_missing_file(tmp_path: Path) -> None:
"""A missing file is not an error."""
hand_back_to_dir_owner(tmp_path / "absent")
class TestLockWarning:
"""The enforce loop warns once when the flag will not stick, not per tick."""
@pytest.fixture(autouse=True)
def _fresh(self) -> None:
relock_mod.reset_lock_warnings()
def test_warns_once_then_notes_recovery(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Three failing ticks: one warning. Then it holds: one recovery line."""
cfg = tmp_path / "config.json"
caplog.set_level(logging.INFO, logger=relock_mod.__name__)
with patch.object(wl, "_try_set_immutable", return_value=False):
for _ in range(3):
wl.lock_enforcement_files(cfg)
warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
# Two files, each warned once.
assert len(warnings) == 2
assert all("immutable flag did not stick" in r.getMessage() for r in warnings)
caplog.clear()
with patch.object(wl, "_try_set_immutable", return_value=True):
wl.lock_enforcement_files(cfg)
wl.lock_enforcement_files(cfg)
assert [r.levelno for r in caplog.records] == [logging.INFO, logging.INFO]
def test_silent_while_flag_holds(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""No log line at all when the flag holds every tick."""
caplog.set_level(logging.INFO, logger=relock_mod.__name__)
with patch.object(wl, "_try_set_immutable", return_value=True):
for _ in range(3):
wl.lock_enforcement_files(tmp_path / "config.json")
assert caplog.records == []