| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo" |
| 5 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 6 | "crypto/rand" |
| 7 | "crypto/sha256" |
| 8 | "encoding/base64" |
| 9 | "encoding/hex" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "net/http/httptest" |
| 14 | "net/url" |
| 15 | "strings" |
| 16 | "testing" |
| 17 | "time" |
| 18 | ) |
| 19 | |
| 20 | func accountRunner(t *testing.T, f *fixture) { |
| 21 | t.Helper() |
| 22 | var instance string |
| 23 | must(t, f.DB.Writer().QueryRow("SELECT id FROM teams").Scan(&instance)) |
| 24 | f.exec(t, "INSERT INTO runners(id,instance_id,person,label,revision,machine_key_hash) VALUES('account-runner',?,?,?,1,'machine')", instance, owner.Address, "Desk") |
| 25 | f.exec(t, "INSERT INTO runner_enrolments(id,runner_id,person,consumed_at) VALUES('account-enrol','account-runner',?,?)", owner.Address, time.Now()) |
| 26 | } |
| 27 | func TestOnboardingClaudeHeadlessBrowserLogin(t *testing.T) { |
| 28 | f := newFixture(t) |
| 29 | accountRunner(t, f) |
| 30 | m := equipo.Mutation{RequestID: "setup"} |
| 31 | s, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "claude", "Personal", m) |
| 32 | must(t, e) |
| 33 | if s.ID == "" || s.State != "pending" || s.Mode != "browser" || s.Challenge != nil { |
| 34 | t.Fatal("unsafe pending projection", s) |
| 35 | } |
| 36 | again, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "claude", "Personal", m) |
| 37 | must(t, e) |
| 38 | if again.ID != s.ID { |
| 39 | t.Fatal("request duplicated") |
| 40 | } |
| 41 | w := f.get(t, owner, "/onboarding") |
| 42 | expectHTTP(t, w, 200) |
| 43 | if !strings.Contains(w.Body.String(), "equipo-runner account login --setup "+s.ID) { |
| 44 | t.Fatal("pending setup command missing") |
| 45 | } |
| 46 | _, e = f.Store.AccountSetup(ctx, peer, s.ID) |
| 47 | if !errors.Is(e, equipo.ErrNotFound) { |
| 48 | t.Fatal("private setup exposed", e) |
| 49 | } |
| 50 | _, e = f.Store.AccountSetup(ctx, owner, "missing") |
| 51 | if !errors.Is(e, equipo.ErrNotFound) { |
| 52 | t.Fatal("missing setup accepted", e) |
| 53 | } |
| 54 | must(t, f.Store.CancelAccountSetup(ctx, owner, s.ID, equipo.Mutation{RequestID: "cancel", Revision: s.Revision})) |
| 55 | s, e = f.Store.AccountSetup(ctx, owner, s.ID) |
| 56 | must(t, e) |
| 57 | if s.State != "cancelled" { |
| 58 | t.Fatal("cancel not persisted") |
| 59 | } |
| 60 | f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| 61 | _, e = f.Store.RequestAccountSetup(ctx, owner, "account-runner", "claude", "Personal", m) |
| 62 | if !errors.Is(e, equipo.ErrForbidden) { |
| 63 | t.Fatal("removed member replay", e) |
| 64 | } |
| 65 | } |
| 66 | func TestOnboardingAccountLifecycle(t *testing.T) { |
| 67 | f := newFixture(t) |
| 68 | accountRunner(t, f) |
| 69 | s, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "codex", "One", equipo.Mutation{RequestID: "one"}) |
| 70 | must(t, e) |
| 71 | other, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "codex", "Two", equipo.Mutation{RequestID: "two"}) |
| 72 | must(t, e) |
| 73 | if s.ID == other.ID { |
| 74 | t.Fatal("account replaced") |
| 75 | } |
| 76 | f.exec(t, "UPDATE account_setups SET expires_at=? WHERE id=?", time.Now().Add(-time.Second), s.ID) |
| 77 | s, e = f.Store.AccountSetup(ctx, owner, s.ID) |
| 78 | must(t, e) |
| 79 | if s.State != "expired" { |
| 80 | t.Fatal("expired setup pending") |
| 81 | } |
| 82 | f.exec(t, "UPDATE runners SET revision=revision+1 WHERE id='account-runner'") |
| 83 | s, e = f.Store.AccountSetup(ctx, owner, other.ID) |
| 84 | must(t, e) |
| 85 | if s.State != "unavailable" { |
| 86 | t.Fatal("stale generation pending") |
| 87 | } |
| 88 | _ = runnerproto.AccountSetupResult{ID: s.ID} |
| 89 | } |
| 90 | func TestOnboardingSafeFirstTask(t *testing.T) { |
| 91 | f := newFixture(t) |
| 92 | task := f.createTask(t) |
| 93 | p, e := f.Store.StartOnboardingTask(ctx, owner, task.ProjectID, equipo.Mutation{RequestID: "safe"}) |
| 94 | must(t, e) |
| 95 | if string(p.Kind) != "recommendation" || len(p.Steps) != 2 || p.Steps[0].Action != "recommend" { |
| 96 | t.Fatal("unsafe first task", p) |
| 97 | } |
| 98 | for _, step := range p.Steps { |
| 99 | if step.Action == "implement" || step.Action == "publish" || step.Action == "review" { |
| 100 | t.Fatal("change path in first task") |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | } |
| 105 | func TestOnboardingSpecialists(t *testing.T) { |
| 106 | f := newFixture(t) |
| 107 | rows, e := f.Store.ListSpecialists(ctx, owner) |
| 108 | must(t, e) |
| 109 | if len(rows) != 5 { |
| 110 | t.Fatal("defaults missing", len(rows)) |
| 111 | } |
| 112 | for _, key := range []string{"engineering", "review"} { |
| 113 | row, e := f.Store.Specialist(ctx, owner, key) |
| 114 | must(t, e) |
| 115 | if !row.Required { |
| 116 | t.Fatal("required specialist optional") |
| 117 | } |
| 118 | if e = f.Store.DeleteSpecialist(ctx, owner, key, equipo.Mutation{RequestID: key, Revision: row.Revision}); !errors.Is(e, equipo.ErrForbidden) { |
| 119 | t.Fatal("required specialist deleted", e) |
| 120 | } |
| 121 | } |
| 122 | s, e := f.Store.InstallSpecialistTemplate(ctx, owner, equipo.TemplateRef{ID: "qa", Version: 1}, equipo.Mutation{RequestID: "install"}) |
| 123 | must(t, e) |
| 124 | if s.TemplateID != "qa" || s.Creator != owner.Address { |
| 125 | t.Fatal("library copy missing") |
| 126 | } |
| 127 | w := f.get(t, owner, "/onboarding") |
| 128 | expectHTTP(t, w, 200) |
| 129 | if strings.Contains(w.Body.String(), ">"+equipo.RunnerText("onboarding.library")+"</a>") { |
| 130 | t.Fatal("library link outside specialists stage") |
| 131 | } |
| 132 | f.exec(t, `INSERT INTO onboarding_states(person,revision,completed) VALUES(?,1,'{"welcome":true,"account":true,"runner":true}')`, owner.Address) |
| 133 | w = f.get(t, owner, "/onboarding") |
| 134 | expectHTTP(t, w, 200) |
| 135 | _, list, ok := strings.Cut(w.Body.String(), "<ul data-onboarding-specialists>") |
| 136 | if !ok { |
| 137 | t.Fatal("specialist-stage choices missing") |
| 138 | } |
| 139 | list, _, _ = strings.Cut(list, "</ul>") |
| 140 | for _, key := range []string{"product", "design", "copy", "engineering", "review"} { |
| 141 | if !strings.Contains(list, "/specialists/"+key) { |
| 142 | t.Fatal("onboarding specialist missing", key) |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | func TestOnboardingAccountRunnerGuards(t *testing.T) { |
| 148 | f := newFixture(t) |
| 149 | accountRunner(t, f) |
| 150 | token := base64.RawURLEncoding.EncodeToString(make([]byte, 32)) |
| 151 | sum := sha256.Sum256([]byte(runnerproto.RunnerAudience + "\x00" + token)) |
| 152 | f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('account-cred','account-runner',?,?,?,'machine',?,?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, hex.EncodeToString(sum[:]), time.Now().Add(time.Hour)) |
| 153 | p, e := f.Store.AuthenticateRunner(ctx, token) |
| 154 | must(t, e) |
| 155 | makeSetup := func(name string) equipo.AccountSetup { |
| 156 | t.Helper() |
| 157 | s, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", name, name, equipo.Mutation{RequestID: rand.Text()}) |
| 158 | must(t, e) |
| 159 | return s |
| 160 | } |
| 161 | s := makeSetup("claude") |
| 162 | for _, wrong := range []equipo.RunnerPrincipal{{RunnerID: "other", Person: p.Person, CredentialID: p.CredentialID}, {RunnerID: p.RunnerID, Person: peer.Address, CredentialID: p.CredentialID}, {RunnerID: p.RunnerID, Person: p.Person, CredentialID: "missing"}} { |
| 163 | if _, e = f.Store.RunnerAccountSetup(ctx, wrong, s.ID); e == nil { |
| 164 | t.Fatal("wrong runner accepted") |
| 165 | } |
| 166 | } |
| 167 | if _, e = f.Store.RunnerAccountSetup(ctx, p, "missing"); e == nil { |
| 168 | t.Fatal("missing setup accepted") |
| 169 | } |
| 170 | request := func(body string) *httptest.ResponseRecorder { |
| 171 | t.Helper() |
| 172 | r := httptest.NewRequest("POST", "/account-setups", strings.NewReader(body)) |
| 173 | r.Header.Set("Authorization", "Bearer "+token) |
| 174 | r.Header.Set("Content-Type", "application/json") |
| 175 | w := httptest.NewRecorder() |
| 176 | f.Store.RunnerHandler().ServeHTTP(w, r) |
| 177 | return w |
| 178 | } |
| 179 | for _, field := range []string{"credential_home", "return_code", "challenge_id"} { |
| 180 | body := fmt.Sprintf(`{"version":2,"id":%q,"result":{"id":%q,"revision":1,"state":"pending",%q:"SECRET-MUST-NOT-ESCAPE"}}`, s.ID, s.ID, field) |
| 181 | w := request(body) |
| 182 | expectHTTP(t, w, 422) |
| 183 | if strings.Contains(w.Body.String(), "SECRET-MUST-NOT-ESCAPE") { |
| 184 | t.Fatal("secret reflected") |
| 185 | } |
| 186 | } |
| 187 | display := &runnerproto.LoginDisplay{VerificationURI: "https://auth.openai.com/codex/device", UserCode: "ABCD-EFGH", ExpiresAt: time.Now().Add(time.Minute)} |
| 188 | if _, e = f.Store.ReportAccountSetup(ctx, p, runnerproto.AccountSetupResult{ID: s.ID, Revision: 1, State: "pending", Challenge: display}); !errors.Is(e, equipo.ErrInvalid) { |
| 189 | t.Fatal("browser challenge stored", e) |
| 190 | } |
| 191 | s = makeSetup("codex") |
| 192 | q := runnerproto.AccountSetupResult{ID: s.ID, Revision: 1, State: "pending", Challenge: display} |
| 193 | for _, uri := range []string{"https://attacker.test/code", "https://auth.openai.com/codex/device?secret=hidden", "http://auth.openai.com/codex/device"} { |
| 194 | bad := *display |
| 195 | bad.VerificationURI = uri |
| 196 | q.Challenge = &bad |
| 197 | if _, e = f.Store.ReportAccountSetup(ctx, p, q); !errors.Is(e, equipo.ErrInvalid) { |
| 198 | t.Fatal("unsafe device link accepted", e) |
| 199 | } |
| 200 | } |
| 201 | q.Challenge = nil |
| 202 | s, e = f.Store.ReportAccountSetup(ctx, p, q) |
| 203 | must(t, e) |
| 204 | if s.Challenge != nil { |
| 205 | t.Fatal("terminal sign-in exposed display") |
| 206 | } |
| 207 | q = runnerproto.AccountSetupResult{ID: s.ID, Revision: s.Revision, State: "connected", AccountID: "observed-account", ProviderVersion: "0.165.0"} |
| 208 | f.exec(t, "CREATE TRIGGER setup_audit_failure BEFORE INSERT ON audit_events WHEN NEW.kind='account_setup.connected' BEGIN SELECT RAISE(ABORT,'fixture'); END") |
| 209 | if _, e = f.Store.ReportAccountSetup(ctx, p, q); e == nil { |
| 210 | t.Fatal("audit failure ignored") |
| 211 | } |
| 212 | if f.count(t, "SELECT count(*) FROM connections WHERE local_id=?", s.ID) != 0 { |
| 213 | t.Fatal("connection escaped rollback") |
| 214 | } |
| 215 | f.exec(t, "DROP TRIGGER setup_audit_failure") |
| 216 | s, e = f.Store.ReportAccountSetup(ctx, p, q) |
| 217 | must(t, e) |
| 218 | again, e := f.Store.ReportAccountSetup(ctx, p, q) |
| 219 | must(t, e) |
| 220 | if again.Revision != s.Revision || again.ConnectionID != s.ConnectionID { |
| 221 | t.Fatal("lost result duplicated connection") |
| 222 | } |
| 223 | if s.State != "connected" || s.ConnectionID == "" || s.Challenge != nil { |
| 224 | t.Fatal("connection result", s) |
| 225 | } |
| 226 | var reports string |
| 227 | must(t, f.DB.Writer().QueryRow("SELECT reports_json FROM connections WHERE id=?", s.ConnectionID).Scan(&reports)) |
| 228 | var rows []runnerproto.ConnectionReport |
| 229 | must(t, json.Unmarshal([]byte(reports), &rows)) |
| 230 | if len(rows) != 1 || rows[0].Available || rows[0].AllowanceKnown || rows[0].AccountLabel != "codex" { |
| 231 | t.Fatal("sign-in fabricated availability or allowance", reports) |
| 232 | } |
| 233 | for _, state := range []string{"expired", "cancelled", "revision", "roster", "role"} { |
| 234 | t.Run(state, func(t *testing.T) { |
| 235 | s := makeSetup("claude") |
| 236 | switch state { |
| 237 | case "expired": |
| 238 | f.exec(t, "UPDATE account_setups SET expires_at=? WHERE id=?", time.Now().Add(-time.Second), s.ID) |
| 239 | case "cancelled": |
| 240 | must(t, f.Store.CancelAccountSetup(ctx, owner, s.ID, equipo.Mutation{RequestID: "cancel", Revision: s.Revision})) |
| 241 | case "revision": |
| 242 | f.exec(t, "UPDATE runners SET revision=revision+1 WHERE id=?", p.RunnerID) |
| 243 | case "roster": |
| 244 | f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| 245 | case "role": |
| 246 | f.exec(t, "UPDATE members SET role='member',revision=revision+1 WHERE address=?", owner.Address) |
| 247 | } |
| 248 | if _, e = f.Store.RunnerAccountSetup(ctx, p, s.ID); e == nil { |
| 249 | t.Fatal("invalid setup exposed") |
| 250 | } |
| 251 | if _, e = f.Store.ReportAccountSetup(ctx, p, runnerproto.AccountSetupResult{ID: s.ID, Revision: s.Revision, State: "connected", AccountID: "observed", ProviderVersion: "2.1.312"}); e == nil { |
| 252 | t.Fatal("invalid setup accepted result") |
| 253 | } |
| 254 | f.exec(t, "UPDATE members SET active=1,role='owner' WHERE address=?", owner.Address) |
| 255 | }) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | func TestOnboardingAccountForms(t *testing.T) { |
| 260 | f := newFixture(t) |
| 261 | accountRunner(t, f) |
| 262 | values := url.Values{"runner_id": {"account-runner"}, "provider": {"claude"}, "label": {"Personal"}, "request_id": {"form"}} |
| 263 | w := inviteRequest(t, f, owner, "POST", "/onboarding/accounts", values, nil) |
| 264 | expectHTTP(t, w, 303) |
| 265 | values.Set("return_code", "SECRET-MUST-NOT-ESCAPE") |
| 266 | w = inviteRequest(t, f, owner, "POST", "/onboarding/accounts", values, nil) |
| 267 | expectHTTP(t, w, 422) |
| 268 | values.Del("return_code") |
| 269 | values.Set("request_id", "csrf") |
| 270 | expectHTTP(t, inviteRequest(t, f, owner, "POST", "/onboarding/accounts", values, nil, "https://foreign.test"), 403) |
| 271 | body := f.get(t, owner, "/onboarding").Body.String() |
| 272 | if strings.Contains(body, "return_code") || strings.Contains(body, "SECRET-MUST-NOT-ESCAPE") { |
| 273 | t.Fatal("browser collected provider code") |
| 274 | } |
| 275 | var audits string |
| 276 | must(t, f.DB.Writer().QueryRow("SELECT group_concat(record_id) FROM audit_events").Scan(&audits)) |
| 277 | if strings.Contains(audits, "SECRET-MUST-NOT-ESCAPE") { |
| 278 | t.Fatal("secret audited") |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | func TestOnboardingSafeFirstTaskHTTP(t *testing.T) { |
| 283 | f := newFixture(t) |
| 284 | task := f.createTask(t) |
| 285 | values := url.Values{"project_id": {fmt.Sprint(task.ProjectID)}, "request_id": {"first-http"}} |
| 286 | w := inviteRequest(t, f, owner, "POST", "/onboarding/first-task", values, nil) |
| 287 | expectHTTP(t, w, 303) |
| 288 | if !strings.HasPrefix(w.Header().Get("Location"), "/tasks/") { |
| 289 | t.Fatal("missing first task redirect") |
| 290 | } |
| 291 | p, e := f.Store.TaskPlan(ctx, owner, strings.TrimPrefix(w.Header().Get("Location"), "/tasks/")) |
| 292 | must(t, e) |
| 293 | if p.Kind != "recommendation" || len(p.Steps) != 2 || p.Steps[0].Action != "recommend" || p.Steps[1].Action != "person" { |
| 294 | t.Fatal("HTTP first task gained changes", p) |
| 295 | } |
| 296 | again := inviteRequest(t, f, owner, "POST", "/onboarding/first-task", values, nil) |
| 297 | expectHTTP(t, again, 303) |
| 298 | if again.Header().Get("Location") != w.Header().Get("Location") { |
| 299 | t.Fatal("HTTP first task duplicated") |
| 300 | } |
| 301 | |
| 302 | values.Set("instructions", "publish changes") |
| 303 | expectHTTP(t, inviteRequest(t, f, owner, "POST", "/onboarding/first-task", values, nil), 422) |
| 304 | values.Del("instructions") |
| 305 | expectHTTP(t, inviteRequest(t, f, owner, "POST", "/onboarding/first-task", values, nil, "https://foreign.test"), 403) |
| 306 | } |
| 307 | |
| 308 | func TestOnboardingAccountCancelHTTP(t *testing.T) { |
| 309 | f := newFixture(t) |
| 310 | accountRunner(t, f) |
| 311 | s, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "codex", "Personal", equipo.Mutation{RequestID: "cancel-http"}) |
| 312 | must(t, e) |
| 313 | values := url.Values{"id": {s.ID}, "revision": {fmt.Sprint(s.Revision)}, "request_id": {"cancel-post"}} |
| 314 | expectHTTP(t, inviteRequest(t, f, owner, "POST", "/onboarding/accounts/cancel", values, nil, "https://foreign.test"), 403) |
| 315 | expectHTTP(t, inviteRequest(t, f, owner, "POST", "/onboarding/accounts/cancel", values, nil), 303) |
| 316 | s, e = f.Store.AccountSetup(ctx, owner, s.ID) |
| 317 | must(t, e) |
| 318 | if s.State != "cancelled" { |
| 319 | t.Fatal("HTTP cancellation was not persisted") |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | func TestOnboardingAccountInstructions(t *testing.T) { |
| 324 | f := newFixture(t) |
| 325 | accountRunner(t, f) |
| 326 | s, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "codex", "Personal", equipo.Mutation{RequestID: "instructions"}) |
| 327 | must(t, e) |
| 328 | body := f.get(t, owner, "/onboarding").Body.String() |
| 329 | if !strings.Contains(body, equipo.RunnerText("account_setup.device")) || strings.Contains(body, equipo.RunnerText("account_setup.browser")) { |
| 330 | t.Fatal("wrong provider instructions") |
| 331 | } |
| 332 | f.exec(t, "UPDATE account_setups SET state='unavailable' WHERE id=?", s.ID) |
| 333 | body = f.get(t, owner, "/onboarding").Body.String() |
| 334 | warning, form := strings.Index(body, "data-login-unavailable"), strings.Index(body, `action="/onboarding/accounts"`) |
| 335 | if warning < 0 || warning > form || strings.Contains(body, "equipo-runner account login --setup "+s.ID) { |
| 336 | t.Fatal("known unavailable login offered as pending") |
| 337 | } |
| 338 | } |
| 339 | |