| 1 | package web |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "mime" |
| 9 | "net/http" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "sync/atomic" |
| 13 | "time" |
| 14 | |
| 15 | _ "amadan.net/rastrillo/rastrillo/locales/en" // pageLocale's marks |
| 16 | "amadan.net/rastrillo/rastrillo/number" |
| 17 | "github.com/go-chi/chi/v5" |
| 18 | |
| 19 | "amadan.net/oficina/base/internal/equipo" |
| 20 | ) |
| 21 | |
| 22 | // Files in Ask (plan P1 to P3, P7, P11): Base relays a member's uploads, |
| 23 | // reads and deletes to Equipo with their own bearer, and keeps no byte of |
| 24 | // any file. Equipo holds them; the page and the apps name a file by its |
| 25 | // Equipo id alone, under Base's own /ask/attachments/{id}. |
| 26 | |
| 27 | // UploadBounds bound the upload relay (plan P1): Slots uploads at once in |
| 28 | // the whole process, each taken before its body is read; a request that |
| 29 | // waits SlotWait for one is told to come back; a body is read within |
| 30 | // ReadDeadline; Equipo answers an upload, or a read's headers, within |
| 31 | // Upstream. A file read from Equipo that brings no byte for ReadIdle |
| 32 | // (30 s when zero) is given up. |
| 33 | type UploadBounds struct { |
| 34 | Slots int |
| 35 | SlotWait time.Duration |
| 36 | ReadDeadline time.Duration |
| 37 | Upstream time.Duration |
| 38 | ReadIdle time.Duration |
| 39 | } |
| 40 | |
| 41 | var uploadBounds = UploadBounds{Slots: 4, SlotWait: 10 * time.Second, ReadDeadline: 60 * time.Second, Upstream: 60 * time.Second} |
| 42 | |
| 43 | // SetUploadBounds makes b the bounds of every app built from now on, and |
| 44 | // gives back what restores the ones before. Tests shorten the times. |
| 45 | func SetUploadBounds(b UploadBounds) (restore func()) { |
| 46 | was := uploadBounds |
| 47 | uploadBounds = b |
| 48 | return func() { uploadBounds = was } |
| 49 | } |
| 50 | |
| 51 | // UploadReading, when set, hears the slots in use each time an upload's |
| 52 | // body read starts. Tests check the slot comes first. |
| 53 | var UploadReading func(inUse int) |
| 54 | |
| 55 | // uploads is the relay's slots: a semaphore, and how many are held. |
| 56 | type uploads struct { |
| 57 | slots chan struct{} |
| 58 | inUse atomic.Int32 |
| 59 | b UploadBounds |
| 60 | } |
| 61 | |
| 62 | func newUploads(b UploadBounds) *uploads { |
| 63 | return &uploads{slots: make(chan struct{}, max(b.Slots, 1)), b: b} |
| 64 | } |
| 65 | |
| 66 | // The four image types Base shows inline (plan P3); the other five of |
| 67 | // Equipo's nine go as downloads, and anything else as an octet stream. |
| 68 | var ( |
| 69 | inlineTypes = map[string]bool{"image/png": true, "image/jpeg": true, "image/webp": true, "image/gif": true} |
| 70 | downloadTypes = map[string]bool{"application/pdf": true, "text/plain": true, "text/markdown": true, "text/csv": true, "application/json": true} |
| 71 | ) |
| 72 | |
| 73 | // fileCSP is what every file Base serves carries: nothing in it may run, |
| 74 | // and only an image of Base's own may show. |
| 75 | const fileCSP = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox" |
| 76 | |
| 77 | // pageLocale is the locale Base's pages are written in (layout.html's |
| 78 | // lang), whose marks a file's size is written with; ask.js writes it in |
| 79 | // the same (fileSize), from the page's lang. |
| 80 | const pageLocale = "en" |
| 81 | |
| 82 | // fileSize is a file's size as the thread shows it: bytes under 1 KB, |
| 83 | // whole KB under 1 MB, then MB to one place, rounding half up (1024 to |
| 84 | // the K, as Equipo's own chips do). ask.js has the twin. |
| 85 | func fileSize(n int64) string { |
| 86 | whole := func(v int64) string { |
| 87 | s, err := number.Format(pageLocale, number.Decimal(strconv.FormatInt(v, 10)), number.Options{}) |
| 88 | if err != nil { |
| 89 | return strconv.FormatInt(v, 10) |
| 90 | } |
| 91 | return s |
| 92 | } |
| 93 | switch { |
| 94 | case n < 1024: |
| 95 | return whole(max(n, 0)) + " B" |
| 96 | case n < 1<<20: |
| 97 | return whole((n+512)/1024) + " KB" |
| 98 | } |
| 99 | tenths := (n*10 + 1<<19) >> 20 |
| 100 | s, err := number.Format(pageLocale, number.Decimal(strconv.FormatInt(tenths/10, 10)+"."+strconv.FormatInt(tenths%10, 10)), number.Options{Places: 1}) |
| 101 | if err != nil { |
| 102 | s = strconv.FormatInt(tenths/10, 10) + "." + strconv.FormatInt(tenths%10, 10) |
| 103 | } |
| 104 | return s + " MB" |
| 105 | } |
| 106 | |
| 107 | // askState is the member's live connection for a relayed call that reads |
| 108 | // no form. Without one it answers for the caller, as askBearer does. |
| 109 | func (a *app) askState(w http.ResponseWriter, r *http.Request) (askConn, bool) { |
| 110 | me, _ := CurrentMember(r) |
| 111 | l, sec, state, err := a.askLink(r.Context(), me) |
| 112 | switch { |
| 113 | case err != nil: |
| 114 | a.logger.Error("ask: link", "err", err) |
| 115 | http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| 116 | case state != askReady && wantsJSON(r): |
| 117 | writeJSON(w, http.StatusConflict, map[string]string{"state": homeState(state)}) |
| 118 | case state != askReady: |
| 119 | http.Redirect(w, r, "/ask", http.StatusSeeOther) |
| 120 | default: |
| 121 | return askConn{me, l.DeviceID, sec.Token}, true |
| 122 | } |
| 123 | return askConn{}, false |
| 124 | } |
| 125 | |
| 126 | // askUpload is POST /ask/attachments: one file, the bytes as the body, its |
| 127 | // type in Content-Type and its name in Content-Disposition, relayed to |
| 128 | // Equipo. The answer is Equipo's attachment (201), or {"code"} with |
| 129 | // Equipo's status for its refusals, 413 attachment_too_large for a body |
| 130 | // over 10 MiB (before Equipo is called), 503 with Retry-After when every |
| 131 | // slot stays busy, or {"state"} as for every Ask write. |
| 132 | func (a *app) askUpload(w http.ResponseWriter, r *http.Request) { |
| 133 | if r.ContentLength > equipo.MaxUpload { |
| 134 | writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"code": "attachment_too_large"}) |
| 135 | return |
| 136 | } |
| 137 | // A body of unknown length would grow its buffer by doubling; a |
| 138 | // browser always sends a File's length. |
| 139 | if r.ContentLength < 0 { |
| 140 | writeJSON(w, http.StatusLengthRequired, map[string]string{"code": "length_required"}) |
| 141 | return |
| 142 | } |
| 143 | c, ok := a.askState(w, r) |
| 144 | if !ok { |
| 145 | return |
| 146 | } |
| 147 | up := a.ask.uploads |
| 148 | wait := time.NewTimer(up.b.SlotWait) |
| 149 | defer wait.Stop() |
| 150 | select { |
| 151 | case up.slots <- struct{}{}: |
| 152 | case <-wait.C: |
| 153 | w.Header().Set("Retry-After", "2") |
| 154 | writeJSON(w, http.StatusServiceUnavailable, map[string]string{"code": "busy"}) |
| 155 | return |
| 156 | case <-r.Context().Done(): |
| 157 | return |
| 158 | } |
| 159 | n := up.inUse.Add(1) |
| 160 | defer func() { up.inUse.Add(-1); <-up.slots }() |
| 161 | // Never read a body without a deadline: a stalled one would hold its |
| 162 | // slot until TCP gave up. |
| 163 | if err := http.NewResponseController(w).SetReadDeadline(time.Now().Add(up.b.ReadDeadline)); err != nil { |
| 164 | a.logger.Error("ask: upload read deadline", "err", err) |
| 165 | writeJSON(w, http.StatusServiceUnavailable, map[string]string{"code": "busy"}) |
| 166 | return |
| 167 | } |
| 168 | if UploadReading != nil { |
| 169 | UploadReading(int(n)) |
| 170 | } |
| 171 | // Read into a buffer of the declared size, so a slot holds about 10 MiB |
| 172 | // at most, not the doubling ReadAll does as it grows. |
| 173 | var buf bytes.Buffer |
| 174 | if r.ContentLength > 0 { |
| 175 | buf.Grow(int(r.ContentLength) + 1) |
| 176 | } |
| 177 | _, err := buf.ReadFrom(io.LimitReader(r.Body, equipo.MaxUpload+1)) |
| 178 | body := buf.Bytes() |
| 179 | if err != nil { |
| 180 | http.Error(w, "bad request", http.StatusBadRequest) |
| 181 | return |
| 182 | } |
| 183 | if len(body) > equipo.MaxUpload { |
| 184 | writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"code": "attachment_too_large"}) |
| 185 | return |
| 186 | } |
| 187 | name := "" |
| 188 | if _, params, err := mime.ParseMediaType(r.Header.Get("Content-Disposition")); err == nil { |
| 189 | name = params["filename"] |
| 190 | } |
| 191 | // Equipo's answer outlives the request, so an upload it takes is never |
| 192 | // half-known: if the page has gone by then (Remove aborted it), the |
| 193 | // upload is deleted at once. |
| 194 | ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), up.b.Upstream) |
| 195 | defer cancel() |
| 196 | at, err := a.ask.client.Upload(ctx, c.token, name, r.Header.Get("Content-Type"), body) |
| 197 | if err == nil && r.Context().Err() != nil { |
| 198 | gone, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 10*time.Second) |
| 199 | defer cancel() |
| 200 | if err := a.ask.client.DeleteAttachment(gone, c.token, at.ID); err != nil { |
| 201 | a.logger.Warn("ask: delete an upload whose page went", "err", err) |
| 202 | } |
| 203 | return |
| 204 | } |
| 205 | var e *equipo.Error |
| 206 | switch { |
| 207 | case err == nil: |
| 208 | writeJSON(w, http.StatusCreated, equipo.CleanAttachment(at)) |
| 209 | case errors.Is(err, equipo.ErrUnauthenticated): |
| 210 | a.askLost(r.Context(), c.me, c.device) |
| 211 | writeJSON(w, http.StatusConflict, map[string]string{"state": askReconnect}) |
| 212 | case errors.As(err, &e) && strings.HasPrefix(e.Code, "attachment_"): |
| 213 | writeJSON(w, e.Status, map[string]string{"code": e.Code}) |
| 214 | case errors.As(err, &e) && e.Status == http.StatusServiceUnavailable: |
| 215 | w.Header().Set("Retry-After", retryAfter(e.RetryAfter)) |
| 216 | writeJSON(w, http.StatusServiceUnavailable, map[string]string{"code": "busy"}) |
| 217 | default: |
| 218 | a.logger.Warn("ask: upload", "err", err) |
| 219 | writeJSON(w, http.StatusBadGateway, map[string]string{"state": askUnavailable}) |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // retryAfter is Equipo's Retry-After when it is a few seconds, else 2. |
| 224 | func retryAfter(s string) string { |
| 225 | if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= 10 { |
| 226 | return s |
| 227 | } |
| 228 | return "2" |
| 229 | } |
| 230 | |
| 231 | // askDeleteAttachment is DELETE /ask/attachments/{id}: Remove on a chip, |
| 232 | // relayed. Equipo's 404 (gone already) is done too: 204. One already sent |
| 233 | // is 409 {"state":"ready","code":"attachment_sent"}. |
| 234 | func (a *app) askDeleteAttachment(w http.ResponseWriter, r *http.Request) { |
| 235 | id := chi.URLParam(r, "id") |
| 236 | if !equipo.ValidAttachmentID(id) { |
| 237 | http.NotFound(w, r) |
| 238 | return |
| 239 | } |
| 240 | c, ok := a.askState(w, r) |
| 241 | if !ok { |
| 242 | return |
| 243 | } |
| 244 | err := a.ask.client.DeleteAttachment(r.Context(), c.token, id) |
| 245 | var e *equipo.Error |
| 246 | switch { |
| 247 | case err == nil: |
| 248 | w.WriteHeader(http.StatusNoContent) |
| 249 | case errors.Is(err, equipo.ErrUnauthenticated): |
| 250 | a.askLost(r.Context(), c.me, c.device) |
| 251 | writeJSON(w, http.StatusConflict, map[string]string{"state": askReconnect}) |
| 252 | case errors.As(err, &e) && e.Status == http.StatusConflict: |
| 253 | writeJSON(w, http.StatusConflict, map[string]string{"state": askReady, "code": e.Code}) |
| 254 | default: |
| 255 | a.logger.Warn("ask: delete attachment", "err", err) |
| 256 | writeJSON(w, http.StatusBadGateway, map[string]string{"state": askUnavailable}) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | // askDiscard is POST /ask/attachments/discard: the page's unsent uploads |
| 261 | // as it goes away (a beacon, up to five id fields), deleted as best Base |
| 262 | // can. It always answers 204: nobody is there to hear more. |
| 263 | func (a *app) askDiscard(w http.ResponseWriter, r *http.Request) { |
| 264 | defer w.WriteHeader(http.StatusNoContent) |
| 265 | r.Body = http.MaxBytesReader(w, r.Body, 4<<10) |
| 266 | if r.ParseForm() != nil { |
| 267 | return |
| 268 | } |
| 269 | me, _ := CurrentMember(r) |
| 270 | l, sec, state, err := a.askLink(r.Context(), me) |
| 271 | if err != nil || state != askReady { |
| 272 | return |
| 273 | } |
| 274 | ctx := context.WithoutCancel(r.Context()) |
| 275 | ids := r.PostForm["id"] |
| 276 | for _, id := range ids[:min(len(ids), equipo.MaxFiles)] { |
| 277 | if !equipo.ValidAttachmentID(id) { |
| 278 | continue |
| 279 | } |
| 280 | err := a.ask.client.DeleteAttachment(ctx, sec.Token, id) |
| 281 | if errors.Is(err, equipo.ErrUnauthenticated) { |
| 282 | a.askLost(ctx, me, l.DeviceID) |
| 283 | return |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | // askAttachment is GET (and HEAD) /ask/attachments/{id}, and its |
| 289 | // /preview: one of the member's files streamed from Equipo, never held, |
| 290 | // with headers Base decides (plan P3). Only four image types show inline; |
| 291 | // /preview is for those alone. Equipo's own headers and error bodies never |
| 292 | // come through. Without a live connection, or for a file that isn't the |
| 293 | // member's, it is 404; when Equipo fails or is slow, 502 with no body, so |
| 294 | // an <img> shows its alt. |
| 295 | func (a *app) askAttachment(preview bool) http.HandlerFunc { |
| 296 | return func(w http.ResponseWriter, r *http.Request) { |
| 297 | id := chi.URLParam(r, "id") |
| 298 | if !equipo.ValidAttachmentID(id) { |
| 299 | http.NotFound(w, r) |
| 300 | return |
| 301 | } |
| 302 | me, _ := CurrentMember(r) |
| 303 | l, sec, state, err := a.askLink(r.Context(), me) |
| 304 | if err != nil { |
| 305 | a.logger.Error("ask: link", "err", err) |
| 306 | w.WriteHeader(http.StatusBadGateway) |
| 307 | return |
| 308 | } |
| 309 | if state != askReady { |
| 310 | http.NotFound(w, r) |
| 311 | return |
| 312 | } |
| 313 | // A read that brings nothing for ReadIdle is given up (the timer is |
| 314 | // reset by every read), so a stalled Equipo never holds a browser's |
| 315 | // connection. |
| 316 | ctx, cancel := context.WithCancel(r.Context()) |
| 317 | defer cancel() |
| 318 | idle := a.ask.uploads.b.ReadIdle |
| 319 | if idle <= 0 { |
| 320 | idle = 30 * time.Second |
| 321 | } |
| 322 | quiet := time.AfterFunc(idle, cancel) |
| 323 | defer quiet.Stop() |
| 324 | res, err := a.ask.client.OpenAttachment(ctx, sec.Token, id, preview) |
| 325 | var e *equipo.Error |
| 326 | switch { |
| 327 | case errors.Is(err, equipo.ErrUnauthenticated): |
| 328 | a.askLost(r.Context(), me, l.DeviceID) |
| 329 | http.NotFound(w, r) |
| 330 | return |
| 331 | case errors.As(err, &e) && e.Status < 500: |
| 332 | http.NotFound(w, r) |
| 333 | return |
| 334 | case err != nil: |
| 335 | if r.Context().Err() == nil { |
| 336 | a.logger.Warn("ask: read attachment", "err", err) |
| 337 | } |
| 338 | w.WriteHeader(http.StatusBadGateway) |
| 339 | return |
| 340 | } |
| 341 | defer res.Body.Close() |
| 342 | media, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type")) |
| 343 | disposition := "attachment" |
| 344 | switch { |
| 345 | case inlineTypes[media]: |
| 346 | disposition = "inline" |
| 347 | case preview: |
| 348 | http.NotFound(w, r) |
| 349 | return |
| 350 | case downloadTypes[media]: |
| 351 | if strings.HasPrefix(media, "text/") || media == "application/json" { |
| 352 | media += "; charset=utf-8" |
| 353 | } |
| 354 | default: |
| 355 | media = "application/octet-stream" |
| 356 | } |
| 357 | // The name is the one place Equipo's header is read: parsed out, |
| 358 | // then put in a header of Base's own. |
| 359 | name := "file" |
| 360 | if _, params, err := mime.ParseMediaType(res.Header.Get("Content-Disposition")); err == nil && params["filename"] != "" { |
| 361 | name = params["filename"] |
| 362 | } |
| 363 | cd := mime.FormatMediaType(disposition, map[string]string{"filename": name}) |
| 364 | if cd == "" { |
| 365 | cd = disposition |
| 366 | } |
| 367 | h := w.Header() |
| 368 | h.Set("Content-Type", media) |
| 369 | h.Set("Content-Disposition", cd) |
| 370 | h.Set("X-Content-Type-Options", "nosniff") |
| 371 | h.Set("Content-Security-Policy", fileCSP) |
| 372 | h.Set("Cross-Origin-Resource-Policy", "same-origin") |
| 373 | if preview { |
| 374 | h.Set("Cache-Control", "private, max-age=3600") |
| 375 | h.Add("Vary", "Cookie") |
| 376 | } else { |
| 377 | h.Set("Cache-Control", "no-store") |
| 378 | } |
| 379 | if n, err := strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64); err == nil && n >= 0 { |
| 380 | h.Set("Content-Length", strconv.FormatInt(n, 10)) |
| 381 | } |
| 382 | w.WriteHeader(http.StatusOK) |
| 383 | if r.Method == http.MethodHead { |
| 384 | return |
| 385 | } |
| 386 | // A browser that stops reading gives up its stream after |
| 387 | // writeWindow, as an event stream does. |
| 388 | rc := http.NewResponseController(w) |
| 389 | buf := make([]byte, 64<<10) |
| 390 | for { |
| 391 | n, err := res.Body.Read(buf) |
| 392 | quiet.Reset(idle) |
| 393 | if n > 0 { |
| 394 | _ = rc.SetWriteDeadline(time.Now().Add(writeWindow)) |
| 395 | if _, werr := w.Write(buf[:n]); werr != nil { |
| 396 | return |
| 397 | } |
| 398 | } |
| 399 | if err != nil { |
| 400 | return |
| 401 | } |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | |