fix(game_install): refuse to delete folders matching an allowed game's name
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run

_remove_game_dirs deleted exactly one path at a time (the manifest's
current installdir, app-id gated by callers), but a real incident showed
that's not enough: an allowed game's install can end up split across
naming variants (spaced display name vs. installdir vs. a typo'd
variant), and any code path touching the wrong one risks destroying real
files. Add a fuzzy name-match safety net inside _remove_game_dirs itself
so it refuses to rmtree anything that plausibly names one of the
currently-allowed games, tolerating case/spacing/punctuation, spelled-out
numbers vs. digits vs. roman numerals, and minor typos -- independent of
whatever app-id gating the caller already does.

Extracted active_manual_picks/allowed_games/_pick_is_active out of
_actions.py into a new leaf module (_allowed_games.py) so game_install.py
can import allowed_games at the top level for this check without a
circular import (_actions.py already imports from game_install.py for
unrelated functions). _actions.py re-exports the two names other modules
still import from it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-07-25 15:50:29 +02:00
parent cdc453bdf4
commit e5d0627a30
7 changed files with 290 additions and 77 deletions

View File

@ -12,17 +12,27 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any
from steam_backlog_enforcer._allowed_games import (
active_manual_picks,
allowed_games,
)
from steam_backlog_enforcer._total_block import get_total_block_status
from steam_backlog_enforcer.game_install import get_installed_games, is_protected_app
# Marks these two as an intentional re-export (they're imported from
# _allowed_games above, not defined here) -- without this, mypy's
# --no-implicit-reexport flags every downstream `from _actions import
# active_manual_picks` as an error. Everything else in this file is
# accessible normally; this only needs to list names imported-then-reexported.
__all__ = [
"active_manual_picks",
"allowed_games",
]
from steam_backlog_enforcer.store_blocker import is_store_blocked
if TYPE_CHECKING:
from steam_backlog_enforcer.config import State
# Days before the manual-pick lock automatically expires. Single source of
# truth: both ``main.py`` and the MCP server import it from here.
MANUAL_LOCK_DAYS = 14
# Mistake-correction window: for this many days after a manual pick the user
# may still back out via ``abandon-pick``. Deliberately short — it exists to
# undo a wrong pick, not to serve as an escape hatch from the lock.
@ -33,50 +43,6 @@ MANUAL_GRACE_DAYS = 4
ABANDON_COOLDOWN_DAYS = 30
def _pick_is_active(state: State, pick: dict[str, Any]) -> bool:
"""Return ``True`` if *pick* still holds the lock.
A pick stops being active once its game is finished (100% achievements) or
once ``MANUAL_LOCK_DAYS`` have elapsed. A missing or malformed timestamp
keeps it active: with no deadline to evaluate, the safe answer for an
enforcement tool is "still locked".
Args:
state: The loaded enforcer state (for ``finished_app_ids``).
pick: One ``state.manual_picks`` entry.
Returns:
Whether this pick still counts toward the lock.
"""
app_id = pick.get("app_id")
if app_id is None or app_id in state.finished_app_ids:
return False
started_at = pick.get("started_at") or ""
if started_at:
try:
started = datetime.fromisoformat(started_at)
except ValueError:
return True
if datetime.now(timezone.utc) >= started + timedelta(days=MANUAL_LOCK_DAYS):
return False
return True
def active_manual_picks(state: State) -> list[dict[str, Any]]:
"""Return the manual picks that still hold the lock, oldest first.
Args:
state: The loaded enforcer state.
Returns:
The subset of ``state.manual_picks`` that is neither finished nor past
its own deadline.
"""
return [p for p in state.manual_picks if _pick_is_active(state, p)]
def find_manual_pick(state: State, app_id: int) -> dict[str, Any] | None:
"""Return the active manual pick for *app_id*, or ``None``.
@ -126,28 +92,6 @@ def allowed_app_ids(state: State) -> set[int]:
return {app_id for app_id, _ in allowed_games(state)}
def allowed_games(state: State) -> list[tuple[int, str]]:
"""Return ``(app_id, name)`` for every game the enforcer must keep.
Same membership as :func:`allowed_app_ids`, but carrying names so callers
can install and report on each one. The current assignment comes first.
Args:
state: The loaded enforcer state.
Returns:
Allowed games as ``(app_id, name)`` pairs, without duplicates.
"""
games: list[tuple[int, str]] = []
if state.current_app_id is not None:
games.append((state.current_app_id, state.current_game_name))
for pick in active_manual_picks(state):
app_id = pick.get("app_id")
if app_id is not None and all(app_id != aid for aid, _ in games):
games.append((app_id, pick.get("game_name", "")))
return games
def manual_pick_slots_left(state: State, max_picks: int) -> int:
"""Return how many further manual picks fit under *max_picks*.

View File

@ -0,0 +1,84 @@
"""Which games the enforcer currently must leave installed and visible.
Pure functions over ``State`` with no dependency on ``game_install.py``.
Kept as its own leaf module (rather than living in ``_actions.py``, which
already imports from ``game_install.py`` for unrelated functions) so that
``game_install.py`` can import ``allowed_games`` at the top level for its
deletion safety net without creating a circular import.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from steam_backlog_enforcer.config import State
# Days before the manual-pick lock automatically expires. Single source of
# truth: both ``main.py`` and the MCP server import it via ``_actions``.
MANUAL_LOCK_DAYS = 14
def _pick_is_active(state: State, pick: dict[str, Any]) -> bool:
"""Return ``True`` if *pick* still holds the lock.
A pick stops being active once its game is finished (100% achievements) or
once ``MANUAL_LOCK_DAYS`` have elapsed. A missing or malformed timestamp
keeps it active: with no deadline to evaluate, the safe answer for an
enforcement tool is "still locked".
Args:
state: The loaded enforcer state (for ``finished_app_ids``).
pick: One ``state.manual_picks`` entry.
Returns:
Whether this pick still counts toward the lock.
"""
app_id = pick.get("app_id")
if app_id is None or app_id in state.finished_app_ids:
return False
started_at = pick.get("started_at") or ""
if started_at:
try:
started = datetime.fromisoformat(started_at)
except ValueError:
return True
if datetime.now(timezone.utc) >= started + timedelta(days=MANUAL_LOCK_DAYS):
return False
return True
def active_manual_picks(state: State) -> list[dict[str, Any]]:
"""Return the manual picks that still hold the lock, oldest first.
Args:
state: The loaded enforcer state.
Returns:
The subset of ``state.manual_picks`` that is neither finished nor past
its own deadline.
"""
return [p for p in state.manual_picks if _pick_is_active(state, p)]
def allowed_games(state: State) -> list[tuple[int, str]]:
"""Return ``(app_id, name)`` for every game the enforcer must keep.
Args:
state: The loaded enforcer state.
Returns:
Allowed games as ``(app_id, name)`` pairs, without duplicates. The
current assignment comes first.
"""
games: list[tuple[int, str]] = []
if state.current_app_id is not None:
games.append((state.current_app_id, state.current_game_name))
for pick in active_manual_picks(state):
app_id = pick.get("app_id")
if app_id is not None and all(app_id != aid for aid, _ in games):
games.append((app_id, pick.get("game_name", "")))
return games

View File

@ -34,7 +34,6 @@ from mcp.server.fastmcp import FastMCP
from steam_backlog_enforcer._actions import (
ABANDON_COOLDOWN_DAYS,
MANUAL_GRACE_DAYS,
MANUAL_LOCK_DAYS,
abandon_manual_pick,
active_manual_picks,
apply_manual_pick,
@ -43,6 +42,7 @@ from steam_backlog_enforcer._actions import (
manual_pick_grace_remaining,
status_payload,
)
from steam_backlog_enforcer._allowed_games import MANUAL_LOCK_DAYS
from steam_backlog_enforcer._total_block import start_total_block
from steam_backlog_enforcer._web_dataset import build_web_dataset, dataset_to_payload
from steam_backlog_enforcer.config import Config, State, load_snapshot

View File

@ -3,6 +3,7 @@
from __future__ import annotations
import contextlib
import difflib
import logging
import os
from pathlib import Path
@ -13,12 +14,99 @@ import subprocess
import sys
import time
from steam_backlog_enforcer._allowed_games import allowed_games
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH
from steam_backlog_enforcer._whitelist import get_approved_exception_ids
from steam_backlog_enforcer.config import State
from steam_backlog_enforcer.library_hider import steam_is_installed
logger = logging.getLogger(__name__)
# Folder-name safety net for _remove_game_dirs. Independent of the app-id
# gating callers already do (uninstall_other_games skips allowed app ids) --
# this protects against deleting the *wrong* directory for an allowed game
# when its name has been written inconsistently (e.g. "KingdomComeDeliverance2"
# vs "Kingdom Come: Deliverance II" vs a typo'd variant), which is exactly the
# kind of multi-name confusion that caused real data loss once already.
_NAME_FUZZY_MATCH_THRESHOLD = 0.82
_NUMBER_WORDS = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"ten": "10",
}
_ROMAN_NUMERALS = {
"i": "1",
"ii": "2",
"iii": "3",
"iv": "4",
"v": "5",
"vi": "6",
"vii": "7",
"viii": "8",
"ix": "9",
"x": "10",
}
def _normalize_game_name(name: str) -> str:
"""Canonicalize a game/folder name for fuzzy comparison.
Splits into alphanumeric words, maps spelled-out numbers ("two") and
roman numerals ("II") to digits, then joins with no separators. Makes
"Kingdom Come: Deliverance II", "KingdomComeDeliverance2", and "kingdom
come deliverance two" all normalize to the same string.
"""
words = re.findall(r"[A-Za-z0-9]+", name.lower())
mapped = [_NUMBER_WORDS.get(w) or _ROMAN_NUMERALS.get(w) or w for w in words]
return "".join(mapped)
def _protected_name_stems() -> list[str]:
"""Every name of every currently-allowed game, for the deletion safety net.
Returns [] (protects nothing extra beyond exact matches already checked
by callers) if state can't be loaded -- this is a best-effort safety net,
not a hard dependency.
"""
try:
return [name for _, name in allowed_games(State.load()) if name]
except Exception:
logger.exception("Could not load allowed games for the deletion safety net")
return []
def _is_protected_name(candidate: str) -> bool:
"""True if *candidate* plausibly names one of the currently-allowed games.
Errs toward over-matching on purpose: a false positive here just skips a
deletion that can be done manually; a false negative deletes real files.
"""
normalized_candidate = _normalize_game_name(candidate)
if not normalized_candidate:
return False
for protected in _protected_name_stems():
normalized_protected = _normalize_game_name(protected)
if not normalized_protected:
continue
if normalized_candidate == normalized_protected:
return True
ratio = difflib.SequenceMatcher(
None, normalized_candidate, normalized_protected
).ratio()
if ratio >= _NAME_FUZZY_MATCH_THRESHOLD:
return True
return False
# Real Steam directory — used as a safety check to block destructive
# operations that leak through during testing.
_REAL_STEAMAPPS = Path("~/.local/share/Steam/steamapps").expanduser()
@ -379,6 +467,11 @@ def _remove_game_dirs(install_dir: Path | None, app_id: int) -> bool:
success = True
if install_dir and install_dir.is_dir():
_assert_not_real_steam(install_dir)
if _is_protected_name(install_dir.name):
logger.warning(
"Refusing to remove %s: name matches an allowed game", install_dir
)
return False
try:
shutil.rmtree(install_dir)
logger.info("Removed game files: %s", install_dir)

View File

@ -14,9 +14,6 @@ from steam_backlog_enforcer._actions import (
from steam_backlog_enforcer._actions import (
MANUAL_GRACE_DAYS as _MANUAL_GRACE_DAYS,
)
from steam_backlog_enforcer._actions import (
MANUAL_LOCK_DAYS as _MANUAL_LOCK_DAYS,
)
from steam_backlog_enforcer._actions import (
abandon_manual_pick,
active_manual_picks,
@ -31,6 +28,9 @@ from steam_backlog_enforcer._actions import (
from steam_backlog_enforcer._actions import (
is_manual_pick_locked as _is_manual_pick_locked,
)
from steam_backlog_enforcer._allowed_games import (
MANUAL_LOCK_DAYS as _MANUAL_LOCK_DAYS,
)
from steam_backlog_enforcer._cmd_done import cmd_done
from steam_backlog_enforcer._enforce_loop import (
do_enforce,

View File

@ -7,7 +7,7 @@ from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _actions
from steam_backlog_enforcer import _actions, _allowed_games
from steam_backlog_enforcer._actions import (
abandon_manual_pick,
active_manual_picks,
@ -59,7 +59,7 @@ class TestIsManualPickLocked:
{
"app_id": 5,
"game_name": "G",
"started_at": _iso_days_ago(_actions.MANUAL_LOCK_DAYS + 1),
"started_at": _iso_days_ago(_allowed_games.MANUAL_LOCK_DAYS + 1),
}
]
)
@ -255,7 +255,7 @@ class TestActiveManualPicksAndAllowedSet:
def test_expired_pick_drops_out(self) -> None:
state = State(
manual_picks=[_pick(days_ago=_actions.MANUAL_LOCK_DAYS + 1)],
manual_picks=[_pick(days_ago=_allowed_games.MANUAL_LOCK_DAYS + 1)],
)
assert active_manual_picks(state) == []

View File

@ -6,6 +6,9 @@ from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from steam_backlog_enforcer.game_install import (
_is_protected_name,
_normalize_game_name,
_protected_name_stems,
_remove_game_dirs,
uninstall_game,
uninstall_other_games,
@ -161,3 +164,92 @@ class TestUninstallOtherGames:
count = uninstall_other_games({440})
assert count == 0
mock_uninstall.assert_not_called()
class TestNormalizeGameName:
"""Tests for _normalize_game_name."""
def test_lowercases_and_strips_punctuation(self) -> None:
assert (
_normalize_game_name("Kingdom Come: Deliverance II")
== "kingdomcomedeliverance2"
)
def test_matches_no_space_variant(self) -> None:
assert _normalize_game_name("KingdomComeDeliverance2") == _normalize_game_name(
"Kingdom Come: Deliverance II"
)
def test_spelled_out_number_matches_digit(self) -> None:
assert _normalize_game_name("Portal Two") == _normalize_game_name("Portal 2")
class TestProtectedNameStems:
"""Tests for _protected_name_stems."""
def test_returns_allowed_game_names(self) -> None:
with (
patch("steam_backlog_enforcer.config.State.load", return_value=MagicMock()),
patch(
f"{PKG}.allowed_games",
return_value=[(1771300, "Kingdom Come: Deliverance II"), (440, "")],
),
):
stems = _protected_name_stems()
assert stems == ["Kingdom Come: Deliverance II"]
def test_returns_empty_list_when_state_cannot_load(self) -> None:
with patch(
"steam_backlog_enforcer.config.State.load", side_effect=RuntimeError("boom")
):
stems = _protected_name_stems()
assert stems == []
class TestIsProtectedName:
"""Tests for _is_protected_name."""
def test_blank_candidate_is_not_protected(self) -> None:
assert _is_protected_name(" ") is False
def test_matches_exact_normalized_name(self) -> None:
with patch(
f"{PKG}._protected_name_stems",
return_value=["Kingdom Come: Deliverance II"],
):
assert _is_protected_name("KingdomComeDeliverance2") is True
def test_matches_typo_via_fuzzy_ratio(self) -> None:
with patch(
f"{PKG}._protected_name_stems",
return_value=["Kingdom Come: Deliverance II"],
):
assert _is_protected_name("Kingdom Come Delievarnce 2") is True
def test_no_match_for_unrelated_name(self) -> None:
with patch(
f"{PKG}._protected_name_stems",
return_value=["Kingdom Come: Deliverance II"],
):
assert _is_protected_name("Cogmind") is False
def test_skips_blank_protected_name(self) -> None:
with patch(f"{PKG}._protected_name_stems", return_value=["", "Cogmind"]):
assert _is_protected_name("Cogmind") is True
class TestRemoveGameDirsProtectedName:
"""Tests for the _is_protected_name safety net inside _remove_game_dirs."""
def test_refuses_to_remove_protected_name(self, tmp_path: Path) -> None:
install_dir = tmp_path / "common" / "Kingdom Come: Deliverance II"
install_dir.mkdir(parents=True)
(install_dir / "game.exe").touch()
with (
patch(f"{PKG}.STEAMAPPS_PATH", tmp_path),
patch(f"{PKG}._is_protected_name", return_value=True),
):
result = _remove_game_dirs(install_dir, 1771300)
assert result is False
assert install_dir.exists()
assert (install_dir / "game.exe").exists()