| 1 | // Package attach decides what a person may attach to a message and makes |
| 2 | // it safe to keep: the type is sniffed from the bytes (never taken from |
| 3 | // the client), the size and count are bounded, the name is reduced to a |
| 4 | // plain base name, and an image's location is stripped. It also scales |
| 5 | // images down for previews and for a model's image input. Pure: no I/O. |
| 6 | // The instance and the runner share it. |
| 7 | package attach |
| 8 | |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "encoding/json" |
| 12 | "errors" |
| 13 | "path" |
| 14 | "strings" |
| 15 | "unicode" |
| 16 | "unicode/utf8" |
| 17 | ) |
| 18 | |
| 19 | // Limits. |
| 20 | const ( |
| 21 | // MaxBytes bounds one attachment. |
| 22 | MaxBytes = 10 << 20 |
| 23 | // MaxPerMessage bounds one message's attachments. |
| 24 | MaxPerMessage = 5 |
| 25 | // ChunkBytes is one relay frame's share of a file: base64 in JSON stays |
| 26 | // well under the stream's 256 KiB frame bound. |
| 27 | ChunkBytes = 128 << 10 |
| 28 | // MaxChunks is a 10 MB file's chunk count. |
| 29 | MaxChunks = (MaxBytes + ChunkBytes - 1) / ChunkBytes |
| 30 | // MaxName bounds a stored name, in bytes. |
| 31 | MaxName = 120 |
| 32 | // MaxSide and MaxPixels bound an image's size, read from its header |
| 33 | // before anything decodes it: a small file can claim a huge canvas. |
| 34 | MaxSide = 12000 |
| 35 | MaxPixels = 40_000_000 |
| 36 | ) |
| 37 | |
| 38 | // Kinds. |
| 39 | const ( |
| 40 | KindImage = "image" |
| 41 | KindFile = "file" |
| 42 | ) |
| 43 | |
| 44 | // Media types Equipo keeps. |
| 45 | const ( |
| 46 | PNG = "image/png" |
| 47 | JPEG = "image/jpeg" |
| 48 | WebP = "image/webp" |
| 49 | GIF = "image/gif" |
| 50 | PDF = "application/pdf" |
| 51 | Text = "text/plain" |
| 52 | Markdown = "text/markdown" |
| 53 | CSV = "text/csv" |
| 54 | JSON = "application/json" |
| 55 | ) |
| 56 | |
| 57 | // Refusals. Each has words in the instance's copy. |
| 58 | var ( |
| 59 | ErrEmpty = errors.New("attach: empty") |
| 60 | ErrTooLarge = errors.New("attach: too large") |
| 61 | ErrType = errors.New("attach: type not allowed") |
| 62 | ErrHEIC = errors.New("attach: heic") |
| 63 | ErrPixels = errors.New("attach: too many pixels") |
| 64 | ) |
| 65 | |
| 66 | // TooBig reports image dimensions over MaxSide or MaxPixels. |
| 67 | func TooBig(w, h int) bool { |
| 68 | return w > MaxSide || h > MaxSide || int64(w)*int64(h) > MaxPixels |
| 69 | } |
| 70 | |
| 71 | // Info is what Inspect found. |
| 72 | type Info struct { |
| 73 | Kind, MediaType, Name string |
| 74 | // Width and Height are an image's pixel size, 0 when unknown. |
| 75 | Width, Height int |
| 76 | } |
| 77 | |
| 78 | // IsImage reports a media type Equipo shows as an image. |
| 79 | func IsImage(mediaType string) bool { |
| 80 | switch mediaType { |
| 81 | case PNG, JPEG, WebP, GIF: |
| 82 | return true |
| 83 | } |
| 84 | return false |
| 85 | } |
| 86 | |
| 87 | // Allowed reports a media type Equipo keeps. |
| 88 | func Allowed(mediaType string) bool { |
| 89 | switch mediaType { |
| 90 | case PNG, JPEG, WebP, GIF, PDF, Text, Markdown, CSV, JSON: |
| 91 | return true |
| 92 | } |
| 93 | return false |
| 94 | } |
| 95 | |
| 96 | var imageExt = map[string]string{".png": PNG, ".jpg": JPEG, ".jpeg": JPEG, ".webp": WebP, ".gif": GIF} |
| 97 | |
| 98 | var heicExt = map[string]bool{".heic": true, ".heif": true, ".hif": true} |
| 99 | |
| 100 | // Inspect checks one upload and returns what it is and the bytes to keep |
| 101 | // (an image with its location stripped). declared is the client's |
| 102 | // Content-Type, a hint only: an image or PDF type that disagrees with the |
| 103 | // bytes is refused. |
| 104 | func Inspect(name, declared string, data []byte) (Info, []byte, error) { |
| 105 | if len(data) == 0 { |
| 106 | return Info{}, nil, ErrEmpty |
| 107 | } |
| 108 | if len(data) > MaxBytes { |
| 109 | return Info{}, nil, ErrTooLarge |
| 110 | } |
| 111 | name = SafeName(name) |
| 112 | ext := strings.ToLower(path.Ext(name)) |
| 113 | declared = strings.ToLower(strings.TrimSpace(strings.SplitN(declared, ";", 2)[0])) |
| 114 | sniffed := Sniff(data) |
| 115 | if sniffed == "image/heic" || (sniffed == "" && heicExt[ext]) || declared == "image/heic" || declared == "image/heif" { |
| 116 | return Info{}, nil, ErrHEIC |
| 117 | } |
| 118 | switch { |
| 119 | case IsImage(sniffed): |
| 120 | if want, ok := imageExt[ext]; (ext != "" && !ok) || (ok && !sameImage(want, sniffed)) { |
| 121 | return Info{}, nil, ErrType |
| 122 | } |
| 123 | if (strings.HasPrefix(declared, "image/") || declared == PDF) && !sameImage(declared, sniffed) { |
| 124 | return Info{}, nil, ErrType |
| 125 | } |
| 126 | clean, err := StripLocation(sniffed, data) |
| 127 | if err != nil { |
| 128 | return Info{}, nil, ErrType |
| 129 | } |
| 130 | w, h := Dimensions(sniffed, clean) |
| 131 | if w == 0 || h == 0 { |
| 132 | return Info{}, nil, ErrType |
| 133 | } |
| 134 | if TooBig(w, h) { |
| 135 | return Info{}, nil, ErrPixels |
| 136 | } |
| 137 | return Info{Kind: KindImage, MediaType: sniffed, Name: withExt(name, sniffed), Width: w, Height: h}, clean, nil |
| 138 | case sniffed == PDF: |
| 139 | if (ext != "" && ext != ".pdf") || (declared != "" && declared != PDF && declared != "application/octet-stream" && (strings.HasPrefix(declared, "image/") || strings.HasPrefix(declared, "text/"))) { |
| 140 | return Info{}, nil, ErrType |
| 141 | } |
| 142 | return Info{Kind: KindFile, MediaType: PDF, Name: withExt(name, PDF)}, data, nil |
| 143 | case sniffed == "": |
| 144 | if !isText(data) || imageExt[ext] != "" || ext == ".pdf" || strings.HasPrefix(declared, "image/") || declared == PDF { |
| 145 | return Info{}, nil, ErrType |
| 146 | } |
| 147 | media := Text |
| 148 | switch ext { |
| 149 | case ".md", ".markdown": |
| 150 | media = Markdown |
| 151 | case ".csv": |
| 152 | media = CSV |
| 153 | case ".json": |
| 154 | if json.Valid(data) { |
| 155 | media = JSON |
| 156 | } |
| 157 | } |
| 158 | if name == "" { |
| 159 | name = "file.txt" |
| 160 | } |
| 161 | return Info{Kind: KindFile, MediaType: media, Name: name}, data, nil |
| 162 | } |
| 163 | return Info{}, nil, ErrType |
| 164 | } |
| 165 | |
| 166 | func sameImage(a, b string) bool { |
| 167 | norm := func(s string) string { |
| 168 | if s == "image/jpg" || s == "image/pjpeg" { |
| 169 | return JPEG |
| 170 | } |
| 171 | return s |
| 172 | } |
| 173 | return norm(a) == norm(b) |
| 174 | } |
| 175 | |
| 176 | // withExt gives a nameless or extensionless image or PDF a fitting name. |
| 177 | func withExt(name, media string) string { |
| 178 | ext := map[string]string{PNG: ".png", JPEG: ".jpg", WebP: ".webp", GIF: ".gif", PDF: ".pdf"}[media] |
| 179 | if name == "" { |
| 180 | kind := "image" |
| 181 | if media == PDF { |
| 182 | kind = "document" |
| 183 | } |
| 184 | return kind + ext |
| 185 | } |
| 186 | if path.Ext(name) == "" { |
| 187 | return name + ext |
| 188 | } |
| 189 | return name |
| 190 | } |
| 191 | |
| 192 | // Sniff names an image, HEIC or PDF by its magic number; "" for anything |
| 193 | // else (text is checked separately). |
| 194 | func Sniff(b []byte) string { |
| 195 | switch { |
| 196 | case bytes.HasPrefix(b, []byte("\x89PNG\r\n\x1a\n")): |
| 197 | return PNG |
| 198 | case bytes.HasPrefix(b, []byte{0xff, 0xd8, 0xff}): |
| 199 | return JPEG |
| 200 | case bytes.HasPrefix(b, []byte("GIF87a")), bytes.HasPrefix(b, []byte("GIF89a")): |
| 201 | return GIF |
| 202 | case len(b) >= 12 && string(b[:4]) == "RIFF" && string(b[8:12]) == "WEBP": |
| 203 | return WebP |
| 204 | case bytes.HasPrefix(b, []byte("%PDF-")): |
| 205 | return PDF |
| 206 | case len(b) >= 12 && string(b[4:8]) == "ftyp": |
| 207 | switch string(b[8:12]) { |
| 208 | case "heic", "heix", "hevc", "hevx", "heim", "heis", "mif1", "msf1", "heif": |
| 209 | return "image/heic" |
| 210 | } |
| 211 | } |
| 212 | return "" |
| 213 | } |
| 214 | |
| 215 | // isText is valid UTF-8 with no NUL and no other control characters |
| 216 | // beyond tab, newline, carriage return and form feed. |
| 217 | func isText(b []byte) bool { |
| 218 | if !utf8.Valid(b) { |
| 219 | return false |
| 220 | } |
| 221 | for _, r := range string(b) { |
| 222 | if r == 0 || (r < 0x20 && r != '\t' && r != '\n' && r != '\r' && r != '\f') || r == 0x7f { |
| 223 | return false |
| 224 | } |
| 225 | } |
| 226 | return true |
| 227 | } |
| 228 | |
| 229 | // SafeName is the base name only, with no path, control or quote |
| 230 | // characters, at most MaxName bytes (the extension kept); "" when nothing |
| 231 | // is left. |
| 232 | func SafeName(name string) string { |
| 233 | name = strings.ReplaceAll(name, "\\", "/") |
| 234 | if i := strings.LastIndex(name, "/"); i >= 0 { |
| 235 | name = name[i+1:] |
| 236 | } |
| 237 | var b strings.Builder |
| 238 | for _, r := range name { |
| 239 | switch { |
| 240 | case r == utf8.RuneError, unicode.IsControl(r), r == '"', r == '\'', r == '`', r == '<', r == '>', r == ':', r == '*', r == '?', r == '|': |
| 241 | continue |
| 242 | case unicode.IsSpace(r): |
| 243 | b.WriteRune(' ') |
| 244 | default: |
| 245 | b.WriteRune(r) |
| 246 | } |
| 247 | } |
| 248 | name = strings.Trim(strings.Join(strings.Fields(b.String()), " "), ". ") |
| 249 | if len(name) > MaxName { |
| 250 | ext := path.Ext(name) |
| 251 | if len(ext) > 12 { |
| 252 | ext = "" |
| 253 | } |
| 254 | stem := name[:MaxName-len(ext)] |
| 255 | for !utf8.ValidString(stem) { |
| 256 | stem = stem[:len(stem)-1] |
| 257 | } |
| 258 | name = strings.TrimRight(stem, ". ") + ext |
| 259 | } |
| 260 | return name |
| 261 | } |
| 262 | |
| 263 | // Chunks is the number of relay frames for size bytes. |
| 264 | func Chunks(size int64) int { |
| 265 | return int((size + ChunkBytes - 1) / ChunkBytes) |
| 266 | } |
| 267 | |