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 TestMineAndThreadSummaries(t *testing.T) { f := newFixture(t, token) l := f.publish(t) // Nothing yet: the listing is there, with nothing in its inbox. var mine []mineView code, body := f.do(t, "GET", "/api/v1/mine", "", true) if code != 200 || json.Unmarshal(body, &mine) != nil || len(mine) != 1 { t.Fatalf("mine: %d %s", code, body) } if mine[0].ID != l.ID || mine[0].Title != l.Title || mine[0].Threads != 0 || mine[0].AddressSaved { t.Fatalf("empty listing: %+v", mine[0]) } // One readable request, one with a link (hidden). ok, bad := newThread(t), newThread(t) f.send(t, buyerHello(t, l, ok, "Ist die Wohnung noch frei?")) f.send(t, buyerHello(t, l, bad, "Schau auf https://evil.example")) f.do(t, "PUT", "/api/v1/listings/"+l.ID+"/address", `{"address":"Musterweg 7, 22765 Hamburg"}`, true) code, body = f.do(t, "GET", "/api/v1/mine", "", true) if code != 200 || json.Unmarshal(body, &mine) != nil { t.Fatalf("mine: %d %s", code, body) } if m := mine[0]; m.Threads != 2 || m.NeedsReply != 1 || m.Hidden != 1 || !m.AddressSaved { t.Fatalf("counts: %+v", m) } byThread := func() map[string]threadView { var ts []threadView code, body := f.do(t, "GET", "/api/v1/inbox?listing="+l.ID, "", true) if code != 200 || json.Unmarshal(body, &ts) != nil { t.Fatalf("inbox: %d %s", code, body) } out := map[string]threadView{} for _, v := range ts { out[v.Thread] = v } return out } ts := byThread() a, b := ts[ok.PublicHex()], ts[bad.PublicHex()] if !a.NeedsReply || a.LastDir != "in" || a.Preview != "Ist die Wohnung noch frei?" || a.Effort < msgDifficulty { t.Fatalf("readable request: %+v", a) } if b.NeedsReply || b.Preview != "" || b.Hidden != 1 { t.Fatalf("hidden request must not leak its text or ask for a reply: %+v", b) } // Answer with an address: the request no longer needs a reply and shows the release. path := "/api/v1/inbox/" + l.ID + "/" + ok.PublicHex() if code, body := f.do(t, "POST", path, `{"type":"grant","note":"Samstag 10 Uhr","valid_days":7}`, true); code != 200 { t.Fatalf("grant: %d %s", code, body) } a = byThread()[ok.PublicHex()] if a.NeedsReply || a.LastDir != "out" || a.GrantUntil == 0 || a.Preview != "" { t.Fatalf("after the grant: %+v", a) } // Another listing's filter returns nothing; the token is required. if code, body := f.do(t, "GET", "/api/v1/inbox?listing="+strings.Repeat("0", 32), "", true); code != 200 || strings.TrimSpace(string(body)) != "[]" { t.Fatalf("filter: %d %s", code, body) } if code, _ := f.do(t, "GET", "/api/v1/mine", "", false); code != 401 { t.Fatalf("mine without a token: %d", code) } } func TestHexZeroBits(t *testing.T) { for h, want := range map[string]int{"": 0, "f": 0, "8": 0, "7": 1, "1": 3, "0": 4, "00f": 8, "0a": 4, "004": 9, "0000": 16, "zz": 0} { if got := hexZeroBits(h); got != want { t.Errorf("hexZeroBits(%q) = %d, want %d", h, got, want) } } } 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"]) } } func TestTheMessagePriceRisesWithTheQueueAndBuyersCanAskForIt(t *testing.T) { f := newFixture(t, token) l := f.publish(t) required := func() int { code, body := f.do(t, "GET", "/api/v1/messages/required?author="+l.Author+"&id="+l.ID, "", false) var r struct { Bits int `json:"bits"` } if code != 200 || json.Unmarshal(body, &r) != nil { t.Fatalf("required: %d %s", code, body) } return r.Bits } if got := required(); got != msgDifficulty { t.Fatalf("a quiet listing asks %d bits, want %d", got, msgDifficulty) } if code, _ := f.do(t, "GET", "/api/v1/messages/required?author=zz&id=1", "", false); code != 400 { t.Fatalf("bad parameters: %d", code) } // Half of the 200-envelope queue costs one bit more. for i := 0; i < 100; i++ { if _, err := f.s.PutMessage(t.Context(), listing.Region(l.Geohash), buyerHello(t, l, newThread(t), "Hallo")); err != nil { t.Fatal(err) } } if got := required(); got != msgDifficulty+1 { t.Fatalf("a half-full queue asks %d bits, want %d", got, msgDifficulty+1) } // A message at the old price is refused, and the answer names the new one. var weak *message.Envelope for { weak = buyerHello(t, l, newThread(t), "Hallo") if w, _ := weak.Work(); w == msgDifficulty { break } } code, body := f.send(t, weak) var refusal struct { Required int `json:"required_bits"` } if code != 429 || json.Unmarshal(body, &refusal) != nil || refusal.Required != msgDifficulty+1 { t.Fatalf("a message at the old price: %d %s", code, body) } } func TestBlockingAConversationOverTheAPI(t *testing.T) { f := newFixture(t, token) l := f.publish(t) tk := newThread(t) f.send(t, buyerHello(t, l, tk, "Hallo")) f.do(t, "GET", "/api/v1/inbox?listing="+l.ID, "", true) // collects path := "/api/v1/inbox/" + l.ID + "/" + tk.PublicHex() if code, _ := f.do(t, "PUT", path+"/block", "", false); code != 401 { t.Fatalf("blocking without the token: %d", code) } if code, body := f.do(t, "PUT", path+"/block", "", true); code != 204 { t.Fatalf("block: %d %s", code, body) } if code, _ := f.do(t, "GET", path, "", true); code != 404 { t.Fatalf("a blocked conversation can still be read: %d", code) } var bl []blockedView code, body := f.do(t, "GET", "/api/v1/blocked", "", true) if code != 200 || json.Unmarshal(body, &bl) != nil || len(bl) != 1 || bl[0].Thread != tk.PublicHex() || bl[0].Listing != l.ID { t.Fatalf("blocked list: %d %s", code, body) } if code, _ := f.do(t, "PUT", "/api/v1/inbox/"+l.ID+"/"+strings.Repeat("0", 64)+"/block", "", true); code != 404 { t.Fatalf("blocking an unknown thread: %d", code) } if code, body := f.do(t, "DELETE", path+"/block", "", true); code != 204 { t.Fatalf("unblock: %d %s", code, body) } if _, body := f.do(t, "GET", "/api/v1/blocked", "", true); string(bytes.TrimSpace(body)) != "[]" { t.Fatalf("blocked list after unblocking: %s", body) } }