Files
allmende/internal/listing/listing_test.go
T
nilsandClaude Sonnet 5.5 d3efe5a3a7 Add device keys, revocation and libp2p gossip with sync
- identity: 12-word recovery phrase, device certificates, revocations,
  device key storage; the identity key is never stored on a node
- listing: signed by a device with an embedded certificate, domain-separated
  signatures, ErrTimeWindow for clock-related failures, region helpers
- store: revocations purge a device's listings; keyset-paged Since for sync
- p2p: gossipsub topic per geohash region plus a global revocation topic,
  validators run before relaying, /allmende/1/sync catch-up protocol,
  bootstrap peers and mDNS
- docs: key model, replication and conflict rules

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 17:43:25 +01:00

295 lines
7.8 KiB
Go

package listing
import (
"errors"
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
)
const testDifficulty = 12
var now = time.Unix(1_800_000_000, 0)
func newDevice(t *testing.T) *identity.Device {
t.Helper()
root, _, err := identity.NewRoot()
if err != nil {
t.Fatal(err)
}
dev, err := identity.Enroll(root, now.Add(-time.Hour), 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
return dev
}
func sample(t *testing.T) *Listing {
t.Helper()
id, err := NewID()
if err != nil {
t.Fatal(err)
}
return &Listing{
Version: Version,
ID: id,
Seq: 1,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(7 * 24 * time.Hour).Unix(),
Kind: "rent",
Category: "apartment",
Geohash: "u1xjhx",
Price: &Price{AmountCents: 120000, Currency: "EUR", Period: "month"},
AreaM2: 55,
RoomsX2: 5,
Features: []string{"balcony", "elevator"},
Title: "Helle 2,5-Zimmer-Wohnung",
}
}
func sealed(t *testing.T) (*Listing, *identity.Device) {
t.Helper()
dev := newDevice(t)
l := sample(t)
if err := l.Seal(dev, testDifficulty); err != nil {
t.Fatal(err)
}
return l, dev
}
func TestSealCheckRoundTrip(t *testing.T) {
l, dev := sealed(t)
if err := l.Check(now, testDifficulty); err != nil {
t.Fatal(err)
}
if l.Author != dev.Cert.Author || l.Device != dev.Key.PublicKeyHex() {
t.Fatal("seal did not fill author/device from the device")
}
}
func TestCanonicalBytesDeterministic(t *testing.T) {
l, _ := sealed(t)
a, _ := l.Bytes()
b, _ := l.Bytes()
if string(a) != string(b) {
t.Fatal("canonical bytes differ between calls")
}
if !strings.HasPrefix(string(a), `{"area_m2":55,"author":`) {
t.Fatalf("unexpected canonical prefix: %s", a[:40])
}
}
func TestTamperDetected(t *testing.T) {
l, _ := sealed(t)
l.Price.AmountCents = 1
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("tampered listing accepted")
}
}
func TestAuthorMustMatchCertificate(t *testing.T) {
l, _ := sealed(t)
other, _, _ := identity.NewRoot()
l.Author = other.PublicKeyHex()
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("listing claiming a foreign author accepted")
}
}
func TestDeviceWithoutCertificateForAuthorRejected(t *testing.T) {
// A device certified by identity A cannot sign for identity B, even if
// the attacker attaches B's public key as author.
attacker := newDevice(t)
victim, _, _ := identity.NewRoot()
l := sample(t)
if err := l.Seal(attacker, testDifficulty); err != nil {
t.Fatal(err)
}
l.Author = victim.PublicKeyHex()
l.Cert.Author = victim.PublicKeyHex() // forged field; certificate signature breaks
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("forged identity accepted")
}
}
func TestSignedByWrongDeviceRejected(t *testing.T) {
l, _ := sealed(t)
other := newDevice(t)
// Re-sign with a different device key while keeping the original cert.
l.Sig = ""
b, _ := l.unsignedBytes()
l.Sig = hexSig(other, b)
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("signature by a different device accepted")
}
}
func hexSig(dev *identity.Device, unsigned []byte) string {
const hexd = "0123456789abcdef"
sig := dev.Key.Sign(append([]byte(listingContext), unsigned...))
out := make([]byte, 0, len(sig)*2)
for _, b := range sig {
out = append(out, hexd[b>>4], hexd[b&0xf])
}
return string(out)
}
func TestCertificateWindow(t *testing.T) {
root, _, _ := identity.NewRoot()
// Listing created before the certificate was issued.
dev, _ := identity.Enroll(root, now.Add(time.Hour), 24*time.Hour)
l := sample(t)
_ = l.Seal(dev, 0)
if err := l.Check(now.Add(2*time.Hour), 0); err == nil {
t.Fatal("listing older than its certificate accepted")
}
// Certificate expired at verification time.
dev, _ = identity.Enroll(root, now.Add(-48*time.Hour), 24*time.Hour)
l = sample(t)
l.CreatedAt = now.Add(-30 * time.Hour).Unix()
l.ExpiresAt = now.Add(24 * time.Hour).Unix()
_ = l.Seal(dev, 0)
err := l.Check(now, 0)
if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("expired certificate: got %v, want ErrTimeWindow", err)
}
}
func TestInsufficientPoW(t *testing.T) {
l, _ := sealed(t)
if err := l.Check(now, 40); err == nil {
t.Fatal("expected proof-of-work failure")
}
}
func TestExpiryAndLifetime(t *testing.T) {
dev := newDevice(t)
l := sample(t)
l.ExpiresAt = l.CreatedAt + int64(31*24*3600)
_ = l.Seal(dev, 0)
if err := l.Check(now, 0); err == nil {
t.Fatal("lifetime over 30 days accepted")
}
l = sample(t)
_ = l.Seal(dev, 0)
err := l.Check(now.Add(8*24*time.Hour), 0)
if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("expired listing: got %v, want ErrTimeWindow", err)
}
l = sample(t)
l.CreatedAt = now.Add(time.Hour).Unix()
l.ExpiresAt = l.CreatedAt + 3600
_ = l.Seal(dev, 0)
err = l.Check(now, 0)
if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("future-dated listing: got %v, want ErrTimeWindow", err)
}
}
func TestContentValidation(t *testing.T) {
dev := newDevice(t)
cases := map[string]func(*Listing){
"bad kind": func(l *Listing) { l.Kind = "swap" },
"bad category": func(l *Listing) { l.Category = "castle" },
"bad geohash": func(l *Listing) { l.Geohash = "u1xjh" },
"geohash alphabet": func(l *Listing) { l.Geohash = "u1xjha" }, // 'a' is not in the alphabet
"rent period": func(l *Listing) { l.Price.Period = "once" },
"zero price": func(l *Listing) { l.Price.AmountCents = 0 },
"currency": func(l *Listing) { l.Price.Currency = "USD" },
"empty title": func(l *Listing) { l.Title = "" },
"control char": func(l *Listing) { l.Title = "a\x00b" },
"bad image hash": func(l *Listing) { l.Images = []Image{{Hash: "zz", ThumbHash: "zz"}} },
"bad delegate": func(l *Listing) { l.Delegate = "no" },
"huge description": func(l *Listing) { l.Description = strings.Repeat("x", 4001) },
}
for name, mutate := range cases {
t.Run(name, func(t *testing.T) {
l := sample(t)
mutate(l)
if err := l.Seal(dev, 0); err != nil {
t.Fatal(err)
}
if err := l.Check(now, 0); err == nil {
t.Fatal("invalid listing accepted")
}
})
}
}
func TestTombstoneAndSupersedes(t *testing.T) {
l, dev := sealed(t)
ts := &Listing{
Version: Version,
ID: l.ID,
Seq: l.Seq + 1,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(24 * time.Hour).Unix(),
Tombstone: true,
Geohash: l.Geohash,
}
if err := ts.Seal(dev, testDifficulty); err != nil {
t.Fatal(err)
}
if err := ts.Check(now, testDifficulty); err != nil {
t.Fatal(err)
}
if !ts.Supersedes(l) || l.Supersedes(ts) {
t.Fatal("tombstone must supersede the original, not the reverse")
}
// A different identity cannot supersede someone else's listing.
forged := *ts
_ = forged.Seal(newDevice(t), testDifficulty)
if forged.Supersedes(l) {
t.Fatal("tombstone by a different author must not supersede")
}
// Another device of the same identity can (e.g. after a node was replaced).
root, _, _ := identity.NewRoot()
devA, _ := identity.Enroll(root, now.Add(-time.Hour), 24*time.Hour)
devB, _ := identity.Enroll(root, now.Add(-time.Hour), 24*time.Hour)
v1 := sample(t)
_ = v1.Seal(devA, 0)
v2 := *v1
v2.Seq = 2
_ = v2.Seal(devB, 0)
if !v2.Supersedes(v1) {
t.Fatal("a second device of the same identity must be able to supersede")
}
// Tombstones must not smuggle content.
ts.Title = "still here"
_ = ts.Seal(dev, testDifficulty)
if err := ts.Check(now, testDifficulty); err == nil {
t.Fatal("tombstone with content accepted")
}
}
func TestHashChangesWithContent(t *testing.T) {
a, _ := sealed(t)
b := *a
b.Seq++
ha, _ := a.Hash()
hb, _ := b.Hash()
if ha == hb {
t.Fatal("hash must differ for different content")
}
}
func TestRegion(t *testing.T) {
if Region("u1xjhx") != "u1x" {
t.Fatal("wrong region")
}
if !ValidRegion("u1x") || ValidRegion("u1") || ValidRegion("u1xa") || ValidRegion("u1a") {
t.Fatal("ValidRegion wrong")
}
}