Merge the runner half of Claude token connections
22 files changed,
+1,965
−19
internal/fakeclaude/fake.go+76 −0internal/headless/token_test.go+130 −0internal/runner/config.go+1 −1internal/runner/connections.go+1 −1internal/runner/containment/linux.go+19 −0internal/runner/containment/mounts.go+48 −0internal/runner/containment/secret_test.go+80 −0internal/runner/enrol.go+14 −0internal/runner/provider/accounts.go+29 −3internal/runner/provider/login_probe.go+14 −2internal/runner/provider/token.go+171 −0internal/runner/provider/token_test.go+120 −0internal/runner/provider/types.go+6 −3internal/runner/setup/account_bindings.go+8 −1internal/runner/thin/connector.go+52 −5internal/runner/thin/conns.go+45 −1internal/runner/thin/link.go+8 −0internal/runner/thin/run.go+14 −2internal/runner/thin/state.go+8 −0internal/runner/thin/token.go+476 −0internal/runner/thin/token_test.go+590 −0internal/runner/token_test.go+55 −0
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index ecf5a830..c261e38f 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -64,6 +64,14 @@ |
| // "ask:write:<path>" asks to Write it and reports the answer, |
| // "asksleep:<ms>" pauses before the reply. |
| // Native tools in system/init are those of --tools. |
| +// |
| +// Setup tokens: with CLAUDE_CODE_OAUTH_TOKEN in its environment the fake |
| +// is signed in by that token, as the CLI is: `auth status` reports it |
| +// (with the email Token encoded, when it has one) and writes no login |
| +// file; a turn on a token that is not one of Token's is refused as an |
| +// authentication failure, and so is a turn in a home with neither a |
| +// token nor a login file. A token anywhere in argv exits 3 at once. A |
| +// reply on a token ends "(signed in by token)". |
| package fakeclaude |
| import ( |
| @@ -95,6 +103,14 @@ const Version = "2.1.312" |
| // Main runs the fake with argv after the program name. |
| func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { |
| + if tok := os.Getenv(tokenEnv); tok != "" { |
| + for _, a := range args { |
| + if strings.Contains(a, tok) { |
| + fmt.Fprintln(stderr, "the token is in argv") |
| + return 3 |
| + } |
| + } |
| + } |
| if len(args) == 1 && args[0] == "--version" { |
| fmt.Fprintln(stdout, Version+" (Claude Code)") |
| return 0 |
| @@ -126,6 +142,20 @@ func home() string { |
| // authStatus reports the identity in the home and refreshes the login the |
| // way the CLI does: a new credential file, atomically replaced. |
| func authStatus(stdout io.Writer) int { |
| + if tok, set := os.LookupEnv(tokenEnv); set { |
| + email, ok := tokenEmail(tok) |
| + if !ok { |
| + fmt.Fprintln(stdout, `{"loggedIn":false,"authMethod":"none","apiProvider":"firstParty"}`) |
| + return 1 |
| + } |
| + status := map[string]any{"loggedIn": true, "authMethod": "oauth_token", "apiProvider": "firstParty"} |
| + if email != "" { |
| + status["email"] = email |
| + } |
| + out, _ := json.Marshal(status) |
| + fmt.Fprintln(stdout, string(out)) |
| + return 0 |
| + } |
| h := home() |
| var id struct { |
| AccountID string `json:"account_id"` |
| @@ -676,6 +706,12 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int { |
| session = "00000000-0000-4000-8000-0000000000ff" |
| } |
| emit(map[string]any{"type": "system", "subtype": "init", "cwd": "/workspace", "session_id": f.session, "tools": append(append([]string{}, f.native...), tools...), "mcp_servers": []any{map[string]string{"name": "equipo", "status": status}}, "model": f.model, "permissionMode": "default", "slash_commands": []string{}, "apiKeySource": "none", "claude_code_version": Version, "output_style": "default", "skills": []string{}, "plugins": []any{map[string]string{"name": "cc-plugin-agents-md", "path": "builtin", "source": "cc-plugin-agents-md@builtin"}, map[string]string{"name": "cc-plugin-plugin-authoring", "path": "builtin", "source": "cc-plugin-plugin-authoring@builtin"}}, "uuid": fmt.Sprintf("init-%d", turn)}) |
| + byToken, ok := signedIn() |
| + if !ok { |
| + emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_auth_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": "Invalid API key"}}}, "error": "authentication_failed", "uuid": fmt.Sprintf("assistant-%d", turn)}) |
| + emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "Invalid API key", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)}) |
| + continue |
| + } |
| context := "fresh" |
| if f.resume || turn > 1 { |
| context = "resumed" |
| @@ -853,6 +889,9 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int { |
| ms, _ := strconv.Atoi(m[1]) |
| pause = time.Duration(ms) * time.Millisecond |
| } |
| + if byToken { |
| + reply += " (signed in by token)" |
| + } |
| chunks := split(reply, 3) |
| for i, chunk := range chunks { |
| if f.partial { |
| @@ -978,8 +1017,45 @@ var reviewAuthWord = regexp.MustCompile(`\breviewauth:([^\s|]+@[^\s|]+[a-z])`) |
| // stepLimitWord is steplimit:<email>, for an Engineering step only. |
| var stepLimitWord = regexp.MustCompile(`\bsteplimit:([^\s|]+@[^\s|]+[a-z])`) |
| +const tokenEnv = "CLAUDE_CODE_OAUTH_TOKEN" |
| + |
| +// Token is a setup token the fake accepts, for email ("" for a token |
| +// whose account the CLI does not name). Any other value is refused. |
| +func Token(email string) string { |
| + return "sk-ant-oat01-fake-" + hex.EncodeToString([]byte(email)) + "-ok" |
| +} |
| + |
| +// tokenEmail reads a token Token made. |
| +func tokenEmail(tok string) (string, bool) { |
| + mid, ok := strings.CutPrefix(tok, "sk-ant-oat01-fake-") |
| + if !ok { |
| + return "", false |
| + } |
| + if mid, ok = strings.CutSuffix(mid, "-ok"); !ok { |
| + return "", false |
| + } |
| + email, err := hex.DecodeString(mid) |
| + return string(email), err == nil |
| +} |
| + |
| +// signedIn is whether a turn may run: on a token, one Token made; else |
| +// a login file in the home. |
| +func signedIn() (byToken, ok bool) { |
| + if tok, set := os.LookupEnv(tokenEnv); set { |
| + _, ok = tokenEmail(tok) |
| + return true, ok |
| + } |
| + _, err := os.Stat(filepath.Join(home(), ".credentials.json")) |
| + return false, err == nil |
| +} |
| + |
| // accountEmail is the signed-in account of the home the fake runs in. |
| func accountEmail() string { |
| + if tok := os.Getenv(tokenEnv); tok != "" { |
| + if email, ok := tokenEmail(tok); ok && email != "" { |
| + return email |
| + } |
| + } |
| var v struct { |
| Account struct { |
| Email string `json:"emailAddress"` |
diff --git a/internal/headless/token_test.go b/internal/headless/token_test.go| new file mode 100644 |
| index 00000000..3f3f0cde |
| --- /dev/null |
| +++ b/internal/headless/token_test.go |
| @@ -0,0 +1,130 @@ |
| +package headless |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/fakeclaude" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/thintest" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// addToken gives the owner a token connection as the runner makes one |
| +// from a delivered secret: a home with the token file and the identity, |
| +// no CLI login, bound as kind token. It returns the token. |
| +func (r *localRunner) addToken(t *testing.T, id, email string) string { |
| + t.Helper() |
| + home := private(t, filepath.Join(r.root, "accounts", id)) |
| + token := fakeclaude.Token(email) |
| + if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(token), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + identity := map[string]string{"account_id": email, "home_id": rand.Text(), "provider_version": fakeclaude.Version} |
| + writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity) |
| + bs := append(r.bindings(t), map[string]any{"id": id, "local_id": id, "label": id, "person_id": thintest.Owner, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": email, "provider_home": home, "kind": "token", "expected_identity": identity}) |
| + writeJSON(t, r.cfg.AccountBindingsPath, bs) |
| + return token |
| +} |
| + |
| +// T1: a turn and an Engineering step on a token connection. The fake CLI |
| +// runs only with the token in CLAUDE_CODE_OAUTH_TOKEN (it refuses a turn |
| +// without it, and exits on a token in argv), and says so in its reply. |
| +// The runner's hello carries its seal key, the one its enrolment key |
| +// gives; nothing the runner sent the instance carries the token. |
| +func TestHeadlessTokenConnection(t *testing.T) { |
| + env, inst, r := localEnv(t) |
| + _, key, _ := ed25519.GenerateKey(rand.Reader) |
| + if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil { |
| + t.Fatal(err) |
| + } |
| + keys, _ := sealbox.FromEd25519(key) |
| + token := r.addToken(t, "claude-7", "tok@example.com") |
| + r.only(t, "claude-7") |
| + r.start(t) |
| + s := open(t, env) |
| + s.keep() |
| + sent := s.send(t, "Hello on a token.") |
| + m := replyOf(t, s, sent.Turn.ID) |
| + if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != "claude-7" { |
| + t.Fatalf("turn on the token connection: %q", m.Text) |
| + } |
| + text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. edit:README.md|teh panes|the panes" |
| + sent = s.send(t, text) |
| + id := s.taskOf(t, sent.Turn.ID) |
| + step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed) |
| + if step.State != wire.StepDone || !step.Pushed || step.Account != "claude-7" || !strings.Contains(step.Summary, "(signed in by token)") { |
| + t.Fatalf("step on the token connection: %+v", step) |
| + } |
| + conns, err := env.Client.Connections(s.ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, c := range conns.Items { |
| + if c.LocalID == "claude-7" && (c.Kind != wire.KindToken || c.State != wire.ConnHealthy) { |
| + t.Fatalf("connection %+v", c) |
| + } |
| + } |
| + var hello string |
| + if err = inst.DB.Writer().QueryRow("SELECT hello FROM runner_sessions").Scan(&hello); err != nil { |
| + t.Fatal(err) |
| + } |
| + var h wire.Hello |
| + if err = json.Unmarshal([]byte(hello), &h); err != nil || h.SealKey != keys.PublicString() { |
| + t.Fatalf("hello seal key %q, want %q", h.SealKey, keys.PublicString()) |
| + } |
| + // Everything the instance stored, every table: no token. |
| + db := inst.DB.Writer() |
| + tables, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var names []string |
| + for tables.Next() { |
| + var n string |
| + _ = tables.Scan(&n) |
| + names = append(names, n) |
| + } |
| + tables.Close() |
| + for _, n := range names { |
| + rows, err := db.Query(`SELECT * FROM "` + n + `"`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cols, _ := rows.Columns() |
| + for rows.Next() { |
| + vals := make([]any, len(cols)) |
| + ptrs := make([]any, len(cols)) |
| + for i := range vals { |
| + ptrs[i] = &vals[i] |
| + } |
| + _ = rows.Scan(ptrs...) |
| + for _, v := range vals { |
| + var s string |
| + switch x := v.(type) { |
| + case string: |
| + s = x |
| + case []byte: |
| + s = string(x) |
| + } |
| + if strings.Contains(s, token) { |
| + rows.Close() |
| + t.Fatalf("the token reached the instance's %s", n) |
| + } |
| + } |
| + } |
| + rows.Close() |
| + } |
| + if page := inst.Get(t, "/tasks/"+id); strings.Contains(page, token) { |
| + t.Fatal("the token is on the task page") |
| + } |
| +} |
diff --git a/internal/runner/config.go b/internal/runner/config.go| index ba72a8c1..e230075a 100644 |
| --- a/internal/runner/config.go |
| +++ b/internal/runner/config.go |
| @@ -159,7 +159,7 @@ func (c Config) DirectBinding(b AccountBinding) (provider.Binding, error) { |
| if !filepath.IsAbs(c.ScratchRoot) || filepath.Clean(c.ScratchRoot) != c.ScratchRoot || c.ScratchRoot == "/" || containsPath(b.ProviderHome, c.ScratchRoot) || containsPath(c.ScratchRoot, b.ProviderHome) { |
| return provider.Binding{}, provider.ErrPolicy |
| } |
| - return provider.Binding{ID: b.ID, Home: b.ProviderHome, AccountID: b.AccountID, Provider: b.Provider, Expected: b.ExpectedIdentity, RuntimeRoot: filepath.Join(c.ScratchRoot, "homes")}, nil |
| + return provider.Binding{ID: b.ID, Home: b.ProviderHome, AccountID: b.AccountID, Provider: b.Provider, Token: b.Kind == "token", Expected: b.ExpectedIdentity, RuntimeRoot: filepath.Join(c.ScratchRoot, "homes")}, nil |
| } |
| func (c Config) bwrap() string { |
diff --git a/internal/runner/connections.go b/internal/runner/connections.go| index c06e3fed..9fbfc1c3 100644 |
| --- a/internal/runner/connections.go |
| +++ b/internal/runner/connections.go |
| @@ -89,7 +89,7 @@ func loadDirectBindings(path string) ([]AccountBinding, error) { |
| rules := provider.DefaultHomeRules() |
| for _, b := range bs { |
| key := b.LocalID + "/" + b.Model |
| - if b.ID == "" || b.LocalID == "" || b.Model == "" || b.AccountID == "" || b.ExpectedIdentity.AccountID != b.AccountID || b.ExpectedIdentity.HomeID == "" || b.ExpectedIdentity.ProviderVersion == "" || !(b.Provider == "codex" && b.Family == "gpt" || b.Provider == "claude" && b.Family == "claude") || !(b.Kind == "subscription" || b.Kind == "api") || rules.RefusesPath(b.ProviderHome) || seen[key] || b.CredentialHome != "" && b.CredentialHome != b.ProviderHome { |
| + if b.ID == "" || b.LocalID == "" || b.Model == "" || b.AccountID == "" || b.ExpectedIdentity.AccountID != b.AccountID || b.ExpectedIdentity.HomeID == "" || b.ExpectedIdentity.ProviderVersion == "" || !(b.Provider == "codex" && b.Family == "gpt" || b.Provider == "claude" && b.Family == "claude") || !(b.Kind == "subscription" || b.Kind == "api" || b.Kind == "token" && b.Provider == "claude") || rules.RefusesPath(b.ProviderHome) || seen[key] || b.CredentialHome != "" && b.CredentialHome != b.ProviderHome { |
| return nil, provider.ErrIdentity |
| } |
| if prior, ok := accounts[b.LocalID]; ok && (prior.ID != b.ID || prior.ProviderHome != b.ProviderHome || prior.AccountID != b.AccountID || prior.PersonID != b.PersonID || prior.ExpectedIdentity != b.ExpectedIdentity) { |
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go| index 6922acac..75800e6e 100644 |
| --- a/internal/runner/containment/linux.go |
| +++ b/internal/runner/containment/linux.go |
| @@ -14,6 +14,7 @@ import ( |
| "os/exec" |
| "path/filepath" |
| "runtime" |
| + "strconv" |
| "sync" |
| "time" |
| @@ -32,6 +33,8 @@ type Manager struct { |
| cfg Config |
| // beforePin is a test seam for replacement after attestation. |
| beforePin func() |
| + // secretEnv is provider.LaunchSecretEnv (a test seam). |
| + secretEnv func(provider.Launch) (map[string]string, error) |
| mu sync.Mutex |
| processes map[string]*process |
| } |
| @@ -222,6 +225,19 @@ func (m *Manager) startRecorded(ctx context.Context, l provider.Launch, argv []s |
| mounts.close() |
| return nil, e |
| } |
| + secretEnv := provider.LaunchSecretEnv |
| + if m.secretEnv != nil { |
| + secretEnv = m.secretEnv |
| + } |
| + secret, e := secretEnv(l) |
| + if e == nil { |
| + e = mounts.addSecretEnv(secret) |
| + } |
| + clear(secret) |
| + if e != nil { |
| + mounts.close() |
| + return nil, e |
| + } |
| manifestHash, e = m.namespaceManifest(l, argv, manifestHash, dir, mounts) |
| if e != nil { |
| mounts.close() |
| @@ -639,6 +655,9 @@ func NamespaceMain(argv []string) int { |
| func namespaceArgs(mounts *mounts, argv []string) []string { |
| args := provider.NamespaceArguments() |
| args = append(args, mounts.args...) |
| + if mounts.secretFD > 0 { |
| + args = append(args, "--args", strconv.Itoa(mounts.secretFD)) |
| + } |
| args = append(args, "--", "/equipo-namespace", "__namespace") |
| if mounts.proxy != nil { |
| args = append(args, "--egress") |
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go| index a0c8cc59..aead7157 100644 |
| --- a/internal/runner/containment/mounts.go |
| +++ b/internal/runner/containment/mounts.go |
| @@ -18,11 +18,59 @@ var errMount = errors.New("namespace_mount_rejected") |
| type mounts struct { |
| binaryFD int |
| + // secretFD is the pipe bubblewrap reads the secret environment from |
| + // (--args), 0 when the launch has none. |
| + secretFD int |
| proxy *egress.Proxy |
| args []string |
| files []*os.File |
| } |
| +// secretEnvKeys are the only variables a launch may receive outside its |
| +// policy: a token connection's token, and the CLI's subprocess scrub. |
| +var secretEnvKeys = map[string]bool{provider.OAuthTokenEnv: true, provider.ScrubEnv: true} |
| + |
| +// addSecretEnv passes env to bubblewrap through a pipe it reads as |
| +// further arguments (--args FD, after --clearenv), so the values are in |
| +// no argv, no manifest and no record: the namespace's environment only. |
| +func (p *mounts) addSecretEnv(env map[string]string) error { |
| + if len(env) == 0 { |
| + return nil |
| + } |
| + keys := make([]string, 0, len(env)) |
| + for k := range env { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + var b []byte |
| + for _, k := range keys { |
| + v := env[k] |
| + if !secretEnvKeys[k] || v == "" || strings.ContainsAny(v, "\x00\n") { |
| + return errMount |
| + } |
| + b = append(b, "--setenv\x00"+k+"\x00"...) |
| + b = append(b, v...) |
| + b = append(b, 0) |
| + } |
| + defer clear(b) |
| + r, w, err := os.Pipe() |
| + if err != nil { |
| + return err |
| + } |
| + // The whole message fits the pipe's buffer: a token is at most 4 KB. |
| + _, err = w.Write(b) |
| + if cerr := w.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + r.Close() |
| + return err |
| + } |
| + p.secretFD = 6 + len(p.files) |
| + p.files = append(p.files, r) |
| + return nil |
| +} |
| + |
| func (p *mounts) close() { |
| for _, f := range p.files { |
| _ = f.Close() |
diff --git a/internal/runner/containment/secret_test.go b/internal/runner/containment/secret_test.go| new file mode 100644 |
| index 00000000..09471e14 |
| --- /dev/null |
| +++ b/internal/runner/containment/secret_test.go |
| @@ -0,0 +1,80 @@ |
| +//go:build linux |
| + |
| +package containment |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +const canary = "sk-ant-oat01-canary-containment-5e1d" |
| + |
| +// A token connection's token reaches the harness's environment inside |
| +// the namespace and nowhere else: not bubblewrap's argv, the manifest or |
| +// the attempt's record. |
| +func TestNamespaceSecretEnvironment(t *testing.T) { |
| + m, l := fixture(t) |
| + m.secretEnv = func(provider.Launch) (map[string]string, error) { |
| + return map[string]string{provider.OAuthTokenEnv: canary, provider.ScrubEnv: "1"}, nil |
| + } |
| + // The script does not hold the token: it reads it from its environment. |
| + script := `import os,sys |
| +tok=os.environ.get("CLAUDE_CODE_OAUTH_TOKEN","") |
| +argv=open("/proc/self/cmdline").read() |
| +sys.stdout.write(tok+"|"+os.environ.get("CLAUDE_CODE_SUBPROCESS_ENV_SCRUB","")+"|"+str(tok!="" and tok in argv)+"\n") |
| +sys.stdout.flush() |
| +sys.stdin.read() |
| +` |
| + p := launch(t, m, l, script) |
| + line, err := bufio.NewReader(p.Stdout()).ReadString('\n') |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if line != canary+"|1|False\n" { |
| + t.Fatalf("namespace environment %q", strings.ReplaceAll(line, canary, "<token>")) |
| + } |
| + // While the harness runs: no host process has the token in its argv. |
| + procs, _ := filepath.Glob("/proc/[0-9]*/cmdline") |
| + for _, path := range procs { |
| + if raw, err := os.ReadFile(path); err == nil && bytes.Contains(raw, []byte(canary)) { |
| + t.Errorf("the token is in the argv of %s", filepath.Dir(path)) |
| + } |
| + } |
| + // Nor any record or manifest the manager keeps. |
| + _ = filepath.WalkDir(m.cfg.ScratchRoot, func(path string, d fs.DirEntry, err error) error { |
| + if err != nil || !d.Type().IsRegular() { |
| + return nil |
| + } |
| + if raw, err := os.ReadFile(path); err == nil && bytes.Contains(raw, []byte(canary)) { |
| + t.Errorf("the token is in %s", path) |
| + } |
| + return nil |
| + }) |
| + if record(t, m, p).ManifestHash == "" { |
| + t.Fatal("no record") |
| + } |
| +} |
| + |
| +// Only the token and the scrub may be passed this way, and no value |
| +// that would split the arguments. |
| +func TestNamespaceSecretEnvironmentRefused(t *testing.T) { |
| + for _, env := range []map[string]string{ |
| + {"ANTHROPIC_API_KEY": "x"}, |
| + {provider.OAuthTokenEnv: "a\x00--bind"}, |
| + {provider.OAuthTokenEnv: "a\nb"}, |
| + {provider.OAuthTokenEnv: ""}, |
| + } { |
| + p := &mounts{} |
| + if err := p.addSecretEnv(env); err == nil { |
| + p.close() |
| + t.Fatalf("accepted %q", env) |
| + } |
| + } |
| +} |
diff --git a/internal/runner/enrol.go b/internal/runner/enrol.go| index 3712b858..44947c0e 100644 |
| --- a/internal/runner/enrol.go |
| +++ b/internal/runner/enrol.go |
| @@ -454,3 +454,17 @@ func DefaultMachineLabel(stateDir, origin, instance string) (string, error) { |
| } |
| return os.Hostname() |
| } |
| + |
| +// ReadMachineKey is the runner's enrolment key (machine-key.json): the |
| +// owner approved its public half, and the seal key is derived from it. |
| +func ReadMachineKey(stateDir string) (ed25519.PrivateKey, error) { |
| + var encoded string |
| + if err := privateJSON(filepath.Join(stateDir, "machine-key.json"), &encoded); err != nil { |
| + return nil, err |
| + } |
| + key, err := base64.RawURLEncoding.DecodeString(encoded) |
| + if err != nil || len(key) != ed25519.PrivateKeySize { |
| + return nil, provider.ErrIdentity |
| + } |
| + return ed25519.PrivateKey(key), nil |
| +} |
diff --git a/internal/runner/provider/accounts.go b/internal/runner/provider/accounts.go| index 13261f20..2bcfadf4 100644 |
| --- a/internal/runner/provider/accounts.go |
| +++ b/internal/runner/provider/accounts.go |
| @@ -124,6 +124,9 @@ type AccountLease struct { |
| contained bool |
| runtimeGeneration [32]byte |
| claudeIdentity []byte |
| + // token is a token home's credential, held for the launch |
| + // environment only (LaunchSecretEnv); never staged in the copy. |
| + token []byte |
| } |
| func OpenAccount(ctx context.Context, b Binding) (*AccountLease, error) { |
| @@ -310,17 +313,20 @@ func (l *AccountLease) snapshot() ([]byte, [32]byte, error) { |
| if dec.Decode(&id) != nil || dec.Decode(new(any)) != io.EOF || id != l.source.Expected { |
| return nil, zero, ErrIdentity |
| } |
| - raw, e := readPrivate(l.dir, credentialName(l.source.Provider)) |
| + raw, e := readPrivate(l.dir, l.credentialFile()) |
| if e != nil { |
| return nil, zero, accountContainment("source_credential") |
| } |
| + if l.source.Token && (l.source.Provider != "claude" || !ValidToken(raw)) { |
| + return nil, zero, accountContainment("source_credential") |
| + } |
| if credentialsExpired(raw, time.Now()) { |
| return nil, zero, ErrAccountMaintenance |
| } |
| // This digest stays in memory. Stat identity detects atomic replacement |
| // even when the replacement contains identical credential bytes. |
| var stat unix.Stat_t |
| - if unix.Fstatat(int(l.dir.Fd()), credentialName(l.source.Provider), &stat, unix.AT_SYMLINK_NOFOLLOW) != nil { |
| + if unix.Fstatat(int(l.dir.Fd()), l.credentialFile(), &stat, unix.AT_SYMLINK_NOFOLLOW) != nil { |
| return nil, zero, ErrAccountMaintenance |
| } |
| state, _ := json.Marshal(struct { |
| @@ -337,6 +343,15 @@ func (l *AccountLease) snapshot() ([]byte, [32]byte, error) { |
| digest := sha256.Sum256(bytes.Join([][]byte{metadata, raw, state, native}, nil)) |
| return raw, digest, nil |
| } |
| + |
| +// credentialFile is the source home's credential: the CLI's own login |
| +// file, or a token home's token. |
| +func (l *AccountLease) credentialFile() string { |
| + if l.source.Token { |
| + return TokenFile |
| + } |
| + return credentialName(l.source.Provider) |
| +} |
| func (l *AccountLease) runtimeDir() (*os.File, error) { |
| f, e := pinDirectory(l.runtime) |
| if e != nil { |
| @@ -396,6 +411,9 @@ func (l *AccountLease) stage() error { |
| return e |
| } |
| defer dir.Close() |
| + if l.source.Token { |
| + return l.stageToken(dir, raw) |
| + } |
| name := credentialName(l.source.Provider) |
| var stat unix.Stat_t |
| if e = unix.Fstatat(int(dir.Fd()), name, &stat, unix.AT_SYMLINK_NOFOLLOW); e == nil && stat.Mode&unix.S_IFMT != unix.S_IFREG { |
| @@ -445,6 +463,12 @@ func (l *AccountLease) runtimeSnapshot() ([]byte, error) { |
| return nil, accountContainment("runtime_claude_identity") |
| } |
| } |
| + if l.source.Token { |
| + if e = tokenRuntimeClean(dir); e != nil { |
| + return nil, e |
| + } |
| + return tokenRuntimeMarker, nil |
| + } |
| raw, e := readPrivate(dir, credentialName(l.source.Provider)) |
| if e != nil { |
| return nil, accountContainment("runtime_credential") |
| @@ -557,7 +581,7 @@ func (l *AccountLease) Preflight(ctx context.Context, probe func(context.Context |
| // private runtime home. The adapter must observe the same identity without |
| // prompting. A successful commit still requires Preflight before another turn. |
| func (l *AccountLease) CommitRefresh(ctx context.Context, probe func(context.Context, Binding) (Identity, error)) error { |
| - if !l.sourceFreshUntil.IsZero() { |
| + if !l.sourceFreshUntil.IsZero() || l.source.Token { |
| return ErrPolicy |
| } |
| return l.check(ctx, probe, true) |
| @@ -707,6 +731,8 @@ func (l *AccountLease) Close() error { |
| } |
| l.closed = true |
| l.ready = false |
| + clear(l.token) |
| + l.token = nil |
| // Do not follow a runtime path replaced by someone else during cleanup. |
| info, e := os.Lstat(l.runtime) |
| var cleanup error |
diff --git a/internal/runner/provider/login_probe.go b/internal/runner/provider/login_probe.go| index e5a5dbd6..3013978e 100644 |
| --- a/internal/runner/provider/login_probe.go |
| +++ b/internal/runner/provider/login_probe.go |
| @@ -46,14 +46,26 @@ func (d *terminalLoginDriver) probe(ctx context.Context, b Binding, refresh bool |
| defer cancel() |
| if b.Provider == "claude" { |
| cmd := exec.CommandContext(ctx, d.binary(b.Provider), "auth", "status", "--json") |
| - cmd.Env = LoginEnvironment(b.Provider, b.Home) |
| + // A token home's token goes in the environment, never in argv. |
| + env, err := tokenEnvironment(b) |
| + if err != nil { |
| + return Identity{}, ErrLoginRequired |
| + } |
| + cmd.Env = env |
| cmd.Dir = b.Home |
| out := &limitedLoginOutput{} |
| cmd.Stdout = out |
| - err := cmd.Run() |
| + err = cmd.Run() |
| if ctx.Err() != nil { |
| return Identity{}, ctx.Err() |
| } |
| + if b.Token { |
| + id, _, perr := ClaudeTokenIdentity(out.Bytes(), b.ID) |
| + if perr != nil || err != nil { |
| + return Identity{}, ErrLoginRequired |
| + } |
| + return id, nil |
| + } |
| var status struct { |
| LoggedIn *bool `json:"loggedIn"` |
| } |
diff --git a/internal/runner/provider/token.go b/internal/runner/provider/token.go| new file mode 100644 |
| index 00000000..5397c973 |
| --- /dev/null |
| +++ b/internal/runner/provider/token.go |
| @@ -0,0 +1,171 @@ |
| +package provider |
| + |
| +import ( |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/json" |
| + "os" |
| + "strings" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// A token connection is a Claude home whose credential is a pasted |
| +// `claude setup-token` OAuth token (Connections spec §2.4, Paul |
| +// 2026-11-09). The token rests only in TokenFile inside the dedicated |
| +// home, which every policy denies; a runtime copy never carries it. The |
| +// unmodified CLI receives it as OAuthTokenEnv in its environment, never |
| +// in argv, never in a policy, manifest or record. |
| +const ( |
| + // TokenFile is the token's final name inside the home (0600). |
| + TokenFile = ".oauth-token" |
| + // TokenStaging is where a delivered token waits until it is committed. |
| + TokenStaging = ".secret.tmp" |
| + // OAuthTokenEnv is the variable the CLI reads the token from. |
| + OAuthTokenEnv = "CLAUDE_CODE_OAUTH_TOKEN" |
| + // ScrubEnv asks the CLI to keep provider credentials out of the |
| + // environment of the subprocesses it starts (its Bash tool, hooks). |
| + ScrubEnv = "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB" |
| + // MaxTokenBytes bounds a token (the sealed box is capped at 4 KB). |
| + MaxTokenBytes = 4096 |
| +) |
| + |
| +// ValidToken reports whether raw can be a token: one line of printable |
| +// ASCII without spaces, as `claude setup-token` prints it. A trailing |
| +// newline is not part of it. |
| +func ValidToken(raw []byte) bool { |
| + if len(raw) == 0 || len(raw) > MaxTokenBytes { |
| + return false |
| + } |
| + for _, c := range raw { |
| + if c <= ' ' || c > '~' { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// ReadToken reads a token home's credential without following links: |
| +// a regular 0600 file of the runner's, one link, a valid token. |
| +func ReadToken(home string) ([]byte, error) { |
| + dir, err := pinDirectory(home) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer dir.Close() |
| + raw, err := readPrivate(dir, TokenFile) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !ValidToken(raw) { |
| + clear(raw) |
| + return nil, ErrPolicy |
| + } |
| + return raw, nil |
| +} |
| + |
| +// tokenEnvironment is the login environment of a token home: the CLI |
| +// reads the token from its environment. |
| +func tokenEnvironment(b Binding) ([]string, error) { |
| + env := LoginEnvironment(b.Provider, b.Home) |
| + if !b.Token { |
| + return env, nil |
| + } |
| + raw, err := ReadToken(b.Home) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer clear(raw) |
| + return append(env, OAuthTokenEnv+"="+string(raw)), nil |
| +} |
| + |
| +// LaunchSecretEnv is the environment a launch on a token connection adds |
| +// inside its namespace, outside the policy: the token from the lease |
| +// that staged the launch's runtime copy. Nil for every other launch. |
| +func LaunchSecretEnv(l Launch) (map[string]string, error) { |
| + if !l.Binding.Token { |
| + return nil, nil |
| + } |
| + if l.Binding.Provider != "claude" { |
| + return nil, ErrPolicy |
| + } |
| + lease, err := l.Binding.AccountLease() |
| + if err != nil { |
| + return nil, err |
| + } |
| + lease.mu.Lock() |
| + token := string(lease.token) |
| + lease.mu.Unlock() |
| + if token == "" { |
| + return nil, accountContainment("token_missing") |
| + } |
| + return map[string]string{OAuthTokenEnv: token, ScrubEnv: "1"}, nil |
| +} |
| + |
| +// ClaudeTokenIdentity reads `claude auth status --json` for a token home. |
| +// The CLI says whether the token signs it in; the email is the account's |
| +// when the CLI reports one. Without one the connection is named for its |
| +// home (local), which is never shown as a label. |
| +func ClaudeTokenIdentity(raw []byte, local string) (Identity, string, error) { |
| + raw, err := canonical(raw) |
| + var status struct { |
| + LoggedIn bool |
| + Email string |
| + } |
| + if err != nil || json.Unmarshal(raw, &status) != nil { |
| + return Identity{}, "", ErrIdentity |
| + } |
| + if !status.LoggedIn { |
| + return Identity{}, "", ErrLoginRequired |
| + } |
| + if strings.ContainsAny(status.Email, "\r\n\x1b") { |
| + return Identity{}, "", ErrIdentity |
| + } |
| + if status.Email != "" { |
| + return Identity{AccountID: status.Email, ProviderVersion: LoginVersion("claude")}, status.Email, nil |
| + } |
| + return Identity{AccountID: TokenAccountID(local), ProviderVersion: LoginVersion("claude")}, "", nil |
| +} |
| + |
| +// TokenAccountID names a token connection whose CLI reports no email. |
| +func TokenAccountID(local string) string { return "token:" + local } |
| + |
| +// tokenRuntimeMarker stands for the absent credential of a token copy. |
| +var tokenRuntimeMarker = []byte("equipo-token-runtime") |
| + |
| +// stageToken stages a token home's copy: the identity and the account |
| +// metadata only. The token stays in the lease's memory for the launch |
| +// environment and is never written to the copy, which the model's |
| +// session runs in. |
| +func (l *AccountLease) stageToken(dir *os.File, raw []byte) error { |
| + if err := tokenRuntimeClean(dir); err != nil { |
| + return err |
| + } |
| + metadata, _ := json.Marshal(l.source.Expected) |
| + if err := atomicPrivate(dir, IdentityFile, metadata); err != nil { |
| + return err |
| + } |
| + native, err := claudeAccountMetadata(l.dir) |
| + if err != nil { |
| + return err |
| + } |
| + if err = atomicPrivate(dir, ".claude.json", native); err != nil { |
| + return err |
| + } |
| + l.claudeIdentity = bytes.Clone(native) |
| + clear(l.token) |
| + l.token = bytes.Clone(raw) |
| + l.runtimeGeneration = sha256.Sum256(tokenRuntimeMarker) |
| + return nil |
| +} |
| + |
| +// tokenRuntimeClean checks a token copy holds no credential file. |
| +func tokenRuntimeClean(dir *os.File) error { |
| + for _, name := range []string{TokenFile, TokenStaging, credentialName("claude")} { |
| + var st unix.Stat_t |
| + if unix.Fstatat(int(dir.Fd()), name, &st, unix.AT_SYMLINK_NOFOLLOW) != unix.ENOENT { |
| + return accountContainment("runtime_token_credential") |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/provider/token_test.go b/internal/runner/provider/token_test.go| new file mode 100644 |
| index 00000000..8a9a129d |
| --- /dev/null |
| +++ b/internal/runner/provider/token_test.go |
| @@ -0,0 +1,120 @@ |
| +package provider |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| +) |
| + |
| +const canaryToken = "sk-ant-oat01-canary-provider-7f3a9c" |
| + |
| +// tokenFixture is a token home: identity, the token file, no CLI login. |
| +func tokenFixture(t *testing.T) Binding { |
| + t.Helper() |
| + root := t.TempDir() |
| + home := filepath.Join(root, "claude-1") |
| + if e := os.Mkdir(home, 0700); e != nil { |
| + t.Fatal(e) |
| + } |
| + identity := Identity{AccountID: "token:claude-1", HomeID: "enrolled-home", ProviderVersion: ClaudeVersion} |
| + writeMetadata(t, home, identity) |
| + writeFake(t, filepath.Join(home, TokenFile), canaryToken) |
| + return Binding{ID: "claude-1", Home: home, AccountID: identity.AccountID, Provider: "claude", Token: true, Expected: identity, RuntimeRoot: filepath.Join(root, "homes")} |
| +} |
| + |
| +func openTokenCopy(t *testing.T, b Binding) *AccountLease { |
| + t.Helper() |
| + l, err := OpenRuntimeCopy(context.Background(), b, func(context.Context, Binding) (Identity, error) { return b.Expected, nil }, time.Second) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { l.Close() }) |
| + return l |
| +} |
| + |
| +// The runtime copy of a token home carries no credential: the token is |
| +// in no file the session (and so the model) can reach, only in the |
| +// launch's environment. |
| +func TestTokenCopyHoldsNoToken(t *testing.T) { |
| + b := tokenFixture(t) |
| + l := openTokenCopy(t, b) |
| + runtime := l.Binding().Home |
| + err := filepath.WalkDir(filepath.Dir(runtime), func(path string, d fs.DirEntry, err error) error { |
| + if err != nil || d.IsDir() { |
| + return err |
| + } |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + return err |
| + } |
| + if bytes.Contains(raw, []byte(canaryToken)) { |
| + t.Errorf("the token is in %s", path) |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = l.CheckCopy(context.Background()); err != nil { |
| + t.Fatalf("token copy refused: %v", err) |
| + } |
| + env, err := LaunchSecretEnv(Launch{Binding: l.Binding()}) |
| + if err != nil || env[OAuthTokenEnv] != canaryToken || env[ScrubEnv] != "1" || len(env) != 2 { |
| + t.Fatalf("launch environment %v", err) |
| + } |
| + // A launch on a login home gets nothing. |
| + plain := l.Binding() |
| + plain.Token = false |
| + if env, err = LaunchSecretEnv(Launch{Binding: plain}); err != nil || env != nil { |
| + t.Fatal("a login home's launch got a secret environment") |
| + } |
| + if l.CommitRefresh(context.Background(), func(context.Context, Binding) (Identity, error) { return b.Expected, nil }) == nil { |
| + t.Fatal("a token copy wrote back to its source") |
| + } |
| + l.Close() |
| + if _, err = LaunchSecretEnv(Launch{Binding: l.Binding()}); err == nil { |
| + t.Fatal("a closed lease still gave out its token") |
| + } |
| +} |
| + |
| +// A credential appearing in a token copy is containment. |
| +func TestTokenCopyRefusesCredentialFile(t *testing.T) { |
| + for _, name := range []string{TokenFile, ".credentials.json"} { |
| + t.Run(name, func(t *testing.T) { |
| + l := openTokenCopy(t, tokenFixture(t)) |
| + writeFake(t, filepath.Join(l.Binding().Home, name), "x") |
| + if err := l.CheckCopy(context.Background()); !errors.Is(err, ErrContainment) { |
| + t.Fatalf("credential in the copy accepted: %v", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A token home with a damaged token is not staged. |
| +func TestTokenHomeRefusesBadToken(t *testing.T) { |
| + b := tokenFixture(t) |
| + writeFake(t, filepath.Join(b.Home, TokenFile), "two words") |
| + if l, err := OpenRuntimeCopy(context.Background(), b, func(context.Context, Binding) (Identity, error) { return b.Expected, nil }, time.Second); err == nil { |
| + l.Close() |
| + t.Fatal("bad token staged") |
| + } |
| +} |
| + |
| +func TestClaudeTokenIdentity(t *testing.T) { |
| + id, label, err := ClaudeTokenIdentity([]byte(`{"loggedIn":true,"authMethod":"oauth_token","email":"a@example.com"}`), "claude-2") |
| + if err != nil || id.AccountID != "a@example.com" || label != "a@example.com" || id.ProviderVersion != ClaudeVersion { |
| + t.Fatal(id, label, err) |
| + } |
| + id, label, err = ClaudeTokenIdentity([]byte(`{"loggedIn":true,"authMethod":"oauth_token"}`), "claude-2") |
| + if err != nil || id.AccountID != "token:claude-2" || label != "" { |
| + t.Fatal(id, label, err) |
| + } |
| + if _, _, err = ClaudeTokenIdentity([]byte(`{"loggedIn":false}`), "claude-2"); !errors.Is(err, ErrLoginRequired) { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/runner/provider/types.go b/internal/runner/provider/types.go| index 174d58a9..c48fb26c 100644 |
| --- a/internal/runner/provider/types.go |
| +++ b/internal/runner/provider/types.go |
| @@ -21,9 +21,12 @@ type Selection struct { |
| type Binding struct { |
| ID, Home, AccountID, Provider string |
| DedicatedHome bool `json:"-"` |
| - Expected Identity |
| - CredentialHome, RuntimeRoot string |
| - provenance *AccountLease |
| + // Token: the home's credential is a pasted setup token (TokenFile), |
| + // passed to the CLI in its environment and never copied. |
| + Token bool `json:"-"` |
| + Expected Identity |
| + CredentialHome, RuntimeRoot string |
| + provenance *AccountLease |
| } |
| // NetworkContract is installed by the runner, never supplied by a permission answer. |
diff --git a/internal/runner/setup/account_bindings.go b/internal/runner/setup/account_bindings.go| index 75519557..114a1acd 100644 |
| --- a/internal/runner/setup/account_bindings.go |
| +++ b/internal/runner/setup/account_bindings.go |
| @@ -80,7 +80,14 @@ func SaveAccountBinding(ctx context.Context, path, person, model string, s runne |
| return provider.ErrIdentity |
| } |
| } |
| - rows = append(rows, AccountBinding{ID: b.ID, LocalID: s.ID, Label: s.Label, PersonID: person, ProviderHome: b.Home, ExpectedIdentity: b.Expected, Provider: b.Provider, Family: map[string]string{"codex": "gpt", "claude": "claude"}[b.Provider], Model: model, AccountID: b.AccountID, Kind: "subscription"}) |
| + kind := "subscription" |
| + if b.Token { |
| + if b.Provider != "claude" { |
| + return provider.ErrIdentity |
| + } |
| + kind = "token" |
| + } |
| + rows = append(rows, AccountBinding{ID: b.ID, LocalID: s.ID, Label: s.Label, PersonID: person, ProviderHome: b.Home, ExpectedIdentity: b.Expected, Provider: b.Provider, Family: map[string]string{"codex": "gpt", "claude": "claude"}[b.Provider], Model: model, AccountID: b.AccountID, Kind: kind}) |
| out, err := os.CreateTemp(dir, ".accounts-") |
| if err != nil { |
| return provider.ErrAccountMaintenance |
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go| index 1c6ef8f7..85d69890 100644 |
| --- a/internal/runner/thin/connector.go |
| +++ b/internal/runner/thin/connector.go |
| @@ -16,6 +16,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/runner/connect" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| "amadan.net/oficina/equipo/internal/wire" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -23,6 +24,7 @@ import ( |
| const connectSchema = ` |
| CREATE TABLE IF NOT EXISTS connect_attempts (id TEXT PRIMARY KEY, person TEXT NOT NULL, provider TEXT NOT NULL, same_machine INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL, home TEXT NOT NULL DEFAULT '', local_id TEXT NOT NULL DEFAULT '', cancelled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL); |
| CREATE TABLE IF NOT EXISTS connect_cleanups (connection TEXT PRIMARY KEY, person TEXT NOT NULL, local_id TEXT NOT NULL, report INTEGER NOT NULL, created_at TEXT NOT NULL); |
| +CREATE TABLE IF NOT EXISTS seen_seals (connection_id TEXT NOT NULL, attempt INTEGER NOT NULL, frame_id TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (connection_id, attempt)); |
| ` |
| // ConnectLimit ends an attempt the person did not finish (spec §2.1: ten |
| @@ -49,13 +51,25 @@ type Connector struct { |
| // Limit bounds an attempt (default ConnectLimit). |
| Limit time.Duration |
| + // Seal opens secrets sealed to this runner (nil: it accepts none); |
| + // RunnerID is the id they must be sealed for. |
| + Seal *sealbox.Keys |
| + RunnerID string |
| + |
| // spawn runs a cleanup in the background (a goroutine; tests replace |
| // it to stop the process between a frame and its cleanup). |
| spawn func(func()) |
| + // fault, in tests, stops a secret's delivery at a boundary ("staged", |
| + // "transaction", "committed") as if the process stopped there. |
| + fault func(stage string) error |
| mu sync.Mutex |
| attempts map[string]context.CancelFunc |
| ctx context.Context |
| + // waits wakes a token attempt waiting for its secret. |
| + waits map[string]chan struct{} |
| + // delivery serialises a secret's delivery with its attempt's end. |
| + delivery sync.Mutex |
| } |
| // cleanup is a sign-out the connector owes: recorded in the transaction |
| @@ -110,17 +124,20 @@ func (c *Connector) log(msg string, err error) { |
| // process died with it) and removes their unfinished homes. |
| func (c *Connector) Start(ctx context.Context) error { |
| c.mu.Lock() |
| - c.ctx, c.attempts = ctx, map[string]context.CancelFunc{} |
| + c.ctx, c.attempts, c.waits = ctx, map[string]context.CancelFunc{}, map[string]chan struct{}{} |
| c.mu.Unlock() |
| - rows, err := c.State.db.QueryContext(ctx, "SELECT id, person, provider, home FROM connect_attempts WHERE state='running'") |
| + 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'") |
| if err != nil { |
| return err |
| } |
| - type left struct{ id, person, provider, home string } |
| + type left struct{ id, person, provider, home, kind, created string } |
| var all []left |
| for rows.Next() { |
| var l left |
| - if err = rows.Scan(&l.id, &l.person, &l.provider, &l.home); err != nil { |
| + if err = rows.Scan(&l.id, &l.person, &l.provider, &l.home, &l.kind, &l.created); err != nil { |
| rows.Close() |
| return err |
| } |
| @@ -128,6 +145,14 @@ func (c *Connector) Start(ctx context.Context) error { |
| } |
| rows.Close() |
| for _, l := range all { |
| + // A token attempt lost no process: it recovers its delivery and |
| + // waits on (or finishes) where it was. |
| + if l.kind == wire.KindToken { |
| + if err = c.resumeToken(ctx, l.id, l.person, l.home, l.created); err != nil { |
| + return 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"}) |
| } |
| @@ -168,12 +193,20 @@ func (c *Connector) Accept(ctx context.Context, frameID string, cmd wire.Connect |
| if cmd.SameMachine { |
| same = 1 |
| } |
| - _, err = t.Exec("INSERT INTO connect_attempts(id, person, provider, same_machine, state, created_at) VALUES(?,?,?,?,?,?) ON CONFLICT DO NOTHING", cmd.Connection, cmd.Person, cmd.Provider, same, "running", now()) |
| + _, err = t.Exec("INSERT INTO connect_attempts(id, person, provider, same_machine, state, kind, created_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", cmd.Connection, cmd.Person, cmd.Provider, same, "running", cmd.Kind, now()) |
| return err |
| }) |
| if err != nil || !fresh { |
| return err |
| } |
| + // A token attempt's home is made before the next frame is read, so |
| + // its secret, however soon it follows, finds the attempt ready (the |
| + // attempt ends if this fails). |
| + if cmd.Kind == wire.KindToken && cmd.Provider == wire.ProviderClaude && slices.Contains(c.Owners, cmd.Person) { |
| + if _, herr := c.tokenHome(ctx, cmd.Connection); herr != nil { |
| + c.log("connect home", herr) |
| + } |
| + } |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| if c.ctx == nil { |
| @@ -286,6 +319,7 @@ func (c *Connector) remove(k cleanup) bool { |
| return false |
| } |
| c.Conns.Forget(b.ID) |
| + c.Conns.forgetExpiry(b.ID) |
| c.Conns.changed() |
| } |
| if k.home != "" { |
| @@ -367,6 +401,14 @@ func (c *Connector) run(ctx context.Context, cancel context.CancelFunc, cmd wire |
| fail("provider_refused") |
| return |
| } |
| + if cmd.Kind == wire.KindToken { |
| + if cmd.Provider != wire.ProviderClaude { |
| + fail("provider_refused") |
| + return |
| + } |
| + c.runToken(ctx, cmd, base) |
| + return |
| + } |
| if cmd.Provider == wire.ProviderClaude && !cmd.SameMachine { |
| c.watchTerminal(ctx, cmd, base, fail) |
| return |
| @@ -571,4 +613,9 @@ func (c *Connector) removeHome(home string) { |
| } |
| } |
| c.log("connect home", os.RemoveAll(home)) |
| + // The deletion (a token's file with its home) is made durable. |
| + if root, err := os.Open(c.Root); err == nil { |
| + c.log("connect home", root.Sync()) |
| + root.Close() |
| + } |
| } |
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go| index 731ddef0..493b2857 100644 |
| --- a/internal/runner/thin/conns.go |
| +++ b/internal/runner/thin/conns.go |
| @@ -17,6 +17,7 @@ import ( |
| const connSchema = ` |
| CREATE TABLE IF NOT EXISTS conn_state (id TEXT PRIMARY KEY, state TEXT NOT NULL, resets_at TEXT NOT NULL DEFAULT '', window TEXT NOT NULL DEFAULT '', cooloff INTEGER NOT NULL DEFAULT 0, headroom TEXT NOT NULL DEFAULT '', plan TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL); |
| +CREATE TABLE IF NOT EXISTS conn_expiry (id TEXT PRIMARY KEY, expires_at TEXT NOT NULL); |
| ` |
| // ErrNoConnection: nothing the person connected can run the role now. |
| @@ -341,6 +342,7 @@ func (c *Conns) Held() []wire.HeldConnection { |
| return out |
| } |
| bs := c.bindings() |
| + expiries := c.expiries() |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| now := c.clock() |
| @@ -354,7 +356,49 @@ func (c *Conns) Held() []wire.HeldConnection { |
| if kind == "" { |
| kind = wire.KindSubscription |
| } |
| - out = append(out, wire.HeldConnection{LocalID: b.ID, Person: b.PersonID, Provider: b.Provider, Kind: kind, Label: b.AccountID, State: state, Plan: cs.Plan, Headroom: cs.Headroom}) |
| + held := wire.HeldConnection{LocalID: b.ID, Person: b.PersonID, Provider: b.Provider, Kind: kind, Label: b.AccountID, State: state, Plan: cs.Plan, Headroom: cs.Headroom} |
| + if kind == wire.KindToken { |
| + held.Label = tokenLabel(b.AccountID) |
| + if at, ok := expiries[b.ID]; ok { |
| + held.ExpiresAt = &at |
| + } |
| + } |
| + out = append(out, held) |
| + } |
| + return out |
| +} |
| + |
| +// setExpiry records when a token connection's token expires, so the |
| +// date stays the same across restarts. |
| +func (c *Conns) setExpiry(id string, at time.Time) error { |
| + _, err := c.State.db.Exec("INSERT INTO conn_expiry(id, expires_at) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET expires_at=excluded.expires_at", id, at.UTC().Format(time.RFC3339Nano)) |
| + return err |
| +} |
| + |
| +// forgetExpiry drops a signed-out connection's expiry. |
| +func (c *Conns) forgetExpiry(id string) { |
| + _, err := c.State.db.Exec("DELETE FROM conn_expiry WHERE id=?", id) |
| + if err != nil && c.Logger != nil { |
| + c.Logger.Warn("connection expiry", "err", sanitize(err)) |
| + } |
| +} |
| + |
| +// expiries are the recorded token expiries by connection. |
| +func (c *Conns) expiries() map[string]time.Time { |
| + out := map[string]time.Time{} |
| + rows, err := c.State.db.Query("SELECT id, expires_at FROM conn_expiry") |
| + if err != nil { |
| + return out |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var id, at string |
| + if rows.Scan(&id, &at) != nil { |
| + continue |
| + } |
| + if t, err := time.Parse(time.RFC3339Nano, at); err == nil { |
| + out[id] = t.UTC() |
| + } |
| } |
| return out |
| } |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index aa5be0af..3f42e7ea 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -735,6 +735,14 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro |
| if err = l.Connector.Conns.Prefer(ctx, f.ID, *v); err != nil { |
| return 0, err |
| } |
| + case *wire.SecretCommand: |
| + // Acked only once the secret is committed (or refused). |
| + if l.Connector == nil { |
| + continue |
| + } |
| + if err = l.Connector.Secret(ctx, f.ID, *v); err != nil { |
| + return 0, err |
| + } |
| case *wire.CancelConnectCommand: |
| if l.Connector == nil { |
| continue |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 51992232..b57dee16 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -21,6 +21,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/runner/containment" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -185,7 +186,18 @@ 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: coordinatorPersons(c)(), Notify: link.Notify, Logger: o.Logger, Limit: o.ConnectLimit} |
| + connector := &Connector{Runner: c, State: state, Conns: conns, Root: o.AccountsRoot, Owners: coordinatorPersons(c)(), Notify: link.Notify, Logger: o.Logger, Limit: o.ConnectLimit, RunnerID: creds.Bearer.RunnerID} |
| + // The seal key: the X25519 form of the enrolment key the owner |
| + // approved; secrets for token connections are sealed to it. |
| + sealKey := "" |
| + if key, err := runner.ReadMachineKey(c.StateDir); err == nil { |
| + if keys, err := sealbox.FromEd25519(key); err == nil { |
| + connector.Seal, sealKey = &keys, keys.PublicString() |
| + } |
| + clear(key) |
| + } else if o.Logger != nil { |
| + o.Logger.Warn("no seal key: token connections cannot be added", "err", sanitize(err)) |
| + } |
| if err = connector.Start(ctx); err != nil { |
| return err |
| } |
| @@ -241,7 +253,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| catalog = []wire.RepoInfo{} |
| } |
| report := caps.Get(ctx) |
| - return wire.Hello{Repos: repos, CreateIn: in, Home: home, Agent: fg.Agent(), Catalog: catalog, Connections: conns.Held(), Versions: map[string]string{"runner": o.Version, "claude": provider.ClaudeVersion}, |
| + return wire.Hello{Repos: repos, CreateIn: in, Home: home, Agent: fg.Agent(), Catalog: catalog, Connections: conns.Held(), Versions: map[string]string{"runner": o.Version, "claude": provider.ClaudeVersion}, SealKey: sealKey, |
| Platform: &platform, Label: c.MachineLabel, Sandbox: wire.SandboxBubblewrap, Capabilities: &report} |
| } |
| if err = engine.Start(ctx); err != nil { |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index ea5a59d1..41822f62 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -102,6 +102,14 @@ func OpenState(ctx context.Context, dir string) (*State, error) { |
| return nil, err |
| } |
| } |
| + // Added with token connections: an attempt's kind, and whether its |
| + // sealed secret is committed (credential_present). |
| + for _, col := range []string{"kind", "secret"} { |
| + 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 |
| + } |
| + } |
| s := &State{db: d} |
| if s.prefix, err = s.meta(ctx, "frame_prefix"); err != nil { |
| d.Close() |
diff --git a/internal/runner/thin/token.go b/internal/runner/thin/token.go| new file mode 100644 |
| index 00000000..e7f1968b |
| --- /dev/null |
| +++ b/internal/runner/thin/token.go |
| @@ -0,0 +1,476 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// Token connections (Connections spec §2.4, Paul 2026-11-09): the person |
| +// runs `claude setup-token`, pastes the token into the app, which seals |
| +// it to this runner's seal key; the instance relays the opaque box in a |
| +// durable secret frame. The runner opens it, keeps the token only in the |
| +// connection's dedicated home (provider.TokenFile, 0600), and the CLI |
| +// reads it from CLAUDE_CODE_OAUTH_TOKEN. The token is never logged, put |
| +// in an error, a report, argv or a frame. |
| + |
| +// sealMemory is how long a delivered (connection, attempt) is remembered. |
| +const sealMemory = 24 * time.Hour |
| + |
| +// credentialPresent marks an attempt whose secret is committed. |
| +const credentialPresent = "credential_present" |
| + |
| +// errStopped is a test fault: the process stops at a delivery boundary. |
| +var errStopped = errors.New("stopped") |
| + |
| +// tokenAttempt is a token attempt's row. |
| +type tokenAttempt struct { |
| + id, person, home, state, kind, secret string |
| + cancelled bool |
| +} |
| + |
| +func (a tokenAttempt) waiting() bool { |
| + return a.state == "running" && a.kind == wire.KindToken && !a.cancelled && a.secret == "" && a.home != "" |
| +} |
| + |
| +func (c *Connector) attempt(ctx context.Context, id string) (tokenAttempt, bool, error) { |
| + a := tokenAttempt{id: id} |
| + var cancelled int |
| + err := c.State.db.QueryRowContext(ctx, "SELECT person, home, state, kind, secret, cancelled FROM connect_attempts WHERE id=?", id).Scan(&a.person, &a.home, &a.state, &a.kind, &a.secret, &cancelled) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return a, false, nil |
| + } |
| + a.cancelled = cancelled == 1 |
| + return a, err == nil, err |
| +} |
| + |
| +// waitFor registers the attempt's wake channel. |
| +func (c *Connector) waitFor(id string) chan struct{} { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + ch := make(chan struct{}, 1) |
| + c.waits[id] = ch |
| + return ch |
| +} |
| + |
| +func (c *Connector) stopWaiting(id string) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + delete(c.waits, id) |
| +} |
| + |
| +func (c *Connector) wake(id string) { |
| + c.mu.Lock() |
| + ch := c.waits[id] |
| + c.mu.Unlock() |
| + if ch != nil { |
| + select { |
| + case ch <- struct{}{}: |
| + default: |
| + } |
| + } |
| +} |
| + |
| +// tokenHome is the attempt's dedicated home: the one it recorded, or a |
| +// new one under the accounts root. |
| +func (c *Connector) tokenHome(ctx context.Context, id string) (string, error) { |
| + a, ok, err := c.attempt(ctx, id) |
| + if err != nil || !ok { |
| + return "", firstErr(err, provider.ErrIdentity) |
| + } |
| + if a.home != "" { |
| + return a.home, provider.CheckLoginHome(a.home) |
| + } |
| + if err = os.MkdirAll(c.Root, 0700); err != nil { |
| + return "", err |
| + } |
| + _, home, err := nextHome(c.Root, wire.ProviderClaude) |
| + if err == nil { |
| + err = provider.CheckLoginHome(home) |
| + } |
| + if err == nil { |
| + _, err = c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET home=? WHERE id=?", home, id) |
| + } |
| + if err != nil && home != "" { |
| + os.Remove(home) |
| + } |
| + return home, err |
| +} |
| + |
| +// runToken is a token attempt: a dedicated home, the card asking for the |
| +// token, then the wait for its sealed secret (Secret); once committed, |
| +// the status probe, the binding and the healthy report. |
| +func (c *Connector) runToken(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { |
| + // end finishes the attempt (one not yet saved) and removes its home, |
| + // never while a secret is being delivered to it. |
| + end := func(home string, r wire.ConnectionReport) { |
| + c.delivery.Lock() |
| + defer c.delivery.Unlock() |
| + c.removeHome(home) |
| + c.finish(cmd.Connection, r) |
| + } |
| + failed := func(home, reason string) { |
| + r := base |
| + r.State, r.Reason = wire.ConnError, reason |
| + end(home, r) |
| + } |
| + wake := c.waitFor(cmd.Connection) |
| + defer c.stopWaiting(cmd.Connection) |
| + home, err := c.tokenHome(ctx, cmd.Connection) |
| + if err != nil { |
| + c.log("connect home", err) |
| + failed(home, "provider_refused") |
| + return |
| + } |
| + a, _, err := c.attempt(ctx, cmd.Connection) |
| + if err == nil && a.secret == "" { |
| + r := base |
| + r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptToken, Code: "claude setup-token"} |
| + c.report(r) |
| + } |
| + for err == nil && a.secret == "" && a.state == "running" { |
| + select { |
| + case <-ctx.Done(): |
| + failed(home, reasonOf(ctx.Err())) |
| + return |
| + case <-wake: |
| + } |
| + a, _, err = c.attempt(ctx, cmd.Connection) |
| + } |
| + if err != nil || a.state != "running" { |
| + // Ended while it waited (a refused box), or unreadable. |
| + if err != nil { |
| + c.log("connect token", err) |
| + failed(home, "provider_refused") |
| + } |
| + return |
| + } |
| + id := filepath.Base(home) |
| + lock, err := os.Open(home) |
| + if err == nil { |
| + err = unix.Flock(int(lock.Fd()), unix.LOCK_EX) |
| + } |
| + if err != nil { |
| + if lock != nil { |
| + lock.Close() |
| + } |
| + failed(home, "provider_refused") |
| + return |
| + } |
| + defer lock.Close() |
| + if a.cancelled || ctx.Err() != nil { |
| + failed(home, reasonOf(firstErr(ctx.Err(), context.Canceled))) |
| + return |
| + } |
| + // The probe: the unmodified CLI's `auth status --json` in the home, |
| + // the token in its environment. |
| + options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath} |
| + observed, err := provider.RefreshLogin(ctx, provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true}, options) |
| + if ctx.Err() != nil { |
| + failed(home, reasonOf(ctx.Err())) |
| + return |
| + } |
| + if err != nil { |
| + // The token does not sign the CLI in: "This token was rejected. |
| + // Run claude setup-token again." |
| + c.log("connect token probe", err) |
| + r := base |
| + r.State = wire.ConnSignInAgain |
| + end(home, r) |
| + return |
| + } |
| + for _, b := range c.mine(cmd.Person) { |
| + if b.Provider == wire.ProviderClaude && b.AccountID == observed.AccountID { |
| + failed(home, "already_connected") |
| + return |
| + } |
| + } |
| + if c.Conns != nil { |
| + c.Conns.Forget(id) |
| + if err = c.Conns.setExpiry(id, time.Now().Add(wire.TokenLifetime)); err != nil { |
| + c.log("connect token", err) |
| + failed(home, "provider_refused") |
| + return |
| + } |
| + } |
| + if err = saveToken(ctx, c.Runner.AccountBindingsPath, cmd.Person, id, home, observed); err != nil { |
| + c.log("connect token binding", err) |
| + failed(home, "provider_refused") |
| + return |
| + } |
| + if c.Conns != nil { |
| + c.Conns.changed() |
| + } |
| + r := base |
| + r.State, r.LocalID, r.Label = wire.ConnHealthy, id, tokenLabel(observed.AccountID) |
| + c.finish(cmd.Connection, r) |
| + c.standOrGo(cmd, id, lock) |
| +} |
| + |
| +// tokenLabel is what a token connection is called: the account's email |
| +// when the CLI reported one, else nothing (the app names it). |
| +func tokenLabel(account string) string { |
| + if strings.HasPrefix(account, "token:") { |
| + return "" |
| + } |
| + return account |
| +} |
| + |
| +// saveToken records a token home as the person's connection: the |
| +// identity file and the binding (kind token). The token stays in the home. |
| +func saveToken(ctx context.Context, bindings, person, id, home string, observed provider.Identity) error { |
| + observed.HomeID = rand.Text() |
| + raw, _ := json.Marshal(observed) |
| + if err := os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600); err != nil { |
| + return err |
| + } |
| + b := provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true, AccountID: observed.AccountID, Expected: observed} |
| + return runnersetup.SaveAccountBinding(ctx, bindings, person, DefaultModels[wire.ProviderClaude], runnerproto.AccountSetup{ID: id, Provider: wire.ProviderClaude, Label: id}, b) |
| +} |
| + |
| +// resumeToken picks a token attempt up after a restart. Recovery (spec |
| +// §2.4): a staged file with no seen_seals row is deleted (the resend is |
| +// processed from received); with the row, the secret is committed and |
| +// the final file must be there (a rename the stop interrupted is |
| +// finished); a row with neither file cannot happen and ends the attempt |
| +// in error. Then the attempt waits on for the rest of its time. |
| +func (c *Connector) resumeToken(ctx context.Context, id, person, home, created string) error { |
| + base := wire.ConnectionReport{Connection: id, Person: person, Provider: wire.ProviderClaude} |
| + var rows int |
| + if err := c.State.db.QueryRowContext(ctx, "SELECT count(*) FROM seen_seals WHERE connection_id=?", id).Scan(&rows); err != nil { |
| + return err |
| + } |
| + if home != "" { |
| + dir, err := os.Open(home) |
| + if err != nil { |
| + c.removeHome(home) |
| + c.finish(id, wire.ConnectionReport{Connection: id, Person: person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: "runner_offline"}) |
| + return nil |
| + } |
| + defer dir.Close() |
| + fd := int(dir.Fd()) |
| + if rows == 0 { |
| + for _, name := range []string{provider.TokenStaging, provider.TokenFile} { |
| + if err = unix.Unlinkat(fd, name, 0); err != nil && err != unix.ENOENT { |
| + return err |
| + } |
| + } |
| + if _, err = c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET secret='' WHERE id=?", id); err != nil { |
| + return err |
| + } |
| + } else { |
| + var st unix.Stat_t |
| + if unix.Fstatat(fd, provider.TokenFile, &st, unix.AT_SYMLINK_NOFOLLOW) == unix.ENOENT { |
| + if err = unix.Renameat(fd, provider.TokenStaging, fd, provider.TokenFile); err != nil { |
| + c.removeHome(home) |
| + r := base |
| + r.State, r.Reason = wire.ConnError, "provider_refused" |
| + c.finish(id, r) |
| + return nil |
| + } |
| + } |
| + } |
| + if err = dir.Sync(); err != nil { |
| + return err |
| + } |
| + } |
| + at, _ := time.Parse(time.RFC3339Nano, created) |
| + limit := c.Limit |
| + if limit <= 0 { |
| + limit = ConnectLimit |
| + } |
| + if !time.Now().Before(at.Add(limit)) { |
| + c.removeHome(home) |
| + r := base |
| + r.State, r.Reason = wire.ConnError, "timed_out" |
| + c.finish(id, r) |
| + return nil |
| + } |
| + actx, cancel := context.WithDeadline(c.ctx, at.Add(limit)) |
| + c.mu.Lock() |
| + c.attempts[id] = cancel |
| + c.mu.Unlock() |
| + go c.run(actx, cancel, wire.ConnectCommand{Connection: id, Person: person, Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| + return nil |
| +} |
| + |
| +// Secret delivers a sealed secret to the token attempt it names (spec |
| +// §2.4), one durable step at a time: (i) received, nothing written; |
| +// (ii) staged: the box opened and checked, the token in the home's |
| +// staging file, synced with the directory, the buffer zeroed; (iii) |
| +// committed: one transaction records (connection, attempt, frame) in |
| +// seen_seals and the attempt's credential_present, and the staging file |
| +// is renamed to the token file, the directory synced; (iv) acked by the |
| +// link once this returns nil. A resend of a delivered pair is acked and |
| +// nothing else. A refused box ends a waiting attempt with a reason; one |
| +// for no waiting attempt is acked and dropped. Nothing secret reaches a |
| +// log, an error or a report. |
| +func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretCommand) error { |
| + c.delivery.Lock() |
| + defer c.delivery.Unlock() |
| + s := cmd.Sealed |
| + var n int |
| + if err := c.State.db.QueryRowContext(ctx, "SELECT count(*) FROM seen_seals WHERE connection_id=? AND attempt=?", s.ConnectionID, s.Attempt).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + return nil |
| + } |
| + a, found, err := c.attempt(ctx, cmd.Connection) |
| + if err != nil { |
| + return err |
| + } |
| + if !found || !a.waiting() { |
| + c.refused("no_attempt") |
| + return nil |
| + } |
| + refuse := func(reason string) error { |
| + c.refused(reason) |
| + r := wire.ConnectionReport{Connection: a.id, Person: a.person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason} |
| + c.removeHome(a.home) |
| + c.finish(a.id, r) |
| + c.wake(a.id) |
| + return nil |
| + } |
| + if c.Seal == nil { |
| + return refuse("provider_refused") |
| + } |
| + p, err := c.Seal.Open(s, time.Now()) |
| + if errors.Is(err, sealbox.ErrExpired) { |
| + return refuse("timed_out") |
| + } |
| + if err != nil { |
| + return refuse("provider_refused") |
| + } |
| + secret := []byte(p.Secret) |
| + p.Secret = "" |
| + defer clear(secret) |
| + if p.RunnerID != c.RunnerID || c.RunnerID == "" || p.ConnectionID != cmd.Connection || cmd.Person != a.person || p.Provider != wire.ProviderClaude || p.Endpoint != wire.EndpointAnthropic || p.Attempt < 1 || !provider.ValidToken(secret) { |
| + return refuse("provider_refused") |
| + } |
| + // (ii) staged. |
| + dir, err := pinHome(a.home) |
| + if err != nil { |
| + return err |
| + } |
| + defer dir.Close() |
| + if err = stage(dir, secret); err != nil { |
| + return err |
| + } |
| + clear(secret) |
| + if err = c.stop("staged"); err != nil { |
| + return err |
| + } |
| + // (iii) committed. |
| + err = c.State.tx(ctx, func(t *sql.Tx) error { |
| + res, err := t.Exec("UPDATE connect_attempts SET secret=? WHERE id=? AND state='running' AND cancelled=0 AND secret=''", credentialPresent, a.id) |
| + if err != nil { |
| + return err |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + return firstErr(err, errNotWaiting) |
| + } |
| + if _, err = t.Exec("INSERT INTO seen_seals(connection_id, attempt, frame_id, created_at) VALUES(?,?,?,?)", s.ConnectionID, s.Attempt, frameID, now()); err != nil { |
| + return err |
| + } |
| + if _, err = t.Exec("DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)); err != nil { |
| + return err |
| + } |
| + if err = unix.Renameat(int(dir.Fd()), provider.TokenStaging, int(dir.Fd()), provider.TokenFile); err != nil { |
| + return err |
| + } |
| + if err = dir.Sync(); err != nil { |
| + return err |
| + } |
| + // A stop here leaves the token file with no committed row: the |
| + // restart deletes it. |
| + return c.stop("transaction") |
| + }) |
| + if err != nil { |
| + if errors.Is(err, errStopped) { |
| + return err |
| + } |
| + // Not committed: nothing of it stays. A cancel that won the race |
| + // is acked; anything else is retried on the resend. |
| + _ = unix.Unlinkat(int(dir.Fd()), provider.TokenStaging, 0) |
| + _ = unix.Unlinkat(int(dir.Fd()), provider.TokenFile, 0) |
| + _ = dir.Sync() |
| + if errors.Is(err, errNotWaiting) { |
| + c.refused("not_waiting") |
| + return nil |
| + } |
| + return err |
| + } |
| + if err = c.stop("committed"); err != nil { |
| + return err |
| + } |
| + c.wake(a.id) |
| + return nil |
| +} |
| + |
| +var errNotWaiting = errors.New("the attempt is not waiting for its secret") |
| + |
| +// refused logs a refused or dropped box: the category only. |
| +func (c *Connector) refused(reason string) { |
| + if c.Logger != nil { |
| + c.Logger.Info("sealed secret refused", "reason", reason) |
| + } |
| +} |
| + |
| +// stop is the test fault at a delivery boundary. |
| +func (c *Connector) stop(stage string) error { |
| + if c.fault != nil { |
| + return c.fault(stage) |
| + } |
| + return nil |
| +} |
| + |
| +// pinHome opens a home directory without following links. |
| +func pinHome(home string) (*os.File, error) { |
| + fd, err := unix.Open(home, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return os.NewFile(uintptr(fd), home), nil |
| +} |
| + |
| +// stage writes the secret to the home's staging file (0600, new) and |
| +// syncs it and the directory. |
| +func stage(dir *os.File, secret []byte) error { |
| + dfd := int(dir.Fd()) |
| + if err := unix.Unlinkat(dfd, provider.TokenStaging, 0); err != nil && err != unix.ENOENT { |
| + return err |
| + } |
| + fd, err := unix.Openat(dfd, provider.TokenStaging, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600) |
| + if err != nil { |
| + return err |
| + } |
| + f := os.NewFile(uintptr(fd), provider.TokenStaging) |
| + _, err = f.Write(secret) |
| + if err == nil { |
| + err = f.Sync() |
| + } |
| + if cerr := f.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err == nil { |
| + err = dir.Sync() |
| + } |
| + if err != nil { |
| + _ = unix.Unlinkat(dfd, provider.TokenStaging, 0) |
| + } |
| + return err |
| +} |
diff --git a/internal/runner/thin/token_test.go b/internal/runner/thin/token_test.go| new file mode 100644 |
| index 00000000..e84107ae |
| --- /dev/null |
| +++ b/internal/runner/thin/token_test.go |
| @@ -0,0 +1,590 @@ |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/json" |
| + "errors" |
| + "log/slog" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/fakeclaude" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +const tokenRunner = "run_token_1" |
| + |
| +// lockedBuffer is a log the connector's goroutines write to. |
| +type lockedBuffer struct { |
| + mu sync.Mutex |
| + b bytes.Buffer |
| +} |
| + |
| +func (l *lockedBuffer) Write(p []byte) (int, error) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.b.Write(p) |
| +} |
| + |
| +func (l *lockedBuffer) Bytes() []byte { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return bytes.Clone(l.b.Bytes()) |
| +} |
| + |
| +func (l *lockedBuffer) Len() int { return len(l.Bytes()) } |
| + |
| +func (l *lockedBuffer) String() string { return string(l.Bytes()) } |
| + |
| +// tokenRig is a runner state with no connections, the fake claude for |
| +// the status probe, a seal key, and connectors over them that a test |
| +// can stop and start again as the runner process would. |
| +type tokenRig struct { |
| + t *testing.T |
| + dir, root string |
| + state *State |
| + cfg runner.Config |
| + conns *Conns |
| + keys sealbox.Keys |
| + logs lockedBuffer |
| + errs []error |
| + ctx context.Context |
| +} |
| + |
| +func newTokenRig(t *testing.T) *tokenRig { |
| + dir := t.TempDir() |
| + r := &tokenRig{t: t, dir: dir, root: filepath.Join(dir, "accounts")} |
| + for _, d := range []string{r.root, filepath.Join(dir, "config"), filepath.Join(dir, "state"), filepath.Join(dir, "bin")} { |
| + if err := os.MkdirAll(d, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + self, _ := os.Executable() |
| + raw, err := os.ReadFile(self) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + claudePath := filepath.Join(dir, "bin", "claude") |
| + if err = os.WriteFile(claudePath, raw, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r.state, err = OpenState(context.Background(), filepath.Join(dir, "state")); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { r.state.Close() }) |
| + r.cfg = runner.Config{AccountBindingsPath: filepath.Join(dir, "config", "bindings.json"), ClaudePath: claudePath, CodexPath: "/bin/true"} |
| + r.conns = &Conns{Runner: r.cfg, State: r.state} |
| + _, key, _ := ed25519.GenerateKey(rand.Reader) |
| + if r.keys, err = sealbox.FromEd25519(key); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + t.Cleanup(cancel) |
| + r.ctx = ctx |
| + return r |
| +} |
| + |
| +// connector starts a connector, as a runner process does. |
| +func (r *tokenRig) connector() *Connector { |
| + 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 = func(f func()) { f() } |
| + if err := c.Start(r.ctx); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return c |
| +} |
| + |
| +// connect starts a token attempt and waits for its card. |
| +func (r *tokenRig) connect(c *Connector, id string) string { |
| + r.t.Helper() |
| + if err := c.Accept(r.ctx, "f-connect-"+id, wire.ConnectCommand{Connection: id, Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + r.waitFor(func() bool { |
| + for _, v := range r.reports(id) { |
| + if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptToken && v.Prompt.Code == "claude setup-token" { |
| + return true |
| + } |
| + } |
| + return false |
| + }, "the token card") |
| + var home string |
| + _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home) |
| + if home == "" || filepath.Dir(home) != r.root { |
| + r.t.Fatalf("attempt home %q", home) |
| + } |
| + return home |
| +} |
| + |
| +// sealed is a box for the attempt, as the app seals it. |
| +func (r *tokenRig) sealed(id, token string, change func(*wire.SealedPayload)) wire.SecretCommand { |
| + r.t.Helper() |
| + p := wire.SealedPayload{Secret: token, RunnerID: tokenRunner, ConnectionID: id, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(5 * time.Minute).UTC()} |
| + if change != nil { |
| + change(&p) |
| + } |
| + s, err := sealbox.Seal(r.keys.PublicString(), p) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s} |
| +} |
| + |
| +// deliver is the link's handling of one secret frame: the handler, and |
| +// an ack only when it returns nil. |
| +func (r *tokenRig) deliver(c *Connector, frame string, cmd wire.SecretCommand) bool { |
| + err := c.Secret(r.ctx, frame, cmd) |
| + if err != nil { |
| + r.errs = append(r.errs, err) |
| + } |
| + return err == nil |
| +} |
| + |
| +func (r *tokenRig) reports(id string) []wire.ConnectionReport { |
| + frames, _, err := r.state.Unacked(context.Background(), 0) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + var out []wire.ConnectionReport |
| + for _, f := range frames { |
| + var v wire.ConnectionReport |
| + if f.Type == wire.FrameConnection && json.Unmarshal(f.Data, &v) == nil && v.Connection == id { |
| + out = append(out, v) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// ended waits for the attempt's final report. |
| +func (r *tokenRig) ended(id string) wire.ConnectionReport { |
| + r.t.Helper() |
| + var last wire.ConnectionReport |
| + r.waitFor(func() bool { |
| + var state string |
| + _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id=?", id).Scan(&state) |
| + rs := r.reports(id) |
| + if state != "done" || len(rs) == 0 { |
| + return false |
| + } |
| + last = rs[len(rs)-1] |
| + return last.State != wire.ConnConnecting |
| + }, "the attempt's end") |
| + return last |
| +} |
| + |
| +func (r *tokenRig) waitFor(ok func() bool, what string) { |
| + r.t.Helper() |
| + deadline := time.Now().Add(20 * time.Second) |
| + for !ok() { |
| + if time.Now().After(deadline) { |
| + r.t.Fatalf("no %s", what) |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| +} |
| + |
| +func (r *tokenRig) seals(id string) int { |
| + var n int |
| + if err := r.state.db.QueryRow("SELECT count(*) FROM seen_seals WHERE connection_id=?", id).Scan(&n); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +func (r *tokenRig) binding(local string) (runner.AccountBinding, bool) { |
| + return r.conns.Binding(local) |
| +} |
| + |
| +// healthy checks a delivered attempt ended as one token connection. |
| +func (r *tokenRig) healthy(id, home, token, email string) { |
| + r.t.Helper() |
| + end := r.ended(id) |
| + local := filepath.Base(home) |
| + if end.State != wire.ConnHealthy || end.LocalID != local || end.Label != email { |
| + r.t.Fatalf("end %+v", end) |
| + } |
| + b, ok := r.binding(local) |
| + if !ok || b.Kind != wire.KindToken || b.Provider != wire.ProviderClaude || b.PersonID != connPerson { |
| + r.t.Fatalf("binding %+v %v", b, ok) |
| + } |
| + raw, err := os.ReadFile(filepath.Join(home, provider.TokenFile)) |
| + info, serr := os.Stat(filepath.Join(home, provider.TokenFile)) |
| + if err != nil || serr != nil || string(raw) != token || info.Mode().Perm() != 0600 { |
| + r.t.Fatalf("token file: %v %v", err, serr) |
| + } |
| + if _, err = os.Lstat(filepath.Join(home, provider.TokenStaging)); !os.IsNotExist(err) { |
| + r.t.Fatalf("staging file left: %v", err) |
| + } |
| + healthy := 0 |
| + for _, v := range r.reports(id) { |
| + if v.State == wire.ConnHealthy { |
| + healthy++ |
| + } |
| + } |
| + if healthy != 1 || r.seals(id) != 1 { |
| + r.t.Fatalf("%d healthy reports, %d seen_seals rows", healthy, r.seals(id)) |
| + } |
| + for _, h := range r.conns.Held() { |
| + if h.LocalID == local { |
| + if h.Kind != wire.KindToken || h.Label != email || h.ExpiresAt == nil || time.Until(*h.ExpiresAt) < wire.TokenLifetime-time.Hour { |
| + r.t.Fatalf("held %+v", h) |
| + } |
| + return |
| + } |
| + } |
| + r.t.Fatal("not held") |
| +} |
| + |
| +// A pasted token: the card, the box delivered once, the probe, the |
| +// binding, healthy with the account's email and a year to run. |
| +func TestTokenConnect(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + home := r.connect(c, "cn_t1") |
| + token := fakeclaude.Token("t@example.com") |
| + if !r.deliver(c, "f-secret", r.sealed("cn_t1", token, nil)) { |
| + t.Fatal(r.errs) |
| + } |
| + r.healthy("cn_t1", home, token, "t@example.com") |
| + // The expiry stays the same across a restart. |
| + before := r.conns.Held()[0].ExpiresAt |
| + r.conns = &Conns{Runner: r.cfg, State: r.state} |
| + r.connector() |
| + if after := r.conns.Held()[0].ExpiresAt; after == nil || !after.Equal(*before) { |
| + t.Fatalf("expiry moved: %v %v", before, after) |
| + } |
| +} |
| + |
| +// A token whose CLI names no account: healthy, no label. |
| +func TestTokenConnectWithoutEmail(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + home := r.connect(c, "cn_t2") |
| + token := fakeclaude.Token("") |
| + r.deliver(c, "f-secret", r.sealed("cn_t2", token, nil)) |
| + r.healthy("cn_t2", home, token, "") |
| + if b, _ := r.binding(filepath.Base(home)); b.AccountID != "token:"+filepath.Base(home) { |
| + t.Fatalf("account %q", b.AccountID) |
| + } |
| +} |
| + |
| +// A token the CLI does not accept: sign in again, nothing kept. |
| +func TestTokenRejected(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + home := r.connect(c, "cn_t3") |
| + r.deliver(c, "f-secret", r.sealed("cn_t3", "sk-ant-oat01-revoked", nil)) |
| + if end := r.ended("cn_t3"); end.State != wire.ConnSignInAgain || end.LocalID != "" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) { |
| + t.Fatal("the rejected token's home stayed") |
| + } |
| + if bs, _ := runner.LoadBindings(r.cfg.AccountBindingsPath); len(bs) != 0 { |
| + t.Fatal("a rejected token was bound") |
| + } |
| +} |
| + |
| +// Crash at each delivery boundary: the process stops after the staging |
| +// file is synced, inside the seen_seals transaction, or after the commit |
| +// and before the ack. The restarted runner recovers and the instance's |
| +// resend ends with one token file, one seen_seals row, one ack and a |
| +// healthy connection. |
| +func TestTokenDeliverySurvivesCrashes(t *testing.T) { |
| + for _, stage := range []string{"staged", "transaction", "committed"} { |
| + t.Run(stage, func(t *testing.T) { |
| + r := newTokenRig(t) |
| + first := r.connector() |
| + first.fault = func(at string) error { |
| + if at == stage { |
| + return errStopped |
| + } |
| + return nil |
| + } |
| + id := "cn_c_" + stage |
| + home := r.connect(first, id) |
| + token := fakeclaude.Token("c@example.com") |
| + cmd := r.sealed(id, token, nil) |
| + if r.deliver(first, "f-secret", cmd) { |
| + t.Fatal("acked through a stop") |
| + } |
| + committed := r.seals(id) |
| + if stage == "committed" && committed != 1 || stage != "committed" && committed != 0 { |
| + t.Fatalf("%d seen_seals rows after a stop at %s", committed, stage) |
| + } |
| + // What the stop left: the staged file; the token file renamed |
| + // in a transaction that never committed; the committed file. |
| + left := map[string]string{"staged": provider.TokenStaging, "transaction": provider.TokenFile, "committed": provider.TokenFile}[stage] |
| + if got := tokenFiles(home); len(got) != 1 || got[0] != left { |
| + t.Fatalf("after the stop: %v", got) |
| + } |
| + // The first process is gone (its attempt never wakes again); a |
| + // new one starts on the same state. Recovery keeps only a |
| + // committed token. |
| + second := r.connector() |
| + want := []string{} |
| + if stage == "committed" { |
| + want = []string{provider.TokenFile} |
| + } |
| + if got := tokenFiles(home); strings.Join(got, ",") != strings.Join(want, ",") { |
| + t.Fatalf("after recovery: %v", got) |
| + } |
| + acks := 0 |
| + if r.deliver(second, "f-secret", cmd) { |
| + acks++ |
| + } |
| + r.healthy(id, home, token, "c@example.com") |
| + if acks != 1 { |
| + t.Fatalf("%d acks", acks) |
| + } |
| + entries, _ := os.ReadDir(home) |
| + files := 0 |
| + for _, e := range entries { |
| + if e.Name() == provider.TokenFile || e.Name() == provider.TokenStaging { |
| + files++ |
| + } |
| + } |
| + if files != 1 { |
| + t.Fatalf("%d token files", files) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The same box again is acked and changes nothing; a box for another |
| +// attempt, an expired box, one sealed for another runner and one whose |
| +// clear fields were changed are refused, ending the attempt. |
| +func TestTokenReplayAndRefusals(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + home := r.connect(c, "cn_r1") |
| + token := fakeclaude.Token("r@example.com") |
| + cmd := r.sealed("cn_r1", token, nil) |
| + r.deliver(c, "f-1", cmd) |
| + r.healthy("cn_r1", home, token, "r@example.com") |
| + before, _ := os.Stat(filepath.Join(home, provider.TokenFile)) |
| + reports := len(r.reports("cn_r1")) |
| + // The resend, and the same box in another frame: acked, nothing else |
| + // (not even opened or looked at as a refusal). |
| + logged := r.logs.Len() |
| + for _, frame := range []string{"f-1", "f-1-again"} { |
| + if !r.deliver(c, frame, cmd) { |
| + t.Fatal(r.errs) |
| + } |
| + } |
| + if r.logs.Len() != logged { |
| + t.Fatalf("a delivered pair was handled again: %s", r.logs.String()[logged:]) |
| + } |
| + // A later attempt's box for a connection already made: dropped. |
| + r.deliver(c, "f-2", r.sealed("cn_r1", fakeclaude.Token("x@example.com"), func(p *wire.SealedPayload) { p.Attempt = 2 })) |
| + after, _ := os.Stat(filepath.Join(home, provider.TokenFile)) |
| + if !os.SameFile(before, after) || !after.ModTime().Equal(before.ModTime()) || len(r.reports("cn_r1")) != reports || r.seals("cn_r1") != 1 { |
| + t.Fatal("a replay changed the connection") |
| + } |
| + |
| + refusals := []struct { |
| + name, reason string |
| + box func(id string) wire.SecretCommand |
| + }{ |
| + {"another attempt's box", "provider_refused", func(id string) wire.SecretCommand { |
| + other := r.sealed("cn_other", token, nil) |
| + other.Connection = id |
| + return other |
| + }}, |
| + {"clear fields changed", "provider_refused", func(id string) wire.SecretCommand { |
| + s := r.sealed(id, token, nil) |
| + s.Sealed.Attempt = 7 |
| + return s |
| + }}, |
| + {"expired", "timed_out", func(id string) wire.SecretCommand { |
| + return r.sealed(id, token, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Second).UTC() }) |
| + }}, |
| + {"another runner's key", "provider_refused", func(id string) wire.SecretCommand { |
| + _, key, _ := ed25519.GenerateKey(rand.Reader) |
| + k, _ := sealbox.FromEd25519(key) |
| + s, _ := sealbox.Seal(k.PublicString(), wire.SealedPayload{Secret: token, RunnerID: tokenRunner, ConnectionID: id, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(time.Minute).UTC()}) |
| + return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s} |
| + }}, |
| + {"another runner's id", "provider_refused", func(id string) wire.SecretCommand { |
| + return r.sealed(id, token, func(p *wire.SealedPayload) { p.RunnerID = "run_other" }) |
| + }}, |
| + {"another endpoint", "provider_refused", func(id string) wire.SecretCommand { |
| + return r.sealed(id, token, func(p *wire.SealedPayload) { p.Endpoint = "https://api.example.com:443" }) |
| + }}, |
| + {"another person", "provider_refused", func(id string) wire.SecretCommand { |
| + s := r.sealed(id, token, nil) |
| + s.Person = "q@example.com" |
| + return s |
| + }}, |
| + } |
| + for i, x := range refusals { |
| + t.Run(x.name, func(t *testing.T) { |
| + id := "cn_x" + string(rune('a'+i)) |
| + home := r.connect(c, id) |
| + if !r.deliver(c, "f-x-"+id, x.box(id)) { |
| + t.Fatal("a refused box was not acked") |
| + } |
| + if end := r.ended(id); end.State != wire.ConnError || end.Reason != x.reason { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) || r.seals(id) != 0 { |
| + t.Fatalf("home %v, %d seals", err, r.seals(id)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A cancel before the box arrives: the attempt ends cancelled and the |
| +// late box is acked and dropped, nothing written. |
| +func TestTokenCancelBeforeSecret(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + home := r.connect(c, "cn_k1") |
| + if err := c.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_k1", Person: connPerson}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if end := r.ended("cn_k1"); end.State != wire.ConnError || end.Reason != "cancelled" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if !r.deliver(c, "f-secret", r.sealed("cn_k1", fakeclaude.Token("k@example.com"), nil)) { |
| + t.Fatal(r.errs) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) || r.seals("cn_k1") != 0 { |
| + t.Fatalf("home %v after a cancel", err) |
| + } |
| +} |
| + |
| +// Sign-out deletes the home with its token, the binding and the expiry. |
| +func TestTokenSignOut(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + home := r.connect(c, "cn_s1") |
| + token := fakeclaude.Token("s@example.com") |
| + r.deliver(c, "f-secret", r.sealed("cn_s1", token, nil)) |
| + r.healthy("cn_s1", home, token, "s@example.com") |
| + local := filepath.Base(home) |
| + if err := c.Disconnect(r.ctx, "f-out", wire.DisconnectCommand{Connection: "cn_s1", Person: connPerson, LocalID: local}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) { |
| + t.Fatal("the home stayed") |
| + } |
| + if _, ok := r.binding(local); ok { |
| + t.Fatal("still bound") |
| + } |
| + var n int |
| + _ = r.state.db.QueryRow("SELECT count(*) FROM conn_expiry WHERE id=?", local).Scan(&n) |
| + if n != 0 || len(r.conns.Held()) != 0 { |
| + t.Fatal("the expiry stayed") |
| + } |
| + signedOut := false |
| + for _, v := range r.reports("cn_s1") { |
| + signedOut = signedOut || v.State == wire.ConnSignedOut |
| + } |
| + if !signedOut { |
| + t.Fatal("no signed_out report") |
| + } |
| +} |
| + |
| +// The canary: whatever happens to a token, nothing the runner sends the |
| +// instance, logs, returns as an error or reports in hello carries it. |
| +func TestTokenNeverLeaves(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + good := fakeclaude.Token("canary@example.com") |
| + bad := "sk-ant-oat01-canary-rejected-91c2" |
| + r.connect(c, "cn_g") |
| + r.deliver(c, "f-g", r.sealed("cn_g", good, nil)) |
| + r.ended("cn_g") |
| + r.connect(c, "cn_b") |
| + r.deliver(c, "f-b", r.sealed("cn_b", bad, nil)) |
| + r.ended("cn_b") |
| + r.connect(c, "cn_e") |
| + r.deliver(c, "f-e", r.sealed("cn_e", good, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Minute).UTC() })) |
| + r.ended("cn_e") |
| + r.connect(c, "cn_w") |
| + r.deliver(c, "f-w", r.sealed("cn_w", good, func(p *wire.SealedPayload) { p.Endpoint = "https://api.example.com:443" })) |
| + r.ended("cn_w") |
| + // A stop mid-delivery returns an error the link logs. |
| + c.fault = func(string) error { return errStopped } |
| + r.connect(c, "cn_f") |
| + r.deliver(c, "f-f", r.sealed("cn_f", good, nil)) |
| + c.fault = nil |
| + |
| + frames, _, err := r.state.Unacked(context.Background(), 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var sent bytes.Buffer |
| + for _, f := range frames { |
| + sent.Write(f.Data) |
| + } |
| + held, _ := json.Marshal(r.conns.Held()) |
| + sent.Write(held) |
| + sent.Write(r.logs.Bytes()) |
| + for _, e := range r.errs { |
| + sent.WriteString(e.Error()) |
| + } |
| + var rows bytes.Buffer |
| + for _, q := range []string{"SELECT id||person||home||state||kind||secret FROM connect_attempts", "SELECT connection_id||attempt||frame_id FROM seen_seals", "SELECT value FROM meta"} { |
| + rs, err := r.state.db.Query(q) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for rs.Next() { |
| + var v string |
| + _ = rs.Scan(&v) |
| + rows.WriteString(v) |
| + } |
| + rs.Close() |
| + } |
| + for _, tok := range []string{good, bad} { |
| + for name, b := range map[string][]byte{"sent, logged, held or returned": sent.Bytes(), "runner state": rows.Bytes()} { |
| + if bytes.Contains(b, []byte(tok)) || strings.Contains(string(b), strings.TrimPrefix(tok, "sk-ant-oat01-")) { |
| + t.Fatalf("a token is in what the runner %s", name) |
| + } |
| + } |
| + } |
| + if len(r.errs) != 1 || !errors.Is(r.errs[0], errStopped) { |
| + t.Fatalf("errors %v", r.errs) |
| + } |
| +} |
| + |
| +// tokenFiles are the token's files in a home, by name. |
| +func tokenFiles(home string) []string { |
| + got := []string{} |
| + for _, name := range []string{provider.TokenStaging, provider.TokenFile} { |
| + if _, err := os.Lstat(filepath.Join(home, name)); err == nil { |
| + got = append(got, name) |
| + } |
| + } |
| + return got |
| +} |
| + |
| +// The secret frame read right after the connect frame, before the |
| +// attempt's card went out: the attempt is ready for it. |
| +func TestTokenSecretRightAfterConnect(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + if err := c.Accept(r.ctx, "f-connect", wire.ConnectCommand{Connection: "cn_q1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}); err != nil { |
| + t.Fatal(err) |
| + } |
| + token := fakeclaude.Token("q@example.com") |
| + if !r.deliver(c, "f-secret", r.sealed("cn_q1", token, nil)) { |
| + t.Fatal(r.errs) |
| + } |
| + var home string |
| + _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id='cn_q1'").Scan(&home) |
| + r.healthy("cn_q1", home, token, "q@example.com") |
| +} |
diff --git a/internal/runner/token_test.go b/internal/runner/token_test.go| new file mode 100644 |
| index 00000000..765e3f6b |
| --- /dev/null |
| +++ b/internal/runner/token_test.go |
| @@ -0,0 +1,55 @@ |
| +package runner |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +// A token connection's home, where its token rests, is denied to every |
| +// launch's policy (the model's own and every other connection's), like |
| +// any dedicated home; the bindings file accepts kind token for Claude |
| +// only; and its launches stage it as a token home. |
| +func TestTokenBinding(t *testing.T) { |
| + c := configFixture(t) |
| + root := filepath.Dir(c.StateDir) |
| + identity := provider.Identity{AccountID: "t@example.com", HomeID: "h1", ProviderVersion: provider.ClaudeVersion} |
| + token := AccountBinding{ID: "claude-2", LocalID: "claude-2", PersonID: "p@example.com", Provider: "claude", Family: "claude", Model: "claude-opus-5-5", AccountID: "t@example.com", ProviderHome: filepath.Join(root, "accounts", "claude-2"), Kind: "token", ExpectedIdentity: identity} |
| + other := token |
| + other.ID, other.LocalID, other.AccountID, other.ProviderHome, other.Kind = "claude-1", "claude-1", "o@example.com", filepath.Join(root, "accounts", "claude-1"), "subscription" |
| + other.ExpectedIdentity = provider.Identity{AccountID: "o@example.com", HomeID: "h2", ProviderVersion: provider.ClaudeVersion} |
| + bs := []AccountBinding{other, token} |
| + for _, b := range bs { |
| + policy, err := bindingPolicy(c, bs, b) |
| + if err != nil || !slices.Contains(policy.DeniedPaths, token.ProviderHome) { |
| + t.Fatalf("the token home is not denied to %s: %v", b.ID, err) |
| + } |
| + } |
| + write := func(bs []AccountBinding) { |
| + raw, _ := json.Marshal(bs) |
| + if err := os.WriteFile(c.AccountBindingsPath, raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + write(bs) |
| + if got, err := loadDirectBindings(c.AccountBindingsPath); err != nil || len(got) != 2 { |
| + t.Fatalf("token binding refused: %v", err) |
| + } |
| + codex := token |
| + codex.Provider, codex.Family = "codex", "gpt" |
| + write([]AccountBinding{codex}) |
| + if _, err := loadDirectBindings(c.AccountBindingsPath); err == nil { |
| + t.Fatal("a Codex token binding was accepted") |
| + } |
| + direct, err := c.DirectBinding(token) |
| + if err != nil || !direct.Token { |
| + t.Fatalf("a token binding stages as a login home: %v", err) |
| + } |
| + if direct, _ = c.DirectBinding(other); direct.Token { |
| + t.Fatal("a login binding stages as a token home") |
| + } |
| +} |