sonda/internal/federation/client_test.go
tgiachi 89826fcd07 feat(federation): shared libraries and the signed read API for friends
A friend's server can now read what an admin chose to share.

- A library has a shared flag, off by default (migration 0024), set with
  PATCH /libraries/{id}. Changing it never waits for a scan.
- Requests between friends are signed with each server's Ed25519 key: the
  method, the path and query from /api/v1/peer on, a date, a nonce and the
  hash of the empty body. A date more than two minutes off, a nonce used
  before, an unknown or removed key and a bad signature all get the same
  401. A friend still waiting for approval gets 403, and while federation is
  off the routes are missing.
- Routes under /api/v1/peer: info, artists, albums, tracks, covers and
  streaming with Range. The catalogue, the counts and the format come from
  the shared libraries only, and the file served is the one in a shared
  library. No path, library id, listen, taste, user or provider data is part
  of an answer.
- A friend never makes this server build a cover, read an audio file or ask
  a provider: only covers already built from the audio files are served.
- Per-friend limits, set by the admin: parallel streams (default 3) and KiB
  a second (default 4096, 0 for none), shared by all the streams of a friend.
- A log of the last requests friends made (route, status, bytes; never the
  query), kept for 7 days, in GET /federation/requests.
- POST /federation/friends/{id}/check lets the side that pasted an invite
  find out that the other admin approved; a signed call from a friend this
  server is waiting for makes it active too.
- Admin: a Shared with friends switch on each library, which asks first, and
  limits, recent requests and a Check button in the Federation section, in
  English and Italian.
- OpenAPI paths and schemas, contract test, two real servers checked end to
  end with tagged audio files.
2026-11-13 15:04:07 +01:00

221 lines
8.5 KiB
Go

package federation
import (
"bytes"
"context"
"crypto/ed25519"
"encoding/base64"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
func serverKey(t *testing.T) ed25519.PublicKey {
t.Helper()
pub, _, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatal(err)
}
return pub
}
func TestClientSendsThePairingRequestAndReadsTheReply(t *testing.T) {
mine, theirs := serverKey(t), serverKey(t)
var got struct {
Method, Path, Type, Agent, Auth string
Body map[string]string
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got.Method, got.Path, got.Type = r.Method, r.URL.Path, r.Header.Get("Content-Type")
got.Agent, got.Auth = r.Header.Get("User-Agent"), r.Header.Get("Authorization")
_ = json.NewDecoder(r.Body).Decode(&got.Body)
_ = json.NewEncoder(w).Encode(map[string]string{
"name": "Anna", "address": "https://anna.example.org", "public_key": base64.RawURLEncoding.EncodeToString(theirs),
})
}))
defer srv.Close()
reply, err := NewClient().Pair(context.Background(), srv.URL, PairRequest{
Code: "the-code", Name: "Bruno", Address: "https://bruno.example.org", PublicKey: mine,
})
if err != nil {
t.Fatal(err)
}
if got.Method != "POST" || got.Path != "/api/v1/peer/pair" || got.Type != "application/json" || got.Auth != "" || !strings.HasPrefix(got.Agent, "Sonda") {
t.Errorf("request = %+v", got)
}
if got.Body["code"] != "the-code" || got.Body["name"] != "Bruno" || got.Body["address"] != "https://bruno.example.org" ||
got.Body["public_key"] != base64.RawURLEncoding.EncodeToString(mine) {
t.Errorf("body = %v", got.Body)
}
if reply.Name != "Anna" || reply.Address != "https://anna.example.org" || !reply.PublicKey.Equal(theirs) {
t.Errorf("reply = %+v", reply)
}
}
func TestClientKeepsTheSubPathOfTheAddress(t *testing.T) {
var path string
srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { path = r.URL.Path }))
defer srv.Close()
_, _ = NewClient().Pair(context.Background(), srv.URL+"/sonda", PairRequest{Code: "c", PublicKey: serverKey(t)})
if path != "/sonda/api/v1/peer/pair" {
t.Errorf("path = %q", path)
}
}
func TestClientMapsWhatTheOtherServerSays(t *testing.T) {
for _, tc := range []struct {
status int
body string
want error
}{
{http.StatusForbidden, `{"error":{"code":"invalid_invite","message":"x"}}`, ErrRefused},
{http.StatusConflict, `{"error":{"code":"already_friends","message":"x"}}`, ErrAlreadyFriend},
{http.StatusTooManyRequests, `{"error":{"code":"too_many_requests","message":"x"}}`, ErrTooMany},
{http.StatusNotFound, `<html>not here</html>`, ErrUnreachable},
{http.StatusInternalServerError, `oops`, ErrUnreachable},
{http.StatusOK, `not json`, ErrUnreachable},
{http.StatusOK, `{"name":"A","address":"https://a.example.org","public_key":"!!"}`, ErrUnreachable},
{http.StatusOK, `{"name":"A","address":"https://a.example.org","public_key":"AAAA"}`, ErrUnreachable},
} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(tc.status)
_, _ = io.WriteString(w, tc.body)
}))
_, err := NewClient().Pair(context.Background(), srv.URL, PairRequest{Code: "c", PublicKey: serverKey(t)})
srv.Close()
if !errors.Is(err, tc.want) {
t.Errorf("%d %q: err = %v, want %v", tc.status, tc.body, err, tc.want)
}
}
}
func TestClientNeverFollowsARedirect(t *testing.T) {
elsewhere := 0
other := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { elsewhere++ }))
defer other.Close()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, other.URL, http.StatusTemporaryRedirect)
}))
defer srv.Close()
_, err := NewClient().Pair(context.Background(), srv.URL, PairRequest{Code: "c", PublicKey: serverKey(t)})
if !errors.Is(err, ErrUnreachable) || elsewhere != 0 {
t.Errorf("err = %v, redirected requests = %d: a redirect must end the attempt", err, elsewhere)
}
}
func TestClientBoundsTheAnswerAndTheWait(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(bytes.Repeat([]byte("x"), 1<<20))
}))
defer srv.Close()
if _, err := NewClient().Pair(context.Background(), srv.URL, PairRequest{Code: "c", PublicKey: serverKey(t)}); !errors.Is(err, ErrUnreachable) {
t.Errorf("a huge answer: err = %v, want ErrUnreachable", err)
}
// The handler waits for the test to end: it does not read the body, so it would not see the client leave.
release := make(chan struct{})
slow := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { <-release }))
defer slow.Close()
defer close(release)
c := NewClient()
c.http.Timeout = 50 * time.Millisecond
if _, err := c.Pair(context.Background(), slow.URL, PairRequest{Code: "c", PublicKey: serverKey(t)}); !errors.Is(err, ErrUnreachable) {
t.Errorf("a server that never answers: err = %v, want ErrUnreachable", err)
}
}
func TestClientDoesNotUseTheProxyOfTheEnvironment(t *testing.T) {
t.Setenv("HTTP_PROXY", "http://127.0.0.1:1")
t.Setenv("http_proxy", "http://127.0.0.1:1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusForbidden) }))
defer srv.Close()
if _, err := NewClient().Pair(context.Background(), srv.URL, PairRequest{Code: "c", PublicKey: serverKey(t)}); !errors.Is(err, ErrRefused) {
t.Errorf("err = %v, want ErrRefused: the request must go straight to the server", err)
}
}
func TestClientAsksWhoAFriendIsWithASignedRequest(t *testing.T) {
pub, priv, _ := ed25519.GenerateKey(nil)
var got Signed
var path, agent string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path, agent = r.URL.Path, r.Header.Get("User-Agent")
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/info",
}
_, _ = io.WriteString(w, `{"name":"Anna","shared_libraries":2}`)
}))
defer srv.Close()
info, err := NewClient().Info(context.Background(), srv.URL+"/sonda/", Auth{KeyID: KeyID(pub), Key: priv})
if err != nil {
t.Fatal(err)
}
if info.Name != "Anna" || info.SharedLibraries != 2 {
t.Errorf("info = %+v", info)
}
// The sub-path of the address is the proxy's: what is signed starts at /api/v1/peer.
if path != "/sonda/api/v1/peer/info" || !strings.HasPrefix(agent, "Sonda") {
t.Errorf("path = %q, agent = %q", path, agent)
}
if got.KeyID != KeyID(pub) || !validNonce(got.Nonce) || !verify(pub, got.Method, got.URI, got.Date, got.Nonce, got.Signature) {
t.Errorf("the request is not properly signed: %+v", got)
}
date, _ := strconv.ParseInt(got.Date, 10, 64)
if d := time.Since(time.Unix(date, 0)); d < -5*time.Second || d > 5*time.Second {
t.Errorf("date is %v from now", d)
}
}
func TestEveryAskIsSignedWithADifferentNonce(t *testing.T) {
_, priv, _ := ed25519.GenerateKey(nil)
seen := map[string]bool{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen[r.Header.Get(HeaderNonce)] = true
_, _ = io.WriteString(w, `{"name":"A","shared_libraries":0}`)
}))
defer srv.Close()
c := NewClient()
for i := 0; i < 5; i++ {
if _, err := c.Info(context.Background(), srv.URL, Auth{KeyID: "0123456789abcdef", Key: priv}); err != nil {
t.Fatal(err)
}
}
if len(seen) != 5 {
t.Errorf("%d different nonces in 5 asks", len(seen))
}
}
func TestClientMapsWhatAFriendAnswersToAsk(t *testing.T) {
_, priv, _ := ed25519.GenerateKey(nil)
for _, tc := range []struct {
status int
body string
want error
}{
{http.StatusForbidden, `{"error":{"code":"not_approved"}}`, ErrNotApproved},
{http.StatusUnauthorized, `{"error":{"code":"unauthorized"}}`, ErrNotFriend},
{http.StatusNotFound, `{"error":{"code":"not_found"}}`, ErrNotFriend},
{http.StatusInternalServerError, `oops`, ErrUnreachable},
{http.StatusOK, `not json`, ErrUnreachable},
{http.StatusOK, `{"shared_libraries":1}`, ErrUnreachable},
} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(tc.status)
_, _ = io.WriteString(w, tc.body)
}))
_, err := NewClient().Info(context.Background(), srv.URL, Auth{KeyID: "0123456789abcdef", Key: priv})
srv.Close()
if !errors.Is(err, tc.want) {
t.Errorf("%d %q: err = %v, want %v", tc.status, tc.body, err, tc.want)
}
}
}