package message import ( "bytes" "crypto/ed25519" "encoding/hex" "errors" "strings" "testing" "time" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/jcs" "git.stinnesbeck.com/nils/allmende/internal/listing" ) const testDifficulty = 6 var now = time.Unix(1_800_000_000, 0) type party struct { dev *identity.Device l *listing.Listing ref Ref } func newOwner(t *testing.T) *party { t.Helper() root, err := identity.Generate() 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) } l := &listing.Listing{ID: strings.Repeat("ab", 16), Author: dev.Cert.Author, Device: dev.Cert.Device} return &party{dev: dev, l: l, ref: Ref{Author: l.Author, ID: l.ID}} } func hello(text string) *Plain { return &Plain{Type: TypeText, N: 1, SentAt: now.Unix(), Text: text} } func thread(t *testing.T) *ThreadKey { t.Helper() k, err := NewThreadKey() if err != nil { t.Fatal(err) } return k } func TestKeyConversionAgrees(t *testing.T) { for i := 0; i < 20; i++ { id, _ := identity.Generate() priv := id.PrivateKey() sk, err := ed25519SecretToX25519(priv) if err != nil { t.Fatal(err) } pk, err := ed25519PublicToX25519(priv.Public().(ed25519.PublicKey)) if err != nil { t.Fatal(err) } if !bytes.Equal(sk.PublicKey().Bytes(), pk.Bytes()) { t.Fatal("converted secret and converted public key do not match") } } } func TestBuyerToOwnerRoundTrip(t *testing.T) { o := newOwner(t) tk := thread(t) e, err := SealToOwner(o.l, tk, hello("Ist die Wohnung noch frei? 🏠"), now, testDifficulty) if err != nil { t.Fatal(err) } if err := e.Check(now, testDifficulty); err != nil { t.Fatal(err) } b, _ := e.Bytes() if bytes.Contains(b, []byte("Wohnung")) { t.Fatal("plaintext visible in the envelope") } if strings.Contains(string(b), tk.PublicHex()) { t.Fatal("thread key must not appear in the envelope") } p, err := e.OpenAsOwner(o.dev) if err != nil { t.Fatal(err) } if p.Text != "Ist die Wohnung noch frei? 🏠" || p.Thread != tk.PublicHex() || p.N != 1 { t.Fatalf("unexpected plaintext %+v", p) } } // The fast miner must keep finding what the old loop found. func TestMiningFindsTheSmallestNonceThatTryingEachOneInOrderWouldFind(t *testing.T) { e, err := SealToOwner(newOwner(t).l, thread(t), hello("Hallo"), now, testDifficulty) if err != nil { t.Fatal(err) } probe := *e for n := uint64(0); ; n++ { probe.PoW = n ok, err := probe.powOK(testDifficulty) if err != nil { t.Fatal(err) } if ok { if n != e.PoW { t.Fatalf("mining chose nonce %d, the smallest that works is %d", e.PoW, n) } return } } } func TestOwnerReplyAndGrantRoundTrip(t *testing.T) { o := newOwner(t) tk := thread(t) reply := &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "Ja, noch frei."} e, err := SealToBuyer(o.dev, o.ref, reply, now, testDifficulty) if err != nil { t.Fatal(err) } if err := e.Check(now, testDifficulty); err != nil { t.Fatal(err) } mb, _ := tk.Mailbox() if e.Rcpt != mb || e.To != ToBuyer { t.Fatal("reply is not addressed to the thread's mailbox") } got, err := e.OpenAsBuyer(tk) if err != nil { t.Fatal(err) } if got.Text != "Ja, noch frei." || got.Device != o.dev.Cert.Device { t.Fatalf("unexpected reply %+v", got) } grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 2, SentAt: now.Unix(), Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 123456", Note: "Samstag 10 Uhr, bitte zweimal klingeln", ValidUntil: now.Add(7 * 24 * time.Hour).Unix()} e, err = SealToBuyer(o.dev, o.ref, grant, now, testDifficulty) if err != nil { t.Fatal(err) } got, err = e.OpenAsBuyer(tk) if err != nil { t.Fatal(err) } if got.Address != grant.Address || got.Note != grant.Note || got.ValidUntil != grant.ValidUntil { t.Fatalf("grant changed in transit: %+v", got) } } func TestTamperingWithTheHeaderBreaksDecryption(t *testing.T) { o := newOwner(t) e, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty) for name, mutate := range map[string]func(*Envelope){ "created_at": func(e *Envelope) { e.CreatedAt++ }, "expires_at": func(e *Envelope) { e.ExpiresAt-- }, "listing id": func(e *Envelope) { e.Listing.ID = strings.Repeat("cd", 16) }, "author": func(e *Envelope) { e.Listing.Author = strings.Repeat("ee", 32) }, "ciphertext": func(e *Envelope) { flipped := byte('0') if e.CT[0] == '0' { flipped = '1' } e.CT = string(flipped) + e.CT[1:] }, } { c := *e mutate(&c) if _, err := c.OpenAsOwner(o.dev); err == nil { t.Errorf("tampering with %s went unnoticed", name) } } } func TestOnlyTheRightKeysOpen(t *testing.T) { o, other := newOwner(t), newOwner(t) tk := thread(t) e, _ := SealToOwner(o.l, tk, hello("hallo"), now, testDifficulty) if _, err := e.OpenAsOwner(other.dev); err == nil { t.Fatal("another device opened the message") } // Same recipient field, wrong secret. c := *e c.Rcpt = other.dev.Cert.Device if _, err := c.OpenAsOwner(other.dev); err == nil { t.Fatal("re-addressed envelope decrypted") } r, _ := SealToBuyer(o.dev, o.ref, &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "x"}, now, testDifficulty) if _, err := r.OpenAsBuyer(thread(t)); err == nil { t.Fatal("another thread opened the reply") } } func TestImpersonationAndReplayAreRejected(t *testing.T) { o, imp := newOwner(t), newOwner(t) tk := thread(t) // A different identity signs a reply that claims to come from o's listing. p := &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "Überweisen Sie die Kaution"} if _, err := SealToBuyer(imp.dev, o.ref, p, now, testDifficulty); err == nil { t.Fatal("SealToBuyer must refuse a device of another author") } p.signOwner(imp.dev, o.ref) // forge it by hand pub, _ := hex.DecodeString(p.Thread) rpk, _ := x25519.NewPublicKey(pub) mb, _ := Mailbox(p.Thread) forged, err := build(o.ref, ToBuyer, mb, rpk, p, now, testDifficulty) if err != nil { t.Fatal(err) } if _, err := forged.OpenAsBuyer(tk); err == nil || !strings.Contains(err.Error(), "certificate") { t.Fatalf("forged reply accepted or wrong error: %v", err) } // A genuine reply for thread A, moved into thread B, fails its signature. a, b := thread(t), thread(t) genuine := &Plain{Type: TypeText, Thread: a.PublicHex(), N: 1, SentAt: now.Unix(), Text: "für A"} if _, err := SealToBuyer(o.dev, o.ref, genuine, now, testDifficulty); err != nil { t.Fatal(err) } moved := *genuine moved.Thread = b.PublicHex() pubB, _ := hex.DecodeString(moved.Thread) rpkB, _ := x25519.NewPublicKey(pubB) mbB, _ := Mailbox(moved.Thread) e, err := build(o.ref, ToBuyer, mbB, rpkB, &moved, now, testDifficulty) if err != nil { t.Fatal(err) } if _, err := e.OpenAsBuyer(b); err == nil || !strings.Contains(err.Error(), "signature") { t.Fatalf("replayed reply accepted or wrong error: %v", err) } // A reply for another listing of the same envelope header fails too. g, _ := SealToBuyer(o.dev, o.ref, &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "x"}, now, testDifficulty) g.Listing.ID = strings.Repeat("cd", 16) if _, err := g.OpenAsBuyer(tk); err == nil { t.Fatal("reply accepted for a different listing id") } } func TestRelayChecks(t *testing.T) { o := newOwner(t) good, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty) if err := good.Check(now, testDifficulty); err != nil { t.Fatal(err) } remine := func(e *Envelope) *Envelope { if err := e.mine(testDifficulty); err != nil { t.Fatal(err) } return e } cases := []struct { name string mutate func(*Envelope) wantErr string window bool }{ {"version", func(e *Envelope) { e.Version = 2 }, "version", false}, {"direction", func(e *Envelope) { e.To = "everyone" }, "direction", false}, {"owner rcpt too short", func(e *Envelope) { e.Rcpt = e.Rcpt[:32] }, "64 hex", false}, {"buyer rcpt too long", func(e *Envelope) { e.To = ToBuyer }, "32 hex", false}, {"uppercase ct", func(e *Envelope) { e.CT = strings.ToUpper(e.CT) }, "lowercase", false}, {"ct too small", func(e *Envelope) { e.CT = "00" }, "size", false}, {"lifetime over 14 days", func(e *Envelope) { e.ExpiresAt = e.CreatedAt + 15*24*3600 }, "14 days", false}, {"expiry before creation", func(e *Envelope) { e.ExpiresAt = e.CreatedAt }, "after created_at", false}, {"expired", func(e *Envelope) { e.CreatedAt -= 20 * 24 * 3600; e.ExpiresAt -= 20 * 24 * 3600 }, "expired", true}, {"from the future", func(e *Envelope) { e.CreatedAt += 3600; e.ExpiresAt += 3600 }, "future", true}, } for _, c := range cases { e := *good c.mutate(&e) remine(&e) err := e.Check(now, testDifficulty) if err == nil || !strings.Contains(err.Error(), c.wantErr) { t.Errorf("%s: err = %v, want %q", c.name, err, c.wantErr) continue } if errors.Is(err, listing.ErrTimeWindow) != c.window { t.Errorf("%s: ErrTimeWindow = %v, want %v", c.name, !c.window, c.window) } } // Proof-of-work is checked against the node's difficulty. if err := good.Check(now, 40); err == nil || !strings.Contains(err.Error(), "proof-of-work") { t.Errorf("weak work accepted: %v", err) } // Any change after mining invalidates the work (with overwhelming probability). c := *good c.CreatedAt++ if err := c.Check(now, 24); err == nil { t.Error("altered envelope kept its proof-of-work") } } func TestSizeLimits(t *testing.T) { o := newOwner(t) tk := thread(t) if _, err := SealToOwner(o.l, tk, hello(strings.Repeat("a", MaxText+1)), now, testDifficulty); err == nil { t.Error("oversized text accepted") } e, err := SealToOwner(o.l, tk, hello(strings.Repeat("ä", MaxText/2)), now, testDifficulty) if err != nil { t.Fatalf("a full-size message failed: %v", err) } b, _ := e.Bytes() if len(b) > MaxSize { t.Fatalf("a full-size envelope is %d bytes, over the %d limit", len(b), MaxSize) } // The largest owner grant, with certificate and signature, still fits. grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Address: strings.Repeat("ä", MaxAddress/2), Phone: strings.Repeat("1", MaxPhone), Email: strings.Repeat("e", MaxEmail), Note: strings.Repeat("ä", MaxNote/2), ValidUntil: now.Add(MaxGrantValidity).Unix()} e, err = SealToBuyer(o.dev, o.ref, grant, now, testDifficulty) if err != nil { t.Fatalf("a maximal grant does not fit: %v", err) } b, _ = e.Bytes() if len(b) > MaxSize { t.Fatalf("a maximal grant envelope is %d bytes, over the %d limit", len(b), MaxSize) } } func TestPaddingHidesLength(t *testing.T) { o := newOwner(t) size := func(text string) int { e, err := SealToOwner(o.l, thread(t), hello(text), now, testDifficulty) if err != nil { t.Fatal(err) } return len(e.CT) } if a, b := size("hi"), size(strings.Repeat("x", 250)); a != b { t.Errorf("short messages differ in size: %d vs %d", a, b) } if a, b := size("hi"), size(strings.Repeat("x", 900)); a >= b { t.Errorf("a longer message should land in a larger bucket: %d vs %d", a, b) } for _, n := range []int{0, 1, 511, 512, 1023, 2047, 2048, MaxPlain} { got, err := pad(bytes.Repeat([]byte{'a'}, n)) if err != nil { t.Fatal(err) } if len(got) != 512 && len(got) != 1024 && len(got) != 2048 && len(got) != 4096 { t.Errorf("pad(%d) = %d bytes, not a bucket", n, len(got)) } back, err := unpad(got) if err != nil || len(back) != n { t.Errorf("unpad(pad(%d)) = %d bytes, %v", n, len(back), err) } } if _, err := pad(make([]byte, MaxPlain+1)); err == nil { t.Error("oversized plaintext padded") } } func TestLowOrderKeysAreRejected(t *testing.T) { o := newOwner(t) e, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty) c := *e c.EPK = strings.Repeat("00", 32) // a point of low order: shared secret would be all zero if _, err := c.OpenAsOwner(o.dev); err == nil { t.Error("low-order ephemeral key accepted") } p := &Plain{Type: TypeText, Thread: strings.Repeat("00", 32), N: 1, SentAt: now.Unix(), Text: "x"} if _, err := SealToBuyer(o.dev, o.ref, p, now, testDifficulty); err == nil { t.Error("sealing to a low-order thread key succeeded") } } func TestPlaintextRules(t *testing.T) { o := newOwner(t) tk := thread(t) own := func(p *Plain) error { _, err := SealToBuyer(o.dev, o.ref, p, now, testDifficulty) return err } buyer := func(p *Plain) error { _, err := SealToOwner(o.l, tk, p, now, testDifficulty) return err } grant := func() *Plain { return &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Address: "Weg 1", ValidUntil: now.Add(time.Hour).Unix()} } if err := own(grant()); err != nil { t.Fatalf("valid grant: %v", err) } bad := map[string]func() error{ "buyers cannot grant": func() error { g := grant() g.Thread = "" return buyer(g) }, "grant without address": func() error { g := grant(); g.Address = ""; return own(g) }, "grant with text": func() error { g := grant(); g.Text = "hi"; return own(g) }, "valid_until in the past": func() error { g := grant() g.ValidUntil = g.SentAt return own(g) }, "valid_until too far": func() error { g := grant() g.ValidUntil = g.SentAt + int64(MaxGrantValidity/time.Second) + 1 return own(g) }, "text with grant fields": func() error { p := hello("hi") p.Address = "Weg 1" return buyer(p) }, "empty text": func() error { return buyer(hello("")) }, "control character": func() error { return buyer(hello("a\x07b")) }, "unknown type": func() error { p := hello("x"); p.Type = "image"; return buyer(p) }, "counter from zero": func() error { p := hello("x"); p.N = 0; return buyer(p) }, "invalid utf-8": func() error { return buyer(hello("a\xffb")) }, } for name, f := range bad { if err := f(); err == nil { t.Errorf("%s: accepted", name) } } if err := buyer(hello("Zeile 1\nZeile
2")); err != nil { t.Errorf("newlines and U+2028 should be fine: %v", err) } } func TestPlaintextMustBeCanonical(t *testing.T) { o := newOwner(t) tk := thread(t) // Valid content plus an unknown field, sealed correctly: the owner must refuse it. body := []byte(`{"n":1,"sent_at":1800000000,"t":"text","text":"hi","thread":"` + tk.PublicHex() + `","x":1}`) rpk, _ := ed25519PublicToX25519(ed25519.PublicKey(mustHex(t, o.l.Device))) e := &Envelope{Version: Version, Listing: o.ref, To: ToOwner, Rcpt: o.l.Device, CreatedAt: now.Unix(), ExpiresAt: now.Add(time.Hour).Unix()} epk, ct, err := seal(rpk, func(epk string) ([]byte, error) { e.EPK = epk; return e.headerBytes() }, body) if err != nil { t.Fatal(err) } e.EPK, e.CT = epk, hex.EncodeToString(ct) if _, err := e.OpenAsOwner(o.dev); err == nil || !strings.Contains(err.Error(), "canonical") { t.Fatalf("non-canonical plaintext accepted: %v", err) } if _, err := decodePlain([]byte(`{"t":"text"`)); err == nil { t.Fatal("broken JSON accepted") } b, _ := jcs.Marshal(hello("x")) if _, err := decodePlain(append([]byte(" "), b...)); err == nil { t.Fatal("whitespace-padded JSON accepted") } } func TestMailboxIsStableAndOpaque(t *testing.T) { k := thread(t) a, _ := k.Mailbox() b, _ := Mailbox(k.PublicHex()) if a != b || len(a) != 32 || strings.Contains(a, k.PublicHex()[:8]) { t.Fatalf("mailbox %q", a) } if _, err := Mailbox("zz"); err == nil { t.Fatal("bad key accepted") } } func TestThreadKeyRoundTrip(t *testing.T) { k := thread(t) again, err := ThreadKeyFromBytes(k.Bytes()) if err != nil || again.PublicHex() != k.PublicHex() { t.Fatalf("restoring a thread key: %v", err) } } func TestFirstMessageRules(t *testing.T) { ok := []string{ "Guten Tag, ist die Wohnung noch frei?", "Ich komme z. B. am Samstag, ca. 10 Uhr.", "Preis 1.200 Euro, ok? Ja. Gut.", "Hallo, wir sind 2 Personen (u.a. Nichtraucher).", } links := []string{ "schaut mal https://example.com/x", "http://evil", "ftp://x", "WWW.example", "auf beispiel.de gibt es mehr", "mail an max@example.com", "Hallo.Ich komme morgen", "Beispiel.DE", "bit.ly/abc", "auf straße-1.com", } for _, s := range ok { if ContainsLink(s) { t.Errorf("%q wrongly flagged as a link", s) } } for _, s := range links { if !ContainsLink(s) { t.Errorf("%q not flagged as a link", s) } } long := &Plain{Type: TypeText, Text: strings.Repeat("a", MaxFirstText+1)} if long.CheckBuyerFirst() == nil { t.Error("overlong first message accepted") } if (&Plain{Type: TypeText, Text: "gerne!"}).CheckBuyerFirst() != nil { t.Error("harmless first message rejected") } } func mustHex(t *testing.T, s string) []byte { t.Helper() b, err := hex.DecodeString(s) if err != nil { t.Fatal(err) } return b }