| 1 | package webtest |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "html" |
| 10 | "image" |
| 11 | "image/color" |
| 12 | "image/png" |
| 13 | "io" |
| 14 | "mime" |
| 15 | "net" |
| 16 | "net/http" |
| 17 | "net/url" |
| 18 | "regexp" |
| 19 | "strings" |
| 20 | "sync" |
| 21 | "testing" |
| 22 | "time" |
| 23 | |
| 24 | "amadan.net/oficina/base/internal/equipo/equipotest" |
| 25 | "amadan.net/oficina/base/internal/web" |
| 26 | ) |
| 27 | |
| 28 | // pngFile is a w×h PNG. |
| 29 | func pngFile(t *testing.T, w, h int) []byte { |
| 30 | t.Helper() |
| 31 | img := image.NewNRGBA(image.Rect(0, 0, w, h)) |
| 32 | img.Set(0, 0, color.NRGBA{G: 180, A: 255}) |
| 33 | var b bytes.Buffer |
| 34 | if err := png.Encode(&b, img); err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | return b.Bytes() |
| 38 | } |
| 39 | |
| 40 | // uploadReq is an upload as the page's script makes it. |
| 41 | func (a *testApp) uploadReq(ctx context.Context, name, typ string, body io.Reader) *http.Request { |
| 42 | req, _ := http.NewRequestWithContext(ctx, http.MethodPost, a.base+"/ask/attachments", body) |
| 43 | req.Header.Set("Content-Type", typ) |
| 44 | req.Header.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name})) |
| 45 | req.Header.Set("Origin", a.origin) |
| 46 | req.Header.Set("Accept", "application/json") |
| 47 | return req |
| 48 | } |
| 49 | |
| 50 | func (a *testApp) upload(name, typ string, body []byte) Resp { |
| 51 | a.t.Helper() |
| 52 | return a.do(a.uploadReq(context.Background(), name, typ, bytes.NewReader(body))) |
| 53 | } |
| 54 | |
| 55 | // uploaded is the id an upload answered with. |
| 56 | func uploaded(t *testing.T, r Resp) string { |
| 57 | t.Helper() |
| 58 | var at struct{ ID string } |
| 59 | if r.Code != 201 || json.Unmarshal([]byte(r.Body), &at) != nil || at.ID == "" { |
| 60 | t.Fatalf("upload: %d %s", r.Code, r.Body) |
| 61 | } |
| 62 | return at.ID |
| 63 | } |
| 64 | |
| 65 | // bounds makes the upload relay's bounds b for the apps the test builds. |
| 66 | func bounds(t *testing.T, b web.UploadBounds) { |
| 67 | t.Cleanup(web.SetUploadBounds(b)) |
| 68 | } |
| 69 | |
| 70 | // codeOf is the JSON answer's code and state. |
| 71 | func codeOf(r Resp) (code, state, files string) { |
| 72 | var out struct{ Code, State, Files string } |
| 73 | _ = json.Unmarshal([]byte(r.Body), &out) |
| 74 | return out.Code, out.State, out.Files |
| 75 | } |
| 76 | |
| 77 | // A member's upload goes to Equipo with their bearer, its name and type, |
| 78 | // and comes back as Equipo's attachment, never cached. |
| 79 | func TestAskUploadRelays(t *testing.T) { |
| 80 | a, f := newAskApp(t) |
| 81 | token := a.connectEquipo(f) |
| 82 | shot := pngFile(t, 30, 20) |
| 83 | r := a.upload("Screen Shot día.png", "image/png", shot) |
| 84 | id := uploaded(t, r) |
| 85 | wantKeys(t, "upload", r.Body, "id", "kind", "name", "media_type", "size", "width", "height") |
| 86 | var at struct { |
| 87 | Kind, Name string |
| 88 | MediaType string `json:"media_type"` |
| 89 | Width, Height int |
| 90 | Size int64 |
| 91 | } |
| 92 | _ = json.Unmarshal([]byte(r.Body), &at) |
| 93 | if r.Header.Get("Cache-Control") != "no-store" || at.Kind != "image" || at.MediaType != "image/png" || at.Width != 30 || at.Height != 20 || at.Size != int64(len(shot)) { |
| 94 | t.Fatalf("answer: %v %s", r.Header, r.Body) |
| 95 | } |
| 96 | data, name, media, _, ok := f.Upload(id) |
| 97 | if !ok || !bytes.Equal(data, shot) || name != "Screen Shot día.png" || media != "image/png" { |
| 98 | t.Fatalf("Equipo holds %d bytes %q %q %v", len(data), name, media, ok) |
| 99 | } |
| 100 | c := f.Calls("/api/v1/attachments")[0] |
| 101 | if c.Header.Get("Authorization") != "Bearer "+token || c.Header.Get("Cookie") != "" || c.Header.Get("Origin") != "" || |
| 102 | len(c.Header.Values("Idempotency-Key")) != 0 { |
| 103 | t.Fatalf("relayed headers: %v", c.Header) |
| 104 | } |
| 105 | a.noLeak(token) |
| 106 | } |
| 107 | |
| 108 | // A body of unknown length is refused before Equipo hears of it (Fable |
| 109 | // N1): a browser always says a File's length. (A declared length over |
| 110 | // 10 MiB is in TestAskUploadStalledBodyFreesItsSlot, which already pays |
| 111 | // for a body the server never reads.) |
| 112 | func TestAskUploadTooBig(t *testing.T) { |
| 113 | a, f := newAskApp(t) |
| 114 | a.connectEquipo(f) |
| 115 | req := a.uploadReq(context.Background(), "big.txt", "text/plain", io.MultiReader(strings.NewReader("a few bytes"))) |
| 116 | req.ContentLength = -1 |
| 117 | r := a.do(req) |
| 118 | if code, _, _ := codeOf(r); r.Code != 411 || code != "length_required" { |
| 119 | t.Fatalf("undeclared: %d %s", r.Code, r.Body) |
| 120 | } |
| 121 | if n := len(f.Calls("/api/v1/attachments")); n != 0 { |
| 122 | t.Fatalf("Equipo heard %d uploads", n) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | // Equipo's refusals come back with its status and code. |
| 127 | func TestAskUploadRefusals(t *testing.T) { |
| 128 | a, f := newAskApp(t) |
| 129 | a.connectEquipo(f) |
| 130 | heic := append([]byte("\x00\x00\x00\x18ftypheic"), make([]byte, 64)...) |
| 131 | for name, tc := range map[string]struct { |
| 132 | body []byte |
| 133 | typ string |
| 134 | status int |
| 135 | code string |
| 136 | }{ |
| 137 | "type": {[]byte("\x00\x01\x02binary"), "application/octet-stream", 415, "attachment_type"}, |
| 138 | "heic": {heic, "image/heic", 415, "attachment_heic"}, |
| 139 | "pixels": {pngFile(t, 1, 12001), "image/png", 413, "attachment_pixels"}, |
| 140 | } { |
| 141 | r := a.upload("x", tc.typ, tc.body) |
| 142 | if code, _, _ := codeOf(r); r.Code != tc.status || code != tc.code { |
| 143 | t.Errorf("%s: %d %s", name, r.Code, r.Body) |
| 144 | } |
| 145 | } |
| 146 | for i := 0; i < 20; i++ { |
| 147 | uploaded(t, a.upload("n.txt", "text/plain", []byte("note"))) |
| 148 | } |
| 149 | r := a.upload("n.txt", "text/plain", []byte("note")) |
| 150 | if code, _, _ := codeOf(r); r.Code != 409 || code != "attachment_limit" { |
| 151 | t.Fatalf("21st: %d %s", r.Code, r.Body) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | // An upload needs what every Ask write needs: a member, from Base's own |
| 156 | // pages, with Ask set up; Equipo refusing the bearer drops the link. |
| 157 | func TestAskUploadNeedsAskReady(t *testing.T) { |
| 158 | a, f := newAskApp(t) |
| 159 | r := a.upload("n.txt", "text/plain", []byte("note")) |
| 160 | if _, state, _ := codeOf(r); r.Code != 409 || state != "connect" { |
| 161 | t.Fatalf("not set up: %d %s", r.Code, r.Body) |
| 162 | } |
| 163 | a.connectEquipo(f) |
| 164 | req := a.uploadReq(context.Background(), "n.txt", "text/plain", strings.NewReader("note")) |
| 165 | req.Header.Set("Origin", "https://evil.example") |
| 166 | if r := a.do(req); r.Code != 403 { |
| 167 | t.Fatalf("cross-site: %d", r.Code) |
| 168 | } |
| 169 | if r := a.newBrowser().upload("n.txt", "text/plain", []byte("note")); r.Code != 401 { |
| 170 | t.Fatalf("signed out: %d %s", r.Code, r.Body) |
| 171 | } |
| 172 | if n := len(f.Calls("/api/v1/attachments")); n != 0 { |
| 173 | t.Fatalf("Equipo heard %d uploads", n) |
| 174 | } |
| 175 | f.RevokeAll() |
| 176 | r = a.upload("n.txt", "text/plain", []byte("note")) |
| 177 | if _, state, _ := codeOf(r); r.Code != 409 || state != "reconnect" { |
| 178 | t.Fatalf("revoked: %d %s", r.Code, r.Body) |
| 179 | } |
| 180 | if s, _ := a.askState(); s.State != "reconnect" { |
| 181 | t.Fatalf("after a refused bearer: %+v", s) |
| 182 | } |
| 183 | // A code waiting for approval is not ready either. |
| 184 | b, g := newAskApp(t) |
| 185 | b.post("/ask/connect", url.Values{"next": {"ask"}}) |
| 186 | r = b.upload("n.txt", "text/plain", []byte("note")) |
| 187 | if _, state, _ := codeOf(r); r.Code != 409 || state != "pending" || len(g.Calls("/api/v1/attachments")) != 0 { |
| 188 | t.Fatalf("pending: %d %s", r.Code, r.Body) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | // Where no read deadline can be set (here, Base served in-process with |
| 193 | // no connection under it), an upload is refused before its body is read: |
| 194 | // never read without one. |
| 195 | func TestAskUploadNeedsAReadDeadline(t *testing.T) { |
| 196 | web, app, f := newNativeAskApp(t) |
| 197 | web.approveEquipo(f) |
| 198 | req, _ := http.NewRequest(http.MethodPost, app.base+"/ask/attachments", strings.NewReader("# Notes")) |
| 199 | req.Header.Set("Content-Type", "text/markdown") |
| 200 | req.Header.Set("Origin", homeOrigin) |
| 201 | req.Header.Set("Accept", "application/json") |
| 202 | r := app.do(req) |
| 203 | if code, _, _ := codeOf(r); r.Code != 503 || code != "busy" || len(f.Calls("/api/v1/attachments")) != 0 { |
| 204 | t.Fatalf("in-process upload: %d %s", r.Code, r.Body) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // cookieHeader is the session cookies a raw request must carry. |
| 209 | func (a *testApp) cookieHeader() string { |
| 210 | u, _ := url.Parse(a.base) |
| 211 | var parts []string |
| 212 | for _, c := range a.client.Jar.Cookies(u) { |
| 213 | parts = append(parts, c.Name+"="+c.Value) |
| 214 | } |
| 215 | return strings.Join(parts, "; ") |
| 216 | } |
| 217 | |
| 218 | // uploadAll sends n uploads at once and answers their statuses. |
| 219 | func (a *testApp) uploadAll(n int) []int { |
| 220 | var wg sync.WaitGroup |
| 221 | out := make([]int, n) |
| 222 | for i := range n { |
| 223 | wg.Go(func() { |
| 224 | res, err := a.client.Do(a.uploadReq(context.Background(), fmt.Sprintf("n%d.txt", i), "text/plain", strings.NewReader("note"))) |
| 225 | if err != nil { |
| 226 | return |
| 227 | } |
| 228 | io.Copy(io.Discard, res.Body) |
| 229 | res.Body.Close() |
| 230 | out[i] = res.StatusCode |
| 231 | }) |
| 232 | } |
| 233 | wg.Wait() |
| 234 | return out |
| 235 | } |
| 236 | |
| 237 | // A body that stalls loses its slot at the read deadline, through the |
| 238 | // whole router (Fable B3): afterwards four uploads at once all pass. A |
| 239 | // declared length over 10 MiB is refused from the headers alone. |
| 240 | func TestAskUploadStalledBodyFreesItsSlot(t *testing.T) { |
| 241 | bounds(t, web.UploadBounds{Slots: 4, SlotWait: 40 * time.Millisecond, ReadDeadline: 100 * time.Millisecond, Upstream: 5 * time.Second}) |
| 242 | a, f := newAskApp(t) |
| 243 | a.connectEquipo(f) |
| 244 | u, _ := url.Parse(a.base) |
| 245 | conn, err := net.Dial("tcp", u.Host) |
| 246 | if err != nil { |
| 247 | t.Fatal(err) |
| 248 | } |
| 249 | defer conn.Close() |
| 250 | fmt.Fprintf(conn, "POST /ask/attachments HTTP/1.1\r\nHost: %s\r\nOrigin: %s\r\nAccept: application/json\r\nCookie: %s\r\n"+ |
| 251 | "Content-Type: text/plain\r\nContent-Disposition: attachment; filename=\"s.txt\"\r\nContent-Length: 1000\r\n\r\n%s", |
| 252 | u.Host, a.origin, a.cookieHeader(), strings.Repeat("a", 500)) |
| 253 | start := time.Now() |
| 254 | _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| 255 | res, err := http.ReadResponse(bufio.NewReader(conn), nil) |
| 256 | if took := time.Since(start); took > 3*time.Second || err == nil && res.StatusCode != 400 { |
| 257 | t.Fatalf("the stalled upload held on for %s (%v %v)", took, res, err) |
| 258 | } |
| 259 | big, err := net.Dial("tcp", u.Host) |
| 260 | if err != nil { |
| 261 | t.Fatal(err) |
| 262 | } |
| 263 | defer big.Close() |
| 264 | fmt.Fprintf(big, "POST /ask/attachments HTTP/1.1\r\nHost: %s\r\nOrigin: %s\r\nAccept: application/json\r\nCookie: %s\r\n"+ |
| 265 | "Content-Type: text/plain\r\nContent-Length: %d\r\n\r\n", u.Host, a.origin, a.cookieHeader(), 10<<20+1) |
| 266 | _ = big.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| 267 | if res, err := http.ReadResponse(bufio.NewReader(big), nil); err != nil || res.StatusCode != 413 { |
| 268 | t.Fatalf("declared over 10 MiB: %v %v", res, err) |
| 269 | } |
| 270 | f.SlowUploads(80 * time.Millisecond) |
| 271 | for i, code := range a.uploadAll(4) { |
| 272 | if code != 201 { |
| 273 | t.Fatalf("upload %d after the stall: %d", i, code) |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // Every slot busy: a fifth upload waits, then is told to come back. |
| 279 | func TestAskUploadBusy(t *testing.T) { |
| 280 | bounds(t, web.UploadBounds{Slots: 4, SlotWait: 60 * time.Millisecond, ReadDeadline: 5 * time.Second, Upstream: 10 * time.Second}) |
| 281 | a, f := newAskApp(t) |
| 282 | a.connectEquipo(f) |
| 283 | f.SlowUploads(300 * time.Millisecond) |
| 284 | done := make(chan []int) |
| 285 | go func() { done <- a.uploadAll(4) }() |
| 286 | for i := 0; f.UploadsAtOnce() < 4; i++ { |
| 287 | if i > 200 { |
| 288 | t.Fatalf("only %d uploads reached Equipo", f.UploadsAtOnce()) |
| 289 | } |
| 290 | time.Sleep(10 * time.Millisecond) |
| 291 | } |
| 292 | r := a.upload("fifth.txt", "text/plain", []byte("note")) |
| 293 | if code, _, _ := codeOf(r); r.Code != 503 || r.Header.Get("Retry-After") != "2" || code != "busy" { |
| 294 | t.Fatalf("fifth: %d %v %s", r.Code, r.Header, r.Body) |
| 295 | } |
| 296 | for i, code := range <-done { |
| 297 | if code != 201 { |
| 298 | t.Fatalf("upload %d: %d", i, code) |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | // The slot comes before the body: with eight uploads at once, no more |
| 304 | // than four bodies are ever being read. |
| 305 | func TestAskUploadSlotComesFirst(t *testing.T) { |
| 306 | bounds(t, web.UploadBounds{Slots: 4, SlotWait: 10 * time.Second, ReadDeadline: 5 * time.Second, Upstream: 10 * time.Second}) |
| 307 | var mu sync.Mutex |
| 308 | most := 0 |
| 309 | web.UploadReading = func(n int) { mu.Lock(); most = max(most, n); mu.Unlock() } |
| 310 | t.Cleanup(func() { web.UploadReading = nil }) |
| 311 | a, f := newAskApp(t) |
| 312 | a.connectEquipo(f) |
| 313 | f.SlowUploads(80 * time.Millisecond) |
| 314 | for i, code := range a.uploadAll(8) { |
| 315 | if code != 201 { |
| 316 | t.Fatalf("upload %d: %d", i, code) |
| 317 | } |
| 318 | } |
| 319 | mu.Lock() |
| 320 | defer mu.Unlock() |
| 321 | if most > 4 || most < 2 || f.UploadsAtOnce() > 4 { |
| 322 | t.Fatalf("bodies read at once: %d; Equipo had %d", most, f.UploadsAtOnce()) |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | // An upload whose page has gone (Remove aborted it) while Equipo took it |
| 327 | // is deleted once Equipo answers. |
| 328 | func TestAskUploadGoneMidFlightIsDeleted(t *testing.T) { |
| 329 | a, f := newAskApp(t) |
| 330 | a.connectEquipo(f) |
| 331 | entered, release := f.HoldNextUpload() |
| 332 | ctx, cancel := context.WithCancel(context.Background()) |
| 333 | errc := make(chan error, 1) |
| 334 | go func() { |
| 335 | res, err := a.client.Do(a.uploadReq(ctx, "n.txt", "text/plain", strings.NewReader("note"))) |
| 336 | if err == nil { |
| 337 | res.Body.Close() |
| 338 | } |
| 339 | errc <- err |
| 340 | }() |
| 341 | <-entered |
| 342 | cancel() |
| 343 | if err := <-errc; err == nil { |
| 344 | t.Fatal("the request finished") |
| 345 | } |
| 346 | time.Sleep(100 * time.Millisecond) |
| 347 | release() |
| 348 | for i := 0; ; i++ { |
| 349 | deletes := 0 |
| 350 | for _, c := range f.Calls("") { |
| 351 | if c.Method == http.MethodDelete && strings.HasPrefix(c.Path, "/api/v1/attachments/") { |
| 352 | deletes++ |
| 353 | } |
| 354 | } |
| 355 | if len(f.Uploads()) == 0 && deletes == 1 { |
| 356 | return |
| 357 | } |
| 358 | if i > 100 { |
| 359 | t.Fatalf("held %v, %d deletes", f.Uploads(), deletes) |
| 360 | } |
| 361 | time.Sleep(20 * time.Millisecond) |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | // A picture shows inline, with headers Base decides; its preview may be |
| 366 | // kept for an hour by this browser alone, the original not at all. |
| 367 | func TestAskAttachmentImage(t *testing.T) { |
| 368 | a, f := newAskApp(t) |
| 369 | a.connectEquipo(f) |
| 370 | shot := pngFile(t, 12, 10) |
| 371 | id := uploaded(t, a.upload("shot.png", "image/png", shot)) |
| 372 | for _, path := range []string{"/ask/attachments/" + id, "/ask/attachments/" + id + "/preview"} { |
| 373 | r := a.get(path) |
| 374 | h := r.Header |
| 375 | if r.Code != 200 || r.Body != string(shot) || h.Get("Content-Type") != "image/png" || h.Get("X-Content-Type-Options") != "nosniff" || |
| 376 | h.Get("Content-Security-Policy") != "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox" || |
| 377 | h.Get("X-Equipo-Only") != "" { |
| 378 | t.Fatalf("%s: %d %v", path, r.Code, h) |
| 379 | } |
| 380 | if _, p, err := mime.ParseMediaType(h.Get("Content-Disposition")); err != nil || !strings.HasPrefix(h.Get("Content-Disposition"), "inline") || p["filename"] != "shot.png" { |
| 381 | t.Fatalf("%s disposition: %q", path, h.Get("Content-Disposition")) |
| 382 | } |
| 383 | preview := strings.HasSuffix(path, "/preview") |
| 384 | if preview && (h.Get("Cache-Control") != "private, max-age=3600" || !strings.Contains(strings.Join(h.Values("Vary"), ","), "Cookie")) || |
| 385 | !preview && h.Get("Cache-Control") != "no-store" { |
| 386 | t.Fatalf("%s caching: %v", path, h) |
| 387 | } |
| 388 | } |
| 389 | req, _ := http.NewRequest(http.MethodHead, a.base+"/ask/attachments/"+id, nil) |
| 390 | if r := a.do(req); r.Code != 200 || r.Body != "" || r.Header.Get("Content-Type") != "image/png" { |
| 391 | t.Fatalf("HEAD: %d %v", r.Code, r.Header) |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | // Every other file is a download; text says it is UTF-8. |
| 396 | func TestAskAttachmentDownload(t *testing.T) { |
| 397 | a, f := newAskApp(t) |
| 398 | a.connectEquipo(f) |
| 399 | id := uploaded(t, a.upload("sales.csv", "text/csv", []byte("a,b\n1,2\n"))) |
| 400 | r := a.get("/ask/attachments/" + id) |
| 401 | if r.Code != 200 || r.Header.Get("Content-Type") != "text/csv; charset=utf-8" || !strings.HasPrefix(r.Header.Get("Content-Disposition"), "attachment") { |
| 402 | t.Fatalf("csv: %d %v", r.Code, r.Header) |
| 403 | } |
| 404 | if r := a.get("/ask/attachments/" + id + "/preview"); r.Code != 404 { |
| 405 | t.Fatalf("a file's preview: %d", r.Code) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | // Base never trusts Equipo's type or disposition (Fable B4): HTML said to |
| 410 | // be inline goes as a download, an SVG as an octet stream, and neither |
| 411 | // has a preview. A hostile name can't add a parameter or a header, and a |
| 412 | // missing one reads "file" (Fable S3). |
| 413 | func TestAskAttachmentHostileUpstream(t *testing.T) { |
| 414 | a, f := newAskApp(t) |
| 415 | a.connectEquipo(f) |
| 416 | note := uploaded(t, a.upload("x.txt", "text/plain", []byte("<script>alert(1)</script>"))) |
| 417 | shot := uploaded(t, a.upload("x.png", "image/png", pngFile(t, 2, 2))) |
| 418 | for typ, id := range map[string]string{"text/html; charset=utf-8": note, "image/svg+xml": shot} { |
| 419 | f.ServeHostile(typ, "inline") |
| 420 | r := a.get("/ask/attachments/" + id) |
| 421 | if r.Code != 200 || r.Header.Get("Content-Type") != "application/octet-stream" || !strings.HasPrefix(r.Header.Get("Content-Disposition"), "attachment") { |
| 422 | t.Errorf("%s: %d %v", typ, r.Code, r.Header) |
| 423 | } |
| 424 | if r := a.get("/ask/attachments/" + id + "/preview"); r.Code != 404 { |
| 425 | t.Errorf("%s preview: %d", typ, r.Code) |
| 426 | } |
| 427 | } |
| 428 | f.ServeHostile("", "") |
| 429 | for name, want := range map[string]string{ |
| 430 | "a\"; filename=evil.html; x=\"\r\nSet-Cookie: a=b.txt": "", |
| 431 | "résumé; final.txt": "résumé; final.txt", |
| 432 | "": "file", |
| 433 | } { |
| 434 | id := uploaded(t, a.upload(name, "text/plain", []byte("note"))) |
| 435 | r := a.get("/ask/attachments/" + id) |
| 436 | cd := r.Header.Get("Content-Disposition") |
| 437 | _, params, err := mime.ParseMediaType(cd) |
| 438 | if r.Code != 200 || err != nil || len(params) != 1 || r.Header.Get("Set-Cookie") != "" || strings.ContainsAny(cd, "\r\n") { |
| 439 | t.Errorf("%q: %d %q %v %v", name, r.Code, cd, params, err) |
| 440 | } |
| 441 | if want != "" && params["filename"] != want { |
| 442 | t.Errorf("%q: name %q, want %q", name, params["filename"], want) |
| 443 | } |
| 444 | if want == "" && strings.Contains(params["filename"], "\n") { |
| 445 | t.Errorf("%q: name %q", name, params["filename"]) |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | // A read that stalls mid-body is given up at the idle bound (Fable S2): |
| 451 | // the browser's connection is let go, and nothing more comes. |
| 452 | func TestAskAttachmentStalledReadIsDropped(t *testing.T) { |
| 453 | bounds(t, web.UploadBounds{Slots: 4, SlotWait: time.Second, ReadDeadline: 5 * time.Second, Upstream: 5 * time.Second, ReadIdle: 150 * time.Millisecond}) |
| 454 | a, f := newAskApp(t) |
| 455 | a.connectEquipo(f) |
| 456 | id := uploaded(t, a.upload("big.txt", "text/plain", bytes.Repeat([]byte("x"), 256<<10))) |
| 457 | f.ServeSlowly(2 * time.Second) // a pause after each 64 KiB, longer than the bound |
| 458 | start := time.Now() |
| 459 | res, err := a.client.Get(a.base + "/ask/attachments/" + id) |
| 460 | if err != nil { |
| 461 | t.Fatal(err) |
| 462 | } |
| 463 | got, err := io.ReadAll(res.Body) |
| 464 | res.Body.Close() |
| 465 | if took := time.Since(start); took > 1500*time.Millisecond || len(got) >= 256<<10 { |
| 466 | t.Fatalf("read %d bytes in %s (%v)", len(got), took, err) |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | // A big file streams through as Equipo writes it, never held whole. |
| 471 | func TestAskAttachmentStreams(t *testing.T) { |
| 472 | a, f := newAskApp(t) |
| 473 | a.connectEquipo(f) |
| 474 | big := bytes.Repeat([]byte("0123456789abcdef"), 9<<20/16) |
| 475 | id := uploaded(t, a.upload("big.txt", "text/plain", big)) |
| 476 | f.ServeSlowly(700 * time.Microsecond) // 144 pieces: about 0.1 s |
| 477 | start := time.Now() |
| 478 | res, err := a.client.Get(a.base + "/ask/attachments/" + id) |
| 479 | if err != nil { |
| 480 | t.Fatal(err) |
| 481 | } |
| 482 | defer res.Body.Close() |
| 483 | first := make([]byte, 1) |
| 484 | if _, err := io.ReadFull(res.Body, first); err != nil { |
| 485 | t.Fatal(err) |
| 486 | } |
| 487 | early := time.Since(start) |
| 488 | rest, err := io.ReadAll(res.Body) |
| 489 | if err != nil || len(rest)+1 != len(big) { |
| 490 | t.Fatalf("read %d bytes: %v", len(rest)+1, err) |
| 491 | } |
| 492 | if total := time.Since(start); early > total/2 { |
| 493 | t.Fatalf("the first byte came after %s of %s", early, total) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | // A file that isn't the member's, or an id that can't be one, is 404: |
| 498 | // Base asks Equipo with the member's own bearer, or not at all. |
| 499 | func TestAskAttachmentNotYours(t *testing.T) { |
| 500 | a, f := newAskApp(t) |
| 501 | a.connectEquipo(f) |
| 502 | if r := a.post("/people", invite("maria@acme.test")); r.Code != 303 { |
| 503 | t.Fatalf("invite: %d", r.Code) |
| 504 | } |
| 505 | maria := a.newBrowser() |
| 506 | if r := maria.signIn("maria@acme.test"); r.Code != 303 { |
| 507 | t.Fatalf("maria: %d", r.Code) |
| 508 | } |
| 509 | maria.approveEquipo(f) |
| 510 | theirs := uploaded(t, maria.upload("hers.txt", "text/plain", []byte("hers"))) |
| 511 | if r := a.get("/ask/attachments/" + theirs); r.Code != 404 { |
| 512 | t.Fatalf("another's: %d", r.Code) |
| 513 | } |
| 514 | for _, bad := range []string{"at_x", "AT_ABCDEFGHIJ", "at_abcdefgh%2F..", "m_0001"} { |
| 515 | if r := a.get("/ask/attachments/" + bad); r.Code != 404 { |
| 516 | t.Errorf("%s: %d", bad, r.Code) |
| 517 | } |
| 518 | if n := len(f.Calls("/api/v1/attachments/" + bad)); n != 0 { |
| 519 | t.Errorf("%s reached Equipo", bad) |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | // Without a live link a file is 404, never a redirect; a refused bearer |
| 525 | // drops the link; Equipo failing or slow is 502 with nothing of Equipo's. |
| 526 | func TestAskAttachmentUpstreamFailures(t *testing.T) { |
| 527 | bounds(t, web.UploadBounds{Slots: 4, SlotWait: time.Second, ReadDeadline: 5 * time.Second, Upstream: 150 * time.Millisecond}) |
| 528 | a, f := newAskApp(t) |
| 529 | if r := a.get("/ask/attachments/at_abcdefgh12"); r.Code != 404 { |
| 530 | t.Fatalf("not set up: %d %v", r.Code, r.Header) |
| 531 | } |
| 532 | a.connectEquipo(f) |
| 533 | id := uploaded(t, a.upload("n.txt", "text/plain", []byte("note"))) |
| 534 | f.FailReads(500) |
| 535 | if r := a.get("/ask/attachments/" + id); r.Code != 502 || r.Body != "" { |
| 536 | t.Fatalf("500: %d %q", r.Code, r.Body) |
| 537 | } |
| 538 | f.FailReads(0) |
| 539 | release := f.HoldReads() |
| 540 | start := time.Now() |
| 541 | if r := a.get("/ask/attachments/" + id); r.Code != 502 || r.Body != "" || time.Since(start) > 3*time.Second { |
| 542 | t.Fatalf("slow: %d %q after %s", r.Code, r.Body, time.Since(start)) |
| 543 | } |
| 544 | release() |
| 545 | f.RevokeAll() |
| 546 | if r := a.get("/ask/attachments/" + id); r.Code != 404 { |
| 547 | t.Fatalf("revoked: %d", r.Code) |
| 548 | } |
| 549 | if s, _ := a.askState(); s.State != "reconnect" { |
| 550 | t.Fatalf("after a refused bearer: %+v", s) |
| 551 | } |
| 552 | for _, r := range a.seen { |
| 553 | if strings.Contains(r.Body, equipotest.FileErrorBody) { |
| 554 | t.Fatalf("Equipo's error body came through: %s", r.Body) |
| 555 | } |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | // del is Remove on a chip. |
| 560 | func (a *testApp) del(id string) Resp { |
| 561 | a.t.Helper() |
| 562 | req, _ := http.NewRequest(http.MethodDelete, a.base+"/ask/attachments/"+id, nil) |
| 563 | req.Header.Set("Origin", a.origin) |
| 564 | req.Header.Set("Accept", "application/json") |
| 565 | return a.do(req) |
| 566 | } |
| 567 | |
| 568 | // Remove deletes the upload in Equipo, which frees its place among the |
| 569 | // twenty unsent (Fable B6); one already gone is done too, one sent is not. |
| 570 | func TestAskRemoveDeletesTheUpload(t *testing.T) { |
| 571 | a, f := newAskApp(t) |
| 572 | token := a.connectEquipo(f) |
| 573 | var ids []string |
| 574 | for i := 0; i < 20; i++ { |
| 575 | ids = append(ids, uploaded(t, a.upload("n.txt", "text/plain", []byte("note")))) |
| 576 | } |
| 577 | if r := a.del(ids[3]); r.Code != 204 { |
| 578 | t.Fatalf("remove: %d %s", r.Code, r.Body) |
| 579 | } |
| 580 | c := f.Calls("/api/v1/attachments/" + ids[3]) |
| 581 | if len(c) != 1 || c[0].Method != http.MethodDelete || c[0].Header.Get("Authorization") != "Bearer "+token { |
| 582 | t.Fatalf("relayed: %+v", c) |
| 583 | } |
| 584 | if r := a.del(ids[3]); r.Code != 204 { |
| 585 | t.Fatalf("again: %d", r.Code) |
| 586 | } |
| 587 | uploaded(t, a.upload("n.txt", "text/plain", []byte("note"))) |
| 588 | f.FilesReady(true) |
| 589 | f.Hold = true |
| 590 | if r := a.postJSON("/ask/messages", url.Values{"text": {"this one"}, "attachments": {ids[0]}}); r.Code != 200 { |
| 591 | t.Fatalf("send: %d %s", r.Code, r.Body) |
| 592 | } |
| 593 | if r := a.del(ids[0]); r.Code != 409 { |
| 594 | t.Fatalf("a sent file: %d %s", r.Code, r.Body) |
| 595 | } |
| 596 | if r := a.del("nope"); r.Code != 404 { |
| 597 | t.Fatalf("not an id: %d", r.Code) |
| 598 | } |
| 599 | // From another site, Remove is refused before Equipo hears of it |
| 600 | // (Fable S3). |
| 601 | req, _ := http.NewRequest(http.MethodDelete, a.base+"/ask/attachments/"+ids[5], nil) |
| 602 | req.Header.Set("Origin", "https://evil.example") |
| 603 | req.Header.Set("Accept", "application/json") |
| 604 | if r := a.do(req); r.Code != 403 || len(f.Calls("/api/v1/attachments/"+ids[5])) != 0 { |
| 605 | t.Fatalf("cross-site remove: %d", r.Code) |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | // A member can't delete or discard another member's upload (Fable S3): |
| 610 | // Base asks Equipo with their own bearer, which answers as if it were |
| 611 | // gone, so both are 204 and the upload stays. |
| 612 | func TestAskRemoveNotYours(t *testing.T) { |
| 613 | a, f := newAskApp(t) |
| 614 | a.connectEquipo(f) |
| 615 | if r := a.post("/people", invite("maria@acme.test")); r.Code != 303 { |
| 616 | t.Fatalf("invite: %d", r.Code) |
| 617 | } |
| 618 | maria := a.newBrowser() |
| 619 | if r := maria.signIn("maria@acme.test"); r.Code != 303 { |
| 620 | t.Fatalf("maria: %d", r.Code) |
| 621 | } |
| 622 | maria.approveEquipo(f) |
| 623 | hers := uploaded(t, maria.upload("hers.txt", "text/plain", []byte("hers"))) |
| 624 | if r := a.del(hers); r.Code != 204 { |
| 625 | t.Fatalf("remove: %d %s", r.Code, r.Body) |
| 626 | } |
| 627 | if r := a.post("/ask/attachments/discard", url.Values{"id": {hers}}); r.Code != 204 { |
| 628 | t.Fatalf("discard: %d", r.Code) |
| 629 | } |
| 630 | if _, _, _, _, ok := f.Upload(hers); !ok { |
| 631 | t.Fatal("another member deleted her upload") |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | // The page's beacon as it goes deletes what was never sent, as best Base |
| 636 | // can: always 204, a malformed id skipped. It comes from Base's own page. |
| 637 | func TestAskDiscard(t *testing.T) { |
| 638 | a, f := newAskApp(t) |
| 639 | a.connectEquipo(f) |
| 640 | one := uploaded(t, a.upload("a.txt", "text/plain", []byte("a"))) |
| 641 | two := uploaded(t, a.upload("b.txt", "text/plain", []byte("b"))) |
| 642 | keep := uploaded(t, a.upload("c.txt", "text/plain", []byte("c"))) |
| 643 | cross := url.Values{"id": {keep}} |
| 644 | req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/attachments/discard", strings.NewReader(cross.Encode())) |
| 645 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 646 | req.Header.Set("Origin", "https://evil.example") |
| 647 | if r := a.do(req); r.Code != 403 { |
| 648 | t.Fatalf("cross-site: %d", r.Code) |
| 649 | } |
| 650 | f.FilesReady(true) |
| 651 | f.Hold = true |
| 652 | sent := uploaded(t, a.upload("s.txt", "text/plain", []byte("s"))) |
| 653 | if r := a.postJSON("/ask/messages", url.Values{"attachments": {sent}}); r.Code != 200 { |
| 654 | t.Fatalf("send: %d", r.Code) |
| 655 | } |
| 656 | // Five at most; a malformed one skipped; one already sent (Equipo's |
| 657 | // 409) doesn't stop the rest. |
| 658 | beacon := url.Values{"id": {sent, one, "../../etc", two, "at_abcdefgh99", keep}} |
| 659 | req, _ = http.NewRequest(http.MethodPost, a.base+"/ask/attachments/discard", strings.NewReader(beacon.Encode())) |
| 660 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 661 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 662 | if r := a.do(req); r.Code != 204 { |
| 663 | t.Fatalf("beacon: %d %s", r.Code, r.Body) |
| 664 | } |
| 665 | left := map[string]bool{} |
| 666 | for _, id := range f.Uploads() { |
| 667 | left[id] = true |
| 668 | } |
| 669 | if len(left) != 2 || !left[keep] || !left[sent] { |
| 670 | t.Fatalf("left: %v", left) |
| 671 | } |
| 672 | if r := a.newBrowser().post("/ask/attachments/discard", url.Values{"id": {keep}}); r.Code == 204 || len(f.Uploads()) != 2 { |
| 673 | t.Fatalf("signed out: %d", r.Code) |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | // A send carries its files in order, and may have no words; Base's own |
| 678 | // checks come first, and refusals of the files keep Ask ready (Fable B1, |
| 679 | // B2). |
| 680 | func TestAskSendWithFiles(t *testing.T) { |
| 681 | a, f := newAskApp(t) |
| 682 | a.connectEquipo(f) |
| 683 | f.FilesReady(true) |
| 684 | f.Hold = true |
| 685 | one := uploaded(t, a.upload("a.md", "text/markdown", []byte("# A"))) |
| 686 | two := uploaded(t, a.upload("b.png", "image/png", pngFile(t, 3, 3))) |
| 687 | r := a.postJSON("/ask/messages", url.Values{"text": {"Look at these"}, "attachments": {two, one}, "key": {"k-files"}}) |
| 688 | var sent struct { |
| 689 | Message struct { |
| 690 | Attachments []struct{ ID, Kind, Name string } |
| 691 | } |
| 692 | } |
| 693 | if r.Code != 200 || json.Unmarshal([]byte(r.Body), &sent) != nil || len(sent.Message.Attachments) != 2 || sent.Message.Attachments[0].ID != two { |
| 694 | t.Fatalf("send: %d %s", r.Code, r.Body) |
| 695 | } |
| 696 | calls := f.Calls("/api/v1/assistant/messages") |
| 697 | if c := calls[len(calls)-1]; c.Header.Get("Idempotency-Key") != "k-files" || !strings.Contains(c.Body, `"attachments":["`+two+`","`+one+`"]`) { |
| 698 | t.Fatalf("relayed: %v %s", c.Header, c.Body) |
| 699 | } |
| 700 | three := uploaded(t, a.upload("c.txt", "text/plain", []byte("c"))) |
| 701 | if r := a.postJSON("/ask/messages", url.Values{"text": {" "}, "attachments": {three}}); r.Code != 200 { |
| 702 | t.Fatalf("files only: %d %s", r.Code, r.Body) |
| 703 | } |
| 704 | // Words alone go as they always did: no attachments key. |
| 705 | if r := a.postJSON("/ask/messages", url.Values{"text": {"just words"}}); r.Code != 200 { |
| 706 | t.Fatalf("words: %d", r.Code) |
| 707 | } |
| 708 | calls = f.Calls("/api/v1/assistant/messages") |
| 709 | if c := calls[len(calls)-1]; strings.Contains(c.Body, "attachments") { |
| 710 | t.Fatalf("words-only body: %s", c.Body) |
| 711 | } |
| 712 | before := len(calls) |
| 713 | six := []string{} |
| 714 | for i := 0; i < 6; i++ { |
| 715 | six = append(six, uploaded(t, a.upload("n.txt", "text/plain", []byte("n")))) |
| 716 | } |
| 717 | for name, form := range map[string]url.Values{ |
| 718 | "six files": {"text": {"hi"}, "attachments": six}, |
| 719 | "malformed id": {"text": {"hi"}, "attachments": {"at_../x"}}, |
| 720 | "nothing at all": {"text": {" "}}, |
| 721 | "a NUL": {"text": {"hi\x00there"}, "attachments": {six[0]}}, |
| 722 | "invalid UTF-8": {"text": {"hi \xff"}, "attachments": {six[0]}}, |
| 723 | "words too long": {"text": {strings.Repeat("a", 16<<10+1)}, "attachments": {six[0]}}, |
| 724 | "an empty id too": {"text": {"hi"}, "attachments": {""}}, |
| 725 | "one id twice": {"text": {"hi"}, "attachments": {six[0], six[0]}}, |
| 726 | } { |
| 727 | r := a.postJSON("/ask/messages", form) |
| 728 | if _, state, files := codeOf(r); r.Code != 422 || state != "ready" || files != "" { |
| 729 | t.Errorf("%s: %d %s", name, r.Code, r.Body) |
| 730 | } |
| 731 | } |
| 732 | if n := len(f.Calls("/api/v1/assistant/messages")); n != before { |
| 733 | t.Fatalf("Base's own refusals reached Equipo: %d", n-before) |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | // A runner that can't take files leaves Ask ready, and the words can go |
| 738 | // alone; an upload Equipo dropped is stale. |
| 739 | func TestAskSendFilesRefused(t *testing.T) { |
| 740 | a, f := newAskApp(t) |
| 741 | a.connectEquipo(f) |
| 742 | f.Hold = true |
| 743 | id := uploaded(t, a.upload("a.md", "text/markdown", []byte("# A"))) |
| 744 | r := a.postJSON("/ask/messages", url.Values{"text": {"Read this"}, "attachments": {id}}) |
| 745 | if _, state, files := codeOf(r); r.Code != 409 || state != "ready" || files != "unavailable" { |
| 746 | t.Fatalf("unavailable: %d %s", r.Code, r.Body) |
| 747 | } |
| 748 | if s, _ := a.askState(); s.State != "ready" { |
| 749 | t.Fatalf("state: %+v", s) |
| 750 | } |
| 751 | if r := a.postJSON("/ask/messages", url.Values{"text": {"Read this"}}); r.Code != 200 { |
| 752 | t.Fatalf("words after: %d %s", r.Code, r.Body) |
| 753 | } |
| 754 | f.FilesReady(true) |
| 755 | f.ExpireUploads() |
| 756 | r = a.postJSON("/ask/messages", url.Values{"text": {"Read this"}, "attachments": {id}}) |
| 757 | if _, state, files := codeOf(r); r.Code != 422 || state != "ready" || files != "stale" { |
| 758 | t.Fatalf("stale: %d %s", r.Code, r.Body) |
| 759 | } |
| 760 | // Words alone refused for an old runner keep today's state. |
| 761 | f.RunnerTooOld() |
| 762 | r = a.postJSON("/ask/messages", url.Values{"text": {"words"}}) |
| 763 | if _, state, _ := codeOf(r); r.Code != 409 || state != "oldrunner" { |
| 764 | t.Fatalf("old runner, words: %d %s", r.Code, r.Body) |
| 765 | } |
| 766 | r = a.postJSON("/ask/messages", url.Values{"text": {"words"}, "attachments": {id}}) |
| 767 | if _, state, files := codeOf(r); r.Code != 409 || state != "ready" || files != "unavailable" { |
| 768 | t.Fatalf("old runner, files: %d %s", r.Code, r.Body) |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | // The conversation read afresh carries each message's files, and says |
| 773 | // the paperclip may show only when Equipo says the runner can take them. |
| 774 | func TestAskStateCarriesFiles(t *testing.T) { |
| 775 | a, f := newAskApp(t) |
| 776 | a.connectEquipo(f) |
| 777 | var st struct { |
| 778 | CanAttach bool `json:"can_attach"` |
| 779 | Messages []struct { |
| 780 | Attachments []map[string]any |
| 781 | } |
| 782 | } |
| 783 | read := func() { |
| 784 | t.Helper() |
| 785 | st.Messages = nil |
| 786 | if r := a.get("/ask/state"); r.Code != 200 || json.Unmarshal([]byte(r.Body), &st) != nil { |
| 787 | t.Fatalf("state: %d %s", r.Code, r.Body) |
| 788 | } |
| 789 | } |
| 790 | if read(); st.CanAttach { |
| 791 | t.Fatal("can_attach before Equipo said so") |
| 792 | } |
| 793 | f.FilesReady(true) |
| 794 | f.Hold = true |
| 795 | if read(); !st.CanAttach { |
| 796 | t.Fatal("no can_attach") |
| 797 | } |
| 798 | id := uploaded(t, a.upload("q3.csv", "text/csv", []byte("a,b\n"))) |
| 799 | if r := a.postJSON("/ask/messages", url.Values{"attachments": {id}}); r.Code != 200 { |
| 800 | t.Fatalf("send: %d %s", r.Code, r.Body) |
| 801 | } |
| 802 | read() |
| 803 | got := st.Messages[len(st.Messages)-1].Attachments |
| 804 | if len(got) != 1 || got[0]["id"] != id || got[0]["name"] != "q3.csv" || got[0]["kind"] != "file" || len(got[0]) != 7 { |
| 805 | t.Fatalf("files: %+v", got) |
| 806 | } |
| 807 | f.NoRunner() |
| 808 | if read(); st.CanAttach { |
| 809 | t.Fatal("can_attach without a runner") |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | // A message event carries its files. |
| 814 | func TestAskEventsCarryFiles(t *testing.T) { |
| 815 | a, f := newAskApp(t) |
| 816 | a.connectEquipo(f) |
| 817 | f.FilesReady(true) |
| 818 | var st struct{ Cursor int64 } |
| 819 | _ = json.Unmarshal([]byte(a.get("/ask/state").Body), &st) |
| 820 | id := uploaded(t, a.upload("shot.png", "image/png", pngFile(t, 5, 4))) |
| 821 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 822 | defer cancel() |
| 823 | req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+strconv64(st.Cursor), nil) |
| 824 | res, err := a.client.Do(req) |
| 825 | if err != nil { |
| 826 | t.Fatal(err) |
| 827 | } |
| 828 | defer res.Body.Close() |
| 829 | a.postJSON("/ask/messages", url.Values{"text": {"this"}, "attachments": {id}}) |
| 830 | sc := bufio.NewScanner(res.Body) |
| 831 | for sc.Scan() { |
| 832 | line := sc.Text() |
| 833 | if strings.HasPrefix(line, "data: ") && strings.Contains(line, `"role":"person"`) { |
| 834 | if !strings.Contains(line, `"attachments":[{"id":"`+id+`","kind":"image","name":"shot.png","media_type":"image/png","size":`) || |
| 835 | !strings.Contains(line, `"width":5,"height":4}]`) { |
| 836 | t.Fatalf("message event: %s", line) |
| 837 | } |
| 838 | return |
| 839 | } |
| 840 | } |
| 841 | t.Fatal("no message event") |
| 842 | } |
| 843 | |
| 844 | // Without scripts the thread shows a person's files above their words: a |
| 845 | // thumbnail linking to the image, a pill downloading anything else, both |
| 846 | // from Base; a message of files alone has no empty words. |
| 847 | func TestAskThreadDrawsFiles(t *testing.T) { |
| 848 | a, f := newAskApp(t) |
| 849 | a.connectEquipo(f) |
| 850 | f.FilesReady(true) |
| 851 | f.Hold = true |
| 852 | shot := uploaded(t, a.upload("Screen <1>.png", "image/png", pngFile(t, 64, 48))) |
| 853 | csv := uploaded(t, a.upload("sales.csv", "text/csv", bytes.Repeat([]byte("1,2\n"), 300))) |
| 854 | if r := a.postJSON("/ask/messages", url.Values{"text": {"These two"}, "attachments": {shot, csv}}); r.Code != 200 { |
| 855 | t.Fatalf("send: %d %s", r.Code, r.Body) |
| 856 | } |
| 857 | lone := uploaded(t, a.upload("q.md", "text/markdown", []byte("# Q"))) |
| 858 | if r := a.postJSON("/ask/messages", url.Values{"attachments": {lone}}); r.Code != 200 { |
| 859 | t.Fatalf("send: %d %s", r.Code, r.Body) |
| 860 | } |
| 861 | page := a.get("/ask") |
| 862 | for _, want := range []string{ |
| 863 | `<div class="files" role="group" aria-label="Attached files"><a class="thumb" href="/ask/attachments/` + shot + `" data-attachment="` + shot + `"><img loading="lazy" src="/ask/attachments/` + shot + `/preview" alt="Screen <1>.png" width="64" height="48"></a>`, |
| 864 | `<a class="file" href="/ask/attachments/` + csv + `" download aria-label="sales.csv, 1 KB. Download">`, |
| 865 | `<span class="file-name">sales.csv</span><span class="file-size">1 KB</span></a></div>These two</li>`, |
| 866 | `<li class="msg person" data-id="`, |
| 867 | `<span class="file-name">q.md</span><span class="file-size">3 B</span></a></div></li>`, |
| 868 | } { |
| 869 | if !strings.Contains(page.Body, want) { |
| 870 | t.Errorf("page lacks %s", want) |
| 871 | } |
| 872 | } |
| 873 | // Every file comes from Base: no address of Equipo's API, and nothing |
| 874 | // the page's img-src 'self' data: would refuse. |
| 875 | if strings.Contains(page.Body, "/api/v1/attachments") || strings.Contains(page.Body, "blob:") { |
| 876 | t.Error("the page links a file somewhere other than Base") |
| 877 | } |
| 878 | } |
| 879 | |
| 880 | // A turn that failed for its files says why under the conversation, |
| 881 | // without scripts too; any other failure says nothing new there. |
| 882 | func TestAskTurnFailedForFiles(t *testing.T) { |
| 883 | a, f := newAskApp(t) |
| 884 | a.connectEquipo(f) |
| 885 | f.Hold = true |
| 886 | for reason, want := range map[string]string{ |
| 887 | "attachment_unavailable": "A file didn’t arrive whole. Attach it again.", |
| 888 | "runner_storage_full": "There’s no room left for these files. Try fewer or smaller ones.", |
| 889 | "runner_too_old": "Files can’t be read right now. Send it again without them.", |
| 890 | "model_error": "", |
| 891 | } { |
| 892 | r := a.postJSON("/ask/messages", url.Values{"text": {"about " + reason}}) |
| 893 | var sent struct{ Turn struct{ ID string } } |
| 894 | if json.Unmarshal([]byte(r.Body), &sent) != nil || sent.Turn.ID == "" { |
| 895 | t.Fatalf("send: %s", r.Body) |
| 896 | } |
| 897 | waitTurn := func(state string) { |
| 898 | for i := 0; f.Turn(sent.Turn.ID) != state; i++ { |
| 899 | if i > 200 { |
| 900 | t.Fatalf("turn %s", f.Turn(sent.Turn.ID)) |
| 901 | } |
| 902 | time.Sleep(10 * time.Millisecond) |
| 903 | } |
| 904 | } |
| 905 | waitTurn("running") |
| 906 | f.FailTurnFor(sent.Turn.ID, reason) |
| 907 | page := a.get("/ask").Body |
| 908 | got := regexp.MustCompile(`<p class="ask-status" role="status">([^<]*)</p>`).FindStringSubmatch(page) |
| 909 | if got == nil || html.UnescapeString(got[1]) != want { |
| 910 | t.Errorf("%s: status %q, want %q", reason, got, want) |
| 911 | } |
| 912 | var st struct{ Status string } |
| 913 | _ = json.Unmarshal([]byte(a.get("/ask/state").Body), &st) |
| 914 | if st.Status != want { |
| 915 | t.Errorf("%s: state status %q", reason, st.Status) |
| 916 | } |
| 917 | } |
| 918 | } |
| 919 | |