| 1 | package equipotest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "os" |
| 13 | "regexp" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 19 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 20 | "amadan.net/oficina/equipo/internal/testci" |
| 21 | |
| 22 | "amadan.net/oficina/equipo/internal/equipo" |
| 23 | "gorm.io/gorm" |
| 24 | ) |
| 25 | |
| 26 | func taskPageServer(t *testing.T, f connectionFixture, always bool) (*httptest.Server, *http.Client) { |
| 27 | t.Helper() |
| 28 | mailer := &capturingMailer{} |
| 29 | cfg := testConfig(testOrigin) |
| 30 | router, err := equipo.RouterWithStore(f.d, cfg, mailer, nil, f.s) |
| 31 | executionMust(t, err) |
| 32 | server := httptest.NewServer(equipo.Mux(router)) |
| 33 | t.Cleanup(func() { equipo.CloseLive(router); server.Close() }) |
| 34 | c := signinClient(t, server.URL) |
| 35 | signinEmail(t, c, server.URL, testOrigin, mailer, ownerAddress) |
| 36 | return server, c |
| 37 | } |
| 38 | func taskGet(t *testing.T, c *http.Client, base, path string, status int) string { |
| 39 | t.Helper() |
| 40 | r, err := c.Get(base + path) |
| 41 | executionMust(t, err) |
| 42 | defer r.Body.Close() |
| 43 | if r.StatusCode != status { |
| 44 | t.Fatalf("GET %s: status %d, want %d", path, r.StatusCode, status) |
| 45 | } |
| 46 | b, err := io.ReadAll(r.Body) |
| 47 | executionMust(t, err) |
| 48 | if r.StatusCode != status { |
| 49 | t.Fatalf("GET %s: %d want %d: %s", path, r.StatusCode, status, b) |
| 50 | } |
| 51 | return string(b) |
| 52 | } |
| 53 | func TestTaskPages(t *testing.T) { |
| 54 | f := bugFixture(t) |
| 55 | task := bugTask(t, f) |
| 56 | setMember(t, f.s, "reader@example.com", equipo.RoleMember, true) |
| 57 | v, err := f.s.TaskView(connectionContext, equipo.Actor{Address: "reader@example.com"}, task.ID) |
| 58 | executionMust(t, err) |
| 59 | if len(v.Steps) != 6 || v.Task.ID != task.ID { |
| 60 | t.Fatal("ordered task projection missing") |
| 61 | } |
| 62 | server, c := taskPageServer(t, f, false) |
| 63 | taskGet(t, c, server.URL, "/live?t=jobs/"+strings.Repeat("f", 64)+"@0", 404) |
| 64 | for _, p := range []string{"/journey", "/tasks/" + task.ID, "/specialists/engineering", "/specialists/review"} { |
| 65 | body := taskGet(t, c, server.URL, p, 200) |
| 66 | if strings.Contains(body, `name="rastrillo-live"`) { |
| 67 | t.Fatal("hibernating app enabled streams") |
| 68 | } |
| 69 | if !strings.Contains(body, task.Description) { |
| 70 | t.Fatalf("%s missing task", p) |
| 71 | } |
| 72 | } |
| 73 | if strings.Contains(taskGet(t, c, server.URL, "/conversation", 200), task.Description) { |
| 74 | t.Fatal("legacy task appeared as a private conversation message") |
| 75 | } |
| 76 | for _, key := range []string{"product", "design", "copy", "engineering", "review"} { |
| 77 | work, err := f.s.SpecialistWork(connectionContext, ownerActor, key) |
| 78 | executionMust(t, err) |
| 79 | if !work.CountsKnown || (key == "engineering" && work.Queued != 1) { |
| 80 | t.Fatal("specialist counts", key, work) |
| 81 | } |
| 82 | } |
| 83 | for _, p := range []string{"/tasks/new", "/connections", "/needs-you", "/settings/recovery"} { |
| 84 | taskGet(t, c, server.URL, p, 200) |
| 85 | } |
| 86 | mustSQL(t, f.d, "UPDATE tasks SET description=?, review_ref=? WHERE id=?", "<script>bad()</script>", "<img src=x>", task.ID) |
| 87 | body := taskGet(t, c, server.URL, "/tasks/"+task.ID, 200) |
| 88 | if strings.Contains(body, "<script>bad()") || strings.Contains(body, "<img src=x>") || !strings.Contains(body, "<script>") { |
| 89 | t.Fatal("task HTML not escaped") |
| 90 | } |
| 91 | mustSQL(t, f.d, "UPDATE tasks SET wait_code='family' WHERE id=?", task.ID) |
| 92 | if !strings.Contains(taskGet(t, c, server.URL, "/tasks/"+task.ID, 200), equipo.RunnerText("task.wait.family")) { |
| 93 | t.Fatal("family wait missing") |
| 94 | } |
| 95 | mustSQL(t, f.d, "UPDATE tasks SET wait_code='' WHERE id=?", task.ID) |
| 96 | mustSQL(t, f.d, "UPDATE tasks SET state='cancel_requested' WHERE id=?", task.ID) |
| 97 | if !strings.Contains(taskGet(t, c, server.URL, "/tasks/"+task.ID, 200), equipo.RunnerText("task.cancel.requested")) { |
| 98 | t.Fatal("requested state missing") |
| 99 | } |
| 100 | mustSQL(t, f.d, "UPDATE tasks SET state='cancelled' WHERE id=?", task.ID) |
| 101 | if !strings.Contains(taskGet(t, c, server.URL, "/tasks/"+task.ID, 200), equipo.RunnerText("task.cancel.stopped")) { |
| 102 | t.Fatal("stopped state missing") |
| 103 | } |
| 104 | mustSQL(t, f.d, "UPDATE tasks SET state='failed' WHERE id=?", task.ID) |
| 105 | failed, err := f.s.TaskView(connectionContext, ownerActor, task.ID) |
| 106 | executionMust(t, err) |
| 107 | if failed.Group != "finished" || failed.StateKey != "task.state.failed" { |
| 108 | t.Fatal("failure missing from finished group") |
| 109 | } |
| 110 | |
| 111 | } |
| 112 | func TestTaskPagesCurrentMemberAndTeam(t *testing.T) { |
| 113 | f := bugFixture(t) |
| 114 | task := bugTask(t, f) |
| 115 | foreign := task |
| 116 | foreign.ID = "foreign" |
| 117 | foreign.TeamID = "another-team" |
| 118 | foreign.RequestID = "foreign" |
| 119 | executionMust(t, f.d.G.Create(&foreign).Error) |
| 120 | mustSQL(t, f.d, `INSERT INTO task_outboxes SELECT ?,state,project_revision,budget_revision,engineering,review,prepared,job_spec FROM task_outboxes WHERE task_id=?`, foreign.ID, task.ID) |
| 121 | if _, err := f.s.TaskView(connectionContext, ownerActor, foreign.ID); !errors.Is(err, equipo.ErrNotFound) { |
| 122 | t.Fatal("cross-team task view", err) |
| 123 | } |
| 124 | views, err := f.s.Journey(connectionContext, ownerActor) |
| 125 | executionMust(t, err) |
| 126 | if len(views) != 1 { |
| 127 | t.Fatal("foreign task in collection") |
| 128 | } |
| 129 | mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress) |
| 130 | if _, err := f.s.TaskView(connectionContext, ownerActor, task.ID); !errors.Is(err, equipo.ErrForbidden) { |
| 131 | t.Fatal("removed member direct task view", err) |
| 132 | } |
| 133 | mustSQL(t, f.d, "DELETE FROM tasks") |
| 134 | if _, err := f.s.Journey(connectionContext, ownerActor); !errors.Is(err, equipo.ErrForbidden) { |
| 135 | t.Fatal("removed member empty collection", err) |
| 136 | } |
| 137 | } |
| 138 | func TestTaskPagesUnknownCounts(t *testing.T) { |
| 139 | f := bugFixture(t) |
| 140 | server, c := taskPageServer(t, f, false) |
| 141 | executionMust(t, f.d.G.Callback().Query().Before("gorm:query").Register("task16_count", func(tx *gorm.DB) { |
| 142 | if tx.Statement.Table == "tasks" { |
| 143 | tx.AddError(errors.New("count unavailable")) |
| 144 | } |
| 145 | })) |
| 146 | defer f.d.G.Callback().Query().Remove("task16_count") |
| 147 | work, err := f.s.SpecialistWork(connectionContext, ownerActor, "engineering") |
| 148 | if err == nil || work.CountsKnown { |
| 149 | t.Fatal("unknown count became known") |
| 150 | } |
| 151 | taskGet(t, c, server.URL, "/journey", 503) |
| 152 | taskGet(t, c, server.URL, "/specialists/engineering", 503) |
| 153 | } |
| 154 | func TestTaskFormsCSRFAndRevision(t *testing.T) { |
| 155 | f := bugFixture(t) |
| 156 | server, c := taskPageServer(t, f, false) |
| 157 | form := url.Values{"project_id": {fmt.Sprint(f.project.ID)}, "description": {"form bug"}, "request_id": {"task16-form"}} |
| 158 | res := clientPost(t, c, server.URL+"/tasks", "http://wrong.invalid", form) |
| 159 | res.Body.Close() |
| 160 | if res.StatusCode != 403 { |
| 161 | t.Fatal("CSRF accepted") |
| 162 | } |
| 163 | res = clientPost(t, c, server.URL+"/tasks", testOrigin, form) |
| 164 | res.Body.Close() |
| 165 | if res.StatusCode != 303 || !strings.HasPrefix(res.Header.Get("Location"), "/tasks/") { |
| 166 | t.Fatal("submission must redirect to task", res.StatusCode, res.Header) |
| 167 | } |
| 168 | taskGet(t, c, server.URL, res.Header.Get("Location"), 200) |
| 169 | } |
| 170 | func TestTaskLayoutRules(t *testing.T) { |
| 171 | css, err := os.ReadFile("../equipo/static/equipo.css") |
| 172 | executionMust(t, err) |
| 173 | for _, accent := range []string{"border-left", "border-inline-start"} { |
| 174 | if strings.Contains(strings.ToLower(string(css)), accent) { |
| 175 | t.Fatal("forbidden CSS accent", accent) |
| 176 | } |
| 177 | } |
| 178 | f := bugFixture(t) |
| 179 | bugTask(t, f) |
| 180 | server, c := taskPageServer(t, f, false) |
| 181 | body := taskGet(t, c, server.URL, "/journey", 200) |
| 182 | for _, bad := range []string{"<table", `http-equiv="refresh"`, "EventSource(", "%"} { |
| 183 | if strings.Contains(body, bad) { |
| 184 | t.Fatal("forbidden task layout", bad) |
| 185 | } |
| 186 | } |
| 187 | // The old journey page is no longer in the thin sidebar (slice 4), so |
| 188 | // nothing there is the current page. |
| 189 | if strings.Count(body, `aria-current="page"`) > 1 || !strings.Contains(body, "rst-shell-nav") || !strings.Contains(body, "equipo-steps") || !strings.Contains(body, `rel="up"`) { |
| 190 | t.Fatal("missing shell or step chips") |
| 191 | } |
| 192 | } |
| 193 | func TestUnconfinedLabelEverySurface(t *testing.T) { |
| 194 | f := bugFixture(t) |
| 195 | task := bugTask(t, f) |
| 196 | seedHistoricalTaskIsolation(t, f, task.ID) |
| 197 | server, c := taskPageServer(t, f, false) |
| 198 | for _, p := range []string{"/journey", "/tasks/" + task.ID, "/specialists/engineering", "/specialists/review"} { |
| 199 | b := taskGet(t, c, server.URL, p, 200) |
| 200 | card := regexp.MustCompile(`(?s)<div equipo-card>.*?</div>`).FindString(b) |
| 201 | if !strings.Contains(card, ">unconfined<") || !strings.Contains(card, "supervised trial") { |
| 202 | t.Fatal("task card missing historical label", p) |
| 203 | } |
| 204 | for _, key := range []string{"reproduce", "implement", "review", "verify", "publish"} { |
| 205 | chip := regexp.MustCompile(`(?s)<li equipo-step data-step="` + key + `">.*?</li>`).FindString(b) |
| 206 | if !strings.Contains(chip, ">unconfined<") { |
| 207 | t.Fatal("affected chip missing historical label", p, key) |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | executionMust(t, setDirectAvailable(f.s, f.principal, f.reports, false)) |
| 212 | v, err := f.s.TaskView(connectionContext, ownerActor, task.ID) |
| 213 | executionMust(t, err) |
| 214 | if !v.Unconfined { |
| 215 | t.Fatal("expiry stripped history") |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | type taskNotices struct { |
| 220 | batches [][]string |
| 221 | topics []string |
| 222 | at []time.Time |
| 223 | check func() |
| 224 | } |
| 225 | |
| 226 | func (n *taskNotices) Notify(topics ...string) { |
| 227 | if n.check != nil { |
| 228 | n.check() |
| 229 | } |
| 230 | n.batches = append(n.batches, append([]string{}, topics...)) |
| 231 | n.topics = append(n.topics, topics...) |
| 232 | } |
| 233 | func (n *taskNotices) NotifyAt(at time.Time, topics ...string) { n.at = append(n.at, at) } |
| 234 | func TestReleaseCopyReviewed(t *testing.T) { |
| 235 | if os.Getenv("EQUIPO_RELEASE_COPY_CHECK") == "1" { |
| 236 | executionMust(t, testci.CopyReleaseCheck(t, "../..")) |
| 237 | } |
| 238 | |
| 239 | for _, key := range equipo.PendingRunnerCopy() { |
| 240 | if equipo.RunnerText(key) == "" { |
| 241 | t.Fatal("pending inventory has no text", key) |
| 242 | } |
| 243 | } |
| 244 | for _, key := range []string{"task.wait.family", "task.wait.setup", "task.cancel.requested", "task.cancel.stopped", "usage.counted_turns", "usage.allowance_unknown", "recovery.unknown_charged", "runner.preflight.unavailable", "isolation.unconfined"} { |
| 245 | if equipo.RunnerText(key) == "" { |
| 246 | t.Fatal("missing inventory key", key) |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | func TestTaskLiveRefreshCommittedServices(t *testing.T) { |
| 252 | f := runnerFixtureNew(t, false) |
| 253 | n := &taskNotices{} |
| 254 | f.s.SetJobNotifier(n) |
| 255 | check := func(name string, fn func() error) { |
| 256 | t.Helper() |
| 257 | n.topics = nil |
| 258 | executionMust(t, fn()) |
| 259 | seen := map[string]bool{} |
| 260 | for _, topic := range n.topics { |
| 261 | seen[topic] = true |
| 262 | } |
| 263 | if len(seen) != 2 { |
| 264 | t.Fatalf("%s did not notify job and collection: %v", name, n.topics) |
| 265 | } |
| 266 | } |
| 267 | check("claim", func() error { |
| 268 | var err error |
| 269 | f.claim, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}) |
| 270 | return err |
| 271 | }) |
| 272 | n.check = func() { _, err := f.x.Core.GetJob(connectionContext, f.claim.Scope); executionMust(t, err) } |
| 273 | // Avoid recursive read observer callbacks: unchanged reads must stay silent. |
| 274 | eventValidators(f) |
| 275 | check("event", func() error { |
| 276 | return f.s.IngestRunnerEvent(connectionContext, f.principal, fixtureEvent(f, "live-event", 1)) |
| 277 | }) |
| 278 | n.check = nil |
| 279 | check("intent and admission", func() error { eventTurn(t, f); return nil }) |
| 280 | check("cancel", func() error { _, err := f.s.CancelTask(connectionContext, ownerActor, f.a.TaskID); return err }) |
| 281 | check("connection acknowledgement revocation", func() error { |
| 282 | return setDirectAvailable(f.s, f.principal, f.reports, false) |
| 283 | }) |
| 284 | if len(n.at) == 0 { |
| 285 | t.Fatal("time transitions not scheduled") |
| 286 | } |
| 287 | n.topics = nil |
| 288 | err := f.x.Write(connectionContext, func(tx *gorm.DB) error { |
| 289 | if err := tx.Model(&equipo.Task{}).Where("id=?", f.a.TaskID).Update("description", "rolled back").Error; err != nil { |
| 290 | return err |
| 291 | } |
| 292 | return errors.New("rollback") |
| 293 | }) |
| 294 | if err == nil || len(n.topics) != 0 { |
| 295 | t.Fatal("core rollback notified") |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | func TestTaskPagesWeeklyAndMergeAuthority(t *testing.T) { |
| 300 | f := runnerFixtureNew(t, false) |
| 301 | mustSQL(t, f.d, "UPDATE jobs SET state='succeeded',updated_at=? WHERE id=?", f.clock.Now().Format(time.RFC3339Nano), f.a.Scope.Job) |
| 302 | task, err := f.s.Task(connectionContext, ownerActor, f.a.TaskID) |
| 303 | executionMust(t, err) |
| 304 | v, err := f.s.TaskView(connectionContext, equipo.Actor{Address: task.MergeOwner}, task.ID) |
| 305 | executionMust(t, err) |
| 306 | if !v.NeedsYou || !v.CanMerge { |
| 307 | t.Fatal("merge not assigned to saved owner") |
| 308 | } |
| 309 | if err = f.s.AcknowledgeMerge(connectionContext, ownerActor, task.ID, task.Revision, "https://amadan.net/oficina/example/pulls/1"); !errors.Is(err, equipo.ErrForbidden) { |
| 310 | t.Fatal("owner impersonated merge person", err) |
| 311 | } |
| 312 | actor := equipo.Actor{Address: task.MergeOwner} |
| 313 | notices := &taskNotices{} |
| 314 | f.s.SetJobNotifier(notices) |
| 315 | if err = f.s.AcknowledgeMerge(connectionContext, actor, task.ID, task.Revision+1, "https://amadan.net/oficina/example/pulls/1"); !errors.Is(err, equipo.ErrConflict) { |
| 316 | t.Fatal("stale merge revision", err) |
| 317 | } |
| 318 | if err = f.s.AcknowledgeMerge(connectionContext, actor, task.ID, task.Revision, "https://outside.invalid/pulls/1"); !errors.Is(err, equipo.ErrInvalid) { |
| 319 | t.Fatal("non-Amadan reference", err) |
| 320 | } |
| 321 | mustSQL(t, f.d, "UPDATE decision_owners SET address=? WHERE project_id=? AND decision='merge'", ownerAddress, f.project.ID) |
| 322 | if err = f.s.AcknowledgeMerge(connectionContext, actor, task.ID, task.Revision, "https://amadan.net/oficina/example/pulls/1"); !errors.Is(err, equipo.ErrConflict) { |
| 323 | t.Fatal("changed merge assignment accepted", err) |
| 324 | } |
| 325 | mustSQL(t, f.d, "UPDATE decision_owners SET address=? WHERE project_id=? AND decision='merge'", task.MergeOwner, f.project.ID) |
| 326 | executionMust(t, f.s.AcknowledgeMerge(connectionContext, actor, task.ID, task.Revision, "https://amadan.net/oficina/example/pulls/1")) |
| 327 | if len(notices.topics) != 2 { |
| 328 | t.Fatal("merge did not notify after commit", notices.topics) |
| 329 | } |
| 330 | v, err = f.s.TaskView(connectionContext, ownerActor, task.ID) |
| 331 | executionMust(t, err) |
| 332 | if v.Group != "finished" || v.MergeReference == "" { |
| 333 | t.Fatal("merge acknowledgement lost", v) |
| 334 | } |
| 335 | mustSQL(t, f.d, "UPDATE audit_events SET at=? WHERE kind='task.merge'", f.clock.Now().AddDate(0, 0, -14)) |
| 336 | mustSQL(t, f.d, "UPDATE jobs SET updated_at=? WHERE id=?", f.clock.Now().AddDate(0, 0, -14).Format(time.RFC3339Nano), f.a.Scope.Job) |
| 337 | views, err := f.s.Journey(connectionContext, ownerActor) |
| 338 | executionMust(t, err) |
| 339 | if len(views) != 0 { |
| 340 | t.Fatal("old finished task retained", views) |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | func TestUnconfinedLabelEverySurfaceConfinedControl(t *testing.T) { |
| 345 | f := bugFixture(t) |
| 346 | // An injected release tuple is the only way this fixture gains confinement. |
| 347 | tuples := []team.IsolationTuple{connectionTuple(f.reports[0]), connectionTuple(f.reports[1])} |
| 348 | f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock), equipo.WithVerifiedIsolationTuples(tuples)) |
| 349 | executionMust(t, f.s.ReportConnections(connectionContext, f.principal, f.reports)) |
| 350 | task := bugTask(t, f) |
| 351 | v, err := f.s.TaskView(connectionContext, ownerActor, task.ID) |
| 352 | executionMust(t, err) |
| 353 | if v.Unconfined { |
| 354 | t.Fatal("untainted control labelled unconfined") |
| 355 | } |
| 356 | for _, step := range v.Steps { |
| 357 | if step.Unconfined { |
| 358 | t.Fatal("confined step labelled") |
| 359 | } |
| 360 | } |
| 361 | server, c := taskPageServer(t, f, false) |
| 362 | if strings.Contains(taskGet(t, c, server.URL, "/tasks/"+task.ID, 200), ">unconfined<") { |
| 363 | t.Fatal("confined surface falsely labelled") |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | func TestTaskLiveRefreshQuestionsUsageAndContainment(t *testing.T) { |
| 368 | f, q := questionFixture(t) |
| 369 | n := &taskNotices{} |
| 370 | f.s.SetJobNotifier(n) |
| 371 | assertNotice := func(name string) { |
| 372 | t.Helper() |
| 373 | seen := map[string]bool{} |
| 374 | for _, topic := range n.topics { |
| 375 | seen[topic] = true |
| 376 | } |
| 377 | if len(seen) != 2 { |
| 378 | t.Fatalf("%s: expected job and collection notices, got %v", name, n.topics) |
| 379 | } |
| 380 | for _, batch := range n.batches { |
| 381 | if len(batch) != 2 || batch[0] == batch[1] { |
| 382 | t.Fatalf("%s: commit did not deduplicate keys: %v", name, batch) |
| 383 | } |
| 384 | } |
| 385 | n.batches = nil |
| 386 | n.topics = nil |
| 387 | } |
| 388 | executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"})) |
| 389 | assertNotice("answer") |
| 390 | f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 391 | _, err := f.s.CancelTask(connectionContext, ownerActor, f.a.TaskID) |
| 392 | executionMust(t, err) |
| 393 | assertNotice("cancel") |
| 394 | request := f.request() |
| 395 | request.RequestID = "contained" |
| 396 | request.Proof = flowJSON(runnerproto.ContainmentProof{Version: 2, Scope: request.Scope, Handle: request.Handle, CheckedAt: time.Now().UTC()}) |
| 397 | rotationValue, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", request) |
| 398 | executionMust(t, err) |
| 399 | assertNotice("containment and rotation") |
| 400 | rotated := rotationValue.(equipo.CredentialRotation) |
| 401 | principal, err := f.s.AuthenticateRunner(connectionContext, rotated.Bearer.Token) |
| 402 | executionMust(t, err) |
| 403 | executionMust(t, f.x.AcknowledgeRotation(connectionContext, principal, request.RequestID)) |
| 404 | assertNotice("rotation acknowledgement") |
| 405 | v, err := f.s.TaskView(connectionContext, ownerActor, f.a.TaskID) |
| 406 | executionMust(t, err) |
| 407 | if v.StateKey != "task.cancel.stopped" || v.Unconfined { |
| 408 | t.Fatal("containment state or history missing") |
| 409 | } |
| 410 | } |
| 411 | func TestTaskPagesUsageAndEscapedLogs(t *testing.T) { |
| 412 | f := runnerFixtureNew(t, true) |
| 413 | id := eventTurn(t, f) |
| 414 | n := &taskNotices{} |
| 415 | f.s.SetJobNotifier(n) |
| 416 | completionValidators(f, &team.Usage{Calls: 1, InputTokens: 13, CachedInputTokens: 3, OutputTokens: 2, CostUnavailable: true}) |
| 417 | executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, completionEvent(f, id))) |
| 418 | if len(n.topics) != 2 { |
| 419 | t.Fatal("usage commit did not notify", n.topics) |
| 420 | } |
| 421 | v, err := f.s.TaskView(connectionContext, ownerActor, f.a.TaskID) |
| 422 | executionMust(t, err) |
| 423 | if !v.UsageKnown || v.CountedTurns != 1 || v.InputTokens != 13 || v.OutputTokens != 2 { |
| 424 | t.Fatal("usage projection", v) |
| 425 | } |
| 426 | work, err := f.s.SpecialistWork(connectionContext, ownerActor, "engineering") |
| 427 | executionMust(t, err) |
| 428 | if !work.UsageKnown || work.CountedTurns != 1 { |
| 429 | t.Fatal("specialist usage", work) |
| 430 | } |
| 431 | e := fixtureEvent(f, "escaped-log", 2) |
| 432 | e.Payload = json.RawMessage(`{"text":"<script>log()</script>"}`) |
| 433 | executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| 434 | server, c := taskPageServer(t, f.connectionFixture, false) |
| 435 | body := taskGet(t, c, server.URL, "/tasks/"+f.a.TaskID, 200) |
| 436 | if strings.Contains(body, "<script>log()") || !strings.Contains(body, "<script>log()") { |
| 437 | t.Fatal("log escaping") |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | func TestUnconfinedLabelEverySurfaceEvidenceAndRestart(t *testing.T) { |
| 442 | f := runnerFixtureNew(t, true) |
| 443 | seedHistoricalTaskIsolation(t, f.connectionFixture, f.a.TaskID) |
| 444 | v, err := f.s.TaskView(connectionContext, ownerActor, f.a.TaskID) |
| 445 | executionMust(t, err) |
| 446 | iso := v.Steps[0].Isolation |
| 447 | raw, err := json.Marshal(team.Provenance{Producer: "executor", Provider: "executor", Context: "trusted-check", Isolation: iso}) |
| 448 | executionMust(t, err) |
| 449 | var step int64 |
| 450 | executionMust(t, f.d.Writer().QueryRow("SELECT step_id FROM attempts WHERE id=?", f.claim.Handle.Attempt).Scan(&step)) |
| 451 | mustSQL(t, f.d, `INSERT INTO artifacts(job_id,step_id,attempt_id,fence,role,hash,media_type,size,provenance,payload,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)`, f.a.Scope.Job, step, f.claim.Handle.Attempt, f.claim.Handle.Fence, "repository_checks", strings.Repeat("a", 64), "application/json", 2, string(raw), []byte(`{"log":"<script>evidence()</script>"}`), f.clock.Now().Format(time.RFC3339Nano)) |
| 452 | server, c := taskPageServer(t, f.connectionFixture, false) |
| 453 | body := taskGet(t, c, server.URL, "/tasks/"+f.a.TaskID, 200) |
| 454 | if !strings.Contains(body, "repository_checks") || strings.Contains(body, "<script>evidence()") || strings.Count(body, ">unconfined<") < 7 { |
| 455 | t.Fatal("executor evidence label or escaping") |
| 456 | } |
| 457 | eventValidators(f) |
| 458 | event := fixtureEvent(f, "historical", 1) |
| 459 | executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, event)) |
| 460 | executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, event)) |
| 461 | executionMust(t, setDirectAvailable(f.s, f.principal, f.reports, false)) |
| 462 | reopened := equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock)) |
| 463 | v, err = reopened.TaskView(connectionContext, ownerActor, f.a.TaskID) |
| 464 | executionMust(t, err) |
| 465 | if !v.Unconfined || len(v.Evidence) != 1 || !v.Evidence[0].Unconfined || len(v.Logs) != 1 || !v.Logs[0].Unconfined { |
| 466 | t.Fatal("replay, expiry or reopening stripped exposure") |
| 467 | } |
| 468 | } |
| 469 | func TestDirectForgedReportCannotHideEligibility(t *testing.T) { |
| 470 | f := bugFixture(t) |
| 471 | if !f.reports[1].ReadIsolation { |
| 472 | t.Fatal("fixture must claim confinement") |
| 473 | } |
| 474 | executionMust(t, setDirectAvailable(f.s, f.principal, f.reports, false)) |
| 475 | waiting, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "forged", "forged") |
| 476 | executionMust(t, err) |
| 477 | if waiting.WaitCode != "task.wait.setup" || waiting.JobID != 0 { |
| 478 | t.Fatal("unavailable direct tuple dispatched") |
| 479 | } |
| 480 | executionMust(t, setDirectAvailable(f.s, f.principal, f.reports, true)) |
| 481 | task := bugTask(t, f) |
| 482 | v, err := f.s.TaskView(connectionContext, ownerActor, task.ID) |
| 483 | executionMust(t, err) |
| 484 | if v.Unconfined { |
| 485 | t.Fatal("forged report hid unconfined") |
| 486 | } |
| 487 | for _, step := range v.Steps { |
| 488 | if step.Key != "merge" && step.Unconfined { |
| 489 | t.Fatal("forged report hid chip label", step.Key) |
| 490 | } |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | func TestTaskFormsCSRFAndRevisionQuestionFields(t *testing.T) { |
| 495 | f, q := questionFixture(t) |
| 496 | server, c := taskPageServer(t, f.connectionFixture, false) |
| 497 | path := "/tasks/" + f.a.TaskID + "/questions/" + q.ID |
| 498 | body := taskGet(t, c, server.URL, path, 200) |
| 499 | if !strings.Contains(body, `name="answer_0"`) || strings.Contains(body, `name="updated_input"`) { |
| 500 | t.Fatal("question needs a text answer form") |
| 501 | } |
| 502 | form := url.Values{"revision": {"2"}, "behavior": {"allow"}, "answer_0": {"Blue"}} |
| 503 | res := clientPost(t, c, server.URL+path+"/answer", testOrigin, form) |
| 504 | res.Body.Close() |
| 505 | if res.StatusCode != 409 { |
| 506 | t.Fatal("stale question revision", res.StatusCode) |
| 507 | } |
| 508 | form.Set("revision", "1") |
| 509 | res = clientPost(t, c, server.URL+path+"/answer", testOrigin, form) |
| 510 | res.Body.Close() |
| 511 | if res.StatusCode != 303 { |
| 512 | t.Fatal("scriptless answer", res.StatusCode) |
| 513 | } |
| 514 | if scalar(t, f.d, "SELECT count(*) FROM questions WHERE answered_by=?", ownerAddress) != 1 { |
| 515 | t.Fatal("answer actor missing") |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | func TestTaskLiveRefreshUnpaginated(t *testing.T) { |
| 520 | f := bugFixture(t) |
| 521 | for i := 0; i < 70; i++ { |
| 522 | _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, fmt.Sprintf("task %d", i), fmt.Sprintf("unpaginated-%d", i)) |
| 523 | executionMust(t, err) |
| 524 | } |
| 525 | server, c := taskPageServer(t, f, true) |
| 526 | body := taskGet(t, c, server.URL, "/journey", 200) |
| 527 | if strings.Count(body, "data-task=") != 70 { |
| 528 | t.Fatal("list silently paginated") |
| 529 | } |
| 530 | for _, tokens := range regexp.MustCompile(`data-live="([^"]+)"`).FindAllStringSubmatch(body, -1) { |
| 531 | if len(strings.Fields(tokens[1])) != 1 { |
| 532 | t.Fatal("list follows each job") |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | func TestTaskLiveRefreshRecovery(t *testing.T) { |
| 538 | f := runnerFixtureNew(t, false) |
| 539 | n := &taskNotices{} |
| 540 | f.s.SetJobNotifier(n) |
| 541 | executionMust(t, f.x.Core.Pause(connectionContext, "recovery review")) |
| 542 | if len(n.topics) != 2 { |
| 543 | t.Fatal("quarantine did not notify", n.topics) |
| 544 | } |
| 545 | n.topics = nil |
| 546 | _, err := f.x.Core.Resume(connectionContext) |
| 547 | executionMust(t, err) |
| 548 | snapshot, err := f.x.Core.RecoverySnapshot(connectionContext) |
| 549 | executionMust(t, err) |
| 550 | n.topics = nil |
| 551 | if err = f.s.ReleaseExecution(connectionContext, ownerActor, snapshot.Revision-1, "checked", snapshot.Hash); err == nil { |
| 552 | t.Fatal("stale recovery revision accepted") |
| 553 | } |
| 554 | if len(n.topics) != 0 { |
| 555 | t.Fatal("rejected recovery notified") |
| 556 | } |
| 557 | executionMust(t, f.s.ReleaseExecution(connectionContext, ownerActor, snapshot.Revision, "checked", snapshot.Hash)) |
| 558 | if len(n.topics) != 2 { |
| 559 | t.Fatal("recovery release did not notify", n.topics) |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | func TestTaskPagesMergeRequiresPublication(t *testing.T) { |
| 564 | f := runnerFixtureNew(t, false) |
| 565 | task, err := f.s.Task(connectionContext, ownerActor, f.a.TaskID) |
| 566 | executionMust(t, err) |
| 567 | if err = f.s.AcknowledgeMerge(connectionContext, equipo.Actor{Address: task.MergeOwner}, task.ID, task.Revision, "https://amadan.net/oficina/example/pulls/1"); !errors.Is(err, equipo.ErrConflict) { |
| 568 | t.Fatal("unpublished task accepted merge", err) |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | func TestTaskPagesQuestionRenewal(t *testing.T) { |
| 573 | f, q := questionFixture(t) |
| 574 | mustSQL(t, f.d, "UPDATE questions SET expires_at=? WHERE id=?", f.clock.Now().Add(-time.Second), q.ID) |
| 575 | v, err := f.s.TaskView(connectionContext, ownerActor, f.a.TaskID) |
| 576 | executionMust(t, err) |
| 577 | if len(v.Questions) != 1 || !v.Questions[0].CanAnswer { |
| 578 | t.Fatal("renewed question used its old lease snapshot") |
| 579 | } |
| 580 | executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"})) |
| 581 | } |
| 582 | |
| 583 | // Historical storage fixtures are inserted directly; no consent setter remains. |
| 584 | func seedHistoricalTaskIsolation(t *testing.T, f connectionFixture, task string) { |
| 585 | t.Helper() |
| 586 | iso := team.IsolationSnapshot{Status: "unconfined", RunnerTainted: true, AcknowledgementIDs: []string{"historical"}, Trial: &team.TrialSnapshot{Label: "supervised trial", AcknowledgementIDs: []string{"historical"}, UnverifiedChecks: team.TrialChecks(), ProviderVersionSource: "observed_locally"}} |
| 587 | for _, column := range []string{"engineering", "review"} { |
| 588 | var raw string |
| 589 | executionMust(t, f.d.Writer().QueryRow("SELECT "+column+" FROM task_outboxes WHERE task_id=?", task).Scan(&raw)) |
| 590 | var selection equipo.Selection |
| 591 | executionMust(t, json.Unmarshal([]byte(raw), &selection)) |
| 592 | selection.Isolation = iso |
| 593 | mustSQL(t, f.d, "UPDATE task_outboxes SET "+column+"=? WHERE task_id=?", string(flowJSON(selection)), task) |
| 594 | } |
| 595 | mustSQL(t, f.d, "UPDATE runner_assignments SET isolation=? WHERE task_id=?", string(flowJSON(iso)), task) |
| 596 | } |
| 597 | |