// 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}) }