From beb78451920c3d4caeab0840a7c3d8f861329f6a Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:26:12 -0500 Subject: [PATCH 01/18] feat: Linux browser tier L5 port (#119) Port the L5 files from the reference branch, whole-file, for files that origin/main has not changed since 106f6a0 (35 files). Three-way apply of the reference deltas for README.md and poc/reverse-attach-linux/src/external.rs (comment only; README keeps main's text and takes the reference split of the 0.12.0 and post-0.12.0 scope). Not built or tested in this commit. Commands: git checkout origin/feat/linux-l5-release-cutover -- <35 files>; git apply -3 on the two reference deltas (both applied cleanly). --- .github/workflows/ci.yml | 9 +- .github/workflows/linux-release-smoke.yml | 235 +++++++ .github/workflows/release.yml | 38 +- README.md | 27 +- docs/adr/linux-browser-tier.md | 31 +- docs/linux-cutover.md | 628 ++++++++++++++++++ docs/linux-setup.md | 106 ++- docs/release-records/TEMPLATE.md | 91 +++ docs/releasing.md | 220 +++++- docs/requirements/linux-browser-tier.md | 32 +- poc/reverse-attach-linux/README.md | 30 +- poc/reverse-attach-linux/pw-mcp.sh | 9 + poc/reverse-attach-linux/src/browser_cli.rs | 13 +- .../src/browser_cli_tests.rs | 4 +- poc/reverse-attach-linux/src/child.rs | 43 +- poc/reverse-attach-linux/src/child_tests.rs | 48 ++ poc/reverse-attach-linux/src/containment.rs | 9 +- .../src/containment_tests.rs | 102 +++ poc/reverse-attach-linux/src/external.rs | 2 + poc/reverse-attach-linux/src/install.rs | 24 +- poc/reverse-attach-linux/src/install_tests.rs | 44 +- poc/reverse-attach-linux/src/legacy.rs | 303 +++++++++ poc/reverse-attach-linux/src/legacy_tests.rs | 416 ++++++++++++ poc/reverse-attach-linux/src/main.rs | 1 + poc/reverse-attach-linux/src/probe.rs | 66 +- poc/reverse-attach-linux/src/probe_tests.rs | 60 ++ poc/reverse-attach-linux/src/proc.rs | 4 +- poc/reverse-attach-linux/src/procnet.rs | 148 ++++- poc/reverse-attach-linux/src/procnet_tests.rs | 205 +++++- poc/reverse-attach-linux/src/sigstop_tests.rs | 36 +- poc/reverse-attach-linux/src/state.rs | 23 + poc/reverse-attach-linux/src/state_tests.rs | 28 + scripts/check-release-record.sh | 131 ++++ scripts/release-smoke-linux.sh | 320 +++++++++ scripts/test-name-consistency.sh | 5 +- scripts/test-pw-mcp-deprecated.sh | 62 ++ scripts/test-release-smoke-linux.sh | 162 +++++ 37 files changed, 3590 insertions(+), 125 deletions(-) create mode 100644 .github/workflows/linux-release-smoke.yml create mode 100644 docs/linux-cutover.md create mode 100644 docs/release-records/TEMPLATE.md create mode 100644 poc/reverse-attach-linux/src/legacy.rs create mode 100644 poc/reverse-attach-linux/src/legacy_tests.rs create mode 100755 scripts/check-release-record.sh create mode 100755 scripts/release-smoke-linux.sh create mode 100755 scripts/test-pw-mcp-deprecated.sh create mode 100755 scripts/test-release-smoke-linux.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21a2aba..2896402 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -111,7 +111,7 @@ jobs: steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: ShellCheck - run: shellcheck scripts/install-linux.sh scripts/test-install-linux.sh scripts/test-name-consistency.sh scripts/test-legacy-agent.sh + run: shellcheck scripts/install-linux.sh scripts/test-install-linux.sh scripts/test-name-consistency.sh scripts/test-legacy-agent.sh scripts/release-smoke-linux.sh scripts/test-release-smoke-linux.sh scripts/check-release-record.sh poc/reverse-attach-linux/pw-mcp.sh scripts/test-pw-mcp-deprecated.sh - name: Generated units (fake HOME, stubbed systemctl/tailscale/loginctl) # Diffs each written unit against its expected text and runs systemd-analyze verify (#90). run: bash scripts/test-install-linux.sh @@ -119,6 +119,13 @@ jobs: run: | bash scripts/test-name-consistency.sh bash scripts/test-legacy-agent.sh + - name: Release smoke gates and the release-record check (fixtures, no network, no systemd) + # The pure parts of scripts/release-smoke-linux.sh and scripts/check-release-record.sh. The + # smoke itself runs in .github/workflows/linux-release-smoke.yml (dispatch and release only). + run: bash scripts/test-release-smoke-linux.sh + - name: pw-mcp.sh is marked deprecated and still launches unchanged (D14) + # A stub stands in for playwright-mcp; nothing real starts and no port opens. + run: bash scripts/test-pw-mcp-deprecated.sh linux-hands-node: name: Linux hands node (${{ matrix.arch }}) diff --git a/.github/workflows/linux-release-smoke.yml b/.github/workflows/linux-release-smoke.yml new file mode 100644 index 0000000..9ac06d3 --- /dev/null +++ b/.github/workflows/linux-release-smoke.yml @@ -0,0 +1,235 @@ +name: Linux release smoke + +# The release-time Linux smoke (docs/requirements/linux-browser-tier.md, section 3.3, and +# docs/releasing.md "Linux release gates"). It runs on `workflow_dispatch` and as the first stage of +# release.yml, never per PR: it downloads hundreds of MB per cell. It builds and tests only. It +# publishes nothing, creates no tag and no release, and holds no secret or environment. +# +# Jobs: +# pins the Playwright pins match upstream for all four platforms (V1, R7.2) +# smoke Ubuntu 22.04 and 24.04, amd64 and arm64: a real `browser install`, the headless health +# check, the listener self-check on the live tree (V2), `kill -9` of the harness and a +# survivor check. The cell FAILS without a systemd user manager. +# debian12 Debian 12 container, amd64 and arm64: install, preflight and the health check, up to +# the containment check (no user manager in a container) +# record the per-release manual record (docs/release-records/linux-VERSION.md); a missing or +# unfinished record fails the release, V2 and D7 included +# +# V2 is decided: no TCP or UDP listener, and any Unix listener inside the child's private per-run 0700 +# TMPDIR owned by the daemon's uid (scripts/release-smoke-linux.sh gate_v2). D7 (the AppArmor profile) +# is decided: the single glob stays. Do not weaken either here. + +on: + workflow_call: + inputs: + ref: + description: "Git ref to build and smoke (the release tag)" + required: false + type: string + default: "" + strict: + description: "Fail when the release record is missing or unfinished (release.yml sets true)" + required: false + type: boolean + default: false + workflow_dispatch: + # Dispatch it on the branch or commit to check: `gh workflow run linux-release-smoke.yml --ref BRANCH`. + +permissions: + contents: read + +jobs: + pins: + name: Pins cover and match upstream (all four platforms) + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ inputs.ref || github.sha }} + - name: Offline check, then every pinned artifact re-downloaded + # The same two commands as the macOS release job, not a weaker form (R7.2). + run: | + set -euo pipefail + python3 scripts/playwright-pins.py verify --offline + python3 scripts/playwright-pins.py verify --online + - name: Each platform has a pinned Node.js and a pinned Chromium source (V1) + run: | + set -euo pipefail + python3 - <<'PY' + import json + pins = json.load(open("release/playwright-pins/pins.json")) + want = ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"] + for label in ("node", "chromium"): + got = sorted(pins[label]["artifacts"]) + assert got == want, "%s artifacts cover %s, need %s" % (label, got, want) + for plat in want: + print("%-12s node ok, chromium source %s" % (plat, pins["chromium"]["artifacts"][plat]["source"])) + PY + + smoke: + name: Smoke ${{ matrix.os }} ${{ matrix.arch }} + strategy: + fail-fast: false + matrix: + include: + - { os: ubuntu-22.04, arch: amd64, runner: ubuntu-22.04 } + - { os: ubuntu-22.04, arch: arm64, runner: ubuntu-22.04-arm } + - { os: ubuntu-24.04, arch: amd64, runner: ubuntu-24.04 } + - { os: ubuntu-24.04, arch: arm64, runner: ubuntu-24.04-arm } + runs-on: ${{ matrix.runner }} + timeout-minutes: 40 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ inputs.ref || github.sha }} + - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable + with: + toolchain: stable + - name: Relax the unprivileged user-namespace restriction (this ephemeral runner only) + # Ubuntu 24.04 restricts unprivileged user namespaces through AppArmor, which stops + # Chromium's sandbox on a runner. This is a property of the throwaway runner, not advice for + # hosts: a host keeps the restriction and uses the path-scoped profile that + # `browser preflight` prints (ADR D7). + run: | + f=/proc/sys/kernel/apparmor_restrict_unprivileged_userns + if [ -e "$f" ] && [ "$(cat "$f")" != 0 ]; then + echo "::notice::kernel.apparmor_restrict_unprivileged_userns was $(cat "$f"); setting it to 0 on this ephemeral runner only" + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + else + echo "kernel.apparmor_restrict_unprivileged_userns: not present or already 0; nothing relaxed" + fi + - id: um + name: Provide a user manager (linger, the per-user service of the runner uid, XDG_RUNTIME_DIR) + run: | + set -u + uid=$(id -u) + rt="/run/user/$uid" + available=false + if [ -d /run/systemd/system ]; then + sudo loginctl enable-linger "$USER" || true + sudo systemctl start "user@${uid}.service" || true + for _ in $(seq 1 30); do + state=$(XDG_RUNTIME_DIR="$rt" systemctl --user is-system-running 2>/dev/null || true) + if [ -S "$rt/bus" ] && { [ "$state" = running ] || [ "$state" = degraded ]; }; then + available=true + break + fi + sleep 2 + done + fi + if [ "$available" = true ]; then + { + echo "XDG_RUNTIME_DIR=$rt" + echo "DBUS_SESSION_BUS_ADDRESS=unix:path=$rt/bus" + } >> "$GITHUB_ENV" + fi + echo "available=$available" >> "$GITHUB_OUTPUT" + - name: A user manager is required (unlike the optional per-PR job, this one fails without it) + if: steps.um.outputs.available != 'true' + run: | + echo "::error::no systemd user manager on this runner; the release smoke cannot run, so the release is blocked (requirements 3.3)" + exit 1 + - name: Build the binary and the end-to-end harness + working-directory: poc/reverse-attach-linux + run: | + set -euo pipefail + cargo build --release + cargo test --release --no-run --message-format=json \ + | jq -r 'select(.reason == "compiler-artifact" and .profile.test == true and .executable != null and .target.name == "oab-computer") | .executable' \ + | tail -n 1 > "$RUNNER_TEMP/harness-path" + test -x "$(cat "$RUNNER_TEMP/harness-path")" + - name: Smoke (install, health check, listeners, kill -9, survivors) + env: + # `--retry` runs the containment self-test in the CLI process (V11). It uses the production + # unit names, which is fine on a throwaway runner. + OAB_SMOKE_STATUS_RETRY: "1" + run: | + set -o pipefail + bash scripts/release-smoke-linux.sh \ + --bin "$PWD/poc/reverse-attach-linux/target/release/oab-computer" \ + --harness "$(cat "$RUNNER_TEMP/harness-path")" 2>&1 | tee "$RUNNER_TEMP/smoke.log" + - name: Gate summary + if: always() + run: grep -h '^GATE ' "$RUNNER_TEMP/smoke.log" || echo "no GATE lines were printed" + - name: Nothing left behind + if: always() + run: | + left=$(systemctl --user list-units 'oab-l[45]-test-*' --all --no-legend 2>/dev/null | wc -l) + echo "transient test units left: $left" + [ "$left" -eq 0 ] + + debian12: + name: Debian 12 container ${{ matrix.arch }} + strategy: + fail-fast: false + matrix: + include: + - { arch: amd64, runner: ubuntu-24.04 } + - { arch: arm64, runner: ubuntu-24.04-arm } + runs-on: ${{ matrix.runner }} + timeout-minutes: 40 + env: + # debian:12-slim, the multi-architecture index digest, resolved 2026-11-17. Pinned by digest, not + # by tag. Refresh it deliberately (docs/releasing.md). + DEBIAN12_IMAGE: debian@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ inputs.ref || github.sha }} + - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable + with: + toolchain: stable + - name: Relax the unprivileged user-namespace restriction (this ephemeral runner only) + run: | + f=/proc/sys/kernel/apparmor_restrict_unprivileged_userns + if [ -e "$f" ] && [ "$(cat "$f")" != 0 ]; then + echo "::notice::kernel.apparmor_restrict_unprivileged_userns was $(cat "$f"); setting it to 0 on this ephemeral runner only" + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + fi + - name: Build the binary (the runner is newer than Debian 12, so this also proves it runs on glibc 2.36) + working-directory: poc/reverse-attach-linux + run: cargo build --release + - name: Install, preflight and the health check inside the container + # Chromium's sandbox needs unprivileged user namespaces, which Docker's default seccomp and + # AppArmor profiles stop. Both are lifted for this one throwaway container, and the log says so. + run: | + set -o pipefail + echo "::notice::container runs with seccomp=unconfined and apparmor=unconfined so Chromium's sandbox can create a user namespace (throwaway container, runner only)" + docker run --rm \ + --security-opt seccomp=unconfined --security-opt apparmor=unconfined \ + -v "$PWD/poc/reverse-attach-linux/target/release/oab-computer:/work/oab-computer:ro" \ + -v "$PWD/scripts/release-smoke-linux.sh:/work/release-smoke-linux.sh:ro" \ + "$DEBIAN12_IMAGE" \ + bash /work/release-smoke-linux.sh --bin /work/oab-computer --in-container 2>&1 | tee "$RUNNER_TEMP/debian12.log" + - name: Gate summary + if: always() + run: grep -h '^GATE ' "$RUNNER_TEMP/debian12.log" || echo "no GATE lines were printed" + + record: + name: Per-release manual record + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ inputs.ref || github.sha }} + - name: docs/release-records/linux-VERSION.md exists, has no PENDING, and V2 and D7 are decided + # Release (strict): a missing or unfinished record fails. Dispatch: it reports and passes, because + # a dispatch is not a release. A V2 or D7 row that says "open, owner decision pending" blocks the + # release; this step never fills or skips them. + env: + STRICT: ${{ inputs.strict && 'true' || 'false' }} + REF: ${{ inputs.ref }} + run: | + set -euo pipefail + case "$REF" in + v[0-9]*) VERSION=$(scripts/release-version.sh "$REF") ;; + *) VERSION=$(scripts/release-version.sh) ;; + esac + echo "version: $VERSION (strict: $STRICT)" + if [ "$STRICT" = true ]; then + scripts/check-release-record.sh "$VERSION" + else + scripts/check-release-record.sh "$VERSION" --report-only + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d9000da..f0160ab 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,16 +14,33 @@ on: # Release is the only workflow allowed to write repository contents. It never # runs PR-controlled code with secrets: push tags and manual dispatch only. +# The default is read-only; each job below asks for exactly what it needs. permissions: - contents: write + contents: read concurrency: group: oab-computer-release-${{ github.ref }} cancel-in-progress: false jobs: + smoke: + # The Linux release gates (docs/releasing.md "Linux release gates"): the pins for all four + # platforms, the four-cell smoke, the Debian 12 container job and the per-release record. A red + # gate stops both jobs below before anything is signed or published. No environment and no + # secret here, so it starts on the tag push and does not wait for the reviewer approval. + name: Linux release gates + uses: ./.github/workflows/linux-release-smoke.yml + permissions: + contents: read + with: + ref: ${{ inputs.tag || github.ref_name }} + strict: true + release: name: Universal app + signed/notarized pkg + needs: smoke + permissions: + contents: write runs-on: macos-15 environment: release env: @@ -187,12 +204,17 @@ jobs: linux: name: Linux hands node tarball (${{ matrix.arch }}) + needs: smoke + permissions: + contents: write # upload to the release + id-token: write # the OIDC token the attestation is signed with + attestations: write # store the attestation strategy: fail-fast: false matrix: include: - arch: amd64 - runner: ubuntu-latest + runner: ubuntu-24.04 - arch: arm64 runner: ubuntu-24.04-arm runs-on: ${{ matrix.runner }} @@ -206,7 +228,10 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: ${{ env.RELEASE_TAG }} - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable + # Pinned by commit: this job now holds id-token: write and contents: write. + with: + toolchain: stable - name: Validate tag against the version source # Same gate as the macOS job: the tag must equal `let version` in main.swift. The tag # is then compiled into the Linux binary, so it cannot report another version (#74). @@ -236,6 +261,13 @@ jobs: tar czf "$NAME.tar.gz" "$NAME" sha256sum "$NAME.tar.gz" > "$NAME.tar.gz.sha256" echo "ASSET=$NAME.tar.gz" >> "$GITHUB_ENV" + - name: Attest build provenance of the tarball + # Only the tarball is a subject, not its .sha256. Consumers verify with `gh attestation + # verify` (docs/releasing.md "Verifying a Linux tarball"). The attestation says this + # repository's workflow built the file from a stated commit; it does not make a download safe. + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: ${{ env.ASSET }} - name: Upload to the release # The macOS job creates the release; wait for it rather than racing on # `gh release create` from two jobs. diff --git a/README.md b/README.md index 97140c9..bc1c107 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ permissions wizard ([details](#download-and-install)). Then point a caller at it ```sh kiro-cli mcp add --name mac-mcp --url https://..ts.net:8444/mcp \ - --header "Authorization: Bearer $(ssh cat ~/.config/oab-computer/token)" \ + --header "Authorization: Bearer $(ssh 'cat ~/.config/oab-computer/token')" \ --scope global --timeout 30000 ``` @@ -454,7 +454,7 @@ permissions block. The Linux node (`poc/reverse-attach-linux/`) has one daemon listener (`127.0.0.1:8795` when installed by `install-linux.sh`). After 0.12.0 the browser is a managed child with no TCP or UDP port of its own (it holds -two private Unix sockets in its own `0700` temporary directory, see +two private Unix sockets in its own `0700` temporary directory, which the status self-check and the release smoke hold to the rule in [Linux setup](docs/linux-setup.md#ports)); 0.12.0 and earlier, and any host that still runs the old browser unit, also have a Playwright listener on `8794` with no authentication. The differences from macOS: @@ -463,9 +463,24 @@ macOS: `scripts/install-linux.sh` sets `127.0.0.1:8795`. - `/attach` is always on. There is no `--no-attach`. - There is no switchboard and no menu bar. +- The Linux node does use a Unix domain socket: it connects, as a client, to the Wayland socket for + display and pointer control. The daemon itself does not listen on one; the managed browser's process + tree holds two listening Unix sockets of its own in a private `0700` directory (see above). +- The mint call is plain `http://` only. A `wss://` runtime with `admin_credential` is refused. + +0.12.0 and earlier, and any host that still runs the old browser unit: + - 0.12.0 and earlier: `install-linux.sh` runs `sudo tailscale serve` when passwordless sudo exists, and installs `oab-computer-pw-mcp.service` on unauthenticated `127.0.0.1:8794` plus an `MCP_UPSTREAM` line when `node` and `npm` exist, unless `--no-browser` is given. +- A host that still runs an old browser unit has an **unauthenticated** port 8794: any local user on + this node can call every browser tool there, including `browser_run_code_unsafe` (arbitrary Node + code). The installer warns with the exact `systemctl --user disable --now ` command and does + not touch the unit; see [Upgrading a host that already has a browser unit](docs/linux-setup.md#upgrading-a-host-that-already-has-a-browser-unit) + and, for the procedure with its rollback, [the cutover guide](docs/linux-cutover.md). + +After 0.12.0 (`main`, the first release that contains these; 0.12.0 does not): + - After 0.12.0, `install-linux.sh` never runs `sudo` on its own. It prints each root action (linger, `tailscale serve` for `:8444`, the AppArmor profile, missing libraries, fonts) with its exact command and reason, and runs them only with `--apply-system-changes`. @@ -480,17 +495,9 @@ macOS: - `MCP_UPSTREAM` takes plain `http://` URLs only, and every `name=url` entry the daemon uses must be a literal loopback `http://127.0.0.1:` or `http://[::1]:` URL: any other host stops the daemon with exit 64. A `browser=` entry that a managed install ignores is not checked. A managed install wins over a `browser=` entry unless `MCP_BROWSER_BACKEND=external` is set. -- A host that still runs an old browser unit has an **unauthenticated** port 8794: any local user on - this node can call every browser tool there, including `browser_run_code_unsafe` (arbitrary Node - code). The installer warns with the exact `systemctl --user disable --now ` command and does - not touch the unit; see [Upgrading a host that already has a browser unit](docs/linux-setup.md#upgrading-a-host-that-already-has-a-browser-unit). - After 0.12.0, sign in once, for a login the browser keeps: `ssh -t '~/.local/oab-computer/oab-computer browser signin'` ([Sign in](docs/linux-setup.md#sign-in)). The profile is obfuscated with `--password-store=basic`, not strongly encrypted. -- The Linux node does use a Unix domain socket: it connects, as a client, to the Wayland socket for - display and pointer control. The daemon itself does not listen on one; the managed browser's process - tree holds two listening Unix sockets of its own in a private `0700` directory (see above). -- The mint call is plain `http://` only. A `wss://` runtime with `admin_credential` is refused. ## Lending this Mac to a sandboxed agent (reverse attach) diff --git a/docs/adr/linux-browser-tier.md b/docs/adr/linux-browser-tier.md index 8a7582c..9b3e03f 100644 --- a/docs/adr/linux-browser-tier.md +++ b/docs/adr/linux-browser-tier.md @@ -1,6 +1,6 @@ # ADR: Linux managed Playwright tier -- **Status:** Accepted. Implemented through L4 (shared pins, download and install, the managed child and router, the installer, `browser signin` and the docs, hardening tiers with effect probes); release work (L5) and the PID-namespace supervisor (L6) are pending. The 0.12.0 release does not contain it: 0.12.0 and earlier run an external unit on `127.0.0.1:8794`. Operator guide: [`docs/linux-setup.md`](../linux-setup.md). +- **Status:** Accepted. Implemented through L5 (shared pins, download and install, the managed child and router, the installer, `browser signin`, the docs, hardening tiers with effect probes, the release gates and the cutover guide); the PID-namespace supervisor (L6) is pending. Nothing is released or cut over yet. The 0.12.0 release does not contain it: 0.12.0 and earlier run an external unit on `127.0.0.1:8794`. Operator guide: [`docs/linux-setup.md`](../linux-setup.md). - **Issues:** [#119](https://github.com/openabdev/openab-computer/issues/119) (this work), [#118](https://github.com/openabdev/openab-computer/issues/118) (macOS tiers) - **Requirement:** [`docs/requirements/linux-browser-tier.md`](../requirements/linux-browser-tier.md) (requirements, cutover runbook, test plan, PR split) - **Related:** [`browser-tiers.md`](browser-tiers.md) (the macOS ADR; its questions are cited here as "macOS Q*n*"), [`reverse-attach.md`](reverse-attach.md), [`docs/linux-setup.md`](../linux-setup.md), [`docs/tool-profiles.md`](../tool-profiles.md) @@ -16,9 +16,9 @@ The old unit also survives a daemon stop and has no pinned downloads. Goal: the same managed tier on Linux, on amd64 and arm64. 1. `@playwright/mcp` runs as a **stdio child** of the daemon. It and its Chromium open no - TCP or UDP port. Port 8794 is retired for the managed path. Target: no Unix listener either. - That target is **not met** by the L2 build: it holds two private Unix listening sockets in the - child's `0700` `TMPDIR` (open under V2 and #132). The Linux docs claim only "no TCP or UDP port". + TCP or UDP port. Port 8794 is retired for the managed path. **Decided (V2):** it holds two private + Unix listening sockets, Playwright's browser socket and Chromium's `SingletonSocket`, and the rule is + that any Unix listener in the managed tree is inside the child's private per-run `0700` `TMPDIR`, owned by the daemon's uid. Anything else fails the self-check and the release smoke. 2. Node, the npm packages and Chromium come from **pinned URLs with pinned sizes and SHA-256 digests** in a manifest embedded in the release binary. The binary never fetches pins. 3. **Update is side by side with a health check** and keeps the old version on failure. It is @@ -287,12 +287,17 @@ root action is printed with its exact command and reason. `--apply-system-change runs them with `sudo`. Its only entry point is `scripts/install-linux.sh`; `oab-computer browser` never runs a root action and refuses the flag. The AppArmor profile is scoped to the installing user's own data path, not `/home/*`, and `update` prints the profile for the new version directory before it commits, so the -old version keeps serving until the new profile is loaded. *As built (L1b, to be confirmed by the -owner):* the profile is one glob over every version directory under that data path, so the profile +old version keeps serving until the new profile is loaded. *As built (L1b), confirmed by the owner +(the single path-scoped glob profile is kept, no pattern change):* the profile is one glob over every version directory under that data path, so the profile that `install` prints already covers the new version directory and `update` prints no further one; the decided order (profile loaded before the commit) holds because no new profile is needed. The profile file and name end in a hash of the install path, so two users on one host do not replace -each other's profile. +each other's profile. Residual risk, stated plainly: the glob's path is inside the user's own data +directory, which that user, and any code running as that user, can write. A file named `chrome` placed +under `/oab-computer/playwright//chromium/` would run with `userns` allowed, which the +distribution restriction withholds from arbitrary programs. That needs code execution as the same user +first, and it returns only the unprivileged user namespace (more kernel attack surface), not new file or +network access. The profile is `flags=(unconfined)` plus `userns`, so it restricts nothing else. Rationale: root changes are announced with their exact command, not made silently. @@ -477,10 +482,16 @@ Rejected: ## Security notes - **No TCP or UDP listener.** The managed tree opens no TCP or UDP port. Two private Unix - listening sockets remain in its `0700` `TMPDIR` (measured; open under V2 and #132), so the - target "no Unix listener" is unmet. `browser status` runs a + listening sockets remain in its `0700` `TMPDIR`; V2 is decided: they are accepted under the rule + "inside the child's private per-run `0700` `TMPDIR`, owned by the daemon's uid", and nothing else is. + Measured on a Debian 13 arm64 node: neither socket can be removed (Playwright binds the first on + every start path, Chromium aborts without the second, and the DevTools transport is already a pipe). + Another local user gets `EACCES` on both, and a web page cannot reach a Unix socket path. The residual + path: a process of the same uid can connect to both and drive the managed browser, which the same uid + can already do by reading the profile directory. `browser status` runs a self-check over `/proc/net/{tcp,tcp6,udp,udp6,unix}` and reports listeners owned by the managed - tree, and the release smoke runs the same check on both architectures. The launch vector never + tree, with how many are outside the private directory and the directory's state (`tmpdir`), and the + release smoke runs the same check on both architectures and recomputes the rule. The launch vector never contains `--port`, `--host`, `--allowed-hosts` or `--no-sandbox`. - **Integrity, not safety.** Downloads are checked against embedded size and SHA-256 values. The manifest is only as trustworthy as the binary carrying it, and the Linux tarball is authenticated diff --git a/docs/linux-cutover.md b/docs/linux-cutover.md new file mode 100644 index 0000000..d5cc1da --- /dev/null +++ b/docs/linux-cutover.md @@ -0,0 +1,628 @@ +# Cutover and rollback: from the old browser unit to the managed browser + +This guide is for a person who moves a Linux hands node from the old external Playwright unit (an +unauthenticated listener on `127.0.0.1:8794`) to the managed browser that the daemon starts itself +(`oab-computer browser install`). It is the runbook of +[requirements, section 2](requirements/linux-browser-tier.md#2-cutover-runbook) with the commands +written out. The decisions behind it are in the [ADR](adr/linux-browser-tier.md): D9 (a fresh profile, +the old one untouched), D10 (a person removes the leftovers), D13 (one host first, a one-week soak, +then the rest) and D14 (`pw-mcp.sh` is deprecated for one more minor release). + +Read it once before you start. Every step has a command, a check and a way back. + +## What exists, and what has not been done + +- **Not released.** The managed tier is built through L5. The commands below need a release that + contains it (written `X.Y.Z` here). 0.12.0 and earlier do not contain it. The things that arrive with + the first release containing L5 are marked "from that release" below: the `legacy_units`, `legacy` + and `legacy_listener` fields of `browser status`, the deprecation notice of `pw-mcp.sh`, the release + smoke and the build-provenance attestation of the Linux tarballs. +- **Nothing has been cut over.** Writing this guide did not change any host. The cutover is yours to + perform, host by host, as below. +- **Decided, not open.** V2 (the listener rule) and D7 (the AppArmor profile) are decided by the + owner. They are summarized under [Decisions that shape this guide](#decisions-that-shape-this-guide). + +## The hosts + +Hosts are described by what they run, never by name. Facts are collected in step 0, not assumed. + +| Host | What it runs | Where `MCP_UPSTREAM` is | The old browser unit | Data | +| --- | --- | --- | --- | --- | +| **A** (new-style unit) | `oab-computer.service`, written by the 0.12.0 installer | In `oab-computer.service` itself | `oab-computer-pw-mcp.service` | `~/.local/oab-computer` | +| **B, C, D** (old-style unit) | `oab-computer.service` | In a drop-in file under `oab-computer.service.d/` or `oab-instance-mcp.service.d/` | `oab-pw-mcp.service` | `~/.local/oab-instance-mcp/pw-mcp` | + +Requirement section 2 and D13 name two classes: one new-style host and the old-style hosts that "follow +together". The four existing hosts map to them: A is the class N host, and B, C and D are the three class O +hosts. A VM or any other host beyond these four is not covered by D13. It uses the class O procedure +only after the owner says when, not as part of the second wave. A host still running `oab-instance-mcp.service` (0.11 or +earlier) first needs [Upgrading from 0.11](linux-setup.md#upgrading-from-011); this guide starts after +that. + +## The order + +```mermaid +flowchart TB + pre["Before anything: a release with the managed tier is installed and verified on a throwaway account, M1 to M4 and the cutover rehearsal M8"] + a["Host A: steps 0 to 7"] + soak["Soak: one week of normal use on host A with no browser incident, old unit disabled and not deleted"] + rest["Hosts B, C and D together: steps 0 to 7 on each"] + soak2["Soak: one week on each, old units disabled and not deleted"] + clean["A person removes the leftovers, section Removing the leftovers"] + rb["Rollback, section Rollback"] + + pre --> a + a -- "any check fails" --> rb + a -- "all checks pass" --> soak + soak -- "browser incident" --> rb + soak -- "no incident" --> rest + rest -- "any check fails on a host" --> rb + rest -- "all pass" --> soak2 + soak2 -- "browser incident" --> rb + soak2 -- "no incident" --> clean +``` + +Within one host, the steps are these. Nothing changes the old setup before step 5, and a failed check +anywhere ends in the rollback. + +```mermaid +flowchart TB + s0["Step 0 Inventory, read only"] + s1["Step 1 Back up by copying, never moving"] + s2["Step 2 Get the new binary under a temporary name"] + s3["Step 3 Preflight"] + s4["Step 4 Side by side install and headless health check, the old unit keeps serving port 8794"] + stay["Stop here, nothing was cut over, the old setup is unchanged"] + s5["Step 5 Cutover window"] + c1["5.1 Disable and stop the old browser unit"] + c2["5.2 Remove the MCP_UPSTREAM line or the drop-in"] + c3["5.3 Put the new binary in place, daemon-reload, restart oab-computer.service"] + c4["5.4 browser signin if a login is needed"] + s6["Step 6 Verify: 32 tools, no listener on 8794, backend managed, still disabled after a new login"] + s7["Step 7 Kill test with kill -9 on the daemon"] + s8["Step 8 Soak for one week"] + rb["Rollback"] + + s0 --> s1 --> s2 --> s3 --> s4 + s4 -- "health check fails" --> stay + s4 -- "health check passes" --> s5 + s5 --> c1 --> c2 --> c3 --> c4 --> s6 + s6 -- "any check fails" --> rb + s6 -- "all checks pass" --> s7 + s7 -- "a process survives" --> rb + s7 -- "passes" --> s8 +``` + +Notation. Commands run on the host being moved, as the user that runs the daemon, in that user's +login session (over `ssh`, so that `XDG_RUNTIME_DIR` and the user manager are set). `$OLD` is the +old browser unit on that host. Set it once per shell, before any command that uses it (host A, then +B to D), and check it names a real unit: + +Host A: + +```sh +OLD=oab-computer-pw-mcp.service +systemctl --user cat "$OLD" >/dev/null && echo "OLD=$OLD" +``` + +Hosts B to D: + +```sh +OLD=oab-pw-mcp.service +systemctl --user cat "$OLD" >/dev/null && echo "OLD=$OLD" +``` + +A new `ssh` session starts without it: set it again. +The binary is `~/.local/oab-computer/oab-computer` (not on `PATH`). Checks that call the daemon from +outside use the commands of [Verify from another tailnet machine](linux-setup.md#6-verify-from-another-tailnet-machine). + +## Step 0. Inventory, read only + +Record what the host really has. Nothing here changes anything. The file may hold your Tailscale login +name, so it is created private and kept outside any repository. + +```sh +umask 077 +INV="$HOME/oab-cutover-inventory-$(date +%Y%m%d).txt" +{ + echo "== date, architecture, glibc"; date -u; uname -m; ldd --version | head -n 1 + echo "== AppArmor user namespace restriction"; cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>&1 + echo "== units"; systemctl --user list-units 'oab-*' --all --no-pager; systemctl --user list-unit-files 'oab-*' --no-pager + echo "== unit files and drop-ins as systemd sees them" + for u in oab-computer.service oab-pw-mcp.service oab-computer-pw-mcp.service; do echo "-- $u"; systemctl --user cat "$u" 2>&1; done + echo "== files in the unit directory"; ls -laR ~/.config/systemd/user/ 2>&1 + echo "== port 8794"; ss -ltnp 'sport = :8794' + echo "== legacy directories" + du -sh ~/.local/oab-computer/pw-mcp ~/.local/oab-computer/pw-profile ~/.local/oab-computer/pw-output \ + ~/.local/oab-instance-mcp/pw-mcp ~/.cache/ms-playwright 2>&1 + echo "== disk"; df -h ~ + echo "== seat socket"; ls "/run/user/$(id -u)" 2>&1 | grep -E '^wayland-[0-9]+$' + echo "== status"; ~/.local/oab-computer/oab-computer browser status 2>&1 +} > "$INV" 2>&1 +less "$INV" +``` + +**Verify.** The file names the old unit, says where the `MCP_UPSTREAM` line is (inside +`oab-computer.service` on host A, in a drop-in file on B to D), shows whether port 8794 is held, and +holds the architecture, glibc version and free disk. If `oab-computer.service` is missing and +`oab-instance-mcp.service` is present, stop: that host is on 0.11 or earlier and first follows +[Upgrading from 0.11](linux-setup.md#upgrading-from-011). The 0.12.0 binary has no `browser` command, +so the last line of the file is an error message there; that is expected at this step. + +**Roll back to here.** Nothing to undo. Delete the inventory file when you no longer need it. + +## Step 1. Back up by copying, never moving + +The backup directory is a sibling of the installer's `playwright/` directory, never inside it, so the +installer never mistakes it for its own data. The profile is not copied (D9). + +```sh +BK="${XDG_DATA_HOME:-$HOME/.local/share}/oab-computer/backup-$(date +%Y%m%d)" +mkdir -p "$BK" && chmod 700 "$BK" +cp -a ~/.local/oab-computer/oab-computer "$BK/oab-computer.prev" +cp -a ~/.config/systemd/user/oab-computer.service "$BK/" +for f in ~/.config/systemd/user/oab-pw-mcp.service ~/.config/systemd/user/oab-computer-pw-mcp.service \ + ~/.local/oab-computer/pw-config.json; do + if [ -e "$f" ]; then cp -a "$f" "$BK/"; fi +done +for d in ~/.config/systemd/user/oab-computer.service.d ~/.config/systemd/user/oab-instance-mcp.service.d; do + if [ -d "$d" ]; then cp -a "$d" "$BK/"; fi +done +(cd "$BK" && find . | sort) +``` + +**Verify.** The listing shows `oab-computer.prev`, `oab-computer.service`, the old unit file and, on +B to D, the drop-in directory with the file that holds `MCP_UPSTREAM`. Write the `$BK` path down: the +rollback uses it (`BK=`). + +**Roll back to here.** Nothing to undo. The backup stays; the installer never deletes it. + +## Step 2. Get the new binary under a temporary name + +Do **not** run `install-linux.sh` here: it replaces the daemon binary and restarts the daemon, which +is step 5. Download, check and unpack the release, and copy the binary beside the old one. + +```sh +V=X.Y.Z # a release that contains the managed tier +A=$(dpkg --print-architecture) # arm64 or amd64 +mkdir -p ~/oab-cutover-dl && cd ~/oab-cutover-dl +curl -fsSLO "https://github.com/openabdev/openab-computer/releases/download/v$V/oab-computer-$V-linux-$A.tar.gz" +curl -fsSLO "https://github.com/openabdev/openab-computer/releases/download/v$V/oab-computer-$V-linux-$A.tar.gz.sha256" +sha256sum -c "oab-computer-$V-linux-$A.tar.gz.sha256" +# Optional, beside the checksum, from that release (the 0.12.x tarballs carry no attestation): +# gh attestation verify "oab-computer-$V-linux-$A.tar.gz" --repo openabdev/openab-computer +tar xzf "oab-computer-$V-linux-$A.tar.gz" +install -m 755 "oab-computer-$V-linux-$A/oab-computer" ~/.local/oab-computer/oab-computer.new +~/.local/oab-computer/oab-computer.new browser plan +``` + +**Verify.** `sha256sum -c` prints `OK`. `browser plan` prints what an install downloads and where it +goes, and writes nothing. The attestation check is optional and does not make the download safe (ADR +D12); the checksum is the required one. The old daemon is still running the old binary. + +**Roll back to here.** `rm ~/.local/oab-computer/oab-computer.new` (and `~/oab-cutover-dl` if you want +the space). + +## Step 3. Preflight + +```sh +~/.local/oab-computer/oab-computer.new browser preflight +~/.local/oab-computer/oab-computer.new browser preflight --root-actions +``` + +The first command checks the host and exits 0 when nothing blocks. A blocker exits 1 and prints +`browser: preflight_failed class=` (`musl`, `glibc_too_old`, `disk_full`, `libraries_missing` +or `unsupported_platform`). The second prints only the root actions, one `command`, a tab and a reason +per line. This tool never runs them. Read each one, then run the ones you accept yourself, as root. +On a host with `/proc/sys/kernel/apparmor_restrict_unprivileged_userns` at `1` (Ubuntu 24.04) one of +them loads the path-scoped AppArmor profile (ADR D7: a single glob profile for your data path, kept as +decided; see [the residual risk](#decisions-that-shape-this-guide)). + +**Verify.** `preflight` exits 0 after you ran what you accepted. Run it again to confirm. + +**Roll back to here.** Libraries and fonts you installed are harmless and stay. If you loaded the +AppArmor profile and want it gone (needs root; `` is the short hash in the file name that `preflight` +printed): + +```sh +sudo apparmor_parser -R /etc/apparmor.d/oab-computer-chromium- && sudo rm /etc/apparmor.d/oab-computer-chromium- +``` + +## Step 4. Side-by-side install + +```sh +~/.local/oab-computer/oab-computer.new browser install +~/.local/oab-computer/oab-computer.new browser status +ss -ltnH 'sport = :8794' | wc -l +systemctl --user is-active "$OLD" +``` + +`install` downloads the pinned set, checks every size and SHA-256, and runs the headless health check +on a throwaway profile. It does not touch the seat, the old profile or the old unit. + +**Verify.** `install` exits 0 and ends with `installed `. `status` shows `state: installed` and +`pins_match: true`. The old listener is still there: `wc -l` prints `1` or more, and `$OLD` is +`active`. From the first release containing L5, `status` also shows `legacy_listener: 8794` and a +`legacy:` line that lists the old directories with sizes; the profile reads `holds_cookies`. Do not +continue unless the install succeeded. If it fails, nothing was cut over and the old setup is +unchanged. + +**Roll back to here.** The old daemon and the old unit never noticed the install: + +```sh +~/.local/oab-computer/oab-computer.new browser remove +``` + +`remove` deletes only what the installer created (it prints `left in place:` for anything else) and +refuses while a managed browser is running (`browser_running`). It restores nothing, because nothing +was changed. + +## Step 5. Cutover, in one short window + +From 5.1 to 5.3 the daemon has no browser. Do them together. Host A first; B to D only after the soak. + +### 5.1 Disable and stop the old browser unit + +```sh +systemctl --user disable --now "$OLD" +``` + +A plain `stop` is not enough: the unit comes back at the next login or boot with its unauthenticated +listener. + +**Verify.** + +```sh +systemctl --user is-enabled "$OLD" # prints disabled (exit status 1 is normal for a disabled unit) +ss -ltnH 'sport = :8794' | wc -l # prints 0 +``` + +**Roll back to here.** `systemctl --user enable --now "$OLD"`. + +### 5.2 Remove the `MCP_UPSTREAM` line (host A) or the drop-in file (hosts B to D) + +The backup of step 1 must exist. Delete nothing else. + +Host A, the line sits inside `oab-computer.service`: + +```sh +grep -n 'MCP_UPSTREAM' ~/.config/systemd/user/oab-computer.service +sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp$/d' ~/.config/systemd/user/oab-computer.service +grep -c 'MCP_UPSTREAM' ~/.config/systemd/user/oab-computer.service +``` + +If the last command does not print `0`, the line has another form (several upstreams, an edit of +yours): remove it by hand with an editor, keeping every other line. + +Hosts B to D, the line sits in a drop-in file. List every active assignment, with its file and line: + +```sh +grep -nE "^[[:space:]]*Environment=(['\"]|[^#;]*[[:space:]'\"])?MCP_UPSTREAM=" \ + ~/.config/systemd/user/oab-computer.service.d/*.conf \ + ~/.config/systemd/user/oab-instance-mcp.service.d/*.conf 2>/dev/null +``` + +Comments, `UnsetEnvironment=` and other variables are not matched. For each file printed, run `cat FILE` +and decide: + +- It holds only `[Service]`, that one `Environment=MCP_UPSTREAM=` line, comments and blank lines: it is + the dedicated drop-in. `rm -f FILE`. +- It holds any other setting: keep the file and delete only the line, + `sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp$/d' FILE`. If the + line has another form (several variables, another URL), edit it by hand and keep everything else. + +A drop-in the `grep` did not list may belong to something else. Do not delete it, and do not delete the +`.d/` directory. + +A unit that carries no installer marker (`# oab-computer-installer:`) is never rewritten by the +installer, which leaves the text it would have written beside it as `oab-computer.service.proposed`. +If one exists, review it, check that its `BIND` port matches the port `tailscale serve` maps (it carries +the `--port` of the run that wrote it, not the kept unit's), and adopt it only then: +`mv ~/.config/systemd/user/oab-computer.service.proposed ~/.config/systemd/user/oab-computer.service`. +It has no `MCP_UPSTREAM` line and carries the marker, so later installer runs keep the unit current. +This guide never creates that file. + +**Verify.** The `grep -nE` above prints nothing, and `grep -c 'MCP_UPSTREAM=' ~/.config/systemd/user/oab-computer.service` +prints `0` on host A. + +**Roll back to here.** Restore from the backup (this is the same as the rollback below, steps 3 and 4). + +### 5.3 Put the new binary in place and restart + +```sh +mv -f ~/.local/oab-computer/oab-computer.new ~/.local/oab-computer/oab-computer +systemctl --user daemon-reload +systemctl --user restart oab-computer.service +systemctl --user is-active oab-computer.service +curl -fsS 127.0.0.1:8795/healthz +``` + +Renaming over a running executable is allowed on Linux; the restart starts the new one. If the unit's +`BIND` port is not 8795, use that port in the `curl`. The daemon chooses its browser backend when it +starts, which is why the restart is needed. + +**Verify.** `is-active` prints `active` and `healthz` answers. + +**Roll back to here.** Follow the [Rollback](#rollback) section from step 1; the binary rollback uses +`oab-computer.prev`. + +### 5.4 Sign in, if a login is needed + +The managed browser starts with a fresh profile (D9). Nothing is copied from the old one, and no +command in this guide copies cookies. Run it over `ssh -t` from your machine: + +```sh +ssh -t '~/.local/oab-computer/oab-computer browser signin' +``` + +It opens a window on the node's seat on the persistent profile and waits for Enter. See +[Sign in](linux-setup.md#sign-in) for the VNC route on a headless seat. + +**Verify.** A later browser call is signed in to the site you logged in to. + +**Roll back to here.** `browser remove` deletes the new profile; the old one is untouched. + +## Step 6. Verify + +Run this after 5.4. The token and the URL are those of +[Verify from another tailnet machine](linux-setup.md#6-verify-from-another-tailnet-machine); run the +`curl` lines from another machine on your tailnet. + +If a `browser signin` window is still open, `browser status` shows `unix_outside>0 result=fail`. That is a false +alarm that fails closed; close the sign-in window and run `status` again. + +```sh +TOKEN=$(ssh 'cat ~/.config/oab-computer/token') +U=https://..ts.net:8444 +H='Content-Type: application/json' +# 1. the tool list: prints 32 (the browser_* names) +curl -s -X POST $U/mcp -H "Authorization: Bearer $TOKEN" -H "$H" \ + -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \ + | python3 -c 'import sys,json;n=[t["name"] for t in json.load(sys.stdin)["result"]["tools"]];print(sum(x.startswith("browser_") for x in n))' +# 2. a navigation: prints (False, False) +curl -s -X POST $U/mcp -H "Authorization: Bearer $TOKEN" -H "$H" \ + -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"browser_navigate","arguments":{"url":"about:blank"}}}' \ + | python3 -c 'import sys,json;d=json.load(sys.stdin);print(("error" in d, d.get("result",{}).get("isError", False)))' +# 3. which backend serves: prints the browser object +curl -s -X POST $U/mcp -H "Authorization: Bearer $TOKEN" -H "$H" \ + -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"sys_info","arguments":{}}}' \ + | python3 -c 'import sys,json;d=json.load(sys.stdin);print(json.loads(d["result"]["content"][0]["text"])["browser"])' +``` + +Then on the host, while or just after the browser ran: + +```sh +ss -ltnH 'sport = :8794' | wc -l +~/.local/oab-computer/oab-computer browser status +``` + +**Verify.** + +- The tool count is `32`, the navigation prints `(False, False)`, and `sys_info` shows + `backend: managed` with a `containment` of `systemd` or `systemd+mount` and a `display` of `headed` or + `headless`. +- `ss` prints `0`: nothing listens on 8794. +- `browser status` shows `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass` while the + browser runs (`none` before its first start). Anything with `result=fail` is a failure (V2): a TCP or + UDP listener, a Unix listener outside the child's private directory, or that directory not being + `0700` or not yours. Run `status` in the daemon's own login session so `XDG_RUNTIME_DIR` matches. + From the first release containing L5, `legacy_listener: none`. +- End your login session and log in again, or reboot. Then `systemctl --user is-enabled "$OLD"` prints + `disabled` and the `ss` check still prints `0`. With linger on, the daemon survives the logout. + +If any check fails, the host is not cut over: use the [Rollback](#rollback). + +## Step 7. Kill test, once per host class + +Hosts A and B are enough to cover both classes; run it on every host if you like. Start a browser, kill +the daemon with `SIGKILL`, and check that nothing from the install directory survives and that the +restarted daemon answers. + +```sh +# start a browser first (check 2 of step 6), then: +D="${XDG_DATA_HOME:-$HOME/.local/share}/oab-computer" +pid=$(systemctl --user show -p MainPID --value oab-computer.service) +case "$pid" in ''|*[!0-9]*|0|1) echo "no daemon main PID ($pid); stop and investigate" ;; *) kill -9 "$pid" ;; esac +sleep 10 +for p in /proc/[0-9]*; do e=$(readlink "$p/exe" 2>/dev/null) || continue + case "$e" in "$D"/playwright/*) echo "SURVIVOR ${p#/proc/} $e" ;; esac; done +systemctl --user is-active oab-computer.service +curl -fsS 127.0.0.1:8795/healthz +``` + +**Verify.** No `SURVIVOR` line, `active`, and `healthz` answers. Repeat check 1 and 2 of step 6 once. +The unit restarts the daemon by itself (`Restart=always`, `RestartSec=2`). The browser stops with the +daemon because it runs as a transient unit bound to it; the time Chromium takes to exit after +`SIGKILL` (V3) is informational, and the stop guarantee does not depend on it. + +**Roll back to here.** A survivor, or a daemon that does not come back, is a failure: use the +[Rollback](#rollback). `systemctl --user stop 'oab-browser-*.service'` clears a stray browser unit. + +## Step 8. Soak + +Leave `$OLD` disabled **but not deleted**, and the legacy directories in place, for one week of normal +use with no browser incident (D13). Check now and then: + +```sh +systemctl --user is-active oab-computer.service +~/.local/oab-computer/oab-computer browser status # state: installed, refusal: none +journalctl --user -u oab-computer --since '7 days ago' --no-pager | grep 'browser:' +``` + +`refusal` should stay `none`, and the journal lines carry fixed classes only. After a week with no +browser incident on host A, do steps 0 to 7 on hosts B to D together, then soak each for a week. A +browser incident on any host sends that host to the [Rollback](#rollback) and pauses the others. + +**Roll back to here.** The [Rollback](#rollback) works for as long as the old units are not deleted. + +## Rollback + +Use it at any point before the old units are deleted: a failed check, or an incident during the soak. +Set `BK` to the backup directory of step 1. + +```mermaid +flowchart TB + start["A check failed, or an incident happened, and the old units are not deleted yet"] + r1["1 Stop the transient browser unit if present, then stop oab-computer.service"] + r2["2 Optional, oab-computer browser remove to free disk, it restores nothing"] + r3["3 Restore the backed up daemon unit and drop-in, put oab-computer.prev back as the binary, daemon-reload"] + r4["4 Enable and start the old browser unit, then start oab-computer.service"] + r5["5 Verify as in step 6, expecting a listener on 8794"] + start --> r1 --> r2 --> r3 --> r4 --> r5 +``` + +1. Stop the browser and the daemon: + + ```sh + systemctl --user stop 'oab-browser-*.service' + systemctl --user stop oab-computer.service + ``` + +2. Optional, to free disk. It restores nothing: + + ```sh + ~/.local/oab-computer/oab-computer browser remove + ``` + + If step 5.3 had not run yet, that path is still the 0.12.0 binary, which has no `browser` + command: use `~/.local/oab-computer/oab-computer.new` instead, or skip this step. + +3. Restore the daemon unit, the drop-in and the binary from the backup, then reload: + + ```sh + BK= + cp -a "$BK/oab-computer.service" ~/.config/systemd/user/ + for d in oab-computer.service.d oab-instance-mcp.service.d; do + if [ -d "$BK/$d" ]; then cp -a "$BK/$d" ~/.config/systemd/user/; fi + done + install -m 755 "$BK/oab-computer.prev" ~/.local/oab-computer/oab-computer + systemctl --user daemon-reload + ``` + + If step 5.3 had not run yet, the old binary is still in place; `install` over it is harmless. + `pw-mcp.sh` was never touched, so the old unit still finds its script. + +4. Start the old unit and the daemon (set `OLD` first, as in the notation at the top, if this is a new shell): + + ```sh + systemctl --user enable --now "$OLD" + systemctl --user start oab-computer.service + ``` + +5. Verify as in step 6, expecting the old behavior: `ss -ltnH 'sport = :8794' | wc -l` prints `1` or + more, and the tool list shows 32 `browser_*` names. The restored 0.12.0 binary has no `browser` + object in `sys_info`. + +**If the new binary stays but the managed tier misbehaves.** Set `OAB_BROWSER=off` in a drop-in and +restart. With a managed install that means no `browser_*` tools at all: the router ignores a stale +`MCP_UPSTREAM browser=` line, because a managed install wins over it (D5), so `OAB_BROWSER=off` is not a +return to the old external unit, on a host that has not reached step 5 either. (`OAB_BROWSER=off` with +nothing installed and a `MCP_UPSTREAM browser=` line still serves that line as external.) To go back +to the external path, set `MCP_BROWSER_BACKEND=external` as the explicit trust act. External mode needs +the `MCP_UPSTREAM=browser=...` line (still there before step 5, removed in step 5) and the old unit +(running before step 5, stopped in step 5). After step 5, restore both from the backup, start the old +unit, and restart the daemon. + +## Profile migration + +There is none, on purpose (D9). The managed browser starts with a fresh profile under +`${XDG_DATA_HOME:-$HOME/.local/share}/oab-computer/playwright/profile/`, and you sign in again with +`browser signin` (step 5.4). The old profile, `~/.local/oab-computer/pw-profile`, holds the old cookies +and stays where it is. From the first release containing L5, `browser status` lists it in `legacy:` +with its size and `holds_cookies`. No command here copies or moves cookies. + +## Removing the leftovers + +Only a person does this, after the soak, from the list that `browser status` prints (from the first +release containing L5) or from your step 0 inventory. The installer never deletes any of it, and +`browser remove` never touches the old locations (D10). The commands are the ones in +[Removing the old browser setup after the soak](linux-setup.md#removing-the-old-browser-setup-after-the-soak); +the same list, in order: + +1. Disable and delete the old unit files, then reload. No root. Step 5.2 owns the drop-in: it already + removed the dedicated drop-in file, or only the `MCP_UPSTREAM` line from a shared one, and the + backup from step 1 keeps the original for the rollback. Remove a dedicated drop-in here only if you + skipped that part of step 5.2, with `rm -f FILE` before the `daemon-reload` below: + + ```sh + for u in oab-pw-mcp.service oab-computer-pw-mcp.service; do + if systemctl --user cat "$u" >/dev/null 2>&1; then systemctl --user disable --now "$u"; fi + done + rm -f ~/.config/systemd/user/oab-pw-mcp.service ~/.config/systemd/user/oab-computer-pw-mcp.service + systemctl --user daemon-reload + ``` + +2. Delete the old directories, after looking inside: the old profile holds cookies. No root. Check + each path against `browser status` first; `rm -rf` cannot be undone: + + ```sh + du -sh ~/.local/oab-computer/pw-mcp ~/.local/oab-computer/pw-profile ~/.local/oab-instance-mcp/pw-mcp + rm -rf ~/.local/oab-computer/pw-mcp ~/.local/oab-computer/pw-profile ~/.local/oab-instance-mcp/pw-mcp + rm -f ~/.local/oab-computer/pw-config.json ~/.local/oab-computer/pw-mcp.sh + rm -rf ~/.cache/ms-playwright # only if nothing else of yours uses Playwright's cache + ``` + + `~/.local/oab-computer/pw-output` is listed by `status` too: look at it, then remove it the same way. + +3. Unload and delete the old AppArmor profile, in this order. **Needs root:** + + ```sh + sudo apparmor_parser -R /etc/apparmor.d/playwright-chromium && sudo rm /etc/apparmor.d/playwright-chromium + ``` + + The profile of the managed browser is a different file, `/etc/apparmor.d/oab-computer-chromium-`, + and stays. + +4. Delete the old Chromium policy file. **Needs root:** `sudo rm /etc/chromium/policies/managed/oab-computer.json` + (0.11-era installers named it `oab-instance-mcp.json`; remove that one the same way if it is there). + +### Never deleted automatically + +The installer, `browser remove`, `browser status` and this guide's scripts delete none of these. Each +is yours to remove, or to keep: + +| What | Why it stays | +| --- | --- | +| The old units `oab-pw-mcp.service` and `oab-computer-pw-mcp.service`, and the backup copy of the drop-in from step 1 | The rollback needs them until you decide to remove them. | +| `~/.local/oab-computer/pw-mcp`, `pw-output`, `pw-config.json`, `pw-mcp.sh` and `~/.local/oab-instance-mcp/pw-mcp` | The old browser's files. | +| `~/.local/oab-computer/pw-profile` | It holds cookies; look first. | +| `~/.cache/ms-playwright` | Playwright's own cache; another tool of yours may use it. | +| The old AppArmor profile and the Chromium policy file | Root-owned. | +| The backup directory `.../oab-computer/backup-/` and `oab-computer.prev` in it | The rollback source. Keep it until the next release has run well. | +| `oab-computer.service.proposed` and `oab-seat.service.proposed` | The installer never removes or adopts them. | +| The `~/oab-cutover-dl` and the inventory file from this guide | Yours. | + +## Deprecation of `pw-mcp.sh` + +`poc/reverse-attach-linux/pw-mcp.sh` (the script behind the old unit) stays in the tarball for one more +minor release so that a binary rollback has a script to restore, and is removed after that (ADR D14, +tracked in [#141](https://github.com/openabdev/openab-computer/issues/141)). From the first release +containing L5 it carries a `DEPRECATED` header and prints one notice on stderr each time it starts, +but only the copy in the tarball has that. The installer does not copy `pw-mcp.sh` and this guide does not replace the copy at `~/.local/oab-computer/pw-mcp.sh`, so an old unit keeps running the old copy and its journal shows no notice. Its launch arguments are unchanged. +The installer no longer writes the unit. The script opens an unauthenticated listener on +`127.0.0.1:8794` that any local user can reach and that serves `browser_run_code_unsafe`, which is why +this guide exists. + +## Decisions that shape this guide + +Both are decided by the owner; neither is reopened here. + +- **V2, listeners.** The managed tree opens no TCP or UDP socket. It holds two Unix listening sockets + (Playwright's browser socket and Chromium's `SingletonSocket`) inside the child's private per-run + `0700` directory, which is accepted, and nothing else is. `browser status` and the release smoke + fail on any other listener, and on a directory that is not mode `0700` or not the daemon's. The + residual path: a process of the same user can connect to those sockets and drive the managed browser, + as it can already read the profile directory. Another local user and a web page cannot reach them. + The V2 gate is blocking, and each release measures it on amd64 and arm64. +- **D7, the AppArmor profile.** The single path-scoped glob profile that `preflight` prints is kept as + built. Its residual risk: the path is in your own data directory, so code running as you could place a + file named `chrome` there and run it with `userns` allowed. That needs code execution as you first + and returns only the unprivileged user namespace. Not to be confused with the ADR's other D7 rule, + that the installer never runs root actions on its own. + +## What is supported + +Support follows ADR D16: Ubuntu 22.04 and 24.04 on amd64 and arm64 have automated release smoke cells; +Debian 12 has a container job on both architectures; Debian 12 hosts and Raspberry Pi OS hardware get +a manual run per release, recorded in `docs/release-records/linux-VERSION.md`. The table with the +current state is [Supported systems](linux-setup.md#supported-systems). A row is "tested" only when its +record says so; the glibc rule makes a distribution supported without being run. diff --git a/docs/linux-setup.md b/docs/linux-setup.md index 317708d..3af10b4 100644 --- a/docs/linux-setup.md +++ b/docs/linux-setup.md @@ -72,19 +72,21 @@ effort. Alpine and other musl systems are refused with a clear message. | System | glibc | amd64 and arm64 | Automated check | Manual run per release | | --- | --- | --- | --- | --- | -| Debian 12 | 2.36 | supported | not yet (arrives with the release work, L5) | not yet | -| Raspberry Pi OS (Debian 12 or 13 based) | 2.36 (Debian 12), 2.41 (Debian 13) | supported (arm64) | not yet | not yet | -| Ubuntu 22.04 | 2.35 | supported | not yet | not yet | -| Ubuntu 24.04 | 2.39 | supported | not yet | not yet | -| Debian 13 and newer, newer Ubuntu | 2.41 and newer | supported by the rule above, not listed as run | not yet | not yet | +| Debian 12 | 2.36 | supported | Debian 12 container job (install, preflight, health check), from the first release that contains L5 | full run on a Debian 12 host, recorded per release | +| Raspberry Pi OS (Debian 12 or 13 based) | 2.36 (Debian 12), 2.41 (Debian 13) | supported (arm64) | none of its own (the Debian 12 based container job covers the Debian 12 glibc on arm64; Debian 13 is not claimed as tested) | full run on Raspberry Pi OS hardware, recorded per release | +| Ubuntu 22.04 | 2.35 | supported | release smoke, amd64 and arm64, from the first release that contains L5 | covered by the smoke | +| Ubuntu 24.04 | 2.39 | supported | release smoke, amd64 and arm64, from the first release that contains L5 | covered by the smoke | +| Debian 13 and newer, newer Ubuntu | 2.41 and newer | supported by the rule above only; no automated or manual run is listed, so it is not claimed as tested | none | none | | Other glibc distributions | 2.28 or newer | best effort | none | none | | Alpine, other musl systems | n/a | refused | none | none | -"Tested" will mean an automated release smoke, a Debian 12 container job, and a manual full run per -release (ADR D16). None of the three exists yet: until the release work lands, every row says "not -yet", and the table is a statement of intent plus what the preflight checks, not a claim that a -release was run there. `oab-computer browser preflight` checks libc, the glibc floor, user -namespaces, disk and missing libraries on the host in front of you. +"Tested" means an automated release smoke, a Debian 12 container job, and a manual full run per +release (ADR D16). The smoke matrix, the container job and the per-release record are defined in +`.github/workflows/linux-release-smoke.yml` and in [Releasing](releasing.md#linux-release-gates). No +release that contains them has been published yet. Until one is, and until its record is filled in, the +columns above describe what a release will be checked against, not a run that happened, and the table +is a statement of intent plus what the preflight checks. `oab-computer browser preflight` checks libc, +the glibc floor, user namespaces, disk and missing libraries on the host in front of you. ## Prerequisites @@ -144,11 +146,19 @@ A=$(dpkg --print-architecture) # arm64 or amd64 curl -fsSLO "https://github.com/openabdev/openab-computer/releases/download/v$V/oab-computer-$V-linux-$A.tar.gz" curl -fsSLO "https://github.com/openabdev/openab-computer/releases/download/v$V/oab-computer-$V-linux-$A.tar.gz.sha256" sha256sum -c "oab-computer-$V-linux-$A.tar.gz.sha256" +# Optional, from the first release that carries an attestation (0.12.x has none, so this fails there). +# gh attestation verify "oab-computer-$V-linux-$A.tar.gz" --repo openabdev/openab-computer tar xzf "oab-computer-$V-linux-$A.tar.gz" && cd "oab-computer-$V-linux-$A" ./install-linux.sh # does steps 3 and 5 below, then asks about the browser (step 4) ./install-linux.sh --headless-seat # same, on a box with no desktop (creates oab-seat.service) ``` +The attestation check is optional. It needs the GitHub CLI, and it shows that the tarball was built by +this repository's release workflow from a stated commit. It does not make the download safe (ADR D12); +the `.sha256` check stays the required one. Only a release built after the attestation step was added +carries an attestation: the 0.12.x tarballs have none, and `gh attestation verify` finds nothing for +them. See [Verifying a Linux tarball](releasing.md#verifying-a-linux-tarball). + A unit file the installer did not write (no installer marker line) is never rewritten: the installer leaves it as it is and writes the unit it would have used next to it as `*.proposed`. That holds for `oab-computer.service` and `oab-seat.service`. @@ -178,7 +188,7 @@ the flag. | --- | --- | --- | | Linger | `sudo loginctl enable-linger $USER` | The daemon and the browser keep running after you log out and start again at boot. Printed only when linger is off. | | Publish | `sudo tailscale serve --bg --https=8444 http://127.0.0.1:8795` | Exposes the daemon on your tailnet over HTTPS (tailnet only). | -| AppArmor | `printf ... \| sudo tee /etc/apparmor.d/oab-computer-chromium-` then `sudo apparmor_parser -r ...` | Only where `kernel.apparmor_restrict_unprivileged_userns` is 1 (Ubuntu 24.04): Chromium cannot make its sandbox without it. The profile names your own data path, not `/home/*`, and covers every version directory, so it serves later updates. `oab-computer browser preflight` prints the exact text. | +| AppArmor | `printf ... \| sudo tee /etc/apparmor.d/oab-computer-chromium-` then `sudo apparmor_parser -r ...` | Only where `kernel.apparmor_restrict_unprivileged_userns` is 1 (Ubuntu 24.04): Chromium cannot make its sandbox without it. The profile names your own data path, not `/home/*`, and covers every version directory, so it serves later updates. The single glob is the decided design (ADR D7): its path lies in your own data directory, so code running as you could place a file named `chrome` there and run it with `userns` allowed; it needs code execution as you first and gives back only the unprivileged user namespace. `oab-computer browser preflight` prints the exact text. | | Libraries | `sudo apt-get install ...` | Libraries the preflight found missing, with the package names. | | Fonts | `sudo apt-get install -y fonts-dejavu-core fonts-liberation fonts-noto-cjk fonts-noto-color-emoji` | A server has none and pages render as boxes. Printed only when no font is found, and only in a run that does the browser step (not with `--browser none`). | @@ -314,8 +324,8 @@ needed, unless you install from files (see [Offline install](#offline-install)). There is no quarantine step on Linux. - The Chromium it installs is a browser: the connections it makes while running are Chromium's, not the installer's. In the project's own measurement of the pinned build the managed tree held no - TCP or UDP socket and two private Unix sockets (see [Ports](#ports)); that is still an open - release gate (V2 in the [ADR](adr/linux-browser-tier.md)), and whether the browser exits when its + TCP or UDP socket and two private Unix sockets (see [Ports](#ports)); the rule for those (V2, decided in + the [ADR](adr/linux-browser-tier.md)) is checked by every release smoke, and whether the browser exits when its stdin closes (V3) has not been measured. The daemon stops the child's whole process tree itself when it stops it. - The install adds no unit and no network port. An update is only ever offered, never applied silently. @@ -339,11 +349,18 @@ the profile and output folders stay. `remove` refuses while a managed browser is ### Ports The managed browser has no TCP or UDP port and does not use `8794`. The daemon listens on -`127.0.0.1:8795`; `tailscale serve` uses `--https=8444`. Chromium holds two Unix listening sockets in the child's own `0700` temporary directory. They -are not TCP or UDP ports, but they are listeners: another process of the same user can connect to -them, so the claim "no socket of any kind" is not made. (The ADR and requirement R1.1 state "no Unix -listener" as a target that is unmet today; V2 is not closed until the release smoke measures it on -both architectures.) Port `8794` is bound only by +`127.0.0.1:8795`; `tailscale serve` uses `--https=8444`. Chromium and Playwright hold two Unix listening sockets in the child's own `0700` temporary +directory. They are not TCP or UDP ports, but they are listeners: another process of the same user +can connect to them and drive the managed browser, so the claim "no socket of any kind" is not made. +The rule (V2, decided in the ADR and requirement R1.1): no TCP or UDP listener, and every Unix listener +inside that private directory, which must be a real directory of the daemon's uid with mode exactly +`0700`. `browser status` shows `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass` +while the browser runs, and `result=fail` for anything else (run it in the daemon's user session, so +`XDG_RUNTIME_DIR` matches the daemon's). While `browser signin` holds the browser, `status` counts that tree's +Unix sockets, which sit in another temporary directory, as `unix_outside>0 result=fail`. This is a false alarm that fails +closed; close the sign-in window and run `status` again. Another local user is refused by the directory and the socket +mode, and a web page cannot reach a Unix socket path. The release smoke measures the rule on amd64 +and arm64 for every release. Port `8794` is bound only by an old browser unit (unauthenticated, loopback) or by whatever you start yourself for `MCP_BROWSER_BACKEND=external`. @@ -421,9 +438,24 @@ without that tier), `not_applicable` (nothing is installed yet) or `not_checked` mount tier still runs without the protection the probes did not confirm. The base tier is different: where the full base list cannot start at all (a user manager that refuses a property such as `ProtectKernelModules`, as on some Ubuntu 24.04 hosts with restricted user namespaces), the -containment check reports `unverified` and the managed browser is unavailable until that is fixed. A listing of leftovers -from an old setup (old units, old directories with sizes, the old profile that holds cookies) is -not in `status` yet: use the checklist under +containment check reports `unverified` and the managed browser is unavailable until that is fixed. + +Three more fields list what the old external setup left behind. They exist from the first release +that contains L5, and they only read: `status` never stops, moves or deletes any of it (D10). +`legacy_units` is `none` or a comma list of `oab-pw-mcp.service`, `oab-computer-pw-mcp.service` +(unit files in `~/.config/systemd/user/`) and `drop-in:oab-computer.service.d` or +`drop-in:oab-instance-mcp.service.d` (a drop-in directory with a `*.conf` with an active +`Environment=MCP_UPSTREAM=` line; the file's content and the URL are never shown). `legacy` is `none` or a comma +list of `:` for the old directories and files (`~/.local/oab-computer/pw-mcp`, +`pw-profile`, `pw-output`, `pw-config.json`, `pw-mcp.sh`, `~/.local/oab-instance-mcp/pw-mcp`, +`~/.cache/ms-playwright`); the old profile carries `:holds_cookies`, a link is `:symlink` and is not +followed, and a size that could not be taken is `:size_unknown`. Sizes are apparent sizes in a +fixed unit (`B`, `KiB`, `MiB`, `GiB`). `legacy_listener` is `8794` when a TCP socket listens on the +old unit's port (any owner, since that port has no authentication), `none`, or `unknown` when the +table cannot be read. `legacy_units` and `legacy` say `unknown` when `HOME` is not set; `legacy_listener` is still probed. When any of them shows +something, the human output adds one line that points at +[the cutover guide](linux-cutover.md); `--json` has the fixed fields only. Removing what they list +is a person's job: use that guide and the checklist under [Removing the old browser setup after the soak](#removing-the-old-browser-setup-after-the-soak). ### Flags and environment variables @@ -565,7 +597,7 @@ code). Turn that unit off after the cutover (see ## 6. Verify from another tailnet machine ```sh -TOKEN=$(ssh cat ~/.config/oab-computer/token) +TOKEN=$(ssh 'cat ~/.config/oab-computer/token') U=https://..ts.net:8444 curl -s $U/healthz # ok curl -s -o /dev/null -w '%{http_code}\n' -X POST $U/mcp -H 'Authorization: Bearer nope' -d '{}' # 401 @@ -804,8 +836,8 @@ The installer never stops, disables, edits or deletes an old browser unit, a dro directory, an old profile or an old AppArmor profile, and never copies cookies. The managed browser starts with a fresh profile, so a migrated host signs in again (`browser signin`); the old profile stays where it is and holds the old cookies until you delete it. The cutover itself is a procedure -for a person -([requirements, section 2](requirements/linux-browser-tier.md#2-cutover-runbook)). What the +for a person: [the cutover guide](linux-cutover.md) has the commands, the checks and the rollback of each step +([requirements, section 2](requirements/linux-browser-tier.md#2-cutover-runbook) is the design). What the installer does on each kind of host: | Host | What the installer does | What you do at cutover | @@ -838,21 +870,25 @@ below is marked if it needs root. ```sh ls ~/.config/systemd/user/ | grep -E 'pw-mcp|oab-instance-mcp' - grep -l MCP_UPSTREAM ~/.config/systemd/user/oab-computer.service.d/*.conf \ - ~/.config/systemd/user/oab-instance-mcp.service.d/*.conf 2>/dev/null # the drop-in file or files + grep -nE "^[[:space:]]*Environment=(['\"]|[^#;]*[[:space:]'\"])?MCP_UPSTREAM=" \ + ~/.config/systemd/user/oab-computer.service.d/*.conf \ + ~/.config/systemd/user/oab-instance-mcp.service.d/*.conf 2>/dev/null # file:line of each active assignment ``` - Disable each old unit that exists, then delete exactly the files that listing printed (for - example `oab-pw-mcp.service`, or `oab-computer-pw-mcp.service`, and the drop-in file it named), - then reload. `rm -f` does not fail on a file the host never had. Do not delete a drop-in the - `grep` did not list: others may belong to something else. No root: + Disable each old unit that exists and delete the old unit files. Then, for each file the `grep` + printed, run `cat` on it. If it holds nothing but `[Service]`, that one `Environment=MCP_UPSTREAM=` + line, comments and blank lines, it is the dedicated drop-in and `rm -f` removes it. If it holds + any other setting, delete only that line (`sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp$/d' FILE`, or an + editor if the line also sets other variables) and keep the file. A file the `grep` did not list + is not touched: it may belong to something else. Reload last. No root: ```sh for u in oab-pw-mcp.service oab-computer-pw-mcp.service; do if systemctl --user cat "$u" >/dev/null 2>&1; then systemctl --user disable --now "$u"; fi done rm -f ~/.config/systemd/user/oab-pw-mcp.service ~/.config/systemd/user/oab-computer-pw-mcp.service - rm -f + cat FILE # for each file the grep printed + rm -f FILE # only a dedicated file, as described above systemctl --user daemon-reload ``` @@ -892,8 +928,12 @@ below is marked if it needs root. 0.12.0 and earlier started Playwright as a separate unit, `oab-computer-pw-mcp.service`, on `127.0.0.1:8794`, with `MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp` in the daemon unit, started -by `poc/reverse-attach-linux/pw-mcp.sh` (kept in the tarball for one more release, to be marked -deprecated by the release PR L5, so that a binary rollback has a script to restore). That path has no authentication on the listener +by `poc/reverse-attach-linux/pw-mcp.sh` (kept in the tarball for one more release so that a binary +rollback has a script to restore, and, from the first release that contains L5, marked deprecated: a +header comment, and a notice on stderr each time it starts, in the tarball's copy only: the installer +does not copy the script, so an old unit still runs the copy it already has and shows no notice; the +launch itself is unchanged). The script is removed in the minor release after that (D14). Moving off +it is described in [the cutover guide](linux-cutover.md). That path has no authentication on the listener and no pinned downloads; it is only for a host that has not moved, or for `MCP_BROWSER_BACKEND=external`. Its pieces: `PW_CHROMIUM` and `PW_NODE_BIN` (the script's own environment, default `/usr/bin/chromium`), a persistent profile under diff --git a/docs/release-records/TEMPLATE.md b/docs/release-records/TEMPLATE.md new file mode 100644 index 0000000..847d56f --- /dev/null +++ b/docs/release-records/TEMPLATE.md @@ -0,0 +1,91 @@ +# Linux release record, VERSION + +Copy this file to `docs/release-records/linux-VERSION.md` (VERSION without the leading `v`), fill it +in against the release candidate, and commit it to `main` **before** the tag. The `record` job of +`.github/workflows/linux-release-smoke.yml` runs `scripts/check-release-record.sh VERSION` and +fails a release when the file is missing, when any table row still holds the placeholder +`PENDING`, when the `V2` or `D7` row is missing or says `open, owner decision pending`, when any of V1 to V13 lacks exactly one row of four cells, or when any of M1 to M10 or any of the six smoke cells lacks exactly one row or has a result other than `pass` (case does not matter; no `n/a`: ADR D16 requires these every release), or when a +blocking gate row is not `pass` (V1, V2 and V7 take only `pass`; another blocking row may read `n/a` with a reason). + +Rules for the person filling it in: + +- Replace every `PENDING` with a result. Write `n/a` and the reason only on a V3 to V13 row that does not apply (never on a blocking row); + never delete a row. M1 to M10 and the six smoke cells take `pass` only. + A gate row whose Blocking cell says `yes` (V1, V2, V7) must read `pass` and nothing else (no `n/a`); `fail` or + anything else fails the record check. +- Record what you ran and saw. No host names, tailnet names, addresses, logins or tokens: name a host + by class ("amd64 desktop", "arm64 desktop", "headless-seat host"). +- The `V2` and `D7` rows record decisions the owner made ([the ADR](../adr/linux-browser-tier.md)). + Never remove those rows, and never change them to say the decision is open again without the owner. + The `V2` result still needs the measurement: quote the `GATE V2 pass` line of each architecture. +- This record is the manual half of "Tested" (ADR D16, requirement R7.4). The automated half is the + smoke run linked below. + +## Release + +| Field | Value | +| --- | --- | +| Version | PENDING | +| Commit | PENDING | +| Date | PENDING | +| Person | PENDING | +| Smoke run URL (`linux-release-smoke.yml`, dispatched on the release candidate) | PENDING | + +## Automated smoke cells (section 3.3, from the smoke run above) + +| Cell | Result | Notes | +| --- | --- | --- | +| Ubuntu 22.04 amd64 | PENDING | PENDING | +| Ubuntu 22.04 arm64 | PENDING | PENDING | +| Ubuntu 24.04 amd64 | PENDING | PENDING | +| Ubuntu 24.04 arm64 | PENDING | PENDING | +| Debian 12 container amd64 | PENDING | PENDING | +| Debian 12 container arm64 | PENDING | PENDING | + +## Manual checks (section 3.4, M1 to M10) + +| Check | Result | Date | Host class | Notes | +| --- | --- | --- | --- | --- | +| M1 amd64 desktop host with a seat: install, consent text, sign-in, restart, session persists | PENDING | PENDING | PENDING | PENDING | +| M2 arm64 desktop host with a seat: the same, plus memory in use | PENDING | PENDING | PENDING | PENDING | +| M3 Headless-seat host with the AppArmor restriction: profile listed, health check fails without it and succeeds with it, sign-in through `screenshot`, `mouse` and `key` | PENDING | PENDING | PENDING | PENDING | +| M4 Each architecture: full install and run on a Debian 12 host and on Raspberry Pi OS hardware, glibc floor against the oldest supported OS | PENDING | PENDING | PENDING | PENDING | +| M5 Transient-unit mode: `kill -9` the daemon, restart, `systemctl stop`, reboot; `browser signin` over SSH and `kill -9` the CLI; a hand-started daemon is refused (`daemon_not_unit_main`) | PENDING | PENDING | PENDING | PENDING | +| M6 `browser update` with a deliberately broken pin (debug build) keeps the old version | PENDING | PENDING | PENDING | PENDING | +| M7 `browser remove` with an unrelated directory inside the data root: it stays and is reported | PENDING | PENDING | PENDING | PENDING | +| M8 Cutover rehearsal on a spare account for each host class, then rollback | PENDING | PENDING | PENDING | PENDING | +| M9 No TCP or UDP listener, and any Unix listener inside the private per-run `TMPDIR` (V2): `ss -ltnup` and `ss -lxp` during a browser call | PENDING | PENDING | PENDING | PENDING | +| M10 The hosts' real network: the downloads work through each host's actual egress | PENDING | PENDING | PENDING | PENDING | + +The wording of each check is in section 3.4 of +[the requirements](../requirements/linux-browser-tier.md); that text wins over the short names here. + +## Release gates (section 3.5, V1 to V13) + +"Blocking" is what section 3.5 says, not a choice made here. V2 and D7 are the two owner decisions, both decided. + +| Gate | Result | Evidence | Blocking | +| --- | --- | --- | --- | +| V1 each platform has a pinned-version Chromium source | PENDING | PENDING | yes | +| V2 no TCP or UDP listener, Unix listeners only inside the private `TMPDIR`, on both architectures | PENDING | the smoke's `GATE V2 pass` line for amd64 and for arm64 | yes | +| V3 stdin EOF and Chromium exit timing after daemon `SIGKILL` | PENDING | the smoke's `GATE V3` line | no (informational) | +| V4 `systemd-run --user --pipe`, `BindsTo`, `NoNewPrivileges` with AppArmor | PENDING | the smoke's `GATE V4` line | no (the tier is unavailable if `BindsTo` does not fire; the smoke cell still fails) | +| V5 `minGlibc` below the oldest supported OS | PENDING | PENDING | no (narrow the matrix) | +| V6 headed Wayland Chromium, sign-in survives a restart | PENDING | PENDING | no (doc fix) | +| V7 cookies readable headed and headless with `--password-store=basic` | PENDING | PENDING | yes (for sign-in) | +| V8 policy directory against a launch flag | PENDING | PENDING | no | +| V9 ELF preflight against the loader | PENDING | the smoke's `GATE V9` line | no | +| V10 `playwright-core` native dependency table | PENDING | PENDING | no | +| V11 `ProtectHome=read-only` in a user manager | PENDING | the smoke's `GATE V11` line | no (drop the namespace tier) | +| V12 `/proc/net/tcp` owner uid | PENDING | PENDING | no (fail closed) | +| V13 `wayvnc` options | PENDING | PENDING | no | +| D7 AppArmor profile: the single path-scoped glob profile is kept (decided; residual risk in the ADR) | decided, glob kept | M3 above is the evidence | no | + +## Support table rows to update (ADR D16) + +| Row of the supported-systems table in `docs/linux-setup.md` | Automated check | Manual run | +| --- | --- | --- | +| Debian 12 | PENDING | PENDING | +| Raspberry Pi OS | PENDING | PENDING | +| Ubuntu 22.04 | PENDING | PENDING | +| Ubuntu 24.04 | PENDING | PENDING | diff --git a/docs/releasing.md b/docs/releasing.md index 448f6be..cb21ff8 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -13,7 +13,7 @@ A `vMAJOR.MINOR.PATCH` tag publishes a GitHub Release titled `oab-computer VERSI | `oab-computer-VERSION-universal.pkg` | Recommended. Double-click; installs/configures the app for the logged-in desktop user | | `oab-computer-VERSION-universal.app.zip` | Pre-signed app, no package receipt. Contains `Contents/Resources/install-prebuilt.sh` for manual installation | | `SHA256SUMS` | SHA-256 of the two macOS artifacts | -| `oab-computer-VERSION-linux-amd64.tar.gz`, `oab-computer-VERSION-linux-arm64.tar.gz` | The Linux node and `install-linux.sh`, each with a `.sha256` file beside it | +| `oab-computer-VERSION-linux-amd64.tar.gz`, `oab-computer-VERSION-linux-arm64.tar.gz` | The Linux node and `install-linux.sh`, each with a `.sha256` file beside it. From the first release built by the attesting workflow, each tarball also has a build-provenance attestation (see [Verifying a Linux tarball](#verifying-a-linux-tarball)) | Since 0.12.0 the asset names (`oab-computer-VERSION-*`), the binary, the bundle id and the install paths all use `oab-computer` (up to 0.11 they were `oab-instance-mcp`). @@ -81,14 +81,26 @@ deleted in an `always()` cleanup step. ## Cut a release -The flow below is what the steps and the `Release macOS installer` workflow do. The three jobs -run in parallel after approval. The Linux jobs wait for the release that the macOS job creates. +The flow below is what the steps and the `Release macOS installer` workflow do. A `smoke` stage (the +Linux release gates, see [Linux release gates](#linux-release-gates)) runs first and needs no approval, +because it holds no secret. Both release jobs `need` it: a red gate stops everything before anything +is signed or published. After the approval the macOS job and the two Linux jobs run in parallel, and +the Linux jobs wait for the release that the macOS job creates. ```mermaid flowchart TB bump["Bump version in main.swift and merge with green CI"] + record["Commit docs/release-records/linux-VERSION.md, every row filled"] tag["Tag the main commit vMAJOR.MINOR.PATCH and push the tag"] - approve["A reviewer approves the release environment, all three jobs wait for it"] + + subgraph gates["smoke stage, linux-release-smoke.yml, read-only, no secrets, no approval"] + g1["pins: offline and online check, all four platforms"] + g2["smoke: Ubuntu 22.04 and 24.04, amd64 and arm64"] + g3["debian12: container job, amd64 and arm64"] + g4["record: the file exists, no PENDING, V2 and D7 decided"] + end + + approve["A reviewer approves the release environment, the three release jobs wait for it"] subgraph mac["macOS job on macos-15"] m1["Validate the tag against main.swift and check the release secrets"] @@ -107,13 +119,22 @@ flowchart TB l1["Validate the tag against the version source"] l2["cargo build and the smoke test"] l3["Package the tarball and its sha256 file"] + l3a["Attest the build provenance of the tarball"] l4["Wait for the release to exist, then upload both files"] - l1 --> l2 --> l3 --> l4 + l1 --> l2 --> l3 --> l3a --> l4 end verify["Download the artifacts, run verify-release.sh and shasum -c, install the pkg on a test Mac, check sys_info and make one reverse attach call"] - bump --> tag --> approve + bump --> record --> tag + tag --> g1 + tag --> g2 + tag --> g3 + tag --> g4 + g1 --> approve + g2 --> approve + g3 --> approve + g4 --> approve approve --> m1 approve --> l1 m8 -. "release now exists" .-> l4 @@ -127,6 +148,9 @@ flowchart TB 2. Ensure the matching active-team release secrets above exist, and that the Playwright pins are current (see [Playwright pins](#playwright-pins)). The workflow runs the same check and a drifted pin stops the release before anything is built. + Go through the [Linux release checklist](#linux-release-checklist) before tagging: the smoke + dispatch is green, `docs/release-records/linux-VERSION.md` is committed and finished, and the two + owner decisions are closed. 3. Tag the exact main commit and push: ```sh @@ -134,12 +158,13 @@ flowchart TB git push origin v0.12.1 ``` -4. The `Release macOS installer` workflow runs the tests and the Playwright pins check, then builds, +4. The `Release macOS installer` workflow first runs the Linux release gates (the `smoke` job), then the tests and the Playwright pins check, then builds, signs, notarizes and publishes the macOS artifacts. From the same run it also publishes `oab-computer-VERSION-linux-{arm64,amd64}.tar.gz` and a `.sha256` for each (Linux tarballs exist since 0.6.5; before 0.12.0 they were named `oab-instance-mcp-VERSION-linux-*`). - All three jobs wait for a reviewer to approve the `release` environment, so open the run and - approve it, or nothing starts. A manual + The three release jobs wait for a reviewer to approve the `release` environment, so open the run + and approve it, or nothing starts. Check first that the `smoke` job of the run is green + (`gh run view RUN_ID`); approve only then. A manual dispatch can retry an existing tag; it is not a way to release an untagged commit, and it **must run on the tag ref** — the environment only allows `v*` refs, so a dispatch from `main` is rejected before any job starts ("Branch main is not allowed to deploy to release"): @@ -169,6 +194,183 @@ must carry the upgrade table and the operator steps from happens to `desktop` requests, to stored `desktop` grants and to a `switchboard.profile` of `desktop`, and how to grant `owner` again. +## Linux release gates + +The Linux managed browser tier ([requirements](requirements/linux-browser-tier.md), section 3.3 to +3.5, and ADR D16) is released only when these pass. They live in +`.github/workflows/linux-release-smoke.yml`, which `release.yml` calls as its first job (`smoke`) and +which can be dispatched on its own. Every release, including a macOS-only hotfix, needs this smoke to be green +and a complete Linux release record, because `smoke` is a prerequisite of both release jobs. The dispatch builds and smokes only: it publishes nothing, +creates no tag and no release, and holds no secret. + +```sh +gh workflow run linux-release-smoke.yml --ref BRANCH_OR_TAG +gh run list --workflow linux-release-smoke.yml --limit 3 +gh run view RUN_ID +``` + +```mermaid +flowchart TB + start["tag push (release.yml, strict) or workflow_dispatch (report only)"] + pins["pins: verify --offline, verify --online, all four platforms in pins.json"] + cells["smoke cells: ubuntu-22.04 and ubuntu-24.04, each amd64 and arm64"] + deb["debian12 container: amd64 and arm64"] + rec["record: docs/release-records/linux-VERSION.md"] + um{"systemctl --user is-system-running is running or degraded"} + cell["install, headless health check, harness as main process of a transient unit"] + v4{"V4: containment is systemd or systemd+mount"} + v2{"V2: no TCP or UDP, Unix only in the private TMPDIR"} + kill["kill -9 the harness, wait for the tree to go"] + surv{"survivors under the install directory"} + ok["cell green"] + red["cell red, the release is blocked"] + start --> pins + start --> cells + start --> deb + start --> rec + cells --> um + um -- no --> red + um -- yes --> cell --> v4 + v4 -- no --> red + v4 -- yes --> v2 + v2 -- no --> red + v2 -- yes --> kill --> surv + surv -- yes --> red + surv -- no --> ok +``` + +Each cell prints one `GATE pass|fail|info` line per gate, so the manual record can quote it. +The release is blocked when any of these is red. + +### The matrix + +| Job | Where | What it runs | +| --- | --- | --- | +| `pins` | `ubuntu-latest` | `playwright-pins.py verify --offline`, then `verify --online` (every platform artifact re-downloaded, `minGlibc`, `needed` and hints recomputed), then an assertion that Node.js and Chromium are pinned for `darwin-arm64`, `darwin-x64`, `linux-x64` and `linux-arm64` (V1, V5, V10) | +| `smoke` Ubuntu 22.04 amd64 | `ubuntu-22.04` | real `browser install` into a temporary `HOME`, headless health check, harness, listener self-check, `kill -9`, survivor check | +| `smoke` Ubuntu 22.04 arm64 | `ubuntu-22.04-arm` | the same | +| `smoke` Ubuntu 24.04 amd64 | `ubuntu-24.04` | the same, with the AppArmor user-namespace restriction relaxed on the runner | +| `smoke` Ubuntu 24.04 arm64 | `ubuntu-24.04-arm` | the same | +| `debian12` amd64 | `ubuntu-24.04`, Debian 12 container pinned by digest | install, preflight and the health check, as a non-root user (the preflight root actions run as root inside the throwaway container), up to the containment check (a container has no user manager) | +| `debian12` arm64 | `ubuntu-24.04-arm`, the same image | the same | +| `record` | `ubuntu-latest` | `scripts/check-release-record.sh VERSION` (fails a release, reports on a dispatch) | + +The smoke cells provide their own user manager (linger, the per-user service of the runner uid, `XDG_RUNTIME_DIR`) and +check `systemctl --user is-system-running` before they start. Unlike the optional per-PR +`linux-systemd.yml`, a cell **fails** when no manager is available, because that blocks the release +(requirements 3.3). On the throwaway runner the cells set +`kernel.apparmor_restrict_unprivileged_userns=0` and the log says so. That is a property of the +ephemeral runner, not advice for hosts. The Debian 12 job also runs its container with +`seccomp=unconfined` and `apparmor=unconfined`, for the same reason (Chromium's sandbox needs a user +namespace), and its log says so. The binary under test is built on the runner and is the one that runs +on Debian 12, so the job also shows that it runs on glibc 2.36. The release tarballs are built on +`ubuntu-24.04` (amd64) and `ubuntu-24.04-arm` (arm64), the same images as the 24.04 smoke cells, so those +cells test the same toolchain and glibc as the shipped binaries. + +Not automated, a person does them once per release and records them: Debian 12 hosts and Raspberry Pi +OS hardware (a full run per architecture, M4), and M1 to M3 and M5 to M10 of +[the requirements](requirements/linux-browser-tier.md#34-manual-checklist-on-real-nodes). + +### Gates, as the requirements define them + +Section 3.5 decides which facts block a release. Only V1, V2 and V7 are named as blocking there. V4 +fails a cell because its self-test fails when `BindsTo` does not fire. V3 is informational: the smoke +prints how long the tree took to go after `kill -9`, and no job fails on it. + +| Gate | Where it is checked | Blocks a release | +| --- | --- | --- | +| V1 a pinned Chromium source for each platform | `pins` job, and `GATE V1` in each cell | yes | +| V2 no TCP or UDP listener, Unix listeners only inside the private TMPDIR, both architectures | `GATE V2` in each cell | **yes** (decided) | +| V3 Chromium exit timing after `kill -9` | `GATE V3`, informational | no | +| V4 `BindsTo` fires, containment verified | `GATE V4` in each cell | yes, through the cell | +| V5 `minGlibc` below the oldest supported OS | `verify --online` and the Ubuntu 22.04 and Debian 12 jobs | narrows the matrix | +| V6 headed Wayland Chromium, sign-in survives a restart | manual record | doc fix | +| V7 cookies readable headed and headless | manual record | yes, for the sign-in flow | +| V8 policy directory against a launch flag | manual record | no | +| V9 ELF preflight against the loader | `GATE V9` (informational) and the record | no | +| V10 `playwright-core` dependency table | `verify --online` | no | +| V11 `ProtectHome=read-only` in a user manager | `GATE V11` (informational) and the record | no | +| V12 `/proc/net/tcp` owner uid | code fails closed; the record | no | +| V13 `wayvnc` options | manual record | no | + +### Owner decisions: V2 and D7 (decided) + +Both are decided. Neither was decided by this workflow, and neither gate is weakened by the decision. + +- **V2: listeners.** Requirement R1.1 now reads: no TCP or UDP listener, and any Unix listener in the + managed tree inside the child's private per-run `0700` `TMPDIR`, owned by the daemon's uid. The tree + holds two such sockets (Playwright's browser socket and Chromium's `SingletonSocket`). `GATE V2` fails + on any TCP or UDP listener, on any Unix listener outside that directory, on a `TMPDIR` that is not + mode `0700` or not the daemon's uid, and on a listener table that cannot be read, and it has no + other allow-list. The gate is blocking and is measured by every release on both architectures; it is + closed for a release only when both cells print `GATE V2 pass`. +- **D7: the AppArmor profile.** The single path-scoped glob profile that `browser preflight` prints is + kept as built; the residual risk (code running as the same user can place a file named `chrome` under + the data path and run it with `userns` allowed) is written in the ADR and in `linux-setup.md`. + M3 stays in the record as the evidence. Do not confuse this with the ADR's other D7 rule, that the + installer never runs root actions on its own. + +`scripts/check-release-record.sh` still fails a record whose `V2` or `D7` row is missing or says +`open, owner decision pending`: a row that reopens the decision blocks the release. It also fails a +record in which a blocking gate row (V1, V2, V7) is not `pass`. These three accept no `n/a`; put a reason in the Evidence cell. + +### The per-release manual record + +The record for a release is `docs/release-records/linux-VERSION.md` (VERSION without the `v`), copied +from [`docs/release-records/TEMPLATE.md`](release-records/TEMPLATE.md). A person fills it in against +the release candidate (the commit the smoke dispatch just passed on) and commits it to `main` +**before** the tag. It lists the smoke run URL and the six automated cells, M1 to M10, V1 to V13 with +the blocking column, and the support-table rows to update. Every unfilled cell is the word `PENDING`. + +The `record` job fails a release when the file is missing, when any table row still has `PENDING`, +when the `V2` or `D7` row is missing or still says `open, owner decision pending`, when any of V1 to V13 +is missing, duplicated or not four cells wide, or when V1, V2 or V7 is not `pass` (another blocking row +needs `pass` or `n/a, reason`), or when any of M1 to M10 or any of the six smoke cells is missing, duplicated or malformed, or has a +result other than `pass` (case does not matter; ADR D16 makes these a per-release requirement, so `n/a` is refused). It never fills a +row for anyone. On a dispatch it reports and passes. The requirements ask for "a release requirement" +and "a person records each result"; this file and this check are how that becomes verifiable. + +### Linux release checklist + +Before tagging a release that contains the managed Linux tier: + +1. `python3 scripts/playwright-pins.py verify --offline` and `scripts/test-release-smoke-linux.sh` + pass locally or in CI. +2. Dispatch `linux-release-smoke.yml` on the release candidate and read every `GATE` line. All of + `pins`, the four cells and the two Debian 12 jobs are green, including `GATE V2 pass` on amd64 and + arm64. +3. Copy `docs/release-records/TEMPLATE.md` to `docs/release-records/linux-VERSION.md`, run the manual + rows, fill every `PENDING`, and commit it to `main`. +4. The `V2` row of the record quotes the two `GATE V2 pass` lines (amd64 and arm64). The decision + itself is in the ADR. +5. The `D7` row of the record says the single glob profile is kept, with the M3 result beside it. +6. Update the supported-systems table in [`linux-setup.md`](linux-setup.md#supported-systems) from the + record. +7. Tag. After the run starts, check that `smoke` is green before approving the `release` environment. + +## Verifying a Linux tarball + +Every `oab-computer-VERSION-linux-ARCH.tar.gz` has a `.sha256` file beside it, and the checksum is +the required check: + +```sh +sha256sum -c "oab-computer-$V-linux-$A.tar.gz.sha256" +``` + +A Linux tarball built by this workflow also carries a signed build-provenance attestation (GitHub +artifact attestations, SLSA provenance). It is an **optional** extra check. With the GitHub CLI: + +```sh +gh attestation verify "oab-computer-$V-linux-$A.tar.gz" --repo openabdev/openab-computer +``` + +Add `--signer-workflow openabdev/openab-computer/.github/workflows/release.yml` to also require that +the file was built by the release workflow. The attestation proves that this repository's workflow +built that exact file from a stated commit. It does **not** make the download safe: it says where the +file came from, not what the code does (ADR D12). Only the tarball is attested, not its `.sha256` +file. Attestations exist only for releases built after the attestation step was added to +`release.yml`; the 0.12.x tarballs have none, and `gh attestation verify` finds nothing for them. + ## Playwright pins `release/playwright-pins/pins.json` is schema 2. Node and Chromium artifacts are keyed by platform id diff --git a/docs/requirements/linux-browser-tier.md b/docs/requirements/linux-browser-tier.md index 6f2cf69..3882a96 100644 --- a/docs/requirements/linux-browser-tier.md +++ b/docs/requirements/linux-browser-tier.md @@ -1,7 +1,9 @@ # Requirements: Linux managed Playwright tier -> **Status:** accepted design, implemented through L4 (the installer, `browser signin`, the docs and -> the hardening tiers with their probes are in; L5, L6 and the cutover are not). The 0.12.0 release does not contain it. The operator guide +> **Status:** accepted design, implemented through L5 (the installer, `browser signin`, the docs, the +> hardening tiers with their probes, the release smoke, provenance, the deprecated `pw-mcp.sh`, the +> legacy listing and the cutover guide [`docs/linux-cutover.md`](../linux-cutover.md) are in; L6 and the +> cutover itself, which a person performs, are not). V2 and D7 are decided (below). The 0.12.0 release does not contain it. The operator guide > is [`docs/linux-setup.md`](../linux-setup.md). - **Issues:** [#119](https://github.com/openabdev/openab-computer/issues/119), [#118](https://github.com/openabdev/openab-computer/issues/118) @@ -13,9 +15,10 @@ ### R1. Managed child - R1.1 `@playwright/mcp` runs as a stdio child of the daemon. No TCP or UDP listener exists in the - managed tree. Port 8794 is not used by the managed path. Target: no Unix listener either. **Unmet - by the L2 build**, which holds two private Unix listening sockets (V2, #132); the docs claim only - "no TCP or UDP port". + managed tree. Port 8794 is not used by the managed path. **Decided (V2):** any Unix listener in the managed tree is inside the child's private per-run `0700` `TMPDIR`, owned by the daemon's uid. The + Playwright browser socket and Chromium's `SingletonSocket` are the two expected ones. `browser status` + and the release smoke fail on a TCP or UDP listener, on a Unix listener outside that directory, and + on a `TMPDIR` that is not mode `0700` or not the daemon's. A process of the same user can still connect to those sockets and drive the managed browser, including its signed-in profile; that user can already read the profile directory, so this adds a second control path and no data access. Another local user is refused (the `0700` directory and the socket file mode; `EACCES` in a measurement), and a web page cannot reach a Unix socket path. - R1.2 The child is started only under a kernel-enforced whole-tree stop mechanism that succeeded in a self-test on the host (D4). Otherwise the backend is `unavailable: containment_unverified` and no child is started. @@ -97,7 +100,8 @@ - R6.3 An upgrade never touches an existing old browser unit. If one is enabled or active, the installer prints a warning with the exact `systemctl --user disable --now ` command. A plain stop is not enough, because those units restart at login or boot. -- R6.4 `browser status` reports `legacy_units`, `legacy` paths with sizes, `listeners`, +- R6.4 `browser status` reports `legacy_units`, `legacy` paths with sizes, `legacy_listener` (`8794`, + `none` or `unknown`: the old unit's own port, which is not part of the managed tree), `listeners`, `containment`, `external_configured` (yes or no, no URL), and the manifest and install ids. It contains no URL, token or page data, and `--json` emits only fixed fields. @@ -127,7 +131,7 @@ person, not a PR. Hosts fall into two classes: Facts such as which unit is enabled, which profile is in use and how large the old directories are are collected in step 0, not assumed. -The order of the steps in section 2.2 is below. The managed tier is built through L4 and not released, so this is the +The order of the steps in section 2.2 is below. The managed tier is built through L5 and not released, so this is the procedure for when it ships. A failed check at any point leads to the rollback in section 2.4. ```mermaid @@ -241,7 +245,7 @@ flowchart TB r2["2 Optional, oab-computer browser remove to free disk, it restores nothing"] r3["3 Restore the backed up daemon unit and drop-in, put oab-computer.prev back as the binary, daemon-reload"] r4["4 Enable and start the old browser unit, then start oab-computer.service"] - r5["5 Verify as in step 6, expecting a listener on 8794 and backend external"] + r5["5 Verify as in step 6, expecting a listener on 8794 (the previous binary has no browser object in sys_info)"] start --> r1 --> r2 --> r3 --> r4 --> r5 ``` @@ -252,7 +256,7 @@ flowchart TB run `daemon-reload`. 4. Enable and start the old browser unit with `systemctl --user enable --now`, then start `oab-computer.service`. -5. Verify as in step 6, expecting the old behaviour: a listener on 8794 and `backend: external`. +5. Verify as in step 6, expecting the old behaviour: a listener on 8794 (the previous binary, 0.12.0, has no `browser` object in `sys_info`). If the new binary stays but the managed tier misbehaves, set `OAB_BROWSER=off` in a drop-in and restart. With a managed install that means no `browser_*` tools at all: the router ignores a stale @@ -301,7 +305,8 @@ unit, and restart the daemon. - With a test double whose self-test fails, the backend is `unavailable: containment_unverified` and nothing is spawned. With one that succeeds, the child starts. - A production start waits up to 10 s for `.sweep.lock` and holds it until its run record exists, - so another start's sweep cannot kill it in between; the sweep itself, run without a start, takes + so another start's sweep cannot kill it in between. A start that cannot get the lock in that time + is refused (`sweep_busy`), never run unswept; the sweep itself, run without a start, takes the lock without blocking and is skipped while another sweep holds it. 8. **Environment in unit mode.** The unit vector begins with `/usr/bin/env -i`, contains no `-E` or `--setenv`, and lists exactly the allow-list. @@ -312,7 +317,8 @@ unit, and restart the daemon. 10. **Secrets and logs.** Canary strings in tool arguments, stub stderr, stub stdout and `install.json` inputs are absent from captured daemon stderr, the data directory and every returned error. 11. **No listener.** With a stub standing in for Playwright, the self-check reports none. A stub that - binds a TCP, a UDP and a Unix listener makes the check report each. + binds a TCP, a UDP and a Unix listener makes the check report each. A Unix listener outside the + private directory, a `0755` directory and a directory of another uid each make it fail. 12. **Router.** Managed beats a stale `MCP_UPSTREAM` unless `MCP_BROWSER_BACKEND=external`. External requires a literal loopback host, including `http://[::1]:/mcp`. A 301, 302, 307 or 308 is refused and a second listener sees no connection. Errors use fixed classes with a canary in the @@ -372,7 +378,7 @@ A person records each result against its check. | M6 | `browser update` with a deliberately broken pin (debug build) keeps the old version. | | M7 | `browser remove` with an unrelated directory inside the data root: it stays and is reported. | | M8 | Cutover rehearsal on a spare account for each host class, then rollback. | -| M9 | No TCP/UDP listener (and, once V2 closes, no Unix listener): `ss -ltnup` and `ss -lxp` during a browser call. | +| M9 | No TCP/UDP listener, and any Unix listener inside the private per-run `TMPDIR` (V2): `ss -ltnup` and `ss -lxp` during a browser call. | | M10 | The hosts' real network: the downloads work through each host's actual egress. | ### 3.5 Facts to verify before release @@ -382,7 +388,7 @@ These are expected, not yet measured. A failed check has the stated consequence. | ID | Question | If it fails | | --- | --- | --- | | V1 | Does the generator find a pinned-version Chromium source for each platform? | Pin the Playwright CDN build for that platform. The release is blocked until each platform has a source. | -| V2 | With the pinned `@playwright/mcp` and no `--port`, does the whole tree hold no TCP, UDP or Unix listener, on both architectures? | Release blocker. | +| V2 | With the pinned `@playwright/mcp` and no `--port`, does the whole tree hold no TCP or UDP listener, and every Unix listener inside the child's private `0700` `TMPDIR`, on both architectures? | Release blocker. **Decided:** R1.1 states the narrowed rule; each release's smoke measures it on both architectures (`GATE V2`). | | V3 | Does node exit on stdin EOF, does Chromium exit when node dies, and how long after daemon `SIGKILL`? | Informational. The stop guarantee does not depend on it. | | V4 | Do `systemd-run --user --pipe`, `BindsTo` on a transient unit and `NoNewPrivileges` work with the AppArmor user-namespace profile, and does `BindsTo` fire when the daemon unit auto-restarts? | If `BindsTo` does not fire, the self-test fails and the tier is unavailable until another mechanism verifies. `NoNewPrivileges` is dropped where it conflicts. | | V5 | Is the measured `minGlibc` below the oldest supported OS? | Narrow the supported matrix. | diff --git a/poc/reverse-attach-linux/README.md b/poc/reverse-attach-linux/README.md index 381ae95..057f1d7 100644 --- a/poc/reverse-attach-linux/README.md +++ b/poc/reverse-attach-linux/README.md @@ -125,6 +125,9 @@ config. Verified from the laptop: click into a field → `type` → screenshot s Same pattern as the Mac: `@playwright/mcp` runs beside the daemon on loopback and the daemon re-serves its tools under its own `tools/list`, filtered by the connection's profile. +- **Deprecated (D14, R7.1).** `pw-mcp.sh` ships for one more minor release and is then removed; it + prints a deprecation notice to stderr when it starts (the tarball copy only). Cutover and rollback: + [`docs/linux-cutover.md`](../../docs/linux-cutover.md). - `pw-mcp.sh` + systemd user unit `oab-computer-pw-mcp.service`: `@playwright/mcp@0.0.82` pinned (same as `poc/pw-mcp`), **headed** Chromium launched into the labwc seat (`WAYLAND_DISPLAY`, `XDG_RUNTIME_DIR`, `DISPLAY=:0` for labwc's Xwayland), using the distro Chromium @@ -194,7 +197,7 @@ comment). | `install [--from-dir DIR]` | Installs the pinned Node.js, Playwright MCP and Chromium below `${XDG_DATA_HOME:-~/.local/share}/oab-computer/playwright/`. `--from-dir` installs from pre-fetched files in `DIR` (the basenames of the pinned URLs and of the lockfile's `resolved` URLs), hash-checked the same way, with `npm ci --offline` and no network. | | `update [--yes] [--from-dir DIR]` | Prompted, never silent (no terminal and no `--yes` is a refusal). Installs the new version beside the old one and keeps the old one if anything fails. | | `remove` | Deletes only what carries the installer's marker and prints `left in place:` for everything else. | -| `status [--json] [--retry]` | Install state, ids, platform, whether an update is available, and (L2) `containment`, `external_configured`, `listeners` and `refusal`, and (L4) `hardening_base`, `hardening_mount`, `hardening_unverified` and `run_records`. `--json` has a fixed set of keys. `--retry` removes the unavailable latch and re-runs the containment self-test in this process. | +| `status [--json] [--retry]` | Install state, ids, platform, whether an update is available, and (L2) `containment`, `external_configured`, `listeners` and `refusal`, and (L4) `hardening_base`, `hardening_mount`, `hardening_unverified` and `run_records`, and (from the first release that contains L5) `legacy_units`, `legacy` and `legacy_listener`, which list what an install from before the managed browser left behind and never change it. `--json` has a fixed set of keys. `--retry` removes the unavailable latch and re-runs the containment self-test in this process. | Exit codes: `0` success (including a no-op), `1` the operation failed or the preflight found a blocker (one `browser: _failed class=` line on stderr), `2` a usage error. A usage @@ -290,11 +293,24 @@ is outside this control. `unverified`, `not_applicable`), `display` (`headed`, `headless`, `not_applicable`) and `external_upstream_ignored`. It carries no URL, path, token or page data. -Known limit (V2): with the pinned Playwright and Chromium the managed tree opens no TCP or UDP -socket, but it does hold two listening Unix sockets inside its private `0700` `TMPDIR` -(Playwright's browser socket and Chromium's `SingletonSocket`). `browser status` reports them as -`listeners: tcp=0 udp=0 unix=2`. The target "no Unix listener" is therefore unmet (the ADR and R1.1 say so -and the docs claim only "no TCP or UDP port"). +V2 (decided): the managed tree opens no TCP or UDP socket, and holds two listening Unix sockets inside its +private `0700` `TMPDIR` (Playwright's browser socket and Chromium's `SingletonSocket`). The rule: any Unix +listener must be inside that directory, which must be a real directory of the daemon's uid with mode +exactly `0700`. `browser status` reports `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok +result=pass`, or `result=fail` for a TCP or UDP listener, a Unix listener outside the directory or a +directory that is not `0700` or not the daemon's (`tmpdir=mode|owner|missing|not_dir|unreadable`). The +release smoke recomputes it on both architectures. + +### Release gates, provenance and cutover (L5) + +From the first release that contains L5: a release is gated by `.github/workflows/linux-release-smoke.yml` +(Ubuntu 22.04 and 24.04 on amd64 and arm64, plus a Debian 12 container job on both architectures; +[Releasing](../../docs/releasing.md#linux-release-gates)), by the per-release manual record +(`docs/release-records/linux-VERSION.md`), and by the Playwright pins check for all four platforms. The +Linux tarballs carry a build-provenance attestation; `gh attestation verify "oab-computer-$V-linux-$A.tar.gz" +--repo openabdev/openab-computer` checks it, and does not make the download safe. `pw-mcp.sh` is +deprecated, and `status` lists what the old external setup left behind. Moving a host over, and back, is +in [the cutover guide](../../docs/linux-cutover.md). The tests: the pure parts run anywhere; process, `/proc` and `systemd` tests are Linux-only. The tests that need a user manager are `#[ignore]`d and run with `OAB_L2_SYSTEMD=1 cargo test --release @@ -356,7 +372,7 @@ Design: `docs/adr/linux-browser-tier.md` ("Process containment", V4, V11) and until the child's run record is written, and the sweep lock (waited for, up to 10 s) across the spawn, so `remove`, `update` and a second start cannot act between the spawn and the record. Run records that are not records (junk `.json` files) are pruned, and a full `run/` is its own - class, `run_records_full`. + class, `run_records_full`. A start that cannot take the sweep lock within that wait is refused with `sweep_busy`, and one whose sweep fails for any other reason with `sweep_unavailable`: no child is started that neither the lock nor a run record protects. Neither counts as a failure of the child. - `src/state.rs`: `open_private_base` is the base of the short temporary directories. `XDG_RUNTIME_DIR` is used only when it opens without following a link and is a directory of ours that others cannot write; otherwise `/tmp/oab-` (0700, ours), never `/tmp` itself. diff --git a/poc/reverse-attach-linux/pw-mcp.sh b/poc/reverse-attach-linux/pw-mcp.sh index e614232..0178189 100644 --- a/poc/reverse-attach-linux/pw-mcp.sh +++ b/poc/reverse-attach-linux/pw-mcp.sh @@ -1,4 +1,10 @@ #!/bin/bash +# DEPRECATED (ADR D14, requirement R7.1). This script ships for one more minor release and is then +# removed. The installer no longer writes a unit that runs it. It opens an unauthenticated Playwright +# MCP listener on 127.0.0.1:8794 that any local user can reach and that serves +# browser_run_code_unsafe. Replacement: `oab-computer browser install` (the managed tier, no port). +# Cutover and rollback steps: docs/linux-cutover.md. +# # Playwright MCP beside the Linux hands node. Loopback only; the daemon re-serves it # via --upstream (never exposed directly). Mirrors poc/pw-mcp/pw-mcp.sh for macOS. # @@ -18,7 +24,10 @@ export WAYLAND_DISPLAY="${WAYLAND_DISPLAY:-wayland-0}" export DISPLAY="${DISPLAY:-:0}" CHROMIUM="${PW_CHROMIUM:-/usr/bin/chromium}" PW_CONFIG="${PW_CONFIG:-$([ -f "$BASE/pw-config.json" ] && echo "$BASE/pw-config.json")}" +# shellcheck disable=SC2164 # unchanged since it shipped: a failed cd falls through to a failed exec cd "$BASE/pw-mcp" +# Runtime notice for the journal of the old unit. Fixed text, stderr only; the launch below is unchanged. +echo "pw-mcp.sh is DEPRECATED: it opens an unauthenticated listener on 127.0.0.1:8794 that any local user can reach (browser_run_code_unsafe included). Replace it with 'oab-computer browser install'; see docs/linux-cutover.md." >&2 exec ./node_modules/.bin/playwright-mcp \ --host 127.0.0.1 --port 8794 \ --allowed-hosts "127.0.0.1,localhost,127.0.0.1:8794,localhost:8794" \ diff --git a/poc/reverse-attach-linux/src/browser_cli.rs b/poc/reverse-attach-linux/src/browser_cli.rs index e3d8cb6..fbace7f 100644 --- a/poc/reverse-attach-linux/src/browser_cli.rs +++ b/poc/reverse-attach-linux/src/browser_cli.rs @@ -331,14 +331,21 @@ pub fn run(args: &[String]) -> i32 { } else { sigstop::CLI_RUNTIME_MAX }); + let home = std::env::var_os("HOME").map(PathBuf::from); let extras = |base: &Path, retry: bool| { - crate::probe::gather( + let mut x = crate::probe::gather( base, retry, std::env::var("MCP_UPSTREAM").ok().as_deref(), &crate::procnet::Proc, &|| Systemd::new(data_root.clone(), false).verify(), - ) + ); + // L5: what the old external setup left behind. Read-only (D10). + x.set_legacy(crate::legacy::gather( + home.as_deref(), + &crate::procnet::Proc, + )); + x }; let o = Opts { manifest, @@ -356,7 +363,7 @@ pub fn run(args: &[String]) -> i32 { npm_timeout: Duration::from_secs(600), lock_wait: Duration::from_secs(30), base, - home: std::env::var_os("HOME").map(PathBuf::from), + home: home.clone(), platform, facts: &facts, launcher: &launcher, diff --git a/poc/reverse-attach-linux/src/browser_cli_tests.rs b/poc/reverse-attach-linux/src/browser_cli_tests.rs index 8985945..a319a8d 100644 --- a/poc/reverse-attach-linux/src/browser_cli_tests.rs +++ b/poc/reverse-attach-linux/src/browser_cli_tests.rs @@ -296,7 +296,7 @@ fn the_commands_end_to_end_with_exit_codes_and_fixed_messages() { good_facts(), None, ); - assert_eq!(r.out.lines().count(), 18); + assert_eq!(r.out.lines().count(), 21); assert!(r.out.lines().all(|l| l.contains(": "))); assert!(r.out.contains("state: installed") && r.out.contains("installed_id: test-id-1")); let r = exec( @@ -315,7 +315,7 @@ fn the_commands_end_to_end_with_exit_codes_and_fixed_messages() { assert_eq!(v["update_available"], false); assert_eq!(v["pins_match"], true); assert_eq!(v["previous"], Value::Null); - assert_eq!(v.as_object().unwrap().len(), 18); + assert_eq!(v.as_object().unwrap().len(), 21); // update without a yes, then declined, then confirmed. let u = Cmd::Update { diff --git a/poc/reverse-attach-linux/src/child.rs b/poc/reverse-attach-linux/src/child.rs index ae7a875..fa4b65d 100644 --- a/poc/reverse-attach-linux/src/child.rs +++ b/poc/reverse-attach-linux/src/child.rs @@ -42,7 +42,8 @@ use crate::sweep; /// How long a start waits for `.install.lock` (an `install`, `update` or `remove` holds it /// exclusive) before it answers `install_busy`. const INSTALL_LOCK_WAIT: Duration = Duration::from_secs(2); -/// How long a start waits for the sweep lock that another start holds. +/// How long a start waits for the sweep lock that another start holds, before it answers +/// `sweep_busy`. const SWEEP_WAIT: Duration = Duration::from_secs(10); pub const PASSWORD_STORE: &str = "--password-store=basic"; @@ -298,6 +299,19 @@ impl RuntimeTmp { RuntimeTmp::create_named(root_abs, "oab-pw") } + fn dir_name(root_abs: &Path, prefix: &str) -> String { + let h = Sha256::digest(root_abs.as_os_str().as_encoded_bytes()); + format!("{prefix}-{}", crate::manifest::hex(&h[..4])) + } + + /// Where the managed child's `TMPDIR` is for this install root, decided without creating + /// anything (`browser status` checks it, V2). Uses this process's `XDG_RUNTIME_DIR`, so it + /// matches the daemon's only when both run in the same user session. + pub(crate) fn expected_path(root_abs: &Path) -> PathBuf { + let runtime = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from); + state::private_base_path(runtime.as_deref()).join(RuntimeTmp::dir_name(root_abs, "oab-pw")) + } + /// Same, under another fixed prefix of the same length. `browser signin` uses its own so that /// starting it never removes the directory of a managed child that started a moment earlier: /// the profile lock decides who may run, and each side only ever touches its own directory. @@ -305,8 +319,7 @@ impl RuntimeTmp { let runtime = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from); let (parent, base) = state::open_private_base(runtime.as_deref()).map_err(|_| "tmp_unavailable")?; - let h = Sha256::digest(root_abs.as_os_str().as_encoded_bytes()); - let name = format!("{prefix}-{}", crate::manifest::hex(&h[..4])); + let name = RuntimeTmp::dir_name(root_abs, prefix); let mut rep = state::Report::default(); // A directory of ours that an earlier child left: marker-gated removal. let _ = state::remove_marked_tree(&parent, &name, OWNED_DATA, &mut rep); @@ -364,6 +377,8 @@ pub struct Config { pub ping_timeout: Duration, /// A child that has said nothing for this long is pinged before a call is sent to it. pub idle_ping_after: Duration, + /// How long a start waits for the sweep lock (`SWEEP_WAIT`; tests shorten it). + pub sweep_wait: Duration, } impl Config { @@ -376,6 +391,7 @@ impl Config { init_timeout: Duration::from_secs(15), ping_timeout: Duration::from_secs(2), idle_ping_after: Duration::from_secs(30), + sweep_wait: SWEEP_WAIT, } } } @@ -548,14 +564,19 @@ impl Supervisor { let mech = Arc::clone(self.avail.mechanism()); // Wait for the sweep lock rather than skip it, and keep it until this child's record is // written: a second start's sweep would otherwise kill this child while no record claims it. - // A run directory too full to list makes the sweep refuse; that is its own class, and no - // child is started that the next sweep could not tell from a stray. Any other sweep error - // (the lock file cannot be opened) leaves the start as it was: unswept. - let sweep_guard = match sweep::sweep_holding(&root, &|u| mech.stop_unit(u), SWEEP_WAIT) { - Ok((_, guard)) => guard, - Err(Fail("run_records_full")) => return Err("run_records_full"), - Err(_) => None, - }; + // Fail closed (#132): a start that did not sweep and holds no guard would spawn a child that + // neither the lock nor a record protects, so every outcome but a held guard is a refusal. A + // run directory too full to list makes the sweep refuse (`run_records_full`: no child is + // started that the next sweep could not tell from a stray); a lock still held when the wait + // ends is `sweep_busy`; any other sweep error (the lock file cannot be opened) is + // `sweep_unavailable`. None of them is a failure of the child: nothing is counted or latched. + let sweep_guard = + match sweep::sweep_holding(&root, &|u| mech.stop_unit(u), self.cfg.sweep_wait) { + Ok((_, Some(guard))) => guard, + Ok((_, None)) => return Err("sweep_busy"), + Err(Fail("run_records_full")) => return Err("run_records_full"), + Err(_) => return Err("sweep_unavailable"), + }; let tmp = RuntimeTmp::create(root.abs_path())?; let seat = (self.cfg.seat)(); let v = launch_vector(&rec, root.abs_path(), &tmp.path, seat.as_ref()); diff --git a/poc/reverse-attach-linux/src/child_tests.rs b/poc/reverse-attach-linux/src/child_tests.rs index 1be7c52..2735e67 100644 --- a/poc/reverse-attach-linux/src/child_tests.rs +++ b/poc/reverse-attach-linux/src/child_tests.rs @@ -81,6 +81,10 @@ pub(crate) struct Sup { } pub(crate) fn sup(fx: &Fx, verify: Result) -> Sup { + sup_with(fx, verify, |_| {}) +} + +fn sup_with(fx: &Fx, verify: Result, tweak: impl FnOnce(&mut Config)) -> Sup { let mech = Arc::new(Direct::new(verify)); let ms = Arc::new(AtomicU64::new(1_000)); let clock = Arc::clone(&ms); @@ -88,6 +92,7 @@ pub(crate) fn sup(fx: &Fx, verify: Result) -> Sup { cfg.clock = Arc::new(move || Duration::from_millis(clock.load(Ordering::SeqCst))); cfg.seat = Arc::new(|| None); cfg.init_timeout = Duration::from_secs(5); + tweak(&mut cfg); let m: Arc = mech.clone(); Sup { sup: Supervisor::new(cfg, Arc::new(Availability::new(m))), @@ -748,6 +753,49 @@ fn remove_cannot_run_between_the_spawn_and_the_record_and_a_second_sweep_cannot_ sup.stop(); } +/// A start with a short sweep wait. +fn sup_with_sweep_wait(fx: &Fx, wait: Duration) -> Sup { + sup_with(fx, Ok(SYSTEMD), |cfg| cfg.sweep_wait = wait) +} + +#[cfg(target_os = "linux")] +#[test] +fn a_start_that_cannot_get_the_sweep_lock_is_refused_not_started_unswept() { + let fx = Fx::new(GOOD); + let s = sup_with_sweep_wait(&fx, Duration::from_millis(300)); + // Another start (or a CLI child's launch) holds the sweep lock for longer than the wait. + let (_, held) = + sweep::sweep_holding(&fx.root(), &|_: &str| {}, Duration::from_secs(5)).unwrap(); + let held = held.expect("the test takes the lock"); + let t = Instant::now(); + assert_eq!(s.sup.ensure().err(), Some("sweep_busy")); + assert!(t.elapsed() >= Duration::from_millis(250), "it did not wait"); + assert_eq!(spawned(&s), 0, "no child was started without a sweep"); + // Not a failure of the child: nothing is latched, and the next call starts it once the lock is free. + assert!(!run_record::latch_is_set(&fx.root())); + drop(held); + assert!(s.sup.ensure().is_ok()); + assert_eq!(spawned(&s), 1); + s.sup.stop(); +} + +#[cfg(target_os = "linux")] +#[test] +fn a_sweep_that_fails_for_another_reason_refuses_the_start_too() { + let fx = Fx::new(GOOD); + let s = sup_with_sweep_wait(&fx, Duration::from_millis(300)); + // The lock file cannot be opened (a link in its place; the open does not follow links). + let lock = fx.root().abs_path().join(state::SWEEP_LOCK_NAME); + let _ = std::fs::remove_file(&lock); + std::os::unix::fs::symlink("/nonexistent", &lock).unwrap(); + assert_eq!(s.sup.ensure().err(), Some("sweep_unavailable")); + assert_eq!(spawned(&s), 0); + assert!(!run_record::latch_is_set(&fx.root())); + std::fs::remove_file(&lock).unwrap(); + assert!(s.sup.ensure().is_ok()); + s.sup.stop(); +} + #[test] fn a_run_directory_too_full_to_sweep_is_its_own_class_and_starts_nothing() { let fx = Fx::new(GOOD); diff --git a/poc/reverse-attach-linux/src/containment.rs b/poc/reverse-attach-linux/src/containment.rs index a5cfd72..f817cb1 100644 --- a/poc/reverse-attach-linux/src/containment.rs +++ b/poc/reverse-attach-linux/src/containment.rs @@ -746,11 +746,16 @@ impl Fixture<'_> { /// unit reads `inactive` or `failed` and none of the recorded processes exists any more. fn cleanup(&mut self) -> bool { let mut all = true; - for u in self.units.iter().rev() { + let units = std::mem::take(&mut self.units); + for u in units.iter().rev() { + // A parent with `Restart=always` has a new main process and a new straggler after a + // restart, which no earlier look recorded. Record what is in the unit now, before the + // kill, so that cleanup cannot pass while one of them lives (#132). + let now = self.inside(u); + self.recorded.extend(now); self.sys.kill_all(u); all &= self.sys.stop(u); } - self.units.clear(); let recorded = std::mem::take(&mut self.recorded); // SIGKILL is asynchronous: give the kernel a moment to reap. let end = Instant::now() + Duration::from_secs(3); diff --git a/poc/reverse-attach-linux/src/containment_tests.rs b/poc/reverse-attach-linux/src/containment_tests.rs index 7fa848c..efab1cc 100644 --- a/poc/reverse-attach-linux/src/containment_tests.rs +++ b/poc/reverse-attach-linux/src/containment_tests.rs @@ -594,6 +594,108 @@ fn kill_all_names_the_unit_and_never_a_pid_or_a_non_unit_name() { assert_eq!(after, log, "a refused name reached systemctl"); } +/// A fake `systemctl` that answers every `show` with `state` and fails every `kill`. +fn failing_kill_tools(t: &TempDir, state: &str) -> Sys { + let bin = t.path.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + write_exec( + &bin.join("systemctl"), + format!( + "#!/bin/sh\ncase \" $* \" in\n *\" show \"*) echo {state}; exit 0;;\n *\" kill \"*) exit 1;;\n *) exit 0;;\nesac\n" + ) + .as_bytes(), + ); + Sys { + path: vec![bin], + runtime_dir: Some(t.path.clone()), + bus: None, + } +} + +#[test] +fn a_cleanup_whose_kill_failed_and_whose_unit_is_still_active_is_a_failed_cleanup() { + let t = TempDir::new(); + let sys = failing_kill_tools(&t, "active"); + let mut fx = Fixture { + sys: &sys, + units: vec!["oab-l4-test-selftest-ab-p.service".into()], + recorded: Vec::new(), + daemon_unit: None, + bind_child: true, + }; + assert!(!fx.cleanup(), "a unit that is still active passed cleanup"); + assert!(fx.units.is_empty(), "the unit list is spent either way"); + // A failed `kill` for a unit that is already gone is not a failure: the state check decides. + let t = TempDir::new(); + let sys = failing_kill_tools(&t, "inactive"); + let mut fx = Fixture { + sys: &sys, + units: vec!["oab-l4-test-selftest-ab-p.service".into()], + recorded: Vec::new(), + daemon_unit: None, + bind_child: true, + }; + assert!(fx.cleanup()); +} + +#[test] +fn cleanup_fails_while_a_recorded_process_lives() { + let t = TempDir::new(); + let sys = failing_kill_tools(&t, "inactive"); + let me = std::process::id(); + let mut fx = Fixture { + sys: &sys, + units: Vec::new(), + // This process, by pid and start time: it does not exit, so cleanup must say so. + recorded: vec![(me, crate::state::proc_start_time(me).unwrap())], + daemon_unit: None, + bind_child: true, + }; + assert!(!fx.cleanup()); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "needs a systemd user manager; OAB_L2_SYSTEMD=1"] +fn cleanup_records_and_kills_the_straggler_of_the_restarted_parent() { + if !enabled() { + return; + } + let sys = Sys::from_env(); + // L5 test units carry their own prefix, so a leftover is attributable to this test. + let prefix = "oab-l5-test-rec"; + let base = format!("{prefix}-{}", crate::state::random_hex(4)); + let parent_u = format!("{base}-p.service"); + let mut fx = Fixture { + sys: &sys, + units: Vec::new(), + recorded: Vec::new(), + daemon_unit: None, + bind_child: true, + }; + assert!(fx.run(&base), "the fixture did not pass"); + // The parent restarted after the kill of its main process (`Restart=always`): its new main + // process and new straggler were never recorded by the run. + let mut now: Vec<(u32, u64)> = Vec::new(); + assert!(fx.wait(Duration::from_secs(6), || { + now = fx.inside(&parent_u); + now.len() >= 2 + })); + assert!( + now.iter().any(|p| !fx.recorded.contains(p)), + "the restart added nothing to record, so this test shows nothing" + ); + assert!(fx.cleanup()); + for (p, t) in &now { + assert_ne!( + crate::state::proc_start_time(*p), + Some(*t), + "a process of the restarted parent outlived cleanup" + ); + } + assert_eq!(sys.list_prefixed(prefix), Some(Vec::new())); +} + #[test] fn the_mode_follows_what_the_mount_probe_applied() { use crate::hardening::Val; diff --git a/poc/reverse-attach-linux/src/external.rs b/poc/reverse-attach-linux/src/external.rs index f69bcdd..6df98dd 100644 --- a/poc/reverse-attach-linux/src/external.rs +++ b/poc/reverse-attach-linux/src/external.rs @@ -108,6 +108,8 @@ impl OwnerCheck for SameUid { // read again, up to `READS` times 20 ms apart (half a second), until it is this uid. Only // our own uid is accepted, and nothing is sent before it is: the retries cost time on a // refusal and never widen what is accepted. + // This is the production check, not a test aid: the same read guards every external + // connection. Pinned by `a_row_that_is_not_there_yet_is_read_again_and_another_owner_is_never_accepted`. const READS: u32 = 25; for read in 1..=READS { if procnet::peer_owner_uid(&*self.source, client, server) diff --git a/poc/reverse-attach-linux/src/install.rs b/poc/reverse-attach-linux/src/install.rs index b3d5602..d5533ca 100644 --- a/poc/reverse-attach-linux/src/install.rs +++ b/poc/reverse-attach-linux/src/install.rs @@ -926,13 +926,22 @@ impl Status { self.extras.hardening_unverified.clone().into(), ); m.insert("run_records".into(), self.extras.run_records.clone().into()); + m.insert( + "legacy_units".into(), + self.extras.legacy_units.clone().into(), + ); + m.insert("legacy".into(), self.extras.legacy.clone().into()); + m.insert( + "legacy_listener".into(), + self.extras.legacy_listener.clone().into(), + ); Value::Object(m).to_string() } pub fn lines(&self) -> Vec { let opt = |v: &Option| v.clone().unwrap_or_else(|| "-".into()); let ob = |v: Option| v.map(|b| b.to_string()).unwrap_or_else(|| "-".into()); - vec![ + let mut v = vec![ format!("state: {}", self.state), format!("manifest_id: {}", self.manifest_id), format!("installed_id: {}", opt(&self.installed_id)), @@ -951,7 +960,18 @@ impl Status { format!("hardening_mount: {}", self.extras.hardening_mount), format!("hardening_unverified: {}", self.extras.hardening_unverified), format!("run_records: {}", self.extras.run_records), - ] + format!("legacy_units: {}", self.extras.legacy_units), + format!("legacy: {}", self.extras.legacy), + format!("legacy_listener: {}", self.extras.legacy_listener), + ]; + // The cutover hint is for people: `--json` has the fixed fields and nothing else. + if self.extras.legacy_present() { + v.push( + "legacy: present, run docs/linux-cutover.md (D10: nothing here is deleted by oab-computer)" + .into(), + ); + } + v } } diff --git a/poc/reverse-attach-linux/src/install_tests.rs b/poc/reverse-attach-linux/src/install_tests.rs index 34bbf5f..b476354 100644 --- a/poc/reverse-attach-linux/src/install_tests.rs +++ b/poc/reverse-attach-linux/src/install_tests.rs @@ -624,20 +624,24 @@ fn a_full_install_commits_records_and_leaves_no_trace_of_the_build() { "hardening_mount", "hardening_unverified", "run_records", + // L5, R6.4: the legacy listing. + "legacy_units", + "legacy", + "legacy_listener", ]; want.sort_unstable(); let mut got = keys.clone(); got.sort_unstable(); assert_eq!(got, want); assert!(!s.to_json().contains("http")); - // The human lines keep the existing order and end with the four L4 fields. + // The human lines keep the existing order and end with the four L4 fields and the three L5 ones. let names: Vec = s .lines() .iter() .map(|l| l.split(": ").next().unwrap().to_string()) .collect(); assert_eq!( - names[names.len() - 8..], + names[names.len() - 11..], [ "containment", "external_configured", @@ -647,6 +651,9 @@ fn a_full_install_commits_records_and_leaves_no_trace_of_the_build() { "hardening_mount", "hardening_unverified", "run_records", + "legacy_units", + "legacy", + "legacy_listener", ] ); // Every value of the new fields is a fixed token: no path, URL or text. @@ -664,6 +671,39 @@ fn a_full_install_commits_records_and_leaves_no_trace_of_the_build() { } } +#[test] +fn the_cutover_hint_is_printed_only_when_something_legacy_exists_and_never_in_json() { + let e = Env::new(Tw::default()); + let m = e.manifest("test-id-1"); + let mut s = e.status(&m); + let hint = |s: &Status| { + s.lines() + .into_iter() + .filter(|l| l.contains("docs/linux-cutover.md")) + .collect::>() + }; + // Nothing legacy, and `unknown` (could not look) is not a finding: no hint. + assert!(hint(&s).is_empty()); + s.extras.legacy_units = "unknown".into(); + s.extras.legacy = "unknown".into(); + assert!(hint(&s).is_empty()); + // Each of the three fields alone is enough. + for set in [ + |x: &mut crate::probe::Extras| x.legacy_units = "oab-pw-mcp.service".into(), + |x: &mut crate::probe::Extras| x.legacy = "~/.cache/ms-playwright:1 MiB".into(), + |x: &mut crate::probe::Extras| x.legacy_listener = "8794".into(), + ] { + let mut s = e.status(&m); + set(&mut s.extras); + let h = hint(&s); + assert_eq!(h.len(), 1, "{h:?}"); + assert!(h[0].starts_with("legacy: present, run docs/linux-cutover.md")); + // The hint is a human line only: JSON has the fixed fields and no hint text. + assert!(!s.to_json().contains("linux-cutover")); + assert!(!s.to_json().contains("present")); + } +} + #[test] fn every_failure_stage_leaves_nothing_behind() { let cases: Vec<(&str, Tw, &str, &'static str)> = vec![ diff --git a/poc/reverse-attach-linux/src/legacy.rs b/poc/reverse-attach-linux/src/legacy.rs new file mode 100644 index 0000000..031052e --- /dev/null +++ b/poc/reverse-attach-linux/src/legacy.rs @@ -0,0 +1,303 @@ +//! The legacy listing of `browser status` (R6.4, D10, D9; L5): what the external Playwright setup of +//! 0.12.0 and earlier left behind. Read-only by construction: `lstat`, `read_dir` and one bounded +//! read of a drop-in file, never a write, a move, a delete, a `systemctl` call or a symlink +//! followed. Three fixed-vocabulary fields, each `none` when nothing is there: +//! +//! - `legacy_units`: a comma list of the fixed names below (a unit file under +//! `~/.config/systemd/user/`, or `drop-in:` for a drop-in directory with a `*.conf` that has a +//! `MCP_UPSTREAM` line). The content of a drop-in and the URL in it are never reported. +//! - `legacy`: a comma list of `:` for the fixed paths below, `~` for the home +//! directory. The old profile is marked `:holds_cookies` (D9). A symlink is reported as +//! `:symlink` and not followed; a size that could not be taken (a permission error, or a tree +//! past the walk caps) is `:size_unknown`. +//! - `legacy_listener`: `8794` when something listens on the old unit's TCP port (any owner: this is +//! the unauthenticated port of the old unit, not the managed tree), `none`, or `unknown` when the +//! tables cannot be read. +//! +//! No URL, token, host name, file content or page data can appear. `unknown` is the answer when the +//! home directory is not known, never `none`. + +use std::fs; +use std::io::Read; +use std::os::unix::fs::OpenOptionsExt; +use std::path::Path; + +use crate::procnet::{parse_inet, Source}; + +/// Unit files looked for under `~/.config/systemd/user/`, in report order. +pub const UNIT_FILES: [&str; 2] = ["oab-pw-mcp.service", "oab-computer-pw-mcp.service"]; +/// Drop-in directories of the daemon units that may carry `MCP_UPSTREAM`. +pub const DROPIN_DIRS: [&str; 2] = ["oab-computer.service.d", "oab-instance-mcp.service.d"]; +/// The old unit's port. +pub const LEGACY_PORT: u16 = 8794; + +/// `(path below the home directory, holds cookies)`, in report order. +pub const PATHS: [(&str, bool); 7] = [ + (".local/oab-computer/pw-mcp", false), + (".local/oab-computer/pw-profile", true), + (".local/oab-computer/pw-output", false), + (".local/oab-computer/pw-config.json", false), + (".local/oab-computer/pw-mcp.sh", false), + (".local/oab-instance-mcp/pw-mcp", false), + (".cache/ms-playwright", false), +]; + +/// Walk caps: entries visited and directory depth. +pub const MAX_ENTRIES: usize = 200_000; +pub const MAX_DEPTH: usize = 64; +/// A drop-in is read up to this many bytes. +const DROPIN_CAP: u64 = 64 * 1024; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Legacy { + pub units: String, + pub paths: String, + pub listener: String, +} + +impl Legacy { + #[cfg(test)] + pub fn none() -> Legacy { + Legacy { + units: "none".into(), + paths: "none".into(), + listener: "none".into(), + } + } + + /// Something real was found (`unknown` is not a finding). + pub fn present(&self) -> bool { + [&self.units, &self.paths, &self.listener] + .iter() + .any(|v| v.as_str() != "none" && v.as_str() != "unknown") + } +} + +/// The three fields. `home` is the user's home directory (`None`: unknown, so `units` and `paths` are +/// `unknown`; the listener is still probed). `src` is the `/proc/net` reader that `listeners` uses. +pub fn gather(home: Option<&Path>, src: &dyn Source) -> Legacy { + let Some(home) = home.filter(|h| !h.as_os_str().is_empty()) else { + return Legacy { + units: "unknown".into(), + paths: "unknown".into(), + listener: listener(src), + }; + }; + Legacy { + units: units(home), + paths: paths(home), + listener: listener(src), + } +} + +fn join_or_none(v: Vec) -> String { + if v.is_empty() { + "none".into() + } else { + v.join(",") + } +} + +/// `Some(true)` present (a link counts), `Some(false)` absent, `None` could not tell. +fn exists(p: &Path) -> Option { + match fs::symlink_metadata(p) { + Ok(_) => Some(true), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(false), + // A path component that is not a directory also means "not there". + Err(e) if e.raw_os_error() == Some(20) => Some(false), + Err(_) => None, + } +} + +fn units(home: &Path) -> String { + let dir = home.join(".config/systemd/user"); + let mut found = Vec::new(); + for name in UNIT_FILES { + match exists(&dir.join(name)) { + Some(true) => found.push(name.to_string()), + Some(false) => {} + None => return "unknown".into(), + } + } + for name in DROPIN_DIRS { + match dropin_has_upstream(&dir.join(name)) { + Some(true) => found.push(format!("drop-in:{name}")), + Some(false) => {} + None => return "unknown".into(), + } + } + join_or_none(found) +} + +/// Does a `*.conf` in the drop-in directory `d` hold an active `Environment=MCP_UPSTREAM=` assignment? `Some(false)` when the +/// directory is absent or is a symlink (not followed); `None` when it cannot be read. +fn dropin_has_upstream(d: &Path) -> Option { + let meta = match fs::symlink_metadata(d) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some(false), + Err(e) if e.raw_os_error() == Some(20) => return Some(false), + Err(_) => return None, + }; + if !meta.is_dir() { + return Some(false); + } + let rd = fs::read_dir(d).ok()?; + let mut names: Vec<_> = rd.flatten().map(|e| e.path()).collect(); + names.sort(); + for p in names { + if p.extension().and_then(|e| e.to_str()) != Some("conf") { + continue; + } + // Regular files only: a link is not followed. + match fs::symlink_metadata(&p) { + Ok(m) if m.is_file() => {} + _ => continue, + } + let mut text = String::new(); + // `O_NOFOLLOW | O_NONBLOCK`: a file swapped for a link or a FIFO after the `lstat` is not read. + let flags = (rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32; + let Ok(f) = fs::OpenOptions::new() + .read(true) + .custom_flags(flags) + .open(&p) + else { + return None; + }; + if f.take(DROPIN_CAP).read_to_string(&mut text).is_err() { + // Not text: it cannot be a unit drop-in that sets the variable. + continue; + } + if text.lines().any(sets_upstream) { + return Some(true); + } + } + Some(false) +} + +/// Is this line an active `Environment=` assignment of `MCP_UPSTREAM`? A comment, `UnsetEnvironment=`, +/// another variable that merely contains the name, and other settings do not count. The cutover guide +/// uses the same rule (`grep -nE`), so the hint and the runbook agree. +fn sets_upstream(line: &str) -> bool { + let Some(value) = line.trim_start().strip_prefix("Environment=") else { + return false; + }; + let value = value.split(['#', ';']).next().unwrap_or(""); + let mut from = 0; + while let Some(i) = value[from..].find("MCP_UPSTREAM=") { + let at = from + i; + match value[..at].chars().next_back() { + None | Some('"') | Some('\'') => return true, + Some(c) if c.is_whitespace() => return true, + _ => {} + } + from = at + 1; + } + false +} + +fn paths(home: &Path) -> String { + let mut found = Vec::new(); + for (rel, cookies) in PATHS { + let p = home.join(rel); + let meta = match fs::symlink_metadata(&p) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound || e.raw_os_error() == Some(20) => { + continue + } + Err(_) => { + found.push(entry(home, &p, "size_unknown", cookies)); + continue; + } + }; + let size = if meta.file_type().is_symlink() { + "symlink".to_string() + } else if meta.is_dir() { + match dir_size(&p) { + Some(n) => format_size(n), + None => "size_unknown".into(), + } + } else { + format_size(meta.len()) + }; + found.push(entry(home, &p, &size, cookies)); + } + join_or_none(found) +} + +fn entry(home: &Path, p: &Path, size: &str, cookies: bool) -> String { + let name = crate::consent::display_path(p, Some(home)); + if cookies { + format!("{name}:{size}:holds_cookies") + } else { + format!("{name}:{size}") + } +} + +/// Sum of the apparent sizes below `root`, by `lstat`: a symlink counts as its own length and is +/// never entered, nothing is read. `None` past the entry or depth cap, or on any error. +fn dir_size(root: &Path) -> Option { + dir_size_with(root, MAX_ENTRIES, MAX_DEPTH) +} + +fn dir_size_with(root: &Path, max_entries: usize, max_depth: usize) -> Option { + let mut total: u64 = 0; + let mut seen = 0usize; + let mut stack = vec![(root.to_path_buf(), 0usize)]; + while let Some((dir, depth)) = stack.pop() { + if depth > max_depth { + return None; + } + for e in fs::read_dir(&dir).ok()? { + let e = e.ok()?; + seen += 1; + if seen > max_entries { + return None; + } + let m = e.metadata().ok()?; + total = total.saturating_add(m.len()); + if m.is_dir() { + stack.push((e.path(), depth + 1)); + } + } + } + Some(total) +} + +/// A fixed unit per size class, rounded up: `B`, `KiB`, `MiB`, `GiB`. +pub fn format_size(n: u64) -> String { + const K: u64 = 1024; + if n < K { + format!("{n} B") + } else if n < K * K { + format!("{} KiB", n.div_ceil(K)) + } else if n < K * K * K { + format!("{} MiB", n.div_ceil(K * K)) + } else { + format!("{} GiB", n.div_ceil(K * K * K)) + } +} + +/// `8794` when a TCP socket listens on the old unit's port, whoever owns it. +fn listener(src: &dyn Source) -> String { + let mut hit = false; + for (name, v6, required) in [("tcp", false, true), ("tcp6", true, false)] { + match src.table(name) { + Ok(t) => { + hit |= parse_inet(&t, v6) + .iter() + .any(|r| r.state == 0x0A && r.local.port() == LEGACY_PORT); + } + Err(_) if required => return "unknown".into(), + Err(_) => {} + } + } + if hit { + LEGACY_PORT.to_string() + } else { + "none".into() + } +} + +#[cfg(test)] +#[path = "legacy_tests.rs"] +mod tests; diff --git a/poc/reverse-attach-linux/src/legacy_tests.rs b/poc/reverse-attach-linux/src/legacy_tests.rs new file mode 100644 index 0000000..9f772c9 --- /dev/null +++ b/poc/reverse-attach-linux/src/legacy_tests.rs @@ -0,0 +1,416 @@ +use super::*; +use crate::state::tests::TempDir; +use std::collections::HashMap; +use std::os::unix::fs::symlink; +use std::path::PathBuf; + +struct Tables(HashMap<&'static str, String>); + +impl Source for Tables { + fn table(&self, name: &str) -> std::io::Result { + self.0 + .get(name) + .cloned() + .ok_or_else(|| std::io::Error::other("none")) + } +} + +const HEAD: &str = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"; + +/// 0x225A is 8794. A row is `state` (0A = LISTEN) on `port` (4 hex digits). +fn row(port: &str, state: &str) -> String { + format!( + " 0: 0100007F:{port} 00000000:0000 {state} 00000000:00000000 00:00000000 00000000 1000 0 12345 1 0000000000000000 100 0 0 10 0\n" + ) +} + +fn tables(tcp: String) -> Tables { + Tables(HashMap::from([ + ("tcp", format!("{HEAD}{tcp}")), + ("tcp6", HEAD.to_string()), + ])) +} + +fn quiet() -> Tables { + tables(String::new()) +} + +fn home(t: &TempDir) -> PathBuf { + let h = t.path.join("home"); + fs::create_dir_all(&h).unwrap(); + h +} + +fn put(h: &Path, rel: &str, body: &str) { + let p = h.join(rel); + fs::create_dir_all(p.parent().unwrap()).unwrap(); + fs::write(p, body).unwrap(); +} + +const UNITS: &str = ".config/systemd/user"; + +/// Every file below `dir` with its bytes, and every directory, to compare before and after. +fn snapshot(dir: &Path) -> Vec<(String, Option>)> { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + for e in fs::read_dir(&d).unwrap().flatten() { + let p = e.path(); + let m = fs::symlink_metadata(&p).unwrap(); + let rel = p.strip_prefix(dir).unwrap().display().to_string(); + if m.is_dir() { + out.push((rel, None)); + stack.push(p); + } else if m.file_type().is_symlink() { + out.push(( + format!("{rel} -> {}", fs::read_link(&p).unwrap().display()), + None, + )); + } else { + out.push((rel, Some(fs::read(&p).unwrap()))); + } + } + } + out.sort(); + out +} + +#[test] +fn an_empty_home_has_nothing_legacy() { + let t = TempDir::new(); + let l = gather(Some(&home(&t)), &quiet()); + assert_eq!(l, Legacy::none()); + assert!(!l.present()); +} + +#[test] +fn each_legacy_unit_file_is_listed_by_its_fixed_name() { + for name in UNIT_FILES { + let t = TempDir::new(); + let h = home(&t); + put(&h, &format!("{UNITS}/{name}"), "[Service]\nExecStart=/x\n"); + let l = gather(Some(&h), &quiet()); + assert_eq!(l.units, name); + assert_eq!((l.paths.as_str(), l.listener.as_str()), ("none", "none")); + assert!(l.present()); + } + // Both, in the fixed order. + let t = TempDir::new(); + let h = home(&t); + for name in UNIT_FILES.iter().rev() { + put(&h, &format!("{UNITS}/{name}"), "x"); + } + assert_eq!( + gather(Some(&h), &quiet()).units, + "oab-pw-mcp.service,oab-computer-pw-mcp.service" + ); +} + +#[test] +fn the_new_unit_alongside_is_not_legacy() { + let t = TempDir::new(); + let h = home(&t); + for n in [ + "oab-computer.service", + "oab-computer-pw-mcp.service.bak", + "oab-seat.service", + ] { + put(&h, &format!("{UNITS}/{n}"), "[Service]\n"); + } + assert_eq!(gather(Some(&h), &quiet()), Legacy::none()); + // A legacy unit next to the new one is the only thing listed. + put(&h, &format!("{UNITS}/oab-computer-pw-mcp.service"), "x"); + let l = gather(Some(&h), &quiet()); + assert_eq!(l.units, "oab-computer-pw-mcp.service"); +} + +#[test] +fn a_drop_in_counts_only_when_it_sets_mcp_upstream_and_its_content_is_never_reported() { + let t = TempDir::new(); + let h = home(&t); + let secret = "Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp\nEnvironment=TOKEN=s3cr3t-token-value\n"; + put( + &h, + &format!("{UNITS}/oab-computer.service.d/browser.conf"), + &format!("[Service]\n{secret}"), + ); + // No MCP_UPSTREAM: not legacy. A commented line: not legacy. A file that is not `*.conf`: ignored. + put( + &h, + &format!("{UNITS}/oab-instance-mcp.service.d/other.conf"), + "[Service]\nEnvironment=FOO=1\n# MCP_UPSTREAM=browser=http://x\n; MCP_UPSTREAM=y\nUnsetEnvironment=MCP_UPSTREAM\n", + ); + put( + &h, + &format!("{UNITS}/oab-instance-mcp.service.d/old.txt"), + "Environment=MCP_UPSTREAM=browser=http://x\n", + ); + let l = gather(Some(&h), &quiet()); + assert_eq!(l.units, "drop-in:oab-computer.service.d"); + let all = format!("{l:?}"); + for bad in ["http", "127.0.0.1", "s3cr3t", "8794/mcp", "browser="] { + assert!(!all.contains(bad), "{bad}: {all}"); + } + // The second directory counts once a conf in it sets the variable (quoted form too). + put( + &h, + &format!("{UNITS}/oab-instance-mcp.service.d/up.conf"), + "[Service]\nEnvironment=\"MCP_UPSTREAM=browser=http://a\"\n", + ); + assert_eq!( + gather(Some(&h), &quiet()).units, + "drop-in:oab-computer.service.d,drop-in:oab-instance-mcp.service.d" + ); +} + +#[test] +fn a_symlinked_drop_in_directory_or_conf_is_not_followed() { + let t = TempDir::new(); + let h = home(&t); + let real = t.path.join("elsewhere"); + fs::create_dir_all(&real).unwrap(); + fs::write(real.join("a.conf"), "Environment=MCP_UPSTREAM=x\n").unwrap(); + fs::create_dir_all(h.join(UNITS)).unwrap(); + symlink(&real, h.join(UNITS).join("oab-computer.service.d")).unwrap(); + // A real directory whose only conf is a link. + let d = h.join(UNITS).join("oab-instance-mcp.service.d"); + fs::create_dir_all(&d).unwrap(); + symlink(real.join("a.conf"), d.join("link.conf")).unwrap(); + assert_eq!(gather(Some(&h), &quiet()).units, "none"); + // A dangling unit link still shows that something is there. + symlink("/nonexistent", h.join(UNITS).join("oab-pw-mcp.service")).unwrap(); + assert_eq!(gather(Some(&h), &quiet()).units, "oab-pw-mcp.service"); +} + +#[test] +fn legacy_paths_are_listed_with_sizes_and_the_old_profile_is_flagged() { + let t = TempDir::new(); + let h = home(&t); + put( + &h, + ".local/oab-computer/pw-mcp/node_modules/a.js", + &"x".repeat(3000), + ); + put(&h, ".local/oab-computer/pw-mcp/b.js", &"y".repeat(100)); + put(&h, ".local/oab-computer/pw-profile/Default/Cookies", "c"); + put(&h, ".local/oab-computer/pw-config.json", "{}"); + put(&h, ".local/oab-computer/pw-mcp.sh", &"s".repeat(2048)); + put(&h, ".cache/ms-playwright/chromium-1/x", "z"); + let l = gather(Some(&h), &quiet()); + let parts: Vec<&str> = l.paths.split(',').collect(); + assert_eq!(parts.len(), 5, "{}", l.paths); + // Directory sizes are the sum of apparent file and directory-entry lengths; assert the shape and + // the fixed unit, and the exact size for the two plain files. + assert!(parts[0].starts_with("~/.local/oab-computer/pw-mcp:") && parts[0].ends_with(" KiB")); + assert!(parts[1].starts_with("~/.local/oab-computer/pw-profile:")); + assert!(parts[1].ends_with(":holds_cookies"), "{}", parts[1]); + assert_eq!(parts[2], "~/.local/oab-computer/pw-config.json:2 B"); + assert_eq!(parts[3], "~/.local/oab-computer/pw-mcp.sh:2 KiB"); + assert!(parts[4].starts_with("~/.cache/ms-playwright:")); + // Only the old profile carries the flag. + assert_eq!(l.paths.matches("holds_cookies").count(), 1); + // The home directory is never spelled out. + assert!(!l.paths.contains(h.to_str().unwrap())); + // The other two fixed paths, when present, come in the fixed order. + put(&h, ".local/oab-instance-mcp/pw-mcp/p", "1"); + fs::create_dir_all(h.join(".local/oab-computer/pw-output")).unwrap(); + let l = gather(Some(&h), &quiet()); + let names: Vec<&str> = l + .paths + .split(',') + .map(|p| p.split(':').next().unwrap()) + .collect(); + assert_eq!( + names, + [ + "~/.local/oab-computer/pw-mcp", + "~/.local/oab-computer/pw-profile", + "~/.local/oab-computer/pw-output", + "~/.local/oab-computer/pw-config.json", + "~/.local/oab-computer/pw-mcp.sh", + "~/.local/oab-instance-mcp/pw-mcp", + "~/.cache/ms-playwright", + ] + ); +} + +#[test] +fn a_symlinked_legacy_directory_is_reported_and_not_followed() { + let t = TempDir::new(); + let h = home(&t); + let big = t.path.join("big"); + fs::create_dir_all(&big).unwrap(); + fs::write(big.join("f"), vec![0u8; 5 * 1024 * 1024]).unwrap(); + fs::create_dir_all(h.join(".local/oab-computer")).unwrap(); + symlink(&big, h.join(".local/oab-computer/pw-profile")).unwrap(); + // A link inside a listed tree counts as its own length and is not entered. + put(&h, ".cache/ms-playwright/a", "a"); + symlink(&big, h.join(".cache/ms-playwright/link")).unwrap(); + let l = gather(Some(&h), &quiet()); + assert!( + l.paths + .contains("~/.local/oab-computer/pw-profile:symlink:holds_cookies"), + "{}", + l.paths + ); + let cache = l + .paths + .split(',') + .find(|p| p.contains("ms-playwright")) + .unwrap(); + assert!(cache.ends_with(" B") || cache.ends_with(" KiB"), "{cache}"); + assert!(!cache.contains("MiB"), "{cache}"); +} + +#[test] +fn a_tree_past_a_cap_or_a_permission_error_is_size_unknown() { + let t = TempDir::new(); + let d = t.path.join("tree"); + for i in 0..5 { + fs::create_dir_all(d.join("sub")).unwrap(); + fs::write(d.join(format!("f{i}")), "x").unwrap(); + } + assert!(dir_size_with(&d, 100, 8).is_some()); + assert_eq!(dir_size_with(&d, 3, 8), None, "entry cap"); + let deep = t.path.join("deep/a/b/c/d"); + fs::create_dir_all(&deep).unwrap(); + assert!(dir_size_with(&t.path.join("deep"), 100, 8).is_some()); + assert_eq!( + dir_size_with(&t.path.join("deep"), 100, 2), + None, + "depth cap" + ); + assert_eq!(dir_size_with(&t.path.join("missing"), 100, 8), None); + // Through `gather`: a legacy directory that cannot be listed. + use std::os::unix::fs::PermissionsExt; + let h = home(&t); + put(&h, ".local/oab-computer/pw-output/f", "x"); + let out = h.join(".local/oab-computer/pw-output"); + fs::set_permissions(&out, fs::Permissions::from_mode(0o000)).unwrap(); + let l = gather(Some(&h), &quiet()); + fs::set_permissions(&out, fs::Permissions::from_mode(0o700)).unwrap(); + // Root can list a mode 000 directory; there is nothing to assert for it. + if rustix::process::geteuid().as_raw() != 0 { + assert_eq!(l.paths, "~/.local/oab-computer/pw-output:size_unknown"); + } +} + +#[test] +fn sizes_use_a_fixed_unit_rounded_up() { + assert_eq!(format_size(0), "0 B"); + assert_eq!(format_size(1023), "1023 B"); + assert_eq!(format_size(1024), "1 KiB"); + assert_eq!(format_size(1025), "2 KiB"); + assert_eq!(format_size(1024 * 1024), "1 MiB"); + assert_eq!(format_size(1024 * 1024 + 1), "2 MiB"); + assert_eq!(format_size(3 * 1024 * 1024 * 1024), "3 GiB"); +} + +#[test] +fn the_old_port_is_reported_only_when_something_listens_on_it() { + let t = TempDir::new(); + let h = home(&t); + // 0x225A = 8794, state 0A = LISTEN. + let l = gather(Some(&h), &tables(row("225A", "0A"))); + assert_eq!(l.listener, "8794"); + assert!(l.present()); + // Another port, or the port in a state that is not LISTEN (an established connection). + for tcp in [row("1F90", "0A"), row("225A", "01"), String::new()] { + assert_eq!(gather(Some(&h), &tables(tcp)).listener, "none"); + } + // tcp6 counts too. + let mut t6 = quiet(); + t6.0.insert( + "tcp6", + format!( + "{HEAD} 0: 00000000000000000000000001000000:225A 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1001 0 22345 1 0000000000000000 100 0 0 10 0\n" + ), + ); + assert_eq!(gather(Some(&h), &t6).listener, "8794"); + // An unreadable tcp table is `unknown`, never `none`; a missing tcp6 table (no IPv6) is fine. + assert_eq!( + gather(Some(&h), &Tables(HashMap::new())).listener, + "unknown" + ); + let only4 = Tables(HashMap::from([("tcp", HEAD.to_string())])); + assert_eq!(gather(Some(&h), &only4).listener, "none"); + // `unknown` is not a finding. + assert!(!gather(Some(&h), &Tables(HashMap::new())).present()); +} + +#[test] +fn only_an_active_environment_assignment_of_mcp_upstream_counts() { + use super::sets_upstream as set; + for yes in [ + "Environment=MCP_UPSTREAM=browser=http://x", + " Environment=MCP_UPSTREAM=a", + "Environment=\"MCP_UPSTREAM=a\"", + "Environment='MCP_UPSTREAM=a'", + "Environment=FOO=1 'MCP_UPSTREAM=a'", + "Environment=FOO=1 MCP_UPSTREAM=a", + "Environment=FOO=1 \"MCP_UPSTREAM=a\"", + ] { + assert!(set(yes), "{yes}"); + } + for no in [ + "# Environment=MCP_UPSTREAM=a", + "UnsetEnvironment=MCP_UPSTREAM", + "UnsetEnvironment=MCP_UPSTREAM=a", + "Environment=XMCP_UPSTREAM=a", + "Environment=FOO=MCP_UPSTREAM", + "Environment=FOO=1 # MCP_UPSTREAM=a", + "ExecStart=/bin/true MCP_UPSTREAM=a", + "Description=MCP_UPSTREAM=a", + ] { + assert!(!set(no), "{no}"); + } +} + +#[test] +fn an_unknown_home_is_unknown_never_none() { + for h in [None, Some(Path::new(""))] { + let l = gather(h, &quiet()); + assert_eq!( + (l.units.as_str(), l.paths.as_str(), l.listener.as_str()), + ("unknown", "unknown", "none") + ); + assert!(!l.present()); + } +} + +#[test] +fn everything_present_is_listed_and_nothing_on_disk_changes() { + let t = TempDir::new(); + let h = home(&t); + for n in UNIT_FILES { + put(&h, &format!("{UNITS}/{n}"), "[Service]\nExecStart=/old\n"); + } + put( + &h, + &format!("{UNITS}/oab-computer.service.d/up.conf"), + "Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp\n", + ); + put(&h, ".local/oab-computer/pw-mcp/a", "1"); + put(&h, ".local/oab-computer/pw-profile/Cookies", "c"); + put(&h, ".local/oab-computer/pw-mcp.sh", "#!/bin/bash\n"); + put(&h, ".cache/ms-playwright/x", "z"); + let before = snapshot(&h); + let l = gather(Some(&h), &tables(row("225A", "0A"))); + assert_ne!(l, Legacy::none()); + assert_eq!(snapshot(&h), before, "the listing changed something"); + // The rendered fields hold no URL, address or token-like text, and no absolute home path. + let all = format!("{} {} {}", l.units, l.paths, l.listener); + for bad in [ + "http", + "127.0.0.1", + "token", + "Bearer", + "://", + h.to_str().unwrap(), + ] { + assert!(!all.contains(bad), "{bad}: {all}"); + } + assert!(all + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b" ~/.:_,-".contains(&b))); +} diff --git a/poc/reverse-attach-linux/src/main.rs b/poc/reverse-attach-linux/src/main.rs index 1d3498c..1199371 100644 --- a/poc/reverse-attach-linux/src/main.rs +++ b/poc/reverse-attach-linux/src/main.rs @@ -35,6 +35,7 @@ mod http; mod http_conformance; mod install; mod jobs; +mod legacy; mod manifest; #[cfg(test)] mod manifest_conformance; diff --git a/poc/reverse-attach-linux/src/probe.rs b/poc/reverse-attach-linux/src/probe.rs index e99dfe9..101dc7a 100644 --- a/poc/reverse-attach-linux/src/probe.rs +++ b/poc/reverse-attach-linux/src/probe.rs @@ -9,7 +9,8 @@ //! - `external_configured`: `yes` when this process's `MCP_UPSTREAM` has a `browser=` entry. //! - `listeners`: what the managed tree (every same-uid process whose executable is below a version //! or staging directory of the root, the sweep's own rule) holds. `not_running`, `none`, -//! `tcp=N udp=N unix=N` or `unknown` when a table cannot be read. +//! `tcp=N udp=N unix=N unix_outside=N tmpdir=S result=pass|fail` (see `listeners_word`) or +//! `unknown` when a table cannot be read. //! - `refusal`: `none`, `launch_refused` or `sandbox_unavailable`. //! //! L4 adds four more, appended after those so existing readers keep their order: @@ -23,6 +24,10 @@ //! not read `1` in an applied tier (`hardening.rs` holds the fixed vocabulary). //! - `run_records`: `ok`, `full` (a managed start would refuse with `run_records_full`) or //! `unavailable` (`run/` missing, unmarked or unreadable). +//! +//! L5 appends three more, the legacy listing of `legacy.rs`: `legacy_units`, `legacy` and +//! `legacy_listener`. They are filled by `Extras::set_legacy`, outside `gather`, because they look at +//! the home directory and not at the data root. use std::path::Path; @@ -43,6 +48,9 @@ pub struct Extras { pub hardening_mount: String, pub hardening_unverified: String, pub run_records: String, + pub legacy_units: String, + pub legacy: String, + pub legacy_listener: String, } impl Extras { @@ -57,8 +65,28 @@ impl Extras { hardening_unverified: Tiers::NONE.unverified_text(), // Without an install root there is no `run/`. run_records: RunRecords::Unavailable.word().into(), + legacy_units: "none".into(), + legacy: "none".into(), + legacy_listener: "none".into(), } } + + /// Fills the three legacy fields (L5). + pub fn set_legacy(&mut self, l: crate::legacy::Legacy) { + self.legacy_units = l.units; + self.legacy = l.paths; + self.legacy_listener = l.listener; + } + + /// Something of the old external setup was found (`unknown` is not a finding). + pub fn legacy_present(&self) -> bool { + crate::legacy::Legacy { + units: self.legacy_units.clone(), + paths: self.legacy.clone(), + listener: self.legacy_listener.clone(), + } + .present() + } } /// The pids of the managed tree, by the sweep's rule. @@ -75,6 +103,28 @@ fn tree_pids(root_abs: &Path) -> Vec { .collect() } +/// The `listeners` field. `none`, `unknown`, or the counts with the V2 verdict: +/// `tcp=N udp=N unix=N unix_outside=N tmpdir= result=pass|fail` (R1.1 as decided: only +/// Unix listeners inside the child's verified private `TMPDIR` pass). +pub(crate) fn listeners_word( + l: Result, + tmp: procnet::TmpState, +) -> String { + match l { + Ok(l) if l.total() == 0 => "none".into(), + Ok(l) => format!( + "tcp={} udp={} unix={} unix_outside={} tmpdir={} result={}", + l.tcp, + l.udp, + l.unix, + l.unix_outside, + tmp.word(), + if l.passes_v2() { "pass" } else { "fail" } + ), + Err(_) => "unknown".into(), + } +} + /// `verify` runs the containment self-test (only called with `retry`). pub fn gather( base: &Path, @@ -100,11 +150,15 @@ pub fn gather( x.run_records = run_record::state(&root).word().into(); let pids = tree_pids(root.abs_path()); if !pids.is_empty() { - x.listeners = match procnet::listeners_of_tree(src, &pids) { - Ok(l) if l.total() == 0 => "none".into(), - Ok(l) => format!("tcp={} udp={} unix={}", l.tcp, l.udp, l.unix), - Err(_) => "unknown".into(), - }; + let tmp = crate::child::RuntimeTmp::expected_path(root.abs_path()); + let tmp_state = procnet::tmp_state(&tmp, rustix::process::geteuid().as_raw()); + let private = (tmp_state == procnet::TmpState::Ok) + .then(|| tmp.to_str().map(str::to_owned)) + .flatten(); + x.listeners = listeners_word( + procnet::listeners_of_tree_in(src, &pids, private.as_deref()), + tmp_state, + ); } } if retry { diff --git a/poc/reverse-attach-linux/src/probe_tests.rs b/poc/reverse-attach-linux/src/probe_tests.rs index 7c0788f..3930c46 100644 --- a/poc/reverse-attach-linux/src/probe_tests.rs +++ b/poc/reverse-attach-linux/src/probe_tests.rs @@ -33,6 +33,30 @@ fn by_default_nothing_runs_and_the_vocabulary_is_fixed() { assert_eq!(x.hardening_mount, "not_checked"); assert_eq!(x.hardening_unverified, "not_checked"); assert_eq!(x.run_records, "unavailable"); + // L5: `gather` does not look at the home directory, so the legacy fields stay `none`. + assert_eq!( + ( + x.legacy_units.as_str(), + x.legacy.as_str(), + x.legacy_listener.as_str() + ), + ("none", "none", "none") + ); + assert!(!x.legacy_present()); +} + +#[test] +fn the_legacy_fields_are_set_apart_from_the_probe() { + let mut x = Extras::none(); + x.set_legacy(crate::legacy::Legacy { + units: "oab-pw-mcp.service".into(), + paths: "~/.cache/ms-playwright:1 MiB".into(), + listener: "8794".into(), + }); + assert!(x.legacy_present()); + assert_eq!(x.legacy_units, "oab-pw-mcp.service"); + assert_eq!(x.legacy, "~/.cache/ms-playwright:1 MiB"); + assert_eq!(x.legacy_listener, "8794"); } #[test] @@ -170,3 +194,39 @@ fn a_full_run_directory_is_named_in_the_status() { "full" ); } + +#[test] +fn the_listeners_word_carries_the_v2_verdict() { + use crate::procnet::{Listeners, TmpState}; + let w = |l: Listeners, t| listeners_word(Ok(l), t); + assert_eq!(w(Listeners::default(), TmpState::Missing), "none"); + let two = Listeners { + unix: 2, + ..Default::default() + }; + assert_eq!( + w(two, TmpState::Ok), + "tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass" + ); + let out = Listeners { + unix: 2, + unix_outside: 1, + ..Default::default() + }; + assert!(w(out, TmpState::Ok).ends_with("unix_outside=1 tmpdir=ok result=fail")); + let all_out = Listeners { + unix: 2, + unix_outside: 2, + ..Default::default() + }; + assert_eq!( + w(all_out, TmpState::Mode), + "tcp=0 udp=0 unix=2 unix_outside=2 tmpdir=mode result=fail" + ); + let tcp = Listeners { + tcp: 1, + ..Default::default() + }; + assert!(w(tcp, TmpState::Ok).ends_with("result=fail")); + assert_eq!(listeners_word(Err("x"), TmpState::Ok), "unknown"); +} diff --git a/poc/reverse-attach-linux/src/proc.rs b/poc/reverse-attach-linux/src/proc.rs index 509f630..d23e73b 100644 --- a/poc/reverse-attach-linux/src/proc.rs +++ b/poc/reverse-attach-linux/src/proc.rs @@ -294,7 +294,9 @@ impl Child { /// refusal and exited closes stdout before the reader thread has necessarily queued that last /// line, so a classification made at once could read an empty ring and call a refusal a plain /// failure. A child that is still running never reaches end of file, so this is a bounded delay - /// on a failure path, never on a success. + /// on a failure path, never on a success. This is production code, not a test aid: every + /// classification of a failed child goes through it. Pinned by + /// `a_child_that_prints_nothing_on_stderr_is_classified_without_waiting_for_a_timeout`. fn settle_stderr(&self) { let end = Instant::now() + Duration::from_millis(250); while !self.stderr_done.load(Ordering::Acquire) && Instant::now() < end { diff --git a/poc/reverse-attach-linux/src/procnet.rs b/poc/reverse-attach-linux/src/procnet.rs index bf2cfc9..518f66c 100644 --- a/poc/reverse-attach-linux/src/procnet.rs +++ b/poc/reverse-attach-linux/src/procnet.rs @@ -26,6 +26,12 @@ pub const UNKNOWN: &str = "listener_owner_unknown"; pub trait Source { /// The text of `/proc/net/` (`tcp`, `tcp6`, `udp`, `udp6`, `unix`). fn table(&self, name: &str) -> std::io::Result; + /// Whether every directory between `private` and the socket's own name is a real directory (not + /// a link), so the node is physically inside `private`. A fixture with no filesystem keeps the + /// default. + fn parents_are_plain(&self, _path: &str, _private: &str) -> bool { + true + } } /// The real `/proc`. @@ -42,6 +48,30 @@ impl Source for Proc { } Ok(s) } + + fn parents_are_plain(&self, path: &str, private: &str) -> bool { + plain_parents(path, private) + } +} + +/// `path` is below `private` by [`is_inside`]. Walk each directory between them with `lstat`: a link +/// (or anything unreadable) fails closed, because the kernel prints the bind path as the program +/// spelled it, so a link could place the node outside the verified directory. +pub fn plain_parents(path: &str, private: &str) -> bool { + let Some(rest) = path.strip_prefix(private).and_then(|r| r.strip_prefix('/')) else { + return false; + }; + let mut cur = std::path::PathBuf::from(private); + let mut segs: Vec<&str> = rest.split('/').collect(); + segs.pop(); + for seg in segs { + cur.push(seg); + match std::fs::symlink_metadata(&cur) { + Ok(m) if m.file_type().is_dir() => {} + _ => return false, + } + } + true } #[derive(Clone, Debug, PartialEq, Eq)] @@ -100,7 +130,17 @@ pub fn parse_inet(text: &str, v6: bool) -> Vec { /// `Num RefCount Protocol Flags Type St Inode [Path]`: listening Unix sockets carry /// `__SO_ACCEPTCON` (0x10000) in the flags. Returns their inodes. +#[cfg(test)] pub fn parse_unix_listeners(text: &str) -> Vec { + parse_unix_listener_paths(text) + .into_iter() + .map(|(inode, _)| inode) + .collect() +} + +/// The same rows with the path the socket was bound to (`""` for an unnamed socket; an abstract +/// name keeps its leading `@`). The kernel prints the path as the program passed it to `bind`. +pub fn parse_unix_listener_paths(text: &str) -> Vec<(u64, String)> { text.lines() .skip(1) .filter_map(|l| { @@ -109,11 +149,72 @@ pub fn parse_unix_listeners(text: &str) -> Vec { if flags & 0x10000 == 0 { return None; } - f.get(6)?.parse().ok() + Some((f.get(6)?.parse().ok()?, f.get(7..)?.join(" "))) }) .collect() } +/// Whether `path`, as bound, is strictly below the private directory `private`: it starts with +/// `private` and a `/`, and every segment after that is a plain name (no empty segment, `.` or +/// `..`). An exact string rule, no pattern and no symlink resolution: a path that reaches the +/// directory in another spelling counts as outside (fail closed). +pub fn is_inside(path: &str, private: &str) -> bool { + let Some(rest) = path.strip_prefix(private).and_then(|r| r.strip_prefix('/')) else { + return false; + }; + !rest.is_empty() + && rest + .split('/') + .all(|s| !s.is_empty() && s != "." && s != "..") +} + +/// What is wrong with the child's private `TMPDIR`, or `ok`. Read without following a link. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TmpState { + Ok, + /// Nothing at the expected path. + Missing, + /// Not a directory (a link or a file in its place). + NotDir, + /// A directory whose mode is not exactly `0700`. + Mode, + /// A directory not owned by the daemon's uid. + Owner, + Unreadable, +} + +impl TmpState { + pub fn word(self) -> &'static str { + match self { + TmpState::Ok => "ok", + TmpState::Missing => "missing", + TmpState::NotDir => "not_dir", + TmpState::Mode => "mode", + TmpState::Owner => "owner", + TmpState::Unreadable => "unreadable", + } + } +} + +/// `ok` only for a real directory (not a link) owned by `uid` with mode exactly `0700`. +pub fn tmp_state(path: &std::path::Path, uid: u32) -> TmpState { + use std::os::unix::fs::MetadataExt; + let m = match std::fs::symlink_metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return TmpState::Missing, + Err(_) => return TmpState::Unreadable, + }; + if !m.file_type().is_dir() { + TmpState::NotDir + } else if m.uid() != uid { + TmpState::Owner + } else if m.mode() & 0o7777 != 0o700 { + TmpState::Mode + } else { + TmpState::Ok + } +} + fn inet_rows(src: &dyn Source, v6: bool, proto: &str) -> std::io::Result> { let name = format!("{proto}{}", if v6 { "6" } else { "" }); Ok(parse_inet(&src.table(&name)?, v6)) @@ -175,12 +276,21 @@ pub struct Listeners { pub tcp: usize, pub udp: usize, pub unix: usize, + /// Of `unix`, the listeners that are not inside the verified private `TMPDIR` (V2). With no + /// verified directory every Unix listener is outside. + pub unix_outside: usize, } impl Listeners { pub fn total(&self) -> usize { self.tcp + self.udp + self.unix } + + /// The V2 rule (R1.1 as decided): no TCP or UDP listener, and no Unix listener outside the + /// private per-run `TMPDIR`. A tree that listens on nothing passes. + pub fn passes_v2(&self) -> bool { + self.tcp == 0 && self.udp == 0 && self.unix_outside == 0 + } } /// Socket inodes held open by `pid` (`/proc//fd/*` links of the form `socket:[N]`). @@ -206,7 +316,18 @@ pub fn socket_inodes(pid: u32) -> HashSet { /// Listeners among `inodes`: TCP in state LISTEN (0A), UDP sockets bound and not connected (07), /// and Unix sockets that accept. An unreadable table is an error: "none" would be a claim. +#[cfg(test)] pub fn listeners_among(src: &dyn Source, inodes: &HashSet) -> Result { + listeners_among_in(src, inodes, None) +} + +/// Like [`listeners_among`]. `private` is the child's private `TMPDIR`, passed only when it was +/// verified (`TmpState::Ok`); a Unix listener is "outside" unless its path is below it. +pub fn listeners_among_in( + src: &dyn Source, + inodes: &HashSet, + private: Option<&str>, +) -> Result { let mut out = Listeners::default(); for v6 in [false, true] { for r in inet_rows(src, v6, "tcp").map_err(|_| UNKNOWN)? { @@ -221,20 +342,35 @@ pub fn listeners_among(src: &dyn Source, inodes: &HashSet) -> Result Result { + listeners_of_tree_in(src, pids, None) +} + +/// Like [`listeners_of_tree`], with the verified private `TMPDIR` (see [`listeners_among_in`]). +pub fn listeners_of_tree_in( + src: &dyn Source, + pids: &[u32], + private: Option<&str>, +) -> Result { let mut inodes = HashSet::new(); for p in pids { inodes.extend(socket_inodes(*p)); } - listeners_among(src, &inodes) + listeners_among_in(src, &inodes, private) } #[cfg(test)] diff --git a/poc/reverse-attach-linux/src/procnet_tests.rs b/poc/reverse-attach-linux/src/procnet_tests.rs index 87bacf3..fefe67a 100644 --- a/poc/reverse-attach-linux/src/procnet_tests.rs +++ b/poc/reverse-attach-linux/src/procnet_tests.rs @@ -120,7 +120,8 @@ fn listeners_of_a_set_of_sockets_are_counted_by_kind() { Ok(Listeners { tcp: 2, udp: 1, - unix: 1 + unix: 1, + unix_outside: 1 }) ); let none: HashSet = [12346, 32].into(); @@ -297,3 +298,205 @@ fn an_ipv6_server_reads_tcp6_only_and_an_unreadable_own_table_fails_closed() { Err(UNKNOWN) ); } + +const UNIX_HEAD: &str = "Num RefCount Protocol Flags Type St Inode Path\n"; +const PRIV: &str = "/run/user/1000/oab-pw-1a2b3c4d"; + +fn unix_src(rows: &str) -> Fixture { + Fixture( + [ + ("tcp", Ok(HEAD.to_string())), + ("tcp6", Ok(HEAD.to_string())), + ("udp", Ok(HEAD.to_string())), + ("udp6", Ok(HEAD.to_string())), + ("unix", Ok(format!("{UNIX_HEAD}{rows}"))), + ] + .into_iter() + .collect(), + ) +} + +#[test] +fn unix_listener_paths_keep_the_bound_name() { + let t = format!( + "{UNIX_HEAD}0: 2 0 00010000 0001 01 7 /a/b c\n1: 2 0 00010000 0001 01 8\n2: 2 0 00010000 0001 01 9 @abs\n3: 2 0 00000000 0001 01 10 /x\n" + ); + assert_eq!( + parse_unix_listener_paths(&t), + [(7, "/a/b c".into()), (8, "".into()), (9, "@abs".into())] + ); +} + +#[test] +fn only_a_plain_path_below_the_private_directory_is_inside() { + let ok = |p: &str| is_inside(p, PRIV); + assert!(ok(&format!( + "{PRIV}/org.chromium.Chromium.x/SingletonSocket" + ))); + assert!(ok(&format!("{PRIV}/pw-ab/browser/browser-1.sock"))); + assert!(!ok(PRIV), "the directory itself is not below it"); + assert!(!ok(&format!("{PRIV}/"))); + assert!( + !ok(&format!("{PRIV}x/s")), + "a sibling that shares the prefix" + ); + assert!(!ok(&format!("{PRIV}/../s"))); + assert!(!ok(&format!("{PRIV}/a/../../s"))); + assert!(!ok(&format!("{PRIV}/./s"))); + assert!(!ok(&format!("{PRIV}//s"))); + assert!(!ok("@abstract")); + assert!(!ok("")); + assert!(!ok("/tmp/s")); + assert!(!ok("run/user/1000/oab-pw-1a2b3c4d/s")); +} + +#[test] +fn v2_unix_listeners_inside_the_private_directory_pass() { + let rows = format!( + "0: 2 0 00010000 0001 01 41 {PRIV}/pw-ab/browser/b.sock\n1: 2 0 00010000 0001 01 42 {PRIV}/org.chromium.Chromium.x/SingletonSocket\n" + ); + let src = unix_src(&rows); + let all: HashSet = [41, 42].into(); + let l = listeners_among_in(&src, &all, Some(PRIV)).unwrap(); + assert_eq!((l.tcp, l.udp, l.unix, l.unix_outside), (0, 0, 2, 0)); + assert!(l.passes_v2()); +} + +#[test] +fn v2_a_unix_listener_outside_the_private_directory_fails() { + let rows = format!( + "0: 2 0 00010000 0001 01 41 {PRIV}/pw-ab/b.sock\n1: 2 0 00010000 0001 01 42 /tmp/elsewhere.sock\n2: 2 0 00010000 0001 01 43 @abstract\n3: 2 0 00010000 0001 01 44\n" + ); + let src = unix_src(&rows); + let all: HashSet = [41, 42, 43, 44].into(); + let l = listeners_among_in(&src, &all, Some(PRIV)).unwrap(); + assert_eq!((l.unix, l.unix_outside), (4, 3)); + assert!(!l.passes_v2()); + // One that belongs to another process is not counted at all. + let only: HashSet = [41].into(); + assert!(listeners_among_in(&src, &only, Some(PRIV)) + .unwrap() + .passes_v2()); +} + +#[test] +fn v2_without_a_verified_private_directory_every_unix_listener_is_outside() { + let rows = format!("0: 2 0 00010000 0001 01 41 {PRIV}/pw-ab/b.sock\n"); + let src = unix_src(&rows); + let all: HashSet = [41].into(); + let l = listeners_among_in(&src, &all, None).unwrap(); + assert_eq!((l.unix, l.unix_outside), (1, 1)); + assert!(!l.passes_v2()); + assert!(!listeners_among(&src, &all).unwrap().passes_v2()); +} + +#[cfg(target_endian = "little")] +#[test] +fn v2_any_tcp_or_udp_listener_fails_even_with_the_private_directory() { + let src = Fixture( + [ + ("tcp", Ok(tcp())), + ("tcp6", Ok(HEAD.to_string())), + ("udp", Ok(HEAD.to_string())), + ("udp6", Ok(HEAD.to_string())), + ("unix", Ok(UNIX_HEAD.to_string())), + ] + .into_iter() + .collect(), + ); + let all: HashSet = [12345].into(); + let l = listeners_among_in(&src, &all, Some(PRIV)).unwrap(); + assert_eq!(l.tcp, 1); + assert!(!l.passes_v2()); +} + +#[cfg(target_os = "linux")] +mod tmp_dir { + use super::*; + use std::os::unix::fs::PermissionsExt; + + fn dir_with_mode( + t: &crate::state::tests::TempDir, + name: &str, + mode: u32, + ) -> std::path::PathBuf { + let d = t.path.join(name); + std::fs::create_dir(&d).unwrap(); + std::fs::set_permissions(&d, std::fs::Permissions::from_mode(mode)).unwrap(); + d + } + + fn me() -> u32 { + rustix::process::geteuid().as_raw() + } + + #[test] + fn a_private_directory_of_ours_is_ok() { + let t = crate::state::tests::TempDir::new(); + let d = dir_with_mode(&t, "ok", 0o700); + assert_eq!(tmp_state(&d, me()), TmpState::Ok); + } + + #[test] + fn a_directory_that_is_not_exactly_0700_fails() { + let t = crate::state::tests::TempDir::new(); + for (n, m) in [ + ("a", 0o755), + ("b", 0o750), + ("c", 0o701), + ("d", 0o770), + ("e", 0o500), + ] { + let d = dir_with_mode(&t, n, m); + assert_eq!(tmp_state(&d, me()), TmpState::Mode, "mode {m:o}"); + } + } + + #[test] + fn a_directory_of_another_uid_fails() { + let t = crate::state::tests::TempDir::new(); + let d = dir_with_mode(&t, "x", 0o700); + assert_eq!(tmp_state(&d, me().wrapping_add(1)), TmpState::Owner); + } + + #[test] + fn a_missing_path_a_file_and_a_link_fail() { + let t = crate::state::tests::TempDir::new(); + assert_eq!(tmp_state(&t.path.join("none"), me()), TmpState::Missing); + let f = t.path.join("f"); + std::fs::write(&f, b"x").unwrap(); + assert_eq!(tmp_state(&f, me()), TmpState::NotDir); + let real = dir_with_mode(&t, "real", 0o700); + let l = t.path.join("link"); + std::os::unix::fs::symlink(&real, &l).unwrap(); + assert_eq!( + tmp_state(&l, me()), + TmpState::NotDir, + "a link is never followed" + ); + } +} + +#[test] +fn a_link_between_the_private_directory_and_the_socket_is_not_plain() { + use std::os::unix::fs::symlink; + let base = std::env::temp_dir().join(format!("oab-plain-{}", std::process::id())); + let private = base.join("priv"); + let outside = base.join("outside"); + std::fs::create_dir_all(private.join("real")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + symlink(&outside, private.join("link")).unwrap(); + let p = private.to_str().unwrap(); + assert!(plain_parents(&format!("{p}/s"), p)); + assert!(plain_parents(&format!("{p}/real/s"), p)); + assert!( + !plain_parents(&format!("{p}/link/s"), p), + "symlinked parent" + ); + assert!( + !plain_parents(&format!("{p}/missing/s"), p), + "unreadable parent" + ); + assert!(!plain_parents("/elsewhere/s", p)); + std::fs::remove_dir_all(&base).unwrap(); +} diff --git a/poc/reverse-attach-linux/src/sigstop_tests.rs b/poc/reverse-attach-linux/src/sigstop_tests.rs index ab95c73..f43482c 100644 --- a/poc/reverse-attach-linux/src/sigstop_tests.rs +++ b/poc/reverse-attach-linux/src/sigstop_tests.rs @@ -300,6 +300,30 @@ fn host_starts_the_base_probe() -> bool { ok } +/// The fallback the two unit-mode tests would otherwise skip over: where the base probe cannot +/// start, `verify` fails closed and a CLI child runs plain (#132). Asserted instead of returned +/// from: the child has a run record with no unit, no unit was made, and SIGTERM still ends the +/// child and its detached grandchild through the process-tree layers. +#[cfg(target_os = "linux")] +fn assert_unit_mode_falls_back_to_plain() { + let t = TempDir::new(); + let mut h = start_helper(&t, "systemd"); + let root = Root::open(&t.base(), false).unwrap().unwrap(); + let live = run_record::live(&root); + assert_eq!(live.len(), 1, "the run record"); + assert_eq!( + live[0].unit, None, + "a unit was made on a host that cannot verify" + ); + assert_eq!(units_left(), 0, "a unit is left"); + assert!(h.child_alive() && h.grand_alive()); + h.signal("TERM"); + h.wait_exit(); + assert!(h.until(|h| !h.child_alive()), "plain: child"); + assert!(h.until(|h| !h.grand_alive()), "plain: detached grandchild"); + assert!(run_record::live(&root).is_empty()); +} + #[cfg(target_os = "linux")] fn units_left() -> usize { test_systemd() @@ -312,7 +336,11 @@ fn units_left() -> usize { #[test] #[ignore = "needs a systemd user manager; OAB_L2_SYSTEMD=1"] fn a_cli_child_in_a_real_unit_is_stopped_by_hup_term_and_int() { - if std::env::var_os("OAB_L2_SYSTEMD").is_none() || !host_starts_the_base_probe() { + if std::env::var_os("OAB_L2_SYSTEMD").is_none() { + return; + } + if !host_starts_the_base_probe() { + assert_unit_mode_falls_back_to_plain(); return; } for sig in ["HUP", "TERM", "INT"] { @@ -343,7 +371,11 @@ fn a_cli_child_in_a_real_unit_is_stopped_by_hup_term_and_int() { #[test] #[ignore = "needs a systemd user manager; OAB_L2_SYSTEMD=1"] fn sigkill_of_a_cli_leaves_its_unit_and_the_next_starts_sweep_stops_it() { - if std::env::var_os("OAB_L2_SYSTEMD").is_none() || !host_starts_the_base_probe() { + if std::env::var_os("OAB_L2_SYSTEMD").is_none() { + return; + } + if !host_starts_the_base_probe() { + assert_unit_mode_falls_back_to_plain(); return; } let t = TempDir::new(); diff --git a/poc/reverse-attach-linux/src/state.rs b/poc/reverse-attach-linux/src/state.rs index ffdc531..b25da3e 100644 --- a/poc/reverse-attach-linux/src/state.rs +++ b/poc/reverse-attach-linux/src/state.rs @@ -156,6 +156,29 @@ pub fn open_private_base(candidate: Option<&Path>) -> R<(OwnedFd, PathBuf)> { open_private_base_in(candidate, Path::new("/tmp"), euid()) } +/// The path `open_private_base` would choose, decided read-only (nothing is created or opened for +/// writing). For `browser status`, which must name the child's `TMPDIR` without making it. +pub fn private_base_path(candidate: Option<&Path>) -> PathBuf { + private_base_path_in(candidate, Path::new("/tmp"), euid()) +} + +pub(crate) fn private_base_path_in( + candidate: Option<&Path>, + shared_tmp: &Path, + uid: u32, +) -> PathBuf { + use std::os::unix::fs::MetadataExt; + if let Some(c) = candidate.filter(|c| c.is_absolute() && c.as_os_str().len() <= SHORT_BASE_MAX) + { + if std::fs::symlink_metadata(c) + .is_ok_and(|m| m.is_dir() && m.uid() == uid && m.mode() & 0o022 == 0) + { + return c.to_path_buf(); + } + } + shared_tmp.join(format!("oab-{uid}")) +} + pub(crate) fn open_private_base_in( candidate: Option<&Path>, shared_tmp: &Path, diff --git a/poc/reverse-attach-linux/src/state_tests.rs b/poc/reverse-attach-linux/src/state_tests.rs index 7e1eac4..9f0df05 100644 --- a/poc/reverse-attach-linux/src/state_tests.rs +++ b/poc/reverse-attach-linux/src/state_tests.rs @@ -1073,3 +1073,31 @@ fn a_planted_or_loose_fallback_directory_is_refused() { dir_with_mode(&t.path.join("tmp").join(format!("oab-{other}")), 0o700); assert!(open_private_base_in(None, &t.path.join("tmp"), other).is_err()); } + +#[test] +fn the_read_only_base_path_matches_the_one_that_creates_and_creates_nothing() { + let t = TempDir::new(); + dir_with_mode(&t.path.join("tmp"), 0o1777); + let shared = t.path.join("tmp"); + let rt = t.path.join("run"); + dir_with_mode(&rt, 0o700); + assert_eq!(private_base_path_in(Some(&rt), &shared, uid()), rt); + // A group-writable candidate, a missing one and none at all fall back to `oab-`. + let loose = t.path.join("loose"); + dir_with_mode(&loose, 0o770); + let want = shared.join(format!("oab-{}", uid())); + assert_eq!(private_base_path_in(Some(&loose), &shared, uid()), want); + assert_eq!( + private_base_path_in(Some(&t.path.join("no")), &shared, uid()), + want + ); + assert_eq!(private_base_path_in(None, &shared, uid()), want); + assert_eq!( + std::fs::read_dir(&shared).unwrap().count(), + 0, + "nothing created" + ); + // Same answer as the creating version, for each case. + assert_eq!(base_of(&t, Some(&rt)).unwrap(), rt); + assert_eq!(base_of(&t, Some(&loose)).unwrap(), want); +} diff --git a/scripts/check-release-record.sh b/scripts/check-release-record.sh new file mode 100755 index 0000000..4d5f174 --- /dev/null +++ b/scripts/check-release-record.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +# The per-release manual record gate (docs/releasing.md "Linux release gates", ADR D16). +# +# check-release-record.sh VERSION [--report-only] [--dir DIR] +# +# VERSION is the release version without the leading v. The record is +# docs/release-records/linux-VERSION.md, committed before the tag. It passes only when: +# - the file exists; +# - no table row still holds the placeholder PENDING; +# - the V2 and D7 rows exist and neither still says "open, owner decision pending"; +# - each of V1 to V13 has exactly one row of exactly four cells (no "|" inside a cell); +# - V1, V2 and V7 have a Result of "pass" whatever their Blocking cell says; any other row whose +# Blocking cell starts with "yes" has "pass", or "n/a, reason". A "fail", an empty cell or any other +# text blocks the release; +# - each of M1 to M10 and each of the six smoke cells has exactly one well-formed row, and its Result, +# lower-cased, is "pass". ADR D16 makes the manual full run and the matrix a per-release +# requirement, so no "n/a" is accepted. A deleted row, "fail", "Fail", "not run", "n/a" or an empty cell blocks. +# The script never writes, never fills a cell and never treats V2 or D7 as resolved: those two rows +# stay red until a person records the owner's decision in the row (and in the ADR). Only lines that +# start with `|` (table rows) are read, so the instructions around the tables may quote the words. +# --report-only prints the same findings and exits 0 (a workflow_dispatch run without a tag). +set -u + +version=${1:-} +[ -n "$version" ] || { echo "usage: check-release-record.sh VERSION [--report-only] [--dir DIR]" >&2; exit 64; } +shift +report_only=0 +dir="$(dirname "$0")/../docs/release-records" +while [ $# -gt 0 ]; do + case $1 in + --report-only) report_only=1; shift ;; + --dir) dir=${2:-}; shift 2 ;; + *) echo "unknown argument: $1" >&2; exit 64 ;; + esac +done +case "$version" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) echo "VERSION must be MAJOR.MINOR.PATCH, without a leading v" >&2; exit 64 ;; +esac + +file="$dir/linux-$version.md" +problems=0 +say() { echo "release record: $*"; problems=$((problems + 1)); } + +if [ ! -f "$file" ]; then + say "missing: docs/release-records/linux-$version.md (copy docs/release-records/TEMPLATE.md, run the manual rows, commit it before the tag)" +else + rows=$(grep '^|' "$file" || true) + n=$(printf '%s\n' "$rows" | grep -c 'PENDING' || true) + [ "$n" -eq 0 ] || say "$n table row(s) still contain PENDING" + for id in V2 D7; do + row=$(printf '%s\n' "$rows" | grep "^| $id " || true) + if [ -z "$row" ]; then + say "the $id row is missing; it may not be removed until the owner's decision is recorded in the ADR" + elif printf '%s' "$row" | grep -q 'open, owner decision pending'; then + say "$id is open, owner decision pending: a release stays blocked" + fi + done + # Gate rows: | Gate | Result | Evidence | Blocking |. Exactly one row per gate V1..V13 must exist and + # have exactly four cells (a "|" inside a cell makes five and is refused, so a row cannot hide from the + # check). V1, V2 and V7 take only "pass", whatever their Blocking cell says. Another row whose Blocking + # cell starts with "yes" takes "pass", or "n/a" with a reason. + bad=$(printf '%s\n' "$rows" | awk -F'|' ' + function trim(x) { gsub(/^[ \t]+|[ \t]+$/, "", x); return x } + $2 ~ /^ *V[0-9]+ / { + id = trim($2); sub(/ .*/, "", id) + seen[id]++ + if (NF != 6) { print id " (malformed row: " NF - 2 " cells, need 4; no \"|\" inside a cell)"; next } + r = trim($3) + strict = (id == "V1" || id == "V2" || id == "V7") + if (strict) { if (r != "pass") print id " (result: " r ")" } + else if (trim($5) ~ /^yes/ && r != "pass" && r !~ /^n\/a[ ]*[,:;-][ ]*[^ ]/) print id " (result: " r ")" + } + END { + for (i = 1; i <= 13; i++) { + k = "V" i + if (seen[k] == 0) print k " (row missing)" + else if (seen[k] > 1) print k " (" seen[k] " rows, need exactly one)" + } + }') + # Manual (M1..M10, five cells) and smoke-cell (six named cells, three cells) rows: each must exist + # exactly once, and its Result, lower-cased, must be "pass" (ADR D16: required every release, no "n/a"). + # A deleted row, an empty result, "n/a", "Fail", "FAIL", "red" or "not run" all block. + badm=$(printf '%s\n' "$rows" | awk -F'|' ' + function trim(x) { gsub(/^[ \t]+|[ \t]+$/, "", x); return x } + function okres(r) { r = tolower(r); return (r == "pass") } + BEGIN { + split("Ubuntu 22.04 amd64|Ubuntu 22.04 arm64|Ubuntu 24.04 amd64|Ubuntu 24.04 arm64|Debian 12 container amd64|Debian 12 container arm64", cells, "|") + for (i in cells) want[cells[i]] = 1 + } + { + id = trim($2) + if (id ~ /^M[0-9]+ /) { + sub(/ .*/, "", id); kind = "m"; need = 7 + } else if (id in want) { + kind = "c"; need = 5 + } else next + seen[id]++ + if (NF != need) { print id " (malformed row: " NF - 2 " cells, need " need - 2 "; no \"|\" inside a cell)"; next } + r = trim($3) + if (!okres(r)) print id " (result: " r ")" + } + END { + for (i = 1; i <= 10; i++) { k = "M" i; if (seen[k] == 0) print k " (row missing)"; else if (seen[k] > 1) print k " (" seen[k] " rows, need exactly one)" } + for (c in want) { if (seen[c] == 0) print c " (row missing)"; else if (seen[c] > 1) print c " (" seen[c] " rows, need exactly one)" } + }') + if [ -n "$badm" ]; then + while IFS= read -r line; do + say "manual or smoke-cell row not acceptable: $line; M1 to M10 and the six smoke cells need one row each, each with pass (no n/a: ADR D16 requires them every release)" + done < (the production Supervisor, Systemd containment, tools/list, navigate, +# snapshot), `browser status --json` while the tree runs, `kill -9` of the harness, and a survivor +# check on the install directory. Nothing outside the temporary HOME and that unit is touched; the +# unit is stopped on exit. +# +# Output: one `GATE pass|fail|info ...` line per gate, so the per-release record can quote them. +# The exit status is the first failing gate's code (below); every gate still runs and prints. +# 12 install (the pinned source, install and the headless health check) +# 13 no systemd user manager (a real cell FAILS without one, section 3.3) +# 14 the harness never became ready +# 20 V2 a TCP or UDP listener, a Unix listener outside the private TMPDIR, a TMPDIR that is not +# 0700 or not the daemon's, or listeners that cannot be read +# 24 V4 containment is not `systemd` or `systemd+mount` +# 30 R1.3 something from the install directory survived `kill -9` of the harness +# 64 usage +# V3 (Chromium exit timing after SIGKILL) and V9, V11 are informational and never fail the cell. +# +# V2 (decided): no TCP or UDP listener, and any Unix listener must be inside the child's private +# per-run 0700 TMPDIR owned by the daemon's uid (the Playwright browser socket and Chromium's +# SingletonSocket). The gate has no other allow-list. + +set -u + +# ---------------------------------------------------------------- pure helpers (tested) + +# json_field JSON KEY: the string value of a top-level key of the flat object `browser status --json` +# prints (fixed keys, values from a fixed vocabulary, no escapes). +json_field() { + printf '%s' "$1" | sed -n "s/.*\"$2\":\"\\([^\"]*\\)\".*/\\1/p" +} + +# list_field LISTENERS KEY: the value of `KEY=` in the `listeners` word, or empty. +list_field() { + printf '%s' "$1" | tr ' ' '\n' | sed -n "s/^$2=//p" | head -n 1 +} + +# gate_v2 STATUS_JSON: the decided V2 rule (R1.1). Passes when the managed tree holds no listener at +# all, or when it holds no TCP or UDP listener and every Unix listener is inside the child's private +# per-run TMPDIR, which `status` has checked to be a real directory of the daemon's uid with mode +# exactly 0700. The word is `tcp=N udp=N unix=N unix_outside=N tmpdir=S result=pass|fail`. This +# gate trusts no `result=` alone: it recomputes the rule from the counts, and a missing or unknown +# field fails. There is no path allow-list here; "inside" is decided by `status`. +gate_v2() { + local l tcp udp unix out tmp res + l=$(json_field "$1" listeners) + if [ "$l" = none ]; then + echo "GATE V2 pass listeners=none" + return 0 + fi + tcp=$(list_field "$l" tcp) + udp=$(list_field "$l" udp) + unix=$(list_field "$l" unix) + out=$(list_field "$l" unix_outside) + tmp=$(list_field "$l" tmpdir) + # tmpdir is judged only when a Unix listener exists (unix>0); with none, a bad TMPDIR cannot hold a + # socket, and the real cell separately requires NAVIGATE ok and SNAPSHOT_HAS_TEXT true. + res=$(list_field "$l" result) + local f + for f in "$tcp" "$udp" "$unix" "$out"; do + case "$f" in + '' | *[!0-9]*) echo "GATE V2 fail listeners=${l:-missing}"; return 1 ;; + esac + done + if [ "$tcp" = 0 ] && [ "$udp" = 0 ] && [ "$out" = 0 ] \ + && [ "$res" = pass ] && { [ "$unix" = 0 ] || [ "$tmp" = ok ]; }; then + echo "GATE V2 pass listeners=$l" + return 0 + fi + echo "GATE V2 fail listeners=$l" + return 1 +} + +# gate_v4 CONTAINMENT: the self-test must have reached a systemd mode (BindsTo fires, V4). +gate_v4() { + case "$1" in + systemd | systemd+mount) + echo "GATE V4 pass containment=$1" + return 0 + ;; + esac + echo "GATE V4 fail containment=${1:-missing}" + return 1 +} + +# survivors_under DIR: the pids of this user's processes whose executable is below DIR. +survivors_under() { + local dir=$1 p exe + for p in /proc/[0-9]*; do + exe=$(readlink "$p/exe" 2>/dev/null) || continue + case "$exe" in + "$dir"/*) echo "${p#/proc/}" ;; + esac + done +} + +# ---------------------------------------------------------------- the cell + +# Milliseconds since the epoch (V3 is a measurement, a whole second is too coarse). +now_ms() { + local t=${EPOCHREALTIME:-} + if [ -n "$t" ]; then + echo $((${t//[.,]/} / 1000)) + else + echo $(($(date +%s) * 1000)) + fi +} + +die() { + echo "release-smoke: $*" >&2 + exit "${2:-64}" +} + +first_fail=0 +note_fail() { [ "$first_fail" -ne 0 ] || first_fail=$1; } + +cleanup() { + if [ -n "${UNIT:-}" ]; then + systemctl --user stop "$UNIT.service" >/dev/null 2>&1 || true + systemctl --user reset-failed "$UNIT.service" >/dev/null 2>&1 || true + fi +} + +# Runs on exit: the transient unit, then the temporary HOME (about 900 MB with the browser) unless +# OAB_SMOKE_KEEP=1 asks to keep it for a look. +cleanup_all() { + cleanup + if [ -n "${TMP:-}" ] && [ "${OAB_SMOKE_KEEP:-0}" != 1 ]; then + rm -rf "$TMP" + fi +} + +# The common part: plan, preflight, install, status. Sets BASE and INSTALL_DIR. +prepare() { + local bin=$1 + TMP=$(mktemp -d "${TMPDIR:-/tmp}/oab-l5-smoke.XXXXXX") || die "mktemp failed" 64 + trap cleanup_all EXIT + export HOME="$TMP/home" + export XDG_DATA_HOME="$HOME/.local/share" + mkdir -p "$HOME" "$XDG_DATA_HOME" + BASE=$XDG_DATA_HOME + INSTALL_DIR=$BASE/oab-computer/playwright + + echo "== browser plan" + "$bin" browser plan || true + echo "== browser preflight" + "$bin" browser preflight + pre=$? + echo "== browser install (downloads the pinned Node.js and Chromium, runs the headless health check)" + if "$bin" browser install; then + echo "GATE V1 pass pinned source downloaded and installed" + echo "GATE health pass headless health check" + else + echo "GATE health fail install or headless health check failed" + note_fail 12 + return 1 + fi + # V9: the preflight's library list against what the health check then did. Informational: the + # health check is the final test (docs/requirements/linux-browser-tier.md, V9). + echo "GATE V9 info preflight_exit=$pre health=ok" + return 0 +} + +real_cell() { + local bin=$1 harness=$2 state log out status contain + prepare "$bin" || return "$first_fail" + + state=$(XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" systemctl --user is-system-running 2>/dev/null || true) + case "$state" in + running | degraded) echo "user manager: $state" ;; + *) + echo "GATE manager fail systemctl --user is-system-running=${state:-none}" + return 13 + ;; + esac + + UNIT="oab-l5-test-harness-$$" + log=$TMP/e2e.log + : >"$log" + echo "== harness as the main process of $UNIT.service" + systemd-run --user --quiet --collect --unit "$UNIT" \ + -E HOME="$HOME" -E XDG_DATA_HOME="$XDG_DATA_HOME" \ + -E OAB_L2_E2E=1 -E OAB_L2_E2E_BASE="$BASE" -E OAB_L2_E2E_OUT="$log" \ + "$harness" --ignored --test-threads=1 e2e_daemon_harness || die "systemd-run failed" 14 + for _ in $(seq 1 240); do + grep -q '^READY \|^TOOLS_LIST_FAILED ' "$log" && break + sleep 1 + done + grep -q '^READY ' "$log" || { + echo "GATE harness fail never ready" + sed 's/^/e2e.log: /' "$log" + return 14 + } + sed 's/^/e2e.log: /' "$log" + # V2 is only measured with a browser running: the harness prints READY whatever the navigation did. + if ! { grep -q '^NAVIGATE ok$' "$log" && grep -q '^SNAPSHOT_HAS_TEXT true$' "$log"; }; then + echo "GATE harness fail no browser page was loaded (need NAVIGATE ok and SNAPSHOT_HAS_TEXT true)" + return 14 + fi + + contain=$(sed -n 's/^CONTAINMENT //p' "$log" | head -n 1) + gate_v4 "$contain" || note_fail 24 + + # The listener self-check on the live tree: the status command reads it from /proc. + status=$("$bin" browser status --json) + echo "status: $status" + gate_v2 "$status" || note_fail 20 + case "$(json_field "$status" listeners)" in + none | "") + echo "GATE V2 fail no listener seen in the real cell: the browser tree was not measured" + note_fail 20 + ;; + esac + # V11: the mount tier's answer. `--retry` runs the containment self-test in this process, which + # uses the production unit names, so only the CI job sets this (a throwaway runner). + if [ "${OAB_SMOKE_STATUS_RETRY:-0}" = 1 ]; then + out=$("$bin" browser status --json --retry) + echo "GATE V11 info hardening_mount=$(json_field "$out" hardening_mount)" + else + echo "GATE V11 info hardening_mount=$(json_field "$status" hardening_mount) (no --retry in this run)" + fi + + # R1.3 and V3: kill -9 the harness, then wait for the tree to go. + echo "== kill -9 the harness main process" + local t0 t1 left=1 + t0=$(now_ms) + systemctl --user kill --kill-who=main --signal=KILL "$UNIT.service" || true + for _ in $(seq 1 300); do + if [ -z "$(survivors_under "$INSTALL_DIR")" ]; then + left=0 + break + fi + sleep 0.2 + done + t1=$(now_ms) + if [ "$left" -eq 0 ]; then + echo "GATE survivors pass nothing from the install directory remains" + else + echo "GATE survivors fail still running: $(survivors_under "$INSTALL_DIR" | tr '\n' ' ')" + note_fail 30 + fi + echo "GATE V3 info ms_until_tree_gone=$((t1 - t0)) (informational; the stop guarantee does not depend on it)" + cleanup + UNIT= + left=$(systemctl --user list-units 'oab-l5-test-*' --all --no-legend 2>/dev/null | wc -l) + echo "units left with the oab-l5-test- prefix: $left" + return "$first_fail" +} + +container_cell() { + local bin=$1 status + prepare "$bin" || return "$first_fail" + status=$("$bin" browser status --json) + echo "status: $status" + echo "GATE V2 info not measured in a container job (no user manager, no running tree); the real cells measure it" + echo "GATE V4 info not measured in a container job; the real cells measure it" + return "$first_fail" +} + +# As root inside the Debian 12 container: the packages a fresh image lacks, a non-root user (euid 0 +# is not realistic and `browser install` does not refuse it), then the cell as that user. +in_container() { + local bin=$1 self line + self=$(readlink -f "$0") + [ "$(id -u)" -eq 0 ] || die "--in-container runs as root inside the container" 64 + if ! { apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates util-linux >/dev/null; }; then + die "apt-get failed" 12 + fi + useradd -m smoke + # The root actions the host-side preflight itself prints (missing libraries). The container is + # throwaway, so running them here is the same as a person following the hint. + runuser -u smoke -- env HOME=/home/smoke "$bin" browser preflight --root-actions >/tmp/root-actions.tsv || true + while IFS= read -r line; do + [ -n "$line" ] || continue + echo "root action: ${line%%$'\t'*}" + act=${line%%$'\t'*} + act=${act#sudo } # already root in the throwaway container, which has no sudo + sh -c "$act" || echo "(that action failed; the health check decides)" + done /dev # ------------------------------------------------------------------ repo-wide: old names only where allowed # Allowed leftovers in code, scripts and CI: the copy-source token path (and the test fixtures that -# seed it), issue links, and the warn-only legacy detection (the two installers and their tests, including test-install-linux.sh). +# seed it), issue links, and the warn-only legacy detection (the two installers and their tests, including test-install-linux.sh, +# and the Linux CLI's legacy listing in `browser status`: legacy.rs, its tests, and the fixtures that seed a legacy unit). LEFT=$(cd "$ROOT" && grep -rnE --exclude-dir=target --exclude-dir=.build 'oab-instance-mcp|instance-mcp|INSTANCE_MCP|oab-pw-mcp|dev\.openab\.instance' \ Sources Tests poc scripts .github images Package.swift 2>/dev/null \ | grep -vE '^scripts/test-(legacy-agent|name-consistency|install-linux)\.sh:' \ + | grep -vE '^poc/reverse-attach-linux/src/legacy(_tests)?\.rs:' \ + | grep -vE '^poc/reverse-attach-linux/src/(probe|install)_tests\.rs:[0-9]+:.*oab-pw-mcp\.service' \ | grep -vE '\.config/oab-instance-mcp/token|instance-mcp(#[0-9]|/issues/)' \ | grep -vE '^scripts/test-packaging\.sh:[0-9]+:mkdir -p .*oab-instance-mcp' \ | grep -vE '^Tests/InstanceMCPCoreTests/FirstRunSetupTests\.swift:[0-9]+:.*contains\("instance-mcp"\)' \ diff --git a/scripts/test-pw-mcp-deprecated.sh b/scripts/test-pw-mcp-deprecated.sh new file mode 100755 index 0000000..19fb149 --- /dev/null +++ b/scripts/test-pw-mcp-deprecated.sh @@ -0,0 +1,62 @@ +#!/bin/bash +# D14, R7.1: poc/reverse-attach-linux/pw-mcp.sh is deprecated. It must say so once on stderr when it +# starts and still launch Playwright MCP with the same arguments (a binary rollback restores a +# working script). A stub stands in for playwright-mcp: nothing real is started and HOME is a temp +# directory. Usage: scripts/test-pw-mcp-deprecated.sh +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +SCRIPT="$ROOT/poc/reverse-attach-linux/pw-mcp.sh" +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT + +fail() { echo "FAIL: $*" >&2; exit 1; } + +# The header says it is deprecated and where to read more. +head -n 8 "$SCRIPT" | grep -q '^# DEPRECATED' || fail "no DEPRECATED header in the first lines of pw-mcp.sh" +head -n 8 "$SCRIPT" | grep -q 'docs/linux-cutover.md' || fail "the header does not point at docs/linux-cutover.md" + +mkdir -p "$T/home/.local/oab-computer/pw-mcp/node_modules/.bin" +STUB="$T/home/.local/oab-computer/pw-mcp/node_modules/.bin/playwright-mcp" +cat >"$STUB" <<'STUBEOF' +#!/bin/bash +echo "STUB-ARGS $*" +exit "${STUB_EXIT:-0}" +STUBEOF +chmod +x "$STUB" + +rc=0 +run() { # run [VAR=value...]: stdout to $T/out, stderr to $T/err, status in $rc + rc=0 + env -i HOME="$T/home" PATH="/usr/bin:/bin" PW_CHROMIUM=/opt/test/chromium "$@" \ + bash "$SCRIPT" >"$T/out" 2>"$T/err" || rc=$? +} + +run +[ "$rc" = 0 ] || fail "exit status $rc, want 0 (the stub's)" +[ "$(grep -c 'DEPRECATED' "$T/err")" = 1 ] || fail "stderr must carry the deprecation line exactly once: $(cat "$T/err")" +grep -q 'docs/linux-cutover.md' "$T/err" || fail "the warning does not point at docs/linux-cutover.md" +grep -q "oab-computer browser install" "$T/err" || fail "the warning does not name the replacement" +grep -q '127.0.0.1:8794' "$T/err" || fail "the warning does not name the listener" +[ "$(wc -l <"$T/err" | tr -d ' ')" = 1 ] || fail "the warning is one line" +# No URL or token in the notice. +if grep -Eq 'https?://|token|Bearer' "$T/err"; then fail "the warning carries a URL or token"; fi +# The warning stays off stdout. +if grep -q 'DEPRECATED' "$T/out"; then fail "the warning leaked to stdout"; fi + +# The launch is unchanged. +want="STUB-ARGS --host 127.0.0.1 --port 8794 --allowed-hosts 127.0.0.1,localhost,127.0.0.1:8794,localhost:8794 --browser chromium --executable-path /opt/test/chromium --user-data-dir $T/home/.local/oab-computer/pw-profile --output-dir $T/home/.local/oab-computer/pw-output --idle-timeout 1800000 --shared-browser-context --caps vision,pdf" +[ "$(cat "$T/out")" = "$want" ] || fail "launch arguments changed: +got: $(cat "$T/out") +want: $want" + +# The stub's exit status passes through exec, and the warning is printed once per start. +run STUB_EXIT=7 +[ "$rc" = 7 ] || fail "exit status $rc, want 7" +[ "$(grep -c 'DEPRECATED' "$T/err")" = 1 ] || fail "the warning is printed once per start" + +# A config file, when present, is still passed (the optional argument is unchanged). +echo '{}' >"$T/home/.local/oab-computer/pw-config.json" +run +grep -q -- "--config $T/home/.local/oab-computer/pw-config.json" "$T/out" || fail "--config no longer passed" + +echo "ok: pw-mcp.sh is marked deprecated, warns once on stderr and launches unchanged" diff --git a/scripts/test-release-smoke-linux.sh b/scripts/test-release-smoke-linux.sh new file mode 100755 index 0000000..7fede0e --- /dev/null +++ b/scripts/test-release-smoke-linux.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +# Pure tests for scripts/release-smoke-linux.sh and scripts/check-release-record.sh. No network, no +# systemd, no browser: fixture JSON, a temporary directory and a copy of `sleep`. +set -u +here=$(cd "$(dirname "$0")" && pwd) +# shellcheck source=/dev/null +. "$here/release-smoke-linux.sh" + +pass=0 +fail=0 +ok() { echo "PASS $1"; pass=$((pass + 1)); } +bad() { echo "FAIL $1"; fail=$((fail + 1)); } +expect() { # name expected-exit actual-exit + if [ "$2" -eq "$3" ]; then ok "$1"; else bad "$1 (wanted exit $2, got $3)"; fi +} +status_json() { # listeners + printf '{"state":"installed","platform":"linux-x64","containment":"not_checked","listeners":"%s","refusal":"none","hardening_mount":"verified"}' "$1" +} + +# V2 (decided): no TCP or UDP listener, and every Unix listener inside the verified private TMPDIR. +P='tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass' +out=$(gate_v2 "$(status_json none)"); expect "V2 none passes" 0 $? +case $out in "GATE V2 pass"*) ok "V2 pass line" ;; *) bad "V2 pass line: $out" ;; esac +out=$(gate_v2 "$(status_json "$P")"); expect "V2 two private unix sockets pass" 0 $? +case $out in *"unix=2"*"result=pass"*) ok "V2 pass line names the listeners" ;; *) bad "V2 pass line: $out" ;; esac +out=$(gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=1 tmpdir=ok result=fail')"); expect "V2 a unix listener outside the private dir fails" 1 $? +case $out in "GATE V2 fail"*) ok "V2 fail line" ;; *) bad "V2 fail line: $out" ;; esac +gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=mode result=fail')" >/dev/null; expect "V2 TMPDIR not 0700 fails" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=owner result=fail')" >/dev/null; expect "V2 TMPDIR of another uid fails" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=mode result=pass')" >/dev/null; expect "V2 recomputed: tmpdir=mode fails even if result=pass" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=missing result=pass')" >/dev/null; expect "V2 recomputed: tmpdir=missing fails" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=1 tmpdir=ok result=pass')" >/dev/null; expect "V2 recomputed: unix_outside=1 fails even if result=pass" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=fail')" >/dev/null; expect "V2 result=fail fails" 1 $? +gate_v2 "$(status_json 'tcp=1 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass')" >/dev/null; expect "V2 tcp=1 fails even with a private dir" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=1 unix=0 unix_outside=0 tmpdir=ok result=pass')" >/dev/null; expect "V2 udp=1 fails" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=2')" >/dev/null; expect "V2 the old word without the verdict fails" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=x tmpdir=ok result=pass')" >/dev/null; expect "V2 a non-number fails" 1 $? +gate_v2 "$(status_json unknown)" >/dev/null; expect "V2 unknown fails" 1 $? +gate_v2 "$(status_json not_running)" >/dev/null; expect "V2 not_running fails (nothing was measured)" 1 $? +gate_v2 '{"state":"installed"}' >/dev/null; expect "V2 missing field fails" 1 $? +gate_v2 '' >/dev/null; expect "V2 empty output fails" 1 $? + +# V4: the two systemd modes pass; anything else fails. +gate_v4 systemd >/dev/null; expect "V4 systemd" 0 $? +gate_v4 systemd+mount >/dev/null; expect "V4 systemd+mount" 0 $? +gate_v4 unverified >/dev/null; expect "V4 unverified fails" 1 $? +gate_v4 not_checked >/dev/null; expect "V4 not_checked fails" 1 $? +gate_v4 '' >/dev/null; expect "V4 empty fails" 1 $? + +if [ "$(json_field "$(status_json 'tcp=0 udp=0 unix=2')" listeners)" = "tcp=0 udp=0 unix=2" ]; then ok "json_field keeps spaces"; else bad "json_field"; fi + +# Survivor check: a process whose executable is below the directory is found, then not once gone. +T=$(mktemp -d "${TMPDIR:-/tmp}/oab-l5-test-smoke.XXXXXX") +trap 'rm -rf "$T"' EXIT +mkdir -p "$T/install" "$T/other" +if [ ! -e /proc/self/exe ]; then + echo "SKIP survivor check (no /proc: Linux only; CI runs it)" +else +cp "$(command -v sleep)" "$T/install/sleep" +cp "$(command -v sleep)" "$T/other/sleep" +"$T/install/sleep" 30 & inside=$! +"$T/other/sleep" 30 & outside=$! +sleep 0.3 +found=$(survivors_under "$T/install" | tr '\n' ' ') +case " $found" in *" $inside "*) ok "survivor below the directory is found" ;; *) bad "survivor not found: '$found'" ;; esac +case " $found" in *" $outside "*) bad "process outside the directory was reported" ;; *) ok "process outside the directory is not reported" ;; esac +kill "$inside" "$outside" 2>/dev/null +wait "$inside" "$outside" 2>/dev/null +if [ -z "$(survivors_under "$T/install")" ]; then ok "no survivor after the kill"; else bad "survivor after the kill"; fi +fi + +# The record gate. A filled record copies the template's rows. +R="$T/records" +mkdir -p "$R" +C="$here/check-release-record.sh" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: missing file fails" 1 $? +"$C" 9.9.9 --dir "$R" --report-only >/dev/null 2>&1; expect "record: missing file, --report-only exits 0" 0 $? +"$C" v9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a leading v is a usage error" 64 $? +cp "$here/../docs/release-records/TEMPLATE.md" "$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: the untouched template fails" 1 $? +fill="$T/filled.md" +sed 's/PENDING/done/g;s/^\(| V[0-9]* [^|]*\)| done |\(.*| yes[^|]*|\)$/\1| pass |\2/;s/^\(| M[0-9]* [^|]*\)| done |/\1| pass |/;s/^\(| Ubuntu [0-9.]* [a-z0-9]* \)| done |/\1| pass |/;s/^\(| Debian 12 container [a-z0-9]* \)| done |/\1| pass |/' "$R/linux-9.9.9.md" >"$fill" +cp "$fill" "$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: all rows filled, V2 and D7 decided, passes" 0 $? +# A row that reopens a decision blocks the release, and the gate names it. +sed 's/^| \(V2 .*\) | pass | /| \1 | open, owner decision pending | /;s/^| \(D7 .*\) | decided, glob kept | /| \1 | open, owner decision pending | /' "$fill" >"$R/linux-9.9.9.md" +out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: V2 and D7 reopened blocks" 1 $? +case $out in *"V2 is open"*"D7 is open"*) ok "record: both open rows are named" ;; *) bad "record: open rows not named: $out" ;; esac +sed 's/^| \(D7 .*\) | decided, glob kept | /| \1 | open, owner decision pending | /' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: D7 reopened alone blocks" 1 $? +grep -v '^| D7 ' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a removed D7 row fails" 1 $? +grep -v '^| V2 ' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a removed V2 row fails" 1 $? +sed 's/^| M3 \(.*\) | pass | done | done | done |$/| M3 \1 | PENDING | done | done | done |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: one PENDING cell fails" 1 $? +sed 's/^| \(V2 .*\) | pass | /| \1 | PENDING | /' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a V2 row without its measurement (PENDING) fails" 1 $? +# A blocking gate (V1, V2, V7) needs exactly pass; n/a (with or without a reason), fail or free text blocks. +for bad_result in fail 'n/a' 'done' 'pass?' ''; do + sed "s#^| \\(V7 [^|]*\\)| pass |#| \\1| $bad_result |#" "$fill" >"$R/linux-9.9.9.md" + out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: V7 result '$bad_result' blocks" 1 $? + case $out in *"gate row not acceptable: V7"*) ok "record: V7 '$bad_result' is named" ;; *) bad "record: V7 '$bad_result' not named: $out" ;; esac +done +sed 's/^| \(V7 [^|]*\)| pass |/| \1| n\/a, no sign-in on this release |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: V7 n/a with a reason blocks" 1 $? +sed 's/^| \(V1 [^|]*\)| pass |/| \1| n\/a, no source yet |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: V1 n/a with a reason blocks" 1 $? +sed 's/^| \(V1 [^|]*\)| pass |/| \1| fail |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: V1 fail blocks" 1 $? +# A strict gate cannot hide: a deleted row, a "|" inside a cell, a Blocking cell edited to "no". +for g in V1 V2 V7 V13; do + grep -v "^| $g " "$fill" >"$R/linux-9.9.9.md" + out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: a removed $g row fails" 1 $? + case $out in *"$g (row missing)"*) ok "record: removed $g row is named" ;; *) bad "record: removed $g row not named: $out" ;; esac +done +sed 's/^| \(V1 [^|]*\)| pass | \([^|]*\)|/| \1| fail | ss -lxp | grep chrome |/' "$fill" >"$R/linux-9.9.9.md" +out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: V1 fail with a pipe in Evidence fails" 1 $? +case $out in *"V1 (malformed row"*) ok "record: the malformed V1 row is named" ;; *) bad "record: malformed V1 not named: $out" ;; esac +sed 's/^| \(V7 .*\)| yes[^|]* |$/| \1| no |/;s/^| \(V7 [^|]*\)| pass |/| \1| fail |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: V7 fail with Blocking edited to no still fails" 1 $? +{ cat "$fill"; grep '^| V7 ' "$fill"; } >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a duplicated V7 row fails" 1 $? +# M rows and smoke-cell rows: each exactly once, Result (any case) pass only (ADR D16, no n/a). +sed 's/^| \(M3 [^|]*\)| pass |/| \1| fail |/' "$fill" >"$R/linux-9.9.9.md" +out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: an M3 fail blocks" 1 $? +case $out in *"manual or smoke-cell row not acceptable: M3"*) ok "record: M3 fail is named" ;; *) bad "record: M3 not named: $out" ;; esac +sed 's/^| \(Ubuntu 22.04 arm64\) | pass |/| \1 | fail |/' "$fill" >"$R/linux-9.9.9.md" +out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: a smoke-cell fail blocks" 1 $? +case $out in *"not acceptable: Ubuntu 22.04 arm64"*) ok "record: cell fail is named" ;; *) bad "record: cell not named: $out" ;; esac +for bad_result in Fail FAIL red 'not run' 'done' ''; do + sed "s#^| \\(M5 [^|]*\\)| pass |#| \\1| $bad_result |#" "$fill" >"$R/linux-9.9.9.md" + out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: M5 result '$bad_result' blocks" 1 $? + sed "s#^| \\(Debian 12 container arm64\\) | pass |#| \\1 | $bad_result |#" "$fill" >"$R/linux-9.9.9.md" + out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: a cell result '$bad_result' blocks" 1 $? +done +sed 's/^| \(M5 [^|]*\)| pass |/| \1| PASS |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: M5 PASS (any case) is accepted" 0 $? +sed 's/^| \(M4 [^|]*\)| pass |/| \1| n\/a, no Raspberry Pi in this cycle |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: M4 n/a with a reason blocks (ADR D16)" 1 $? +sed 's/^| \(M4 [^|]*\)| pass |/| \1| n\/a |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: M4 n/a without a reason blocks" 1 $? +sed 's/^| \(Ubuntu 24.04 arm64\) | pass |/| \1 | n\/a, no runner |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a smoke cell n/a with a reason blocks" 1 $? +# A deleted M row or smoke-cell row cannot hide (no PENDING left to find). +for g in 'M1 ' 'M10 ' 'Ubuntu 22.04 amd64 ' 'Debian 12 container arm64 '; do + grep -v "^| $g" "$fill" >"$R/linux-9.9.9.md" + out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: a removed '$g' row fails" 1 $? + case $out in *"(row missing)"*) ok "record: removed '$g' row is named" ;; *) bad "record: removed '$g' not named: $out" ;; esac +done +{ cat "$fill"; grep '^| M2 ' "$fill"; } >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a duplicated M2 row fails" 1 $? +# A non-blocking row may be anything but PENDING. +sed 's/^| \(V3 [^|]*\)| done |/| \1| fail |/' "$fill" >"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a non-blocking V3 fail does not block" 0 $? +# The instruction text outside the tables may quote the words without tripping the gate. +cp "$fill" "$R/linux-9.9.9.md" +printf '\nThe words open, owner decision pending and PENDING in prose are not a table row.\n' >>"$R/linux-9.9.9.md" +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: prose outside the tables is ignored" 0 $? + +echo "pass=$pass fail=$fail" +[ "$fail" -eq 0 ] From f6b8055dda3c15a4b19706da936d3fd714883488 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:42:08 -0500 Subject: [PATCH 02/18] fix: release record and smoke gates require a pass (findings 1, 4, 5) Finding 1: scripts/check-release-record.sh now requires "pass" (lower-cased) on every V1 to V13, M1 to M10 and smoke-cell row. n/a, fail, empty, PENDING, a deleted, duplicated or malformed row all block. The Blocking column no longer relaxes the rule. docs/release-records/TEMPLATE.md states the same. Finding 5: gate_real_cell LOG STATUS_JSON. V2 in a real cell passes only with NAVIGATE ok and SNAPSHOT_HAS_TEXT true in the harness log and a measured, passing tree; listeners=none alone fails. gate_v2 also requires tmpdir=ok whenever the word has counts. Finding 4: root_command strips a leading "sudo " from a root action inside the Debian 12 container, which has no sudo. The container path and the docker run line name no sudo; a test checks both. Tests: scripts/test-release-smoke-linux.sh adds the bypass matrix (V1 to V13, M1 to M10, six cells, each deleted/duplicated/malformed/failed/n/a, plus the V2 and D7 rows) and each case edits a copy of a valid record. Commands and results: - bash scripts/test-release-smoke-linux.sh on a Debian 13 arm64 node: pass=270 fail=0 (220 reject cases, 2 accept cases, the rest V2, V4, real-cell and root_command cases) - Same file on the pre-fix reference scripts: 40 record cases and the real-cell and root_command cases fail (shows the tests catch the findings) - shellcheck: not installed on that node; run in CI (linux-installer job) - bash -n on each changed shell script (laptop): ok --- docs/release-records/TEMPLATE.md | 14 ++- scripts/check-release-record.sh | 16 +-- scripts/release-smoke-linux.sh | 48 ++++++-- scripts/test-release-smoke-linux.sh | 179 +++++++++++++++------------- 4 files changed, 146 insertions(+), 111 deletions(-) diff --git a/docs/release-records/TEMPLATE.md b/docs/release-records/TEMPLATE.md index 847d56f..79ad0cd 100644 --- a/docs/release-records/TEMPLATE.md +++ b/docs/release-records/TEMPLATE.md @@ -4,15 +4,17 @@ Copy this file to `docs/release-records/linux-VERSION.md` (VERSION without the l in against the release candidate, and commit it to `main` **before** the tag. The `record` job of `.github/workflows/linux-release-smoke.yml` runs `scripts/check-release-record.sh VERSION` and fails a release when the file is missing, when any table row still holds the placeholder -`PENDING`, when the `V2` or `D7` row is missing or says `open, owner decision pending`, when any of V1 to V13 lacks exactly one row of four cells, or when any of M1 to M10 or any of the six smoke cells lacks exactly one row or has a result other than `pass` (case does not matter; no `n/a`: ADR D16 requires these every release), or when a -blocking gate row is not `pass` (V1, V2 and V7 take only `pass`; another blocking row may read `n/a` with a reason). +`PENDING`, when the `V2` or `D7` row is missing or says `open, owner decision pending`, or when any +of V1 to V13, M1 to M10 or the six smoke cells lacks exactly one well-formed row (four cells for V, +five for the smoke cells, seven for M) or has a result other than `pass` (case does not matter). +`n/a` is never accepted: ADR D16 requires the manual checks and the matrix every release. Rules for the person filling it in: -- Replace every `PENDING` with a result. Write `n/a` and the reason only on a V3 to V13 row that does not apply (never on a blocking row); - never delete a row. M1 to M10 and the six smoke cells take `pass` only. - A gate row whose Blocking cell says `yes` (V1, V2, V7) must read `pass` and nothing else (no `n/a`); `fail` or - anything else fails the record check. +- Replace every `PENDING` with a result. Every V1 to V13 row, every M row and every smoke-cell row takes + `pass` only. `n/a`, `fail`, an empty cell or any other text fails the record check, and so does a + deleted, duplicated or malformed row. Do not change the cell count of a row (no `|` inside a cell). + A row that cannot be run is a release blocker to report, not a row to mark `n/a`. - Record what you ran and saw. No host names, tailnet names, addresses, logins or tokens: name a host by class ("amd64 desktop", "arm64 desktop", "headless-seat host"). - The `V2` and `D7` rows record decisions the owner made ([the ADR](../adr/linux-browser-tier.md)). diff --git a/scripts/check-release-record.sh b/scripts/check-release-record.sh index 4d5f174..4add87a 100755 --- a/scripts/check-release-record.sh +++ b/scripts/check-release-record.sh @@ -8,10 +8,9 @@ # - the file exists; # - no table row still holds the placeholder PENDING; # - the V2 and D7 rows exist and neither still says "open, owner decision pending"; -# - each of V1 to V13 has exactly one row of exactly four cells (no "|" inside a cell); -# - V1, V2 and V7 have a Result of "pass" whatever their Blocking cell says; any other row whose -# Blocking cell starts with "yes" has "pass", or "n/a, reason". A "fail", an empty cell or any other -# text blocks the release; +# - each of V1 to V13 has exactly one row of exactly four cells (no "|" inside a cell), and its +# Result, lower-cased, is "pass". A "fail", "n/a" (with or without a reason), an empty cell, "PENDING" +# or any other text blocks the release, whatever the Blocking cell says; # - each of M1 to M10 and each of the six smoke cells has exactly one well-formed row, and its Result, # lower-cased, is "pass". ADR D16 makes the manual full run and the matrix a per-release # requirement, so no "n/a" is accepted. A deleted row, "fail", "Fail", "not run", "n/a" or an empty cell blocks. @@ -58,8 +57,7 @@ else done # Gate rows: | Gate | Result | Evidence | Blocking |. Exactly one row per gate V1..V13 must exist and # have exactly four cells (a "|" inside a cell makes five and is refused, so a row cannot hide from the - # check). V1, V2 and V7 take only "pass", whatever their Blocking cell says. Another row whose Blocking - # cell starts with "yes" takes "pass", or "n/a" with a reason. + # check). Every one of them must read "pass" (lower-cased): the Blocking cell does not relax it. bad=$(printf '%s\n' "$rows" | awk -F'|' ' function trim(x) { gsub(/^[ \t]+|[ \t]+$/, "", x); return x } $2 ~ /^ *V[0-9]+ / { @@ -67,9 +65,7 @@ else seen[id]++ if (NF != 6) { print id " (malformed row: " NF - 2 " cells, need 4; no \"|\" inside a cell)"; next } r = trim($3) - strict = (id == "V1" || id == "V2" || id == "V7") - if (strict) { if (r != "pass") print id " (result: " r ")" } - else if (trim($5) ~ /^yes/ && r != "pass" && r !~ /^n\/a[ ]*[,:;-][ ]*[^ ]/) print id " (result: " r ")" + if (tolower(r) != "pass") print id " (result: " r ")" } END { for (i = 1; i <= 13; i++) { @@ -113,7 +109,7 @@ EOF fi if [ -n "$bad" ]; then while IFS= read -r line; do - say "gate row not acceptable: $line; V1 to V13 need one well-formed row each; V1, V2 and V7 need pass; another blocking row needs pass, or n/a with a reason" + say "gate row not acceptable: $line; V1 to V13 need one well-formed row each, each with pass" done <0); with none, a bad TMPDIR cannot hold a - # socket, and the real cell separately requires NAVIGATE ok and SNAPSHOT_HAS_TEXT true. + # The TMPDIR must be the verified private directory whenever the word has counts (decided V2: a + # directory that is not 0700 or not the daemon's fails the gate, even with no Unix listener). res=$(list_field "$l" result) local f for f in "$tcp" "$udp" "$unix" "$out"; do @@ -76,7 +76,7 @@ gate_v2() { esac done if [ "$tcp" = 0 ] && [ "$udp" = 0 ] && [ "$out" = 0 ] \ - && [ "$res" = pass ] && { [ "$unix" = 0 ] || [ "$tmp" = ok ]; }; then + && [ "$res" = pass ] && [ "$tmp" = ok ]; then echo "GATE V2 pass listeners=$l" return 0 fi @@ -84,6 +84,33 @@ gate_v2() { return 1 } +# gate_real_cell LOG STATUS_JSON: V2 in a real cell, the only place it is measured. It passes only when +# the harness log shows a loaded page (NAVIGATE ok and SNAPSHOT_HAS_TEXT true) and the status word +# measured a tree with listeners that pass gate_v2. `listeners=none` alone is not a pass: a tree that +# was never measured reads the same way. +gate_real_cell() { + local log=$1 status=$2 l + if ! { grep -q '^NAVIGATE ok$' "$log" && grep -q '^SNAPSHOT_HAS_TEXT true$' "$log"; }; then + echo "GATE V2 fail no browser page was loaded (need NAVIGATE ok and SNAPSHOT_HAS_TEXT true)" + return 1 + fi + l=$(json_field "$status" listeners) + case "$l" in + none | "") + echo "GATE V2 fail no listener seen in the real cell: the browser tree was not measured" + return 1 + ;; + esac + gate_v2 "$status" +} + +# root_command LINE: a root action as it runs inside the throwaway Debian 12 container. That process +# is already root and the image has no sudo, so a leading `sudo ` is removed; any other line runs +# unchanged. The host-side `sudo sysctl` line is not run through here. +root_command() { + printf '%s\n' "${1#sudo }" +} + # gate_v4 CONTAINMENT: the self-test must have reached a systemd mode (BindsTo fires, V4). gate_v4() { case "$1" in @@ -205,9 +232,11 @@ real_cell() { return 14 } sed 's/^/e2e.log: /' "$log" - # V2 is only measured with a browser running: the harness prints READY whatever the navigation did. + # The harness prints READY whatever the navigation did, so a cell without a loaded page stops here, + # and V2 is reported as not passing (gate_real_cell below would say the same). if ! { grep -q '^NAVIGATE ok$' "$log" && grep -q '^SNAPSHOT_HAS_TEXT true$' "$log"; }; then echo "GATE harness fail no browser page was loaded (need NAVIGATE ok and SNAPSHOT_HAS_TEXT true)" + echo "GATE V2 fail not measured: no browser page was loaded" return 14 fi @@ -217,13 +246,7 @@ real_cell() { # The listener self-check on the live tree: the status command reads it from /proc. status=$("$bin" browser status --json) echo "status: $status" - gate_v2 "$status" || note_fail 20 - case "$(json_field "$status" listeners)" in - none | "") - echo "GATE V2 fail no listener seen in the real cell: the browser tree was not measured" - note_fail 20 - ;; - esac + gate_real_cell "$log" "$status" || note_fail 20 # V11: the mount tier's answer. `--retry` runs the containment self-test in this process, which # uses the production unit names, so only the CI job sets this (a throwaway runner). if [ "${OAB_SMOKE_STATUS_RETRY:-0}" = 1 ]; then @@ -286,8 +309,7 @@ in_container() { while IFS= read -r line; do [ -n "$line" ] || continue echo "root action: ${line%%$'\t'*}" - act=${line%%$'\t'*} - act=${act#sudo } # already root in the throwaway container, which has no sudo + act=$(root_command "${line%%$'\t'*}") sh -c "$act" || echo "(that action failed; the health check decides)" done /dev/null; expect "V2 TMPDIR of another uid fails" 1 $? gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=mode result=pass')" >/dev/null; expect "V2 recomputed: tmpdir=mode fails even if result=pass" 1 $? gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=missing result=pass')" >/dev/null; expect "V2 recomputed: tmpdir=missing fails" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=mode result=pass')" >/dev/null; expect "V2 a bad TMPDIR fails even with no unix listener" 1 $? gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=1 tmpdir=ok result=pass')" >/dev/null; expect "V2 recomputed: unix_outside=1 fails even if result=pass" 1 $? gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=fail')" >/dev/null; expect "V2 result=fail fails" 1 $? gate_v2 "$(status_json 'tcp=1 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass')" >/dev/null; expect "V2 tcp=1 fails even with a private dir" 1 $? @@ -40,6 +41,31 @@ gate_v2 "$(status_json not_running)" >/dev/null; expect "V2 not_running fails (n gate_v2 '{"state":"installed"}' >/dev/null; expect "V2 missing field fails" 1 $? gate_v2 '' >/dev/null; expect "V2 empty output fails" 1 $? +# V2 in a real cell: a loaded page is required, and `listeners=none` alone never passes. +L="$(mktemp -d "${TMPDIR:-/tmp}/oab-l5-test-gate.XXXXXX")" +trap 'rm -rf "$L"' EXIT +printf 'READY ok\n' >"$L/nonav.log" +printf 'READY ok\nNAVIGATE ok\nSNAPSHOT_HAS_TEXT true\n' >"$L/page.log" +gate_real_cell "$L/nonav.log" "$(status_json "$P")" >/dev/null; expect "real cell: no NAVIGATE ok fails even with two private sockets" 1 $? +gate_real_cell "$L/page.log" "$(status_json none)" >/dev/null; expect "real cell: a loaded page with listeners=none alone fails" 1 $? +out=$(gate_real_cell "$L/page.log" "$(status_json none)"); case $out in *"not measured"*) ok "real cell: listeners=none is named" ;; *) bad "real cell none not named: $out" ;; esac +out=$(gate_real_cell "$L/page.log" "$(status_json "$P")"); expect "real cell: a loaded page and two private sockets pass" 0 $? +case $out in "GATE V2 pass"*) ok "real cell: pass line" ;; *) bad "real cell pass line: $out" ;; esac +gate_real_cell "$L/page.log" "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=fail')" >/dev/null; expect "real cell: result=fail fails" 1 $? +gate_real_cell "$L/page.log" "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=1 tmpdir=ok result=pass')" >/dev/null; expect "real cell: unix_outside=1 fails" 1 $? + +# root_command: the container runs as root with no sudo, so a leading sudo is removed. +[ "$(root_command 'sudo apt-get install -y libnss3')" = 'apt-get install -y libnss3' ]; expect "root_command strips a leading sudo" 0 $? +[ "$(root_command 'apt-get install -y libnss3')" = 'apt-get install -y libnss3' ]; expect "root_command leaves a line without sudo unchanged" 0 $? +[ "$(root_command 'echo sudo here')" = 'echo sudo here' ]; expect "root_command does not strip sudo mid-line" 0 $? +# The container path (the in_container body, and the docker run in the workflow) names no sudo. +body=$(sed -n '/^in_container() {/,/^}/p' "$here/release-smoke-linux.sh" | grep -v '^ *#') +case $body in *sudo*) bad "in_container runs sudo" ;; *) ok "in_container body names no sudo" ;; esac +wf="$here/../.github/workflows/linux-release-smoke.yml" +run=$(sed -n '/docker run/,/--in-container/p' "$wf") +case $run in *"docker run"*) ;; *) bad "docker run line not found in the workflow" ;; esac +case $run in *sudo*) bad "docker run passes sudo into the container" ;; *) ok "docker run line names no sudo" ;; esac + # V4: the two systemd modes pass; anything else fails. gate_v4 systemd >/dev/null; expect "V4 systemd" 0 $? gate_v4 systemd+mount >/dev/null; expect "V4 systemd+mount" 0 $? @@ -51,7 +77,7 @@ if [ "$(json_field "$(status_json 'tcp=0 udp=0 unix=2')" listeners)" = "tcp=0 ud # Survivor check: a process whose executable is below the directory is found, then not once gone. T=$(mktemp -d "${TMPDIR:-/tmp}/oab-l5-test-smoke.XXXXXX") -trap 'rm -rf "$T"' EXIT +trap 'rm -rf "$T" "$L"' EXIT mkdir -p "$T/install" "$T/other" if [ ! -e /proc/self/exe ]; then echo "SKIP survivor check (no /proc: Linux only; CI runs it)" @@ -69,94 +95,83 @@ wait "$inside" "$outside" 2>/dev/null if [ -z "$(survivors_under "$T/install")" ]; then ok "no survivor after the kill"; else bad "survivor after the kill"; fi fi -# The record gate. A filled record copies the template's rows. +# ---------------------------------------------------------------- the record gate (ADR D16) +# +# The valid record is the template with every PENDING replaced by pass. Each bypass below edits a COPY +# of it and must make check-release-record.sh exit 1; the untouched copy must exit 0. The rows are +# matched by their first cell, so a row is found by its id (V1 .. V13, M1 .. M10) or by its cell name. +# Known limit: the checker reads every line that starts with "|", so a row placed inside an HTML comment +# still counts. Nothing here relies on comments. R="$T/records" mkdir -p "$R" C="$here/check-release-record.sh" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: missing file fails" 1 $? -"$C" 9.9.9 --dir "$R" --report-only >/dev/null 2>&1; expect "record: missing file, --report-only exits 0" 0 $? +TPL="$here/../docs/release-records/TEMPLATE.md" +VALID="$R/valid.md" +REC="$R/linux-9.9.9.md" +sed 's/PENDING/pass/g' "$TPL" >"$VALID" + +"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: no record file fails" 1 $? +"$C" 9.9.9 --dir "$R" --report-only >/dev/null 2>&1; expect "record: no record file, --report-only exits 0" 0 $? "$C" v9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a leading v is a usage error" 64 $? -cp "$here/../docs/release-records/TEMPLATE.md" "$R/linux-9.9.9.md" +"$C" abc --dir "$R" >/dev/null 2>&1; expect "record: a non-version is a usage error" 64 $? +cp "$TPL" "$REC" "$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: the untouched template fails" 1 $? -fill="$T/filled.md" -sed 's/PENDING/done/g;s/^\(| V[0-9]* [^|]*\)| done |\(.*| yes[^|]*|\)$/\1| pass |\2/;s/^\(| M[0-9]* [^|]*\)| done |/\1| pass |/;s/^\(| Ubuntu [0-9.]* [a-z0-9]* \)| done |/\1| pass |/;s/^\(| Debian 12 container [a-z0-9]* \)| done |/\1| pass |/' "$R/linux-9.9.9.md" >"$fill" -cp "$fill" "$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: all rows filled, V2 and D7 decided, passes" 0 $? -# A row that reopens a decision blocks the release, and the gate names it. -sed 's/^| \(V2 .*\) | pass | /| \1 | open, owner decision pending | /;s/^| \(D7 .*\) | decided, glob kept | /| \1 | open, owner decision pending | /' "$fill" >"$R/linux-9.9.9.md" -out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: V2 and D7 reopened blocks" 1 $? -case $out in *"V2 is open"*"D7 is open"*) ok "record: both open rows are named" ;; *) bad "record: open rows not named: $out" ;; esac -sed 's/^| \(D7 .*\) | decided, glob kept | /| \1 | open, owner decision pending | /' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: D7 reopened alone blocks" 1 $? -grep -v '^| D7 ' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a removed D7 row fails" 1 $? -grep -v '^| V2 ' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a removed V2 row fails" 1 $? -sed 's/^| M3 \(.*\) | pass | done | done | done |$/| M3 \1 | PENDING | done | done | done |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: one PENDING cell fails" 1 $? -sed 's/^| \(V2 .*\) | pass | /| \1 | PENDING | /' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a V2 row without its measurement (PENDING) fails" 1 $? -# A blocking gate (V1, V2, V7) needs exactly pass; n/a (with or without a reason), fail or free text blocks. -for bad_result in fail 'n/a' 'done' 'pass?' ''; do - sed "s#^| \\(V7 [^|]*\\)| pass |#| \\1| $bad_result |#" "$fill" >"$R/linux-9.9.9.md" - out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: V7 result '$bad_result' blocks" 1 $? - case $out in *"gate row not acceptable: V7"*) ok "record: V7 '$bad_result' is named" ;; *) bad "record: V7 '$bad_result' not named: $out" ;; esac -done -sed 's/^| \(V7 [^|]*\)| pass |/| \1| n\/a, no sign-in on this release |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: V7 n/a with a reason blocks" 1 $? -sed 's/^| \(V1 [^|]*\)| pass |/| \1| n\/a, no source yet |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: V1 n/a with a reason blocks" 1 $? -sed 's/^| \(V1 [^|]*\)| pass |/| \1| fail |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: V1 fail blocks" 1 $? -# A strict gate cannot hide: a deleted row, a "|" inside a cell, a Blocking cell edited to "no". -for g in V1 V2 V7 V13; do - grep -v "^| $g " "$fill" >"$R/linux-9.9.9.md" - out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: a removed $g row fails" 1 $? - case $out in *"$g (row missing)"*) ok "record: removed $g row is named" ;; *) bad "record: removed $g row not named: $out" ;; esac +cp "$VALID" "$REC" +"$C" 9.9.9 --dir "$R" >"$T/valid.out" 2>&1; expect "record: the valid record passes" 0 $? + +# reject NAME SED_PROGRAM: the copy edited by SED_PROGRAM must make the checker exit 1, and the name is +# printed for each case. +reject() { + sed "$2" "$VALID" >"$REC" + "$C" 9.9.9 --dir "$R" >"$T/out" 2>&1 + code=$? + if [ "$code" -eq 1 ] && grep -q '^release record: ' "$T/out"; then ok "reject: $1"; else bad "reject: $1 (exit $code, wanted 1 with a finding): $(head -c 300 "$T/out")"; fi +} +# accept NAME SED_PROGRAM: the copy must still pass. +accept() { + sed "$2" "$VALID" >"$REC" + "$C" 9.9.9 --dir "$R" >"$T/out" 2>&1 + code=$? + if [ "$code" -eq 0 ]; then ok "accept: $1"; else bad "accept: $1 (exit $code, wanted 0): $(head -c 300 "$T/out")"; fi +} + +# Each row id (with its trailing space, so V1 does not match V10) gets the same set of mutations. +for id in V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13; do + reject "$id row deleted" "/^| $id /d" + reject "$id row duplicated" "/^| $id /p" + reject "$id row malformed (five cells)" "/^| $id /s/\$/ extra |/" + reject "$id result fail" "/^| $id /s#| pass |#| fail |#" + reject "$id result empty" "/^| $id /s#| pass |#| |#" + reject "$id result n/a without a reason" "/^| $id /s#| pass |#| n/a |#" + reject "$id result n/a with a reason" "/^| $id /s#| pass |#| n/a, no runner in this cycle |#" + reject "$id result PENDING" "/^| $id /s#| pass |#| PENDING |#" done -sed 's/^| \(V1 [^|]*\)| pass | \([^|]*\)|/| \1| fail | ss -lxp | grep chrome |/' "$fill" >"$R/linux-9.9.9.md" -out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: V1 fail with a pipe in Evidence fails" 1 $? -case $out in *"V1 (malformed row"*) ok "record: the malformed V1 row is named" ;; *) bad "record: malformed V1 not named: $out" ;; esac -sed 's/^| \(V7 .*\)| yes[^|]* |$/| \1| no |/;s/^| \(V7 [^|]*\)| pass |/| \1| fail |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: V7 fail with Blocking edited to no still fails" 1 $? -{ cat "$fill"; grep '^| V7 ' "$fill"; } >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a duplicated V7 row fails" 1 $? -# M rows and smoke-cell rows: each exactly once, Result (any case) pass only (ADR D16, no n/a). -sed 's/^| \(M3 [^|]*\)| pass |/| \1| fail |/' "$fill" >"$R/linux-9.9.9.md" -out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: an M3 fail blocks" 1 $? -case $out in *"manual or smoke-cell row not acceptable: M3"*) ok "record: M3 fail is named" ;; *) bad "record: M3 not named: $out" ;; esac -sed 's/^| \(Ubuntu 22.04 arm64\) | pass |/| \1 | fail |/' "$fill" >"$R/linux-9.9.9.md" -out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: a smoke-cell fail blocks" 1 $? -case $out in *"not acceptable: Ubuntu 22.04 arm64"*) ok "record: cell fail is named" ;; *) bad "record: cell not named: $out" ;; esac -for bad_result in Fail FAIL red 'not run' 'done' ''; do - sed "s#^| \\(M5 [^|]*\\)| pass |#| \\1| $bad_result |#" "$fill" >"$R/linux-9.9.9.md" - out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: M5 result '$bad_result' blocks" 1 $? - sed "s#^| \\(Debian 12 container arm64\\) | pass |#| \\1 | $bad_result |#" "$fill" >"$R/linux-9.9.9.md" - out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: a cell result '$bad_result' blocks" 1 $? +for id in M1 M2 M3 M4 M5 M6 M7 M8 M9 M10; do + reject "$id row deleted" "/^| $id /d" + reject "$id row duplicated" "/^| $id /p" + reject "$id row malformed (extra cell)" "/^| $id /s/\$/ extra |/" + reject "$id result n/a" "/^| $id /s#| pass |#| n/a |#" + reject "$id result n/a with a reason" "/^| $id /s#| pass |#| n/a, no Raspberry Pi in this cycle |#" + reject "$id result fail" "/^| $id /s#| pass |#| fail |#" + reject "$id result FAIL (upper case)" "/^| $id /s#| pass |#| FAIL |#" + reject "$id result PENDING" "/^| $id /s#| pass |#| PENDING |#" done -sed 's/^| \(M5 [^|]*\)| pass |/| \1| PASS |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: M5 PASS (any case) is accepted" 0 $? -sed 's/^| \(M4 [^|]*\)| pass |/| \1| n\/a, no Raspberry Pi in this cycle |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: M4 n/a with a reason blocks (ADR D16)" 1 $? -sed 's/^| \(M4 [^|]*\)| pass |/| \1| n\/a |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: M4 n/a without a reason blocks" 1 $? -sed 's/^| \(Ubuntu 24.04 arm64\) | pass |/| \1 | n\/a, no runner |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a smoke cell n/a with a reason blocks" 1 $? -# A deleted M row or smoke-cell row cannot hide (no PENDING left to find). -for g in 'M1 ' 'M10 ' 'Ubuntu 22.04 amd64 ' 'Debian 12 container arm64 '; do - grep -v "^| $g" "$fill" >"$R/linux-9.9.9.md" - out=$("$C" 9.9.9 --dir "$R" 2>&1); expect "record: a removed '$g' row fails" 1 $? - case $out in *"(row missing)"*) ok "record: removed '$g' row is named" ;; *) bad "record: removed '$g' not named: $out" ;; esac +for cell in "Ubuntu 22.04 amd64" "Ubuntu 22.04 arm64" "Ubuntu 24.04 amd64" "Ubuntu 24.04 arm64" "Debian 12 container amd64" "Debian 12 container arm64"; do + reject "smoke cell '$cell' row deleted" "/^| $cell |/d" + reject "smoke cell '$cell' row duplicated" "/^| $cell |/p" + reject "smoke cell '$cell' row malformed" "/^| $cell |/s/\$/ extra |/" + reject "smoke cell '$cell' result n/a" "/^| $cell |/s#| pass |#| n/a |#" + reject "smoke cell '$cell' result fail" "/^| $cell |/s#| pass |#| fail |#" done -{ cat "$fill"; grep '^| M2 ' "$fill"; } >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a duplicated M2 row fails" 1 $? -# A non-blocking row may be anything but PENDING. -sed 's/^| \(V3 [^|]*\)| done |/| \1| fail |/' "$fill" >"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: a non-blocking V3 fail does not block" 0 $? -# The instruction text outside the tables may quote the words without tripping the gate. -cp "$fill" "$R/linux-9.9.9.md" -printf '\nThe words open, owner decision pending and PENDING in prose are not a table row.\n' >>"$R/linux-9.9.9.md" -"$C" 9.9.9 --dir "$R" >/dev/null 2>&1; expect "record: prose outside the tables is ignored" 0 $? +reject "V2 row still PENDING" "/^| V2 /s#| pass |#| PENDING |#" +reject "V2 reopened as an owner decision" "/^| V2 /s#| pass |#| open, owner decision pending |#" +reject "D7 reopened as an owner decision" "/^| D7 /s#| decided, glob kept |#| open, owner decision pending |#" +reject "V2 row removed" "/^| V2 /d" +reject "D7 row removed" "/^| D7 /d" +reject "a PENDING cell in a manual row" "/^| M6 /s#| pass |#| PENDING |#" +accept "M5 result in another case (PASS) is pass" "/^| M5 /s#| pass |#| PASS |#" +accept "prose outside the tables may quote the words" "\$a\\ +The words open, owner decision pending, n/a and PENDING in prose are not a table row." echo "pass=$pass fail=$fail" [ "$fail" -eq 0 ] From 0d093e17ec572b0f71ae32b6ba42f4f2d5e3d530 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:42:17 -0500 Subject: [PATCH 03/18] fix: cutover guide runs as written (findings 2, 6, 7) Finding 2, $OLD: the guide no longer uses an OLD variable. Every systemctl line names the unit literally: oab-computer-pw-mcp.service on host A, oab-pw-mcp.service on hosts B to D, with the other name after "#". Finding 2, single quotes: Environment='MCP_UPSTREAM=...' is detected by the Rust sets_upstream (legacy_tests.rs) and by the guide's grep -nE, which scripts/test-cutover-guide.sh runs from the guide text itself. Finding 2, placeholders: the AppArmor command used , which the shell reads as a redirection; it is ID now. Finding 6: step 5.2 and removal step 1 use one block (dropin_is_ours) that removes an MCP_UPSTREAM drop-in only when it is exactly [Service], comments, blanks and the one dedicated Environment line, and not a link. Other files are kept and reported. The block is run by the test under a fake HOME. Finding 7: step 5.4's rollback links the full Rollback section with BK set. No rollback line says "browser remove" alone. BK is a path, not <...>. scripts/test-cutover-guide.sh (new, in CI linux-installer): bash -n on every sh block, no OLD notation, allowed unit names only, the 5.4 link, the drop-in fixtures (exact removed; extra setting, other URL, quoted, double-quoted, two [Service] sections, symlink kept), and the guide's grep -nE fixtures. scripts/test-name-consistency.sh excludes the new test, which names old units on purpose (as the other test scripts do). Commands and results: - bash scripts/test-cutover-guide.sh on a Debian 13 arm64 node: pass=20 fail=0 - Same test on the pre-fix reference guide: 2 sh blocks fail to parse, $OLD notation found, the browser-remove-only rollback found, #rollback missing, drop-in block absent (shows the tests catch the findings) - bash scripts/test-name-consistency.sh on a Debian 13 arm64 node: all checks passed - markdownlint-cli2 on a Debian 13 arm64 node: this file adds no new finding beyond main's MD060 table findings (fixed one MD031 finding from this edit) --- .github/workflows/ci.yml | 5 +- docs/linux-cutover.md | 92 +++++++++++++++++++-------- scripts/test-cutover-guide.sh | 103 +++++++++++++++++++++++++++++++ scripts/test-name-consistency.sh | 2 +- 4 files changed, 175 insertions(+), 27 deletions(-) create mode 100755 scripts/test-cutover-guide.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2896402..c353df4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -111,7 +111,7 @@ jobs: steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: ShellCheck - run: shellcheck scripts/install-linux.sh scripts/test-install-linux.sh scripts/test-name-consistency.sh scripts/test-legacy-agent.sh scripts/release-smoke-linux.sh scripts/test-release-smoke-linux.sh scripts/check-release-record.sh poc/reverse-attach-linux/pw-mcp.sh scripts/test-pw-mcp-deprecated.sh + run: shellcheck scripts/install-linux.sh scripts/test-install-linux.sh scripts/test-name-consistency.sh scripts/test-legacy-agent.sh scripts/release-smoke-linux.sh scripts/test-release-smoke-linux.sh scripts/check-release-record.sh scripts/test-cutover-guide.sh poc/reverse-attach-linux/pw-mcp.sh scripts/test-pw-mcp-deprecated.sh - name: Generated units (fake HOME, stubbed systemctl/tailscale/loginctl) # Diffs each written unit against its expected text and runs systemd-analyze verify (#90). run: bash scripts/test-install-linux.sh @@ -123,6 +123,9 @@ jobs: # The pure parts of scripts/release-smoke-linux.sh and scripts/check-release-record.sh. The # smoke itself runs in .github/workflows/linux-release-smoke.yml (dispatch and release only). run: bash scripts/test-release-smoke-linux.sh + - name: Cutover guide: its shell blocks parse, its drop-in removal block and grep match the fixtures + # Runs the guide's own text against fixtures under a temporary HOME. Touches no unit or port. + run: bash scripts/test-cutover-guide.sh - name: pw-mcp.sh is marked deprecated and still launches unchanged (D14) # A stub stands in for playwright-mcp; nothing real starts and no port opens. run: bash scripts/test-pw-mcp-deprecated.sh diff --git a/docs/linux-cutover.md b/docs/linux-cutover.md index d5cc1da..48aad44 100644 --- a/docs/linux-cutover.md +++ b/docs/linux-cutover.md @@ -93,25 +93,22 @@ flowchart TB ``` Notation. Commands run on the host being moved, as the user that runs the daemon, in that user's -login session (over `ssh`, so that `XDG_RUNTIME_DIR` and the user manager are set). `$OLD` is the -old browser unit on that host. Set it once per shell, before any command that uses it (host A, then -B to D), and check it names a real unit: +login session (over `ssh`, so that `XDG_RUNTIME_DIR` and the user manager are set). The old browser +unit has one name on host A and another on hosts B to D. A command that names it gives host A's name, +then hosts B to D's name after the `#`. Before the first use on a host, check that the unit exists: Host A: ```sh -OLD=oab-computer-pw-mcp.service -systemctl --user cat "$OLD" >/dev/null && echo "OLD=$OLD" +systemctl --user cat oab-computer-pw-mcp.service >/dev/null && echo "old unit: oab-computer-pw-mcp.service" ``` Hosts B to D: ```sh -OLD=oab-pw-mcp.service -systemctl --user cat "$OLD" >/dev/null && echo "OLD=$OLD" +systemctl --user cat oab-pw-mcp.service >/dev/null && echo "old unit: oab-pw-mcp.service" ``` -A new `ssh` session starts without it: set it again. The binary is `~/.local/oab-computer/oab-computer` (not on `PATH`). Checks that call the daemon from outside use the commands of [Verify from another tailnet machine](linux-setup.md#6-verify-from-another-tailnet-machine). @@ -220,11 +217,11 @@ decided; see [the residual risk](#decisions-that-shape-this-guide)). **Verify.** `preflight` exits 0 after you ran what you accepted. Run it again to confirm. **Roll back to here.** Libraries and fonts you installed are harmless and stay. If you loaded the -AppArmor profile and want it gone (needs root; `` is the short hash in the file name that `preflight` +AppArmor profile and want it gone (needs root; `ID` in the commands is the short hash in the file name that `preflight` printed): ```sh -sudo apparmor_parser -R /etc/apparmor.d/oab-computer-chromium- && sudo rm /etc/apparmor.d/oab-computer-chromium- +sudo apparmor_parser -R /etc/apparmor.d/oab-computer-chromium-ID && sudo rm /etc/apparmor.d/oab-computer-chromium-ID ``` ## Step 4. Side-by-side install @@ -233,15 +230,15 @@ sudo apparmor_parser -R /etc/apparmor.d/oab-computer-chromium- && sudo rm /e ~/.local/oab-computer/oab-computer.new browser install ~/.local/oab-computer/oab-computer.new browser status ss -ltnH 'sport = :8794' | wc -l -systemctl --user is-active "$OLD" +systemctl --user is-active oab-computer-pw-mcp.service # host A; hosts B to D: oab-pw-mcp.service ``` `install` downloads the pinned set, checks every size and SHA-256, and runs the headless health check on a throwaway profile. It does not touch the seat, the old profile or the old unit. **Verify.** `install` exits 0 and ends with `installed `. `status` shows `state: installed` and -`pins_match: true`. The old listener is still there: `wc -l` prints `1` or more, and `$OLD` is -`active`. From the first release containing L5, `status` also shows `legacy_listener: 8794` and a +`pins_match: true`. The old listener is still there: `wc -l` prints `1` or more, and the old unit is +`active` (host A `oab-computer-pw-mcp.service`, hosts B to D `oab-pw-mcp.service`). From the first release containing L5, `status` also shows `legacy_listener: 8794` and a `legacy:` line that lists the old directories with sizes; the profile reads `holds_cookies`. Do not continue unless the install succeeded. If it fails, nothing was cut over and the old setup is unchanged. @@ -263,7 +260,7 @@ From 5.1 to 5.3 the daemon has no browser. Do them together. Host A first; B to ### 5.1 Disable and stop the old browser unit ```sh -systemctl --user disable --now "$OLD" +systemctl --user disable --now oab-computer-pw-mcp.service # host A; hosts B to D: oab-pw-mcp.service ``` A plain `stop` is not enough: the unit comes back at the next login or boot with its unauthenticated @@ -272,11 +269,11 @@ listener. **Verify.** ```sh -systemctl --user is-enabled "$OLD" # prints disabled (exit status 1 is normal for a disabled unit) +systemctl --user is-enabled oab-computer-pw-mcp.service # host A; hosts B to D: oab-pw-mcp.service. Prints disabled (exit status 1 is normal for a disabled unit) ss -ltnH 'sport = :8794' | wc -l # prints 0 ``` -**Roll back to here.** `systemctl --user enable --now "$OLD"`. +**Roll back to here.** `systemctl --user enable --now oab-computer-pw-mcp.service` (host A; hosts B to D: `oab-pw-mcp.service`). ### 5.2 Remove the `MCP_UPSTREAM` line (host A) or the drop-in file (hosts B to D) @@ -305,11 +302,33 @@ Comments, `UnsetEnvironment=` and other variables are not matched. For each file and decide: - It holds only `[Service]`, that one `Environment=MCP_UPSTREAM=` line, comments and blank lines: it is - the dedicated drop-in. `rm -f FILE`. + the dedicated drop-in. The block below removes it. - It holds any other setting: keep the file and delete only the line, `sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp$/d' FILE`. If the line has another form (several variables, another URL), edit it by hand and keep everything else. +Run this block once, after the bullets above. It removes a drop-in only when the file has exactly the +dedicated shape and is not a link. It keeps every other file and says why: + +```sh +# Removes only the dedicated MCP_UPSTREAM drop-in (see step 5.2). Anything else is kept and reported. +dropin_is_ours() { + [ -f "$1" ] && [ ! -L "$1" ] || return 1 + awk ' + /^[[:space:]]*$/ || /^[[:space:]]*#/ { next } + /^\[Service\][[:space:]]*$/ { svc++; next } + /^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp[[:space:]]*$/ { line++; next } + { bad = 1 } + END { exit (bad || svc != 1 || line != 1) } + ' "$1" +} +for f in ~/.config/systemd/user/oab-computer.service.d/*.conf ~/.config/systemd/user/oab-instance-mcp.service.d/*.conf; do + [ -e "$f" ] || continue + grep -q 'MCP_UPSTREAM=' "$f" || continue + if dropin_is_ours "$f"; then rm -f -- "$f"; echo "removed $f"; else echo "kept $f: not exactly the dedicated drop-in, edit it by hand"; fi +done +``` + A drop-in the `grep` did not list may belong to something else. Do not delete it, and do not delete the `.d/` directory. @@ -359,7 +378,9 @@ It opens a window on the node's seat on the persistent profile and waits for Ent **Verify.** A later browser call is signed in to the site you logged in to. -**Roll back to here.** `browser remove` deletes the new profile; the old one is untouched. +**Roll back to here.** Follow the full [Rollback](#rollback) section, with `BK` set to the backup directory of +step 1. `browser remove` alone is not a rollback: it deletes the new profile, and the old unit, the drop-in +and the binary stay as they are until that section restores them. ## Step 6. Verify @@ -406,7 +427,7 @@ ss -ltnH 'sport = :8794' | wc -l UDP listener, a Unix listener outside the child's private directory, or that directory not being `0700` or not yours. Run `status` in the daemon's own login session so `XDG_RUNTIME_DIR` matches. From the first release containing L5, `legacy_listener: none`. -- End your login session and log in again, or reboot. Then `systemctl --user is-enabled "$OLD"` prints +- End your login session and log in again, or reboot. Then `systemctl --user is-enabled oab-computer-pw-mcp.service` (host A; hosts B to D: `oab-pw-mcp.service`) prints `disabled` and the `ss` check still prints `0`. With linger on, the daemon survives the logout. If any check fails, the host is not cut over: use the [Rollback](#rollback). @@ -439,7 +460,7 @@ daemon because it runs as a transient unit bound to it; the time Chromium takes ## Step 8. Soak -Leave `$OLD` disabled **but not deleted**, and the legacy directories in place, for one week of normal +Leave the old unit disabled **but not deleted** (host A `oab-computer-pw-mcp.service`, hosts B to D `oab-pw-mcp.service`), and the legacy directories in place, for one week of normal use with no browser incident (D13). Check now and then: ```sh @@ -489,7 +510,7 @@ flowchart TB 3. Restore the daemon unit, the drop-in and the binary from the backup, then reload: ```sh - BK= + BK="${XDG_DATA_HOME:-$HOME/.local/share}/oab-computer/backup-YYYYMMDD" # the directory step 1 created cp -a "$BK/oab-computer.service" ~/.config/systemd/user/ for d in oab-computer.service.d oab-instance-mcp.service.d; do if [ -d "$BK/$d" ]; then cp -a "$BK/$d" ~/.config/systemd/user/; fi @@ -501,10 +522,10 @@ flowchart TB If step 5.3 had not run yet, the old binary is still in place; `install` over it is harmless. `pw-mcp.sh` was never touched, so the old unit still finds its script. -4. Start the old unit and the daemon (set `OLD` first, as in the notation at the top, if this is a new shell): +4. Start the old unit and the daemon (host A `oab-computer-pw-mcp.service`; hosts B to D `oab-pw-mcp.service`): ```sh - systemctl --user enable --now "$OLD" + systemctl --user enable --now oab-computer-pw-mcp.service # host A; hosts B to D: oab-pw-mcp.service systemctl --user start oab-computer.service ``` @@ -540,8 +561,29 @@ the same list, in order: 1. Disable and delete the old unit files, then reload. No root. Step 5.2 owns the drop-in: it already removed the dedicated drop-in file, or only the `MCP_UPSTREAM` line from a shared one, and the - backup from step 1 keeps the original for the rollback. Remove a dedicated drop-in here only if you - skipped that part of step 5.2, with `rm -f FILE` before the `daemon-reload` below: + backup from step 1 keeps the original for the rollback. If you skipped the drop-in part of step 5.2, run + the same block from step 5.2 first (indented here), then the `daemon-reload` below: + + ```sh + # Removes only the dedicated MCP_UPSTREAM drop-in (see step 5.2). Anything else is kept and reported. + dropin_is_ours() { + [ -f "$1" ] && [ ! -L "$1" ] || return 1 + awk ' + /^[[:space:]]*$/ || /^[[:space:]]*#/ { next } + /^\[Service\][[:space:]]*$/ { svc++; next } + /^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp[[:space:]]*$/ { line++; next } + { bad = 1 } + END { exit (bad || svc != 1 || line != 1) } + ' "$1" + } + for f in ~/.config/systemd/user/oab-computer.service.d/*.conf ~/.config/systemd/user/oab-instance-mcp.service.d/*.conf; do + [ -e "$f" ] || continue + grep -q 'MCP_UPSTREAM=' "$f" || continue + if dropin_is_ours "$f"; then rm -f -- "$f"; echo "removed $f"; else echo "kept $f: not exactly the dedicated drop-in, edit it by hand"; fi + done + ``` + + Then unload and delete the old unit files: ```sh for u in oab-pw-mcp.service oab-computer-pw-mcp.service; do diff --git a/scripts/test-cutover-guide.sh b/scripts/test-cutover-guide.sh new file mode 100755 index 0000000..c074138 --- /dev/null +++ b/scripts/test-cutover-guide.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# Tests for docs/linux-cutover.md that run the guide's own text, not a copy of it: +# - every ```sh block parses (bash -n), and no `$OLD` or `OLD=` notation is left; +# - every literal oab-* unit name on a `systemctl` line is one of the names the guide allows; +# - the step 5.4 rollback links to the full Rollback section and does not say `browser remove` alone; +# - the drop-in removal block (step 5.2) removes only the dedicated file, against a fake HOME; +# - the guide's `grep -nE` for active MCP_UPSTREAM assignments matches single-quoted, double-quoted +# and bare forms, and not comments or UnsetEnvironment=. +# Nothing here touches a real unit, a real HOME, or a port. +set -u +here=$(cd "$(dirname "$0")" && pwd) +GUIDE="$here/../docs/linux-cutover.md" +pass=0 +fail=0 +ok() { echo "PASS $1"; pass=$((pass + 1)); } +bad() { echo "FAIL $1"; fail=$((fail + 1)); } + +T=$(mktemp -d "${TMPDIR:-/tmp}/oab-l5-test-guide.XXXXXX") +trap 'rm -rf "$T"' EXIT + +# Every ```sh fenced block, indented or not, one file per block. +awk -v dir="$T" ' + /^ *```sh$/ { inb = 1; n++; f = dir "/block" n ".sh"; next } + /^ *```$/ && inb { inb = 0; close(f); next } + inb { print > f } +' "$GUIDE" +blocks=$(ls "$T"/block*.sh 2>/dev/null | wc -l) +[ "$blocks" -gt 0 ] && ok "found $blocks sh blocks" || bad "no sh blocks found" +syntax_bad=0 +for f in "$T"/block*.sh; do + if ! bash -n "$f" 2>"$T/err"; then syntax_bad=$((syntax_bad + 1)); echo " syntax: $(basename "$f"): $(head -n 1 "$T/err")"; fi +done +[ "$syntax_bad" -eq 0 ] && ok "every sh block parses (bash -n)" || bad "$syntax_bad sh block(s) do not parse" + +# No `$OLD` notation, no `OLD=` assignment. +if grep -nE '\$OLD|OLD=' "$GUIDE" >"$T/old.txt"; then bad "the guide still uses the OLD notation: $(head -n 1 "$T/old.txt")"; else ok "no \$OLD or OLD= notation"; fi + +# Literal oab-* unit names on systemctl lines. Allowed: the old unit of each host class, the daemon +# unit, the instance-mcp unit of 0.11, and the browser wildcard the guide names. +allowed='oab-computer-pw-mcp.service oab-pw-mcp.service oab-computer.service oab-instance-mcp.service oab-browser-*.service' +unit_bad=0 +grep -h 'systemctl' "$GUIDE" | grep -oE "oab-[A-Za-z0-9*._-]+\.service" | sort -u >"$T/units.txt" +while IFS= read -r u; do + case " $allowed " in *" $u "*) ;; *) unit_bad=$((unit_bad + 1)); echo " unexpected unit name: $u" ;; esac +done <"$T/units.txt" +[ "$unit_bad" -eq 0 ] && ok "every literal unit name on a systemctl line is allowed ($(wc -l <"$T/units.txt" | tr -d ' ') distinct)" || bad "$unit_bad unexpected unit name(s)" + +# Step 5.4 rollback: it links to the Rollback section, and no line gives `browser remove` alone. +if grep -qE '^\*\*Roll back to here\.\*\* `browser remove`' "$GUIDE"; then bad "a rollback line says browser remove alone"; else ok "no rollback line says browser remove alone"; fi +sec=$(sed -n '/^### 5\.4 /,/^## Step 6/p' "$GUIDE") +case $sec in *"(#rollback)"*) ok "step 5.4 rollback links to the full Rollback section" ;; *) bad "step 5.4 does not link to #rollback" ;; esac + +# The drop-in removal block: the one whose text defines dropin_is_ours. Run it with a fake HOME. +block=$(awk '/^ *```sh$/ { inb = 1; buf = ""; next } /^ *```$/ && inb { if (buf ~ /dropin_is_ours\(\)/) { printf "%s", buf; exit } inb = 0; next } inb { buf = buf $0 "\n" }' "$GUIDE") +if [ -z "$block" ]; then + bad "the drop-in removal block is not in the guide" +else + printf '%s\n' "$block" >"$T/dropin.sh" + dropin_case() { # dropin_case NAME EXPECT(removed|kept) CONTENT [symlink] + local h="$T/home-$1" + rm -rf "$h" + mkdir -p "$h/.config/systemd/user/oab-computer.service.d" + local f="$h/.config/systemd/user/oab-computer.service.d/upstream.conf" + if [ "${4:-}" = symlink ]; then + printf '[Service]\nEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp\n' >"$T/target-$1.conf" + ln -s "$T/target-$1.conf" "$f" + else + printf '%b' "$3" >"$f" + fi + HOME="$h" bash "$T/dropin.sh" >"$T/out-$1" 2>&1 + if [ "$2" = removed ]; then + if [ ! -e "$f" ] && [ ! -L "$f" ]; then ok "drop-in: $1 is removed"; else bad "drop-in: $1 should be removed"; fi + else + if [ -e "$f" ] || [ -L "$f" ]; then ok "drop-in: $1 is kept"; else bad "drop-in: $1 should be kept"; fi + fi + } + dropin_case exact removed '[Service]\nEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp\n' + dropin_case comments_and_blank removed '# written by an installer\n\n[Service]\n\nEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp\n' + dropin_case extra_setting kept '[Service]\nEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp\nEnvironment=OAB_BROWSER=off\n' + dropin_case other_url kept '[Service]\nEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8795/mcp\n' + dropin_case quoted kept "[Service]\nEnvironment='MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp'\n" + dropin_case double_quoted kept '[Service]\nEnvironment="MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp"\n' + dropin_case two_service_sections kept '[Service]\n[Service]\nEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp\n' + dropin_case symlink kept '' symlink +fi + +# The guide's own grep -nE, read from the guide, against fixtures. +re=$(grep -E '^grep -nE "' "$GUIDE" | head -n 1 | sed -e 's/^grep -nE "//' -e 's/" \\$//') +re=${re//\\\"/\"} +if [ -z "$re" ]; then + bad "the guide's grep -nE pattern is not found" +else + match() { printf '%s\n' "$1" | grep -qE "$re"; } + match "Environment='MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp'" && ok "grep: single-quoted assignment matches" || bad "grep: single-quoted assignment does not match" + match 'Environment="MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp"' && ok "grep: double-quoted assignment matches" || bad "grep: double-quoted assignment does not match" + match "Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" && ok "grep: bare assignment matches" || bad "grep: bare assignment does not match" + match "Environment=OAB_X=1 MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" && ok "grep: assignment after another setting matches" || bad "grep: later assignment does not match" + match "# Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" && bad "grep: a commented line matches" || ok "grep: a commented line does not match" + match "UnsetEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" && bad "grep: UnsetEnvironment= matches" || ok "grep: UnsetEnvironment= does not match" +fi + +echo "pass=$pass fail=$fail" +[ "$fail" -eq 0 ] diff --git a/scripts/test-name-consistency.sh b/scripts/test-name-consistency.sh index 37d90fe..968c37d 100755 --- a/scripts/test-name-consistency.sh +++ b/scripts/test-name-consistency.sh @@ -204,7 +204,7 @@ OLD_HITS=$(grep -rlE 'instance-mcp|oab-pw-mcp' "$LH/.config" "$LH/.local" 2>/dev # and the Linux CLI's legacy listing in `browser status`: legacy.rs, its tests, and the fixtures that seed a legacy unit). LEFT=$(cd "$ROOT" && grep -rnE --exclude-dir=target --exclude-dir=.build 'oab-instance-mcp|instance-mcp|INSTANCE_MCP|oab-pw-mcp|dev\.openab\.instance' \ Sources Tests poc scripts .github images Package.swift 2>/dev/null \ - | grep -vE '^scripts/test-(legacy-agent|name-consistency|install-linux)\.sh:' \ + | grep -vE '^scripts/test-(legacy-agent|name-consistency|install-linux|cutover-guide)\.sh:' \ | grep -vE '^poc/reverse-attach-linux/src/legacy(_tests)?\.rs:' \ | grep -vE '^poc/reverse-attach-linux/src/(probe|install)_tests\.rs:[0-9]+:.*oab-pw-mcp\.service' \ | grep -vE '\.config/oab-instance-mcp/token|instance-mcp(#[0-9]|/issues/)' \ From 6853cafc0823fb27977a04a5345741a1c3d78bf2 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:42:26 -0500 Subject: [PATCH 04/18] fix: judge Unix listeners by their resolved directory (finding 3) is_inside (a lexical prefix test) and plain_parents (a walk of the directories between the TMPDIR and the socket) are replaced by inside_resolved(path, private_real). It requires an absolute path, a socket node that still exists (an unlinked socket is outside), and that the socket's directory, canonicalized so every link is followed, starts_with the canonical private TMPDIR. Path::starts_with compares whole components, so a sibling with the same name prefix is outside. probe.rs canonicalizes the verified TMPDIR once and passes it in. The Source trait loses parents_are_plain. tmp_state gets a doc comment saying its verdict is a point-in-time self-report. Tests (procnet_tests.rs, real directories and real bound sockets): a socket directly in the private directory is inside; in a real subdirectory is inside; reached through a link to the private directory is inside; in a subdirectory that is a link to a directory outside is outside (the finding); a sibling that shares the name prefix is outside; a socket elsewhere, a relative path, an abstract name and an empty path are outside; an unlinked socket is outside. Fixture-level: two inside sockets pass; one outside fails; a socket unlinked after bind counts outside; no verified TMPDIR makes every Unix listener outside. Commands and results: - cargo fmt (applied) then cargo fmt --check on a Debian 13 arm64 node: clean - cargo clippy --release -- -D warnings on a Debian 13 arm64 node: clean (one dead-code error for a test-only method was fixed in the sigstop commit) - cargo test --release on a Debian 13 arm64 node: 553 passed, 0 failed, 17 ignored (the ignored tests are the end-to-end harnesses, not run here) - cargo fmt --check and cargo clippy --release -- -D warnings on a macOS arm64 node: clean; cargo test --release does not link there (undefined _prctl in the Linux seat code, unchanged from main; see the PR's unmet items) --- poc/reverse-attach-linux/src/probe.rs | 3 +- poc/reverse-attach-linux/src/procnet.rs | 74 +++--- poc/reverse-attach-linux/src/procnet_tests.rs | 242 +++++++++++++----- 3 files changed, 211 insertions(+), 108 deletions(-) diff --git a/poc/reverse-attach-linux/src/probe.rs b/poc/reverse-attach-linux/src/probe.rs index 101dc7a..ac97f5a 100644 --- a/poc/reverse-attach-linux/src/probe.rs +++ b/poc/reverse-attach-linux/src/probe.rs @@ -152,8 +152,9 @@ pub fn gather( if !pids.is_empty() { let tmp = crate::child::RuntimeTmp::expected_path(root.abs_path()); let tmp_state = procnet::tmp_state(&tmp, rustix::process::geteuid().as_raw()); + // The directory is resolved once here; a link in its path is followed (V2). let private = (tmp_state == procnet::TmpState::Ok) - .then(|| tmp.to_str().map(str::to_owned)) + .then(|| std::fs::canonicalize(&tmp).ok()) .flatten(); x.listeners = listeners_word( procnet::listeners_of_tree_in(src, &pids, private.as_deref()), diff --git a/poc/reverse-attach-linux/src/procnet.rs b/poc/reverse-attach-linux/src/procnet.rs index 518f66c..1699d7c 100644 --- a/poc/reverse-attach-linux/src/procnet.rs +++ b/poc/reverse-attach-linux/src/procnet.rs @@ -26,12 +26,6 @@ pub const UNKNOWN: &str = "listener_owner_unknown"; pub trait Source { /// The text of `/proc/net/
` (`tcp`, `tcp6`, `udp`, `udp6`, `unix`). fn table(&self, name: &str) -> std::io::Result; - /// Whether every directory between `private` and the socket's own name is a real directory (not - /// a link), so the node is physically inside `private`. A fixture with no filesystem keeps the - /// default. - fn parents_are_plain(&self, _path: &str, _private: &str) -> bool { - true - } } /// The real `/proc`. @@ -48,30 +42,6 @@ impl Source for Proc { } Ok(s) } - - fn parents_are_plain(&self, path: &str, private: &str) -> bool { - plain_parents(path, private) - } -} - -/// `path` is below `private` by [`is_inside`]. Walk each directory between them with `lstat`: a link -/// (or anything unreadable) fails closed, because the kernel prints the bind path as the program -/// spelled it, so a link could place the node outside the verified directory. -pub fn plain_parents(path: &str, private: &str) -> bool { - let Some(rest) = path.strip_prefix(private).and_then(|r| r.strip_prefix('/')) else { - return false; - }; - let mut cur = std::path::PathBuf::from(private); - let mut segs: Vec<&str> = rest.split('/').collect(); - segs.pop(); - for seg in segs { - cur.push(seg); - match std::fs::symlink_metadata(&cur) { - Ok(m) if m.file_type().is_dir() => {} - _ => return false, - } - } - true } #[derive(Clone, Debug, PartialEq, Eq)] @@ -154,18 +124,28 @@ pub fn parse_unix_listener_paths(text: &str) -> Vec<(u64, String)> { .collect() } -/// Whether `path`, as bound, is strictly below the private directory `private`: it starts with -/// `private` and a `/`, and every segment after that is a plain name (no empty segment, `.` or -/// `..`). An exact string rule, no pattern and no symlink resolution: a path that reaches the -/// directory in another spelling counts as outside (fail closed). -pub fn is_inside(path: &str, private: &str) -> bool { - let Some(rest) = path.strip_prefix(private).and_then(|r| r.strip_prefix('/')) else { +/// Whether the Unix socket bound as `path` lies physically inside the private directory +/// `private_real`, which the caller has already resolved with `canonicalize`. +/// +/// The kernel prints the bind path as the program spelled it, so `path` is judged by where its +/// directory really is: the directory is canonicalized (every link in it is followed), then compared +/// with `Path::starts_with`, which compares whole components (a sibling `x` is outside). The +/// node itself must still exist as a socket. A socket unlinked after the bind prints ` (deleted)` in +/// the table and fails here. A relative path, or a directory that cannot be resolved, is outside. +pub fn inside_resolved(path: &str, private_real: &std::path::Path) -> bool { + use std::os::unix::fs::FileTypeExt; + let p = std::path::Path::new(path); + if !p.is_absolute() { + return false; + } + match std::fs::symlink_metadata(p) { + Ok(m) if m.file_type().is_socket() => {} + _ => return false, + } + let Some(dir) = p.parent() else { return false; }; - !rest.is_empty() - && rest - .split('/') - .all(|s| !s.is_empty() && s != "." && s != "..") + std::fs::canonicalize(dir).is_ok_and(|real| real.starts_with(private_real)) } /// What is wrong with the child's private `TMPDIR`, or `ok`. Read without following a link. @@ -197,6 +177,9 @@ impl TmpState { } /// `ok` only for a real directory (not a link) owned by `uid` with mode exactly `0700`. +/// +/// The TMPDIR state and the listener table are read at different times, so a verdict that uses +/// both is a point-in-time self-report, not an atomic snapshot. pub fn tmp_state(path: &std::path::Path, uid: u32) -> TmpState { use std::os::unix::fs::MetadataExt; let m = match std::fs::symlink_metadata(path) { @@ -321,12 +304,13 @@ pub fn listeners_among(src: &dyn Source, inodes: &HashSet) -> Result, - private: Option<&str>, + private: Option<&std::path::Path>, ) -> Result { let mut out = Listeners::default(); for v6 in [false, true] { @@ -347,7 +331,7 @@ pub fn listeners_among_in( continue; } out.unix += 1; - if !private.is_some_and(|p| is_inside(&path, p) && src.parents_are_plain(&path, p)) { + if !private.is_some_and(|p| inside_resolved(&path, p)) { out.unix_outside += 1; } } @@ -364,7 +348,7 @@ pub fn listeners_of_tree(src: &dyn Source, pids: &[u32]) -> Result, + private: Option<&std::path::Path>, ) -> Result { let mut inodes = HashSet::new(); for p in pids { diff --git a/poc/reverse-attach-linux/src/procnet_tests.rs b/poc/reverse-attach-linux/src/procnet_tests.rs index fefe67a..0be6c7d 100644 --- a/poc/reverse-attach-linux/src/procnet_tests.rs +++ b/poc/reverse-attach-linux/src/procnet_tests.rs @@ -327,63 +327,205 @@ fn unix_listener_paths_keep_the_bound_name() { ); } +/// A scratch directory under /tmp, removed on drop. The name carries the process id. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let d = std::path::PathBuf::from(format!("/tmp/oab-procnet-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + Scratch(d) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Binds a real Unix socket at `path`. Returns the listener (kept alive by the caller) and the inode +/// that `/proc/net/unix` prints for it. +fn bind(path: &std::path::Path) -> (std::os::unix::net::UnixListener, u64) { + use std::os::unix::fs::MetadataExt; + let l = std::os::unix::net::UnixListener::bind(path).unwrap(); + let ino = std::fs::symlink_metadata(path).unwrap().ino(); + (l, ino) +} + +/// `/proc/net/unix` rows for accepting sockets `(inode, bound path)`. +fn unix_rows(socks: &[(u64, String)]) -> String { + socks + .iter() + .enumerate() + .map(|(i, (ino, p))| format!("{i}: 00000002 00000000 00010000 0001 01 {ino} {p}\n")) + .collect() +} + +fn s(p: &std::path::Path) -> String { + p.to_str().unwrap().to_string() +} + #[test] -fn only_a_plain_path_below_the_private_directory_is_inside() { - let ok = |p: &str| is_inside(p, PRIV); - assert!(ok(&format!( - "{PRIV}/org.chromium.Chromium.x/SingletonSocket" - ))); - assert!(ok(&format!("{PRIV}/pw-ab/browser/browser-1.sock"))); - assert!(!ok(PRIV), "the directory itself is not below it"); - assert!(!ok(&format!("{PRIV}/"))); +fn a_socket_directly_in_the_private_directory_is_inside() { + let t = Scratch::new("direct"); + let private = t.0.join("priv"); + std::fs::create_dir(&private).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let sock = private.join("s.sock"); + let (_l, _) = bind(&sock); + assert!(inside_resolved(&s(&sock), &real)); +} + +#[test] +fn a_socket_in_a_real_subdirectory_is_inside() { + let t = Scratch::new("sub"); + let private = t.0.join("priv"); + std::fs::create_dir_all(private.join("pw-ab/browser")).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let sock = private.join("pw-ab/browser/browser-1.sock"); + let (_l, _) = bind(&sock); + assert!(inside_resolved(&s(&sock), &real)); +} + +#[test] +fn a_second_name_for_the_private_directory_reaches_the_same_place() { + // The directory is also reachable through a link: the socket is still physically inside it. + let t = Scratch::new("alias"); + let private = t.0.join("priv"); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&private, t.0.join("alias")).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let sock = t.0.join("alias/s.sock"); + let (_l, _) = bind(&sock); + assert!(inside_resolved(&s(&sock), &real)); +} + +#[test] +fn a_link_inside_the_private_directory_that_leads_outside_is_outside() { + // The finding: private/sub is a link to a directory outside the TMPDIR. A socket bound under it + // is created outside, and its bound path still starts with the private directory. + let t = Scratch::new("escape"); + let private = t.0.join("priv"); + let outside = t.0.join("outside"); + std::fs::create_dir_all(&private).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, private.join("sub")).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let sock = private.join("sub/s.sock"); + let (_l, _) = bind(&sock); assert!( - !ok(&format!("{PRIV}x/s")), - "a sibling that shares the prefix" + outside.join("s.sock").exists(), + "the socket was made outside" ); - assert!(!ok(&format!("{PRIV}/../s"))); - assert!(!ok(&format!("{PRIV}/a/../../s"))); - assert!(!ok(&format!("{PRIV}/./s"))); - assert!(!ok(&format!("{PRIV}//s"))); - assert!(!ok("@abstract")); - assert!(!ok("")); - assert!(!ok("/tmp/s")); - assert!(!ok("run/user/1000/oab-pw-1a2b3c4d/s")); + assert!(!inside_resolved(&s(&sock), &real)); +} + +#[test] +fn a_sibling_that_shares_the_name_prefix_is_outside() { + let t = Scratch::new("sibling"); + let private = t.0.join("priv"); + let sibling = t.0.join("privx"); + std::fs::create_dir_all(&private).unwrap(); + std::fs::create_dir_all(&sibling).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let sock = sibling.join("s.sock"); + let (_l, _) = bind(&sock); + assert!(!inside_resolved(&s(&sock), &real)); +} + +#[test] +fn a_socket_elsewhere_and_a_relative_path_are_outside() { + let t = Scratch::new("elsewhere"); + let private = t.0.join("priv"); + std::fs::create_dir_all(&private).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let sock = t.0.join("other.sock"); + let (_l, _) = bind(&sock); + assert!(!inside_resolved(&s(&sock), &real)); + assert!(!inside_resolved("s.sock", &real), "relative"); + assert!(!inside_resolved("@abstract", &real), "abstract name"); + assert!(!inside_resolved("", &real)); +} + +#[test] +fn a_socket_unlinked_after_the_bind_is_outside() { + let t = Scratch::new("gone"); + let private = t.0.join("priv"); + std::fs::create_dir_all(&private).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let sock = private.join("gone.sock"); + let (_l, _) = bind(&sock); + std::fs::remove_file(&sock).unwrap(); + assert!(!inside_resolved(&s(&sock), &real)); } #[test] fn v2_unix_listeners_inside_the_private_directory_pass() { - let rows = format!( - "0: 2 0 00010000 0001 01 41 {PRIV}/pw-ab/browser/b.sock\n1: 2 0 00010000 0001 01 42 {PRIV}/org.chromium.Chromium.x/SingletonSocket\n" - ); - let src = unix_src(&rows); - let all: HashSet = [41, 42].into(); - let l = listeners_among_in(&src, &all, Some(PRIV)).unwrap(); + let t = Scratch::new("v2in"); + let private = t.0.join("priv"); + std::fs::create_dir_all(private.join("pw-ab/browser")).unwrap(); + std::fs::create_dir_all(private.join("org.chromium.Chromium.x")).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let a = private.join("pw-ab/browser/b.sock"); + let b = private.join("org.chromium.Chromium.x/SingletonSocket"); + let (_la, ia) = bind(&a); + let (_lb, ib) = bind(&b); + let src = unix_src(&unix_rows(&[(ia, s(&a)), (ib, s(&b))])); + let all: HashSet = [ia, ib].into(); + let l = listeners_among_in(&src, &all, Some(&real)).unwrap(); assert_eq!((l.tcp, l.udp, l.unix, l.unix_outside), (0, 0, 2, 0)); assert!(l.passes_v2()); } #[test] fn v2_a_unix_listener_outside_the_private_directory_fails() { - let rows = format!( - "0: 2 0 00010000 0001 01 41 {PRIV}/pw-ab/b.sock\n1: 2 0 00010000 0001 01 42 /tmp/elsewhere.sock\n2: 2 0 00010000 0001 01 43 @abstract\n3: 2 0 00010000 0001 01 44\n" - ); - let src = unix_src(&rows); - let all: HashSet = [41, 42, 43, 44].into(); - let l = listeners_among_in(&src, &all, Some(PRIV)).unwrap(); - assert_eq!((l.unix, l.unix_outside), (4, 3)); + let t = Scratch::new("v2out"); + let private = t.0.join("priv"); + std::fs::create_dir_all(&private).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let a = private.join("b.sock"); + let other = t.0.join("elsewhere.sock"); + let (_la, ia) = bind(&a); + let (_lo, io) = bind(&other); + let src = unix_src(&unix_rows(&[(ia, s(&a)), (io, s(&other))])); + let all: HashSet = [ia, io].into(); + let l = listeners_among_in(&src, &all, Some(&real)).unwrap(); + assert_eq!((l.unix, l.unix_outside), (2, 1)); assert!(!l.passes_v2()); - // One that belongs to another process is not counted at all. - let only: HashSet = [41].into(); - assert!(listeners_among_in(&src, &only, Some(PRIV)) + // The inside one alone passes: only listeners of this tree are counted. + let only: HashSet = [ia].into(); + assert!(listeners_among_in(&src, &only, Some(&real)) .unwrap() .passes_v2()); } +#[test] +fn v2_a_socket_unlinked_after_the_bind_counts_as_outside() { + let t = Scratch::new("v2gone"); + let private = t.0.join("priv"); + std::fs::create_dir_all(&private).unwrap(); + let real = std::fs::canonicalize(&private).unwrap(); + let gone = private.join("gone.sock"); + let (_l, ino) = bind(&gone); + std::fs::remove_file(&gone).unwrap(); + let src = unix_src(&unix_rows(&[(ino, s(&gone) + " (deleted)")])); + let all: HashSet = [ino].into(); + let l = listeners_among_in(&src, &all, Some(&real)).unwrap(); + assert_eq!((l.unix, l.unix_outside), (1, 1)); + assert!(!l.passes_v2()); +} + #[test] fn v2_without_a_verified_private_directory_every_unix_listener_is_outside() { - let rows = format!("0: 2 0 00010000 0001 01 41 {PRIV}/pw-ab/b.sock\n"); - let src = unix_src(&rows); - let all: HashSet = [41].into(); + let t = Scratch::new("v2none"); + let private = t.0.join("priv"); + std::fs::create_dir_all(&private).unwrap(); + let a = private.join("b.sock"); + let (_l, ia) = bind(&a); + let src = unix_src(&unix_rows(&[(ia, s(&a))])); + let all: HashSet = [ia].into(); let l = listeners_among_in(&src, &all, None).unwrap(); assert_eq!((l.unix, l.unix_outside), (1, 1)); assert!(!l.passes_v2()); @@ -405,7 +547,7 @@ fn v2_any_tcp_or_udp_listener_fails_even_with_the_private_directory() { .collect(), ); let all: HashSet = [12345].into(); - let l = listeners_among_in(&src, &all, Some(PRIV)).unwrap(); + let l = listeners_among_in(&src, &all, Some(std::path::Path::new(PRIV))).unwrap(); assert_eq!(l.tcp, 1); assert!(!l.passes_v2()); } @@ -476,27 +618,3 @@ mod tmp_dir { ); } } - -#[test] -fn a_link_between_the_private_directory_and_the_socket_is_not_plain() { - use std::os::unix::fs::symlink; - let base = std::env::temp_dir().join(format!("oab-plain-{}", std::process::id())); - let private = base.join("priv"); - let outside = base.join("outside"); - std::fs::create_dir_all(private.join("real")).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - symlink(&outside, private.join("link")).unwrap(); - let p = private.to_str().unwrap(); - assert!(plain_parents(&format!("{p}/s"), p)); - assert!(plain_parents(&format!("{p}/real/s"), p)); - assert!( - !plain_parents(&format!("{p}/link/s"), p), - "symlinked parent" - ); - assert!( - !plain_parents(&format!("{p}/missing/s"), p), - "unreadable parent" - ); - assert!(!plain_parents("/elsewhere/s", p)); - std::fs::remove_dir_all(&base).unwrap(); -} From 30f1fe6a6935f13c31e785881bc8e8fb0cac89a4 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:42:37 -0500 Subject: [PATCH 05/18] fix: sweep failure refuses a CLI launch; legacy listener errors are unknown (round-1 items 9a, 9b) 9a: Supervised::launch discarded a sweep error with .ok() and started the CLI child anyway. It now maps the result like Supervisor::start (#132): a held guard proceeds, a busy sweep is refused with sweep_busy, any other sweep error with sweep_unavailable. The wait is Supervised::with_sweep_wait (test only; the production default stays 10 s). 9b: legacy.rs listener(): only a missing tcp6 table (NotFound) means no IPv6. Any other error on tcp6 is unknown. The fixture in legacy_tests.rs returns NotFound for an absent table, as the real /proc does. Finding 2, Rust side: legacy_tests.rs tests that a single-quoted, double-quoted or bare MCP_UPSTREAM assignment is detected, and that comments and UnsetEnvironment= are not. Tests: sigstop_tests.rs a_cli_launch_that_cannot_get_the_sweep_lock_is_refused_and_spawns_nothing (a held lock; the launch would run touch; the marker must not exist). legacy_tests.rs an_unreadable_ipv6_table_is_unknown_and_only_a_missing_one_is_none; a_real_directory_holding_a_link_counts_only_the_link (round-1 F6 nested link). Commands and results: - cargo test --release on a Debian 13 arm64 node: 553 passed, 0 failed (includes the tests above) - cargo clippy --release -- -D warnings after gating with_sweep_wait behind #[cfg(test)] (the production build had flagged it as dead code): clean - cargo fmt --check on the same node: clean --- poc/reverse-attach-linux/src/legacy.rs | 6 +- poc/reverse-attach-linux/src/legacy_tests.rs | 61 ++++++++++++++++++- poc/reverse-attach-linux/src/sigstop.rs | 25 +++++--- poc/reverse-attach-linux/src/sigstop_tests.rs | 31 ++++++++++ 4 files changed, 113 insertions(+), 10 deletions(-) diff --git a/poc/reverse-attach-linux/src/legacy.rs b/poc/reverse-attach-linux/src/legacy.rs index 031052e..2ebd427 100644 --- a/poc/reverse-attach-linux/src/legacy.rs +++ b/poc/reverse-attach-linux/src/legacy.rs @@ -287,8 +287,10 @@ fn listener(src: &dyn Source) -> String { .iter() .any(|r| r.state == 0x0A && r.local.port() == LEGACY_PORT); } - Err(_) if required => return "unknown".into(), - Err(_) => {} + // Only a table that does not exist (no IPv6 on this host) is a clean absence. Any other + // error means the listener is unknown, never none. + Err(e) if !required && e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return "unknown".into(), } } if hit { diff --git a/poc/reverse-attach-linux/src/legacy_tests.rs b/poc/reverse-attach-linux/src/legacy_tests.rs index 9f772c9..af53c09 100644 --- a/poc/reverse-attach-linux/src/legacy_tests.rs +++ b/poc/reverse-attach-linux/src/legacy_tests.rs @@ -11,7 +11,7 @@ impl Source for Tables { self.0 .get(name) .cloned() - .ok_or_else(|| std::io::Error::other("none")) + .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound)) } } @@ -414,3 +414,62 @@ fn everything_present_is_listed_and_nothing_on_disk_changes() { .bytes() .all(|b| b.is_ascii_alphanumeric() || b" ~/.:_,-".contains(&b))); } + +/// A table that is readable for `tcp` and fails for every other name with a permission error. +struct Denied; + +impl Source for Denied { + fn table(&self, name: &str) -> std::io::Result { + match name { + "tcp" => Ok(HEAD.to_string()), + _ => Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)), + } + } +} + +#[test] +fn an_unreadable_ipv6_table_is_unknown_and_only_a_missing_one_is_none() { + let t = TempDir::new(); + let h = home(&t); + assert_eq!(gather(Some(&h), &Denied).listener, "unknown"); + assert!( + !gather(Some(&h), &Denied).present(), + "unknown is not a finding" + ); + let only4 = Tables(HashMap::from([("tcp", HEAD.to_string())])); + assert_eq!(gather(Some(&h), &only4).listener, "none"); +} + +#[test] +fn a_real_directory_holding_a_link_counts_only_the_link() { + let t = TempDir::new(); + let big = t.path.join("big"); + fs::create_dir_all(&big).unwrap(); + fs::write(big.join("f"), vec![0u8; 5 * 1024 * 1024]).unwrap(); + let d = t.path.join("real"); + fs::create_dir_all(&d).unwrap(); + symlink(&big, d.join("inner")).unwrap(); + let n = dir_size(&d).unwrap(); + assert!(n < 1024, "only the link's own length is counted, got {n}"); +} + +#[test] +fn a_single_quoted_or_double_quoted_or_bare_assignment_of_mcp_upstream_counts() { + // systemd accepts all three forms; the cutover guide's grep matches the same three. + use super::sets_upstream as set; + assert!(set( + "Environment='MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp'" + )); + assert!(set( + "Environment=\"MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp\"" + )); + assert!(set( + "Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + )); + assert!(!set( + "# Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + )); + assert!(!set( + "UnsetEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + )); +} diff --git a/poc/reverse-attach-linux/src/sigstop.rs b/poc/reverse-attach-linux/src/sigstop.rs index 4c84358..b434249 100644 --- a/poc/reverse-attach-linux/src/sigstop.rs +++ b/poc/reverse-attach-linux/src/sigstop.rs @@ -159,6 +159,7 @@ impl Launcher for Plain { pub struct Supervised { avail: Arc, runtime_max: Duration, + sweep_wait: Duration, } impl Supervised { @@ -166,9 +167,18 @@ impl Supervised { Supervised { avail: Arc::new(Availability::new(mech)), runtime_max: CLI_RUNTIME_MAX, + sweep_wait: Duration::from_secs(10), } } + /// How long a start waits for another start's sweep lock before it is refused (`sweep_busy`). + /// The production wait is the 10 s default; the test shortens it. + #[cfg(test)] + pub fn with_sweep_wait(mut self, d: Duration) -> Supervised { + self.sweep_wait = d; + self + } + /// A longer (or shorter) bound on the unit's life than the health check's. pub fn with_runtime_max(mut self, d: Duration) -> Supervised { self.runtime_max = d; @@ -183,13 +193,14 @@ impl Launcher for Supervised { // and keeps the sweep lock until this child's record is written, so a second start cannot // kill the new child while no record claims it. `.install.lock` is not taken here: `install` // and `update` call this launcher while holding it exclusively, in this same process. - let sweep_guard = crate::sweep::sweep_holding( - root, - &|u| mech.stop_unit(u), - std::time::Duration::from_secs(10), - ) - .ok() - .and_then(|(_, guard)| guard); + // Fail closed, as `Supervisor::start` does (#132): a start that did not sweep and holds no + // guard is refused, so no CLI child runs that neither the lock nor a record protects. + let sweep_guard = + match crate::sweep::sweep_holding(root, &|u| mech.stop_unit(u), self.sweep_wait) { + Ok((_, Some(guard))) => guard, + Ok((_, None)) => return Err(std::io::Error::other("sweep_busy")), + Err(_) => return Err(std::io::Error::other("sweep_unavailable")), + }; let Ok(mode) = self.avail.get() else { eprintln!("browser: cli_child containment=none"); return Plain.launch(root, spec, scope); diff --git a/poc/reverse-attach-linux/src/sigstop_tests.rs b/poc/reverse-attach-linux/src/sigstop_tests.rs index f43482c..ee109f9 100644 --- a/poc/reverse-attach-linux/src/sigstop_tests.rs +++ b/poc/reverse-attach-linux/src/sigstop_tests.rs @@ -409,3 +409,34 @@ fn sigkill_of_a_cli_leaves_its_unit_and_the_next_starts_sweep_stops_it() { ); assert_eq!(units_left(), 0); } + +#[cfg(target_os = "linux")] +#[test] +fn a_cli_launch_that_cannot_get_the_sweep_lock_is_refused_and_spawns_nothing() { + // A busy sweep lock is a refusal of the launch (as in `Supervisor::start`), not a start that + // goes on unswept. The launch would run `touch`, so a marker file shows whether it started. + let t = TempDir::new(); + let root = t.root(); + let held = crate::state::open_named_lock(&root, crate::state::SWEEP_LOCK_NAME).unwrap(); + rustix::fs::flock(&held, rustix::fs::FlockOperation::NonBlockingLockExclusive).unwrap(); + let marker = t.path.join("spawned"); + let spec = crate::proc::Spec { + exe: std::path::PathBuf::from("/bin/sh"), + args: vec![ + "-c".into(), + format!("touch '{}'; sleep 30", marker.display()), + ], + env: vec![], + cwd: t.path.clone(), + }; + let sup = Supervised::new(Arc::new(Direct::new(Ok(SYSTEMD)))) + .with_sweep_wait(Duration::from_millis(100)); + let err = sup + .launch(&root, &spec, &t.path) + .err() + .expect("the launch is refused"); + assert_eq!(err.to_string(), "sweep_busy"); + std::thread::sleep(Duration::from_millis(300)); + assert!(!marker.exists(), "a child was started without a sweep"); + drop(held); +} From 2c706ad2f06cce3569d1ccb11bbff497ddba2a47 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:42:55 -0500 Subject: [PATCH 06/18] docs: release smoke dispatch is post-merge; V2 and D7 wording; root actions (findings 4, 8) Finding 8: docs/releasing.md states that this change does not dispatch linux-release-smoke.yml. The dispatch is a post-merge step on the release candidate, and the record gate is what blocks a release until then. Finding 4: docs/releasing.md states that the Debian 12 container install runs as a non-root user, that its root actions run as root inside the throwaway container, and that the image has no sudo. Record rule: docs/releasing.md says every V1 to V13 row needs pass, not only the blocking ones. V2 wording (requirement R1.1, ADR security notes, linux-setup.md, the daemon README): a Unix listener is inside only when its directory, with every link followed, is the private TMPDIR. The owner decisions (V2 option 1, D7 option 1) are unchanged. Commands and results: - markdownlint-cli2 "docs/**/*.md" on a Debian 13 arm64 node: the branch adds no finding beyond main's MD060 set (main has 324 MD060 findings; this branch the same plus none from this commit after fixing the two it introduced) - scripts/check-no-private-identifiers.sh on the laptop: ok, no private identifiers in 300 files - bash scripts/test-cutover-guide.sh and scripts/test-release-smoke-linux.sh: see the earlier commits --- docs/adr/linux-browser-tier.md | 2 +- docs/linux-setup.md | 2 +- docs/releasing.md | 28 +++++++++++++++++-------- docs/requirements/linux-browser-tier.md | 2 +- poc/reverse-attach-linux/README.md | 2 +- 5 files changed, 23 insertions(+), 13 deletions(-) diff --git a/docs/adr/linux-browser-tier.md b/docs/adr/linux-browser-tier.md index 9b3e03f..f4652e8 100644 --- a/docs/adr/linux-browser-tier.md +++ b/docs/adr/linux-browser-tier.md @@ -483,7 +483,7 @@ Rejected: - **No TCP or UDP listener.** The managed tree opens no TCP or UDP port. Two private Unix listening sockets remain in its `0700` `TMPDIR`; V2 is decided: they are accepted under the rule - "inside the child's private per-run `0700` `TMPDIR`, owned by the daemon's uid", and nothing else is. + "inside the child's private per-run `0700` `TMPDIR`, owned by the daemon's uid", and nothing else is. Inside is judged on the resolved path of the socket's directory, so a link that leads outside the directory does not count. Measured on a Debian 13 arm64 node: neither socket can be removed (Playwright binds the first on every start path, Chromium aborts without the second, and the DevTools transport is already a pipe). Another local user gets `EACCES` on both, and a web page cannot reach a Unix socket path. The residual diff --git a/docs/linux-setup.md b/docs/linux-setup.md index 3af10b4..5fa135c 100644 --- a/docs/linux-setup.md +++ b/docs/linux-setup.md @@ -354,7 +354,7 @@ directory. They are not TCP or UDP ports, but they are listeners: another proces can connect to them and drive the managed browser, so the claim "no socket of any kind" is not made. The rule (V2, decided in the ADR and requirement R1.1): no TCP or UDP listener, and every Unix listener inside that private directory, which must be a real directory of the daemon's uid with mode exactly -`0700`. `browser status` shows `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass` +`0700`. A socket counts as inside only when its directory, with every link followed, is that directory. `browser status` shows `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass` while the browser runs, and `result=fail` for anything else (run it in the daemon's user session, so `XDG_RUNTIME_DIR` matches the daemon's). While `browser signin` holds the browser, `status` counts that tree's Unix sockets, which sit in another temporary directory, as `unix_outside>0 result=fail`. This is a false alarm that fails diff --git a/docs/releasing.md b/docs/releasing.md index cb21ff8..30ee016 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -262,7 +262,10 @@ check `systemctl --user is-system-running` before they start. Unlike the optiona `kernel.apparmor_restrict_unprivileged_userns=0` and the log says so. That is a property of the ephemeral runner, not advice for hosts. The Debian 12 job also runs its container with `seccomp=unconfined` and `apparmor=unconfined`, for the same reason (Chromium's sandbox needs a user -namespace), and its log says so. The binary under test is built on the runner and is the one that runs +namespace), and its log says so. Inside that container the install runs as a non-root user, and the +root actions it needs (apt packages from `browser preflight --root-actions`) run as root. The image has +no `sudo`, so the container path never calls it: `root_command` removes a leading "sudo" followed by a space and runs the +line as root, and the host-side `sudo sysctl` line runs before the container starts. The binary under test is built on the runner and is the one that runs on Debian 12, so the job also shows that it runs on glibc 2.36. The release tarballs are built on `ubuntu-24.04` (amd64) and `ubuntu-24.04-arm` (arm64), the same images as the 24.04 smoke cells, so those cells test the same toolchain and glibc as the shipped binaries. @@ -302,8 +305,12 @@ Both are decided. Neither was decided by this workflow, and neither gate is weak holds two such sockets (Playwright's browser socket and Chromium's `SingletonSocket`). `GATE V2` fails on any TCP or UDP listener, on any Unix listener outside that directory, on a `TMPDIR` that is not mode `0700` or not the daemon's uid, and on a listener table that cannot be read, and it has no - other allow-list. The gate is blocking and is measured by every release on both architectures; it is - closed for a release only when both cells print `GATE V2 pass`. + other allow-list. A Unix listener counts as inside only when its directory resolves (every link + followed) to that `TMPDIR`; a socket reached through a link that leads elsewhere is outside. A real + cell passes V2 only with `NAVIGATE ok` and `SNAPSHOT_HAS_TEXT true` in its log, so `listeners=none` + alone never passes. The gate is blocking and is measured by every release on both architectures; it + is closed for a release only when both cells print `GATE V2 pass`, and the cells have not been + dispatched for this change (see the checklist). - **D7: the AppArmor profile.** The single path-scoped glob profile that `browser preflight` prints is kept as built; the residual risk (code running as the same user can place a file named `chrome` under the data path and run it with `userns` allowed) is written in the ADR and in `linux-setup.md`. @@ -312,7 +319,8 @@ Both are decided. Neither was decided by this workflow, and neither gate is weak `scripts/check-release-record.sh` still fails a record whose `V2` or `D7` row is missing or says `open, owner decision pending`: a row that reopens the decision blocks the release. It also fails a -record in which a blocking gate row (V1, V2, V7) is not `pass`. These three accept no `n/a`; put a reason in the Evidence cell. +record in which any of V1 to V13 is not `pass`. `n/a`, `fail` and an empty cell all block; the +Blocking column does not relax this. ### The per-release manual record @@ -324,10 +332,10 @@ the blocking column, and the support-table rows to update. Every unfilled cell i The `record` job fails a release when the file is missing, when any table row still has `PENDING`, when the `V2` or `D7` row is missing or still says `open, owner decision pending`, when any of V1 to V13 -is missing, duplicated or not four cells wide, or when V1, V2 or V7 is not `pass` (another blocking row -needs `pass` or `n/a, reason`), or when any of M1 to M10 or any of the six smoke cells is missing, duplicated or malformed, or has a -result other than `pass` (case does not matter; ADR D16 makes these a per-release requirement, so `n/a` is refused). It never fills a -row for anyone. On a dispatch it reports and passes. The requirements ask for "a release requirement" +is missing, duplicated or not four cells wide, or has a result other than `pass`, or when any of M1 to M10 +or any of the six smoke cells is missing, duplicated or malformed, or has a result other than `pass` +(case does not matter; ADR D16 makes these a per-release requirement, so `n/a` is refused everywhere). +It never fills a row for anyone. On a dispatch it reports and passes. The requirements ask for "a release requirement" and "a person records each result"; this file and this check are how that becomes verifiable. ### Linux release checklist @@ -336,7 +344,9 @@ Before tagging a release that contains the managed Linux tier: 1. `python3 scripts/playwright-pins.py verify --offline` and `scripts/test-release-smoke-linux.sh` pass locally or in CI. -2. Dispatch `linux-release-smoke.yml` on the release candidate and read every `GATE` line. All of +2. **Post-merge step, not part of the change that adds this checklist.** That change does not dispatch + `linux-release-smoke.yml`. After it is merged, dispatch the workflow on the release candidate and read + every `GATE` line. All of `pins`, the four cells and the two Debian 12 jobs are green, including `GATE V2 pass` on amd64 and arm64. 3. Copy `docs/release-records/TEMPLATE.md` to `docs/release-records/linux-VERSION.md`, run the manual diff --git a/docs/requirements/linux-browser-tier.md b/docs/requirements/linux-browser-tier.md index 3882a96..c9c1cea 100644 --- a/docs/requirements/linux-browser-tier.md +++ b/docs/requirements/linux-browser-tier.md @@ -15,7 +15,7 @@ ### R1. Managed child - R1.1 `@playwright/mcp` runs as a stdio child of the daemon. No TCP or UDP listener exists in the - managed tree. Port 8794 is not used by the managed path. **Decided (V2):** any Unix listener in the managed tree is inside the child's private per-run `0700` `TMPDIR`, owned by the daemon's uid. The + managed tree. Port 8794 is not used by the managed path. **Decided (V2):** any Unix listener in the managed tree is inside the child's private per-run `0700` `TMPDIR`, owned by the daemon's uid. Inside is judged on the resolved path of the socket's directory: a link that leads outside that directory does not make a socket inside. The Playwright browser socket and Chromium's `SingletonSocket` are the two expected ones. `browser status` and the release smoke fail on a TCP or UDP listener, on a Unix listener outside that directory, and on a `TMPDIR` that is not mode `0700` or not the daemon's. A process of the same user can still connect to those sockets and drive the managed browser, including its signed-in profile; that user can already read the profile directory, so this adds a second control path and no data access. Another local user is refused (the `0700` directory and the socket file mode; `EACCES` in a measurement), and a web page cannot reach a Unix socket path. diff --git a/poc/reverse-attach-linux/README.md b/poc/reverse-attach-linux/README.md index 057f1d7..fa37222 100644 --- a/poc/reverse-attach-linux/README.md +++ b/poc/reverse-attach-linux/README.md @@ -296,7 +296,7 @@ is outside this control. V2 (decided): the managed tree opens no TCP or UDP socket, and holds two listening Unix sockets inside its private `0700` `TMPDIR` (Playwright's browser socket and Chromium's `SingletonSocket`). The rule: any Unix listener must be inside that directory, which must be a real directory of the daemon's uid with mode -exactly `0700`. `browser status` reports `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok +exactly `0700`. Inside is judged on the resolved path of the socket's directory, so a link that leads outside does not count. `browser status` reports `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass`, or `result=fail` for a TCP or UDP listener, a Unix listener outside the directory or a directory that is not `0700` or not the daemon's (`tmpdir=mode|owner|missing|not_dir|unreadable`). The release smoke recomputes it on both architectures. From 717bd6c9557ddee14b8148555fed7e9e20c8fff7 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:33:28 -0500 Subject: [PATCH 07/18] fix: reject bare-id release rows; browser status exits 1 on a V2 failure (review round 2) - check-release-record.sh: an M row whose id cell is only "M1", and a V row whose id is unpadded ("|V1|"), were not recognised, so a non-pass duplicate passed. The id is now matched as a whole token. Tests added to test-release-smoke-linux.sh: M1 bare-id duplicate with result fail, M1 bare-id duplicate with an empty result, M1 result empty, V1 unpadded-id duplicate with result fail. - browser status exits 1 when the listeners field is result=fail or unknown (review MEDIUM). Test: status_fails_on_a_v2_failure_or_an_unreadable_listener_table. When XDG_RUNTIME_DIR is unset in the calling shell, stderr says the result may be a false fail (review LOW). - docs/linux-cutover.md: the MCP_UPSTREAM drop-in is identified by its content, not by its provenance, and a hand-written file of that shape is removed too (review LOW). Step 6 documents the status exit code. - test-cutover-guide.sh and test-release-smoke-linux.sh: no ShellCheck findings (SC2012, SC2015, SC2016, SC2319), as CI runs them. Verification, commands and results: - Debian 13 arm64 node (copy of the worktree in a scratch directory): cargo fmt --check: ok. cargo clippy --release -- -D warnings: ok. cargo test --release: 554 passed, 0 failed, 17 ignored (the systemd-gated tests, which the linux-systemd workflow runs). bash scripts/test-release-smoke-linux.sh: pass=274 fail=0. bash scripts/test-cutover-guide.sh: pass=20 fail=0. bash scripts/test-install-linux.sh, test-name-consistency.sh, test-legacy-agent.sh, test-pw-mcp-deprecated.sh, test-check-no-private-identifiers.sh: exit 0 each. - macOS arm64 node (copy of the worktree in a scratch directory): cargo fmt --check: ok. cargo clippy --release -- -D warnings: ok. cargo test --release: does not link. The prctl declaration in src/platform/linux/seat.rs is unconditional and is also on origin/main, so this predates this change. Not fixed here. ShellCheck over the CI file list: exit 0. npx markdownlint-cli2@0.18.1 "docs/**/*.md": 0 errors. - Bypass mutations, before and after: the matrix run against the checker from the previous commit accepts the three bare-id bypasses (exit 0). Against this commit every bypass is rejected (exit 1). - scripts/check-no-private-identifiers.sh: ok, 301 files. --- docs/linux-cutover.md | 11 +++++-- poc/reverse-attach-linux/src/browser_cli.rs | 18 +++++++++++ .../src/browser_cli_tests.rs | 27 ++++++++++++++++ poc/reverse-attach-linux/src/probe.rs | 6 ++++ scripts/check-release-record.sh | 4 +-- scripts/test-cutover-guide.sh | 32 +++++++++++-------- scripts/test-release-smoke-linux.sh | 15 +++++++-- 7 files changed, 92 insertions(+), 21 deletions(-) diff --git a/docs/linux-cutover.md b/docs/linux-cutover.md index 48aad44..20611b4 100644 --- a/docs/linux-cutover.md +++ b/docs/linux-cutover.md @@ -302,7 +302,9 @@ Comments, `UnsetEnvironment=` and other variables are not matched. For each file and decide: - It holds only `[Service]`, that one `Environment=MCP_UPSTREAM=` line, comments and blank lines: it is - the dedicated drop-in. The block below removes it. + the dedicated drop-in. The block below removes it. The file is identified by its content, not by who + wrote it: no installer in this repository writes an `MCP_UPSTREAM` drop-in, so a hand-written file of + the same shape is removed too. - It holds any other setting: keep the file and delete only the line, `sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp$/d' FILE`. If the line has another form (several variables, another URL), edit it by hand and keep everything else. @@ -425,7 +427,9 @@ ss -ltnH 'sport = :8794' | wc -l - `browser status` shows `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass` while the browser runs (`none` before its first start). Anything with `result=fail` is a failure (V2): a TCP or UDP listener, a Unix listener outside the child's private directory, or that directory not being - `0700` or not yours. Run `status` in the daemon's own login session so `XDG_RUNTIME_DIR` matches. + `0700` or not yours. `browser status` then exits `1`, so a script can test it. Run `status` in the + daemon's own login session so `XDG_RUNTIME_DIR` matches; without it a healthy host can report a false + `result=fail`, and `status` says so on stderr. From the first release containing L5, `legacy_listener: none`. - End your login session and log in again, or reboot. Then `systemctl --user is-enabled oab-computer-pw-mcp.service` (host A; hosts B to D: `oab-pw-mcp.service`) prints `disabled` and the `ss` check still prints `0`. With linger on, the daemon survives the logout. @@ -561,7 +565,8 @@ the same list, in order: 1. Disable and delete the old unit files, then reload. No root. Step 5.2 owns the drop-in: it already removed the dedicated drop-in file, or only the `MCP_UPSTREAM` line from a shared one, and the - backup from step 1 keeps the original for the rollback. If you skipped the drop-in part of step 5.2, run + backup from step 1 keeps the original for the rollback. As step 5.2 says, the block identifies a + drop-in by its content, so a hand-written file of the same shape is removed too. If you skipped the drop-in part of step 5.2, run the same block from step 5.2 first (indented here), then the `daemon-reload` below: ```sh diff --git a/poc/reverse-attach-linux/src/browser_cli.rs b/poc/reverse-attach-linux/src/browser_cli.rs index fbace7f..9cc64f2 100644 --- a/poc/reverse-attach-linux/src/browser_cli.rs +++ b/poc/reverse-attach-linux/src/browser_cli.rs @@ -123,6 +123,17 @@ fn one_line(s: &str) -> String { .collect() } +/// The line added to a failed `browser status` when this shell has no `XDG_RUNTIME_DIR`. `expected_path` +/// then looks for the private directory under `/tmp`, while the daemon uses its own runtime dir, so a +/// failure can be a false one. +fn xdg_hint(xdg_set: bool) -> Option<&'static str> { + if xdg_set { + None + } else { + Some("XDG_RUNTIME_DIR is not set in this shell: the private TMPDIR was looked up under /tmp, so this may be a false fail. Run status with the daemon's XDG_RUNTIME_DIR (see docs/linux-cutover.md, step 6).") + } +} + fn hint(class: &str) -> Option<&'static str> { Some(match class { "use_update" => "a different version is installed; run `oab-computer browser update`", @@ -278,6 +289,13 @@ pub fn execute( io.say(&l); } } + if s.extras.listeners_blocks() { + let _ = writeln!(io.err, "browser: status_failed class=listeners"); + if let Some(h) = xdg_hint(std::env::var_os("XDG_RUNTIME_DIR").is_some()) { + let _ = writeln!(io.err, "{h}"); + } + return 1; + } 0 } Err(f) => fail(io, "status", f), diff --git a/poc/reverse-attach-linux/src/browser_cli_tests.rs b/poc/reverse-attach-linux/src/browser_cli_tests.rs index a319a8d..595d1a1 100644 --- a/poc/reverse-attach-linux/src/browser_cli_tests.rs +++ b/poc/reverse-attach-linux/src/browser_cli_tests.rs @@ -430,6 +430,33 @@ fn failures_print_one_fixed_line_and_a_hint_and_nothing_else() { assert!(r.out.contains("foreign_install")); } +#[test] +fn status_fails_on_a_v2_failure_or_an_unreadable_listener_table() { + let mut x = crate::probe::Extras::none(); + for (word, blocks) in [ + ("none", false), + ("not_running", false), + ( + "tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass", + false, + ), + ( + "tcp=0 udp=0 unix=2 unix_outside=1 tmpdir=ok result=fail", + true, + ), + ( + "tcp=1 udp=0 unix=0 unix_outside=0 tmpdir=ok result=fail", + true, + ), + ("unknown", true), + ] { + x.listeners = word.into(); + assert_eq!(x.listeners_blocks(), blocks, "{word}"); + } + assert!(xdg_hint(false).is_some_and(|h| h.contains("XDG_RUNTIME_DIR"))); + assert!(xdg_hint(true).is_none()); +} + #[test] fn an_unsupported_platform_is_reported() { let e = Env::new(Tw::default()); diff --git a/poc/reverse-attach-linux/src/probe.rs b/poc/reverse-attach-linux/src/probe.rs index ac97f5a..9691634 100644 --- a/poc/reverse-attach-linux/src/probe.rs +++ b/poc/reverse-attach-linux/src/probe.rs @@ -71,6 +71,12 @@ impl Extras { } } + /// `browser status` fails on this listeners field: a V2 `result=fail`, or `unknown` (a table that + /// could not be read). `none` and `not_running` are not failures. + pub fn listeners_blocks(&self) -> bool { + self.listeners == "unknown" || self.listeners.ends_with("result=fail") + } + /// Fills the three legacy fields (L5). pub fn set_legacy(&mut self, l: crate::legacy::Legacy) { self.legacy_units = l.units; diff --git a/scripts/check-release-record.sh b/scripts/check-release-record.sh index 4add87a..f3f87b7 100755 --- a/scripts/check-release-record.sh +++ b/scripts/check-release-record.sh @@ -60,7 +60,7 @@ else # check). Every one of them must read "pass" (lower-cased): the Blocking cell does not relax it. bad=$(printf '%s\n' "$rows" | awk -F'|' ' function trim(x) { gsub(/^[ \t]+|[ \t]+$/, "", x); return x } - $2 ~ /^ *V[0-9]+ / { + trim($2) ~ /^V[0-9]+( |$)/ { id = trim($2); sub(/ .*/, "", id) seen[id]++ if (NF != 6) { print id " (malformed row: " NF - 2 " cells, need 4; no \"|\" inside a cell)"; next } @@ -86,7 +86,7 @@ else } { id = trim($2) - if (id ~ /^M[0-9]+ /) { + if (id ~ /^M[0-9]+( |$)/) { sub(/ .*/, "", id); kind = "m"; need = 7 } else if (id in want) { kind = "c"; need = 5 diff --git a/scripts/test-cutover-guide.sh b/scripts/test-cutover-guide.sh index c074138..b66770f 100755 --- a/scripts/test-cutover-guide.sh +++ b/scripts/test-cutover-guide.sh @@ -24,16 +24,16 @@ awk -v dir="$T" ' /^ *```$/ && inb { inb = 0; close(f); next } inb { print > f } ' "$GUIDE" -blocks=$(ls "$T"/block*.sh 2>/dev/null | wc -l) -[ "$blocks" -gt 0 ] && ok "found $blocks sh blocks" || bad "no sh blocks found" +blocks=$(find "$T" -maxdepth 1 -name 'block*.sh' | wc -l | tr -d ' ') +if [ "$blocks" -gt 0 ]; then ok "found $blocks sh blocks"; else bad "no sh blocks found"; fi syntax_bad=0 for f in "$T"/block*.sh; do if ! bash -n "$f" 2>"$T/err"; then syntax_bad=$((syntax_bad + 1)); echo " syntax: $(basename "$f"): $(head -n 1 "$T/err")"; fi done -[ "$syntax_bad" -eq 0 ] && ok "every sh block parses (bash -n)" || bad "$syntax_bad sh block(s) do not parse" +if [ "$syntax_bad" -eq 0 ]; then ok "every sh block parses (bash -n)"; else bad "$syntax_bad sh block(s) do not parse"; fi # No `$OLD` notation, no `OLD=` assignment. -if grep -nE '\$OLD|OLD=' "$GUIDE" >"$T/old.txt"; then bad "the guide still uses the OLD notation: $(head -n 1 "$T/old.txt")"; else ok "no \$OLD or OLD= notation"; fi +if grep -nE '[$]OLD|OLD=' "$GUIDE" >"$T/old.txt"; then bad "the guide still uses the OLD notation: $(head -n 1 "$T/old.txt")"; else ok "no \$OLD or OLD= notation"; fi # Literal oab-* unit names on systemctl lines. Allowed: the old unit of each host class, the daemon # unit, the instance-mcp unit of 0.11, and the browser wildcard the guide names. @@ -43,10 +43,11 @@ grep -h 'systemctl' "$GUIDE" | grep -oE "oab-[A-Za-z0-9*._-]+\.service" | sort - while IFS= read -r u; do case " $allowed " in *" $u "*) ;; *) unit_bad=$((unit_bad + 1)); echo " unexpected unit name: $u" ;; esac done <"$T/units.txt" -[ "$unit_bad" -eq 0 ] && ok "every literal unit name on a systemctl line is allowed ($(wc -l <"$T/units.txt" | tr -d ' ') distinct)" || bad "$unit_bad unexpected unit name(s)" +if [ "$unit_bad" -eq 0 ]; then ok "every literal unit name on a systemctl line is allowed ($(wc -l <"$T/units.txt" | tr -d ' ') distinct)"; else bad "$unit_bad unexpected unit name(s)"; fi # Step 5.4 rollback: it links to the Rollback section, and no line gives `browser remove` alone. -if grep -qE '^\*\*Roll back to here\.\*\* `browser remove`' "$GUIDE"; then bad "a rollback line says browser remove alone"; else ok "no rollback line says browser remove alone"; fi +bt='`' +if grep -qE "^[*][*]Roll back to here[.][*][*] ${bt}browser remove${bt}" "$GUIDE"; then bad "a rollback line says browser remove alone"; else ok "no rollback line says browser remove alone"; fi sec=$(sed -n '/^### 5\.4 /,/^## Step 6/p' "$GUIDE") case $sec in *"(#rollback)"*) ok "step 5.4 rollback links to the full Rollback section" ;; *) bad "step 5.4 does not link to #rollback" ;; esac @@ -90,13 +91,18 @@ re=${re//\\\"/\"} if [ -z "$re" ]; then bad "the guide's grep -nE pattern is not found" else - match() { printf '%s\n' "$1" | grep -qE "$re"; } - match "Environment='MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp'" && ok "grep: single-quoted assignment matches" || bad "grep: single-quoted assignment does not match" - match 'Environment="MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp"' && ok "grep: double-quoted assignment matches" || bad "grep: double-quoted assignment does not match" - match "Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" && ok "grep: bare assignment matches" || bad "grep: bare assignment does not match" - match "Environment=OAB_X=1 MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" && ok "grep: assignment after another setting matches" || bad "grep: later assignment does not match" - match "# Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" && bad "grep: a commented line matches" || ok "grep: a commented line does not match" - match "UnsetEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" && bad "grep: UnsetEnvironment= matches" || ok "grep: UnsetEnvironment= does not match" + # check NAME yes|no TEXT: the guide's pattern matches TEXT (yes) or does not (no). + check() { + local got=no + if printf '%s\n' "$3" | grep -qE "$re"; then got=yes; fi + if [ "$got" = "$2" ]; then ok "$1"; else bad "$1"; fi + } + check "grep: single-quoted assignment matches" yes "Environment='MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp'" + check "grep: double-quoted assignment matches" yes 'Environment="MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp"' + check "grep: bare assignment matches" yes "Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + check "grep: assignment after another setting matches" yes "Environment=OAB_X=1 MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + check "grep: a commented line does not match" no "# Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + check "grep: UnsetEnvironment= does not match" no "UnsetEnvironment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" fi echo "pass=$pass fail=$fail" diff --git a/scripts/test-release-smoke-linux.sh b/scripts/test-release-smoke-linux.sh index 62b7b93..8c2f909 100755 --- a/scripts/test-release-smoke-linux.sh +++ b/scripts/test-release-smoke-linux.sh @@ -55,9 +55,9 @@ gate_real_cell "$L/page.log" "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 t gate_real_cell "$L/page.log" "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=1 tmpdir=ok result=pass')" >/dev/null; expect "real cell: unix_outside=1 fails" 1 $? # root_command: the container runs as root with no sudo, so a leading sudo is removed. -[ "$(root_command 'sudo apt-get install -y libnss3')" = 'apt-get install -y libnss3' ]; expect "root_command strips a leading sudo" 0 $? -[ "$(root_command 'apt-get install -y libnss3')" = 'apt-get install -y libnss3' ]; expect "root_command leaves a line without sudo unchanged" 0 $? -[ "$(root_command 'echo sudo here')" = 'echo sudo here' ]; expect "root_command does not strip sudo mid-line" 0 $? +if [ "$(root_command 'sudo apt-get install -y libnss3')" = 'apt-get install -y libnss3' ]; then ok "root_command strips a leading sudo"; else bad "root_command strips a leading sudo"; fi +if [ "$(root_command 'apt-get install -y libnss3')" = 'apt-get install -y libnss3' ]; then ok "root_command leaves a line without sudo unchanged"; else bad "root_command leaves a line without sudo unchanged"; fi +if [ "$(root_command 'echo sudo here')" = 'echo sudo here' ]; then ok "root_command does not strip sudo mid-line"; else bad "root_command does not strip sudo mid-line"; fi # The container path (the in_container body, and the docker run in the workflow) names no sudo. body=$(sed -n '/^in_container() {/,/^}/p' "$here/release-smoke-linux.sh" | grep -v '^ *#') case $body in *sudo*) bad "in_container runs sudo" ;; *) ok "in_container body names no sudo" ;; esac @@ -156,6 +156,15 @@ for id in M1 M2 M3 M4 M5 M6 M7 M8 M9 M10; do reject "$id result FAIL (upper case)" "/^| $id /s#| pass |#| FAIL |#" reject "$id result PENDING" "/^| $id /s#| pass |#| PENDING |#" done +# A bare id (the cell is only "M1", with no description) is still that row: a non-pass duplicate of a +# valid M1 row, or an empty result, must be refused. +reject "M1 bare-id duplicate with result fail" "/^| M1 /a\\ +| M1 | fail | | | |" +reject "M1 bare-id duplicate with an empty result" "/^| M1 /a\\ +| M1 | | | | |" +reject "M1 result empty" "/^| M1 /s#| pass |#| |#" +reject "V1 unpadded-id duplicate with result fail" "/^| V1 /a\\ +|V1|fail|e|b|" for cell in "Ubuntu 22.04 amd64" "Ubuntu 22.04 arm64" "Ubuntu 24.04 amd64" "Ubuntu 24.04 arm64" "Debian 12 container amd64" "Debian 12 container arm64"; do reject "smoke cell '$cell' row deleted" "/^| $cell |/d" reject "smoke cell '$cell' row duplicated" "/^| $cell |/p" From 054016dd8597fb11318ecdfd7b2771da1b47bc6e Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:24:24 -0500 Subject: [PATCH 08/18] fix: quote a CI step name that stopped the CI workflow from starting The name of the cutover guide step contains ": ", which is not valid in an unquoted YAML value (.github/workflows/ci.yml, line 126). GitHub rejected the whole workflow file, so the CI run for the head had conclusion failure and no jobs. Verification, command and result: - Ruby YAML.load_file on each .github/workflows/*.yml, before: ci.yml failed with "mapping values are not allowed in this context at line 126"; after: ci.yml loads with 8 jobs, and the other seven workflow files load as before. --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c353df4..0918e95 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -123,7 +123,7 @@ jobs: # The pure parts of scripts/release-smoke-linux.sh and scripts/check-release-record.sh. The # smoke itself runs in .github/workflows/linux-release-smoke.yml (dispatch and release only). run: bash scripts/test-release-smoke-linux.sh - - name: Cutover guide: its shell blocks parse, its drop-in removal block and grep match the fixtures + - name: "Cutover guide: its shell blocks parse, its drop-in removal block and grep match the fixtures" # Runs the guide's own text against fixtures under a temporary HOME. Touches no unit or port. run: bash scripts/test-cutover-guide.sh - name: pw-mcp.sh is marked deprecated and still launches unchanged (D14) From 342709b8d25a277df40c03dec99cfe159c11654f Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:21:13 -0500 Subject: [PATCH 09/18] fix: a tree with no listener fails V2 when its TMPDIR is not private browser status printed `listeners=none` before it checked the TMPDIR, so a running tree with no listener and a 0755 or foreign-owned TMPDIR exited 0. The decided V2 rule fails that case. Now `none` is printed only when the TMPDIR is clean (the verified private directory, or no child running). Otherwise the counts are printed with `tmpdir= result=fail`, and browser status exits 1. Changes: - probe.rs: listeners_word judges the TMPDIR state for a zero-listener tree. - probe_tests.rs: a_zero_listener_tree_fails_v2_when_its_tmpdir_is_not_private. It fails on the pre-fix probe.rs (left "none", right "tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=mode result=fail") and passes after the fix. - test-release-smoke-linux.sh: two gate_v2 cases for the zero-listener mode and owner words. - release-smoke-linux.sh: gate_v2 comment states what `none` now guarantees. - linux-setup.md: XDG_RUNTIME_DIR caveat in the status section, and the zero-listener rule. The eight findings from the PR #170 reviews were re-checked on this head. Each has a test or a read-through noted below; no code change was needed for them. 1. check-release-record.sh: test-release-smoke-linux.sh rejects 224 bypass mutations of a copy of the valid record and accepts 2 valid cases (pass=276 fail=0). 2. Cutover guide: test-cutover-guide.sh passes; legacy_tests.rs covers the single-quoted Environment='MCP_UPSTREAM=...' form. 3. Socket check: procnet_tests.rs resolved-path cases (link out of the private directory, name prefix sibling, unlinked socket, relative path, abstract name). 4. Container job without sudo: root_command strips a leading sudo; docs/releasing.md says so. Read-through only, no automated test. 5. NAVIGATE required for V2: test-release-smoke-linux.sh gate_real_cell cases pass. 6. Drop-in removal: test-cutover-guide.sh dropin_case cases pass. 7. Rollback: test-cutover-guide.sh rejects a bare `browser remove` rollback line and checks the #rollback link. 8. Smoke dispatch is post-merge: documented in docs/releasing.md. Read-through only. Commands run and results: - Debian 13 arm64 node, poc/reverse-attach-linux: `cargo test --release` (the CI command): 555 passed, 0 failed, 17 ignored. - Debian 13 arm64 node: `cargo test` (debug): 553 passed, 2 failed. Both fail the same way on origin/main: proc::tests::a_pid_that_does_not_exist_signals_nothing_and_does_not_panic (a rustix debug_assert on a negative pid; release builds compile it out) and external::tests::paging::a_server_that_stops_reading_ends_the_request_by_the_deadline (timing). - Debian 13 arm64 node: test-install-linux.sh, test-name-consistency.sh, test-legacy-agent.sh, test-release-smoke-linux.sh, test-cutover-guide.sh, test-pw-mcp-deprecated.sh and test-check-no-private-identifiers.sh: all PASS. - Debian 13 arm64 node: shellcheck (shellcheck-py, installed in a scratch venv) on the 10 files in the CI ShellCheck step: clean. - macOS arm64 node: `cargo check --release --all-targets`: finished. `cargo test --release` does not link: undefined `_prctl` in platform/linux/seat.rs, because platform/mod.rs declares the linux module without a cfg. origin/main has the same code, and this change touches nothing under platform/. - scripts/check-no-private-identifiers.sh on the tree: clean. --- docs/linux-setup.md | 2 +- poc/reverse-attach-linux/src/probe.rs | 18 ++++++++++++--- poc/reverse-attach-linux/src/probe_tests.rs | 25 +++++++++++++++++++++ scripts/release-smoke-linux.sh | 14 +++++++----- scripts/test-release-smoke-linux.sh | 2 ++ 5 files changed, 51 insertions(+), 10 deletions(-) diff --git a/docs/linux-setup.md b/docs/linux-setup.md index 5fa135c..1fb15ce 100644 --- a/docs/linux-setup.md +++ b/docs/linux-setup.md @@ -356,7 +356,7 @@ The rule (V2, decided in the ADR and requirement R1.1): no TCP or UDP listener, inside that private directory, which must be a real directory of the daemon's uid with mode exactly `0700`. A socket counts as inside only when its directory, with every link followed, is that directory. `browser status` shows `listeners: tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass` while the browser runs, and `result=fail` for anything else (run it in the daemon's user session, so -`XDG_RUNTIME_DIR` matches the daemon's). While `browser signin` holds the browser, `status` counts that tree's +`XDG_RUNTIME_DIR` matches the daemon's). The TMPDIR path is derived from `XDG_RUNTIME_DIR` in the shell that runs `status`; a shell without it looks in another place and can report `tmpdir=missing` on a healthy host, which is why `status` prints a hint on stderr when it fails. A tree that listens on nothing prints `listeners: none` only when its TMPDIR is clean; a wrong TMPDIR with no listener prints the counts with `result=fail`. While `browser signin` holds the browser, `status` counts that tree's Unix sockets, which sit in another temporary directory, as `unix_outside>0 result=fail`. This is a false alarm that fails closed; close the sign-in window and run `status` again. Another local user is refused by the directory and the socket mode, and a web page cannot reach a Unix socket path. The release smoke measures the rule on amd64 diff --git a/poc/reverse-attach-linux/src/probe.rs b/poc/reverse-attach-linux/src/probe.rs index 9691634..c1c151a 100644 --- a/poc/reverse-attach-linux/src/probe.rs +++ b/poc/reverse-attach-linux/src/probe.rs @@ -109,15 +109,23 @@ fn tree_pids(root_abs: &Path) -> Vec { .collect() } +/// A TMPDIR state that a tree with no listener may show. `Ok` is the verified directory. `Missing` +/// is normal when no child is running (the directory exists only while one runs). Any other state +/// at the expected path is a V2 finding even when nothing listens (R1.1 as decided). +fn tmp_is_clean(tmp: procnet::TmpState) -> bool { + matches!(tmp, procnet::TmpState::Ok | procnet::TmpState::Missing) +} + /// The `listeners` field. `none`, `unknown`, or the counts with the V2 verdict: /// `tcp=N udp=N unix=N unix_outside=N tmpdir= result=pass|fail` (R1.1 as decided: only -/// Unix listeners inside the child's verified private `TMPDIR` pass). +/// Unix listeners inside the child's verified private `TMPDIR` pass, and a TMPDIR that is not +/// clean fails even with zero listeners). `none` is printed only when the TMPDIR is clean. pub(crate) fn listeners_word( l: Result, tmp: procnet::TmpState, ) -> String { match l { - Ok(l) if l.total() == 0 => "none".into(), + Ok(l) if l.total() == 0 && tmp_is_clean(tmp) => "none".into(), Ok(l) => format!( "tcp={} udp={} unix={} unix_outside={} tmpdir={} result={}", l.tcp, @@ -125,7 +133,11 @@ pub(crate) fn listeners_word( l.unix, l.unix_outside, tmp.word(), - if l.passes_v2() { "pass" } else { "fail" } + if l.passes_v2() && tmp_is_clean(tmp) { + "pass" + } else { + "fail" + } ), Err(_) => "unknown".into(), } diff --git a/poc/reverse-attach-linux/src/probe_tests.rs b/poc/reverse-attach-linux/src/probe_tests.rs index 3930c46..cab7b2c 100644 --- a/poc/reverse-attach-linux/src/probe_tests.rs +++ b/poc/reverse-attach-linux/src/probe_tests.rs @@ -230,3 +230,28 @@ fn the_listeners_word_carries_the_v2_verdict() { assert!(w(tcp, TmpState::Ok).ends_with("result=fail")); assert_eq!(listeners_word(Err("x"), TmpState::Ok), "unknown"); } + +/// A running tree that listens on nothing still fails V2 when its TMPDIR is not the verified private +/// directory (decided V2 rule: the status self-check fails on a TMPDIR that is not 0700 or not the +/// daemon's uid). Before the fix this printed `none` and exited 0. +#[test] +fn a_zero_listener_tree_fails_v2_when_its_tmpdir_is_not_private() { + use crate::procnet::{Listeners, TmpState}; + let silent = || Listeners::default(); + let w = |t| listeners_word(Ok(silent()), t); + assert_eq!( + w(TmpState::Mode), + "tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=mode result=fail" + ); + assert_eq!( + w(TmpState::Owner), + "tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=owner result=fail" + ); + assert_eq!( + w(TmpState::NotDir), + "tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=not_dir result=fail" + ); + // The clean states still read `none`: the verified directory, or no child running yet. + assert_eq!(w(TmpState::Ok), "none"); + assert_eq!(w(TmpState::Missing), "none"); +} diff --git a/scripts/release-smoke-linux.sh b/scripts/release-smoke-linux.sh index d61d449..1fcc10c 100755 --- a/scripts/release-smoke-linux.sh +++ b/scripts/release-smoke-linux.sh @@ -48,12 +48,14 @@ list_field() { printf '%s' "$1" | tr ' ' '\n' | sed -n "s/^$2=//p" | head -n 1 } -# gate_v2 STATUS_JSON: the decided V2 rule (R1.1). Passes when the managed tree holds no listener at -# all, or when it holds no TCP or UDP listener and every Unix listener is inside the child's private -# per-run TMPDIR, which `status` has checked to be a real directory of the daemon's uid with mode -# exactly 0700. The word is `tcp=N udp=N unix=N unix_outside=N tmpdir=S result=pass|fail`. This -# gate trusts no `result=` alone: it recomputes the rule from the counts, and a missing or unknown -# field fails. There is no path allow-list here; "inside" is decided by `status`. +# gate_v2 STATUS_JSON: the decided V2 rule (R1.1). `status` prints `none` only when the tree holds no +# listener and its TMPDIR is clean (the verified directory, or no child running). A bad TMPDIR with no +# listener prints counts with `tmpdir=S result=fail`, which is judged below. Otherwise it passes when +# the tree holds no TCP or UDP listener and every Unix listener is inside the child's private per-run +# TMPDIR, which `status` has checked to be a real directory of the daemon's uid with mode exactly 0700. +# The word is `tcp=N udp=N unix=N unix_outside=N tmpdir=S result=pass|fail`. This gate trusts no +# `result=` alone: it recomputes the rule from the counts, and a missing or unknown field fails. There +# is no path allow-list here; "inside" is decided by `status`. gate_v2() { local l tcp udp unix out tmp res l=$(json_field "$1" listeners) diff --git a/scripts/test-release-smoke-linux.sh b/scripts/test-release-smoke-linux.sh index 8c2f909..fcbc50d 100755 --- a/scripts/test-release-smoke-linux.sh +++ b/scripts/test-release-smoke-linux.sh @@ -30,6 +30,8 @@ gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=owner result=fa gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=mode result=pass')" >/dev/null; expect "V2 recomputed: tmpdir=mode fails even if result=pass" 1 $? gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=missing result=pass')" >/dev/null; expect "V2 recomputed: tmpdir=missing fails" 1 $? gate_v2 "$(status_json 'tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=mode result=pass')" >/dev/null; expect "V2 a bad TMPDIR fails even with no unix listener" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=mode result=fail')" >/dev/null; expect "V2 zero listeners with a 0755 TMPDIR fails (status word)" 1 $? +gate_v2 "$(status_json 'tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=owner result=fail')" >/dev/null; expect "V2 zero listeners with a foreign-owned TMPDIR fails (status word)" 1 $? gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=1 tmpdir=ok result=pass')" >/dev/null; expect "V2 recomputed: unix_outside=1 fails even if result=pass" 1 $? gate_v2 "$(status_json 'tcp=0 udp=0 unix=2 unix_outside=0 tmpdir=ok result=fail')" >/dev/null; expect "V2 result=fail fails" 1 $? gate_v2 "$(status_json 'tcp=1 udp=0 unix=2 unix_outside=0 tmpdir=ok result=pass')" >/dev/null; expect "V2 tcp=1 fails even with a private dir" 1 $? From 4206857ca1dff73ae8e16a2b98266f630e829daa Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:05:47 -0500 Subject: [PATCH 10/18] fix: a stale TMPDIR fails V2 when no tree runs (review round 3, LOW) With no managed tree running, `browser status` printed `listeners=not_running` and exited 0, whatever the expected TMPDIR held. The V2 decision fails the status self-check on a TMPDIR that is not 0700 or not owned by the daemon uid, so an idle tree now reports the V2 word for an unclean directory. A missing or clean directory still reports `not_running`. Test: - Debian 13 arm64 node: cargo test --release: 556 passed, 0 failed, 17 ignored (555 before; the new test is the one added). - Debian 13 arm64 node: cargo test --release a_stale_tmpdir: 1 passed. - macOS arm64 node: cargo test --release does not link (undefined _prctl in platform/linux/seat.rs, the same link error origin/main has; this change does not touch platform/). cargo check --release --tests: Finished, exit 0. - The new unit test does not compile before the fix (idle_listeners_word did not exist), so it fails before and passes after. --- poc/reverse-attach-linux/src/probe.rs | 19 ++++++++++++++++--- poc/reverse-attach-linux/src/probe_tests.rs | 17 +++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/poc/reverse-attach-linux/src/probe.rs b/poc/reverse-attach-linux/src/probe.rs index c1c151a..343aa87 100644 --- a/poc/reverse-attach-linux/src/probe.rs +++ b/poc/reverse-attach-linux/src/probe.rs @@ -143,6 +143,17 @@ pub(crate) fn listeners_word( } } +/// The `listeners` field when no tree runs: `not_running`, unless the expected TMPDIR is present and +/// not clean. A stale directory with the wrong mode or owner fails V2 even with no tree (decided V2 +/// rule), so it prints the V2 word with zero counts. +pub(crate) fn idle_listeners_word(tmp: procnet::TmpState) -> String { + if tmp_is_clean(tmp) { + "not_running".into() + } else { + listeners_word(Ok(procnet::Listeners::default()), tmp) + } +} + /// `verify` runs the containment self-test (only called with `retry`). pub fn gather( base: &Path, @@ -167,9 +178,11 @@ pub fn gather( x.refusal = run_record::refusal_get(&root).unwrap_or_else(|| "none".into()); x.run_records = run_record::state(&root).word().into(); let pids = tree_pids(root.abs_path()); - if !pids.is_empty() { - let tmp = crate::child::RuntimeTmp::expected_path(root.abs_path()); - let tmp_state = procnet::tmp_state(&tmp, rustix::process::geteuid().as_raw()); + let tmp = crate::child::RuntimeTmp::expected_path(root.abs_path()); + let tmp_state = procnet::tmp_state(&tmp, rustix::process::geteuid().as_raw()); + if pids.is_empty() { + x.listeners = idle_listeners_word(tmp_state); + } else { // The directory is resolved once here; a link in its path is followed (V2). let private = (tmp_state == procnet::TmpState::Ok) .then(|| std::fs::canonicalize(&tmp).ok()) diff --git a/poc/reverse-attach-linux/src/probe_tests.rs b/poc/reverse-attach-linux/src/probe_tests.rs index cab7b2c..ef369da 100644 --- a/poc/reverse-attach-linux/src/probe_tests.rs +++ b/poc/reverse-attach-linux/src/probe_tests.rs @@ -231,6 +231,23 @@ fn the_listeners_word_carries_the_v2_verdict() { assert_eq!(listeners_word(Err("x"), TmpState::Ok), "unknown"); } +/// With no tree running, a stale TMPDIR that is not private fails V2 too (decided V2 rule). Before +/// this fix `listeners` was `not_running` whatever the directory held, and `browser status` exited 0. +#[test] +fn a_stale_tmpdir_fails_v2_even_when_no_tree_runs() { + use crate::procnet::TmpState; + assert_eq!(idle_listeners_word(TmpState::Missing), "not_running"); + assert_eq!(idle_listeners_word(TmpState::Ok), "not_running"); + assert_eq!( + idle_listeners_word(TmpState::Mode), + "tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=mode result=fail" + ); + assert_eq!( + idle_listeners_word(TmpState::Owner), + "tcp=0 udp=0 unix=0 unix_outside=0 tmpdir=owner result=fail" + ); +} + /// A running tree that listens on nothing still fails V2 when its TMPDIR is not the verified private /// directory (decided V2 rule: the status self-check fails on a TMPDIR that is not 0700 or not the /// daemon's uid). Before the fix this printed `none` and exited 0. From 80b3b14ce03f3804cd156c105e9d910c0dd3947c Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:18:11 -0500 Subject: [PATCH 11/18] docs: match trailing whitespace in MCP_UPSTREAM sed, note first Linux release record Gate CHANGES_REQUESTED on 4206857 (opus5 low, sol low), fixed by docs only: - linux-cutover.md step 5.2: the two sed removals now allow trailing whitespace, the same as the detection grep and the drop-in awk check. Ran: sed (no -i) with the new pattern on a temp file holding a trailing-space MCP_UPSTREAM line, an exact line and an unrelated line. Result: 0 MCP_UPSTREAM lines left, unrelated line kept. Same input with the old pattern: 1 line left. - releasing.md Linux release checklist step 3: states that docs/release-records/ holds only TEMPLATE.md, so the first Linux release fails the record job until the record is committed. Not run: no build or test targets (docs only). --- docs/linux-cutover.md | 4 ++-- docs/releasing.md | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/linux-cutover.md b/docs/linux-cutover.md index 20611b4..748463d 100644 --- a/docs/linux-cutover.md +++ b/docs/linux-cutover.md @@ -283,7 +283,7 @@ Host A, the line sits inside `oab-computer.service`: ```sh grep -n 'MCP_UPSTREAM' ~/.config/systemd/user/oab-computer.service -sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp$/d' ~/.config/systemd/user/oab-computer.service +sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp[[:space:]]*$/d' ~/.config/systemd/user/oab-computer.service grep -c 'MCP_UPSTREAM' ~/.config/systemd/user/oab-computer.service ``` @@ -306,7 +306,7 @@ and decide: wrote it: no installer in this repository writes an `MCP_UPSTREAM` drop-in, so a hand-written file of the same shape is removed too. - It holds any other setting: keep the file and delete only the line, - `sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp$/d' FILE`. If the + `sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp[[:space:]]*$/d' FILE`. If the line has another form (several variables, another URL), edit it by hand and keep everything else. Run this block once, after the bullets above. It removes a drop-in only when the file has exactly the diff --git a/docs/releasing.md b/docs/releasing.md index 30ee016..4549995 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -350,7 +350,8 @@ Before tagging a release that contains the managed Linux tier: `pins`, the four cells and the two Debian 12 jobs are green, including `GATE V2 pass` on amd64 and arm64. 3. Copy `docs/release-records/TEMPLATE.md` to `docs/release-records/linux-VERSION.md`, run the manual - rows, fill every `PENDING`, and commit it to `main`. + rows, fill every `PENDING`, and commit it to `main`. **`docs/release-records/` holds only the + template today, so the first Linux release fails the `record` job until this file is committed.** 4. The `V2` row of the record quotes the two `GATE V2 pass` lines (amd64 and arm64). The decision itself is in the ADR. 5. The `D7` row of the record says the single glob profile is kept, with the M3 result beside it. From 6381f43bcbef299b40bcb3db3aed2c405442c415 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:45:50 -0500 Subject: [PATCH 12/18] fix: close the fail-open gaps in the record gate, fd scan, legacy hint and cleanup docs Fixes the review findings on PR 171 (head 80b3b14). Each fix has a test that fails on the base code and passes after the change. "Before" below means the same test run against the base 80b3b14 (shell: base checker or base docs; Rust: base source files). - Release record (F1): check-release-record.sh refuses any record that contains "' +reject "a complete valid record wrapped in one HTML comment" '1i\ +' # A bare id (the cell is only "M1", with no description) is still that row: a non-pass duplicate of a # valid M1 row, or an empty result, must be refused. reject "M1 bare-id duplicate with result fail" "/^| M1 /a\\ From e8f4e0a63076e9c4a84c0b25287b820c70c2d3d7 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:50:39 -0500 Subject: [PATCH 13/18] fix: keep one drop-in removal block in the cutover guide (review B1) "Removing the leftovers" step 1 pasted the step 5.2 dropin_is_ours() block a second time. The two copies could drift, and test-cutover-guide.sh only read the first, so the second was never tested. Step 1 now points to step 5.2 and keeps no copy of the block. Tests run: - scripts/test-cutover-guide.sh, new "exactly one sh block defines dropin_is_ours()": FAIL before the change (2 blocks), PASS after (1 block). Full run after the change: pass=26 fail=0. - scripts/test-release-smoke-linux.sh after the change: pass=275 fail=0. - git diff --check: clean. --- docs/linux-cutover.md | 24 +++--------------------- scripts/test-cutover-guide.sh | 10 ++++++++++ 2 files changed, 13 insertions(+), 21 deletions(-) diff --git a/docs/linux-cutover.md b/docs/linux-cutover.md index 82b0617..9b889ee 100644 --- a/docs/linux-cutover.md +++ b/docs/linux-cutover.md @@ -572,27 +572,9 @@ points here and repeats none of these commands. 1. Disable and delete the old unit files, then reload. No root. Step 5.2 owns the drop-in: it already removed the dedicated drop-in file, or only the `MCP_UPSTREAM` line from a shared one, and the backup from step 1 keeps the original for the rollback. As step 5.2 says, the block identifies a - drop-in by its content, so a hand-written file of the same shape is removed too. If you skipped the drop-in part of step 5.2, run - the same block from step 5.2 first (indented here), then the `daemon-reload` below: - - ```sh - # Removes only the dedicated MCP_UPSTREAM drop-in (see step 5.2). Anything else is kept and reported. - dropin_is_ours() { - [ -f "$1" ] && [ ! -L "$1" ] || return 1 - awk ' - /^[[:space:]]*$/ || /^[[:space:]]*#/ { next } - /^\[Service\][[:space:]]*$/ { svc++; next } - /^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp[[:space:]]*$/ { line++; next } - { bad = 1 } - END { exit (bad || svc != 1 || line != 1) } - ' "$1" - } - for f in ~/.config/systemd/user/oab-computer.service.d/*.conf ~/.config/systemd/user/oab-instance-mcp.service.d/*.conf; do - [ -e "$f" ] || continue - grep -q 'MCP_UPSTREAM=' "$f" || continue - if dropin_is_ours "$f"; then rm -f -- "$f"; echo "removed $f"; else echo "kept $f: not exactly the dedicated drop-in, edit it by hand"; fi - done - ``` + drop-in by its content, so a hand-written file of the same shape is removed too. If you skipped the + drop-in part of step 5.2, run the block in step 5.2 first, then the `daemon-reload` below. That block + is the only copy of the drop-in rule; do not paste a second one here. Then unload and delete the old unit files: diff --git a/scripts/test-cutover-guide.sh b/scripts/test-cutover-guide.sh index 1365a32..9c40a39 100755 --- a/scripts/test-cutover-guide.sh +++ b/scripts/test-cutover-guide.sh @@ -119,5 +119,15 @@ else if printf '%s\n' "$rem" | grep -qE '(^|[[:space:];&|])(rm|sed|apparmor_parser|systemctl|mv)[[:space:]]|^[[:space:]]*```'; then bad "setup removal section repeats removal commands; keep one procedure in linux-cutover.md"; else ok "setup removal section repeats no removal commands"; fi fi +# The drop-in removal logic is defined once in the cutover guide. A second copy would drift untested, +# because the block test above reads only the first one. +defs=$(awk ' + /^ *```sh$/ { inb = 1; buf = ""; next } + /^ *```$/ && inb { if (buf ~ /dropin_is_ours\(\)/) n++; inb = 0; next } + inb { buf = buf $0 "\n" } + END { print n + 0 } +' "$GUIDE") +if [ "$defs" -eq 1 ]; then ok "exactly one sh block defines dropin_is_ours()"; else bad "$defs sh blocks define dropin_is_ours(); keep one copy in step 5.2"; fi + echo "pass=$pass fail=$fail" [ "$fail" -eq 0 ] From 0412f1d815a86e7f29a92b6c493673eb3c687631 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:01:16 -0500 Subject: [PATCH 14/18] docs: point every drop-in removal at the content-based step 5.2 The requirements runbook (section 2.3) said "delete the drop-in" with no content check, a third removal description that could drift from owner decision A. Replace it, and the other drop-in removal wording in the requirements doc and the setup guide's upgrade table, with a pointer to docs/linux-cutover.md step 5.2. No mechanism is restated. Checks run: - bash scripts/test-cutover-guide.sh: pass=26 fail=0 (exit 0) - bash scripts/test-release-smoke-linux.sh: pass=275 fail=0 (exit 0) - git diff --check: clean - git grep for drop-in removal wording in docs: only pointers, location and restore text remain --- docs/linux-setup.md | 2 +- docs/requirements/linux-browser-tier.md | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/linux-setup.md b/docs/linux-setup.md index 0a6c5f5..6a5a68f 100644 --- a/docs/linux-setup.md +++ b/docs/linux-setup.md @@ -844,7 +844,7 @@ installer does on each kind of host: | --- | --- | --- | | New: nothing from before | Writes the daemon unit without `MCP_UPSTREAM`, asks about the browser. | Nothing. | | New-style unit: `oab-computer-pw-mcp.service` from 0.12.0, and an `MCP_UPSTREAM` line inside `oab-computer.service` | Warns, with the exact command to turn the unit off. The installer rewrites `oab-computer.service` only when the unit carries its own marker line (`# oab-computer-installer:`). A unit without it, which includes any unit from before the marker existed, is left byte for byte as it is (whatever it contains, `MCP_UPSTREAM` included); the unit this run would have written is put beside it as `oab-computer.service.proposed`. The binary is still replaced. The installer restarts that unit only if it is already running, and never enables or starts it (the same rule as for `oab-seat.service`). | After `browser status` shows the managed browser working: `systemctl --user disable --now oab-computer-pw-mcp.service`, then remove the `MCP_UPSTREAM` line (back it up first), or review and move `.proposed` over the unit, `daemon-reload`, restart. | -| Old-style unit: `oab-pw-mcp.service` and an `MCP_UPSTREAM` drop-in under `oab-computer.service.d/` or `oab-instance-mcp.service.d/` | Warns the same way for `oab-pw-mcp.service`, names the drop-in file, writes `oab-computer.service` without the line when there is none or it carries the installer's marker (an unmarked existing one is left as it is, with `.proposed` beside it, and is restarted only if it is already running, never enabled or started; no backup copy is made) and leaves the drop-in alone. If `oab-instance-mcp.service` (0.11 or earlier) is still live it holds port 8795: the installer warns, writes the new unit but does not enable, start or restart `oab-computer.service` and does not check the daemon; disable that unit first (`systemctl --user disable --now oab-instance-mcp.service`), then `systemctl --user enable --now oab-computer.service`. | `systemctl --user disable --now oab-pw-mcp.service`, then remove the drop-in file (back it up first), `daemon-reload`, restart. If a `.proposed` file sits beside `oab-computer.service`, adopt it too (review it, move it over the unit): until then later installer runs leave the unmarked unit alone. | +| Old-style unit: `oab-pw-mcp.service` and an `MCP_UPSTREAM` drop-in under `oab-computer.service.d/` or `oab-instance-mcp.service.d/` | Warns the same way for `oab-pw-mcp.service`, names the drop-in file, writes `oab-computer.service` without the line when there is none or it carries the installer's marker (an unmarked existing one is left as it is, with `.proposed` beside it, and is restarted only if it is already running, never enabled or started; no backup copy is made) and leaves the drop-in alone. If `oab-instance-mcp.service` (0.11 or earlier) is still live it holds port 8795: the installer warns, writes the new unit but does not enable, start or restart `oab-computer.service` and does not check the daemon; disable that unit first (`systemctl --user disable --now oab-instance-mcp.service`), then `systemctl --user enable --now oab-computer.service`. | `systemctl --user disable --now oab-pw-mcp.service`, then remove the drop-in as the [cutover guide](linux-cutover.md) step 5.2 describes (back it up first), `daemon-reload`, restart. If a `.proposed` file sits beside `oab-computer.service`, adopt it too (review it, move it over the unit): until then later installer runs leave the unmarked unit alone. | A plain `systemctl stop` is not enough: those units come back at the next login or boot, and each is an unauthenticated Playwright on loopback `8794`. While the old unit and its line exist, a diff --git a/docs/requirements/linux-browser-tier.md b/docs/requirements/linux-browser-tier.md index c9c1cea..8561de1 100644 --- a/docs/requirements/linux-browser-tier.md +++ b/docs/requirements/linux-browser-tier.md @@ -193,7 +193,7 @@ together after one week of normal use on the class N host with no browser incide 5. **Cutover, in one short window.** 1. Stop and disable the old browser unit with `systemctl --user disable --now `. A plain stop would bring the unauthenticated listener back at the next login or boot. - 2. Remove the `MCP_UPSTREAM` line (class N) or the drop-in file (class O). Edit after the backup + 2. Remove the `MCP_UPSTREAM` line (class N) or the drop-in (class O), as `docs/linux-cutover.md` step 5.2 describes. Edit after the backup of step 1, and do not delete anything else. A unit written before the installer's ownership marker existed is never updated by the installer. If an installer run left `oab-computer.service.proposed`, review it and adopt it only after checking that its `BIND` @@ -221,7 +221,8 @@ together after one week of normal use on the class N host with no browser incide Differences for class N: the unit to disable is the one the installer wrote, the `MCP_UPSTREAM` line sits inside the daemon unit (edited, with the backup), and its profile and output directories are -under `~/.local/oab-computer`. Differences for class O: the thing to remove is the drop-in, the old +under `~/.local/oab-computer`. Differences for class O: the thing to remove is the drop-in (the rule is in +`docs/linux-cutover.md` step 5.2), the old unit has its own name, and the legacy tree may hold a `node_modules`, a profile with cookies and an output directory. @@ -230,7 +231,9 @@ output directory. The installer never deletes these. A person does, from the list that `browser status` prints with sizes. Each command is documented in `docs/linux-setup.md` and marked if it needs root. -1. Disable and delete the old unit files, delete the drop-in, run `daemon-reload`. +1. Disable and delete the old unit files. Remove the drop-in only by the content rule in + `docs/linux-cutover.md` step 5.2, which keeps any file that differs from the dedicated shape. Then run + `daemon-reload`. 2. Delete the legacy directories. The old profile holds cookies, so check it first. 3. Delete the old AppArmor profile (root) and the stale `pw-config.json`. From da642fc13c916e1c40f4374c0018bc81ec4645d7 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:01:30 -0500 Subject: [PATCH 15/18] docs: state exactly which drop-in lines the step 5.2 awk accepts Step 5.2 said a dedicated drop-in holds "comments and blank lines", but dropin_is_ours accepts only lines that are blank or whose first non-blank character is "#". A ";" comment line makes the file kept. The sentence now lists the accepted lines, the leading-whitespace and trailing-space rules, and says that a ";" line keeps the file, the safe direction. No code changed. Checks run: - bash scripts/test-cutover-guide.sh: pass=26 fail=0 (exit 0) - bash scripts/test-release-smoke-linux.sh: pass=275 fail=0 (exit 0) - git diff --check: clean --- docs/linux-cutover.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/linux-cutover.md b/docs/linux-cutover.md index 9b889ee..7ce27b2 100644 --- a/docs/linux-cutover.md +++ b/docs/linux-cutover.md @@ -303,9 +303,14 @@ an ordinary character (systemd reads them as comments only at the start of a lin `Environment=FOO=1 # MCP_UPSTREAM=...` is matched and counted. For each file printed, run `cat FILE` and decide: -- It holds only `[Service]`, that one `Environment=MCP_UPSTREAM=` line, comments and blank lines: it is - the dedicated drop-in. The block below removes it. The file is identified by its content, not by who - wrote it (see the owner decision below). +- It is the dedicated drop-in only if the `dropin_is_ours` block below accepts it. That block accepts a line + only when it is blank, or its first non-blank character is `#` (leading spaces and tabs are allowed, and + a comment may sit anywhere in the file). Besides those lines, the file must have exactly one `[Service]` + header at the start of a line, and exactly one `Environment=MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp` + line at the start of a line; trailing spaces are allowed on those three lines. A line that starts with `;` + is not accepted, so a file that contains one is kept and reported. Keeping is the safe direction: edit it by + hand if you want it removed. The file is identified by its content, not by who wrote it (see the owner + decision below). - It holds any other setting: keep the file and delete only the line, `sed -i '/^Environment=MCP_UPSTREAM=browser=http:\/\/127\.0\.0\.1:8794\/mcp[[:space:]]*$/d' FILE`. If the line has another form (several variables, another URL), edit it by hand and keep everything else. From 153414aebc4fa51f1acb1c363263c53ef3b6b4a7 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:01:51 -0500 Subject: [PATCH 16/18] docs: record the drop-in removal owner decision in the ADR The earlier review asked that the owner decision (option A, content-based drop-in removal) be recorded in the ADR. It was only in step 5.2 and the PR body. Add a short note under D10 with pointers to step 5.2 and to PR #171. The note does not restate the rule. Checks run: - bash scripts/test-cutover-guide.sh: pass=26 fail=0 (exit 0) - bash scripts/test-release-smoke-linux.sh: pass=275 fail=0 (exit 0) - bash scripts/test-check-no-private-identifiers.sh: exit 0 (see result line in output) - git diff --check: clean --- docs/adr/linux-browser-tier.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/adr/linux-browser-tier.md b/docs/adr/linux-browser-tier.md index f4652e8..d6d3198 100644 --- a/docs/adr/linux-browser-tier.md +++ b/docs/adr/linux-browser-tier.md @@ -352,6 +352,11 @@ Rejected: paths that have no marker. - *Automatic removal after some days of managed use.* Deletes unmarked data with nobody present. +**Note, drop-in removal (owner decision A).** A person may remove an `MCP_UPSTREAM` drop-in by its +content, not by who wrote it. The rule and the exact accepted shape are in +[docs/linux-cutover.md](../linux-cutover.md) step 5.2. The installer still never removes a drop-in. The +decision came up in [PR #171](https://github.com/openabdev/openab-computer/pull/171). + #### D11. Which Chromium password store holds cookie encryption on Linux? **Chosen: always `--password-store=basic`.** Headed and headless runs then read the same key, From ce52de0457148830843a90df92f9a7bcda4403b7 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:06:05 -0500 Subject: [PATCH 17/18] test: a pid that exits before its fd scan is unknown (F2) A PID that exits between listing and reading its fd directory must report unknown, never no sockets. Adds a_pid_that_exits_before_its_fd_scan_is_unknown_never_no_sockets and documents that a vanished fd or PID is deliberately not special-cased. Tests run (Debian 13 arm64 host, cargo test on a /tmp copy of the crate): - cargo test procnet: 33 passed, 0 failed. - cargo test legacy: 19 passed, 0 failed. - The new test passes on the code from 6381f43, which already maps a failed read_dir to UNKNOWN. It is a regression guard, not a red-to-green fix. --- poc/reverse-attach-linux/src/procnet.rs | 5 +++++ poc/reverse-attach-linux/src/procnet_tests.rs | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/poc/reverse-attach-linux/src/procnet.rs b/poc/reverse-attach-linux/src/procnet.rs index d780c8e..e9b6f68 100644 --- a/poc/reverse-attach-linux/src/procnet.rs +++ b/poc/reverse-attach-linux/src/procnet.rs @@ -285,6 +285,11 @@ pub fn socket_inodes(pid: u32) -> Result, &'static str> { /// [`socket_inodes`] for the fd directory at `dir`. An unreadable directory, an unreadable entry, an /// unreadable link, or more than `FD_LIMIT` entries is `UNKNOWN`: a listener could be among the /// descriptors that were not read. +/// +/// A PID or fd that disappears during the scan is `UNKNOWN` as well, by design. A `read_link` that fails +/// with ENOENT (the process closed the fd after `read_dir` listed it) is not special-cased, and neither is +/// a PID that exited before its fd directory was read. Reading "gone" as "no sockets" would turn an unknown +/// state into a claim. The cost: `browser status` reports `unknown` when a busy process churns its fds. pub fn socket_inodes_in(dir: &std::path::Path) -> Result, &'static str> { let rd = std::fs::read_dir(dir).map_err(|_| UNKNOWN)?; let mut set = HashSet::new(); diff --git a/poc/reverse-attach-linux/src/procnet_tests.rs b/poc/reverse-attach-linux/src/procnet_tests.rs index 2c38620..3bd1cca 100644 --- a/poc/reverse-attach-linux/src/procnet_tests.rs +++ b/poc/reverse-attach-linux/src/procnet_tests.rs @@ -396,6 +396,15 @@ fn an_fd_table_at_the_scan_limit_is_read_in_full() { assert_eq!(socket_inodes_in(&d.0).unwrap().len(), FD_LIMIT); } +#[test] +fn a_pid_that_exits_before_its_fd_scan_is_unknown_never_no_sockets() { + let mut child = std::process::Command::new("sleep").arg("30").spawn().unwrap(); + let pid = child.id(); + child.kill().unwrap(); + child.wait().unwrap(); + assert_eq!(socket_inodes(pid), Err(UNKNOWN)); +} + #[test] fn socket_links_are_collected_and_other_fds_are_ignored() { let d = Scratch::new("fd-kinds"); From 2a2393851ad3888529a86ff77264fbd91807bf63 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:16:45 -0500 Subject: [PATCH 18/18] fix: cargo fmt and shellcheck for the L5 cutover CI Format job (cargo fmt --check, CI runner stable toolchain): - poc/reverse-attach-linux/src/legacy_tests.rs: wrap the three assert!(set(...)) calls in the sets_upstream test onto multiple lines. - poc/reverse-attach-linux/src/procnet_tests.rs: wrap the sleep Command chain in a_pid_that_exits_before_its_fd_scan_is_unknown_never_no_sockets. CI also reported this file, so it is included here. Both diffs are whitespace-only: with spaces, tabs and newlines removed, the old and new file contents are identical. ShellCheck job (linux-installer): - scripts/test-release-smoke-linux.sh lines 162 and 167: SC2016 (info). The single-quoted sed programs contained a literal $a (last-line address). Rewritten as double-quoted strings with \$a and \\ line continuations. The sed program text is byte-identical, so the test inputs do not change. No shellcheck directive was added. Verification (local worktree): - shellcheck on the CI file list: clean. - scripts/test-cutover-guide.sh: pass=26 fail=0. - scripts/test-release-smoke-linux.sh: pass=275 fail=0. Verification (Linux build node, copies under /tmp, stable toolchain): - cargo fmt --check on the crate: exit 0. - cargo test --no-fail-fast, head: 560 passed, 2 failed. - cargo test --no-fail-fast, base (merge-base with main): 509 passed, 2 failed. The same two tests fail on both: external::tests::paging::a_server_that_stops_reading_ends_the_request_by_the_deadline proc::tests::a_pid_that_does_not_exist_signals_nothing_and_does_not_panic No new failures on head. --- poc/reverse-attach-linux/src/legacy_tests.rs | 12 +++++++++--- poc/reverse-attach-linux/src/procnet_tests.rs | 5 ++++- scripts/test-release-smoke-linux.sh | 16 ++++++++-------- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/poc/reverse-attach-linux/src/legacy_tests.rs b/poc/reverse-attach-linux/src/legacy_tests.rs index 8ad56c1..9d42a38 100644 --- a/poc/reverse-attach-linux/src/legacy_tests.rs +++ b/poc/reverse-attach-linux/src/legacy_tests.rs @@ -371,9 +371,15 @@ fn only_an_active_environment_assignment_of_mcp_upstream_counts() { #[test] fn a_hash_or_semicolon_inside_a_quoted_value_does_not_hide_the_assignment() { use super::sets_upstream as set; - assert!(set("Environment=\"FOO=x;y\" MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp")); - assert!(set("Environment=\"FOO=1#2\" MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp")); - assert!(set("Environment='FOO=1#2' MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp")); + assert!(set( + "Environment=\"FOO=x;y\" MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + )); + assert!(set( + "Environment=\"FOO=1#2\" MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + )); + assert!(set( + "Environment='FOO=1#2' MCP_UPSTREAM=browser=http://127.0.0.1:8794/mcp" + )); } #[test] diff --git a/poc/reverse-attach-linux/src/procnet_tests.rs b/poc/reverse-attach-linux/src/procnet_tests.rs index 3bd1cca..24bf79a 100644 --- a/poc/reverse-attach-linux/src/procnet_tests.rs +++ b/poc/reverse-attach-linux/src/procnet_tests.rs @@ -398,7 +398,10 @@ fn an_fd_table_at_the_scan_limit_is_read_in_full() { #[test] fn a_pid_that_exits_before_its_fd_scan_is_unknown_never_no_sockets() { - let mut child = std::process::Command::new("sleep").arg("30").spawn().unwrap(); + let mut child = std::process::Command::new("sleep") + .arg("30") + .spawn() + .unwrap(); let pid = child.id(); child.kill().unwrap(); child.wait().unwrap(); diff --git a/scripts/test-release-smoke-linux.sh b/scripts/test-release-smoke-linux.sh index 676ae7f..f65807a 100755 --- a/scripts/test-release-smoke-linux.sh +++ b/scripts/test-release-smoke-linux.sh @@ -159,15 +159,15 @@ for id in M1 M2 M3 M4 M5 M6 M7 M8 M9 M10; do done # Hidden rows: the visible V1 row is deleted and a passing copy is placed inside an HTML comment, and a # whole valid record is wrapped in one comment. Both must be refused. -reject "V1 row deleted and a passing copy hidden in an HTML comment" '/^| V1 /d -$a\ -' -reject "a complete valid record wrapped in one HTML comment" '1i\ +reject "V1 row deleted and a passing copy hidden in an HTML comment" "/^| V1 /d +\$a\\ +" +reject "a complete valid record wrapped in one HTML comment" "1i\\ ' +\$a\\ +-->" # A bare id (the cell is only "M1", with no description) is still that row: a non-pass duplicate of a # valid M1 row, or an empty result, must be refused. reject "M1 bare-id duplicate with result fail" "/^| M1 /a\\