Files

394 lines
13 KiB
Go

package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/inbox"
"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
node *p2p.Node
dev *identity.Device
phrase string // the recovery phrase of the identity behind dev
}
const msgDifficulty = 4
func newFixture(t *testing.T, tok string, tweak ...func(*Config)) *fixture {
t.Helper()
root, phrase, _ := 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, MessageDifficulty: msgDifficulty,
Trust: store.Trust{Self: dev.Cert.Author}, // the operator's own reports hide on this node
})
if err != nil {
t.Fatal(err)
}
node, err := p2p.New(context.Background(), p2p.Config{
Device: dev, Store: s, Regions: []string{"u1x"}, Difficulty: difficulty,
MessageDifficulty: msgDifficulty,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err != nil {
t.Fatal(err)
}
cfg := Config{
Store: s, Node: node, Device: dev, Regions: []string{"u1x"}, Token: tok, Difficulty: difficulty,
MessageDifficulty: msgDifficulty,
Inbox: &inbox.Inbox{Store: s, Device: dev, Publisher: node, Difficulty: msgDifficulty},
}
for _, f := range tweak {
f(&cfg)
}
srv := httptest.NewServer(New(cfg))
t.Cleanup(func() { srv.Close(); node.Close(); s.Close() })
return &fixture{srv: srv, s: s, node: node, dev: dev, phrase: phrase}
}
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")
}
}
// keeper is a RegionKeeper that follows the node's real regions.
type keeper struct {
node *p2p.Node
fail error
}
func (k *keeper) Regions() []string { return k.node.Regions() }
func (k *keeper) SetRegions(r []string) error {
if k.fail != nil {
return k.fail
}
return k.node.SetRegions(r)
}
func TestOwnerChangesTheRegions(t *testing.T) {
k := &keeper{}
f := newFixture(t, token, func(c *Config) {
k.node = c.Node
c.RegionKeeper = k
})
regions := func() []string {
_, body := f.do(t, "GET", "/api/v1/status", "", false)
var st struct {
Regions []string `json:"regions"`
}
_ = json.Unmarshal(body, &st)
return st.Regions
}
if got := regions(); len(got) != 1 || got[0] != "u1x" {
t.Fatalf("regions = %v", got)
}
if code, _ := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, false); code != 401 {
t.Fatalf("without the token: %d, want 401", code)
}
code, body := f.do(t, "PUT", "/api/v1/regions", `{"regions":[" U1J ","u1x","u1j"]}`, true)
if code != 200 {
t.Fatalf("PUT: %d %s", code, body)
}
if got := regions(); len(got) != 2 || got[0] != "u1x" || got[1] != "u1j" {
t.Fatalf("regions after the change (case and repeats tidied) = %v", got)
}
for name, tc := range map[string]struct{ body, want string }{
"not a region": {`{"regions":["u1j","nope"]}`, "not a region"},
"none": {`{"regions":[]}`, "at least one"},
"unknown field": {`{"regions":["u1j"],"x":1}`, "invalid JSON"},
"too many": {`{"regions":["u00","u01","u02","u03","u04","u05","u06","u07","u08","u09","u0b",` +
`"u0c","u0d","u0e","u0f","u0g","u0h","u0j","u0k","u0m","u0n"]}`, "too many"},
} {
code, body := f.do(t, "PUT", "/api/v1/regions", tc.body, true)
if code != 400 || !strings.Contains(string(body), tc.want) {
t.Errorf("%s: %d %s, want 400 containing %q", name, code, body, tc.want)
}
}
if got := regions(); len(got) != 2 {
t.Fatalf("a refused change must change nothing, regions = %v", got)
}
k.fail = errors.New("disk full")
if code, body := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, true); code != 500 || !strings.Contains(string(body), "disk full") {
t.Fatalf("a failing keeper: %d %s", code, body)
}
}
func TestRegionsCannotBeChangedWithoutAKeeper(t *testing.T) {
f := newFixture(t, token)
if code, _ := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, true); code == 200 {
t.Fatal("regions changed on a node that has no keeper")
}
}
type noRegions struct{}
func (noRegions) Regions() []string { return nil }
func (noRegions) SetRegions([]string) error { return nil }
func TestAStatusWithoutRegionsListsNone(t *testing.T) {
f := newFixture(t, token, func(c *Config) { c.Regions = nil; c.RegionKeeper = noRegions{} })
_, body := f.do(t, "GET", "/api/v1/status", "", false)
if !strings.Contains(string(body), `"regions":[]`) {
t.Fatalf("regions must be an empty list the UI can read, not null: %s", body)
}
}