| 1 | package mapatest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/binary" |
| 7 | "hash/crc32" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/rastrillo/rastrillo/blobs" |
| 18 | |
| 19 | "amadan.net/oficina/mapa/internal/mapa" |
| 20 | ) |
| 21 | |
| 22 | // IMG6, refusals, headers and memory (images spec §6). |
| 23 | |
| 24 | // pngHeader is a PNG of width by height that is only its signature and |
| 25 | // header: the decoder reads its size, which is all the limits need. |
| 26 | func pngHeader(width, height uint32) []byte { |
| 27 | data := make([]byte, 13) |
| 28 | binary.BigEndian.PutUint32(data[0:], width) |
| 29 | binary.BigEndian.PutUint32(data[4:], height) |
| 30 | data[8], data[9] = 8, 2 |
| 31 | chunk := append([]byte("IHDR"), data...) |
| 32 | out := []byte("\x89PNG\r\n\x1a\n") |
| 33 | out = binary.BigEndian.AppendUint32(out, 13) |
| 34 | out = append(out, chunk...) |
| 35 | return binary.BigEndian.AppendUint32(out, crc32.ChecksumIEEE(chunk)) |
| 36 | } |
| 37 | |
| 38 | func TestIMG6TheUploadsMapaRefuses(t *testing.T) { |
| 39 | rig := newRig(t) |
| 40 | huge := append(pngOf(t, 1), make([]byte, 10<<20)...) |
| 41 | cases := []struct { |
| 42 | name, file string |
| 43 | raw []byte |
| 44 | status int |
| 45 | }{ |
| 46 | {"an SVG claiming PNG", "a.png", []byte(`<svg xmlns=` + |
| 47 | `"http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`), |
| 48 | http.StatusUnsupportedMediaType}, |
| 49 | {"HEIC", "a.heic", append([]byte("\x00\x00\x00\x18ftypheic"), |
| 50 | make([]byte, 40)...), http.StatusUnsupportedMediaType}, |
| 51 | {"HTML", "a.jpg", []byte("<!doctype html><p>hello"), |
| 52 | http.StatusUnsupportedMediaType}, |
| 53 | {"over 10 MB", "a.png", huge, http.StatusRequestEntityTooLarge}, |
| 54 | {"over 10,000 px", "a.png", pngHeader(10001, 1), |
| 55 | http.StatusUnprocessableEntity}, |
| 56 | {"over 50 MP", "a.png", pngHeader(7100, 7100), |
| 57 | http.StatusUnprocessableEntity}, |
| 58 | } |
| 59 | before := rig.count(t, "images") |
| 60 | for _, each := range cases { |
| 61 | reply := rig.sendFile(t, Ana, "/images", nil, each.file, each.raw) |
| 62 | if reply.Code != each.status { |
| 63 | t.Errorf("%s: %d, want %d: %s", each.name, reply.Code, |
| 64 | each.status, reply.Body.String()) |
| 65 | } |
| 66 | } |
| 67 | if rig.count(t, "images") != before { |
| 68 | t.Error("a refused upload left a row") |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | func TestIMG6TheAllowances(t *testing.T) { |
| 73 | // Two images of one 64 KiB step each fit; a third does not. |
| 74 | limit := func(config *mapa.Config, _ string) { |
| 75 | config.Images.QuotaPerson = 2*(64<<10+28) + 10 |
| 76 | } |
| 77 | rig := newRigWith(t, limit) |
| 78 | rig.upload(t, Ana, pngOf(t, 1)) |
| 79 | rig.upload(t, Ana, pngOf(t, 2)) |
| 80 | reply := rig.sendFile(t, Ana, "/images", nil, "a.png", pngOf(t, 3)) |
| 81 | if reply.Code != http.StatusInsufficientStorage || |
| 82 | !strings.Contains(reply.Body.String(), "Your image allowance of") { |
| 83 | t.Errorf("over a person's allowance: %d %s", reply.Code, |
| 84 | reply.Body.String()) |
| 85 | } |
| 86 | team := newRigWith(t, func(config *mapa.Config, _ string) { |
| 87 | config.Images.QuotaTeam = 2*(64<<10+28) + 10 |
| 88 | }) |
| 89 | one, two := team.upload(t, Bo, pngOf(t, 1)), team.upload(t, Bo, pngOf(t, 2)) |
| 90 | team.createPage(t, Bo, "Team", one.markdown("a")+"\n\n"+two.markdown("b")) |
| 91 | reply = team.sendFile(t, Ana, "/images", nil, "a.png", pngOf(t, 3)) |
| 92 | if reply.Code != http.StatusInsufficientStorage || |
| 93 | !strings.Contains(reply.Body.String(), "Team pages hold") { |
| 94 | t.Errorf("over the team's allowance: %d %s", reply.Code, |
| 95 | reply.Body.String()) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | func TestIMG6NoStoreIs503(t *testing.T) { |
| 100 | rig := newRigWith(t, func(config *mapa.Config, _ string) { |
| 101 | config.Images.Objects = nil |
| 102 | }) |
| 103 | reply := rig.sendFile(t, Ana, "/images", nil, "a.png", pngOf(t, 1)) |
| 104 | if reply.Code != http.StatusServiceUnavailable || |
| 105 | !strings.Contains(reply.Body.String(), "aren't set up") { |
| 106 | t.Errorf("%d %s", reply.Code, reply.Body.String()) |
| 107 | } |
| 108 | if got := rig.get(t, Ana, "/"); got.Code != http.StatusOK { |
| 109 | t.Errorf("Mapa without images does not serve: %d", got.Code) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | func TestIMG6AServedImageCarriesItsHeaders(t *testing.T) { |
| 114 | rig := newRig(t) |
| 115 | shown := rig.upload(t, Ana, pngOf(t, 1)) |
| 116 | reply := rig.get(t, Ana, shown.Src) |
| 117 | want := map[string]string{ |
| 118 | "Content-Type": "image/png", |
| 119 | "X-Content-Type-Options": "nosniff", |
| 120 | "Content-Security-Policy": "default-src 'none'; sandbox", |
| 121 | "Content-Disposition": "inline", |
| 122 | "Cross-Origin-Resource-Policy": "same-origin", |
| 123 | "Etag": `"` + shown.ID + `"`, |
| 124 | "Cache-Control": "private, max-age=3600, immutable", |
| 125 | } |
| 126 | for name, value := range want { |
| 127 | if got := reply.Header().Get(name); got != value { |
| 128 | t.Errorf("%s: %q, want %q", name, got, value) |
| 129 | } |
| 130 | } |
| 131 | if !bytes.Equal(reply.Body.Bytes()[:8], []byte("\x89PNG\r\n\x1a\n")) { |
| 132 | t.Error("the body is not the picture") |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // gatedStore holds every Put until released, so the blob slots fill. |
| 137 | type gatedStore struct { |
| 138 | blobs.Store |
| 139 | gate chan struct{} |
| 140 | held sync.WaitGroup |
| 141 | } |
| 142 | |
| 143 | func (store *gatedStore) Put(ctx context.Context, data io.Reader, |
| 144 | kind string) (blobs.Ref, error) { |
| 145 | store.held.Done() |
| 146 | <-store.gate |
| 147 | return store.Store.Put(ctx, data, kind) |
| 148 | } |
| 149 | |
| 150 | func TestIMG6AWaitForASlotAnswers503(t *testing.T) { |
| 151 | gated := &gatedStore{gate: make(chan struct{})} |
| 152 | rig := newRigWith(t, func(config *mapa.Config, dir string) { |
| 153 | gated.Store = config.Images.Objects |
| 154 | config.Images.Objects = gated |
| 155 | }) |
| 156 | rig.built.Store.SetImageWaits(50*time.Millisecond, |
| 157 | 100*time.Millisecond) |
| 158 | gated.held.Add(1) |
| 159 | go close(gated.gate) // the first upload passes straight through |
| 160 | shown := rig.upload(t, Ana, pngOf(t, 9)) |
| 161 | gated.gate = make(chan struct{}) |
| 162 | gated.held.Add(mapa.BlobSlots) |
| 163 | var done sync.WaitGroup |
| 164 | for seed := range mapa.BlobSlots { |
| 165 | done.Add(1) |
| 166 | go func() { |
| 167 | defer done.Done() |
| 168 | body, kind := multipartOf(t, nil, "a.png", pngOf(t, seed)) |
| 169 | request := httptest.NewRequest(http.MethodPost, "/images", body) |
| 170 | request.Header.Set("Content-Type", kind) |
| 171 | request.Header.Set("Origin", testOrigin) |
| 172 | rig.built.As(Ana).ServeHTTP(httptest.NewRecorder(), request) |
| 173 | }() |
| 174 | } |
| 175 | gated.held.Wait() |
| 176 | busy := map[string]*httptest.ResponseRecorder{ |
| 177 | "upload": rig.sendFile(t, Ana, "/images", nil, "b.png", pngOf(t, 7)), |
| 178 | "copy": rig.post(t, Ana, "/images/copy", |
| 179 | url.Values{"id": {shown.ID}}), |
| 180 | "serve": rig.get(t, Ana, shown.Src), |
| 181 | } |
| 182 | close(gated.gate) |
| 183 | done.Wait() |
| 184 | for name, reply := range busy { |
| 185 | if reply.Code != http.StatusServiceUnavailable || |
| 186 | reply.Header().Get("Retry-After") == "" { |
| 187 | t.Errorf("%s with every slot taken: %d, Retry-After %q", name, |
| 188 | reply.Code, reply.Header().Get("Retry-After")) |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | // Fable L2 on 49d8df3: POST /images/copy copies each id once, and when |
| 194 | // one copy is refused, the copies it made before are removed with it. |
| 195 | func TestACopyIsAllOrNothingAndOncePerID(t *testing.T) { |
| 196 | rig := newRigWith(t, func(config *mapa.Config, _ string) { |
| 197 | config.Images.QuotaPerson = 2*(64<<10+28) + 10 |
| 198 | }) |
| 199 | one, two := rig.upload(t, Ana, pngOf(t, 1)), rig.upload(t, Ana, pngOf(t, 2)) |
| 200 | rig.createPage(t, Ana, "Shared", one.markdown("a")+"\n\n"+two.markdown("b")) |
| 201 | twice := rig.post(t, Bo, "/images/copy", url.Values{"id": {one.ID, one.ID}}) |
| 202 | if twice.Code != http.StatusOK || strings.Count(twice.Body.String(), |
| 203 | `"src"`) != 1 || bosImages(t, rig) != 1 { |
| 204 | t.Fatalf("one id twice: %d %s, %d rows", twice.Code, |
| 205 | twice.Body.String(), bosImages(t, rig)) |
| 206 | } |
| 207 | // Bo holds one copy; two more would pass his allowance at the second. |
| 208 | over := rig.post(t, Bo, "/images/copy", url.Values{"id": {two.ID, one.ID}}) |
| 209 | if over.Code != http.StatusInsufficientStorage || bosImages(t, rig) != 1 { |
| 210 | t.Fatalf("a refused copy: %d, %d rows of Bo's", over.Code, |
| 211 | bosImages(t, rig)) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | func bosImages(t *testing.T, rig *rig) int64 { |
| 216 | t.Helper() |
| 217 | viewer, _ := rig.built.Store.Viewer(context.Background(), Bo, nil) |
| 218 | var count int64 |
| 219 | rig.db.G.Table("images").Where("owner_id = ?", viewer.MemberID). |
| 220 | Count(&count) |
| 221 | return count |
| 222 | } |
| 223 | |
| 224 | // Fable N7 on 4c95863: reading an upload into memory is bounded too. At |
| 225 | // most UploadReads requests are read at once; the next waits, then |
| 226 | // answers 503 with Retry-After, holding no body in memory. |
| 227 | func TestReadingUploadsIsBounded(t *testing.T) { |
| 228 | rig := newRig(t) |
| 229 | rig.built.Store.SetImageWaits(50*time.Millisecond, 50*time.Millisecond) |
| 230 | server := httptest.NewServer(rig.built.As(Ana)) |
| 231 | defer server.Close() |
| 232 | var writers []*io.PipeWriter |
| 233 | var done sync.WaitGroup |
| 234 | for range mapa.UploadReads { |
| 235 | reader, writer := io.Pipe() |
| 236 | writers = append(writers, writer) |
| 237 | body, kind := multipartOf(t, nil, "a.png", pngOf(t, 1)) |
| 238 | go func() { _, _ = writer.Write(body.Bytes()[:body.Len()/2]) }() |
| 239 | request, _ := http.NewRequest(http.MethodPost, server.URL+"/images", |
| 240 | reader) |
| 241 | request.Header.Set("Content-Type", kind) |
| 242 | request.Header.Set("Origin", testOrigin) |
| 243 | done.Add(1) |
| 244 | go func() { |
| 245 | defer done.Done() |
| 246 | if response, err := http.DefaultClient.Do(request); err == nil { |
| 247 | response.Body.Close() |
| 248 | } |
| 249 | }() |
| 250 | } |
| 251 | time.Sleep(200 * time.Millisecond) |
| 252 | reply := rig.sendFile(t, Ana, "/images", nil, "b.png", pngOf(t, 2)) |
| 253 | for _, writer := range writers { |
| 254 | writer.Close() |
| 255 | } |
| 256 | done.Wait() |
| 257 | if reply.Code != http.StatusServiceUnavailable || |
| 258 | reply.Header().Get("Retry-After") == "" { |
| 259 | t.Fatalf("a read past the bound: %d %q", reply.Code, |
| 260 | reply.Header().Get("Retry-After")) |
| 261 | } |
| 262 | } |
| 263 | |