Sign-in: contain setup-token, prove its namespace gone
Astra round 1 on the sign-in by a link (four Important): - setup-token runs through the containment manager as a terminal launch (policy signin-v1): bubblewrap, its scratch home the only writable home, the dedicated home and runner state not mounted, BROWSER a no-op, egress to platform.claude.com and api.anthropic.com only, as read statically from the pinned 2.1.312 (TOKEN_URL and BASE_API_URL; setup-token stores no credential). - Stopping it kills the whole namespace and waits for proof before its record goes and before the home is deleted; an unproven stop leaves both for the next start. - The namespace record is kept in the attempt before the fork; a start after a crash proves it gone before removing the home. A real SIGKILL test on a runner process. - A link counts only once its end has arrived (every cut tested). From the same read, the runner presses Enter after "OAuth error" and shows the link the CLI then shows. Mutations are in the report.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
29 files changed,
+1,201
−217
.rastrillo/budgets.txt+2 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+36 −0docs/superpowers/specs/2026-11-08-equipo-connections.md+27 −9internal/fakeclaude/fake.go+3 −0internal/fakeclaude/setuptoken.go+147 −24internal/headless/signin_contained_test.go+158 −0internal/headless/signin_test.go+121 −7internal/runner/connect/pty_darwin.go+0 −12internal/runner/connect/pty_linux.go+0 −35internal/runner/connect/setuptoken.go+98 −68internal/runner/connect/setuptoken_test.go+22 −0internal/runner/containment/egress.go+5 −0internal/runner/containment/isolation.go+1 −1internal/runner/containment/linux.go+39 −9internal/runner/containment/mounts.go+16 −4internal/runner/containment/mounts_test.go+2 −2internal/runner/containment/sys_darwin.go+4 −0internal/runner/containment/sys_linux.go+29 −0internal/runner/egress/policy.go+12 −0internal/runner/provider/policy.go+3 −0internal/runner/provider/signin_policy.go+110 −0internal/runner/provider/signin_policy_test.go+67 −0internal/runner/thin/connector.go+22 −3internal/runner/thin/run.go+1 −1internal/runner/thin/signin.go+154 −30internal/runner/thin/signin_host_test.go+53 −0internal/runner/thin/signin_test.go+65 −10internal/runner/thin/state.go+3 −1internal/runner/thin/token_test.go+1 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 9207e9b5..58c59749 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -36,7 +36,7 @@ perf GET /releases/* skip Verified runner release file downloads, not browser GE |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; niced serial reruns measured 5.773s and 5.750s. The added coordinator mount check has no repeated launches to remove; 15s leaves 38 percent headroom for namespace, process-exit and recovery assertions. |
| time internal/tryequipo 30s Release starter-set controller K3 records CI runs of 10.8s and 13.1s; 30s retains the guide integration checks with headroom on the shared runner. |
| -size internal/runner/thin 15750 - Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| +size internal/runner/thin 15850 - Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| time internal/thintest 180s Mac runners slices A and B add role, scoping, migration, placement, withdrawal, transfer and publication contracts, and Astra round 1 eight transition contracts (about 15s; the package measured 126s locally under load). Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing a waiting test two seconds after it starts. About 6s alone; loaded CI measured 12.5s. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom. |
| @@ -63,4 +63,5 @@ perf GET /conversation/attachments/{id} skip Composer attachments: the bytes of |
| perf GET /conversation/attachments/{id}/preview skip Composer attachments: an image thumbnail inside the conversation; a file, not a screen. |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s Mac runners slice B: TestReleaseRunnerHasNoFakeWorker builds the release runner exactly as make release-runner does and the thin package under the testbuild tag (measured 11.9s locally with a warm cache). |
| +size internal/headless - 8300 Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. |
| size internal/thintest - 10000 Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 7db34810..87d38bec 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -6494,6 +6494,42 @@ and the connection browser tests (`-tags browser`). |
| | `same_machine` refused | accept it | `TestContractSameMachineRefused` | red (red first) | |
| | Runner ignores `same_machine` | route it elsewhere | `TestSignInIgnoresSameMachine` | red (red first) | |
| +### Review round 1 (Astra, d9cc4a8: request changes, four Important) |
| + |
| +- **Contained setup-token.** The CLI runs through the containment |
| + manager (`StartTerminal`, a terminal launch; policy `signin-v1`, |
| + `provider.BuildSignInPolicy`): bubblewrap, its scratch home the only |
| + writable home, the dedicated home and runner state not mounted, no |
| + workspace or tool socket, `BROWSER=/usr/bin/true`, egress through the |
| + relay to `platform.claude.com` and `api.anthropic.com`. Hosts read |
| + statically from the pinned 2.1.312: `TOKEN_URL` |
| + `https://platform.claude.com/v1/oauth/token`, `BASE_API_URL` |
| + `https://api.anthropic.com`; setup-token skips the profile fetch and |
| + credential storage and exits 500 ms after printing the token. No live |
| + sign-in, and no CONNECT to an allowed host from tests (a real |
| + connection to Anthropic); the refusal of a host off the list is |
| + tested. |
| +- **Descendants.** Stopping the CLI kills its namespace (pidfd SIGKILL |
| + to its init) and waits for proof, then forgets the record; the home |
| + is deleted only after. An unproven stop leaves the attempt and its |
| + home for the next start. |
| +- **Crash recovery.** The namespace record id is kept in the attempt |
| + before the fork; at start a sign-in attempt's home goes only after |
| + its namespace is recovered and forgotten. |
| +- **Truncated links.** A link counts only once its OSC 8 terminator, |
| + or for plain text a following character, has arrived. |
| +- Also from the static read: after "OAuth error: ..." the CLI waits for |
| + Enter; the runner presses it once and shows the link the CLI shows |
| + then (the same for an unreadable code, a new sign-in's for a refused |
| + one). The fake does the same. |
| + |
| +| Finding | Test (red first or mutation) | Mutation | Result | |
| +|---|---|---|---| |
| +| 4 truncated link | `TestAuthorizeNeverTruncated` (every cut of an OSC 8 and a plain screen) | red first; then accept an unterminated OSC 8; accept a plain link at the end | red, red | |
| +| 1 containment | `TestHeadlessSignInContained` (real bwrap: another home and runner state absent, writes only to its scratch home and /tmp, a CONNECT off the list 403 and counted); `TestSignInPolicyAttestation` | mount the runner's files into the sign-in | red: a canary readable | |
| +| 2 descendants | `TestHeadlessClaudeSignIn` (the CLI leaves a child ignoring SIGHUP and exits; none survives before the new link), `TestHeadlessSignInContained` | start the CLI outside a namespace, killing its group only while it runs (the reviewed code) | red: 1 child outlived it | |
| +| 3 crash recovery | `TestHeadlessSignInRunnerKilled` (SIGKILL to a runner process while setup-token waits; restart: runner_offline, home, record, scratch and every process of the namespace gone); `TestSignInRecoveryProvesNamespaceGone` | no recovery of a killed runner's namespaces; skip the proof before the home goes | red: record stayed; red: home removed unproven | |
| + |
| ### To confirm on the first live use |
| What CLI 2.1.312 prints after a right code (the runner takes the first |
diff --git a/docs/superpowers/specs/2026-11-08-equipo-connections.md b/docs/superpowers/specs/2026-11-08-equipo-connections.md| index ffe934e4..fcfa5621 100644 |
| --- a/docs/superpowers/specs/2026-11-08-equipo-connections.md |
| +++ b/docs/superpowers/specs/2026-11-08-equipo-connections.md |
| @@ -587,11 +587,26 @@ add Claude with the browser elsewhere, and case 1's loopback sign-in |
| "at this machine" too: the app refuses `same_machine` and the runner |
| ignores it. A token row's Sign in again and the renewal line start |
| this sign-in, the paste offered second. The runner runs the unmodified |
| -`claude setup-token` itself, on a pseudo-terminal in the connection's |
| -new home with the login environment and `BROWSER` a program that opens |
| -nothing, and reads the authorize URL it prints (through ANSI and OSC 8 |
| -escapes and redraws; only https on claude.com or claude.ai whose |
| -redirect is `platform.claude.com/oauth/code/callback`). The card |
| +`claude setup-token` itself, on a pseudo-terminal, contained like every |
| +provider launch (the `signin-v1` policy, `provider.BuildSignInPolicy`): |
| +its own bubblewrap namespace, recorded before anything forks, with the |
| +launch's scratch home its only writable home (the connection's |
| +dedicated home and the runner's state are not mounted; the runner |
| +writes the token into the home itself), no workspace or tool socket, |
| +`BROWSER` a program that opens nothing, and egress through the relay to |
| +`platform.claude.com` and `api.anthropic.com` only. Those hosts were |
| +read from the pinned CLI 2.1.312 statically: its production OAuth |
| +config has `TOKEN_URL` `https://platform.claude.com/v1/oauth/token` |
| +(the code exchange) and `BASE_API_URL` `https://api.anthropic.com`; |
| +setup-token fetches no profile and stores no credential, prints the |
| +token and exits after half a second. Stopping the CLI kills its whole |
| +namespace and waits for the exit to be proven, children included; |
| +after a runner crash the next start recovers the attempt's namespace |
| +(killed if it survived, its exit verified) before deleting its home. |
| +The runner reads the authorize URL the CLI prints (through ANSI and OSC |
| +8 escapes and redraws, only once the link's end has arrived; only https |
| +on claude.com or claude.ai whose redirect is |
| +`platform.claude.com/oauth/code/callback`). The card |
| (prompt kind `authorize_link`) shows Open Anthropic and Copy link, then |
| "Paste the code Anthropic shows you". The page seals the code exactly |
| as it seals a token, bound to `endpoint` |
| @@ -614,10 +629,13 @@ after the commit the restart carries it on as a token attempt. To |
| confirm on the first live use, since only the start was observed (CLI |
| 2.1.321): what the CLI prints after a right code (the runner takes the |
| first whole `sk-ant-oat` token in its output) and after a wrong one |
| -(the runner looks for error, invalid, failed, expired or wrong, then |
| -the prompt again), that a typed code followed by a separate carriage |
| -return is taken as entered, whether it exits after printing the token, |
| -and what it writes into the home. |
| +(the runner looks for error, invalid, failed, expired or wrong; the |
| +static read says "OAuth error: ..." then Enter to retry, the same link |
| +for a code it cannot read and a new sign-in for one the exchange |
| +refuses, and the runner presses Enter once), that a typed code followed |
| +by a separate carriage return is taken as entered, that the CLI honours |
| +the relay's proxy for the exchange, and what it writes into its scratch |
| +home (gone with the namespace either way). |
| **Sealing.** The app seals with libsodium `crypto_box_seal` over a |
| payload `{secret, runner_id, connection_id, provider, endpoint, |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index 96098506..052ddb96 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -114,6 +114,9 @@ func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { |
| fmt.Fprintln(stdout, Version+" (Claude Code)") |
| return 0 |
| } |
| + if len(args) == 1 && args[0] == "setup-token-child" && os.Getenv("FAKE_SETUP_CHILD") == "1" { |
| + return setupChild() |
| + } |
| if len(args) >= 1 && args[0] == "setup-token" { |
| return setupToken(args, stdin, stdout) |
| } |
diff --git a/internal/fakeclaude/setuptoken.go b/internal/fakeclaude/setuptoken.go| index 3cb36d3c..8820b208 100644 |
| --- a/internal/fakeclaude/setuptoken.go |
| +++ b/internal/fakeclaude/setuptoken.go |
| @@ -6,12 +6,15 @@ import ( |
| "encoding/hex" |
| "fmt" |
| "io" |
| + "net" |
| "net/url" |
| "os" |
| "os/exec" |
| + "os/signal" |
| "path/filepath" |
| "strconv" |
| "strings" |
| + "syscall" |
| "time" |
| "golang.org/x/sys/unix" |
| @@ -22,22 +25,29 @@ import ( |
| // browser to sign in…" (it runs $BROWSER with the URL), a spinner, then |
| // "Browser didn't open? Use the url below to sign in (c to copy)" and |
| // the authorize URL as an OSC 8 hyperlink, redrawn several times, then |
| -// the prompt "Paste code here if prompted > ". What follows a code was |
| -// not observed; the fake prints the token after a right code and an |
| -// error after a wrong one, then asks again (or exits, steered). |
| +// the prompt "Paste code here if prompted > ". After a code it does what |
| +// the pinned 2.1.312 does, read statically: the token, printed, then |
| +// exit; for a code it cannot read (no "#"), "OAuth error: Invalid code. |
| +// Please make sure the full code was copied" and, on Enter, the same |
| +// link again; for a code the exchange refuses, "OAuth error: |
| +// Authentication failed: Invalid authorization code" and, on Enter, a |
| +// new sign-in with a new link. |
| // |
| // A right code is SetupCode(email, state) for the state in the URL it |
| // printed: a code from another run's link is wrong. The token it prints |
| // is Token(email). It refuses to run off a terminal (as Ink does), with |
| // a BROWSER that is not a no-op (it would open one), or with anything |
| -// in argv but setup-token. |
| +// in argv but setup-token. A code starting "orphan" makes it start a child that |
| +// ignores a hangup and exit, leaving the child. |
| // |
| -// Steering, from SetupSteerFile beside the binary, one word a line: |
| +// Steering, from SetupSteerFile beside the binary (absent inside a |
| +// namespace, where the binary is /opt/claude), one word a line: |
| // "fail_start" exits before any URL; "exit_on_wrong" exits after a wrong |
| // code; "expire_ms=<n>" exits when no code came within n ms (the CLI's |
| -// own expiry). Every run appends its argv to SetupArgvFile and its pid |
| -// to SetupPidFile beside the binary, so a test sees what the runner |
| -// passed and whether the process is gone. |
| +// own expiry); "orphan" starts the child once the link shows. Every run |
| +// appends its argv to SetupArgvFile and its pid to SetupPidFile beside |
| +// the binary, so a test sees what the runner passed and whether the |
| +// process is gone. |
| const ( |
| SetupSteerFile = "setup-token.steer" |
| SetupArgvFile = "setup-token.argv" |
| @@ -98,21 +108,33 @@ func setupToken(args []string, stdin io.Reader, stdout io.Writer) int { |
| out("\x1b[31mError: could not start the sign-in\x1b[39m\r\n") |
| return 1 |
| } |
| - state := rand.Text() |
| - link := "https://claude.com/cai/oauth/authorize?code=true&client_id=9d1c250a-fake&response_type=code&redirect_uri=" + url.QueryEscape("https://platform.claude.com/oauth/code/callback") + "&scope=user%3Ainference&code_challenge=fake-challenge&code_challenge_method=S256&state=" + state |
| - out("Opening browser to sign in…\r\n") |
| - _ = exec.Command(browser, link).Run() |
| - for _, f := range []string{"⠋", "⠙", "⠹", "⠸"} { |
| - out("\r\x1b[2K\x1b[36m" + f + "\x1b[39m Waiting for sign-in…") |
| - time.Sleep(10 * time.Millisecond) |
| + // prompt draws the link and the prompt, redrawn as the CLI does. |
| + prompt := func(link string) { |
| + screen := "\r\x1b[2KBrowser didn't open? Use the url below to sign in \x1b[2m(c to copy)\x1b[22m\r\n\r\n\x1b]8;;" + link + "\x1b\\\x1b[34m" + link + "\x1b[39m\x1b]8;;\x1b\\\r\n\r\n\x1b[1mPaste code here if prompted >\x1b[22m " |
| + for i := 0; i < 3; i++ { |
| + if i > 0 { |
| + out("\x1b[4A\r\x1b[J") |
| + } |
| + out(screen) |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| } |
| - screen := "\r\x1b[2KBrowser didn't open? Use the url below to sign in \x1b[2m(c to copy)\x1b[22m\r\n\r\n\x1b]8;;" + link + "\x1b\\\x1b[34m" + link + "\x1b[39m\x1b]8;;\x1b\\\r\n\r\n\x1b[1mPaste code here if prompted >\x1b[22m " |
| - for i := 0; i < 3; i++ { |
| - if i > 0 { |
| - out("\x1b[4A\r\x1b[J") |
| + var state, link string |
| + // signIn starts a sign-in: a new state, a new link, the screen. |
| + signIn := func() { |
| + state = rand.Text() |
| + link = "https://claude.com/cai/oauth/authorize?code=true&client_id=9d1c250a-fake&response_type=code&redirect_uri=" + url.QueryEscape("https://platform.claude.com/oauth/code/callback") + "&scope=user%3Ainference&code_challenge=fake-challenge&code_challenge_method=S256&state=" + state |
| + out("Opening browser to sign in…\r\n") |
| + _ = exec.Command(browser, link).Run() |
| + for _, f := range []string{"⠋", "⠙", "⠹", "⠸"} { |
| + out("\r\x1b[2K\x1b[36m" + f + "\x1b[39m Waiting for sign-in…") |
| + time.Sleep(10 * time.Millisecond) |
| } |
| - out(screen) |
| - time.Sleep(10 * time.Millisecond) |
| + prompt(link) |
| + } |
| + signIn() |
| + if _, ok := steer["orphan"]; ok { |
| + orphan() |
| } |
| lines := make(chan string) |
| go func() { |
| @@ -143,16 +165,117 @@ func setupToken(args []string, stdin io.Reader, stdout io.Writer) int { |
| } |
| out("\x1b[36m⠋\x1b[39m Exchanging the code…\r\n") |
| time.Sleep(20 * time.Millisecond) |
| + if paths, ok := strings.CutPrefix(code, "probe:"); ok { |
| + // What this process can reach: the paths named, writes in |
| + // its namespace's places, a CONNECT to a host off the list. |
| + probe(out, strings.Split(paths, ",")) |
| + prompt(link) |
| + continue |
| + } |
| + if strings.HasPrefix(code, "orphan") { |
| + // A child that ignores a hangup and outlives this process. |
| + orphan() |
| + return 0 |
| + } |
| mid, got, ok := strings.Cut(code, "#") |
| email, err := hex.DecodeString(strings.TrimPrefix(mid, "fakecode-")) |
| if ok && got == state && strings.HasPrefix(mid, "fakecode-") && err == nil { |
| - out("\r\n\x1b[32m✓\x1b[39m Long-lived authentication token created successfully!\r\n\r\nYour OAuth token (valid for 1 year):\r\n\r\n\x1b[1m" + Token(string(email)) + "\x1b[22m\r\n\r\nStore this token securely. You won't be able to see it again.\r\n\r\nUse this token by setting: export CLAUDE_CODE_OAUTH_TOKEN=<token>\r\n") |
| + out("\r\n\x1b[32m✓\x1b[39m Long-lived authentication token created successfully!\r\n\r\nYour OAuth token (valid for 1 year):\r\n\r\n\x1b[33m" + Token(string(email)) + "\x1b[39m\r\n\r\nStore this token securely. You won't be able to see it again.\r\n\r\nUse this token by setting: export CLAUDE_CODE_OAUTH_TOKEN=<token>\r\n") |
| return 0 |
| } |
| - out("\r\n\x1b[31mOAuth error: Invalid code. Please make sure the full code was copied.\x1b[39m\r\n") |
| + // As 2.1.312: a code it cannot read keeps the link; one the |
| + // exchange refuses starts a new sign-in. Both wait for Enter. |
| + message := "Authentication failed: Invalid authorization code" |
| + if !ok || mid == "" || got == "" { |
| + message = "Invalid code. Please make sure the full code was copied" |
| + } |
| + out("\r\n\x1b[31mOAuth error: " + message + "\x1b[39m\r\n\r\nPress \x1b[1mEnter\x1b[22m to retry.\r\n") |
| if _, ok := steer["exit_on_wrong"]; ok { |
| return 1 |
| } |
| - out("\r\n\x1b[1mPaste code here if prompted >\x1b[22m ") |
| + select { |
| + case _, open := <-lines: |
| + if !open { |
| + return 1 |
| + } |
| + case <-time.After(expire): |
| + return 1 |
| + } |
| + if message == "Invalid code. Please make sure the full code was copied" { |
| + prompt(link) |
| + } else { |
| + signIn() |
| + } |
| + } |
| +} |
| + |
| +// orphan starts a child of this process that ignores a hangup and |
| +// outlives it (FAKE_SETUP_CHILD), as a CLI's helper could. |
| +func orphan() { |
| + self, err := os.Executable() |
| + if err != nil { |
| + return |
| + } |
| + ready, said, err := os.Pipe() |
| + if err != nil { |
| + return |
| + } |
| + cmd := exec.Command(self, "setup-token-child") |
| + cmd.Env = append(os.Environ(), "FAKE_SETUP_CHILD=1") |
| + cmd.ExtraFiles = []*os.File{said} |
| + if cmd.Start() == nil { |
| + // Only once it ignores a hangup: the exit sends one. |
| + said.Close() |
| + var b [1]byte |
| + _, _ = ready.Read(b[:]) |
| + } |
| + ready.Close() |
| +} |
| + |
| +// SetupChild is the orphan: it ignores SIGHUP, says so on fd 3, and |
| +// sleeps. |
| +func setupChild() int { |
| + signal.Ignore(syscall.SIGHUP) |
| + if f := os.NewFile(3, "ready"); f != nil { |
| + _, _ = f.Write([]byte{1}) |
| + f.Close() |
| + } |
| + time.Sleep(10 * time.Minute) |
| + return 0 |
| +} |
| + |
| +// probe reports, one "probe ..." line each, whether each path reads, |
| +// whether each of the namespace's places takes a write, and what the |
| +// egress proxy says to a CONNECT for a host off the sign-in's list; then |
| +// "probe done". |
| +func probe(out func(string), paths []string) { |
| + for _, p := range paths { |
| + _, err := os.ReadFile(p) |
| + word := "ok" |
| + if os.IsNotExist(err) { |
| + word = "absent" |
| + } else if err != nil { |
| + word = "denied" |
| + } |
| + out("probe read " + p + " " + word + "\r\n") |
| + } |
| + for _, p := range []string{"/home/runner/w", "/tmp/w", "/workspace/w", "/opt/w", "/etc/w", "/usr/w"} { |
| + word := "ok" |
| + if os.WriteFile(p, []byte("x"), 0600) != nil { |
| + word = "denied" |
| + } |
| + out("probe write " + p + " " + word + "\r\n") |
| + } |
| + status := "no-proxy" |
| + if proxy, err := url.Parse(os.Getenv("HTTPS_PROXY")); err == nil && proxy.Host != "" { |
| + status = "unreachable" |
| + if c, err := net.DialTimeout("tcp", proxy.Host, 5*time.Second); err == nil { |
| + _ = c.SetDeadline(time.Now().Add(10 * time.Second)) |
| + fmt.Fprintf(c, "CONNECT example.net:443 HTTP/1.1\r\nHost: example.net:443\r\n\r\n") |
| + line, _ := bufio.NewReader(c).ReadString('\n') |
| + status = strings.ReplaceAll(strings.TrimSpace(line), " ", "_") |
| + c.Close() |
| + } |
| } |
| + out("probe connect example.net " + status + "\r\nprobe done\r\n") |
| } |
diff --git a/internal/headless/signin_contained_test.go b/internal/headless/signin_contained_test.go| new file mode 100644 |
| index 00000000..1535c058 |
| --- /dev/null |
| +++ b/internal/headless/signin_contained_test.go |
| @@ -0,0 +1,158 @@ |
| +package headless |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/testci" |
| +) |
| + |
| +// The sign-in's `claude setup-token` (the fake) in the real namespace, |
| +// as the runner starts it (provider.BuildSignInPolicy, StartTerminal): |
| +// on a terminal; another account's home and the runner's state are not |
| +// there to read; it writes to disk only in its own scratch home and |
| +// /tmp, not to the workspace, /etc or /usr; a CONNECT to a host off its list |
| +// is refused by the egress proxy and counted. A child the CLI starts |
| +// that ignores a hangup dies with the namespace when the CLI exits, and |
| +// the namespace's scratch, where a code typed in could have been |
| +// written, is gone once its exit is proven. |
| +func TestHeadlessSignInContained(t *testing.T) { |
| + testci.Tools(t, "bwrap") |
| + if _, err := exec.LookPath("/usr/bin/bwrap"); err != nil { |
| + t.Skip("bubblewrap is required") |
| + } |
| + root := private(t, filepath.Join(t.TempDir(), "root")) |
| + bin := private(t, filepath.Join(root, "bin")) |
| + copyExecutable(t, filepath.Join(bin, "claude")) |
| + other := private(t, filepath.Join(root, "accounts", "claude-1")) |
| + state := private(t, filepath.Join(root, "state")) |
| + canaries := []string{filepath.Join(other, ".credentials.json"), filepath.Join(other, ".oauth-token"), filepath.Join(state, "thin.db"), filepath.Join(bin, "claude")} |
| + for _, f := range canaries[:3] { |
| + if err := os.WriteFile(f, []byte("CANARY-NOT-FOR-THE-SIGN-IN"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + scratch := private(t, filepath.Join(root, "scratch")) |
| + self, _ := os.Executable() |
| + m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + policy, err := provider.BuildSignInPolicy(provider.SignInPolicyInputs{Binary: filepath.Join(bin, "claude"), Bwrap: "/usr/bin/bwrap"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var mu sync.Mutex |
| + var record containment.Record |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) |
| + defer cancel() |
| + proc, err := m.StartTerminal(ctx, provider.Launch{AttemptKey: "signin/contained", Selection: provider.Selection{Provider: "claude"}, Policy: policy}, provider.SignInArgv, func(_ context.Context, r containment.Record) error { |
| + mu.Lock() |
| + record = r |
| + mu.Unlock() |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out bytes.Buffer |
| + read := make(chan struct{}) |
| + go func() { |
| + defer close(read) |
| + buf := make([]byte, 4096) |
| + for { |
| + n, err := proc.Stdout().Read(buf) |
| + mu.Lock() |
| + out.Write(buf[:n]) |
| + mu.Unlock() |
| + if err != nil { |
| + return |
| + } |
| + } |
| + }() |
| + seen := func(what string) string { |
| + t.Helper() |
| + deadline := time.Now().Add(time.Minute) |
| + for time.Now().Before(deadline) { |
| + mu.Lock() |
| + s := out.String() |
| + mu.Unlock() |
| + if strings.Contains(s, what) { |
| + return s |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + t.Fatalf("no %q in %q", what, out.String()) |
| + return "" |
| + } |
| + seen("Paste code here if prompted >") |
| + if _, err = proc.Stdin().Write([]byte("probe:" + strings.Join(canaries, ",") + "\r")); err != nil { |
| + t.Fatal(err) |
| + } |
| + screen := seen("probe done") |
| + for _, f := range canaries { |
| + if !strings.Contains(screen, "probe read "+f+" absent") { |
| + t.Errorf("%s is there to read in the namespace", f) |
| + } |
| + } |
| + // /opt is in bubblewrap's own root, in memory, as for every launch: |
| + // a write there reaches no host disk and ends with the namespace. |
| + for path, word := range map[string]string{"/home/runner/w": "ok", "/tmp/w": "ok", "/workspace/w": "denied", "/etc/w": "denied", "/usr/w": "denied"} { |
| + if !strings.Contains(screen, "probe write "+path+" "+word) { |
| + t.Errorf("write to %s is not %s", path, word) |
| + } |
| + } |
| + if !strings.Contains(screen, "probe connect example.net HTTP/1.1_403_Forbidden") { |
| + t.Errorf("a host off the list was not refused: %q", screen) |
| + } |
| + if d, ok := proc.(interface{ EgressDenials() uint64 }); !ok || d.EgressDenials() == 0 { |
| + t.Error("the refusal was not counted") |
| + } |
| + if strings.Contains(screen, "CANARY") { |
| + t.Fatal("the namespace read a canary") |
| + } |
| + |
| + // The CLI leaves a child that ignores a hangup, and exits: the |
| + // namespace ends with it, the child too, and its scratch goes. |
| + if _, err = proc.Stdin().Write([]byte("orphan-child\r")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = proc.Wait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + <-read |
| + mu.Lock() |
| + ns := record.NamespaceID |
| + id := record.ID |
| + mu.Unlock() |
| + if ns == "" { |
| + t.Fatal("no namespace recorded") |
| + } |
| + entries, _ := os.ReadDir("/proc") |
| + for _, e := range entries { |
| + if link, err := os.Readlink(filepath.Join("/proc", e.Name(), "ns", "pid")); err == nil && link == ns { |
| + t.Fatalf("process %s outlived the namespace", e.Name()) |
| + } |
| + } |
| + if children() != 0 { |
| + t.Fatal("the CLI's child outlived it") |
| + } |
| + if _, err = os.Stat(filepath.Join(scratch, "attempt-"+id)); !os.IsNotExist(err) { |
| + t.Fatalf("the namespace's scratch stayed: %v", err) |
| + } |
| + records, _ := m.Records(ctx) |
| + for _, r := range records { |
| + if err = m.Forget(ctx, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
diff --git a/internal/headless/signin_test.go b/internal/headless/signin_test.go| index 8743efa4..d34a9abe 100644 |
| --- a/internal/headless/signin_test.go |
| +++ b/internal/headless/signin_test.go |
| @@ -99,14 +99,27 @@ func TestHeadlessClaudeSignIn(t *testing.T) { |
| } |
| } |
| const email = "signin@example.com" |
| + // The CLI starts a child that ignores a hangup, and exits: before the |
| + // runner starts it again (a new link), the whole namespace is gone, |
| + // the child too. |
| + send("orphan-child", 1) |
| + s.wait(t, "the card after the CLI exited", time.Minute, func(cv *thintest.Conversation) bool { |
| + v := cv.Connections[c.ID].Prompt |
| + return v != nil && v.Attempt == 2 && v.URL != "" && v.URL != p.URL |
| + }) |
| + if n := children(); n != 0 { |
| + t.Fatalf("%d of the CLI's children outlived it", n) |
| + } |
| wrong := fakeclaude.SetupCode(email, "not-this-link") |
| - send(wrong, 1) |
| + send(wrong, 2) |
| s.wait(t, "the wrong-code card", time.Minute, func(cv *thintest.Conversation) bool { |
| v := cv.Connections[c.ID].Prompt |
| - return v != nil && v.Attempt == 2 && v.WrongCode && v.URL == p.URL |
| + return v != nil && v.Attempt == 3 && v.WrongCode && v.URL != "" |
| }) |
| + p = *latest(s, c.ID) |
| + u, _ = url.Parse(p.URL) |
| code := fakeclaude.SetupCode(email, u.Query().Get("state")) |
| - send(code, 2) |
| + send(code, 3) |
| var got wire.Connection |
| s.wait(t, "healthy", 2*time.Minute, func(cv *thintest.Conversation) bool { |
| got = cv.Connections[c.ID] |
| @@ -135,10 +148,8 @@ func TestHeadlessClaudeSignIn(t *testing.T) { |
| if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != got.LocalID { |
| t.Fatalf("turn on the new connection: %q", m.Text) |
| } |
| - argv, _ := os.ReadFile(filepath.Join(filepath.Dir(r.cfg.ClaudePath), fakeclaude.SetupArgvFile)) |
| - if string(argv) != "setup-token\n" { |
| - t.Fatalf("the CLI's argv: %q", argv) |
| - } |
| + // The CLI's argv is the policy's, attested at launch |
| + // (TestSignInPolicyAttestation): setup-token and nothing else. |
| // The canary sweep. |
| list, _ := env.Client.Connections(s.ctx) |
| @@ -181,3 +192,106 @@ func TestHeadlessClaudeSignIn(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// latest is the attempt's card now. |
| +func latest(s *session, id string) *wire.ConnectPrompt { |
| + var p wire.ConnectPrompt |
| + s.conv.Locked(func(c *thintest.Conversation) { |
| + if v := c.Connections[id].Prompt; v != nil { |
| + p = *v |
| + } |
| + }) |
| + return &p |
| +} |
| + |
| +// children counts the fake CLI's hangup-ignoring children still running |
| +// anywhere on this machine under this user. |
| +func children() int { |
| + n := 0 |
| + entries, _ := os.ReadDir("/proc") |
| + for _, e := range entries { |
| + raw, err := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline")) |
| + args := bytes.Split(raw, []byte{0}) |
| + if err == nil && len(args) >= 2 && string(args[1]) == "setup-token-child" && filepath.Base(string(args[0])) == "claude" { |
| + if stat, err := os.ReadFile(filepath.Join("/proc", e.Name(), "stat")); err == nil && !bytes.Contains(stat, []byte(") Z ")) { |
| + n++ |
| + } |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// A real crash (Paul's runner killed with SIGKILL) while the contained |
| +// setup-token waits for a code: the namespace recorded for the attempt |
| +// dies with the runner or is killed by the next start's recovery, which |
| +// proves it gone before it deletes the attempt's home and ends it |
| +// runner_offline. Nothing of the namespace is left: no process in it, |
| +// no record, no scratch, no child of the CLI. |
| +func TestHeadlessSignInRunnerKilled(t *testing.T) { |
| + env, _, r := localEnv(t) |
| + r.subprocess = true |
| + r.only(t) |
| + homes := func() map[string]bool { |
| + out := map[string]bool{} |
| + entries, _ := os.ReadDir(filepath.Join(r.root, "accounts")) |
| + for _, e := range entries { |
| + out[e.Name()] = true |
| + } |
| + return out |
| + } |
| + before := homes() |
| + r.start(t) |
| + s := open(t, env) |
| + c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.wait(t, "the sign-in link", time.Minute, func(cv *thintest.Conversation) bool { |
| + v := cv.Connections[c.ID].Prompt |
| + return v != nil && v.URL != "" |
| + }) |
| + var home string |
| + for name := range homes() { |
| + if !before[name] { |
| + home = filepath.Join(r.root, "accounts", name) |
| + } |
| + } |
| + // The namespace the runner recorded for the attempt's CLI. |
| + var ns, id string |
| + files, _ := filepath.Glob(filepath.Join(r.cfg.ScratchRoot, "*.json")) |
| + for _, f := range files { |
| + var rec struct{ ID, AttemptKey, NamespaceID string } |
| + raw, _ := os.ReadFile(f) |
| + if json.Unmarshal(raw, &rec) == nil && strings.HasPrefix(rec.AttemptKey, "signin/"+c.ID+"/") { |
| + ns, id = rec.NamespaceID, rec.ID |
| + } |
| + } |
| + if home == "" || ns == "" { |
| + t.Fatalf("home %q, namespace %q", home, ns) |
| + } |
| + r.kill(t) |
| + r.start(t) |
| + var end wire.Connection |
| + s.wait(t, "the attempt's end", 2*time.Minute, func(cv *thintest.Conversation) bool { |
| + end = cv.Connections[c.ID] |
| + return end.State != wire.ConnConnecting |
| + }) |
| + if end.State != wire.ConnError || end.Reason != "runner_offline" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + until(t, "the home gone", func() bool { _, err := os.Stat(home); return os.IsNotExist(err) }) |
| + entries, _ := os.ReadDir("/proc") |
| + for _, e := range entries { |
| + if link, err := os.Readlink(filepath.Join("/proc", e.Name(), "ns", "pid")); err == nil && link == ns { |
| + t.Fatalf("process %s of the killed runner's namespace survived", e.Name()) |
| + } |
| + } |
| + for _, leftover := range []string{filepath.Join(r.cfg.ScratchRoot, id+".json"), filepath.Join(r.cfg.ScratchRoot, "attempt-"+id)} { |
| + if _, err := os.Stat(leftover); !os.IsNotExist(err) { |
| + t.Fatalf("%s stayed: %v", leftover, err) |
| + } |
| + } |
| + if children() != 0 { |
| + t.Fatal("a child of the CLI survived") |
| + } |
| +} |
diff --git a/internal/runner/connect/pty_darwin.go b/internal/runner/connect/pty_darwin.go| deleted file mode 100644 |
| index 8fd82439..00000000 |
| --- a/internal/runner/connect/pty_darwin.go |
| +++ /dev/null |
| @@ -1,12 +0,0 @@ |
| -package connect |
| - |
| -import ( |
| - "errors" |
| - "os" |
| -) |
| - |
| -// openPTY: signing in on a Mac waits for probe P3 (Mac runners spec |
| -// §3.4); a Mac worker runs checks, which need no account. |
| -func openPTY() (*os.File, *os.File, error) { |
| - return nil, nil, errors.New("signing in on a Mac runner is not available yet") |
| -} |
diff --git a/internal/runner/connect/pty_linux.go b/internal/runner/connect/pty_linux.go| deleted file mode 100644 |
| index b241bc16..00000000 |
| --- a/internal/runner/connect/pty_linux.go |
| +++ /dev/null |
| @@ -1,35 +0,0 @@ |
| -package connect |
| - |
| -import ( |
| - "fmt" |
| - "os" |
| - |
| - "golang.org/x/sys/unix" |
| -) |
| - |
| -// openPTY opens a pseudo-terminal pair, wide enough that the CLI never |
| -// wraps a line. |
| -func openPTY() (*os.File, *os.File, error) { |
| - master, err := os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) |
| - if err != nil { |
| - return nil, nil, err |
| - } |
| - fd := int(master.Fd()) |
| - if err = unix.IoctlSetPointerInt(fd, unix.TIOCSPTLCK, 0); err != nil { |
| - master.Close() |
| - return nil, nil, err |
| - } |
| - n, err := unix.IoctlGetInt(fd, unix.TIOCGPTN) |
| - if err != nil { |
| - master.Close() |
| - return nil, nil, err |
| - } |
| - tty, err := os.OpenFile(fmt.Sprintf("/dev/pts/%d", n), os.O_RDWR|unix.O_NOCTTY, 0) |
| - if err != nil { |
| - master.Close() |
| - return nil, nil, err |
| - } |
| - ws := unix.Winsize{Row: 50, Col: 1000} |
| - _ = unix.IoctlSetWinsize(int(tty.Fd()), unix.TIOCSWINSZ, &ws) |
| - return master, tty, nil |
| -} |
diff --git a/internal/runner/connect/setuptoken.go b/internal/runner/connect/setuptoken.go| index c8a1feab..e1d7ead1 100644 |
| --- a/internal/runner/connect/setuptoken.go |
| +++ b/internal/runner/connect/setuptoken.go |
| @@ -3,18 +3,14 @@ package connect |
| import ( |
| "bytes" |
| "context" |
| - "errors" |
| + "io" |
| "net/url" |
| - "os" |
| - "os/exec" |
| "regexp" |
| "strings" |
| "sync" |
| - "syscall" |
| "time" |
| "amadan.net/oficina/equipo/internal/wire" |
| - "golang.org/x/sys/unix" |
| ) |
| // Claude's sign-in with no terminal (Paul, 2026-11-10: "Can you not run |
| @@ -27,10 +23,6 @@ import ( |
| // the token and a failure; it is never logged or returned, and it is |
| // zeroed when the run ends (it echoes the code and shows the token). |
| -// ErrNoBrowser: neither /usr/bin/true nor /bin/true is there to stand in |
| -// for a browser. |
| -var ErrNoBrowser = errors.New("no no-op browser") |
| - |
| // Outcomes of a typed code (SetupToken.Result). |
| const ( |
| // CodeToken: the CLI printed a token. |
| @@ -59,16 +51,6 @@ var ( |
| failPattern = regexp.MustCompile(`(?i)\b(error|invalid|failed|failure|expired|wrong|try again)\b`) |
| ) |
| -// noBrowser is a program that opens nothing: the CLI's BROWSER. |
| -func noBrowser() (string, error) { |
| - for _, p := range []string{"/usr/bin/true", "/bin/true"} { |
| - if info, err := os.Stat(p); err == nil && info.Mode().IsRegular() && info.Mode()&0111 != 0 { |
| - return p, nil |
| - } |
| - } |
| - return "", ErrNoBrowser |
| -} |
| - |
| // AuthorizeURL checks a URL the CLI printed: Anthropic's own authorize |
| // page on claude.com or claude.ai, over https, whose redirect is the code |
| // page (wire.EndpointClaudeCode) that shows the person a code to paste. |
| @@ -127,7 +109,9 @@ func visible(raw []byte) (text []byte, links []string) { |
| if end == len(raw) { |
| i = len(raw) |
| } |
| - if raw[start-1] == ']' { |
| + // An OSC not yet terminated is not yet a link: its target |
| + // may still be arriving. |
| + if raw[start-1] == ']' && end < len(raw) { |
| // OSC 8 ; params ; URI |
| if body := string(raw[start:end]); strings.HasPrefix(body, "8;") { |
| if _, target, ok := strings.Cut(body[2:], ";"); ok && target != "" { |
| @@ -150,7 +134,8 @@ func visible(raw []byte) (text []byte, links []string) { |
| } |
| // authorizeIn finds the first valid authorize URL in raw: an OSC 8 |
| -// target first, else the visible text. |
| +// target first, else the visible text; only whole ones (TestAuthorize |
| +// NeverTruncated). |
| func authorizeIn(raw []byte) (string, bool) { |
| text, links := visible(raw) |
| defer clear(text) |
| @@ -159,8 +144,13 @@ func authorizeIn(raw []byte) (string, bool) { |
| return u, true |
| } |
| } |
| - for _, m := range linkPattern.FindAll(text, -1) { |
| - if u, ok := AuthorizeURL(string(m)); ok { |
| + // A visible link counts once something follows it: the rest of it |
| + // may still be arriving. |
| + for _, loc := range linkPattern.FindAllIndex(text, -1) { |
| + if loc[1] == len(text) { |
| + continue |
| + } |
| + if u, ok := AuthorizeURL(string(text[loc[0]:loc[1]])); ok { |
| return u, true |
| } |
| } |
| @@ -193,52 +183,46 @@ func failedAt(text []byte) int { |
| return -1 |
| } |
| +// Terminal is one run of the CLI on a pseudo-terminal, started by its |
| +// host inside the launch's containment: reads and writes go to the |
| +// terminal; Done is closed once the CLI has exited; Stop ends the whole |
| +// launch boundary (every process the CLI started, whether or not it is |
| +// still running itself) and returns only once that is proven, or with |
| +// an error when it cannot be. |
| +type Terminal interface { |
| + io.ReadWriter |
| + Done() <-chan struct{} |
| + Stop() error |
| +} |
| + |
| // SetupToken is one run of `claude setup-token`. |
| type SetupToken struct { |
| - cmd *exec.Cmd |
| - master *os.File |
| - exited chan struct{} |
| + term Terminal |
| + exited <-chan struct{} |
| read chan struct{} |
| more chan struct{} |
| mu sync.Mutex |
| // raw is the last of what the CLI printed; mark is where in raw the |
| // output after the last typed code starts; asked says the CLI asked |
| - // again for a code before mark. |
| + // again for a code before mark; link is the latest whole link. |
| raw []byte |
| mark int |
| asked bool |
| + link string |
| } |
| -// StartSetupToken starts the CLI in home with env (the login |
| -// environment), its BROWSER a program that opens nothing. |
| -func StartSetupToken(binary, home string, env []string) (*SetupToken, error) { |
| - browser, err := noBrowser() |
| - if err != nil { |
| - return nil, err |
| - } |
| - master, tty, err := openPTY() |
| - if err != nil { |
| - return nil, err |
| - } |
| - cmd := exec.Command(binary, "setup-token") |
| - cmd.Dir = home |
| - cmd.Env = append(append([]string{}, env...), "BROWSER="+browser, "TERM=xterm-256color") |
| - cmd.Stdin, cmd.Stdout, cmd.Stderr = tty, tty, tty |
| - cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true} |
| - if err = cmd.Start(); err != nil { |
| - tty.Close() |
| - master.Close() |
| - return nil, err |
| - } |
| - tty.Close() |
| - s := &SetupToken{cmd: cmd, master: master, exited: make(chan struct{}), read: make(chan struct{}), more: make(chan struct{}, 1)} |
| +// NewSetupToken reads the CLI's output on term from now on. The host |
| +// started it as `claude setup-token` with BROWSER a program that opens |
| +// nothing (provider.BuildSignInPolicy). |
| +func NewSetupToken(term Terminal) *SetupToken { |
| + s := &SetupToken{term: term, exited: term.Done(), read: make(chan struct{}), more: make(chan struct{}, 1)} |
| go func() { |
| defer close(s.read) |
| buf := make([]byte, 8192) |
| defer clear(buf) |
| for { |
| - n, err := master.Read(buf) |
| + n, err := term.Read(buf) |
| if n > 0 { |
| s.mu.Lock() |
| s.raw = append(s.raw, buf[:n]...) |
| @@ -256,11 +240,10 @@ func StartSetupToken(binary, home string, env []string) (*SetupToken, error) { |
| } |
| }() |
| go func() { |
| - _ = cmd.Wait() |
| - close(s.exited) |
| + <-s.exited |
| s.poke() |
| }() |
| - return s, nil |
| + return s |
| } |
| func (s *SetupToken) poke() { |
| @@ -310,6 +293,9 @@ func (s *SetupToken) URL(ctx context.Context) (string, error) { |
| } |
| s.mu.Lock() |
| u, ok := authorizeIn(s.raw) |
| + if ok { |
| + s.link = u |
| + } |
| s.mu.Unlock() |
| if ok { |
| return u, nil |
| @@ -346,7 +332,7 @@ func (s *SetupToken) Submit(ctx context.Context, code []byte) error { |
| s.mu.Lock() |
| s.mark, s.asked = len(s.raw), false |
| s.mu.Unlock() |
| - if _, err := s.master.Write(code); err != nil { |
| + if _, err := s.term.Write(code); err != nil { |
| return err |
| } |
| // Enter apart from the text, so it is a key press and not part of a |
| @@ -356,16 +342,22 @@ func (s *SetupToken) Submit(ctx context.Context, code []byte) error { |
| return ctx.Err() |
| case <-time.After(150 * time.Millisecond): |
| } |
| - _, err := s.master.Write([]byte{'\r'}) |
| + _, err := s.term.Write([]byte{'\r'}) |
| return err |
| } |
| // Result waits for what the CLI does with the code: a token (returned; |
| -// the caller clears it), a failure with the prompt shown again while it |
| -// runs (CodeAgain), or nothing more (CodeEnded: it exited, or said the |
| -// code failed and asked for no other within giveUp). |
| +// the caller clears it), a failure after which the CLI asks again while |
| +// it runs (CodeAgain; Link is then the link to show), or nothing more |
| +// (CodeEnded: it exited, or said the code failed and asked for no other |
| +// within giveUp). The pinned CLI (2.1.312, read statically) shows a |
| +// failed code as "OAuth error: ..." and waits for Enter to retry: for a |
| +// code it could not read, at the same link; for one the exchange |
| +// refused, in a new sign-in with a new link. Result presses Enter once |
| +// for it. |
| func (s *SetupToken) Result(ctx context.Context) (string, []byte, error) { |
| var failed time.Time |
| + pressed := false |
| for { |
| ended := s.done() |
| if ended { |
| @@ -387,13 +379,23 @@ func (s *SetupToken) Result(ctx context.Context) (string, []byte, error) { |
| failed = time.Now() |
| } |
| if again { |
| - // Asked again: let the screen settle, then hand the prompt back. |
| + // Asked again: let the screen settle, then hand the prompt |
| + // back with the link it shows now. |
| if time.Since(failed) >= 500*time.Millisecond { |
| s.mu.Lock() |
| s.mark, s.asked = len(s.raw), true |
| + if u, ok := lastAuthorize(s.raw); ok { |
| + s.link = u |
| + } |
| s.mu.Unlock() |
| return CodeAgain, nil, nil |
| } |
| + } else if !failed.IsZero() && !pressed && time.Since(failed) >= time.Second { |
| + // The error screen waits for Enter to retry. |
| + pressed = true |
| + if _, err := s.term.Write([]byte{'\r'}); err != nil { |
| + return CodeEnded, nil, nil |
| + } |
| } else if !failed.IsZero() && time.Since(failed) > giveUp { |
| return CodeEnded, nil, nil |
| } |
| @@ -403,17 +405,44 @@ func (s *SetupToken) Result(ctx context.Context) (string, []byte, error) { |
| } |
| } |
| +// Link is the latest whole link the CLI printed. |
| +func (s *SetupToken) Link() string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.link |
| +} |
| + |
| +// lastAuthorize finds the last valid authorize URL in raw, as |
| +// authorizeIn finds the first. |
| +func lastAuthorize(raw []byte) (string, bool) { |
| + text, links := visible(raw) |
| + defer clear(text) |
| + for i := len(links) - 1; i >= 0; i-- { |
| + if u, ok := AuthorizeURL(links[i]); ok { |
| + return u, true |
| + } |
| + } |
| + locs := linkPattern.FindAllIndex(text, -1) |
| + for i := len(locs) - 1; i >= 0; i-- { |
| + if locs[i][1] == len(text) { |
| + continue |
| + } |
| + if u, ok := AuthorizeURL(string(text[locs[i][0]:locs[i][1]])); ok { |
| + return u, true |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| // Done is closed once the CLI has exited, on its own or stopped. |
| func (s *SetupToken) Done() <-chan struct{} { return s.exited } |
| -// Close stops the CLI and its process group, waits for it, and zeroes |
| -// everything it printed. |
| -func (s *SetupToken) Close() { |
| - if !s.done() { |
| - _ = unix.Kill(-s.cmd.Process.Pid, unix.SIGKILL) |
| - } |
| - <-s.exited |
| - s.master.Close() |
| +// Close stops the CLI and everything it started (Terminal.Stop: the |
| +// whole launch boundary, proven gone) and zeroes everything it printed. |
| +// An error says the boundary could not be proven gone: the caller keeps |
| +// what it would delete until recovery proves it. |
| +func (s *SetupToken) Close() error { |
| + err := s.term.Stop() |
| select { |
| case <-s.read: |
| case <-time.After(2 * time.Second): |
| @@ -422,4 +451,5 @@ func (s *SetupToken) Close() { |
| clear(s.raw) |
| s.raw, s.mark = nil, 0 |
| s.mu.Unlock() |
| + return err |
| } |
diff --git a/internal/runner/connect/setuptoken_test.go b/internal/runner/connect/setuptoken_test.go| index 7cb7f715..b2f16df9 100644 |
| --- a/internal/runner/connect/setuptoken_test.go |
| +++ b/internal/runner/connect/setuptoken_test.go |
| @@ -92,3 +92,25 @@ func TestTokenAndFailure(t *testing.T) { |
| t.Fatalf("failure at %d", at) |
| } |
| } |
| + |
| +// Output read in pieces: a link cut anywhere is not a link until its end |
| +// is there (the OSC 8 terminator, or for plain text a space or line end |
| +// after it). Every cut of the hyperlinked screen and of a plain one |
| +// finds nothing or the whole link, never a prefix. |
| +func TestAuthorizeNeverTruncated(t *testing.T) { |
| + osc := "Use the url below to sign in\r\n\x1b]8;;" + authorize + "\x1b\\" + authorize + "\x1b]8;;\x1b\\\r\nPaste code here if prompted > " |
| + plain := "Use the url below to sign in\r\n" + authorize + "\r\nPaste code here if prompted > " |
| + for name, screen := range map[string]string{"hyperlink": osc, "plain": plain} { |
| + whole := false |
| + for cut := 0; cut <= len(screen); cut++ { |
| + got, ok := authorizeIn([]byte(screen[:cut])) |
| + if ok && got != authorize { |
| + t.Fatalf("%s cut at %d: took %q", name, cut, got) |
| + } |
| + whole = whole || ok |
| + } |
| + if !whole { |
| + t.Fatalf("%s: never found", name) |
| + } |
| + } |
| +} |
diff --git a/internal/runner/containment/egress.go b/internal/runner/containment/egress.go| index 96c4758e..ea588614 100644 |
| --- a/internal/runner/containment/egress.go |
| +++ b/internal/runner/containment/egress.go |
| @@ -27,6 +27,11 @@ func (m *Manager) openEgress(ctx context.Context, l provider.Launch, dir string, |
| } |
| } |
| policy, e := egress.ProviderPolicy(contract, l.Binding.VerifiedDedicatedHome()) |
| + if l.Policy.IsSignIn() { |
| + // Claude's sign-in reaches its sign-in and API hosts, nothing |
| + // else (provider.SignInHosts). |
| + policy, e = egress.SignInPolicy(contract) |
| + } |
| if e != nil { |
| return "", e |
| } |
diff --git a/internal/runner/containment/isolation.go b/internal/runner/containment/isolation.go| index ccae7da9..3bdac417 100644 |
| --- a/internal/runner/containment/isolation.go |
| +++ b/internal/runner/containment/isolation.go |
| @@ -86,7 +86,7 @@ func (m *Manager) ProbeIsolation(ctx context.Context, l provider.Launch, targets |
| ctx, cancel := context.WithTimeout(ctx, 20*time.Second) |
| defer cancel() |
| l.AttemptKey += "/isolation/" + report.Layer |
| - p, err := m.startRecorded(ctx, l, manifest.Argv, nil, command) |
| + p, err := m.startRecorded(ctx, l, manifest.Argv, nil, command, false) |
| if err != nil { |
| return report, err |
| } |
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go| index 75800e6e..87233404 100644 |
| --- a/internal/runner/containment/linux.go |
| +++ b/internal/runner/containment/linux.go |
| @@ -16,6 +16,7 @@ import ( |
| "runtime" |
| "strconv" |
| "sync" |
| + "syscall" |
| "time" |
| unix "amadan.net/oficina/equipo/internal/runner/containment/sysunix" |
| @@ -151,10 +152,24 @@ func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) ( |
| } |
| func (m *Manager) StartRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error) (provider.Process, error) { |
| - return m.startRecorded(ctx, l, argv, record, nil) |
| + if l.Policy.IsSignIn() { |
| + return nil, errStartup |
| + } |
| + return m.startRecorded(ctx, l, argv, record, nil, false) |
| } |
| -func (m *Manager) startRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error, probe []string) (provider.Process, error) { |
| +// StartTerminal starts a sign-in launch (provider.BuildSignInPolicy) as |
| +// StartRecorded starts any other, with the harness's stdin and stdout a |
| +// pseudo-terminal: its Stdin and Stdout are the terminal's master side. |
| +// Only a sign-in gets a terminal. |
| +func (m *Manager) StartTerminal(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error) (provider.Process, error) { |
| + if !l.Policy.IsSignIn() { |
| + return nil, errStartup |
| + } |
| + return m.startRecorded(ctx, l, argv, record, nil, true) |
| +} |
| + |
| +func (m *Manager) startRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error, probe []string, terminal bool) (provider.Process, error) { |
| if e := ctx.Err(); e != nil { |
| return nil, e |
| } |
| @@ -264,7 +279,7 @@ func (m *Manager) startRecorded(ctx context.Context, l provider.Launch, argv []s |
| // The goroutine that forks also waits. Keeping its OS thread locked prevents |
| // Go's Pdeathsig from firing when an unrelated calling goroutine returns. |
| finished := make(chan struct{}) |
| - go func() { m.lifecycle(ctx, r, argv, mounts, dir, result, record); close(finished) }() |
| + go func() { m.lifecycle(ctx, r, argv, mounts, dir, result, record, terminal); close(finished) }() |
| cleanup = false |
| transferred = true |
| resultValue := <-result |
| @@ -290,7 +305,7 @@ type readiness struct { |
| } |
| func pipePair() (*os.File, *os.File, error) { return os.Pipe() } |
| -func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts *mounts, dir string, result chan<- startResult, admit func(context.Context, Record) error) { |
| +func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts *mounts, dir string, result chan<- startResult, admit func(context.Context, Record) error, terminal bool) { |
| runtime.LockOSThread() |
| defer runtime.UnlockOSThread() |
| cleanupScratch := true |
| @@ -341,12 +356,27 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts |
| result <- startResult{err: e} |
| return |
| } |
| - inputR, inputW, e := pipe() |
| - if e != nil { |
| - result <- startResult{err: e} |
| - return |
| + var inputR, inputW, outputR, outputW *os.File |
| + if terminal { |
| + // One terminal for the harness's input and output: the slave side |
| + // is its stdin and stdout, the master side the caller's. |
| + inputW, inputR, e = OpenTerminal() |
| + if e == nil { |
| + files = append(files, inputW, inputR) |
| + var fd int |
| + if fd, e = syscall.Dup(int(inputW.Fd())); e == nil { |
| + syscall.CloseOnExec(fd) |
| + outputR = os.NewFile(uintptr(fd), "terminal") |
| + outputW = inputR |
| + files = append(files, outputR) |
| + } |
| + } |
| + } else { |
| + inputR, inputW, e = pipe() |
| + if e == nil { |
| + outputR, outputW, e = pipe() |
| + } |
| } |
| - outputR, outputW, e := pipe() |
| if e != nil { |
| result <- startResult{err: e} |
| return |
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go| index aead7157..c846be3d 100644 |
| --- a/internal/runner/containment/mounts.go |
| +++ b/internal/runner/containment/mounts.go |
| @@ -139,11 +139,16 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error |
| p.close() |
| } |
| }() |
| - if !cleanAbsolute(l.Workspace) || overlaps(l.Workspace, m.cfg.ScratchRoot) { |
| + // A sign-in has no workspace: an empty read-only one. |
| + signIn := l.Policy.IsSignIn() |
| + if signIn && (l.Workspace != "" || l.Binding.Home != "" || l.ToolSocket != "") { |
| + return nil, errMount |
| + } |
| + if !signIn && (!cleanAbsolute(l.Workspace) || overlaps(l.Workspace, m.cfg.ScratchRoot)) { |
| return nil, errMount |
| } |
| for _, root := range []string{"/proc", "/sys", "/run", "/dev", "/etc", "/usr"} { |
| - if overlaps(l.Workspace, root) { |
| + if !signIn && overlaps(l.Workspace, root) { |
| return nil, errMount |
| } |
| } |
| @@ -151,7 +156,7 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error |
| if err != nil { |
| return nil, err |
| } |
| - if within(home, l.Workspace) || l.Workspace == "/home" || filepath.Dir(l.Workspace) == "/home" || l.Workspace == "/tmp" || l.Workspace == "/root" { |
| + if !signIn && (within(home, l.Workspace) || l.Workspace == "/home" || filepath.Dir(l.Workspace) == "/home" || l.Workspace == "/tmp" || l.Workspace == "/root") { |
| return nil, errMount |
| } |
| if err = p.bind("/usr", "/usr", true, false); err != nil { |
| @@ -164,7 +169,7 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error |
| if err = p.bind(l.Workspace, "/workspace", true, true); err != nil { |
| return nil, err |
| } |
| - } else if l.Policy.Coordinator() { |
| + } else if l.Policy.Coordinator() || signIn { |
| p.args = append(p.args, "--tmpfs", "/workspace", "--remount-ro", "/workspace") |
| } else if err = p.bind(l.Workspace, "/workspace", l.Policy.ReadOnlyWorkspace(), true); err != nil { |
| return nil, err |
| @@ -225,6 +230,13 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error |
| } |
| p.args = append(p.args, "--clearenv", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "LANG", "C.UTF-8") |
| allowed := map[string]bool{"LANG": true, "LC_ALL": true, "TERM": true, "CODEX_HOME": true, "CLAUDE_CONFIG_DIR": true, "CLAUDE_SECURESTORAGE_CONFIG_DIR": true, "CLAUDE_TMPDIR": true, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": true, "DISABLE_AUTOUPDATER": true} |
| + if signIn { |
| + // The sign-in's browser opens nothing. |
| + if l.Policy.Env["BROWSER"] != provider.SignInBrowser { |
| + return nil, errMount |
| + } |
| + allowed["BROWSER"] = true |
| + } |
| if l.Policy.IsCheck() { |
| for k, v := range map[string]string{"GOCACHE": "/tmp/go-build", "GOTMPDIR": "/tmp/go-tmp", "GOMODCACHE": "/opt/go-mod", "GOROOT": "/opt/go", "GOTOOLCHAIN": "local", "GOWORK": "off", "GOENV": "off", "GOTELEMETRY": "off", "GOPROXY": "off", "GOSUMDB": "off", "CGO_ENABLED": "0", "XDG_CONFIG_HOME": "/tmp/xdg", "PATH": "/opt/go/bin:/usr/bin:/bin"} { |
| if l.Policy.Env[k] != v { |
diff --git a/internal/runner/containment/mounts_test.go b/internal/runner/containment/mounts_test.go| index a606c4f9..e0cb4625 100644 |
| --- a/internal/runner/containment/mounts_test.go |
| +++ b/internal/runner/containment/mounts_test.go |
| @@ -54,7 +54,7 @@ func TestNamespacePinnedMountSwap(t *testing.T) { |
| t.Fatal(e) |
| } |
| result := make(chan startResult, 1) |
| - go m.lifecycle(context.Background(), r, []string{"/usr/bin/cat", "/workspace/marker"}, plan, dir, result, nil) |
| + go m.lifecycle(context.Background(), r, []string{"/usr/bin/cat", "/workspace/marker"}, plan, dir, result, nil, false) |
| started := <-result |
| if started.err != nil { |
| t.Fatal(started.err) |
| @@ -226,7 +226,7 @@ print(os.path.exists("/workspace/../session.jsonl"))` |
| t.Fatal(err) |
| } |
| result := make(chan startResult, 1) |
| - go m.lifecycle(context.Background(), r, argv, plan, dir, result, nil) |
| + go m.lifecycle(context.Background(), r, argv, plan, dir, result, nil, false) |
| started := <-result |
| if started.err != nil { |
| t.Fatal(started.err) |
diff --git a/internal/runner/containment/sys_darwin.go b/internal/runner/containment/sys_darwin.go| index 8f14973b..063855f6 100644 |
| --- a/internal/runner/containment/sys_darwin.go |
| +++ b/internal/runner/containment/sys_darwin.go |
| @@ -1,6 +1,7 @@ |
| package containment |
| import ( |
| + "os" |
| "syscall" |
| "golang.org/x/sys/unix" |
| @@ -16,3 +17,6 @@ func pidfdOpen(int) (int, error) { return -1, unix.ENOSYS } |
| func pidfdSignal(int, unix.Signal) error { return unix.ENOSYS } |
| func parentDeathKill() *syscall.SysProcAttr { return &syscall.SysProcAttr{} } |
| func pathNoLinks(string) (int, error) { return -1, unix.ENOSYS } |
| + |
| +// OpenTerminal: no terminal launch on a Mac (no namespace to put it in). |
| +func OpenTerminal() (master, tty *os.File, err error) { return nil, nil, unix.ENOSYS } |
diff --git a/internal/runner/containment/sys_linux.go b/internal/runner/containment/sys_linux.go| index 912de26b..2418a2ba 100644 |
| --- a/internal/runner/containment/sys_linux.go |
| +++ b/internal/runner/containment/sys_linux.go |
| @@ -1,6 +1,8 @@ |
| package containment |
| import ( |
| + "fmt" |
| + "os" |
| "syscall" |
| "golang.org/x/sys/unix" |
| @@ -21,3 +23,30 @@ func parentDeathKill() *syscall.SysProcAttr { |
| func pathNoLinks(path string) (int, error) { |
| return unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_PATH | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS}) |
| } |
| + |
| +// OpenTerminal opens a pseudo-terminal pair for a launch that needs a |
| +// terminal (StartTerminal), wide enough that the CLI never wraps a line. |
| +func OpenTerminal() (master, tty *os.File, err error) { |
| + master, err = os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + fd := int(master.Fd()) |
| + if err = unix.IoctlSetPointerInt(fd, unix.TIOCSPTLCK, 0); err != nil { |
| + master.Close() |
| + return nil, nil, err |
| + } |
| + n, err := unix.IoctlGetInt(fd, unix.TIOCGPTN) |
| + if err != nil { |
| + master.Close() |
| + return nil, nil, err |
| + } |
| + tty, err = os.OpenFile(fmt.Sprintf("/dev/pts/%d", n), os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + master.Close() |
| + return nil, nil, err |
| + } |
| + ws := unix.Winsize{Row: 50, Col: 1000} |
| + _ = unix.IoctlSetWinsize(int(tty.Fd()), unix.TIOCSWINSZ, &ws) |
| + return master, tty, nil |
| +} |
diff --git a/internal/runner/egress/policy.go b/internal/runner/egress/policy.go| index 4416cc94..8d576709 100644 |
| --- a/internal/runner/egress/policy.go |
| +++ b/internal/runner/egress/policy.go |
| @@ -45,6 +45,18 @@ func ProviderPolicy(c provider.NetworkContract, dedicated bool) (Policy, error) |
| return p, nil |
| } |
| +// SignInPolicy is Claude's sign-in's: provider.SignInHosts, under the |
| +// same installed contract as Claude's launches. |
| +func SignInPolicy(c provider.NetworkContract) (Policy, error) { |
| + if c.Conflict != "" { |
| + return Policy{}, fmt.Errorf("%w: %s", ErrConflict, c.Conflict) |
| + } |
| + if c.Provider != "claude" || c.AuthHost != "" { |
| + return Policy{}, errPolicy |
| + } |
| + return Policy{Provider: "claude", Hosts: append([]string(nil), provider.SignInHosts...)}, nil |
| +} |
| + |
| func hostname(s string) bool { |
| if len(s) > 253 || !strings.Contains(s, ".") || s != strings.ToLower(s) { |
| return false |
diff --git a/internal/runner/provider/policy.go b/internal/runner/provider/policy.go| index 9c49a77b..b1494747 100644 |
| --- a/internal/runner/provider/policy.go |
| +++ b/internal/runner/provider/policy.go |
| @@ -487,6 +487,9 @@ func AttestLaunch(l Launch, argv []string) (string, error) { |
| if l.Policy.IsCheck() { |
| return attestCheck(l, argv) |
| } |
| + if l.Policy.IsSignIn() { |
| + return attestSignIn(l, argv) |
| + } |
| p := l.Policy |
| if p.ManifestHash == "" { |
| // Legacy check jobs have no direct-provider manifest during the cutover. |
diff --git a/internal/runner/provider/signin_policy.go b/internal/runner/provider/signin_policy.go| new file mode 100644 |
| index 00000000..0dd2cb35 |
| --- /dev/null |
| +++ b/internal/runner/provider/signin_policy.go |
| @@ -0,0 +1,110 @@ |
| +package provider |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "reflect" |
| + "sort" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// Claude's sign-in with no terminal (Paul, 2026-11-10): the unmodified |
| +// `claude setup-token` runs contained like every provider launch, in a |
| +// bubblewrap namespace whose only writable home is the launch's own |
| +// scratch home (the connection's dedicated home is not mounted: the |
| +// runner writes the token there itself), with no workspace, no tool |
| +// socket, no other home and no runner state, and egress only through the |
| +// relay to SignInHosts. Its policy is built here like a check's: no |
| +// account, no binding, a pinned binary. |
| + |
| +const signInPolicyVersion = "signin-v1" |
| + |
| +// SignInHosts are the hosts setup-token reaches, read from the pinned |
| +// CLI 2.1.312 statically (its production OAuth config): TOKEN_URL |
| +// https://platform.claude.com/v1/oauth/token, where the code is |
| +// exchanged for the token, and BASE_API_URL https://api.anthropic.com. |
| +// The authorize page (claude.com) is opened by the person's browser, |
| +// never by the CLI. Sorted. |
| +var SignInHosts = []string{"api.anthropic.com", "platform.claude.com"} |
| + |
| +// SignInBrowser stands in for a browser inside the namespace: setup-token |
| +// runs it with the URL and it opens nothing. |
| +const SignInBrowser = "/usr/bin/true" |
| + |
| +// SignInArgv is the CLI's argv inside the namespace. |
| +var SignInArgv = []string{"/opt/claude", "setup-token"} |
| + |
| +// SignInPolicyInputs are the pinned CLI and the host's bubblewrap. |
| +type SignInPolicyInputs struct { |
| + Binary, Bwrap string |
| +} |
| + |
| +// signInEnv is the CLI's environment: its config in the scratch home, |
| +// no nonessential traffic, no updater, a terminal, no browser. |
| +func signInEnv() map[string]string { |
| + return map[string]string{ |
| + "CLAUDE_CONFIG_DIR": "/home/runner", |
| + "CLAUDE_SECURESTORAGE_CONFIG_DIR": "/home/runner", |
| + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", |
| + "DISABLE_AUTOUPDATER": "1", |
| + "TERM": "xterm-256color", |
| + "BROWSER": SignInBrowser, |
| + } |
| +} |
| + |
| +// BuildSignInPolicy pins the CLI (mounted read-only at /opt/claude) and |
| +// the host's bubblewrap (certified, not mounted). |
| +func BuildSignInPolicy(in SignInPolicyInputs) (Policy, error) { |
| + m := effectiveManifest{Version: signInPolicyVersion, Provider: "claude", Argv: append([]string(nil), SignInArgv...), Env: signInEnv(), NamespaceArgs: NamespaceArguments(), EgressHosts: append([]string(nil), SignInHosts...)} |
| + sort.Strings(m.EgressHosts) |
| + cli := Mount{Source: in.Binary, Target: "/opt/claude", ReadOnly: true} |
| + m.OuterMounts = []Mount{cli} |
| + for _, mount := range []Mount{cli, {Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true}} { |
| + fd, err := openNoLinks(mount.Source, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) |
| + if err != nil { |
| + return Policy{}, ErrPolicy |
| + } |
| + f := os.NewFile(uintptr(fd), mount.Source) |
| + info, err := f.Stat() |
| + f.Close() |
| + if err != nil || !info.Mode().IsRegular() { |
| + return Policy{}, ErrPolicy |
| + } |
| + raw, err := os.ReadFile(mount.Source) |
| + if err != nil { |
| + return Policy{}, err |
| + } |
| + m.Files = append(m.Files, fileDigest{Mount: mount, SHA256: digest(raw)}) |
| + } |
| + raw, hash, err := hashJSON(m) |
| + if err != nil { |
| + return Policy{}, err |
| + } |
| + return Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: signInEnv()}, nil |
| +} |
| + |
| +// IsSignIn says the policy is a sign-in's (BuildSignInPolicy). |
| +func (p Policy) IsSignIn() bool { |
| + var m effectiveManifest |
| + return p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && m.Version == signInPolicyVersion |
| +} |
| + |
| +// attestSignIn binds a sign-in launch to its policy: Claude and nothing |
| +// else selected, no binding, workspace, tool socket or session, the |
| +// policy's own argv, environment and mounts, the pinned files unchanged. |
| +func attestSignIn(l Launch, argv []string) (string, error) { |
| + p := l.Policy |
| + var m effectiveManifest |
| + if l.Selection != (Selection{Provider: "claude"}) || l.Binding != (Binding{}) || l.Workspace != "" || l.ToolSocket != "" || l.ResumeSessionID != "" || l.AttemptKey == "" || json.Unmarshal(p.Manifest, &m) != nil || digest(p.Manifest) != p.ManifestHash || p.Hash != p.ManifestHash || !reflect.DeepEqual(argv, m.Argv) || !reflect.DeepEqual(argv, SignInArgv) || !reflect.DeepEqual(p.Env, m.Env) || !reflect.DeepEqual(m.Env, signInEnv()) || !reflect.DeepEqual(p.Mounts, m.OuterMounts) || !reflect.DeepEqual(m.NamespaceArgs, NamespaceArguments()) || !reflect.DeepEqual(m.EgressHosts, SignInHosts) { |
| + return "", ErrPolicy |
| + } |
| + for _, f := range m.Files { |
| + raw, err := os.ReadFile(f.Mount.Source) |
| + if err != nil || digest(raw) != f.SHA256 { |
| + return "", ErrPolicy |
| + } |
| + } |
| + _, hash, err := hashJSON(struct{ Manifest, Attempt string }{p.ManifestHash, l.AttemptKey}) |
| + return hash, err |
| +} |
diff --git a/internal/runner/provider/signin_policy_test.go b/internal/runner/provider/signin_policy_test.go| new file mode 100644 |
| index 00000000..4830b8dc |
| --- /dev/null |
| +++ b/internal/runner/provider/signin_policy_test.go |
| @@ -0,0 +1,67 @@ |
| +package provider |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "testing" |
| +) |
| + |
| +// The sign-in's policy: the CLI pinned at /opt/claude and run as |
| +// `setup-token` alone, its environment fixed (BROWSER a no-op, its |
| +// config in the scratch home), Claude's sign-in and API hosts its only |
| +// egress. A launch is attested only as exactly that: another argv, an |
| +// account binding, a workspace, a tool socket, another selection, a |
| +// changed environment or a changed binary is refused. |
| +func TestSignInPolicyAttestation(t *testing.T) { |
| + dir := t.TempDir() |
| + cli, bwrap := filepath.Join(dir, "claude"), filepath.Join(dir, "bwrap") |
| + for _, f := range []string{cli, bwrap} { |
| + if err := os.WriteFile(f, []byte("binary "+f), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + p, err := BuildSignInPolicy(SignInPolicyInputs{Binary: cli, Bwrap: bwrap}) |
| + if err != nil || !p.IsSignIn() || p.IsCheck() || p.Converse() { |
| + t.Fatalf("policy %v", err) |
| + } |
| + if !reflect.DeepEqual(SignInHosts, []string{"api.anthropic.com", "platform.claude.com"}) || p.ValidateNetwork("claude", []string{"platform.claude.com", "api.anthropic.com"}) != nil || p.ValidateNetwork("claude", []string{"api.anthropic.com"}) == nil || p.ValidateNetwork("claude", append([]string{"claude.ai"}, SignInHosts...)) == nil { |
| + t.Fatal("the sign-in's egress is not exactly its two hosts") |
| + } |
| + if p.Env["BROWSER"] != SignInBrowser || p.Env["CLAUDE_CONFIG_DIR"] != "/home/runner" || len(p.Mounts) != 1 || p.Mounts[0].Target != "/opt/claude" || !p.Mounts[0].ReadOnly { |
| + t.Fatalf("env %v mounts %v", p.Env, p.Mounts) |
| + } |
| + if err = p.ValidateRuntimeBinaries(bwrap); err != nil { |
| + t.Fatal(err) |
| + } |
| + good := Launch{AttemptKey: "signin/a", Selection: Selection{Provider: "claude"}, Policy: p} |
| + if _, err := AttestLaunch(good, SignInArgv); err != nil { |
| + t.Fatalf("the launch itself: %v", err) |
| + } |
| + refused := map[string]func() (Launch, []string){ |
| + "another argv": func() (Launch, []string) { return good, []string{"/opt/claude", "setup-token", "sk-ant-oat01-x"} }, |
| + "auth login": func() (Launch, []string) { return good, []string{"/opt/claude", "auth", "login"} }, |
| + "a binding": func() (Launch, []string) { l := good; l.Binding.Home = dir; return l, SignInArgv }, |
| + "a workspace": func() (Launch, []string) { l := good; l.Workspace = dir; return l, SignInArgv }, |
| + "a tool socket": func() (Launch, []string) { l := good; l.ToolSocket = cli; return l, SignInArgv }, |
| + "an account": func() (Launch, []string) { l := good; l.Selection.AccountID = "a@example.com"; return l, SignInArgv }, |
| + "no attempt": func() (Launch, []string) { l := good; l.AttemptKey = ""; return l, SignInArgv }, |
| + "a changed browser": func() (Launch, []string) { |
| + l := good |
| + l.Policy.Env = map[string]string{"BROWSER": "/usr/bin/xdg-open"} |
| + return l, SignInArgv |
| + }, |
| + } |
| + for name, f := range refused { |
| + l, argv := f() |
| + if _, err := AttestLaunch(l, argv); err == nil { |
| + t.Errorf("%s: attested", name) |
| + } |
| + } |
| + if err := os.WriteFile(cli, []byte("another binary"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := AttestLaunch(good, SignInArgv); err == nil { |
| + t.Fatal("a changed CLI was attested") |
| + } |
| +} |
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go| index 9ea6973a..7bd74da3 100644 |
| --- a/internal/runner/thin/connector.go |
| +++ b/internal/runner/thin/connector.go |
| @@ -14,6 +14,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| "amadan.net/oficina/equipo/internal/sealbox" |
| @@ -54,6 +55,15 @@ type Connector struct { |
| // RunnerID is the id they must be sealed for. |
| Seal *sealbox.Keys |
| RunnerID string |
| + // Manager contains a sign-in's `claude setup-token` (nil: Claude's |
| + // sign-in by a link is unavailable). |
| + Manager *containment.Manager |
| + |
| + // terminal starts setup-token for an attempt (contained, signin.go; |
| + // tests replace it); gone proves an attempt's namespace gone at |
| + // start (namespaceGone; tests replace it). |
| + terminal func(ctx context.Context, attempt string) (connect.Terminal, error) |
| + gone func(ctx context.Context, id string) error |
| // spawn runs a cleanup in the background (a goroutine; tests replace |
| // it to stop the process between a frame and its cleanup). |
| @@ -132,15 +142,15 @@ func (c *Connector) Start(ctx context.Context) error { |
| if _, err := c.State.db.ExecContext(ctx, "DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)); err != nil { |
| return err |
| } |
| - rows, err := c.State.db.QueryContext(ctx, "SELECT id, person, provider, home, kind, created_at FROM connect_attempts WHERE state='running'") |
| + rows, err := c.State.db.QueryContext(ctx, "SELECT id, person, provider, home, kind, created_at, namespace FROM connect_attempts WHERE state='running'") |
| if err != nil { |
| return err |
| } |
| - type left struct{ id, person, provider, home, kind, created string } |
| + type left struct{ id, person, provider, home, kind, created, namespace string } |
| var all []left |
| for rows.Next() { |
| var l left |
| - if err = rows.Scan(&l.id, &l.person, &l.provider, &l.home, &l.kind, &l.created); err != nil { |
| + if err = rows.Scan(&l.id, &l.person, &l.provider, &l.home, &l.kind, &l.created, &l.namespace); err != nil { |
| rows.Close() |
| return err |
| } |
| @@ -158,6 +168,15 @@ func (c *Connector) Start(ctx context.Context) error { |
| } |
| continue |
| } |
| + // A sign-in's contained CLI is proven gone (its namespace killed |
| + // and its exit verified) before its home goes; one that cannot be |
| + // is left running, home and all, for the next start. |
| + if l.namespace != "" { |
| + if err = c.namespaceGone(ctx, l.namespace); err != nil { |
| + c.log("connect sign-in recovery", err) |
| + continue |
| + } |
| + } |
| c.removeHome(l.home) |
| c.finish(l.id, wire.ConnectionReport{Connection: l.id, Person: l.person, Provider: l.provider, State: wire.ConnError, Reason: "runner_offline"}) |
| } |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 31902e09..98c2e132 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -195,7 +195,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| if o.AccountsRoot == "" { |
| o.AccountsRoot = DefaultAccountsRoot() |
| } |
| - connector := &Connector{Runner: c, State: state, Conns: conns, Root: o.AccountsRoot, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), Notify: link.Notify, Logger: o.Logger, Limit: o.ConnectLimit, RunnerID: creds.Bearer.RunnerID} |
| + connector := &Connector{Runner: c, State: state, Conns: conns, Root: o.AccountsRoot, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), Notify: link.Notify, Logger: o.Logger, Limit: o.ConnectLimit, RunnerID: creds.Bearer.RunnerID, Manager: manager} |
| // The seal key: the X25519 form of the enrolment key the owner |
| // approved; secrets for token connections are sealed to it. |
| sealKey := "" |
diff --git a/internal/runner/thin/signin.go b/internal/runner/thin/signin.go| index 6e7a733e..423a5b3a 100644 |
| --- a/internal/runner/thin/signin.go |
| +++ b/internal/runner/thin/signin.go |
| @@ -8,6 +8,7 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/sealbox" |
| "amadan.net/oficina/equipo/internal/wire" |
| @@ -17,9 +18,11 @@ import ( |
| // Claude with no terminal (Paul, 2026-11-10: "Can you not run this on |
| // the server and get a link to give to the browser? We're trying to |
| // avoid the round-trip over SSH here."). The runner runs the unmodified |
| -// `claude setup-token` itself, on a pseudo-terminal, in the connection's |
| -// new dedicated home with the login environment, and shows the authorize |
| -// URL it prints (wire.PromptAuthorize). The person signs in at Anthropic |
| +// `claude setup-token` itself, on a pseudo-terminal, contained like |
| +// every provider launch (provider.BuildSignInPolicy: its own scratch |
| +// home the only writable home, the connection's dedicated home and the |
| +// runner's state not mounted, egress to Claude's sign-in and API hosts |
| +// only), and shows the authorize URL it prints (wire.PromptAuthorize). The person signs in at Anthropic |
| // and pastes the one-time code it shows; the page seals the code to this |
| // runner (wire.EndpointClaudeCode, the prompt's attempt) and the instance |
| // relays the box as it relays a token. The runner opens it, records the |
| @@ -117,8 +120,14 @@ func (c *Connector) runSignIn(ctx context.Context, cmd wire.ConnectCommand, base |
| c.failToken(cmd, base, home, "provider_refused") |
| return |
| } |
| - token, reason := c.signIn(ctx, cmd, base, home) |
| + token, reason, err := c.signIn(ctx, cmd, base, home) |
| lock.Close() |
| + if err != nil { |
| + // Its CLI could not be proven gone: the home stays, and the |
| + // attempt runs on until the next start's recovery proves it. |
| + c.log("connect sign-in", err) |
| + return |
| + } |
| if token == nil { |
| // "": a test fault stopped it; "ended" is the test's stop of a |
| // process whose CLI died with it, before anything is cleaned. |
| @@ -156,31 +165,53 @@ func (c *Connector) runSignIn(ctx context.Context, cmd wire.ConnectCommand, base |
| c.madeToken(ctx, cmd, base, home, a) |
| } |
| +// errUnproven: the CLI's launch boundary could not be proven gone. |
| +var errUnproven = errors.New("the sign-in's namespace could not be proven gone") |
| + |
| // signIn runs the CLI until it prints a token: the token (the caller |
| // clears it), or nil and the reason the attempt ends ("" when a test |
| -// fault stopped it as if the process had). |
| -func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, home string) ([]byte, string) { |
| +// fault stopped it as if the process had). Every run of the CLI is |
| +// stopped, its whole launch boundary proven gone, before this returns; |
| +// errUnproven when it cannot be (the attempt is then left for the next |
| +// start's recovery, home and all). |
| +func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, home string) ([]byte, string, error) { |
| var attempt int64 |
| wrong, reason := false, "provider_refused" |
| + start := c.terminal |
| + if start == nil { |
| + start = c.containedSetupToken |
| + } |
| for launch := 0; launch < maxLaunches; launch++ { |
| - cli, err := connect.StartSetupToken(c.Runner.ClaudePath, home, provider.LoginEnvironment(wire.ProviderClaude, home)) |
| + term, err := start(ctx, cmd.Connection) |
| if err != nil { |
| c.log("connect sign-in", err) |
| - return nil, "provider_refused" |
| + if ctx.Err() != nil { |
| + return nil, reasonOf(ctx.Err()), nil |
| + } |
| + return nil, "provider_refused", nil |
| + } |
| + cli := connect.NewSetupToken(term) |
| + stop := func() error { |
| + if err := cli.Close(); err != nil { |
| + c.log("connect sign-in stop", err) |
| + return errUnproven |
| + } |
| + return nil |
| } |
| link, err := cli.URL(ctx) |
| if err != nil { |
| - cli.Close() |
| + if serr := stop(); serr != nil { |
| + return nil, "", serr |
| + } |
| if ctx.Err() != nil { |
| - return nil, reasonOf(ctx.Err()) |
| + return nil, reasonOf(ctx.Err()), nil |
| } |
| // Exited before a link: nothing to show, nothing to retry. |
| - return nil, "provider_refused" |
| + return nil, "provider_refused", nil |
| } |
| for cli != nil { |
| if attempt++; attempt > wire.MaxCodeAttempts { |
| - cli.Close() |
| - return nil, "provider_refused" |
| + return nil, "provider_refused", stop() |
| } |
| codes := c.expectCode(cmd.Connection, attempt) |
| r := base |
| @@ -190,27 +221,28 @@ func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wi |
| select { |
| case <-ctx.Done(): |
| c.stopCode(cmd.Connection, codes) |
| - cli.Close() |
| - return nil, reasonOf(ctx.Err()) |
| - case <-cli.Done(): |
| + return nil, reasonOf(ctx.Err()), stop() |
| + case <-term.Done(): |
| // It stopped waiting on its own (its own time limit): a new |
| // run, a new link. |
| c.stopCode(cmd.Connection, codes) |
| - cli.Close() |
| + if err := stop(); err != nil { |
| + return nil, "", err |
| + } |
| cli, wrong, reason = nil, false, "timed_out" |
| continue |
| case in = <-codes: |
| } |
| c.stopCode(cmd.Connection, codes) |
| if in.refuse != "" { |
| - cli.Close() |
| - return nil, in.refuse |
| + return nil, in.refuse, stop() |
| } |
| err = cli.Submit(ctx, in.code) |
| clear(in.code) |
| if err == nil && c.stop("code_typed") != nil { |
| - cli.Close() |
| - return nil, "" |
| + // As if the process stopped here: the CLI dies with it. |
| + _ = stop() |
| + return nil, "", nil |
| } |
| outcome, token := connect.CodeEnded, []byte(nil) |
| if err == nil { |
| @@ -218,29 +250,121 @@ func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wi |
| } |
| if ctx.Err() != nil { |
| clear(token) |
| - cli.Close() |
| - return nil, reasonOf(ctx.Err()) |
| + return nil, reasonOf(ctx.Err()), stop() |
| } |
| switch { |
| case err == nil && outcome == connect.CodeToken: |
| - cli.Close() |
| + if serr := stop(); serr != nil { |
| + clear(token) |
| + return nil, "", serr |
| + } |
| if !provider.ValidToken(token) { |
| clear(token) |
| - return nil, "provider_refused" |
| + return nil, "provider_refused", nil |
| } |
| - return token, "" |
| + return token, "", nil |
| case err == nil && outcome == connect.CodeAgain: |
| - // It asks again: the same link, a new code. |
| - wrong = true |
| + // It asks again: the link it shows now (the same, or a new |
| + // sign-in's), a new code. |
| + wrong, link = true, cli.Link() |
| default: |
| // It stopped: a new run, a new link. The code was wrong |
| // unless it never took it. |
| - cli.Close() |
| + if serr := stop(); serr != nil { |
| + return nil, "", serr |
| + } |
| cli, wrong, reason = nil, err == nil, "provider_refused" |
| } |
| } |
| } |
| - return nil, reason |
| + return nil, reason, nil |
| +} |
| + |
| +// containedSetupToken starts the attempt's setup-token in its own |
| +// namespace (provider.BuildSignInPolicy) on a terminal. The namespace's |
| +// record is kept in the attempt before anything is forked, so a start |
| +// after a crash finds it (namespaceGone). |
| +func (c *Connector) containedSetupToken(ctx context.Context, attempt string) (connect.Terminal, error) { |
| + if c.Manager == nil { |
| + return nil, provider.ErrLoginUnavailable |
| + } |
| + policy, err := provider.BuildSignInPolicy(provider.SignInPolicyInputs{Binary: c.Runner.ClaudePath, Bwrap: c.Runner.Bwrap()}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + launch := provider.Launch{AttemptKey: "signin/" + attempt + "/" + uuid(), Selection: provider.Selection{Provider: wire.ProviderClaude}, Policy: policy} |
| + record := func(ctx context.Context, r containment.Record) error { |
| + _, err := c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET namespace=? WHERE id=?", r.ID, attempt) |
| + return err |
| + } |
| + // The namespace lives until Stop, whatever ctx does. |
| + pctx, kill := context.WithCancel(context.Background()) |
| + proc, err := c.Manager.StartTerminal(pctx, launch, append([]string(nil), provider.SignInArgv...), record) |
| + if err != nil { |
| + kill() |
| + return nil, err |
| + } |
| + t := &contained{proc: proc, kill: kill, done: make(chan struct{}), c: c} |
| + go func() { |
| + _, _ = proc.Wait(context.Background()) |
| + close(t.done) |
| + }() |
| + return t, nil |
| +} |
| + |
| +// contained is a sign-in's terminal in its namespace. |
| +type contained struct { |
| + proc provider.Process |
| + kill context.CancelFunc |
| + done chan struct{} |
| + c *Connector |
| +} |
| + |
| +func (t *contained) Read(p []byte) (int, error) { return t.proc.Stdout().Read(p) } |
| +func (t *contained) Write(p []byte) (int, error) { return t.proc.Stdin().Write(p) } |
| +func (t *contained) Done() <-chan struct{} { return t.done } |
| + |
| +// Stop kills the namespace (every process in it, the CLI's children |
| +// whether or not the CLI is still running) and waits for its exit to be |
| +// proven; then its record and scratch go. |
| +func (t *contained) Stop() error { |
| + t.kill() |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + var err error |
| + if p, ok := t.proc.(interface{ Contain(context.Context) error }); ok { |
| + err = p.Contain(ctx) |
| + } else { |
| + _, err = t.proc.Wait(ctx) |
| + } |
| + t.proc.Stdin().Close() |
| + t.proc.Stdout().Close() |
| + if err != nil { |
| + return err |
| + } |
| + return t.c.namespaceGone(ctx, t.proc.ID()) |
| +} |
| + |
| +// namespaceGone proves a sign-in's namespace gone: its record, when the |
| +// manager still holds one, is recovered (the namespace killed if it |
| +// survived, its exit verified) and forgotten. nil: gone. |
| +func (c *Connector) namespaceGone(ctx context.Context, id string) error { |
| + if c.gone != nil { |
| + return c.gone(ctx, id) |
| + } |
| + if c.Manager == nil { |
| + return errUnproven |
| + } |
| + records, err := c.Manager.Records(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + for _, r := range records { |
| + if r.ID == id { |
| + return c.Manager.Forget(ctx, r) |
| + } |
| + } |
| + return nil |
| } |
| // code takes a sealed sign-in code for a sign-in attempt (Secret, spec |
diff --git a/internal/runner/thin/signin_host_test.go b/internal/runner/thin/signin_host_test.go| new file mode 100644 |
| index 00000000..3a1c9100 |
| --- /dev/null |
| +++ b/internal/runner/thin/signin_host_test.go |
| @@ -0,0 +1,53 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "os/exec" |
| + "syscall" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// execTerminal runs the fake setup-token on a terminal with no |
| +// namespace, in its own process group, for the attempt's state machine |
| +// (the contained launch is TestHeadlessSignInContained's). Its Stop |
| +// kills the group and waits. |
| +func (r *tokenRig) execTerminal(ctx context.Context, attempt string) (connect.Terminal, error) { |
| + master, tty, err := containment.OpenTerminal() |
| + if err != nil { |
| + return nil, err |
| + } |
| + dir := r.t.TempDir() |
| + cmd := exec.Command(r.cfg.ClaudePath, "setup-token") |
| + cmd.Dir = dir |
| + cmd.Env = append(provider.LoginEnvironment(wire.ProviderClaude, dir), "BROWSER="+provider.SignInBrowser, "TERM=xterm-256color") |
| + cmd.Stdin, cmd.Stdout, cmd.Stderr = tty, tty, tty |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true} |
| + if err = cmd.Start(); err != nil { |
| + tty.Close() |
| + master.Close() |
| + return nil, err |
| + } |
| + tty.Close() |
| + t := &execTerm{File: master, cmd: cmd, done: make(chan struct{})} |
| + go func() { _ = cmd.Wait(); close(t.done) }() |
| + return t, nil |
| +} |
| + |
| +type execTerm struct { |
| + *os.File |
| + cmd *exec.Cmd |
| + done chan struct{} |
| +} |
| + |
| +func (t *execTerm) Done() <-chan struct{} { return t.done } |
| +func (t *execTerm) Stop() error { |
| + _ = unix.Kill(-t.cmd.Process.Pid, unix.SIGKILL) |
| + <-t.done |
| + return t.File.Close() |
| +} |
diff --git a/internal/runner/thin/signin_test.go b/internal/runner/thin/signin_test.go| index ef4f6228..bdda66d6 100644 |
| --- a/internal/runner/thin/signin_test.go |
| +++ b/internal/runner/thin/signin_test.go |
| @@ -35,10 +35,12 @@ func (r *tokenRig) steer(words ...string) { |
| } |
| } |
| -// crashable starts a connector whose process can be stopped as a crash |
| -// stops it: at stage (or at once, by crash) every later boundary stops |
| -// too and its context ends, so its CLI dies with it and nothing it does |
| -// after reaches the state. |
| +// crashable starts a connector that can be stopped at a delivery |
| +// boundary, for the durable state each boundary leaves: at stage (or at |
| +// once, by crash) every later boundary stops too and its context ends, |
| +// so its CLI is stopped and nothing it does after reaches the state. It |
| +// is not a process death; that is TestHeadlessSignInRunnerKilled |
| +// (SIGKILL to a real runner process, its namespace recovered). |
| type crashable struct { |
| *Connector |
| cancel context.CancelFunc |
| @@ -56,6 +58,7 @@ func (r *tokenRig) crashable(stage string) *crashable { |
| k := &crashable{cancel: cancel} |
| k.Connector = &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: limit, Logger: slog.New(slog.NewTextHandler(&r.logs, nil))} |
| k.spawn = func(f func()) { f() } |
| + k.terminal = r.execTerminal |
| k.fault = func(at string) error { |
| if at == stage { |
| k.dead.Store(true) |
| @@ -253,23 +256,32 @@ func TestSignInTokenRejected(t *testing.T) { |
| } |
| } |
| -// A wrong code while the CLI asks again: the card says so with the same |
| -// link and the next attempt; the right code then connects. |
| +// Wrong codes while the CLI asks again (as 2.1.312 does, read |
| +// statically: after "OAuth error: ..." it waits for Enter, which the |
| +// runner presses). A code it cannot read: the same link. A code the |
| +// exchange refuses: a new sign-in, a new link, in the same run. The card |
| +// says the code was wrong each time; the right code for the latest link |
| +// connects. |
| func TestSignInWrongCodeAgain(t *testing.T) { |
| t.Parallel() |
| r := newTokenRig(t) |
| c := r.connector() |
| link, home := r.signIn(c, "cn_w1") |
| - r.deliver(c, "f-code-1", r.sealedCode("cn_w1", "fakecode-not-the-right-one#x", 1, nil)) |
| + r.deliver(c, "f-code-1", r.sealedCode("cn_w1", "notacode-without-a-state", 1, nil)) |
| p := r.prompt("cn_w1", 2) |
| if p.URL != link || !p.WrongCode { |
| t.Fatalf("second card %+v", p) |
| } |
| + r.deliver(c, "f-code-2", r.sealedCode("cn_w1", "fakecode-not-the-right-one#x", 2, nil)) |
| + p3 := r.prompt("cn_w1", 3) |
| + if p3.URL == link || !p3.WrongCode { |
| + t.Fatalf("third card %+v", p3) |
| + } |
| if len(r.pids()) != 1 { |
| t.Fatal("the CLI was started again") |
| } |
| - r.deliver(c, "f-code-2", r.sealedCode("cn_w1", codeFor(link, "w@example.com"), 2, nil)) |
| - r.healthy2("cn_w1", home, fakeclaude.Token("w@example.com"), "w@example.com", 2) |
| + r.deliver(c, "f-code-3", r.sealedCode("cn_w1", codeFor(p3.URL, "w@example.com"), 3, nil)) |
| + r.healthy2("cn_w1", home, fakeclaude.Token("w@example.com"), "w@example.com", 3) |
| } |
| // healthy2 is healthy for an attempt that took seals boxes. |
| @@ -452,7 +464,8 @@ func TestSignInCodeReplayAndRefusals(t *testing.T) { |
| } |
| } |
| -// A stop at each boundary of a code's delivery and its token's keeping. |
| +// A stop at each boundary of a code's delivery and its token's keeping |
| +// (crashable; the real kill is TestHeadlessSignInRunnerKilled). |
| // Before the token is committed the CLI died with the process: the |
| // restart ends the attempt runner_offline and deletes its home (with any |
| // staged or renamed token file), and the resent box is acked and |
| @@ -544,3 +557,45 @@ func TestSignInIgnoresSameMachine(t *testing.T) { |
| t.Fatalf("end %+v", end) |
| } |
| } |
| + |
| +// A start after a crash proves a sign-in's namespace gone before it |
| +// removes the attempt's home: while it cannot (a namespace survived and |
| +// would not die), the home stays and the attempt runs on, unreported; |
| +// once it can, the attempt ends runner_offline and the home goes. |
| +func TestSignInRecoveryProvesNamespaceGone(t *testing.T) { |
| + t.Parallel() |
| + r := newTokenRig(t) |
| + first := r.crashable("never") |
| + _, home := r.signIn(first.Connector, "cn_g1") |
| + first.crash(r) |
| + if _, err := r.state.db.Exec("UPDATE connect_attempts SET namespace='ns-of-cn_g1' WHERE id='cn_g1'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + start := func(gone func(context.Context, string) error) { |
| + keys := r.keys |
| + c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: time.Hour, Logger: slog.New(slog.NewTextHandler(&r.logs, nil))} |
| + c.spawn, c.terminal, c.gone = func(f func()) { f() }, r.execTerminal, gone |
| + if err := c.Start(r.ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var asked []string |
| + start(func(_ context.Context, id string) error { asked = append(asked, id); return errors.New("survived") }) |
| + var state string |
| + _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id='cn_g1'").Scan(&state) |
| + if _, err := os.Stat(home); err != nil || state != "running" || len(asked) != 1 || asked[0] != "ns-of-cn_g1" { |
| + t.Fatalf("home %v, state %s, asked %v", err, state, asked) |
| + } |
| + for _, v := range r.reports("cn_g1") { |
| + if v.State != wire.ConnConnecting { |
| + t.Fatalf("reported %+v", v) |
| + } |
| + } |
| + start(func(context.Context, string) error { return nil }) |
| + if end := r.ended("cn_g1"); end.Reason != "runner_offline" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) { |
| + t.Fatalf("home %v", err) |
| + } |
| +} |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index 01fb6e88..40356c28 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -104,7 +104,9 @@ func OpenState(ctx context.Context, dir string) (*State, error) { |
| } |
| // Added with token connections: an attempt's kind, and whether its |
| // sealed secret is committed (credential_present). |
| - for _, col := range []string{"kind", "secret"} { |
| + // Added with Claude's sign-in by a link: the namespace record of the |
| + // attempt's contained setup-token, proven gone before its home goes. |
| + for _, col := range []string{"kind", "secret", "namespace"} { |
| if _, err = d.ExecContext(ctx, "ALTER TABLE connect_attempts ADD COLUMN "+col+" TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| d.Close() |
| return nil, err |
diff --git a/internal/runner/thin/token_test.go b/internal/runner/thin/token_test.go| index 123e4231..2989f302 100644 |
| --- a/internal/runner/thin/token_test.go |
| +++ b/internal/runner/thin/token_test.go |
| @@ -129,6 +129,7 @@ func (r *tokenRig) connector() *Connector { |
| } |
| c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: limit, Logger: slog.New(slog.NewTextHandler(&r.logs, nil))} |
| c.spawn = func(f func()) { f() } |
| + c.terminal = r.execTerminal |
| if err := c.Start(r.ctx); err != nil { |
| r.t.Fatal(err) |
| } |