Add the research game slot and ctl ops

game-research's approved game is kept installed, visible and on
disk; it is spared from the kill only while game-research launches
or records it. research_game/research_game_revoke ops are audited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-21 15:57:06 +01:00
parent 9725e48044
commit 2ac30bcdaf
15 changed files with 667 additions and 7 deletions

View File

@ -73,3 +73,23 @@ the budget cutoff and its mounts persist throughout.
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.
## Research game
`research_game {"app_id": N}` and `research_game_revoke {}` (`_ctl_research_game.py`,
rules in `_research_game.py`). game-research (PlayStudy) writes its approval
file `~/.config/game-research/research_game.json` (`{app_id, added_at, flags}`)
and then calls `research_game`; the op refuses (`invalid_params`) unless the
file names the same app id, writes the root record
`/var/lib/steam-backlog-enforcer/research_game.json` and appends
`RESEARCH_GAME_ADDED app_id=N` to `exception_audit.log`. No phrase, no delay,
no time lock: it can only confirm what the file says, one game at a time.
The game is the research game while the file and the record agree. It is
never uninstalled (`uninstall_game` refuses it for every caller), never hidden,
exempt from the tampering check, and a total-block purge keeps
`~/.local/share/Steam`. The unauthorized-game kill spares it only while one of
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`.

View File

@ -23,6 +23,7 @@ from steam_backlog_enforcer._ctl_context import (
require_phrase,
)
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
from steam_backlog_enforcer._ctl_restart import RESTART_OPS, restart_available_at
from steam_backlog_enforcer._fast_install_progress import fast_install_status
@ -167,4 +168,5 @@ OPS: Final[dict[str, Callable[[CtlContext, dict[str, object]], dict[str, object]
"gaming_unblock": op_gaming_unblock,
**RESET_OPS,
**RESTART_OPS,
**RESEARCH_GAME_OPS,
}

View File

@ -0,0 +1,50 @@
"""Control-socket ops for the research game (:mod:`_research_game`).
Instant and not time-locked, by design (kuhy 2026-11-21): game-research calls
``research_game`` right after writing its approval file and
``research_game_revoke`` when the game leaves its list. Both are audited.
Neither needs a phrase: the op can only confirm what the approval file
already says, one game at a time.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Final
from steam_backlog_enforcer import _research_game
from steam_backlog_enforcer._ctl_context import hold_tick, int_arg
from steam_backlog_enforcer._ctl_protocol import INVALID_PARAMS, CtlError
if TYPE_CHECKING:
from collections.abc import Callable
from steam_backlog_enforcer._ctl_context import CtlContext
_MAX_APP_ID: Final = 2**31 - 1
def op_research_game(ctx: CtlContext, args: dict[str, object]) -> dict[str, object]:
"""Register the approval file's game as the research game."""
app_id = int_arg(args, "app_id", 1, _MAX_APP_ID)
with hold_tick(ctx):
try:
record = _research_game.register(app_id)
except _research_game.ResearchGameError as exc:
raise CtlError(INVALID_PARAMS, str(exc)) from exc
return record
def op_research_game_revoke(
ctx: CtlContext, _args: dict[str, object]
) -> dict[str, object]:
"""Drop the research game; the next pass treats it like any game."""
with hold_tick(ctx):
return {"app_id": _research_game.revoke()}
RESEARCH_GAME_OPS: Final[
dict[str, Callable[[CtlContext, dict[str, object]], dict[str, object]]]
] = {
"research_game": op_research_game,
"research_game_revoke": op_research_game_revoke,
}

View File

@ -10,6 +10,7 @@ import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._actions import allowed_games
from steam_backlog_enforcer._research_game import kept_ids
from steam_backlog_enforcer.enforcer import send_notification
from steam_backlog_enforcer.game_uninstall import (
get_installed_games,
@ -52,9 +53,11 @@ def guard_installed_games(allowed: set[int], *, strict: bool = False) -> int:
return 0
spared = is_infrastructure_app if strict else is_protected_app
installed = get_installed_games()
# The research game stays installed even in a strict research window.
keep = allowed | kept_ids()
count = 0
for app_id, name in installed:
if app_id in allowed:
if app_id in keep:
continue
if spared(app_id):
continue

View File

@ -0,0 +1,182 @@
"""The research game: one game game-research may install and record.
kuhy 2026-11-21: to research a blocked game he adds it in game-research (the
PlayStudy wrapper). Not the total-block research *window*
(:mod:`_research_window`); this one is a standing slot, separate from the
manual picks and from the time-locked exceptions. The rules:
* **Two halves must agree.** game-research writes ``APPROVAL_FILE`` in kuhy's
``~/.config/game-research/`` and asks the daemon, over the control socket
(``research_game`` op), to register it; the daemon keeps its own root
record (``RECORD_FILE``) and logs every add and revoke to ``AUDIT_LOG``. A
game is the research game only while both name the same app id, so a hand
edit of the file never takes effect unaudited, and deleting the file (the
game-research "remove") revokes it at once.
* **Kept the whole time it is on the list**: never uninstalled, its files
never deleted, never hidden, never purged with Steam's data folder
(:func:`kept_ids`).
* **Playable only while recorded**: the kill exemption holds only while a
session flag game-research lists in the approval file names a live
game-research wrapper (:func:`playable_ids`). Launched from plain Steam it
is killed like any blocked game.
* **Fail closed**: a missing, malformed or disagreeing file is "no research
game"; a flag that is unreadable, outside the home, stale or owned by any
other process is "not recording".
"""
from __future__ import annotations
import contextlib
from datetime import UTC, datetime
import json
import logging
from pathlib import Path
import time
from typing import Final
from steam_backlog_enforcer import config
logger = logging.getLogger(__name__)
HOME: Path = config.CONFIG_DIR.parent.parent
APPROVAL_FILE: Path = config.CONFIG_DIR.parent / "game-research" / "research_game.json"
RECORD_FILE: Path = Path("/var/lib/steam-backlog-enforcer/research_game.json")
AUDIT_LOG: Path = config.CONFIG_DIR / "exception_audit.log"
PROC: Path = Path("/proc")
# The launch flag spans "Steam asked to start the game" to "recording": the
# wrapper gives up on a window after 900 s (WINDOW_TIMEOUT_S), so an older
# flag is a leak, never a launch.
LAUNCH_FLAG_MAX_AGE_S: Final = 1200
_LAUNCH_FLAG_NAME: Final = "research_launch.pid"
_WRAPPER_NAMES: Final = ("game_research_desktop",)
_MAX_FLAGS: Final = 4
class ResearchGameError(ValueError):
"""The approval file does not allow the requested change."""
def _read_json(path: Path) -> object:
try:
return json.loads(path.read_text(encoding="utf-8"))
except OSError, ValueError:
return None
def _app_id_of(data: object) -> int | None:
if not isinstance(data, dict):
return None
app_id = data.get("app_id")
if isinstance(app_id, bool) or not isinstance(app_id, int) or app_id <= 0:
return None
return app_id
def approved_app_id() -> int | None:
"""The app id game-research's approval file names, or ``None``."""
return _app_id_of(_read_json(APPROVAL_FILE))
def research_game_id() -> int | None:
"""The research game: file and root record agree, else ``None``."""
approved = approved_app_id()
if approved is None or _app_id_of(_read_json(RECORD_FILE)) != approved:
return None
return approved
def kept_ids() -> frozenset[int]:
"""App ids that must stay installed, visible and on disk."""
app_id = research_game_id()
return frozenset() if app_id is None else frozenset({app_id})
def _is_wrapper(pid: int) -> bool:
try:
raw = (PROC / str(pid) / "cmdline").read_bytes()
except OSError:
return False
return any(
Path(arg).name.startswith(_WRAPPER_NAMES)
for arg in raw.decode(errors="replace").split("\0")[:3]
)
def _flag_live(raw: object) -> bool:
if not isinstance(raw, str):
return False
flag = Path(raw)
if not flag.is_absolute() or not flag.resolve().is_relative_to(HOME.resolve()):
return False
try:
stat = flag.stat()
pid = int(flag.read_text(encoding="utf-8").strip())
except OSError, ValueError:
return False
if flag.name == _LAUNCH_FLAG_NAME and time.time() - stat.st_mtime > (
LAUNCH_FLAG_MAX_AGE_S
):
return False
return pid > 0 and _is_wrapper(pid)
def session_live() -> bool:
"""Whether game-research is launching or recording right now."""
data = _read_json(APPROVAL_FILE)
flags = data.get("flags") if isinstance(data, dict) else None
if not isinstance(flags, list):
return False
return any(_flag_live(f) for f in flags[:_MAX_FLAGS])
def playable_ids() -> frozenset[int]:
"""App ids spared from the unauthorized-game kill: kept and recorded."""
kept = kept_ids()
return kept if kept and session_live() else frozenset()
def _audit(app_id: int, event: str) -> None:
stamp = datetime.now(UTC).isoformat()
with contextlib.suppress(OSError):
AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
with AUDIT_LOG.open("a", encoding="utf-8") as fh:
fh.write(f"{stamp} {event} app_id={app_id}\n")
def _write_record(payload: dict[str, object] | None) -> None:
RECORD_FILE.parent.mkdir(parents=True, exist_ok=True)
if payload is None:
RECORD_FILE.unlink(missing_ok=True)
return
tmp = RECORD_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(payload) + "\n", encoding="utf-8")
tmp.replace(RECORD_FILE)
def register(app_id: int) -> dict[str, object]:
"""Register *app_id* as the research game; instant, no delay.
Raises:
ResearchGameError: the approval file does not name *app_id*.
"""
approved = approved_app_id()
if approved != app_id:
msg = f"approval file names {approved}, not {app_id}"
raise ResearchGameError(msg)
record: dict[str, object] = {"app_id": app_id, "registered_at": time.time()}
_write_record(record)
_audit(app_id, "RESEARCH_GAME_ADDED")
logger.warning("Research game registered: AppID=%d", app_id)
return record
def revoke() -> int | None:
"""Drop the root record; return the app id it held (``None``: none)."""
app_id = _app_id_of(_read_json(RECORD_FILE))
if app_id is None:
return None
_write_record(None)
_audit(app_id, "RESEARCH_GAME_REVOKED")
logger.warning("Research game revoked: AppID=%d", app_id)
return app_id

View File

@ -17,6 +17,7 @@ from steam_backlog_enforcer._achievement_skip import zero_achievement_ids
from steam_backlog_enforcer._allowed_games import allowed_games
from steam_backlog_enforcer._assignment_progress import iso_to_epoch
from steam_backlog_enforcer._progress import current_progress
from steam_backlog_enforcer._research_game import kept_ids
from steam_backlog_enforcer._snapshot import load_snapshot
from steam_backlog_enforcer._steam_models import MAX_WORKERS
from steam_backlog_enforcer._whitelist_locking import get_approved_exception_ids
@ -58,6 +59,7 @@ def _legitimately_played(state: State) -> set[int]:
exempt.update(state.finished_app_ids)
exempt.update(get_approved_exception_ids())
exempt.update(zero_achievement_ids())
exempt.update(kept_ids())
exempt.update(
pick["app_id"] for pick in state.manual_picks if pick.get("app_id") is not None
)

View File

@ -25,6 +25,7 @@ from steam_backlog_enforcer._pacman import (
pacman_owner,
uninstall_package,
)
from steam_backlog_enforcer._research_game import kept_ids
from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
from steam_backlog_enforcer.enforcer import kill_processes_by_name
@ -220,7 +221,10 @@ def purge_steam_and_proton(*, keep_steam_dir: bool = False) -> None:
reappearance check: a stat() per fixed path and a ``pacman -Qi`` per
helper package are cheap even when there is nothing left to do.
"""
removed_paths = _remove_steam_remnants(keep_steam_dir=keep_steam_dir)
# The research game's install lives in the Steam folder: keep it while
# the game is on game-research's list, total block or not.
keep = keep_steam_dir or bool(kept_ids())
removed_paths = _remove_steam_remnants(keep_steam_dir=keep)
removed_packages = _uninstall_proton_helpers()
if removed_paths or removed_packages:
logger.info(

View File

@ -19,6 +19,7 @@ from steam_backlog_enforcer._desktop_env import (
desktop_user_cmd,
resolve_desktop_user,
)
from steam_backlog_enforcer._research_game import playable_ids
from steam_backlog_enforcer._store_tools import run_quiet
from steam_backlog_enforcer.game_uninstall import (
is_infrastructure_app,
@ -81,9 +82,11 @@ def enforce_allowed_game(
spared = is_infrastructure_app if strict else is_protected_app
running = get_running_steam_game_pids()
violations: list[tuple[int, int]] = []
# The research game only while game-research launches or records it.
allowed = allowed_app_ids | playable_ids() if running else allowed_app_ids
for pid, app_id in running.items():
if app_id in allowed_app_ids:
if app_id in allowed:
continue
# Skip Steam client itself (app_id 0 or very low IDs).
if app_id == 0:

View File

@ -17,6 +17,7 @@ from steam_backlog_enforcer._achievement_skip import zero_achievement_ids
from steam_backlog_enforcer._game_names import _is_protected_name
from steam_backlog_enforcer._progress import tracked
from steam_backlog_enforcer._protected_apps import PROTECTED_APP_IDS
from steam_backlog_enforcer._research_game import kept_ids
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH, _assert_not_real_steam
from steam_backlog_enforcer._whitelist_locking import get_approved_exception_ids
@ -130,6 +131,11 @@ def uninstall_game(app_id: int, game_name: str = "") -> bool:
Uses direct file removal instead of ``steam://uninstall`` URI to avoid
GUI popups and to work when Steam is not running.
"""
# Last line of defence for every caller: the research game's manifest
# and files are never removed while it is on game-research's list.
if app_id in kept_ids():
logger.warning("Refusing to uninstall research game AppID=%d", app_id)
return False
manifest = STEAMAPPS_PATH / f"appmanifest_{app_id}.acf"
install_dir = _read_install_dir(manifest)
success = _remove_manifest(manifest, game_name, app_id)
@ -149,8 +155,9 @@ def uninstall_other_games(allowed_app_ids: set[int]) -> int:
"""
to_remove: list[tuple[int, str]] = []
kept_protected: list[str] = []
keep = allowed_app_ids | kept_ids()
for app_id, name in get_installed_games():
if app_id in allowed_app_ids:
if app_id in keep:
logger.info("KEEPING allowed game: %s (AppID=%d)", name, app_id)
elif is_protected_app(app_id):
kept_protected.append(name)

View File

@ -27,6 +27,7 @@ from steam_backlog_enforcer._cdp import _cdp_result_value, _evaluate_js
from steam_backlog_enforcer._echo import _echo
from steam_backlog_enforcer._owned_apps_cache import get_all_owned_app_ids
from steam_backlog_enforcer._progress import current_progress
from steam_backlog_enforcer._research_game import kept_ids
from steam_backlog_enforcer._steam_errors import (
SteamUnavailableError,
)
@ -95,7 +96,10 @@ def hide_other_games(
ensure_steam_debug_port()
allowed_app_ids = (
allowed_app_ids | get_approved_exception_ids() | zero_achievement_ids()
allowed_app_ids
| get_approved_exception_ids()
| zero_achievement_ids()
| kept_ids()
)
allowed_json = json.dumps(sorted(allowed_app_ids))
extra_ids = sorted(aid for aid in owned_app_ids if aid not in allowed_app_ids)

View File

@ -1,10 +1,13 @@
"""Autouse isolation for the total-block research window.
"""Autouse isolation for the total-block research window and research game.
The record lives in ``/var/lib/steam-backlog-enforcer`` (root only) and the
install step checks pacman's real ``db.lck``. A test that reached either would
open or burn a window on the developer's machine, so both are redirected to
``tmp_path`` for every test, and the module-level memory (corrupt-record log
dedupe, install backoff, windows already released) starts empty each time.
The research game slot (game-research's approval file in ``~/.config``, the
root record, the audit log and the home its session flags must sit under) is
redirected the same way.
"""
from __future__ import annotations
@ -23,7 +26,9 @@ if TYPE_CHECKING:
@pytest.fixture(autouse=True)
def _isolate_research(tmp_path: Path) -> Iterator[None]:
"""Point the research record and pacman lock at tmp_path; reset memory."""
"""Point research records, files and pacman lock at tmp_path; reset memory."""
rg = "steam_backlog_enforcer._research_game"
home = tmp_path / "fake_home"
_research_window.LOGGED.clear()
_research_net.RETRY.clear()
_research_net.RELEASED.clear()
@ -36,5 +41,12 @@ def _isolate_research(tmp_path: Path) -> Iterator[None]:
"steam_backlog_enforcer._research_net.DB_LOCK_FILE",
tmp_path / "pacman" / "db.lck",
),
patch(
f"{rg}.APPROVAL_FILE",
home / ".config" / "game-research" / "research_game.json",
),
patch(f"{rg}.RECORD_FILE", tmp_path / "research" / "research_game.json"),
patch(f"{rg}.AUDIT_LOG", tmp_path / "research" / "audit.log"),
patch(f"{rg}.HOME", home),
):
yield

View File

@ -183,4 +183,6 @@ class TestOpsTable:
"gaming_reset_commit",
"gaming_reset_cancel",
"restart",
"research_game",
"research_game_revoke",
}

View File

@ -0,0 +1,66 @@
"""The ``research_game`` / ``research_game_revoke`` control-socket ops."""
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 _research_game as rg
from steam_backlog_enforcer._ctl_protocol import INVALID_PARAMS, CtlError
from steam_backlog_enforcer._total_block_purge import _remove_steam_remnants
from steam_backlog_enforcer.tests._ctl_fixtures import make_ctx
APP = 4197610
def _approve(app_id: int = APP) -> None:
rg.APPROVAL_FILE.parent.mkdir(parents=True, exist_ok=True)
rg.APPROVAL_FILE.write_text(json.dumps({"app_id": app_id}), encoding="utf-8")
def test_ops_are_allowlisted() -> None:
assert "research_game" in _ctl_ops.OPS
assert "research_game_revoke" in _ctl_ops.OPS
def test_add_takes_effect_at_once() -> None:
_approve()
data = _ctl_ops.OPS["research_game"](make_ctx(), {"app_id": APP})
assert data["app_id"] == APP
assert rg.research_game_id() == APP
def test_add_refuses_other_app_than_the_file() -> None:
_approve(APP + 1)
with pytest.raises(CtlError) as err:
_ctl_ops.OPS["research_game"](make_ctx(), {"app_id": APP})
assert err.value.code == INVALID_PARAMS
assert rg.research_game_id() is None
def test_add_needs_an_int_app_id() -> None:
with pytest.raises(CtlError):
_ctl_ops.OPS["research_game"](make_ctx(), {"app_id": "x"})
def test_revoke() -> None:
_approve()
_ctl_ops.OPS["research_game"](make_ctx(), {"app_id": APP})
assert _ctl_ops.OPS["research_game_revoke"](make_ctx(), {}) == {"app_id": APP}
assert rg.research_game_id() is None
def test_total_block_purge_keeps_the_steam_folder() -> None:
from steam_backlog_enforcer import _total_block_purge as purge
purge.STEAM_DATA_DIR.mkdir(parents=True, exist_ok=True)
_approve()
rg.register(APP)
with patch.object(purge, "_uninstall_proton_helpers", return_value=[]):
purge.purge_steam_and_proton()
assert purge.STEAM_DATA_DIR.is_dir()
rg.revoke()
assert str(purge.STEAM_DATA_DIR) in _remove_steam_remnants()

View File

@ -0,0 +1,147 @@
"""The research game slot: approval file, root record and live-session gate."""
from __future__ import annotations
import json
import os
import time
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _research_game as rg
if TYPE_CHECKING:
from pathlib import Path
APP = 4197610
def _approve(path: Path, app_id: int = APP, flags: list[str] | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps({"app_id": app_id, "added_at": 1.0, "flags": flags or []}),
encoding="utf-8",
)
def _wrapper_proc(proc: Path, pid: int, argv0: str = "game_research_desktop") -> None:
(proc / str(pid)).mkdir(parents=True)
(proc / str(pid) / "cmdline").write_bytes(f"/x/bin/{argv0}\0--serve\0".encode())
def test_no_file_means_no_research_game() -> None:
assert rg.research_game_id() is None
assert rg.kept_ids() == frozenset()
assert rg.playable_ids() == frozenset()
def test_file_alone_is_not_honoured() -> None:
_approve(rg.APPROVAL_FILE)
assert rg.research_game_id() is None
def test_file_and_record_agree() -> None:
_approve(rg.APPROVAL_FILE)
rg.register(APP)
assert rg.research_game_id() == APP
assert rg.kept_ids() == frozenset({APP})
def test_file_changed_to_other_app_revokes() -> None:
_approve(rg.APPROVAL_FILE)
rg.register(APP)
_approve(rg.APPROVAL_FILE, app_id=APP + 1)
assert rg.research_game_id() is None
@pytest.mark.parametrize(
"text",
["", "{", "[]", '{"app_id": "x"}', '{"app_id": true}', '{"app_id": -1}'],
)
def test_malformed_file_fails_closed(text: str) -> None:
rg.APPROVAL_FILE.parent.mkdir(parents=True, exist_ok=True)
rg.APPROVAL_FILE.write_text(text, encoding="utf-8")
rg.RECORD_FILE.parent.mkdir(parents=True, exist_ok=True)
rg.RECORD_FILE.write_text(json.dumps({"app_id": APP}), encoding="utf-8")
assert rg.research_game_id() is None
def test_register_refuses_mismatch_and_logs_add() -> None:
_approve(rg.APPROVAL_FILE)
with pytest.raises(rg.ResearchGameError):
rg.register(APP + 1)
rg.register(APP)
log = rg.AUDIT_LOG.read_text(encoding="utf-8")
assert f"RESEARCH_GAME_ADDED app_id={APP}" in log
assert log.count("\n") == 1
def test_register_refuses_without_file() -> None:
with pytest.raises(rg.ResearchGameError):
rg.register(APP)
assert not rg.RECORD_FILE.exists()
def test_revoke_clears_record_and_logs() -> None:
_approve(rg.APPROVAL_FILE)
rg.register(APP)
assert rg.revoke() == APP
assert rg.research_game_id() is None
assert "RESEARCH_GAME_REVOKED" in rg.AUDIT_LOG.read_text(encoding="utf-8")
assert rg.revoke() is None
def test_playable_only_while_wrapper_flag_live(tmp_path: Path) -> None:
proc = tmp_path / "proc"
flag = rg.APPROVAL_FILE.parent / "recording.pid"
_approve(rg.APPROVAL_FILE, flags=[str(flag)])
rg.register(APP)
with patch.object(rg, "PROC", proc):
assert rg.playable_ids() == frozenset()
flag.write_text("4242", encoding="utf-8")
assert rg.playable_ids() == frozenset() # pid not alive
_wrapper_proc(proc, 4242)
assert rg.playable_ids() == frozenset({APP})
flag.unlink()
assert rg.playable_ids() == frozenset()
def test_flag_owned_by_other_process_is_ignored(tmp_path: Path) -> None:
proc = tmp_path / "proc"
flag = rg.APPROVAL_FILE.parent / "recording.pid"
_approve(rg.APPROVAL_FILE, flags=[str(flag)])
rg.register(APP)
flag.write_text("77", encoding="utf-8")
_wrapper_proc(proc, 77, argv0="bash")
with patch.object(rg, "PROC", proc):
assert rg.playable_ids() == frozenset()
def test_flag_outside_home_is_ignored(tmp_path: Path) -> None:
proc = tmp_path / "proc"
_wrapper_proc(proc, 5)
outside = tmp_path / "elsewhere.pid"
outside.write_text("5", encoding="utf-8")
_approve(rg.APPROVAL_FILE, flags=[str(outside)])
rg.register(APP)
with (
patch.object(rg, "PROC", proc),
patch.object(rg, "HOME", rg.APPROVAL_FILE.parent / "home"),
):
assert rg.playable_ids() == frozenset()
def test_stale_launch_flag_is_ignored(tmp_path: Path) -> None:
proc = tmp_path / "proc"
_wrapper_proc(proc, 9)
flag = rg.APPROVAL_FILE.parent / "research_launch.pid"
_approve(rg.APPROVAL_FILE, flags=[str(flag)])
flag.write_text("9", encoding="utf-8")
rg.register(APP)
with patch.object(rg, "PROC", proc):
assert rg.playable_ids() == frozenset({APP})
old = time.time() - rg.LAUNCH_FLAG_MAX_AGE_S - 5
os.utime(flag, (old, old))
assert rg.playable_ids() == frozenset()

View File

@ -0,0 +1,156 @@
"""The research game is kept installed and visible; killed unless recorded."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _research_game as rg
from steam_backlog_enforcer._enforce_guards import guard_installed_games
from steam_backlog_enforcer._scanning_tampering import _legitimately_played
from steam_backlog_enforcer.config import State
from steam_backlog_enforcer.enforcer import enforce_allowed_game
from steam_backlog_enforcer.game_uninstall import uninstall_game, uninstall_other_games
from steam_backlog_enforcer.library_hider import hide_other_games
from steam_backlog_enforcer.tests._no_approved_exceptions import no_approved_exceptions
from steam_backlog_enforcer.tests._zero_ach import ASSIGNED, js_list, recorder
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
RESEARCH = 4197610
OTHER = 570
@pytest.fixture(autouse=True)
def _research_slot() -> Iterator[None]:
"""RESEARCH is approved and registered; no other exception protects."""
rg.APPROVAL_FILE.parent.mkdir(parents=True, exist_ok=True)
rg.APPROVAL_FILE.write_text(json.dumps({"app_id": RESEARCH}), encoding="utf-8")
rg.register(RESEARCH)
yield from no_approved_exceptions()
def _record_live(tmp_path: Path) -> Path:
"""Point the approval file at a live wrapper flag; return the fake /proc."""
proc = tmp_path / "proc"
(proc / "31").mkdir(parents=True)
(proc / "31" / "cmdline").write_bytes(b"game_research_desktop\0")
flag = rg.APPROVAL_FILE.parent / "recording.pid"
flag.write_text("31", encoding="utf-8")
rg.APPROVAL_FILE.write_text(
json.dumps({"app_id": RESEARCH, "flags": [str(flag)]}), encoding="utf-8"
)
return proc
def test_uninstall_sweep_keeps_it() -> None:
removed: list[int] = []
with (
patch(
"steam_backlog_enforcer.game_uninstall.get_installed_games",
return_value=[(RESEARCH, "Librarian"), (OTHER, "Other")],
),
patch(
"steam_backlog_enforcer.game_uninstall.uninstall_game",
side_effect=recorder(removed),
),
):
uninstall_other_games({ASSIGNED})
assert removed == [OTHER]
@pytest.mark.parametrize("strict", [False, True])
def test_install_guard_keeps_it(*, strict: bool) -> None:
removed: list[int] = []
pkg = "steam_backlog_enforcer._enforce_guards"
with (
patch(
f"{pkg}.get_installed_games",
return_value=[(RESEARCH, "Librarian"), (OTHER, "Other")],
),
patch(f"{pkg}.uninstall_game", side_effect=recorder(removed)),
patch(f"{pkg}.send_notification"),
):
assert guard_installed_games({ASSIGNED}, strict=strict) == 1
assert removed == [OTHER]
def test_uninstall_game_refuses_its_files() -> None:
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH
manifest = STEAMAPPS_PATH / f"appmanifest_{RESEARCH}.acf"
game_dir = STEAMAPPS_PATH / "common" / "Librarian"
game_dir.mkdir(parents=True)
manifest.write_text('"AppState"\n{\n\t"installdir"\t\t"Librarian"\n}\n')
assert uninstall_game(RESEARCH, "Librarian") is False
assert manifest.exists()
assert game_dir.is_dir()
def test_stays_visible_in_the_library() -> None:
pkg = "steam_backlog_enforcer.library_hider"
captured: dict[str, str] = {}
def fake_eval(js: str) -> dict[str, object]:
captured["js"] = js
return {}
with (
patch(f"{pkg}.ensure_steam_debug_port"),
patch(f"{pkg}._evaluate_js", side_effect=fake_eval),
patch(f"{pkg}._cdp_result_value", return_value='{"totalHidden": 0}'),
):
hide_other_games([RESEARCH, ASSIGNED, OTHER], {ASSIGNED})
assert RESEARCH in js_list(r"new Set\((\[.*?\])\)", captured["js"])
assert js_list(r"const extraIds = (\[.*?\]);", captured["js"]) == [OTHER]
def test_tampering_check_exempts_it() -> None:
assert RESEARCH in _legitimately_played(State(current_app_id=ASSIGNED))
def test_killed_when_not_recording() -> None:
with (
patch(
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: RESEARCH, 200: OTHER},
),
patch("steam_backlog_enforcer.enforcer.kill_process") as kill,
):
assert enforce_allowed_game({ASSIGNED}) == [(100, RESEARCH), (200, OTHER)]
assert kill.call_count == 2
def test_spared_while_recording(tmp_path: Path) -> None:
with (
patch.object(rg, "PROC", _record_live(tmp_path)),
patch(
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: RESEARCH, 200: OTHER},
),
patch("steam_backlog_enforcer.enforcer.kill_process") as kill,
):
assert enforce_allowed_game({ASSIGNED}) == [(200, OTHER)]
kill.assert_called_once_with(200, OTHER)
def test_revoked_game_is_treated_normally() -> None:
rg.APPROVAL_FILE.unlink()
removed: list[int] = []
with (
patch(
"steam_backlog_enforcer.game_uninstall.get_installed_games",
return_value=[(RESEARCH, "Librarian")],
),
patch(
"steam_backlog_enforcer.game_uninstall.uninstall_game",
side_effect=recorder(removed),
),
):
uninstall_other_games({ASSIGNED})
assert removed == [RESEARCH]