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, `not here`, 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) } } } 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) } } func TestClientOpensAStreamSignedAndReadsAsMuchAsItIsGiven(t *testing.T) { pub, priv, _ := ed25519.GenerateKey(nil) big := bytes.Repeat([]byte("a"), 5<<20) // far more than a page of the catalogue may be var got Signed var rangeHeader, cookie string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rangeHeader, cookie = r.Header.Get("Range"), r.Header.Get("Cookie") 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/1/stream", } w.Header().Set("Content-Type", "audio/mpeg") _, _ = w.Write(big) })) defer srv.Close() resp, err := NewClient().Open(context.Background(), srv.URL+"/", "/api/v1/peer/tracks/1/stream", Auth{KeyID: KeyID(pub), Key: priv}, http.Header{"Range": {"bytes=0-"}}) if err != nil { t.Fatal(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) if len(body) != len(big) || resp.Header.Get("Content-Type") != "audio/mpeg" { t.Errorf("read %d of %d bytes, type %q", len(body), len(big), resp.Header.Get("Content-Type")) } if rangeHeader != "bytes=0-" || cookie != "" { t.Errorf("Range = %q, Cookie = %q", rangeHeader, cookie) } if !verify(pub, got.Method, got.URI, got.Date, got.Nonce, got.Signature) { t.Errorf("not properly signed: %+v", got) } } func TestClientOpenNeverFollowsARedirectAndStopsWhenAskedTo(t *testing.T) { _, priv, _ := ed25519.GenerateKey(nil) 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() resp, err := NewClient().Open(context.Background(), srv.URL, "/api/v1/peer/tracks/1/stream", Auth{KeyID: "0123456789abcdef", Key: priv}, nil) if err != nil { t.Fatal(err) } _ = resp.Body.Close() if resp.StatusCode != http.StatusTemporaryRedirect || elsewhere != 0 { t.Errorf("status %d, redirected requests %d: the redirect must be handed back, not followed", resp.StatusCode, elsewhere) } // A listener that goes away ends the request to the friend. started := make(chan struct{}) ended := make(chan struct{}) slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "audio/mpeg") _, _ = w.Write([]byte("start")) w.(http.Flusher).Flush() close(started) <-r.Context().Done() close(ended) })) defer slow.Close() ctx, cancel := context.WithCancel(context.Background()) resp, err = NewClient().Open(ctx, slow.URL, "/api/v1/peer/tracks/1/stream", Auth{KeyID: "0123456789abcdef", Key: priv}, nil) if err != nil { t.Fatal(err) } <-started cancel() select { case <-ended: case <-time.After(3 * time.Second): t.Error("the request to the friend went on after the listener left") } _ = resp.Body.Close() }