package httpapi import ( "bytes" "context" "encoding/json" "image" "image/color" "net/http" "net/http/httptest" "path/filepath" "strconv" "sync/atomic" "testing" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/images" "git.kmalloc.org/squid/sonda/internal/providers" "git.kmalloc.org/squid/sonda/internal/storage" ) type fakeArtistPictures struct { found images.Found err error calls int32 } func (f *fakeArtistPictures) ArtistImage(context.Context, int64) (images.Found, error) { atomic.AddInt32(&f.calls, 1) return f.found, f.err } type artistImageEnv struct { *similarEnv pics *fakeArtistPictures } func newArtistImageEnv(t *testing.T) *artistImageEnv { t.Helper() e := &artistImageEnv{pics: &fakeArtistPictures{found: images.Found{ Data: testJPEG(t, 1500, 1200, color.RGBA{30, 60, 200, 255}), Credit: images.Credit{Author: "Raph_PH", License: "CC BY 4.0", LicenseURL: "https://creativecommons.org/licenses/by/4.0", PageURL: "https://commons.wikimedia.org/wiki/File:Band.jpg"}, }}} e.similarEnv = newSimilarEnvWith(t, func(d *Deps, db *bun.DB, _ *providers.Service) { repo := storage.NewImageRepo(db) svc := images.NewService(filepath.Join(t.TempDir(), "data"), repo, repo) svc.SetArtistSource(e.pics) d.ArtistImages = svc }) return e } func (e *artistImageEnv) get(method, path, token string, header ...string) *httptest.ResponseRecorder { req := httptest.NewRequest(method, "/api/v1"+path, nil) if token != "" { req.Header.Set("Authorization", "Bearer "+token) } for i := 0; i+1 < len(header); i += 2 { req.Header.Set(header[i], header[i+1]) } rec := httptest.NewRecorder() e.h.ServeHTTP(rec, req) return rec } func (e *artistImageEnv) path(id int64, rest string) string { return "/artists/" + strconv.FormatInt(id, 10) + "/image" + rest } func TestArtistImageNeedsASignedInUserAndTakesTheTokenInTheQuery(t *testing.T) { e := newArtistImageEnv(t) if rec := e.get("GET", e.path(e.alpha, ""), ""); rec.Code != http.StatusUnauthorized { t.Errorf("no token: %d", rec.Code) } if rec := e.get("GET", e.path(e.alpha, "/credit"), ""); rec.Code != http.StatusUnauthorized { t.Errorf("credit without a token: %d", rec.Code) } if rec := e.get("GET", e.path(e.alpha, "?access_token="+e.admin), ""); rec.Code != http.StatusOK { t.Errorf("token in the query (an cannot send a header): %d", rec.Code) } // The credit is JSON for a program: a token in the query is not accepted there. if rec := e.get("GET", e.path(e.alpha, "/credit?access_token="+e.admin), ""); rec.Code != http.StatusUnauthorized { t.Errorf("credit with the token in the query: %d, want 401", rec.Code) } } func TestArtistImageIsAJPEGInTheSizeAskedAndCached(t *testing.T) { e := newArtistImageEnv(t) for query, width := range map[string]int{"": 1000, "?size=large": 1000, "?size=small": 300} { rec := e.get("GET", e.path(e.alpha, query), e.admin) if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "image/jpeg" { t.Fatalf("%q: %d %s", query, rec.Code, rec.Header().Get("Content-Type")) } cfg, format, err := image.DecodeConfig(bytes.NewReader(rec.Body.Bytes())) if err != nil || format != "jpeg" || cfg.Width != width { t.Errorf("%q: %v %s %v, want %d wide", query, cfg, format, err, width) } if rec.Header().Get("X-Content-Type-Options") != "nosniff" || rec.Header().Get("Cache-Control") != "private, max-age=3600" { t.Errorf("%q: headers %v", query, rec.Header()) } } if n := atomic.LoadInt32(&e.pics.calls); n != 1 { t.Errorf("the provider was asked %d times, want 1", n) } first := e.get("GET", e.path(e.alpha, ""), e.admin) etag := first.Header().Get("ETag") if etag == "" || etag[0] != '"' { t.Fatalf("etag = %q", etag) } if rec := e.get("GET", e.path(e.alpha, ""), e.admin, "If-None-Match", etag); rec.Code != http.StatusNotModified || rec.Body.Len() != 0 { t.Errorf("If-None-Match: %d", rec.Code) } if rec := e.get("HEAD", e.path(e.alpha, ""), e.admin); rec.Code != http.StatusOK || rec.Body.Len() != 0 { t.Errorf("HEAD: %d, %d bytes", rec.Code, rec.Body.Len()) } } func TestArtistImageCreditSaysWhoseItIsAndUnderWhichLicence(t *testing.T) { e := newArtistImageEnv(t) rec := e.get("GET", e.path(e.alpha, "/credit"), e.admin) if rec.Code != http.StatusOK { t.Fatalf("%d %s", rec.Code, rec.Body.String()) } var got map[string]any if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatal(err) } sameKeys(t, "credit", got, "source", "author", "license", "license_url", "page_url") if got["source"] != "Wikimedia Commons" || got["author"] != "Raph_PH" || got["license"] != "CC BY 4.0" || got["license_url"] != "https://creativecommons.org/licenses/by/4.0" || got["page_url"] != "https://commons.wikimedia.org/wiki/File:Band.jpg" { t.Errorf("credit = %v", got) } // The credit comes from the record, with no new request. if n := atomic.LoadInt32(&e.pics.calls); n != 1 { t.Errorf("the provider was asked %d times, want 1", n) } } func TestArtistImageErrors(t *testing.T) { for name, tt := range map[string]struct { err error code int want string }{ "no free picture": {images.ErrNoImage, 404, "image_not_found"}, "provider off": {images.ErrProviderDisabled, 404, "provider_disabled"}, "no id": {images.ErrNoID, 404, "no_musicbrainz_id"}, "unknown artist": {images.ErrArtistNotFound, 404, "artist_not_found"}, "provider down": {images.ErrSourceUnavailable, 502, "provider_unavailable"}, } { e := newArtistImageEnv(t) e.pics.err = tt.err for _, path := range []string{e.path(e.alpha, ""), e.path(e.alpha, "/credit")} { rec := e.get("GET", path, e.admin) var body struct { Error struct{ Code string } `json:"error"` } _ = json.Unmarshal(rec.Body.Bytes(), &body) if rec.Code != tt.code || body.Error.Code != tt.want { t.Errorf("%s %s: %d %s, want %d %s", name, path, rec.Code, rec.Body.String(), tt.code, tt.want) } } } } func TestArtistImageRefusesWhatItCannotUnderstand(t *testing.T) { e := newArtistImageEnv(t) for name, path := range map[string]string{ "a bad id": "/artists/abc/image", "id zero": "/artists/0/image", "a bad size": e.path(e.alpha, "?size=huge"), "size twice": e.path(e.alpha, "?size=small&size=large"), "credit bad id": "/artists/abc/image/credit", } { rec := e.get("GET", path, e.admin) var body struct { Error struct{ Code string } `json:"error"` } _ = json.Unmarshal(rec.Body.Bytes(), &body) if rec.Code != http.StatusBadRequest || body.Error.Code != "invalid_input" { t.Errorf("%s: %d %s", name, rec.Code, rec.Body.String()) } } if n := atomic.LoadInt32(&e.pics.calls); n != 0 { t.Errorf("the provider was asked %d times for requests that were refused", n) } }