package equipotest import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "image" _ "image/gif" // DecodeConfig for the image types Equipo sniffs _ "image/jpeg" _ "image/png" "io" "mime" "net/http" "path" "strconv" "strings" "sync" "time" "unicode/utf8" ) // Equipo's attachments (internal/attach, chat/attachments.go and // attachments_http.go, and the delete route of the assistant-attachments // spec, A2): POST /api/v1/attachments takes one file (the bytes as the // body, its type in Content-Type, its name in Content-Disposition) and // answers 201 with its wire.MessageAttachment; GET // /api/v1/attachments/{id} and /preview serve the person's own file; // DELETE /api/v1/attachments/{id} deletes an unsent one (204), 404 when it // isn't the person's or is gone, 409 attachment_sent once it is on a // message. A person here is a device: another device's file is 404. // Equipo's limits (internal/attach). const ( maxUpload = 10 << 20 maxFiles = 5 maxUnsent = 20 maxSide = 12000 maxPixels = 40_000_000 attachments = "/api/v1/attachments" ) // file is one upload: its wire.MessageAttachment and its bytes. type file struct { ID string `json:"id"` Revision int64 `json:"revision"` Kind string `json:"kind"` Name string `json:"name"` MediaType string `json:"media_type"` Size int64 `json:"size"` SHA256 string `json:"sha256"` Width int `json:"width"` Height int `json:"height"` MessageID string `json:"message_id"` CreatedAt time.Time `json:"created_at"` owner string data []byte } // fileState is the fake's files and the switches tests turn. type fileState struct { fmu sync.Mutex files map[string]*file // filesReady says the person's runner can take files (can_attach); // false, as for a runner never seen, until FilesReady. filesReady bool // expired makes the next send with files 422, as an upload dropped // after 24 hours does. expired bool // uploadHold and uploadEntered hold the next upload, once its body has // arrived and before it answers; busyNext makes the next upload 503 // with Retry-After: 1; uploadDelay slows every upload, so a test sees // how many overlap (uploading, most). uploadHold, uploadEntered chan struct{} busyNext bool uploadDelay time.Duration uploading, most int // hostileType and hostileDisposition, when set, are what every read // answers with instead of Equipo's own; readDelay writes a read in 64 // KiB pieces with this pause between; readStatus, when set, is what // every read answers (with an error body). 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{} } func (s *fileState) initFiles() { s.files = map[string]*file{} } // FilesReady says whether the person's runner can take files: the // snapshot's can_attach, and whether a send with files passes (else 409 // attachments_unavailable). func (f *Fake) FilesReady(ok bool) { f.fmu.Lock(); f.filesReady = ok; f.fmu.Unlock() } // ExpireUploads makes the next send with files 422 invalid_input, as when // an upload was dropped after 24 hours unsent. func (f *Fake) ExpireUploads() { f.fmu.Lock(); f.expired = true; f.fmu.Unlock() } // HoldNextUpload makes the next upload wait, once its body has arrived and // before it answers, until release is called. entered is closed when it // arrives. func (f *Fake) HoldNextUpload() (entered <-chan struct{}, release func()) { f.fmu.Lock() defer f.fmu.Unlock() f.uploadHold, f.uploadEntered = make(chan struct{}), make(chan struct{}) hold := f.uploadHold return f.uploadEntered, sync.OnceFunc(func() { close(hold) }) } // HoldNextSend makes the next send of a message wait, once it has arrived // and before it is looked at, until release is called. entered is closed // when it arrives. func (f *Fake) HoldNextSend() (entered <-chan struct{}, release func()) { f.fmu.Lock() defer f.fmu.Unlock() f.sendHold, f.sendEntered = make(chan struct{}), make(chan struct{}) hold := f.sendHold return f.sendEntered, sync.OnceFunc(func() { close(hold) }) } // BusyNextUpload makes the next upload answer 503 with Retry-After: 1. func (f *Fake) BusyNextUpload() { f.fmu.Lock(); f.busyNext = true; f.fmu.Unlock() } // SlowUploads makes every upload take d before it answers. func (f *Fake) SlowUploads(d time.Duration) { f.fmu.Lock(); f.uploadDelay = d; f.fmu.Unlock() } // UploadsAtOnce is the most uploads the fake has had in flight at once. func (f *Fake) UploadsAtOnce() int { f.fmu.Lock(); defer f.fmu.Unlock(); return f.most } // ServeHostile makes every read answer with Content-Type typ and // Content-Disposition disposition, as a broken Equipo might ("" for // Equipo's own). func (f *Fake) ServeHostile(typ, disposition string) { f.fmu.Lock() f.hostileType, f.hostileDisposition = typ, disposition f.fmu.Unlock() } // ServeSlowly makes every read write its bytes 64 KiB at a time, pausing // 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() } // FileErrorBody is in the body of every read FailReads fails, so a test // can see that it never comes through. const FileErrorBody = "equipo-error-body" // Upload is the upload with id as the fake keeps it: its bytes, name and // type, and the message it went with ("" while unsent). ok is false once // it is deleted, or if there never was one. func (f *Fake) Upload(id string) (data []byte, name, media, message string, ok bool) { f.fmu.Lock() defer f.fmu.Unlock() u, ok := f.files[id] if !ok { return nil, "", "", "", false } return u.data, u.Name, u.MediaType, u.MessageID, true } // Uploads are the ids of the files the fake holds, sent or not. func (f *Fake) Uploads() []string { f.fmu.Lock() defer f.fmu.Unlock() var out []string for id := range f.files { out = append(out, id) } return out } // serveFiles answers the attachment routes for the person behind the // bearer (owner); ok is false for any other path. func (f *Fake) serveFiles(w http.ResponseWriter, r *http.Request, owner string) bool { p := r.URL.Path switch { case r.Method == http.MethodPost && p == attachments: f.upload(w, r, owner) case !strings.HasPrefix(p, attachments+"/"): return false case r.Method == http.MethodDelete: f.deleteFile(w, r, owner, strings.TrimPrefix(p, attachments+"/")) case r.Method == http.MethodGet || r.Method == http.MethodHead: id, preview := strings.TrimPrefix(p, attachments+"/"), false if rest, ok := strings.CutSuffix(id, "/preview"); ok { id, preview = rest, true } f.readFile(w, r, owner, id, preview) default: writeError(w, r, 404, "not_found") } return true } // upload is POST /api/v1/attachments, as Equipo's chat.ReadUpload and // Store.Upload: the type sniffed from the bytes, never the declared one. func (f *Fake) upload(w http.ResponseWriter, r *http.Request, owner string) { f.fmu.Lock() f.uploading++ f.most = max(f.most, f.uploading) hold, entered, busy, delay := f.uploadHold, f.uploadEntered, f.busyNext, f.uploadDelay f.uploadHold, f.uploadEntered, f.busyNext = nil, nil, false f.fmu.Unlock() defer func() { f.fmu.Lock(); f.uploading--; f.fmu.Unlock() }() f.waitHeld(hold, entered) if delay > 0 { select { case <-time.After(delay): case <-f.closing: } } if busy { w.Header().Set("Retry-After", "1") writeError(w, r, 503, "unavailable") return } data, _ := io.ReadAll(r.Body) if r.ContentLength > maxUpload || len(data) > maxUpload { writeError(w, r, 413, "attachment_too_large") return } name := "" if _, params, err := mime.ParseMediaType(r.Header.Get("Content-Disposition")); err == nil { name = params["filename"] } u, status, code := sniff(name, r.Header.Get("Content-Type"), data) if status != 0 { writeError(w, r, status, code) return } f.fmu.Lock() defer f.fmu.Unlock() unsent := 0 for _, x := range f.files { if x.owner == owner && x.MessageID == "" { unsent++ } } if unsent >= maxUnsent { writeError(w, r, 409, "attachment_limit") return } sum := sha256.Sum256(data) u.ID, u.Revision, u.owner, u.data = "at_"+strings.ToLower(rand.Text()), 1, owner, data u.Size, u.SHA256, u.CreatedAt = int64(len(data)), hex.EncodeToString(sum[:]), time.Now().UTC() f.files[u.ID] = u writeJSON(w, http.StatusCreated, *u) } // sniff is the file Equipo would keep for data named name: its kind, // type, name and size, or the status and code it refuses it with. func sniff(name, declared string, data []byte) (*file, int, string) { u := &file{Kind: "file", Name: safeName(name)} declared, _, _ = mime.ParseMediaType(declared) heic := len(data) >= 12 && string(data[4:8]) == "ftyp" && strings.Contains("heic heix mif1 hevc", string(data[8:12])) if declared == "image/heic" || declared == "image/heif" || heic { return nil, 415, "attachment_heic" } if len(data) == 0 { return nil, 415, "attachment_type" } switch ct := http.DetectContentType(data); { case ct == "image/png" || ct == "image/jpeg" || ct == "image/gif" || ct == "image/webp": u.Kind, u.MediaType = "image", ct if cfg, _, err := image.DecodeConfig(bytes.NewReader(data)); err == nil { u.Width, u.Height = cfg.Width, cfg.Height } if u.Width > maxSide || u.Height > maxSide || u.Width*u.Height > maxPixels { return nil, 413, "attachment_pixels" } case ct == "application/pdf": u.MediaType = ct case strings.HasPrefix(ct, "text/") && utf8.Valid(data): switch ext := strings.ToLower(path.Ext(u.Name)); { case declared == "text/markdown" || ext == ".md" || ext == ".markdown": u.MediaType = "text/markdown" case declared == "text/csv" || ext == ".csv": u.MediaType = "text/csv" case declared == "application/json" || ext == ".json": u.MediaType = "application/json" default: u.MediaType = "text/plain" } default: return nil, 415, "attachment_type" } return u, 0, "" } // safeName is a name as Equipo keeps it: its last path part, without // control characters, at most 255 bytes, "file" when nothing is left. func safeName(name string) string { name = path.Base(strings.ReplaceAll(name, `\`, "/")) name = strings.Map(func(r rune) rune { if r < 0x20 || r == 0x7f { return -1 } return r }, strings.ToValidUTF8(name, "")) for len(name) > 255 { _, n := utf8.DecodeLastRuneInString(name) name = name[:len(name)-n] } if name == "" || name == "." || name == "/" { return "file" } return name } // readFile is GET /api/v1/attachments/{id}[/preview], as Equipo's // serveFile: the sniffed type (text with its charset), inline for an image // and a download for anything else, nosniff and a sandboxing CSP. A // preview is an image's own bytes here (Equipo scales it), and 404 for a // file. 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, 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 } if !ok || u.owner != owner || preview && u.Kind != "image" { writeError(w, r, 404, "not_found") return } if typ == "" { typ = u.MediaType if strings.HasPrefix(typ, "text/") || typ == "application/json" { typ += "; charset=utf-8" } } if disposition == "" { disposition = "attachment" if u.Kind == "image" { disposition = "inline" } } h := w.Header() h.Set("Content-Type", typ) h.Set("Content-Length", strconv.Itoa(len(u.data))) h.Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": u.Name})) h.Set("X-Content-Type-Options", "nosniff") h.Set("Content-Security-Policy", "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox") h.Set("Cache-Control", "private, max-age=86400") h.Set("X-Equipo-Only", "yes") w.WriteHeader(http.StatusOK) if r.Method == http.MethodHead { return } rc := http.NewResponseController(w) for rest := u.data; len(rest) > 0; { n := min(len(rest), 64<<10) if _, err := w.Write(rest[:n]); err != nil { return } rest = rest[n:] if delay > 0 { _ = rc.Flush() select { case <-time.After(delay): case <-r.Context().Done(): return case <-f.closing: return } } } } // deleteFile is DELETE /api/v1/attachments/{id}. func (f *Fake) deleteFile(w http.ResponseWriter, r *http.Request, owner, id string) { f.fmu.Lock() defer f.fmu.Unlock() u, ok := f.files[id] switch { case !ok || u.owner != owner: writeError(w, r, 404, "not_found") case u.MessageID != "": writeError(w, r, 409, "attachment_sent") default: delete(f.files, id) w.WriteHeader(http.StatusNoContent) } } // checkFiles reports whether a send may name ids, as Equipo's checkFiles // and linkFiles do: at most five, each the person's own and unsent, none // twice, and no upload dropped meanwhile (ExpireUploads). func (f *Fake) checkFiles(owner string, ids []string) bool { f.fmu.Lock() defer f.fmu.Unlock() if len(ids) == 0 { return true } if len(ids) > maxFiles { return false } if f.expired { f.expired = false return false } seen := map[string]bool{} for _, id := range ids { u, ok := f.files[id] if !ok || u.owner != owner || u.MessageID != "" || seen[id] { return false } seen[id] = true } return true } // linkFiles links the checked ids to message m, in order, and answers // them as the message carries them. func (f *Fake) linkFiles(ids []string, m string) []file { f.fmu.Lock() defer f.fmu.Unlock() var out []file for _, id := range ids { u := f.files[id] u.MessageID, u.Revision = m, u.Revision+1 out = append(out, *u) } return out }