package runnersetup import ( "context" "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "testing" "testing/synctest" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type loginFixture struct { home string state string cancelled bool identity provider.Identity } func (d *loginFixture) Begin(_ context.Context, name, home string) (provider.LoginChallenge, error) { d.home = home return provider.LoginChallenge{ID: "provider-secret", Mode: map[string]string{"claude": "browser", "codex": "device"}[name], VerificationURI: "https://auth.openai.com/codex/device", UserCode: "ABCD-EFGH", ExpiresAt: time.Now().Add(time.Minute)}, nil } func (d *loginFixture) Poll(context.Context, string) (provider.LoginResult, error) { return provider.LoginResult{State: d.state, Identity: d.identity}, nil } func (d *loginFixture) Cancel(context.Context, string) error { d.cancelled = true; return nil } type loginInstance struct { setup runnerproto.AccountSetup result runnerproto.AccountSetupResult err error } func (i *loginInstance) AccountSetup(_ context.Context, id string) (runnerproto.AccountSetup, error) { if id != i.setup.ID || i.err != nil { return runnerproto.AccountSetup{}, provider.ErrIdentity } return i.setup, nil } func (i *loginInstance) ReportAccountSetup(_ context.Context, r runnerproto.AccountSetupResult) (runnerproto.AccountSetup, error) { i.result = r if i.err != nil { return runnerproto.AccountSetup{}, i.err } i.setup.State = r.State i.setup.Revision++ return i.setup, nil } func loginHarness(t *testing.T, name string) (*AccountLogin, *loginFixture, *loginInstance) { t.Helper() root := filepath.Join(t.TempDir(), "private") d := &loginFixture{state: "pending", identity: provider.Identity{AccountID: "account", HomeID: "home", ProviderVersion: "fixture"}} i := &loginInstance{setup: runnerproto.AccountSetup{ID: "setup-one", RunnerID: "runner", Provider: name, State: "pending", Mode: map[string]string{"claude": "browser", "codex": "device"}[name], Revision: 1}} l := &AccountLogin{Root: root, RunnerID: "runner", Instance: i, Driver: d, Probe: func(context.Context, provider.Binding) (provider.Identity, error) { return d.identity, nil }, Save: func(context.Context, runnerproto.AccountSetup, provider.Binding) error { return nil }} return l, d, i } func TestOnboardingAccountDedicatedHome(t *testing.T) { ctx := context.Background() l, d, i := loginHarness(t, "codex") c, e := l.Begin(ctx, "setup-one") if e != nil { t.Fatal(e) } first := d.home st, e := os.Stat(first) if e != nil || st.Mode().Perm() != 0700 { t.Fatal("home not private", e) } if e = l.Cancel(ctx); e != nil { t.Fatal(e) } i.setup.State = "pending" i.setup.ID = "setup-two" _, e = l.Begin(ctx, "setup-two") if e != nil { t.Fatal(e) } if first == d.home { t.Fatal("same-provider homes shared") } if err := os.WriteFile(filepath.Join(d.home, "auth.json"), []byte(`{"token":"NATIVE-SECRET"}`), 0600); err != nil { t.Fatal(err) } d.state = "connected" probes := 0 l.Probe = func(context.Context, provider.Binding) (provider.Identity, error) { probes++; return d.identity, nil } out, err := l.Poll(ctx) if err != nil || out.State != "connected" || probes != 1 || i.result.AccountID != d.identity.AccountID { t.Fatal("dedicated home missing identity readback", out, err) } entries, err := os.ReadDir(l.Root) if err != nil { t.Fatal(err) } for _, entry := range entries { if strings.Contains(entry.Name(), "journal") || strings.HasSuffix(entry.Name(), ".jsonl") { t.Fatal("login emitted journal events") } } raw, _ := json.Marshal(i.result) if strings.Contains(string(raw), "NATIVE-SECRET") { t.Fatal("credential left runner") } if strings.Contains(string(raw), "provider-secret") || strings.Contains(string(raw), l.Root) { t.Fatal("secret left runner") } if c.ID != "provider-secret" { t.Fatal("local challenge lost") } bad, _, bi := loginHarness(t, "codex") bi.setup.ID = "fresh" bad.Root = filepath.Join(l.Root, ".codex") t.Setenv("CODEX_HOME", bad.Root) if _, e = bad.Begin(ctx, "fresh"); e == nil { t.Fatal("interactive home accepted") } } func TestOnboardingDeviceFlow(t *testing.T) { for _, state := range []string{"pending", "connected", "expired", "denied", "cancelled"} { t.Run(state, func(t *testing.T) { l, d, i := loginHarness(t, "codex") ctx := context.Background() _, e := l.Begin(ctx, i.setup.ID) if e != nil { t.Fatal(e) } d.state = state r, e := l.Poll(ctx) if state == "connected" { if e == nil || r.State == "connected" { t.Fatal("login succeeded without credential readback") } } else if e != nil || r.State != state { t.Fatal(state, r, e) } }) } l, d, i := loginHarness(t, "codex") _, e := l.Begin(context.Background(), i.setup.ID) if e != nil { t.Fatal(e) } if e = l.Cancel(context.Background()); e != nil || !d.cancelled || i.result.State != "cancelled" { t.Fatal("cancel not contained", e) } restart := *l restart.active = nil if _, e = restart.Poll(context.Background()); e == nil { t.Fatal("restart invented success") } } func TestOnboardingNoDeviceCapability(t *testing.T) { for _, name := range []string{"claude", "codex"} { d := provider.NewLoginDriver() _, e := d.Begin(context.Background(), name, filepath.Join(t.TempDir(), "never-created")) if !errors.Is(e, provider.ErrLoginUnavailable) { t.Fatal("unrecorded login contract enabled", name, e) } } l, _, i := loginHarness(t, "claude") c, e := l.Begin(context.Background(), i.setup.ID) if e != nil || c.Mode != "browser" || i.result.Challenge != nil { t.Fatal("browser fallback exposed challenge", e) } } func TestOnboardingAccountBindings(t *testing.T) { root := filepath.Join(t.TempDir(), "state") if e := os.Mkdir(root, 0700); e != nil { t.Fatal(e) } path := filepath.Join(root, "accounts.json") s := runnerproto.AccountSetup{ID: "one", Provider: "codex", Label: "Personal"} b := provider.Binding{ID: "one", Provider: "codex", Home: filepath.Join(root, "one"), AccountID: "account-one", Expected: provider.Identity{AccountID: "account-one", HomeID: "home-one", ProviderVersion: "0.165.0"}} if e := SaveAccountBinding(context.Background(), path, "person", "model", s, b); e != nil { t.Fatal(e) } original, e := os.ReadFile(path) if e != nil { t.Fatal(e) } if e = SaveAccountBinding(context.Background(), path, "person", "model", s, b); e == nil { t.Fatal("new setup replaced existing home") } after, _ := os.ReadFile(path) if string(after) != string(original) { t.Fatal("rejected save changed bindings") } s.ID = "two" s.Label = "Work" b.ID = "two" b.Home = filepath.Join(root, "two") b.AccountID = "account-two" b.Expected.AccountID = b.AccountID b.Expected.HomeID = "home-two" if e = SaveAccountBinding(context.Background(), path, "person", "model", s, b); e != nil { t.Fatal(e) } raw, _ := os.ReadFile(path) var rows []AccountBinding if e = json.Unmarshal(raw, &rows); e != nil || len(rows) != 2 || rows[0].Label != "Personal" || rows[1].Label != "Work" { t.Fatal("labeled accounts lost", e) } } func TestOnboardingAccountReportRetry(t *testing.T) { l, d, i := loginHarness(t, "codex") ctx := context.Background() if _, e := l.Begin(ctx, i.setup.ID); e != nil { t.Fatal(e) } if e := os.WriteFile(filepath.Join(d.home, "auth.json"), []byte(`{"token":"fixture"}`), 0600); e != nil { t.Fatal(e) } saves := 0 l.Save = func(context.Context, runnerproto.AccountSetup, provider.Binding) error { saves++ i.err = errors.New("lost response") return nil } d.state = "connected" if _, e := l.Poll(ctx); e == nil { t.Fatal("expected report failure") } i.err = nil out, e := l.Poll(ctx) if e != nil || out.State != "connected" || saves != 1 { t.Fatal("saved account report not retryable", out, e, saves) } } func TestOnboardingAccountClockExpiry(t *testing.T) { l, d, i := loginHarness(t, "codex") if _, e := l.Begin(context.Background(), i.setup.ID); e != nil { t.Fatal(e) } l.active.challenge.ExpiresAt = time.Now().Add(-time.Second) out, e := l.Poll(context.Background()) if e != nil || out.State != "expired" || !d.cancelled { t.Fatal("clock expiry ignored", out, e) } if _, e = os.Stat(d.home); !os.IsNotExist(e) { t.Fatal("expired home retained") } } type beginFailure struct { loginFixture invalid bool } func (d *beginFailure) Begin(ctx context.Context, name, home string) (provider.LoginChallenge, error) { c, e := d.loginFixture.Begin(ctx, name, home) if d.invalid { c.Mode = "wrong" return c, e } return c, provider.ErrLoginUnavailable } func TestOnboardingAccountBeginCleanup(t *testing.T) { for _, invalid := range []bool{false, true} { t.Run(fmt.Sprint(invalid), func(t *testing.T) { l, base, i := loginHarness(t, "claude") d := &beginFailure{loginFixture: *base, invalid: invalid} l.Driver = d if _, e := l.Begin(context.Background(), i.setup.ID); e == nil { t.Fatal("bad Begin accepted") } entries, e := os.ReadDir(l.Root) if e != nil || len(entries) != 0 { t.Fatal("failed Begin leaked home or marker", entries, e) } if invalid && !d.cancelled { t.Fatal("invalid challenge left CLI running") } }) } } func TestOnboardingAccountResumeSavedReport(t *testing.T) { l, d, i := loginHarness(t, "codex") ctx := context.Background() if _, e := l.Begin(ctx, i.setup.ID); e != nil { t.Fatal(e) } if e := os.WriteFile(filepath.Join(d.home, "auth.json"), []byte(`{"token":"fixture"}`), 0600); e != nil { t.Fatal(e) } path := filepath.Join(l.Root, "bindings.json") l.Save = func(ctx context.Context, s runnerproto.AccountSetup, b provider.Binding) error { if e := SaveAccountBinding(ctx, path, "person", "model", s, b); e != nil { return e } i.err = errors.New("offline after save") return nil } d.state = "connected" if _, e := l.Poll(ctx); e == nil { t.Fatal("expected report loss") } i.err = nil handled, e := ResumeSavedAccount(ctx, path, "person", i.setup, i, l.Probe) if e != nil || !handled || i.setup.State != "connected" { t.Fatal("restart could not report saved binding", handled, e) } if _, e = os.Stat(d.home); e != nil { t.Fatal("saved home removed", e) } i.setup.State = "pending" _, e = ResumeSavedAccount(ctx, path, "other-person", i.setup, i, l.Probe) if e == nil { t.Fatal("saved binding changed owner") } } type cancelOnBegin struct { loginFixture stop context.CancelFunc } func (d *cancelOnBegin) Begin(ctx context.Context, name, home string) (provider.LoginChallenge, error) { c, e := d.loginFixture.Begin(ctx, name, home) d.stop() return c, e } func TestOnboardingAccountCommandCancel(t *testing.T) { l, base, i := loginHarness(t, "claude") ctx, stop := context.WithCancel(context.Background()) defer stop() d := &cancelOnBegin{loginFixture: *base, stop: stop} l.Driver = d if e := RunAccountLogin(ctx, l, i.setup.ID); !errors.Is(e, context.Canceled) { t.Fatal("interrupt not returned", e) } if !d.cancelled || i.setup.State != "cancelled" { t.Fatal("interrupt not reported", i.setup) } if _, e := os.Stat(d.home); !os.IsNotExist(e) { t.Fatal("cancelled home retained") } } type contextAccountInstance struct{ *loginInstance } func (i contextAccountInstance) ReportAccountSetup(ctx context.Context, q runnerproto.AccountSetupResult) (runnerproto.AccountSetup, error) { if e := ctx.Err(); e != nil { return runnerproto.AccountSetup{}, e } return i.loginInstance.ReportAccountSetup(ctx, q) } func TestOnboardingAccountInterruptDuringBegin(t *testing.T) { l, base, i := loginHarness(t, "claude") l.Instance = contextAccountInstance{i} ctx, stop := context.WithCancel(context.Background()) defer stop() d := &cancelOnBegin{loginFixture: *base, stop: stop} l.Driver = d if e := RunAccountLogin(ctx, l, i.setup.ID); !errors.Is(e, context.Canceled) { t.Fatal("interrupt not returned", e) } if !d.cancelled || i.setup.State != "cancelled" { t.Fatal("interrupt during Begin not reported", i.setup) } if _, e := os.Stat(d.home); !os.IsNotExist(e) { t.Fatal("cancelled home retained") } } func TestOnboardingAccountInterruptDuringProbe(t *testing.T) { l, d, i := loginHarness(t, "codex") l.Instance = contextAccountInstance{i} ctx, stop := context.WithCancel(context.Background()) defer stop() if _, e := l.Begin(ctx, i.setup.ID); e != nil { t.Fatal(e) } if e := os.WriteFile(filepath.Join(d.home, "auth.json"), []byte(`{"token":"fixture"}`), 0600); e != nil { t.Fatal(e) } d.state = "connected" l.Probe = func(context.Context, provider.Binding) (provider.Identity, error) { stop() return provider.Identity{}, context.Canceled } _, e := l.Poll(ctx) if !errors.Is(e, context.Canceled) || i.setup.State != "cancelled" || !d.cancelled { t.Fatal("probe interrupt not cancelled", e, i.setup) } if _, e = os.Stat(d.home); !os.IsNotExist(e) { t.Fatal("interrupted probe retained home") } } type transientInstance struct { *loginInstance fail bool } func (i *transientInstance) AccountSetup(ctx context.Context, id string) (runnerproto.AccountSetup, error) { if i.fail { return runnerproto.AccountSetup{}, runnerproto.ErrTransient } return i.loginInstance.AccountSetup(ctx, id) } func TestFinalFixAccountTransientPoll(t *testing.T) { l, d, base := loginHarness(t, "codex") i := &transientInstance{loginInstance: base} l.Instance = i if _, err := l.Begin(context.Background(), base.setup.ID); err != nil { t.Fatal(err) } i.fail = true if _, err := l.Poll(context.Background()); !errors.Is(err, runnerproto.ErrTransient) { t.Fatal("transient error lost", err) } if d.cancelled || l.active == nil { t.Fatal("network error cancelled in-progress login") } if _, err := os.Stat(d.home); err != nil { t.Fatal("network error deleted login home", err) } i.fail = false out, err := l.Poll(context.Background()) if err != nil || out.State != "pending" { t.Fatal("login could not continue", out, err) } if err = l.Cancel(context.Background()); err != nil { t.Fatal(err) } } type commandRetryInstance struct { *loginInstance calls []time.Time stop context.CancelFunc driver *loginFixture } func (i *commandRetryInstance) AccountSetup(ctx context.Context, id string) (runnerproto.AccountSetup, error) { i.calls = append(i.calls, time.Now()) if len(i.calls) == 2 { return runnerproto.AccountSetup{}, runnerproto.ErrTransient } if len(i.calls) == 3 { i.stop() } return i.loginInstance.AccountSetup(ctx, id) } func TestFinalFixAccountPollBackoff(t *testing.T) { l, d, base := loginHarness(t, "claude") ctx, stop := context.WithTimeout(context.Background(), 6*time.Second) defer stop() i := &commandRetryInstance{loginInstance: base, stop: stop, driver: d} l.Instance = i _ = RunAccountLogin(ctx, l, base.setup.ID) if len(i.calls) < 3 { t.Fatal("transient poll was not retried", len(i.calls)) } if i.calls[1].Sub(i.calls[0]) < time.Second || i.calls[2].Sub(i.calls[1]) < 2*time.Second { t.Fatal("poll interval or backoff too short", i.calls) } } func TestFinalFixAccountTransientExpiry(t *testing.T) { l, d, base := loginHarness(t, "codex") i := &transientInstance{loginInstance: base} l.Instance = i if _, err := l.Begin(context.Background(), base.setup.ID); err != nil { t.Fatal(err) } l.active.challenge.ExpiresAt = time.Now().Add(-time.Second) i.fail = true _, err := l.Poll(context.Background()) if err == nil || !d.cancelled || l.active != nil { t.Fatal("expired offline login left provider running", err, d.cancelled) } } func TestFinalFixAccountBackoffBound(t *testing.T) { synctest.Test(t, func(t *testing.T) { l, d, base := loginHarness(t, "codex") i := &commandRetryInstance{loginInstance: base, driver: d} l.Instance = &offlineAfterBegin{instance: i} err := RunAccountLogin(context.Background(), l, base.setup.ID) if !errors.Is(err, runnerproto.ErrTransient) || !d.cancelled { t.Fatal("expired offline login not stopped", err) } if len(i.calls) < 7 { t.Fatal("retry schedule not exercised", len(i.calls)) } for n := 1; n < len(i.calls); n++ { delta := i.calls[n].Sub(i.calls[n-1]) if delta < time.Second || delta > 30*time.Second { t.Fatal("unbounded backoff", delta) } } }) } type offlineAfterBegin struct{ instance *commandRetryInstance } func (i *offlineAfterBegin) AccountSetup(ctx context.Context, id string) (runnerproto.AccountSetup, error) { i.instance.calls = append(i.instance.calls, time.Now()) if len(i.instance.calls) > 1 { return runnerproto.AccountSetup{}, runnerproto.ErrTransient } return i.instance.loginInstance.AccountSetup(ctx, id) } func (i *offlineAfterBegin) ReportAccountSetup(ctx context.Context, q runnerproto.AccountSetupResult) (runnerproto.AccountSetup, error) { return i.instance.ReportAccountSetup(ctx, q) } func TestFinalFixAccountAuthorityAfterProbe(t *testing.T) { for _, mode := range []string{"revoked", "transient"} { t.Run(mode, func(t *testing.T) { l, d, base := loginHarness(t, "codex") i := &transientInstance{loginInstance: base} l.Instance = i if _, err := l.Begin(context.Background(), base.setup.ID); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(d.home, "auth.json"), []byte(`{"token":"fixture"}`), 0600); err != nil { t.Fatal(err) } d.state = "connected" probes, saves := 0, 0 l.Probe = func(context.Context, provider.Binding) (provider.Identity, error) { probes++ if mode == "revoked" { base.setup.State = "cancelled" } else { i.fail = true } return d.identity, nil } l.Save = func(context.Context, runnerproto.AccountSetup, provider.Binding) error { saves++; return nil } _, err := l.Poll(context.Background()) if err == nil || saves != 0 { t.Fatal("saved without current instance authority", err, saves) } if mode == "transient" { i.fail = false out, err := l.Poll(context.Background()) if err != nil || out.State != "connected" || probes != 1 || saves != 1 { t.Fatal("verified login could not resume", out, err, probes, saves) } } }) } }