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:
2026-11-18 23:19:30 +01:00
co-authored by Claude Sonnet 5.5
parent 210ba1b3e9
commit dfe35b422d
23 changed files with 1011 additions and 29 deletions
+51
View File
@@ -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 {
+6 -5
View File
@@ -26,16 +26,17 @@ const (
)
type fixture struct {
srv *httptest.Server
s *store.Store
dev *identity.Device
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) {
+152
View File
@@ -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")
}
}
+43 -2
View File
@@ -6,14 +6,55 @@ import (
"errors"
"os"
"path/filepath"
"sync"
"time"
)
// Device is what a running node holds: its own key plus the certificate that
// ties it to an identity. The identity key itself is never stored.
type Device struct {
Key *Identity
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
}
+104
View File
@@ -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)
}
+4 -3
View File
@@ -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 {
+3 -2
View File
@@ -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...)))
+4 -3
View File
@@ -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 {