package httpapi import ( "bytes" "context" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "time" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/federation" "git.kmalloc.org/squid/sonda/internal/storage" ) // browseFixture is a server C whose listener browses the shared libraries of a friend P, a real server of its own. type browseFixture struct { p *peerFixture ts *httptest.Server c *friendServer listener string friendID string // the id of P among C's friends pFriend string // the id of C among P's friends } func newBrowseFixture(t *testing.T) *browseFixture { t.Helper() p := newPeerFixture(t) p.share(t, p.shared, true) ts := httptest.NewServer(p.h) t.Cleanup(ts.Close) if r := p.admin1(t, "PUT", "/federation", map[string]any{"enabled": true, "name": "Anna", "address": ts.URL}); r.Code != 200 { t.Fatalf("turn P on: %d %v", r.Code, r.Body) } c := newFriendServer(t, false) c.setUp(t, "Bruno", "https://bruno.example.org") inv := p.admin1(t, "POST", "/federation/invites", nil) mine := c.call(t, "POST", "/federation/friends", map[string]any{"invite": inv.Body["invite"]}) if mine.Code != 201 { t.Fatalf("C pastes the invite: %d %v", mine.Code, mine.Body) } f := &browseFixture{p: p, ts: ts, c: c, friendID: strconv.Itoa(int(mine.Body["id"].(float64)))} list := p.admin1(t, "GET", "/federation", nil).Body["friends"].([]any) f.pFriend = strconv.Itoa(int(list[0].(map[string]any)["id"].(float64))) p.admin1(t, "POST", "/federation/friends/"+f.pFriend+"/approve", nil) if r := c.call(t, "POST", "/federation/friends/"+f.friendID+"/check", nil); r.Code != 200 { t.Fatalf("C checks: %d %v", r.Code, r.Body) } _, f.listener = addUser(t, c.h, c.admin, "lia", false) return f } func (f *browseFixture) get(t *testing.T, path string) resp { t.Helper() return do(t, f.c.h, "GET", "/api/v1"+path, f.listener, nil) } func TestAListenerSeesTheNamesOfTheFriendsAndNothingMore(t *testing.T) { f := newBrowseFixture(t) if r := do(t, f.c.h, "GET", "/api/v1/friends", "", nil); r.Code != 401 { t.Errorf("without a login: %d", r.Code) } r := f.get(t, "/friends") list := r.Body["friends"].([]any) if r.Code != 200 || len(list) != 1 { t.Fatalf("friends = %d %v", r.Code, r.Body) } sameKeys(t, "friend", list[0].(map[string]any), "id", "name") if list[0].(map[string]any)["name"] != "Anna" || list[0].(map[string]any)["id"] != mustFloat(t, f.friendID) { t.Errorf("friend = %v", list[0]) } // The address and the key are for the admin. if body := jsonOf(t, r.Body); strings.Contains(body, "127.0.0.1") || strings.Contains(body, "key") { t.Errorf("the list says more than a name: %s", body) } // Federation off: nobody to browse. f.c.call(t, "PUT", "/federation", map[string]any{"enabled": false}) if r := f.get(t, "/friends"); r.Code != 200 || len(r.Body["friends"].([]any)) != 0 { t.Errorf("while off: %d %v", r.Code, r.Body) } } func mustFloat(t *testing.T, s string) float64 { t.Helper() n, err := strconv.ParseFloat(s, 64) if err != nil { t.Fatal(err) } return n } func TestAWaitingFriendIsNotInTheList(t *testing.T) { f := newPeerFixture(t) f.admin1(t, "PUT", "/federation", map[string]any{"enabled": true, "address": "https://anna.example.org"}) _, lia := addUser(t, f.h, f.admin, "lia", false) inv := f.admin1(t, "POST", "/federation/invites", nil) do(t, f.h, "POST", "/api/v1/peer/pair", "", pairBody(inviteCode(t, str(inv.Body, "invite")), "Bruno", "https://bruno.example.org")) if r := do(t, f.h, "GET", "/api/v1/friends", lia, nil); r.Code != 200 || len(r.Body["friends"].([]any)) != 0 { t.Errorf("a friend nobody approved: %d %v", r.Code, r.Body) } } func TestAListenerBrowsesWhatAFriendSharesAndNothingElse(t *testing.T) { f := newBrowseFixture(t) base := "/friends/" + f.friendID for path, want := range map[string]string{"/tracks": "Shared Song", "/albums": "Shared Album", "/artists": "Shared Band"} { r := f.get(t, base+path) if r.Code != 200 { t.Fatalf("%s: %d %v", path, r.Code, r.Body) } sameKeys(t, "page", r.Body, "items", "total", "limit", "offset") if got := titlesIn(r); len(got) != 1 || got[0] != want || r.Body["total"] != float64(1) { t.Errorf("%s = %v (total %v)", path, got, r.Body["total"]) } } if got := titlesIn(f.get(t, base+"/tracks?q=private")); len(got) != 0 { t.Errorf("a search found %v in a library that is not shared", got) } if got := titlesIn(f.get(t, base+"/tracks?q=shared&limit=1&offset=0")); len(got) != 1 { t.Errorf("a search = %v", got) } // One item of each kind, found through the lists. track := f.get(t, base+"/tracks").Body["items"].([]any)[0].(map[string]any) album := f.get(t, base+"/albums").Body["items"].([]any)[0].(map[string]any) artist := f.get(t, base+"/artists").Body["items"].([]any)[0].(map[string]any) for path, title := range map[string]string{ "/tracks/" + idOf(track): "Shared Song", "/albums/" + idOf(album): "Shared Album", "/artists/" + idOf(artist): "Shared Band", } { r := f.get(t, base+path) if r.Code != 200 || (r.Body["title"] != title && r.Body["name"] != title) { t.Errorf("%s = %d %v", path, r.Code, r.Body) } } sameKeys(t, "track", f.get(t, base+"/tracks/"+idOf(track)).Body, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format", "replay_gain") if got := titlesIn(f.get(t, base+"/tracks?album_id="+idOf(album))); len(got) != 1 { t.Errorf("the tracks of an album = %v", got) } // What the friend does not share is not there, by id either. private := strconv.FormatInt(f.p.track["Private Song"], 10) if r := f.get(t, base+"/tracks/"+private); r.Code != 404 || errCode(r) != "track_not_found" { t.Errorf("a track that is not shared: %d %v", r.Code, r.Body) } for path, code := range map[string]string{"/artists/999999": "artist_not_found", "/albums/999999": "album_not_found"} { if r := f.get(t, base+path); r.Code != 404 || errCode(r) != code { t.Errorf("%s: %d %v", path, r.Code, r.Body) } } } func TestOnlyTheCatalogueOfAFriendCanBeAsked(t *testing.T) { f := newBrowseFixture(t) base := "/friends/" + f.friendID // The friend's other routes are not reachable through this server. for _, p := range []string{"/info", "/pair", "/tracks/1/stream", "/albums/1/cover", "/../federation"} { if r := f.get(t, base+p); r.Code != 404 { t.Errorf("%s: %d, want 404", p, r.Code) } } // What the routes do not take is dropped, so a listener cannot steer the request. if r := f.get(t, base+"/tracks?"+url.Values{"library_id": {strconv.FormatInt(f.p.private, 10)}, "evil": {"1"}}.Encode()); r.Code != 200 || r.Body["total"] != float64(1) { t.Errorf("an unknown parameter: %d %v", r.Code, r.Body) } if r := f.get(t, base+"/tracks?q="+strings.Repeat("a", 201)); r.Code != 400 || errCode(r) != "invalid_input" { t.Errorf("a search that is too long: %d %v", r.Code, r.Body) } if r := f.get(t, base+"/tracks?limit=abc"); r.Code != 400 { t.Errorf("a limit that is no number: %d %v", r.Code, r.Body) } } func TestAFriendThatIsNotThereIsNotFound(t *testing.T) { f := newBrowseFixture(t) for _, p := range []string{"/friends/99999/tracks", "/friends/99999/artists/1"} { if r := f.get(t, p); r.Code != 404 || errCode(r) != "friend_not_found" { t.Errorf("%s: %d %v", p, r.Code, r.Body) } } if r := f.get(t, "/friends/abc/tracks"); r.Code != 400 { t.Errorf("a friend that is no number: %d", r.Code) } if r := do(t, f.c.h, "GET", "/api/v1/friends/"+f.friendID+"/tracks", "", nil); r.Code != 401 { t.Errorf("without a login: %d", r.Code) } // Federation off: the friend is not there for a listener. f.c.call(t, "PUT", "/federation", map[string]any{"enabled": false}) if r := f.get(t, "/friends/"+f.friendID+"/tracks"); r.Code != 404 || errCode(r) != "friend_not_found" { t.Errorf("while off: %d %v", r.Code, r.Body) } } func TestWhenAFriendChangesItsMindTheListenerIsToldInWords(t *testing.T) { f := newBrowseFixture(t) base := "/friends/" + f.friendID // P stops sharing: the friend has nothing, and that is no error. f.p.share(t, f.p.shared, false) if r := f.get(t, base+"/tracks"); r.Code != 200 || r.Body["total"] != float64(0) { t.Errorf("after unsharing: %d %v", r.Code, r.Body) } // P removes this server from its friends. f.p.admin1(t, "DELETE", "/federation/friends/"+f.pFriend, nil) r := f.get(t, base+"/tracks") if r.Code != 409 || errCode(r) != "friend_gone" { t.Errorf("after being removed: %d %v", r.Code, r.Body) } // P goes away. f.ts.Close() r = f.get(t, base+"/tracks") if r.Code != 502 || errCode(r) != "friend_unreachable" { t.Errorf("a friend that is down: %d %v", r.Code, r.Body) } if body := jsonOf(t, r.Body); strings.Contains(body, "127.0.0.1") || strings.Contains(body, "dial") { t.Errorf("the answer names the friend's address: %s", body) } } // crafted is a Federation whose friend sends what it likes. type crafted struct { federationService body string } func (c crafted) Browse(context.Context, int64, string, int64, url.Values) ([]byte, error) { return []byte(c.body), nil } func (c crafted) Peaks(context.Context, int64, int64) ([]byte, error) { return []byte(c.body), nil } func TestWhatAFriendSendsIsCheckedBeforeItIsPassedOn(t *testing.T) { h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) { d.Federation = crafted{ federationService: federation.NewService(storage.NewFederationRepo(db), federation.NewClient()), body: `{"items":[{"id":1,"name":"","album_count":2,"track_count":3,"path":"/srv/music/secret","token":"x"}],"total":1,"limit":50,"offset":0,"debug":"yes"}`, } }) tok := registerAndLogin(t, h) r := do(t, h, "GET", "/api/v1/friends/1/artists", tok, nil) if r.Code != 200 { t.Fatalf("%d %v", r.Code, r.Body) } sameKeys(t, "page", r.Body, "items", "total", "limit", "offset") item := r.Body["items"].([]any)[0].(map[string]any) sameKeys(t, "artist", item, "id", "name", "album_count", "track_count") if strings.Contains(jsonOf(t, r.Body), "secret") { t.Errorf("a field the friend added was passed on: %v", r.Body) } } func TestAnAnswerThatIsNotACataloguePageIsNotPassedOn(t *testing.T) { for name, body := range map[string]string{"html": "hello", "a list": `[1,2]`, "empty": ``} { h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) { d.Federation = crafted{federationService: federation.NewService(storage.NewFederationRepo(db), federation.NewClient()), body: body} }) tok := registerAndLogin(t, h) r := do(t, h, "GET", "/api/v1/friends/1/tracks", tok, nil) if r.Code != http.StatusBadGateway || errCode(r) != "friend_unreachable" { t.Errorf("%s: %d %v", name, r.Code, r.Body) } } } // listen asks this server (C) for something as its listener would: with a header, or with the token in the // query, as an