package web import ( "bytes" "context" "errors" "io" "mime" "net/http" "strconv" "strings" "sync/atomic" "time" _ "amadan.net/rastrillo/rastrillo/locales/en" // pageLocale's marks "amadan.net/rastrillo/rastrillo/number" "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. A file read from Equipo that brings no byte for ReadIdle // (30 s when zero) is given up. type UploadBounds struct { Slots int SlotWait time.Duration ReadDeadline time.Duration Upstream time.Duration ReadIdle 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} } // 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" // pageLocale is the locale Base's pages are written in (layout.html's // lang), whose marks a file's size is written with; ask.js writes it in // the same (fileSize), from the page's lang. const pageLocale = "en" // fileSize is a file's size as the thread shows it: bytes under 1 KB, // whole KB under 1 MB, then MB to one place, rounding half up (1024 to // the K, as Equipo's own chips do). ask.js has the twin. func fileSize(n int64) string { whole := func(v int64) string { s, err := number.Format(pageLocale, number.Decimal(strconv.FormatInt(v, 10)), number.Options{}) if err != nil { return strconv.FormatInt(v, 10) } return s } switch { case n < 1024: return whole(max(n, 0)) + " B" case n < 1<<20: return whole((n+512)/1024) + " KB" } tenths := (n*10 + 1<<19) >> 20 s, err := number.Format(pageLocale, number.Decimal(strconv.FormatInt(tenths/10, 10)+"."+strconv.FormatInt(tenths%10, 10)), number.Options{Places: 1}) if err != nil { s = strconv.FormatInt(tenths/10, 10) + "." + strconv.FormatInt(tenths%10, 10) } return s + " MB" } // 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 } // A body of unknown length would grow its buffer by doubling; a // browser always sends a File's length. if r.ContentLength < 0 { writeJSON(w, http.StatusLengthRequired, map[string]string{"code": "length_required"}) 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)) } // Read into a buffer of the declared size, so a slot holds about 10 MiB // at most, not the doubling ReadAll does as it grows. var buf bytes.Buffer if r.ContentLength > 0 { buf.Grow(int(r.ContentLength) + 1) } _, err := buf.ReadFrom(io.LimitReader(r.Body, equipo.MaxUpload+1)) body := buf.Bytes() 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 { gone, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 10*time.Second) defer cancel() if err := a.ask.client.DeleteAttachment(gone, 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, equipo.CleanAttachment(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 !equipo.ValidAttachmentID(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 !equipo.ValidAttachmentID(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 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 !equipo.ValidAttachmentID(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 } // A read that brings nothing for ReadIdle is given up (the timer is // reset by every read), so a stalled Equipo never holds a browser's // connection. ctx, cancel := context.WithCancel(r.Context()) defer cancel() idle := a.ask.uploads.b.ReadIdle if idle <= 0 { idle = 30 * time.Second } quiet := time.AfterFunc(idle, cancel) defer quiet.Stop() res, err := a.ask.client.OpenAttachment(ctx, 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) h.Set("Cross-Origin-Resource-Policy", "same-origin") 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) quiet.Reset(idle) if n > 0 { _ = rc.SetWriteDeadline(time.Now().Add(writeWindow)) if _, werr := w.Write(buf[:n]); werr != nil { return } } if err != nil { return } } } }