package store import ( "context" "errors" "path/filepath" "testing" "time" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/listing" ) const difficulty = 8 var ( ctx = context.Background() t0 = time.Unix(1_800_000_000, 0) ) type env struct { s *Store now time.Time root *identity.Identity dev *identity.Device } func newDevice(t *testing.T, root *identity.Identity) *identity.Device { t.Helper() dev, err := identity.Enroll(root, t0.Add(-time.Hour), 180*24*time.Hour) if err != nil { t.Fatal(err) } return dev } func newEnv(t *testing.T) *env { t.Helper() e := &env{now: t0} e.root, _, _ = identity.NewRoot() e.dev = newDevice(t, e.root) s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }}) if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) e.s = s return e } // sibling returns a second store sharing e's identity and clock. func (e *env) sibling(t *testing.T) *env { t.Helper() e2 := newEnv(t) e2.root, e2.dev = e.root, e.dev return e2 } func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.Listing { t.Helper() id, _ := listing.NewID() l := &listing.Listing{ Version: listing.Version, ID: id, Seq: 1, CreatedAt: e.now.Unix(), ExpiresAt: e.now.Add(7 * 24 * time.Hour).Unix(), Kind: "rent", Category: "apartment", Geohash: "u1xjhx", Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"}, AreaM2: 50, RoomsX2: 4, Title: "Wohnung", } if mutate != nil { mutate(l) } if err := l.Seal(e.dev, difficulty); err != nil { t.Fatal(err) } return l } func (e *env) put(t *testing.T, l *listing.Listing) Outcome { t.Helper() o, err := e.s.Put(ctx, l) if err != nil { t.Fatal(err) } return o } func TestPutGet(t *testing.T) { e := newEnv(t) l := e.listing(t, nil) if o := e.put(t, l); o != Inserted { t.Fatalf("got %v want inserted", o) } got, err := e.s.Get(ctx, l.Author, l.ID) if err != nil { t.Fatal(err) } a, _ := l.Bytes() b, _ := got.Bytes() if string(a) != string(b) { t.Fatal("stored listing differs from original") } if o := e.put(t, l); o != Ignored { t.Fatalf("duplicate: got %v want ignored", o) } } func TestRejectsInvalid(t *testing.T) { e := newEnv(t) l := e.listing(t, nil) l.Price.AmountCents = 1 // breaks signature _, err := e.s.Put(ctx, l) if !errors.Is(err, ErrInvalid) { t.Fatalf("got %v, want ErrInvalid", err) } if n, _ := e.s.Count(ctx); n != 0 { t.Fatal("invalid listing was stored") } } func TestHigherSeqWinsInAnyOrder(t *testing.T) { e := newEnv(t) v1 := e.listing(t, nil) v2 := *v1 v2.Seq = 2 v2.Title = "Neuer Titel" if err := v2.Seal(e.dev, difficulty); err != nil { t.Fatal(err) } // Newer first, older second: older must be ignored. if o := e.put(t, &v2); o != Inserted { t.Fatalf("v2: %v", o) } if o := e.put(t, v1); o != Ignored { t.Fatalf("v1 after v2: got %v want ignored", o) } got, _ := e.s.Get(ctx, v1.Author, v1.ID) if got.Title != "Neuer Titel" { t.Fatalf("got %q", got.Title) } // Fresh store, natural order: second is a replacement. e2 := e.sibling(t) e2.put(t, v1) if o := e2.put(t, &v2); o != Replaced { t.Fatalf("got %v want replaced", o) } } func TestEqualSeqConvergesOnSmallerHash(t *testing.T) { e := newEnv(t) a := e.listing(t, nil) b := *a b.Title = "Anderer Titel" if err := b.Seal(e.dev, difficulty); err != nil { t.Fatal(err) } ha, _ := a.Hash() hb, _ := b.Hash() winner, loser := a, &b if hb < ha { winner, loser = &b, a } for name, order := range map[string][]*listing.Listing{ "winner first": {winner, loser}, "loser first": {loser, winner}, } { t.Run(name, func(t *testing.T) { e2 := e.sibling(t) for _, l := range order { e2.put(t, l) } got, _ := e2.s.Get(ctx, a.Author, a.ID) if got.Title != winner.Title { t.Fatalf("converged on %q, want %q", got.Title, winner.Title) } }) } } func (e *env) tombstone(t *testing.T, l *listing.Listing) *listing.Listing { t.Helper() ts := &listing.Listing{ Version: listing.Version, ID: l.ID, Seq: l.Seq + 1, CreatedAt: e.now.Unix(), ExpiresAt: e.now.Add(30 * 24 * time.Hour).Unix(), Tombstone: true, Geohash: l.Geohash, } if err := ts.Seal(e.dev, difficulty); err != nil { t.Fatal(err) } return ts } func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) { e := newEnv(t) l := e.listing(t, nil) e.put(t, l) ts := e.tombstone(t, l) if o := e.put(t, ts); o != Replaced { t.Fatalf("got %v want replaced", o) } if _, err := e.s.Get(ctx, l.Author, l.ID); !errors.Is(err, ErrNotFound) { t.Fatalf("deleted listing still readable: %v", err) } if o := e.put(t, l); o != Ignored { t.Fatalf("old version resurrected: %v", o) } if n, _ := e.s.Count(ctx); n != 0 { t.Fatalf("count %d, want 0", n) } // A tombstone arriving before the listing it deletes still wins. e2 := e.sibling(t) e2.put(t, ts) if o := e2.put(t, l); o != Ignored { t.Fatalf("listing after tombstone: %v", o) } } func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) { e := newEnv(t) victim := e.listing(t, nil) e.put(t, victim) otherRoot, _, _ := identity.NewRoot() squat := *victim squat.Seq = 99 squat.Title = "Betrug" if err := squat.Seal(newDevice(t, otherRoot), difficulty); err != nil { t.Fatal(err) } e.put(t, &squat) got, err := e.s.Get(ctx, victim.Author, victim.ID) if err != nil || got.Title != "Wohnung" { t.Fatalf("victim listing disturbed: %v %v", got, err) } } func TestRevocationVoidsDevice(t *testing.T) { e := newEnv(t) stolen := e.dev mine := e.listing(t, nil) e.put(t, mine) // The attacker hijacks the listing with the stolen device and a huge seq. hijack := *mine hijack.Seq = 1 << 40 hijack.Title = "Betrug" if err := hijack.Seal(stolen, difficulty); err != nil { t.Fatal(err) } if o := e.put(t, &hijack); o != Replaced { t.Fatalf("hijack: %v", o) } // The owner restores from the recovery phrase and revokes the device. rev, err := identity.Revoke(e.root, stolen.Cert, e.now, difficulty) if err != nil { t.Fatal(err) } if o, err := e.s.PutRevocation(ctx, rev); err != nil || o != Inserted { t.Fatalf("PutRevocation = %v, %v", o, err) } if _, err := e.s.Get(ctx, mine.Author, mine.ID); !errors.Is(err, ErrNotFound) { t.Fatal("revoked device's listing still readable") } if _, err := e.s.Put(ctx, &hijack); !errors.Is(err, ErrRevoked) { t.Fatalf("revoked device accepted again: %v", err) } if o, _ := e.s.PutRevocation(ctx, rev); o != Ignored { t.Fatalf("duplicate revocation: %v", o) } // The owner republishes from a new device with a low seq: it must win, // because the attacker's huge seq was purged with the revocation. newDev := newDevice(t, e.root) again := *mine again.Seq = 2 if err := again.Seal(newDev, difficulty); err != nil { t.Fatal(err) } if o := e.put(t, &again); o != Inserted { t.Fatalf("republish from new device: %v", o) } got, _ := e.s.Get(ctx, mine.Author, mine.ID) if got.Title != "Wohnung" { t.Fatalf("got %q", got.Title) } } func TestRevocationValidation(t *testing.T) { e := newEnv(t) other, _, _ := identity.NewRoot() // Someone else's identity cannot revoke our device. if _, err := identity.Revoke(other, e.dev.Cert, e.now, difficulty); err == nil { t.Fatal("foreign identity could create a revocation") } rev, _ := identity.Revoke(e.root, e.dev.Cert, e.now, difficulty) rev.Device = other.PublicKeyHex() if _, err := e.s.PutRevocation(ctx, rev); !errors.Is(err, ErrInvalid) { t.Fatalf("tampered revocation: %v", err) } } func TestRevocationExpiresWithCertificate(t *testing.T) { e := newEnv(t) rev, _ := identity.Revoke(e.root, e.dev.Cert, e.now, difficulty) e.s.PutRevocation(ctx, rev) if list, _ := e.s.Revocations(ctx); len(list) != 1 { t.Fatalf("got %d revocations, want 1", len(list)) } e.now = time.Unix(e.dev.Cert.ExpiresAt+1, 0) if list, _ := e.s.Revocations(ctx); len(list) != 0 { t.Fatal("expired revocation still listed") } if n, _ := e.s.Expire(ctx); n != 1 { t.Fatalf("Expire removed %d, want 1", n) } } func TestSearch(t *testing.T) { e := newEnv(t) mk := func(geo, kind string, cents int64, area, rooms int) { period := map[string]string{"rent": "month", "sale": "once"}[kind] e.put(t, e.listing(t, func(l *listing.Listing) { l.Geohash, l.Kind = geo, kind l.Price = &listing.Price{AmountCents: cents, Currency: "EUR", Period: period} l.AreaM2, l.RoomsX2 = area, rooms })) } mk("u1xjhx", "rent", 90000, 40, 3) mk("u1xjhz", "rent", 150000, 80, 6) mk("u1xkbb", "rent", 120000, 60, 4) mk("u1xjhx", "sale", 30000000, 90, 6) mk("u30000", "rent", 100000, 50, 4) // different region count := func(q Query) int { t.Helper() got, err := e.s.Search(ctx, q) if err != nil { t.Fatal(err) } return len(got) } cases := []struct { name string q Query want int }{ {"all", Query{}, 5}, {"region prefix", Query{Geohashes: []string{"u1x"}}, 4}, {"narrow prefix", Query{Geohashes: []string{"u1xjh"}}, 3}, {"two prefixes", Query{Geohashes: []string{"u1xk", "u3"}}, 2}, {"rent in region", Query{Geohashes: []string{"u1x"}, Kind: "rent"}, 3}, {"price range", Query{Kind: "rent", MinPriceCents: 95000, MaxPriceCents: 130000}, 2}, {"min area", Query{Kind: "rent", MinAreaM2: 55}, 2}, {"min rooms", Query{MinRoomsX2: 6}, 2}, {"limit", Query{Limit: 2}, 2}, {"offset", Query{Offset: 4}, 1}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { if got := count(tc.q); got != tc.want { t.Fatalf("got %d want %d", got, tc.want) } }) } if _, err := e.s.Search(ctx, Query{Geohashes: []string{"u1x' OR 1=1 --"}}); err == nil { t.Fatal("invalid geohash prefix accepted") } } func TestSinceKeysetPaging(t *testing.T) { e := newEnv(t) // Five listings in the same second plus one tombstone and one outside the region. var all []*listing.Listing for i := 0; i < 5; i++ { l := e.listing(t, nil) e.put(t, l) all = append(all, l) } e.put(t, e.tombstone(t, all[0])) e.put(t, e.listing(t, func(l *listing.Listing) { l.Geohash = "u30000" })) var got []*listing.Listing cur := Cursor{} for pages := 0; pages < 10; pages++ { page, err := e.s.Since(ctx, "u1x", cur, 2) if err != nil { t.Fatal(err) } if len(page) == 0 { break } got = append(got, page...) cur = CursorOf(page[len(page)-1]) } // 5 distinct listings; one of them is now a tombstone. if len(got) != 5 { t.Fatalf("paged %d records, want 5", len(got)) } tombstones := 0 seen := map[string]bool{} for _, l := range got { if seen[l.ID] { t.Fatalf("duplicate %s across pages", l.ID) } seen[l.ID] = true if l.Tombstone { tombstones++ } } if tombstones != 1 { t.Fatalf("got %d tombstones, want 1 (peers need them to learn deletions)", tombstones) } } func TestExpiry(t *testing.T) { e := newEnv(t) l := e.listing(t, nil) e.put(t, l) e.now = e.now.Add(8 * 24 * time.Hour) if _, err := e.s.Get(ctx, l.Author, l.ID); !errors.Is(err, ErrNotFound) { t.Fatal("expired listing still readable") } if got, _ := e.s.Search(ctx, Query{}); len(got) != 0 { t.Fatal("expired listing in search results") } n, err := e.s.Expire(ctx) if err != nil || n != 1 { t.Fatalf("Expire = %d, %v; want 1", n, err) } } func TestPersistence(t *testing.T) { path := filepath.Join(t.TempDir(), "allmende.db") opt := Options{Difficulty: difficulty, Clock: func() time.Time { return t0 }} s, err := Open(path, opt) if err != nil { t.Fatal(err) } e := newEnv(t) e.s = s l := e.listing(t, nil) e.put(t, l) s.Close() s, err = Open(path, opt) if err != nil { t.Fatal(err) } defer s.Close() if _, err := s.Get(ctx, l.Author, l.ID); err != nil { t.Fatalf("listing lost after reopen: %v", err) } } func TestRevokeAllRecovery(t *testing.T) { e := newEnv(t) mine := e.listing(t, nil) e.put(t, mine) // Recovery on a new machine: only the phrase is known. Everything issued // before the cutoff is void; the replacement device is enrolled at the cutoff. cutoff := e.now rev, err := identity.RevokeAll(e.root, cutoff, difficulty) if err != nil { t.Fatal(err) } if o, err := e.s.PutRevocation(ctx, rev); err != nil || o != Inserted { t.Fatalf("PutRevocation = %v, %v", o, err) } if _, err := e.s.Get(ctx, mine.Author, mine.ID); !errors.Is(err, ErrNotFound) { t.Fatal("listing of an older device survived the revocation") } // The old device can no longer publish, not even a fresh listing. if _, err := e.s.Put(ctx, e.listing(t, nil)); !errors.Is(err, ErrRevoked) { t.Fatalf("old device accepted: %v", err) } // The replacement device (issued at the cutoff) works. fresh, err := identity.Enroll(e.root, cutoff, 90*24*time.Hour) if err != nil { t.Fatal(err) } e.dev = fresh again := *mine again.Seq = 2 if err := again.Seal(fresh, difficulty); err != nil { t.Fatal(err) } if o := e.put(t, &again); o != Inserted { t.Fatalf("republish from the new device: %v", o) } // An older cutoff must not replace a newer one, and a repeat is ignored. if o, _ := e.s.PutRevocation(ctx, rev); o != Ignored { t.Fatalf("duplicate all-devices revocation: %v", o) } stale, _ := identity.RevokeAll(e.root, cutoff.Add(-time.Hour), difficulty) if o, _ := e.s.PutRevocation(ctx, stale); o != Ignored { t.Fatalf("older cutoff replaced a newer one: %v", o) } // Other identities are unaffected. otherRoot, _, _ := identity.NewRoot() otherDev := newDevice(t, otherRoot) theirs := e.listing(t, nil) if err := theirs.Seal(otherDev, difficulty); err != nil { t.Fatal(err) } if o := e.put(t, theirs); o != Inserted { t.Fatalf("someone else's listing blocked: %v", o) } }