Skip to content

Commit 1da5031

Browse files
shellz-n-stuffclaudecodex
authored
[3/5] Add protection to the Claude harness plugin (#1878)
Based on main. The base fix [#2044](#2044) and Pi's adapter [#1877](#1877) have merged. Companion plugin: [squareup/buzz-plugin-security#2](squareup/buzz-plugin-security#2). Protected Claude agents now pause native input and tool calls for the agent's bound policy. Security reviews that use a Claude model run tool-free and return a structured verdict. Both run Claude's pinned release, and the host runs its own verified copy of it. Security reviews also sign in apart from `~/.claude`, with their own Claude folder and token. ### What this changes - **Pinned, host-verified runtime.** The plugin declares Claude 2.1.305 as two macOS artifact processes, `claude-protected-arm64` and `claude-protected-x64`. - Each has the release's SHA-256 and the path `~/Library/Application Support/Buzz/claude-code/2.1.305/claude`. The host expands `~/` under the user's home. - For a contained spawn, the host hashes the bytes from one no-follow descriptor and copies them into its write-denied artifact store, then runs that copy. A changed file in the download folder doesn't start, and swapping it after the check changes nothing. - The plugin picks the process from `uname -sm`. A wrong answer only names a pin whose checksum then fails. - Setup checks the pin by starting the host's copy contained, with the same read-only Claude root as the real launch, and then stopping it. It never runs the download folder's file outside the sandbox. A pruned 2.1.305 folder doesn't trigger a download while the store copy is valid. - If the host refuses its copy, setup installs the pinned release through `claude.sh` and checks again the same way. A failed install step reports "could not be installed"; a copy the host still refuses surfaces the host's own reason. The host, not `claude.sh`, verifies and starts protected Claude. `claude.sh` only installs the pinned release on request, checking its SHA-256, and keeps 2.1.305 when it prunes. - A caller waiting for that download stops waiting when its own signal aborts, and the shared download carries on for later callers. - **Protected sessions.** Hooks pause native input, tool actions and raw output for the policy. The native watchdog (350 s) stops a stalled callback before the CLI's 600 s hook timeout. - Exact tool arguments and unknown evidence are kept, and prompt and history representations map to stable message sources. - Sessions retire before protection changes. - An entry made before `sync`, by `session`, `run` or `runOnce`, is already marked protected, so the "no live policy binding" backstop applies to it. - `AgentSessions` tracks every process it starts, from the request to its exit, including a spare it took. `shutdown()` kills each one and waits for it, even one still starting. A pool that has shut down starts nothing. - A session subscriber that throws is logged and can't stop the others, so it can no longer break a shutdown before every process is killed and waited for. - A failed retirement is dropped rather than kept, so the agent can start again. - When the host's hook guard stops a worker for an invalid or oversized frame, it writes the reason to stderr, so the turn's error names it. - After a guarded worker exits, the host still delivers its last output, such as its final `result` or error. Only the guard's timers stop, and input to an exited worker is still refused. - **Security reviews.** Reviews run the pinned copy, contained and with no tools. Trusted instructions are kept apart from evidence. The output schema goes to native `--json-schema`, and the adapter requires `structured_output`, so formatted prose can't pass as a verdict. - Reviews, like protected agents, pass `--setting-sources ""`, so Claude reads no user, project or local settings file. A contained worker can't redirect reviews through `env` (such as `ANTHROPIC_BASE_URL`) or `apiKeyHelper` in `~/.claude/settings.json`. - **Own folder and sign-in** (Alex's idea of giving reviewers credentials that contained workers can't reach). Reviews run with `CLAUDE_CONFIG_DIR` set to `~/Library/Application Support/Buzz/claude-code-review-home`, and sign in with a `claude setup-token` token in `CLAUDE_CODE_OAUTH_TOKEN`. So a review reads nothing from `~/.claude`: no `.credentials.json` and no cached `remote-settings.json`. The companion creates that folder at 0700 and lists it in `hiddenPaths`, so contained workers can neither read nor write it. - **Setting it up.** The person runs `claude setup-token` in Terminal and pastes the token under **Sign in for reviews** in **Settings → Agent setup → Harness defaults → Claude → Edit configuration**. A new `claude.sh review-token` step reads it from stdin and prints only fixed lines, so the token never appears in argv, step output or the setup log. It refuses a folder that is a link or not a folder, and writes `token` at 0600 through an exclusive temp file and `mv -h`. A `review` step reads the folder and token back for the reviewer, skips a token that is a link, and off macOS fails with "Claude security reviews need macOS". Closing the dialog during a save cancels it, as Cancel does. - **Fail closed.** With no saved token, a review fails before the download or any model starts. Clear auth failures (`authentication_error`, or an expired or revoked OAuth token) map to one message that also says a Claude subscription is needed. - **Env hygiene.** The review env nulls `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`, `CLAUDE_CODE_API_BASE_URL`, `CLAUDE_CODE_SIMPLE`, `ANTHROPIC_UNIX_SOCKET`, `CLAUDE_CODE_REMOTE_SESSION_ID` and the `CLAUDE_CODE_USE_*` routes. - A review's 60 s budget now covers reading its sign-in and waiting for the pinned release's first download. A longer download fails the review closed and carries on for later reviews. - **File reads.** Buzz file tools and the transcript paths a worker chooses use the app-bundled reader under the captured policy. It accepts `~/…`, passes the filename as its own argument, and never falls back to an ordinary reader. - **Codex launcher fixes that are reachable from here.** `codex.sh` `run` and `adopt` already run uncontained at this point in the stack, so two link-following fixes land here rather than in #1879: - The sign-in handover moves Buzz's sign-in file onto the shared `auth.json` in one rename (`mv -f -h` on macOS). It no longer reads or writes through a link, so a worker can't use it to overwrite or copy out a protected file. A user's own link at `~/.codex/auth.json` is now replaced by a regular file, as `codex login` does; the Codex README says so. - `adopt` skips a saved thread that is a link, creates its copy as a new file (`set -C`, keeping the time with `touch -r`), and on macOS publishes it with `ln -P`. A link planted at the temporary name makes adopt stop without touching the target, and the thread starts new. - **CI.** `install-protected-claude-test.mjs` checks that both pins exist in the plugin manifest and match the release manifest before it checks the download. ### Known gaps and tradeoffs - Protected agents and Claude-model reviews need a release build of the macOS desktop app. In dev builds and on other platforms they fail closed. - Claude-model reviews sign in only with their own `claude setup-token` token. That needs a Claude Pro, Max, Team or Enterprise subscription and lasts a year. API-key, gateway, Bedrock and Vertex setups can't run Claude-model reviews; choose another review model. - **Existing users must sign in for reviews once.** Until the review sign-in is saved, and after it expires or is revoked, Claude-model reviews fail closed. - **Release coupling.** Ship the companion change (squareup/buzz-plugin-security#2) in the same Buzz release that carries both this PR and [#839](#839). The companion lists protected paths that may not exist yet, and a host without #839 refuses a protected launch when a listed path is missing. Without the companion change, the review folder is not hidden from contained workers. - **Process environment.** While a review runs, another process of the user can read the review token from that review's process environment. Whether contained agents can read the pinned binary's environment this way (`KERN_PROCARGS2`) has not been checked. Closing this needs a new host channel for the token, so it is documented instead. - **Protected runs still use `~/.claude`.** The review folder applies only to security reviews. Another contained worker can plant a sign-in, or cached managed settings that carry hooks and env, in `~/.claude`, and they reach a protected run's checks. Transcripts in `~/.claude/projects` can also be swapped between a run's checks or between the CLI's `--resume` load and Buzz's read for the review. Moving protected runs to a Buzz-owned folder would also move their sign-in, cached managed settings and session history, so it is a separate change. Both gaps are in `agent-protection.md`. - The review env's null list was read from 2.1.312's strings and is not yet checked against 2.1.305. - Review model choices come from the Claude in use, but reviews run 2.1.305. An alias such as `opus` resolves inside 2.1.305, and a model newer than it may be unknown to it. - A symlinked home directory, or any symlinked component of the artifact path, fails closed. Reinstalling doesn't help, because the install writes to the same path. - A spare still being handed over when a pool shuts down is killed as soon as it arrives, but not waited for. Spares serve only unprotected launches. - The first protected launch copies the release into the artifact store: about 273 MB on Apple silicon, 284 MB on Intel. Each review still hashes the release twice (the contained check, then the launch). - Older Buzz builds prune 2.1.305 from the shared download folder, so switching between builds can download it again. - Pi's protected runtime does not verify its runtime bytes at launch: it runs the shared host file and Node, made read-only for the worker, without hashing or copying them as this PR now does for Claude. Fixing it is a follow-up. - Planting a program on `PATH` stays outside the documented boundary. - A tool result Claude echoes over the 4 MiB frame cap, such as a large PDF or image, stops the turn closed, now with a reason. - Codex `adopt` keeps small residuals that bash can't close: a rollout swapped for a link between the check and the read can still be copied, linked folders along the path can place a new `rollout-*.jsonl` elsewhere, and noclobber still writes through a link to a FIFO or device. The handover guards only the last path part, so a linked `~/.codex` still receives `auth.json` in the folder it points to. - **Size.** The Claude review sign-in is about 195 production lines, against a checkpoint budget of about 55. The author chose to keep it as is. - Follow-ups not in this PR, tracked in [the follow-up issue](#2334) with the protected-run `CLAUDE_CONFIG_DIR` and Pi's runtime bytes: - a per-hook TypeScript deadline below the native 350 s, which would make a stalled review's error clearer; - removing the duplication in `protectedEvents`, and the O(n) source checks per hook; - a wall-clock hook deadline. Tokio's `Instant` stops during macOS sleep. If the CLI's hook timer doesn't stop, a laptop that sleeps through a pending `PostToolUse` review could let the CLI time out first, and that hook fails open; - caching the artifact snapshot's validation in the host, so a review doesn't hash the release twice; - carrying the Buzz destination explicitly in natively gated tool reviews, across Claude, Codex and Goose; - the shared 256 KiB action cap, which a long protected Claude conversation can reach. ### Validation Restacked onto main `066e34f12` with the round-2 fixes: now `4564d2b68` (stack tip `b85084bff`). Main's saved session prompts ([#1855](#1855)) overlapped the Claude runtime's session store: both are kept, the store keyed by protection state and main's `started` prompt save. At the stack tip (`b85084bff`): `pnpm check` (Biome, `tsc`, design checks), the integration suite (248 passed, 1 skipped), the full Vitest run (16,072 passed, 22 skipped), `cargo test -p buzzodz-plugins` (64), `cargo test --lib` in `src-tauri` (841 passed, 2 ignored), Clippy (`-D warnings`) and `cargo fmt --check` pass. One `src-tauri` test was left out: `window_state::tests::onboarding_snapshot_is_kept_until_next_launch_restore` crashes (SIGSEGV) on main as well (seen at `7cb3cb2c1`), and this stack doesn't change `window_state`. The round-2 checks below ran on the round-2 changes over `0caf2fd59`, before the restack. Round 2, on the changes over `0caf2fd59`: - `vitest run src/bundled/claude-code`: 316 passed, 4 skipped. `vitest run src/bundled/codex`: 297 passed, 2 skipped. `tsc --noEmit` and `biome check` on the changed files are clean. `bash -n` and `shellcheck -s bash` are clean for `claude.sh`; `codex.sh` has only the existing SC2174. - `cargo test --lib host_process`: 34 passed. Clippy (`-D warnings`) and `cargo fmt --check` are clean. - **New tests, each seen failing on the previous code:** - the pinned check starts the copy contained, never the download folder's file; - a cancelled wait for the pinned copy ends, during the check or the download, while one download serves the next caller; - a review's 60 s budget fires during a held install; - a failed install step is reported without checking the copy again; - a subscriber that throws during retirement no longer stops the worker being killed; - a guarded worker's last frame reaches the page after it exits, and the guard drains an exited worker's output but refuses its input; - a review without its own sign-in fails closed before any model; a review signs in with its own folder and token, over other sign-ins; only a refused sign-in maps to the sign-in message; the save step gets the token on stdin alone; - the review sign-in field saves through stdin, keeps its result, cancels a save from the footer and when the dialog closes, and keeps the field and Save focusable while a save is pending; - `claude.sh` saves the review sign-in privately, refuses a linked or non-folder home and a non-Claude token without printing it, and reads no sign-in through a link; - `codex.sh` never writes a handed-over sign-in through a link to a file or into a linked folder; adopt never copies a linked thread, never writes through a planted temporary link, and never hard-links what a swapped-in link points to. - **CI gap.** The `claude-sh` and `codex-sh` shell tests that depend on macOS are skipped elsewhere. CI's Vitest job runs on Ubuntu, so CI does not run them; they ran only locally on macOS. - **UI check.** Before the last polish, the real Claude configuration dialog body ran in Chromium through the browser test server: both themes, 390 px and 1280 px, root text at 200%, keyboard and pointer. That check found focus loss while a save was pending, and a dialog close that didn't cancel a save. Both are fixed and covered by the tests above, but the fixed version was not rendered again. - **Agent review:** independent reviews of the round-2 changes scored them 9 or higher with no blockers. Earlier rounds, at `29828e405` (stack tip `6b514fff4`), on main `6dc462a2d`, with later rebases onto main `61a67d28f`: - At this head, `vitest run src/bundled/claude-code`: 281 passed, 4 skipped, and `tsc --noEmit` is clean. At the stack tip, the Claude, Codex, Goose and Pi plugins, agent harness, agent protection, agents, Buzz MCP, Builderlab and scripts: 3,000 passed, 18 skipped. - At the stack tip: `cargo test --lib host_process`: 33 passed. `cargo test -p buzzodz-plugins`: 64 passed. Clippy (`-D warnings`) and `cargo fmt --check` are clean. - `biome check` and `tsc --noEmit` are clean at the stack tip. - After the rebase onto `61a67d28f`, one conflict: main's recent-notes read ([#2040](#2040)) now runs after the protection check at session launch; in protected sessions the notes reach the policy with the rest of the system prompt. The agent, Buzz MCP, relay, Builderlab, Inbox, Channels and scripts suites (6,882 passed, 22 skipped), `tsc --noEmit`, `cargo test --lib host_process` (33), `cargo test -p buzzodz-plugins` (64), Clippy (`-D warnings`) and `cargo fmt --check` passed there. - **New tests, each seen failing on the previous code:** - a review runs the pinned copy, contained; - a review installs the pin first, and fails without starting a worker when that install fails; - shutdown waits for processes still starting and for a spare it took, and starts nothing for a conversation still launching; - the backstop refuses a protected entry made before `sync`; - an agent runs again after its retirement failed. - **Other new tests:** a review passes `--setting-sources ""`; the hook guard's stderr reason and its quiet ordinary exit; `~/` artifact and protection paths; the `uname` mapping for both Mac architectures, refusing Linux; the manifest pins matching `PROTECTED_CLAUDE_ROOT` and `PROTECTED_CLAUDE_VERSION`; `claude.sh` keeping 2.1.305 when it switches past it. - **Agent review:** an independent review of the earlier round's fixes found no blockers. An independent review of the settings change scored it 9/10 with no blockers. ### Not yet done - No packaged-app run of the sandbox and the artifact copy. Dev builds refuse contained spawns. - The CI pin check runs only in hosted CI. I didn't download the release locally. - **Deferred live checks.** No pinned Claude 2.1.305 binary or real Claude account was run for the review sign-in. Not yet checked: - that `CLAUDE_SECURESTORAGE_CONFIG_DIR` and the keychain don't supply another sign-in; - a review with a fresh, empty `CLAUDE_CONFIG_DIR` (trust and onboarding skip, and Claude writing into that folder); - `CLAUDE_CODE_OAUTH_TOKEN` taking precedence over stored sign-ins, and its 401 behavior; - the real `claude setup-token` output, and the real error texts for an expired, revoked or non-subscription token; - whether remote managed settings are fetched into the review folder under an env token. - Not checked live: a Claude-model review under the flag with hostile settings files. - The companion creating and hiding the review folder was not run against this build in the app. - The Codex launcher fixes were checked only in fake homes, not against a real Codex. - The review sign-in field in the native app: both themes, narrow and wide widths, enlarged text, keyboard and pointer. - Human testing. <!-- buzz-security-flow:start --> ### Code flow ![[3/5] Add protection to the Claude harness plugin — illustrative code flow](https://raw.githubusercontent.com/block/buzz-app/f36b5077959f8c565487457947a479525ff4d05f/docs/assets/agent-protection/claude.png) Claude holds native input, tool actions and raw output. Its 350-second native watchdog stops stalled callbacks before the 600-second CLI timeout. Illustrative flow; checks shown enabled. Source: [claude.ts](https://github.com/block/buzz-app/blob/4564d2b68/src/bundled/claude-code/claude.ts), [claude_hooks.rs](https://github.com/block/buzz-app/blob/4564d2b68/src-tauri/src/host_process/claude_hooks.rs). <!-- buzz-security-flow:end --> Review and merge bottom to top: 1. [[1/5] Keep protected launches on the startup Agents root](#2044) (merged) 2. [[2/5] Pi harness integration](#1877) (merged) 3. [[3/5] Claude harness integration](#1878) (this PR) 4. [[4/5] Codex harness integration](#1879) 5. [[5/5] Goose harness integration](#839) Above these: [#2088](#2088) (exact history records) and [#2105](#2105) (denial reasons for the owner). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Alex Rosenzweig <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Codex <[email protected]>
1 parent f08310e commit 1da5031

39 files changed

Lines changed: 4274 additions & 158 deletions

‎.github/workflows/ci.yml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ jobs:
7575
with:
7676
key: agent-protection
7777
save-if: ${{ github.event_name == 'push' }}
78+
- name: Install exact protected Claude fixture
79+
run: ./bin/node scripts/install-protected-claude-test.mjs
80+
- name: Native Claude protection boundary
81+
env:
82+
BUZZ_TEST_WORKERS: "2"
83+
CLAUDE_PROTECTION_BIN: ${{ github.workspace }}/target/protected-claude-test/claude
84+
run: ./bin/node scripts/ci-test-report.mjs kind=vitest report=test-results/protection/native-vitest.json evidence=test-results/protection/native-timing.json title="Native security hooks" -- ./bin/pnpm exec vitest run src/bundled/claude-code/protection.live.test.ts --reporter=default --reporter=json --outputFile=test-results/protection/native-vitest.json
7885
- name: Native approval-state containment
7986
run: |
8087
mkdir -p test-results/protection

‎crates/plugin-manager/src/lib.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,11 @@ fn valid_sha256(hash: &str) -> bool {
144144
.bytes()
145145
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
146146
}
147+
/// An artifact is absolute, or under the user's home written `~/…`, which the
148+
/// host expands when it starts the process.
147149
fn valid_artifact(artifact: &ProcessArtifact) -> bool {
148150
let path = Path::new(&artifact.path);
149-
if !path.is_absolute()
151+
if !(path.is_absolute() || artifact.path.starts_with("~/"))
150152
|| artifact.path.len() > 4096
151153
|| artifact.path.contains('\0')
152154
|| !valid_sha256(&artifact.sha256)
@@ -2156,8 +2158,12 @@ mod tests {
21562158
"siblings": [{"name": "runtime.js", "sha256": "b".repeat(64)}]
21572159
});
21582160
assert!(artifact_from_text(&artifact.to_string(), "export const x = 1".into()).is_ok());
2161+
let mut home = artifact.clone();
2162+
home["host"]["processes"][0]["artifact"]["path"] = serde_json::json!("~/agent/cli");
2163+
assert!(artifact_from_text(&home.to_string(), "export const x = 1".into()).is_ok());
21592164
for (field, value) in [
21602165
("path", serde_json::json!("relative/agent")),
2166+
("path", serde_json::json!("~agent/cli")),
21612167
("sha256", serde_json::json!("A".repeat(64))),
21622168
("sha256", serde_json::json!("a".repeat(63))),
21632169
(

‎docs/agent-protection.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,5 +83,27 @@ is not general workstation isolation or a guarantee against code that runs later
8383
outside Buzz. Runtime and installed-plugin code remain trusted. Declared native
8484
artifacts are verified and staged before launch; that does not verify an entire
8585
runtime dependency graph or defend against other unsandboxed same-user programs.
86+
Claude's protected agents and security reviews run its pinned release this way:
87+
the host runs only its own verified copy, so a changed file in the download
88+
folder never runs. Both ignore Claude settings files, though Claude still reads
89+
its folder's sign-in and cached managed settings. Security reviews also have
90+
their own sign-in, in a Claude folder of their own that Buzz Security
91+
hides from contained agents (`~/Library/Application Support/Buzz/claude-code-review-home`).
92+
To set it up, run `claude setup-token` in Terminal, then paste the token it
93+
prints under **Sign in for reviews** in **Settings → Agent setup → Harness
94+
defaults → Claude → Edit configuration**. It needs a Claude Pro, Max, Team or
95+
Enterprise subscription, not an API key or gateway, and lasts a year. Until it
96+
is saved, and once it expires or is revoked, Claude reviews fail closed; save a
97+
new token or choose another review model. A review's 60-second budget includes
98+
waiting for Buzz to download that release the first time; a longer download
99+
fails the review closed and carries on for later reviews.
100+
Known Claude gaps: while a review runs, other processes of yours, likely
101+
contained agents too (not checked against the pinned release), can read its
102+
sign-in from the review's process environment. Protected Claude agents, unlike
103+
reviews, still use `~/.claude`, which other contained agents can write, so one
104+
can plant a sign-in there, or cached managed settings that carry hooks and env
105+
into a protected run's checks. Their transcripts live in `~/.claude/projects`
106+
too, so a contained agent can swap one between a run's checks or before it
107+
resumes.
86108
Broader restrictions on workspace writes, startup files and login jobs belong to
87109
Sandpit.

‎docs/buzz-help.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,10 @@ available rather than silently discarding it.
285285
- **Settings → Agent setup → Harness defaults** is where supported agent types
286286
offer installation, sign-in, and default-model controls. Available controls
287287
depend on the type. Do not assume a provider is configured or signed in.
288+
On macOS, Claude security reviews need their own sign-in: run
289+
`claude setup-token` in Terminal and paste its token under **Sign in for
290+
reviews** in Claude's **Edit configuration**. Until it is saved, Claude
291+
reviews fail closed. It needs a Claude subscription and lasts a year.
288292
- **Activity**, where the agent type provides it, shows sessions and their
289293
transcripts in the agent's profile. A turn's **Thread** or **Channel** label
290294
opens that conversation. Working indicators describe current work,

‎docs/plugin-architecture.md‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1199,19 +1199,21 @@ SIGKILL three seconds later; the group is always killed once the process exits,
11991199
so descendants do not outlive it. At most 64 processes run at once. Processes
12001200
run with the user's full access by default; the import preview says so.
12011201
`protection: { readOnlyPaths, hiddenPaths }` adds macOS containment for the worker
1202-
and descendants. Both arrays contain absolute existing paths. Read-only paths
1203-
reject writes; hidden paths reject reads and writes. The host adds its application,
1204-
plugin storage and actual Agents folder, blocks Apple Events, and refuses mutable
1205-
development frontends or unsupported operating systems.
1202+
and descendants. Both arrays contain existing paths, absolute or under the user's
1203+
home written `~/…`. Read-only paths reject writes; hidden paths reject reads and
1204+
writes. The host adds its application, plugin storage and actual Agents folder,
1205+
blocks Apple Events, and refuses mutable development frontends or unsupported
1206+
operating systems.
12061207

12071208
Contained launches require an app-bundled executable or an `artifact` descriptor;
1208-
PATH-only entrypoints are refused. Artifact descriptors name an absolute executable,
1209-
its SHA-256, and optional flat sibling files with their hashes. Native launch hashes
1210-
while copying those declared files into a content-addressed generation beneath the
1211-
actual shared Agents folder, then launches that copy. All contained workers are
1212-
prevented from writing this store. Corrupt generations fail closed and are never
1213-
repaired in place. Equivalent Windows path forms are accepted; symlinks remain
1214-
rejected. Control characters in containment paths refuse launch.
1209+
PATH-only entrypoints are refused. Artifact descriptors name an executable, absolute
1210+
or under the user's home written `~/…`, its SHA-256, and optional flat sibling files
1211+
with their hashes. Native launch hashes while copying those declared files into a
1212+
content-addressed generation beneath the actual shared Agents folder, then launches
1213+
that copy. All contained workers are prevented from writing this store. Corrupt
1214+
generations fail closed and are never repaired in place. Equivalent Windows path
1215+
forms are accepted; symlinks remain rejected. Control characters in containment
1216+
paths refuse launch.
12151217

12161218
This is approval-authority containment, covering the application, controls, private
12171219
approval state, and declared launch files. It does not verify every dependency an
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// CI's exact native fixture, without changing the user's Claude installation.
2+
// It also checks the plugin pins the bytes the release publishes.
3+
import { createHash } from "node:crypto";
4+
import { createReadStream } from "node:fs";
5+
import { chmod, mkdir, readFile } from "node:fs/promises";
6+
import { spawnSync } from "node:child_process";
7+
import { join } from "node:path";
8+
import { PROTECTED_CLAUDE_VERSION as version } from "../src/bundled/claude-code/security.ts";
9+
10+
const platform = `darwin-${process.arch === "arm64" ? "arm64" : "x64"}`;
11+
const plugin = JSON.parse(
12+
await readFile(
13+
new URL("../src/bundled/claude-code/manifest.json", import.meta.url),
14+
"utf8",
15+
),
16+
);
17+
if (process.platform !== "darwin")
18+
throw new Error("This fixture requires macOS");
19+
const base = `https://downloads.claude.ai/claude-code-releases/${version}`;
20+
function download(path, destination) {
21+
const result = spawnSync(
22+
"curl",
23+
[
24+
"-fsSL",
25+
"--connect-timeout",
26+
"15",
27+
"--max-time",
28+
"300",
29+
"--speed-limit",
30+
"1024",
31+
"--speed-time",
32+
"60",
33+
...(destination ? ["-o", destination] : []),
34+
`${base}/${path}`,
35+
],
36+
{ encoding: "utf8", timeout: 310000, maxBuffer: 1024 * 1024 },
37+
);
38+
if (result.status !== 0)
39+
throw new Error(
40+
`Claude fixture download failed: ${result.stderr || result.error || result.status}`,
41+
);
42+
return result.stdout;
43+
}
44+
const manifest = JSON.parse(download("manifest.json"));
45+
const checksum = manifest.platforms?.[platform]?.checksum;
46+
if (typeof checksum !== "string" || !/^[a-f0-9]{64}$/.test(checksum))
47+
throw new Error("The pinned release has no valid platform checksum");
48+
for (const arch of ["arm64", "x64"]) {
49+
const pinned = plugin.host.processes.find(
50+
(process) => process.id === `claude-protected-${arch}`,
51+
)?.artifact?.sha256;
52+
if (
53+
typeof pinned !== "string" ||
54+
pinned !== manifest.platforms?.[`darwin-${arch}`]?.checksum
55+
)
56+
throw new Error(
57+
`The plugin's ${arch} Claude pin does not match the release`,
58+
);
59+
}
60+
const root = join(process.cwd(), "target/protected-claude-test");
61+
await mkdir(root, { recursive: true });
62+
const binary = join(root, "claude");
63+
console.log(`Downloading pinned Claude ${version} (${platform})`);
64+
download(`${platform}/claude`, binary);
65+
const hash = createHash("sha256");
66+
for await (const chunk of createReadStream(binary)) hash.update(chunk);
67+
if (hash.digest("hex") !== checksum)
68+
throw new Error("The Claude fixture checksum does not match");
69+
await chmod(binary, 0o755);
70+
const result = spawnSync(binary, ["--version"], {
71+
encoding: "utf8",
72+
timeout: 15000,
73+
});
74+
if (result.status !== 0 || !result.stdout.startsWith(`${version} `))
75+
throw new Error(
76+
"The pinned Claude fixture did not start with the expected version",
77+
);
78+
console.log(`Claude ${version} verified at ${binary}`);

0 commit comments

Comments
 (0)