Every node now serves a search and listing-detail UI at GET /. It is vanilla TypeScript, bundled unminified into web/dist (committed) and embedded with go:embed, so `go build` is enough to run a node. The browser verifies each listing itself (certificate, binding, validity, signature, proof-of-work) with pure-JS ed25519, so a gateway can withhold listings but not forge them. Unverifiable results are hidden and their content is never shown. Listing text is only inserted via textContent and the UI is served with a strict CSP. Canonical JSON is reimplemented in TypeScript and tested against a golden fixture signed by the Go code. /api/v1/status now reports difficulty. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
293 lines
9.4 KiB
Go
293 lines
9.4 KiB
Go
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, `<script type="module" src="app.js">`) {
|
|
t.Fatalf("index: %d %.80s", resp.StatusCode, body)
|
|
}
|
|
csp := resp.Header.Get("Content-Security-Policy")
|
|
for _, want := range []string{"default-src 'none'", "script-src 'self'", "connect-src 'self'", "frame-ancestors 'none'"} {
|
|
if !strings.Contains(csp, want) {
|
|
t.Fatalf("CSP %q lacks %q", csp, want)
|
|
}
|
|
}
|
|
if strings.Contains(csp, "unsafe-inline") || strings.Contains(csp, "unsafe-eval") {
|
|
t.Fatalf("CSP must not allow inline or eval: %q", csp)
|
|
}
|
|
|
|
resp, body = get("/app.js")
|
|
if resp.StatusCode != 200 || !strings.Contains(resp.Header.Get("Content-Type"), "javascript") {
|
|
t.Fatalf("app.js: %d %s", resp.StatusCode, resp.Header.Get("Content-Type"))
|
|
}
|
|
if !strings.Contains(body, "allmende-listing-v1") {
|
|
t.Fatal("the embedded bundle does not contain the verifier; rebuild it with `npm run build` in web/")
|
|
}
|
|
if resp, _ = get("/style.css"); resp.StatusCode != 200 {
|
|
t.Fatalf("style.css: %d", resp.StatusCode)
|
|
}
|
|
if resp, _ = get("/nope.js"); resp.StatusCode != 404 {
|
|
t.Fatalf("unknown file: %d, want 404", resp.StatusCode)
|
|
}
|
|
|
|
// The API is untouched and also refuses content sniffing.
|
|
resp, _ = get("/api/v1/status")
|
|
if resp.StatusCode != 200 || resp.Header.Get("X-Content-Type-Options") != "nosniff" {
|
|
t.Fatalf("status: %d nosniff=%q", resp.StatusCode, resp.Header.Get("X-Content-Type-Options"))
|
|
}
|
|
if req, _ := http.NewRequest("POST", f.srv.URL+"/", nil); req != nil {
|
|
if r, err := http.DefaultClient.Do(req); err == nil {
|
|
r.Body.Close()
|
|
if r.StatusCode != 405 {
|
|
t.Fatalf("POST /: %d, want 405", r.StatusCode)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestStatusReportsDifficultyForTheBrowserVerifier(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["difficulty"] != float64(difficulty) {
|
|
t.Fatalf("difficulty = %v, want %d", st["difficulty"], difficulty)
|
|
}
|
|
}
|
|
|
|
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")
|
|
}
|
|
}
|