| 1 | package headless |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/ed25519" |
| 6 | "crypto/rand" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "io/fs" |
| 10 | "log/slog" |
| 11 | "net/url" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/fakeclaude" |
| 20 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 21 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 22 | "amadan.net/oficina/equipo/internal/sealbox" |
| 23 | "amadan.net/oficina/equipo/internal/thintest" |
| 24 | "amadan.net/oficina/equipo/internal/wire" |
| 25 | ) |
| 26 | |
| 27 | // syncBuffer is a log several goroutines write to. |
| 28 | type syncBuffer struct { |
| 29 | mu sync.Mutex |
| 30 | b bytes.Buffer |
| 31 | } |
| 32 | |
| 33 | func (s *syncBuffer) Write(p []byte) (int, error) { |
| 34 | s.mu.Lock() |
| 35 | defer s.mu.Unlock() |
| 36 | return s.b.Write(p) |
| 37 | } |
| 38 | |
| 39 | func (s *syncBuffer) String() string { |
| 40 | s.mu.Lock() |
| 41 | defer s.mu.Unlock() |
| 42 | return s.b.String() |
| 43 | } |
| 44 | |
| 45 | // Claude with no terminal, end to end through the real runner (Paul, |
| 46 | // 2026-11-10): Connect Claude; the runner runs setup-token itself (the |
| 47 | // fake CLI, in a pseudo-terminal in the new home) and the card shows its |
| 48 | // link; the person signs in (the code the fake's page would show for the |
| 49 | // link's state) and the page seals the code to the runner's published |
| 50 | // key; a wrong code first, then the right one; the CLI prints the token, |
| 51 | // the runner keeps it 0600 and checks it with a real request through the |
| 52 | // contained launch; healthy, and a turn runs on it. The canary: neither |
| 53 | // the code nor the token is anywhere on the instance (database file and |
| 54 | // WAL bytes, logs, API responses, pages), in the runner's log, its state |
| 55 | // or the CLI's argv; the token is only in its file. |
| 56 | func TestHeadlessClaudeSignIn(t *testing.T) { |
| 57 | env, inst, r := localEnv(t) |
| 58 | _, key, _ := ed25519.GenerateKey(rand.Reader) |
| 59 | if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | logs := &syncBuffer{} |
| 63 | r.opts.Logger = slog.New(slog.NewTextHandler(logs, nil)) |
| 64 | r.only(t) |
| 65 | r.start(t) |
| 66 | s := open(t, env) |
| 67 | s.keep() |
| 68 | c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude}) |
| 69 | if err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | var p wire.ConnectPrompt |
| 73 | s.wait(t, "the sign-in link", time.Minute, func(cv *thintest.Conversation) bool { |
| 74 | if v := cv.Connections[c.ID].Prompt; v != nil && v.Kind == wire.PromptAuthorize && v.URL != "" { |
| 75 | p = *v |
| 76 | return true |
| 77 | } |
| 78 | return false |
| 79 | }) |
| 80 | if page := inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "Open Anthropic") || p.Attempt != 1 || p.WrongCode { |
| 81 | t.Fatalf("the card %+v", p) |
| 82 | } |
| 83 | u, err := url.Parse(p.URL) |
| 84 | if err != nil || u.Host != "claude.com" || u.Query().Get("redirect_uri") != wire.EndpointClaudeCode { |
| 85 | t.Fatalf("link %q", p.URL) |
| 86 | } |
| 87 | snap, err := env.Client.Snapshot(s.ctx) |
| 88 | if err != nil || snap.Runner.SealKey == "" { |
| 89 | t.Fatalf("no seal key published: %v", err) |
| 90 | } |
| 91 | send := func(code string, attempt int64) { |
| 92 | t.Helper() |
| 93 | sealed, err := sealbox.Seal(snap.Runner.SealKey, wire.SealedPayload{Secret: code, RunnerID: snap.Runner.ID, ConnectionID: c.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointClaudeCode, Attempt: attempt, ExpiresAt: time.Now().Add(wire.SealedTTL).UTC().Truncate(time.Second)}) |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | if _, err = env.Client.Secret(s.ctx, c.ID, sealed); err != nil { |
| 98 | t.Fatal(err) |
| 99 | } |
| 100 | } |
| 101 | const email = "signin@example.com" |
| 102 | // The CLI starts a child that ignores a hangup, and exits: before the |
| 103 | // runner starts it again (a new link), the whole namespace is gone, |
| 104 | // the child too. |
| 105 | send("orphan-child", 1) |
| 106 | s.wait(t, "the card after the CLI exited", time.Minute, func(cv *thintest.Conversation) bool { |
| 107 | v := cv.Connections[c.ID].Prompt |
| 108 | return v != nil && v.Attempt == 2 && v.URL != "" && v.URL != p.URL |
| 109 | }) |
| 110 | if n := children(); n != 0 { |
| 111 | t.Fatalf("%d of the CLI's children outlived it", n) |
| 112 | } |
| 113 | wrong := fakeclaude.SetupCode(email, "not-this-link") |
| 114 | send(wrong, 2) |
| 115 | s.wait(t, "the wrong-code card", time.Minute, func(cv *thintest.Conversation) bool { |
| 116 | v := cv.Connections[c.ID].Prompt |
| 117 | return v != nil && v.Attempt == 3 && v.WrongCode && v.URL != "" |
| 118 | }) |
| 119 | // The CLI wrote the wrong code into its home and /tmp and is still |
| 120 | // waiting: both are its namespace's memory, nothing on the host. |
| 121 | onHost(t, r, wrong, "the code the CLI wrote") |
| 122 | p = *latest(s, c.ID) |
| 123 | u, _ = url.Parse(p.URL) |
| 124 | code := fakeclaude.SetupCode(email, u.Query().Get("state")) |
| 125 | send(code, 3) |
| 126 | var got wire.Connection |
| 127 | s.wait(t, "healthy", 2*time.Minute, func(cv *thintest.Conversation) bool { |
| 128 | got = cv.Connections[c.ID] |
| 129 | return got.State == wire.ConnHealthy |
| 130 | }) |
| 131 | if got.Kind != wire.KindToken || got.Label != email || got.LocalID == "" || got.ExpiresAt == nil || !got.ExpiresEstimated { |
| 132 | t.Fatalf("connection %+v", got) |
| 133 | } |
| 134 | // Healthy only after a real request through the contained launch. |
| 135 | until(t, "the check's usage", func() bool { |
| 136 | var n int |
| 137 | err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND connection = ? AND outcome = ?", got.LocalID, wire.OutcomeReplied).Scan(&n) |
| 138 | return err == nil && n == 1 |
| 139 | }) |
| 140 | onHost(t, r, code, "the code the CLI wrote") |
| 141 | onHost(t, r, fakeclaude.Token(email), "the token the CLI wrote") |
| 142 | home := filepath.Join(r.root, "accounts", got.LocalID) |
| 143 | token := fakeclaude.Token(email) |
| 144 | tokenFile := filepath.Join(home, provider.TokenFile) |
| 145 | if raw, err := os.ReadFile(tokenFile); err != nil || string(raw) != token { |
| 146 | t.Fatalf("token file: %v", err) |
| 147 | } |
| 148 | if info, err := os.Stat(tokenFile); err != nil || info.Mode().Perm() != 0600 { |
| 149 | t.Fatalf("token file mode: %v", err) |
| 150 | } |
| 151 | sent := s.send(t, "Hello on the signed-in Claude.") |
| 152 | m := replyOf(t, s, sent.Turn.ID) |
| 153 | if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != got.LocalID { |
| 154 | t.Fatalf("turn on the new connection: %q", m.Text) |
| 155 | } |
| 156 | // The CLI's argv is the policy's, attested at launch |
| 157 | // (TestSignInPolicyAttestation): setup-token and nothing else. |
| 158 | |
| 159 | // The canary sweep. |
| 160 | list, _ := env.Client.Connections(s.ctx) |
| 161 | api, _ := json.Marshal(list) |
| 162 | sinks := map[string]string{"the instance's logs": inst.Logs(), "the API": string(api), "the runner's log": logs.String()} |
| 163 | for _, path := range []string{"/conversation/settings/connections", "/conversation/settings/connections/add", "/conversation"} { |
| 164 | sinks[path] = inst.Get(t, path) |
| 165 | } |
| 166 | for _, f := range []string{inst.Path, inst.Path + "-wal"} { |
| 167 | raw, err := os.ReadFile(f) |
| 168 | if err != nil && !os.IsNotExist(err) { |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | sinks[filepath.Base(f)] = string(raw) |
| 172 | } |
| 173 | secrets := map[string]string{"code": code, "wrong code": wrong, "token": token, "token's middle": strings.TrimPrefix(token, "sk-ant-oat01-")} |
| 174 | for name, sink := range sinks { |
| 175 | for what, secret := range secrets { |
| 176 | if strings.Contains(sink, secret) { |
| 177 | t.Fatalf("the %s is in %s", what, name) |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | // On the runner: the code nowhere, the token only in its file (its |
| 182 | // state database and WAL, the homes, its scratch and config, the |
| 183 | // CLI's argv record). |
| 184 | bin := filepath.Dir(r.cfg.ClaudePath) |
| 185 | for _, dir := range []string{r.cfg.StateDir, filepath.Join(r.root, "accounts"), r.cfg.ScratchRoot, filepath.Dir(r.cfg.AccountBindingsPath), bin} { |
| 186 | _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { |
| 187 | if err != nil || d.IsDir() || !d.Type().IsRegular() || path == tokenFile || filepath.Dir(path) == bin && !strings.HasPrefix(d.Name(), "setup-token.") { |
| 188 | return nil |
| 189 | } |
| 190 | raw, _ := os.ReadFile(path) |
| 191 | for what, secret := range secrets { |
| 192 | if bytes.Contains(raw, []byte(secret)) { |
| 193 | t.Fatalf("the %s is in %s", what, path) |
| 194 | } |
| 195 | } |
| 196 | return nil |
| 197 | }) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // latest is the attempt's card now. |
| 202 | func latest(s *session, id string) *wire.ConnectPrompt { |
| 203 | var p wire.ConnectPrompt |
| 204 | s.conv.Locked(func(c *thintest.Conversation) { |
| 205 | if v := c.Connections[id].Prompt; v != nil { |
| 206 | p = *v |
| 207 | } |
| 208 | }) |
| 209 | return &p |
| 210 | } |
| 211 | |
| 212 | // children counts the fake CLI's hangup-ignoring children still running |
| 213 | // anywhere on this machine under this user. |
| 214 | func children() int { |
| 215 | n := 0 |
| 216 | entries, _ := os.ReadDir("/proc") |
| 217 | for _, e := range entries { |
| 218 | raw, err := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline")) |
| 219 | args := bytes.Split(raw, []byte{0}) |
| 220 | if err == nil && len(args) >= 2 && string(args[1]) == "setup-token-child" && filepath.Base(string(args[0])) == "claude" { |
| 221 | if stat, err := os.ReadFile(filepath.Join("/proc", e.Name(), "stat")); err == nil && !bytes.Contains(stat, []byte(") Z ")) { |
| 222 | n++ |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | return n |
| 227 | } |
| 228 | |
| 229 | // A real crash (Paul's runner killed with SIGKILL) while the contained |
| 230 | // setup-token waits for a code: the namespace recorded for the attempt |
| 231 | // dies with the runner or is killed by the next start's recovery, which |
| 232 | // proves it gone before it deletes the attempt's home and ends it |
| 233 | // runner_offline. Nothing of the namespace is left: no process in it, |
| 234 | // no record, no scratch, no child of the CLI. |
| 235 | func TestHeadlessSignInRunnerKilled(t *testing.T) { |
| 236 | env, _, r := localEnv(t) |
| 237 | r.subprocess = true |
| 238 | r.only(t) |
| 239 | homes := func() map[string]bool { |
| 240 | out := map[string]bool{} |
| 241 | entries, _ := os.ReadDir(filepath.Join(r.root, "accounts")) |
| 242 | for _, e := range entries { |
| 243 | out[e.Name()] = true |
| 244 | } |
| 245 | return out |
| 246 | } |
| 247 | before := homes() |
| 248 | r.start(t) |
| 249 | s := open(t, env) |
| 250 | c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude}) |
| 251 | if err != nil { |
| 252 | t.Fatal(err) |
| 253 | } |
| 254 | s.wait(t, "the sign-in link", time.Minute, func(cv *thintest.Conversation) bool { |
| 255 | v := cv.Connections[c.ID].Prompt |
| 256 | return v != nil && v.URL != "" |
| 257 | }) |
| 258 | var home string |
| 259 | for name := range homes() { |
| 260 | if !before[name] { |
| 261 | home = filepath.Join(r.root, "accounts", name) |
| 262 | } |
| 263 | } |
| 264 | // The namespace the runner recorded for the attempt's CLI. |
| 265 | var ns, id string |
| 266 | files, _ := filepath.Glob(filepath.Join(r.cfg.ScratchRoot, "*.json")) |
| 267 | for _, f := range files { |
| 268 | var rec struct{ ID, AttemptKey, NamespaceID string } |
| 269 | raw, _ := os.ReadFile(f) |
| 270 | if json.Unmarshal(raw, &rec) == nil && strings.HasPrefix(rec.AttemptKey, "signin/"+c.ID+"/") { |
| 271 | ns, id = rec.NamespaceID, rec.ID |
| 272 | } |
| 273 | } |
| 274 | if home == "" || ns == "" { |
| 275 | t.Fatalf("home %q, namespace %q", home, ns) |
| 276 | } |
| 277 | r.kill(t) |
| 278 | r.start(t) |
| 279 | var end wire.Connection |
| 280 | s.wait(t, "the attempt's end", 2*time.Minute, func(cv *thintest.Conversation) bool { |
| 281 | end = cv.Connections[c.ID] |
| 282 | return end.State != wire.ConnConnecting |
| 283 | }) |
| 284 | if end.State != wire.ConnError || end.Reason != "runner_offline" { |
| 285 | t.Fatalf("end %+v", end) |
| 286 | } |
| 287 | until(t, "the home gone", func() bool { _, err := os.Stat(home); return os.IsNotExist(err) }) |
| 288 | entries, _ := os.ReadDir("/proc") |
| 289 | for _, e := range entries { |
| 290 | if link, err := os.Readlink(filepath.Join("/proc", e.Name(), "ns", "pid")); err == nil && link == ns { |
| 291 | t.Fatalf("process %s of the killed runner's namespace survived", e.Name()) |
| 292 | } |
| 293 | } |
| 294 | for _, leftover := range []string{filepath.Join(r.cfg.ScratchRoot, id+".json"), filepath.Join(r.cfg.ScratchRoot, "attempt-"+id)} { |
| 295 | if _, err := os.Stat(leftover); !os.IsNotExist(err) { |
| 296 | t.Fatalf("%s stayed: %v", leftover, err) |
| 297 | } |
| 298 | } |
| 299 | if children() != 0 { |
| 300 | t.Fatal("a child of the CLI survived") |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // onHost fails if secret is in any file in the runner's scratch, state, |
| 305 | // homes or config, but the connection's token file (which is the token's |
| 306 | // only place, written by the runner from the CLI's output). |
| 307 | func onHost(t *testing.T, r *localRunner, secret, what string) { |
| 308 | t.Helper() |
| 309 | for _, dir := range []string{r.cfg.ScratchRoot, r.cfg.StateDir, filepath.Join(r.root, "accounts"), filepath.Dir(r.cfg.AccountBindingsPath)} { |
| 310 | _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { |
| 311 | if err != nil || !d.Type().IsRegular() || d.Name() == provider.TokenFile { |
| 312 | return nil |
| 313 | } |
| 314 | if raw, _ := os.ReadFile(path); bytes.Contains(raw, []byte(secret)) { |
| 315 | t.Fatalf("%s is on the host: %s", what, path) |
| 316 | } |
| 317 | return nil |
| 318 | }) |
| 319 | } |
| 320 | } |
| 321 | |