package thintest import ( "bytes" "net/http" "net/url" "regexp" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // Research on the pages (Research spec §3.6 and §5, slice R5): the // sources and inventory cards in the conversation, the Research step's // waiting states on the task page, its findings, kept images served by // the instance only, and its fetch log as escaped text. Nothing on a // page loads a remote resource. // cardOf is one card's markup on a conversation page. func cardOf(t *testing.T, page, id string) string { t.Helper() card := regexp.MustCompile(`(?s)
  • ]* data-card="` + regexp.QuoteMeta(id) + `".*?\n
  • `).FindString(page) if card == "" { t.Fatalf("no card %s in:\n%s", id, page) } return card } // researchItem is the task page's timeline entry for a Research step. func researchItem(t *testing.T, page string) string { t.Helper() item := regexp.MustCompile(`(?s)
  • ]*>.*?
  • `).FindString(page) if item == "" { t.Fatalf("no Research entry in:\n%s", page) } return item } // noRemoteLoads fails when markup would load anything from another // origin: an image, frame, embed, object, script or stylesheet whose // address is absolute. func noRemoteLoads(t *testing.T, what, markup string) { t.Helper() if m := regexp.MustCompile(`(?i)<(img|iframe|embed|object|script|link|source|video|audio)\b[^>]*\b(src|href|data|srcset)="(https?:)?//`).FindString(markup); m != "" { t.Fatalf("%s loads a remote resource: %s", what, m) } for _, tag := range []string{"alert("hours")` if res := r.call("p-r", wire.ToolResearch, map[string]any{"task": id, "question": question, "urls": proposed}); res.IsError { t.Fatalf("request %+v", res) } card := r.sourcesCard(wire.CardOpen) owner := r.inst.Cookie() page := r.get(owner, "/conversation", 200) c := cardOf(t, page, card.ID) if !strings.Contains(c, `equipo-card="research_sources"`) || !strings.Contains(c, ">Let Research read these pages?

    ") { t.Fatalf("sources card:\n%s", c) } for _, u := range proposed { if !strings.Contains(c, "
  • "+u+"
  • ") { t.Fatalf("URL %s not shown in full:\n%s", u, c) } } // Local project-correction links do not authorise reading a source URL. if strings.Contains(c, `href="http`) || strings.Contains(c, `href="//`) { t.Fatalf("the card links a URL:\n%s", c) } noRemoteLoads(t, "the sources card", c) if strings.Contains(page, "` log := fetchLog() log[0].Type = `text/html">` log = append(log, wire.ResearchFetch{SourceID: "s5", Origin: wire.ResearchOriginExpanded, Parent: "s1", URL: `https://shop.example.com/search?q=`, Millis: 1, Reason: "not_followed"}) r.step("a-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Termination: true, Summary: "Read four pages.", Research: &wire.ResearchResult{Findings: findingsJSON(t, f), Fetches: log, Images: []wire.ResearchImage{keptRecord("img1", logo, 5, 4)}}}) r.nextDispatch() s := r.newest(id, wire.SpecialistResearch) if s.Research == nil || len(s.Research.Images) != 1 || s.Research.Findings.Summary != f.Summary { t.Fatalf("not done with findings %+v", s.Research) } file := s.Research.Images[0].ID full := page() item := researchItem(t, full) for _, want := range []string{ "

    " + f.Summary + "

    ", "
    Colours
    ", "Navy <b>and</b> cream <script>alert(1)</script>", "
    Hours
    ", "Tue to Sat, 9 to 6", `https://shop.example.com/`, `https://shop.example.com/hours`, "
  • No phone number found
  • ", `The shop's logo.`, "
    Logo The shop's logo.
    ", `
    `, "Web requests (5)", "https://shop.example.com/search?q=<script>alert(3)</script>", "https://shop.example.com/", "text/html"><script>alert(2)</script>", "5 KB", "https://shop.example.com/hours", "https://shop.example.com/opening-hours", "https://cdn.example.net/x.webp", "type_refused", } { if !strings.Contains(item, want) { t.Fatalf("the findings lack %s:\n%s", want, item) } } if strings.Contains(item, "
    alert") || strings.Contains(full, "and") { t.Fatal("findings or the log rendered as markup") } noRemoteLoads(t, "the task page", full) if n := strings.Count(item, "]*>`).FindAllString(item, -1) { if !strings.Contains(a, `target="_blank" rel="noopener noreferrer"`) { t.Fatalf("source link %s", a) } } } // TestResearchTaskPageStopped: a Research step that failed says so with // its reason in words. func TestResearchTaskPageStopped(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() d := r.runningResearch("a") r.step("a-stop", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) item := researchItem(t, r.get(r.inst.Cookie(), "/tasks/"+d.TaskID, 200)) if !strings.Contains(item, "Research stopped") || !strings.Contains(item, "

    The model connection failed.

    ") { t.Fatalf("stopped Research:\n%s", item) } } // TestResearchFileRoute: a kept image is served to the page's session // as the person API serves it (its type, nosniff, a sandboxing CSP, // inline), to anyone who reads the task, and to nobody else: not under // another task, not an image that was not kept, not someone outside the // team, not without a session. func TestResearchFileRoute(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, 2)) r.step("a-done", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Termination: true, Research: &wire.ResearchResult{Findings: findingsJSON(t, goodFindings("img1")), Fetches: fetchLog(), Images: []wire.ResearchImage{keptRecord("img1", logo, 5, 4)}}}) r.nextDispatch() file := r.newest(d.TaskID, wire.SpecialistResearch).Research.Images[0].ID path := "/tasks/" + d.TaskID + "/files/" + file get := func(c *http.Cookie, path string) (int, []byte, http.Header) { t.Helper() req, _ := http.NewRequest("GET", r.inst.URL+path, nil) if c != nil { req.AddCookie(c) } res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() var b bytes.Buffer _, _ = b.ReadFrom(res.Body) return res.StatusCode, b.Bytes(), res.Header } status, body, h := get(r.inst.Cookie(), path) if status != 200 || !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") || h.Get("Cache-Control") != "private, max-age=86400" { t.Fatalf("served %d, %d bytes, %v", status, len(body), h) } personToolRigAt(t, r, "member@example.com", equipo.RoleMember, wire.ProtocolCurrent) if status, body, _ := get(r.inst.SessionFor(t, "member@example.com"), path); status != 200 || !bytes.Equal(body, logo) { t.Fatalf("a teammate: %d", status) } other := r.namedTask("b") for _, p := range []string{"/tasks/" + other + "/files/" + file, "/tasks/" + d.TaskID + "/files/tf_nothing"} { if status, _, _ := get(r.inst.Cookie(), p); status != 404 { t.Fatalf("%s: %d", p, status) } } // Someone signed in who is not on the team is refused at the // membership gate, as every page is: the same answer for a kept image // as for one that does not exist, and never its bytes. out := r.inst.SessionFor(t, "outsider@example.org") none, _, _ := get(out, "/tasks/tk_nothing/files/tf_nothing") if status, body, _ := get(out, path); status == 200 || status != none || bytes.Contains(body, logo[:8]) { t.Fatalf("someone outside the team: %d (nothing there: %d)", status, none) } // No session: sign in first. if status, body, h := get(nil, path); status != http.StatusSeeOther || !strings.HasPrefix(h.Get("Location"), "/signin?") || bytes.Contains(body, logo[:8]) { t.Fatalf("no session: %d %s", status, h.Get("Location")) } }