package mapatest import ( "bytes" "context" "encoding/binary" "hash/crc32" "io" "net/http" "net/http/httptest" "net/url" "strings" "sync" "testing" "time" "amadan.net/rastrillo/rastrillo/blobs" "amadan.net/oficina/mapa/internal/mapa" ) // IMG6, refusals, headers and memory (images spec ยง6). // pngHeader is a PNG of width by height that is only its signature and // header: the decoder reads its size, which is all the limits need. func pngHeader(width, height uint32) []byte { data := make([]byte, 13) binary.BigEndian.PutUint32(data[0:], width) binary.BigEndian.PutUint32(data[4:], height) data[8], data[9] = 8, 2 chunk := append([]byte("IHDR"), data...) out := []byte("\x89PNG\r\n\x1a\n") out = binary.BigEndian.AppendUint32(out, 13) out = append(out, chunk...) return binary.BigEndian.AppendUint32(out, crc32.ChecksumIEEE(chunk)) } func TestIMG6TheUploadsMapaRefuses(t *testing.T) { rig := newRig(t) huge := append(pngOf(t, 1), make([]byte, 10<<20)...) cases := []struct { name, file string raw []byte status int }{ {"an SVG claiming PNG", "a.png", []byte(``), http.StatusUnsupportedMediaType}, {"HEIC", "a.heic", append([]byte("\x00\x00\x00\x18ftypheic"), make([]byte, 40)...), http.StatusUnsupportedMediaType}, {"HTML", "a.jpg", []byte("

hello"), http.StatusUnsupportedMediaType}, {"over 10 MB", "a.png", huge, http.StatusRequestEntityTooLarge}, {"over 10,000 px", "a.png", pngHeader(10001, 1), http.StatusUnprocessableEntity}, {"over 50 MP", "a.png", pngHeader(7100, 7100), http.StatusUnprocessableEntity}, } before := rig.count(t, "images") for _, each := range cases { reply := rig.sendFile(t, Ana, "/images", nil, each.file, each.raw) if reply.Code != each.status { t.Errorf("%s: %d, want %d: %s", each.name, reply.Code, each.status, reply.Body.String()) } } if rig.count(t, "images") != before { t.Error("a refused upload left a row") } } func TestIMG6TheAllowances(t *testing.T) { // Two images of one 64 KiB step each fit; a third does not. limit := func(config *mapa.Config, _ string) { config.Images.QuotaPerson = 2*(64<<10+28) + 10 } rig := newRigWith(t, limit) rig.upload(t, Ana, pngOf(t, 1)) rig.upload(t, Ana, pngOf(t, 2)) reply := rig.sendFile(t, Ana, "/images", nil, "a.png", pngOf(t, 3)) if reply.Code != http.StatusInsufficientStorage || !strings.Contains(reply.Body.String(), "Your image allowance of") { t.Errorf("over a person's allowance: %d %s", reply.Code, reply.Body.String()) } team := newRigWith(t, func(config *mapa.Config, _ string) { config.Images.QuotaTeam = 2*(64<<10+28) + 10 }) one, two := team.upload(t, Bo, pngOf(t, 1)), team.upload(t, Bo, pngOf(t, 2)) team.createPage(t, Bo, "Team", one.markdown("a")+"\n\n"+two.markdown("b")) reply = team.sendFile(t, Ana, "/images", nil, "a.png", pngOf(t, 3)) if reply.Code != http.StatusInsufficientStorage || !strings.Contains(reply.Body.String(), "Team pages hold") { t.Errorf("over the team's allowance: %d %s", reply.Code, reply.Body.String()) } } func TestIMG6NoStoreIs503(t *testing.T) { rig := newRigWith(t, func(config *mapa.Config, _ string) { config.Images.Objects = nil }) reply := rig.sendFile(t, Ana, "/images", nil, "a.png", pngOf(t, 1)) if reply.Code != http.StatusServiceUnavailable || !strings.Contains(reply.Body.String(), "aren't set up") { t.Errorf("%d %s", reply.Code, reply.Body.String()) } if got := rig.get(t, Ana, "/"); got.Code != http.StatusOK { t.Errorf("Mapa without images does not serve: %d", got.Code) } } func TestIMG6AServedImageCarriesItsHeaders(t *testing.T) { rig := newRig(t) shown := rig.upload(t, Ana, pngOf(t, 1)) reply := rig.get(t, Ana, shown.Src) want := map[string]string{ "Content-Type": "image/png", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; sandbox", "Content-Disposition": "inline", "Cross-Origin-Resource-Policy": "same-origin", "Etag": `"` + shown.ID + `"`, "Cache-Control": "private, max-age=3600, immutable", } for name, value := range want { if got := reply.Header().Get(name); got != value { t.Errorf("%s: %q, want %q", name, got, value) } } if !bytes.Equal(reply.Body.Bytes()[:8], []byte("\x89PNG\r\n\x1a\n")) { t.Error("the body is not the picture") } } // gatedStore holds every Put until released, so the blob slots fill. type gatedStore struct { blobs.Store gate chan struct{} held sync.WaitGroup } func (store *gatedStore) Put(ctx context.Context, data io.Reader, kind string) (blobs.Ref, error) { store.held.Done() <-store.gate return store.Store.Put(ctx, data, kind) } func TestIMG6AWaitForASlotAnswers503(t *testing.T) { gated := &gatedStore{gate: make(chan struct{})} rig := newRigWith(t, func(config *mapa.Config, dir string) { gated.Store = config.Images.Objects config.Images.Objects = gated }) rig.built.Store.SetImageWaits(50*time.Millisecond, 100*time.Millisecond) gated.held.Add(1) go close(gated.gate) // the first upload passes straight through shown := rig.upload(t, Ana, pngOf(t, 9)) gated.gate = make(chan struct{}) gated.held.Add(mapa.BlobSlots) var done sync.WaitGroup for seed := range mapa.BlobSlots { done.Add(1) go func() { defer done.Done() body, kind := multipartOf(t, nil, "a.png", pngOf(t, seed)) request := httptest.NewRequest(http.MethodPost, "/images", body) request.Header.Set("Content-Type", kind) request.Header.Set("Origin", testOrigin) rig.built.As(Ana).ServeHTTP(httptest.NewRecorder(), request) }() } gated.held.Wait() busy := map[string]*httptest.ResponseRecorder{ "upload": rig.sendFile(t, Ana, "/images", nil, "b.png", pngOf(t, 7)), "copy": rig.post(t, Ana, "/images/copy", url.Values{"id": {shown.ID}}), "serve": rig.get(t, Ana, shown.Src), } close(gated.gate) done.Wait() for name, reply := range busy { if reply.Code != http.StatusServiceUnavailable || reply.Header().Get("Retry-After") == "" { t.Errorf("%s with every slot taken: %d, Retry-After %q", name, reply.Code, reply.Header().Get("Retry-After")) } } } // Fable L2 on 49d8df3: POST /images/copy copies each id once, and when // one copy is refused, the copies it made before are removed with it. func TestACopyIsAllOrNothingAndOncePerID(t *testing.T) { rig := newRigWith(t, func(config *mapa.Config, _ string) { config.Images.QuotaPerson = 2*(64<<10+28) + 10 }) one, two := rig.upload(t, Ana, pngOf(t, 1)), rig.upload(t, Ana, pngOf(t, 2)) rig.createPage(t, Ana, "Shared", one.markdown("a")+"\n\n"+two.markdown("b")) twice := rig.post(t, Bo, "/images/copy", url.Values{"id": {one.ID, one.ID}}) if twice.Code != http.StatusOK || strings.Count(twice.Body.String(), `"src"`) != 1 || bosImages(t, rig) != 1 { t.Fatalf("one id twice: %d %s, %d rows", twice.Code, twice.Body.String(), bosImages(t, rig)) } // Bo holds one copy; two more would pass his allowance at the second. over := rig.post(t, Bo, "/images/copy", url.Values{"id": {two.ID, one.ID}}) if over.Code != http.StatusInsufficientStorage || bosImages(t, rig) != 1 { t.Fatalf("a refused copy: %d, %d rows of Bo's", over.Code, bosImages(t, rig)) } } func bosImages(t *testing.T, rig *rig) int64 { t.Helper() viewer, _ := rig.built.Store.Viewer(context.Background(), Bo, nil) var count int64 rig.db.G.Table("images").Where("owner_id = ?", viewer.MemberID). Count(&count) return count } // Fable N7 on 4c95863: reading an upload into memory is bounded too. At // most UploadReads requests are read at once; the next waits, then // answers 503 with Retry-After, holding no body in memory. func TestReadingUploadsIsBounded(t *testing.T) { rig := newRig(t) rig.built.Store.SetImageWaits(50*time.Millisecond, 50*time.Millisecond) server := httptest.NewServer(rig.built.As(Ana)) defer server.Close() var writers []*io.PipeWriter var done sync.WaitGroup for range mapa.UploadReads { reader, writer := io.Pipe() writers = append(writers, writer) body, kind := multipartOf(t, nil, "a.png", pngOf(t, 1)) go func() { _, _ = writer.Write(body.Bytes()[:body.Len()/2]) }() request, _ := http.NewRequest(http.MethodPost, server.URL+"/images", reader) request.Header.Set("Content-Type", kind) request.Header.Set("Origin", testOrigin) done.Add(1) go func() { defer done.Done() if response, err := http.DefaultClient.Do(request); err == nil { response.Body.Close() } }() } time.Sleep(200 * time.Millisecond) reply := rig.sendFile(t, Ana, "/images", nil, "b.png", pngOf(t, 2)) for _, writer := range writers { writer.Close() } done.Wait() if reply.Code != http.StatusServiceUnavailable || reply.Header().Get("Retry-After") == "" { t.Fatalf("a read past the bound: %d %q", reply.Code, reply.Header().Get("Retry-After")) } }