| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net/http/httptest" |
| 6 | "net/url" |
| 7 | "sort" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/equipo" |
| 13 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 14 | "amadan.net/oficina/equipo/internal/taskplan" |
| 15 | ) |
| 16 | |
| 17 | func TestPersonAPICurrentRevision(t *testing.T) { |
| 18 | f, _, _, b := coordinatorFixture(t) |
| 19 | apiRouter(t, f, nil) |
| 20 | p := apiFixPlan(t, f) |
| 21 | pref, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "original", Status: "confirmed"}, equipo.Mutation{RequestID: "pref"}) |
| 22 | must(t, err) |
| 23 | p.Steps[0].Instructions = "updated" |
| 24 | p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "advance-plan", Revision: p.Revision}) |
| 25 | must(t, err) |
| 26 | pref.Text = "updated" |
| 27 | pref, err = f.Store.SetPreference(ctx, owner, pref, equipo.Mutation{RequestID: "advance-pref", Revision: pref.Revision}) |
| 28 | must(t, err) |
| 29 | b, err = f.Store.SaveCoordinatorBinding(ctx, owner, "fixture-runner", "codex", equipo.Mutation{RequestID: "advance-binding", Revision: b.Revision}) |
| 30 | must(t, err) |
| 31 | expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/me/settings", `{"landing":"work"}`, "advance-settings", `"1"`), 200) |
| 32 | cases := []struct { |
| 33 | name, path, body, rev string |
| 34 | want int64 |
| 35 | }{ |
| 36 | {"plan", "/tasks/" + p.TaskID + "/plan", jsonBody(t, personapi.ProjectPlan(p).PlanInput), `"99"`, p.Revision}, |
| 37 | {"preference", "/preferences/" + pref.ID, `{"text":"changed"}`, `"99"`, pref.Revision}, |
| 38 | {"binding", "/coordinator", `{"runner_id":"fixture-runner","connection_id":"codex"}`, `"99"`, b.Revision}, |
| 39 | {"settings", "/me/settings", `{"landing":"work"}`, `"99"`, 2}, |
| 40 | {"limits", "/coordinator/limits", `{"person":"owner@example.com","limits":{"calls":23,"input_tokens":200000,"output_tokens":40000,"seconds":10000}}`, `"99"`, 1}, |
| 41 | } |
| 42 | for _, tc := range cases { |
| 43 | t.Run(tc.name, func(t *testing.T) { |
| 44 | w := apiRequest(t, f, owner, "PATCH", "/api/v1"+tc.path, tc.body, tc.name, tc.rev) |
| 45 | expectHTTP(t, w, 409) |
| 46 | e := apiValue[personapi.Error](t, w) |
| 47 | if e.Code != "revision_conflict" || e.CurrentRevision == nil || *e.CurrentRevision != tc.want { |
| 48 | t.Fatalf("current revision: %+v; want %d", e, tc.want) |
| 49 | } |
| 50 | }) |
| 51 | } |
| 52 | expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/"+pref.ID, `{}`, "delete-pref", fmt.Sprintf(`"%d"`, pref.Revision)), 200) |
| 53 | conflict := apiRequest(t, f, owner, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"restore"}`, "stale-deleted", `"1"`) |
| 54 | expectHTTP(t, conflict, 409) |
| 55 | e := apiValue[personapi.Error](t, conflict) |
| 56 | if e.CurrentRevision == nil || *e.CurrentRevision != pref.Revision+1 { |
| 57 | t.Fatal("missing deleted preference revision", e) |
| 58 | } |
| 59 | expectHTTP(t, apiRequest(t, f, peer, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"foreign"}`, "foreign", `"1"`), 404) |
| 60 | |
| 61 | } |
| 62 | |
| 63 | func TestPersonAPIReplayBeforeStale(t *testing.T) { |
| 64 | for _, op := range []string{"plan", "route", "binding", "limits"} { |
| 65 | t.Run(op, func(t *testing.T) { |
| 66 | f, _, _, b := coordinatorFixture(t) |
| 67 | apiRouter(t, f, nil) |
| 68 | p := apiFixPlan(t, f) |
| 69 | method, path, body, changed, rev := "PATCH", "", "", "", `"1"` |
| 70 | switch op { |
| 71 | case "plan": |
| 72 | path = "/api/v1/tasks/" + p.TaskID + "/plan" |
| 73 | in := personapi.ProjectPlan(p).PlanInput |
| 74 | in.Steps[0].Instructions = "First edit" |
| 75 | body = jsonBody(t, in) |
| 76 | in.Steps[0].Instructions = "Different edit" |
| 77 | changed = jsonBody(t, in) |
| 78 | case "route": |
| 79 | msg, err := f.Store.SendMessage(ctx, owner, "", "route source", equipo.Mutation{RequestID: "source"}) |
| 80 | must(t, err) |
| 81 | method, path = "POST", "/api/v1/conversation/messages/"+msg.ID+"/route" |
| 82 | body = jsonBody(t, personapi.RouteInput{TaskID: p.TaskID}) |
| 83 | other := apiFixPlan(t, f) |
| 84 | changed = jsonBody(t, personapi.RouteInput{TaskID: other.TaskID}) |
| 85 | case "binding": |
| 86 | path = "/api/v1/coordinator" |
| 87 | body = `{"runner_id":"fixture-runner","connection_id":"codex"}` |
| 88 | changed = `{"runner_id":"fixture-runner","connection_id":"claude"}` |
| 89 | rev = fmt.Sprintf(`"%d"`, b.Revision) |
| 90 | case "limits": |
| 91 | path = "/api/v1/coordinator/limits" |
| 92 | body = `{"person":"owner@example.com","limits":{"calls":23,"input_tokens":200000,"output_tokens":40000,"seconds":10000}}` |
| 93 | changed = strings.Replace(body, `"calls":23`, `"calls":22`, 1) |
| 94 | } |
| 95 | first := apiRequest(t, f, owner, method, path, body, "retry", rev) |
| 96 | expectHTTP(t, first, 200) |
| 97 | if op == "route" { |
| 98 | f.exec(t, "UPDATE conversation_messages SET revision=revision+1 WHERE id=?", strings.Split(path, "/")[5]) |
| 99 | } |
| 100 | replay := apiRequest(t, f, owner, method, path, body, "retry", rev) |
| 101 | expectHTTP(t, replay, 200) |
| 102 | if first.Body.String() != replay.Body.String() { |
| 103 | t.Fatal("saved result changed") |
| 104 | } |
| 105 | expectHTTP(t, apiRequest(t, f, owner, method, path, changed, "retry", rev), 409) |
| 106 | expectHTTP(t, apiRequest(t, f, owner, method, path, body, "new-key", rev), 409) |
| 107 | f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| 108 | expectHTTP(t, apiRequest(t, f, owner, method, path, body, "retry", rev), 403) |
| 109 | }) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | func TestPersonAPIListReadsNoWrites(t *testing.T) { |
| 114 | f := newFixture(t) |
| 115 | p := proposed(t, f) |
| 116 | for i := 0; i < 3; i++ { |
| 117 | _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: fmt.Sprintf("private %d", i), Status: "confirmed"}, equipo.Mutation{RequestID: fmt.Sprint(i)}) |
| 118 | must(t, err) |
| 119 | _, err = f.Store.SendMessage(ctx, owner, "", "message", equipo.Mutation{RequestID: fmt.Sprintf("main-%d", i)}) |
| 120 | must(t, err) |
| 121 | _, err = f.Store.SendMessage(ctx, owner, p.TaskID, "thread", equipo.Mutation{RequestID: fmt.Sprintf("thread-%d", i)}) |
| 122 | must(t, err) |
| 123 | } |
| 124 | // Reject every attempted write, including lazy stream creation and cursor inserts. |
| 125 | rows, err := f.DB.Writer().Query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") |
| 126 | must(t, err) |
| 127 | var tables []string |
| 128 | for rows.Next() { |
| 129 | var table string |
| 130 | must(t, rows.Scan(&table)) |
| 131 | tables = append(tables, table) |
| 132 | } |
| 133 | must(t, rows.Close()) |
| 134 | for _, table := range tables { |
| 135 | for _, event := range []string{"INSERT", "UPDATE", "DELETE"} { |
| 136 | f.exec(t, fmt.Sprintf(`CREATE TRIGGER "deny_%s_%s" BEFORE %s ON "%s" BEGIN SELECT RAISE(ABORT,'read attempted write'); END`, table, event, event, table)) |
| 137 | } |
| 138 | } |
| 139 | for _, path := range []string{"people", "preferences", "conversation/cards", "tasks", "journey", "needs-you", "conversation", "tasks/" + p.TaskID + "/thread"} { |
| 140 | t.Run(path, func(t *testing.T) { |
| 141 | for repeat := 0; repeat < 3; repeat++ { |
| 142 | cursor := "" |
| 143 | for page := 0; page < 20; page++ { |
| 144 | w := apiRequest(t, f, owner, "GET", "/api/v1/"+path+"?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") |
| 145 | expectHTTP(t, w, 200) |
| 146 | value := apiValue[struct { |
| 147 | NextCursor string `json:"next_cursor"` |
| 148 | }](t, w) |
| 149 | cursor = value.NextCursor |
| 150 | if cursor == "" { |
| 151 | break |
| 152 | } |
| 153 | if page == 19 { |
| 154 | t.Fatal("paging did not terminate") |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | }) |
| 159 | } |
| 160 | for _, path := range []string{"conversation", "preferences", "conversation/cards"} { |
| 161 | expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/"+path, "", "", ""), 200) |
| 162 | } |
| 163 | if f.count(t, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='person_api_cursors'") != 0 && f.count(t, "SELECT count(*) FROM person_api_cursors") != 0 { |
| 164 | t.Fatal("paging persisted cursor rows") |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | func TestPersonAPICursorFreshnessAndOrder(t *testing.T) { |
| 169 | f := newFixture(t) |
| 170 | for _, id := range []string{"b", "d", "f"} { |
| 171 | _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "secret-" + id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) |
| 172 | must(t, err) |
| 173 | f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), "secret-"+id) |
| 174 | f.exec(t, "UPDATE audit_events SET record_id=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", id, "secret-"+id) |
| 175 | f.exec(t, "UPDATE personal_preferences SET id=? WHERE text=?", id, "secret-"+id) |
| 176 | } |
| 177 | read := func(cursor string) personapi.Page[personapi.Preference] { |
| 178 | w := apiRequest(t, f, owner, "GET", "/api/v1/preferences?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") |
| 179 | expectHTTP(t, w, 200) |
| 180 | return apiValue[personapi.Page[personapi.Preference]](t, w) |
| 181 | } |
| 182 | first := read("") |
| 183 | if len(first.Items) != 1 || first.Items[0].ID != "b" { |
| 184 | t.Fatal(first) |
| 185 | } |
| 186 | expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/d", `{}`, "delete", `"1"`), 200) |
| 187 | for _, id := range []string{"a", "c"} { |
| 188 | _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "secret-" + id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) |
| 189 | must(t, err) |
| 190 | f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), "secret-"+id) |
| 191 | f.exec(t, "UPDATE audit_events SET record_id=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", id, "secret-"+id) |
| 192 | f.exec(t, "UPDATE personal_preferences SET id=? WHERE text=?", id, "secret-"+id) |
| 193 | } |
| 194 | var ids []string |
| 195 | cursor := first.NextCursor |
| 196 | for pages := 0; cursor != ""; pages++ { |
| 197 | if pages > 20 { |
| 198 | t.Fatal("cursor never advanced") |
| 199 | } |
| 200 | page := read(cursor) |
| 201 | for _, item := range page.Items { |
| 202 | if item.Text == "secret-d" { |
| 203 | t.Fatal("deleted text served") |
| 204 | } |
| 205 | ids = append(ids, item.ID) |
| 206 | } |
| 207 | cursor = page.NextCursor |
| 208 | } |
| 209 | if strings.Join(ids, ",") != "c,f" { |
| 210 | t.Fatalf("unstable keyset: %v", ids) |
| 211 | } |
| 212 | expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/preferences?cursor="+url.QueryEscape(first.NextCursor+"x"), "", "", ""), 410) |
| 213 | } |
| 214 | |
| 215 | func TestPersonAPINativeReplayAfterResolution(t *testing.T) { |
| 216 | f, _, _, _, q := nativeConversationFixture(t) |
| 217 | apiRouter(t, f, nil) |
| 218 | path := "/api/v1/questions/" + q.ID + "/answer" |
| 219 | body := `{"kind":"native","behavior":"allow","updated_input":{"answers":{"Which?":"Blue"}}}` |
| 220 | first := apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`) |
| 221 | expectHTTP(t, first, 200) |
| 222 | f.exec(t, "UPDATE questions SET state='invalid',expires_at=? WHERE id=?", time.Now().Add(-time.Hour), q.ID) |
| 223 | f.exec(t, "UPDATE runner_assignments SET state='finished' WHERE id=?", q.AssignmentID) |
| 224 | replay := apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`) |
| 225 | expectHTTP(t, replay, 200) |
| 226 | if first.Body.String() != replay.Body.String() { |
| 227 | t.Fatal("replay result changed") |
| 228 | } |
| 229 | expectHTTP(t, apiRequest(t, f, owner, "POST", path, strings.Replace(body, "Blue", "Red", 1), "answer", `"1"`), 409) |
| 230 | expectHTTP(t, apiRequest(t, f, owner, "POST", path, body, "new", `"1"`), 409) |
| 231 | f.exec(t, "UPDATE members SET role='member' WHERE address=?", owner.Address) |
| 232 | f.exec(t, "UPDATE tasks SET requester=? WHERE id=?", peer.Address, q.TaskID) |
| 233 | expectHTTP(t, apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`), 403) |
| 234 | f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| 235 | expectHTTP(t, apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`), 403) |
| 236 | } |
| 237 | |
| 238 | func TestPersonAPIEncodedPathCSRF(t *testing.T) { |
| 239 | f := newFixture(t) |
| 240 | for _, path := range []string{"/api%2Fv1/me", "/api%2fv1/conversation/messages", "/api%2Frunner/v2/heartbeat", "/api%2Fenrolments"} { |
| 241 | for _, method := range []string{"GET", "POST"} { |
| 242 | r := httptest.NewRequest(method, path, strings.NewReader(`{}`)) |
| 243 | r.AddCookie(f.Cookies[owner.Address]) |
| 244 | r.Header.Set("Origin", "https://evil.example") |
| 245 | w := httptest.NewRecorder() |
| 246 | f.Handler.ServeHTTP(w, r) |
| 247 | if w.Code != 422 && w.Code != 403 { |
| 248 | t.Fatalf("%s %s bypassed dispatcher protection: %d", method, path, w.Code) |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | func TestPersonAPITaskListParity(t *testing.T) { |
| 255 | f := newFixture(t) |
| 256 | base := f.createTask(t) |
| 257 | f.exec(t, "DELETE FROM tasks WHERE id=?", base.ID) |
| 258 | for _, id := range []string{"active", "peer-task", "old-finished", "recent-finished"} { |
| 259 | task := base |
| 260 | task.PlanRevision = 0 |
| 261 | task.ID = id |
| 262 | task.RequestID = id |
| 263 | if id == "peer-task" { |
| 264 | task.Requester = peer.Address |
| 265 | } |
| 266 | must(t, f.DB.G.Create(&task).Error) |
| 267 | f.exec(t, "INSERT INTO task_outboxes(task_id,state,engineering,review) VALUES(?,?,?,?)", id, "pending", "", "") |
| 268 | } |
| 269 | for _, id := range []string{"old-finished", "recent-finished"} { |
| 270 | f.exec(t, "UPDATE tasks SET state='cancelled' WHERE id=?", id) |
| 271 | at := time.Now() |
| 272 | if id == "old-finished" { |
| 273 | at = at.Add(-14 * 24 * time.Hour) |
| 274 | } |
| 275 | f.exec(t, "INSERT INTO audit_events(actor,kind,record_id,at) VALUES(?,?,?,?)", owner.Address, "task.cancel", id, at) |
| 276 | } |
| 277 | w := apiRequest(t, f, owner, "GET", "/api/v1/tasks", "", "", "") |
| 278 | expectHTTP(t, w, 200) |
| 279 | page := apiValue[personapi.Page[personapi.Task]](t, w) |
| 280 | var ids []string |
| 281 | for _, task := range page.Items { |
| 282 | ids = append(ids, task.ID) |
| 283 | } |
| 284 | sort.Strings(ids) |
| 285 | if strings.Join(ids, ",") != "active,peer-task,recent-finished" { |
| 286 | t.Fatal(ids) |
| 287 | } |
| 288 | html := f.get(t, owner, "/journey") |
| 289 | expectHTTP(t, html, 200) |
| 290 | for _, id := range []string{"active", "peer-task", "old-finished", "recent-finished"} { |
| 291 | present := strings.Contains(html.Body.String(), `href="/tasks/`+id+`"`) |
| 292 | if present != (id != "old-finished") { |
| 293 | t.Fatalf("HTML selection differs for %s", id) |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | func apiFixPlan(t *testing.T, f *fixture) taskplan.Plan { |
| 299 | t.Helper() |
| 300 | var project int64 |
| 301 | must(t, f.DB.Writer().QueryRow("SELECT project_id FROM tasks LIMIT 1").Scan(&project)) |
| 302 | p := taskplan.BugPlan("", project) |
| 303 | p.Steps[0].Instructions = "fixture symptom" |
| 304 | p.Revision = 0 |
| 305 | out, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: fmt.Sprintf("plan-%d", time.Now().UnixNano())}) |
| 306 | must(t, err) |
| 307 | return out |
| 308 | } |
| 309 | |