From 918e16ed375db401a09a1e1d75cb89d0e02006f2 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Tue, 17 Nov 2026 18:03:46 +0100 Subject: [PATCH] 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 --- README.md | 11 + cmd/node/init.go | 126 +++++++++++ cmd/node/main.go | 118 +++++++++++ cmd/node/recover.go | 137 ++++++++++++ cmd/node/run.go | 163 ++++++++++++++ docs/PROTOCOL.md | 63 +++++- go.mod | 1 + go.sum | 2 + internal/api/api.go | 353 +++++++++++++++++++++++++++++++ internal/api/api_test.go | 226 ++++++++++++++++++++ internal/identity/device_test.go | 33 +++ internal/identity/revocation.go | 43 +++- internal/listing/listing.go | 4 + internal/p2p/node.go | 89 ++++++-- internal/p2p/p2p_test.go | 85 +++++++- internal/p2p/sync.go | 14 +- internal/store/store.go | 104 ++++++--- internal/store/store_test.go | 60 ++++++ 18 files changed, 1550 insertions(+), 82 deletions(-) create mode 100644 cmd/node/init.go create mode 100644 cmd/node/main.go create mode 100644 cmd/node/recover.go create mode 100644 cmd/node/run.go create mode 100644 internal/api/api.go create mode 100644 internal/api/api_test.go diff --git a/README.md b/README.md index e638d03..43bc5a1 100644 --- a/README.md +++ b/README.md @@ -4,4 +4,15 @@ A free, distributed marketplace for buying, selling and renting. Listings are replicated across the nodes of everyone who participates, so there is no central server and no cost. See [docs/PROTOCOL.md](docs/PROTOCOL.md). +## Try it + +``` +go build -o bin/node ./cmd/node +bin/node init # shows your 12-word recovery phrase once +bin/node run --region u1x # u1x = Hamburg area; API on http://127.0.0.1:8080 +``` + +A second node on the same network finds this one automatically (mDNS); across +networks, pass `--bootstrap /ip4//tcp//p2p/`. + Licensed under the [GNU AGPL-3.0](LICENSE): free for everyone, and it stays free. diff --git a/cmd/node/init.go b/cmd/node/init.go new file mode 100644 index 0000000..9e6a708 --- /dev/null +++ b/cmd/node/init.go @@ -0,0 +1,126 @@ +package main + +import ( + "bufio" + "crypto/rand" + "errors" + "flag" + "fmt" + "io" + "math/big" + "os" + "path/filepath" + "strings" + "time" + + "golang.org/x/term" + + "git.stinnesbeck.com/nils/allmende/internal/identity" +) + +func cmdInit(args []string) error { + fs := flag.NewFlagSet("init", flag.ExitOnError) + data := dataFlag(fs) + fs.Parse(args) + + if _, err := os.Stat(filepath.Join(*data, "device.key")); err == nil { + return fmt.Errorf("%s is already set up. To get access back after losing this machine, use 'node recover'", *data) + } + + root, phrase, err := identity.NewRoot() + if err != nil { + return err + } + words := strings.Fields(phrase) + showPhrase(words) + + // Only ask for confirmation when a person is at the keyboard. + if term.IsTerminal(int(os.Stdin.Fd())) { + if err := confirmPhrase(bufio.NewReader(os.Stdin), words); err != nil { + return err + } + } + + dev, err := identity.Enroll(root, time.Now(), certLifetime) + if err != nil { + return err + } + // The identity key is not saved anywhere: only the phrase can recreate it. + if err := dev.Save(*data); err != nil { + return err + } + token, err := newToken() + if err != nil { + return err + } + if err := writeToken(*data, token); err != nil { + return err + } + + fmt.Printf("\nDone. This machine is set up as a device of identity %s…\n", dev.Cert.Author[:12]) + fmt.Printf("Your device certificate is valid until %s.\n\n", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02")) + fmt.Printf("Next: node run --region --data %s\n", *data) + fmt.Printf("The admin token for publishing is in %s\n", filepath.Join(*data, tokenFile)) + return nil +} + +func showPhrase(words []string) { + fmt.Print(` +Your recovery phrase +-------------------- +These 12 words ARE your identity. They are shown only once and are not stored +on this computer. Write them on paper and keep them somewhere safe. + +With them you can recover your account if this computer is lost, broken or +hacked. Anyone who has them can act as you, so never type them into a website +or share them. +`) + for i := 0; i < len(words); i += 3 { + fmt.Printf(" %2d. %-12s %2d. %-12s %2d. %-12s\n", + i+1, words[i], i+2, words[i+1], i+3, words[i+2]) + } + fmt.Println() +} + +// confirmPhrase asks for two random words so the user has really written +// the phrase down. +func confirmPhrase(in *bufio.Reader, words []string) error { + picks, err := twoDistinct(len(words)) + if err != nil { + return err + } + fmt.Println("To make sure you wrote it down, please enter two of the words.") + for _, i := range picks { + for { + fmt.Printf("Word number %d: ", i+1) + line, err := in.ReadString('\n') + if err != nil && (!errors.Is(err, io.EOF) || line == "") { + return errors.New("no input; run 'node init' again in a terminal") + } + if strings.EqualFold(strings.TrimSpace(line), words[i]) { + break + } + fmt.Println("That is not the right word. Check your notes and try again.") + } + } + return nil +} + +func twoDistinct(n int) ([2]int, error) { + a, err := rand.Int(rand.Reader, big.NewInt(int64(n))) + if err != nil { + return [2]int{}, err + } + b, err := rand.Int(rand.Reader, big.NewInt(int64(n-1))) + if err != nil { + return [2]int{}, err + } + x, y := int(a.Int64()), int(b.Int64()) + if y >= x { + y++ + } + if x > y { + x, y = y, x + } + return [2]int{x, y}, nil +} diff --git a/cmd/node/main.go b/cmd/node/main.go new file mode 100644 index 0000000..2284f11 --- /dev/null +++ b/cmd/node/main.go @@ -0,0 +1,118 @@ +// Command node runs an Allmende node. +// +// node init first-time setup: creates your identity and shows your recovery phrase +// node run run the node (replicates listings, serves the HTTP API) +// node recover restore from the recovery phrase after a lost or compromised machine +package main + +import ( + "crypto/rand" + "encoding/hex" + "flag" + "fmt" + "os" + "path/filepath" + "strings" + "time" +) + +const ( + certLifetime = 365 * 24 * time.Hour + + dbFile = "allmende.db" + tokenFile = "admin.token" +) + +const usage = `Allmende: a free, distributed marketplace for homes. + +Usage: + node init [--data DIR] create your identity (first run) + node run [--data DIR] --region u1x run the node + node recover [--data DIR] restore access using your recovery phrase + +Run "node -h" for the options of a command. +` + +func main() { + if len(os.Args) < 2 { + fmt.Fprint(os.Stderr, usage) + os.Exit(2) + } + var err error + switch os.Args[1] { + case "init": + err = cmdInit(os.Args[2:]) + case "run": + err = cmdRun(os.Args[2:]) + case "recover": + err = cmdRecover(os.Args[2:]) + case "help", "-h", "--help": + fmt.Print(usage) + default: + fmt.Fprintf(os.Stderr, "unknown command %q\n\n%s", os.Args[1], usage) + os.Exit(2) + } + if err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +// --- shared helpers ------------------------------------------------------- + +func defaultDataDir() string { + if d := os.Getenv("ALLMENDE_DATA"); d != "" { + return d + } + if x := os.Getenv("XDG_DATA_HOME"); x != "" { + return filepath.Join(x, "allmende") + } + home, err := os.UserHomeDir() + if err != nil { + return "allmende-data" + } + return filepath.Join(home, ".local", "share", "allmende") +} + +func dataFlag(fs *flag.FlagSet) *string { + return fs.String("data", defaultDataDir(), "directory for keys and the database (env ALLMENDE_DATA)") +} + +// listFlag is a repeatable, comma-separated string flag. +type listFlag []string + +func (l *listFlag) String() string { return strings.Join(*l, ",") } +func (l *listFlag) Set(v string) error { + for _, p := range strings.Split(v, ",") { + if p = strings.TrimSpace(p); p != "" { + *l = append(*l, p) + } + } + return nil +} + +func newToken() (string, error) { + var b [32]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + return hex.EncodeToString(b[:]), nil +} + +// writeToken replaces the admin token file, readable only by the owner. +func writeToken(dir, token string) error { + path := filepath.Join(dir, tokenFile) + tmp := path + ".tmp" + if err := os.WriteFile(tmp, []byte(token+"\n"), 0o600); err != nil { + return err + } + return os.Rename(tmp, path) +} + +func readToken(dir string) string { + b, err := os.ReadFile(filepath.Join(dir, tokenFile)) + if err != nil { + return "" + } + return strings.TrimSpace(string(b)) +} diff --git a/cmd/node/recover.go b/cmd/node/recover.go new file mode 100644 index 0000000..688d351 --- /dev/null +++ b/cmd/node/recover.go @@ -0,0 +1,137 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "time" + + "golang.org/x/term" + + "git.stinnesbeck.com/nils/allmende/internal/identity" + "git.stinnesbeck.com/nils/allmende/internal/listing" + "git.stinnesbeck.com/nils/allmende/internal/store" +) + +// cmdRecover restores access from the recovery phrase. It voids every device +// certified so far (including a stolen one), enrolls this machine as a fresh +// device, and re-signs this node's own listings so they carry on. It also +// serves as the yearly certificate renewal. +func cmdRecover(args []string) error { + fs := flag.NewFlagSet("recover", flag.ExitOnError) + data := dataFlag(fs) + difficulty := fs.Int("difficulty", listing.DefaultDifficulty, "proof-of-work bits; must match the network") + fs.Parse(args) + + phrase, err := readPhrase() + if err != nil { + return err + } + root, err := identity.FromPhrase(phrase) + if err != nil { + return err + } + author := root.PublicKeyHex() + ctx := context.Background() + + st, err := store.Open(filepath.Join(*data, dbFile), store.Options{Difficulty: *difficulty}) + if err != nil { + return err + } + defer st.Close() + + // Remember our listings: the revocation below purges them from the store. + own, err := st.ByAuthor(ctx, author) + if err != nil { + return err + } + + now := time.Now() + rev, err := identity.RevokeAll(root, now, *difficulty) + if err != nil { + return err + } + // Enrolled at the same instant: a certificate issued at the cutoff stays valid. + dev, err := identity.Enroll(root, now, certLifetime) + if err != nil { + return err + } + + if err := retireOldDevice(*data, now); err != nil { + return err + } + if err := dev.Save(*data); err != nil { + return err + } + token, err := newToken() + if err != nil { + return err + } + if err := writeToken(*data, token); err != nil { + return err + } + + if _, err := st.PutRevocation(ctx, rev); err != nil { + return err + } + + republished := 0 + for _, old := range own { + l := *old + l.Seq = old.Seq + 1 + l.CreatedAt = now.Unix() + if max := now.Add(listing.MaxLifetime).Unix(); l.ExpiresAt > max { + l.ExpiresAt = max + } + if err := l.Seal(dev, *difficulty); err != nil { + return err + } + if _, err := st.Put(ctx, &l); err != nil { + fmt.Fprintf(os.Stderr, "warning: could not re-sign listing %s: %v\n", old.ID, err) + continue + } + republished++ + } + + fmt.Printf("Recovered identity %s…\n", author[:12]) + fmt.Println(" - All earlier devices of this identity have been revoked.") + fmt.Printf(" - This machine is now a new device (certificate valid until %s).\n", + time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02")) + fmt.Printf(" - %d of your listings were re-signed from this device.\n", republished) + fmt.Println(" - A new admin token was written; the old one no longer works.") + fmt.Println("\nStart the node with 'node run' so the revocation spreads through the network.") + return nil +} + +// retireOldDevice moves a previous device's files aside so the revoked key is +// never used again but is not silently destroyed either. +func retireOldDevice(dir string, now time.Time) error { + for _, name := range []string{"device.key", "device.cert"} { + src := filepath.Join(dir, name) + if _, err := os.Stat(src); errors.Is(err, os.ErrNotExist) { + continue + } + dst := fmt.Sprintf("%s.revoked-%d", src, now.Unix()) + if err := os.Rename(src, dst); err != nil { + return err + } + } + return nil +} + +// readPhrase reads the recovery phrase without echoing it when possible. +func readPhrase() (string, error) { + fd := int(os.Stdin.Fd()) + if term.IsTerminal(fd) { + fmt.Fprint(os.Stderr, "Recovery phrase (12 words; what you type is hidden): ") + b, err := term.ReadPassword(fd) + fmt.Fprintln(os.Stderr) + return string(b), err + } + b, err := io.ReadAll(io.LimitReader(os.Stdin, 4096)) + return string(b), err +} diff --git a/cmd/node/run.go b/cmd/node/run.go new file mode 100644 index 0000000..a2c4c3a --- /dev/null +++ b/cmd/node/run.go @@ -0,0 +1,163 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "path/filepath" + "syscall" + "time" + + "git.stinnesbeck.com/nils/allmende/internal/api" + "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 ( + announceFirst = 10 * time.Second + announceInterval = 30 * time.Minute + certWarnBefore = 30 * 24 * time.Hour +) + +func cmdRun(args []string) error { + fs := flag.NewFlagSet("run", flag.ExitOnError) + data := dataFlag(fs) + var regions, bootstrap, listen listFlag + fs.Var(®ions, "region", "geohash region (3 characters, e.g. u1x) to replicate; repeatable") + fs.Var(&bootstrap, "bootstrap", "multiaddr of a known peer (…/p2p/); repeatable") + fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)") + httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API") + noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network") + difficulty := fs.Int("difficulty", listing.DefaultDifficulty, + "proof-of-work bits; must match the rest of the network") + fs.Parse(args) + + if len(regions) == 0 { + return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)") + } + + dev, err := identity.LoadDevice(*data) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("%s is not set up yet: run 'node init' first", *data) + } + return err + } + until := time.Until(time.Unix(dev.Cert.ExpiresAt, 0)) + if until <= 0 { + return errors.New("this device's certificate has expired; run 'node recover' to renew it") + } + log := slog.New(slog.NewTextHandler(os.Stderr, nil)) + if until < certWarnBefore { + log.Warn("device certificate expires soon; run 'node recover' to renew it", + "expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02")) + } + + st, err := store.Open(filepath.Join(*data, dbFile), store.Options{Difficulty: *difficulty}) + if err != nil { + return err + } + defer st.Close() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + node, err := p2p.New(ctx, p2p.Config{ + Device: dev, + Store: st, + ListenAddrs: listen, + Bootstrap: bootstrap, + Regions: regions, + MDNS: !*noMDNS, + Difficulty: *difficulty, + Logger: log, + }) + if err != nil { + return err + } + defer node.Close() + + token := readToken(*data) + if token == "" { + log.Warn("no admin token found; publishing through the API is disabled") + } + handler := api.New(api.Config{ + Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty, + }) + + ln, err := net.Listen("tcp", *httpAddr) + if err != nil { + return err + } + srv := &http.Server{ + Handler: handler, + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 60 * time.Second, // publishing mines proof-of-work + IdleTimeout: 2 * time.Minute, + } + go func() { + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Error("http server", "err", err) + stop() + } + }() + + log.Info("node running", + "peer_id", node.ID().String(), "identity", dev.Cert.Author[:12]+"…", + "regions", []string(regions), "http", ln.Addr().String()) + for _, a := range node.Addrs() { + log.Info("listening", "addr", a) + } + if host, _, _ := net.SplitHostPort(ln.Addr().String()); host != "127.0.0.1" && host != "::1" { + log.Warn("the HTTP API is reachable from other machines; put it behind TLS if it is public") + } + + go announce(ctx, log, node, st, dev.Cert.Author) + + <-ctx.Done() + log.Info("shutting down") + shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return srv.Shutdown(shutdown) +} + +// announce periodically re-gossips this identity's revocations and live +// listings. Gossip only reaches peers connected at that moment; this makes +// sure newcomers hear about them without waiting for a sync. +func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.Store, author string) { + timer := time.NewTimer(announceFirst) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + if revs, err := st.Revocations(ctx); err == nil { + for _, r := range revs { + if r.Author == author { + if err := node.PublishRevocation(ctx, r); err != nil { + log.Debug("announce revocation", "err", err) + } + } + } + } + if own, err := st.ByAuthor(ctx, author); err == nil { + for _, l := range own { + if err := node.Publish(ctx, l); err != nil { + log.Debug("announce listing", "id", l.ID, "err", err) + } + } + } + timer.Reset(announceInterval) + } +} diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 4d15691..3004d84 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -37,9 +37,19 @@ revoked. There are no accounts. - **Revocation**: `{v, author, device, revoked_at, cert_expires_at, pow, sig}` signed by the identity key, gossiped on `/allmende/1/revocations` (all nodes subscribe), kept until `cert_expires_at`. A revoked device's signatures are - void: its listings are purged and refused. The owner restores the identity - from the phrase on a new machine, revokes the old device, enrolls a new one - and republishes (higher `seq`). + void: its listings are purged and refused. Two forms: + - **one device** (`device` set): voids exactly that device; + - **all devices** (`device` empty): voids every device of the author whose + certificate was issued *before* `revoked_at`. This is what recovery uses, + because on a new machine the owner has only the phrase and does not know + the old device's key. The replacement device is enrolled at the same + instant (`issued_at == revoked_at`), which stays valid. +- **Recovery** (`node recover`): phrase in, all-devices revocation out, fresh + device enrolled, the node's own listings re-signed (`seq + 1`) from the new + device. The same command renews the yearly certificate. +- **Peer IDs change on recovery** because the device key is the libp2p + identity. Anyone who listed the old peer ID as a bootstrap address has a + stale entry; the recovered node dials out to its own bootstrap peers. - Lost phrase and lost device: start a new identity. Cheap, because listings expire within 30 days anyway. - Signed payloads are domain-separated (`allmende-cert-v1\n`, @@ -108,11 +118,44 @@ within 30 days. `(author, id)`; higher `seq` wins; equal `seq` -> smaller hash wins; tombstones are stored like any version so old copies cannot resurrect a deleted listing. -- **Sync** (`/allmende/1/sync`): on connecting to a peer (at most every - 5 minutes) a node pulls revocations first, then each subscribed region, - paged by a `(created_at, author, id)` keyset cursor. Tombstones are included - so deletions propagate. Currently a full pull; a digest-based incremental - sync is future work. +- **Sync** (`/allmende/1/sync`): on every new connection to a peer a node + pulls revocations first, then each subscribed region, paged by a + `(created_at, author, id)` keyset cursor. Tombstones are included so + deletions propagate. Simultaneous connections to the same peer (e.g. TCP and + QUIC) share one running sync. Currently a full pull; a digest-based + incremental sync is future work. Gossip lost *while connected* is only + repaired by the next reconnect; periodic anti-entropy is future work. +- **Reconnection**: bootstrap peers are redialed every 20 s when disconnected. +- **Re-announce**: a running node re-gossips its own live listings and + revocations every 30 minutes, so newcomers hear about them without waiting + for a sync. + +## HTTP API (`internal/api`) + +Public reads serve the signed records in their **canonical encoding**, so a +browser verifies signatures itself and need not trust the gateway. Writes act +as the node's owner and need `Authorization: Bearer ` (a random +token written to `admin.token` at init, mode 0600). + +| method and path | auth | | +|---|---|---| +| `GET /api/v1/status` | no | peer ID, addresses, identity, regions, peer and listing counts | +| `GET /api/v1/listings` | no | filters: `geohash` (comma-separated prefixes), `kind`, `category`, `min_price`, `max_price`, `min_area`, `min_rooms`, `limit` (max 200), `offset` | +| `GET /api/v1/listings/{author}/{id}` | no | one listing | +| `POST /api/v1/listings` | token | publish a draft; the node adds identity, time, PoW and signature | +| `PUT /api/v1/listings/{id}` | token | replace own listing (`seq + 1`); the region cannot change | +| `DELETE /api/v1/listings/{id}` | token | publish a tombstone | + +Reads send `Access-Control-Allow-Origin: *` (the data is public). Writes are +not cross-origin. Images are not supported yet. + +## Running a node (`cmd/node`) + +``` +node init # create identity, show the 12-word phrase (once) +node run --region u1x [--bootstrap ] # replicate a region, serve the API on 127.0.0.1:8080 +node recover # restore from the phrase; also yearly cert renewal +``` ## Spam @@ -123,4 +166,6 @@ Proof-of-work per listing and per revocation, plus subscribable blocklists Buyer/seller messaging (E2E, store-and-forward), reciprocity rules, anti- discrimination (AGG) content rules, blocklists, peer scoring and rate limits, -incremental sync, DHT discovery, HTTP gateway and web UI, image hosting. +incremental sync and anti-entropy, DHT discovery, web UI, image hosting, +recovering listings onto a fresh machine with an empty database, a helper to +turn a place name into a region. diff --git a/go.mod b/go.mod index 811e719..09738b2 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/libp2p/go-libp2p v0.52.0 github.com/libp2p/go-libp2p-pubsub v0.19.0 github.com/tyler-smith/go-bip39 v1.1.0 + golang.org/x/term v0.48.0 modernc.org/sqlite v1.62.0 ) diff --git a/go.sum b/go.sum index 23bbfab..b8d9433 100644 --- a/go.sum +++ b/go.sum @@ -234,6 +234,8 @@ golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/telemetry v0.0.0-20261111153349-cdaf7e97dd7b h1:HDLCiByjRbzmSn/z4+smkCRQ58Hr5yxP+pq4CwqwCv8= golang.org/x/telemetry v0.0.0-20261111153349-cdaf7e97dd7b/go.mod h1:frnW8knEsfI9dILitAKHe8/iQ1ycXgpvIjQ/xz9QFYk= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= diff --git a/internal/api/api.go b/internal/api/api.go new file mode 100644 index 0000000..4097991 --- /dev/null +++ b/internal/api/api.go @@ -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}) +} diff --git a/internal/api/api_test.go b/internal/api/api_test.go new file mode 100644 index 0000000..3db7f0c --- /dev/null +++ b/internal/api/api_test.go @@ -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") + } +} diff --git a/internal/identity/device_test.go b/internal/identity/device_test.go index 9e0ab5a..55bb49e 100644 --- a/internal/identity/device_test.go +++ b/internal/identity/device_test.go @@ -121,3 +121,36 @@ func TestDeviceSaveLoad(t *testing.T) { t.Fatal("Save must not overwrite an existing device key") } } + +func TestRevokeAll(t *testing.T) { + root, _, _ := NewRoot() + oldDev, _ := Enroll(root, testNow.Add(-time.Hour), 24*time.Hour) + newDev, _ := Enroll(root, testNow, 24*time.Hour) // enrolled at the cutoff + other, _, _ := NewRoot() + foreign, _ := Enroll(other, testNow.Add(-time.Hour), 24*time.Hour) + + r, err := RevokeAll(root, testNow, 8) + if err != nil { + t.Fatal(err) + } + if err := r.Check(8); err != nil { + t.Fatal(err) + } + if !r.AllDevices() { + t.Fatal("expected an all-devices revocation") + } + if !r.Covers(oldDev.Cert) { + t.Fatal("older device must be covered") + } + if r.Covers(newDev.Cert) { + t.Fatal("device enrolled at the cutoff must stay valid") + } + if r.Covers(foreign.Cert) { + t.Fatal("another identity's device must not be covered") + } + + // It must outlive every certificate it covers. + if r.CertExpiresAt < oldDev.Cert.ExpiresAt { + t.Fatal("revocation would be dropped before the covered certificates expire") + } +} diff --git a/internal/identity/revocation.go b/internal/identity/revocation.go index fc5c788..bc0bf63 100644 --- a/internal/identity/revocation.go +++ b/internal/identity/revocation.go @@ -15,9 +15,12 @@ const ( ) // Revocation voids a device: every signature made by Device is rejected from -// now on. Nodes keep it until the device's certificate would have expired -// anyway (CertExpiresAt). It carries proof-of-work so nobody can flood the -// network with revocations for throwaway identities. +// now on. With Device empty it voids every device of Author whose certificate +// was issued before RevokedAt, which is what recovery on a new machine needs: +// the owner only has the phrase, not the old device's key. Nodes keep it +// until the certificates it covers would have expired anyway +// (CertExpiresAt). It carries proof-of-work so nobody can flood the network +// with revocations for throwaway identities. type Revocation struct { Version int `json:"v"` Author string `json:"author"` @@ -44,13 +47,27 @@ func Revoke(root *Identity, cert *Cert, at time.Time, difficulty int) (*Revocati if root.PublicKeyHex() != cert.Author { return nil, errors.New("identity: cert does not belong to this identity") } - r := &Revocation{ + return mineRevocation(root, &Revocation{ Version: RevocationVersion, Author: cert.Author, Device: cert.Device, RevokedAt: at.Unix(), CertExpiresAt: cert.ExpiresAt, - } + }, difficulty) +} + +// RevokeAll voids every device certified before at. Enroll the replacement +// device with the same timestamp: certificates issued at or after at stay valid. +func RevokeAll(root *Identity, at time.Time, difficulty int) (*Revocation, error) { + return mineRevocation(root, &Revocation{ + Version: RevocationVersion, + Author: root.PublicKeyHex(), + RevokedAt: at.Unix(), + CertExpiresAt: at.Add(MaxCertLifetime).Unix(), // older certs all expire before this + }, difficulty) +} + +func mineRevocation(root *Identity, r *Revocation, difficulty int) (*Revocation, error) { for ; ; r.PoW++ { b, err := r.signingBytes() if err != nil { @@ -63,12 +80,26 @@ func Revoke(root *Identity, cert *Cert, at time.Time, difficulty int) (*Revocati } } +// AllDevices reports whether r covers every earlier device of the author. +func (r *Revocation) AllDevices() bool { return r.Device == "" } + +// Covers reports whether r voids the device certified by c. +func (r *Revocation) Covers(c *Cert) bool { + if r.Author != c.Author { + return false + } + if r.AllDevices() { + return c.IssuedAt < r.RevokedAt + } + return r.Device == c.Device +} + // Check verifies structure, signature and proof-of-work. func (r *Revocation) Check(difficulty int) error { if r.Version != RevocationVersion { return errors.New("identity: unsupported revocation version") } - if !isHex(r.Author, 64) || !isHex(r.Device, 64) { + if !isHex(r.Author, 64) || (r.Device != "" && !isHex(r.Device, 64)) { return errors.New("identity: revocation keys must be 64 hex characters") } if r.PoW > 1<<53-1 { diff --git a/internal/listing/listing.go b/internal/listing/listing.go index 191a72d..ef87d6c 100644 --- a/internal/listing/listing.go +++ b/internal/listing/listing.go @@ -35,6 +35,10 @@ const ( listingContext = "allmende-listing-v1\n" ) +// DefaultDifficulty is the proof-of-work (leading zero bits) the network +// requires. All nodes must agree on it, or they reject each other's messages. +const DefaultDifficulty = 16 + // ErrTimeWindow marks failures caused by the clock (expired, or created in // the future). They are not the sender's fault, so the p2p layer ignores such // messages instead of penalizing the peer that relayed them. diff --git a/internal/p2p/node.go b/internal/p2p/node.go index 2b7d7b6..ddea1e1 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -39,7 +39,6 @@ const ( RevocationTopic = "/allmende/1/revocations" mdnsService = "allmende" - resyncInterval = 5 * time.Minute maintenanceTick = time.Hour ) @@ -53,10 +52,11 @@ type Config struct { Regions []string // geohash precision-3 cells to replicate MDNS bool // discover peers on the local network - Difficulty int // required proof-of-work bits - SyncPageSize int // records per sync page (default 500) - Clock func() time.Time // default time.Now - Logger *slog.Logger + Difficulty int // required proof-of-work bits + SyncPageSize int // records per sync page (default 500) + RedialInterval time.Duration // how often lost bootstrap peers are redialed (default 20s) + Clock func() time.Time // default time.Now + Logger *slog.Logger } // Node is a running participant. @@ -75,7 +75,8 @@ type Node struct { mu sync.Mutex topics map[string]*pubsub.Topic subscribed []string - synced map[peer.ID]time.Time + bootstrap []peer.AddrInfo + syncing map[peer.ID]bool revTopic *pubsub.Topic } @@ -95,6 +96,17 @@ func New(ctx context.Context, cfg Config) (*Node, error) { if cfg.SyncPageSize <= 0 { cfg.SyncPageSize = 500 } + if cfg.RedialInterval <= 0 { + cfg.RedialInterval = 20 * time.Second + } + var bootstrap []peer.AddrInfo + for _, addr := range cfg.Bootstrap { + ai, err := peer.AddrInfoFromString(addr) + if err != nil { + return nil, fmt.Errorf("p2p: bad bootstrap address %q: %w", addr, err) + } + bootstrap = append(bootstrap, *ai) + } priv, err := crypto.UnmarshalEd25519PrivateKey(cfg.Device.Key.PrivateKey()) if err != nil { @@ -107,14 +119,15 @@ func New(ctx context.Context, cfg Config) (*Node, error) { nctx, cancel := context.WithCancel(ctx) n := &Node{ - cfg: cfg, - host: h, - clock: cfg.Clock, - log: cfg.Logger, - ctx: nctx, - cancel: cancel, - topics: map[string]*pubsub.Topic{}, - synced: map[peer.ID]time.Time{}, + cfg: cfg, + host: h, + clock: cfg.Clock, + log: cfg.Logger, + ctx: nctx, + cancel: cancel, + topics: map[string]*pubsub.Topic{}, + syncing: map[peer.ID]bool{}, + bootstrap: bootstrap, } if n.clock == nil { n.clock = time.Now @@ -149,11 +162,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) { ConnectedF: func(_ network.Network, c network.Conn) { n.syncSoon(c.RemotePeer()) }, }) - for _, addr := range cfg.Bootstrap { - if err := n.Connect(nctx, addr); err != nil { - n.log.Warn("bootstrap peer unreachable", "addr", addr, "err", err) - } - } + n.dialBootstrap() if cfg.MDNS { n.mdns = mdns.NewMdnsService(h, mdnsService, &mdnsNotifee{n: n}) if err := n.mdns.Start(); err != nil { @@ -162,8 +171,9 @@ func New(ctx context.Context, cfg Config) (*Node, error) { } } - n.wg.Add(1) + n.wg.Add(2) go n.maintain() + go n.redial() return n, nil } @@ -192,6 +202,9 @@ func (n *Node) Connect(ctx context.Context, addr string) error { return n.host.Connect(ctx, *ai) } +// PeerCount returns the number of currently connected peers. +func (n *Node) PeerCount() int { return len(n.host.Network().Peers()) } + // RegionPeers lists peers known to be subscribed to the region's topic. func (n *Node) RegionPeers(region string) []peer.ID { return n.ps.ListPeers(listingTopicPrefix + region) @@ -366,7 +379,7 @@ func (n *Node) validateListing(ctx context.Context, data []byte) (*listing.Listi } return nil, pubsub.ValidationReject } - if revoked, err := n.cfg.Store.IsRevoked(ctx, l.Author, l.Device); err != nil || revoked { + if revoked, err := n.cfg.Store.IsRevoked(ctx, l.Author, l.Device, l.Cert.IssuedAt); err != nil || revoked { return nil, pubsub.ValidationIgnore } return &l, pubsub.ValidationAccept @@ -417,6 +430,40 @@ func (m *mdnsNotifee) HandlePeerFound(pi peer.AddrInfo) { }() } +// dialBootstrap connects to every configured bootstrap peer we are not +// already connected to. +func (n *Node) dialBootstrap() { + for _, ai := range n.bootstrap { + if n.host.Network().Connectedness(ai.ID) == network.Connected { + continue + } + ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second) + if err := n.host.Connect(ctx, ai); err != nil { + n.log.Warn("bootstrap peer unreachable", "peer", ai.ID, "err", err) + } + cancel() + } +} + +// redial keeps the node attached to its bootstrap peers across restarts and +// network outages on either side. +func (n *Node) redial() { + defer n.wg.Done() + if len(n.bootstrap) == 0 { + return + } + t := time.NewTicker(n.cfg.RedialInterval) + defer t.Stop() + for { + select { + case <-n.ctx.Done(): + return + case <-t.C: + n.dialBootstrap() + } + } +} + // maintain periodically drops expired data. func (n *Node) maintain() { defer n.wg.Done() diff --git a/internal/p2p/p2p_test.go b/internal/p2p/p2p_test.go index d73919f..19a03bb 100644 --- a/internal/p2p/p2p_test.go +++ b/internal/p2p/p2p_test.go @@ -6,6 +6,7 @@ import ( "errors" "io" "log/slog" + "os" "testing" "time" @@ -19,6 +20,14 @@ import ( const difficulty = 6 +// testLogger is silent unless P2P_DEBUG is set. +func testLogger() *slog.Logger { + if os.Getenv("P2P_DEBUG") != "" { + return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug})) + } + return slog.New(slog.NewTextHandler(io.Discard, nil)) +} + type tnode struct { *Node s *store.Store @@ -27,6 +36,11 @@ type tnode struct { } func startNode(t *testing.T, root *identity.Identity, regions ...string) *tnode { + t.Helper() + return startNodeWith(t, root, nil, regions...) +} + +func startNodeWith(t *testing.T, root *identity.Identity, tweak func(*Config), regions ...string) *tnode { t.Helper() if root == nil { root, _, _ = identity.NewRoot() @@ -39,15 +53,20 @@ func startNode(t *testing.T, root *identity.Identity, regions ...string) *tnode if err != nil { t.Fatal(err) } - n, err := New(context.Background(), Config{ - Device: dev, - Store: s, - ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, - Regions: regions, - Difficulty: difficulty, - SyncPageSize: 3, - Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), - }) + cfg := Config{ + Device: dev, + Store: s, + ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, + Regions: regions, + Difficulty: difficulty, + SyncPageSize: 3, + RedialInterval: 200 * time.Millisecond, + Logger: testLogger(), + } + if tweak != nil { + tweak(&cfg) + } + n, err := New(context.Background(), cfg) if err != nil { t.Fatal(err) } @@ -207,7 +226,7 @@ func TestRevocationPropagatesAndBlocks(t *testing.T) { late := startNode(t, nil, "u1x") connect(t, late, b) eventually(t, "late joiner learns the revocation", func() bool { - ok, _ := late.s.IsRevoked(ctx, a.dev.Cert.Author, a.dev.Cert.Device) + ok, _ := late.s.IsRevoked(ctx, a.dev.Cert.Author, a.dev.Cert.Device, a.dev.Cert.IssuedAt) return ok }) } @@ -255,3 +274,49 @@ func TestValidatorRejectsBadMessages(t *testing.T) { t.Fatalf("expired listing: %v", r) } } + +func TestRedialsBootstrapPeerAfterDisconnect(t *testing.T) { + a := startNode(t, nil, "u1x") + b := startNodeWith(t, nil, func(c *Config) { c.Bootstrap = []string{a.Addrs()[0]} }, "u1x") + eventually(t, "b connected to a", func() bool { return b.PeerCount() == 1 }) + + if err := b.host.Network().ClosePeer(a.ID()); err != nil { + t.Fatal(err) + } + eventually(t, "b redials its bootstrap peer", func() bool { return b.PeerCount() == 1 }) +} + +func TestEveryNewConnectionCatchesUp(t *testing.T) { + a := startNode(t, nil, "u1x") + b := startNode(t, nil, "u1x") + connect(t, b, a) + eventually(t, "first connection settled", func() bool { return len(b.RegionPeers("u1x")) == 1 }) + + // The link drops, and a gains a listing that is never gossiped to b. + l := a.listing(t, "u1xjhx") // sealed up front: proof-of-work is slow under -race + if err := b.host.Network().ClosePeer(a.ID()); err != nil { + t.Fatal(err) + } + eventually(t, "link is down", func() bool { return b.PeerCount() == 0 }) + if _, err := a.s.Put(context.Background(), l); err != nil { + t.Fatal(err) + } + + // A reconnect, however soon after the last sync, must catch up. + connect(t, b, a) + eventually(t, "b catches up after reconnecting", func() bool { return count(b) == 1 }) +} + +func TestBadBootstrapAddressRejectedUpFront(t *testing.T) { + root, _, _ := identity.NewRoot() + dev, _ := identity.Enroll(root, time.Now().Add(-time.Hour), 24*time.Hour) + s, _ := store.Open(":memory:", store.Options{Difficulty: difficulty}) + defer s.Close() + _, err := New(context.Background(), Config{ + Device: dev, Store: s, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, + Bootstrap: []string{"not-an-address"}, + }) + if err == nil { + t.Fatal("malformed bootstrap address accepted") + } +} diff --git a/internal/p2p/sync.go b/internal/p2p/sync.go index 914d453..2b4f5cf 100644 --- a/internal/p2p/sync.go +++ b/internal/p2p/sync.go @@ -105,19 +105,27 @@ func (n *Node) handleSync(s network.Stream) { // --- client --------------------------------------------------------------- -// syncSoon schedules a catch-up with p, at most once per resyncInterval. +// syncSoon starts a catch-up with p for a new connection. Every genuinely new +// connection syncs, so a peer that reconnects after a restart or outage gets +// everything it missed. Connections that arrive while a sync with the same +// peer is still running (e.g. TCP and QUIC opened together) are collapsed. func (n *Node) syncSoon(p peer.ID) { n.mu.Lock() - if last, ok := n.synced[p]; ok && n.clock().Sub(last) < resyncInterval { + if n.syncing[p] { n.mu.Unlock() return } - n.synced[p] = n.clock() + n.syncing[p] = true n.mu.Unlock() n.wg.Add(1) go func() { defer n.wg.Done() + defer func() { + n.mu.Lock() + delete(n.syncing, p) + n.mu.Unlock() + }() ctx, cancel := context.WithTimeout(n.ctx, syncTimeout) defer cancel() if err := n.SyncFrom(ctx, p); err != nil { diff --git a/internal/store/store.go b/internal/store/store.go index 185ffe5..c3bb7d7 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -58,6 +58,7 @@ CREATE TABLE IF NOT EXISTS listings ( author TEXT NOT NULL, id TEXT NOT NULL, device TEXT NOT NULL, + cert_issued_at INTEGER NOT NULL, seq INTEGER NOT NULL, hash TEXT NOT NULL, tombstone INTEGER NOT NULL, @@ -75,11 +76,13 @@ CREATE TABLE IF NOT EXISTS listings ( CREATE INDEX IF NOT EXISTS listings_geohash ON listings (geohash); CREATE INDEX IF NOT EXISTS listings_expires ON listings (expires_at); CREATE INDEX IF NOT EXISTS listings_device ON listings (author, device); +CREATE INDEX IF NOT EXISTS listings_cert ON listings (author, cert_issued_at); CREATE INDEX IF NOT EXISTS listings_created ON listings (created_at, author, id); CREATE TABLE IF NOT EXISTS revocations ( author TEXT NOT NULL, - device TEXT NOT NULL, + device TEXT NOT NULL, -- '' = every device certified before revoked_at + revoked_at INTEGER NOT NULL, cert_expires_at INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (author, device) @@ -140,9 +143,10 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) { defer tx.Rollback() var revoked int - err = tx.QueryRowContext(ctx, - `SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, l.Author, l.Device). - Scan(&revoked) + err = tx.QueryRowContext(ctx, ` + SELECT COUNT(*) FROM revocations + WHERE author = ? AND (device = ? OR (device = '' AND revoked_at > ?))`, + l.Author, l.Device, l.Cert.IssuedAt).Scan(&revoked) if err != nil { return Ignored, err } @@ -174,10 +178,10 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) { } _, err = tx.ExecContext(ctx, ` INSERT OR REPLACE INTO listings - (author, id, device, seq, hash, tombstone, created_at, expires_at, geohash, + (author, id, device, cert_issued_at, seq, hash, tombstone, created_at, expires_at, geohash, kind, category, price_cents, area_m2, rooms_x2, data) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - l.Author, l.ID, l.Device, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + l.Author, l.ID, l.Device, l.Cert.IssuedAt, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt, l.Geohash, l.Kind, l.Category, price, l.AreaM2, l.RoomsX2, data) if err != nil { return Ignored, err @@ -324,30 +328,17 @@ func (s *Store) Since(ctx context.Context, prefix string, cur Cursor, limit int) if err != nil { return nil, err } - defer rows.Close() - var out []*listing.Listing - for rows.Next() { - var data []byte - if err := rows.Scan(&data); err != nil { - return nil, err - } - l, err := decode(data) - if err != nil { - return nil, err - } - out = append(out, l) - } - return out, rows.Err() + return collect(rows) } -// PutRevocation verifies and stores a revocation, and removes every listing -// the revoked device signed. The owner re-publishes them from a new device. +// PutRevocation verifies and stores a revocation and removes every listing it +// voids. The owner republishes them from a new device. func (s *Store) PutRevocation(ctx context.Context, r *identity.Revocation) (Outcome, error) { if err := r.Check(s.difficulty); err != nil { return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err) } if r.CertExpiresAt <= s.clock().Unix() { - return Ignored, nil // the certificate is dead anyway + return Ignored, nil // everything it covers is dead anyway } data, err := r.Bytes() if err != nil { @@ -359,17 +350,31 @@ func (s *Store) PutRevocation(ctx context.Context, r *identity.Revocation) (Outc } defer tx.Rollback() - res, err := tx.ExecContext(ctx, - `INSERT OR IGNORE INTO revocations (author, device, cert_expires_at, data) VALUES (?, ?, ?, ?)`, - r.Author, r.Device, r.CertExpiresAt, data) + // Keep only the latest revocation per (author, device); for the + // all-devices form (device = '') that is the one with the newest cutoff. + res, err := tx.ExecContext(ctx, ` + INSERT INTO revocations (author, device, revoked_at, cert_expires_at, data) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT (author, device) DO UPDATE SET + revoked_at = excluded.revoked_at, + cert_expires_at = excluded.cert_expires_at, + data = excluded.data + WHERE excluded.revoked_at > revocations.revoked_at`, + r.Author, r.Device, r.RevokedAt, r.CertExpiresAt, data) if err != nil { return Ignored, err } if n, _ := res.RowsAffected(); n == 0 { return Ignored, nil // already known } - if _, err := tx.ExecContext(ctx, - `DELETE FROM listings WHERE author = ? AND device = ?`, r.Author, r.Device); err != nil { + if r.AllDevices() { + _, err = tx.ExecContext(ctx, + `DELETE FROM listings WHERE author = ? AND cert_issued_at < ?`, r.Author, r.RevokedAt) + } else { + _, err = tx.ExecContext(ctx, + `DELETE FROM listings WHERE author = ? AND device = ?`, r.Author, r.Device) + } + if err != nil { return Ignored, err } if err := tx.Commit(); err != nil { @@ -401,11 +406,14 @@ func (s *Store) Revocations(ctx context.Context) ([]*identity.Revocation, error) return out, rows.Err() } -// IsRevoked reports whether the device has been revoked. -func (s *Store) IsRevoked(ctx context.Context, author, device string) (bool, error) { +// IsRevoked reports whether the device, certified at certIssuedAt, has been +// voided by a revocation. +func (s *Store) IsRevoked(ctx context.Context, author, device string, certIssuedAt int64) (bool, error) { var n int - err := s.db.QueryRowContext(ctx, - `SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, author, device).Scan(&n) + err := s.db.QueryRowContext(ctx, ` + SELECT COUNT(*) FROM revocations + WHERE author = ? AND (device = ? OR (device = '' AND revoked_at > ?))`, + author, device, certIssuedAt).Scan(&n) return n > 0, err } @@ -437,6 +445,36 @@ func (s *Store) Count(ctx context.Context) (int, error) { return n, err } +// ByAuthor returns the author's live (not deleted, not expired) listings. +func (s *Store) ByAuthor(ctx context.Context, author string) ([]*listing.Listing, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT data FROM listings + WHERE author = ? AND tombstone = 0 AND expires_at > ? + ORDER BY created_at, id`, author, s.clock().Unix()) + if err != nil { + return nil, err + } + return collect(rows) +} + +// collect decodes a result set of listing blobs and closes it. +func collect(rows *sql.Rows) ([]*listing.Listing, error) { + defer rows.Close() + var out []*listing.Listing + for rows.Next() { + var data []byte + if err := rows.Scan(&data); err != nil { + return nil, err + } + l, err := decode(data) + if err != nil { + return nil, err + } + out = append(out, l) + } + return out, rows.Err() +} + func decode(data []byte) (*listing.Listing, error) { var l listing.Listing if err := json.Unmarshal(data, &l); err != nil { diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 1f8d799..6e4e7ad 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -467,3 +467,63 @@ func TestPersistence(t *testing.T) { t.Fatalf("listing lost after reopen: %v", err) } } + +func TestRevokeAllRecovery(t *testing.T) { + e := newEnv(t) + mine := e.listing(t, nil) + e.put(t, mine) + + // Recovery on a new machine: only the phrase is known. Everything issued + // before the cutoff is void; the replacement device is enrolled at the cutoff. + cutoff := e.now + rev, err := identity.RevokeAll(e.root, cutoff, difficulty) + if err != nil { + t.Fatal(err) + } + if o, err := e.s.PutRevocation(ctx, rev); err != nil || o != Inserted { + t.Fatalf("PutRevocation = %v, %v", o, err) + } + if _, err := e.s.Get(ctx, mine.Author, mine.ID); !errors.Is(err, ErrNotFound) { + t.Fatal("listing of an older device survived the revocation") + } + + // The old device can no longer publish, not even a fresh listing. + if _, err := e.s.Put(ctx, e.listing(t, nil)); !errors.Is(err, ErrRevoked) { + t.Fatalf("old device accepted: %v", err) + } + + // The replacement device (issued at the cutoff) works. + fresh, err := identity.Enroll(e.root, cutoff, 90*24*time.Hour) + if err != nil { + t.Fatal(err) + } + e.dev = fresh + again := *mine + again.Seq = 2 + if err := again.Seal(fresh, difficulty); err != nil { + t.Fatal(err) + } + if o := e.put(t, &again); o != Inserted { + t.Fatalf("republish from the new device: %v", o) + } + + // An older cutoff must not replace a newer one, and a repeat is ignored. + if o, _ := e.s.PutRevocation(ctx, rev); o != Ignored { + t.Fatalf("duplicate all-devices revocation: %v", o) + } + stale, _ := identity.RevokeAll(e.root, cutoff.Add(-time.Hour), difficulty) + if o, _ := e.s.PutRevocation(ctx, stale); o != Ignored { + t.Fatalf("older cutoff replaced a newer one: %v", o) + } + + // Other identities are unaffected. + otherRoot, _, _ := identity.NewRoot() + otherDev := newDevice(t, otherRoot) + theirs := e.listing(t, nil) + if err := theirs.Seal(otherDev, difficulty); err != nil { + t.Fatal(err) + } + if o := e.put(t, theirs); o != Inserted { + t.Fatalf("someone else's listing blocked: %v", o) + } +}