diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21a2aba..0918e95 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 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 @@ -119,6 +119,16 @@ 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: "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 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..d6d3198 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. @@ -347,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, @@ -477,10 +487,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. 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 + 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..7ce27b2 --- /dev/null +++ b/docs/linux-cutover.md @@ -0,0 +1,675 @@ +# 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). 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 +systemctl --user cat oab-computer-pw-mcp.service >/dev/null && echo "old unit: oab-computer-pw-mcp.service" +``` + +Hosts B to D: + +```sh +systemctl --user cat oab-pw-mcp.service >/dev/null && echo "old unit: oab-pw-mcp.service" +``` + +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; `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-ID && sudo rm /etc/apparmor.d/oab-computer-chromium-ID +``` + +## 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 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 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. + +**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 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 +listener. + +**Verify.** + +```sh +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 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) + +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[[:space:]]*$/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. A `#` or `;` in the middle of a line is +an ordinary character (systemd reads them as comments only at the start of a line), so +`Environment=FOO=1 # MCP_UPSTREAM=...` is matched and counted. For each file printed, run `cat FILE` +and decide: + +- 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. + +**Owner decision: content-based removal (option A).** The owner decided that the drop-in is removed by +its content, not by who wrote it, and accepted that rule. No installer in this repository writes an +`MCP_UPSTREAM` drop-in, so a hand-written file with exactly the dedicated shape is removed too. A file +that differs in any way is kept and reported. + +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. + +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.** 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 + +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. `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. + +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 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 +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="${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 + 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 (host A `oab-computer-pw-mcp.service`; hosts B to D `oab-pw-mcp.service`): + + ```sh + 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 + ``` + +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). This section is the one removal procedure for +the old browser setup. The [setup guide](linux-setup.md#removing-the-old-browser-setup-after-the-soak) +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 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: + + ```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. A host that ran a pre-release `main` build may also have an unsuffixed + `/etc/apparmor.d/oab-computer-chromium`. No release shipped it, so remove it the same way + (`sudo apparmor_parser -R` it, then `sudo rm` it). + +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). + +5. Decide on the `.proposed` files that an earlier installer run may have left. No root. Review + `~/.config/systemd/user/oab-computer.service.proposed` (step 5.2 says how to adopt it) and either + adopt it or delete it. Delete `~/.config/systemd/user/oab-seat.service.proposed` the same way. The + installer never adopts or removes either file. + +### 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..6a5a68f 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`. 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). 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 +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,15 +836,15 @@ 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 | | --- | --- | --- | | 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 @@ -830,70 +862,20 @@ so it does not loop). A `browser=` entry that a managed install ignores is not c ## Removing the old browser setup after the soak -Only a person does this, after the managed browser has run for about a week without trouble. The -installer never deletes any of it. Take the old paths from your inventory of the host; each command -below is marked if it needs root. - -1. Find what the host has. No 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 - ``` - - 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: - - ```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 - systemctl --user daemon-reload - ``` - - If an earlier installer run left `~/.config/systemd/user/oab-computer.service.proposed` (it keeps - a unit that has no installer marker, see - [Upgrading a host that already has a browser unit](#upgrading-a-host-that-already-has-a-browser-unit)), - either adopt it (review it, `mv` it over `oab-computer.service`, `daemon-reload`, restart) or - delete it. Same for `oab-seat.service.proposed`. No root. - -2. Delete the old directories, after looking inside: the old profile holds cookies. No root: - - ```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 - ``` - -3. Unload the old AppArmor profile that allowed `/home/*/.cache/ms-playwright/...`, then delete - it (in this order: once the file is gone the profile can no longer be unloaded by name). - **Root:** - - ```sh - sudo apparmor_parser -R /etc/apparmor.d/playwright-chromium && sudo rm /etc/apparmor.d/playwright-chromium - ``` - - The profile for the managed browser is a different file, `/etc/apparmor.d/oab-computer-chromium-` (`` is a short hash of the install - path, so each user on a host has their own), and stays. A host that ran a pre-release `main` build - may also have an unsuffixed `/etc/apparmor.d/oab-computer-chromium`; no release shipped it, and it can be removed the same way as the file above (`sudo apparmor_parser -R` it, then `sudo rm` it). - -4. Delete the old Chromium policy file the old installer wrote. **Root:** - `sudo rm /etc/chromium/policies/managed/oab-computer.json`. Installers from the 0.11 era named - it `oab-instance-mcp.json`; if `ls /etc/chromium/policies/managed/` shows that file, remove it the - same way (`sudo rm /etc/chromium/policies/managed/oab-instance-mcp.json`). +The removal procedure is in one place: [Removing the leftovers](linux-cutover.md#removing-the-leftovers) +in the cutover guide. Only a person runs it, after the managed browser has run for about a week without +trouble. The installer never deletes any of it. Take the old paths from your inventory of the host. ## Old external browser (deprecated) 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..79ad0cd --- /dev/null +++ b/docs/release-records/TEMPLATE.md @@ -0,0 +1,93 @@ +# 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`, 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. 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)). + 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..4549995 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,194 @@ 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. 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. + +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. 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`. + 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 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 + +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 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 + +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. **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 + 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. +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..8561de1 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. 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. - 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 @@ -189,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` @@ -217,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. @@ -226,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`. @@ -241,7 +248,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 +259,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 +308,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 +320,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 +381,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 +391,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..fa37222 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`. 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. + +### 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..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), @@ -331,14 +349,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 +381,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..595d1a1 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 { @@ -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/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..2df1394 --- /dev/null +++ b/poc/reverse-attach-linux/src/legacy.rs @@ -0,0 +1,306 @@ +//! 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. systemd reads +/// `#` and `;` as comments only at the start of a line (`systemd.syntax(7)`), so a mid-line one is an +/// ordinary word and does not end the value. Comment lines never reach here: they do not start with +/// `Environment=`. 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 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); + } + // 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 { + 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..9d42a38 --- /dev/null +++ b/poc/reverse-attach-linux/src/legacy_tests.rs @@ -0,0 +1,491 @@ +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::from(std::io::ErrorKind::NotFound)) + } +} + +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\"", + // systemd reads a "#" or ";" only at the start of a line; mid-line it is an ordinary word. + "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", + "ExecStart=/bin/true MCP_UPSTREAM=a", + "Description=MCP_UPSTREAM=a", + ] { + assert!(!set(no), "{no}"); + } +} + +#[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" + )); +} + +#[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))); +} + +/// 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/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..343aa87 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,34 @@ 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(), } } + + /// `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; + 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 +109,51 @@ 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, 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 && tmp_is_clean(tmp) => "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() && tmp_is_clean(tmp) { + "pass" + } else { + "fail" + } + ), + Err(_) => "unknown".into(), + } +} + +/// 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, @@ -99,12 +178,19 @@ 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() { - 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()); + 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()) + .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..ef369da 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,81 @@ 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"); +} + +/// 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. +#[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/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..e9b6f68 100644 --- a/poc/reverse-attach-linux/src/procnet.rs +++ b/poc/reverse-attach-linux/src/procnet.rs @@ -100,7 +100,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 +119,85 @@ 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 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; + }; + 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. +#[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`. +/// +/// 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) { + 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,38 +259,73 @@ 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]`). -pub fn socket_inodes(pid: u32) -> HashSet { +/// Socket inodes held open by `pid` (`/proc//fd/*` links of the form `socket:[N]`). A failure to +/// read the fd table is `UNKNOWN`, never an empty set: "no sockets" would be a claim. +pub fn socket_inodes(pid: u32) -> Result, &'static str> { + socket_inodes_in(std::path::Path::new(&format!("/proc/{pid}/fd"))) +} + +/// [`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(); - let Ok(rd) = std::fs::read_dir(format!("/proc/{pid}/fd")) else { - return set; - }; - for e in rd.flatten().take(FD_LIMIT) { - if let Ok(t) = std::fs::read_link(e.path()) { - if let Some(n) = t - .to_str() - .and_then(|s| s.strip_prefix("socket:[")) - .and_then(|s| s.strip_suffix(']')) - .and_then(|s| s.parse::().ok()) - { - set.insert(n); - } + for (i, e) in rd.enumerate() { + if i >= FD_LIMIT { + return Err(UNKNOWN); + } + let e = e.map_err(|_| UNKNOWN)?; + let t = std::fs::read_link(e.path()).map_err(|_| UNKNOWN)?; + if let Some(n) = t + .to_str() + .and_then(|s| s.strip_prefix("socket:[")) + .and_then(|s| s.strip_suffix(']')) + .and_then(|s| s.parse::().ok()) + { + set.insert(n); } } - set + Ok(set) } /// 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`, resolved with `canonicalize` +/// and passed only when it was verified (`TmpState::Ok`); a Unix listener is "outside" unless its +/// directory resolves below it (see [`inside_resolved`]). +pub fn listeners_among_in( + src: &dyn Source, + inodes: &HashSet, + private: Option<&std::path::Path>, +) -> Result { let mut out = Listeners::default(); for v6 in [false, true] { for r in inet_rows(src, v6, "tcp").map_err(|_| UNKNOWN)? { @@ -221,20 +340,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<&std::path::Path>, +) -> Result { let mut inodes = HashSet::new(); for p in pids { - inodes.extend(socket_inodes(*p)); + 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..24bf79a 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,372 @@ 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())] + ); +} + +/// 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() +} + +// ---------------------------------------------------------------- the fd scan (F2) + +#[test] +fn an_unreadable_fd_directory_is_unknown_never_no_sockets() { + let d = Scratch::new("fd-unreadable"); + let not_a_dir = d.0.join("fd"); + std::fs::write(¬_a_dir, b"").unwrap(); + assert_eq!(socket_inodes_in(¬_a_dir), Err(UNKNOWN)); + assert_eq!(socket_inodes_in(&d.0.join("absent")), Err(UNKNOWN)); +} + +#[test] +fn more_fds_than_the_scan_limit_is_unknown_never_a_partial_set() { + let d = Scratch::new("fd-over-cap"); + for i in 0..=FD_LIMIT { + std::os::unix::fs::symlink(format!("socket:[{}]", i + 1), d.0.join(i.to_string())).unwrap(); + } + assert_eq!(socket_inodes_in(&d.0), Err(UNKNOWN)); +} + +#[test] +fn an_fd_table_at_the_scan_limit_is_read_in_full() { + let d = Scratch::new("fd-at-cap"); + for i in 0..FD_LIMIT { + std::os::unix::fs::symlink(format!("socket:[{}]", i + 1), d.0.join(i.to_string())).unwrap(); + } + 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"); + std::os::unix::fs::symlink("socket:[7]", d.0.join("3")).unwrap(); + std::os::unix::fs::symlink("pipe:[9]", d.0.join("4")).unwrap(); + assert_eq!(socket_inodes_in(&d.0), Ok(HashSet::from([7]))); +} + +#[test] +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!( + outside.join("s.sock").exists(), + "the socket was made outside" + ); + 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 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 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()); + // 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 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()); + 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(std::path::Path::new(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" + ); + } +} 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 ab95c73..ee109f9 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(); @@ -377,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); +} 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..ac7912b --- /dev/null +++ b/scripts/check-release-record.sh @@ -0,0 +1,132 @@ +#!/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), 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. +# 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. +# A record that contains an HTML comment (`" +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\\ +| 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" + 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 +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 ]