diff --git a/.github/workflows/disposable-backup-restore-rdte.yml b/.github/workflows/disposable-backup-restore-rdte.yml new file mode 100644 index 00000000..479ea653 --- /dev/null +++ b/.github/workflows/disposable-backup-restore-rdte.yml @@ -0,0 +1,36 @@ +name: Disposable User-State Backup and Restore RDTE +on: + pull_request: + paths: + - '.github/workflows/disposable-backup-restore-rdte.yml' + - 'scripts/ci/qualify-volume-backup-restore.sh' +permissions: + contents: read +concurrency: + group: layer-backup-${{ github.event.pull_request.number }} + cancel-in-progress: true +jobs: + synthetic-six-volume-recovery: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + steps: + - name: Checkout exact public PR code without credentials + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - name: Source syntax and destructive-operation scope + run: | + set -euo pipefail + bash -n scripts/ci/qualify-volume-backup-restore.sh + grep -q '^prefix="winebot-recovery-' scripts/ci/qualify-volume-backup-restore.sh + grep -q 'archive_integrity_negative' scripts/ci/qualify-volume-backup-restore.sh + grep -q 'backup_volume="$prefix-snapshots"' scripts/ci/qualify-volume-backup-restore.sh + ! grep -q 'rm -rf' scripts/ci/qualify-volume-backup-restore.sh + - name: Fully disposable checksum archive and nonroot recovery + run: bash scripts/ci/qualify-volume-backup-restore.sh + - name: Report only synthetic result + if: success() + run: echo 'LAYER_BACKUP_RDTE stage=qualified_synthetic_replay' diff --git a/.github/workflows/disposable-layer-qualification.yml b/.github/workflows/disposable-layer-qualification.yml new file mode 100644 index 00000000..0170c9ab --- /dev/null +++ b/.github/workflows/disposable-layer-qualification.yml @@ -0,0 +1,48 @@ +name: Disposable Layer Contract Qualification +on: + pull_request: + paths: + - '.github/workflows/disposable-layer-qualification.yml' + - 'compose/layered.yml' + - 'docker/app-bundle.Dockerfile' + - 'docker/Dockerfile' + - 'docker/entrypoint.sh' + - 'scripts/layers/**' + - 'scripts/ci/qualify-disposable-layers.sh' + - 'scripts/ci/test.sh' + - 'tests/test_disposable_layer_contract.py' + - 'docs/disposable-layer-architecture.md' + +permissions: + contents: read + +env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + +concurrency: + group: disposable-layer-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + source-and-replay: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - name: Checkout exact untrusted public PR source + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + persist-credentials: false + ref: ${{ github.event.pull_request.head.sha }} + - name: Verify offline source and shell contracts + run: | + python3 -m unittest discover -s tests -p 'test_disposable_layer_contract.py' -v + bash -n scripts/layers/preflight.sh + bash -n scripts/ci/qualify-disposable-layers.sh + sh -n scripts/layers/prepare-state.sh + sh -n scripts/layers/seed-apps.sh + bash -n docker/entrypoint.sh + - name: Qualify disposable images, replay and external state + run: bash scripts/ci/qualify-disposable-layers.sh + - name: Report only bounded overall result + if: success() + run: echo 'LAYER_CONTRACT_DIAGNOSTIC stage=source_and_replay_passed' diff --git a/.github/workflows/layered-contract-integration-rdte.yml b/.github/workflows/layered-contract-integration-rdte.yml new file mode 100644 index 00000000..46d1e7cf --- /dev/null +++ b/.github/workflows/layered-contract-integration-rdte.yml @@ -0,0 +1,112 @@ +name: Layered + Frozen Conformance Integration RDTE +on: + pull_request: + paths: + - '.github/workflows/layered-contract-integration-rdte.yml' +permissions: + contents: read +concurrency: + group: layered-conformance-integration-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + source-integrated-frozen-v1: + runs-on: ubuntu-24.04 + timeout-minutes: 45 + env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + steps: + - name: Checkout exact layered PR with Git ancestry + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + path: winebot + - name: Test-only source merge with pinned successful conformance PR + working-directory: winebot + shell: bash + run: | + set -euo pipefail + git config user.name 'WineBot Public RDTE' + git config user.email 'winebot-rdte@users.noreply.github.com' + git fetch --no-tags --quiet origin 3acc219a1627a74bdcea6388144cc391ec2b57b4 + if ! git merge --no-commit --no-ff --no-edit 3acc219a1627a74bdcea6388144cc391ec2b57b4 >"$RUNNER_TEMP/merge-local.log" 2>&1; then + # Only the known independent test-list append conflict is + # resolvable. Every other merge collision fails closed. + python3 scripts/ci/resolve-conformance-units.py || exit 1 + fi + if git diff --name-only --diff-filter=U | grep -q .; then + echo 'LAYERED_CONFORMANCE_RDTE stage=unresolved_files' + exit 1 + fi + echo 'LAYERED_CONFORMANCE_RDTE stage=source_merge_pass' + - name: Existing bounded unit tests on combined source + working-directory: winebot + shell: bash + run: | + set -euo pipefail + if ! docker compose -f compose/docker-compose.yml --profile test --profile interactive run \ + --rm --no-deps test-runner scripts/ci/test.sh >"$RUNNER_TEMP/unit-local.log" 2>&1; then + echo 'LAYERED_CONFORMANCE_RDTE stage=merged_unit_fail' + exit 1 + fi + echo 'LAYERED_CONFORMANCE_RDTE stage=merged_unit_pass' + - name: Checkout pinned frozen public contract suite + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + repository: mark-e-deyoung/winebot-contracts + ref: 205666f7f0235cb0fc51ca8a5af84f9f67831a74 + persist-credentials: false + path: contracts + - name: Install frozen suite requirements + shell: bash + run: | + set -euo pipefail + python3 -m pip install -q -r contracts/tests/conformance/requirements.txt \ + >"$RUNNER_TEMP/deps-local.log" 2>&1 || + { echo 'LAYERED_CONFORMANCE_RDTE stage=contract_deps_fail'; exit 1; } + - name: Start actual source-integrated WineBot API + working-directory: winebot + shell: bash + run: | + set -euo pipefail + if ! docker compose -f compose/docker-compose.yml --profile headless \ + up --build -d winebot >"$RUNNER_TEMP/runtime-local.log" 2>&1; then + echo 'LAYERED_CONFORMANCE_RDTE stage=runtime_start_failed' + exit 1 + fi + if ! scripts/ci/wait-for-container-health.sh compose/docker-compose.yml headless winebot 60 2 \ + >"$RUNNER_TEMP/health-local.log" 2>&1; then + echo 'LAYERED_CONFORMANCE_RDTE stage=runtime_health_failed' + exit 1 + fi + echo 'LAYERED_CONFORMANCE_RDTE stage=runtime_ready' + - name: Run pinned frozen v1 against source-integrated runtime + shell: bash + run: | + set -euo pipefail + cd winebot + cid="$(docker compose -f compose/docker-compose.yml ps -q winebot)" + [ -n "$cid" ] || { echo 'LAYERED_CONFORMANCE_RDTE stage=runtime_absent'; exit 1; } + ip="$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$cid")" + token="$(docker compose -f compose/docker-compose.yml exec -T winebot cat /tmp/winebot_api_token 2>/dev/null || true)" + if [[ ! "$token" =~ ^[A-Za-z0-9._~-]{16,512}$ ]]; then + echo 'LAYERED_CONFORMANCE_RDTE stage=token_invalid' + exit 1 + fi + printf '::add-mask::%s\n' "$token" + cd .. + if ! python3 -m pytest contracts/tests/conformance/ \ + --api-url "http://$ip:8000" --api-token "$token" \ + --results-file "$RUNNER_TEMP/conformance-local.json" \ + -q --tb=no --show-capture=no -rN \ + >"$RUNNER_TEMP/conformance-local.log" 2>&1; then + echo 'LAYERED_CONFORMANCE_RDTE stage=frozen_v1_failed' + exit 1 + fi + echo 'LAYERED_CONFORMANCE_RDTE stage=frozen_v1_pass' + - name: Remove only disposable service containers + if: always() + working-directory: winebot + run: docker compose -f compose/docker-compose.yml --profile headless down --remove-orphans >/dev/null 2>&1 || true diff --git a/.github/workflows/wine11-disposable-layer-hil.yml b/.github/workflows/wine11-disposable-layer-hil.yml new file mode 100644 index 00000000..b4cf491a --- /dev/null +++ b/.github/workflows/wine11-disposable-layer-hil.yml @@ -0,0 +1,59 @@ +name: Wine 11 Disposable-Layer Composite HIL + +# Public PR source snapshots only; never publishes images/diagnostics. +on: + pull_request: + paths: + - '.github/workflows/wine11-disposable-layer-hil.yml' + - 'compose/layered.yml' + - 'docker/Dockerfile' + - 'docker/entrypoint.sh' + - 'scripts/layers/**' + - 'scripts/ci/qualify-wine11-layered.sh' + - 'scripts/ci/classify-layer-init-logs.py' + - 'tests/test_layer_init_diagnostics.py' + +permissions: + contents: read + +env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + +concurrency: + group: wine11-layer-hil-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + composite-wine11-hil: + runs-on: ubuntu-24.04 + timeout-minutes: 115 + steps: + - name: Checkout exact layered architecture PR source + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + persist-credentials: false + ref: ${{ github.event.pull_request.head.sha }} + path: layered + - name: Checkout exact separately qualified Wine11 source + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + repository: SemperSupra/WineBot + persist-credentials: false + ref: 8c5ed8019a3518cf534b158662755172bfce7c59 + path: wine11-candidate + - name: Free disposable runner disk + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /usr/share/swift + - name: Source syntax and frozen composite ownership + working-directory: layered + run: | + bash -n scripts/ci/qualify-wine11-layered.sh + python3 -m unittest discover -s tests -p 'test_layer_init_diagnostics.py' -v + test -f ../wine11-candidate/scripts/init/20-setup-wine.sh + test -f ../wine11-candidate/scripts/ci/classify-wine11-soak.py + - name: Build ephemeral candidate and qualify read-only Wine11 replay + working-directory: layered + run: bash scripts/ci/qualify-wine11-layered.sh + - name: Report only fixed result + if: success() + run: echo 'WINE11_LAYER_HIL stage=qualified_composite' diff --git a/AGENTS.md b/AGENTS.md index ce429f83..c347a1cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,6 +2,17 @@ This document is a navigation aid for autonomous agents working on the WineBot codebase. +## Disposable three-layer deployment (opt-in) + +The authoritative architecture target separates a replaceable Wine runtime +image, immutable/versioned application pack seeded by a short-lived container, +and external persistent per-user state volumes. Start with +[docs/disposable-layer-architecture.md](docs/disposable-layer-architecture.md) +and `compose/layered.yml`. Do not run legacy per-boot loadouts or delete +volumes during housekeeping. Public GHA qualification owns synthetic +disposable-layer replay; the actual Wine 11 layered runtime is not yet +release qualified. Existing main legacy behavior is maintained. + ## 1. System Architecture WineBot is a containerized Windows application runtime (Wine 10.0) with an X11 display stack, controlled via a Python FastAPI. diff --git a/compose/layered.yml b/compose/layered.yml new file mode 100644 index 00000000..d4c0dedb --- /dev/null +++ b/compose/layered.yml @@ -0,0 +1,158 @@ +# Opt-in three-layer deployment. Use this file ALONE, never as an +# override of the legacy Compose stack; there are no build: directives. +# All state and app volumes are EXTERNAL and cannot be deleted by down -v. +name: winebot-layered +services: + app-seed: + image: ${WINEBOT_APP_BUNDLE_IMAGE:?pin application pack to sha256 digest} + user: "0:0" + network_mode: none + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 256m + volumes: + - app-store:/winebot-apps + restart: "no" + + state-init: + image: ${WINEBOT_APP_BUNDLE_IMAGE:?pin application pack to sha256 digest} + entrypoint: ["/bin/sh", "/usr/local/bin/winebot-prepare-state"] + user: "0:0" + network_mode: none + read_only: true + cap_drop: [ALL] + cap_add: [CHOWN] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 256m + volumes: + - wineprefix:/state/prefix + - user-home:/state/home + - config:/state/config + - userdata:/state/userdata + - artifacts:/state/artifacts + - shared:/state/shared + restart: "no" + + winebot-interactive: + image: ${WINEBOT_RUNTIME_IMAGE:?pin WineBot runtime to sha256 digest} + user: "1000:1000" + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + init: true + pids_limit: 512 + mem_limit: 3g + cpus: 2 + tmpfs: + - /tmp:rw,nosuid,nodev,mode=1777,size=256m + - /run:rw,nosuid,nodev,mode=0755,size=64m + - /var/tmp:rw,nosuid,nodev,mode=1777,size=64m + depends_on: + app-seed: + condition: service_completed_successfully + state-init: + condition: service_completed_successfully + environment: + HOME: /home/winebot + WINEBOT_STATE_MODEL: layered + WINEBOT_CONFIG_ROOT: /config + WINEBOT_SYNC_OPENBOX_CONFIG: "0" + WINEPREFIX: /wineprefix + DISPLAY: ":99" + SCREEN: 1280x720x24 + WINEARCH: win64 + MODE: interactive + BUILD_INTENT: rel + # 30-start-services.sh launches the API only when explicitly enabled. + # Keep the private token-file healthcheck authenticated, never bypass it. + ENABLE_API: "1" + INIT_PREFIX: "1" + ENABLE_VNC: "1" + WINEBOT_RECORD: "1" + WINEBOT_INPUT_TRACE: "1" + WINEBOT_INPUT_TRACE_WINDOWS: "1" + WINEBOT_INPUT_TRACE_NETWORK: "0" + WINEBOT_LOADOUT: "" + WINE_WINETRICKS: "" + WINE_INSTALL_MS_FONTS: "0" + API_TOKEN: ${WINEBOT_API_TOKEN:?provide an API token via deployment secret delivery} + VNC_PASSWORD: ${WINEBOT_VNC_PASSWORD:?provide a VNC password via secret delivery} + ports: + - "127.0.0.1:8000:8000" + - "127.0.0.1:6080:6080" + - "127.0.0.1:5900:5900" + # The dependent runtime must never populate fresh state/app volumes from + # its image: that can race one-shot initialization and change ownership. + volumes: + - type: volume + source: app-store + target: /apps + read_only: true + volume: + nocopy: true + - type: volume + source: wineprefix + target: /wineprefix + volume: + nocopy: true + - type: volume + source: user-home + target: /home/winebot + volume: + nocopy: true + - type: volume + source: config + target: /config + volume: + nocopy: true + - type: volume + source: userdata + target: /userdata + volume: + nocopy: true + - type: volume + source: artifacts + target: /artifacts + volume: + nocopy: true + - type: volume + source: shared + target: /winebot-shared + volume: + nocopy: true + # Require the credential; the one-line command avoids a YAML-preserved + # newline between curl and URL. No unauthenticated fallback is allowed. + healthcheck: + test: + - CMD-SHELL + - 'TOKENS="$$(cat /tmp/winebot_api_token 2>/dev/null || true)"; for TOKEN in $$TOKENS; do [ -z "$$TOKEN" ] && continue; curl -fsS -H "X-API-Key: $$TOKEN" http://127.0.0.1:8000/health >/dev/null && exit 0; done; exit 1' + interval: 10s + timeout: 10s + retries: 30 + start_period: 30s + +volumes: + app-store: + external: true + name: ${WINEBOT_APP_VOLUME:?provide version-specific application volume name} + wineprefix: + external: true + name: ${WINEBOT_PREFIX_VOLUME:?provide persistent Wine profile volume name} + user-home: + external: true + name: ${WINEBOT_HOME_VOLUME:?provide persistent home volume name} + config: + external: true + name: ${WINEBOT_CONFIG_VOLUME:?provide persistent configuration volume name} + userdata: + external: true + name: ${WINEBOT_USERDATA_VOLUME:?provide persistent user files volume name} + artifacts: + external: true + name: ${WINEBOT_ARTIFACT_VOLUME:?provide persistent evidence volume name} + shared: + external: true + name: ${WINEBOT_SHARED_VOLUME:?provide persistent shared state volume name} diff --git a/docker/Dockerfile b/docker/Dockerfile index a7b84085..b8576012 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -5,7 +5,8 @@ ARG BUILD_DATE=unknown ARG SOURCE_REPO="https://github.com/SemperSupra/WineBot" # --- Stage 1: Tool Builders (Parallel) --- -FROM debian:trixie-slim AS tool-base +ARG TOOL_BUILDER_BASE_IMAGE=debian@sha256:cedb1ef40439206b673ee8b33a46a03a0c9fa90bf3732f54704f99cb061d2c5a +FROM ${TOOL_BUILDER_BASE_IMAGE} AS tool-base RUN apt-get update && apt-get install -y --no-install-recommends curl unzip ca-certificates && rm -rf /var/lib/apt/lists/* COPY windows-tools/download_tool.sh /download_tool.sh diff --git a/docker/app-bundle.Dockerfile b/docker/app-bundle.Dockerfile new file mode 100644 index 00000000..6830dad4 --- /dev/null +++ b/docker/app-bundle.Dockerfile @@ -0,0 +1,17 @@ +# App packages are built separately from the WineBot runtime. +# The builder is pinned to an already-qualified Debian digest. No network +# downloads or unverified Windows installer execution occur during startup. +ARG APP_PACK_BUILDER_IMAGE=debian@sha256:cedb1ef40439206b673ee8b33a46a03a0c9fa90bf3732f54704f99cb061d2c5a +FROM ${APP_PACK_BUILDER_IMAGE} +COPY apps/ /opt/winebot/app-payload/ +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; \ + test -d /opt/winebot/app-payload; \ + test -z "$(find /opt/winebot/app-payload -type l -print -quit)"; \ + cd /opt/winebot/app-payload; \ + find . -type f -exec sha256sum {} + | LC_ALL=C sort > /opt/winebot/app-manifest.sha256; \ + test -s /opt/winebot/app-manifest.sha256 +LABEL org.opencontainers.image.description="Disposable WineBot immutable application payload / seeder" +ENTRYPOINT ["/bin/sh", "/usr/local/bin/winebot-seed-apps"] diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index ccd34e85..67e006ed 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -32,6 +32,32 @@ if [ "$WINEBOT_SESSION_MODE" != "persistent" ] && [ "$WINEBOT_SESSION_MODE" != " exit 2 fi +# Opt-in layered deployments must never depend on a mutable container root. +# The one-shot state preparer has already made external volumes writable by +# uid 1000; application assets are mounted read-only. +if [ "${WINEBOT_STATE_MODEL:-legacy}" = "layered" ]; then + if [ "$(id -u)" != "1000" ] || [ "${WINEBOT_CONFIG_ROOT:-}" != "/config" ]; then + echo 'LAYERED_RUNTIME_DIAGNOSTIC stage=identity_or_config_invalid' >&2 + exit 2 + fi + if [ -n "${WINEBOT_LOADOUT:-}" ] || [ -n "${WINE_WINETRICKS:-}" ] || + [ "${WINE_INSTALL_MS_FONTS:-0}" != "0" ]; then + echo 'LAYERED_RUNTIME_DIAGNOSTIC stage=runtime_install_forbidden' >&2 + exit 2 + fi + for persistent in /wineprefix /home/winebot /config /userdata /artifacts /winebot-shared; do + if [ ! -d "$persistent" ] || [ -L "$persistent" ] || [ ! -w "$persistent" ]; then + echo 'LAYERED_RUNTIME_DIAGNOSTIC stage=persistent_mount_unavailable' >&2 + exit 2 + fi + done + if [ ! -d /apps ] || [ -w /apps ] || + [ ! -s /apps/.winebot-app-content-sha256 ]; then + echo 'LAYERED_RUNTIME_DIAGNOSTIC stage=app_mount_invalid' >&2 + exit 2 + fi +fi + # 1. Root Level Setup (User creation, permissions) source /scripts/init/00-setup-user.sh @@ -84,8 +110,13 @@ fi echo $$ > /tmp/entrypoint.user.pid # Load runtime configuration overrides -WINEBOT_CONFIG_FILE="/wineprefix/winebot.env" -WINEBOT_INSTANCE_CONFIG="/wineprefix/winebot.${HOSTNAME}.env" +if [ "${WINEBOT_STATE_MODEL:-legacy}" = "layered" ]; then + WINEBOT_CONFIG_FILE="/config/winebot.env" + WINEBOT_INSTANCE_CONFIG="/config/winebot.instance.env" +else + WINEBOT_CONFIG_FILE="/wineprefix/winebot.env" + WINEBOT_INSTANCE_CONFIG="/wineprefix/winebot.${HOSTNAME}.env" +fi if [ -f "$WINEBOT_CONFIG_FILE" ]; then chmod 600 "$WINEBOT_CONFIG_FILE" diff --git a/docs/disposable-layer-architecture.md b/docs/disposable-layer-architecture.md new file mode 100644 index 00000000..f0816598 --- /dev/null +++ b/docs/disposable-layer-architecture.md @@ -0,0 +1,150 @@ +# WineBot: Disposable runtime / application / persistent-state architecture + +**Status:** opt-in public RDTE, **not production-promoted**. This is separate +from legacy `compose/docker-compose.yml`. Do not combine the two files until +an explicit migration/release gate has been qualified. + +## Authority and design + +Git/DLE holds desired topology, source, pins, package custody, diagnostics and +acceptance receipts. No long-lived local checkout, worktree, builder container, +runtime container, cache or privileged sidecar is authoritative. + +| Layer | Representation | Lifetime | Allowed writes | +| --- | --- | --- | --- | +| Runtime | digest-pinned OCI WineBot REL image | disposable per run/restart | `tmpfs` only; no permanent rootfs writes | +| Applications | separately built digest-pinned OCI app pack; one-shot seed into a **version-specific external** volume mounted `/apps:ro` | replaceable independently | one-shot offline pack seeder only; never a running WineBot process | +| Persistent user state | external named volumes for Wine prefix, user home, configuration, user files, session evidence, and shared state | survives upgrades, container deletion and `docker compose down` | the unprivileged runtime/user; not app seeder | + +The package *seeder* and state-preparer are short-lived, network-disabled +containers. Runtime runs as uid/gid 1000, with no capabilities, read-only image +filesystem and bounded writable tmpfs. The preparer runs as root with only +CHOWN, modifies top-level volume directory ownership but does not recursively +rewrite or delete user files. The app seeder is root inside its container but +has no Linux capabilities and no network. Neither preparer sees credentials. + +The disposable runtime mounts all seven external application/state volumes with +`volume.nocopy: true`. Docker's default initial volume population can copy +image directory contents **and metadata/ownership** into a newly created +external volume when multiple dependent Compose containers are created. +Prevent runtime image copy-up before the independent one-shot app seeder and +state initializer execute. Do not use runtime image copy-up as an installer, +migration, backup or profile-provisioning mechanism. The build and deployment +must be qualified together: the composite startup test specifically tests this +ownership race and keeps its proof volumes isolated to one disposable runner. +Failure to acquire a seeder lock is not automatically a concurrent installation; +a separately classified unwritable app volume must fail without modifying user +data. This correction remains experimental until composite HIL demonstrates it. + +The original `/wineprefix` retains Wine registry and per-user installed-app +state; this is **not** yet a clean separation of arbitrary Windows MSI/EXE +installation mutations. The new app layer is fully usable for portable packages +and curated read-only application payloads. Nonportable installers that alter +registry, Program Files, fonts, system DLLs and user configuration still need a +future snapshot/registry-overlay/migration qualification; do not assert their +portable installation semantics from this MVP. Never download or install +unverified programs on every runtime boot. The legacy +`WINEBOT_LOADOUT`, `WINE_WINETRICKS`, and `WINE_INSTALL_MS_FONTS` runtime +install paths are fail-closed in layered mode. + +## Build / promotion + +1. Build the runtime independently in a disposable public GHA job from + pinned tool-builder and Wine base sources; tools fetched during build are + checksum-controlled. The current third-party E2E Playwright builder image + and remaining mutable input references require independent custody review + before release. Artifact signatures, SBOM and provenance remain separate + release/security gates. +2. Assemble an app pack from `apps/` into `docker/app-bundle.Dockerfile`. + The builder uses an immutable Debian digest; there is no download or Wine + installation step inside the app pack image. It creates deterministic + per-file SHA-256 manifests, rejects symlinks and exits on errors. + Restricted installers/assets must NOT be committed into the public repo; + qualify them in a private controlled app-pack build and move only permitted + verified artifacts. +3. Promote immutable runtime and app pack image **digests** independently. + Create a fresh version-specific app volume when its app-pack content + changes. The app seeder refuses existing mismatched/incomplete packs rather + than overwriting them. Roll back by selecting the older immutable + app image/dedicated volume; never alter user state implicitly. +4. Integrate installed-app registry migration only with explicit per-app + compatibility metadata and reversible, backed-up state transactions. + Uninstall or reset is never `docker compose down --volumes`. + +## Deployment contract + +Required environment variables (use a secure deployment/secret manager; never +publish values to CI logs or DLE): + +- `WINEBOT_RUNTIME_IMAGE` and `WINEBOT_APP_BUNDLE_IMAGE`: immutable + `registry/repository@sha256:<64-hex-digest>`. +- `WINEBOT_APP_VOLUME`: a **version-specific** existing external app-pack + volume, not shared with mutable user state. +- `WINEBOT_PREFIX_VOLUME`, `WINEBOT_HOME_VOLUME`, + `WINEBOT_CONFIG_VOLUME`, `WINEBOT_USERDATA_VOLUME`, + `WINEBOT_ARTIFACT_VOLUME`, `WINEBOT_SHARED_VOLUME`: independent + external volumes, each unique to the deployment/user and starting with + `winebot-`; the preflight validates distinct names. +- `WINEBOT_API_TOKEN`, `WINEBOT_VNC_PASSWORD`: secrets supplied at + deployment. The current API/VNC implementation uses environment-based + injection and must receive separate secret-file or manager qualification + before deployment beyond localhost. + +Run `bash scripts/layers/preflight.sh --check` to validate without +modification, or `--create` to initialize only missing named volumes. +Then `docker compose -f compose/layered.yml config --quiet` and +`docker compose -f compose/layered.yml up --no-build -d winebot-interactive`. +No build occurs on the deployed host. UI/API/VNC only bind loopback until +an approved authenticated ingress/proxy is independently qualified. + +`docker compose -f compose/layered.yml down` removes only containers/networks. +All volumes are declared `external: true`; even `down -v` must not delete +their data. Do not use `docker volume rm` on user/app volumes. Back up and +restore each external volume before any migration or rollback and verify the +restored user profile, application settings, files and credentials. A change to +app version may require a compatible Wine prefix migration; do not silently +rewrite the profile to make an installer pass. + +## Qualification / DX / UX + +The dedicated public `disposable-layer-qualification.yml` workflow performs +zero-secret, synthetic, network-off GHA replay: source-contract checks, shell +syntax checks, bundle build, idempotent seed, state ownership bootstrap, +read-only nonroot runtime recreation, persistent state replay, rejected app +version overwrite, fresh versioned app volume and retained profile data. +Only fixed-category results are published. Disposable CI volumes and images +are cleaned without ever touching real deployment volumes. + +The composite source-pinned Wine 11 HIL has now passed real read-only-root +startup, authenticated API health, 90-second resource sampling, container +recreation with retained prefix/home/configuration/user/evidence state, and a +forced SIGKILL with retained state and health. That was a public RDTE milestone +and does **not** by itself qualify a production deployment. + +The next gate, qualified in the same disposable public-runner composite, +extends the source-pinned Wine 11 candidate to a **55-minute sustained resource +soak**, an authenticated post-soak health check, bounded in-container Openbox +termination/recovery and another health check, followed by the previously +qualified container restart and SIGKILL persistent-state replay. The soak +records raw output only within the disposable runner; a fixed-enum classifier +from the pinned candidate reports failures. This gate is pending until its +exact-head public Actions result is terminal green. + +Still required for release: arbitrary Windows installer/registry overlays and +safe migration, WinInspect real application observer and human accessibility +acceptance, user-data external-volume backup/restore and disaster recovery, +secure secret delivery, mandatory legacy-v1 conformance, and rights/security +reviews. + +Human UI: recognizable profiles/app-pack versions, explicit backup/rollback +warnings, and desktop settings that survive replacement. Automation DX: +stable exit statuses, bounded enumerated markers, declarative configuration +and no hidden installs. Agent DX: exact immutable image/volume IDs, DLE +evidence, no secret/raw data publication, and non-destructive reconciliation. + +## Legacy caveat + +`docs/installing-apps.md` and the older `scripts/install-app.sh` describe +the legacy mutable-prefix flow. They are **not** approved as the new app +promotion mechanism. In particular, legacy `down -v` destroys data and must +not be used to reset a layered deployment. diff --git a/docs/installing-apps.md b/docs/installing-apps.md index 485a3359..53bbdfe1 100644 --- a/docs/installing-apps.md +++ b/docs/installing-apps.md @@ -1,3 +1,9 @@ +> **Legacy mutable-prefix instructions only.** The opt-in disposable +> runtime/application/persistent-state architecture is documented in +> [Disposable Layer Architecture](disposable-layer-architecture.md). +> Never use the legacy `down -v` reset on persistent user data; layered +> deployments use external volumes and immutable application packages. +> # Installing Apps This workflow separates installation (into the persistent Wine prefix) from running the app for automation. diff --git a/scripts/ci/classify-layer-init-logs.py b/scripts/ci/classify-layer-init-logs.py new file mode 100644 index 00000000..e3e36de5 --- /dev/null +++ b/scripts/ci/classify-layer-init-logs.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Project bounded, allowlisted init-failure categories without exposing raw logs. + +Never include raw container stdout/stderr, paths, environment variables, +container IDs, host details or credential material in public CI output. +""" +import re +import sys + +STAGES = { + "app-seed": { + "unavailable", "invalid_mount", "invalid_manifest", "version_mismatch", + "unexpected_files", "unexpected_symlink", "integrity_mismatch", + "incomplete_volume", "concurrent_init", "permissions_failed", "copy_failed", "stamp_failed", + "existing_verified", "created_verified", + }, + "state-init": { + "invalid_identity", "mount_unavailable", "permissions_failed", + "ownership_failed", "ready", + }, +} +PREFIX = { + "app-seed": "APP_LAYER_DIAGNOSTIC", + "state-init": "STATE_LAYER_DIAGNOSTIC", +} + + +def classify(service: str, lines) -> str: + if service not in STAGES: + raise ValueError("unrecognized service") + match = re.compile(rf"^{PREFIX[service]} stage=([a-z_]+)$") + found = "" + any_log_lines = False + for line in lines: + any_log_lines = True + if len(line) > 256: + continue + category = match.fullmatch(line.rstrip("\r\n")) + if category and category.group(1) in STAGES[service]: + found = category.group(1) + if not found: + found = "unclassified_nonempty" if any_log_lines else "unclassified_empty" + return f"WINE11_LAYER_HIL service={service} cause={found}" + + +def main() -> int: + if len(sys.argv) != 2 or sys.argv[1] not in STAGES: + print("WINE11_LAYER_HIL cause=invalid_classifier_input", file=sys.stderr) + return 2 + print(classify(sys.argv[1], sys.stdin)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/ci/qualify-disposable-layers.sh b/scripts/ci/qualify-disposable-layers.sh new file mode 100755 index 00000000..059fb63e --- /dev/null +++ b/scripts/ci/qualify-disposable-layers.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# Public-runner-only $0 RDTE. Creates/deletes ONLY synthetic test volumes. +# No real user data, installer, credential, screenshot, raw stdout or image push. +set -euo pipefail +fail() { + printf 'LAYER_RDTE stage=%s\n' "$1" >&2 + exit 1 +} +[ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_EVENT_NAME:-}" = pull_request ] || + fail unqualified_venue +[[ "${GITHUB_RUN_ID:-}" =~ ^[0-9]+$ ]] && + [[ "${GITHUB_RUN_ATTEMPT:-}" =~ ^[0-9]+$ ]] || fail invalid_identity +prefix="winebot-ci-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" +volumes=() +cleanup() { + for v in "${volumes[@]}"; do + docker volume rm "$v" >/dev/null 2>&1 || true + done + docker image rm winebot-apps:fixture-v1 winebot-apps:fixture-v2 >/dev/null 2>&1 || true +} +trap cleanup EXIT +export WINEBOT_RUNTIME_IMAGE="debian@sha256:cedb1ef40439206b673ee8b33a46a03a0c9fa90bf3732f54704f99cb061d2c5a" +export WINEBOT_APP_BUNDLE_IMAGE="$WINEBOT_RUNTIME_IMAGE" +export WINEBOT_APP_VOLUME="$prefix-apps-v1" +export WINEBOT_PREFIX_VOLUME="$prefix-prefix" +export WINEBOT_HOME_VOLUME="$prefix-home" +export WINEBOT_CONFIG_VOLUME="$prefix-config" +export WINEBOT_USERDATA_VOLUME="$prefix-userdata" +export WINEBOT_ARTIFACT_VOLUME="$prefix-artifacts" +export WINEBOT_SHARED_VOLUME="$prefix-shared" +export WINEBOT_API_TOKEN=synthetic-ci-only-token +export WINEBOT_VNC_PASSWORD=synthetic-ci-only-password + +# Dry-run should fail with missing external volumes, never create state. +if bash scripts/layers/preflight.sh --check >/dev/null 2>&1; then fail missing_volume_not_rejected; fi +bash scripts/layers/preflight.sh --create >/dev/null 2>&1 || fail preflight_create +bash scripts/layers/preflight.sh --check >/dev/null 2>&1 || fail preflight_check +volumes=("$WINEBOT_APP_VOLUME" "$WINEBOT_PREFIX_VOLUME" "$WINEBOT_HOME_VOLUME" + "$WINEBOT_CONFIG_VOLUME" "$WINEBOT_USERDATA_VOLUME" "$WINEBOT_ARTIFACT_VOLUME" + "$WINEBOT_SHARED_VOLUME") +docker compose -f compose/layered.yml config --quiet >/dev/null 2>&1 || fail compose_invalid + +mkdir -p apps/ci-fixture +printf 'app-fixture-v1\n' > apps/ci-fixture/version.txt +docker build -f docker/app-bundle.Dockerfile -t winebot-apps:fixture-v1 . >/dev/null 2>&1 || + fail app_build_v1 +app_image=winebot-apps:fixture-v1 +# Seed only the dedicated applications volume; never mount personal state here. +docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges --memory 256m --pids-limit 64 \ + -v "$WINEBOT_APP_VOLUME:/winebot-apps" "$app_image" >/dev/null 2>&1 || + fail app_seed_v1 +docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges --memory 256m --pids-limit 64 \ + -v "$WINEBOT_APP_VOLUME:/winebot-apps" "$app_image" >/dev/null 2>&1 || + fail app_seed_idempotency + +# Fail closed on an unauthorized extra executable or symlink in an app volume. +docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges --entrypoint /bin/sh \ + -v "$WINEBOT_APP_VOLUME:/winebot-apps" "$app_image" -ec ' + printf "UNTRUSTED" >/winebot-apps/unexpected.exe + ' >/dev/null 2>&1 || fail tamper_fixture +if docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges -v "$WINEBOT_APP_VOLUME:/winebot-apps" \ + "$app_image" >/dev/null 2>&1; then + fail tamper_not_rejected +fi +docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges --entrypoint /bin/sh \ + -v "$WINEBOT_APP_VOLUME:/winebot-apps" "$app_image" -ec ' + rm /winebot-apps/unexpected.exe + ' >/dev/null 2>&1 || fail tamper_cleanup +docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges -v "$WINEBOT_APP_VOLUME:/winebot-apps" \ + "$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 \ + --security-opt no-new-privileges --memory 256m --pids-limit 64 \ + --entrypoint /bin/sh \ + -v "$WINEBOT_PREFIX_VOLUME:/state/prefix" \ + -v "$WINEBOT_HOME_VOLUME:/state/home" \ + -v "$WINEBOT_CONFIG_VOLUME:/state/config" \ + -v "$WINEBOT_USERDATA_VOLUME:/state/userdata" \ + -v "$WINEBOT_ARTIFACT_VOLUME:/state/artifacts" \ + -v "$WINEBOT_SHARED_VOLUME:/state/shared" \ + "$app_image" /usr/local/bin/winebot-prepare-state >/dev/null 2>&1 || + fail state_preparation + +# Test two fully disposable nonroot containers against the same external state. +docker run --rm --network none --read-only --user 1000:1000 --cap-drop ALL \ + --security-opt no-new-privileges --memory 256m --pids-limit 64 \ + --tmpfs /tmp:rw,nosuid,nodev,mode=1777 \ + --entrypoint /bin/sh \ + -v "$WINEBOT_APP_VOLUME:/apps:ro" -v "$WINEBOT_USERDATA_VOLUME:/userdata" \ + -v "$WINEBOT_CONFIG_VOLUME:/config" \ + "$app_image" -ec ' + grep -qx app-fixture-v1 /apps/ci-fixture/version.txt + printf "durable-user-file\n" >/userdata/proof.txt + printf "durable-setting\n" >/config/proof.txt + printf "ephemeral\n" >/tmp/not-retained + if touch /apps/ci-fixture/new.txt >/dev/null 2>&1; then exit 9; fi + if touch /opt/winebot/should-not-write >/dev/null 2>&1; then exit 10; fi + ' >/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 \ + --security-opt no-new-privileges --memory 256m --pids-limit 64 \ + --entrypoint /bin/sh \ + -v "$WINEBOT_PREFIX_VOLUME:/state/prefix" \ + -v "$WINEBOT_HOME_VOLUME:/state/home" \ + -v "$WINEBOT_CONFIG_VOLUME:/state/config" \ + -v "$WINEBOT_USERDATA_VOLUME:/state/userdata" \ + -v "$WINEBOT_ARTIFACT_VOLUME:/state/artifacts" \ + -v "$WINEBOT_SHARED_VOLUME:/state/shared" \ + "$app_image" /usr/local/bin/winebot-prepare-state >/dev/null 2>&1 || + fail state_preparation_idempotency + +docker run --rm --network none --read-only --user 1000:1000 --cap-drop ALL \ + --security-opt no-new-privileges --memory 256m --pids-limit 64 \ + --tmpfs /tmp:rw,nosuid,nodev,mode=1777 \ + --entrypoint /bin/sh \ + -v "$WINEBOT_APP_VOLUME:/apps:ro" -v "$WINEBOT_USERDATA_VOLUME:/userdata" \ + -v "$WINEBOT_CONFIG_VOLUME:/config" \ + "$app_image" -ec ' + grep -qx app-fixture-v1 /apps/ci-fixture/version.txt + grep -qx durable-user-file /userdata/proof.txt + grep -qx durable-setting /config/proof.txt + test ! -e /tmp/not-retained + ' >/dev/null 2>&1 || fail state_replay + +# A different app pack must refuse the old versioned volume without mutation. +printf 'app-fixture-v2\n' > apps/ci-fixture/version.txt +docker build -f docker/app-bundle.Dockerfile -t winebot-apps:fixture-v2 . >/dev/null 2>&1 || + fail app_build_v2 +if docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges -v "$WINEBOT_APP_VOLUME:/winebot-apps" \ + winebot-apps:fixture-v2 >/dev/null 2>&1; then + fail version_mismatch_not_rejected +fi +docker volume create "$prefix-apps-v2" >/dev/null 2>&1 || fail second_volume +volumes+=("$prefix-apps-v2") +docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges -v "$prefix-apps-v2:/winebot-apps" \ + winebot-apps:fixture-v2 >/dev/null 2>&1 || fail app_seed_v2 +docker run --rm --network none --read-only --user 1000:1000 --cap-drop ALL \ + --security-opt no-new-privileges --entrypoint /bin/sh \ + -v "$prefix-apps-v2:/apps:ro" -v "$WINEBOT_USERDATA_VOLUME:/userdata" \ + -v "$WINEBOT_CONFIG_VOLUME:/config" \ + winebot-apps:fixture-v2 -ec ' + grep -qx app-fixture-v2 /apps/ci-fixture/version.txt + grep -qx durable-user-file /userdata/proof.txt + grep -qx durable-setting /config/proof.txt + ' >/dev/null 2>&1 || fail app_upgrade_replay +echo 'LAYER_RDTE stage=pass' diff --git a/scripts/ci/qualify-volume-backup-restore.sh b/scripts/ci/qualify-volume-backup-restore.sh new file mode 100644 index 00000000..66d21cff --- /dev/null +++ b/scripts/ci/qualify-volume-backup-restore.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# Synthetic, disposable-only state backup + restore RDTE. +# NOT a production backup system. No user data, logs, image pushes or uploads. +set -euo pipefail +fail() { printf 'LAYER_BACKUP_RDTE stage=%s\n' "$1" >&2; exit 1; } +[ "${GITHUB_ACTIONS:-}" = true ] && + [ "${GITHUB_EVENT_NAME:-}" = pull_request ] || fail unqualified_venue +[[ "${GITHUB_RUN_ID:-}" =~ ^[0-9]+$ ]] && + [[ "${GITHUB_RUN_ATTEMPT:-}" =~ ^[0-9]+$ ]] || fail invalid_run +command -v docker >/dev/null 2>&1 || fail docker_unavailable +image='debian@sha256:cedb1ef40439206b673ee8b33a46a03a0c9fa90bf3732f54704f99cb061d2c5a' +prefix="winebot-recovery-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" +backup_volume="$prefix-snapshots" +if docker volume inspect "$backup_volume" >/dev/null 2>&1; then + fail volume_already_exists +fi +docker volume create "$backup_volume" >/dev/null 2>&1 || fail volume_create +volumes=("$backup_volume") +cleanup() { + for name in "${volumes[@]}"; do + docker volume rm "$name" >/dev/null 2>&1 || true + done +} +trap cleanup EXIT +# An isolated synthetic archive volume is initialized once; no host paths, +# temporary directories, or real user state cross this container boundary. +docker run --rm --network none --read-only --cap-drop ALL --cap-add CHOWN \ + --security-opt no-new-privileges --memory 128m --pids-limit 32 \ + --entrypoint /bin/sh -v "$backup_volume:/snapshots" "$image" -ec ' + test -z "$(find /snapshots -mindepth 1 -maxdepth 1 -print -quit)" + chown 1000:1000 /snapshots + ' >/dev/null 2>&1 || fail backup_volume_init +# App packs are separately immutable/versioned; six volumes contain user state. +roles=(prefix home config userdata artifacts shared) +for role in "${roles[@]}"; do + source_volume="$prefix-$role-src" + dest_volume="$prefix-$role-dst" + for name in "$source_volume" "$dest_volume"; do + if docker volume inspect "$name" >/dev/null 2>&1; then + fail volume_already_exists + fi + docker volume create "$name" >/dev/null 2>&1 || fail volume_create + volumes+=("$name") + done + # No preexisting content may be chowned or overwritten. + for name in "$source_volume" "$dest_volume"; do + docker run --rm --network none --read-only --cap-drop ALL --cap-add CHOWN \ + --security-opt no-new-privileges --memory 128m --pids-limit 32 \ + --entrypoint /bin/sh -v "$name:/state" "$image" -ec ' + test -z "$(find /state -mindepth 1 -maxdepth 1 -print -quit)" + chown 1000:1000 /state + ' >/dev/null 2>&1 || fail volume_init + done + docker run --rm --network none --read-only --user 1000:1000 --cap-drop ALL \ + --security-opt no-new-privileges --memory 128m --pids-limit 32 \ + --entrypoint /bin/sh -v "$source_volume:/state" "$image" -ec ' + mkdir /state/data + printf "synthetic-volume-replay\n" > /state/data/proof.txt + printf "synthetic-metadata\n" > /state/config.ini + ' >/dev/null 2>&1 || fail source_write + # Archive output never leaves this disposable runner. + docker run --rm --network none --read-only --user 1000:1000 \ + --cap-drop ALL --security-opt no-new-privileges --memory 128m \ + --pids-limit 32 --entrypoint /bin/sh \ + -v "$source_volume:/state:ro" -v "$backup_volume:/snapshots" \ + "$image" -ec 'tar -C /state -cf "/snapshots/$1.tar" .' sh "$role" \ + >/dev/null 2>&1 || fail snapshot + # Archive integrity and tamper-negative tests run only in a fresh, nonroot + # short-lived container against the disposable backup volume. + docker run --rm --network none --read-only --user 1000:1000 \ + --cap-drop ALL --security-opt no-new-privileges --memory 128m \ + --pids-limit 32 --entrypoint /bin/sh \ + -v "$backup_volume:/snapshots" "$image" -ec ' + cd /snapshots + sha256sum "$1.tar" > "$1.sha256" + sha256sum -c "$1.sha256" >/dev/null + cp "$1.tar" tampered.tar + printf tamper >> tampered.tar + expected="$(cut -d " " -f1 "$1.sha256")" + if printf "%s tampered.tar\n" "$expected" | sha256sum -c - >/dev/null 2>&1; then + exit 41 + fi + rm -f tampered.tar + ' sh "$role" >/dev/null 2>&1 || fail archive_integrity_negative + # Restore to a different EMPTY state volume with unprivileged user. + docker run --rm --network none --read-only --user 1000:1000 \ + --cap-drop ALL --security-opt no-new-privileges --memory 128m \ + --pids-limit 32 --entrypoint /bin/sh \ + -v "$dest_volume:/state" -v "$backup_volume:/snapshots:ro" \ + "$image" -ec ' + test -z "$(find /state -mindepth 1 -maxdepth 1 -print -quit)" + tar --no-same-owner --no-same-permissions -C /state -xf "/snapshots/$1.tar" + ' sh "$role" >/dev/null 2>&1 || fail restore + # A new nonroot disposable process reads exactly restored synthetic state. + docker run --rm --network none --read-only --user 1000:1000 --cap-drop ALL \ + --security-opt no-new-privileges --memory 128m --pids-limit 32 \ + --entrypoint /bin/sh -v "$dest_volume:/state:ro" "$image" -ec ' + test "$(id -u)" -eq 1000 + test "$(stat -c %u /state)" -eq 1000 + test "$(cat /state/data/proof.txt)" = synthetic-volume-replay + test "$(cat /state/config.ini)" = synthetic-metadata + ' >/dev/null 2>&1 || fail restored_replay +done +echo 'LAYER_BACKUP_RDTE stage=synthetic_six_volume_replay_passed' diff --git a/scripts/ci/qualify-wine11-layered.sh b/scripts/ci/qualify-wine11-layered.sh new file mode 100755 index 00000000..77c62898 --- /dev/null +++ b/scripts/ci/qualify-wine11-layered.sh @@ -0,0 +1,288 @@ +#!/usr/bin/env bash +# Disposable composite HIL for pinned Wine11 R018 source and layer branch. +# This intentionally does not claim that either PR head alone is release-ready. +set -euo pipefail +fail() { + printf 'WINE11_LAYER_HIL stage=%s\n' "$1" >&2 + exit 1 +} +[ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_EVENT_NAME:-}" = pull_request ] || + fail unqualified_venue +[[ "${GITHUB_RUN_ID:-}" =~ ^[0-9]+$ ]] && + [[ "${GITHUB_RUN_ATTEMPT:-}" =~ ^[0-9]+$ ]] || fail invalid_runner +[ -f ../wine11-candidate/docker/base.Dockerfile ] && + [ -f ../wine11-candidate/scripts/init/20-setup-wine.sh ] || + fail source_unavailable + +prefix="winebot-hil-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" +export WINEBOT_APP_VOLUME="$prefix-apps" +export WINEBOT_PREFIX_VOLUME="$prefix-prefix" +export WINEBOT_HOME_VOLUME="$prefix-home" +export WINEBOT_CONFIG_VOLUME="$prefix-config" +export WINEBOT_USERDATA_VOLUME="$prefix-userdata" +export WINEBOT_ARTIFACT_VOLUME="$prefix-artifacts" +export WINEBOT_SHARED_VOLUME="$prefix-shared" +export WINEBOT_API_TOKEN=synthetic-hil-local-only-token +export WINEBOT_VNC_PASSWORD=synthetic-hil-local-only-password +volumes=("$WINEBOT_APP_VOLUME" "$WINEBOT_PREFIX_VOLUME" "$WINEBOT_HOME_VOLUME" + "$WINEBOT_CONFIG_VOLUME" "$WINEBOT_USERDATA_VOLUME" "$WINEBOT_ARTIFACT_VOLUME" + "$WINEBOT_SHARED_VOLUME") +cleanup() { + docker compose -f compose/layered.yml down --remove-orphans >/dev/null 2>&1 || true + for volume in "${volumes[@]}"; do + docker volume rm "$volume" >/dev/null 2>&1 || true + done + docker image rm winebot:layered-hil winebot-base:layered-hil winebot-apps:layered-hil >/dev/null 2>&1 || true +} +trap cleanup EXIT +for volume in "${volumes[@]}"; do + docker volume create "$volume" >/dev/null 2>&1 || fail create_synthetic_volume +done + +# The base and Wine init come exclusively from qualified Wine11 exact SHA. +# This is a declared composite experiment, never source-exact promotion. +docker build --file ../wine11-candidate/docker/base.Dockerfile --target final \ + --tag winebot-base:layered-hil ../wine11-candidate >/dev/null 2>&1 || + fail wine11_base_build +cp ../wine11-candidate/scripts/init/20-setup-wine.sh scripts/init/20-setup-wine.sh +docker build --file docker/Dockerfile --target intent-rel \ + --build-arg BASE_IMAGE=winebot-base:layered-hil \ + --build-arg BUILD_INTENT=rel \ + --tag winebot:layered-hil . >/dev/null 2>&1 || fail layered_runtime_build +docker build --file docker/app-bundle.Dockerfile \ + --tag winebot-apps:layered-hil . >/dev/null 2>&1 || fail app_pack_build + +# Use immutable local OCI content IDs, not floating tags, in this HIL only. +export WINEBOT_RUNTIME_IMAGE="$(docker image inspect --format '{{.Id}}' winebot:layered-hil)" +export WINEBOT_APP_BUNDLE_IMAGE="$(docker image inspect --format '{{.Id}}' winebot-apps:layered-hil)" +[[ "$WINEBOT_RUNTIME_IMAGE" =~ ^sha256:[0-9a-f]{64}$ ]] && + [[ "$WINEBOT_APP_BUNDLE_IMAGE" =~ ^sha256:[0-9a-f]{64}$ ]] || + fail image_identity_invalid +docker compose -f compose/layered.yml config --quiet >/dev/null 2>&1 || + fail compose_invalid +# Qualify the OCI image's actual script contract without mutating external volumes. +# A missing script or invalid local image reference must fail before Compose. +docker run --rm --network none --read-only --cap-drop ALL \ + --security-opt no-new-privileges --entrypoint /bin/sh \ + "$WINEBOT_APP_BUNDLE_IMAGE" -ec ' + test -r /usr/local/bin/winebot-seed-apps + test -r /usr/local/bin/winebot-prepare-state + test -s /opt/winebot/app-manifest.sha256 + ' >/dev/null 2>&1 || fail app_bundle_script_contract +# Project container state and fixed-domain diagnostics only. Never print raw +# Compose logs, environment variables, container IDs, mounts or user paths. +classify_startup() { + local service cid state exit_code health expected_image actual_image image_match entrypoint actual_entrypoint expected_entrypoint + for service in app-seed state-init winebot-interactive; do + cid="$(docker compose -f compose/layered.yml ps -a -q "$service" 2>/dev/null || true)" + if [ -z "$cid" ]; then + printf 'WINE11_LAYER_HIL service=%s state=absent\n' "$service" >&2 + continue + fi + state="$(docker inspect --format '{{.State.Status}}' "$cid" 2>/dev/null || true)" + exit_code="$(docker inspect --format '{{.State.ExitCode}}' "$cid" 2>/dev/null || true)" + health="$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$cid" 2>/dev/null || true)" + case "$state" in created|running|restarting|exited|dead|paused) ;; *) state=unknown ;; esac + case "$health" in healthy|unhealthy|starting|none) ;; *) health=unknown ;; esac + [[ "$exit_code" =~ ^[0-9]{1,3}$ ]] || exit_code=unknown + printf 'WINE11_LAYER_HIL service=%s state=%s exit=%s health=%s\n' "$service" "$state" "$exit_code" "$health" >&2 + # Print only source-exact equality verdicts. Raw inspect image IDs, + # entrypoint paths, container IDs, and Docker error strings stay private. + expected_image="$WINEBOT_APP_BUNDLE_IMAGE" + [ "$service" = winebot-interactive ] && expected_image="$WINEBOT_RUNTIME_IMAGE" + actual_image="$(docker inspect --format '{{.Image}}' "$cid" 2>/dev/null || true)" + image_match=no + [ "$actual_image" = "$expected_image" ] && image_match=yes + entrypoint=not_applicable + case "$service" in + app-seed|state-init) + expected_entrypoint='["/bin/sh","/usr/local/bin/winebot-seed-apps"]' + [ "$service" = state-init ] && + expected_entrypoint='["/bin/sh","/usr/local/bin/winebot-prepare-state"]' + actual_entrypoint="$(docker inspect --format '{{json .Config.Entrypoint}}' "$cid" 2>/dev/null || true)" + entrypoint=unexpected + [ "$actual_entrypoint" = "$expected_entrypoint" ] && entrypoint=expected + ;; + esac + printf 'WINE11_LAYER_HIL service=%s image_match=%s entrypoint=%s\n' "$service" "$image_match" "$entrypoint" >&2 + # The scripts emit fixed-domain markers on failure. Process container logs + # privately; the classifier emits ONLY one enumerated category, not raw text. + case "$service" in + app-seed|state-init) + docker logs --tail 80 "$cid" 2>&1 | + python3 scripts/ci/classify-layer-init-logs.py "$service" >&2 || true + ;; + esac + done +} +if ! docker compose -f compose/layered.yml up --no-build -d winebot-interactive >/dev/null 2>&1; then + classify_startup + fail startup +fi + +wait_health() { + local attempt cid status + for attempt in $(seq 1 90); do + cid="$(docker compose -f compose/layered.yml ps -q winebot-interactive 2>/dev/null || true)" + if [ -n "$cid" ]; then + status="$(docker inspect --format '{{.State.Health.Status}}' "$cid" 2>/dev/null || true)" + if [ "$status" = healthy ]; then return 0; fi + fi + sleep 2 + done + return 1 +} +# A failed real health gate must remain a failure. Classify only immutable +# state/enumerated probes, without leaking runtime logs, tokens, host paths or +# Docker inspection payloads into the public runner stream. +classify_health_failure() { + local cid state health + cid="$(docker compose -f compose/layered.yml ps -a -q winebot-interactive 2>/dev/null || true)" + if [ -z "$cid" ]; then + echo 'WINE11_LAYER_HEALTH state=absent' + return + fi + state="$(docker inspect --format '{{.State.Status}}' "$cid" 2>/dev/null || true)" + health="$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$cid" 2>/dev/null || true)" + case "$state" in created|running|restarting|exited|dead|paused) ;; *) state=unknown ;; esac + case "$health" in healthy|unhealthy|starting|none) ;; *) health=unknown ;; esac + printf 'WINE11_LAYER_HEALTH state=%s health=%s\n' "$state" "$health" + # Existing allowlist-only classifier consumes stdout/stderr privately. + docker logs --tail 200 "$cid" 2>&1 | + python3 scripts/ci/classify-startup-logs.py || true + [ "$state" = running ] || return + if docker exec --user 1000 "$cid" test -s /tmp/winebot_api_token >/dev/null 2>&1; then + echo 'WINE11_LAYER_HEALTH token_file=present' + else + echo 'WINE11_LAYER_HEALTH token_file=missing' + fi + if docker exec --user 1000 "$cid" test -s /wineprefix/system.reg >/dev/null 2>&1; then + echo 'WINE11_LAYER_HEALTH registry=present' + else + echo 'WINE11_LAYER_HEALTH registry=missing' + fi + if docker exec --user 1000 "$cid" /bin/sh -c ' + token="$(cat /tmp/winebot_api_token 2>/dev/null || true)" + [ -n "$token" ] || exit 1 + curl --max-time 6 -fsS -H "X-API-Key: $token" http://127.0.0.1:8000/health >/dev/null 2>&1 + ' >/dev/null 2>&1; then + echo 'WINE11_LAYER_HEALTH authorized_api=pass' + else + echo 'WINE11_LAYER_HEALTH authorized_api=fail' + fi +} +if ! wait_health; then + classify_health_failure + fail health_initial +fi +docker compose -f compose/layered.yml exec -T winebot-interactive wine --version \ + 2>/dev/null | grep -Eq '^wine-11([.]|$)' || fail wine11_version + +# Verify ownership, persistent user state and immutable application mount. +docker compose -f compose/layered.yml exec -T winebot-interactive /bin/sh -ec ' + [ "$(id -u)" -eq 1000 ] || exit 12 + printf "durable-user\n" > /userdata/hil-proof + printf "durable-config\n" > /config/hil-proof + printf "durable-home\n" > /home/winebot/hil-proof + printf "durable-wineprefix\n" > /wineprefix/hil-proof + printf "durable-evidence\n" > /artifacts/hil-proof + test -s /apps/.winebot-app-content-sha256 + if touch /apps/unauthorized-executable.exe >/dev/null 2>&1; then exit 13; fi + if touch /opt/winebot/unauthorized-root-write >/dev/null 2>&1; then exit 14; fi +' >/dev/null 2>&1 || fail state_write_or_readonly + +# 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 \ + -e MAX_LOG_MB=1024 -e MAX_SESSION_MB=8192 \ + -e MAX_PID1_RSS_MB=2048 \ + winebot-interactive /scripts/diagnostics/soak-resource-bounds.sh nightly \ + >/dev/null 2>&1 || fail resource_sample + +# Qualify the same exact layered service and persistent mounts through the +# full 55-minute sustained resource gate, not merely the independent #150 +# mutable-runtime qualifier. Raw output stays on this disposable public runner. +long_soak_log="$(mktemp)" +if ! docker compose -f compose/layered.yml exec -T --user 1000 \ + -e DURATION_SECONDS=3300 -e INTERVAL_SECONDS=30 \ + -e MAX_LOG_MB=1024 -e MAX_SESSION_MB=8192 \ + -e MAX_PID1_RSS_MB=2048 \ + winebot-interactive /scripts/diagnostics/soak-resource-bounds.sh nightly \ + >"$long_soak_log" 2>&1; then + python3 ../wine11-candidate/scripts/ci/classify-wine11-soak.py "$long_soak_log" || + echo 'WINE11_SOAK_DIAGNOSTIC stage=unknown' + rm -f "$long_soak_log" + fail layered_long_soak +fi +rm -f "$long_soak_log" +if ! wait_health; then + classify_health_failure + fail layered_post_soak_health +fi +echo 'WINE11_LAYER_HIL stage=long_soak_passed' + +# Use the running layered service for bounded supervisor recovery, not a +# production host process. Do not reveal PID values or any application logs. +read_openbox_pid() { + docker compose -f compose/layered.yml exec -T --user 1000 \ + winebot-interactive pgrep -o -x openbox 2>/dev/null || true +} +openbox_before="$(read_openbox_pid)" +[[ "$openbox_before" =~ ^[0-9]+$ ]] || fail layered_openbox_missing +if ! docker compose -f compose/layered.yml exec -T --user 1000 \ + winebot-interactive pkill -x openbox >/dev/null 2>&1; then + fail layered_openbox_injection +fi +openbox_deadline=$((SECONDS + 75)) +openbox_recovered=0 +while ((SECONDS < openbox_deadline)); do + openbox_after="$(read_openbox_pid)" + if [[ "$openbox_after" =~ ^[0-9]+$ ]] && [ "$openbox_after" != "$openbox_before" ]; then + openbox_recovered=1 + break + fi + sleep 2 +done +[ "$openbox_recovered" = 1 ] || fail layered_openbox_recovery_timeout +if ! wait_health; then + classify_health_failure + fail layered_openbox_health +fi +echo 'WINE11_LAYER_HIL stage=openbox_recovery_passed' + +# Destroy/recreate only disposable runtime containers; never remove state. +docker compose -f compose/layered.yml up --no-build --force-recreate -d winebot-interactive \ + >/dev/null 2>&1 || fail runtime_recreate +wait_health || fail health_recreate +docker compose -f compose/layered.yml exec -T winebot-interactive /bin/sh -ec ' + grep -qx durable-user /userdata/hil-proof + grep -qx durable-config /config/hil-proof + grep -qx durable-home /home/winebot/hil-proof + grep -qx durable-wineprefix /wineprefix/hil-proof + grep -qx durable-evidence /artifacts/hil-proof + test -s /apps/.winebot-app-content-sha256 +' >/dev/null 2>&1 || fail state_replay + +# Fail-stop only the disposable runtime process. External app/state volumes +# must survive a forced SIGKILL, with no Docker volume deletion or promotion. +docker compose -f compose/layered.yml kill -s SIGKILL winebot-interactive \ + >/dev/null 2>&1 || fail fault_signal +fault_cid="$(docker compose -f compose/layered.yml ps -a -q winebot-interactive 2>/dev/null || true)" +[ -n "$fault_cid" ] || fail fault_container_missing +fault_exit="$(docker inspect --format '{{.State.ExitCode}}' "$fault_cid" 2>/dev/null || true)" +[ "$fault_exit" = 137 ] || fail fault_exit_not_sigkill +docker compose -f compose/layered.yml up --no-build --force-recreate -d winebot-interactive \ + >/dev/null 2>&1 || fail fault_recreate +if ! wait_health; then + classify_health_failure + fail fault_health +fi +docker compose -f compose/layered.yml exec -T winebot-interactive /bin/sh -ec ' + grep -qx durable-user /userdata/hil-proof + grep -qx durable-config /config/hil-proof + grep -qx durable-home /home/winebot/hil-proof + grep -qx durable-wineprefix /wineprefix/hil-proof + grep -qx durable-evidence /artifacts/hil-proof + test -s /apps/.winebot-app-content-sha256 +' >/dev/null 2>&1 || fail fault_state_replay +echo 'WINE11_LAYER_HIL stage=pass' diff --git a/scripts/ci/resolve-conformance-units.py b/scripts/ci/resolve-conformance-units.py new file mode 100644 index 00000000..7c4c3415 --- /dev/null +++ b/scripts/ci/resolve-conformance-units.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Narrow test-manifest conflict resolver for disposable PR123+PR154 bake-off. + +Do not generalize to production merges. Only a simultaneous append to the +explicit unit-test manifest is resolvable here; all other conflicts fail closed. +""" +import re +import subprocess +import sys +from pathlib import Path + +PATH = "scripts/ci/test.sh" +TEST_LINE = re.compile(r"^ (tests/test_[a-z0-9_]+\.py)(?: \\)?$") + + +def git(*args: str) -> str: + return subprocess.check_output(["git", *args], text=True) + + +def parse(source: str) -> tuple[str, list[str]]: + lines = source.splitlines() + i = next((n for n, line in enumerate(lines) if TEST_LINE.fullmatch(line)), -1) + if i < 0: + raise ValueError("unit manifest lacks test entries") + prefix = "\n".join(lines[:i]) + "\n" + tests = [] + for line in lines[i:]: + match = TEST_LINE.fullmatch(line) + if not match: + raise ValueError("unexpected content in unit-test list") + tests.append(match.group(1)) + if len(set(tests)) != len(tests): + raise ValueError("duplicate unit test") + return prefix, tests + + +def main() -> int: + try: + conflicts = git("diff", "--name-only", "--diff-filter=U").splitlines() + if conflicts != [PATH]: + raise ValueError("unexpected conflict set") + ours = git("show", ":2:" + PATH) + theirs = git("show", ":3:" + PATH) + base = git("show", ":1:" + PATH) + pre_ours, tests_ours = parse(ours) + pre_theirs, tests_theirs = parse(theirs) + pre_base, tests_base = parse(base) + if pre_ours != pre_theirs or pre_ours != pre_base: + raise ValueError("non-manifest content diverged") + if set(tests_base) - set(tests_ours) or set(tests_base) - set(tests_theirs): + raise ValueError("test removed by a candidate") + if set(tests_ours) - set(tests_base) != {"tests/test_disposable_layer_contract.py"}: + raise ValueError("unexpected layered source tests") + integrated = tests_theirs + [s for s in tests_ours if s not in tests_theirs] + if set(integrated) != set(tests_ours) | set(tests_theirs): + raise ValueError("test union lost coverage") + result = pre_theirs + " \\\n".join(" " + s for s in integrated) + "\n" + Path(PATH).write_text(result, encoding="utf-8") + subprocess.check_call(["git", "add", "--", PATH]) + if git("diff", "--name-only", "--diff-filter=U").strip(): + raise ValueError("merge still unmerged") + except (OSError, ValueError, subprocess.CalledProcessError): + print("LAYERED_CONFORMANCE_RDTE stage=source_merge_conflict", file=sys.stderr) + return 1 + print("LAYERED_CONFORMANCE_RDTE stage=unit_test_union_resolved") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index b4931410..c339dc40 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -29,4 +29,5 @@ pytest \ tests/test_ci_unit_isolation.py \ tests/test_winepath_startup_retry.py \ tests/test_wininspect_error_redaction.py \ - tests/test_health_system_memory.py + tests/test_health_system_memory.py \ + tests/test_disposable_layer_contract.py diff --git a/scripts/layers/preflight.sh b/scripts/layers/preflight.sh new file mode 100755 index 00000000..e8019bf1 --- /dev/null +++ b/scripts/layers/preflight.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Validate or initialize external volumes; never delete user state. +set -euo pipefail +case "${1:-}" in + --check|--create) operation="$1" ;; + *) echo 'LAYERED_PREFLIGHT stage=invalid_operation' >&2; exit 2 ;; +esac + +for image_var in WINEBOT_RUNTIME_IMAGE WINEBOT_APP_BUNDLE_IMAGE; do + image="${!image_var:-}" + if [[ ! "$image" =~ ^[^[:space:]]+@sha256:[0-9a-f]{64}$ ]]; then + echo 'LAYERED_PREFLIGHT stage=unpinned_image' >&2 + exit 2 + fi +done + +variables=( + WINEBOT_APP_VOLUME WINEBOT_PREFIX_VOLUME WINEBOT_HOME_VOLUME + WINEBOT_CONFIG_VOLUME WINEBOT_USERDATA_VOLUME WINEBOT_ARTIFACT_VOLUME + WINEBOT_SHARED_VOLUME +) +declare -A seen=() +for variable in "${variables[@]}"; do + value="${!variable:-}" + if [[ ! "$value" =~ ^winebot-[a-z0-9][a-z0-9-]{1,70}$ ]] || [[ -n "${seen[$value]:-}" ]]; then + echo 'LAYERED_PREFLIGHT stage=invalid_volume_namespace' >&2 + exit 2 + fi + seen[$value]=1 +done + +if ! command -v docker >/dev/null 2>&1; then + echo 'LAYERED_PREFLIGHT stage=docker_unavailable' >&2 + exit 2 +fi +for variable in "${variables[@]}"; do + volume="${!variable}" + if docker volume inspect "$volume" >/dev/null 2>&1; then continue; fi + if [ "$operation" = --check ]; then + echo 'LAYERED_PREFLIGHT stage=volume_missing' >&2 + exit 1 + fi + docker volume create "$volume" >/dev/null 2>&1 || { + echo 'LAYERED_PREFLIGHT stage=create_failed' >&2 + exit 1 + } +done +echo 'LAYERED_PREFLIGHT stage=ready' diff --git a/scripts/layers/prepare-state.sh b/scripts/layers/prepare-state.sh new file mode 100755 index 00000000..fe806a20 --- /dev/null +++ b/scripts/layers/prepare-state.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# Run once per deployment before a non-root WineBot runtime starts. +# Only adjust top-level volume ownership: never traverse, wipe, or migrate +# user files. This is a disposable, network-off bootstrap process. +set -eu +fail() { + printf 'STATE_LAYER_DIAGNOSTIC stage=%s\n' "$1" >&2 + exit 1 +} +[ "$(id -u)" = 0 ] || fail invalid_identity +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 + case "$owner" in + 1000:1000) + # Idempotent restart: CAP_CHOWN-only root is NOT permitted to chmod a + # user-owned directory. Verify the owner has rwx; never modify it. + mode="$(stat -c '%A' "$dir" 2>/dev/null)" || fail mount_unavailable + case "$mode" in + drwx*) ;; + *) fail permissions_failed ;; + esac + ;; + 0:0) + # First deployment only. chmod while root still owns the directory; + # afterward CAP_CHOWN alone cannot chmod the now-user-owned path. + chmod u+rwx "$dir" >/dev/null 2>&1 || fail permissions_failed + chown 1000:1000 "$dir" >/dev/null 2>&1 || fail ownership_failed + ;; + *) + # Existing foreign-owner state is neither ours to migrate nor erase. + fail unexpected_ownership + ;; + esac +done +echo 'STATE_LAYER_DIAGNOSTIC stage=ready' diff --git a/scripts/layers/seed-apps.sh b/scripts/layers/seed-apps.sh new file mode 100755 index 00000000..3c24c5ab --- /dev/null +++ b/scripts/layers/seed-apps.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# One-shot, offline copier from immutable OCI app bundle to a versioned volume. +# Never upgrade or merge into an existing version: fail closed instead. +set -eu +umask 022 +source_dir=/opt/winebot/app-payload +volume=/winebot-apps +manifest=/opt/winebot/app-manifest.sha256 +stamp="$volume/.winebot-app-content-sha256" +lock="$volume/.winebot-app-seeding" + +verify_inventory() { + # Valid hashes alone are insufficient: reject any unexpected file/symlink + # that could otherwise be executable by the next disposable runtime. + expected="$(wc -l < "$manifest" | tr -d '[:space:]')" + actual="$(find "$volume" -type f ! -path "$stamp" | wc -l | tr -d '[:space:]')" + [ "$actual" = "$expected" ] || fail unexpected_files + [ -z "$(find "$volume" -type l -print -quit)" ] || fail unexpected_symlink + (cd "$volume" && sha256sum -c "$manifest" >/dev/null 2>&1) || + fail integrity_mismatch +} + + +fail() { + printf 'APP_LAYER_DIAGNOSTIC stage=%s\n' "$1" >&2 + exit 1 +} + +[ -d "$source_dir" ] && [ -d "$volume" ] && [ -s "$manifest" ] || fail unavailable +[ ! -L "$volume" ] && [ ! -L "$stamp" ] || fail invalid_mount +digest="$(sha256sum "$manifest" | cut -c 1-64)" +case "$digest" in *[!0-9a-f]*|'') fail invalid_manifest;; esac +if [ -f "$stamp" ]; then + [ "$(cat "$stamp")" = "$digest" ] || fail version_mismatch + verify_inventory + echo 'APP_LAYER_DIAGNOSTIC stage=existing_verified' + exit 0 +fi +[ -z "$(find "$volume" -mindepth 1 -maxdepth 1 -print -quit)" ] || fail incomplete_volume +# A failed lock creation can mean a competing seeder OR an unwritable +# volume. Keep those causes distinct; never overwrite an existing volume. +if ! mkdir "$lock" >/dev/null 2>&1; then + [ -e "$lock" ] && fail concurrent_init + fail permissions_failed +fi +cp -a "$source_dir"/. "$volume"/ >/dev/null 2>&1 || fail copy_failed +verify_inventory +rmdir "$lock" >/dev/null 2>&1 || fail incomplete_volume +printf '%s\n' "$digest" > "$stamp.tmp" || fail stamp_failed +mv "$stamp.tmp" "$stamp" || fail stamp_failed +echo 'APP_LAYER_DIAGNOSTIC stage=created_verified' diff --git a/tests/test_disposable_layer_contract.py b/tests/test_disposable_layer_contract.py new file mode 100644 index 00000000..ba6ca8e8 --- /dev/null +++ b/tests/test_disposable_layer_contract.py @@ -0,0 +1,182 @@ +"""Source-contract tests for opt-in disposable runtime/app/state layout. + +These tests use only stdlib and deliberately do not provision real users. +An independent public Actions job performs disposable Docker replay. +""" +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +class DisposableAppBundleSourceTests(unittest.TestCase): + def test_builder_requires_offline_manifest_and_rejects_symlinks(self): + src = (ROOT / "docker/app-bundle.Dockerfile").read_text(encoding="utf-8") + self.assertIn("FROM ${APP_PACK_BUILDER_IMAGE}", src) + self.assertIn("debian@sha256:", src) + self.assertIn("find /opt/winebot/app-payload -type l", src) + self.assertIn("app-manifest.sha256", src) + self.assertIn("COPY apps/", src) + for forbidden in ("apt-get", "curl ", "wget ", "ADD https://", "docker push"): + self.assertNotIn(forbidden, src) + + def test_seed_is_idempotent_and_never_replaces_existing_apps(self): + src = (ROOT / "scripts/layers/seed-apps.sh").read_text(encoding="utf-8") + for marker in ("stage=existing_verified", "stage=created_verified", + "version_mismatch", "integrity_mismatch", + "incomplete_volume", "sha256sum -c", "set -eu"): + self.assertIn(marker, src) + self.assertLess(src.index('if [ -f "$stamp" ]; then'), + src.index('cp -a "$source_dir"/.')) + self.assertIn("fail unexpected_files", src) + self.assertIn("fail unexpected_symlink", src) + self.assertIn('mkdir "$lock"', src) + self.assertIn('fail concurrent_init', src) + self.assertIn('fail permissions_failed', src) + self.assertIn('[ -e "$lock" ] && fail concurrent_init', src) + self.assertLess(src.index('verify_inventory() {'), + src.index('if [ -f "$stamp" ]; then')) + for forbidden in ("rm -rf", "curl ", "wget ", "docker push"): + self.assertNotIn(forbidden, src) + + + def test_external_volumes_and_disposable_runtime_are_enforced(self): + source = (ROOT / "compose/layered.yml").read_text(encoding="utf-8") + self.assertEqual(source.count("external: true"), 7) + self.assertIn("condition: service_completed_successfully", source) + self.assertIn("read_only: true", source) + self.assertIn("user: \"1000:1000\"", source) + self.assertIn("source: app-store", source) + self.assertIn("target: /apps", source) + self.assertIn("read_only: true", source) + # Every runtime state/app volume refuses Docker image copy-up, or + # Compose may initialize/chown it before one-shot seed/state services. + self.assertEqual(source.count("nocopy: true"), 7) + self.assertIn("WINEBOT_STATE_MODEL: layered", source) + self.assertIn("WINEBOT_INPUT_TRACE_WINDOWS: \"1\"", source) + self.assertIn("127.0.0.1:8000:8000", source) + self.assertNotIn(" build:", source) + self.assertNotIn("actions/upload-artifact@", source) + + def test_layered_api_is_enabled_without_unauthenticated_fallback(self): + compose = (ROOT / "compose/layered.yml").read_text(encoding="utf-8") + start = (ROOT / "scripts/init/30-start-services.sh").read_text( + encoding="utf-8" + ) + self.assertIn('if [ "${ENABLE_API:-0}" = "1" ]; then', start) + self.assertIn(' ENABLE_API: "1"', compose) + self.assertIn("API_TOKEN: ${WINEBOT_API_TOKEN:", compose) + self.assertIn('TOKENS="$$(cat /tmp/winebot_api_token', compose) + self.assertIn('X-API-Key: $$TOKEN', compose) + self.assertIn( + 'curl -fsS -H "X-API-Key: $$TOKEN" http://127.0.0.1:8000/health', + compose, + ) + self.assertNotIn('curl -fsS http://127.0.0.1:8000/health', compose) + self.assertNotIn('curl -fsS http://localhost:8000/health', compose) + + def test_layered_extended_soak_and_window_manager_fault_are_fail_closed(self): + script = (ROOT / "scripts/ci/qualify-wine11-layered.sh").read_text( + encoding="utf-8" + ) + workflow = ( + ROOT / ".github/workflows/wine11-disposable-layer-hil.yml" + ).read_text(encoding="utf-8") + expected = ( + "DURATION_SECONDS=3300", + "INTERVAL_SECONDS=30", + "MAX_LOG_MB=1024", + "MAX_SESSION_MB=8192", + "MAX_PID1_RSS_MB=2048", + "classify-wine11-soak.py", + "fail layered_long_soak", + "fail layered_post_soak_health", + "fail layered_openbox_missing", + "fail layered_openbox_injection", + "fail layered_openbox_recovery_timeout", + "fail layered_openbox_health", + "fail fault_state_replay", + ) + for marker in expected: + self.assertIn(marker, script) + self.assertLess( + script.index("DURATION_SECONDS=90"), + script.index("DURATION_SECONDS=3300"), + ) + self.assertLess( + script.index("DURATION_SECONDS=3300"), + script.index("pkill -x openbox"), + ) + self.assertLess( + script.index("pkill -x openbox"), + script.index("kill -s SIGKILL winebot-interactive"), + ) + self.assertIn(' timeout-minutes: 115', workflow) + self.assertIn('ref: 8c5ed8019a3518cf534b158662755172bfce7c59', workflow) + self.assertNotIn("actions/upload-artifact@", workflow) + self.assertIn('>"$long_soak_log" 2>&1', script) + self.assertIn('rm -f "$long_soak_log"', script) + + def test_layered_entrypoint_fail_closed_without_legacy_impact(self): + source = (ROOT / "docker/entrypoint.sh").read_text(encoding="utf-8") + self.assertIn('WINEBOT_STATE_MODEL:-legacy', source) + self.assertIn("stage=runtime_install_forbidden", source) + self.assertIn("stage=persistent_mount_unavailable", source) + self.assertIn("stage=app_mount_invalid", source) + self.assertIn('WINEBOT_CONFIG_FILE="/config/winebot.env"', source) + self.assertIn('WINEBOT_CONFIG_FILE="/wineprefix/winebot.env"', source) + + def test_state_preparer_does_not_recurse_or_remove_user_data(self): + source = (ROOT / "scripts/layers/prepare-state.sh").read_text(encoding="utf-8") + self.assertIn("chown 1000:1000", source) + self.assertNotIn("chown -R", source) + self.assertNotIn("rm -rf", source) + self.assertLess(source.index('chmod u+rwx "$dir"'), + source.index('chown 1000:1000 "$dir"')) + + def test_deployment_preflight_never_prunes_external_volumes(self): + src = (ROOT / "scripts/layers/preflight.sh").read_text(encoding="utf-8") + self.assertIn("docker volume inspect", src) + self.assertIn("docker volume create", src) + self.assertIn("stage=unpinned_image", src) + self.assertNotIn("docker volume rm", src) + self.assertNotIn("docker system prune", src) + + def test_tool_builder_uses_immutable_image_digest(self): + src = (ROOT / "docker/Dockerfile").read_text(encoding="utf-8") + self.assertIn("TOOL_BUILDER_BASE_IMAGE=debian@sha256:", src) + self.assertIn("FROM ${TOOL_BUILDER_BASE_IMAGE} AS tool-base", src) + self.assertNotIn("FROM debian:trixie-slim AS tool-base", src) + + def test_actual_unit_manifest_includes_layer_contract(self): + src = (ROOT / "scripts/ci/test.sh").read_text(encoding="utf-8") + self.assertIn("tests/test_disposable_layer_contract.py", src) + + + def test_wine11_hil_is_public_disposable_and_provenance_bound(self): + wf = (ROOT / ".github/workflows/wine11-disposable-layer-hil.yml").read_text( + encoding="utf-8" + ) + script = (ROOT / "scripts/ci/qualify-wine11-layered.sh").read_text( + encoding="utf-8" + ) + self.assertIn("runs-on: ubuntu-24.04", wf) + self.assertIn("8c5ed8019a3518cf534b158662755172bfce7c59", wf) + self.assertIn("persist-credentials: false", wf) + self.assertIn("DOCKER_BUILD_RECORD_UPLOAD: 'false'", wf) + self.assertNotIn("actions/upload-artifact@", wf) + self.assertNotIn("push: true", wf) + self.assertIn("fail health_recreate", script) + self.assertIn("fail state_replay", script) + self.assertIn("kill -s SIGKILL winebot-interactive", script) + self.assertIn("fault_exit_not_sigkill", script) + self.assertIn("fail fault_health", script) + self.assertIn("fail fault_state_replay", script) + self.assertIn("DURATION_SECONDS=90", script) + self.assertIn("--read-only", (ROOT / "compose/layered.yml").read_text( + encoding="utf-8" + ).replace("read_only: true", "--read-only")) + self.assertNotIn("docker volume prune", script) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_layer_init_diagnostics.py b/tests/test_layer_init_diagnostics.py new file mode 100644 index 00000000..410b6bcc --- /dev/null +++ b/tests/test_layer_init_diagnostics.py @@ -0,0 +1,89 @@ +"""Zero-secret regression tests for public composite startup classification.""" +import importlib.util +import io +import unittest +from pathlib import Path + +MODULE = Path(__file__).resolve().parents[1] / "scripts/ci/classify-layer-init-logs.py" +spec = importlib.util.spec_from_file_location("layer_init", MODULE) +layer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(layer) + + +class LayerDiagnosticsTest(unittest.TestCase): + def test_specific_allowlisted_initialization_failures(self): + self.assertEqual( + layer.classify("app-seed", io.StringIO("APP_LAYER_DIAGNOSTIC stage=copy_failed\n")), + "WINE11_LAYER_HIL service=app-seed cause=copy_failed", + ) + self.assertEqual( + layer.classify("state-init", io.StringIO("STATE_LAYER_DIAGNOSTIC stage=ownership_failed\n")), + "WINE11_LAYER_HIL service=state-init cause=ownership_failed", + ) + self.assertEqual( + layer.classify("app-seed", io.StringIO("APP_LAYER_DIAGNOSTIC stage=permissions_failed\n")), + "WINE11_LAYER_HIL service=app-seed cause=permissions_failed", + ) + + def test_does_not_reflect_raw_or_malformed_sensitive_output(self): + secret = "private-token-should-not-appear" + text = ( + f"STATE_LAYER_DIAGNOSTIC stage=ownership_failed credential={secret}\n" + f"{secret} /home/private/mount\n" + "APP_LAYER_DIAGNOSTIC stage=copy_failed\n" + "STATE_LAYER_DIAGNOSTIC stage=invalid_identity extra\n" + ) + output = layer.classify("state-init", io.StringIO(text)) + self.assertEqual(output, "WINE11_LAYER_HIL service=state-init cause=unclassified_nonempty") + self.assertNotIn(secret, output) + self.assertNotIn("/home", output) + + def test_foreign_service_marker_is_ignored(self): + self.assertEqual( + layer.classify("app-seed", io.StringIO("STATE_LAYER_DIAGNOSTIC stage=ownership_failed\n")), + "WINE11_LAYER_HIL service=app-seed cause=unclassified_nonempty", + ) + + def test_hil_classifies_stderr_without_publishing_raw_logs(self): + source = (MODULE.parents[2] / "scripts/ci/qualify-wine11-layered.sh").read_text( + encoding="utf-8" + ) + self.assertIn('docker logs --tail 80 "$cid" 2>&1 |', source) + self.assertNotIn('docker logs --tail 80 "$cid" 2>/dev/null |', source) + self.assertIn('classify-layer-init-logs.py "$service"', source) + + def test_empty_logs_classified_without_raw_output(self): + self.assertEqual( + layer.classify("app-seed", io.StringIO("")), + "WINE11_LAYER_HIL service=app-seed cause=unclassified_empty", + ) + + def test_composite_health_failure_remains_fail_closed_and_private(self): + source = (MODULE.parents[2] / "scripts/ci/qualify-wine11-layered.sh").read_text( + encoding="utf-8" + ) + for expected in ( + "classify_health_failure()", + "if ! wait_health; then", + "fail health_initial", + "WINE11_LAYER_HEALTH state=%s health=%s", + "WINE11_LAYER_HEALTH token_file=present", + "WINE11_LAYER_HEALTH token_file=missing", + "WINE11_LAYER_HEALTH registry=present", + "WINE11_LAYER_HEALTH authorized_api=pass", + "WINE11_LAYER_HEALTH authorized_api=fail", + "python3 scripts/ci/classify-startup-logs.py", + ): + self.assertIn(expected, source) + self.assertIn('docker logs --tail 200 "$cid" 2>&1 |', source) + self.assertIn('http://127.0.0.1:8000/health >/dev/null 2>&1', source) + self.assertNotIn("docker logs --tail 200 \"$cid\" >&2", source) + self.assertNotIn("set -x", source) + + def test_invalid_service_refused(self): + with self.assertRaises(ValueError): + layer.classify("winebot-interactive", io.StringIO("APP_LAYER_DIAGNOSTIC stage=copy_failed\n")) + + +if __name__ == "__main__": + unittest.main()