| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "net/http" |
| 6 | "net/url" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/equipo" |
| 13 | "amadan.net/oficina/equipo/internal/wire" |
| 14 | ) |
| 15 | |
| 16 | // Research on the pages (Research spec §3.6 and §5, slice R5): the |
| 17 | // sources and inventory cards in the conversation, the Research step's |
| 18 | // waiting states on the task page, its findings, kept images served by |
| 19 | // the instance only, and its fetch log as escaped text. Nothing on a |
| 20 | // page loads a remote resource. |
| 21 | |
| 22 | // cardOf is one card's markup on a conversation page. |
| 23 | func cardOf(t *testing.T, page, id string) string { |
| 24 | t.Helper() |
| 25 | card := regexp.MustCompile(`(?s)<li equipo-card="[a-z_]+"[^>]* data-card="` + regexp.QuoteMeta(id) + `".*?\n</li>`).FindString(page) |
| 26 | if card == "" { |
| 27 | t.Fatalf("no card %s in:\n%s", id, page) |
| 28 | } |
| 29 | return card |
| 30 | } |
| 31 | |
| 32 | // researchItem is the task page's timeline entry for a Research step. |
| 33 | func researchItem(t *testing.T, page string) string { |
| 34 | t.Helper() |
| 35 | item := regexp.MustCompile(`(?s)<li data-kind="[a-z]+" data-specialist="research"[^>]*>.*?</div></li>`).FindString(page) |
| 36 | if item == "" { |
| 37 | t.Fatalf("no Research entry in:\n%s", page) |
| 38 | } |
| 39 | return item |
| 40 | } |
| 41 | |
| 42 | // noRemoteLoads fails when markup would load anything from another |
| 43 | // origin: an image, frame, embed, object, script or stylesheet whose |
| 44 | // address is absolute. |
| 45 | func noRemoteLoads(t *testing.T, what, markup string) { |
| 46 | t.Helper() |
| 47 | if m := regexp.MustCompile(`(?i)<(img|iframe|embed|object|script|link|source|video|audio)\b[^>]*\b(src|href|data|srcset)="(https?:)?//`).FindString(markup); m != "" { |
| 48 | t.Fatalf("%s loads a remote resource: %s", what, m) |
| 49 | } |
| 50 | for _, tag := range []string{"<iframe", "<embed", "<object"} { |
| 51 | if strings.Contains(markup, tag) { |
| 52 | t.Fatalf("%s embeds %s", what, tag) |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | // TestResearchSourcesCardPage: the sources card shows the question and |
| 58 | // every proposed URL in full as text (never a link), Allow and Skip post |
| 59 | // the card's own form, and the answer shows in words. An open card from |
| 60 | // an earlier day still needs the person: it stands at the top of today. |
| 61 | func TestResearchSourcesCardPage(t *testing.T) { |
| 62 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 63 | r.researchOn() |
| 64 | id := r.shopTask("p") |
| 65 | proposed := []string{"https://maps.example.org/place/barber-shop-on-main-street", "https://www.example.net/reviews/barber-shop"} |
| 66 | question := `Its colours and <script>alert("hours")</script>` |
| 67 | if res := r.call("p-r", wire.ToolResearch, map[string]any{"task": id, "question": question, "urls": proposed}); res.IsError { |
| 68 | t.Fatalf("request %+v", res) |
| 69 | } |
| 70 | card := r.sourcesCard(wire.CardOpen) |
| 71 | owner := r.inst.Cookie() |
| 72 | page := r.get(owner, "/conversation", 200) |
| 73 | c := cardOf(t, page, card.ID) |
| 74 | if !strings.Contains(c, `equipo-card="research_sources"`) || !strings.Contains(c, ">Let Research read these pages?</p>") { |
| 75 | t.Fatalf("sources card:\n%s", c) |
| 76 | } |
| 77 | for _, u := range proposed { |
| 78 | if !strings.Contains(c, "<li><code>"+u+"</code></li>") { |
| 79 | t.Fatalf("URL %s not shown in full:\n%s", u, c) |
| 80 | } |
| 81 | } |
| 82 | // Local project-correction links do not authorise reading a source URL. |
| 83 | if strings.Contains(c, `href="http`) || strings.Contains(c, `href="//`) { |
| 84 | t.Fatalf("the card links a URL:\n%s", c) |
| 85 | } |
| 86 | noRemoteLoads(t, "the sources card", c) |
| 87 | if strings.Contains(page, "<script>alert") || !strings.Contains(c, "<script>alert("hours")</script>") { |
| 88 | t.Fatalf("question not escaped:\n%s", c) |
| 89 | } |
| 90 | for _, want := range []string{`<form method="post" action="/conversation/cards/` + card.ID + `/answer" data-card-form equipo-actions>`, `<input type="hidden" name="revision" value="1">`, |
| 91 | `<button rst-btn="primary" name="choice" value="allow" type="submit" data-research-choice="allow">Allow</button>`, `<button rst-btn="" name="choice" value="skip" type="submit" data-research-choice="skip">Skip</button>`} { |
| 92 | if !strings.Contains(c, want) { |
| 93 | t.Fatalf("card lacks %s:\n%s", want, c) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // Two days on, still open: the top of today, under "still open". |
| 98 | r.backdate(48 * time.Hour) |
| 99 | later := r.get(owner, "/conversation", 200) |
| 100 | if !strings.Contains(later, "data-still-open") || !strings.Contains(later, `data-card="`+card.ID+`"`) { |
| 101 | t.Fatalf("an open sources card from an earlier day is not at the top of today:\n%s", later) |
| 102 | } |
| 103 | |
| 104 | // Allow through the page's form, then the card says what it decided. |
| 105 | if status, _ := r.post(owner, "/conversation/cards/"+card.ID+"/answer", url.Values{"choice": {"allow"}, "revision": {"1"}}); status != http.StatusSeeOther { |
| 106 | t.Fatalf("Allow: %d", status) |
| 107 | } |
| 108 | r.sourcesCard(wire.CardAnswered) |
| 109 | r.backdate(-48 * time.Hour) |
| 110 | after := cardOf(t, r.get(owner, "/conversation", 200), card.ID) |
| 111 | if strings.Contains(after, "<form") || !strings.Contains(after, "Allowed. Research can read these pages.</p>") || !strings.Contains(after, "data-done") { |
| 112 | t.Fatalf("answered card:\n%s", after) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | // TestResearchInventoryCardPage: the inventory card lists every detected |
| 117 | // address as text with Confirm; open on an earlier day it stands at the |
| 118 | // top of today; Confirm through the page records it and says so. |
| 119 | func TestResearchInventoryCardPage(t *testing.T) { |
| 120 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 121 | r.researchOn() |
| 122 | r.addresses(2, "81.2.69.7", "2a01:4f8:1:2::7") |
| 123 | r.waitingTask("a") |
| 124 | card := r.inventoryCard(wire.CardOpen) |
| 125 | owner := r.inst.Cookie() |
| 126 | c := cardOf(t, r.get(owner, "/conversation", 200), card.ID) |
| 127 | for _, want := range []string{`equipo-card="research_inventory"`, "<li><code>81.2.69.7</code></li>", "<li><code>2a01:4f8:1:2::7</code></li>", |
| 128 | `<input type="hidden" name="revision" value="1">`, `<button rst-btn="primary" name="choice" value="confirm" type="submit" data-inventory-confirm>Confirm</button>`} { |
| 129 | if !strings.Contains(c, want) { |
| 130 | t.Fatalf("inventory card lacks %s:\n%s", want, c) |
| 131 | } |
| 132 | } |
| 133 | noRemoteLoads(t, "the inventory card", c) |
| 134 | r.backdate(48 * time.Hour) |
| 135 | if later := r.get(owner, "/conversation", 200); !strings.Contains(later, "data-still-open") || !strings.Contains(later, `data-card="`+card.ID+`"`) { |
| 136 | t.Fatalf("an open inventory card from an earlier day is not at the top of today:\n%s", later) |
| 137 | } |
| 138 | if status, _ := r.post(owner, "/conversation/cards/"+card.ID+"/answer", url.Values{"choice": {"confirm"}, "revision": {"1"}}); status != http.StatusSeeOther { |
| 139 | t.Fatalf("Confirm: %d", status) |
| 140 | } |
| 141 | r.inventoryCard(wire.CardAnswered) |
| 142 | r.backdate(-48 * time.Hour) |
| 143 | after := cardOf(t, r.get(owner, "/conversation", 200), card.ID) |
| 144 | if strings.Contains(after, "<form") || !strings.Contains(after, "Confirmed. Research will block pages served from these addresses.</p>") { |
| 145 | t.Fatalf("confirmed card:\n%s", after) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // TestResearchTaskPage: the task page says where a Research step is in |
| 150 | // plain words while it waits (the next round, the person's answer on the |
| 151 | // pages, the addresses), while it runs, and once done shows the |
| 152 | // findings: the summary, facts with their sources as text and a plain |
| 153 | // link, the gaps, kept images from the instance only, and the fetch log |
| 154 | // folded, every line escaped. |
| 155 | func TestResearchTaskPage(t *testing.T) { |
| 156 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 157 | r.researchOn() |
| 158 | r.addresses(1, "81.2.69.7") |
| 159 | owner := r.inst.Cookie() |
| 160 | id := r.namedTask("a") |
| 161 | if res := r.research("a-r", id, "https://maps.example.org/place/barber-shop-on-main-street"); res.IsError { |
| 162 | t.Fatalf("research %+v", res) |
| 163 | } |
| 164 | page := func() string { return r.get(owner, "/tasks/"+id, 200) } |
| 165 | says := func(when, want string) string { |
| 166 | t.Helper() |
| 167 | item := researchItem(t, page()) |
| 168 | if !strings.Contains(item, want) { |
| 169 | t.Fatalf("%s: the Research entry does not say %q:\n%s", when, want, item) |
| 170 | } |
| 171 | return item |
| 172 | } |
| 173 | says("requested", "Waiting for the work to start or the next review round") |
| 174 | r.begin("a-start", id) |
| 175 | r.heldForResearch(id) |
| 176 | says("at its fixed point", "Waiting for you to approve or skip the pages") |
| 177 | if !strings.Contains(page(), "Waiting for Research to finish.") { |
| 178 | t.Fatal("the held Engineering step does not say why it waits") |
| 179 | } |
| 180 | card := r.sourcesCard(wire.CardOpen) |
| 181 | if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); err != nil { |
| 182 | t.Fatal(err) |
| 183 | } |
| 184 | says("before the inventory", "Waiting for an owner to confirm the primary machine’s public internet addresses") |
| 185 | inv := r.inventoryCard(wire.CardOpen) |
| 186 | if _, err := r.client.Answer(r.ctx, inv.ID, wire.ChoiceConfirm, inv.Revision); err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | d := r.nextDispatch() |
| 190 | if d.Specialist != wire.SpecialistResearch { |
| 191 | t.Fatalf("not Research %+v", d) |
| 192 | } |
| 193 | r.step("a-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning}) |
| 194 | says("running", "Reading the pages") |
| 195 | |
| 196 | logo := pngOf(t, 5, 4) |
| 197 | r.sendFile("logo", fileChunks(d, "img1", logo, 1)) |
| 198 | f := goodFindings("img1") |
| 199 | f.Facts[0].Value = `Navy <b>and</b> cream <script>alert(1)</script>` |
| 200 | log := fetchLog() |
| 201 | log[0].Type = `text/html"><script>alert(2)</script>` |
| 202 | log = append(log, wire.ResearchFetch{SourceID: "s5", Origin: wire.ResearchOriginExpanded, Parent: "s1", URL: `https://shop.example.com/search?q=<script>alert(3)</script>`, Millis: 1, Reason: "not_followed"}) |
| 203 | r.step("a-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Termination: true, Summary: "Read four pages.", |
| 204 | Research: &wire.ResearchResult{Findings: findingsJSON(t, f), Fetches: log, Images: []wire.ResearchImage{keptRecord("img1", logo, 5, 4)}}}) |
| 205 | r.nextDispatch() |
| 206 | s := r.newest(id, wire.SpecialistResearch) |
| 207 | if s.Research == nil || len(s.Research.Images) != 1 || s.Research.Findings.Summary != f.Summary { |
| 208 | t.Fatalf("not done with findings %+v", s.Research) |
| 209 | } |
| 210 | file := s.Research.Images[0].ID |
| 211 | full := page() |
| 212 | item := researchItem(t, full) |
| 213 | for _, want := range []string{ |
| 214 | "<p equipo-research-summary>" + f.Summary + "</p>", |
| 215 | "<dt>Colours</dt>", "Navy <b>and</b> cream <script>alert(1)</script>", |
| 216 | "<dt>Hours</dt>", "Tue to Sat, 9 to 6", |
| 217 | `<a equipo-source href="https://shop.example.com/" target="_blank" rel="noopener noreferrer" data-source="s1">https://shop.example.com/</a>`, |
| 218 | `<a equipo-source href="https://shop.example.com/hours" target="_blank" rel="noopener noreferrer" data-source="s2">https://shop.example.com/hours</a>`, |
| 219 | "<li>No phone number found</li>", |
| 220 | `<img src="/tasks/` + id + `/files/` + file + `" alt="The shop's logo." width="5" height="4" loading="lazy" decoding="async">`, |
| 221 | "<figcaption><b>Logo</b> The shop's logo.</figcaption>", |
| 222 | `<details equipo-tl-more data-fetch-log id="research-` + s.ID + `">`, "Web requests (5)", "<code>https://shop.example.com/search?q=<script>alert(3)</script></code>", |
| 223 | "<code>https://shop.example.com/</code>", "text/html"><script>alert(2)</script>", "<span>5 KB</span>", |
| 224 | "<code>https://shop.example.com/hours</code>", "https://shop.example.com/opening-hours", |
| 225 | "<code>https://cdn.example.net/x.webp</code>", "type_refused", |
| 226 | } { |
| 227 | if !strings.Contains(item, want) { |
| 228 | t.Fatalf("the findings lack %s:\n%s", want, item) |
| 229 | } |
| 230 | } |
| 231 | if strings.Contains(item, "<details equipo-tl-more data-fetch-log open") { |
| 232 | t.Fatal("the fetch log is not folded") |
| 233 | } |
| 234 | if strings.Contains(full, "<script>alert") || strings.Contains(full, "<b>and</b>") { |
| 235 | t.Fatal("findings or the log rendered as markup") |
| 236 | } |
| 237 | noRemoteLoads(t, "the task page", full) |
| 238 | if n := strings.Count(item, "<img "); n != 1 { |
| 239 | t.Fatalf("%d images", n) |
| 240 | } |
| 241 | // Every source link opens in a new tab, cut off from this page. |
| 242 | for _, a := range regexp.MustCompile(`<a equipo-source [^>]*>`).FindAllString(item, -1) { |
| 243 | if !strings.Contains(a, `target="_blank" rel="noopener noreferrer"`) { |
| 244 | t.Fatalf("source link %s", a) |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // TestResearchTaskPageStopped: a Research step that failed says so with |
| 250 | // its reason in words. |
| 251 | func TestResearchTaskPageStopped(t *testing.T) { |
| 252 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 253 | r.researchOn() |
| 254 | r.inventoryOn() |
| 255 | d := r.runningResearch("a") |
| 256 | r.step("a-stop", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) |
| 257 | item := researchItem(t, r.get(r.inst.Cookie(), "/tasks/"+d.TaskID, 200)) |
| 258 | if !strings.Contains(item, "<b>Research stopped</b>") || !strings.Contains(item, "<p equipo-headline>The model connection failed.</p>") { |
| 259 | t.Fatalf("stopped Research:\n%s", item) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | // TestResearchFileRoute: a kept image is served to the page's session |
| 264 | // as the person API serves it (its type, nosniff, a sandboxing CSP, |
| 265 | // inline), to anyone who reads the task, and to nobody else: not under |
| 266 | // another task, not an image that was not kept, not someone outside the |
| 267 | // team, not without a session. |
| 268 | func TestResearchFileRoute(t *testing.T) { |
| 269 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 270 | r.researchOn() |
| 271 | r.inventoryOn() |
| 272 | d := r.runningResearch("a") |
| 273 | logo := pngOf(t, 5, 4) |
| 274 | r.sendFile("logo", fileChunks(d, "img1", logo, 2)) |
| 275 | r.step("a-done", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Termination: true, |
| 276 | Research: &wire.ResearchResult{Findings: findingsJSON(t, goodFindings("img1")), Fetches: fetchLog(), Images: []wire.ResearchImage{keptRecord("img1", logo, 5, 4)}}}) |
| 277 | r.nextDispatch() |
| 278 | file := r.newest(d.TaskID, wire.SpecialistResearch).Research.Images[0].ID |
| 279 | path := "/tasks/" + d.TaskID + "/files/" + file |
| 280 | get := func(c *http.Cookie, path string) (int, []byte, http.Header) { |
| 281 | t.Helper() |
| 282 | req, _ := http.NewRequest("GET", r.inst.URL+path, nil) |
| 283 | if c != nil { |
| 284 | req.AddCookie(c) |
| 285 | } |
| 286 | res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) |
| 287 | if err != nil { |
| 288 | t.Fatal(err) |
| 289 | } |
| 290 | defer res.Body.Close() |
| 291 | var b bytes.Buffer |
| 292 | _, _ = b.ReadFrom(res.Body) |
| 293 | return res.StatusCode, b.Bytes(), res.Header |
| 294 | } |
| 295 | status, body, h := get(r.inst.Cookie(), path) |
| 296 | if status != 200 || !bytes.Equal(body, logo) || h.Get("Content-Type") != "image/png" || h.Get("X-Content-Type-Options") != "nosniff" || |
| 297 | !strings.Contains(h.Get("Content-Security-Policy"), "sandbox") || !strings.HasPrefix(h.Get("Content-Disposition"), "inline") || h.Get("Cache-Control") != "private, max-age=86400" { |
| 298 | t.Fatalf("served %d, %d bytes, %v", status, len(body), h) |
| 299 | } |
| 300 | personToolRigAt(t, r, "member@example.com", equipo.RoleMember, wire.ProtocolCurrent) |
| 301 | if status, body, _ := get(r.inst.SessionFor(t, "member@example.com"), path); status != 200 || !bytes.Equal(body, logo) { |
| 302 | t.Fatalf("a teammate: %d", status) |
| 303 | } |
| 304 | other := r.namedTask("b") |
| 305 | for _, p := range []string{"/tasks/" + other + "/files/" + file, "/tasks/" + d.TaskID + "/files/tf_nothing"} { |
| 306 | if status, _, _ := get(r.inst.Cookie(), p); status != 404 { |
| 307 | t.Fatalf("%s: %d", p, status) |
| 308 | } |
| 309 | } |
| 310 | // Someone signed in who is not on the team is refused at the |
| 311 | // membership gate, as every page is: the same answer for a kept image |
| 312 | // as for one that does not exist, and never its bytes. |
| 313 | out := r.inst.SessionFor(t, "outsider@example.org") |
| 314 | none, _, _ := get(out, "/tasks/tk_nothing/files/tf_nothing") |
| 315 | if status, body, _ := get(out, path); status == 200 || status != none || bytes.Contains(body, logo[:8]) { |
| 316 | t.Fatalf("someone outside the team: %d (nothing there: %d)", status, none) |
| 317 | } |
| 318 | // No session: sign in first. |
| 319 | if status, body, h := get(nil, path); status != http.StatusSeeOther || !strings.HasPrefix(h.Get("Location"), "/signin?") || bytes.Contains(body, logo[:8]) { |
| 320 | t.Fatalf("no session: %d %s", status, h.Get("Location")) |
| 321 | } |
| 322 | } |
| 323 | |