package httpapi import ( "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "fmt" "net/http" "net/http/httptest" "regexp" "strconv" "strings" "testing" "time" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/federation" "git.kmalloc.org/squid/sonda/internal/storage" ) // friendServer is a whole Sonda that other tests can reach over HTTP, with its admin signed in. type friendServer struct { h http.Handler db *bun.DB ts *httptest.Server admin string } func newFriendServer(t *testing.T, listen bool) *friendServer { t.Helper() h, db := newTestEnvDB(t, func(d *Deps, db *bun.DB) { d.Federation = federation.NewService(storage.NewFederationRepo(db), federation.NewClient()) }) s := &friendServer{h: h, db: db, admin: registerAndLogin(t, h)} if listen { s.ts = httptest.NewServer(h) t.Cleanup(s.ts.Close) } return s } func (s *friendServer) call(t *testing.T, method, path string, body any) resp { t.Helper() return do(t, s.h, method, "/api/v1"+path, s.admin, body) } func (s *friendServer) setUp(t *testing.T, name, address string) { t.Helper() r := s.call(t, "PUT", "/federation", map[string]any{"enabled": true, "name": name, "address": address}) if r.Code != http.StatusOK { t.Fatalf("set up federation: %d %v", r.Code, r.Body) } } func TestFederationRoutesAreForAdminsOnly(t *testing.T) { h := newTestAPI(t) admin := registerAndLogin(t, h) _, bob := addUser(t, h, admin, "bob", false) for _, c := range []struct{ method, path string }{ {"GET", "/api/v1/federation"}, {"PUT", "/api/v1/federation"}, {"POST", "/api/v1/federation/invites"}, {"POST", "/api/v1/federation/friends"}, {"POST", "/api/v1/federation/friends/1/approve"}, {"DELETE", "/api/v1/federation/friends/1"}, } { if r := do(t, h, c.method, c.path, "", nil); r.Code != http.StatusUnauthorized { t.Errorf("%s %s without a token: %d", c.method, c.path, r.Code) } r := do(t, h, c.method, c.path, bob, map[string]any{}) if r.Code != http.StatusForbidden || errCode(r) != "admin_required" { t.Errorf("%s %s as a normal user: %d %v", c.method, c.path, r.Code, r.Body) } } } func TestFederationStartsOffAndSaysWhatItSends(t *testing.T) { s := newFriendServer(t, false) r := s.call(t, "GET", "/federation", nil) if r.Code != http.StatusOK { t.Fatalf("get: %d %v", r.Code, r.Body) } sameKeys(t, "federation", r.Body, "enabled", "name", "address", "key_id", "sends", "friends", "max_streams", "max_kib_per_sec") if r.Body["enabled"] != false || r.Body["key_id"] != "" || r.Body["address"] != "" { t.Errorf("federation must start off with no key and no address: %v", r.Body) } if friends, ok := r.Body["friends"].([]any); !ok || len(friends) != 0 { t.Errorf("friends = %#v, want an empty list", r.Body["friends"]) } if !strings.Contains(r.Body["sends"].(string), "never learns who listens") { t.Errorf("sends = %q", r.Body["sends"]) } } func TestSettingUpFederation(t *testing.T) { s := newFriendServer(t, false) // Nothing can be made while it is off, and an invite needs the address of this server. if r := s.call(t, "POST", "/federation/invites", nil); r.Code != http.StatusConflict || errCode(r) != "federation_off" { t.Errorf("invite while off: %d %v", r.Code, r.Body) } for name, body := range map[string]any{ "ftp address": map[string]any{"address": "ftp://x.example.org"}, "public http": map[string]any{"address": "http://music.example.org"}, "long name": map[string]any{"name": strings.Repeat("n", 61)}, "bad json": "{nope", "wrong type": map[string]any{"enabled": "yes"}, } { if r := s.call(t, "PUT", "/federation", body); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" { t.Errorf("%s: %d %v", name, r.Code, r.Body) } } r := s.call(t, "PUT", "/federation", map[string]any{"enabled": true}) if r.Code != http.StatusOK || r.Body["enabled"] != true || !regexp.MustCompile(`^[0-9a-f]{16}$`).MatchString(str(r.Body, "key_id")) { t.Fatalf("turn on: %d %v", r.Code, r.Body) } if r := s.call(t, "POST", "/federation/invites", nil); r.Code != http.StatusConflict || errCode(r) != "address_required" { t.Errorf("invite without an address: %d %v", r.Code, r.Body) } r = s.call(t, "PUT", "/federation", map[string]any{"address": "https://Music.Example.org/", "name": " Home "}) if r.Body["address"] != "https://music.example.org" || r.Body["name"] != "Home" || r.Body["enabled"] != true { t.Errorf("update: %v (fields left out must be kept)", r.Body) } r = s.call(t, "POST", "/federation/invites", nil) if r.Code != http.StatusCreated { t.Fatalf("invite: %d %v", r.Code, r.Body) } sameKeys(t, "invite", r.Body, "invite", "expires_at") if !strings.HasPrefix(str(r.Body, "invite"), "sonda1.") { t.Errorf("invite = %v", r.Body["invite"]) } if _, err := time.Parse(time.RFC3339, str(r.Body, "expires_at")); err != nil { t.Errorf("expires_at = %v", r.Body["expires_at"]) } } func TestTwoServersBecomeFriendsOverHTTP(t *testing.T) { a := newFriendServer(t, true) b := newFriendServer(t, false) a.setUp(t, "Anna", a.ts.URL) b.setUp(t, "Bruno", "https://bruno.example.org") inv := a.call(t, "POST", "/federation/invites", nil) if inv.Code != http.StatusCreated { t.Fatalf("invite: %d %v", inv.Code, inv.Body) } // Bruno's admin pastes the invite. r := b.call(t, "POST", "/federation/friends", map[string]any{"invite": inv.Body["invite"]}) if r.Code != http.StatusCreated { t.Fatalf("redeem: %d %v", r.Code, r.Body) } sameKeys(t, "friend", r.Body, "id", "name", "address", "key_id", "state", "created_at", "approved_at") if r.Body["name"] != "Anna" || r.Body["address"] != a.ts.URL || r.Body["state"] != "outgoing" || r.Body["approved_at"] != nil { t.Errorf("Bruno's friend = %v", r.Body) } fromB := r.Body // Anna sees a request, and nothing is agreed yet. st := a.call(t, "GET", "/federation", nil) list := st.Body["friends"].([]any) if len(list) != 1 { t.Fatalf("Anna's friends = %v", list) } req := list[0].(map[string]any) if req["name"] != "Bruno" || req["address"] != "https://bruno.example.org" || req["state"] != "incoming" { t.Errorf("Anna's request = %v", req) } // Each side shows the key id of the other, so the two admins can compare them out of band. if req["key_id"] != b.call(t, "GET", "/federation", nil).Body["key_id"] || fromB["key_id"] != st.Body["key_id"] { t.Errorf("key ids do not match: %v / %v", req["key_id"], fromB["key_id"]) } id := strconv.Itoa(int(req["id"].(float64))) ok := a.call(t, "POST", "/federation/friends/"+id+"/approve", nil) if ok.Code != http.StatusOK || ok.Body["state"] != "active" || ok.Body["approved_at"] == nil { t.Fatalf("approve: %d %v", ok.Code, ok.Body) } if again := a.call(t, "POST", "/federation/friends/"+id+"/approve", nil); again.Code != http.StatusConflict || errCode(again) != "not_waiting" { t.Errorf("approve twice: %d %v", again.Code, again.Body) } // The invite was good once. c := newFriendServer(t, false) c.setUp(t, "Carla", "https://carla.example.org") if r := c.call(t, "POST", "/federation/friends", map[string]any{"invite": inv.Body["invite"]}); r.Code != http.StatusUnprocessableEntity || errCode(r) != "invite_refused" { t.Errorf("second use: %d %v", r.Code, r.Body) } // Revoking, on either side. if r := b.call(t, "DELETE", "/federation/friends/"+strconv.Itoa(int(fromB["id"].(float64))), nil); r.Code != http.StatusNoContent { t.Errorf("delete: %d %v", r.Code, r.Body) } if r := a.call(t, "DELETE", "/federation/friends/"+id, nil); r.Code != http.StatusNoContent { t.Errorf("delete: %d %v", r.Code, r.Body) } if r := a.call(t, "DELETE", "/federation/friends/"+id, nil); r.Code != http.StatusNotFound || errCode(r) != "friend_not_found" { t.Errorf("delete twice: %d %v", r.Code, r.Body) } } func TestThePrivateKeyIsNeverReturned(t *testing.T) { s := newFriendServer(t, false) s.setUp(t, "Anna", "https://anna.example.org") var priv string if err := s.db.NewRaw("SELECT private_key FROM federation_settings").Scan(context.Background(), &priv); err != nil || priv == "" { t.Fatalf("private key = %q, %v", priv, err) } for _, path := range []string{"/federation"} { if body := fmt.Sprint(s.call(t, "GET", path, nil).Body); strings.Contains(body, priv) { t.Errorf("GET %s returned the private key", path) } } } func TestRedeemChecksTheInvite(t *testing.T) { s := newFriendServer(t, false) if r := s.call(t, "POST", "/federation/friends", map[string]any{"invite": "sonda1.x"}); r.Code != http.StatusConflict || errCode(r) != "federation_off" { t.Errorf("while off: %d %v", r.Code, r.Body) } s.setUp(t, "Bruno", "https://bruno.example.org") for name, body := range map[string]any{ "garbage": map[string]any{"invite": "hello"}, "empty": map[string]any{"invite": ""}, "no field": map[string]any{}, "bad json": "[", } { if r := s.call(t, "POST", "/federation/friends", body); r.Code != http.StatusBadRequest || (errCode(r) != "invalid_invite" && errCode(r) != "invalid_input") { t.Errorf("%s: %d %v", name, r.Code, r.Body) } } // An invite whose server is gone. a := newFriendServer(t, true) a.setUp(t, "Anna", a.ts.URL) inv := a.call(t, "POST", "/federation/invites", nil) a.ts.Close() if r := s.call(t, "POST", "/federation/friends", map[string]any{"invite": inv.Body["invite"]}); r.Code != http.StatusBadGateway || errCode(r) != "friend_unreachable" { t.Errorf("server gone: %d %v", r.Code, r.Body) } if r := s.call(t, "GET", "/federation", nil); len(r.Body["friends"].([]any)) != 0 { t.Errorf("a failed attempt left a friend: %v", r.Body["friends"]) } } func TestApprovingWhatIsNotWaiting(t *testing.T) { s := newFriendServer(t, false) if r := s.call(t, "POST", "/federation/friends/99/approve", nil); r.Code != http.StatusNotFound || errCode(r) != "friend_not_found" { t.Errorf("approve missing: %d %v", r.Code, r.Body) } if r := s.call(t, "POST", "/federation/friends/zero/approve", nil); r.Code != http.StatusBadRequest { t.Errorf("approve bad id: %d %v", r.Code, r.Body) } } func pairBody(code, name, address string) map[string]any { pub, _, _ := ed25519.GenerateKey(rand.Reader) return map[string]any{"code": code, "name": name, "address": address, "public_key": base64.RawURLEncoding.EncodeToString(pub)} } func TestThePairingRouteIsPublicAndGivesNothingAway(t *testing.T) { s := newFriendServer(t, false) anon := func(body any) resp { return do(t, s.h, "POST", "/api/v1/peer/pair", "", body) } // While federation is off the route is as good as missing. if r := anon(pairBody("c", "B", "https://b.example.org")); r.Code != http.StatusNotFound || errCode(r) != "not_found" { t.Errorf("while off: %d %v", r.Code, r.Body) } s.setUp(t, "Anna", "https://anna.example.org") if r := anon(pairBody("not-an-invite", "B", "https://b.example.org")); r.Code != http.StatusForbidden || errCode(r) != "invalid_invite" { t.Errorf("unknown code: %d %v", r.Code, r.Body) } for name, body := range map[string]any{ "no name": pairBody("c", "", "https://b.example.org"), "bad address": pairBody("c", "B", "ftp://b"), "bad key": map[string]any{"code": "c", "name": "B", "address": "https://b.example.org", "public_key": "AAAA"}, "not base64": map[string]any{"code": "c", "name": "B", "address": "https://b.example.org", "public_key": "!!"}, "bad json": "{", } { if r := anon(body); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" { t.Errorf("%s: %d %v", name, r.Code, r.Body) } } } func TestPairingIsSlowedDown(t *testing.T) { s := newFriendServer(t, false) s.setUp(t, "Anna", "https://anna.example.org") var last resp for i := 0; i < 11; i++ { last = do(t, s.h, "POST", "/api/v1/peer/pair", "", pairBody("guess", "B", "https://b.example.org")) } if last.Code != http.StatusTooManyRequests || errCode(last) != "too_many_requests" { t.Errorf("11th attempt: %d %v", last.Code, last.Body) } }