package headless import ( "crypto/ed25519" "crypto/rand" "encoding/base64" "net/http" "net/http/httptest" "net/netip" "path/filepath" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/thin" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // A token whose CLI names no account, pasted end to end: the real check // (the contained launch) answers, then reads the account profile from // the runner with the same token, at a fake profile endpoint on // 127.0.0.1. The email it names is the connection's label, from the // healthy report on: the row shows it and asks for no email. The token // reaches neither the instance's log nor its page. func TestHeadlessTokenProfileNamesAccount(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) } token := fakeclaude.Token("") var reads atomic.Int64 profile := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { reads.Add(1) if req.Method != http.MethodGet || req.URL.Path != "/api/oauth/profile" || req.Header.Get("Authorization") != "Bearer "+token || req.Header.Get("User-Agent") != thin.ProfileAgent+"/test" { w.WriteHeader(http.StatusUnauthorized) return } _, _ = w.Write([]byte(`{"account":{"uuid":"acc-1","email":"linked@example.com"},"organization":{"uuid":"org-1"}}`)) })) defer profile.Close() r.opts.Claude.Profile = &thin.ProfileReader{Origin: profile.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, 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, Kind: wire.KindToken}) if err != nil { t.Fatal(err) } s.wait(t, "token card", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c.ID] return v.Prompt != nil && v.Prompt.Kind == wire.PromptToken }) snap, err := env.Client.Snapshot(s.ctx) if err != nil { t.Fatal(err) } sealed, err := sealbox.Seal(snap.Runner.SealKey, wire.SealedPayload{Secret: token, RunnerID: snap.Runner.ID, ConnectionID: c.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, 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) } var got wire.Connection s.wait(t, "token healthy", time.Minute, func(cv *thintest.Conversation) bool { got = cv.Connections[c.ID] return got.State == wire.ConnHealthy }) if got.Label != "linked@example.com" || reads.Load() != 1 { t.Fatalf("healthy %+v after %d profile reads", got, reads.Load()) } row := inst.Get(t, "/conversation/connections") if !strings.Contains(row, "linked@example.com") || strings.Contains(row, "Add the account email") || strings.Contains(row, "(added by you)") { t.Fatal("the row does not show the provider's email plainly, or still asks for one") } if strings.Contains(inst.Logs(), token) || strings.Contains(row, token) { t.Fatal("the token reached the instance") } } // A token connection made before the profile read existed: the runner // reads its profile once as it starts, with no check and no turn, and // names itself (thin.ProfileAgent/). The row is named and asks for // no email. A restart reads it no more: the answer stands. func TestHeadlessTokenProfileAtStart(t *testing.T) { env, inst, r := localEnv(t) // A bare token connection, as the runner records one the CLI named no // account for. token := r.addToken(t, "claude-7", "token:claude-7") var reads atomic.Int64 profile := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { reads.Add(1) if req.Method != http.MethodGet || req.URL.Path != "/api/oauth/profile" || req.Header.Get("Authorization") != "Bearer "+token || req.Header.Get("User-Agent") != thin.ProfileAgent+"/test" { w.WriteHeader(http.StatusUnauthorized) return } _, _ = w.Write([]byte(`{"account":{"uuid":"acc-7","email":"existing@example.com"},"organization":{"uuid":"org-7"}}`)) })) defer profile.Close() r.opts.Claude.Profile = &thin.ProfileReader{Origin: profile.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} r.only(t, "claude-7") r.start(t) s := open(t, env) s.keep() s.wait(t, "the existing row named", time.Minute, func(cv *thintest.Conversation) bool { for _, c := range cv.Connections { if c.LocalID == "claude-7" && c.Label == "existing@example.com" { return true } } return false }) if reads.Load() != 1 { t.Fatalf("%d profile reads at start", reads.Load()) } if page := inst.Get(t, "/conversation/connections"); !strings.Contains(page, "existing@example.com") || strings.Contains(page, "Add the account email") { t.Fatal("the row is not named, or still asks for the email") } r.stop(t) r.start(t) time.Sleep(2 * time.Second) if reads.Load() != 1 { t.Fatalf("a restart read again: %d", reads.Load()) } }