package webtest import ( "bufio" "bytes" "context" "encoding/json" "fmt" "html" "image" "image/color" "image/png" "io" "mime" "net" "net/http" "net/url" "regexp" "strings" "sync" "testing" "time" "amadan.net/oficina/base/internal/equipo/equipotest" "amadan.net/oficina/base/internal/web" ) // pngFile is a w×h PNG. func pngFile(t *testing.T, w, h int) []byte { t.Helper() img := image.NewNRGBA(image.Rect(0, 0, w, h)) img.Set(0, 0, color.NRGBA{G: 180, A: 255}) var b bytes.Buffer if err := png.Encode(&b, img); err != nil { t.Fatal(err) } return b.Bytes() } // uploadReq is an upload as the page's script makes it. func (a *testApp) uploadReq(ctx context.Context, name, typ string, body io.Reader) *http.Request { req, _ := http.NewRequestWithContext(ctx, http.MethodPost, a.base+"/ask/attachments", body) req.Header.Set("Content-Type", typ) req.Header.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name})) req.Header.Set("Origin", a.origin) req.Header.Set("Accept", "application/json") return req } func (a *testApp) upload(name, typ string, body []byte) Resp { a.t.Helper() return a.do(a.uploadReq(context.Background(), name, typ, bytes.NewReader(body))) } // uploaded is the id an upload answered with. func uploaded(t *testing.T, r Resp) string { t.Helper() var at struct{ ID string } if r.Code != 201 || json.Unmarshal([]byte(r.Body), &at) != nil || at.ID == "" { t.Fatalf("upload: %d %s", r.Code, r.Body) } return at.ID } // bounds makes the upload relay's bounds b for the apps the test builds. func bounds(t *testing.T, b web.UploadBounds) { t.Cleanup(web.SetUploadBounds(b)) } // codeOf is the JSON answer's code and state. func codeOf(r Resp) (code, state, files string) { var out struct{ Code, State, Files string } _ = json.Unmarshal([]byte(r.Body), &out) return out.Code, out.State, out.Files } // A member's upload goes to Equipo with their bearer, its name and type, // and comes back as Equipo's attachment, never cached. func TestAskUploadRelays(t *testing.T) { a, f := newAskApp(t) token := a.connectEquipo(f) shot := pngFile(t, 30, 20) r := a.upload("Screen Shot día.png", "image/png", shot) id := uploaded(t, r) wantKeys(t, "upload", r.Body, "id", "kind", "name", "media_type", "size", "width", "height") var at struct { Kind, Name string MediaType string `json:"media_type"` Width, Height int Size int64 } _ = json.Unmarshal([]byte(r.Body), &at) 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)) { t.Fatalf("answer: %v %s", r.Header, r.Body) } data, name, media, _, ok := f.Upload(id) if !ok || !bytes.Equal(data, shot) || name != "Screen Shot día.png" || media != "image/png" { t.Fatalf("Equipo holds %d bytes %q %q %v", len(data), name, media, ok) } c := f.Calls("/api/v1/attachments")[0] if c.Header.Get("Authorization") != "Bearer "+token || c.Header.Get("Cookie") != "" || c.Header.Get("Origin") != "" || len(c.Header.Values("Idempotency-Key")) != 0 { t.Fatalf("relayed headers: %v", c.Header) } a.noLeak(token) } // A body of unknown length is refused before Equipo hears of it (Fable // N1): a browser always says a File's length. (A declared length over // 10 MiB is in TestAskUploadStalledBodyFreesItsSlot, which already pays // for a body the server never reads.) func TestAskUploadTooBig(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) req := a.uploadReq(context.Background(), "big.txt", "text/plain", io.MultiReader(strings.NewReader("a few bytes"))) req.ContentLength = -1 r := a.do(req) if code, _, _ := codeOf(r); r.Code != 411 || code != "length_required" { t.Fatalf("undeclared: %d %s", r.Code, r.Body) } if n := len(f.Calls("/api/v1/attachments")); n != 0 { t.Fatalf("Equipo heard %d uploads", n) } } // Equipo's refusals come back with its status and code. func TestAskUploadRefusals(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) heic := append([]byte("\x00\x00\x00\x18ftypheic"), make([]byte, 64)...) for name, tc := range map[string]struct { body []byte typ string status int code string }{ "type": {[]byte("\x00\x01\x02binary"), "application/octet-stream", 415, "attachment_type"}, "heic": {heic, "image/heic", 415, "attachment_heic"}, "pixels": {pngFile(t, 1, 12001), "image/png", 413, "attachment_pixels"}, } { r := a.upload("x", tc.typ, tc.body) if code, _, _ := codeOf(r); r.Code != tc.status || code != tc.code { t.Errorf("%s: %d %s", name, r.Code, r.Body) } } for i := 0; i < 20; i++ { uploaded(t, a.upload("n.txt", "text/plain", []byte("note"))) } r := a.upload("n.txt", "text/plain", []byte("note")) if code, _, _ := codeOf(r); r.Code != 409 || code != "attachment_limit" { t.Fatalf("21st: %d %s", r.Code, r.Body) } } // An upload needs what every Ask write needs: a member, from Base's own // pages, with Ask set up; Equipo refusing the bearer drops the link. func TestAskUploadNeedsAskReady(t *testing.T) { a, f := newAskApp(t) r := a.upload("n.txt", "text/plain", []byte("note")) if _, state, _ := codeOf(r); r.Code != 409 || state != "connect" { t.Fatalf("not set up: %d %s", r.Code, r.Body) } a.connectEquipo(f) req := a.uploadReq(context.Background(), "n.txt", "text/plain", strings.NewReader("note")) req.Header.Set("Origin", "https://evil.example") if r := a.do(req); r.Code != 403 { t.Fatalf("cross-site: %d", r.Code) } if r := a.newBrowser().upload("n.txt", "text/plain", []byte("note")); r.Code != 401 { t.Fatalf("signed out: %d %s", r.Code, r.Body) } if n := len(f.Calls("/api/v1/attachments")); n != 0 { t.Fatalf("Equipo heard %d uploads", n) } f.RevokeAll() r = a.upload("n.txt", "text/plain", []byte("note")) if _, state, _ := codeOf(r); r.Code != 409 || state != "reconnect" { t.Fatalf("revoked: %d %s", r.Code, r.Body) } if s, _ := a.askState(); s.State != "reconnect" { t.Fatalf("after a refused bearer: %+v", s) } // A code waiting for approval is not ready either. b, g := newAskApp(t) b.post("/ask/connect", url.Values{"next": {"ask"}}) r = b.upload("n.txt", "text/plain", []byte("note")) if _, state, _ := codeOf(r); r.Code != 409 || state != "pending" || len(g.Calls("/api/v1/attachments")) != 0 { t.Fatalf("pending: %d %s", r.Code, r.Body) } } // Where no read deadline can be set (here, Base served in-process with // no connection under it), an upload is refused before its body is read: // never read without one. func TestAskUploadNeedsAReadDeadline(t *testing.T) { web, app, f := newNativeAskApp(t) web.approveEquipo(f) req, _ := http.NewRequest(http.MethodPost, app.base+"/ask/attachments", strings.NewReader("# Notes")) req.Header.Set("Content-Type", "text/markdown") req.Header.Set("Origin", homeOrigin) req.Header.Set("Accept", "application/json") r := app.do(req) if code, _, _ := codeOf(r); r.Code != 503 || code != "busy" || len(f.Calls("/api/v1/attachments")) != 0 { t.Fatalf("in-process upload: %d %s", r.Code, r.Body) } } // cookieHeader is the session cookies a raw request must carry. func (a *testApp) cookieHeader() string { u, _ := url.Parse(a.base) var parts []string for _, c := range a.client.Jar.Cookies(u) { parts = append(parts, c.Name+"="+c.Value) } return strings.Join(parts, "; ") } // uploadAll sends n uploads at once and answers their statuses. func (a *testApp) uploadAll(n int) []int { var wg sync.WaitGroup out := make([]int, n) for i := range n { wg.Go(func() { res, err := a.client.Do(a.uploadReq(context.Background(), fmt.Sprintf("n%d.txt", i), "text/plain", strings.NewReader("note"))) if err != nil { return } io.Copy(io.Discard, res.Body) res.Body.Close() out[i] = res.StatusCode }) } wg.Wait() return out } // A body that stalls loses its slot at the read deadline, through the // whole router (Fable B3): afterwards four uploads at once all pass. A // declared length over 10 MiB is refused from the headers alone. func TestAskUploadStalledBodyFreesItsSlot(t *testing.T) { bounds(t, web.UploadBounds{Slots: 4, SlotWait: 40 * time.Millisecond, ReadDeadline: 100 * time.Millisecond, Upstream: 5 * time.Second}) a, f := newAskApp(t) a.connectEquipo(f) u, _ := url.Parse(a.base) conn, err := net.Dial("tcp", u.Host) if err != nil { t.Fatal(err) } defer conn.Close() fmt.Fprintf(conn, "POST /ask/attachments HTTP/1.1\r\nHost: %s\r\nOrigin: %s\r\nAccept: application/json\r\nCookie: %s\r\n"+ "Content-Type: text/plain\r\nContent-Disposition: attachment; filename=\"s.txt\"\r\nContent-Length: 1000\r\n\r\n%s", u.Host, a.origin, a.cookieHeader(), strings.Repeat("a", 500)) start := time.Now() _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) res, err := http.ReadResponse(bufio.NewReader(conn), nil) if took := time.Since(start); took > 3*time.Second || err == nil && res.StatusCode != 400 { t.Fatalf("the stalled upload held on for %s (%v %v)", took, res, err) } big, err := net.Dial("tcp", u.Host) if err != nil { t.Fatal(err) } defer big.Close() fmt.Fprintf(big, "POST /ask/attachments HTTP/1.1\r\nHost: %s\r\nOrigin: %s\r\nAccept: application/json\r\nCookie: %s\r\n"+ "Content-Type: text/plain\r\nContent-Length: %d\r\n\r\n", u.Host, a.origin, a.cookieHeader(), 10<<20+1) _ = big.SetReadDeadline(time.Now().Add(5 * time.Second)) if res, err := http.ReadResponse(bufio.NewReader(big), nil); err != nil || res.StatusCode != 413 { t.Fatalf("declared over 10 MiB: %v %v", res, err) } f.SlowUploads(80 * time.Millisecond) for i, code := range a.uploadAll(4) { if code != 201 { t.Fatalf("upload %d after the stall: %d", i, code) } } } // Every slot busy: a fifth upload waits, then is told to come back. func TestAskUploadBusy(t *testing.T) { bounds(t, web.UploadBounds{Slots: 4, SlotWait: 60 * time.Millisecond, ReadDeadline: 5 * time.Second, Upstream: 10 * time.Second}) a, f := newAskApp(t) a.connectEquipo(f) f.SlowUploads(300 * time.Millisecond) done := make(chan []int) go func() { done <- a.uploadAll(4) }() for i := 0; f.UploadsAtOnce() < 4; i++ { if i > 200 { t.Fatalf("only %d uploads reached Equipo", f.UploadsAtOnce()) } time.Sleep(10 * time.Millisecond) } r := a.upload("fifth.txt", "text/plain", []byte("note")) if code, _, _ := codeOf(r); r.Code != 503 || r.Header.Get("Retry-After") != "2" || code != "busy" { t.Fatalf("fifth: %d %v %s", r.Code, r.Header, r.Body) } for i, code := range <-done { if code != 201 { t.Fatalf("upload %d: %d", i, code) } } } // The slot comes before the body: with eight uploads at once, no more // than four bodies are ever being read. func TestAskUploadSlotComesFirst(t *testing.T) { bounds(t, web.UploadBounds{Slots: 4, SlotWait: 10 * time.Second, ReadDeadline: 5 * time.Second, Upstream: 10 * time.Second}) var mu sync.Mutex most := 0 web.UploadReading = func(n int) { mu.Lock(); most = max(most, n); mu.Unlock() } t.Cleanup(func() { web.UploadReading = nil }) a, f := newAskApp(t) a.connectEquipo(f) f.SlowUploads(80 * time.Millisecond) for i, code := range a.uploadAll(8) { if code != 201 { t.Fatalf("upload %d: %d", i, code) } } mu.Lock() defer mu.Unlock() if most > 4 || most < 2 || f.UploadsAtOnce() > 4 { t.Fatalf("bodies read at once: %d; Equipo had %d", most, f.UploadsAtOnce()) } } // An upload whose page has gone (Remove aborted it) while Equipo took it // is deleted once Equipo answers. func TestAskUploadGoneMidFlightIsDeleted(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) entered, release := f.HoldNextUpload() ctx, cancel := context.WithCancel(context.Background()) errc := make(chan error, 1) go func() { res, err := a.client.Do(a.uploadReq(ctx, "n.txt", "text/plain", strings.NewReader("note"))) if err == nil { res.Body.Close() } errc <- err }() <-entered cancel() if err := <-errc; err == nil { t.Fatal("the request finished") } time.Sleep(100 * time.Millisecond) release() for i := 0; ; i++ { deletes := 0 for _, c := range f.Calls("") { if c.Method == http.MethodDelete && strings.HasPrefix(c.Path, "/api/v1/attachments/") { deletes++ } } if len(f.Uploads()) == 0 && deletes == 1 { return } if i > 100 { t.Fatalf("held %v, %d deletes", f.Uploads(), deletes) } time.Sleep(20 * time.Millisecond) } } // A picture shows inline, with headers Base decides; its preview may be // kept for an hour by this browser alone, the original not at all. func TestAskAttachmentImage(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) shot := pngFile(t, 12, 10) id := uploaded(t, a.upload("shot.png", "image/png", shot)) for _, path := range []string{"/ask/attachments/" + id, "/ask/attachments/" + id + "/preview"} { r := a.get(path) h := r.Header if r.Code != 200 || r.Body != string(shot) || h.Get("Content-Type") != "image/png" || h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Content-Security-Policy") != "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox" || h.Get("X-Equipo-Only") != "" { t.Fatalf("%s: %d %v", path, r.Code, h) } if _, p, err := mime.ParseMediaType(h.Get("Content-Disposition")); err != nil || !strings.HasPrefix(h.Get("Content-Disposition"), "inline") || p["filename"] != "shot.png" { t.Fatalf("%s disposition: %q", path, h.Get("Content-Disposition")) } preview := strings.HasSuffix(path, "/preview") if preview && (h.Get("Cache-Control") != "private, max-age=3600" || !strings.Contains(strings.Join(h.Values("Vary"), ","), "Cookie")) || !preview && h.Get("Cache-Control") != "no-store" { t.Fatalf("%s caching: %v", path, h) } } req, _ := http.NewRequest(http.MethodHead, a.base+"/ask/attachments/"+id, nil) if r := a.do(req); r.Code != 200 || r.Body != "" || r.Header.Get("Content-Type") != "image/png" { t.Fatalf("HEAD: %d %v", r.Code, r.Header) } } // Every other file is a download; text says it is UTF-8. func TestAskAttachmentDownload(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) id := uploaded(t, a.upload("sales.csv", "text/csv", []byte("a,b\n1,2\n"))) r := a.get("/ask/attachments/" + id) if r.Code != 200 || r.Header.Get("Content-Type") != "text/csv; charset=utf-8" || !strings.HasPrefix(r.Header.Get("Content-Disposition"), "attachment") { t.Fatalf("csv: %d %v", r.Code, r.Header) } if r := a.get("/ask/attachments/" + id + "/preview"); r.Code != 404 { t.Fatalf("a file's preview: %d", r.Code) } } // Base never trusts Equipo's type or disposition (Fable B4): HTML said to // be inline goes as a download, an SVG as an octet stream, and neither // has a preview. A hostile name can't add a parameter or a header, and a // missing one reads "file" (Fable S3). func TestAskAttachmentHostileUpstream(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) note := uploaded(t, a.upload("x.txt", "text/plain", []byte(""))) shot := uploaded(t, a.upload("x.png", "image/png", pngFile(t, 2, 2))) for typ, id := range map[string]string{"text/html; charset=utf-8": note, "image/svg+xml": shot} { f.ServeHostile(typ, "inline") r := a.get("/ask/attachments/" + id) if r.Code != 200 || r.Header.Get("Content-Type") != "application/octet-stream" || !strings.HasPrefix(r.Header.Get("Content-Disposition"), "attachment") { t.Errorf("%s: %d %v", typ, r.Code, r.Header) } if r := a.get("/ask/attachments/" + id + "/preview"); r.Code != 404 { t.Errorf("%s preview: %d", typ, r.Code) } } f.ServeHostile("", "") for name, want := range map[string]string{ "a\"; filename=evil.html; x=\"\r\nSet-Cookie: a=b.txt": "", "résumé; final.txt": "résumé; final.txt", "": "file", } { id := uploaded(t, a.upload(name, "text/plain", []byte("note"))) r := a.get("/ask/attachments/" + id) cd := r.Header.Get("Content-Disposition") _, params, err := mime.ParseMediaType(cd) if r.Code != 200 || err != nil || len(params) != 1 || r.Header.Get("Set-Cookie") != "" || strings.ContainsAny(cd, "\r\n") { t.Errorf("%q: %d %q %v %v", name, r.Code, cd, params, err) } if want != "" && params["filename"] != want { t.Errorf("%q: name %q, want %q", name, params["filename"], want) } if want == "" && strings.Contains(params["filename"], "\n") { t.Errorf("%q: name %q", name, params["filename"]) } } } // A read that stalls mid-body is given up at the idle bound (Fable S2): // the browser's connection is let go, and nothing more comes. func TestAskAttachmentStalledReadIsDropped(t *testing.T) { bounds(t, web.UploadBounds{Slots: 4, SlotWait: time.Second, ReadDeadline: 5 * time.Second, Upstream: 5 * time.Second, ReadIdle: 150 * time.Millisecond}) a, f := newAskApp(t) a.connectEquipo(f) id := uploaded(t, a.upload("big.txt", "text/plain", bytes.Repeat([]byte("x"), 256<<10))) f.ServeSlowly(2 * time.Second) // a pause after each 64 KiB, longer than the bound start := time.Now() res, err := a.client.Get(a.base + "/ask/attachments/" + id) if err != nil { t.Fatal(err) } got, err := io.ReadAll(res.Body) res.Body.Close() if took := time.Since(start); took > 1500*time.Millisecond || len(got) >= 256<<10 { t.Fatalf("read %d bytes in %s (%v)", len(got), took, err) } } // A big file streams through as Equipo writes it, never held whole. func TestAskAttachmentStreams(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) big := bytes.Repeat([]byte("0123456789abcdef"), 9<<20/16) id := uploaded(t, a.upload("big.txt", "text/plain", big)) f.ServeSlowly(700 * time.Microsecond) // 144 pieces: about 0.1 s start := time.Now() res, err := a.client.Get(a.base + "/ask/attachments/" + id) if err != nil { t.Fatal(err) } defer res.Body.Close() first := make([]byte, 1) if _, err := io.ReadFull(res.Body, first); err != nil { t.Fatal(err) } early := time.Since(start) rest, err := io.ReadAll(res.Body) if err != nil || len(rest)+1 != len(big) { t.Fatalf("read %d bytes: %v", len(rest)+1, err) } if total := time.Since(start); early > total/2 { t.Fatalf("the first byte came after %s of %s", early, total) } } // A file that isn't the member's, or an id that can't be one, is 404: // Base asks Equipo with the member's own bearer, or not at all. func TestAskAttachmentNotYours(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) if r := a.post("/people", invite("maria@acme.test")); r.Code != 303 { t.Fatalf("invite: %d", r.Code) } maria := a.newBrowser() if r := maria.signIn("maria@acme.test"); r.Code != 303 { t.Fatalf("maria: %d", r.Code) } maria.approveEquipo(f) theirs := uploaded(t, maria.upload("hers.txt", "text/plain", []byte("hers"))) if r := a.get("/ask/attachments/" + theirs); r.Code != 404 { t.Fatalf("another's: %d", r.Code) } for _, bad := range []string{"at_x", "AT_ABCDEFGHIJ", "at_abcdefgh%2F..", "m_0001"} { if r := a.get("/ask/attachments/" + bad); r.Code != 404 { t.Errorf("%s: %d", bad, r.Code) } if n := len(f.Calls("/api/v1/attachments/" + bad)); n != 0 { t.Errorf("%s reached Equipo", bad) } } } // Without a live link a file is 404, never a redirect; a refused bearer // drops the link; Equipo failing or slow is 502 with nothing of Equipo's. func TestAskAttachmentUpstreamFailures(t *testing.T) { bounds(t, web.UploadBounds{Slots: 4, SlotWait: time.Second, ReadDeadline: 5 * time.Second, Upstream: 150 * time.Millisecond}) a, f := newAskApp(t) if r := a.get("/ask/attachments/at_abcdefgh12"); r.Code != 404 { t.Fatalf("not set up: %d %v", r.Code, r.Header) } a.connectEquipo(f) id := uploaded(t, a.upload("n.txt", "text/plain", []byte("note"))) f.FailReads(500) if r := a.get("/ask/attachments/" + id); r.Code != 502 || r.Body != "" { t.Fatalf("500: %d %q", r.Code, r.Body) } f.FailReads(0) release := f.HoldReads() start := time.Now() if r := a.get("/ask/attachments/" + id); r.Code != 502 || r.Body != "" || time.Since(start) > 3*time.Second { t.Fatalf("slow: %d %q after %s", r.Code, r.Body, time.Since(start)) } release() f.RevokeAll() if r := a.get("/ask/attachments/" + id); r.Code != 404 { t.Fatalf("revoked: %d", r.Code) } if s, _ := a.askState(); s.State != "reconnect" { t.Fatalf("after a refused bearer: %+v", s) } for _, r := range a.seen { if strings.Contains(r.Body, equipotest.FileErrorBody) { t.Fatalf("Equipo's error body came through: %s", r.Body) } } } // del is Remove on a chip. func (a *testApp) del(id string) Resp { a.t.Helper() req, _ := http.NewRequest(http.MethodDelete, a.base+"/ask/attachments/"+id, nil) req.Header.Set("Origin", a.origin) req.Header.Set("Accept", "application/json") return a.do(req) } // Remove deletes the upload in Equipo, which frees its place among the // twenty unsent (Fable B6); one already gone is done too, one sent is not. func TestAskRemoveDeletesTheUpload(t *testing.T) { a, f := newAskApp(t) token := a.connectEquipo(f) var ids []string for i := 0; i < 20; i++ { ids = append(ids, uploaded(t, a.upload("n.txt", "text/plain", []byte("note")))) } if r := a.del(ids[3]); r.Code != 204 { t.Fatalf("remove: %d %s", r.Code, r.Body) } c := f.Calls("/api/v1/attachments/" + ids[3]) if len(c) != 1 || c[0].Method != http.MethodDelete || c[0].Header.Get("Authorization") != "Bearer "+token { t.Fatalf("relayed: %+v", c) } if r := a.del(ids[3]); r.Code != 204 { t.Fatalf("again: %d", r.Code) } uploaded(t, a.upload("n.txt", "text/plain", []byte("note"))) f.FilesReady(true) f.Hold = true if r := a.postJSON("/ask/messages", url.Values{"text": {"this one"}, "attachments": {ids[0]}}); r.Code != 200 { t.Fatalf("send: %d %s", r.Code, r.Body) } if r := a.del(ids[0]); r.Code != 409 { t.Fatalf("a sent file: %d %s", r.Code, r.Body) } if r := a.del("nope"); r.Code != 404 { t.Fatalf("not an id: %d", r.Code) } // From another site, Remove is refused before Equipo hears of it // (Fable S3). req, _ := http.NewRequest(http.MethodDelete, a.base+"/ask/attachments/"+ids[5], nil) req.Header.Set("Origin", "https://evil.example") req.Header.Set("Accept", "application/json") if r := a.do(req); r.Code != 403 || len(f.Calls("/api/v1/attachments/"+ids[5])) != 0 { t.Fatalf("cross-site remove: %d", r.Code) } } // A member can't delete or discard another member's upload (Fable S3): // Base asks Equipo with their own bearer, which answers as if it were // gone, so both are 204 and the upload stays. func TestAskRemoveNotYours(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) if r := a.post("/people", invite("maria@acme.test")); r.Code != 303 { t.Fatalf("invite: %d", r.Code) } maria := a.newBrowser() if r := maria.signIn("maria@acme.test"); r.Code != 303 { t.Fatalf("maria: %d", r.Code) } maria.approveEquipo(f) hers := uploaded(t, maria.upload("hers.txt", "text/plain", []byte("hers"))) if r := a.del(hers); r.Code != 204 { t.Fatalf("remove: %d %s", r.Code, r.Body) } if r := a.post("/ask/attachments/discard", url.Values{"id": {hers}}); r.Code != 204 { t.Fatalf("discard: %d", r.Code) } if _, _, _, _, ok := f.Upload(hers); !ok { t.Fatal("another member deleted her upload") } } // The page's beacon as it goes deletes what was never sent, as best Base // can: always 204, a malformed id skipped. It comes from Base's own page. func TestAskDiscard(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) one := uploaded(t, a.upload("a.txt", "text/plain", []byte("a"))) two := uploaded(t, a.upload("b.txt", "text/plain", []byte("b"))) keep := uploaded(t, a.upload("c.txt", "text/plain", []byte("c"))) cross := url.Values{"id": {keep}} req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/attachments/discard", strings.NewReader(cross.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", "https://evil.example") if r := a.do(req); r.Code != 403 { t.Fatalf("cross-site: %d", r.Code) } f.FilesReady(true) f.Hold = true sent := uploaded(t, a.upload("s.txt", "text/plain", []byte("s"))) if r := a.postJSON("/ask/messages", url.Values{"attachments": {sent}}); r.Code != 200 { t.Fatalf("send: %d", r.Code) } // Five at most; a malformed one skipped; one already sent (Equipo's // 409) doesn't stop the rest. beacon := url.Values{"id": {sent, one, "../../etc", two, "at_abcdefgh99", keep}} req, _ = http.NewRequest(http.MethodPost, a.base+"/ask/attachments/discard", strings.NewReader(beacon.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Sec-Fetch-Site", "same-origin") if r := a.do(req); r.Code != 204 { t.Fatalf("beacon: %d %s", r.Code, r.Body) } left := map[string]bool{} for _, id := range f.Uploads() { left[id] = true } if len(left) != 2 || !left[keep] || !left[sent] { t.Fatalf("left: %v", left) } if r := a.newBrowser().post("/ask/attachments/discard", url.Values{"id": {keep}}); r.Code == 204 || len(f.Uploads()) != 2 { t.Fatalf("signed out: %d", r.Code) } } // A send carries its files in order, and may have no words; Base's own // checks come first, and refusals of the files keep Ask ready (Fable B1, // B2). func TestAskSendWithFiles(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) f.FilesReady(true) f.Hold = true one := uploaded(t, a.upload("a.md", "text/markdown", []byte("# A"))) two := uploaded(t, a.upload("b.png", "image/png", pngFile(t, 3, 3))) r := a.postJSON("/ask/messages", url.Values{"text": {"Look at these"}, "attachments": {two, one}, "key": {"k-files"}}) var sent struct { Message struct { Attachments []struct{ ID, Kind, Name string } } } if r.Code != 200 || json.Unmarshal([]byte(r.Body), &sent) != nil || len(sent.Message.Attachments) != 2 || sent.Message.Attachments[0].ID != two { t.Fatalf("send: %d %s", r.Code, r.Body) } calls := f.Calls("/api/v1/assistant/messages") if c := calls[len(calls)-1]; c.Header.Get("Idempotency-Key") != "k-files" || !strings.Contains(c.Body, `"attachments":["`+two+`","`+one+`"]`) { t.Fatalf("relayed: %v %s", c.Header, c.Body) } three := uploaded(t, a.upload("c.txt", "text/plain", []byte("c"))) if r := a.postJSON("/ask/messages", url.Values{"text": {" "}, "attachments": {three}}); r.Code != 200 { t.Fatalf("files only: %d %s", r.Code, r.Body) } // Words alone go as they always did: no attachments key. if r := a.postJSON("/ask/messages", url.Values{"text": {"just words"}}); r.Code != 200 { t.Fatalf("words: %d", r.Code) } calls = f.Calls("/api/v1/assistant/messages") if c := calls[len(calls)-1]; strings.Contains(c.Body, "attachments") { t.Fatalf("words-only body: %s", c.Body) } before := len(calls) six := []string{} for i := 0; i < 6; i++ { six = append(six, uploaded(t, a.upload("n.txt", "text/plain", []byte("n")))) } for name, form := range map[string]url.Values{ "six files": {"text": {"hi"}, "attachments": six}, "malformed id": {"text": {"hi"}, "attachments": {"at_../x"}}, "nothing at all": {"text": {" "}}, "a NUL": {"text": {"hi\x00there"}, "attachments": {six[0]}}, "invalid UTF-8": {"text": {"hi \xff"}, "attachments": {six[0]}}, "words too long": {"text": {strings.Repeat("a", 16<<10+1)}, "attachments": {six[0]}}, "an empty id too": {"text": {"hi"}, "attachments": {""}}, "one id twice": {"text": {"hi"}, "attachments": {six[0], six[0]}}, } { r := a.postJSON("/ask/messages", form) if _, state, files := codeOf(r); r.Code != 422 || state != "ready" || files != "" { t.Errorf("%s: %d %s", name, r.Code, r.Body) } } if n := len(f.Calls("/api/v1/assistant/messages")); n != before { t.Fatalf("Base's own refusals reached Equipo: %d", n-before) } } // A runner that can't take files leaves Ask ready, and the words can go // alone; an upload Equipo dropped is stale. func TestAskSendFilesRefused(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) f.Hold = true id := uploaded(t, a.upload("a.md", "text/markdown", []byte("# A"))) r := a.postJSON("/ask/messages", url.Values{"text": {"Read this"}, "attachments": {id}}) if _, state, files := codeOf(r); r.Code != 409 || state != "ready" || files != "unavailable" { t.Fatalf("unavailable: %d %s", r.Code, r.Body) } if s, _ := a.askState(); s.State != "ready" { t.Fatalf("state: %+v", s) } if r := a.postJSON("/ask/messages", url.Values{"text": {"Read this"}}); r.Code != 200 { t.Fatalf("words after: %d %s", r.Code, r.Body) } f.FilesReady(true) f.ExpireUploads() r = a.postJSON("/ask/messages", url.Values{"text": {"Read this"}, "attachments": {id}}) if _, state, files := codeOf(r); r.Code != 422 || state != "ready" || files != "stale" { t.Fatalf("stale: %d %s", r.Code, r.Body) } // Words alone refused for an old runner keep today's state. f.RunnerTooOld() r = a.postJSON("/ask/messages", url.Values{"text": {"words"}}) if _, state, _ := codeOf(r); r.Code != 409 || state != "oldrunner" { t.Fatalf("old runner, words: %d %s", r.Code, r.Body) } r = a.postJSON("/ask/messages", url.Values{"text": {"words"}, "attachments": {id}}) if _, state, files := codeOf(r); r.Code != 409 || state != "ready" || files != "unavailable" { t.Fatalf("old runner, files: %d %s", r.Code, r.Body) } } // The conversation read afresh carries each message's files, and says // the paperclip may show only when Equipo says the runner can take them. func TestAskStateCarriesFiles(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) var st struct { CanAttach bool `json:"can_attach"` Messages []struct { Attachments []map[string]any } } read := func() { t.Helper() st.Messages = nil if r := a.get("/ask/state"); r.Code != 200 || json.Unmarshal([]byte(r.Body), &st) != nil { t.Fatalf("state: %d %s", r.Code, r.Body) } } if read(); st.CanAttach { t.Fatal("can_attach before Equipo said so") } f.FilesReady(true) f.Hold = true if read(); !st.CanAttach { t.Fatal("no can_attach") } id := uploaded(t, a.upload("q3.csv", "text/csv", []byte("a,b\n"))) if r := a.postJSON("/ask/messages", url.Values{"attachments": {id}}); r.Code != 200 { t.Fatalf("send: %d %s", r.Code, r.Body) } read() got := st.Messages[len(st.Messages)-1].Attachments if len(got) != 1 || got[0]["id"] != id || got[0]["name"] != "q3.csv" || got[0]["kind"] != "file" || len(got[0]) != 7 { t.Fatalf("files: %+v", got) } f.NoRunner() if read(); st.CanAttach { t.Fatal("can_attach without a runner") } } // A message event carries its files. func TestAskEventsCarryFiles(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) f.FilesReady(true) var st struct{ Cursor int64 } _ = json.Unmarshal([]byte(a.get("/ask/state").Body), &st) id := uploaded(t, a.upload("shot.png", "image/png", pngFile(t, 5, 4))) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+strconv64(st.Cursor), nil) res, err := a.client.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() a.postJSON("/ask/messages", url.Values{"text": {"this"}, "attachments": {id}}) sc := bufio.NewScanner(res.Body) for sc.Scan() { line := sc.Text() if strings.HasPrefix(line, "data: ") && strings.Contains(line, `"role":"person"`) { if !strings.Contains(line, `"attachments":[{"id":"`+id+`","kind":"image","name":"shot.png","media_type":"image/png","size":`) || !strings.Contains(line, `"width":5,"height":4}]`) { t.Fatalf("message event: %s", line) } return } } t.Fatal("no message event") } // Without scripts the thread shows a person's files above their words: a // thumbnail linking to the image, a pill downloading anything else, both // from Base; a message of files alone has no empty words. func TestAskThreadDrawsFiles(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) f.FilesReady(true) f.Hold = true shot := uploaded(t, a.upload("Screen <1>.png", "image/png", pngFile(t, 64, 48))) csv := uploaded(t, a.upload("sales.csv", "text/csv", bytes.Repeat([]byte("1,2\n"), 300))) if r := a.postJSON("/ask/messages", url.Values{"text": {"These two"}, "attachments": {shot, csv}}); r.Code != 200 { t.Fatalf("send: %d %s", r.Code, r.Body) } lone := uploaded(t, a.upload("q.md", "text/markdown", []byte("# Q"))) if r := a.postJSON("/ask/messages", url.Values{"attachments": {lone}}); r.Code != 200 { t.Fatalf("send: %d %s", r.Code, r.Body) } page := a.get("/ask") for _, want := range []string{ `
These two`, `([^<]*)
`).FindStringSubmatch(page) if got == nil || html.UnescapeString(got[1]) != want { t.Errorf("%s: status %q, want %q", reason, got, want) } var st struct{ Status string } _ = json.Unmarshal([]byte(a.get("/ask/state").Body), &st) if st.Status != want { t.Errorf("%s: state status %q", reason, st.Status) } } }