oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "bytes"
5 "crypto/rand"
6 "crypto/sha256"
7 "encoding/hex"
8 "image"
9 _ "image/gif" // DecodeConfig for the image types Equipo sniffs
10 _ "image/jpeg"
11 _ "image/png"
12 "io"
13 "mime"
14 "net/http"
15 "path"
16 "strconv"
17 "strings"
18 "sync"
19 "time"
20 "unicode/utf8"
21)
22
23// Equipo's attachments (internal/attach, chat/attachments.go and
24// attachments_http.go, and the delete route of the assistant-attachments
25// spec, A2): POST /api/v1/attachments takes one file (the bytes as the
26// body, its type in Content-Type, its name in Content-Disposition) and
27// answers 201 with its wire.MessageAttachment; GET
28// /api/v1/attachments/{id} and /preview serve the person's own file;
29// DELETE /api/v1/attachments/{id} deletes an unsent one (204), 404 when it
30// isn't the person's or is gone, 409 attachment_sent once it is on a
31// message. A person here is a device: another device's file is 404.
32
33// Equipo's limits (internal/attach).
34const (
35 maxUpload = 10 << 20
36 maxFiles = 5
37 maxUnsent = 20
38 maxSide = 12000
39 maxPixels = 40_000_000
40 attachments = "/api/v1/attachments"
41)
42
43// file is one upload: its wire.MessageAttachment and its bytes.
44type file struct {
45 ID string `json:"id"`
46 Revision int64 `json:"revision"`
47 Kind string `json:"kind"`
48 Name string `json:"name"`
49 MediaType string `json:"media_type"`
50 Size int64 `json:"size"`
51 SHA256 string `json:"sha256"`
52 Width int `json:"width"`
53 Height int `json:"height"`
54 MessageID string `json:"message_id"`
55 CreatedAt time.Time `json:"created_at"`
56 owner string
57 data []byte
58}
59
60// fileState is the fake's files and the switches tests turn.
61type fileState struct {
62 fmu sync.Mutex
63 files map[string]*file
64 // filesReady says the person's runner can take files (can_attach);
65 // false, as for a runner never seen, until FilesReady.
66 filesReady bool
67 // expired makes the next send with files 422, as an upload dropped
68 // after 24 hours does.
69 expired bool
70 // uploadHold and uploadEntered hold the next upload, once its body has
71 // arrived and before it answers; busyNext makes the next upload 503
72 // with Retry-After: 1; uploadDelay slows every upload, so a test sees
73 // how many overlap (uploading, most).
74 uploadHold, uploadEntered chan struct{}
75 busyNext bool
76 uploadDelay time.Duration
77 uploading, most int
78 // hostileType and hostileDisposition, when set, are what every read
79 // answers with instead of Equipo's own; readDelay writes a read in 64
80 // KiB pieces with this pause between; readStatus, when set, is what
81 // every read answers (with an error body).
82 hostileType, hostileDisposition string
83 readDelay time.Duration
84 readStatus int
85 // readHold, when set, holds every read before its headers until it is
86 // closed (or the reader gives up).
87 readHold chan struct{}
88 // sendHold and sendEntered hold the next send of a message, once it
89 // has arrived and before it is looked at.
90 sendHold, sendEntered chan struct{}
91}
92
93func (s *fileState) initFiles() { s.files = map[string]*file{} }
94
95// FilesReady says whether the person's runner can take files: the
96// snapshot's can_attach, and whether a send with files passes (else 409
97// attachments_unavailable).
98func (f *Fake) FilesReady(ok bool) { f.fmu.Lock(); f.filesReady = ok; f.fmu.Unlock() }
99
100// ExpireUploads makes the next send with files 422 invalid_input, as when
101// an upload was dropped after 24 hours unsent.
102func (f *Fake) ExpireUploads() { f.fmu.Lock(); f.expired = true; f.fmu.Unlock() }
103
104// HoldNextUpload makes the next upload wait, once its body has arrived and
105// before it answers, until release is called. entered is closed when it
106// arrives.
107func (f *Fake) HoldNextUpload() (entered <-chan struct{}, release func()) {
108 f.fmu.Lock()
109 defer f.fmu.Unlock()
110 f.uploadHold, f.uploadEntered = make(chan struct{}), make(chan struct{})
111 hold := f.uploadHold
112 return f.uploadEntered, sync.OnceFunc(func() { close(hold) })
113}
114
115// HoldNextSend makes the next send of a message wait, once it has arrived
116// and before it is looked at, until release is called. entered is closed
117// when it arrives.
118func (f *Fake) HoldNextSend() (entered <-chan struct{}, release func()) {
119 f.fmu.Lock()
120 defer f.fmu.Unlock()
121 f.sendHold, f.sendEntered = make(chan struct{}), make(chan struct{})
122 hold := f.sendHold
123 return f.sendEntered, sync.OnceFunc(func() { close(hold) })
124}
125
126// BusyNextUpload makes the next upload answer 503 with Retry-After: 1.
127func (f *Fake) BusyNextUpload() { f.fmu.Lock(); f.busyNext = true; f.fmu.Unlock() }
128
129// SlowUploads makes every upload take d before it answers.
130func (f *Fake) SlowUploads(d time.Duration) { f.fmu.Lock(); f.uploadDelay = d; f.fmu.Unlock() }
131
132// UploadsAtOnce is the most uploads the fake has had in flight at once.
133func (f *Fake) UploadsAtOnce() int { f.fmu.Lock(); defer f.fmu.Unlock(); return f.most }
134
135// ServeHostile makes every read answer with Content-Type typ and
136// Content-Disposition disposition, as a broken Equipo might ("" for
137// Equipo's own).
138func (f *Fake) ServeHostile(typ, disposition string) {
139 f.fmu.Lock()
140 f.hostileType, f.hostileDisposition = typ, disposition
141 f.fmu.Unlock()
142}
143
144// ServeSlowly makes every read write its bytes 64 KiB at a time, pausing
145// d between pieces.
146func (f *Fake) ServeSlowly(d time.Duration) { f.fmu.Lock(); f.readDelay = d; f.fmu.Unlock() }
147
148// HoldReads holds every read before its headers until release is called.
149func (f *Fake) HoldReads() (release func()) {
150 hold := make(chan struct{})
151 f.fmu.Lock()
152 f.readHold = hold
153 f.fmu.Unlock()
154 return sync.OnceFunc(func() {
155 f.fmu.Lock()
156 f.readHold = nil
157 f.fmu.Unlock()
158 close(hold)
159 })
160}
161
162// FailReads makes every read answer status with an error body (0 stops).
163func (f *Fake) FailReads(status int) { f.fmu.Lock(); f.readStatus = status; f.fmu.Unlock() }
164
165// FileErrorBody is in the body of every read FailReads fails, so a test
166// can see that it never comes through.
167const FileErrorBody = "equipo-error-body"
168
169// Upload is the upload with id as the fake keeps it: its bytes, name and
170// type, and the message it went with ("" while unsent). ok is false once
171// it is deleted, or if there never was one.
172func (f *Fake) Upload(id string) (data []byte, name, media, message string, ok bool) {
173 f.fmu.Lock()
174 defer f.fmu.Unlock()
175 u, ok := f.files[id]
176 if !ok {
177 return nil, "", "", "", false
178 }
179 return u.data, u.Name, u.MediaType, u.MessageID, true
180}
181
182// Uploads are the ids of the files the fake holds, sent or not.
183func (f *Fake) Uploads() []string {
184 f.fmu.Lock()
185 defer f.fmu.Unlock()
186 var out []string
187 for id := range f.files {
188 out = append(out, id)
189 }
190 return out
191}
192
193// serveFiles answers the attachment routes for the person behind the
194// bearer (owner); ok is false for any other path.
195func (f *Fake) serveFiles(w http.ResponseWriter, r *http.Request, owner string) bool {
196 p := r.URL.Path
197 switch {
198 case r.Method == http.MethodPost && p == attachments:
199 f.upload(w, r, owner)
200 case !strings.HasPrefix(p, attachments+"/"):
201 return false
202 case r.Method == http.MethodDelete:
203 f.deleteFile(w, r, owner, strings.TrimPrefix(p, attachments+"/"))
204 case r.Method == http.MethodGet || r.Method == http.MethodHead:
205 id, preview := strings.TrimPrefix(p, attachments+"/"), false
206 if rest, ok := strings.CutSuffix(id, "/preview"); ok {
207 id, preview = rest, true
208 }
209 f.readFile(w, r, owner, id, preview)
210 default:
211 writeError(w, r, 404, "not_found")
212 }
213 return true
214}
215
216// upload is POST /api/v1/attachments, as Equipo's chat.ReadUpload and
217// Store.Upload: the type sniffed from the bytes, never the declared one.
218func (f *Fake) upload(w http.ResponseWriter, r *http.Request, owner string) {
219 f.fmu.Lock()
220 f.uploading++
221 f.most = max(f.most, f.uploading)
222 hold, entered, busy, delay := f.uploadHold, f.uploadEntered, f.busyNext, f.uploadDelay
223 f.uploadHold, f.uploadEntered, f.busyNext = nil, nil, false
224 f.fmu.Unlock()
225 defer func() { f.fmu.Lock(); f.uploading--; f.fmu.Unlock() }()
226 f.waitHeld(hold, entered)
227 if delay > 0 {
228 select {
229 case <-time.After(delay):
230 case <-f.closing:
231 }
232 }
233 if busy {
234 w.Header().Set("Retry-After", "1")
235 writeError(w, r, 503, "unavailable")
236 return
237 }
238 data, _ := io.ReadAll(r.Body)
239 if r.ContentLength > maxUpload || len(data) > maxUpload {
240 writeError(w, r, 413, "attachment_too_large")
241 return
242 }
243 name := ""
244 if _, params, err := mime.ParseMediaType(r.Header.Get("Content-Disposition")); err == nil {
245 name = params["filename"]
246 }
247 u, status, code := sniff(name, r.Header.Get("Content-Type"), data)
248 if status != 0 {
249 writeError(w, r, status, code)
250 return
251 }
252 f.fmu.Lock()
253 defer f.fmu.Unlock()
254 unsent := 0
255 for _, x := range f.files {
256 if x.owner == owner && x.MessageID == "" {
257 unsent++
258 }
259 }
260 if unsent >= maxUnsent {
261 writeError(w, r, 409, "attachment_limit")
262 return
263 }
264 sum := sha256.Sum256(data)
265 u.ID, u.Revision, u.owner, u.data = "at_"+strings.ToLower(rand.Text()), 1, owner, data
266 u.Size, u.SHA256, u.CreatedAt = int64(len(data)), hex.EncodeToString(sum[:]), time.Now().UTC()
267 f.files[u.ID] = u
268 writeJSON(w, http.StatusCreated, *u)
269}
270
271// sniff is the file Equipo would keep for data named name: its kind,
272// type, name and size, or the status and code it refuses it with.
273func sniff(name, declared string, data []byte) (*file, int, string) {
274 u := &file{Kind: "file", Name: safeName(name)}
275 declared, _, _ = mime.ParseMediaType(declared)
276 heic := len(data) >= 12 && string(data[4:8]) == "ftyp" && strings.Contains("heic heix mif1 hevc", string(data[8:12]))
277 if declared == "image/heic" || declared == "image/heif" || heic {
278 return nil, 415, "attachment_heic"
279 }
280 if len(data) == 0 {
281 return nil, 415, "attachment_type"
282 }
283 switch ct := http.DetectContentType(data); {
284 case ct == "image/png" || ct == "image/jpeg" || ct == "image/gif" || ct == "image/webp":
285 u.Kind, u.MediaType = "image", ct
286 if cfg, _, err := image.DecodeConfig(bytes.NewReader(data)); err == nil {
287 u.Width, u.Height = cfg.Width, cfg.Height
288 }
289 if u.Width > maxSide || u.Height > maxSide || u.Width*u.Height > maxPixels {
290 return nil, 413, "attachment_pixels"
291 }
292 case ct == "application/pdf":
293 u.MediaType = ct
294 case strings.HasPrefix(ct, "text/") && utf8.Valid(data):
295 switch ext := strings.ToLower(path.Ext(u.Name)); {
296 case declared == "text/markdown" || ext == ".md" || ext == ".markdown":
297 u.MediaType = "text/markdown"
298 case declared == "text/csv" || ext == ".csv":
299 u.MediaType = "text/csv"
300 case declared == "application/json" || ext == ".json":
301 u.MediaType = "application/json"
302 default:
303 u.MediaType = "text/plain"
304 }
305 default:
306 return nil, 415, "attachment_type"
307 }
308 return u, 0, ""
309}
310
311// safeName is a name as Equipo keeps it: its last path part, without
312// control characters, at most 255 bytes, "file" when nothing is left.
313func safeName(name string) string {
314 name = path.Base(strings.ReplaceAll(name, `\`, "/"))
315 name = strings.Map(func(r rune) rune {
316 if r < 0x20 || r == 0x7f {
317 return -1
318 }
319 return r
320 }, strings.ToValidUTF8(name, ""))
321 for len(name) > 255 {
322 _, n := utf8.DecodeLastRuneInString(name)
323 name = name[:len(name)-n]
324 }
325 if name == "" || name == "." || name == "/" {
326 return "file"
327 }
328 return name
329}
330
331// readFile is GET /api/v1/attachments/{id}[/preview], as Equipo's
332// serveFile: the sniffed type (text with its charset), inline for an image
333// and a download for anything else, nosniff and a sandboxing CSP. A
334// preview is an image's own bytes here (Equipo scales it), and 404 for a
335// file.
336func (f *Fake) readFile(w http.ResponseWriter, r *http.Request, owner, id string, preview bool) {
337 f.fmu.Lock()
338 u, ok := f.files[id]
339 status, typ, disposition, delay, hold := f.readStatus, f.hostileType, f.hostileDisposition, f.readDelay, f.readHold
340 f.fmu.Unlock()
341 if hold != nil {
342 select {
343 case <-hold:
344 case <-r.Context().Done():
345 return
346 case <-f.closing:
347 return
348 }
349 }
350 if status != 0 {
351 writeJSON(w, status, map[string]string{"code": FileErrorBody, "detail": FileErrorBody})
352 return
353 }
354 if !ok || u.owner != owner || preview && u.Kind != "image" {
355 writeError(w, r, 404, "not_found")
356 return
357 }
358 if typ == "" {
359 typ = u.MediaType
360 if strings.HasPrefix(typ, "text/") || typ == "application/json" {
361 typ += "; charset=utf-8"
362 }
363 }
364 if disposition == "" {
365 disposition = "attachment"
366 if u.Kind == "image" {
367 disposition = "inline"
368 }
369 }
370 h := w.Header()
371 h.Set("Content-Type", typ)
372 h.Set("Content-Length", strconv.Itoa(len(u.data)))
373 h.Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": u.Name}))
374 h.Set("X-Content-Type-Options", "nosniff")
375 h.Set("Content-Security-Policy", "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox")
376 h.Set("Cache-Control", "private, max-age=86400")
377 h.Set("X-Equipo-Only", "yes")
378 w.WriteHeader(http.StatusOK)
379 if r.Method == http.MethodHead {
380 return
381 }
382 rc := http.NewResponseController(w)
383 for rest := u.data; len(rest) > 0; {
384 n := min(len(rest), 64<<10)
385 if _, err := w.Write(rest[:n]); err != nil {
386 return
387 }
388 rest = rest[n:]
389 if delay > 0 {
390 _ = rc.Flush()
391 select {
392 case <-time.After(delay):
393 case <-r.Context().Done():
394 return
395 case <-f.closing:
396 return
397 }
398 }
399 }
400}
401
402// deleteFile is DELETE /api/v1/attachments/{id}.
403func (f *Fake) deleteFile(w http.ResponseWriter, r *http.Request, owner, id string) {
404 f.fmu.Lock()
405 defer f.fmu.Unlock()
406 u, ok := f.files[id]
407 switch {
408 case !ok || u.owner != owner:
409 writeError(w, r, 404, "not_found")
410 case u.MessageID != "":
411 writeError(w, r, 409, "attachment_sent")
412 default:
413 delete(f.files, id)
414 w.WriteHeader(http.StatusNoContent)
415 }
416}
417
418// checkFiles reports whether a send may name ids, as Equipo's checkFiles
419// and linkFiles do: at most five, each the person's own and unsent, none
420// twice, and no upload dropped meanwhile (ExpireUploads).
421func (f *Fake) checkFiles(owner string, ids []string) bool {
422 f.fmu.Lock()
423 defer f.fmu.Unlock()
424 if len(ids) == 0 {
425 return true
426 }
427 if len(ids) > maxFiles {
428 return false
429 }
430 if f.expired {
431 f.expired = false
432 return false
433 }
434 seen := map[string]bool{}
435 for _, id := range ids {
436 u, ok := f.files[id]
437 if !ok || u.owner != owner || u.MessageID != "" || seen[id] {
438 return false
439 }
440 seen[id] = true
441 }
442 return true
443}
444
445// linkFiles links the checked ids to message m, in order, and answers
446// them as the message carries them.
447func (f *Fake) linkFiles(ids []string, m string) []file {
448 f.fmu.Lock()
449 defer f.fmu.Unlock()
450 var out []file
451 for _, id := range ids {
452 u := f.files[id]
453 u.MessageID, u.Revision = m, u.Revision+1
454 out = append(out, *u)
455 }
456 return out
457}
458