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>
This commit is contained in:
2026-11-17 19:44:59 +01:00
co-authored by Claude Sonnet 5.5
parent b9e1b0c058
commit 3b0351c774
45 changed files with 8228 additions and 292 deletions
+354
View File
@@ -0,0 +1,354 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
)
func (f *fixture) publish(t *testing.T) *listing.Listing {
t.Helper()
code, body := f.do(t, "POST", "/api/v1/listings", draftJSON, true)
if code != 200 {
t.Fatalf("create: %d %s", code, body)
}
var l listing.Listing
if err := json.Unmarshal(body, &l); err != nil {
t.Fatal(err)
}
return &l
}
// send posts an envelope the way a buyer's browser does (no token).
func (f *fixture) send(t *testing.T, e *message.Envelope) (int, []byte) {
t.Helper()
b, err := e.Bytes()
if err != nil {
t.Fatal(err)
}
return f.sendRaw(t, b)
}
func (f *fixture) sendRaw(t *testing.T, b []byte) (int, []byte) {
t.Helper()
resp, err := http.Post(f.srv.URL+"/api/v1/messages", "application/json", bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var buf bytes.Buffer
buf.ReadFrom(resp.Body)
return resp.StatusCode, buf.Bytes()
}
func buyerHello(t *testing.T, l *listing.Listing, tk *message.ThreadKey, text string) *message.Envelope {
t.Helper()
p := &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: text}
e, err := message.SealToOwner(l, tk, p, time.Now(), msgDifficulty)
if err != nil {
t.Fatal(err)
}
return e
}
func newThread(t *testing.T) *message.ThreadKey {
t.Helper()
tk, err := message.NewThreadKey()
if err != nil {
t.Fatal(err)
}
return tk
}
func TestMessagingOverHTTP(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
tk := newThread(t)
thread := tk.PublicHex()
// 1. The buyer's browser posts an encrypted envelope. No token.
code, body := f.send(t, buyerHello(t, l, tk, "Ist die Wohnung noch frei?"))
if code != http.StatusAccepted || !bytes.Contains(body, []byte(`"hash"`)) {
t.Fatalf("post: %d %s", code, body)
}
// 2. The owner sees one conversation, with the decrypted text.
code, body = f.do(t, "GET", "/api/v1/inbox", "", true)
var threads []threadView
if code != 200 || json.Unmarshal([]byte(body), &threads) != nil || len(threads) != 1 {
t.Fatalf("inbox: %d %s", code, body)
}
if threads[0].Listing != l.ID || threads[0].Thread != thread || threads[0].Replied || threads[0].Messages != 1 {
t.Fatalf("thread summary: %+v", threads[0])
}
path := "/api/v1/inbox/" + l.ID + "/" + thread
code, body = f.do(t, "GET", path, "", true)
var msgs []messageView
if code != 200 || json.Unmarshal([]byte(body), &msgs) != nil || len(msgs) != 1 || msgs[0].Text != "Ist die Wohnung noch frei?" || msgs[0].Dir != "in" {
t.Fatalf("thread: %d %s", code, body)
}
// 3. The owner answers with text, then saves the address and grants it.
if code, body = f.do(t, "POST", path, `{"type":"text","text":"Ja, noch frei."}`, true); code != 200 {
t.Fatalf("reply: %d %s", code, body)
}
if code, body = f.do(t, "PUT", "/api/v1/listings/"+l.ID+"/address",
`{"address":"Musterstraße 12, 20255 Hamburg","phone":"+49 40 1"}`, true); code != 204 {
t.Fatalf("put address: %d %s", code, body)
}
if code, body = f.do(t, "POST", path,
`{"type":"grant","note":"Samstag 10 Uhr, bitte zweimal klingeln","valid_days":3}`, true); code != 200 {
t.Fatalf("grant: %d %s", code, body)
}
// 4. The buyer polls its mailbox and decrypts both, verified as the owner's.
mb, _ := tk.Mailbox()
resp, err := http.Get(f.srv.URL + "/api/v1/messages?mailbox=" + mb)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 || resp.Header.Get("Cache-Control") != "no-store" || resp.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatalf("mailbox headers: %d %v", resp.StatusCode, resp.Header)
}
var box []message.Envelope
if err := json.NewDecoder(resp.Body).Decode(&box); err != nil || len(box) != 2 {
t.Fatalf("mailbox: %d envelopes, %v", len(box), err)
}
var sawText, sawGrant bool
for i := range box {
p, err := box[i].OpenAsBuyer(tk)
if err != nil {
t.Fatalf("buyer cannot open a reply: %v", err)
}
switch p.Type {
case message.TypeText:
sawText = p.Text == "Ja, noch frei."
case message.TypeGrant:
sawGrant = p.Address == "Musterstraße 12, 20255 Hamburg" && p.Phone == "+49 40 1" &&
p.Note == "Samstag 10 Uhr, bitte zweimal klingeln"
}
}
if !sawText || !sawGrant {
t.Fatalf("text=%v grant=%v", sawText, sawGrant)
}
// The owner's view now shows the replies too and marks the thread answered.
_, body = f.do(t, "GET", "/api/v1/inbox", "", true)
_ = json.Unmarshal([]byte(body), &threads)
if !threads[0].Replied || threads[0].Messages != 3 {
t.Fatalf("after replying: %+v", threads[0])
}
// 5. Erasing the conversation removes it from the node.
if code, _ = f.do(t, "DELETE", path, "", true); code != 204 {
t.Fatalf("delete: %d", code)
}
if code, _ = f.do(t, "GET", path, "", true); code != 404 {
t.Fatalf("deleted thread still served: %d", code)
}
}
func TestHiddenFirstMessageTextIsWithheld(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
tk := newThread(t)
if code, body := f.send(t, buyerHello(t, l, tk, "Hier: https://example.com/kaution")); code != 202 {
t.Fatalf("post: %d %s", code, body)
}
code, body := f.do(t, "GET", "/api/v1/inbox/"+l.ID+"/"+tk.PublicHex(), "", true)
if code != 200 || bytes.Contains(body, []byte("example.com")) {
t.Fatalf("the link text must not be served: %d %s", code, body)
}
var msgs []messageView
_ = json.Unmarshal([]byte(body), &msgs)
if len(msgs) != 1 || !msgs[0].Hidden || msgs[0].Reason == "" {
t.Fatalf("message should be marked hidden: %+v", msgs)
}
}
func TestPostingRules(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
good := buyerHello(t, l, newThread(t), "hallo")
goodBytes, _ := good.Bytes()
// Not canonical: same content, different spelling.
var pretty bytes.Buffer
_ = json.Indent(&pretty, goodBytes, "", " ")
for name, tc := range map[string]struct {
body []byte
want int
}{
"not JSON": {[]byte("hello"), 400},
"not canonical": {pretty.Bytes(), 400},
"unknown field": {bytes.Replace(goodBytes, []byte(`{"created_at"`), []byte(`{"extra":1,"created_at"`), 1), 400},
"too large": {bytes.Repeat([]byte("a"), message.MaxSize+100), 413},
"empty": {nil, 400},
"unknown listing": {func() []byte {
other := *l
other.ID = strings.Repeat("ab", 16)
e := buyerHello(t, &other, newThread(t), "x")
b, _ := e.Bytes()
return b
}(), 404},
"weak work": {func() []byte {
for {
e, err := message.SealToOwner(l, newThread(t), &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: "x"}, time.Now(), 0)
if err != nil {
t.Fatal(err)
}
if w, _ := e.Work(); w < msgDifficulty {
b, _ := e.Bytes()
return b
}
}
}(), 400},
} {
if code, body := f.sendRaw(t, tc.body); code != tc.want {
t.Errorf("%s: %d %s, want %d", name, code, body, tc.want)
}
}
if code, body := f.sendRaw(t, goodBytes); code != 202 {
t.Fatalf("the valid one: %d %s", code, body)
}
// Posting it again is harmless.
if code, _ := f.sendRaw(t, goodBytes); code != 202 {
t.Fatalf("duplicate: %d", code)
}
}
func TestPostingIsRateLimited(t *testing.T) {
f := newFixture(t, token, func(c *Config) { c.PostsPerMinute = 3 })
l := f.publish(t)
for i := 0; i < 3; i++ {
if code, body := f.send(t, buyerHello(t, l, newThread(t), "hallo")); code != 202 {
t.Fatalf("post %d: %d %s", i, code, body)
}
}
resp, err := http.Post(f.srv.URL+"/api/v1/messages", "application/json", strings.NewReader("{}"))
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 429 || resp.Header.Get("Retry-After") == "" {
t.Fatalf("fourth post: %d retry-after=%q", resp.StatusCode, resp.Header.Get("Retry-After"))
}
}
func TestMailboxQueryIsValidated(t *testing.T) {
f := newFixture(t, token)
for _, q := range []string{
"", "?mailbox=zz", "?mailbox=" + strings.Repeat("A", 32), "?mailbox=" + strings.Repeat("0", 31),
"?mailbox=" + strings.Repeat("0", 32) + "&since=-1", "?mailbox=" + strings.Repeat("0", 32) + "&limit=0",
"?mailbox=" + strings.Repeat("0", 32) + "&limit=1000", "?mailbox=" + strings.Repeat("0", 32) + "&since=abc",
} {
if code, _ := f.do(t, "GET", "/api/v1/messages"+q, "", false); code != 400 {
t.Errorf("%q: %d, want 400", q, code)
}
}
code, body := f.do(t, "GET", "/api/v1/messages?mailbox="+strings.Repeat("0", 32), "", false)
if code != 200 || string(body) != "[]" {
t.Fatalf("empty mailbox: %d %s", code, body)
}
}
func TestOwnerEndpointsNeedTheToken(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
thread := strings.Repeat("ab", 32)
for _, c := range []struct{ method, path string }{
{"GET", "/api/v1/inbox"},
{"GET", "/api/v1/inbox/" + l.ID + "/" + thread},
{"POST", "/api/v1/inbox/" + l.ID + "/" + thread},
{"DELETE", "/api/v1/inbox/" + l.ID + "/" + thread},
{"PUT", "/api/v1/listings/" + l.ID + "/address"},
{"GET", "/api/v1/listings/" + l.ID + "/address"},
{"DELETE", "/api/v1/listings/" + l.ID + "/address"},
} {
if code, _ := f.do(t, c.method, c.path, "{}", false); code != 401 {
t.Errorf("%s %s without token: %d, want 401", c.method, c.path, code)
}
}
}
func TestReplyErrors(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
tk := newThread(t)
f.send(t, buyerHello(t, l, tk, "hallo"))
path := "/api/v1/inbox/" + l.ID + "/" + tk.PublicHex()
f.do(t, "GET", "/api/v1/inbox", "", true) // collect
for name, c := range map[string]struct {
path, body string
want int
}{
"unknown thread": {"/api/v1/inbox/" + l.ID + "/" + strings.Repeat("ab", 32), `{"type":"text","text":"x"}`, 404},
"malformed thread": {"/api/v1/inbox/" + l.ID + "/xyz", `{"type":"text","text":"x"}`, 400},
"unknown field": {path, `{"type":"text","text":"x","bogus":1}`, 400},
"grant with no address": {path, `{"type":"grant"}`, 400},
"grant for 31 days": {path, `{"type":"grant","address":"Weg 1","valid_days":31}`, 400},
"empty text": {path, `{"type":"text","text":""}`, 400},
"unknown type": {path, `{"type":"image"}`, 400},
"text over the limit": {path, `{"type":"text","text":"` + strings.Repeat("a", message.MaxText+1) + `"}`, 400},
"trailing data": {path, `{"type":"text","text":"x"} {}`, 400},
"someone else's listing": {"/api/v1/inbox/" + strings.Repeat("cd", 16) + "/" + tk.PublicHex(), `{"type":"text","text":"x"}`, 404},
} {
if code, body := f.do(t, "POST", c.path, c.body, true); code != c.want {
t.Errorf("%s: %d %s, want %d", name, code, body, c.want)
}
}
}
func TestAddressEndpoints(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
path := "/api/v1/listings/" + l.ID + "/address"
if code, _ := f.do(t, "GET", path, "", true); code != 404 {
t.Fatalf("before saving: %d", code)
}
if code, body := f.do(t, "PUT", path, `{"address":"Weg 1, 20095 Hamburg","email":"a@example.com"}`, true); code != 204 {
t.Fatalf("put: %d %s", code, body)
}
code, body := f.do(t, "GET", path, "", true)
if code != 200 || !strings.Contains(string(body), "Weg 1") || !strings.Contains(string(body), "a@example.com") {
t.Fatalf("get: %d %s", code, body)
}
// The exact address is nowhere on the public side.
if _, pub := f.do(t, "GET", "/api/v1/listings/"+l.Author+"/"+l.ID, "", false); strings.Contains(string(pub), "Weg 1") {
t.Fatal("the address leaked into the public listing")
}
if code, _ := f.do(t, "PUT", path, `{"address":""}`, true); code != 400 {
t.Errorf("empty address: %d", code)
}
if code, _ := f.do(t, "PUT", path, `{"address":"`+strings.Repeat("a", message.MaxAddress+1)+`"}`, true); code != 400 {
t.Errorf("long address: %d", code)
}
if code, _ := f.do(t, "PUT", "/api/v1/listings/"+strings.Repeat("cd", 16)+"/address", `{"address":"x"}`, true); code != 404 {
t.Errorf("someone else's listing: %d", code)
}
if code, _ := f.do(t, "DELETE", path, "", true); code != 204 {
t.Fatalf("delete: %d", code)
}
if code, _ := f.do(t, "GET", path, "", true); code != 404 {
t.Fatalf("address survived deletion: %d", code)
}
}
func TestStatusReportsMessageDifficulty(t *testing.T) {
f := newFixture(t, token)
_, body := f.do(t, "GET", "/api/v1/status", "", false)
var st map[string]any
_ = json.Unmarshal(body, &st)
if st["message_difficulty"] != float64(msgDifficulty) {
t.Fatalf("message_difficulty = %v", st["message_difficulty"])
}
}