package thintest import ( "bytes" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "image" "image/color" "image/gif" "image/png" "io" "net/http" "slices" "strings" "testing" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // A Research step's results (Research spec ยง5, slice R3): kept images // arrive in research_file chunks bound to the running attempt, before // the done report; the report's findings, fetch log and kept images are // checked again and stored; the task's read shape shows them and the // person API serves the images under the attachment rules. // pngOf is a w by h PNG. func pngOf(t *testing.T, w, h int) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, w, h)) for x := range w { for y := range h { img.Set(x, y, color.RGBA{uint8(x * 40), uint8(y * 60), 120, 255}) } } var b bytes.Buffer if err := png.Encode(&b, img); err != nil { t.Fatal(err) } return b.Bytes() } func sum(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } // fileChunks splits data into parts research_file chunks. func fileChunks(d *wire.DispatchCommand, image string, data []byte, parts int) []wire.ResearchFile { var out []wire.ResearchFile size := (len(data) + parts - 1) / parts for i := range parts { end := min(len(data), (i+1)*size) out = append(out, wire.ResearchFile{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, ImageID: image, Index: i, Total: parts, Size: int64(len(data)), SHA256: sum(data), Data: base64.StdEncoding.EncodeToString(data[i*size : end])}) } return out } // file sends one research_file chunk and waits for its ack: refused or // not, a chunk is acked (refused ones are dropped). func (r *toolRig) file(id string, f wire.ResearchFile) { r.t.Helper() if err := r.runner.Send(r.ctx, id, wire.FrameResearchFile, f); err != nil { r.t.Fatal(err) } for { fr, body, err := r.runner.Next(r.ctx) if err != nil { r.t.Fatal(err) } if a, ok := body.(*wire.Ack); ok && fr.Type == wire.FrameAck && a.ID == id { return } if fr.Type != wire.FrameAck { r.held = append(r.held, heldFrame{fr, body, r.runner.Received[len(r.runner.Received)-1]}) } } } func (r *toolRig) sendFile(key string, chunks []wire.ResearchFile) { r.t.Helper() for i, c := range chunks { r.file(key+"-"+itoa(i), c) } } // keptFile is a complete stored file for the step's image: its id, or "". func (r *toolRig) completeFile(step, image string) bool { r.t.Helper() return r.rows("SELECT count(*) FROM chat_task_files WHERE step_id = ? AND image_id = ? AND complete = 1", step, image) == 1 } // runningResearch records and starts a task whose Research is // dispatched and reported running. func (r *toolRig) runningResearch(key string) *wire.DispatchCommand { r.t.Helper() id := r.namedTask(key) r.research(key+"-r", id) r.begin(key+"-start", id) d := r.nextDispatch() if d.Specialist != wire.SpecialistResearch { r.t.Fatalf("not Research %+v", d) } r.step(key+"-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning}) return d } func fetchLog() []wire.ResearchFetch { return []wire.ResearchFetch{ {SourceID: "s1", Origin: wire.ResearchOriginPerson, URL: "https://shop.example.com/", Address: "81.2.69.50", Status: 200, Type: "text/html", Bytes: 5120, SHA256: strings.Repeat("a", 64), Millis: 120}, {SourceID: "s2", Origin: wire.ResearchOriginPerson, URL: "https://shop.example.com/hours", Hops: []wire.ResearchHop{{URL: "https://shop.example.com/opening-hours", Address: "81.2.69.50", Status: 200}}, Address: "81.2.69.50", Status: 200, Type: "text/html", Bytes: 2048, Millis: 80}, {SourceID: "s3", Origin: "expanded", Parent: "s1", URL: "https://shop.example.com/logo.png", Address: "81.2.69.50", Status: 200, Type: "image/png", Bytes: 300, Millis: 30}, {SourceID: "s4", Origin: "expanded", Parent: "s1", URL: "https://cdn.example.net/x.webp", Millis: 1, Reason: "type_refused"}, } } func findingsJSON(t *testing.T, f wire.ResearchFindings) json.RawMessage { t.Helper() raw, err := json.Marshal(f) if err != nil { t.Fatal(err) } return raw } func goodFindings(images ...string) wire.ResearchFindings { if images == nil { images = []string{} } return wire.ResearchFindings{Summary: "A barber shop on Main Street; navy and cream.", Facts: []wire.ResearchFact{{Label: "Colours", Value: "Navy #1B2A4A and cream", Sources: []string{"s1"}}, {Label: "Hours", Value: "Tue to Sat, 9 to 6", Sources: []string{"s2", "s1"}}}, Images: images, Gaps: []string{"No phone number found"}} } func keptRecord(id string, data []byte, w, h int) wire.ResearchImage { return wire.ResearchImage{ID: id, SourceID: "s3", Role: wire.ImageRoleLogo, Description: "The shop's logo.", SHA256: sum(data), Size: int64(len(data)), Width: w, Height: h} } // TestResearchFileRefused: chunks are kept only from the runner the // running step is placed on, for its current attempt, in order, within // bounds; a file whose hash, size or type does not check is never // complete. Every refused chunk is acked and dropped. func TestResearchFileRefused(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() id := r.shopTask("a") r.research("a-r", id) r.begin("a-start", id) d := r.nextDispatch() img := pngOf(t, 4, 3) // Not running yet. r.sendFile("early", fileChunks(d, "img1", img, 1)) if r.rows("SELECT count(*) FROM chat_task_files") != 0 { t.Fatal("a chunk before the step ran") } r.step("a-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning}) refused := func(name string, chunks []wire.ResearchFile) { t.Helper() r.sendFile(name, chunks) if r.completeFile(d.StepID, chunks[0].ImageID) { t.Fatalf("%s: kept", name) } } stale := fileChunks(d, "img1", img, 1) stale[0].Attempt = 2 refused("stale", stale) other := fileChunks(d, "img1", img, 1) other[0].TaskID = "tk_other" refused("other-task", other) // Out of order: the second chunk first, then the first and second. two := fileChunks(d, "img2", img, 2) refused("order", []wire.ResearchFile{two[1], two[0]}) if r.rows("SELECT count(*) FROM chat_task_file_data") != 1 { t.Fatalf("%d chunks kept", r.rows("SELECT count(*) FROM chat_task_file_data")) } r.file("order-again", two[1]) if !r.completeFile(d.StepID, "img2") { t.Fatal("the file in order was not kept") } // A chunk that skips one is refused too; the file goes on in order. three := fileChunks(d, "img20", img, 3) r.sendFile("skip", []wire.ResearchFile{three[0], three[2]}) if n := r.rows("SELECT count(*) FROM chat_task_file_data WHERE file_id IN (SELECT id FROM chat_task_files WHERE image_id = 'img20')"); n != 1 { t.Fatalf("%d chunks after a skip", n) } r.sendFile("skip-again", three[1:]) if !r.completeFile(d.StepID, "img20") { t.Fatal("the file in order was not kept") } // Bounds: each first chunk of two would be kept as a partial file if // its bound did not refuse it. none := func(name string, f wire.ResearchFile) { t.Helper() r.file(name, f) if n := r.rows("SELECT count(*) FROM chat_task_files WHERE image_id = 'img3'"); n != 0 { t.Fatalf("%s: kept %d", name, n) } } half := fileChunks(d, "img3", img, 2)[0] big := half big.Size = wire.MaxKeptImageBytes + 1 none("size", big) many := half many.Total = wire.MaxResearchFileChunks + 1 none("total", many) fat := half fat.Data, fat.Size = base64.StdEncoding.EncodeToString(make([]byte, wire.ResearchFileChunk+1)), 2*(wire.ResearchFileChunk+1) none("chunk", fat) badID := half badID.ImageID = "../x" none("id", badID) garbled := half garbled.Data = "*not base64*" none("base64", garbled) short := fileChunks(d, "img3", img, 1) short[0].Size++ refused("short", short) // The hash. hashed := fileChunks(d, "img4", img, 2) for i := range hashed { hashed[i].SHA256 = strings.Repeat("b", 64) } refused("hash", hashed) // Not a PNG (a GIF with a matching hash). var g bytes.Buffer _ = gif.Encode(&g, image.NewPaletted(image.Rect(0, 0, 2, 2), []color.Color{color.Black, color.White}), nil) refused("gif", fileChunks(d, "img5", g.Bytes(), 1)) refused("text", fileChunks(d, "img6", []byte(""), 1)) refused("trailing", fileChunks(d, "img21", append(slices.Clone(img), []byte("")...), 1)) // Another runner (another person's primary) cannot send the step's. b := personToolRigAt(t, r, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) b.sendFile("foreign", fileChunks(d, "img7", img, 1)) if r.rows("SELECT count(*) FROM chat_task_files WHERE image_id = 'img7'") != 0 { t.Fatal("a chunk from another runner") } // At most eight images per attempt (img2, img20 and the partial img4 // so far). for i := 10; i < 15; i++ { r.sendFile("n"+itoa(i), fileChunks(d, "img"+itoa(i), img, 1)) } refused("ninth", fileChunks(d, "img16", img, 1)) if n := r.rows("SELECT count(*) FROM chat_task_files WHERE step_id = ?", d.StepID); n != wire.MaxKeptImages { t.Fatalf("%d files", n) } if !strings.Contains(r.inst.Logs(), "research_file") { t.Fatal("refusals are not logged") } // The step's next attempt: the old attempt's chunks are refused. if n := r.rows("SELECT count(*) FROM chat_task_files WHERE complete = 1"); n != 7 { t.Fatalf("%d complete files", n) } r.step("a-next", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 2, State: wire.StepRunning}) refused("late", fileChunks(d, "img8", img, 1)) // An ended step takes none. r.step("a-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 2, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) ended := fileChunks(d, "img9", img, 1) ended[0].Attempt = 2 refused("ended", ended) } // TestResearchDoneStoresFindings: a done report's findings, fetch log and // kept images are stored; Engineering goes; the task shows them and the // person API serves the image as an attachment is served. func TestResearchDoneStoresFindings(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() d := r.runningResearch("a") logo := pngOf(t, 5, 4) r.sendFile("logo", fileChunks(d, "img1", logo, 3)) extra := pngOf(t, 2, 2) r.sendFile("extra", fileChunks(d, "img2", extra, 1)) f := goodFindings("img1") r.step("a-done", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Termination: true, Summary: "Read four pages.", Research: &wire.ResearchResult{Findings: findingsJSON(t, f), Fetches: fetchLog(), Images: []wire.ResearchImage{keptRecord("img1", logo, 5, 4)}}}) if e := r.nextDispatch(); e.Specialist != wire.SpecialistEngineering || e.TaskID != d.TaskID { t.Fatalf("Engineering after Research %+v", e) } var stored string if err := r.inst.DB.Writer().QueryRow("SELECT findings FROM chat_research WHERE step_id = ? AND attempt = 1 AND task_id = ?", d.StepID, d.TaskID).Scan(&stored); err != nil { t.Fatal(err) } if stored != string(findingsJSON(t, f)) { t.Fatalf("stored findings %s", stored) } if n := r.rows("SELECT count(*) FROM chat_research_fetches WHERE step_id = ? AND attempt = 1", d.StepID); n != 4 { t.Fatalf("%d fetch lines", n) } if n := r.rows("SELECT count(*) FROM chat_task_files WHERE step_id = ? AND kept = 1", d.StepID); n != 1 { t.Fatalf("%d kept", n) } // img2 was sent but never reported: it is not kept, nor its bytes. if n := r.rows("SELECT count(*) FROM chat_task_files WHERE image_id = 'img2'"); n != 0 { t.Fatalf("an unreported image stays (%d)", n) } k := r.task(d.TaskID) s := stepsOf(k, wire.SpecialistResearch)[0] v := s.Research if v == nil || v.Attempt != 1 || v.Findings.Summary != f.Summary || len(v.Findings.Facts) != 2 || !slices.Equal(v.Findings.Images, []string{"img1"}) || len(v.Fetches) != 4 || v.Fetches[1].Hops[0] != (wire.ResearchHop{URL: "https://shop.example.com/opening-hours", Address: "81.2.69.50", Status: 200}) || v.Fetches[3].Reason != "type_refused" { t.Fatalf("read shape %+v", v) } if len(v.Images) != 1 || v.Images[0].ImageID != "img1" || v.Images[0].ID == "" || v.Images[0].Width != 5 || v.Images[0].Role != wire.ImageRoleLogo || v.Images[0].Size != int64(len(logo)) { t.Fatalf("images %+v", v.Images) } for _, other := range stepsOf(k, wire.SpecialistEngineering) { if other.Research != nil { t.Fatal("Engineering carries research") } } // The image, as an attachment is served. path := "/api/v1/tasks/" + d.TaskID + "/files/" + v.Images[0].ID body, h := r.fetch(r.client.Token, path, 200) if !bytes.Equal(body, logo) || h.Get("Content-Type") != "image/png" || h.Get("X-Content-Type-Options") != "nosniff" || !strings.Contains(h.Get("Content-Security-Policy"), "sandbox") || !strings.HasPrefix(h.Get("Content-Disposition"), "inline") { t.Fatalf("served %d bytes %v", len(body), h) } // A teammate reads the task, so the image too; nobody reads it under // another task, or an image that was not kept. m := personToolRigAt(t, r, "member@example.com", equipo.RoleMember, wire.ProtocolCurrent) r.fetch(m.client.Token, path, 200) other := r.namedTask("b") r.fetch(r.client.Token, "/api/v1/tasks/"+other+"/files/"+v.Images[0].ID, 404) r.fetch(r.client.Token, "/api/v1/tasks/"+d.TaskID+"/files/tf_nothing", 404) r.fetch("", path, 401) } // fetch GETs path with a bearer token and wants status. func (r *toolRig) fetch(token, path string, want int) ([]byte, http.Header) { r.t.Helper() req, _ := http.NewRequestWithContext(r.ctx, "GET", r.inst.URL+path, nil) if token != "" { req.Header.Set("Authorization", "Bearer "+token) } res, err := http.DefaultClient.Do(req) if err != nil { r.t.Fatal(err) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) if res.StatusCode != want { r.t.Fatalf("GET %s: %d, want %d: %.200s", path, res.StatusCode, want, raw) } return raw, res.Header } // TestResearchDoneFallsBack: findings that cite a source not in the log // (or only on a line that did not check), or an image not kept, or a // report with no Research payload, or a fetch log too long, are stored // as "Research ended without findings" // and Engineering still goes; images that do not check are dropped, // never stored. func TestResearchDoneFallsBack(t *testing.T) { gap := string(findingsJSON(t, wire.NoFindings())) for name, c := range map[string]struct { findings func([]byte) wire.ResearchFindings images func([]byte) []wire.ResearchImage fetches func() []wire.ResearchFetch none bool fetched int kept int // good: the findings stand (only the bad line is dropped). good bool }{ "a source not in the log": {findings: func([]byte) wire.ResearchFindings { f := goodFindings() f.Facts[0].Sources = []string{"s9"} return f }, fetched: 4}, "an image not kept": {findings: func([]byte) wire.ResearchFindings { return goodFindings("img2") }, fetched: 4}, "an image whose record does not match its file": {findings: func([]byte) wire.ResearchFindings { return goodFindings("img1") }, images: func(b []byte) []wire.ResearchImage { m := keptRecord("img1", b, 5, 4) m.Width = 6 return []wire.ResearchImage{m} }, fetched: 4}, "an image whose hash is another's": {findings: func([]byte) wire.ResearchFindings { return goodFindings("img1") }, images: func(b []byte) []wire.ResearchImage { m := keptRecord("img1", b, 5, 4) m.SHA256 = strings.Repeat("c", 64) return []wire.ResearchImage{m} }, fetched: 4}, "an image from a source not in the log": {findings: func([]byte) wire.ResearchFindings { return goodFindings("img1") }, images: func(b []byte) []wire.ResearchImage { m := keptRecord("img1", b, 5, 4) m.SourceID = "s8" return []wire.ResearchImage{m} }, fetched: 4}, "no research payload": {none: true}, // A line that does not check is dropped alone (Astra security // finding 5): the rest of the log, and findings that do not cite // it, stand. "a fetch line with a bad URL and no refusal": {findings: func([]byte) wire.ResearchFindings { return goodFindings() }, fetches: func() []wire.ResearchFetch { l := fetchLog() l[2].URL = "http://localhost:8080/admin" return l }, fetched: 3, good: true}, "a fetch line with a bad source id": {findings: func([]byte) wire.ResearchFindings { return goodFindings() }, fetches: func() []wire.ResearchFetch { l := fetchLog() l[1].SourceID = "S 2" return l }, fetched: 3}, "a long reason": {findings: func([]byte) wire.ResearchFindings { return goodFindings() }, fetches: func() []wire.ResearchFetch { l := fetchLog() l[3].Reason = strings.Repeat("r", 200) return l }, fetched: 3, good: true}, "too long a log": {findings: func([]byte) wire.ResearchFindings { return goodFindings() }, fetches: func() []wire.ResearchFetch { var l []wire.ResearchFetch for len(l) <= wire.MaxResearchFetches { l = append(l, fetchLog()...) } return l }}, // Valid findings with an image that does not check: the image is // dropped, the findings (which do not cite it) stay. "a bad image the findings do not cite": {findings: func([]byte) wire.ResearchFindings { return goodFindings() }, images: func(b []byte) []wire.ResearchImage { m := keptRecord("img1", b, 5, 4) m.Size++ return []wire.ResearchImage{m} }, fetched: 4, good: true}, } { t.Run(strings.ReplaceAll(name, " ", "_"), func(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() d := r.runningResearch("a") logo := pngOf(t, 5, 4) r.sendFile("logo", fileChunks(d, "img1", logo, 1)) rep := wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Termination: true} if !c.none { res := &wire.ResearchResult{Findings: findingsJSON(t, c.findings(logo)), Fetches: fetchLog(), Images: []wire.ResearchImage{}} if c.fetches != nil { res.Fetches = c.fetches() } if c.images != nil { res.Images = c.images(logo) } rep.Research = res } r.step("a-done", rep) if e := r.nextDispatch(); e.Specialist != wire.SpecialistEngineering { t.Fatalf("Engineering after Research %+v", e) } var stored string if err := r.inst.DB.Writer().QueryRow("SELECT findings FROM chat_research WHERE step_id = ?", d.StepID).Scan(&stored); err != nil { t.Fatal(err) } want := gap if c.good { want = string(findingsJSON(t, goodFindings())) } if stored != want { t.Fatalf("stored %s", stored) } if n := r.rows("SELECT count(*) FROM chat_research_fetches WHERE step_id = ?", d.StepID); n != c.fetched { t.Fatalf("%d fetch lines", n) } if n := r.rows("SELECT count(*) FROM chat_task_files WHERE step_id = ?", d.StepID); n != c.kept { t.Fatalf("%d files stay", n) } if n := r.rows("SELECT count(*) FROM chat_task_file_data"); n != 0 { t.Fatalf("%d chunks stay", n) } s := r.newest(d.TaskID, wire.SpecialistResearch) if s.State != wire.StepDone || s.Research == nil || len(s.Research.Images) != 0 { t.Fatalf("step %+v", s) } if !c.good && !slices.Equal(s.Research.Findings.Gaps, []string{wire.ResearchNoFindingsGap}) { t.Fatalf("read shape %+v", s.Research.Findings) } }) } }