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:
+31
-2
@@ -19,6 +19,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/inbox"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
@@ -39,10 +40,20 @@ type Config struct {
|
||||
Token string // admin bearer token; empty disables all writes
|
||||
Difficulty int
|
||||
Clock func() time.Time
|
||||
|
||||
// MessageDifficulty is reported to browsers so they can mine the
|
||||
// proof-of-work of the messages they send.
|
||||
MessageDifficulty int
|
||||
// PostsPerMinute limits envelopes accepted per client address; 0 means 30.
|
||||
PostsPerMinute int
|
||||
// Inbox is the owner's conversations. Without it the owner endpoints are
|
||||
// absent; relaying messages for buyers still works.
|
||||
Inbox *inbox.Inbox
|
||||
}
|
||||
|
||||
type server struct {
|
||||
Config
|
||||
limiter *limiter
|
||||
}
|
||||
|
||||
// New returns the HTTP handler.
|
||||
@@ -50,7 +61,10 @@ func New(cfg Config) http.Handler {
|
||||
if cfg.Clock == nil {
|
||||
cfg.Clock = time.Now
|
||||
}
|
||||
s := &server{cfg}
|
||||
if cfg.PostsPerMinute <= 0 {
|
||||
cfg.PostsPerMinute = defaultPostsPerMinute
|
||||
}
|
||||
s := &server{Config: cfg, limiter: newLimiter(cfg.PostsPerMinute, time.Minute, cfg.Clock)}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/v1/status", s.status)
|
||||
mux.HandleFunc("GET /api/v1/listings", s.search)
|
||||
@@ -58,6 +72,20 @@ func New(cfg Config) http.Handler {
|
||||
mux.HandleFunc("POST /api/v1/listings", s.admin(s.create))
|
||||
mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update))
|
||||
mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove))
|
||||
|
||||
// Messaging: public relay endpoints for buyers' browsers...
|
||||
mux.HandleFunc("POST /api/v1/messages", s.postMessage)
|
||||
mux.HandleFunc("GET /api/v1/messages", s.getMailbox)
|
||||
// ...and the owner's inbox and private address, behind the admin token.
|
||||
if cfg.Inbox != nil {
|
||||
mux.HandleFunc("GET /api/v1/inbox", s.admin(s.listThreads))
|
||||
mux.HandleFunc("GET /api/v1/inbox/{id}/{thread}", s.admin(s.getThread))
|
||||
mux.HandleFunc("POST /api/v1/inbox/{id}/{thread}", s.admin(s.reply))
|
||||
mux.HandleFunc("DELETE /api/v1/inbox/{id}/{thread}", s.admin(s.deleteThread))
|
||||
mux.HandleFunc("PUT /api/v1/listings/{id}/address", s.admin(s.putAddress))
|
||||
mux.HandleFunc("GET /api/v1/listings/{id}/address", s.admin(s.getAddress))
|
||||
mux.HandleFunc("DELETE /api/v1/listings/{id}/address", s.admin(s.deleteAddress))
|
||||
}
|
||||
mux.Handle("GET /", s.ui())
|
||||
return secure(mux)
|
||||
}
|
||||
@@ -106,7 +134,8 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
|
||||
"peers": s.Node.PeerCount(),
|
||||
"listings": n,
|
||||
// Lets the browser report how much anti-spam work a listing carries.
|
||||
"difficulty": s.Difficulty,
|
||||
"difficulty": s.Difficulty,
|
||||
"message_difficulty": s.MessageDifficulty,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/inbox"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
@@ -29,28 +30,37 @@ type fixture struct {
|
||||
dev *identity.Device
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T, tok string) *fixture {
|
||||
const msgDifficulty = 4
|
||||
|
||||
func newFixture(t *testing.T, tok string, tweak ...func(*Config)) *fixture {
|
||||
t.Helper()
|
||||
root, _, _ := identity.NewRoot()
|
||||
dev, err := identity.Enroll(root, time.Now().Add(-time.Hour), 90*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty})
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
node, err := p2p.New(context.Background(), p2p.Config{
|
||||
Device: dev, Store: s, Regions: []string{"u1x"}, Difficulty: difficulty,
|
||||
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
MessageDifficulty: msgDifficulty,
|
||||
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(New(Config{
|
||||
cfg := Config{
|
||||
Store: s, Node: node, Device: dev, Regions: []string{"u1x"}, Token: tok, Difficulty: difficulty,
|
||||
}))
|
||||
MessageDifficulty: msgDifficulty,
|
||||
Inbox: &inbox.Inbox{Store: s, Device: dev, Publisher: node, Difficulty: msgDifficulty},
|
||||
}
|
||||
for _, f := range tweak {
|
||||
f(&cfg)
|
||||
}
|
||||
srv := httptest.NewServer(New(cfg))
|
||||
t.Cleanup(func() { srv.Close(); node.Close(); s.Close() })
|
||||
return &fixture{srv: srv, s: s, dev: dev}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/inbox"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPostsPerMinute = 30
|
||||
maxMailboxPage = 100
|
||||
)
|
||||
|
||||
// --- public relay endpoints -------------------------------------------------
|
||||
//
|
||||
// A browser-only buyer talks to the network through these: it posts an
|
||||
// encrypted envelope and polls its mailbox. The node sees only ciphertext.
|
||||
|
||||
func (s *server) postMessage(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.limiter.allow(clientIP(r)) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
fail(w, http.StatusTooManyRequests, "too many messages from this address; try again in a minute")
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, message.MaxSize+1))
|
||||
if err != nil {
|
||||
fail(w, http.StatusRequestEntityTooLarge, "message too large")
|
||||
return
|
||||
}
|
||||
var e message.Envelope
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&e); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
// Only the canonical encoding travels, so everyone derives the same hash.
|
||||
if canon, err := e.Bytes(); err != nil || !bytes.Equal(canon, body) {
|
||||
fail(w, http.StatusBadRequest, "the envelope must be in canonical JSON form")
|
||||
return
|
||||
}
|
||||
region, err := s.Store.Region(r.Context(), e.Listing.Author, e.Listing.ID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
fail(w, http.StatusNotFound, "this node does not know that listing")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
if err := s.Node.PublishMessage(r.Context(), region, &e); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrInvalid):
|
||||
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), store.ErrInvalid.Error()+": "))
|
||||
case errors.Is(err, store.ErrNoListing):
|
||||
fail(w, http.StatusNotFound, "that listing is not live here (anymore), or its owner changed device")
|
||||
case errors.Is(err, store.ErrQueueFull):
|
||||
fail(w, http.StatusTooManyRequests, "the queue for this listing is full of messages with more proof-of-work; mine more and retry")
|
||||
default:
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
}
|
||||
return
|
||||
}
|
||||
h, _ := e.Hash()
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"hash": h})
|
||||
}
|
||||
|
||||
func (s *server) getMailbox(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
tag := q.Get("mailbox")
|
||||
if len(tag) != 32 || !isLowerHex(tag) {
|
||||
fail(w, http.StatusBadRequest, "mailbox must be 32 hex characters")
|
||||
return
|
||||
}
|
||||
var since int64
|
||||
if v := q.Get("since"); v != "" {
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil || n < 0 {
|
||||
fail(w, http.StatusBadRequest, "since must be a non-negative integer")
|
||||
return
|
||||
}
|
||||
since = n
|
||||
}
|
||||
limit := maxMailboxPage
|
||||
if v := q.Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > maxMailboxPage {
|
||||
fail(w, http.StatusBadRequest, "limit must be 1-100")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
items, err := s.Store.Mailbox(r.Context(), tag, since, limit)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
// Ciphertext addressed by an unguessable tag: any site may read it, but it
|
||||
// must not be cached, or a reply would show up late.
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte("["))
|
||||
for i, e := range items {
|
||||
b, err := e.Bytes()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if i > 0 {
|
||||
w.Write([]byte(","))
|
||||
}
|
||||
w.Write(b)
|
||||
}
|
||||
w.Write([]byte("]"))
|
||||
}
|
||||
|
||||
func isLowerHex(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// --- the owner's inbox (admin token) ------------------------------------------
|
||||
|
||||
type threadView struct {
|
||||
Listing string `json:"listing"`
|
||||
Thread string `json:"thread"`
|
||||
Messages int `json:"messages"`
|
||||
Hidden int `json:"hidden"`
|
||||
Replied bool `json:"replied"`
|
||||
FirstAt int64 `json:"first_at"`
|
||||
LastAt int64 `json:"last_at"`
|
||||
}
|
||||
|
||||
func (s *server) listThreads(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := s.Inbox.Collect(r.Context()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
threads, err := s.Store.Threads(r.Context(), s.Device.Cert.Author)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
out := make([]threadView, 0, len(threads))
|
||||
for _, t := range threads {
|
||||
out = append(out, threadView{t.Listing.ID, t.Thread, t.Messages, t.Hidden, t.Replied, t.FirstAt, t.LastAt})
|
||||
}
|
||||
noStore(w)
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
type messageView struct {
|
||||
Hash string `json:"hash"`
|
||||
Dir string `json:"dir"`
|
||||
Hidden bool `json:"hidden,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
ReceivedAt int64 `json:"received_at"`
|
||||
Type string `json:"type"`
|
||||
N int64 `json:"n"`
|
||||
SentAt int64 `json:"sent_at"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Address string `json:"address,omitempty"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
ValidUntil int64 `json:"valid_until,omitempty"`
|
||||
}
|
||||
|
||||
func (s *server) getThread(w http.ResponseWriter, r *http.Request) {
|
||||
ref, thread, ok := s.threadRef(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := s.Inbox.Collect(r.Context()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
msgs, err := s.Store.ThreadMessages(r.Context(), ref, thread)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
if len(msgs) == 0 {
|
||||
fail(w, http.StatusNotFound, "no such conversation")
|
||||
return
|
||||
}
|
||||
out := make([]messageView, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
p := m.Plain
|
||||
v := messageView{Hash: m.Hash, Dir: m.Dir, ReceivedAt: m.ReceivedAt, Type: p.Type, N: p.N, SentAt: p.SentAt,
|
||||
Text: p.Text, Address: p.Address, Phone: p.Phone, Email: p.Email, Note: p.Note, ValidUntil: p.ValidUntil}
|
||||
if m.Hidden {
|
||||
// Withheld: the buyer broke the first-message rules (a link, or too long).
|
||||
v.Hidden, v.Reason, v.Text = true, "a first message must be short and contain no links", ""
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
noStore(w)
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
type replyBody struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Address string `json:"address"`
|
||||
Phone string `json:"phone"`
|
||||
Email string `json:"email"`
|
||||
Note string `json:"note"`
|
||||
ValidDays int `json:"valid_days"`
|
||||
}
|
||||
|
||||
func (s *server) reply(w http.ResponseWriter, r *http.Request) {
|
||||
ref, thread, ok := s.threadRef(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var b replyBody
|
||||
if !decodeBody(w, r, &b) {
|
||||
return
|
||||
}
|
||||
env, err := s.Inbox.Send(r.Context(), ref, thread, inbox.Reply{
|
||||
Type: b.Type, Text: b.Text, Address: b.Address, Phone: b.Phone, Email: b.Email, Note: b.Note, ValidDays: b.ValidDays,
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
h, _ := env.Hash()
|
||||
writeJSON(w, http.StatusOK, map[string]string{"hash": h})
|
||||
case errors.Is(err, inbox.ErrNoThread), errors.Is(err, inbox.ErrNotOwner):
|
||||
fail(w, http.StatusNotFound, "no such conversation")
|
||||
case errors.Is(err, inbox.ErrInvalid):
|
||||
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), inbox.ErrInvalid.Error()+": "))
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
fail(w, http.StatusConflict, "the listing is gone, so the reply cannot be routed")
|
||||
default:
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) deleteThread(w http.ResponseWriter, r *http.Request) {
|
||||
ref, thread, ok := s.threadRef(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
found, err := s.Store.DeleteThread(r.Context(), ref, thread)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
fail(w, http.StatusNotFound, "no such conversation")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// threadRef reads {id} and {thread} from the path. The listing is always the
|
||||
// node's own: the inbox holds nobody else's conversations.
|
||||
func (s *server) threadRef(w http.ResponseWriter, r *http.Request) (message.Ref, string, bool) {
|
||||
id, thread := r.PathValue("id"), r.PathValue("thread")
|
||||
if len(id) != 32 || !isLowerHex(id) || len(thread) != 64 || !isLowerHex(thread) {
|
||||
fail(w, http.StatusBadRequest, "malformed listing id or thread")
|
||||
return message.Ref{}, "", false
|
||||
}
|
||||
return message.Ref{Author: s.Device.Cert.Author, ID: id}, thread, true
|
||||
}
|
||||
|
||||
// --- the exact address (admin token) ------------------------------------------
|
||||
|
||||
func (s *server) putAddress(w http.ResponseWriter, r *http.Request) {
|
||||
l, ok := s.own(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var a store.Address
|
||||
if !decodeBody(w, r, &a) {
|
||||
return
|
||||
}
|
||||
for _, f := range []struct {
|
||||
name, v string
|
||||
min, max int
|
||||
nl bool
|
||||
}{
|
||||
{"address", a.Address, 1, message.MaxAddress, true},
|
||||
{"phone", a.Phone, 0, message.MaxPhone, false},
|
||||
{"email", a.Email, 0, message.MaxEmail, false},
|
||||
} {
|
||||
if len(f.v) > f.max {
|
||||
fail(w, http.StatusBadRequest, f.name+" is too long")
|
||||
return
|
||||
}
|
||||
if err := listing.ValidText(f.v, f.min, f.max, f.nl); err != nil {
|
||||
fail(w, http.StatusBadRequest, f.name+": "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.Store.SetAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID}, a); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *server) getAddress(w http.ResponseWriter, r *http.Request) {
|
||||
l, ok := s.own(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
a, err := s.Store.GetAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID})
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
fail(w, http.StatusNotFound, "no address saved for this listing")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
noStore(w)
|
||||
writeJSON(w, http.StatusOK, a)
|
||||
}
|
||||
|
||||
func (s *server) deleteAddress(w http.ResponseWriter, r *http.Request) {
|
||||
l, ok := s.own(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Store.DeleteAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID}); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// --- helpers ------------------------------------------------------------------
|
||||
|
||||
func noStore(w http.ResponseWriter) { w.Header().Set("Cache-Control", "no-store") }
|
||||
|
||||
// decodeBody reads a small JSON object strictly: no unknown fields, no
|
||||
// trailing data.
|
||||
func decodeBody(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
|
||||
return false
|
||||
}
|
||||
if _, err := dec.Token(); err != io.EOF {
|
||||
fail(w, http.StatusBadRequest, "unexpected data after JSON body")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// clientIP is the peer address of the connection. Forwarding headers are not
|
||||
// trusted: they are trivial to forge. Behind a reverse proxy every client then
|
||||
// shares one allowance, which is the safe failure.
|
||||
func clientIP(r *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
// limiter allows each key a number of events per fixed window.
|
||||
type limiter struct {
|
||||
mu sync.Mutex
|
||||
limit int
|
||||
window time.Duration
|
||||
clock func() time.Time
|
||||
hits map[string]*bucket
|
||||
}
|
||||
|
||||
type bucket struct {
|
||||
start time.Time
|
||||
n int
|
||||
}
|
||||
|
||||
func newLimiter(limit int, window time.Duration, clock func() time.Time) *limiter {
|
||||
return &limiter{limit: limit, window: window, clock: clock, hits: map[string]*bucket{}}
|
||||
}
|
||||
|
||||
func (l *limiter) allow(key string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := l.clock()
|
||||
if len(l.hits) > 10000 { // forget idle clients
|
||||
for k, b := range l.hits {
|
||||
if now.Sub(b.start) >= l.window {
|
||||
delete(l.hits, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
b := l.hits[key]
|
||||
if b == nil || now.Sub(b.start) >= l.window {
|
||||
l.hits[key] = &bucket{start: now, n: 1}
|
||||
return true
|
||||
}
|
||||
if b.n >= l.limit {
|
||||
return false
|
||||
}
|
||||
b.n++
|
||||
return true
|
||||
}
|
||||
@@ -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"])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user