Files
allmende/internal/inbox/inbox_test.go
T
nilsandClaude Sonnet 5.5 13c82f8d59 messaging: owners can block a conversation
A blocked thread key is dropped unread (not announced, not counted against
the daily new-conversation limit). API, UI button with confirmation, and a
list with unblock.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-18 20:50:38 +01:00

480 lines
15 KiB
Go

package inbox
import (
"context"
"errors"
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
listingDifficulty = 6
msgDifficulty = 4
region = "u1x"
)
var (
ctx = context.Background()
t0 = time.Unix(1_800_000_000, 0)
)
// relay stands in for the network: it stores what the owner publishes, like
// a gateway would.
type relay struct {
st *store.Store
sent []*message.Envelope
fail error
}
func (r *relay) PublishMessage(ctx context.Context, region string, e *message.Envelope) error {
if r.fail != nil {
return r.fail
}
if _, err := r.st.PutMessage(ctx, region, e); err != nil {
return err
}
r.sent = append(r.sent, e)
return nil
}
type fixture struct {
t *testing.T
now time.Time
st *store.Store
dev *identity.Device
relay *relay
in *Inbox
}
func newFixture(t *testing.T, maxNew int) *fixture {
t.Helper()
f := &fixture{t: t, now: t0}
root, _, _ := identity.NewRoot()
dev, err := identity.Enroll(root, t0.Add(-time.Hour), 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
f.dev = dev
f.st, err = store.Open(":memory:", store.Options{
Difficulty: listingDifficulty, MessageDifficulty: msgDifficulty,
Clock: func() time.Time { return f.now },
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { f.st.Close() })
f.relay = &relay{st: f.st}
f.in = &Inbox{Store: f.st, Device: dev, Publisher: f.relay, Difficulty: msgDifficulty,
MaxNewThreads: maxNew, Clock: func() time.Time { return f.now }}
return f
}
func (f *fixture) listing() *listing.Listing {
f.t.Helper()
id, _ := listing.NewID()
l := &listing.Listing{
Version: listing.Version, ID: id, Seq: 1, CreatedAt: f.now.Unix(),
ExpiresAt: f.now.Add(7 * 24 * time.Hour).Unix(), Kind: "rent", Category: "apartment",
Geohash: "u1xjhx", Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"},
Title: "Wohnung",
}
if err := l.Seal(f.dev, listingDifficulty); err != nil {
f.t.Fatal(err)
}
if _, err := f.st.Put(ctx, l); err != nil {
f.t.Fatal(err)
}
return l
}
// buyer sends a message with exactly `work` bits of proof-of-work.
func (f *fixture) buyer(l *listing.Listing, tk *message.ThreadKey, n int64, text string, work int) {
f.t.Helper()
for {
p := &message.Plain{Type: message.TypeText, N: n, SentAt: f.now.Unix() + n, Text: text}
e, err := message.SealToOwner(l, tk, p, f.now, work)
if err != nil {
f.t.Fatal(err)
}
if w, _ := e.Work(); w != work {
continue
}
if _, err := f.st.PutMessage(ctx, region, e); err != nil {
f.t.Fatal(err)
}
return
}
}
func (f *fixture) newThread() *message.ThreadKey {
f.t.Helper()
tk, err := message.NewThreadKey()
if err != nil {
f.t.Fatal(err)
}
return tk
}
func (f *fixture) collect() int {
f.t.Helper()
n, err := f.in.Collect(ctx)
if err != nil {
f.t.Fatal(err)
}
return n
}
func TestCollectFilesConversationsOnce(t *testing.T) {
f := newFixture(t, 0)
l, l2 := f.listing(), f.listing()
a, b := f.newThread(), f.newThread()
f.buyer(l, a, 1, "Ist die Wohnung noch frei?", msgDifficulty)
f.buyer(l, a, 2, "Ich könnte morgen vorbeikommen.", msgDifficulty)
f.buyer(l2, b, 1, "Guten Tag", msgDifficulty)
if n := f.collect(); n != 3 {
t.Fatalf("collected %d, want 3", n)
}
if n := f.collect(); n != 0 {
t.Fatalf("a second collection added %d", n)
}
threads, err := f.st.Threads(ctx, l.Author)
if err != nil || len(threads) != 2 {
t.Fatalf("threads = %d, %v", len(threads), err)
}
msgs, _ := f.st.ThreadMessages(ctx, message.Ref{Author: l.Author, ID: l.ID}, a.PublicHex())
if len(msgs) != 2 || msgs[0].Plain.Text != "Ist die Wohnung noch frei?" || msgs[1].Plain.N != 2 {
t.Fatalf("conversation is wrong: %+v", msgs)
}
for _, m := range msgs {
if m.Dir != store.InboxIn || m.Hidden {
t.Fatalf("unexpected %+v", m)
}
}
}
func TestArrivalsAreAnnouncedOnceAndWithoutText(t *testing.T) {
f := newFixture(t, 0)
var calls [][]Arrival
f.in.OnArrivals = func(a []Arrival) { calls = append(calls, a) }
l := f.listing()
ref := message.Ref{Author: l.Author, ID: l.ID}
a, b, spam := f.newThread(), f.newThread(), f.newThread()
if f.collect(); len(calls) != 0 {
t.Fatalf("nothing arrived but %d calls were made", len(calls))
}
f.buyer(l, a, 1, "Ist die Wohnung noch frei?", msgDifficulty)
f.buyer(l, a, 2, "Ich könnte morgen vorbeikommen.", msgDifficulty)
f.buyer(l, b, 1, "Guten Tag", msgDifficulty)
f.buyer(l, spam, 1, "Schaut euch https://example.com/x an", msgDifficulty) // hidden
f.collect()
if len(calls) != 1 {
t.Fatalf("one collection must make one call, got %d", len(calls))
}
got := calls[0]
if len(got) != 3 {
t.Fatalf("got %d arrivals, want 3 (the hidden one is not announced): %+v", len(got), got)
}
starts := 0
for _, x := range got {
if x.Listing != ref {
t.Errorf("wrong listing %+v", x.Listing)
}
if x.Thread == spam.PublicHex() {
t.Error("a hidden message was announced")
}
if x.New {
starts++
}
}
if starts != 2 {
t.Errorf("%d conversations started, want 2 (a and b)", starts)
}
// Nothing new: no repeat. A further message in a known conversation is not a start.
if f.collect(); len(calls) != 1 {
t.Fatalf("a second collection announced again: %d calls", len(calls))
}
f.buyer(l, a, 3, "Noch da?", msgDifficulty)
f.collect()
if len(calls) != 2 || len(calls[1]) != 1 || calls[1][0].New || calls[1][0].Thread != a.PublicHex() {
t.Fatalf("follow-up not announced as a plain message in a: %+v", calls)
}
}
func TestLinksInFirstMessagesAreHiddenUntilTheOwnerReplies(t *testing.T) {
f := newFixture(t, 0)
l := f.listing()
ref := message.Ref{Author: l.Author, ID: l.ID}
tk := f.newThread()
f.buyer(l, tk, 1, "Schaut euch https://example.com/kaution an", msgDifficulty)
f.buyer(l, tk, 2, strings.Repeat("x", message.MaxFirstText+1), msgDifficulty)
f.collect()
msgs, _ := f.st.ThreadMessages(ctx, ref, tk.PublicHex())
if len(msgs) != 2 || !msgs[0].Hidden || !msgs[1].Hidden {
t.Fatalf("violating first messages must be hidden: %+v", msgs)
}
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{Type: message.TypeText, Text: "Hallo!"}); err != nil {
t.Fatal(err)
}
f.buyer(l, tk, 3, "Hier ist mein Profil: https://example.com/me", msgDifficulty)
f.collect()
msgs, _ = f.st.ThreadMessages(ctx, ref, tk.PublicHex())
for _, m := range msgs {
if m.Dir != store.InboxIn {
continue
}
wantHidden := m.Plain.N < 3 // the first two broke the rules before any reply
if m.Hidden != wantHidden {
t.Errorf("message %d: hidden = %v, want %v", m.Plain.N, m.Hidden, wantHidden)
}
}
}
func TestNewConversationsAreLimitedPerDay(t *testing.T) {
f := newFixture(t, 2)
l := f.listing()
ref := message.Ref{Author: l.Author, ID: l.ID}
weakest := f.newThread()
f.buyer(l, weakest, 1, "schwach", 4)
strong := f.newThread()
f.buyer(l, strong, 1, "stark", 10)
mid := f.newThread()
f.buyer(l, mid, 1, "mittel", 7)
mid2 := f.newThread()
f.buyer(l, mid2, 1, "mittel2", 7)
f.collect()
has := func(tk *message.ThreadKey) bool {
ok, _ := f.st.HasThread(ctx, ref, tk.PublicHex())
return ok
}
if !has(strong) || !(has(mid) != has(mid2)) || has(weakest) {
t.Fatalf("room for 2 goes to the strongest: strong=%v mid=%v mid2=%v weakest=%v",
has(strong), has(mid), has(mid2), has(weakest))
}
// Follow-ups to an existing conversation are never held back.
f.buyer(l, strong, 2, "noch eine Frage", 4)
if n := f.collect(); n != 1 {
t.Fatalf("follow-up not filed (%d)", n)
}
// The waiting ones stay queued and are not marked as seen...
if has(weakest) {
t.Fatal("limit exceeded")
}
// ...so they get in once a day has passed and the window has moved on.
f.now = f.now.Add(25 * time.Hour)
f.collect()
if !has(weakest) || !has(mid) || !has(mid2) {
t.Fatalf("queued conversations should be admitted the next day: weakest=%v mid=%v mid2=%v",
has(weakest), has(mid), has(mid2))
}
}
func TestRepliesReachTheBuyerAndAreSigned(t *testing.T) {
f := newFixture(t, 0)
l := f.listing()
ref := message.Ref{Author: l.Author, ID: l.ID}
tk := f.newThread()
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
f.collect()
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{Type: message.TypeText, Text: "Ja, noch frei."}); err != nil {
t.Fatal(err)
}
if err := f.st.SetAddress(ctx, ref, store.Address{Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 1"}); err != nil {
t.Fatal(err)
}
// A grant prefilled from the saved address, with the owner's own words.
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{
Type: message.TypeGrant, Note: "Samstag 10 Uhr, bitte zweimal klingeln", ValidDays: 3,
}); err != nil {
t.Fatal(err)
}
mb, _ := tk.Mailbox()
box, err := f.st.Mailbox(ctx, mb, 0, 10)
if err != nil || len(box) != 2 {
t.Fatalf("mailbox = %d, %v", len(box), err)
}
var text, grant *message.Plain
for _, e := range box {
p, err := e.OpenAsBuyer(tk)
if err != nil {
t.Fatalf("buyer cannot open a reply: %v", err)
}
if p.Type == message.TypeGrant {
grant = p
} else {
text = p
}
}
if text == nil || text.Text != "Ja, noch frei." || text.N != 1 {
t.Fatalf("text reply: %+v", text)
}
if grant == nil || grant.Address != "Musterstraße 12, 20255 Hamburg" || grant.Phone != "+49 40 1" ||
grant.Note != "Samstag 10 Uhr, bitte zweimal klingeln" || grant.N != 2 ||
grant.ValidUntil != f.now.Add(3*24*time.Hour).Unix() {
t.Fatalf("grant: %+v", grant)
}
// The conversation keeps both our replies, in order.
msgs, _ := f.st.ThreadMessages(ctx, ref, tk.PublicHex())
var outs int
for _, m := range msgs {
if m.Dir == store.InboxOut {
outs++
}
}
if outs != 2 {
t.Fatalf("recorded %d outgoing messages, want 2", outs)
}
}
func TestSendRefusals(t *testing.T) {
f := newFixture(t, 0)
l := f.listing()
ref := message.Ref{Author: l.Author, ID: l.ID}
tk := f.newThread()
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
f.collect()
th := tk.PublicHex()
if _, err := f.in.Send(ctx, ref, strings.Repeat("ab", 32), Reply{Type: message.TypeText, Text: "x"}); !errors.Is(err, ErrNoThread) {
t.Errorf("unknown thread: %v", err)
}
if _, err := f.in.Send(ctx, message.Ref{Author: strings.Repeat("cd", 32), ID: l.ID}, th, Reply{Type: message.TypeText, Text: "x"}); !errors.Is(err, ErrNotOwner) {
t.Errorf("foreign listing: %v", err)
}
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeGrant}); err == nil || !strings.Contains(err.Error(), "no address") {
t.Errorf("grant without any address: %v", err)
}
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeGrant, Address: "Weg 1", ValidDays: 31}); err == nil {
t.Error("a grant valid for 31 days was accepted")
}
if _, err := f.in.Send(ctx, ref, th, Reply{Type: "image"}); err == nil {
t.Error("unknown reply type accepted")
}
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeText, Text: ""}); err == nil {
t.Error("empty reply accepted")
}
// A failed publish leaves nothing behind.
f.relay.fail = errors.New("network down")
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeText, Text: "x"}); err == nil {
t.Error("publish failure was swallowed")
}
msgs, _ := f.st.ThreadMessages(ctx, ref, th)
if len(msgs) != 1 {
t.Fatalf("a failed send was recorded: %d messages", len(msgs))
}
}
func TestAddressesAndThreadsCanBeErased(t *testing.T) {
f := newFixture(t, 0)
l := f.listing()
ref := message.Ref{Author: l.Author, ID: l.ID}
tk := f.newThread()
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
f.collect()
if _, err := f.st.GetAddress(ctx, ref); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("address before saving: %v", err)
}
f.st.SetAddress(ctx, ref, store.Address{Address: "A"})
f.st.SetAddress(ctx, ref, store.Address{Address: "B", Email: "x@example.com"})
if a, _ := f.st.GetAddress(ctx, ref); a.Address != "B" || a.Email != "x@example.com" {
t.Fatalf("address was not replaced: %+v", a)
}
f.st.DeleteAddress(ctx, ref)
if _, err := f.st.GetAddress(ctx, ref); !errors.Is(err, store.ErrNotFound) {
t.Fatal("address survived deletion")
}
if ok, _ := f.st.DeleteThread(ctx, ref, tk.PublicHex()); !ok {
t.Fatal("thread not deleted")
}
if th, _ := f.st.Threads(ctx, l.Author); len(th) != 0 {
t.Fatal("thread survived deletion")
}
// The envelope was marked seen, so deleting a thread does not resurrect it.
if n := f.collect(); n != 0 {
t.Fatalf("an erased conversation came back (%d)", n)
}
}
func TestABlockedConversationStaysSilentAndFreesNothingElse(t *testing.T) {
f := newFixture(t, 1) // one new conversation per day
l := f.listing()
ref := message.Ref{Author: l.Author, ID: l.ID}
var announced int
f.in.OnArrivals = func(a []Arrival) { announced += len(a) }
spam := f.newThread()
f.buyer(l, spam, 1, "Hallo", msgDifficulty)
f.collect()
if err := f.in.Block(ctx, ref, spam.PublicHex()); err != nil {
t.Fatal(err)
}
if th, _ := f.st.Threads(ctx, l.Author); len(th) != 0 {
t.Fatal("the blocked conversation is still listed")
}
announced = 0
// The buyer keeps writing in the same thread: nothing is filed or announced.
f.buyer(l, spam, 2, "Hallo?", msgDifficulty)
f.buyer(l, spam, 3, "Antwortet bitte", msgDifficulty)
if n := f.collect(); n != 0 || announced != 0 {
t.Fatalf("a blocked thread got through: filed %d, announced %d", n, announced)
}
if th, _ := f.st.Threads(ctx, l.Author); len(th) != 0 {
t.Fatal("a blocked thread reappeared")
}
// Blocking is per thread: someone else (here under a new daily budget) is heard.
f.now = f.now.Add(25 * time.Hour)
other := f.newThread()
f.buyer(l, other, 1, "Guten Tag", msgDifficulty)
if n := f.collect(); n != 1 {
t.Fatalf("another buyer was not heard: %d", n)
}
// The block can be lifted; the buyer's later messages arrive again.
if err := f.in.Unblock(ctx, ref, spam.PublicHex()); err != nil {
t.Fatal(err)
}
f.now = f.now.Add(25 * time.Hour) // it starts a new conversation, which the daily limit applies to
f.buyer(l, spam, 4, "Noch da?", msgDifficulty)
f.collect()
if th, _ := f.st.Threads(ctx, l.Author); len(th) != 2 {
t.Fatalf("after unblocking, %d conversations, want 2", len(th))
}
}
func TestBlockingNeedsAnExistingConversationOfYours(t *testing.T) {
f := newFixture(t, 0)
l := f.listing()
tk := f.newThread()
if err := f.in.Block(ctx, message.Ref{Author: l.Author, ID: l.ID}, tk.PublicHex()); !errors.Is(err, ErrNoThread) {
t.Fatalf("blocking an unknown thread: %v", err)
}
if err := f.in.Block(ctx, message.Ref{Author: "someone-else", ID: l.ID}, tk.PublicHex()); !errors.Is(err, ErrNotOwner) {
t.Fatalf("blocking another author's listing: %v", err)
}
if err := f.in.Unblock(ctx, message.Ref{Author: l.Author, ID: l.ID}, tk.PublicHex()); !errors.Is(err, ErrNoThread) {
t.Fatalf("unblocking a thread that is not blocked: %v", err)
}
}