diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml index 3d8ee26a..3ce3daba 100644 --- a/.github/workflows/formal-cross-layer-tlc.yml +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -10,6 +10,8 @@ on: - "api/routers/lifecycle.py" - "api/server.py" - "api/utils/files.py" + - "api/core/writer_admission.py" + - "tests/test_writer_admission.py" - "tests/test_invariants.py" - "tests/test_mvp_control_safety.py" - "tests/test_mvp_inflight_cancel.py" diff --git a/api/core/writer_admission.py b/api/core/writer_admission.py new file mode 100644 index 00000000..0981bf95 --- /dev/null +++ b/api/core/writer_admission.py @@ -0,0 +1,87 @@ +"""Fail-closed single mutating-process admission for one shared session root. + +POSIX filesystem lock, not a distributed lock or generation-fencing scheme. +""" + +import os +import stat +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +try: + import fcntl +except ImportError: # WineBot server runs on Linux, not Windows hosts. + fcntl = None # type: ignore[assignment] + +LOCK_BASENAME = ".winebot-active-writer.lock" + + +class WriterAdmissionError(RuntimeError): + """No exclusive mutating-process admission was granted.""" + + +def _acquire_writer_fd(session_root: str) -> int: + if os.name != "posix" or fcntl is None: + raise WriterAdmissionError("Exclusive writer admission is unsupported") + required = ("O_DIRECTORY", "O_NOFOLLOW", "O_CLOEXEC") + if any(not hasattr(os, flag) for flag in required): + raise WriterAdmissionError("Secure writer lock operations are unavailable") + + root = Path(session_root) + if not root.is_absolute() or root.is_symlink(): + raise WriterAdmissionError("Writer session root is not an admitted directory") + root_fd = None + writer_fd = None + try: + # Directory creation is lock infrastructure only; no session/control + # state is mutated before this admission has succeeded. + root.mkdir(mode=0o700, parents=True, exist_ok=True) + root_fd = os.open( + root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC + ) + if not stat.S_ISDIR(os.fstat(root_fd).st_mode): + raise WriterAdmissionError("Writer root must be a directory") + writer_fd = os.open( + LOCK_BASENAME, + os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + dir_fd=root_fd, + ) + lock_stat = os.fstat(writer_fd) + if ( + not stat.S_ISREG(lock_stat.st_mode) + or lock_stat.st_nlink != 1 + or lock_stat.st_uid != os.geteuid() + ): + raise WriterAdmissionError("Writer lock file identity rejected") + os.fchmod(writer_fd, 0o600) + try: + fcntl.flock(writer_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + raise WriterAdmissionError( + "Another WineBot mutating process is admitted" + ) from exc + acquired_fd = writer_fd + writer_fd = None + return acquired_fd + except OSError as exc: + raise WriterAdmissionError("Writer admission filesystem unavailable") from exc + finally: + if writer_fd is not None: + os.close(writer_fd) + if root_fd is not None: + os.close(root_fd) + + +@contextmanager +def admit_single_writer(session_root: str) -> Iterator[None]: + """Retain one exclusive lock FD across the entire API server lifespan.""" + fd = _acquire_writer_fd(session_root) + try: + yield + finally: + try: + fcntl.flock(fd, fcntl.LOCK_UN) + finally: + os.close(fd) diff --git a/api/server.py b/api/server.py index 5bd040af..edee39c7 100644 --- a/api/server.py +++ b/api/server.py @@ -29,6 +29,7 @@ ARTIFACT_SCHEMA_VERSION, EVENT_SCHEMA_VERSION, ) +from api.core.writer_admission import admit_single_writer from api.routers import automation, control, health, input, lifecycle, recording from api.utils.config import config from api.utils.files import ( @@ -87,7 +88,7 @@ async def resource_monitor_task(): @asynccontextmanager -async def lifespan(_app: FastAPI): +async def _lifespan_after_writer_admission(_app: FastAPI): validation_errors = validate_current_environment() if validation_errors: joined = "; ".join(validation_errors) @@ -146,6 +147,15 @@ async def lifespan(_app: FastAPI): ) +@asynccontextmanager +async def lifespan(app: FastAPI): + # Admission precedes any persistent instance metadata, user-profile + # relink, broker hydration or interrupted handover reconciliation. + with admit_single_writer(config.WINEBOT_SESSION_ROOT): + async with _lifespan_after_writer_admission(app): + yield + + app = FastAPI( title="WineBot API", description="Internal API for controlling WineBot", diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index 4123eb62..d57d7a24 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -10,6 +10,7 @@ pytest \ tests/test_conformance_runtime_policy.py \ tests/test_config_strict_validation.py \ tests/test_invariants.py \ + tests/test_writer_admission.py \ tests/test_input_validation.py \ tests/test_input_keyboard_conformance.py \ tests/test_input_lifecycle_regression.py \ diff --git a/tests/test_writer_admission.py b/tests/test_writer_admission.py new file mode 100644 index 00000000..7e5181b5 --- /dev/null +++ b/tests/test_writer_admission.py @@ -0,0 +1,115 @@ +"""Disposable Linux process-admission and synthetic SIGKILL tests.""" + +import asyncio +import os +import signal +import subprocess +import sys +import time +from pathlib import Path +from unittest.mock import patch + +import pytest + +from api.core.writer_admission import WriterAdmissionError, admit_single_writer + +pytestmark = pytest.mark.skipif(sys.platform != "linux", reason="Linux POSIX flock only") + +PROBE = """ +import sys +from api.core.writer_admission import WriterAdmissionError, admit_single_writer +try: + with admit_single_writer(sys.argv[1]): + pass +except WriterAdmissionError: + raise SystemExit(43) +""" +HOLD = """ +import sys, time +from pathlib import Path +from api.core.writer_admission import admit_single_writer +with admit_single_writer(sys.argv[1]): + Path(sys.argv[2]).write_text('ready', encoding='ascii') + time.sleep(20) +""" + + +def test_two_independent_open_descriptors_and_processes_admit_only_one(tmp_path): + with admit_single_writer(str(tmp_path)): + with pytest.raises(WriterAdmissionError, match="Another WineBot"): + with admit_single_writer(str(tmp_path)): + pytest.fail("Unexpected double writer") + proc = subprocess.run( + [sys.executable, "-c", PROBE, str(tmp_path)], + cwd=Path(__file__).resolve().parents[1], + timeout=4, + check=False, + ) + assert proc.returncode == 43 + with admit_single_writer(str(tmp_path)): + pass + + +def test_writer_symlink_lock_and_symlink_root_fail_closed(tmp_path): + root = tmp_path / "root" + root.mkdir() + (root / ".winebot-active-writer.lock").symlink_to(tmp_path / "victim") + with pytest.raises(WriterAdmissionError): + with admit_single_writer(str(root)): + pytest.fail("Symlink writer lock admitted") + alias = tmp_path / "alias" + alias.symlink_to(root, target_is_directory=True) + with pytest.raises(WriterAdmissionError): + with admit_single_writer(str(alias)): + pytest.fail("Symlink writer root admitted") + + +def test_sigkill_releases_lock_without_deleting_identity(tmp_path): + root = tmp_path / "sessions" + ready = tmp_path / "ready.txt" + proc = subprocess.Popen( + [sys.executable, "-c", HOLD, str(root), str(ready)], + cwd=Path(__file__).resolve().parents[1], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + for _ in range(200): + if ready.is_file() or proc.poll() is not None: + break + time.sleep(0.01) + assert ready.is_file(), "Synthetic owner failed to acquire admission" + with pytest.raises(WriterAdmissionError): + with admit_single_writer(str(root)): + pytest.fail("Second writer admitted while owner alive") + os.kill(proc.pid, signal.SIGKILL) + proc.wait(timeout=3) + with admit_single_writer(str(root)): + assert (root / ".winebot-active-writer.lock").is_file() + finally: + if proc.poll() is None: + proc.kill() + proc.wait(timeout=3) + + +def test_relative_root_is_not_admitted(): + with pytest.raises(WriterAdmissionError): + with admit_single_writer("relative/sessions"): + pytest.fail("Nonabsolute writer root admitted") + + +def test_lifespan_rejects_writer_contention_before_instance_mutation(): + from api import server + + async def enter_lifespan(): + async with server.lifespan(server.app): + pass + + with ( + patch("api.server.admit_single_writer", + side_effect=WriterAdmissionError("synthetic contention")), + patch("api.server.write_instance_state") as state_writer, + ): + with pytest.raises(WriterAdmissionError, match="synthetic contention"): + asyncio.run(enter_lifespan()) + state_writer.assert_not_called()