sonda/internal/api/http/friends_test.go
tgiachi 7f38ae038e feat(federation): play a friend's music and show its covers through this server
A listener can now play the music of a friend from the web app.

- GET /friends/{friend}/tracks/{id}/stream and /friends/{friend}/albums/{id}/cover,
  in the group that accepts the access token in the query, like the local ones.
  This server asks the friend with a signed request and passes the bytes on,
  forwarding Range and the conditional headers, so a player can seek. The
  friend sees this server and never the listener.
- Only audio (for a stream) and a JPEG (for a cover) are passed on, with a
  fixed set of headers: Content-Type, Content-Length, Content-Range,
  Accept-Ranges, Last-Modified and ETag. Anything else a friend sends, or
  what a listener's request carries (cookies, authorization), is not passed
  either way, so a friend cannot make this server serve anything else.
- The client of friends can open a streaming answer: no limit on its whole
  length, one only on its beginning, no redirect followed, and it ends when
  the listener leaves.
- The player holds a friend's track next to the local ones. It streams
  through this server, shows the friend's cover, links to the music of the
  friend and not to a local page, is told apart from a local track with the
  same id, and is never reported as a listen: it does not feed taste.
- The songs of a friend have play buttons, the albums their covers.
- OpenAPI paths, contract test, and two real servers checked end to end: the
  bytes of the file arrive unchanged, with ranges, and a song plays in a
  browser from the friend's server through the other one.
2026-11-13 16:11:59 +01:00

440 lines
18 KiB
Go

package httpapi
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"time"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/federation"
"codeberg.org/squidd/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")
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 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":"<script>alert(1)</script>","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": "<html>hello</html>", "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 <audio> or <img> element has to.
func (f *browseFixture) listen(path string, mutate ...func(*http.Request)) *httptest.ResponseRecorder {
req := httptest.NewRequest("GET", "/api/v1"+path, nil)
req.Header.Set("Authorization", "Bearer "+f.listener)
for _, m := range mutate {
m(req)
}
rec := httptest.NewRecorder()
f.c.h.ServeHTTP(rec, req)
return rec
}
func (f *browseFixture) sharedTrack(t *testing.T) string {
t.Helper()
items := f.get(t, "/friends/"+f.friendID+"/tracks").Body["items"].([]any)
return idOf(items[0].(map[string]any))
}
func TestAListenerPlaysTheMusicOfAFriendThroughThisServer(t *testing.T) {
f := newBrowseFixture(t)
track := f.sharedTrack(t)
path := "/friends/" + f.friendID + "/tracks/" + track + "/stream"
want := f.p.bytes["Shared Song"]
rec := f.listen(path)
if rec.Code != 200 || !bytes.Equal(rec.Body.Bytes(), want) {
t.Fatalf("stream: %d, %d bytes of %d", rec.Code, rec.Body.Len(), len(want))
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "audio/") {
t.Errorf("Content-Type = %q", ct)
}
h := rec.Header()
if h.Get("Accept-Ranges") != "bytes" || h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Referrer-Policy") != "no-referrer" || h.Get("Cache-Control") != "private, no-cache" {
t.Errorf("headers = %v", h)
}
if h.Get("Set-Cookie") != "" || h.Get("Content-Disposition") != "" {
t.Errorf("headers a friend must not decide: %v", h)
}
// An <audio> element cannot send a header: the token goes in the address.
rec = f.listen(path+"?access_token="+f.listener, func(r *http.Request) { r.Header.Del("Authorization") })
if rec.Code != 200 || !bytes.Equal(rec.Body.Bytes(), want) {
t.Errorf("with the token in the address: %d", rec.Code)
}
if rec := f.listen(path, func(r *http.Request) { r.Header.Del("Authorization") }); rec.Code != 401 {
t.Errorf("without a login: %d", rec.Code)
}
// Seeking.
rec = f.listen(path, func(r *http.Request) { r.Header.Set("Range", "bytes=100-199") })
if rec.Code != 206 || !bytes.Equal(rec.Body.Bytes(), want[100:200]) || rec.Header().Get("Content-Range") != "bytes 100-199/400" {
t.Errorf("range: %d %q %d bytes", rec.Code, rec.Header().Get("Content-Range"), rec.Body.Len())
}
rec = f.listen(path, func(r *http.Request) { r.Header.Set("Range", "bytes=9999-") })
if rec.Code != 416 || rec.Body.Len() != 0 {
t.Errorf("a range past the end: %d with %d bytes", rec.Code, rec.Body.Len())
}
if rec := f.listen(path, func(r *http.Request) {
r.Header.Set("If-Modified-Since", time.Now().Add(time.Hour).UTC().Format(http.TimeFormat))
}); rec.Code != 304 {
t.Errorf("asking again: %d, want 304", rec.Code)
}
}
func TestTheFriendSeesThisServerAndNeverTheListener(t *testing.T) {
f := newBrowseFixture(t)
track := f.sharedTrack(t)
f.listen("/friends/" + f.friendID + "/tracks/" + track + "/stream")
log := f.p.admin1(t, "GET", "/federation/requests", nil)
var stream map[string]any
for _, r := range log.Body["requests"].([]any) {
if r.(map[string]any)["route"] == "/api/v1/peer/tracks/:id/stream" {
stream = r.(map[string]any)
}
}
if stream == nil || stream["friend"] != "Bruno" || stream["bytes"] != float64(400) {
t.Fatalf("the friend's log = %v", log.Body)
}
if body := jsonOf(t, log.Body); strings.Contains(body, "lia") || strings.Contains(body, f.listener) {
t.Errorf("the friend's log names the listener: %s", body)
}
}
func TestAStreamThatCannotBePlayedIsToldInWords(t *testing.T) {
f := newBrowseFixture(t)
track := f.sharedTrack(t)
base := "/friends/" + f.friendID
private := strconv.FormatInt(f.p.track["Private Song"], 10)
if r := f.get(t, base+"/tracks/"+private+"/stream"); r.Code != 404 || errCode(r) != "track_not_found" {
t.Errorf("a track that is not shared: %d %v", r.Code, r.Body)
}
if r := f.get(t, "/friends/99999/tracks/"+track+"/stream"); r.Code != 404 || errCode(r) != "friend_not_found" {
t.Errorf("a friend that is not there: %d %v", r.Code, r.Body)
}
if r := f.get(t, "/friends/abc/tracks/"+track+"/stream"); r.Code != 400 {
t.Errorf("a friend that is no number: %d", r.Code)
}
if r := f.get(t, base+"/tracks/0/stream"); r.Code != 400 {
t.Errorf("track 0: %d", r.Code)
}
// The friend allows no more streams for this server.
one := 1
if _, err := f.p.fed.Update(t.Context(), federation.Patch{MaxStreams: &one}); err != nil {
t.Fatal(err)
}
fid, _ := strconv.ParseInt(f.pFriend, 10, 64)
open, err := f.p.fed.StartStream(t.Context(), fid)
if err != nil {
t.Fatal(err)
}
rec := f.listen(base + "/tracks/" + track + "/stream")
if rec.Code != 429 || !strings.Contains(rec.Body.String(), `"friend_busy"`) || rec.Header().Get("Retry-After") == "" {
t.Errorf("a friend that is busy: %d %s", rec.Code, rec.Body.String())
}
open.Close()
// The friend removes this server, then goes away.
f.p.admin1(t, "DELETE", "/federation/friends/"+f.pFriend, nil)
if rec := f.listen(base + "/tracks/" + track + "/stream"); rec.Code != 409 || !strings.Contains(rec.Body.String(), `"friend_gone"`) {
t.Errorf("after being removed: %d %s", rec.Code, rec.Body.String())
}
f.ts.Close()
rec = f.listen(base + "/tracks/" + track + "/stream")
if rec.Code != 502 || !strings.Contains(rec.Body.String(), `"friend_unreachable"`) || strings.Contains(rec.Body.String(), "127.0.0.1") {
t.Errorf("a friend that is down: %d %s", rec.Code, rec.Body.String())
}
}
func TestACoverOfAFriendIsPassedOnOnceItIsBuilt(t *testing.T) {
f := newBrowseFixture(t)
album := idOf(f.get(t, "/friends/"+f.friendID+"/albums").Body["items"].([]any)[0].(map[string]any))
path := "/friends/" + f.friendID + "/albums/" + album + "/cover"
rec := f.listen(path)
if rec.Code != 404 || !strings.Contains(rec.Body.String(), `"cover_not_found"`) {
t.Fatalf("a cover that was not built: %d %s", rec.Code, rec.Body.String())
}
// Somebody on the friend's server opens it: it is built, and from then on it is passed on.
var pAlbum int64
_ = f.p.db.QueryRow("SELECT id FROM albums WHERE title = 'Shared Album'").Scan(&pAlbum)
local := f.p.serveAs(t, "GET", "/api/v1/albums/"+strconv.FormatInt(pAlbum, 10)+"/cover")
if local.Code != 200 {
t.Fatalf("the cover on the friend's server: %d %s", local.Code, local.Body.String())
}
rec = f.listen(path)
if rec.Code != 200 || rec.Header().Get("Content-Type") != "image/jpeg" || !bytes.Equal(rec.Body.Bytes(), local.Body.Bytes()) {
t.Fatalf("the cover: %d %q, %d bytes of %d", rec.Code, rec.Header().Get("Content-Type"), rec.Body.Len(), local.Body.Len())
}
if rec.Header().Get("Cache-Control") != "private, max-age=3600" || rec.Header().Get("ETag") == "" {
t.Errorf("headers = %v", rec.Header())
}
etag := rec.Header().Get("ETag")
if rec := f.listen(path, func(r *http.Request) { r.Header.Set("If-None-Match", etag) }); rec.Code != 304 {
t.Errorf("asking again: %d, want 304", rec.Code)
}
if rec := f.listen(path + "?size=small&access_token=" + f.listener); rec.Code != 200 {
t.Errorf("the small one: %d", rec.Code)
}
if rec := f.listen(path + "?size=huge"); rec.Code != 400 {
t.Errorf("a size that does not exist: %d", rec.Code)
}
private := idOf(map[string]any{"id": float64(f.p.track["Private Song"])}) // an id the friend does not share as an album
if rec := f.listen("/friends/" + f.friendID + "/albums/" + private + "/cover"); rec.Code != 404 {
t.Errorf("an album that is not shared: %d", rec.Code)
}
}