feat(federation): browse and search a friend's catalogue
A listener can now browse the music that a friend's server shares.
- GET /friends lists the friends both admins agreed to, by id and name; an
address or a key is for the admin only. It is empty while federation is off.
- GET /friends/{friend}/artists, albums and tracks (q, limit, offset,
artist_id, album_id) and the one-item routes: this server asks the friend
with a request signed by its own key and passes the page on. The answer is
read into this API's own types first, so what a friend adds is dropped and
the shape is the one in the spec. Nothing is kept, and the ids are the
friend's own.
- Only the three kinds of thing can be asked, and only the parameters their
routes take: a listener cannot make this server ask a friend for anything
else. The friend's address and what the connection said never reach a
listener.
- A friend that cannot be reached, no longer takes this server for a friend,
is busy or is not there is told in words, never as an error page.
- The client of friends gets a generic signed GET with a size limit.
- The web app has a Friends entry in the menu, shown only when there is a
friend to browse, a list of friends and a page for each with artists,
albums and songs, a search and links from an artist to its albums and from
an album to its songs, in English and Italian.
- OpenAPI paths and schemas, contract test with a friend that is a whole
server, and two real servers checked end to end.
This commit is contained in:
parent
8702ff9786
commit
29bd46c3ba
13 changed files with 2090 additions and 25 deletions
|
|
@ -1175,6 +1175,7 @@ func (c *contract) federation(t *testing.T, token, libID, albumID string) {
|
|||
c.expect(c.call("DELETE", "/federation/friends/"+id, token, nil), 404, "end it twice", "friend_not_found")
|
||||
|
||||
c.peer(t, token, libID, albumID)
|
||||
c.friends(t, token)
|
||||
|
||||
// This server uses an invite of another one, which is a real server of its own.
|
||||
other := newFriendServer(t, true)
|
||||
|
|
@ -1283,3 +1284,52 @@ func (c *contract) peer(t *testing.T, token, libID, albumID string) {
|
|||
c.expect(c.call("DELETE", "/federation/friends/"+friendID, token, nil), 204, "remove the reader")
|
||||
c.expect(c.call("PATCH", "/libraries/"+libID, token, map[string]any{"shared": false}), 200, "stop sharing the library")
|
||||
}
|
||||
|
||||
// friends plays a listener of this server who browses what a friend shares. The friend is a whole server of its own.
|
||||
func (c *contract) friends(t *testing.T, token string) {
|
||||
t.Helper()
|
||||
p := newPeerFixture(t)
|
||||
p.share(t, p.shared, true)
|
||||
ts := httptest.NewServer(p.h)
|
||||
defer ts.Close()
|
||||
p.admin1(t, "PUT", "/federation", map[string]any{"enabled": true, "name": "Anna", "address": ts.URL})
|
||||
inv := p.admin1(t, "POST", "/federation/invites", nil)
|
||||
mine := c.expect(c.call("POST", "/federation/friends", token, map[string]any{"invite": inv.Body["invite"]}), 201, "use the invite of a friend to browse")
|
||||
fid := idOf(mine)
|
||||
theirs := p.admin1(t, "GET", "/federation", nil).Body["friends"].([]any)
|
||||
p.admin1(t, "POST", "/federation/friends/"+idOf(theirs[0].(map[string]any))+"/approve", nil)
|
||||
|
||||
c.expect(c.call("GET", "/friends", "", nil), 401, "the friends without a login", "unauthorized")
|
||||
if got := c.expect(c.call("GET", "/friends", token, nil), 200, "the friends before it is checked")["friends"].([]any); len(got) != 0 {
|
||||
t.Fatalf("a friend that is waiting is listed: %v", got)
|
||||
}
|
||||
c.expect(c.call("POST", "/federation/friends/"+fid+"/check", token, nil), 200, "check the friend")
|
||||
list := c.expect(c.call("GET", "/friends", token, nil), 200, "the friends")["friends"].([]any)
|
||||
if len(list) != 1 || list[0].(map[string]any)["name"] != "Anna" {
|
||||
t.Fatalf("friends = %v", list)
|
||||
}
|
||||
|
||||
base := "/friends/" + fid
|
||||
c.expect(c.call("GET", base+"/tracks", "", nil), 401, "a friend's tracks without a login", "unauthorized")
|
||||
artists := c.expect(c.call("GET", base+"/artists?limit=5", token, nil), 200, "a friend's artists")
|
||||
albums := c.expect(c.call("GET", base+"/albums?q=shared", token, nil), 200, "a friend's albums")
|
||||
tracks := c.expect(c.call("GET", base+"/tracks?limit=5&offset=0", token, nil), 200, "a friend's tracks")
|
||||
if artists["total"] != float64(1) || albums["total"] != float64(1) || tracks["total"] != float64(1) {
|
||||
t.Fatalf("what the friend shares: %v %v %v", artists["total"], albums["total"], tracks["total"])
|
||||
}
|
||||
albumID, trackID := idOf(albums["items"].([]any)[0].(map[string]any)), idOf(tracks["items"].([]any)[0].(map[string]any))
|
||||
c.expect(c.call("GET", base+"/artists/"+idOf(artists["items"].([]any)[0].(map[string]any)), token, nil), 200, "one artist of a friend")
|
||||
c.expect(c.call("GET", base+"/albums/"+albumID, token, nil), 200, "one album of a friend")
|
||||
c.expect(c.call("GET", base+"/tracks/"+trackID, token, nil), 200, "one track of a friend")
|
||||
c.expect(c.call("GET", base+"/tracks?album_id="+albumID, token, nil), 200, "the tracks of an album of a friend")
|
||||
c.expect(c.call("GET", base+"/artists/999999", token, nil), 404, "an artist the friend does not have", "artist_not_found")
|
||||
c.expect(c.call("GET", base+"/albums/999999", token, nil), 404, "an album the friend does not have", "album_not_found")
|
||||
c.expect(c.call("GET", base+"/tracks/999999", token, nil), 404, "a track the friend does not have", "track_not_found")
|
||||
c.expect(c.call("GET", "/friends/999999/tracks", token, nil), 404, "a friend that is not there", "friend_not_found")
|
||||
c.expect(c.call("GET", base+"/tracks?limit=abc", token, nil), 400, "a limit that is no number", "invalid_input")
|
||||
|
||||
// The friend removes this server: the listener is told, and nothing is kept.
|
||||
p.admin1(t, "DELETE", "/federation/friends/"+idOf(theirs[0].(map[string]any)), nil)
|
||||
c.expect(c.call("GET", base+"/tracks", token, nil), 409, "a friend that removed this server", "friend_gone")
|
||||
c.expect(c.call("DELETE", "/federation/friends/"+fid, token, nil), 204, "forget the friend")
|
||||
}
|
||||
|
|
|
|||
267
internal/api/http/friends_test.go
Normal file
267
internal/api/http/friends_test.go
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
|
|
@ -27,6 +28,9 @@ type federationService interface {
|
|||
StartStream(ctx context.Context, friendID int64) (*federation.Stream, error)
|
||||
Pace(ctx context.Context, friendID int64) (*federation.Stream, error)
|
||||
Record(ctx context.Context, r federation.FriendRequest)
|
||||
// What a listener may ask about friends.
|
||||
ActiveFriends(ctx context.Context) ([]federation.Friend, error)
|
||||
Browse(ctx context.Context, friendID int64, resource string, id int64, query url.Values) ([]byte, error)
|
||||
}
|
||||
|
||||
// federationHandlers are the admin routes that set up federation and its friends, and the one public route
|
||||
|
|
|
|||
127
internal/api/http/handlers_friends.go
Normal file
127
internal/api/http/handlers_friends.go
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"codeberg.org/squidd/sonda/internal/federation"
|
||||
)
|
||||
|
||||
// friendsHandlers let any signed-in listener browse the catalogue that a friend shares. This server asks the
|
||||
// friend, with a request signed by its own key, and passes the answer on after checking its shape; nothing is
|
||||
// kept. A listener learns a friend's name and nothing more: the address and the key are for the admin.
|
||||
type friendsHandlers struct{ svc federationService }
|
||||
|
||||
// friendNotFound maps a kind of thing to the code of the answer when the friend does not have it.
|
||||
var friendNotFound = map[string]string{"artists": "artist_not_found", "albums": "album_not_found", "tracks": "track_not_found"}
|
||||
|
||||
func (h *friendsHandlers) list(c *gin.Context) {
|
||||
friends, err := h.svc.ActiveFriends(c.Request.Context())
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
out := make([]gin.H, len(friends))
|
||||
for i, f := range friends {
|
||||
out[i] = gin.H{"id": f.ID, "name": f.Name}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"friends": out})
|
||||
}
|
||||
|
||||
// writeFriendError tells a listener, in fixed words, what went wrong with a friend. The address of the friend and
|
||||
// what the connection said never leave the server.
|
||||
func writeFriendError(c *gin.Context, err error, resource string) {
|
||||
switch {
|
||||
case errors.Is(err, federation.ErrFriendMissing):
|
||||
writeError(c, http.StatusNotFound, "friend_not_found", "no such friend")
|
||||
case errors.Is(err, federation.ErrInvalidInput):
|
||||
writeError(c, http.StatusBadRequest, "invalid_input", "the question was not valid")
|
||||
case errors.Is(err, federation.ErrNotFoundThere):
|
||||
writeError(c, http.StatusNotFound, friendNotFound[resource], "not found")
|
||||
case errors.Is(err, federation.ErrNotFriend), errors.Is(err, federation.ErrNotApproved):
|
||||
writeError(c, http.StatusConflict, "friend_gone", "this friend does not answer as a friend any more")
|
||||
case errors.Is(err, federation.ErrTooMany):
|
||||
c.Header("Retry-After", "5")
|
||||
writeError(c, http.StatusTooManyRequests, "friend_busy", "this friend is busy: try again in a moment")
|
||||
case errors.Is(err, federation.ErrUnreachable):
|
||||
_ = c.Error(err) // the cause stays in the log
|
||||
writeError(c, http.StatusBadGateway, "friend_unreachable", "this friend could not be reached")
|
||||
default:
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||
}
|
||||
}
|
||||
|
||||
// fetch asks the friend of the request for a list or an item, and returns what it said.
|
||||
func (h *friendsHandlers) fetch(c *gin.Context, resource string, withID bool) ([]byte, bool) {
|
||||
friend, err := strconv.ParseInt(c.Param("friend"), 10, 64)
|
||||
if err != nil || friend <= 0 {
|
||||
writeError(c, http.StatusBadRequest, "invalid_input", "friend must be a positive number")
|
||||
return nil, false
|
||||
}
|
||||
var id int64
|
||||
if withID {
|
||||
v, ok := pathID(c)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
id = v
|
||||
}
|
||||
body, err := h.svc.Browse(c.Request.Context(), friend, resource, id, c.Request.URL.Query())
|
||||
if err != nil {
|
||||
writeFriendError(c, err, resource)
|
||||
return nil, false
|
||||
}
|
||||
return body, true
|
||||
}
|
||||
|
||||
func badAnswer(c *gin.Context) {
|
||||
_ = c.Error(errors.New("a friend sent an answer that is not a catalogue page"))
|
||||
writeError(c, http.StatusBadGateway, "friend_unreachable", "this friend could not be reached")
|
||||
}
|
||||
|
||||
// relayPage passes a page of the friend's catalogue on. It is read into the types of this server's own API first,
|
||||
// so whatever else the friend added is dropped and the answer has the shape the spec promises.
|
||||
func relayPage[T any](h *friendsHandlers, resource string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
body, ok := h.fetch(c, resource, false)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var page struct {
|
||||
Items []T `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
if json.Unmarshal(body, &page) != nil || page.Total < 0 {
|
||||
badAnswer(c)
|
||||
return
|
||||
}
|
||||
if page.Items == nil {
|
||||
page.Items = []T{}
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
}
|
||||
|
||||
// relayOne passes one artist, album or track of the friend on, checked the same way.
|
||||
func relayOne[T any](h *friendsHandlers, resource string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
body, ok := h.fetch(c, resource, true)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var item T
|
||||
if json.Unmarshal(body, &item) != nil {
|
||||
badAnswer(c)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, item)
|
||||
}
|
||||
}
|
||||
|
|
@ -320,6 +320,14 @@ func NewRouter(d Deps) *gin.Engine {
|
|||
protected.GET("/smart-playlists/:id/tracks", sm.tracks)
|
||||
protected.GET("/smart-playlists/:id/covers", sm.covers)
|
||||
protected.POST("/smart-playlists/:id/playlist", sm.save)
|
||||
fr := &friendsHandlers{svc: d.Federation}
|
||||
protected.GET("/friends", fr.list)
|
||||
protected.GET("/friends/:friend/artists", relayPage[artistJSON](fr, "artists"))
|
||||
protected.GET("/friends/:friend/artists/:id", relayOne[artistJSON](fr, "artists"))
|
||||
protected.GET("/friends/:friend/albums", relayPage[albumJSON](fr, "albums"))
|
||||
protected.GET("/friends/:friend/albums/:id", relayOne[albumJSON](fr, "albums"))
|
||||
protected.GET("/friends/:friend/tracks", relayPage[trackJSON](fr, "tracks"))
|
||||
protected.GET("/friends/:friend/tracks/:id", relayOne[trackJSON](fr, "tracks"))
|
||||
protected.GET("/wishlist", fb.list(feedback.Wishlist))
|
||||
protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist))
|
||||
protected.DELETE("/wishlist/:id", fb.remove(feedback.Wishlist))
|
||||
|
|
|
|||
|
|
@ -47,6 +47,8 @@ tags:
|
|||
description: External services Sonda can ask about artists, set up by an admin.
|
||||
- name: Federation
|
||||
description: Friend Sonda servers, whose listeners can play the libraries an admin shares (admin).
|
||||
- name: Friends
|
||||
description: Browsing the music that a friend's server shares, for any signed-in listener.
|
||||
|
||||
paths:
|
||||
/health:
|
||||
|
|
@ -3502,6 +3504,207 @@ paths:
|
|||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/friends:
|
||||
get:
|
||||
tags: [Friends]
|
||||
operationId: listFriends
|
||||
summary: The friends whose music can be browsed
|
||||
description: |
|
||||
The friends that both admins agreed to, by name. A listener never sees an address or a key: those are for the
|
||||
admin (`GET /federation`). Empty while federation is off.
|
||||
security: [{bearerAuth: []}]
|
||||
responses:
|
||||
'200':
|
||||
description: The friends, oldest first.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [friends]
|
||||
properties:
|
||||
friends:
|
||||
type: array
|
||||
items: {$ref: '#/components/schemas/FriendRef'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
|
||||
/friends/{friend}/artists:
|
||||
parameters:
|
||||
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}}
|
||||
get:
|
||||
tags: [Friends]
|
||||
operationId: listFriendArtists
|
||||
summary: The artists a friend shares
|
||||
description: |
|
||||
This server asks the friend, with a request signed by its own key, and passes the page on after checking its
|
||||
shape; nothing is kept. Only what the friend shares is there. `q`, `limit` and `offset` are the same as in
|
||||
`GET /artists`. A friend that cannot be reached is `502` (`friend_unreachable`); one that no longer takes this
|
||||
server for a friend is `409` (`friend_gone`).
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/Q'}
|
||||
- {$ref: '#/components/parameters/Limit'}
|
||||
- {$ref: '#/components/parameters/Offset'}
|
||||
responses:
|
||||
'200':
|
||||
description: A page of artists.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/ArtistPage'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'409': {$ref: '#/components/responses/FriendGone'}
|
||||
'429': {$ref: '#/components/responses/FriendBusy'}
|
||||
'502': {$ref: '#/components/responses/FriendUnreachable'}
|
||||
'404':
|
||||
description: No such friend, or it is not active (`friend_not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/friends/{friend}/artists/{id}:
|
||||
parameters:
|
||||
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}}
|
||||
- {$ref: '#/components/parameters/Id'}
|
||||
get:
|
||||
tags: [Friends]
|
||||
operationId: getFriendArtist
|
||||
summary: One artist of a friend
|
||||
security: [{bearerAuth: []}]
|
||||
responses:
|
||||
'200':
|
||||
description: The artist.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Artist'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'409': {$ref: '#/components/responses/FriendGone'}
|
||||
'429': {$ref: '#/components/responses/FriendBusy'}
|
||||
'502': {$ref: '#/components/responses/FriendUnreachable'}
|
||||
'404':
|
||||
description: No such friend, or it is not active (`friend_not_found`) or the friend has no such artist (`artist_not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/friends/{friend}/albums:
|
||||
parameters:
|
||||
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}}
|
||||
get:
|
||||
tags: [Friends]
|
||||
operationId: listFriendAlbums
|
||||
summary: The albums a friend shares
|
||||
description: Like `GET /friends/{friend}/artists`, for albums; `artist_id` is the friend's own id of an artist.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/Q'}
|
||||
- {$ref: '#/components/parameters/Limit'}
|
||||
- {$ref: '#/components/parameters/Offset'}
|
||||
- {$ref: '#/components/parameters/ArtistId'}
|
||||
responses:
|
||||
'200':
|
||||
description: A page of albums.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/AlbumPage'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'409': {$ref: '#/components/responses/FriendGone'}
|
||||
'429': {$ref: '#/components/responses/FriendBusy'}
|
||||
'502': {$ref: '#/components/responses/FriendUnreachable'}
|
||||
'404':
|
||||
description: No such friend, or it is not active (`friend_not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/friends/{friend}/albums/{id}:
|
||||
parameters:
|
||||
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}}
|
||||
- {$ref: '#/components/parameters/Id'}
|
||||
get:
|
||||
tags: [Friends]
|
||||
operationId: getFriendAlbum
|
||||
summary: One album of a friend
|
||||
security: [{bearerAuth: []}]
|
||||
responses:
|
||||
'200':
|
||||
description: The album.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Album'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'409': {$ref: '#/components/responses/FriendGone'}
|
||||
'429': {$ref: '#/components/responses/FriendBusy'}
|
||||
'502': {$ref: '#/components/responses/FriendUnreachable'}
|
||||
'404':
|
||||
description: No such friend, or it is not active (`friend_not_found`) or the friend has no such album (`album_not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/friends/{friend}/tracks:
|
||||
parameters:
|
||||
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}}
|
||||
get:
|
||||
tags: [Friends]
|
||||
operationId: listFriendTracks
|
||||
summary: The tracks a friend shares
|
||||
description: |
|
||||
Like `GET /friends/{friend}/artists`, for tracks; `artist_id` and `album_id` are the friend's own ids. The ids in
|
||||
every answer are the friend's, never this server's: a listener keeps the friend and the id together.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/Q'}
|
||||
- {$ref: '#/components/parameters/Limit'}
|
||||
- {$ref: '#/components/parameters/Offset'}
|
||||
- {$ref: '#/components/parameters/ArtistId'}
|
||||
- {$ref: '#/components/parameters/AlbumId'}
|
||||
responses:
|
||||
'200':
|
||||
description: A page of tracks.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/TrackPage'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'409': {$ref: '#/components/responses/FriendGone'}
|
||||
'429': {$ref: '#/components/responses/FriendBusy'}
|
||||
'502': {$ref: '#/components/responses/FriendUnreachable'}
|
||||
'404':
|
||||
description: No such friend, or it is not active (`friend_not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/friends/{friend}/tracks/{id}:
|
||||
parameters:
|
||||
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}}
|
||||
- {$ref: '#/components/parameters/Id'}
|
||||
get:
|
||||
tags: [Friends]
|
||||
operationId: getFriendTrack
|
||||
summary: One track of a friend
|
||||
security: [{bearerAuth: []}]
|
||||
responses:
|
||||
'200':
|
||||
description: The track.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Track'}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'409': {$ref: '#/components/responses/FriendGone'}
|
||||
'429': {$ref: '#/components/responses/FriendBusy'}
|
||||
'502': {$ref: '#/components/responses/FriendUnreachable'}
|
||||
'404':
|
||||
description: No such friend, or it is not active (`friend_not_found`) or the friend has no such track (`track_not_found`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
|
|
@ -3606,6 +3809,25 @@ components:
|
|||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
FriendGone:
|
||||
description: The friend no longer takes this server for a friend (`friend_gone`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
FriendBusy:
|
||||
description: The friend is busy (`friend_busy`). Try again after `Retry-After` seconds.
|
||||
headers:
|
||||
Retry-After:
|
||||
description: Seconds to wait.
|
||||
schema: {type: integer}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
FriendUnreachable:
|
||||
description: The friend could not be reached, or sent something that is not a catalogue page (`friend_unreachable`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
FederationOff:
|
||||
description: Federation is off on this server, so the route is as good as missing (`not_found`).
|
||||
content:
|
||||
|
|
@ -4913,6 +5135,13 @@ components:
|
|||
route: {type: string, description: "The route pattern, like `/api/v1/peer/tracks/:id/stream`. Never the query."}
|
||||
status: {type: integer}
|
||||
bytes: {type: integer, format: int64, description: Bytes of the answer.}
|
||||
FriendRef:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [id, name]
|
||||
properties:
|
||||
id: {type: integer, format: int64, description: Names the friend in the routes under `/friends`.}
|
||||
name: {type: string}
|
||||
PeerInfo:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
|
|
|
|||
157
internal/federation/browse_test.go
Normal file
157
internal/federation/browse_test.go
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
package federation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// getRemote is a Remote whose signed GET answers as a script says.
|
||||
type getRemote struct {
|
||||
fakeRemote
|
||||
status int
|
||||
body string
|
||||
err error
|
||||
uri string
|
||||
auth Auth
|
||||
addr string
|
||||
calls int
|
||||
}
|
||||
|
||||
func (g *getRemote) Get(_ context.Context, addr, uri string, auth Auth) (int, []byte, error) {
|
||||
g.calls++
|
||||
g.addr, g.uri, g.auth = addr, uri, auth
|
||||
return g.status, []byte(g.body), g.err
|
||||
}
|
||||
|
||||
// browsing returns a server that has an active friend, and the remote it asks.
|
||||
func browsing(t *testing.T) (*Service, *memStore, *getRemote, int64) {
|
||||
t.Helper()
|
||||
s, st, _, _, _, id := pairedServers(t)
|
||||
remote := &getRemote{status: 200, body: `{"items":[],"total":0,"limit":50,"offset":0}`}
|
||||
s.remote = remote
|
||||
return s, st, remote, id
|
||||
}
|
||||
|
||||
func TestAListenerSeesTheFriendsThatAreActiveAndNothingElse(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, st, _, _ := browsing(t)
|
||||
pub, _, _ := ed25519.GenerateKey(nil)
|
||||
_, _ = st.AddFriend(ctx, Friend{Name: "Waiting", Address: "https://w.example.org", PublicKey: pub, State: Outgoing})
|
||||
pub2, _, _ := ed25519.GenerateKey(nil)
|
||||
_, _ = st.AddFriend(ctx, Friend{Name: "Asking", Address: "https://a.example.org", PublicKey: pub2, State: Incoming})
|
||||
|
||||
got, err := s.ActiveFriends(ctx)
|
||||
if err != nil || len(got) != 1 || got[0].Name != "Bruno" {
|
||||
t.Fatalf("ActiveFriends = %+v, %v", got, err)
|
||||
}
|
||||
off := false
|
||||
if _, err := s.Update(ctx, Patch{Enabled: &off}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := s.ActiveFriends(ctx); err != nil || len(got) != 0 {
|
||||
t.Errorf("while off: %+v, %v, want none", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrowsingAsksTheFriendWithASignedRequestForTheRightRoute(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, st, remote, id := browsing(t)
|
||||
q := url.Values{"q": {"blue train"}, "limit": {"5"}, "offset": {"10"}, "artist_id": {"3"}, "album_id": {"4"}}
|
||||
|
||||
body, err := s.Browse(ctx, id, "tracks", 0, q)
|
||||
if err != nil || string(body) != remote.body {
|
||||
t.Fatalf("Browse = %q, %v", body, err)
|
||||
}
|
||||
if remote.uri != "/api/v1/peer/tracks?album_id=4&artist_id=3&limit=5&offset=10&q=blue+train" {
|
||||
t.Errorf("uri = %q", remote.uri)
|
||||
}
|
||||
if remote.addr != "https://bruno.example.org" || remote.auth.KeyID != KeyID(st.settings.PublicKey) || len(remote.auth.Key) != ed25519.PrivateKeySize {
|
||||
t.Errorf("asked %q with %+v", remote.addr, remote.auth.KeyID)
|
||||
}
|
||||
|
||||
if _, err := s.Browse(ctx, id, "albums", 7, nil); err != nil || remote.uri != "/api/v1/peer/albums/7" {
|
||||
t.Errorf("one album: %v, uri %q", err, remote.uri)
|
||||
}
|
||||
// Only what the friend's routes take is passed on, however it is asked.
|
||||
if _, err := s.Browse(ctx, id, "artists", 0, url.Values{"q": {"x"}, "evil": {"1"}, "library_id": {"1"}, "access_token": {"secret"}}); err != nil || remote.uri != "/api/v1/peer/artists?q=x" {
|
||||
t.Errorf("filtered: %v, uri %q", err, remote.uri)
|
||||
}
|
||||
// An item has no list parameters at all.
|
||||
if _, err := s.Browse(ctx, id, "artists", 9, url.Values{"q": {"x"}, "limit": {"3"}}); err != nil || remote.uri != "/api/v1/peer/artists/9" {
|
||||
t.Errorf("an item with parameters: %v, uri %q", err, remote.uri)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrowsingOnlyAsksForTheThreeKindsOfThing(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, _, remote, id := browsing(t)
|
||||
for _, resource := range []string{"", "info", "tracks/1/stream", "../pair", "artists?x=1", "Tracks"} {
|
||||
if _, err := s.Browse(ctx, id, resource, 0, nil); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("%q: err = %v, want ErrInvalidInput", resource, err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Browse(ctx, id, "tracks", -1, nil); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("a negative id: %v", err)
|
||||
}
|
||||
if remote.calls != 0 {
|
||||
t.Errorf("the friend was asked %d times for things that cannot be asked", remote.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyAnActiveFriendCanBeBrowsed(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, st, remote, id := browsing(t)
|
||||
pub, _, _ := ed25519.GenerateKey(nil)
|
||||
waiting, _ := st.AddFriend(ctx, Friend{Name: "Waiting", Address: "https://w.example.org", PublicKey: pub, State: Outgoing})
|
||||
pub2, _, _ := ed25519.GenerateKey(nil)
|
||||
asking, _ := st.AddFriend(ctx, Friend{Name: "Asking", Address: "https://a.example.org", PublicKey: pub2, State: Incoming})
|
||||
|
||||
for name, fid := range map[string]int64{"waiting": waiting.ID, "asking": asking.ID, "unknown": 999} {
|
||||
if _, err := s.Browse(ctx, fid, "tracks", 0, nil); !errors.Is(err, ErrFriendMissing) {
|
||||
t.Errorf("%s: err = %v, want ErrFriendMissing", name, err)
|
||||
}
|
||||
}
|
||||
off := false
|
||||
_, _ = s.Update(ctx, Patch{Enabled: &off})
|
||||
if _, err := s.Browse(ctx, id, "tracks", 0, nil); !errors.Is(err, ErrFriendMissing) {
|
||||
t.Errorf("while off: %v, want ErrFriendMissing", err)
|
||||
}
|
||||
if remote.calls != 0 {
|
||||
t.Errorf("the friend was asked %d times", remote.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhatAFriendAnswersIsToldInOurOwnTerms(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, _, remote, id := browsing(t)
|
||||
for _, tc := range []struct {
|
||||
status int
|
||||
body string
|
||||
err error
|
||||
want error
|
||||
}{
|
||||
{400, `{"error":{"code":"invalid_input"}}`, nil, ErrInvalidInput},
|
||||
{401, `{"error":{"code":"unauthorized"}}`, nil, ErrNotFriend},
|
||||
{403, `{"error":{"code":"not_approved"}}`, nil, ErrNotApproved},
|
||||
{404, `{"error":{"code":"not_found"}}`, nil, ErrNotFriend},
|
||||
{404, `<html>nginx</html>`, nil, ErrNotFriend},
|
||||
{404, `{"error":{"code":"track_not_found"}}`, nil, ErrNotFoundThere},
|
||||
{404, `{"error":{"code":"album_not_found"}}`, nil, ErrNotFoundThere},
|
||||
{429, `{"error":{"code":"too_many_requests"}}`, nil, ErrTooMany},
|
||||
{500, `oops`, nil, ErrUnreachable},
|
||||
{200, ``, ErrUnreachable, ErrUnreachable},
|
||||
} {
|
||||
remote.status, remote.body, remote.err = tc.status, tc.body, tc.err
|
||||
_, err := s.Browse(ctx, id, "tracks", 1, nil)
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Errorf("%d %q: err = %v, want %v", tc.status, tc.body, err, tc.want)
|
||||
}
|
||||
if err != nil && strings.Contains(err.Error(), "bruno.example.org") && !errors.Is(err, ErrUnreachable) {
|
||||
t.Errorf("the error names the friend's address: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,8 @@ const (
|
|||
pairPath = "/api/v1/peer/pair"
|
||||
infoPath = "/api/v1/peer/info"
|
||||
maxReplyBytes = 16 << 10
|
||||
// A page of 200 tracks with their credits is far below this.
|
||||
maxBrowseBytes = 2 << 20
|
||||
)
|
||||
|
||||
// Client talks to other Sonda servers. It is not the outbound client of the providers, which by design never sends a
|
||||
|
|
@ -105,17 +107,18 @@ type infoBody struct {
|
|||
SharedLibraries int `json:"shared_libraries"`
|
||||
}
|
||||
|
||||
// Info asks the server at address who it is, with a request signed by auth.Key. The path that is signed starts at
|
||||
// /api/v1/peer, so a server that sits behind a proxy under a sub-path checks the same text.
|
||||
func (c *Client) Info(ctx context.Context, address string, auth Auth) (Info, error) {
|
||||
// get sends a signed GET of uri (the path from /api/v1/peer on, and the query) and returns the status and the body,
|
||||
// whatever the status, up to limit bytes. The path that is signed starts at /api/v1/peer, so a server that sits
|
||||
// behind a proxy under a sub-path checks the same text.
|
||||
func (c *Client) get(ctx context.Context, address, uri string, auth Auth, limit int64) (int, []byte, error) {
|
||||
raw := make([]byte, 18)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return Info{}, fmt.Errorf("make a nonce: %w", err)
|
||||
return 0, nil, fmt.Errorf("make a nonce: %w", err)
|
||||
}
|
||||
h := Sign(auth.Key, http.MethodGet, infoPath, time.Now(), base64.RawURLEncoding.EncodeToString(raw))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(address, "/")+infoPath, nil)
|
||||
h := Sign(auth.Key, http.MethodGet, uri, time.Now(), base64.RawURLEncoding.EncodeToString(raw))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(address, "/")+uri, nil)
|
||||
if err != nil {
|
||||
return Info{}, fmt.Errorf("%w: %v", ErrUnreachable, err)
|
||||
return 0, nil, fmt.Errorf("%w: %v", ErrUnreachable, err)
|
||||
}
|
||||
req.Header.Set("User-Agent", "Sonda (federation)")
|
||||
req.Header.Set(HeaderKeyID, auth.KeyID)
|
||||
|
|
@ -125,14 +128,28 @@ func (c *Client) Info(ctx context.Context, address string, auth Auth) (Info, err
|
|||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return Info{}, fmt.Errorf("%w: %v", ErrUnreachable, err)
|
||||
return 0, nil, fmt.Errorf("%w: %v", ErrUnreachable, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxReplyBytes+1))
|
||||
if err != nil || len(body) > maxReplyBytes {
|
||||
return Info{}, fmt.Errorf("%w: no usable answer", ErrUnreachable)
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||
if err != nil || int64(len(body)) > limit {
|
||||
return 0, nil, fmt.Errorf("%w: no usable answer", ErrUnreachable)
|
||||
}
|
||||
switch resp.StatusCode {
|
||||
return resp.StatusCode, body, nil
|
||||
}
|
||||
|
||||
// Get is a signed GET for the catalogue of a friend: lists are a few hundred kilobytes at most.
|
||||
func (c *Client) Get(ctx context.Context, address, uri string, auth Auth) (int, []byte, error) {
|
||||
return c.get(ctx, address, uri, auth, maxBrowseBytes)
|
||||
}
|
||||
|
||||
// Info asks the server at address who it is, with a request signed by auth.Key.
|
||||
func (c *Client) Info(ctx context.Context, address string, auth Auth) (Info, error) {
|
||||
status, body, err := c.get(ctx, address, infoPath, auth, maxReplyBytes)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
switch status {
|
||||
case http.StatusOK:
|
||||
var in infoBody
|
||||
if json.Unmarshal(body, &in) != nil || in.Name == "" {
|
||||
|
|
@ -144,6 +161,6 @@ func (c *Client) Info(ctx context.Context, address string, auth Auth) (Info, err
|
|||
case http.StatusUnauthorized, http.StatusNotFound:
|
||||
return Info{}, ErrNotFriend
|
||||
default:
|
||||
return Info{}, fmt.Errorf("%w: it answered %d", ErrUnreachable, resp.StatusCode)
|
||||
return Info{}, fmt.Errorf("%w: it answered %d", ErrUnreachable, status)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -219,3 +219,38 @@ func TestClientMapsWhatAFriendAnswersToAsk(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGetsAPageOfTheCatalogueSignedWithItsQuery(t *testing.T) {
|
||||
pub, priv, _ := ed25519.GenerateKey(nil)
|
||||
var got Signed
|
||||
var rawQuery string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
rawQuery = r.URL.RawQuery
|
||||
got = Signed{
|
||||
KeyID: r.Header.Get(HeaderKeyID), Date: r.Header.Get(HeaderDate), Nonce: r.Header.Get(HeaderNonce),
|
||||
Signature: r.Header.Get(HeaderSignature), Method: r.Method, URI: "/api/v1/peer/tracks?limit=5&q=blue+train",
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = io.WriteString(w, `{"error":{"code":"track_not_found"}}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
status, body, err := NewClient().Get(context.Background(), srv.URL, "/api/v1/peer/tracks?limit=5&q=blue+train", Auth{KeyID: KeyID(pub), Key: priv})
|
||||
if err != nil || status != 404 || !strings.Contains(string(body), "track_not_found") {
|
||||
t.Fatalf("Get = %d %q, %v: a status other than 200 is an answer, not an error", status, body, err)
|
||||
}
|
||||
if rawQuery != "limit=5&q=blue+train" || !verify(pub, got.Method, got.URI, got.Date, got.Nonce, got.Signature) {
|
||||
t.Errorf("query %q, signed %+v", rawQuery, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRefusesAnAnswerThatIsTooBigForACatalogue(t *testing.T) {
|
||||
_, priv, _ := ed25519.GenerateKey(nil)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write(bytes.Repeat([]byte("x"), 3<<20))
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, _, err := NewClient().Get(context.Background(), srv.URL, "/api/v1/peer/tracks", Auth{KeyID: "0123456789abcdef", Key: priv}); !errors.Is(err, ErrUnreachable) {
|
||||
t.Errorf("a 3 MiB answer: err = %v, want ErrUnreachable", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ var (
|
|||
// ErrNotFriend: the other server does not take this server for a friend (it removed it, or federation is off there).
|
||||
ErrNotFriend = errors.New("the other server does not take this server for a friend")
|
||||
ErrTooManyStreams = errors.New("this friend already has as many streams open as allowed")
|
||||
// ErrNotFoundThere: the friend has no such artist, album or track among what it shares.
|
||||
ErrNotFoundThere = errors.New("the friend has no such item")
|
||||
)
|
||||
|
||||
// Defaults of the limits a friend is held to, and what they may be set to.
|
||||
|
|
|
|||
|
|
@ -322,6 +322,10 @@ func (f *fakeRemote) Pair(context.Context, string, PairRequest) (PairReply, erro
|
|||
return PairReply{}, errors.New("not used")
|
||||
}
|
||||
|
||||
func (f *fakeRemote) Get(context.Context, string, string, Auth) (int, []byte, error) {
|
||||
return 0, nil, errors.New("not used")
|
||||
}
|
||||
|
||||
func (f *fakeRemote) Info(_ context.Context, addr string, auth Auth) (Info, error) {
|
||||
f.got, f.addr = auth, addr
|
||||
return f.info, f.err
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
|
|
@ -69,6 +70,9 @@ type Remote interface {
|
|||
// when the other admin has not approved yet, ErrNotFriend when that server does not take this one for a friend,
|
||||
// and ErrUnreachable when it did not answer as a Sonda server.
|
||||
Info(ctx context.Context, address string, auth Auth) (Info, error)
|
||||
// Get sends a signed GET of uri (the path from /api/v1/peer on, and the query) to the server at address and
|
||||
// returns its status and body, whatever the status. An error means no answer was had.
|
||||
Get(ctx context.Context, address, uri string, auth Auth) (status int, body []byte, err error)
|
||||
}
|
||||
|
||||
// Auth is what signs a request to a friend: this server's key.
|
||||
|
|
@ -620,3 +624,95 @@ func (s *Service) Record(ctx context.Context, r FriendRequest) {
|
|||
func (s *Service) Requests(ctx context.Context) ([]FriendRequest, error) {
|
||||
return s.store.Requests(ctx, requestsShown)
|
||||
}
|
||||
|
||||
// ActiveFriends lists the friends a listener may browse. While federation is off there are none.
|
||||
func (s *Service) ActiveFriends(ctx context.Context) ([]Friend, error) {
|
||||
set, err := s.load(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !set.Enabled || set.PublicKey == nil {
|
||||
return nil, nil
|
||||
}
|
||||
all, err := s.store.Friends(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list friends: %w", err)
|
||||
}
|
||||
var out []Friend
|
||||
for _, f := range all {
|
||||
if f.State == Active {
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// What a listener may ask a friend: the three lists and their items, with the few parameters those take.
|
||||
var (
|
||||
browseResources = map[string]bool{"artists": true, "albums": true, "tracks": true}
|
||||
browseParams = []string{"q", "limit", "offset", "artist_id", "album_id"}
|
||||
)
|
||||
|
||||
// Browse asks an active friend, with a signed request, for a list (id 0) or one item of what it shares, and
|
||||
// returns the answer as the friend gave it, to be checked by whoever uses it. Nothing is kept. Anything else than
|
||||
// the three kinds of thing, and any parameter a route does not take, is dropped before the friend is asked, so a
|
||||
// listener cannot make this server ask for anything but the catalogue. A friend that is not active, does not
|
||||
// exist or is not reachable while federation is off is ErrFriendMissing.
|
||||
func (s *Service) Browse(ctx context.Context, friendID int64, resource string, id int64, query url.Values) ([]byte, error) {
|
||||
if !browseResources[resource] || id < 0 {
|
||||
return nil, fmt.Errorf("%w: there is no such thing to browse", ErrInvalidInput)
|
||||
}
|
||||
set, err := s.load(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !set.Enabled || set.PublicKey == nil {
|
||||
return nil, ErrFriendMissing
|
||||
}
|
||||
f, err := s.store.Friend(ctx, friendID)
|
||||
if err != nil || f.State != Active {
|
||||
return nil, ErrFriendMissing
|
||||
}
|
||||
uri := "/api/v1/peer/" + resource
|
||||
if id > 0 {
|
||||
uri += "/" + strconv.FormatInt(id, 10)
|
||||
} else {
|
||||
keep := url.Values{}
|
||||
for _, k := range browseParams {
|
||||
if v := query.Get(k); v != "" {
|
||||
keep.Set(k, v)
|
||||
}
|
||||
}
|
||||
if len(keep) > 0 {
|
||||
uri += "?" + keep.Encode()
|
||||
}
|
||||
}
|
||||
status, body, err := s.remote.Get(ctx, f.Address, uri, Auth{KeyID: KeyID(set.PublicKey), Key: set.PrivateKey})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch status {
|
||||
case http.StatusOK:
|
||||
return body, nil
|
||||
case http.StatusBadRequest:
|
||||
return nil, fmt.Errorf("%w: the friend did not take the question", ErrInvalidInput)
|
||||
case http.StatusForbidden:
|
||||
return nil, ErrNotApproved
|
||||
case http.StatusUnauthorized:
|
||||
return nil, ErrNotFriend
|
||||
case http.StatusNotFound:
|
||||
var e struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(body, &e) == nil && strings.HasSuffix(e.Error.Code, "_not_found") {
|
||||
return nil, ErrNotFoundThere
|
||||
}
|
||||
return nil, ErrNotFriend // federation is off there, or it is not a Sonda server that knows us
|
||||
case http.StatusTooManyRequests:
|
||||
return nil, ErrTooMany
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: it answered %d", ErrUnreachable, status)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -171,6 +171,10 @@ func (d *direct) Info(context.Context, string, Auth) (Info, error) {
|
|||
return Info{}, errors.New("not used")
|
||||
}
|
||||
|
||||
func (d *direct) Get(context.Context, string, string, Auth) (int, []byte, error) {
|
||||
return 0, nil, errors.New("not used")
|
||||
}
|
||||
|
||||
type clock struct{ t time.Time }
|
||||
|
||||
func (c *clock) now() time.Time { return c.t }
|
||||
|
|
@ -395,6 +399,10 @@ func (s swapKey) Info(ctx context.Context, addr string, a Auth) (Info, error) {
|
|||
return s.real.Info(ctx, addr, a)
|
||||
}
|
||||
|
||||
func (s swapKey) Get(ctx context.Context, addr, uri string, a Auth) (int, []byte, error) {
|
||||
return s.real.Get(ctx, addr, uri, a)
|
||||
}
|
||||
|
||||
func (s swapKey) Pair(ctx context.Context, addr string, req PairRequest) (PairReply, error) {
|
||||
r, err := s.real.Pair(ctx, addr, req)
|
||||
if err != nil {
|
||||
|
|
|
|||
Loading…
Reference in a new issue