Renew the device certificate from the browser, with the recovery phrase
Within the last 30 days the owner page offers it. The node signs a new certificate for the same device key (peer ID and listings stay), saves it, and signs again own listings that would outlive the old certificate. The phrase is used for one request and not kept; another identity's phrase and no-phrase identities are refused. Device.Current gives the certificate to sign with while a renewal happens. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
@@ -23,7 +23,9 @@ bin/allmende init # or: make init
|
||||
|
||||
This prints your 12-word recovery phrase **once**. Write it down: it is the only
|
||||
way to get your identity and listings back if the machine is lost
|
||||
(`allmende recover`). Keys and the database live in the data directory,
|
||||
(`allmende recover`). The same words renew your device certificate, which lasts
|
||||
a year: in its last 30 days the owner page offers to renew it, and you type them
|
||||
once there. Keys and the database live in the data directory,
|
||||
`~/.local/share/allmende` by default (change it with `--data <dir>` or the
|
||||
`ALLMENDE_DATA` environment variable). Besides the numbered list, `init` prints the
|
||||
words as one plain line you can triple-click and paste into a password manager.
|
||||
|
||||
@@ -70,8 +70,10 @@ in the middle.
|
||||
The device key signs listings and is the libp2p peer ID. Lose the machine:
|
||||
`allmende recover` with the phrase signs a **revocation** and a new
|
||||
certificate. Lose the phrase: start a new identity (listings expire in 30
|
||||
days anyway). `init --no-phrase` creates an identity that cannot be renewed
|
||||
(used for the bootstrap node).
|
||||
days anyway). The same phrase renews the certificate from the owner page in
|
||||
its last 30 days (same device key; the node never stores the phrase).
|
||||
`init --no-phrase` creates an identity that cannot be renewed (used for the
|
||||
bootstrap node).
|
||||
- **Listings.** Canonical JSON (RFC 8785), ed25519 signatures, proof-of-work,
|
||||
geohash location, `seq`-based versions (higher wins), tombstones for
|
||||
deletion, at most 30 days to live (the owner renews by hand, so abandoned
|
||||
@@ -109,6 +111,7 @@ in the middle.
|
||||
| Abuse reports: record, gossip, sync, hide rule, tips, operator form and queue | done (phase 1) |
|
||||
| Place names for `--region` (GeoNames, CC BY 4.0) | done |
|
||||
| Expiry reminder in the terminal (≤5 days left) | done |
|
||||
| Device certificate renewal from the browser with the phrase (last 30 days; same device key, listings re-signed) | done |
|
||||
| Packaging: Dockerfile, Nix flake and module, `make image` | done |
|
||||
| Kubernetes bootstrap node (`k8s/`, kustomize, Traefik IngressRoute) | written and **deployed by the owner**; running image is older than digest sync, anti-entropy, reports |
|
||||
| Network simulator `cmd/allmende-sim`: 100-300 real nodes, latency, connection loss, attackers, seeds down, repair (results in docs/PROTOCOL.md) | done |
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
// publisher is what the keeper needs of the node: store a listing and gossip it.
|
||||
type publisher interface {
|
||||
Publish(ctx context.Context, l *listing.Listing) error
|
||||
}
|
||||
|
||||
// certKeeper renews the running node's device certificate from the recovery
|
||||
// phrase, which the owner types into the browser. The device key stays, so the
|
||||
// peer ID and every listing stay; only the certificate is replaced.
|
||||
type certKeeper struct {
|
||||
dev *identity.Device
|
||||
dir string
|
||||
store *store.Store
|
||||
node publisher
|
||||
difficulty int
|
||||
clock func() time.Time
|
||||
mu sync.Mutex // one renewal at a time
|
||||
}
|
||||
|
||||
func (k *certKeeper) CanRenew() bool {
|
||||
_, err := os.Stat(filepath.Join(k.dir, noRecoveryFile))
|
||||
return err != nil
|
||||
}
|
||||
|
||||
func (k *certKeeper) Renew(root *identity.Identity) (*identity.Cert, error) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
|
||||
now := k.clock()
|
||||
cert, err := k.dev.Renew(root, now, certLifetime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := k.dev.SaveCert(k.dir); err != nil {
|
||||
// The new certificate works until the node stops; say so, so the owner
|
||||
// does not believe it will survive a restart.
|
||||
return nil, fmt.Errorf("the certificate was renewed but could not be saved, so it is lost when the node stops: %w", err)
|
||||
}
|
||||
if err := k.resign(now); err != nil {
|
||||
return nil, fmt.Errorf("the certificate was renewed, but re-signing your listings failed: %w", err)
|
||||
}
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
// resign signs again, with the new certificate, every live listing of this
|
||||
// identity that would outlive the certificate it carries: a listing is refused
|
||||
// once its certificate has expired, whatever its own date says.
|
||||
func (k *certKeeper) resign(now time.Time) error {
|
||||
ctx := context.Background()
|
||||
own, err := k.store.ByAuthor(ctx, k.dev.Cert.Author)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, old := range own {
|
||||
if old.Cert == nil || old.Cert.ExpiresAt >= old.ExpiresAt {
|
||||
continue
|
||||
}
|
||||
l := *old
|
||||
l.Seq = old.Seq + 1
|
||||
l.CreatedAt = now.Unix()
|
||||
if err := l.Seal(k.dev, k.difficulty); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := k.node.Publish(ctx, &l); err != nil {
|
||||
return fmt.Errorf("listing %s: %w", old.ID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const keeperDifficulty = 6
|
||||
|
||||
// storePublisher is a node that only stores: enough to see what gets published.
|
||||
type storePublisher struct {
|
||||
st *store.Store
|
||||
published []*listing.Listing
|
||||
}
|
||||
|
||||
func (p *storePublisher) Publish(ctx context.Context, l *listing.Listing) error {
|
||||
if _, err := p.st.Put(ctx, l); err != nil {
|
||||
return err
|
||||
}
|
||||
p.published = append(p.published, l)
|
||||
return nil
|
||||
}
|
||||
|
||||
type keeperFixture struct {
|
||||
k *certKeeper
|
||||
root *identity.Identity
|
||||
dir string
|
||||
st *store.Store
|
||||
pub *storePublisher
|
||||
}
|
||||
|
||||
// newKeeper makes a device whose certificate runs out in certLeft.
|
||||
func newKeeper(t *testing.T, certLeft time.Duration) *keeperFixture {
|
||||
t.Helper()
|
||||
root, _, err := identity.NewRoot()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
dev, err := identity.Enroll(root, now.Add(-time.Hour), certLeft+time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if err := dev.Save(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := store.Open(":memory:", store.Options{Difficulty: keeperDifficulty})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
pub := &storePublisher{st: st}
|
||||
return &keeperFixture{
|
||||
k: &certKeeper{dev: dev, dir: dir, store: st, node: pub, difficulty: keeperDifficulty, clock: time.Now},
|
||||
root: root, dir: dir, st: st, pub: pub,
|
||||
}
|
||||
}
|
||||
|
||||
func (f *keeperFixture) add(t *testing.T, lives time.Duration) *listing.Listing {
|
||||
t.Helper()
|
||||
id, err := listing.NewID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
l := &listing.Listing{
|
||||
Version: listing.Version, ID: id, Seq: 1,
|
||||
CreatedAt: now.Add(-time.Minute).Unix(), ExpiresAt: now.Add(lives).Unix(),
|
||||
Kind: "rent", Category: "apartment", Geohash: "u1xjhx",
|
||||
Price: &listing.Price{AmountCents: 120000, Currency: "EUR", Period: "month"},
|
||||
AreaM2: 55, RoomsX2: 5, Features: []string{"balcony"}, Title: "Helle 2,5-Zimmer-Wohnung",
|
||||
}
|
||||
if err := l.Seal(f.k.dev, keeperDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.st.Put(context.Background(), l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func TestRenewingKeepsTheDeviceAndSavesTheNewCertificate(t *testing.T) {
|
||||
f := newKeeper(t, 10*24*time.Hour)
|
||||
oldExpiry := f.k.dev.Current().ExpiresAt
|
||||
|
||||
cert, err := f.k.Renew(f.root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cert.ExpiresAt <= oldExpiry+300*24*3600 {
|
||||
t.Fatalf("renewed certificate expires %d, only %d s after the old one", cert.ExpiresAt, cert.ExpiresAt-oldExpiry)
|
||||
}
|
||||
loaded, err := identity.LoadDevice(f.dir)
|
||||
if err != nil {
|
||||
t.Fatalf("what is on disk does not load: %v", err)
|
||||
}
|
||||
if loaded.Cert.ExpiresAt != cert.ExpiresAt {
|
||||
t.Fatalf("disk holds a certificate expiring %d, want the renewed %d: a restart would lose the renewal", loaded.Cert.ExpiresAt, cert.ExpiresAt)
|
||||
}
|
||||
if loaded.Key.PublicKeyHex() != f.k.dev.Key.PublicKeyHex() {
|
||||
t.Fatal("renewing must not change the device key (it is the peer ID)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewingSignsAgainOnlyTheListingsThatWouldOutliveTheOldCertificate(t *testing.T) {
|
||||
f := newKeeper(t, 10*24*time.Hour)
|
||||
short := f.add(t, 5*24*time.Hour) // gone before the old certificate runs out
|
||||
long := f.add(t, 25*24*time.Hour) // would be refused after day 10
|
||||
|
||||
if _, err := f.k.Renew(f.root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(f.pub.published) != 1 {
|
||||
t.Fatalf("%d listings were signed again, want exactly the long one", len(f.pub.published))
|
||||
}
|
||||
got := f.pub.published[0]
|
||||
if got.ID != long.ID || got.Seq != long.Seq+1 {
|
||||
t.Fatalf("re-signed %s seq %d, want %s seq %d", got.ID, got.Seq, long.ID, long.Seq+1)
|
||||
}
|
||||
if got.ExpiresAt != long.ExpiresAt {
|
||||
t.Fatal("re-signing must not change when the listing expires")
|
||||
}
|
||||
if got.Cert.ExpiresAt <= got.ExpiresAt {
|
||||
t.Fatal("the re-signed listing must carry a certificate that outlives it")
|
||||
}
|
||||
if err := got.Check(time.Now(), keeperDifficulty); err != nil {
|
||||
t.Fatalf("the re-signed listing does not verify: %v", err)
|
||||
}
|
||||
stored, err := f.st.Get(context.Background(), short.Author, short.ID)
|
||||
if err != nil || stored.Seq != short.Seq {
|
||||
t.Fatalf("the short listing must be left alone: %v seq %d", err, stored.Seq)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewingWithTheWrongIdentityChangesNothing(t *testing.T) {
|
||||
f := newKeeper(t, 10*24*time.Hour)
|
||||
f.add(t, 25*24*time.Hour)
|
||||
stranger, _, _ := identity.NewRoot()
|
||||
before := f.k.dev.Current().ExpiresAt
|
||||
|
||||
if _, err := f.k.Renew(stranger); err != identity.ErrWrongIdentity {
|
||||
t.Fatalf("err = %v, want ErrWrongIdentity", err)
|
||||
}
|
||||
if f.k.dev.Current().ExpiresAt != before {
|
||||
t.Fatal("the certificate changed")
|
||||
}
|
||||
if len(f.pub.published) != 0 {
|
||||
t.Fatal("no listing may be signed again after a refused renewal")
|
||||
}
|
||||
loaded, err := identity.LoadDevice(f.dir)
|
||||
if err != nil || loaded.Cert.ExpiresAt != before {
|
||||
t.Fatalf("the saved certificate changed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnIdentityWithoutAPhraseCannotBeRenewed(t *testing.T) {
|
||||
f := newKeeper(t, 10*24*time.Hour)
|
||||
if !f.k.CanRenew() {
|
||||
t.Fatal("an identity with a phrase must be renewable")
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(f.dir, noRecoveryFile), []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.k.CanRenew() {
|
||||
t.Fatal("init --no-phrase marks the directory: renewal must be off")
|
||||
}
|
||||
}
|
||||
+9
-4
@@ -112,16 +112,20 @@ func cmdRun(args []string) error {
|
||||
return err
|
||||
}
|
||||
until := time.Until(time.Unix(dev.Cert.ExpiresAt, 0))
|
||||
renew := "run 'allmende recover' to renew it"
|
||||
// An expired certificate stops the node, so the browser is out of reach
|
||||
// then and only 'recover' helps; before that the owner can renew in the browser.
|
||||
renewExpired := "run 'allmende recover' to renew it"
|
||||
renewSoon := "renew it in the browser (sign in, then \"Renew certificate\" on your listings page) or run 'allmende recover'"
|
||||
if _, err := os.Stat(filepath.Join(*data, noRecoveryFile)); err == nil {
|
||||
renew = "this identity has no recovery phrase, so it cannot be renewed: start over with 'allmende init --no-phrase' on an empty data directory (a new identity, so update any DNS records that name this node)"
|
||||
renewExpired = "this identity has no recovery phrase, so it cannot be renewed: start over with 'allmende init --no-phrase' on an empty data directory (a new identity, so update any DNS records that name this node)"
|
||||
renewSoon = renewExpired
|
||||
}
|
||||
if until <= 0 {
|
||||
return errors.New("this device's certificate has expired; " + renew)
|
||||
return errors.New("this device's certificate has expired; " + renewExpired)
|
||||
}
|
||||
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
|
||||
if until < certWarnBefore {
|
||||
log.Warn("device certificate expires soon; "+renew,
|
||||
log.Warn("device certificate expires soon; "+renewSoon,
|
||||
"expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
|
||||
}
|
||||
|
||||
@@ -174,6 +178,7 @@ func cmdRun(args []string) error {
|
||||
MessageDifficulty: *msgDifficulty,
|
||||
Inbox: in,
|
||||
RegionKeeper: ®ionKeeper{node: node, dir: *data},
|
||||
CertKeeper: &certKeeper{dev: dev, dir: *data, store: st, node: node, difficulty: *difficulty, clock: time.Now},
|
||||
})
|
||||
|
||||
ln, err := net.Listen("tcp", *httpAddr)
|
||||
|
||||
+2
-1
@@ -449,7 +449,8 @@ 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/status` | no | peer ID, addresses, identity, regions, peer and listing counts, `cert_expires_at` (unix seconds) and `can_renew` |
|
||||
| `PUT /api/v1/certificate` | token | `{"phrase": "<12 words>"}`: renew the device certificate (see "Recovery" and renewal above); answers `{"cert_expires_at"}`. 400 malformed phrase, 409 another identity's phrase or an identity without a phrase |
|
||||
| `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 |
|
||||
|
||||
@@ -53,6 +53,18 @@ type Config struct {
|
||||
// RegionKeeper lets the owner change the regions the node follows while it
|
||||
// runs. Without it Regions is fixed and the endpoint is absent.
|
||||
RegionKeeper RegionKeeper
|
||||
// CertKeeper renews the device certificate from the recovery phrase. Without
|
||||
// it the endpoint is absent and the node reports that it cannot renew.
|
||||
CertKeeper CertKeeper
|
||||
}
|
||||
|
||||
// CertKeeper renews this node's device certificate and makes it stick: the
|
||||
// same device key, a new certificate, saved, and the node's own listings
|
||||
// signed with it where the old one would run out first.
|
||||
type CertKeeper interface {
|
||||
// CanRenew is false for an identity made without a recovery phrase.
|
||||
CanRenew() bool
|
||||
Renew(root *identity.Identity) (*identity.Cert, error)
|
||||
}
|
||||
|
||||
// RegionKeeper holds the regions a node follows: it applies and remembers a change.
|
||||
@@ -101,6 +113,9 @@ func New(cfg Config) http.Handler {
|
||||
if cfg.RegionKeeper != nil {
|
||||
mux.HandleFunc("PUT /api/v1/regions", s.admin(s.putRegions))
|
||||
}
|
||||
if cfg.CertKeeper != nil {
|
||||
mux.HandleFunc("PUT /api/v1/certificate", s.admin(s.putCertificate))
|
||||
}
|
||||
|
||||
// Messaging: public relay endpoints for buyers' browsers...
|
||||
mux.HandleFunc("POST /api/v1/messages", s.postMessage)
|
||||
@@ -175,6 +190,10 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
|
||||
"regions": s.regions(),
|
||||
"peers": s.Node.PeerCount(),
|
||||
"listings": n,
|
||||
// When this node's device certificate runs out (it is public: it
|
||||
// travels with every listing) and whether the owner can renew it here.
|
||||
"cert_expires_at": s.Device.Current().ExpiresAt,
|
||||
"can_renew": s.CertKeeper != nil && s.CertKeeper.CanRenew(),
|
||||
// Lets the browser report how much anti-spam work a listing carries.
|
||||
"difficulty": s.Difficulty,
|
||||
"message_difficulty": s.MessageDifficulty,
|
||||
@@ -307,6 +326,38 @@ func (s *server) admin(next http.HandlerFunc) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// putCertificate renews the device certificate from the recovery phrase. The
|
||||
// phrase is used for this one request and not kept; it never leaves the node
|
||||
// the owner is signed in to, but it does cross the connection to it, so over
|
||||
// anything but localhost the node must sit behind TLS (as for the admin token).
|
||||
func (s *server) putCertificate(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Phrase string `json:"phrase"`
|
||||
}
|
||||
if !decodeBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if !s.CertKeeper.CanRenew() {
|
||||
fail(w, http.StatusConflict, "this identity has no recovery phrase, so its certificate cannot be renewed")
|
||||
return
|
||||
}
|
||||
root, err := identity.FromPhrase(body.Phrase)
|
||||
if err != nil {
|
||||
fail(w, http.StatusBadRequest, "that is not a valid recovery phrase: check the twelve words")
|
||||
return
|
||||
}
|
||||
cert, err := s.CertKeeper.Renew(root)
|
||||
switch {
|
||||
case errors.Is(err, identity.ErrWrongIdentity):
|
||||
fail(w, http.StatusConflict, "these words belong to a different identity than this node")
|
||||
return
|
||||
case err != nil:
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"cert_expires_at": cert.ExpiresAt})
|
||||
}
|
||||
|
||||
// putRegions changes the regions the node follows, at once and for good.
|
||||
func (s *server) putRegions(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
|
||||
@@ -29,13 +29,14 @@ type fixture struct {
|
||||
srv *httptest.Server
|
||||
s *store.Store
|
||||
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, _, _ := identity.NewRoot()
|
||||
root, phrase, _ := identity.NewRoot()
|
||||
dev, err := identity.Enroll(root, time.Now().Add(-time.Hour), 90*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -66,7 +67,7 @@ func newFixture(t *testing.T, tok string, tweak ...func(*Config)) *fixture {
|
||||
}
|
||||
srv := httptest.NewServer(New(cfg))
|
||||
t.Cleanup(func() { srv.Close(); node.Close(); s.Close() })
|
||||
return &fixture{srv: srv, s: s, dev: dev}
|
||||
return &fixture{srv: srv, s: s, dev: dev, phrase: phrase}
|
||||
}
|
||||
|
||||
func (f *fixture) do(t *testing.T, method, path, body string, auth bool) (int, []byte) {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
)
|
||||
|
||||
// fakeKeeper renews the device in memory, like the real one minus the disk.
|
||||
type fakeKeeper struct {
|
||||
dev *identity.Device
|
||||
canRenew bool
|
||||
renewed int
|
||||
}
|
||||
|
||||
func (k *fakeKeeper) CanRenew() bool { return k.canRenew }
|
||||
|
||||
func (k *fakeKeeper) Renew(root *identity.Identity) (*identity.Cert, error) {
|
||||
k.renewed++
|
||||
return k.dev.Renew(root, time.Now(), 365*24*time.Hour)
|
||||
}
|
||||
|
||||
// withKeeper installs a keeper for the fixture's own device.
|
||||
func withKeeper(canRenew bool) (func(*Config), **fakeKeeper) {
|
||||
var k *fakeKeeper
|
||||
return func(c *Config) {
|
||||
k = &fakeKeeper{dev: c.Device, canRenew: canRenew}
|
||||
c.CertKeeper = k
|
||||
}, &k
|
||||
}
|
||||
|
||||
type certStatus struct {
|
||||
CertExpiresAt int64 `json:"cert_expires_at"`
|
||||
CanRenew bool `json:"can_renew"`
|
||||
}
|
||||
|
||||
func (f *fixture) certStatus(t *testing.T) certStatus {
|
||||
t.Helper()
|
||||
code, body := f.do(t, "GET", "/api/v1/status", "", false)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("status: %d %s", code, body)
|
||||
}
|
||||
var s certStatus
|
||||
if err := json.Unmarshal(body, &s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestStatusReportsWhenTheCertificateExpiresAndWhetherItCanBeRenewed(t *testing.T) {
|
||||
tweak, _ := withKeeper(true)
|
||||
f := newFixture(t, token, tweak)
|
||||
s := f.certStatus(t)
|
||||
if s.CertExpiresAt != f.dev.Cert.ExpiresAt {
|
||||
t.Fatalf("cert_expires_at = %d, want %d", s.CertExpiresAt, f.dev.Cert.ExpiresAt)
|
||||
}
|
||||
if !s.CanRenew {
|
||||
t.Fatal("a node with a recovery phrase must say it can renew")
|
||||
}
|
||||
|
||||
noPhrase, _ := withKeeper(false)
|
||||
g := newFixture(t, token, noPhrase)
|
||||
if g.certStatus(t).CanRenew {
|
||||
t.Fatal("an identity without a recovery phrase must not offer renewal")
|
||||
}
|
||||
plain := newFixture(t, token)
|
||||
if plain.certStatus(t).CanRenew {
|
||||
t.Fatal("a node without a keeper must not offer renewal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewingFromThePhraseExtendsTheCertificate(t *testing.T) {
|
||||
tweak, keeper := withKeeper(true)
|
||||
f := newFixture(t, token, tweak)
|
||||
before := f.certStatus(t).CertExpiresAt
|
||||
|
||||
code, body := f.do(t, "PUT", "/api/v1/certificate", `{"phrase":"`+f.phrase+`"}`, true)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("renew: %d %s", code, body)
|
||||
}
|
||||
var out certStatus
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after := f.certStatus(t).CertExpiresAt
|
||||
if after <= before {
|
||||
t.Fatalf("expiry %d did not move past %d", after, before)
|
||||
}
|
||||
if out.CertExpiresAt != after {
|
||||
t.Fatalf("the reply says %d but status says %d", out.CertExpiresAt, after)
|
||||
}
|
||||
if (*keeper).renewed != 1 {
|
||||
t.Fatalf("the keeper renewed %d times, want 1", (*keeper).renewed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewingNeedsTheAdminToken(t *testing.T) {
|
||||
tweak, keeper := withKeeper(true)
|
||||
f := newFixture(t, token, tweak)
|
||||
code, _ := f.do(t, "PUT", "/api/v1/certificate", `{"phrase":"`+f.phrase+`"}`, false)
|
||||
if code != http.StatusUnauthorized {
|
||||
t.Fatalf("without the token: %d, want 401", code)
|
||||
}
|
||||
if (*keeper).renewed != 0 {
|
||||
t.Fatal("nothing may be renewed without the token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewingWithAnotherIdentitysPhraseIsRefusedAndChangesNothing(t *testing.T) {
|
||||
tweak, _ := withKeeper(true)
|
||||
f := newFixture(t, token, tweak)
|
||||
_, other, _ := identity.NewRoot()
|
||||
before := f.certStatus(t).CertExpiresAt
|
||||
|
||||
code, body := f.do(t, "PUT", "/api/v1/certificate", `{"phrase":"`+other+`"}`, true)
|
||||
if code != http.StatusConflict || !strings.Contains(string(body), "different identity") {
|
||||
t.Fatalf("another identity's phrase: %d %s, want 409 naming the different identity", code, body)
|
||||
}
|
||||
if after := f.certStatus(t).CertExpiresAt; after != before {
|
||||
t.Fatalf("a refused renewal moved the expiry from %d to %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewingWithAnInvalidPhraseIsABadRequest(t *testing.T) {
|
||||
tweak, keeper := withKeeper(true)
|
||||
f := newFixture(t, token, tweak)
|
||||
for _, phrase := range []string{"", "not twelve words", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"} {
|
||||
code, body := f.do(t, "PUT", "/api/v1/certificate", `{"phrase":"`+phrase+`"}`, true)
|
||||
if code != http.StatusBadRequest {
|
||||
t.Fatalf("phrase %q: %d %s, want 400", phrase, code, body)
|
||||
}
|
||||
}
|
||||
if (*keeper).renewed != 0 {
|
||||
t.Fatal("an invalid phrase must never reach the keeper")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewingIsRefusedForAnIdentityWithoutAPhrase(t *testing.T) {
|
||||
tweak, keeper := withKeeper(false)
|
||||
f := newFixture(t, token, tweak)
|
||||
code, body := f.do(t, "PUT", "/api/v1/certificate", `{"phrase":"`+f.phrase+`"}`, true)
|
||||
if code != http.StatusConflict || !strings.Contains(string(body), "no recovery phrase") {
|
||||
t.Fatalf("no-phrase identity: %d %s, want 409 saying there is no recovery phrase", code, body)
|
||||
}
|
||||
if (*keeper).renewed != 0 {
|
||||
t.Fatal("nothing may be renewed")
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,47 @@ import (
|
||||
// ties it to an identity. The identity key itself is never stored.
|
||||
type Device struct {
|
||||
Key *Identity
|
||||
// Cert is the certificate the device was created or loaded with. Its
|
||||
// Author and Device never change, so they can be read from it at any time.
|
||||
// A renewal replaces the certificate to sign with, not this field: use
|
||||
// Current for that (and for the expiry).
|
||||
Cert *Cert
|
||||
|
||||
mu sync.RWMutex
|
||||
cur *Cert // set by Renew; nil until then
|
||||
}
|
||||
|
||||
// Current is the certificate to sign with and to report the expiry of. It is
|
||||
// safe to call while another goroutine renews.
|
||||
func (d *Device) Current() *Cert {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
if d.cur != nil {
|
||||
return d.cur
|
||||
}
|
||||
return d.Cert
|
||||
}
|
||||
|
||||
// ErrWrongIdentity means the identity key offered for a renewal is not the
|
||||
// one that certified this device.
|
||||
var ErrWrongIdentity = errors.New("identity: these words belong to a different identity than this device")
|
||||
|
||||
// Renew certifies this same device key again, for validFor from now, with the
|
||||
// identity key root. The device key does not change, so neither does the
|
||||
// node's peer ID, and nothing is revoked. Only the identity that certified
|
||||
// the device can do it.
|
||||
func (d *Device) Renew(root *Identity, now time.Time, validFor time.Duration) (*Cert, error) {
|
||||
if root.PublicKeyHex() != d.Cert.Author {
|
||||
return nil, ErrWrongIdentity
|
||||
}
|
||||
cert, err := IssueCert(root, d.Cert.Device, now, now.Add(validFor))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.mu.Lock()
|
||||
d.cur = cert
|
||||
d.mu.Unlock()
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
// Enroll creates a new device key and certifies it with the identity key.
|
||||
@@ -44,7 +85,7 @@ func (d *Device) Save(dir string) error {
|
||||
|
||||
// SaveCert (over)writes only the certificate, e.g. after renewal.
|
||||
func (d *Device) SaveCert(dir string) error {
|
||||
data, err := json.Marshal(d.Cert)
|
||||
data, err := json.Marshal(d.Current())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -154,3 +154,107 @@ func TestRevokeAll(t *testing.T) {
|
||||
t.Fatal("revocation would be dropped before the covered certificates expire")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewCertifiesTheSameDeviceKeyAgain(t *testing.T) {
|
||||
root, _, _ := NewRoot()
|
||||
dev, err := Enroll(root, testNow, 30*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := dev.Current()
|
||||
if first != dev.Cert {
|
||||
t.Fatal("before a renewal the current certificate is the one the device has")
|
||||
}
|
||||
|
||||
later := testNow.Add(20 * 24 * time.Hour)
|
||||
renewed, err := dev.Renew(root, later, 365*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := renewed.Check(); err != nil {
|
||||
t.Fatalf("the renewed certificate must verify: %v", err)
|
||||
}
|
||||
if renewed.Device != first.Device || renewed.Author != first.Author {
|
||||
t.Fatal("a renewal must keep the device key (and so the peer ID) and the identity")
|
||||
}
|
||||
if renewed.IssuedAt != later.Unix() || renewed.ExpiresAt != later.Add(365*24*time.Hour).Unix() {
|
||||
t.Fatalf("renewed cert runs %d to %d, want %d for a year", renewed.IssuedAt, renewed.ExpiresAt, later.Unix())
|
||||
}
|
||||
if dev.Current() != renewed {
|
||||
t.Fatal("Current must return the renewed certificate")
|
||||
}
|
||||
if dev.Cert != first {
|
||||
t.Fatal("the loaded certificate field must not change: other goroutines read it")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyTheIdentityThatCertifiedTheDeviceCanRenewIt(t *testing.T) {
|
||||
root, _, _ := NewRoot()
|
||||
stranger, _, _ := NewRoot()
|
||||
dev, _ := Enroll(root, testNow, 30*24*time.Hour)
|
||||
before := dev.Current()
|
||||
|
||||
if _, err := dev.Renew(stranger, testNow, 365*24*time.Hour); err != ErrWrongIdentity {
|
||||
t.Fatalf("a different identity renewing: err = %v, want ErrWrongIdentity", err)
|
||||
}
|
||||
if dev.Current() != before {
|
||||
t.Fatal("a refused renewal must leave the certificate alone")
|
||||
}
|
||||
if _, err := dev.Renew(root, testNow, 400*24*time.Hour); err == nil {
|
||||
t.Fatal("a certificate longer than the maximum must be refused")
|
||||
}
|
||||
if dev.Current() != before {
|
||||
t.Fatal("a refused renewal must leave the certificate alone")
|
||||
}
|
||||
}
|
||||
|
||||
func TestARenewedCertificateIsWhatGetsSavedAndLoaded(t *testing.T) {
|
||||
root, _, _ := NewRoot()
|
||||
dev, _ := Enroll(root, testNow, 30*24*time.Hour)
|
||||
dir := t.TempDir()
|
||||
if err := dev.Save(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
renewed, err := dev.Renew(root, testNow.Add(24*time.Hour), 365*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := dev.SaveCert(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := LoadDevice(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded.Cert.ExpiresAt != renewed.ExpiresAt || loaded.Cert.Device != dev.Cert.Device {
|
||||
t.Fatalf("loaded cert expires %d, want %d: the renewal was not saved", loaded.Cert.ExpiresAt, renewed.ExpiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
// Handlers sign while a renewal happens; run with -race.
|
||||
func TestRenewWhileOthersSign(t *testing.T) {
|
||||
root, _, _ := NewRoot()
|
||||
dev, _ := Enroll(root, testNow, 30*24*time.Hour)
|
||||
done := make(chan struct{})
|
||||
for i := 0; i < 4; i++ {
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
default:
|
||||
if c := dev.Current(); c.Device != dev.Cert.Device {
|
||||
t.Error("a reader saw a certificate for another device")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for i := 0; i < 50; i++ {
|
||||
if _, err := dev.Renew(root, testNow.Add(time.Duration(i)*time.Hour), 365*24*time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
close(done)
|
||||
}
|
||||
|
||||
@@ -145,9 +145,10 @@ func (l *Listing) powOK(difficulty int) (bool, error) {
|
||||
// Seal fills in author, device and certificate from dev, mines the
|
||||
// proof-of-work and signs the listing with the device key.
|
||||
func (l *Listing) Seal(dev *identity.Device, difficulty int) error {
|
||||
l.Author = dev.Cert.Author
|
||||
l.Device = dev.Cert.Device
|
||||
l.Cert = dev.Cert
|
||||
cert := dev.Current()
|
||||
l.Author = cert.Author
|
||||
l.Device = cert.Device
|
||||
l.Cert = cert
|
||||
l.Sig = ""
|
||||
for l.PoW = 0; ; l.PoW++ {
|
||||
if l.PoW > maxSafeInt {
|
||||
|
||||
@@ -75,8 +75,9 @@ func (p *Plain) unsignedBytes() ([]byte, error) {
|
||||
|
||||
func (p *Plain) signOwner(dev *identity.Device, ref Ref) {
|
||||
p.Listing = &Ref{Author: ref.Author, ID: ref.ID}
|
||||
p.Device = dev.Cert.Device
|
||||
p.Cert = dev.Cert
|
||||
cert := dev.Current()
|
||||
p.Device = cert.Device
|
||||
p.Cert = cert
|
||||
p.Sig = ""
|
||||
b, _ := p.unsignedBytes() // cannot fail for the types in Plain
|
||||
p.Sig = hex.EncodeToString(dev.Key.Sign(append([]byte(replyContext), b...)))
|
||||
|
||||
@@ -102,9 +102,10 @@ func (r *Report) Hash() (string, error) {
|
||||
// Seal fills in the reporter from dev, mines the proof-of-work and signs.
|
||||
func (r *Report) Seal(dev *identity.Device, difficulty int) error {
|
||||
r.Version = Version
|
||||
r.Reporter = dev.Cert.Author
|
||||
r.Device = dev.Cert.Device
|
||||
r.Cert = dev.Cert
|
||||
cert := dev.Current()
|
||||
r.Reporter = cert.Author
|
||||
r.Device = cert.Device
|
||||
r.Cert = cert
|
||||
r.Sig = ""
|
||||
for r.PoW = 0; ; r.PoW++ {
|
||||
if r.PoW > maxSafeInt {
|
||||
|
||||
@@ -141,6 +141,26 @@ sleep 1 # a newer report must be dated a second later
|
||||
curl -s -X POST -H "Authorization: Bearer $TOKEN" -d "${REPORT/scam/withdrawn}" http://127.0.0.1:18101/api/v1/reports >/dev/null
|
||||
[ "$(count 18101 '')" = 1 ] && ok "withdrawing the report shows the listing again" || bad "a withdrawn report still hides it"
|
||||
|
||||
echo "== renewing the device certificate from the browser, with the phrase"
|
||||
status_field() { curl -s http://127.0.0.1:18101/api/v1/status | python3 -c "import json,sys; print(json.load(sys.stdin)[\"$1\"])"; }
|
||||
CERT_BEFORE=$(status_field cert_expires_at)
|
||||
[ "$(status_field can_renew)" = True ] && ok "status says the certificate can be renewed, and until when ($CERT_BEFORE)" || bad "status does not offer renewal"
|
||||
renew_code() { curl -s -o /dev/null -w "%{http_code}" -X PUT ${2:+-H "Authorization: Bearer $2"} -d "{\"phrase\":\"$1\"}" http://127.0.0.1:18101/api/v1/certificate; }
|
||||
[ "$(renew_code "$PHRASE")" = 401 ] && ok "renewal without the admin token is refused" || bad "renewal worked without a token"
|
||||
PHRASE_B=$(grep -E '^ +[0-9]+\.' $W/init-b.txt | sed -E 's/[0-9]+\.//g' | tr -s ' \n' ' ' | sed 's/^ //; s/ $//')
|
||||
[ "$(renew_code "$PHRASE_B" "$TOKEN")" = 409 ] && ok "another identity's phrase is refused" || bad "renewed with the wrong identity's phrase"
|
||||
[ "$(renew_code "wrong words here" "$TOKEN")" = 400 ] && ok "a malformed phrase is refused" || bad "a malformed phrase was accepted"
|
||||
[ "$(status_field cert_expires_at)" = "$CERT_BEFORE" ] && ok "refused renewals changed nothing" || bad "a refused renewal moved the expiry"
|
||||
sleep 1.2 # the new certificate must be dated a second later to expire later
|
||||
[ "$(renew_code "$PHRASE" "$TOKEN")" = 200 ] && ok "the owner's phrase renews it" || bad "renewal with the right phrase failed"
|
||||
CERT_AFTER=$(status_field cert_expires_at)
|
||||
[ "$CERT_AFTER" -gt "$CERT_BEFORE" ] && ok "the certificate now runs until $CERT_AFTER" || bad "expiry did not move: $CERT_BEFORE -> $CERT_AFTER"
|
||||
[ "$(status_field peer_id)" = "$PEER" ] && ok "same device key, same peer ID" || bad "renewing changed the peer ID"
|
||||
grep -q "\"expires_at\":$CERT_AFTER" $A/device.cert && ok "the new certificate is saved, so a restart keeps it" || bad "device.cert does not hold the renewal"
|
||||
grep -rqi "$(echo $PHRASE | cut -d' ' -f1-3)" $A && bad "the phrase was written to the data directory"
|
||||
ok "the phrase was not stored"
|
||||
[ "$(count 18101 '')" = 1 ] && ok "the owner's listing is untouched" || bad "renewal disturbed the listing"
|
||||
|
||||
echo "== recover on A (simulate a stolen machine)"
|
||||
OLD_DEVICE=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["device"])')
|
||||
kill ${PIDS[0]}; wait ${PIDS[0]} 2>/dev/null
|
||||
|
||||
Vendored
+97
-5
@@ -233,6 +233,16 @@ var de = {
|
||||
"rep.done": "Gemeldet.",
|
||||
"rep.withdrawn": "Zur\xFCckgezogen.",
|
||||
"rep.mine": "Deine Meldung: {what}.",
|
||||
"cert.title": "Ger\xE4te-Zertifikat",
|
||||
"cert.soon": "Das Zertifikat dieses Knotens l\xE4uft am {date} ab (in {n} Tagen). Danach geht der Knoten nicht mehr an und deine Anzeigen verschwinden.",
|
||||
"cert.expired": "Das Zertifikat dieses Knotens ist am {date} abgelaufen. Erneuere es jetzt.",
|
||||
"cert.noPhrase": "Diese Identit\xE4t hat keine Wiederherstellungsphrase und l\xE4sst sich nicht erneuern. Lege mit \u201Eallmende init --no-phrase\u201C in einem leeren Datenverzeichnis eine neue an.",
|
||||
"cert.intro": "Gib die zw\xF6lf W\xF6rter deiner Wiederherstellungsphrase ein. Der Knoten stellt damit ein neues Zertifikat aus und vergisst sie sofort wieder. Der Schl\xFCssel des Ger\xE4ts bleibt gleich, nichts wird widerrufen.",
|
||||
"cert.phrase": "Die zw\xF6lf W\xF6rter",
|
||||
"cert.renew": "Zertifikat erneuern",
|
||||
"cert.working": "Wird erneuert \u2026",
|
||||
"cert.done": "Erneuert. Das Zertifikat gilt jetzt bis zum {date}.",
|
||||
"cert.fail": "Das hat nicht geklappt: {detail}",
|
||||
"rep.title": "Meldungen",
|
||||
"rep.tipsIntro": "Hinweise von Besuchern dieses Knotens. Sie blenden nichts aus: du entscheidest, ob du selbst meldest.",
|
||||
"rep.none": "Keine Hinweise von Besuchern.",
|
||||
@@ -521,6 +531,16 @@ var en = {
|
||||
"rep.done": "Reported.",
|
||||
"rep.withdrawn": "Withdrawn.",
|
||||
"rep.mine": "Your report: {what}.",
|
||||
"cert.title": "Device certificate",
|
||||
"cert.soon": "This node's certificate expires on {date} (in {n} days). After that the node will not start and your listings disappear.",
|
||||
"cert.expired": "This node's certificate expired on {date}. Renew it now.",
|
||||
"cert.noPhrase": "This identity has no recovery phrase, so it cannot be renewed. Make a new one with \u201Callmende init --no-phrase\u201D in an empty data directory.",
|
||||
"cert.intro": "Enter the twelve words of your recovery phrase. The node signs a new certificate with them and forgets them at once. The device key stays the same and nothing is revoked.",
|
||||
"cert.phrase": "The twelve words",
|
||||
"cert.renew": "Renew certificate",
|
||||
"cert.working": "Renewing\u2026",
|
||||
"cert.done": "Renewed. The certificate is now valid until {date}.",
|
||||
"cert.fail": "That did not work: {detail}",
|
||||
"rep.title": "Reports",
|
||||
"rep.tipsIntro": "Tips from visitors of this node. They hide nothing: you decide whether to report yourself.",
|
||||
"rep.none": "No tips from visitors.",
|
||||
@@ -5021,6 +5041,9 @@ async function deleteAddress(listing) {
|
||||
async function setRegions(regions) {
|
||||
return (await call("PUT", "/api/v1/regions", { regions })).regions;
|
||||
}
|
||||
async function renewCertificate(phrase) {
|
||||
return (await call("PUT", "/api/v1/certificate", { phrase })).cert_expires_at;
|
||||
}
|
||||
async function createListing(d) {
|
||||
return await call("POST", "/api/v1/listings", d);
|
||||
}
|
||||
@@ -5039,6 +5062,74 @@ async function renewListing(author, id, days = MAX_LIFETIME_DAYS) {
|
||||
return updateListing(id, draftFromListing(l, days));
|
||||
}
|
||||
|
||||
// src/certificate.ts
|
||||
var RENEW_WINDOW_DAYS = 30;
|
||||
function describe2(e2) {
|
||||
if (e2 instanceof Unauthorized) return t("reg.signedOut");
|
||||
if (e2 instanceof HttpError) return e2.detail;
|
||||
return t("send.network");
|
||||
}
|
||||
function certificatePanel() {
|
||||
const expires = state.node?.cert_expires_at;
|
||||
if (expires === void 0) return null;
|
||||
const days = Math.floor((expires - nowSeconds()) / 86400);
|
||||
if (days > RENEW_WINDOW_DAYS) return null;
|
||||
const root = h("section", { class: "panel certificate" });
|
||||
const lead = days >= 0 ? t("cert.soon", { date: date(expires), n: days }) : t("cert.expired", { date: date(expires) });
|
||||
append(root, [h("h2", { class: "pane-title" }, t("cert.title")), h("p", { class: "note warn", role: "status" }, lead)]);
|
||||
if (!state.node?.can_renew) {
|
||||
append(root, [h("p", { class: "muted" }, t("cert.noPhrase"))]);
|
||||
return root;
|
||||
}
|
||||
const phrase = h("input", {
|
||||
type: "password",
|
||||
name: "phrase",
|
||||
autocomplete: "off",
|
||||
autocapitalize: "none",
|
||||
spellcheck: "false",
|
||||
// a bare false would drop the attribute
|
||||
"aria-label": t("cert.phrase"),
|
||||
placeholder: t("cert.phrase")
|
||||
});
|
||||
const status = h("p", { class: "muted", role: "status" });
|
||||
const problem = h("p", { class: "error", role: "alert" });
|
||||
const button = h("button", { type: "submit", class: "btn primary" }, t("cert.renew"));
|
||||
const form = h(
|
||||
"form",
|
||||
{
|
||||
class: "compose",
|
||||
onsubmit: (ev) => {
|
||||
ev.preventDefault();
|
||||
const words = phrase.value.trim();
|
||||
problem.textContent = "";
|
||||
if (!words) {
|
||||
problem.textContent = t("cert.fail", { detail: t("cert.phrase") });
|
||||
return;
|
||||
}
|
||||
button.disabled = true;
|
||||
status.textContent = t("cert.working");
|
||||
void renewCertificate(words).then((until) => {
|
||||
phrase.value = "";
|
||||
if (state.node) state.node.cert_expires_at = until;
|
||||
clear(root);
|
||||
append(root, [h("h2", { class: "pane-title" }, t("cert.title")), h("p", { role: "status" }, t("cert.done", { date: date(until) }))]);
|
||||
}).catch((e2) => {
|
||||
button.disabled = false;
|
||||
status.textContent = "";
|
||||
problem.textContent = t("cert.fail", { detail: describe2(e2) });
|
||||
});
|
||||
}
|
||||
},
|
||||
h("p", { class: "muted" }, t("cert.intro")),
|
||||
phrase,
|
||||
h("div", { class: "actions" }, button),
|
||||
status,
|
||||
problem
|
||||
);
|
||||
root.append(form);
|
||||
return root;
|
||||
}
|
||||
|
||||
// src/owner.ts
|
||||
var VALID_DAYS = [1, 3, 7, 14, 30];
|
||||
var DEFAULT_DAYS = 7;
|
||||
@@ -5097,6 +5188,7 @@ async function showOwner(listingId, thread) {
|
||||
const listingsPane = h(
|
||||
"section",
|
||||
{ class: "pane pane-listings" },
|
||||
certificatePanel(),
|
||||
h("h2", { class: "pane-title" }, t("own.listings")),
|
||||
h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))),
|
||||
listingsBox,
|
||||
@@ -5634,7 +5726,7 @@ async function sendTip(author, id, category, note) {
|
||||
await mine(body, bits);
|
||||
await postSignal(canonicalize(body));
|
||||
}
|
||||
function describe2(e2) {
|
||||
function describe3(e2) {
|
||||
if (e2 instanceof Unauthorized) return t("reg.signedOut");
|
||||
if (e2 instanceof HttpError) return e2.detail;
|
||||
return t("send.network");
|
||||
@@ -5695,7 +5787,7 @@ function visitorForm(l) {
|
||||
}).catch((e2) => {
|
||||
button.disabled = false;
|
||||
status.textContent = "";
|
||||
problem.textContent = t("rep.fail", { detail: describe2(e2) });
|
||||
problem.textContent = t("rep.fail", { detail: describe3(e2) });
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -5717,7 +5809,7 @@ function operatorForm(l, changed) {
|
||||
status.textContent = t(done);
|
||||
changed();
|
||||
}).catch((e2) => {
|
||||
problem.textContent = t("rep.fail", { detail: describe2(e2) });
|
||||
problem.textContent = t("rep.fail", { detail: describe3(e2) });
|
||||
});
|
||||
};
|
||||
return h(
|
||||
@@ -5769,7 +5861,7 @@ async function showReports() {
|
||||
tips = await getTips();
|
||||
} catch (e2) {
|
||||
if (e2 instanceof Unauthorized) return renderLogin(true);
|
||||
problem.textContent = describe2(e2);
|
||||
problem.textContent = describe3(e2);
|
||||
return;
|
||||
}
|
||||
clear(list);
|
||||
@@ -5786,7 +5878,7 @@ async function showReports() {
|
||||
function card(group, reload, problem) {
|
||||
const first = group[0];
|
||||
const fail2 = (e2) => {
|
||||
problem.textContent = describe2(e2);
|
||||
problem.textContent = describe3(e2);
|
||||
};
|
||||
const categories = [...new Set(group.map((g) => g.category))];
|
||||
return h(
|
||||
|
||||
@@ -14,6 +14,10 @@ export interface Status {
|
||||
difficulty: number;
|
||||
/** Proof-of-work bits a message needs; absent on nodes without messaging. */
|
||||
message_difficulty?: number;
|
||||
/** When this node's device certificate runs out, in unix seconds; absent on older nodes. */
|
||||
cert_expires_at?: number;
|
||||
/** Whether the owner can renew that certificate here (it needs the recovery phrase). */
|
||||
can_renew?: boolean;
|
||||
}
|
||||
|
||||
async function getJSON(url: string): Promise<unknown> {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Renewing the node's device certificate from the browser.
|
||||
//
|
||||
// A certificate lasts at most a year. Within the last 30 days the owner's page
|
||||
// says so and offers the renewal: the owner types the twelve words once, the
|
||||
// node signs a new certificate with them and forgets them. The device key does
|
||||
// not change, so the node keeps its peer ID and every listing stays valid.
|
||||
|
||||
import { HttpError } from "./api.ts";
|
||||
import { append, clear, h } from "./dom.ts";
|
||||
import { date } from "./format.ts";
|
||||
import { t } from "./i18n.ts";
|
||||
import { Unauthorized, renewCertificate } from "./ownerApi.ts";
|
||||
import { nowSeconds, state } from "./state.ts";
|
||||
|
||||
/** How long before the end the page starts asking. */
|
||||
export const RENEW_WINDOW_DAYS = 30;
|
||||
|
||||
function describe(e: unknown): string {
|
||||
if (e instanceof Unauthorized) return t("reg.signedOut");
|
||||
if (e instanceof HttpError) return e.detail;
|
||||
return t("send.network");
|
||||
}
|
||||
|
||||
/**
|
||||
* The renewal panel, or null when there is nothing to say: the certificate has
|
||||
* plenty of time left, or the node is too old to report it.
|
||||
*/
|
||||
export function certificatePanel(): HTMLElement | null {
|
||||
const expires = state.node?.cert_expires_at;
|
||||
if (expires === undefined) return null;
|
||||
const days = Math.floor((expires - nowSeconds()) / 86_400);
|
||||
if (days > RENEW_WINDOW_DAYS) return null;
|
||||
|
||||
const root = h("section", { class: "panel certificate" });
|
||||
const lead = days >= 0 ? t("cert.soon", { date: date(expires), n: days }) : t("cert.expired", { date: date(expires) });
|
||||
append(root, [h("h2", { class: "pane-title" }, t("cert.title")), h("p", { class: "note warn", role: "status" }, lead)]);
|
||||
|
||||
if (!state.node?.can_renew) {
|
||||
append(root, [h("p", { class: "muted" }, t("cert.noPhrase"))]);
|
||||
return root;
|
||||
}
|
||||
|
||||
const phrase = h("input", {
|
||||
type: "password",
|
||||
name: "phrase",
|
||||
autocomplete: "off",
|
||||
autocapitalize: "none",
|
||||
spellcheck: "false", // a bare false would drop the attribute
|
||||
"aria-label": t("cert.phrase"),
|
||||
placeholder: t("cert.phrase"),
|
||||
}) as HTMLInputElement;
|
||||
const status = h("p", { class: "muted", role: "status" });
|
||||
const problem = h("p", { class: "error", role: "alert" });
|
||||
const button = h("button", { type: "submit", class: "btn primary" }, t("cert.renew")) as HTMLButtonElement;
|
||||
const form = h(
|
||||
"form",
|
||||
{
|
||||
class: "compose",
|
||||
onsubmit: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
const words = phrase.value.trim();
|
||||
problem.textContent = "";
|
||||
if (!words) {
|
||||
problem.textContent = t("cert.fail", { detail: t("cert.phrase") });
|
||||
return;
|
||||
}
|
||||
button.disabled = true;
|
||||
status.textContent = t("cert.working");
|
||||
void renewCertificate(words)
|
||||
.then((until) => {
|
||||
phrase.value = ""; // the words are not kept anywhere on this page
|
||||
if (state.node) state.node.cert_expires_at = until;
|
||||
clear(root);
|
||||
append(root, [h("h2", { class: "pane-title" }, t("cert.title")), h("p", { role: "status" }, t("cert.done", { date: date(until) }))]);
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
button.disabled = false;
|
||||
status.textContent = "";
|
||||
problem.textContent = t("cert.fail", { detail: describe(e) });
|
||||
});
|
||||
},
|
||||
},
|
||||
h("p", { class: "muted" }, t("cert.intro")),
|
||||
phrase,
|
||||
h("div", { class: "actions" }, button),
|
||||
status,
|
||||
problem,
|
||||
);
|
||||
root.append(form);
|
||||
return root;
|
||||
}
|
||||
@@ -94,6 +94,16 @@ const de = {
|
||||
"rep.done": "Gemeldet.",
|
||||
"rep.withdrawn": "Zurückgezogen.",
|
||||
"rep.mine": "Deine Meldung: {what}.",
|
||||
"cert.title": "Geräte-Zertifikat",
|
||||
"cert.soon": "Das Zertifikat dieses Knotens läuft am {date} ab (in {n} Tagen). Danach geht der Knoten nicht mehr an und deine Anzeigen verschwinden.",
|
||||
"cert.expired": "Das Zertifikat dieses Knotens ist am {date} abgelaufen. Erneuere es jetzt.",
|
||||
"cert.noPhrase": "Diese Identität hat keine Wiederherstellungsphrase und lässt sich nicht erneuern. Lege mit „allmende init --no-phrase“ in einem leeren Datenverzeichnis eine neue an.",
|
||||
"cert.intro": "Gib die zwölf Wörter deiner Wiederherstellungsphrase ein. Der Knoten stellt damit ein neues Zertifikat aus und vergisst sie sofort wieder. Der Schlüssel des Geräts bleibt gleich, nichts wird widerrufen.",
|
||||
"cert.phrase": "Die zwölf Wörter",
|
||||
"cert.renew": "Zertifikat erneuern",
|
||||
"cert.working": "Wird erneuert …",
|
||||
"cert.done": "Erneuert. Das Zertifikat gilt jetzt bis zum {date}.",
|
||||
"cert.fail": "Das hat nicht geklappt: {detail}",
|
||||
"rep.title": "Meldungen",
|
||||
"rep.tipsIntro": "Hinweise von Besuchern dieses Knotens. Sie blenden nichts aus: du entscheidest, ob du selbst meldest.",
|
||||
"rep.none": "Keine Hinweise von Besuchern.",
|
||||
@@ -407,6 +417,16 @@ const en: Record<keyof typeof de, string> = {
|
||||
"rep.done": "Reported.",
|
||||
"rep.withdrawn": "Withdrawn.",
|
||||
"rep.mine": "Your report: {what}.",
|
||||
"cert.title": "Device certificate",
|
||||
"cert.soon": "This node's certificate expires on {date} (in {n} days). After that the node will not start and your listings disappear.",
|
||||
"cert.expired": "This node's certificate expired on {date}. Renew it now.",
|
||||
"cert.noPhrase": "This identity has no recovery phrase, so it cannot be renewed. Make a new one with “allmende init --no-phrase” in an empty data directory.",
|
||||
"cert.intro": "Enter the twelve words of your recovery phrase. The node signs a new certificate with them and forgets them at once. The device key stays the same and nothing is revoked.",
|
||||
"cert.phrase": "The twelve words",
|
||||
"cert.renew": "Renew certificate",
|
||||
"cert.working": "Renewing…",
|
||||
"cert.done": "Renewed. The certificate is now valid until {date}.",
|
||||
"cert.fail": "That did not work: {detail}",
|
||||
"rep.title": "Reports",
|
||||
"rep.tipsIntro": "Tips from visitors of this node. They hide nothing: you decide whether to report yourself.",
|
||||
"rep.none": "No tips from visitors.",
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
// with textContent only, never as links.
|
||||
|
||||
import { HttpError } from "./api.ts";
|
||||
import { certificatePanel } from "./certificate.ts";
|
||||
import { append, clear, h, sendOnCtrlEnter } from "./dom.ts";
|
||||
import { keepFresh } from "./fresh.ts";
|
||||
import { date, price, when } from "./format.ts";
|
||||
@@ -87,6 +88,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
|
||||
const listingsPane = h(
|
||||
"section",
|
||||
{ class: "pane pane-listings" },
|
||||
certificatePanel(),
|
||||
h("h2", { class: "pane-title" }, t("own.listings")),
|
||||
h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))),
|
||||
listingsBox,
|
||||
|
||||
@@ -224,6 +224,15 @@ export async function setRegions(regions: string[]): Promise<string[]> {
|
||||
return ((await call("PUT", "/api/v1/regions", { regions })) as { regions: string[] }).regions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renews the node's device certificate from the recovery phrase, which is
|
||||
* used for this one request. The device key stays, so nothing else changes.
|
||||
* Returns when the new certificate runs out, in unix seconds.
|
||||
*/
|
||||
export async function renewCertificate(phrase: string): Promise<number> {
|
||||
return ((await call("PUT", "/api/v1/certificate", { phrase })) as { cert_expires_at: number }).cert_expires_at;
|
||||
}
|
||||
|
||||
export async function createListing(d: Draft): Promise<Listing> {
|
||||
return (await call("POST", "/api/v1/listings", d)) as Listing;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { afterEach, test } from "node:test";
|
||||
|
||||
import { NOW, openPage, startGateway, type Gateway, type Page } from "./helpers.ts";
|
||||
|
||||
const TOKEN = "ef56".repeat(16);
|
||||
const DAY = 86_400;
|
||||
const PHRASE = "legal winner thank year wave sausage worth useful legal winner thank yellow";
|
||||
|
||||
let gw: Gateway | undefined;
|
||||
let page: Page | undefined;
|
||||
let calls: { method: string; path: string; body: string; auth: string }[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
page?.close();
|
||||
page = undefined;
|
||||
await gw?.close();
|
||||
gw = undefined;
|
||||
});
|
||||
|
||||
/** A node whose certificate runs out in `days` days, with an owner who may sign in. */
|
||||
async function node(days: number | null, canRenew = true, answer?: { status: number; body: unknown }): Promise<void> {
|
||||
gw = await startGateway({ listings: [], ...(days === null ? {} : { cert: { expires_at: NOW + days * DAY, can_renew: canRenew } }) });
|
||||
calls = [];
|
||||
gw.owner = (r) => {
|
||||
calls.push({ method: r.method, path: r.path, body: r.body, auth: r.auth });
|
||||
if (r.auth !== `Bearer ${TOKEN}`) return { status: 401, body: { error: "unauthorized" } };
|
||||
if (r.path === "/api/v1/mine") return { status: 200, body: [] };
|
||||
if (r.path === "/api/v1/certificate" && r.method === "PUT") {
|
||||
return answer ?? { status: 200, body: { cert_expires_at: NOW + 365 * DAY } };
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
page = openPage(gw.url, `#/login/${TOKEN}`);
|
||||
await page.waitFor(() => page!.document.querySelector(".pane-listings") !== null, "the owner page");
|
||||
}
|
||||
|
||||
const text = () => page!.document.body.textContent ?? "";
|
||||
const panel = () => page!.document.querySelector("section.certificate");
|
||||
const renew = () => [...page!.document.querySelectorAll("button")].find((b) => b.textContent === "Renew certificate") as HTMLButtonElement | undefined;
|
||||
|
||||
function submit(words: string): void {
|
||||
const form = panel()!.querySelector("form")!;
|
||||
(form.querySelector("input[name=phrase]") as HTMLInputElement).value = words;
|
||||
form.dispatchEvent(new page!.window.Event("submit", { cancelable: true }));
|
||||
}
|
||||
|
||||
test("with plenty of time left the owner page says nothing about the certificate", async () => {
|
||||
await node(200);
|
||||
assert.equal(panel(), null);
|
||||
assert.doesNotMatch(text(), /certificate/i);
|
||||
});
|
||||
|
||||
test("an older node that does not report the certificate shows no panel", async () => {
|
||||
await node(null);
|
||||
assert.equal(panel(), null);
|
||||
});
|
||||
|
||||
test("in the last 30 days it says when the certificate ends and offers to renew it", async () => {
|
||||
await node(12);
|
||||
assert.ok(panel(), "the panel");
|
||||
assert.match(panel()!.textContent!, /expires on .* \(in 12 days\)/);
|
||||
assert.ok(renew(), "the renew button");
|
||||
const input = panel()!.querySelector("input[name=phrase]") as HTMLInputElement;
|
||||
assert.equal(input.type, "password", "the words are not shown while typing");
|
||||
assert.equal(input.getAttribute("autocomplete"), "off");
|
||||
});
|
||||
|
||||
test("exactly 30 days left is the first day it asks, 31 is not", async () => {
|
||||
await node(30);
|
||||
assert.ok(panel(), "30 days left");
|
||||
page!.close();
|
||||
await gw!.close();
|
||||
await node(31);
|
||||
assert.equal(panel(), null, "31 days left");
|
||||
});
|
||||
|
||||
test("renewing sends the words once, with the token, and the panel then confirms", async () => {
|
||||
await node(12);
|
||||
submit(` ${PHRASE} `);
|
||||
await page!.waitFor(() => /Renewed\. The certificate is now valid until/.test(text()), "the confirmation");
|
||||
const puts = calls.filter((c) => c.path === "/api/v1/certificate");
|
||||
assert.equal(puts.length, 1);
|
||||
assert.equal(puts[0]!.method, "PUT");
|
||||
assert.equal(puts[0]!.auth, `Bearer ${TOKEN}`);
|
||||
assert.deepEqual(JSON.parse(puts[0]!.body), { phrase: PHRASE }, "the words arrive trimmed, in a JSON body");
|
||||
assert.equal(panel()!.querySelector("form"), null, "the form is gone");
|
||||
const left = [...page!.document.querySelectorAll("input, textarea")].filter((i) => (i as HTMLInputElement).value.includes("winner"));
|
||||
assert.equal(left.length, 0, "the words are not left in any field on the page");
|
||||
});
|
||||
|
||||
test("empty words are not sent", async () => {
|
||||
await node(12);
|
||||
submit(" ");
|
||||
assert.match(panel()!.textContent!, /That did not work/);
|
||||
assert.equal(calls.filter((c) => c.path === "/api/v1/certificate").length, 0);
|
||||
});
|
||||
|
||||
test("a refusal is shown, the words stay for another try, and the button works again", async () => {
|
||||
await node(12, true, { status: 409, body: { error: "these words belong to a different identity than this node" } });
|
||||
submit(PHRASE);
|
||||
await page!.waitFor(() => /different identity/.test(text()), "the refusal");
|
||||
assert.match(panel()!.textContent!, /That did not work: these words belong to a different identity than this node/);
|
||||
assert.equal(renew()!.disabled, false);
|
||||
assert.equal((panel()!.querySelector("input[name=phrase]") as HTMLInputElement).value, PHRASE);
|
||||
assert.ok(panel()!.querySelector("form"), "the form is still there");
|
||||
});
|
||||
|
||||
test("an identity without a recovery phrase is told so and gets no form", async () => {
|
||||
await node(5, false);
|
||||
assert.match(panel()!.textContent!, /no recovery phrase/);
|
||||
assert.equal(panel()!.querySelector("form"), null);
|
||||
assert.equal(renew(), undefined);
|
||||
});
|
||||
|
||||
test("a certificate that already ran out says so", async () => {
|
||||
await node(-2);
|
||||
assert.match(panel()!.textContent!, /expired on/);
|
||||
assert.ok(renew(), "it can still be renewed while the node runs");
|
||||
});
|
||||
+4
-1
@@ -204,6 +204,8 @@ export interface GatewayOptions {
|
||||
statusFails?: boolean;
|
||||
/** The regions the node reports; default ["u1x"]. */
|
||||
regions?: string[];
|
||||
/** The device certificate the node reports in /status; unset, it says nothing (an older node). */
|
||||
cert?: { expires_at: number; can_renew: boolean };
|
||||
}
|
||||
|
||||
export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
|
||||
@@ -245,7 +247,7 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
|
||||
}
|
||||
// The owner's token-protected routes are played by the test, if it sets `owner`.
|
||||
const writesListing = req.method !== "GET" && /^\/api\/v1\/listings(\/[0-9a-f]{32})?$/.test(url.pathname);
|
||||
if (writesListing || /^\/api\/v1\/(mine|inbox|regions|blocked|signals|reports)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
|
||||
if (writesListing || /^\/api\/v1\/(mine|inbox|regions|blocked|signals|reports|certificate)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
|
||||
let body = "";
|
||||
req.on("data", (c) => (body += c));
|
||||
req.on("end", () => {
|
||||
@@ -292,6 +294,7 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
|
||||
listings: opts.listings.length,
|
||||
difficulty: DIFFICULTY,
|
||||
message_difficulty: 6,
|
||||
...(opts.cert ? { cert_expires_at: opts.cert.expires_at, can_renew: opts.cert.can_renew } : {}),
|
||||
});
|
||||
}
|
||||
if (url.pathname === "/api/v1/listings") {
|
||||
|
||||
Reference in New Issue
Block a user