package api import ( "bytes" "context" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/p2p" "git.stinnesbeck.com/nils/allmende/internal/store" ) const ( difficulty = 6 token = "s3cret-token" ) type fixture struct { srv *httptest.Server s *store.Store dev *identity.Device } func newFixture(t *testing.T, tok string) *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}) 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)), }) if err != nil { t.Fatal(err) } srv := httptest.NewServer(New(Config{ Store: s, Node: node, Device: dev, Regions: []string{"u1x"}, Token: tok, Difficulty: difficulty, })) t.Cleanup(func() { srv.Close(); node.Close(); s.Close() }) return &fixture{srv: srv, s: s, dev: dev} } func (f *fixture) do(t *testing.T, method, path, body string, auth bool) (int, []byte) { t.Helper() req, _ := http.NewRequest(method, f.srv.URL+path, strings.NewReader(body)) if auth { req.Header.Set("Authorization", "Bearer "+token) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() b, _ := io.ReadAll(resp.Body) return resp.StatusCode, b } const draftJSON = `{ "kind": "rent", "category": "apartment", "geohash": "u1xjhx", "price": {"amount_cents": 95000, "currency": "EUR", "period": "month"}, "area_m2": 48, "rooms_x2": 4, "features": ["balcony"], "title": "Helle Wohnung", "description": "Ruhig gelegen." }` func TestCreateSearchGetUpdateDelete(t *testing.T) { f := newFixture(t, token) code, body := f.do(t, "POST", "/api/v1/listings", draftJSON, true) if code != 200 { t.Fatalf("create: %d %s", code, body) } var created listing.Listing if err := json.Unmarshal(body, &created); err != nil { t.Fatal(err) } // The reply must be the verifiable signed record. if err := created.Check(time.Now(), difficulty); err != nil { t.Fatalf("returned listing does not verify: %v", err) } if created.Author != f.dev.Cert.Author || created.Seq != 1 { t.Fatalf("unexpected listing: %+v", created) } // Search (public, no token) returns canonical bytes that verify. code, body = f.do(t, "GET", "/api/v1/listings?geohash=u1x&kind=rent&max_price=100000", "", false) if code != 200 { t.Fatalf("search: %d %s", code, body) } var found []json.RawMessage if err := json.Unmarshal(body, &found); err != nil || len(found) != 1 { t.Fatalf("search returned %d items (%v): %s", len(found), err, body) } want, _ := created.Bytes() if !bytes.Equal(found[0], want) { t.Fatal("search result is not the canonical encoding") } if code, body = f.do(t, "GET", "/api/v1/listings?kind=sale", "", false); string(body) != "[]" { t.Fatalf("filter ignored: %d %s", code, body) } // Get one. path := "/api/v1/listings/" + created.Author + "/" + created.ID if code, _ = f.do(t, "GET", path, "", false); code != 200 { t.Fatalf("get: %d", code) } // Update bumps seq and replaces the content. upd := strings.Replace(draftJSON, "Helle Wohnung", "Sehr helle Wohnung", 1) code, body = f.do(t, "PUT", "/api/v1/listings/"+created.ID, upd, true) if code != 200 { t.Fatalf("update: %d %s", code, body) } var updated listing.Listing _ = json.Unmarshal(body, &updated) if updated.Seq != 2 || updated.Title != "Sehr helle Wohnung" { t.Fatalf("unexpected update: %+v", updated) } // Moving to another region is refused. moved := strings.Replace(draftJSON, "u1xjhx", "u30000", 1) if code, _ = f.do(t, "PUT", "/api/v1/listings/"+created.ID, moved, true); code != 400 { t.Fatalf("region change: got %d, want 400", code) } // Delete publishes a tombstone. if code, body = f.do(t, "DELETE", "/api/v1/listings/"+created.ID, "", true); code != 200 { t.Fatalf("delete: %d %s", code, body) } if code, _ = f.do(t, "GET", path, "", false); code != 404 { t.Fatalf("deleted listing still served: %d", code) } if code, _ = f.do(t, "DELETE", "/api/v1/listings/"+created.ID, "", true); code != 404 { t.Fatalf("second delete: got %d, want 404", code) } } func TestWritesRequireToken(t *testing.T) { f := newFixture(t, token) for _, tc := range []struct{ method, path string }{ {"POST", "/api/v1/listings"}, {"PUT", "/api/v1/listings/abc"}, {"DELETE", "/api/v1/listings/abc"}, } { if code, _ := f.do(t, tc.method, tc.path, draftJSON, false); code != 401 { t.Fatalf("%s %s without token: %d, want 401", tc.method, tc.path, code) } } req, _ := http.NewRequest("POST", f.srv.URL+"/api/v1/listings", strings.NewReader(draftJSON)) req.Header.Set("Authorization", "Bearer wrong") resp, _ := http.DefaultClient.Do(req) if resp.StatusCode != 401 { t.Fatalf("wrong token: %d", resp.StatusCode) } off := newFixture(t, "") if code, _ := off.do(t, "POST", "/api/v1/listings", draftJSON, true); code != 403 { t.Fatalf("writes on a node without a token: %d, want 403", code) } } func TestValidationErrors(t *testing.T) { f := newFixture(t, token) cases := map[string]string{ "unknown field": strings.Replace(draftJSON, `"kind"`, `"owner_phone": "0170", "kind"`, 1), "bad kind": strings.Replace(draftJSON, `"rent"`, `"swap"`, 1), "bad geohash": strings.Replace(draftJSON, "u1xjhx", "aaaaaa", 1), "trailing data": draftJSON + `{}`, "not json": `nope`, "too long ttl": strings.Replace(draftJSON, `"kind"`, `"expires_in_days": 90, "kind"`, 1), "no price": strings.Replace(draftJSON, `"price": {"amount_cents": 95000, "currency": "EUR", "period": "month"},`, "", 1), "huge body": `{"title":"` + strings.Repeat("x", 70<<10) + `"}`, "price mismatch": strings.Replace(draftJSON, `"month"`, `"once"`, 1), } for name, body := range cases { t.Run(name, func(t *testing.T) { if code, resp := f.do(t, "POST", "/api/v1/listings", body, true); code != 400 { t.Fatalf("got %d (%s), want 400", code, resp) } }) } if n, _ := f.s.Count(context.Background()); n != 0 { t.Fatalf("%d invalid listings were stored", n) } } func TestSearchParameterValidation(t *testing.T) { f := newFixture(t, token) for _, q := range []string{ "geohash=u1x'%20OR%201=1", "geohash=abc", "min_price=-5", "limit=lots", "max_price=1.5", } { if code, _ := f.do(t, "GET", "/api/v1/listings?"+q, "", false); code != 400 { t.Fatalf("%q: got %d, want 400", q, code) } } } func TestServesTheWebUIWithStrictHeaders(t *testing.T) { f := newFixture(t, token) get := func(path string) (*http.Response, string) { resp, err := http.Get(f.srv.URL + path) if err != nil { t.Fatal(err) } defer resp.Body.Close() b, _ := io.ReadAll(resp.Body) return resp, string(b) } resp, body := get("/") if resp.StatusCode != 200 || !strings.Contains(body, `