ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
test(utils): refuse bare-name sbin execs at runtime, not just in AST
Juan Denisd5dd6a5dd208
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex 5b55441b..a0626a7b 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -9,6 +9,12 @@ _backend = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))if _backend not in sys.path:sys.path.insert(0, _backend)+# And this directory, so sibling helper modules (popen_guard) import cleanly+# regardless of pytest's import mode.+_tests = os.path.dirname(os.path.abspath(__file__))+if _tests not in sys.path:+ sys.path.insert(0, _tests)+os.environ.setdefault('FLASK_ENV', 'testing')# Keep the suite offline: unset SERVERKIT_REGISTRY_URL now means "use the@@ -105,6 +111,30 @@ def pytest_configure(config):)[email protected](autouse=True)+def _popen_sbin_guard(monkeypatch):+ """Route every subprocess exec through the runtime sbin guard (plan 75 §B2).++ The static guard in test_sbin_command_guard.py reads literal argv lists —+ at most 57% of raw subprocess sites. This fixture sees the actual argv of+ every exec the suite performs (variables, f-strings, concatenation — the+ 43% AST cannot), and fails any bare-name call that only resolves through+ an sbin dir: the plan 74 outage class, where a call works in dev and dies+ under the panel unit's sbin-less PATH.++ Tests that patch subprocess.run/Popen themselves replace this wrapper for+ their duration — the guard only judges execs that really happen. POSIX+ only; sbin semantics do not exist on a Windows dev box.+ """+ if os.name != 'posix':+ yield+ return+ import subprocess+ from popen_guard import GuardedPopen+ monkeypatch.setattr(subprocess, 'Popen', GuardedPopen)+ yield++@pytest.fixture(scope='session')def _flask_app():"""The Flask application and the schema, built ONCE for the test process.diff --git a/backend/tests/popen_guard.py b/backend/tests/popen_guard.pynew file mode 100644index 00000000..08bbc937--- /dev/null+++ b/backend/tests/popen_guard.py@@ -0,0 +1,98 @@+"""Runtime layer of the sbin guard (plan 75 §B2).++The static scan in ``test_sbin_command_guard.py`` only sees literal argv lists —+164 of the 288 raw ``subprocess.*`` sites in ``backend/app``. The other 43%+(variables, f-strings, concatenation) are opaque to AST, and they are where a+bare-name exec of an sbin-resident binary can still hide.++This module closes that gap at runtime, during tests. ``GuardedPopen`` wraps+``subprocess.Popen`` — the one primitive ``run``/``call``/``check_output``/+``check_call`` all funnel through — and inspects the *actual* argv at call+time. A bare-name head that resolves under the current ``$PATH`` but NOT under+a ``$PATH`` with the sbin dirs removed fails loudly:++ works in dev (PATH has sbin), dies under the panel's systemd unit+ (PATH has none) — plan 74's outage class, caught before it ships.++Its coverage is exactly "whatever the suite exercises" — honest, measurable,+and improving for free as tests are added. A call the suite never makes is a+call no test can vouch for either way; this guard makes no claim about it.++Deliberate non-failures:++* a head that resolves under NEITHER PATH is simply absent on this machine.+ The real ``Popen`` will raise ``FileNotFoundError`` — the honest result, and+ one probe-honesty suites exercise deliberately. The guard does not turn a+ missing-on-this-box binary into a guard violation.+* string-form argv (``shell=True``) and heads containing a path separator are+ not PATH searches and are left alone.+"""++import os+import shutil+import subprocess+import traceback+++class SbinPathError(BaseException):+ """A bare-name exec that only resolves through an sbin dir.++ ``BaseException`` on purpose: the bug class this catches ships BECAUSE a+ blanket ``except Exception`` converts ``FileNotFoundError`` into a false+ fact ("No Firewall Installed"). A plain ``AssertionError`` raised here+ would be swallowed by exactly the handlers it exists to catch.+ """+++def sanitized_path(env=None):+ """The current ``$PATH`` with every sbin dir removed — the shape of the+ panel unit's ``Environment="PATH=..."`` that caused the plan 74 outage."""+ env = os.environ if env is None else env+ parts = env.get('PATH', '').split(os.pathsep)+ kept = [p for p in parts+ if p and os.path.basename(p.rstrip('/\\')) not in ('sbin',)]+ return os.pathsep.join(kept)+++def offending_head(argv, env=None):+ """argv[0] if this argv is a bare-name exec that only resolves through an+ sbin dir, else ``None``. Pure and env-injectable so it can be tested+ without spawning anything."""+ if os.name != 'posix' or isinstance(argv, (str, bytes)) or not argv:+ return None+ head = argv[0]+ if not isinstance(head, str) or os.path.sep in head:+ return None # absolute, or explicitly relative — not a PATH search+ if shutil.which(head, path=sanitized_path(env)):+ return None # resolves without sbin: equally safe under the unit+ if not shutil.which(head):+ return None # absent on this machine — FileNotFoundError is honest+ return head+++def _callsite():+ """First stack frame outside this module and subprocess internals."""+ for frame in reversed(traceback.extract_stack()):+ base = os.path.basename(frame.filename)+ if base != 'popen_guard.py' and base != 'subprocess.py':+ return f'{frame.filename}:{frame.lineno}'+ return '<unknown>'+++class GuardedPopen(subprocess.Popen):+ """``subprocess.Popen`` that refuses bare-name sbin-only execs (test-time)."""++ def __init__(self, args, *a, **kw):+ head = offending_head(args)+ if head is not None:+ raise SbinPathError(+ f'{head!r} is exec\'d by bare name but only resolves through '+ f'an sbin dir. The panel\'s systemd unit ships a PATH with no '+ f'sbin, so this call raises FileNotFoundError in production '+ f'while passing every dev run — plan 74\'s outage class.\n'+ f' called from: {_callsite()}\n'+ f'Use run_privileged() (or run_unprivileged() when no root is '+ f'needed); both resolve argv[0] to an absolute path when '+ f'$PATH cannot.'+ )+ super().__init__(args, *a, **kw)diff --git a/backend/tests/test_popen_guard.py b/backend/tests/test_popen_guard.pynew file mode 100644index 00000000..589bc557--- /dev/null+++ b/backend/tests/test_popen_guard.py@@ -0,0 +1,142 @@+"""The runtime sbin guard must actually fire (plan 75 §B2).++`popen_guard.GuardedPopen` is installed autouse by conftest; these tests are+its mutation check — the fixture existing is not the same as the trap working.+They prove: the wrapper is live during tests, a bare-name sbin-only exec is+refused loudly (loudly = ``BaseException``, so a blanket ``except Exception``+— the exact handler this bug class hides behind — cannot swallow it), and+everything that is NOT the bug class passes through untouched.+"""++import os+import subprocess+from unittest.mock import patch++import pytest++import popen_guard+from popen_guard import GuardedPopen, SbinPathError, offending_head++pytestmark = pytest.mark.skipif(os.name != 'posix',+ reason='sbin semantics are POSIX-only')++#: A PATH shaped like the panel unit's: no sbin anywhere.+NO_SBIN_ENV = {'PATH': '/usr/local/bin:/usr/bin:/bin'}+++def _which_only_in_sbin(head, path=None):+ """``shutil.which`` where *head* exists, but only under an sbin dir."""+ if path is not None and 'sbin' not in path:+ return None # sanitized PATH: not found+ return f'/usr/sbin/{head}'+++# --------------------------------------------------------------------------- #+# The fixture is live+# --------------------------------------------------------------------------- #++def test_the_guard_is_installed_for_the_whole_suite():+ """Autouse is the point — a guard a test must remember to request is a+ guard that protects nothing."""+ assert subprocess.Popen is GuardedPopen+++# --------------------------------------------------------------------------- #+# offending_head: precisely the bug class, nothing else+# --------------------------------------------------------------------------- #++def test_bare_name_resolving_only_through_sbin_offends():+ with patch('popen_guard.shutil.which', side_effect=_which_only_in_sbin):+ assert offending_head(['ufw', 'status'], env=NO_SBIN_ENV) == 'ufw'+++def test_bare_name_resolving_without_sbin_is_fine():+ with patch('popen_guard.shutil.which', return_value='/usr/bin/git'):+ assert offending_head(['git', 'status'], env=NO_SBIN_ENV) is None+++def test_a_binary_absent_on_this_machine_is_not_a_guard_violation():+ """Missing here means FileNotFoundError here — the honest failure suites+ already exercise. The guard judges PATH shape, not machine contents."""+ with patch('popen_guard.shutil.which', return_value=None):+ assert offending_head(['definitely-not-installed', '-t'],+ env=NO_SBIN_ENV) is None+++def test_absolute_paths_are_not_path_searches():+ with patch('popen_guard.shutil.which', side_effect=AssertionError(+ 'which() must not even be consulted for an absolute path')):+ assert offending_head(['/usr/sbin/ufw', 'status']) is None+++def test_explicit_relative_paths_are_not_path_searches():+ assert offending_head(['./sbin/ufw', 'status']) is None+++def test_string_form_argv_is_left_alone():+ """shell=True is a deliberate, separate decision (one site, a user hook)."""+ assert offending_head('ufw status') is None+++def test_empty_argv_is_left_alone():+ assert offending_head([]) is None+++def test_sanitized_path_drops_every_sbin_dir():+ env = {'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'}+ assert popen_guard.sanitized_path(env) == '/usr/local/bin:/usr/bin:/bin'+++# --------------------------------------------------------------------------- #+# The trap fires through the real subprocess entry points+# --------------------------------------------------------------------------- #++def test_guarded_popen_refuses_a_bare_sbin_only_exec():+ with patch('popen_guard.shutil.which', side_effect=_which_only_in_sbin):+ with pytest.raises(SbinPathError) as excinfo:+ GuardedPopen(['ufw', 'status'])+ message = str(excinfo.value)+ assert 'ufw' in message+ assert 'run_privileged' in message+ assert __file__ in message # the callsite is named+++def test_subprocess_run_funnels_through_the_guard():+ """run/call/check_output/check_call all land on Popen — patch the module+ attribute once and every entry point is covered."""+ with patch('popen_guard.shutil.which', side_effect=_which_only_in_sbin):+ with pytest.raises(SbinPathError):+ subprocess.run(['nginx', '-t'])+ with pytest.raises(SbinPathError):+ subprocess.check_output(['iptables', '-L'])+++def test_the_refusal_survives_a_blanket_except():+ """The failure mode this guard exists for: `except Exception` turning an+ exec failure into a false fact. SbinPathError is a BaseException so the+ trap cannot be eaten by the handlers it hunts."""+ caught = None+ with patch('popen_guard.shutil.which', side_effect=_which_only_in_sbin):+ try:+ subprocess.run(['ufw', 'status'])+ except Exception as exc: # noqa: BLE001 — the dishonest handler shape+ caught = exc+ except SbinPathError:+ caught = 'guard'+ assert caught == 'guard'+++# --------------------------------------------------------------------------- #+# Passthrough: real execs that are not the bug class still work+# --------------------------------------------------------------------------- #++def test_a_real_resolvable_exec_still_runs():+ """The guard wraps, it does not block: /bin/sh resolves without sbin and+ must exec for real."""+ proc = subprocess.run(['sh', '-c', 'exit 0'])+ assert proc.returncode == 0+++def test_a_real_missing_binary_still_raises_file_not_found():+ with pytest.raises(FileNotFoundError):+ subprocess.run(['definitely-not-installed-anywhere-75', '-t'])