oficina / base Public

Ask relays uploads, reads, removes and sends files (Tasks 2-5)

Human

Prompt

Build Base's half of files in Ask, slice 1, task by task from the approved plan, tests first, against the fake Equipo.

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

POST /ask/attachments: length check, then one of 4 slots, then the body under a 60 s read deadline (refused if the deadline can't be set); 503 with Retry-After when busy; an upload whose page went is deleted. GET/HEAD /ask/attachments/{id}[/preview]: streamed, Base's own headers (four image types inline, five downloads, the rest octet-stream), 404 for anything not the member's, 502 with no body when Equipo fails. DELETE and the discard beacon relay Equipo's delete. Sends carry up to five files; Base checks the text itself, so Equipo's 422 with files is stale and attachments_unavailable or runner_too_old keep Ask ready.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a4be6f0896a4029c5e91d0384befa022ff2ab1ec parent 4775d85
5 files changed, +1,065 −22
  • internal/equipo/equipotest/files.go +27 −1
  • internal/web/ask.go +11 −1
  • internal/web/ask_files.go +346 −0
  • internal/web/ask_relay.go +34 −20
  • internal/webtest/ask_files_test.go +647 −0
diff --git a/internal/equipo/equipotest/files.go b/internal/equipo/equipotest/files.go
index 8bc6e6c..20d668d 100644
--- a/internal/equipo/equipotest/files.go
+++ b/internal/equipo/equipotest/files.go
@@ -82,6 +82,9 @@ type fileState struct {
hostileType, hostileDisposition string
readDelay time.Duration
readStatus int
+ // readHold, when set, holds every read before its headers until it is
+ // closed (or the reader gives up).
+ readHold chan struct{}
// sendHold and sendEntered hold the next send of a message, once it
// has arrived and before it is looked at.
sendHold, sendEntered chan struct{}
@@ -142,6 +145,20 @@ func (f *Fake) ServeHostile(typ, disposition string) {
// d between pieces.
func (f *Fake) ServeSlowly(d time.Duration) { f.fmu.Lock(); f.readDelay = d; f.fmu.Unlock() }
+// HoldReads holds every read before its headers until release is called.
+func (f *Fake) HoldReads() (release func()) {
+ hold := make(chan struct{})
+ f.fmu.Lock()
+ f.readHold = hold
+ f.fmu.Unlock()
+ return sync.OnceFunc(func() {
+ f.fmu.Lock()
+ f.readHold = nil
+ f.fmu.Unlock()
+ close(hold)
+ })
+}
+
// FailReads makes every read answer status with an error body (0 stops).
func (f *Fake) FailReads(status int) { f.fmu.Lock(); f.readStatus = status; f.fmu.Unlock() }
@@ -319,8 +336,17 @@ func safeName(name string) string {
func (f *Fake) readFile(w http.ResponseWriter, r *http.Request, owner, id string, preview bool) {
f.fmu.Lock()
u, ok := f.files[id]
- status, typ, disposition, delay := f.readStatus, f.hostileType, f.hostileDisposition, f.readDelay
+ status, typ, disposition, delay, hold := f.readStatus, f.hostileType, f.hostileDisposition, f.readDelay, f.readHold
f.fmu.Unlock()
+ if hold != nil {
+ select {
+ case <-hold:
+ case <-r.Context().Done():
+ return
+ case <-f.closing:
+ return
+ }
+ }
if status != 0 {
writeJSON(w, status, map[string]string{"code": FileErrorBody, "detail": FileErrorBody})
return
diff --git a/internal/web/ask.go b/internal/web/ask.go
index 462e586..d803638 100644
--- a/internal/web/ask.go
+++ b/internal/web/ask.go
@@ -38,6 +38,8 @@ type asker struct {
zone string
zoneMu sync.Mutex
zones map[string]*zoneTold
+ // uploads is the upload relay's slots (ask_files.go).
+ uploads *uploads
}
// askRoutes mounts the chat, behind the member gate and Base's CSRF check.
@@ -46,6 +48,13 @@ func (a *app) askRoutes(r chi.Router) {
r.Get("/ask/state", a.askStateJSON)
r.Get("/ask/events", a.askEvents)
r.Post("/ask/messages", a.askSend)
+ r.Post("/ask/attachments", a.askUpload)
+ r.Post("/ask/attachments/discard", a.askDiscard)
+ r.Delete("/ask/attachments/{id}", a.askDeleteAttachment)
+ r.Get("/ask/attachments/{id}", a.askAttachment(false))
+ r.Head("/ask/attachments/{id}", a.askAttachment(false))
+ r.Get("/ask/attachments/{id}/preview", a.askAttachment(true))
+ r.Head("/ask/attachments/{id}/preview", a.askAttachment(true))
r.Post("/ask/turns/{id}/cancel", a.askCancel)
r.Post("/ask/cards/{id}/answer", a.askAnswer)
r.Post("/ask/cards/{id}/carry_on", a.askCarryOn)
@@ -90,7 +99,8 @@ func (a *app) askDock(w http.ResponseWriter, r *http.Request) {
// (BASE_TIMEZONE), which Base tells Equipo for each member (zoneFor).
func newAsker(origin, instanceKey, name string, zone *time.Location) *asker {
a := &asker{client: equipo.New(origin), seal: equipo.NewSealer(instanceKey), label: "Base (" + name + ")",
- zones: map[string]*zoneTold{}}
+ zones: map[string]*zoneTold{}, uploads: newUploads(uploadBounds)}
+ a.client.FileTimeout = uploadBounds.Upstream
if zone != nil {
a.zone = zone.String()
}
diff --git a/internal/web/ask_files.go b/internal/web/ask_files.go
new file mode 100644
index 0000000..48eb175
--- /dev/null
+++ b/internal/web/ask_files.go
@@ -0,0 +1,346 @@
+package web
+
+import (
+ "context"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+
+ "amadan.net/oficina/base/internal/equipo"
+)
+
+// Files in Ask (plan P1 to P3, P7, P11): Base relays a member's uploads,
+// reads and deletes to Equipo with their own bearer, and keeps no byte of
+// any file. Equipo holds them; the page and the apps name a file by its
+// Equipo id alone, under Base's own /ask/attachments/{id}.
+
+// UploadBounds bound the upload relay (plan P1): Slots uploads at once in
+// the whole process, each taken before its body is read; a request that
+// waits SlotWait for one is told to come back; a body is read within
+// ReadDeadline; Equipo answers an upload, or a read's headers, within
+// Upstream.
+type UploadBounds struct {
+ Slots int
+ SlotWait time.Duration
+ ReadDeadline time.Duration
+ Upstream time.Duration
+}
+
+var uploadBounds = UploadBounds{Slots: 4, SlotWait: 10 * time.Second, ReadDeadline: 60 * time.Second, Upstream: 60 * time.Second}
+
+// SetUploadBounds makes b the bounds of every app built from now on, and
+// gives back what restores the ones before. Tests shorten the times.
+func SetUploadBounds(b UploadBounds) (restore func()) {
+ was := uploadBounds
+ uploadBounds = b
+ return func() { uploadBounds = was }
+}
+
+// UploadReading, when set, hears the slots in use each time an upload's
+// body read starts. Tests check the slot comes first.
+var UploadReading func(inUse int)
+
+// uploads is the relay's slots: a semaphore, and how many are held.
+type uploads struct {
+ slots chan struct{}
+ inUse atomic.Int32
+ b UploadBounds
+}
+
+func newUploads(b UploadBounds) *uploads {
+ return &uploads{slots: make(chan struct{}, max(b.Slots, 1)), b: b}
+}
+
+// attachmentID is the shape of an Equipo attachment id; anything else is
+// refused before Equipo is called.
+var attachmentID = regexp.MustCompile(`^at_[a-z0-9]{8,60}$`)
+
+// The four image types Base shows inline (plan P3); the other five of
+// Equipo's nine go as downloads, and anything else as an octet stream.
+var (
+ inlineTypes = map[string]bool{"image/png": true, "image/jpeg": true, "image/webp": true, "image/gif": true}
+ downloadTypes = map[string]bool{"application/pdf": true, "text/plain": true, "text/markdown": true, "text/csv": true, "application/json": true}
+)
+
+// fileCSP is what every file Base serves carries: nothing in it may run,
+// and only an image of Base's own may show.
+const fileCSP = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox"
+
+// askState is the member's live connection for a relayed call that reads
+// no form. Without one it answers for the caller, as askBearer does.
+func (a *app) askState(w http.ResponseWriter, r *http.Request) (askConn, bool) {
+ me, _ := CurrentMember(r)
+ l, sec, state, err := a.askLink(r.Context(), me)
+ switch {
+ case err != nil:
+ a.logger.Error("ask: link", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ case state != askReady && wantsJSON(r):
+ writeJSON(w, http.StatusConflict, map[string]string{"state": homeState(state)})
+ case state != askReady:
+ http.Redirect(w, r, "/ask", http.StatusSeeOther)
+ default:
+ return askConn{me, l.DeviceID, sec.Token}, true
+ }
+ return askConn{}, false
+}
+
+// askUpload is POST /ask/attachments: one file, the bytes as the body, its
+// type in Content-Type and its name in Content-Disposition, relayed to
+// Equipo. The answer is Equipo's attachment (201), or {"code"} with
+// Equipo's status for its refusals, 413 attachment_too_large for a body
+// over 10 MiB (before Equipo is called), 503 with Retry-After when every
+// slot stays busy, or {"state"} as for every Ask write.
+func (a *app) askUpload(w http.ResponseWriter, r *http.Request) {
+ if r.ContentLength > equipo.MaxUpload {
+ writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"code": "attachment_too_large"})
+ return
+ }
+ c, ok := a.askState(w, r)
+ if !ok {
+ return
+ }
+ up := a.ask.uploads
+ wait := time.NewTimer(up.b.SlotWait)
+ defer wait.Stop()
+ select {
+ case up.slots <- struct{}{}:
+ case <-wait.C:
+ w.Header().Set("Retry-After", "2")
+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{"code": "busy"})
+ return
+ case <-r.Context().Done():
+ return
+ }
+ n := up.inUse.Add(1)
+ defer func() { up.inUse.Add(-1); <-up.slots }()
+ // Never read a body without a deadline: a stalled one would hold its
+ // slot until TCP gave up.
+ if err := http.NewResponseController(w).SetReadDeadline(time.Now().Add(up.b.ReadDeadline)); err != nil {
+ a.logger.Error("ask: upload read deadline", "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{"code": "busy"})
+ return
+ }
+ if UploadReading != nil {
+ UploadReading(int(n))
+ }
+ body, err := io.ReadAll(io.LimitReader(r.Body, equipo.MaxUpload+1))
+ if err != nil {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ if len(body) > equipo.MaxUpload {
+ writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"code": "attachment_too_large"})
+ return
+ }
+ name := ""
+ if _, params, err := mime.ParseMediaType(r.Header.Get("Content-Disposition")); err == nil {
+ name = params["filename"]
+ }
+ // Equipo's answer outlives the request, so an upload it takes is never
+ // half-known: if the page has gone by then (Remove aborted it), the
+ // upload is deleted at once.
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), up.b.Upstream)
+ defer cancel()
+ at, err := a.ask.client.Upload(ctx, c.token, name, r.Header.Get("Content-Type"), body)
+ if err == nil && r.Context().Err() != nil {
+ if err := a.ask.client.DeleteAttachment(ctx, c.token, at.ID); err != nil {
+ a.logger.Warn("ask: delete an upload whose page went", "err", err)
+ }
+ return
+ }
+ var e *equipo.Error
+ switch {
+ case err == nil:
+ writeJSON(w, http.StatusCreated, at)
+ case errors.Is(err, equipo.ErrUnauthenticated):
+ a.askLost(r.Context(), c.me, c.device)
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askReconnect})
+ case errors.As(err, &e) && strings.HasPrefix(e.Code, "attachment_"):
+ writeJSON(w, e.Status, map[string]string{"code": e.Code})
+ case errors.As(err, &e) && e.Status == http.StatusServiceUnavailable:
+ w.Header().Set("Retry-After", retryAfter(e.RetryAfter))
+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{"code": "busy"})
+ default:
+ a.logger.Warn("ask: upload", "err", err)
+ writeJSON(w, http.StatusBadGateway, map[string]string{"state": askUnavailable})
+ }
+}
+
+// retryAfter is Equipo's Retry-After when it is a few seconds, else 2.
+func retryAfter(s string) string {
+ if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= 10 {
+ return s
+ }
+ return "2"
+}
+
+// askDeleteAttachment is DELETE /ask/attachments/{id}: Remove on a chip,
+// relayed. Equipo's 404 (gone already) is done too: 204. One already sent
+// is 409 {"state":"ready","code":"attachment_sent"}.
+func (a *app) askDeleteAttachment(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ if !attachmentID.MatchString(id) {
+ http.NotFound(w, r)
+ return
+ }
+ c, ok := a.askState(w, r)
+ if !ok {
+ return
+ }
+ err := a.ask.client.DeleteAttachment(r.Context(), c.token, id)
+ var e *equipo.Error
+ switch {
+ case err == nil:
+ w.WriteHeader(http.StatusNoContent)
+ case errors.Is(err, equipo.ErrUnauthenticated):
+ a.askLost(r.Context(), c.me, c.device)
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askReconnect})
+ case errors.As(err, &e) && e.Status == http.StatusConflict:
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askReady, "code": e.Code})
+ default:
+ a.logger.Warn("ask: delete attachment", "err", err)
+ writeJSON(w, http.StatusBadGateway, map[string]string{"state": askUnavailable})
+ }
+}
+
+// askDiscard is POST /ask/attachments/discard: the page's unsent uploads
+// as it goes away (a beacon, up to five id fields), deleted as best Base
+// can. It always answers 204: nobody is there to hear more.
+func (a *app) askDiscard(w http.ResponseWriter, r *http.Request) {
+ defer w.WriteHeader(http.StatusNoContent)
+ r.Body = http.MaxBytesReader(w, r.Body, 4<<10)
+ if r.ParseForm() != nil {
+ return
+ }
+ me, _ := CurrentMember(r)
+ l, sec, state, err := a.askLink(r.Context(), me)
+ if err != nil || state != askReady {
+ return
+ }
+ ctx := context.WithoutCancel(r.Context())
+ ids := r.PostForm["id"]
+ for _, id := range ids[:min(len(ids), equipo.MaxFiles)] {
+ if !attachmentID.MatchString(id) {
+ continue
+ }
+ err := a.ask.client.DeleteAttachment(ctx, sec.Token, id)
+ if errors.Is(err, equipo.ErrUnauthenticated) {
+ a.askLost(ctx, me, l.DeviceID)
+ return
+ }
+ }
+}
+
+// askAttachment is GET (and HEAD) /ask/attachments/{id}, and its
+// /preview: one of the member's files streamed from Equipo, never held,
+// with headers Base decides (plan P3). Only four image types show inline;
+// /preview is for those alone. Equipo's own headers and error bodies never
+// come through. Without a live connection, or for a file that isn't the
+// member's, it is 404; when Equipo fails or is slow, 502 with no body, so
+// an <img> shows its alt.
+func (a *app) askAttachment(preview bool) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ if !attachmentID.MatchString(id) {
+ http.NotFound(w, r)
+ return
+ }
+ me, _ := CurrentMember(r)
+ l, sec, state, err := a.askLink(r.Context(), me)
+ if err != nil {
+ a.logger.Error("ask: link", "err", err)
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ if state != askReady {
+ http.NotFound(w, r)
+ return
+ }
+ res, err := a.ask.client.OpenAttachment(r.Context(), sec.Token, id, preview)
+ var e *equipo.Error
+ switch {
+ case errors.Is(err, equipo.ErrUnauthenticated):
+ a.askLost(r.Context(), me, l.DeviceID)
+ http.NotFound(w, r)
+ return
+ case errors.As(err, &e) && e.Status < 500:
+ http.NotFound(w, r)
+ return
+ case err != nil:
+ if r.Context().Err() == nil {
+ a.logger.Warn("ask: read attachment", "err", err)
+ }
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ defer res.Body.Close()
+ media, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type"))
+ disposition := "attachment"
+ switch {
+ case inlineTypes[media]:
+ disposition = "inline"
+ case preview:
+ http.NotFound(w, r)
+ return
+ case downloadTypes[media]:
+ if strings.HasPrefix(media, "text/") || media == "application/json" {
+ media += "; charset=utf-8"
+ }
+ default:
+ media = "application/octet-stream"
+ }
+ // The name is the one place Equipo's header is read: parsed out,
+ // then put in a header of Base's own.
+ name := "file"
+ if _, params, err := mime.ParseMediaType(res.Header.Get("Content-Disposition")); err == nil && params["filename"] != "" {
+ name = params["filename"]
+ }
+ cd := mime.FormatMediaType(disposition, map[string]string{"filename": name})
+ if cd == "" {
+ cd = disposition
+ }
+ h := w.Header()
+ h.Set("Content-Type", media)
+ h.Set("Content-Disposition", cd)
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Content-Security-Policy", fileCSP)
+ if preview {
+ h.Set("Cache-Control", "private, max-age=3600")
+ h.Add("Vary", "Cookie")
+ } else {
+ h.Set("Cache-Control", "no-store")
+ }
+ if n, err := strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64); err == nil && n >= 0 {
+ h.Set("Content-Length", strconv.FormatInt(n, 10))
+ }
+ w.WriteHeader(http.StatusOK)
+ if r.Method == http.MethodHead {
+ return
+ }
+ // A browser that stops reading gives up its stream after
+ // writeWindow, as an event stream does.
+ rc := http.NewResponseController(w)
+ buf := make([]byte, 64<<10)
+ for {
+ n, err := res.Body.Read(buf)
+ if n > 0 {
+ _ = rc.SetWriteDeadline(time.Now().Add(writeWindow))
+ if _, werr := w.Write(buf[:n]); werr != nil {
+ return
+ }
+ }
+ if err != nil {
+ return
+ }
+ }
+ }
+}
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go
index 4c54c8a..5e44afb 100644
--- a/internal/web/ask_relay.go
+++ b/internal/web/ask_relay.go
@@ -30,28 +30,16 @@ func wantsJSON(r *http.Request) bool {
return strings.Contains(r.Header.Get("Accept"), "application/json")
}
-// askBearer is the member's bearer for a relayed write. Without one it
-// answers for the caller: the panel hears the state, a form goes to /ask.
+// askBearer is the member's bearer for a relayed write of a form, read
+// first (at most maxAskForm). Without one it answers for the caller: the
+// panel hears the state, a form goes to /ask.
func (a *app) askBearer(w http.ResponseWriter, r *http.Request) (askConn, bool) {
- me, _ := CurrentMember(r)
r.Body = http.MaxBytesReader(w, r.Body, maxAskForm)
if err := r.ParseForm(); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return askConn{}, false
}
- l, sec, state, err := a.askLink(r.Context(), me)
- switch {
- case err != nil:
- a.logger.Error("ask: link", "err", err)
- http.Error(w, "unavailable", http.StatusServiceUnavailable)
- case state != askReady && wantsJSON(r):
- writeJSON(w, http.StatusConflict, map[string]string{"state": homeState(state)})
- case state != askReady:
- http.Redirect(w, r, "/ask", http.StatusSeeOther)
- default:
- return askConn{me, l.DeviceID, sec.Token}, true
- }
- return askConn{}, false
+ return a.askState(w, r)
}
// askConn is a member's live connection for one relayed write.
@@ -108,20 +96,35 @@ func (a *app) askDone(w http.ResponseWriter, r *http.Request, c askConn, err err
// twice is one request to Equipo; a missing or unusable one gets a fresh
// key.
func askKey(k string) string {
- if k == "" || len(k) > 128 || !utf8.ValidString(k) || strings.HasPrefix(k, "reply:") || strings.HasPrefix(k, "card:") {
+ if k == "" || len(k) > 128 || !utf8.ValidString(k) || strings.HasPrefix(k, "reply:") || strings.HasPrefix(k, "card:") || strings.HasPrefix(k, "handoff:") {
return equipo.NewKey()
}
return k
}
-// askSend is POST /ask/messages.
+// askSend is POST /ask/messages: text and, from the panel's script, up to
+// five attachments (uploaded first, their ids in order). Text may be
+// empty when files come. Base checks the text as Equipo does (UTF-8, no
+// NUL, at most maxAskText) and answers 422 {"state":"ready"} itself, so
+// Equipo's 422 on a send with files can only be about the files: 422
+// {"state":"ready","files":"stale"} (one expired, or already sent). A
+// runner that can't take files (409 attachments_unavailable, or
+// runner_too_old) is 409 {"state":"ready","files":"unavailable"}: Ask
+// stays ready, and the words can go alone. Words alone keep askDone's
+// answers.
func (a *app) askSend(w http.ResponseWriter, r *http.Request) {
c, ok := a.askBearer(w, r)
if !ok {
return
}
text := strings.TrimSpace(r.PostFormValue("text"))
- if text == "" || len(text) > maxAskText {
+ files := r.PostForm["attachments"]
+ valid := len(files) <= equipo.MaxFiles && (text != "" || len(files) > 0) && len(text) <= maxAskText &&
+ utf8.ValidString(text) && !strings.ContainsRune(text, 0)
+ for _, id := range files {
+ valid = valid && attachmentID.MatchString(id)
+ }
+ if !valid {
if wantsJSON(r) {
writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": askReady})
} else {
@@ -129,7 +132,18 @@ func (a *app) askSend(w http.ResponseWriter, r *http.Request) {
}
return
}
- sent, err := a.ask.client.Send(r.Context(), c.token, text, askKey(r.PostFormValue("key")), nil)
+ sent, err := a.ask.client.Send(r.Context(), c.token, text, askKey(r.PostFormValue("key")), files)
+ var e *equipo.Error
+ if len(files) > 0 && err != nil && wantsJSON(r) {
+ switch {
+ case errors.Is(err, equipo.ErrAttachmentsUnavailable) || errors.Is(err, equipo.ErrRunnerTooOld):
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askReady, "files": "unavailable"})
+ return
+ case errors.As(err, &e) && e.Status == http.StatusUnprocessableEntity:
+ writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": askReady, "files": "stale"})
+ return
+ }
+ }
a.askDone(w, r, c, err, sent)
}
diff --git a/internal/webtest/ask_files_test.go b/internal/webtest/ask_files_test.go
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)
+ }
+}