diff --git a/compose/layered.yml b/compose/layered.yml index d4c0dedb..e642a32b 100644 --- a/compose/layered.yml +++ b/compose/layered.yml @@ -23,7 +23,9 @@ services: network_mode: none read_only: true cap_drop: [ALL] - cap_add: [CHOWN] + # Required only by the isolated root initializer to reopen the + # mode-0600 runtime writer lock after its owner is uid 1000. + cap_add: [CHOWN, DAC_OVERRIDE] security_opt: [no-new-privileges:true] pids_limit: 64 mem_limit: 256m diff --git a/docker/app-bundle.Dockerfile b/docker/app-bundle.Dockerfile index 6830dad4..784a94d4 100644 --- a/docker/app-bundle.Dockerfile +++ b/docker/app-bundle.Dockerfile @@ -8,6 +8,7 @@ COPY scripts/layers/seed-apps.sh /usr/local/bin/winebot-seed-apps COPY scripts/layers/prepare-state.sh /usr/local/bin/winebot-prepare-state RUN set -eu; \ chmod 0555 /usr/local/bin/winebot-seed-apps /usr/local/bin/winebot-prepare-state; \ + command -v flock >/dev/null 2>&1; \ test -d /opt/winebot/app-payload; \ test -z "$(find /opt/winebot/app-payload -type l -print -quit)"; \ cd /opt/winebot/app-payload; \ diff --git a/scripts/ci/classify-layer-init-logs.py b/scripts/ci/classify-layer-init-logs.py index e3e36de5..771e8387 100644 --- a/scripts/ci/classify-layer-init-logs.py +++ b/scripts/ci/classify-layer-init-logs.py @@ -16,7 +16,8 @@ }, "state-init": { "invalid_identity", "mount_unavailable", "permissions_failed", - "ownership_failed", "ready", + "ownership_failed", "lock_unavailable", "lock_identity_invalid", + "lock_contended", "ready", }, } PREFIX = { diff --git a/scripts/ci/qualify-disposable-layers.sh b/scripts/ci/qualify-disposable-layers.sh index 059fb63e..35aae96f 100755 --- a/scripts/ci/qualify-disposable-layers.sh +++ b/scripts/ci/qualify-disposable-layers.sh @@ -76,7 +76,7 @@ docker run --rm --network none --read-only --cap-drop ALL \ "$app_image" >/dev/null 2>&1 || fail reverified_app # One-shot root task prepares only volume root ownership, never user contents. -docker run --rm --network none --read-only --cap-drop ALL --cap-add CHOWN \ +docker run --rm --network none --read-only --cap-drop ALL --cap-add CHOWN --cap-add DAC_OVERRIDE \ --security-opt no-new-privileges --memory 256m --pids-limit 64 \ --entrypoint /bin/sh \ -v "$WINEBOT_PREFIX_VOLUME:/state/prefix" \ @@ -105,8 +105,9 @@ docker run --rm --network none --read-only --user 1000:1000 --cap-drop ALL \ ' >/dev/null 2>&1 || fail first_runtime # Replay the exact privileged bootstrap against *already user-owned* volumes -# with preserved files. CAP_CHOWN-only root must not try chmod on UID1000. -docker run --rm --network none --read-only --cap-drop ALL --cap-add CHOWN \ +# with preserved files. Root needs DAC_OVERRIDE only to reopen the locked, +# mode-0600 UID1000 writer lock; never chmod user-owned volume directories. +docker run --rm --network none --read-only --cap-drop ALL --cap-add CHOWN --cap-add DAC_OVERRIDE \ --security-opt no-new-privileges --memory 256m --pids-limit 64 \ --entrypoint /bin/sh \ -v "$WINEBOT_PREFIX_VOLUME:/state/prefix" \ diff --git a/scripts/ci/qualify-wine11-layered.sh b/scripts/ci/qualify-wine11-layered.sh index 77c62898..331f8398 100755 --- a/scripts/ci/qualify-wine11-layered.sh +++ b/scripts/ci/qualify-wine11-layered.sh @@ -191,6 +191,22 @@ docker compose -f compose/layered.yml exec -T winebot-interactive /bin/sh -ec ' if touch /opt/winebot/unauthorized-root-write >/dev/null 2>&1; then exit 14; fi ' >/dev/null 2>&1 || fail state_write_or_readonly +# Another Compose project using the same external volumes may NOT +# initialize persistent state while an admitted WineBot runtime is alive. +# Only fixed status/marker is published; raw Compose/container text stays +# disposable and local to this synthetic public runner. +competing_log="$(mktemp)" +if docker compose -f compose/layered.yml run --rm --no-deps state-init >"$competing_log" 2>&1; then + rm -f "$competing_log" + fail state_init_competing_writer_admitted +fi +if ! grep -Fq 'STATE_LAYER_DIAGNOSTIC stage=lock_contended' "$competing_log"; then + rm -f "$competing_log" + fail state_init_conflict_unclassified +fi +rm -f "$competing_log" +echo 'WINE11_LAYER_HIL stage=state_init_conflict_rejected' + # Use the actual WineBot bounded trace/resource checker (90-second tier). docker compose -f compose/layered.yml exec -T --user 1000 \ -e DURATION_SECONDS=90 -e INTERVAL_SECONDS=15 \ diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index da53eebb..8ac392fa 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -41,6 +41,7 @@ pytest \ tests/test_lifecycle_cancel_window.py \ tests/test_health_system_memory.py \ tests/test_disposable_layer_contract.py \ + tests/test_layered_writer_fencing.py \ tests/test_mvp_control_safety.py \ tests/test_mvp_control_api.py \ tests/test_mvp_mouse_lease.py \ diff --git a/scripts/layers/prepare-state.sh b/scripts/layers/prepare-state.sh index fe806a20..2519e595 100755 --- a/scripts/layers/prepare-state.sh +++ b/scripts/layers/prepare-state.sh @@ -8,6 +8,51 @@ fail() { exit 1 } [ "$(id -u)" = 0 ] || fail invalid_identity +# Coordinate with the runtime's exact /artifacts/sessions/.winebot-active-writer.lock. +# This protects concurrent state ownership mutations; it does NOT guarantee +# atomic ownership of a whole deployment across state-init -> runtime. +command -v flock >/dev/null 2>&1 || fail lock_unavailable +control_parent=/state/artifacts +control_root="$control_parent/sessions" +control_file="$control_root/.winebot-active-writer.lock" +[ -d "$control_parent" ] && [ ! -L "$control_parent" ] || fail mount_unavailable +if [ ! -d "$control_root" ]; then + [ ! -e "$control_root" ] && [ ! -L "$control_root" ] || fail lock_identity_invalid + mkdir -m 0700 "$control_root" >/dev/null 2>&1 || fail lock_unavailable +fi +[ -d "$control_root" ] && [ ! -L "$control_root" ] || fail lock_identity_invalid +if [ ! -e "$control_file" ]; then + [ ! -L "$control_file" ] || fail lock_identity_invalid + (umask 077; : > "$control_file") 2>/dev/null || fail lock_unavailable +fi +[ -f "$control_file" ] && [ ! -L "$control_file" ] || fail lock_identity_invalid +[ "$(stat -c '%h' "$control_file" 2>/dev/null)" = 1 ] || fail lock_identity_invalid +exec 9<>"$control_file" || fail lock_unavailable +[ "$(stat -c '%d:%i' "$control_file")" = "$(stat -Lc '%d:%i' /proc/self/fd/9)" ] || + fail lock_identity_invalid +flock -n -x 9 >/dev/null 2>&1 || fail lock_contended +# Revalidate identity while the lock is held; absent / attacker-controlled +# lock swaps are refused rather than treated as a new independent lock. +[ ! -L "$control_file" ] && + [ "$(stat -c '%d:%i' "$control_file")" = "$(stat -Lc '%d:%i' /proc/self/fd/9)" ] || + fail lock_identity_invalid +case "$(stat -c '%u:%g:%a' "$control_file" 2>/dev/null)" in + 0:0:600) + chown 1000:1000 "$control_file" >/dev/null 2>&1 || fail ownership_failed + ;; + 1000:1000:600) ;; + *) fail lock_identity_invalid ;; +esac +case "$(stat -c '%u:%g' "$control_root" 2>/dev/null)" in + 0:0) + chmod u+rwx "$control_root" >/dev/null 2>&1 || fail permissions_failed + chown 1000:1000 "$control_root" >/dev/null 2>&1 || fail ownership_failed + ;; + 1000:1000) ;; + *) fail lock_identity_invalid ;; +esac +# FD9 remains open until this process exits; another writer's nonblocking +# kernel flock will reject mutations while this state-init owns the lock. for dir in /state/prefix /state/home /state/config /state/userdata /state/artifacts /state/shared; do [ -d "$dir" ] && [ ! -L "$dir" ] || fail mount_unavailable owner="$(stat -c '%u:%g' "$dir" 2>/dev/null)" || fail mount_unavailable diff --git a/tests/test_layered_writer_fencing.py b/tests/test_layered_writer_fencing.py new file mode 100644 index 00000000..b0600483 --- /dev/null +++ b/tests/test_layered_writer_fencing.py @@ -0,0 +1,74 @@ +"""Synthetic cooperative flock and source-bound layered admission gates. + +No deployment, network, non-synthetic state, or privileged test target. +These controls are not evidence of an atomic inter-container handoff. +""" +import fcntl +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +class LayeredWriterFence(unittest.TestCase): + def test_same_lock_identity_and_stage_before_mutation(self): + script = (ROOT / "scripts/layers/prepare-state.sh").read_text() + owner = (ROOT / "api/core/writer_admission.py").read_text() + self.assertIn('LOCK_BASENAME = ".winebot-active-writer.lock"', owner) + self.assertIn('DEFAULT_SESSION_ROOT = "/artifacts/sessions"', owner) + self.assertIn('control_root="$control_parent/sessions"', script) + self.assertIn('control_file="$control_root/.winebot-active-writer.lock"', script) + self.assertIn('flock -n -x 9', script) + self.assertLess(script.index('flock -n -x 9'), script.index('for dir in /state/prefix')) + self.assertLess(script.index('flock -n -x 9'), script.index('chown 1000:1000 "$dir"')) + self.assertIn('stat -Lc', script) + self.assertIn('fail lock_contended', script) + self.assertIn('fail lock_identity_invalid', script) + + def test_prerequisites_and_actual_guest_contender_required(self): + compose = (ROOT / "compose/layered.yml").read_text() + dockerfile = (ROOT / "docker/app-bundle.Dockerfile").read_text() + hil = (ROOT / "scripts/ci/qualify-wine11-layered.sh").read_text() + self.assertIn('cap_add: [CHOWN, DAC_OVERRIDE]', compose) + self.assertIn('command -v flock >/dev/null', dockerfile) + self.assertIn('run --rm --no-deps state-init', hil) + self.assertIn('stage=state_init_conflict_rejected', hil) + self.assertNotIn('docker push', hil) + self.assertNotIn('actions/upload-artifact', hil) + + def test_independent_process_cannot_acquire_held_lock(self): + if os.name != "posix": + self.skipTest("Linux-only flock contract") + with tempfile.TemporaryDirectory() as root: + path = Path(root) / ".winebot-active-writer.lock" + with path.open("a+b") as held: + fcntl.flock(held.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + # A distinct subprocess must open its own OFD. Testing in the + # parent process or after fork with inherited FD is invalid. + code = ( + "import fcntl,sys\n" + "with open(sys.argv[1], 'r+b') as f:\n" + " try: fcntl.flock(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)\n" + " except BlockingIOError: sys.exit(73)\n" + " sys.exit(0)\n" + ) + denied = subprocess.run( + [sys.executable, "-c", code, str(path)], + check=False, capture_output=True, text=True, timeout=5, + ) + self.assertEqual(denied.returncode, 73) + self.assertEqual(denied.stdout, "") + self.assertEqual(denied.stderr, "") + allowed = subprocess.run( + [sys.executable, "-c", code, str(path)], + check=False, capture_output=True, text=True, timeout=5, + ) + self.assertEqual(allowed.returncode, 0) + + +if __name__ == "__main__": + unittest.main()