steam-backlog-enforcer/steam_backlog_enforcer/tests/test_enforcer.py
Krzysztof kuhy Rudnicki 21fe2f7742 Stop the enforcer launching Steam and notifications as root
The enforce service runs as root (no User=) but sets DISPLAY=:0, so any GUI
it starts lands on the desktop session. Two resolvers disagreed about who to
drop privileges to:

  library_hider._resolve_desktop_user()  read STEAM_ENFORCER_DESKTOP_USER
  game_install._get_real_user()          read only SUDO_USER or USER

systemd sets neither of the latter, so _get_real_user() returned None under
the service and every `geteuid() == 0 and real_user and ...` guard fell
through to running as root. Steam answered with a zenity modal ("Cannot run
as root user", /usr/lib/steam/steam:261) on screen.

Confirmed from the live process tree: root `bash /usr/lib/steam/steam
-cef-disable-gpu ... steam://install/618510` with a root zenity child. It
never reached the journal, because that text goes to zenity and _run_as_user
sends child output to DEVNULL.

- _desktop_env: add resolve_desktop_user/desktop_uid/desktop_user_cmd. Only
  the argv builder is shared, never the spawn call: tests/_no_subprocess.py
  patches subprocess per module by name, so a spawn site in an unpatched
  module could fire a real `sudo -u kuhy steam`.
- game_install._get_real_user: delegate to the shared resolver. This alone
  also fixes the root `steam -silent` in _ensure_steam_running and the
  no-op os.chown on new appmanifests.
- _trigger_steam_install / enforcer.send_notification: drop privileges.
  send_notification had no DBUS_SESSION_BUS_ADDRESS, so it silently reached
  nobody for all six of its callers.
- _run_as_user: fail closed. Running unchanged as root when no desktop user
  resolves is what put the modal on screen; refuse and log instead.

Also stop the retry storm behind it. steamapps does not exist (Steam has
never completed sign-in), so is_game_installed() was always False and the
loop re-triggered every allowed game every pass: 1656 attempts in 30
minutes, service RSS 1.5 GB (peak 4.3 GB), a FileNotFoundError traceback
each time. Guard install_game and _reinstall_missing_allowed on
steam_library_ready() -- a missing library means no install can succeed by
any route, so this is a correctness check rather than a tuned retry limit.

The module splits here are forced by the pre-commit 250-line gate, which
blocks any commit touching an over-cap file: game_install, library_hider and
_enforce_loop were already over before this change. They are split by
responsibility (_cdp transport, _steam_launch lifecycle, _steam_process
spawning, _steam_errors, _steam_client, _game_names, game_uninstall,
_enforce_steps, _owned_apps_cache, _echo, _protected_apps). game_install and
library_hider re-export their old public names, so the 15 modules that
import from them are untouched by this commit.

Verified as real root under the unit's environment: argv is now
`sudo -u kuhy env DISPLAY=:0 ... xdg-open steam://install/...` for both the
installer and notify-send; three enforce passes spawn no process and log
once; _run_as_user refuses with no desktop user. After restart: 0 retries,
0 tracebacks, 0 root-owned files under ~/.local/share/Steam, RSS 342 MB.

1311 tests pass. _desktop_env and _steam_state at 100% branch coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 13:55:44 +02:00

239 lines
7.9 KiB
Python

"""Tests for enforcer module."""
from __future__ import annotations
import subprocess
from typing import TYPE_CHECKING
from unittest.mock import patch
from steam_backlog_enforcer.enforcer import (
enforce_allowed_game,
get_running_steam_game_pids,
kill_process,
send_notification,
)
if TYPE_CHECKING:
from pathlib import Path
class TestGetRunningPids:
"""Tests for get_running_steam_game_pids."""
def test_finds_steam_pid(self, tmp_path: Path) -> None:
proc_dir = tmp_path / "proc"
pid_dir = proc_dir / "12345"
pid_dir.mkdir(parents=True)
environ = b"HOME=/home/user\x00SteamAppId=440\x00PATH=/usr/bin"
(pid_dir / "environ").write_bytes(environ)
with patch(
"steam_backlog_enforcer.enforcer.Path",
return_value=proc_dir,
):
result = get_running_steam_game_pids()
assert result == {12345: 440}
def test_skips_non_digit_entries(self, tmp_path: Path) -> None:
proc_dir = tmp_path / "proc"
proc_dir.mkdir(parents=True)
(proc_dir / "self").mkdir()
(proc_dir / "cpuinfo").touch()
with patch(
"steam_backlog_enforcer.enforcer.Path",
return_value=proc_dir,
):
result = get_running_steam_game_pids()
assert result == {}
def test_handles_permission_error(self, tmp_path: Path) -> None:
proc_dir = tmp_path / "proc"
pid_dir = proc_dir / "99"
pid_dir.mkdir(parents=True)
# No environ file -> OSError when reading
with patch(
"steam_backlog_enforcer.enforcer.Path",
return_value=proc_dir,
):
result = get_running_steam_game_pids()
assert result == {}
def test_skips_non_digit_steam_app_id(self, tmp_path: Path) -> None:
proc_dir = tmp_path / "proc"
pid_dir = proc_dir / "100"
pid_dir.mkdir(parents=True)
environ = b"SteamAppId=notanumber\x00"
(pid_dir / "environ").write_bytes(environ)
with patch(
"steam_backlog_enforcer.enforcer.Path",
return_value=proc_dir,
):
result = get_running_steam_game_pids()
assert result == {}
def test_no_steam_env(self, tmp_path: Path) -> None:
proc_dir = tmp_path / "proc"
pid_dir = proc_dir / "200"
pid_dir.mkdir(parents=True)
environ = b"HOME=/home/user\x00PATH=/usr/bin\x00"
(pid_dir / "environ").write_bytes(environ)
with patch(
"steam_backlog_enforcer.enforcer.Path",
return_value=proc_dir,
):
result = get_running_steam_game_pids()
assert result == {}
class TestEnforceAllowedGame:
"""Tests for enforce_allowed_game."""
def test_no_violations(self) -> None:
with patch(
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: 440},
):
result = enforce_allowed_game({440})
assert result == []
def test_kills_unauthorized(self) -> None:
with (
patch(
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: 570, 200: 440},
),
patch("steam_backlog_enforcer.enforcer.kill_process") as mock_kill,
):
result = enforce_allowed_game({440}, kill_unauthorized=True)
assert result == [(100, 570)]
mock_kill.assert_called_once_with(100, 570)
def test_skips_app_id_zero(self) -> None:
with patch(
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: 0},
):
result = enforce_allowed_game({440})
assert result == []
def test_detects_without_killing(self) -> None:
with patch(
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: 570},
):
result = enforce_allowed_game({440}, kill_unauthorized=False)
assert result == [(100, 570)]
def test_allowed_none(self) -> None:
result = enforce_allowed_game(set(), kill_unauthorized=True)
assert result == []
def test_skips_protected_app_id(self) -> None:
"""Protected IDs must never be killed even if not the assigned game."""
with (
patch(
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: 1331550, 200: 440},
),
patch(
"steam_backlog_enforcer.enforcer.is_protected_app",
side_effect=lambda aid: aid == 1331550,
),
patch("steam_backlog_enforcer.enforcer.kill_process") as mock_kill,
):
result = enforce_allowed_game({440}, kill_unauthorized=True)
assert result == []
mock_kill.assert_not_called()
class TestKillProcess:
"""Tests for kill_process."""
def test_kill_success(self) -> None:
with patch("steam_backlog_enforcer.enforcer.os.kill") as mock_kill:
kill_process(123, 440)
mock_kill.assert_called_once()
def test_process_already_gone(self) -> None:
with patch(
"steam_backlog_enforcer.enforcer.os.kill",
side_effect=ProcessLookupError,
):
kill_process(123, 440) # Should not raise
def test_permission_error(self) -> None:
with patch(
"steam_backlog_enforcer.enforcer.os.kill",
side_effect=PermissionError,
):
kill_process(123, 440) # Should not raise
class TestSendNotification:
"""Tests for send_notification."""
def test_sends(self) -> None:
with patch("steam_backlog_enforcer.enforcer.subprocess.run") as mock_run:
send_notification("Title", "Body")
mock_run.assert_called_once()
def test_handles_missing_notify_send(self) -> None:
with patch(
"steam_backlog_enforcer.enforcer.subprocess.run",
side_effect=FileNotFoundError,
):
send_notification("Title", "Body") # Should not raise
def test_handles_os_error(self) -> None:
with patch(
"steam_backlog_enforcer.enforcer.subprocess.run",
side_effect=OSError,
):
send_notification("Title", "Body") # Should not raise
class TestSendNotificationPrivilegeDrop:
"""As root, notifications must be delivered into the user's session bus.
A bare root ``notify-send`` has no DBUS_SESSION_BUS_ADDRESS and silently
reached nobody, for every caller of send_notification.
"""
_PKG = "steam_backlog_enforcer.enforcer"
_ENV = "steam_backlog_enforcer._desktop_env"
def test_root_drops_to_desktop_user(self) -> None:
with (
patch(f"{self._ENV}.os.geteuid", return_value=0),
patch(f"{self._ENV}.desktop_uid", return_value=1000),
patch(f"{self._PKG}.resolve_desktop_user", return_value="kuhy"),
patch(f"{self._PKG}.subprocess.run") as mock_run,
):
send_notification("Title", "Body")
argv = mock_run.call_args[0][0]
assert argv[:4] == ["sudo", "-u", "kuhy", "env"]
assert "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus" in argv
def test_non_root_does_not_wrap(self) -> None:
with (
patch(f"{self._ENV}.os.geteuid", return_value=1000),
patch(f"{self._PKG}.resolve_desktop_user", return_value="kuhy"),
patch(f"{self._PKG}.subprocess.run") as mock_run,
):
send_notification("Title", "Body")
assert mock_run.call_args[0][0][0] != "sudo"
def test_handles_timeout(self) -> None:
"""sudo can block where a bare notify-send would not."""
with patch(
f"{self._PKG}.subprocess.run",
side_effect=subprocess.TimeoutExpired("cmd", 5),
):
send_notification("Title", "Body") # Should not raise