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 // 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 // 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 // stream is for what is too big to read whole: no limit on the whole answer, only on its beginning. stream *http.Client } // NewClient builds a Client. func NewClient() *Client { return &Client{stream: &http.Client{ Transport: &http.Transport{ Proxy: nil, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 15 * time.Second, }, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, }, 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"` } // 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 0, nil, fmt.Errorf("make a nonce: %w", err) } 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 0, nil, 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 0, nil, fmt.Errorf("%w: %v", ErrUnreachable, err) } defer resp.Body.Close() 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) } 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 == "" { 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, status) } } // Open sends a signed GET with these request headers and returns the answer with its body open: the caller reads it // (as far as the listener wants) and closes it, and it ends when ctx does. func (c *Client) Open(ctx context.Context, address, uri string, auth Auth, header http.Header) (*http.Response, error) { raw := make([]byte, 18) if _, err := rand.Read(raw); err != nil { return nil, fmt.Errorf("make a nonce: %w", err) } // What is signed is the path from /api/v1/peer on and the query, as in get. 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 nil, fmt.Errorf("%w: %v", ErrUnreachable, err) } for k, vs := range header { for _, v := range vs { req.Header.Add(k, v) } } 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.stream.Do(req) if err != nil { return nil, fmt.Errorf("%w: %v", ErrUnreachable, err) } return resp, nil }