package headless import ( "bytes" "crypto/ed25519" "crypto/rand" "encoding/base64" "encoding/json" "io/fs" "log/slog" "net/url" "os" "path/filepath" "strings" "sync" "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" ) // syncBuffer is a log several goroutines write to. type syncBuffer struct { mu sync.Mutex b bytes.Buffer } func (s *syncBuffer) Write(p []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() return s.b.Write(p) } func (s *syncBuffer) String() string { s.mu.Lock() defer s.mu.Unlock() return s.b.String() } // Claude with no terminal, end to end through the real runner (Paul, // 2026-11-10): Connect Claude; the runner runs setup-token itself (the // fake CLI, in a pseudo-terminal in the new home) and the card shows its // link; the person signs in (the code the fake's page would show for the // link's state) and the page seals the code to the runner's published // key; a wrong code first, then the right one; the CLI prints the token, // the runner keeps it 0600 and checks it with a real request through the // contained launch; healthy, and a turn runs on it. The canary: neither // the code nor the token is anywhere on the instance (database file and // WAL bytes, logs, API responses, pages), in the runner's log, its state // or the CLI's argv; the token is only in its file. func TestHeadlessClaudeSignIn(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) } logs := &syncBuffer{} r.opts.Logger = slog.New(slog.NewTextHandler(logs, nil)) r.only(t) r.start(t) s := open(t, env) s.keep() c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude}) if err != nil { t.Fatal(err) } var p wire.ConnectPrompt s.wait(t, "the sign-in link", time.Minute, func(cv *thintest.Conversation) bool { if v := cv.Connections[c.ID].Prompt; v != nil && v.Kind == wire.PromptAuthorize && v.URL != "" { p = *v return true } return false }) if page := inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "Open Anthropic") || p.Attempt != 1 || p.WrongCode { t.Fatalf("the card %+v", p) } u, err := url.Parse(p.URL) if err != nil || u.Host != "claude.com" || u.Query().Get("redirect_uri") != wire.EndpointClaudeCode { t.Fatalf("link %q", p.URL) } snap, err := env.Client.Snapshot(s.ctx) if err != nil || snap.Runner.SealKey == "" { t.Fatalf("no seal key published: %v", err) } send := func(code string, attempt int64) { t.Helper() 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)}) if err != nil { t.Fatal(err) } if _, err = env.Client.Secret(s.ctx, c.ID, sealed); err != nil { t.Fatal(err) } } const email = "signin@example.com" // The CLI starts a child that ignores a hangup, and exits: before the // runner starts it again (a new link), the whole namespace is gone, // the child too. send("orphan-child", 1) s.wait(t, "the card after the CLI exited", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c.ID].Prompt return v != nil && v.Attempt == 2 && v.URL != "" && v.URL != p.URL }) if n := children(); n != 0 { t.Fatalf("%d of the CLI's children outlived it", n) } wrong := fakeclaude.SetupCode(email, "not-this-link") send(wrong, 2) s.wait(t, "the wrong-code card", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c.ID].Prompt return v != nil && v.Attempt == 3 && v.WrongCode && v.URL != "" }) // The CLI wrote the wrong code into its home and /tmp and is still // waiting: both are its namespace's memory, nothing on the host. onHost(t, r, wrong, "the code the CLI wrote") p = *latest(s, c.ID) u, _ = url.Parse(p.URL) code := fakeclaude.SetupCode(email, u.Query().Get("state")) send(code, 3) var got wire.Connection s.wait(t, "healthy", 2*time.Minute, func(cv *thintest.Conversation) bool { got = cv.Connections[c.ID] return got.State == wire.ConnHealthy }) if got.Kind != wire.KindToken || got.Label != email || got.LocalID == "" || got.ExpiresAt == nil || !got.ExpiresEstimated { t.Fatalf("connection %+v", got) } // Healthy only after a real request through the contained launch. until(t, "the check's usage", func() bool { var n int err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND connection = ? AND outcome = ?", got.LocalID, wire.OutcomeReplied).Scan(&n) return err == nil && n == 1 }) onHost(t, r, code, "the code the CLI wrote") onHost(t, r, fakeclaude.Token(email), "the token the CLI wrote") home := filepath.Join(r.root, "accounts", got.LocalID) token := fakeclaude.Token(email) tokenFile := filepath.Join(home, provider.TokenFile) if raw, err := os.ReadFile(tokenFile); err != nil || string(raw) != token { t.Fatalf("token file: %v", err) } if info, err := os.Stat(tokenFile); err != nil || info.Mode().Perm() != 0600 { t.Fatalf("token file mode: %v", err) } sent := s.send(t, "Hello on the signed-in Claude.") m := replyOf(t, s, sent.Turn.ID) if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != got.LocalID { t.Fatalf("turn on the new connection: %q", m.Text) } // The CLI's argv is the policy's, attested at launch // (TestSignInPolicyAttestation): setup-token and nothing else. // The canary sweep. list, _ := env.Client.Connections(s.ctx) api, _ := json.Marshal(list) sinks := map[string]string{"the instance's logs": inst.Logs(), "the API": string(api), "the runner's log": logs.String()} for _, path := range []string{"/conversation/settings/connections", "/conversation/settings/connections/add", "/conversation"} { sinks[path] = inst.Get(t, path) } for _, f := range []string{inst.Path, inst.Path + "-wal"} { raw, err := os.ReadFile(f) if err != nil && !os.IsNotExist(err) { t.Fatal(err) } sinks[filepath.Base(f)] = string(raw) } secrets := map[string]string{"code": code, "wrong code": wrong, "token": token, "token's middle": strings.TrimPrefix(token, "sk-ant-oat01-")} for name, sink := range sinks { for what, secret := range secrets { if strings.Contains(sink, secret) { t.Fatalf("the %s is in %s", what, name) } } } // On the runner: the code nowhere, the token only in its file (its // state database and WAL, the homes, its scratch and config, the // CLI's argv record). bin := filepath.Dir(r.cfg.ClaudePath) for _, dir := range []string{r.cfg.StateDir, filepath.Join(r.root, "accounts"), r.cfg.ScratchRoot, filepath.Dir(r.cfg.AccountBindingsPath), bin} { _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() || !d.Type().IsRegular() || path == tokenFile || filepath.Dir(path) == bin && !strings.HasPrefix(d.Name(), "setup-token.") { return nil } raw, _ := os.ReadFile(path) for what, secret := range secrets { if bytes.Contains(raw, []byte(secret)) { t.Fatalf("the %s is in %s", what, path) } } return nil }) } } // latest is the attempt's card now. func latest(s *session, id string) *wire.ConnectPrompt { var p wire.ConnectPrompt s.conv.Locked(func(c *thintest.Conversation) { if v := c.Connections[id].Prompt; v != nil { p = *v } }) return &p } // children counts the fake CLI's hangup-ignoring children still running // anywhere on this machine under this user. func children() int { n := 0 entries, _ := os.ReadDir("/proc") for _, e := range entries { raw, err := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline")) args := bytes.Split(raw, []byte{0}) if err == nil && len(args) >= 2 && string(args[1]) == "setup-token-child" && filepath.Base(string(args[0])) == "claude" { if stat, err := os.ReadFile(filepath.Join("/proc", e.Name(), "stat")); err == nil && !bytes.Contains(stat, []byte(") Z ")) { n++ } } } return n } // A real crash (Paul's runner killed with SIGKILL) while the contained // setup-token waits for a code: the namespace recorded for the attempt // dies with the runner or is killed by the next start's recovery, which // proves it gone before it deletes the attempt's home and ends it // runner_offline. Nothing of the namespace is left: no process in it, // no record, no scratch, no child of the CLI. func TestHeadlessSignInRunnerKilled(t *testing.T) { env, _, r := localEnv(t) r.subprocess = true r.only(t) homes := func() map[string]bool { out := map[string]bool{} entries, _ := os.ReadDir(filepath.Join(r.root, "accounts")) for _, e := range entries { out[e.Name()] = true } return out } before := homes() r.start(t) s := open(t, env) c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude}) if err != nil { t.Fatal(err) } s.wait(t, "the sign-in link", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c.ID].Prompt return v != nil && v.URL != "" }) var home string for name := range homes() { if !before[name] { home = filepath.Join(r.root, "accounts", name) } } // The namespace the runner recorded for the attempt's CLI. var ns, id string files, _ := filepath.Glob(filepath.Join(r.cfg.ScratchRoot, "*.json")) for _, f := range files { var rec struct{ ID, AttemptKey, NamespaceID string } raw, _ := os.ReadFile(f) if json.Unmarshal(raw, &rec) == nil && strings.HasPrefix(rec.AttemptKey, "signin/"+c.ID+"/") { ns, id = rec.NamespaceID, rec.ID } } if home == "" || ns == "" { t.Fatalf("home %q, namespace %q", home, ns) } r.kill(t) r.start(t) var end wire.Connection s.wait(t, "the attempt's end", 2*time.Minute, func(cv *thintest.Conversation) bool { end = cv.Connections[c.ID] return end.State != wire.ConnConnecting }) if end.State != wire.ConnError || end.Reason != "runner_offline" { t.Fatalf("end %+v", end) } until(t, "the home gone", func() bool { _, err := os.Stat(home); return os.IsNotExist(err) }) entries, _ := os.ReadDir("/proc") for _, e := range entries { if link, err := os.Readlink(filepath.Join("/proc", e.Name(), "ns", "pid")); err == nil && link == ns { t.Fatalf("process %s of the killed runner's namespace survived", e.Name()) } } for _, leftover := range []string{filepath.Join(r.cfg.ScratchRoot, id+".json"), filepath.Join(r.cfg.ScratchRoot, "attempt-"+id)} { if _, err := os.Stat(leftover); !os.IsNotExist(err) { t.Fatalf("%s stayed: %v", leftover, err) } } if children() != 0 { t.Fatal("a child of the CLI survived") } } // onHost fails if secret is in any file in the runner's scratch, state, // homes or config, but the connection's token file (which is the token's // only place, written by the runner from the CLI's output). func onHost(t *testing.T, r *localRunner, secret, what string) { t.Helper() for _, dir := range []string{r.cfg.ScratchRoot, r.cfg.StateDir, filepath.Join(r.root, "accounts"), filepath.Dir(r.cfg.AccountBindingsPath)} { _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if err != nil || !d.Type().IsRegular() || d.Name() == provider.TokenFile { return nil } if raw, _ := os.ReadFile(path); bytes.Contains(raw, []byte(secret)) { t.Fatalf("%s is on the host: %s", what, path) } return nil }) } }