|
| 1 | +// Package uploads handles creator image uploads (product/cover photos) — most |
| 2 | +// importantly for mobile, where there's no easy way to paste an image URL. |
| 3 | +// Files are written to a configured directory and served back under /uploads. |
| 4 | +package uploads |
| 5 | + |
| 6 | +import ( |
| 7 | + "crypto/rand" |
| 8 | + "encoding/hex" |
| 9 | + "encoding/json" |
| 10 | + "io" |
| 11 | + "net/http" |
| 12 | + "os" |
| 13 | + "path/filepath" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + maxUploadBytes = 8 << 20 // 8 MiB — generous for a phone photo. |
| 18 | + sniffLen = 512 // bytes http.DetectContentType needs. |
| 19 | +) |
| 20 | + |
| 21 | +// extByType maps the sniffed content type to a safe, server-chosen extension. |
| 22 | +// Only these image types are accepted; anything else is rejected. The user |
| 23 | +// never controls the stored filename or extension. |
| 24 | +var extByType = map[string]string{ |
| 25 | + "image/jpeg": ".jpg", |
| 26 | + "image/png": ".png", |
| 27 | + "image/webp": ".webp", |
| 28 | + "image/gif": ".gif", |
| 29 | +} |
| 30 | + |
| 31 | +// Handler returns an http.HandlerFunc that accepts a multipart "file" field, |
| 32 | +// validates it is an allowed image, stores it under dir with a random name, |
| 33 | +// and responds {"url":"/uploads/<name>"}. Mount it behind auth. |
| 34 | +func Handler(dir string) http.HandlerFunc { |
| 35 | + return func(w http.ResponseWriter, r *http.Request) { |
| 36 | + // Cap the whole request body before reading anything. |
| 37 | + r.Body = http.MaxBytesReader(w, r.Body, maxUploadBytes+1024) |
| 38 | + if err := r.ParseMultipartForm(maxUploadBytes + 1024); err != nil { |
| 39 | + http.Error(w, "file too large or malformed (max 8MB)", http.StatusRequestEntityTooLarge) |
| 40 | + return |
| 41 | + } |
| 42 | + file, _, err := r.FormFile("file") |
| 43 | + if err != nil { |
| 44 | + http.Error(w, "missing file field", http.StatusBadRequest) |
| 45 | + return |
| 46 | + } |
| 47 | + defer file.Close() |
| 48 | + |
| 49 | + // Sniff the real content type from the bytes, not the client's claim. |
| 50 | + head := make([]byte, sniffLen) |
| 51 | + n, _ := io.ReadFull(file, head) |
| 52 | + head = head[:n] |
| 53 | + ext, ok := extByType[http.DetectContentType(head)] |
| 54 | + if !ok { |
| 55 | + http.Error(w, "only JPEG, PNG, WebP or GIF images are allowed", http.StatusUnsupportedMediaType) |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + name, err := randomName() |
| 60 | + if err != nil { |
| 61 | + http.Error(w, "could not generate name", http.StatusInternalServerError) |
| 62 | + return |
| 63 | + } |
| 64 | + name += ext |
| 65 | + |
| 66 | + if err := os.MkdirAll(dir, 0o755); err != nil { |
| 67 | + http.Error(w, "storage unavailable", http.StatusInternalServerError) |
| 68 | + return |
| 69 | + } |
| 70 | + dst, err := os.Create(filepath.Join(dir, name)) |
| 71 | + if err != nil { |
| 72 | + http.Error(w, "could not store file", http.StatusInternalServerError) |
| 73 | + return |
| 74 | + } |
| 75 | + defer dst.Close() |
| 76 | + |
| 77 | + // Write the sniffed head, then the rest, bounded again as defence in depth. |
| 78 | + if _, err := dst.Write(head); err != nil { |
| 79 | + http.Error(w, "write failed", http.StatusInternalServerError) |
| 80 | + return |
| 81 | + } |
| 82 | + if _, err := io.Copy(dst, io.LimitReader(file, maxUploadBytes)); err != nil { |
| 83 | + http.Error(w, "write failed", http.StatusInternalServerError) |
| 84 | + return |
| 85 | + } |
| 86 | + |
| 87 | + w.Header().Set("Content-Type", "application/json") |
| 88 | + _ = json.NewEncoder(w).Encode(map[string]string{"url": "/uploads/" + name}) |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +func randomName() (string, error) { |
| 93 | + b := make([]byte, 16) |
| 94 | + if _, err := rand.Read(b); err != nil { |
| 95 | + return "", err |
| 96 | + } |
| 97 | + return hex.EncodeToString(b), nil |
| 98 | +} |
| 99 | + |
| 100 | +// FileServer serves uploaded images from dir for public GETs, but never lists |
| 101 | +// directory contents (so the upload directory can't be enumerated) and sends |
| 102 | +// X-Content-Type-Options: nosniff so a file is never interpreted as anything |
| 103 | +// other than its declared type. |
| 104 | +func FileServer(dir string) http.Handler { |
| 105 | + fs := http.FileServer(noListFS{http.Dir(dir)}) |
| 106 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 107 | + w.Header().Set("X-Content-Type-Options", "nosniff") |
| 108 | + fs.ServeHTTP(w, r) |
| 109 | + }) |
| 110 | +} |
| 111 | + |
| 112 | +// noListFS wraps an http.FileSystem and reports directories as "not found", |
| 113 | +// which makes http.FileServer 404 instead of rendering a directory listing. |
| 114 | +type noListFS struct{ fs http.FileSystem } |
| 115 | + |
| 116 | +func (n noListFS) Open(name string) (http.File, error) { |
| 117 | + f, err := n.fs.Open(name) |
| 118 | + if err != nil { |
| 119 | + return nil, err |
| 120 | + } |
| 121 | + info, err := f.Stat() |
| 122 | + if err != nil { |
| 123 | + f.Close() |
| 124 | + return nil, err |
| 125 | + } |
| 126 | + if info.IsDir() { |
| 127 | + f.Close() |
| 128 | + return nil, os.ErrNotExist |
| 129 | + } |
| 130 | + return f, nil |
| 131 | +} |
0 commit comments