Add runnable node, HTTP API, all-devices revocation and reconnect sync
- cmd/node: init (recovery phrase onboarding), run, recover - api: public reads of canonical signed records, token-protected writes - identity: RevokeAll voids every device certified before a cutoff, so recovery works with only the phrase; store purges by certificate age - p2p: redial bootstrap peers, sync on every new connection (in-flight guard only), validate bootstrap addresses up front - docs: API, recovery semantics, peer-ID change on recovery Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,353 @@
|
||||
// Package api is the node's HTTP interface.
|
||||
//
|
||||
// Reading is public: it serves the signed listing records exactly as
|
||||
// replicated, so a browser can verify every signature itself and does not
|
||||
// have to trust the gateway. Writing (publish, update, delete) acts as the
|
||||
// node's owner and requires the admin bearer token.
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"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 (
|
||||
maxBody = 64 << 10
|
||||
defaultLifetime = 30 // days
|
||||
)
|
||||
|
||||
// Config wires the API to a running node.
|
||||
type Config struct {
|
||||
Store *store.Store
|
||||
Node *p2p.Node
|
||||
Device *identity.Device
|
||||
Regions []string
|
||||
Token string // admin bearer token; empty disables all writes
|
||||
Difficulty int
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
type server struct {
|
||||
Config
|
||||
}
|
||||
|
||||
// New returns the HTTP handler.
|
||||
func New(cfg Config) http.Handler {
|
||||
if cfg.Clock == nil {
|
||||
cfg.Clock = time.Now
|
||||
}
|
||||
s := &server{cfg}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/v1/status", s.status)
|
||||
mux.HandleFunc("GET /api/v1/listings", s.search)
|
||||
mux.HandleFunc("GET /api/v1/listings/{author}/{id}", s.get)
|
||||
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))
|
||||
return mux
|
||||
}
|
||||
|
||||
// --- reading --------------------------------------------------------------
|
||||
|
||||
func (s *server) status(w http.ResponseWriter, r *http.Request) {
|
||||
n, err := s.Store.Count(r.Context())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"peer_id": s.Node.ID().String(),
|
||||
"addrs": s.Node.Addrs(),
|
||||
"author": s.Device.Cert.Author,
|
||||
"device": s.Device.Cert.Device,
|
||||
"regions": s.Regions,
|
||||
"peers": s.Node.PeerCount(),
|
||||
"listings": n,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *server) search(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
query := store.Query{Kind: q.Get("kind"), Category: q.Get("category")}
|
||||
|
||||
if g := q.Get("geohash"); g != "" {
|
||||
for _, p := range strings.Split(g, ",") {
|
||||
if !listing.ValidGeohashPrefix(p) {
|
||||
fail(w, http.StatusBadRequest, fmt.Sprintf("invalid geohash prefix %q", p))
|
||||
return
|
||||
}
|
||||
query.Geohashes = append(query.Geohashes, p)
|
||||
}
|
||||
}
|
||||
ints := []struct {
|
||||
name string
|
||||
dst any
|
||||
}{
|
||||
{"min_price", &query.MinPriceCents}, {"max_price", &query.MaxPriceCents},
|
||||
{"min_area", &query.MinAreaM2}, {"min_rooms", &query.MinRoomsX2},
|
||||
{"limit", &query.Limit}, {"offset", &query.Offset},
|
||||
}
|
||||
for _, f := range ints {
|
||||
v := q.Get(f.name)
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil || n < 0 {
|
||||
fail(w, http.StatusBadRequest, fmt.Sprintf("%s must be a non-negative integer", f.name))
|
||||
return
|
||||
}
|
||||
switch d := f.dst.(type) {
|
||||
case *int64:
|
||||
*d = n
|
||||
case *int:
|
||||
*d = int(n)
|
||||
}
|
||||
}
|
||||
|
||||
items, err := s.Store.Search(r.Context(), query)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
writeListings(w, items)
|
||||
}
|
||||
|
||||
func (s *server) get(w http.ResponseWriter, r *http.Request) {
|
||||
l, err := s.Store.Get(r.Context(), r.PathValue("author"), r.PathValue("id"))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
fail(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
b, err := l.Bytes()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
setPublic(w)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
// writeListings sends the records in their canonical encoding so clients can
|
||||
// verify signatures over the exact bytes.
|
||||
func writeListings(w http.ResponseWriter, items []*listing.Listing) {
|
||||
setPublic(w)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte("["))
|
||||
for i, l := range items {
|
||||
b, err := l.Bytes()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if i > 0 {
|
||||
w.Write([]byte(","))
|
||||
}
|
||||
w.Write(b)
|
||||
}
|
||||
w.Write([]byte("]"))
|
||||
}
|
||||
|
||||
// setPublic marks a response as public data that any website may read.
|
||||
func setPublic(w http.ResponseWriter) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Cache-Control", "public, max-age=15")
|
||||
}
|
||||
|
||||
// --- writing --------------------------------------------------------------
|
||||
|
||||
// draft is what the owner provides; the node adds identity, time, proof of
|
||||
// work and signature. Images are not supported yet.
|
||||
type draft struct {
|
||||
Kind string `json:"kind"`
|
||||
Category string `json:"category"`
|
||||
Geohash string `json:"geohash"`
|
||||
Price *listing.Price `json:"price"`
|
||||
AreaM2 int `json:"area_m2"`
|
||||
RoomsX2 int `json:"rooms_x2"`
|
||||
Features []string `json:"features"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Delegate string `json:"delegate"`
|
||||
ExpiresInDays int `json:"expires_in_days"`
|
||||
}
|
||||
|
||||
func (s *server) admin(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Token == "" {
|
||||
fail(w, http.StatusForbidden, "writing is disabled on this node")
|
||||
return
|
||||
}
|
||||
got := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if subtle.ConstantTimeCompare([]byte(got), []byte(s.Token)) != 1 {
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
fail(w, http.StatusUnauthorized, "missing or wrong admin token")
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) readDraft(w http.ResponseWriter, r *http.Request) (*draft, bool) {
|
||||
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody))
|
||||
dec.DisallowUnknownFields()
|
||||
var d draft
|
||||
if err := dec.Decode(&d); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
|
||||
return nil, false
|
||||
}
|
||||
if _, err := dec.Token(); err != io.EOF {
|
||||
fail(w, http.StatusBadRequest, "unexpected data after JSON body")
|
||||
return nil, false
|
||||
}
|
||||
if d.ExpiresInDays < 0 || d.ExpiresInDays > defaultLifetime {
|
||||
fail(w, http.StatusBadRequest, fmt.Sprintf("expires_in_days must be 1-%d", defaultLifetime))
|
||||
return nil, false
|
||||
}
|
||||
return &d, true
|
||||
}
|
||||
|
||||
func (d *draft) build(id string, seq uint64, now time.Time) *listing.Listing {
|
||||
days := d.ExpiresInDays
|
||||
if days == 0 {
|
||||
days = defaultLifetime
|
||||
}
|
||||
return &listing.Listing{
|
||||
Version: listing.Version,
|
||||
ID: id,
|
||||
Seq: seq,
|
||||
CreatedAt: now.Unix(),
|
||||
ExpiresAt: now.Add(time.Duration(days) * 24 * time.Hour).Unix(),
|
||||
Kind: d.Kind,
|
||||
Category: d.Category,
|
||||
Geohash: d.Geohash,
|
||||
Price: d.Price,
|
||||
AreaM2: d.AreaM2,
|
||||
RoomsX2: d.RoomsX2,
|
||||
Features: d.Features,
|
||||
Title: d.Title,
|
||||
Description: d.Description,
|
||||
Delegate: d.Delegate,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) create(w http.ResponseWriter, r *http.Request) {
|
||||
d, ok := s.readDraft(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, err := listing.NewID()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
s.seal(w, r, d.build(id, 1, s.Clock()))
|
||||
}
|
||||
|
||||
func (s *server) update(w http.ResponseWriter, r *http.Request) {
|
||||
d, ok := s.readDraft(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
old, ok := s.own(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if listing.Region(d.Geohash) != listing.Region(old.Geohash) {
|
||||
fail(w, http.StatusBadRequest,
|
||||
"the region cannot change; delete this listing and create a new one")
|
||||
return
|
||||
}
|
||||
s.seal(w, r, d.build(old.ID, old.Seq+1, s.Clock()))
|
||||
}
|
||||
|
||||
func (s *server) remove(w http.ResponseWriter, r *http.Request) {
|
||||
old, ok := s.own(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
now := s.Clock()
|
||||
s.seal(w, r, &listing.Listing{
|
||||
Version: listing.Version,
|
||||
ID: old.ID,
|
||||
Seq: old.Seq + 1,
|
||||
CreatedAt: now.Unix(),
|
||||
// Outlives every earlier version (<= 30 days), so old copies cannot return.
|
||||
ExpiresAt: now.Add(listing.MaxLifetime).Unix(),
|
||||
Tombstone: true,
|
||||
Geohash: old.Geohash,
|
||||
})
|
||||
}
|
||||
|
||||
// own loads the caller's live listing named in the URL.
|
||||
func (s *server) own(w http.ResponseWriter, r *http.Request) (*listing.Listing, bool) {
|
||||
l, err := s.Store.Get(r.Context(), s.Device.Cert.Author, r.PathValue("id"))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
fail(w, http.StatusNotFound, "no such listing of yours")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return nil, false
|
||||
}
|
||||
return l, true
|
||||
}
|
||||
|
||||
// seal signs l with the node's device, stores and gossips it, and replies
|
||||
// with the signed record.
|
||||
func (s *server) seal(w http.ResponseWriter, r *http.Request, l *listing.Listing) {
|
||||
if err := l.Seal(s.Device, s.Difficulty); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
if err := s.Node.Publish(r.Context(), l); 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.ErrRevoked):
|
||||
fail(w, http.StatusConflict, "this node's device has been revoked; run 'allmende recover'")
|
||||
case errors.Is(err, context.Canceled):
|
||||
fail(w, http.StatusRequestTimeout, "request cancelled")
|
||||
default:
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
}
|
||||
return
|
||||
}
|
||||
b, err := l.Bytes()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
// --- helpers --------------------------------------------------------------
|
||||
|
||||
func writeJSON(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func fail(w http.ResponseWriter, code int, msg string) {
|
||||
writeJSON(w, code, map[string]string{"error": msg})
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
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 TestStatus(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
code, body := f.do(t, "GET", "/api/v1/status", "", false)
|
||||
if code != 200 {
|
||||
t.Fatalf("status: %d", code)
|
||||
}
|
||||
var st map[string]any
|
||||
_ = json.Unmarshal(body, &st)
|
||||
if st["author"] != f.dev.Cert.Author || st["peer_id"] == "" {
|
||||
t.Fatalf("unexpected status: %s", body)
|
||||
}
|
||||
if strings.Contains(string(body), "token") {
|
||||
t.Fatal("status must never expose the admin token")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user