| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/binary" |
| 9 | "encoding/hex" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "hash/crc32" |
| 13 | "image" |
| 14 | "image/color" |
| 15 | "image/png" |
| 16 | "math/rand" |
| 17 | "net/http" |
| 18 | "net/http/httptest" |
| 19 | "strings" |
| 20 | "testing" |
| 21 | |
| 22 | "github.com/go-chi/chi/v5" |
| 23 | "gorm.io/gorm" |
| 24 | |
| 25 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 26 | "amadan.net/oficina/equipo/internal/wire" |
| 27 | ) |
| 28 | |
| 29 | // Task 19 (dynamic specialists slice 1): Design's captures. A Design |
| 30 | // attempt's render_file chunks are staged for its current attempt and |
| 31 | // never served; its final report's options are checked against them |
| 32 | // (ids, hashes, tree digests, each PNG decoded within bounds) and its |
| 33 | // binding with grantFor in the report's transaction, and only then are |
| 34 | // they kept. The task page and the direction card show what was kept; |
| 35 | // with more than one option, Build this needs the person's note. |
| 36 | |
| 37 | var ( |
| 38 | digestWork = strings.Repeat("d", 64) |
| 39 | digestBase = strings.Repeat("e", 64) |
| 40 | ) |
| 41 | |
| 42 | // capturePNG is a w by h PNG. |
| 43 | func capturePNG(t *testing.T, w, h int, shade uint8) []byte { |
| 44 | t.Helper() |
| 45 | img := image.NewNRGBA(image.Rect(0, 0, w, h)) |
| 46 | for y := 0; y < h; y++ { |
| 47 | for x := 0; x < w; x++ { |
| 48 | img.Set(x, y, color.NRGBA{R: shade, G: uint8(x), B: uint8(y), A: 255}) |
| 49 | } |
| 50 | } |
| 51 | var b bytes.Buffer |
| 52 | if err := png.Encode(&b, img); err != nil { |
| 53 | t.Fatal(err) |
| 54 | } |
| 55 | return b.Bytes() |
| 56 | } |
| 57 | |
| 58 | // noisyPNG is a w by h PNG of noise: it does not compress, so it takes |
| 59 | // several chunks. |
| 60 | func noisyPNG(t *testing.T, w, h int, seed int64) []byte { |
| 61 | t.Helper() |
| 62 | rng := rand.New(rand.NewSource(seed)) |
| 63 | img := image.NewNRGBA(image.Rect(0, 0, w, h)) |
| 64 | rng.Read(img.Pix) |
| 65 | for i := 3; i < len(img.Pix); i += 4 { |
| 66 | img.Pix[i] = 255 |
| 67 | } |
| 68 | var b bytes.Buffer |
| 69 | if err := png.Encode(&b, img); err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | return b.Bytes() |
| 73 | } |
| 74 | |
| 75 | // brokenIDAT is a PNG whose signature, header and chunk checksums are |
| 76 | // sound but whose image data is not a zlib stream: it passes every check |
| 77 | // short of decoding the pixels. |
| 78 | func brokenIDAT(t *testing.T) []byte { |
| 79 | t.Helper() |
| 80 | data := capturePNG(t, 40, 30, 9) |
| 81 | out := append([]byte(nil), data[:8]...) |
| 82 | for i := 8; i < len(data); { |
| 83 | n := int(binary.BigEndian.Uint32(data[i:])) |
| 84 | kind := data[i+4 : i+8] |
| 85 | body := append([]byte(nil), data[i+8:i+8+n]...) |
| 86 | if string(kind) == "IDAT" { |
| 87 | for j := range body { |
| 88 | body[j] = 0xA5 |
| 89 | } |
| 90 | } |
| 91 | var head [8]byte |
| 92 | binary.BigEndian.PutUint32(head[:], uint32(n)) |
| 93 | copy(head[4:], kind) |
| 94 | out = append(out, head[:]...) |
| 95 | out = append(out, body...) |
| 96 | var sum [4]byte |
| 97 | binary.BigEndian.PutUint32(sum[:], crc32.ChecksumIEEE(append(append([]byte(nil), kind...), body...))) |
| 98 | out = append(out, sum[:]...) |
| 99 | i += 12 + n |
| 100 | } |
| 101 | if _, err := png.DecodeConfig(bytes.NewReader(out)); err != nil { |
| 102 | t.Fatalf("the broken PNG's header does not read: %v", err) |
| 103 | } |
| 104 | if _, err := png.Decode(bytes.NewReader(out)); err == nil { |
| 105 | t.Fatal("the broken PNG decodes") |
| 106 | } |
| 107 | return out |
| 108 | } |
| 109 | |
| 110 | func shaOf(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } |
| 111 | |
| 112 | // renderChunks are a capture's render_file chunks for the step's attempt. |
| 113 | func renderChunks(s stepRecord, attempt int64, id string, data []byte) []wire.RenderFile { |
| 114 | total := (len(data) + wire.RenderFileChunk - 1) / wire.RenderFileChunk |
| 115 | var out []wire.RenderFile |
| 116 | for i := 0; i < total; i++ { |
| 117 | part := data[i*wire.RenderFileChunk : min(len(data), (i+1)*wire.RenderFileChunk)] |
| 118 | out = append(out, wire.RenderFile{TaskID: s.TaskID, StepID: s.ID, Attempt: attempt, CaptureID: id, Index: i, Total: total, Size: int64(len(data)), SHA256: shaOf(data), Data: base64.StdEncoding.EncodeToString(part)}) |
| 119 | } |
| 120 | return out |
| 121 | } |
| 122 | |
| 123 | func (r *hkRig) renderFile(l Lease, f wire.RenderFile) error { |
| 124 | return r.tx(func(tx *txn) error { return tx.renderFile(l, &f) }) |
| 125 | } |
| 126 | |
| 127 | // uploadCapture sends every chunk of a capture, each accepted. |
| 128 | func (r *hkRig) uploadCapture(l Lease, s stepRecord, id string, data []byte) { |
| 129 | r.t.Helper() |
| 130 | for _, f := range renderChunks(s, s.Attempt, id, data) { |
| 131 | if err := r.renderFile(l, f); err != nil { |
| 132 | r.t.Fatalf("chunk %d of %s: %v", f.Index, id, err) |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | func capture(id string, data []byte, digest string) wire.DesignCapture { |
| 138 | return wire.DesignCapture{ID: id, SHA256: shaOf(data), TreeDigest: digest} |
| 139 | } |
| 140 | |
| 141 | // designRunning is a Patrix exploration made by Design whose attempt has |
| 142 | // started and reported its candidate. |
| 143 | func designRunning(t *testing.T) (*hkRig, Lease, specialistRecord, string, stepRecord) { |
| 144 | r, l, _ := grantRig(t) |
| 145 | // The direction card reads the person's runners (previews). |
| 146 | r.exec("CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, role text, label text, removing_at datetime, tainted_at datetime, revoked_at datetime)") |
| 147 | r.exec("INSERT INTO runners(id, person, role) VALUES ('RUNNER1', ?, ?)", paul, wire.RolePrimary) |
| 148 | for k, w := range map[string]string{"work.explore.build_note": "%s said which option to build in their own words: %s"} { |
| 149 | words := r.s.authority.Copy |
| 150 | k, w := k, w |
| 151 | r.s.authority.Copy = func(key string) string { |
| 152 | if key == k { |
| 153 | return w |
| 154 | } |
| 155 | return words(key) |
| 156 | } |
| 157 | } |
| 158 | sp := r.active(l, "Patrix", "p_patrix") |
| 159 | task, s := r.runningDesign(l, sp, wire.KindExplore) |
| 160 | r.report(l, s, wire.StepReport{State: wire.StepRunning, BaseSHA: strings.Repeat("b", 40), CandidateSHA: candidateSHA}) |
| 161 | return r, l, sp, task, r.stepNow(s.ID) |
| 162 | } |
| 163 | |
| 164 | // done reports the Design attempt done and pushed with these options. |
| 165 | func (r *hkRig) done(l Lease, s stepRecord, opts []wire.DesignOption) { |
| 166 | r.t.Helper() |
| 167 | r.report(l, s, wire.StepReport{State: wire.StepDone, BaseSHA: strings.Repeat("b", 40), CandidateSHA: candidateSHA, Pushed: true, Termination: true, Options: opts}) |
| 168 | } |
| 169 | |
| 170 | // files are the task files of the step, by capture id. |
| 171 | func (r *hkRig) files(stepID string) map[string]taskFileRecord { |
| 172 | r.t.Helper() |
| 173 | var rows []taskFileRecord |
| 174 | r.must(r.s.db.G.Where("step_id = ?", stepID).Find(&rows).Error) |
| 175 | out := map[string]taskFileRecord{} |
| 176 | for _, f := range rows { |
| 177 | out[f.ImageID+"#"+itoa64(f.Attempt)] = f |
| 178 | } |
| 179 | return out |
| 180 | } |
| 181 | |
| 182 | // keptCount counts the step's kept files, and every file's bytes left. |
| 183 | func (r *hkRig) keptCount(stepID string) (kept, all, chunks int64) { |
| 184 | kept = r.count("SELECT count(*) FROM chat_task_files WHERE step_id = ? AND kept = ?", stepID, true) |
| 185 | all = r.count("SELECT count(*) FROM chat_task_files WHERE step_id = ?", stepID) |
| 186 | chunks = r.count("SELECT count(*) FROM chat_task_file_data WHERE file_id IN (SELECT id FROM chat_task_files WHERE step_id = ?)", stepID) |
| 187 | return |
| 188 | } |
| 189 | |
| 190 | func (r *hkRig) stepDesign(task, stepID string) *wire.StepDesign { |
| 191 | r.t.Helper() |
| 192 | v, err := r.s.Task(r.ctx, paul, task) |
| 193 | r.must(err) |
| 194 | for _, s := range v.Steps { |
| 195 | if s.ID == stepID { |
| 196 | return s.Design |
| 197 | } |
| 198 | } |
| 199 | r.t.Fatalf("no step %s", stepID) |
| 200 | return nil |
| 201 | } |
| 202 | |
| 203 | // nothingKept: no file of the step kept or left, and no options. |
| 204 | func (r *hkRig) nothingKept(task, stepID, why string) { |
| 205 | r.t.Helper() |
| 206 | if kept, all, chunks := r.keptCount(stepID); kept != 0 || all != 0 || chunks != 0 { |
| 207 | r.t.Fatalf("%s: kept %d, files %d, chunks %d", why, kept, all, chunks) |
| 208 | } |
| 209 | if d := r.stepDesign(task, stepID); d != nil { |
| 210 | r.t.Fatalf("%s: options shown %+v", why, d) |
| 211 | } |
| 212 | if s := r.stepNow(stepID); s.DesignOptions != "" || s.State != wire.StepDone { |
| 213 | r.t.Fatalf("%s: step %s %q", why, s.State, s.DesignOptions) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // TestDesignCapturesKeptByTheReport: staged chunks are never served; the |
| 218 | // report keeps the captures it names, by option and in its order, with |
| 219 | // their tree digest and pixel size, and drops what it does not name. |
| 220 | // Only kept files are served, under their own task. |
| 221 | func TestDesignCapturesKeptByTheReport(t *testing.T) { |
| 222 | r, l, _, task, s := designRunning(t) |
| 223 | calm1, calm2, bold := capturePNG(t, 390, 844, 1), capturePNG(t, 1440, 900, 2), capturePNG(t, 390, 2000, 3) |
| 224 | // The first through the runner frame's own path (Apply). |
| 225 | for i, f := range renderChunks(s, s.Attempt, "1-work-1.png", calm1) { |
| 226 | frame, err := wire.NewFrame("c"+itoa64(int64(900+i)), wire.FrameRenderFile, f) |
| 227 | r.must(err) |
| 228 | r.must(r.s.Apply(r.ctx, l, frame, &f)) |
| 229 | } |
| 230 | r.uploadCapture(l, s, "1-work-2.png", calm2) |
| 231 | r.uploadCapture(l, s, "2-work-1.png", bold) |
| 232 | r.uploadCapture(l, s, "2-base-1.png", capturePNG(t, 20, 20, 4)) |
| 233 | staged := r.files(s.ID) |
| 234 | if len(staged) != 4 || !staged["1-work-1.png#1"].Complete || staged["1-work-1.png#1"].Kept || staged["1-work-1.png#1"].Source != taskFileRender { |
| 235 | t.Fatalf("staged %+v", staged) |
| 236 | } |
| 237 | if _, _, err := r.s.TaskFile(r.ctx, paul, task, staged["1-work-1.png#1"].ID); !errors.Is(err, ErrNotFound) { |
| 238 | t.Fatalf("a staged capture is served: %v", err) |
| 239 | } |
| 240 | opts := []wire.DesignOption{ |
| 241 | {Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-2.png", calm2, digestWork), capture("1-work-1.png", calm1, digestWork)}}, |
| 242 | {Name: "Bold", Captures: []wire.DesignCapture{capture("2-work-1.png", bold, digestWork)}}, |
| 243 | {Name: "Plain"}, |
| 244 | } |
| 245 | r.done(l, s, opts) |
| 246 | if kept, all, _ := r.keptCount(s.ID); kept != 3 || all != 3 { |
| 247 | t.Fatalf("kept %d of %d", kept, all) |
| 248 | } |
| 249 | files := r.files(s.ID) |
| 250 | if f := files["1-work-2.png#1"]; !f.Kept || f.Option != "Calm" || f.TreeDigest != digestWork || f.Width != 1440 || f.Height != 900 || f.MediaType != "image/png" { |
| 251 | t.Fatalf("kept capture %+v", f) |
| 252 | } |
| 253 | if _, ok := files["2-base-1.png#1"]; ok { |
| 254 | t.Fatal("an unnamed capture was kept") |
| 255 | } |
| 256 | d := r.stepDesign(task, s.ID) |
| 257 | if d == nil || d.Attempt != 1 || len(d.Options) != 3 || d.Options[0].Name != "Calm" || d.Options[1].Name != "Bold" || d.Options[2].Name != "Plain" || len(d.Options[2].Captures) != 0 { |
| 258 | t.Fatalf("design view %+v", d) |
| 259 | } |
| 260 | if c := d.Options[0].Captures; len(c) != 2 || c[0].CaptureID != "1-work-2.png" || c[1].CaptureID != "1-work-1.png" || c[0].ID != files["1-work-2.png#1"].ID || c[0].Width != 1440 || c[0].Height != 900 || c[0].Size != int64(len(calm2)) { |
| 261 | t.Fatalf("Calm's captures %+v", c) |
| 262 | } |
| 263 | name, data, err := r.s.TaskFile(r.ctx, paul, task, files["2-work-1.png#1"].ID) |
| 264 | if err != nil || name != "2-work-1.png" || !bytes.Equal(data, bold) { |
| 265 | t.Fatalf("served %q %d bytes %v", name, len(data), err) |
| 266 | } |
| 267 | // Under another task's route, a kept capture is not found; nor is it |
| 268 | // for someone who is not a current member. |
| 269 | other := r.plainTask(l, "tk_other_task") |
| 270 | if _, _, err := r.s.TaskFile(r.ctx, paul, other.TaskID, files["2-work-1.png#1"].ID); !errors.Is(err, ErrNotFound) { |
| 271 | t.Fatalf("served under another task: %v", err) |
| 272 | } |
| 273 | current := r.s.authority.CurrentPerson |
| 274 | r.s.authority.CurrentPerson = func(context.Context, *gorm.DB) error { return ErrForbidden } |
| 275 | if _, _, err := r.s.TaskFile(r.ctx, "stranger@example.com", task, files["2-work-1.png#1"].ID); !errors.Is(err, ErrForbidden) { |
| 276 | t.Fatalf("served to someone not on the team: %v", err) |
| 277 | } |
| 278 | r.s.authority.CurrentPerson = current |
| 279 | } |
| 280 | |
| 281 | // TestDesignRenderFileRefused: a chunk is staged only from the runner the |
| 282 | // Design step runs on, for its current attempt while it runs, at |
| 283 | // protocol 38, bound to the task's maker, valid, in order, within the |
| 284 | // capture bound and the declared size and hash; anything else is refused |
| 285 | // and stages nothing. |
| 286 | func TestDesignRenderFileRefused(t *testing.T) { |
| 287 | r, l, _, task, s := designRunning(t) |
| 288 | data := noisyPNG(t, 400, 300, 5) |
| 289 | good := renderChunks(s, s.Attempt, "1-work-1.png", data) |
| 290 | if len(good) < 2 { |
| 291 | t.Fatalf("want a capture of several chunks, got %d", len(good)) |
| 292 | } |
| 293 | refused := func(why string, l Lease, f wire.RenderFile) { |
| 294 | t.Helper() |
| 295 | if err := r.renderFile(l, f); !errors.Is(err, ErrRefused) { |
| 296 | t.Fatalf("%s: %v", why, err) |
| 297 | } |
| 298 | } |
| 299 | old := l |
| 300 | old.Protocol = wire.ProtocolDesign - 1 |
| 301 | refused("below protocol 38", old, good[0]) |
| 302 | bad := good[0] |
| 303 | bad.Total++ |
| 304 | refused("a chunk the wire refuses", l, bad) |
| 305 | noStep := good[0] |
| 306 | noStep.StepID = "s_missing" |
| 307 | if err := r.renderFile(l, noStep); !errors.Is(err, ErrRefused) { |
| 308 | t.Fatalf("no such step: %v", err) |
| 309 | } |
| 310 | other := l |
| 311 | other.Runner.RunnerID = "RUNNER2" |
| 312 | refused("another runner", other, good[0]) |
| 313 | someone := l |
| 314 | someone.Runner.Person = "someone@example.com" |
| 315 | refused("another person", someone, good[0]) |
| 316 | r.exec("UPDATE chat_steps SET withdrawn = ? WHERE id = ?", true, s.ID) |
| 317 | refused("a withdrawn attempt", l, good[0]) |
| 318 | r.exec("UPDATE chat_steps SET withdrawn = ? WHERE id = ?", false, s.ID) |
| 319 | stale := renderChunks(s, s.Attempt+1, "1-work-1.png", data)[0] |
| 320 | refused("another attempt", l, stale) |
| 321 | refused("out of order", l, good[1]) |
| 322 | if len(good) < 3 { |
| 323 | t.Fatalf("want a capture of three chunks or more, got %d", len(good)) |
| 324 | } |
| 325 | plain := r.plainTask(l, "tk_plain_task") |
| 326 | r.report(l, plain, wire.StepReport{State: wire.StepRunning}) |
| 327 | refused("an unbound Engineering step", l, renderChunks(r.stepNow(plain.ID), 1, "1-work-1.png", data)[0]) |
| 328 | for i, f := range good { |
| 329 | if i == len(good)-2 { |
| 330 | // One chunk skipped: the last cannot come before it. |
| 331 | refused("a chunk skipped", l, good[len(good)-1]) |
| 332 | } |
| 333 | if i == len(good)-1 { |
| 334 | break |
| 335 | } |
| 336 | if err := r.renderFile(l, f); err != nil { |
| 337 | t.Fatal(err) |
| 338 | } |
| 339 | } |
| 340 | refused("a chunk again", l, good[0]) |
| 341 | last := good[len(good)-1] |
| 342 | tampered := last |
| 343 | raw, _ := base64.StdEncoding.DecodeString(last.Data) |
| 344 | raw[0] ^= 0xFF |
| 345 | tampered.Data = base64.StdEncoding.EncodeToString(raw) |
| 346 | refused("the whole does not match its hash", l, tampered) |
| 347 | if f := r.files(s.ID)["1-work-1.png#1"]; f.Complete { |
| 348 | t.Fatal("a capture that does not match its hash completed") |
| 349 | } |
| 350 | // The thirteenth capture of an attempt is refused. |
| 351 | for n := 2; n <= wire.MaxDesignCaptures; n++ { |
| 352 | r.uploadCapture(l, s, "2-work-"+itoa64(int64(n))+".png", capturePNG(t, 4, 4, uint8(n))) |
| 353 | } |
| 354 | refused("a thirteenth capture", l, renderChunks(s, s.Attempt, "3-work-1.png", capturePNG(t, 4, 4, 99))[0]) |
| 355 | // The task cancelled: nothing more is staged. |
| 356 | r.exec("UPDATE chat_tasks SET cancel_requested = ? WHERE id = ?", true, task) |
| 357 | r.exec("DELETE FROM chat_task_files WHERE step_id = ? AND image_id = ?", s.ID, "2-work-2.png") |
| 358 | refused("the task cancelled", l, renderChunks(s, s.Attempt, "3-work-2.png", capturePNG(t, 4, 4, 98))[0]) |
| 359 | r.exec("UPDATE chat_tasks SET cancel_requested = ? WHERE id = ?", false, task) |
| 360 | // A step that is not running stages nothing. |
| 361 | r.exec("UPDATE chat_steps SET state = ? WHERE id = ?", wire.StepQueued, s.ID) |
| 362 | refused("a queued step", l, renderChunks(s, s.Attempt, "3-work-2.png", capturePNG(t, 4, 4, 98))[0]) |
| 363 | r.exec("UPDATE chat_steps SET state = ? WHERE id = ?", wire.StepRunning, s.ID) |
| 364 | // A step bound to anything but the task's maker stages nothing. |
| 365 | r.exec("UPDATE chat_tasks SET maker_specialist_id = ? WHERE id = ?", "sp_other", task) |
| 366 | refused("not the task's maker", l, renderChunks(s, s.Attempt, "3-work-2.png", capturePNG(t, 4, 4, 98))[0]) |
| 367 | } |
| 368 | |
| 369 | // TestDesignCapturesForeignID: a report naming a capture this attempt |
| 370 | // never sent keeps nothing, not even the ones it did send. |
| 371 | func TestDesignCapturesForeignID(t *testing.T) { |
| 372 | r, l, _, task, s := designRunning(t) |
| 373 | a := capturePNG(t, 30, 30, 1) |
| 374 | r.uploadCapture(l, s, "1-work-1.png", a) |
| 375 | r.done(l, s, []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-1.png", a, digestWork)}}, {Name: "Bold", Captures: []wire.DesignCapture{capture("1-work-2.png", a, digestWork)}}}) |
| 376 | r.nothingKept(task, s.ID, "a foreign capture id") |
| 377 | } |
| 378 | |
| 379 | // TestDesignCapturesIncomplete: a capture whose chunks did not all |
| 380 | // arrive keeps nothing. |
| 381 | func TestDesignCapturesIncomplete(t *testing.T) { |
| 382 | r, l, _, task, s := designRunning(t) |
| 383 | a, b := capturePNG(t, 30, 30, 1), noisyPNG(t, 400, 300, 2) |
| 384 | r.uploadCapture(l, s, "1-work-1.png", a) |
| 385 | chunks := renderChunks(s, s.Attempt, "1-work-2.png", b) |
| 386 | if err := r.renderFile(l, chunks[0]); err != nil { |
| 387 | t.Fatal(err) |
| 388 | } |
| 389 | r.done(l, s, []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-1.png", a, digestWork), capture("1-work-2.png", b, digestWork)}}}) |
| 390 | r.nothingKept(task, s.ID, "an incomplete upload") |
| 391 | } |
| 392 | |
| 393 | // TestDesignCapturesChecked: what the report says must be exactly what |
| 394 | // was staged, and each PNG must decode within the capture bounds: a PNG |
| 395 | // that passes its signature and header but not decoding, one wider than |
| 396 | // a capture can be, one with bytes after its end, a hash that is not the |
| 397 | // file's, tree digests that disagree within one render, options the wire |
| 398 | // refuses. Each keeps nothing. |
| 399 | func TestDesignCapturesChecked(t *testing.T) { |
| 400 | good := func(t *testing.T) []byte { return capturePNG(t, 30, 30, 1) } |
| 401 | for _, c := range []struct { |
| 402 | name string |
| 403 | upload func(t *testing.T) []byte |
| 404 | opts func(data []byte) []wire.DesignOption |
| 405 | }{ |
| 406 | {"not decodable", brokenIDAT, nil}, |
| 407 | {"too wide", func(t *testing.T) []byte { return capturePNG(t, wire.MaxCaptureWidth+1, 2, 1) }, nil}, |
| 408 | {"too tall", func(t *testing.T) []byte { return capturePNG(t, 1, wire.MaxCaptureHeight+1, 1) }, nil}, |
| 409 | {"bytes after the end", func(t *testing.T) []byte { return append(good(t), "<html>"...) }, nil}, |
| 410 | {"another hash", good, func(data []byte) []wire.DesignOption { |
| 411 | return []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{{ID: "1-work-1.png", SHA256: strings.Repeat("0", 64), TreeDigest: digestWork}}}} |
| 412 | }}, |
| 413 | {"digests disagree", good, func(data []byte) []wire.DesignOption { |
| 414 | return []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-1.png", data, digestWork)}}, {Name: "Bold", Captures: []wire.DesignCapture{capture("1-diff-1.png", data, digestBase)}}} |
| 415 | }}, |
| 416 | {"invalid options", good, func(data []byte) []wire.DesignOption { |
| 417 | return []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-1.png", data, digestWork)}}, {Name: "calm"}} |
| 418 | }}, |
| 419 | } { |
| 420 | t.Run(c.name, func(t *testing.T) { |
| 421 | r, l, _, task, s := designRunning(t) |
| 422 | data := c.upload(t) |
| 423 | r.uploadCapture(l, s, "1-work-1.png", data) |
| 424 | r.uploadCapture(l, s, "1-diff-1.png", data) |
| 425 | opts := []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-1.png", data, digestWork)}}} |
| 426 | if c.opts != nil { |
| 427 | opts = c.opts(data) |
| 428 | } |
| 429 | r.done(l, s, opts) |
| 430 | r.nothingKept(task, s.ID, c.name) |
| 431 | }) |
| 432 | } |
| 433 | // A base capture carries the base tree's digest, a diff its work's: |
| 434 | // both kept beside a work capture of the same render. |
| 435 | r, l, _, task, s := designRunning(t) |
| 436 | data := good(t) |
| 437 | for _, id := range []string{"1-work-1.png", "1-diff-1.png", "1-base-1.png"} { |
| 438 | r.uploadCapture(l, s, id, data) |
| 439 | } |
| 440 | r.done(l, s, []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-1.png", data, digestWork), capture("1-diff-1.png", data, digestWork), capture("1-base-1.png", data, digestBase)}}}) |
| 441 | if kept, _, _ := r.keptCount(s.ID); kept != 3 { |
| 442 | t.Fatalf("kept %d of a consistent render", kept) |
| 443 | } |
| 444 | if d := r.stepDesign(task, s.ID); d == nil || len(d.Options[0].Captures) != 3 { |
| 445 | t.Fatalf("design view %+v", d) |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | // TestDesignCapturesRevokedDuringUpload: Design removed while its |
| 450 | // captures arrive: the report's transaction finds no grant, and nothing |
| 451 | // is kept, though the chunks were all staged. |
| 452 | func TestDesignCapturesRevokedDuringUpload(t *testing.T) { |
| 453 | r, l, sp, task, s := designRunning(t) |
| 454 | a := noisyPNG(t, 400, 300, 1) |
| 455 | chunks := renderChunks(s, s.Attempt, "1-work-1.png", a) |
| 456 | if err := r.renderFile(l, chunks[0]); err != nil { |
| 457 | t.Fatal(err) |
| 458 | } |
| 459 | r.revoke(sp.ID) |
| 460 | for _, f := range chunks[1:] { |
| 461 | if err := r.renderFile(l, f); err != nil { |
| 462 | t.Fatal(err) |
| 463 | } |
| 464 | } |
| 465 | r.done(l, r.stepNow(s.ID), []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-1.png", a, digestWork)}}}) |
| 466 | r.nothingKept(task, s.ID, "revoked during the upload") |
| 467 | } |
| 468 | |
| 469 | // TestDesignCapturesMakerChanged: a step that is no longer its task's |
| 470 | // maker keeps nothing, though its captures were staged while it was. |
| 471 | func TestDesignCapturesMakerChanged(t *testing.T) { |
| 472 | r, l, _, task, s := designRunning(t) |
| 473 | a := capturePNG(t, 30, 30, 1) |
| 474 | r.uploadCapture(l, s, "1-work-1.png", a) |
| 475 | r.exec("UPDATE chat_tasks SET maker_specialist_id = ? WHERE id = ?", "sp_other", task) |
| 476 | r.done(l, s, []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-1.png", a, digestWork)}}}) |
| 477 | if kept, all, chunks := r.keptCount(s.ID); kept != 0 || all != 0 || chunks != 0 || r.stepNow(s.ID).DesignOptions != "" { |
| 478 | t.Fatalf("the maker changed: kept %d, files %d, chunks %d", kept, all, chunks) |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | // TestDesignCapturesStaleAttempt: after a failover the step's attempt |
| 483 | // moved on; the old attempt's chunks are refused, its staged captures are |
| 484 | // never kept, even when the new attempt's report names them, and they |
| 485 | // are dropped when the step ends. |
| 486 | func TestDesignCapturesStaleAttempt(t *testing.T) { |
| 487 | r, l, _, task, s := designRunning(t) |
| 488 | a := noisyPNG(t, 400, 300, 1) |
| 489 | old := capturePNG(t, 30, 30, 7) |
| 490 | r.uploadCapture(l, s, "1-work-3.png", old) |
| 491 | chunks := renderChunks(s, 1, "1-work-1.png", a) |
| 492 | if err := r.renderFile(l, chunks[0]); err != nil { |
| 493 | t.Fatal(err) |
| 494 | } |
| 495 | r.report(l, s, wire.StepReport{State: wire.StepRunning, Attempt: 2}) |
| 496 | s = r.stepNow(s.ID) |
| 497 | if s.Attempt != 2 { |
| 498 | t.Fatalf("attempt %d", s.Attempt) |
| 499 | } |
| 500 | if err := r.renderFile(l, chunks[1]); !errors.Is(err, ErrRefused) { |
| 501 | t.Fatalf("a stale attempt's chunk: %v", err) |
| 502 | } |
| 503 | r.uploadCapture(l, s, "1-work-2.png", a) |
| 504 | // Attempt 1's whole capture, named by attempt 2's report. |
| 505 | r.done(l, s, []wire.DesignOption{{Name: "Calm", Captures: []wire.DesignCapture{capture("1-work-3.png", old, digestWork), capture("1-work-2.png", a, digestWork)}}}) |
| 506 | r.nothingKept(task, s.ID, "the old attempt's capture named") |
| 507 | } |
| 508 | |
| 509 | // TestDesignCapturesDroppedOnFailure: a Design attempt that ends any way |
| 510 | // but done keeps nothing it sent. |
| 511 | func TestDesignCapturesDroppedOnFailure(t *testing.T) { |
| 512 | r, l, _, _, s := designRunning(t) |
| 513 | r.uploadCapture(l, s, "1-work-1.png", capturePNG(t, 30, 30, 1)) |
| 514 | r.report(l, s, wire.StepReport{State: wire.StepFailed, Reason: "model_failed", Termination: true}) |
| 515 | if kept, all, chunks := r.keptCount(s.ID); kept != 0 || all != 0 || chunks != 0 { |
| 516 | t.Fatalf("after a failure: kept %d, files %d, chunks %d", kept, all, chunks) |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | // designDirection takes the running Design attempt to done with opts |
| 521 | // (each capture uploaded as a small PNG) and its review to approve: the |
| 522 | // direction card is open. |
| 523 | func (r *hkRig) designDirection(l Lease, task string, s stepRecord, names ...string) cardRecord { |
| 524 | r.t.Helper() |
| 525 | var opts []wire.DesignOption |
| 526 | for i, name := range names { |
| 527 | data := capturePNG(r.t, 20, 20, uint8(i)) |
| 528 | id := itoa64(int64(i+1)) + "-work-1.png" |
| 529 | r.uploadCapture(l, s, id, data) |
| 530 | opts = append(opts, wire.DesignOption{Name: name, Captures: []wire.DesignCapture{capture(id, data, digestWork)}}) |
| 531 | } |
| 532 | r.done(l, s, opts) |
| 533 | var review stepRecord |
| 534 | r.must(r.s.db.G.Where("task_id = ? AND specialist = ?", task, wire.SpecialistReview).Order("idx DESC").First(&review).Error) |
| 535 | r.report(l, review, wire.StepReport{State: wire.StepDone, CandidateSHA: candidateSHA, Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewOtherFamily, Termination: true, Findings: []wire.Finding{}}) |
| 536 | var c cardRecord |
| 537 | r.must(r.s.db.G.Where("task_id = ? AND kind = ? AND state = ?", task, wire.CardDirection, wire.CardOpen).First(&c).Error) |
| 538 | return c |
| 539 | } |
| 540 | |
| 541 | // TestDirectionShowsCapturesAndBuildNeedsANote: the direction shows the |
| 542 | // kept captures by option. With more than one option Build this without |
| 543 | // a note is a card conflict (direction_note) and builds nothing; with a |
| 544 | // note the new task's brief quotes it as the person's own words. |
| 545 | func TestDirectionShowsCapturesAndBuildNeedsANote(t *testing.T) { |
| 546 | r, l, sp, task, s := designRunning(t) |
| 547 | c := r.designDirection(l, task, s, "Calm", "Bold") |
| 548 | v, err := r.s.Task(r.ctx, paul, task) |
| 549 | r.must(err) |
| 550 | d := v.Direction |
| 551 | if d == nil || !d.NoteNeeded || len(d.Options) != 2 || d.Options[1].Name != "Bold" || len(d.Options[1].Captures) != 1 || d.Options[1].Captures[0].CaptureID != "2-work-1.png" { |
| 552 | t.Fatalf("direction %+v", d) |
| 553 | } |
| 554 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceBuild, Revision: c.Revision}); !errors.Is(err, ErrCardConflict) || !errors.Is(err, ErrDirectionNote) { |
| 555 | t.Fatalf("Build without a note: %v", err) |
| 556 | } |
| 557 | if k := r.load(task); k.BuiltAs != "" { |
| 558 | t.Fatalf("built without a note: %s", k.BuiltAs) |
| 559 | } |
| 560 | // The person API says so in its conflict. |
| 561 | h := &HTTP{Store: r.s} |
| 562 | body, _ := json.Marshal(wire.AnswerCard{Choice: wire.ChoiceBuild, Revision: c.Revision}) |
| 563 | route := chi.NewRouteContext() |
| 564 | route.URLParams.Add("id", c.ID) |
| 565 | req := httptest.NewRequest(http.MethodPost, "/cards/"+c.ID+"/answer", bytes.NewReader(body)).WithContext(context.WithValue(r.ctx, chi.RouteCtxKey, route)) |
| 566 | req.Header.Set("Content-Type", "application/json") |
| 567 | w := httptest.NewRecorder() |
| 568 | h.answer(w, req, personapi.PersonPrincipal{Address: paul, CredentialID: "cr_phone"}) |
| 569 | var conflict wire.CardConflict |
| 570 | if w.Code != http.StatusConflict || json.Unmarshal(w.Body.Bytes(), &conflict) != nil || conflict.Code != wire.ConflictDirectionNote || conflict.CopyKey != "api."+wire.ConflictDirectionNote || conflict.Card.ID != c.ID || conflict.Card.State != wire.CardOpen { |
| 571 | t.Fatalf("person API: %d %s", w.Code, w.Body.String()) |
| 572 | } |
| 573 | note := "The \"Bold\" one, with the calm header." |
| 574 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceBuild, Note: note, Revision: c.Revision}); err != nil { |
| 575 | t.Fatal(err) |
| 576 | } |
| 577 | built := r.load(r.load(task).BuiltAs) |
| 578 | name, _ := DisplayName(paul) |
| 579 | if want := name + " said which option to build in their own words: " + wire.QuotedData(note); !strings.HasSuffix(built.Brief, want) || built.MakerSpecialistID != sp.ID { |
| 580 | t.Fatalf("brief %q", built.Brief) |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | // TestBuildNoteFitsTheBrief: a long exploration brief is cut, never the |
| 585 | // person's note. |
| 586 | func TestBuildNoteFitsTheBrief(t *testing.T) { |
| 587 | r, l, _, task, s := designRunning(t) |
| 588 | r.exec("UPDATE chat_tasks SET brief = ? WHERE id = ?", strings.Repeat("x", wire.MaxTaskBrief), task) |
| 589 | c := r.designDirection(l, task, s, "Calm", "Bold") |
| 590 | note := strings.Repeat("Bold. ", 150) |
| 591 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceBuild, Note: note, Revision: c.Revision}); err != nil { |
| 592 | t.Fatal(err) |
| 593 | } |
| 594 | built := r.load(r.load(task).BuiltAs) |
| 595 | if len(built.Brief) > wire.MaxTaskBrief || !strings.HasSuffix(built.Brief, wire.QuotedData(strings.TrimSpace(note))) { |
| 596 | t.Fatalf("brief %d bytes, ends %q", len(built.Brief), built.Brief[max(0, len(built.Brief)-80):]) |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | // TestBuildNoteThatCannotFit: a note whose quoting grows past what a |
| 601 | // brief holds builds nothing (it is never cut). |
| 602 | func TestBuildNoteThatCannotFit(t *testing.T) { |
| 603 | r, l, _, task, s := designRunning(t) |
| 604 | c := r.designDirection(l, task, s, "Calm", "Bold") |
| 605 | note := strings.Repeat("\x01", wire.MaxDirectionNote) |
| 606 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceBuild, Note: note, Revision: c.Revision}); !errors.Is(err, ErrInvalid) { |
| 607 | t.Fatalf("an oversized note: %v", err) |
| 608 | } |
| 609 | if k := r.load(task); k.BuiltAs != "" { |
| 610 | t.Fatalf("built %s", k.BuiltAs) |
| 611 | } |
| 612 | var open cardRecord |
| 613 | r.must(r.s.db.G.Where("id = ?", c.ID).First(&open).Error) |
| 614 | if open.State != wire.CardOpen { |
| 615 | t.Fatalf("card %s", open.State) |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | // TestBuildOneOptionNeedsNoNote: one option, or none, needs no note. |
| 620 | func TestBuildOneOptionNeedsNoNote(t *testing.T) { |
| 621 | for _, names := range [][]string{{"Calm"}, nil} { |
| 622 | r, l, _, task, s := designRunning(t) |
| 623 | c := r.designDirection(l, task, s, names...) |
| 624 | v, err := r.s.Task(r.ctx, paul, task) |
| 625 | r.must(err) |
| 626 | if v.Direction == nil || v.Direction.NoteNeeded || len(v.Direction.Options) != len(names) { |
| 627 | t.Fatalf("direction %+v", v.Direction) |
| 628 | } |
| 629 | if len(names) == 0 && r.makerStep(task).DesignOptions != "" { |
| 630 | t.Fatalf("no options stored as %q", r.makerStep(task).DesignOptions) |
| 631 | } |
| 632 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceBuild, Revision: c.Revision}); err != nil { |
| 633 | t.Fatalf("%d options: %v", len(names), err) |
| 634 | } |
| 635 | if built := r.load(r.load(task).BuiltAs); strings.Contains(built.Brief, "said which option") { |
| 636 | t.Fatalf("a note line with no note: %q", built.Brief) |
| 637 | } |
| 638 | } |
| 639 | } |
| 640 | |