package main import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type accountTransport func(*http.Request) (*http.Response, error) func (f accountTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } func TestOnboardingClaudeHeadlessBrowserLogin(t *testing.T) { for _, supported := range []bool{false, true} { t.Run(fmt.Sprint(supported), func(t *testing.T) { testAccountCommand(t, supported) }) } } func testAccountCommand(t *testing.T, supported bool) { root := t.TempDir() fake := filepath.Join(root, "fake") script := "#!/bin/sh\nexit 99\n" if supported { script = `#!/bin/sh set -eu umask 077 case "$*" in '--version') echo '2.1.312 (Claude Code)' ;; 'auth login --help') exit 0 ;; 'auth login') test "$HOME" = "$CLAUDE_CONFIG_DIR" test "$HOME" = "$CLAUDE_SECURESTORAGE_CONFIG_DIR" IFS= read -r code test "$code" = TERMINAL-RETURN-SECRET printf '%s' '{"token":"NATIVE-SECRET"}' > "$HOME/.credentials.json" ;; 'auth status --json') printf '%s' '{"loggedIn":true,"authMethod":"claude.ai","email":"person@example.test"}' ;; *) exit 3 ;; esac ` } if e := os.WriteFile(fake, []byte(script), 0700); e != nil { t.Fatal(e) } state := filepath.Join(root, "state") if e := os.Mkdir(state, 0700); e != nil { t.Fatal(e) } cred := runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "fixture-bearer", RunnerID: "runner", Person: "person", ExpiresAt: time.Now().Add(time.Hour)}} raw, _ := json.Marshal(cred) if e := os.WriteFile(filepath.Join(state, "credentials.json"), raw, 0600); e != nil { t.Fatal(e) } values := map[string]string{"HOME": root, "EQUIPO_ORIGIN": "https://fixture.test", "EQUIPO_INSTANCE_ID": "team", "EQUIPO_RUNNER_STATE_DIR": state, "EQUIPO_WORKSPACE_ROOT": filepath.Join(root, "work"), "EQUIPO_SCRATCH_ROOT": filepath.Join(root, "scratch")} for _, key := range []string{"EQUIPO_CLAUDE_PATH", "EQUIPO_CODEX_PATH", "EQUIPO_AMADAN_PATH", "EQUIPO_BWRAP_PATH", "EQUIPO_CODEX_CODE_MODE_HOST_PATH", "EQUIPO_ACCOUNT_BINDINGS_PATH", "EQUIPO_AMADAN_CREDENTIAL_PATH", "EQUIPO_GO_ROOT", "EQUIPO_GO_BINARY", "EQUIPO_GIT_PATH"} { values[key] = fake } values["EQUIPO_CLAUDE_MODEL"] = "fixture-model" values["EQUIPO_ACCOUNT_BINDINGS_PATH"] = filepath.Join(state, "accounts.json") prior := http.DefaultTransport t.Cleanup(func() { http.DefaultTransport = prior }) calls := 0 lostReport := false setup := runnerproto.AccountSetup{ID: "pending-setup", RunnerID: "runner", Provider: "claude", State: "pending", Mode: "browser", Revision: 1} http.DefaultTransport = accountTransport(func(r *http.Request) (*http.Response, error) { calls++ if r.URL.Path != "/api/runner/v2/account-setups" || r.Header.Get("Authorization") != "Bearer fixture-bearer" { t.Fatal("wrong authenticated channel", r.URL) } var q runnerproto.AccountSetupRequest rawRequest, e := io.ReadAll(r.Body) if e != nil || bytes.Contains(rawRequest, []byte("SECRET")) || bytes.Contains(rawRequest, []byte(root)) { t.Fatal("terminal data entered request") } if e := runnerproto.Decode(bytes.NewReader(rawRequest), &q); e != nil { t.Fatal(e) } if q.ID != "pending-setup" { t.Fatal("wrong setup ID") } if q.Result != nil { if q.Result.Challenge != nil { t.Fatal("display left terminal") } if q.Result.State == "connected" && (q.Result.AccountID != "person@example.test" || q.Result.ProviderVersion != "2.1.312") { t.Fatal("missing verified identity") } setup.State = q.Result.State setup.Revision++ if supported && q.Result.State == "connected" && !lostReport { lostReport = true return nil, errors.New("fixture dropped successful report response") } } raw, _ := runnerproto.Marshal(runnerproto.WorkResponse{Version: 2, Result: setup}) return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(raw)), Header: make(http.Header)}, nil }) journal, e := runner.OpenJournal(context.Background(), filepath.Join(state, "journal.db")) if e != nil { t.Fatal(e) } t.Cleanup(func() { _ = journal.Close() }) var out, logs bytes.Buffer code := run(context.Background(), []string{"account", "login", "--setup", "pending-setup"}, strings.NewReader("TERMINAL-RETURN-SECRET\n"), &out, &logs, func(k string) string { return values[k] }) wantCode, wantState := 1, "unavailable" if supported { wantCode, wantState = 0, "connected" } if code != wantCode || calls < 3 || setup.State != wantState || strings.Contains(logs.String(), "SECRET") || strings.Contains(logs.String(), "fixture-bearer") || strings.Contains(logs.String(), root) { t.Fatal("unsafe terminal command", code, calls, logs.String()) } if _, e := os.Stat(filepath.Join(state, "accounts")); !supported && !os.IsNotExist(e) { t.Fatal("unavailable flow allocated a credential home") } if supported { if !lostReport { t.Fatal("lost report not exercised") } raw, e := os.ReadFile(values["EQUIPO_ACCOUNT_BINDINGS_PATH"]) if e != nil || !bytes.Contains(raw, []byte("person@example.test")) || bytes.Contains(raw, []byte("SECRET")) { t.Fatal("binding was not saved safely", e) } // This command has no journal: terminal streams never enter captures/events. paths, e := filepath.Glob(filepath.Join(state, "*.jsonl")) if e != nil || len(paths) != 0 { t.Fatal("login created journal events") } } events, e := journal.Pending(context.Background(), 10) if e != nil || len(events) != 0 { t.Fatal("login leaked journal events", e) } rawJournal, e := os.ReadFile(filepath.Join(state, "journal.db")) if e != nil || bytes.Contains(rawJournal, []byte("SECRET")) { t.Fatal("login secret entered journal", e) } calls = 0 for _, args := range [][]string{{"account", "login"}, {"account", "login", "--setup", "id", "--code", "SECRET"}, {"account", "login", "--setup", ""}} { if run(context.Background(), args, strings.NewReader(""), &out, &logs, func(k string) string { return values[k] }) != 1 { t.Fatal("invalid login argv accepted") } } if calls != 0 { t.Fatal("invalid argv reached instance") } } func TestOnboardingAccountEnvironment(t *testing.T) { root := t.TempDir() dir := filepath.Join(root, ".local/share/equipo-runner") if e := os.MkdirAll(dir, 0700); e != nil { t.Fatal(e) } path := filepath.Join(dir, "runner.env") data := "EQUIPO_ORIGIN=\"https://fixture.test\"\nEQUIPO_INSTANCE_ID=\"fixture\"\n" if e := os.WriteFile(path, []byte(data), 0600); e != nil { t.Fatal(e) } getenv := func(k string) string { if k == "HOME" { return root } return "" } env, e := accountEnvironment(getenv) if e != nil || env("EQUIPO_ORIGIN") != "https://fixture.test" { t.Fatal("installed configuration not read", e) } if e = os.Chmod(path, 0644); e != nil { t.Fatal(e) } if _, e = accountEnvironment(getenv); e == nil { t.Fatal("shared configuration accepted") } if e = os.Chmod(path, 0600); e != nil { t.Fatal(e) } if e = os.WriteFile(path, []byte(data+"EQUIPO_INSTANCE_ID=\"changed\"\n"), 0600); e != nil { t.Fatal(e) } if _, e = accountEnvironment(getenv); e == nil { t.Fatal("duplicate environment accepted") } } func TestOnboardingAccountFailureMessages(t *testing.T) { cases := map[error]string{context.Canceled: "account_setup.cancelled", runner.ErrTransient: "account_setup.network", provider.ErrIdentity: "account_setup.identity_failed", provider.ErrLoginUnavailable: "account_setup.unavailable", provider.ErrUncertain: "account_setup.interrupted", provider.ErrAccountMaintenance: "account_setup.save_failed", provider.ErrContract: "account_setup.config"} for err, want := range cases { if got := accountLoginFailure(err); got != want { t.Fatal("failure kind hidden", err, got) } } } func TestOnboardingAccountCustomEnvironment(t *testing.T) { root := t.TempDir() if e := os.WriteFile(filepath.Join(root, "runner.env"), []byte("EQUIPO_ORIGIN=https://fixture.test\nEQUIPO_INSTANCE_ID=fixture\n"), 0600); e != nil { t.Fatal(e) } values := map[string]string{"HOME": t.TempDir(), "EQUIPO_RUNNER_ROOT": root} env, e := accountEnvironment(func(k string) string { return values[k] }) if e != nil || env("EQUIPO_INSTANCE_ID") != "fixture" { t.Fatal("custom root or unquoted environment rejected", e) } }