sonda/internal/federation/client.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

149 lines
5.1 KiB
Go

package federation
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
const (
pairPath = "/api/v1/peer/pair"
infoPath = "/api/v1/peer/info"
maxReplyBytes = 16 << 10
)
// Client talks to other Sonda servers. It is not the outbound client of the providers, which by design never sends a
// header that identifies anything: this one is for a friend, and it has the same bounds otherwise: no redirect is
// followed, no proxy of the environment is used, the answer has a size limit and every attempt has a time limit.
type Client struct{ http *http.Client }
// NewClient builds a Client.
func NewClient() *Client {
return &Client{http: &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
Proxy: nil,
DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
DisableKeepAlives: true,
},
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}}
}
type pairBody struct {
Code string `json:"code"`
Name string `json:"name"`
Address string `json:"address"`
PublicKey string `json:"public_key"`
}
type pairReplyBody struct {
Name string `json:"name"`
Address string `json:"address"`
PublicKey string `json:"public_key"`
}
// Pair asks the server at address to accept this server as a friend, with the code of an invite.
func (c *Client) Pair(ctx context.Context, address string, req PairRequest) (PairReply, error) {
payload, err := json.Marshal(pairBody{
Code: req.Code, Name: req.Name, Address: req.Address, PublicKey: base64.RawURLEncoding.EncodeToString(req.PublicKey),
})
if err != nil {
return PairReply{}, err
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(address, "/")+pairPath, bytes.NewReader(payload))
if err != nil {
return PairReply{}, fmt.Errorf("%w: %v", ErrUnreachable, err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("User-Agent", "Sonda (federation)")
resp, err := c.http.Do(httpReq)
if err != nil {
return PairReply{}, 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 PairReply{}, fmt.Errorf("%w: no usable answer", ErrUnreachable)
}
switch resp.StatusCode {
case http.StatusOK:
var r pairReplyBody
if json.Unmarshal(body, &r) != nil {
return PairReply{}, fmt.Errorf("%w: the answer is not that of a Sonda server", ErrUnreachable)
}
key, err := base64.RawURLEncoding.DecodeString(r.PublicKey)
if err != nil || r.Name == "" || len(key) != ed25519.PublicKeySize {
return PairReply{}, fmt.Errorf("%w: the answer is not that of a Sonda server", ErrUnreachable)
}
return PairReply{Name: r.Name, Address: r.Address, PublicKey: key}, nil
case http.StatusForbidden:
return PairReply{}, ErrRefused
case http.StatusConflict:
return PairReply{}, ErrAlreadyFriend
case http.StatusTooManyRequests:
return PairReply{}, ErrTooMany
default:
return PairReply{}, fmt.Errorf("%w: it answered %d", ErrUnreachable, resp.StatusCode)
}
}
type infoBody struct {
Name string `json:"name"`
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) {
raw := make([]byte, 18)
if _, err := rand.Read(raw); err != nil {
return Info{}, 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)
if err != nil {
return Info{}, fmt.Errorf("%w: %v", ErrUnreachable, err)
}
req.Header.Set("User-Agent", "Sonda (federation)")
req.Header.Set(HeaderKeyID, auth.KeyID)
req.Header.Set(HeaderDate, h.Date)
req.Header.Set(HeaderNonce, h.Nonce)
req.Header.Set(HeaderSignature, h.Signature)
resp, err := c.http.Do(req)
if err != nil {
return Info{}, 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)
}
switch resp.StatusCode {
case http.StatusOK:
var in infoBody
if json.Unmarshal(body, &in) != nil || in.Name == "" {
return Info{}, fmt.Errorf("%w: the answer is not that of a Sonda server", ErrUnreachable)
}
return Info{Name: in.Name, SharedLibraries: in.SharedLibraries}, nil
case http.StatusForbidden:
return Info{}, ErrNotApproved
case http.StatusUnauthorized, http.StatusNotFound:
return Info{}, ErrNotFriend
default:
return Info{}, fmt.Errorf("%w: it answered %d", ErrUnreachable, resp.StatusCode)
}
}