| new file mode 100644 |
| index 0000000..0cb07cf |
| --- /dev/null |
| +++ b/internal/webtest/ask_files_test.go |
| @@ -0,0 +1,647 @@ |
| +package webtest |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "image" |
| + "image/color" |
| + "image/png" |
| + "io" |
| + "mime" |
| + "net" |
| + "net/http" |
| + "net/url" |
| + "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) |
| + var at struct { |
| + Kind, Name, 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.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) |
| +} |
| + |
| +// Over 10 MiB is refused before Equipo hears of it, whether the length |
| +// is declared or not. |
| +func TestAskUploadTooBig(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + big := bytes.Repeat([]byte("a"), 10<<20+1) |
| + if r := a.upload("big.txt", "text/plain", big); r.Code != 413 { |
| + t.Fatalf("declared: %d %s", r.Code, r.Body) |
| + } |
| + req := a.uploadReq(context.Background(), "big.txt", "text/plain", io.MultiReader(bytes.NewReader(big))) |
| + req.ContentLength = -1 |
| + r := a.do(req) |
| + if code, _, _ := codeOf(r); r.Code != 413 || code != "attachment_too_large" { |
| + 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) |
| + } |
| +} |
| + |
| +// 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. |
| +func TestAskUploadStalledBodyFreesItsSlot(t *testing.T) { |
| + bounds(t, web.UploadBounds{Slots: 4, SlotWait: 300 * time.Millisecond, ReadDeadline: 400 * 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)) |
| + _, err = http.ReadResponse(bufio.NewReader(conn), nil) |
| + if took := time.Since(start); took > 3*time.Second { |
| + t.Fatalf("the stalled upload held on for %s (%v)", took, err) |
| + } |
| + f.SlowUploads(200 * 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: 300 * time.Millisecond, ReadDeadline: 5 * time.Second, Upstream: 10 * time.Second}) |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + f.SlowUploads(1500 * 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(150 * 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. |
| +func TestAskAttachmentHostileUpstream(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + note := uploaded(t, a.upload("x.txt", "text/plain", []byte("<script>alert(1)</script>"))) |
| + 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) |
| + } |
| + } |
| +} |
| + |
| +// 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(4 * time.Millisecond) // 144 pieces: about 0.6 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: 300 * 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) |
| + } |
| +} |
| + |
| +// 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) |
| + } |
| + beacon := url.Values{"id": {one, "../../etc", two}} |
| + 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 := f.Uploads() |
| + if len(left) != 1 || left[0] != keep { |
| + t.Fatalf("left: %v", left) |
| + } |
| + f.FailReads(0) |
| + if r := a.newBrowser().post("/ask/attachments/discard", beacon); r.Code != 204 && r.Code != 403 && r.Code != 303 { |
| + 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": {""}}, |
| + } { |
| + 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) |
| + } |
| +} |