oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "os"
12 "path/filepath"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/runner"
18 "amadan.net/oficina/equipo/internal/runner/provider"
19 "amadan.net/oficina/equipo/internal/runnerproto"
20)
21
22type accountTransport func(*http.Request) (*http.Response, error)
23
24func (f accountTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
25func TestOnboardingClaudeHeadlessBrowserLogin(t *testing.T) {
26 for _, supported := range []bool{false, true} {
27 t.Run(fmt.Sprint(supported), func(t *testing.T) { testAccountCommand(t, supported) })
28 }
29}
30func testAccountCommand(t *testing.T, supported bool) {
31 root := t.TempDir()
32 fake := filepath.Join(root, "fake")
33 script := "#!/bin/sh\nexit 99\n"
34 if supported {
35 script = `#!/bin/sh
36set -eu
37umask 077
38case "$*" in
39 '--version') echo '2.1.312 (Claude Code)' ;;
40 'auth login --help') exit 0 ;;
41 'auth login')
42 test "$HOME" = "$CLAUDE_CONFIG_DIR"
43 test "$HOME" = "$CLAUDE_SECURESTORAGE_CONFIG_DIR"
44 IFS= read -r code
45 test "$code" = TERMINAL-RETURN-SECRET
46 printf '%s' '{"token":"NATIVE-SECRET"}' > "$HOME/.credentials.json" ;;
47 'auth status --json') printf '%s' '{"loggedIn":true,"authMethod":"claude.ai","email":"person@example.test"}' ;;
48 *) exit 3 ;;
49esac
50`
51 }
52 if e := os.WriteFile(fake, []byte(script), 0700); e != nil {
53 t.Fatal(e)
54 }
55 state := filepath.Join(root, "state")
56 if e := os.Mkdir(state, 0700); e != nil {
57 t.Fatal(e)
58 }
59 cred := runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "fixture-bearer", RunnerID: "runner", Person: "person", ExpiresAt: time.Now().Add(time.Hour)}}
60 raw, _ := json.Marshal(cred)
61 if e := os.WriteFile(filepath.Join(state, "credentials.json"), raw, 0600); e != nil {
62 t.Fatal(e)
63 }
64 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")}
65 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"} {
66 values[key] = fake
67 }
68 values["EQUIPO_CLAUDE_MODEL"] = "fixture-model"
69 values["EQUIPO_ACCOUNT_BINDINGS_PATH"] = filepath.Join(state, "accounts.json")
70 prior := http.DefaultTransport
71 t.Cleanup(func() { http.DefaultTransport = prior })
72 calls := 0
73 lostReport := false
74 setup := runnerproto.AccountSetup{ID: "pending-setup", RunnerID: "runner", Provider: "claude", State: "pending", Mode: "browser", Revision: 1}
75 http.DefaultTransport = accountTransport(func(r *http.Request) (*http.Response, error) {
76 calls++
77 if r.URL.Path != "/api/runner/v2/account-setups" || r.Header.Get("Authorization") != "Bearer fixture-bearer" {
78 t.Fatal("wrong authenticated channel", r.URL)
79 }
80 var q runnerproto.AccountSetupRequest
81 rawRequest, e := io.ReadAll(r.Body)
82 if e != nil || bytes.Contains(rawRequest, []byte("SECRET")) || bytes.Contains(rawRequest, []byte(root)) {
83 t.Fatal("terminal data entered request")
84 }
85 if e := runnerproto.Decode(bytes.NewReader(rawRequest), &q); e != nil {
86 t.Fatal(e)
87 }
88 if q.ID != "pending-setup" {
89 t.Fatal("wrong setup ID")
90 }
91 if q.Result != nil {
92 if q.Result.Challenge != nil {
93 t.Fatal("display left terminal")
94 }
95 if q.Result.State == "connected" && (q.Result.AccountID != "person@example.test" || q.Result.ProviderVersion != "2.1.312") {
96 t.Fatal("missing verified identity")
97 }
98 setup.State = q.Result.State
99 setup.Revision++
100 if supported && q.Result.State == "connected" && !lostReport {
101 lostReport = true
102 return nil, errors.New("fixture dropped successful report response")
103 }
104 }
105 raw, _ := runnerproto.Marshal(runnerproto.WorkResponse{Version: 2, Result: setup})
106 return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(raw)), Header: make(http.Header)}, nil
107 })
108 journal, e := runner.OpenJournal(context.Background(), filepath.Join(state, "journal.db"))
109 if e != nil {
110 t.Fatal(e)
111 }
112 t.Cleanup(func() { _ = journal.Close() })
113 var out, logs bytes.Buffer
114 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] })
115 wantCode, wantState := 1, "unavailable"
116 if supported {
117 wantCode, wantState = 0, "connected"
118 }
119 if code != wantCode || calls < 3 || setup.State != wantState || strings.Contains(logs.String(), "SECRET") || strings.Contains(logs.String(), "fixture-bearer") || strings.Contains(logs.String(), root) {
120 t.Fatal("unsafe terminal command", code, calls, logs.String())
121 }
122 if _, e := os.Stat(filepath.Join(state, "accounts")); !supported && !os.IsNotExist(e) {
123 t.Fatal("unavailable flow allocated a credential home")
124 }
125 if supported {
126 if !lostReport {
127 t.Fatal("lost report not exercised")
128 }
129 raw, e := os.ReadFile(values["EQUIPO_ACCOUNT_BINDINGS_PATH"])
130 if e != nil || !bytes.Contains(raw, []byte("person@example.test")) || bytes.Contains(raw, []byte("SECRET")) {
131 t.Fatal("binding was not saved safely", e)
132 }
133 // This command has no journal: terminal streams never enter captures/events.
134 paths, e := filepath.Glob(filepath.Join(state, "*.jsonl"))
135 if e != nil || len(paths) != 0 {
136 t.Fatal("login created journal events")
137 }
138 }
139 events, e := journal.Pending(context.Background(), 10)
140 if e != nil || len(events) != 0 {
141 t.Fatal("login leaked journal events", e)
142 }
143 rawJournal, e := os.ReadFile(filepath.Join(state, "journal.db"))
144 if e != nil || bytes.Contains(rawJournal, []byte("SECRET")) {
145 t.Fatal("login secret entered journal", e)
146 }
147 calls = 0
148 for _, args := range [][]string{{"account", "login"}, {"account", "login", "--setup", "id", "--code", "SECRET"}, {"account", "login", "--setup", ""}} {
149 if run(context.Background(), args, strings.NewReader(""), &out, &logs, func(k string) string { return values[k] }) != 1 {
150 t.Fatal("invalid login argv accepted")
151 }
152 }
153 if calls != 0 {
154 t.Fatal("invalid argv reached instance")
155 }
156}
157
158func TestOnboardingAccountEnvironment(t *testing.T) {
159 root := t.TempDir()
160 dir := filepath.Join(root, ".local/share/equipo-runner")
161 if e := os.MkdirAll(dir, 0700); e != nil {
162 t.Fatal(e)
163 }
164 path := filepath.Join(dir, "runner.env")
165 data := "EQUIPO_ORIGIN=\"https://fixture.test\"\nEQUIPO_INSTANCE_ID=\"fixture\"\n"
166 if e := os.WriteFile(path, []byte(data), 0600); e != nil {
167 t.Fatal(e)
168 }
169 getenv := func(k string) string {
170 if k == "HOME" {
171 return root
172 }
173 return ""
174 }
175 env, e := accountEnvironment(getenv)
176 if e != nil || env("EQUIPO_ORIGIN") != "https://fixture.test" {
177 t.Fatal("installed configuration not read", e)
178 }
179 if e = os.Chmod(path, 0644); e != nil {
180 t.Fatal(e)
181 }
182 if _, e = accountEnvironment(getenv); e == nil {
183 t.Fatal("shared configuration accepted")
184 }
185 if e = os.Chmod(path, 0600); e != nil {
186 t.Fatal(e)
187 }
188 if e = os.WriteFile(path, []byte(data+"EQUIPO_INSTANCE_ID=\"changed\"\n"), 0600); e != nil {
189 t.Fatal(e)
190 }
191 if _, e = accountEnvironment(getenv); e == nil {
192 t.Fatal("duplicate environment accepted")
193 }
194}
195
196func TestOnboardingAccountFailureMessages(t *testing.T) {
197 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"}
198 for err, want := range cases {
199 if got := accountLoginFailure(err); got != want {
200 t.Fatal("failure kind hidden", err, got)
201 }
202 }
203}
204
205func TestOnboardingAccountCustomEnvironment(t *testing.T) {
206 root := t.TempDir()
207 if e := os.WriteFile(filepath.Join(root, "runner.env"), []byte("EQUIPO_ORIGIN=https://fixture.test\nEQUIPO_INSTANCE_ID=fixture\n"), 0600); e != nil {
208 t.Fatal(e)
209 }
210 values := map[string]string{"HOME": t.TempDir(), "EQUIPO_RUNNER_ROOT": root}
211 env, e := accountEnvironment(func(k string) string { return values[k] })
212 if e != nil || env("EQUIPO_INSTANCE_ID") != "fixture" {
213 t.Fatal("custom root or unquoted environment rejected", e)
214 }
215}
216