| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "mime" |
| 5 | "net/http" |
| 6 | "regexp" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // Every request body is bounded, and only the upload routes take |
| 11 | // multipart (Fable N3 on 4c95863). Every other handler reads its form |
| 12 | // with PostFormValue, and Go's ParseMultipartForm writes any file part |
| 13 | // over 32 MiB to a temporary file nobody removes: the sign-in door |
| 14 | // would hold a stranger's upload on disk. So a multipart body anywhere |
| 15 | // else is refused, 415, before a handler reads it. |
| 16 | |
| 17 | // uploadScreens are the actions that read ?upload=1: the Markdown |
| 18 | // screens' (a page's, a day's and New scratch page's), and a team |
| 19 | // page's look page (columns and icons spec §2.5). |
| 20 | var uploadScreens = regexp.MustCompile( |
| 21 | `^/(?:scratch|p/[^/]+(?:/look)?|d/[^/]+)$`) |
| 22 | |
| 23 | // isUploadRoute is POST /images, or a Markdown screen's Upload and |
| 24 | // insert (?upload=1 on one of the actions that read it). ?upload=1 |
| 25 | // anywhere else is no upload (Fable, round 5). |
| 26 | func isUploadRoute(request *http.Request) bool { |
| 27 | if request.Method != http.MethodPost { |
| 28 | return false |
| 29 | } |
| 30 | return request.URL.Path == "/images" || |
| 31 | (isUpload(request) && uploadScreens.MatchString(request.URL.Path)) |
| 32 | } |
| 33 | |
| 34 | // bounded is the middleware: a body cap on every request, and multipart |
| 35 | // only where an upload is read. |
| 36 | func bounded(next http.Handler) http.Handler { |
| 37 | return http.HandlerFunc(func(writer http.ResponseWriter, |
| 38 | request *http.Request) { |
| 39 | kind, _, _ := mime.ParseMediaType(request.Header.Get("Content-Type")) |
| 40 | upload := isUploadRoute(request) |
| 41 | if strings.HasPrefix(kind, "multipart/") && !upload { |
| 42 | http.Error(writer, "Unsupported Media Type", |
| 43 | http.StatusUnsupportedMediaType) |
| 44 | return |
| 45 | } |
| 46 | if !upload && request.Body != nil { |
| 47 | request.Body = http.MaxBytesReader(writer, request.Body, |
| 48 | maxFormText+uploadSlack) |
| 49 | } |
| 50 | next.ServeHTTP(writer, request) |
| 51 | }) |
| 52 | } |
| 53 | |