package federation import ( "context" "crypto/ed25519" "errors" "net/http" "strings" "testing" "time" ) // memStore is a Store in memory. type memStore struct { settings *Settings invites map[string]memInvite friends []Friend requests []FriendRequest nextID int64 } type memInvite struct { expires time.Time used bool } func newMemStore() *memStore { return &memStore{invites: map[string]memInvite{}} } func (m *memStore) Settings(context.Context) (Settings, bool, error) { if m.settings == nil { return Settings{}, false, nil } return *m.settings, true, nil } func (m *memStore) SaveSettings(_ context.Context, s Settings) error { m.settings = &s; return nil } func (m *memStore) AddInvite(_ context.Context, hash string, _, expires time.Time) error { m.invites[hash] = memInvite{expires: expires} return nil } func (m *memStore) UseInvite(_ context.Context, hash string, now time.Time) (bool, error) { inv, ok := m.invites[hash] if !ok || inv.used || !now.Before(inv.expires) { return false, nil } inv.used = true m.invites[hash] = inv return true, nil } func (m *memStore) Friends(context.Context) ([]Friend, error) { return append([]Friend(nil), m.friends...), nil } func (m *memStore) Friend(_ context.Context, id int64) (Friend, error) { for _, f := range m.friends { if f.ID == id { return f, nil } } return Friend{}, ErrFriendMissing } func (m *memStore) FriendByKey(_ context.Context, key ed25519.PublicKey) (Friend, bool, error) { for _, f := range m.friends { if f.PublicKey.Equal(key) { return f, true, nil } } return Friend{}, false, nil } func (m *memStore) AddFriend(ctx context.Context, f Friend) (Friend, error) { if _, found, _ := m.FriendByKey(ctx, f.PublicKey); found { return Friend{}, ErrAlreadyFriend } m.nextID++ f.ID = m.nextID m.friends = append(m.friends, f) return f, nil } func (m *memStore) Approve(_ context.Context, id int64, now time.Time) error { for i, f := range m.friends { if f.ID != id { continue } if f.State != Incoming { return ErrWrongState } m.friends[i].State, m.friends[i].ApprovedAt = Active, now return nil } return ErrFriendMissing } func (m *memStore) Activate(_ context.Context, id int64, now time.Time) error { for i, f := range m.friends { if f.ID != id { continue } if f.State != Outgoing { return ErrWrongState } m.friends[i].State, m.friends[i].ApprovedAt = Active, now return nil } return ErrFriendMissing } func (m *memStore) LogRequest(_ context.Context, r FriendRequest) error { m.requests = append(m.requests, r) return nil } func (m *memStore) Requests(_ context.Context, limit int) ([]FriendRequest, error) { var out []FriendRequest for i := len(m.requests) - 1; i >= 0 && len(out) < limit; i-- { r := m.requests[i] for _, f := range m.friends { if f.ID == r.FriendID { r.FriendName = f.Name } } out = append(out, r) } return out, nil } func (m *memStore) PruneRequests(_ context.Context, before time.Time) error { kept := m.requests[:0] for _, r := range m.requests { if !r.At.Before(before) { kept = append(kept, r) } } m.requests = kept return nil } func (m *memStore) DeleteFriend(_ context.Context, id int64) error { for i, f := range m.friends { if f.ID == id { m.friends = append(m.friends[:i], m.friends[i+1:]...) return nil } } return ErrFriendMissing } // direct is a Remote that reaches another Service in the same process, answering as the HTTP layer would. type direct struct { to *Service calls int } func (d *direct) Pair(ctx context.Context, _ string, req PairRequest) (PairReply, error) { d.calls++ reply, err := d.to.Pair(ctx, req) switch { case errors.Is(err, ErrInvalidInvite), errors.Is(err, ErrOff): return PairReply{}, ErrRefused case err != nil: return PairReply{}, err } return reply, nil } func (d *direct) Info(context.Context, string, Auth) (Info, error) { return Info{}, errors.New("not used") } func (d *direct) Get(context.Context, string, string, Auth) (int, []byte, error) { return 0, nil, errors.New("not used") } func (d *direct) Open(context.Context, string, string, Auth, http.Header) (*http.Response, error) { return nil, errors.New("not used") } type clock struct{ t time.Time } func (c *clock) now() time.Time { return c.t } func newServer(t *testing.T, name, address string, remote Remote) (*Service, *memStore, *clock) { t.Helper() st := newMemStore() ck := &clock{t: time.Unix(1_700_000_000, 0)} s := NewService(st, remote) s.now = ck.now s.host = func() string { return "host-" + name } on, n, a := true, name, address if _, err := s.Update(context.Background(), Patch{Enabled: &on, Name: &n, Address: &a}); err != nil { t.Fatal(err) } return s, st, ck } func TestFederationStartsOffAndAsksNothing(t *testing.T) { ctx := context.Background() s := NewService(newMemStore(), nil) s.host = func() string { return "nas" } st, err := s.Status(ctx) if err != nil { t.Fatal(err) } if st.Enabled || st.KeyID != "" || len(st.Friends) != 0 || st.Address != "" || st.Name != "nas" { t.Errorf("Status = %+v: federation must start off, with no key and no friend, named after the host", st) } if !strings.Contains(st.Sends, "never learns who listens") { t.Errorf("Sends = %q, it must say what a friend is sent", st.Sends) } if _, err := s.CreateInvite(ctx); !errors.Is(err, ErrOff) { t.Errorf("CreateInvite = %v, want ErrOff", err) } if _, err := s.Redeem(ctx, "sonda1.x"); !errors.Is(err, ErrOff) { t.Errorf("Redeem = %v, want ErrOff", err) } if _, err := s.Pair(ctx, PairRequest{}); !errors.Is(err, ErrOff) { t.Errorf("Pair = %v, want ErrOff", err) } } func TestTheKeyIsMadeOnceOnFirstUse(t *testing.T) { ctx := context.Background() st := newMemStore() s := NewService(st, nil) on, off := true, false got, err := s.Update(ctx, Patch{Enabled: &on}) if err != nil { t.Fatal(err) } if !got.Enabled || len(got.KeyID) != 16 { t.Fatalf("Status = %+v", got) } if len(st.settings.PrivateKey) != ed25519.PrivateKeySize || KeyID(st.settings.PublicKey) != got.KeyID { t.Errorf("the stored pair does not match the key id") } if _, err := s.Update(ctx, Patch{Enabled: &off}); err != nil { t.Fatal(err) } again, _ := s.Update(ctx, Patch{Enabled: &on}) if again.KeyID != got.KeyID { t.Errorf("key id changed from %s to %s: turning it off and on must keep the key", got.KeyID, again.KeyID) } } func TestUpdateChecksTheNameAndTheAddress(t *testing.T) { ctx := context.Background() s := NewService(newMemStore(), nil) set := func(name, addr string) error { _, err := s.Update(ctx, Patch{Name: &name, Address: &addr}) return err } for _, addr := range []string{ "ftp://music.example.org", "music.example.org", "https://", "https://user:pw@music.example.org", "https://music.example.org/?a=b", "https://music.example.org/#x", "http://music.example.org", "http://8.8.8.8", "http://" + strings.Repeat("a", 300) + ".example.org", "https://exa mple.org", } { if err := set("Home", addr); !errors.Is(err, ErrInvalidInput) { t.Errorf("address %q: err = %v, want ErrInvalidInput", addr, err) } } for _, name := range []string{strings.Repeat("n", 61), "line\nbreak", "tab\there"} { if err := set(name, ""); !errors.Is(err, ErrInvalidInput) { t.Errorf("name %q: err = %v, want ErrInvalidInput", name, err) } } // https is fine anywhere. Plain http only on a network of one's own: a private or loopback address, or a local name. for addr, want := range map[string]string{ "https://Music.Example.org/": "https://music.example.org", "https://music.example.org/sonda/": "https://music.example.org/sonda", "http://192.168.1.20:8080": "http://192.168.1.20:8080", "http://10.0.0.5": "http://10.0.0.5", "http://127.0.0.1:8081": "http://127.0.0.1:8081", "http://[::1]:8081": "http://[::1]:8081", "http://nas": "http://nas", "http://nas.local:8080": "http://nas.local:8080", "http://music.lan": "http://music.lan", "http://router.home.arpa": "http://router.home.arpa", "https://8.8.8.8": "https://8.8.8.8", } { if err := set("Home", addr); err != nil { t.Errorf("address %q: %v", addr, err) continue } if st, _ := s.Status(ctx); st.Address != want { t.Errorf("address %q saved as %q, want %q", addr, st.Address, want) } } // An empty address clears it. if err := set(" Home ", ""); err != nil { t.Fatal(err) } if st, _ := s.Status(ctx); st.Address != "" || st.Name != "Home" { t.Errorf("Status = %+v", st) } } func TestAnInviteNeedsAnAddressAndKeepsOnlyAHash(t *testing.T) { ctx := context.Background() st := newMemStore() s := NewService(st, nil) s.now = (&clock{t: time.Unix(1_700_000_000, 0)}).now on := true if _, err := s.Update(ctx, Patch{Enabled: &on}); err != nil { t.Fatal(err) } if _, err := s.CreateInvite(ctx); !errors.Is(err, ErrNoAddress) { t.Fatalf("CreateInvite without an address = %v, want ErrNoAddress", err) } addr := "https://a.example.org" if _, err := s.Update(ctx, Patch{Address: &addr}); err != nil { t.Fatal(err) } inv, err := s.CreateInvite(ctx) if err != nil { t.Fatal(err) } if !strings.HasPrefix(inv.Text, "sonda1.") || inv.ExpiresAt.Sub(s.now()) != 24*time.Hour { t.Errorf("invite = %+v", inv) } if len(st.invites) != 1 { t.Fatalf("stored invites = %d", len(st.invites)) } for hash := range st.invites { if len(hash) != 64 || strings.Contains(inv.Text, hash) { t.Errorf("stored %q: want only the SHA-256 of the code", hash) } } } func TestTwoServersBecomeFriendsWithTwoConfirmations(t *testing.T) { ctx := context.Background() a, aStore, _ := newServer(t, "Anna", "https://anna.example.org", nil) toA := &direct{to: a} b, bStore, _ := newServer(t, "Bruno", "https://bruno.example.org", toA) inv, err := a.CreateInvite(ctx) if err != nil { t.Fatal(err) } friend, err := b.Redeem(ctx, inv.Text) if err != nil { t.Fatal(err) } // B pasted the invite: that is its confirmation. It waits for Anna. if friend.Name != "Anna" || friend.Address != "https://anna.example.org" || friend.State != Outgoing { t.Errorf("B's friend = %+v", friend) } // A now has a request to approve, and has not agreed to anything yet. list, _ := aStore.Friends(ctx) if len(list) != 1 || list[0].State != Incoming || list[0].Name != "Bruno" || list[0].Address != "https://bruno.example.org" { t.Fatalf("A's friends = %+v", list) } if got, _ := bStore.Friends(ctx); len(got) != 1 || got[0].State != Outgoing { t.Errorf("B's friends = %+v", got) } approved, err := a.Approve(ctx, list[0].ID) if err != nil { t.Fatal(err) } if approved.State != Active || approved.ApprovedAt.IsZero() { t.Errorf("approved = %+v", approved) } st, _ := a.Status(ctx) if len(st.Friends) != 1 || st.Friends[0].State != Active { t.Errorf("Status.Friends = %+v", st.Friends) } // The invite was good once. c, _, _ := newServer(t, "Carla", "https://carla.example.org", toA) if _, err := c.Redeem(ctx, inv.Text); !errors.Is(err, ErrRefused) { t.Errorf("second use of the invite = %v, want ErrRefused", err) } } func TestAnExpiredInviteIsRefused(t *testing.T) { ctx := context.Background() a, _, ack := newServer(t, "Anna", "https://anna.example.org", nil) b, bStore, _ := newServer(t, "Bruno", "https://bruno.example.org", &direct{to: a}) inv, _ := a.CreateInvite(ctx) ack.t = ack.t.Add(24*time.Hour + time.Second) if _, err := b.Redeem(ctx, inv.Text); !errors.Is(err, ErrRefused) { t.Fatalf("Redeem = %v, want ErrRefused", err) } if got, _ := bStore.Friends(ctx); len(got) != 0 { t.Errorf("B kept %+v after a refusal", got) } } // A server that answers with another key than the one in the invite is not the one the invite came from. type swapKey struct{ real Remote } func (s swapKey) Info(ctx context.Context, addr string, a Auth) (Info, error) { return s.real.Info(ctx, addr, a) } func (s swapKey) Get(ctx context.Context, addr, uri string, a Auth) (int, []byte, error) { return s.real.Get(ctx, addr, uri, a) } func (s swapKey) Open(ctx context.Context, addr, uri string, a Auth, h http.Header) (*http.Response, error) { return s.real.Open(ctx, addr, uri, a, h) } func (s swapKey) Pair(ctx context.Context, addr string, req PairRequest) (PairReply, error) { r, err := s.real.Pair(ctx, addr, req) if err != nil { return r, err } pub, _, _ := ed25519.GenerateKey(nil) r.PublicKey = pub return r, nil } func TestAKeyThatIsNotTheOneInTheInviteIsNotAFriend(t *testing.T) { ctx := context.Background() a, _, _ := newServer(t, "Anna", "https://anna.example.org", nil) b, bStore, _ := newServer(t, "Bruno", "https://bruno.example.org", swapKey{&direct{to: a}}) inv, _ := a.CreateInvite(ctx) if _, err := b.Redeem(ctx, inv.Text); !errors.Is(err, ErrKeyMismatch) { t.Fatalf("Redeem = %v, want ErrKeyMismatch", err) } if got, _ := bStore.Friends(ctx); len(got) != 0 { t.Errorf("B kept %+v", got) } } func TestPairingChecksWhatItIsSent(t *testing.T) { ctx := context.Background() a, aStore, _ := newServer(t, "Anna", "https://anna.example.org", nil) pub, _, _ := ed25519.GenerateKey(nil) ownPub := aStore.settings.PublicKey for name, req := range map[string]PairRequest{ "no name": {Code: "c", Name: "", Address: "https://b.example.org", PublicKey: pub}, "bad address": {Code: "c", Name: "B", Address: "ftp://b", PublicKey: pub}, "short key": {Code: "c", Name: "B", Address: "https://b.example.org", PublicKey: pub[:10]}, "its own key": {Code: "c", Name: "B", Address: "https://b.example.org", PublicKey: ownPub}, "no code at all": {Code: "", Name: "B", Address: "https://b.example.org", PublicKey: pub}, } { _, err := a.Pair(ctx, req) want := ErrInvalidInput if name == "no code at all" { want = ErrInvalidInvite } if !errors.Is(err, want) { t.Errorf("%s: err = %v, want %v", name, err, want) } } if got, _ := aStore.Friends(ctx); len(got) != 0 { t.Errorf("A kept %+v", got) } } func TestAKnownServerDoesNotBurnAnInvite(t *testing.T) { ctx := context.Background() a, _, _ := newServer(t, "Anna", "https://anna.example.org", nil) b, _, _ := newServer(t, "Bruno", "https://bruno.example.org", &direct{to: a}) first, _ := a.CreateInvite(ctx) friend, err := b.Redeem(ctx, first.Text) if err != nil { t.Fatal(err) } second, _ := a.CreateInvite(ctx) if _, err := b.Redeem(ctx, second.Text); !errors.Is(err, ErrAlreadyFriend) { t.Fatalf("second Redeem = %v, want ErrAlreadyFriend", err) } // The second invite was not used up by that attempt: once B's friend is removed on A's side it works. list, _ := a.Status(ctx) if err := a.Remove(ctx, list.Friends[0].ID); err != nil { t.Fatal(err) } if err := b.Remove(ctx, friend.ID); err != nil { t.Fatal(err) } if _, err := b.Redeem(ctx, second.Text); err != nil { t.Errorf("Redeem after removal = %v, the invite must still be good", err) } } func TestTooManyAttemptsAreSlowedDown(t *testing.T) { ctx := context.Background() a, _, ack := newServer(t, "Anna", "https://anna.example.org", nil) pub, _, _ := ed25519.GenerateKey(nil) req := PairRequest{Code: "guess", Name: "B", Address: "https://b.example.org", PublicKey: pub} for i := 0; i < 10; i++ { if _, err := a.Pair(ctx, req); !errors.Is(err, ErrInvalidInvite) { t.Fatalf("attempt %d = %v, want ErrInvalidInvite", i, err) } } if _, err := a.Pair(ctx, req); !errors.Is(err, ErrTooMany) { t.Fatalf("attempt 11 = %v, want ErrTooMany", err) } ack.t = ack.t.Add(61 * time.Second) if _, err := a.Pair(ctx, req); !errors.Is(err, ErrInvalidInvite) { t.Errorf("after a minute = %v, want ErrInvalidInvite", err) } } func TestPairingStopsWhenFederationIsTurnedOff(t *testing.T) { ctx := context.Background() a, _, _ := newServer(t, "Anna", "https://anna.example.org", nil) b, _, _ := newServer(t, "Bruno", "https://bruno.example.org", &direct{to: a}) inv, _ := a.CreateInvite(ctx) off := false if _, err := a.Update(ctx, Patch{Enabled: &off}); err != nil { t.Fatal(err) } if _, err := b.Redeem(ctx, inv.Text); !errors.Is(err, ErrRefused) { t.Errorf("Redeem = %v, want ErrRefused while the other side is off", err) } } func TestRedeemRefusesWhatIsNotAnInvite(t *testing.T) { ctx := context.Background() remote := &direct{} b, _, _ := newServer(t, "Bruno", "https://bruno.example.org", remote) for _, text := range []string{ "", "hello", "sonda1.", "sonda1.!!!", "sonda1.e30", // {} "sonda2.e30", } { if _, err := b.Redeem(ctx, text); !errors.Is(err, ErrInvalidInvite) { t.Errorf("Redeem(%q) = %v, want ErrInvalidInvite", text, err) } } // Its own invite is no use to it. own, _ := b.CreateInvite(ctx) if _, err := b.Redeem(ctx, own.Text); !errors.Is(err, ErrInvalidInput) { t.Errorf("Redeem(own invite) = %v, want ErrInvalidInput", err) } if remote.calls != 0 { t.Errorf("the other server was called %d times for invites that could not be used", remote.calls) } } func TestRedeemNeedsAnAddressOfItsOwn(t *testing.T) { ctx := context.Background() a, _, _ := newServer(t, "Anna", "https://anna.example.org", nil) inv, _ := a.CreateInvite(ctx) b := NewService(newMemStore(), &direct{to: a}) on := true if _, err := b.Update(ctx, Patch{Enabled: &on}); err != nil { t.Fatal(err) } if _, err := b.Redeem(ctx, inv.Text); !errors.Is(err, ErrNoAddress) { t.Errorf("Redeem = %v, want ErrNoAddress: the friend must know where to reach it", err) } } func TestApproveAndRemove(t *testing.T) { ctx := context.Background() a, _, _ := newServer(t, "Anna", "https://anna.example.org", nil) b, _, _ := newServer(t, "Bruno", "https://bruno.example.org", &direct{to: a}) inv, _ := a.CreateInvite(ctx) mine, err := b.Redeem(ctx, inv.Text) if err != nil { t.Fatal(err) } // B waits for A: it has nothing to approve. if _, err := b.Approve(ctx, mine.ID); !errors.Is(err, ErrWrongState) { t.Errorf("approve an outgoing friend = %v, want ErrWrongState", err) } if _, err := a.Approve(ctx, 999); !errors.Is(err, ErrFriendMissing) { t.Errorf("approve a missing friend = %v, want ErrFriendMissing", err) } if err := a.Remove(ctx, 999); !errors.Is(err, ErrFriendMissing) { t.Errorf("remove a missing friend = %v, want ErrFriendMissing", err) } if err := b.Remove(ctx, mine.ID); err != nil { t.Errorf("a request one made can be withdrawn: %v", err) } }