Files
allmende/internal/message/fixture_test.go
T
nilsandClaude Sonnet 5.5 3b0351c774 Implement end-to-end encrypted buyer/seller messaging
Wire format (internal/message): sealed boxes to the listing's device key
(X25519 + HKDF + ChaCha20-Poly1305), padded, proof-of-work stamped, with
signed owner replies and address grants. Relay validation, bounded queues,
gossip on per-region message topics and sync (store, p2p).

Owner side (internal/inbox, API): inbox with hidden link messages and a
per-day new-thread limit, replies, grants, and a private per-listing
address. Public POST/GET /api/v1/messages for buyers.

Browser: noble-based sealing and reply verification checked against a Go
fixture, contact form, conversation view, message list, de/en strings.

Docs: PROTOCOL.md messaging section matches the implementation.

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

198 lines
6.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package message
import (
"bytes"
"encoding/hex"
"encoding/json"
"io"
"os"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/listing"
)
// The browser seals buyer messages and opens owner replies. This golden file
// is produced by the Go implementation and consumed by the TypeScript tests
// (web/test), which must reproduce every byte: same envelope from the same
// ephemeral key, same plaintext from the same thread key.
//
// Refresh it after an intentional format change with:
//
// UPDATE_FIXTURES=1 go test ./internal/message -run TestGoldenFixture
const fixturePath = "testdata/fixture.json"
const (
fixtureNow = 1_800_000_000
fixtureDifficulty = 8
)
type fixtureEnvelope struct {
EphemeralSecret string `json:"esk"` // hex; the only randomness in the envelope
Plain json.RawMessage `json:"plain"` // what was sealed, as plain JSON
PlainCanonical string `json:"plain_canonical"`
PaddedLen int `json:"padded_len"`
Canonical string `json:"canonical"` // the exact envelope bytes
Hash string `json:"hash"`
Work int `json:"work"`
}
type linkCase struct {
Text string `json:"text"`
Link bool `json:"link"`
}
type fixtureFile struct {
Now int64 `json:"now"`
Difficulty int `json:"difficulty"`
Listing Ref `json:"listing"`
Device string `json:"device"`
DeviceSeed string `json:"device_seed"`
ThreadSecret string `json:"thread_secret"`
ThreadPublic string `json:"thread_public"`
Mailbox string `json:"mailbox"`
ToOwner fixtureEnvelope `json:"to_owner"`
ToBuyer fixtureEnvelope `json:"to_buyer"`
Links []linkCase `json:"links"`
}
func withEntropy(t *testing.T, b []byte) {
t.Helper()
old := entropy
entropy = io.Reader(bytes.NewReader(b))
t.Cleanup(func() { entropy = old })
}
func buildFixture(t *testing.T) *fixtureFile {
t.Helper()
root, err := identity.FromPhrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
if err != nil {
t.Fatal(err)
}
deviceSeed := bytes.Repeat([]byte{7}, 32)
devKey, err := identity.FromSeed(deviceSeed)
if err != nil {
t.Fatal(err)
}
at := time.Unix(fixtureNow, 0)
cert, err := identity.IssueCert(root, devKey.PublicKeyHex(), at.Add(-time.Hour), at.Add(90*24*time.Hour))
if err != nil {
t.Fatal(err)
}
dev := &identity.Device{Key: devKey, Cert: cert}
l := &listing.Listing{ID: "00112233445566778899aabbccddeeff", Author: cert.Author, Device: cert.Device}
ref := Ref{Author: l.Author, ID: l.ID}
threadSecret := bytes.Repeat([]byte{0x11}, 32)
tk, err := ThreadKeyFromBytes(threadSecret)
if err != nil {
t.Fatal(err)
}
mailbox, _ := tk.Mailbox()
f := &fixtureFile{
Now: fixtureNow, Difficulty: fixtureDifficulty, Listing: ref, Device: cert.Device,
DeviceSeed: hex.EncodeToString(deviceSeed), ThreadSecret: hex.EncodeToString(threadSecret),
ThreadPublic: tk.PublicHex(), Mailbox: mailbox,
}
fill := func(e *Envelope, p *Plain, esk []byte) fixtureEnvelope {
canon, _ := e.Bytes()
hash, _ := e.Hash()
work, _ := e.Work()
plain, _ := json.Marshal(p)
pc, _ := jcs.Marshal(p) // p was filled in by sealing: thread, and the owner's signature
padded, _ := pad(pc)
return fixtureEnvelope{
EphemeralSecret: hex.EncodeToString(esk), Plain: plain, PlainCanonical: string(pc),
PaddedLen: len(padded), Canonical: string(canon), Hash: hash, Work: work,
}
}
// Awkward text on purpose: umlauts, an emoji, a newline and U+2028.
esk1 := bytes.Repeat([]byte{0x22}, 32)
withEntropy(t, esk1)
hello := &Plain{Type: TypeText, N: 1, SentAt: fixtureNow,
Text: "Guten Tag, ist die Wohnung noch frei? Schöne Grüße \U0001F3E0\nZeile 2
Zeile 3"}
e1, err := SealToOwner(l, tk, hello, at, fixtureDifficulty)
if err != nil {
t.Fatal(err)
}
f.ToOwner = fill(e1, hello, esk1)
esk2 := bytes.Repeat([]byte{0x33}, 32)
withEntropy(t, esk2)
grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: fixtureNow,
Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 123456",
Note: "Samstag 10 Uhr, bitte zweimal klingeln \U0001F514", ValidUntil: fixtureNow + 7*24*3600}
e2, err := SealToBuyer(dev, ref, grant, at, fixtureDifficulty)
if err != nil {
t.Fatal(err)
}
// The grant now carries the owner's certificate and signature.
f.ToBuyer = fill(e2, grant, esk2)
for _, c := range []struct {
text string
link bool
}{
{"Guten Tag, ist die Wohnung noch frei?", false},
{"Ich komme z. B. am Samstag, ca. 10 Uhr.", false},
{"Preis 1.200 Euro, ok? Ja. Gut.", false},
{"Hallo, wir sind 2 Personen (u.a. Nichtraucher).", false},
{"schaut mal https://example.com/x", true},
{"WWW.example", true},
{"auf beispiel.de gibt es mehr", true},
{"mail an max@example.com", true},
{"Hallo.Ich komme morgen", true},
{"Beispiel.DE", true},
{"auf straße-1.com", true},
{"bit.ly/abc", true},
} {
if got := ContainsLink(c.text); got != c.link {
t.Fatalf("ContainsLink(%q) = %v, want %v", c.text, got, c.link)
}
f.Links = append(f.Links, linkCase{c.text, c.link})
}
return f
}
func TestGoldenFixture(t *testing.T) {
f := buildFixture(t)
got, err := json.MarshalIndent(f, "", " ")
if err != nil {
t.Fatal(err)
}
got = append(got, '\n')
if os.Getenv("UPDATE_FIXTURES") != "" {
if err := os.MkdirAll("testdata", 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(fixturePath, got, 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(fixturePath)
if err != nil {
t.Fatalf("%v (create it with UPDATE_FIXTURES=1)", err)
}
if !bytes.Equal(got, want) {
t.Fatal("fixture is out of date: the wire format changed; if intended, refresh with UPDATE_FIXTURES=1 and update the TypeScript side")
}
// The fixture must be self-consistent: both envelopes pass the relay
// checks and open with the keys from the file.
for name, c := range map[string]fixtureEnvelope{"to_owner": f.ToOwner, "to_buyer": f.ToBuyer} {
var e Envelope
if err := json.Unmarshal([]byte(c.Canonical), &e); err != nil {
t.Fatal(err)
}
if err := e.Check(time.Unix(fixtureNow, 0), fixtureDifficulty); err != nil {
t.Errorf("%s: %v", name, err)
}
}
}