From 7984917acaa1ee67ca940eee1adc80d260e5764c Mon Sep 17 00:00:00 2001 From: Artur Maciag Date: Wed, 18 Nov 2026 19:46:24 +0000 Subject: [PATCH 1/3] node: keep trusted keys the control plane still lists (#916) A trusted key's age counted from when the node first received it, and a /keys sync kept that time. Pruning keeps only the newest key past the grace period, so a key the control plane still lists in its rotation grace period was dropped a day after the node first saw it, even when it signed the node's own identity. The next start then failed the role check ("biscuit: invalid signature") on a valid identity, and if the control plane could not be reached at that moment, both recoveries failed too. - mergeTrustedKeys: every key a /keys answer lists counts as vouched for at that sync, so pruning only drops keys the control plane stopped listing, or ones the node could not confirm for longer than the grace period. - pruneTrustedKeys: keeps every key with the latest time, since a /keys answer vouches for all its keys at once and its order says nothing about which is current, and never drops the key that signed the node's current identity. - NewAgentMeshNode: the configured key re-added next to persisted keys gets a fixed old time (the zero time is not stored and read back as now), so it cannot outrank the control plane's newer keys after a restart. - Start returns *StaleIdentityError when the stored identity fails the role check and neither recovery renews it. It unwraps to the role, refresh and recovery errors, so callers can tell a refusal (*RefreshError with its status) from a control plane that never answered. --- internal/node/controlplane.go | 16 ++-- internal/node/controlplane_test.go | 4 +- internal/node/node.go | 94 +++++++++++++++++---- internal/node/node_test.go | 126 ++++++++++++++++++++++++++++- 4 files changed, 212 insertions(+), 28 deletions(-) diff --git a/internal/node/controlplane.go b/internal/node/controlplane.go index ae7c039f7..c48d9de21 100644 --- a/internal/node/controlplane.go +++ b/internal/node/controlplane.go @@ -15,7 +15,6 @@ package node import ( - "bytes" "context" "crypto/ed25519" "time" @@ -87,19 +86,14 @@ func FetchControlPlaneInfo(ctx context.Context, controlPlaneURL string) (*api.Co } // mergeTrustedKeys replaces the stored trust set with the authoritative set -// from /keys, preserving ReceivedAt for keys already known so local grace -// pruning keeps working across syncs. +// from /keys. The control plane lists every key that is still valid, its +// current key and any in their rotation grace period, so each listed key's +// ReceivedAt becomes now: local pruning then ages a key from the last time +// the control plane vouched for it, and never drops one it still lists. func mergeTrustedKeys(existing []TrustedKey, fetched []ed25519.PublicKey, now time.Time) []TrustedKey { merged := make([]TrustedKey, 0, len(fetched)) for _, key := range fetched { - tk := TrustedKey{Key: key, ReceivedAt: now} - for _, old := range existing { - if bytes.Equal(old.Key, key) { - tk.ReceivedAt = old.ReceivedAt - break - } - } - merged = append(merged, tk) + merged = append(merged, TrustedKey{Key: key, ReceivedAt: now}) } return merged } diff --git a/internal/node/controlplane_test.go b/internal/node/controlplane_test.go index ad2e693bf..bd529cb86 100644 --- a/internal/node/controlplane_test.go +++ b/internal/node/controlplane_test.go @@ -51,8 +51,8 @@ func TestMergeTrustedKeys(t *testing.T) { if len(got) != 2 { t.Fatalf("expected 2 keys, got %d", len(got)) } - if !got[0].Key.Equal(keyA) || !got[0].ReceivedAt.Equal(earlier) { - t.Errorf("known key must keep its ReceivedAt: got %+v", got[0]) + if !got[0].Key.Equal(keyA) || !got[0].ReceivedAt.Equal(now) { + t.Errorf("a key the control plane still lists must get the sync time: got %+v", got[0]) } if !got[1].Key.Equal(keyB) || !got[1].ReceivedAt.Equal(now) { t.Errorf("new key must get the sync time: got %+v", got[1]) diff --git a/internal/node/node.go b/internal/node/node.go index d65839c8b..dd12fc342 100644 --- a/internal/node/node.go +++ b/internal/node/node.go @@ -118,11 +118,46 @@ var ( var ErrFatalAuth = errors.New("fatal authentication error") +// TrustedKey is a control plane public key the node trusts. ReceivedAt is +// the last time the control plane vouched for the key, by listing it in /keys +// or announcing it in a rotation event; key pruning ages keys from it. type TrustedKey struct { Key ed25519.PublicKey ReceivedAt time.Time } +// neverVouched is the ReceivedAt of a key the control plane has not vouched +// for in this trust set's lifetime: older than any real one, and, unlike the +// zero time, kept as it is through the store, which reads a missing time as +// now. +var neverVouched = time.Unix(0, 0).UTC() + +// StaleIdentityError is Start's error when the stored identity fails the +// role check against every trusted key and neither recovery renewed it. It +// unwraps to the role check's error and to both recovery errors, so a caller +// can tell a control plane that refused the identity (a *RefreshError with +// its status) from one that never answered. +type StaleIdentityError struct { + Role string + RoleErr error + RefreshErr error + RecoveryErr error +} + +func (e *StaleIdentityError) Error() string { + return fmt.Sprintf("loaded identity fails role requirement %q (autonomous refresh: %v; refresh-token recovery: %v): %v", e.Role, e.RefreshErr, e.RecoveryErr, e.RoleErr) +} + +func (e *StaleIdentityError) Unwrap() []error { + var errs []error + for _, err := range []error{e.RoleErr, e.RefreshErr, e.RecoveryErr} { + if err != nil { + errs = append(errs, err) + } + } + return errs +} + type nodeRelayACL struct { node *AgentMeshNode } @@ -483,7 +518,15 @@ func NewAgentMeshNode(cfg Options) (*AgentMeshNode, error) { } } if len(cfg.ControlPlanePubKey) > 0 && !containsTrustedKey(trustedKeys, cfg.ControlPlanePubKey) { - trustedKeys = append(trustedKeys, TrustedKey{Key: cfg.ControlPlanePubKey, ReceivedAt: time.Now()}) + // The configured key is only as fresh as the enrollment or /info + // answer that stored it. Next to persisted keys it must not count as + // just vouched for, or it would outrank the control plane's newer + // keys when pruning picks the newest; alone, it is all there is. + vouched := neverVouched + if len(trustedKeys) == 0 { + vouched = time.Now() + } + trustedKeys = append(trustedKeys, TrustedKey{Key: cfg.ControlPlanePubKey, ReceivedAt: vouched}) } node := &AgentMeshNode{ @@ -579,7 +622,7 @@ func (n *AgentMeshNode) Start(ctx context.Context) error { } else { logger.Warnf("Autonomous refresh refused (%v); attempting recovery via stored refresh token", refreshErr) if recErr := n.ReEnrollWithRefreshToken(ctx); recErr != nil { - return fmt.Errorf("loaded identity fails role requirement %q (autonomous refresh: %v; refresh-token recovery: %v): %w", n.config.RequiredRole, refreshErr, recErr, roleErr) + return &StaleIdentityError{Role: n.config.RequiredRole, RoleErr: roleErr, RefreshErr: refreshErr, RecoveryErr: recErr} } logger.Info("Identity recovered via refresh-token re-enrollment.") } @@ -1979,29 +2022,52 @@ func (n *AgentMeshNode) handleKeyRotationEvent(event *api.MeshEvent) { n.triggerControlPlaneSync() } -// pruneTrustedKeys drops keys older than gracePeriod but always keeps the -// most recently received one: the current signing key has no successor until -// a rotation event arrives, so ageing it out would empty the trust set and -// leave the node unable to verify any peer or router. -func pruneTrustedKeys(keys []TrustedKey, now time.Time, gracePeriod time.Duration) []TrustedKey { +// pruneTrustedKeys drops keys the control plane has not vouched for within +// gracePeriod, as when it stopped listing them or the node could not reach +// it, but always keeps the most recently vouched-for ones: the current +// signing key has no successor until a rotation event arrives, so ageing it +// out would empty the trust set and leave the node unable to verify any peer +// or router. A /keys answer vouches for all its keys at once and says +// nothing about which is current, so every key with the latest time is kept, +// never one of them by its place in the list. It also keeps every key keep reports, which is the key that +// signed the node's own identity: the control plane lists all its valid keys +// alike, so the newest vouched-for key need not be the one a refresh signed +// with, and dropping that one after a long time offline leaves a valid +// identity that fails the check at the next start, when only the control +// plane can renew it. +func pruneTrustedKeys(keys []TrustedKey, now time.Time, gracePeriod time.Duration, keep func(ed25519.PublicKey) bool) []TrustedKey { if len(keys) == 0 { return keys } - newest := 0 - for i, tk := range keys { - if tk.ReceivedAt.After(keys[newest].ReceivedAt) { - newest = i + latest := keys[0].ReceivedAt + for _, tk := range keys { + if tk.ReceivedAt.After(latest) { + latest = tk.ReceivedAt } } var active []TrustedKey - for i, tk := range keys { - if i == newest || now.Sub(tk.ReceivedAt) <= gracePeriod { + for _, tk := range keys { + if tk.ReceivedAt.Equal(latest) || now.Sub(tk.ReceivedAt) <= gracePeriod || (keep != nil && keep(tk.Key)) { active = append(active, tk) } } return active } +// signedOwnIdentity reports whether key signed the node's current identity. +func (n *AgentMeshNode) signedOwnIdentity(key ed25519.PublicKey) bool { + token := n.GetIdentity() + if len(token) == 0 { + return false + } + b, err := biscuit.Unmarshal(token) + if err != nil { + return false + } + _, err = b.Authorizer(key) + return err == nil +} + func (n *AgentMeshNode) startKeyPruning(ctx context.Context, gracePeriod time.Duration) { if gracePeriod <= 0 { return @@ -2014,7 +2080,7 @@ func (n *AgentMeshNode) startKeyPruning(ctx context.Context, gracePeriod time.Du case <-ticker.C: logger.Info("[KeyPruning] Pruning expired keys...") n.keysMu.Lock() - pruned := pruneTrustedKeys(n.trustedKeys, time.Now(), gracePeriod) + pruned := pruneTrustedKeys(n.trustedKeys, time.Now(), gracePeriod, n.signedOwnIdentity) changed := len(pruned) != len(n.trustedKeys) n.trustedKeys = pruned snapshot := append([]TrustedKey(nil), pruned...) diff --git a/internal/node/node_test.go b/internal/node/node_test.go index 10a693348..e5d24c6dd 100644 --- a/internal/node/node_test.go +++ b/internal/node/node_test.go @@ -353,7 +353,7 @@ func TestPruneTrustedKeys(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := pruneTrustedKeys(tt.in, now, grace) + got := pruneTrustedKeys(tt.in, now, grace, nil) if len(got) != len(tt.want) { t.Fatalf("got %d keys, want %d", len(got), len(tt.want)) } @@ -366,6 +366,54 @@ func TestPruneTrustedKeys(t *testing.T) { } } +// TestKeyPruningKeepsTheIdentitySigner covers a node whose identity was +// signed by a key it learned before the newest one it holds, as when the +// control plane's newest key reached it earlier or its stored key was added +// again at a restart: pruning must not drop the signer, or the next start +// finds a valid identity that no trusted key verifies. +func TestKeyPruningKeepsTheIdentitySigner(t *testing.T) { + now := time.Now() + signerPub, signerPriv, err := ed25519.GenerateKey(nil) + if err != nil { + t.Fatal(err) + } + otherPub, _, err := ed25519.GenerateKey(nil) + if err != nil { + t.Fatal(err) + } + stalePub, _, err := ed25519.GenerateKey(nil) + if err != nil { + t.Fatal(err) + } + priv, _, err := crypto.GenerateEd25519Key(nil) + if err != nil { + t.Fatal(err) + } + pid, err := peer.IDFromPrivateKey(priv) + if err != nil { + t.Fatal(err) + } + token, err := identity.MintBootstrapBiscuitToken(signerPriv, pid, api.RoleNode, now.Add(24*time.Hour), nil, nil) + if err != nil { + t.Fatal(err) + } + n := &AgentMeshNode{} + n.SetIdentityCache(token) + + keys := []TrustedKey{ + {Key: signerPub, ReceivedAt: now.Add(-72 * time.Hour)}, + {Key: stalePub, ReceivedAt: now.Add(-48 * time.Hour)}, + {Key: otherPub, ReceivedAt: now.Add(-time.Minute)}, + } + got := pruneTrustedKeys(keys, now, 24*time.Hour, n.signedOwnIdentity) + if len(got) != 2 || !got[0].Key.Equal(signerPub) || !got[1].Key.Equal(otherPub) { + t.Fatalf("got %d keys, want the identity's signer and the newest key", len(got)) + } + if !n.signedOwnIdentity(signerPub) || n.signedOwnIdentity(otherPub) { + t.Fatal("signedOwnIdentity does not tell the signer from another key") + } +} + // TestHandleAuthHandshake covers the admission office: the relay ACL trusts // authPeers, so the cached instant must be the token's own expiry, and a token // that is expired or bound to another peer must leave no entry at all (#296). @@ -860,3 +908,79 @@ func TestFindProvidersSkipsRevoked(t *testing.T) { t.Errorf("revoked peer returned as provider: %v", providers) } } + +// TestStaleIdentityErrorUnwraps covers what a caller needs from a failed +// start: the refresh status when the control plane answered, and no status +// when it did not. +func TestStaleIdentityErrorUnwraps(t *testing.T) { + refused := &StaleIdentityError{Role: api.RoleNode, RoleErr: errors.New("biscuit: invalid signature"), RefreshErr: &RefreshError{StatusCode: 401, Message: "refused"}, RecoveryErr: errors.New("no refresh token")} + var re *RefreshError + if !errors.As(refused, &re) || re.StatusCode != 401 { + t.Fatalf("errors.As found no refresh status in %v", refused) + } + offline := &StaleIdentityError{Role: api.RoleNode, RoleErr: errors.New("biscuit: invalid signature"), RefreshErr: context.DeadlineExceeded} + if errors.As(offline, &re) || !errors.Is(offline, context.DeadlineExceeded) { + t.Fatalf("offline error unwraps wrong: %v", offline) + } +} + +// TestKeyPruningKeepsEveryLatestKey covers a /keys answer that vouched for +// a retiring and a current key at once, followed by an outage longer than +// the grace period: the answer's order says nothing about which key is +// current, so pruning keeps both rather than whichever came first. +func TestKeyPruningKeepsEveryLatestKey(t *testing.T) { + now := time.Now() + synced := now.Add(-48 * time.Hour) + retiring, _, _ := ed25519.GenerateKey(nil) + current, _, _ := ed25519.GenerateKey(nil) + dropped, _, _ := ed25519.GenerateKey(nil) + keys := []TrustedKey{{Key: retiring, ReceivedAt: synced}, {Key: current, ReceivedAt: synced}, {Key: dropped, ReceivedAt: synced.Add(-time.Hour)}} + got := pruneTrustedKeys(keys, now, 24*time.Hour, func(k ed25519.PublicKey) bool { return k.Equal(retiring) }) + if len(got) != 2 || !got[0].Key.Equal(retiring) || !got[1].Key.Equal(current) { + t.Fatalf("got %d keys, want the retiring and the current key of the last sync", len(got)) + } +} + +// TestFallbackKeyStaysOldThroughTheStore covers the configured key re-added +// next to persisted keys at a start: it must stay older than them after the +// set is saved and loaded again, or the next start would take it for the +// newest key and prune the real rotation key. +func TestFallbackKeyStaysOldThroughTheStore(t *testing.T) { + store, err := NewStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer store.Close() + rotated, _, _ := ed25519.GenerateKey(nil) + configured, _, _ := ed25519.GenerateKey(nil) + learned := time.Now().Add(-30 * time.Hour).Truncate(time.Second) + if err := store.SaveTrustedKeys([]TrustedKey{{Key: rotated, ReceivedAt: learned}}); err != nil { + t.Fatal(err) + } + priv, _, err := crypto.GenerateEd25519Key(nil) + if err != nil { + t.Fatal(err) + } + n, err := NewAgentMeshNode(Options{PrivKey: priv, Store: store, ControlPlanePubKey: configured}) + if err != nil { + t.Fatal(err) + } + // A rotation event persists the set before any sync succeeds. + n.persistTrustedKeys(n.trustedKeys) + loaded, err := store.LoadTrustedKeys() + if err != nil { + t.Fatal(err) + } + for _, tk := range loaded { + switch { + case tk.Key.Equal(configured) && !tk.ReceivedAt.Equal(neverVouched): + t.Fatalf("configured key loaded as vouched for at %s", tk.ReceivedAt) + case tk.Key.Equal(rotated) && !tk.ReceivedAt.Equal(learned): + t.Fatalf("rotation key loaded with %s, want %s", tk.ReceivedAt, learned) + } + } + got := pruneTrustedKeys(loaded, time.Now(), 24*time.Hour, nil) + if len(got) != 1 || !got[0].Key.Equal(rotated) { + t.Fatalf("pruning kept %d keys, want only the rotation key", len(got)) + } +} From 6b02d80d28cf300d51dcf577d0d4056a4cc3ecd1 Mon Sep 17 00:00:00 2001 From: Artur Maciag Date: Wed, 18 Nov 2026 20:10:45 +0000 Subject: [PATCH 2/3] node: check key generation and store close errors in the pruning tests Use mustGenerateKey instead of ignoring ed25519.GenerateKey's error, and report a failed store close (errcheck). --- internal/node/node_test.go | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/internal/node/node_test.go b/internal/node/node_test.go index e5d24c6dd..b50d3808d 100644 --- a/internal/node/node_test.go +++ b/internal/node/node_test.go @@ -373,18 +373,9 @@ func TestPruneTrustedKeys(t *testing.T) { // finds a valid identity that no trusted key verifies. func TestKeyPruningKeepsTheIdentitySigner(t *testing.T) { now := time.Now() - signerPub, signerPriv, err := ed25519.GenerateKey(nil) - if err != nil { - t.Fatal(err) - } - otherPub, _, err := ed25519.GenerateKey(nil) - if err != nil { - t.Fatal(err) - } - stalePub, _, err := ed25519.GenerateKey(nil) - if err != nil { - t.Fatal(err) - } + signerPub, signerPriv := mustGenerateKey(t) + otherPub, _ := mustGenerateKey(t) + stalePub, _ := mustGenerateKey(t) priv, _, err := crypto.GenerateEd25519Key(nil) if err != nil { t.Fatal(err) @@ -931,9 +922,9 @@ func TestStaleIdentityErrorUnwraps(t *testing.T) { func TestKeyPruningKeepsEveryLatestKey(t *testing.T) { now := time.Now() synced := now.Add(-48 * time.Hour) - retiring, _, _ := ed25519.GenerateKey(nil) - current, _, _ := ed25519.GenerateKey(nil) - dropped, _, _ := ed25519.GenerateKey(nil) + retiring, _ := mustGenerateKey(t) + current, _ := mustGenerateKey(t) + dropped, _ := mustGenerateKey(t) keys := []TrustedKey{{Key: retiring, ReceivedAt: synced}, {Key: current, ReceivedAt: synced}, {Key: dropped, ReceivedAt: synced.Add(-time.Hour)}} got := pruneTrustedKeys(keys, now, 24*time.Hour, func(k ed25519.PublicKey) bool { return k.Equal(retiring) }) if len(got) != 2 || !got[0].Key.Equal(retiring) || !got[1].Key.Equal(current) { @@ -950,9 +941,13 @@ func TestFallbackKeyStaysOldThroughTheStore(t *testing.T) { if err != nil { t.Fatal(err) } - defer store.Close() - rotated, _, _ := ed25519.GenerateKey(nil) - configured, _, _ := ed25519.GenerateKey(nil) + t.Cleanup(func() { + if err := store.Close(); err != nil { + t.Errorf("close store: %v", err) + } + }) + rotated, _ := mustGenerateKey(t) + configured, _ := mustGenerateKey(t) learned := time.Now().Add(-30 * time.Hour).Truncate(time.Second) if err := store.SaveTrustedKeys([]TrustedKey{{Key: rotated, ReceivedAt: learned}}); err != nil { t.Fatal(err) From 2c1f1c84202f6ebd0d0b3ed83cb5e0475969e645 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Wed, 25 Nov 2026 15:34:15 +0000 Subject: [PATCH 3/3] node: reduce the trusted key fix to what #916 needs Apply the review of #917: - Remove mergeTrustedKeys; syncTrustedKeys gives each key of the /keys answer the time of the sync. - Log each key that pruning drops, with its last vouched time and the grace period. - Remove the keep parameter, signedOwnIdentity, neverVouched and StaleIdentityError, and their tests: #916 does not need them. - Correct the meaning of receive_time in api/agentmesh.proto and of --key-grace-period in the node reference. - Test the sequence of the issue (sync, then prune) and add a row for the keys of one sync to TestPruneTrustedKeys. --- api/agentmesh.pb.go | 6 +- api/agentmesh.proto | 6 +- internal/node/controlplane.go | 13 -- internal/node/controlplane_sync.go | 15 ++- internal/node/controlplane_test.go | 52 ++++---- internal/node/node.go | 91 +++---------- internal/node/node_test.go | 123 +----------------- sdk/js/src/gen/agentmesh_pb.ts | 6 +- site/content/docs/reference/agentmesh-node.md | 2 +- 9 files changed, 68 insertions(+), 246 deletions(-) diff --git a/api/agentmesh.pb.go b/api/agentmesh.pb.go index ecd9221a4..0c99089ca 100644 --- a/api/agentmesh.pb.go +++ b/api/agentmesh.pb.go @@ -5583,8 +5583,10 @@ type TrustedSigningKey struct { state protoimpl.MessageState `protogen:"open.v1"` // Raw ed25519 public key. PublicKey []byte `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` - // When the member first learned the key. A key rotated out is dropped a - // grace period after this; unset means unknown and is read as now. + // When the control plane last vouched for the key: the last /keys answer + // that listed it, or the enrollment or rotation event that announced it. A + // member that prunes drops a key a grace period after this, unless no key + // has a later time; unset means unknown and is read as now. ReceiveTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=receive_time,json=receiveTime,proto3" json:"receive_time,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache diff --git a/api/agentmesh.proto b/api/agentmesh.proto index b265be2ae..6d0f04e65 100644 --- a/api/agentmesh.proto +++ b/api/agentmesh.proto @@ -931,8 +931,10 @@ message MemberCredential { message TrustedSigningKey { // Raw ed25519 public key. bytes public_key = 1; - // When the member first learned the key. A key rotated out is dropped a - // grace period after this; unset means unknown and is read as now. + // When the control plane last vouched for the key: the last /keys answer + // that listed it, or the enrollment or rotation event that announced it. A + // member that prunes drops a key a grace period after this, unless no key + // has a later time; unset means unknown and is read as now. google.protobuf.Timestamp receive_time = 2; } diff --git a/internal/node/controlplane.go b/internal/node/controlplane.go index c48d9de21..4635fcd64 100644 --- a/internal/node/controlplane.go +++ b/internal/node/controlplane.go @@ -85,19 +85,6 @@ func FetchControlPlaneInfo(ctx context.Context, controlPlaneURL string) (*api.Co return controlPlaneClient(controlPlaneURL).FetchInfo(ctx) } -// mergeTrustedKeys replaces the stored trust set with the authoritative set -// from /keys. The control plane lists every key that is still valid, its -// current key and any in their rotation grace period, so each listed key's -// ReceivedAt becomes now: local pruning then ages a key from the last time -// the control plane vouched for it, and never drops one it still lists. -func mergeTrustedKeys(existing []TrustedKey, fetched []ed25519.PublicKey, now time.Time) []TrustedKey { - merged := make([]TrustedKey, 0, len(fetched)) - for _, key := range fetched { - merged = append(merged, TrustedKey{Key: key, ReceivedAt: now}) - } - return merged -} - func publicKeysOf(keys []TrustedKey) []ed25519.PublicKey { out := make([]ed25519.PublicKey, 0, len(keys)) for _, tk := range keys { diff --git a/internal/node/controlplane_sync.go b/internal/node/controlplane_sync.go index 5329c6143..f0e31dfb7 100644 --- a/internal/node/controlplane_sync.go +++ b/internal/node/controlplane_sync.go @@ -139,13 +139,20 @@ func (n *AgentMeshNode) syncTrustedKeys(ctx context.Context, controlPlaneURL str if len(keys) == 0 { return errors.New("/keys returned no keys") } - merged := mergeTrustedKeys(existing, keys, time.Now()) + // The answer lists every key the control plane still accepts, so it + // vouches for each of them now: pruning ages a key from the last answer + // that listed it, not from the first time the node saw it. + now := time.Now() + synced := make([]TrustedKey, 0, len(keys)) + for _, key := range keys { + synced = append(synced, TrustedKey{Key: key, ReceivedAt: now}) + } n.keysMu.Lock() - n.trustedKeys = merged - snapshot := append([]TrustedKey(nil), merged...) + n.trustedKeys = synced + snapshot := append([]TrustedKey(nil), synced...) n.keysMu.Unlock() n.persistTrustedKeys(snapshot) - logger.Debugf("Synced %d valid control plane keys", len(merged)) + logger.Debugf("Synced %d valid control plane keys", len(synced)) return nil } diff --git a/internal/node/controlplane_test.go b/internal/node/controlplane_test.go index bd529cb86..765a4b5a2 100644 --- a/internal/node/controlplane_test.go +++ b/internal/node/controlplane_test.go @@ -35,35 +35,6 @@ import ( "google.golang.org/protobuf/proto" ) -func TestMergeTrustedKeys(t *testing.T) { - now := time.Now() - earlier := now.Add(-2 * time.Hour) - keyA, _, _ := ed25519.GenerateKey(nil) - keyB, _, _ := ed25519.GenerateKey(nil) - keyC, _, _ := ed25519.GenerateKey(nil) - - existing := []TrustedKey{ - {Key: keyA, ReceivedAt: earlier}, - {Key: keyC, ReceivedAt: earlier}, // expired at the CP: absent from /keys - } - got := mergeTrustedKeys(existing, []ed25519.PublicKey{keyA, keyB}, now) - - if len(got) != 2 { - t.Fatalf("expected 2 keys, got %d", len(got)) - } - if !got[0].Key.Equal(keyA) || !got[0].ReceivedAt.Equal(now) { - t.Errorf("a key the control plane still lists must get the sync time: got %+v", got[0]) - } - if !got[1].Key.Equal(keyB) || !got[1].ReceivedAt.Equal(now) { - t.Errorf("new key must get the sync time: got %+v", got[1]) - } - for _, tk := range got { - if tk.Key.Equal(keyC) { - t.Error("key expired at the control plane must be dropped") - } - } -} - // mustGenerateKey is an ed25519 key pair or a failed test. func mustGenerateKey(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) { t.Helper() @@ -153,6 +124,29 @@ func TestSyncTrustedKeys(t *testing.T) { } }) + // The node got the current key at enrollment and the retiring key from a + // later sync. While /keys lists both, pruning must keep both, whatever + // the time since the node first saw each (#916). A key that /keys no + // longer lists is dropped at the sync. + t.Run("a key /keys still lists outlives the grace period", func(t *testing.T) { + expiredPub, _ := mustGenerateKey(t) + srv := keysServer(t, []ed25519.PublicKey{retiredPub, currentPub}, []ed25519.PrivateKey{retiredPriv, currentPriv}) + defer srv.Close() + n := newNode(t) + enrolled := time.Now().Add(-25 * time.Hour) + n.trustedKeys = []TrustedKey{{Key: currentPub, ReceivedAt: enrolled}, {Key: expiredPub, ReceivedAt: enrolled}} + if err := n.syncTrustedKeys(context.Background(), srv.URL); err != nil { + t.Fatalf("syncTrustedKeys: %v", err) + } + if containsTrustedKey(n.trustedKeys, expiredPub) { + t.Error("a key /keys does not list stayed in the trust set") + } + got := pruneTrustedKeys(n.trustedKeys, time.Now(), 24*time.Hour) + if len(got) != 2 || !containsTrustedKey(got, retiredPub) || !containsTrustedKey(got, currentPub) { + t.Errorf("pruning kept %d keys, want the retired and the current key that /keys lists", len(got)) + } + }) + t.Run("rejects a set no trusted key signed", func(t *testing.T) { srv := keysServer(t, []ed25519.PublicKey{strangerPub}, []ed25519.PrivateKey{strangerPriv}) defer srv.Close() diff --git a/internal/node/node.go b/internal/node/node.go index dd12fc342..15c595f6f 100644 --- a/internal/node/node.go +++ b/internal/node/node.go @@ -126,38 +126,6 @@ type TrustedKey struct { ReceivedAt time.Time } -// neverVouched is the ReceivedAt of a key the control plane has not vouched -// for in this trust set's lifetime: older than any real one, and, unlike the -// zero time, kept as it is through the store, which reads a missing time as -// now. -var neverVouched = time.Unix(0, 0).UTC() - -// StaleIdentityError is Start's error when the stored identity fails the -// role check against every trusted key and neither recovery renewed it. It -// unwraps to the role check's error and to both recovery errors, so a caller -// can tell a control plane that refused the identity (a *RefreshError with -// its status) from one that never answered. -type StaleIdentityError struct { - Role string - RoleErr error - RefreshErr error - RecoveryErr error -} - -func (e *StaleIdentityError) Error() string { - return fmt.Sprintf("loaded identity fails role requirement %q (autonomous refresh: %v; refresh-token recovery: %v): %v", e.Role, e.RefreshErr, e.RecoveryErr, e.RoleErr) -} - -func (e *StaleIdentityError) Unwrap() []error { - var errs []error - for _, err := range []error{e.RoleErr, e.RefreshErr, e.RecoveryErr} { - if err != nil { - errs = append(errs, err) - } - } - return errs -} - type nodeRelayACL struct { node *AgentMeshNode } @@ -518,15 +486,7 @@ func NewAgentMeshNode(cfg Options) (*AgentMeshNode, error) { } } if len(cfg.ControlPlanePubKey) > 0 && !containsTrustedKey(trustedKeys, cfg.ControlPlanePubKey) { - // The configured key is only as fresh as the enrollment or /info - // answer that stored it. Next to persisted keys it must not count as - // just vouched for, or it would outrank the control plane's newer - // keys when pruning picks the newest; alone, it is all there is. - vouched := neverVouched - if len(trustedKeys) == 0 { - vouched = time.Now() - } - trustedKeys = append(trustedKeys, TrustedKey{Key: cfg.ControlPlanePubKey, ReceivedAt: vouched}) + trustedKeys = append(trustedKeys, TrustedKey{Key: cfg.ControlPlanePubKey, ReceivedAt: time.Now()}) } node := &AgentMeshNode{ @@ -622,7 +582,7 @@ func (n *AgentMeshNode) Start(ctx context.Context) error { } else { logger.Warnf("Autonomous refresh refused (%v); attempting recovery via stored refresh token", refreshErr) if recErr := n.ReEnrollWithRefreshToken(ctx); recErr != nil { - return &StaleIdentityError{Role: n.config.RequiredRole, RoleErr: roleErr, RefreshErr: refreshErr, RecoveryErr: recErr} + return fmt.Errorf("loaded identity fails role requirement %q (autonomous refresh: %v; refresh-token recovery: %v): %w", n.config.RequiredRole, refreshErr, recErr, roleErr) } logger.Info("Identity recovered via refresh-token re-enrollment.") } @@ -2022,20 +1982,13 @@ func (n *AgentMeshNode) handleKeyRotationEvent(event *api.MeshEvent) { n.triggerControlPlaneSync() } -// pruneTrustedKeys drops keys the control plane has not vouched for within -// gracePeriod, as when it stopped listing them or the node could not reach -// it, but always keeps the most recently vouched-for ones: the current -// signing key has no successor until a rotation event arrives, so ageing it -// out would empty the trust set and leave the node unable to verify any peer -// or router. A /keys answer vouches for all its keys at once and says -// nothing about which is current, so every key with the latest time is kept, -// never one of them by its place in the list. It also keeps every key keep reports, which is the key that -// signed the node's own identity: the control plane lists all its valid keys -// alike, so the newest vouched-for key need not be the one a refresh signed -// with, and dropping that one after a long time offline leaves a valid -// identity that fails the check at the next start, when only the control -// plane can renew it. -func pruneTrustedKeys(keys []TrustedKey, now time.Time, gracePeriod time.Duration, keep func(ed25519.PublicKey) bool) []TrustedKey { +// pruneTrustedKeys drops the keys the control plane last vouched for more +// than gracePeriod ago, but always keeps the ones with the latest time: a +// node that cannot reach the control plane must not age out its whole trust +// set and lose the means to verify any peer or router. A /keys answer vouches +// for all its keys at once and its order does not say which is current, so +// the latest time keeps all of them, not the first one in the list. +func pruneTrustedKeys(keys []TrustedKey, now time.Time, gracePeriod time.Duration) []TrustedKey { if len(keys) == 0 { return keys } @@ -2047,27 +2000,13 @@ func pruneTrustedKeys(keys []TrustedKey, now time.Time, gracePeriod time.Duratio } var active []TrustedKey for _, tk := range keys { - if tk.ReceivedAt.Equal(latest) || now.Sub(tk.ReceivedAt) <= gracePeriod || (keep != nil && keep(tk.Key)) { + if tk.ReceivedAt.Equal(latest) || now.Sub(tk.ReceivedAt) <= gracePeriod { active = append(active, tk) } } return active } -// signedOwnIdentity reports whether key signed the node's current identity. -func (n *AgentMeshNode) signedOwnIdentity(key ed25519.PublicKey) bool { - token := n.GetIdentity() - if len(token) == 0 { - return false - } - b, err := biscuit.Unmarshal(token) - if err != nil { - return false - } - _, err = b.Authorizer(key) - return err == nil -} - func (n *AgentMeshNode) startKeyPruning(ctx context.Context, gracePeriod time.Duration) { if gracePeriod <= 0 { return @@ -2080,11 +2019,17 @@ func (n *AgentMeshNode) startKeyPruning(ctx context.Context, gracePeriod time.Du case <-ticker.C: logger.Info("[KeyPruning] Pruning expired keys...") n.keysMu.Lock() - pruned := pruneTrustedKeys(n.trustedKeys, time.Now(), gracePeriod, n.signedOwnIdentity) - changed := len(pruned) != len(n.trustedKeys) + before := n.trustedKeys + pruned := pruneTrustedKeys(before, time.Now(), gracePeriod) + changed := len(pruned) != len(before) n.trustedKeys = pruned snapshot := append([]TrustedKey(nil), pruned...) n.keysMu.Unlock() + for _, tk := range before { + if !containsTrustedKey(pruned, tk.Key) { + logger.Infow("[KeyPruning] dropped control plane key", "key", fmt.Sprintf("%x", tk.Key), "last_vouched", tk.ReceivedAt.UTC().Format(time.RFC3339), "grace_period", gracePeriod.String()) + } + } if changed { n.persistTrustedKeys(snapshot) } diff --git a/internal/node/node_test.go b/internal/node/node_test.go index b50d3808d..913769cdc 100644 --- a/internal/node/node_test.go +++ b/internal/node/node_test.go @@ -337,6 +337,7 @@ func TestPruneTrustedKeys(t *testing.T) { stale := k(48 * time.Hour) staler := k(72 * time.Hour) fresh := k(time.Hour) + sameSync := k(48 * time.Hour) tests := []struct { name string @@ -348,12 +349,13 @@ func TestPruneTrustedKeys(t *testing.T) { {"newest of two stale keys survives", []TrustedKey{staler, stale}, []TrustedKey{stale}}, {"fresh keys all kept", []TrustedKey{fresh, k(2 * time.Hour)}, nil}, // want computed below {"empty", nil, nil}, + {"every key of the latest sync survives", []TrustedKey{stale, staler, sameSync}, []TrustedKey{stale, sameSync}}, } tests[3].want = tests[3].in for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := pruneTrustedKeys(tt.in, now, grace, nil) + got := pruneTrustedKeys(tt.in, now, grace) if len(got) != len(tt.want) { t.Fatalf("got %d keys, want %d", len(got), len(tt.want)) } @@ -366,45 +368,6 @@ func TestPruneTrustedKeys(t *testing.T) { } } -// TestKeyPruningKeepsTheIdentitySigner covers a node whose identity was -// signed by a key it learned before the newest one it holds, as when the -// control plane's newest key reached it earlier or its stored key was added -// again at a restart: pruning must not drop the signer, or the next start -// finds a valid identity that no trusted key verifies. -func TestKeyPruningKeepsTheIdentitySigner(t *testing.T) { - now := time.Now() - signerPub, signerPriv := mustGenerateKey(t) - otherPub, _ := mustGenerateKey(t) - stalePub, _ := mustGenerateKey(t) - priv, _, err := crypto.GenerateEd25519Key(nil) - if err != nil { - t.Fatal(err) - } - pid, err := peer.IDFromPrivateKey(priv) - if err != nil { - t.Fatal(err) - } - token, err := identity.MintBootstrapBiscuitToken(signerPriv, pid, api.RoleNode, now.Add(24*time.Hour), nil, nil) - if err != nil { - t.Fatal(err) - } - n := &AgentMeshNode{} - n.SetIdentityCache(token) - - keys := []TrustedKey{ - {Key: signerPub, ReceivedAt: now.Add(-72 * time.Hour)}, - {Key: stalePub, ReceivedAt: now.Add(-48 * time.Hour)}, - {Key: otherPub, ReceivedAt: now.Add(-time.Minute)}, - } - got := pruneTrustedKeys(keys, now, 24*time.Hour, n.signedOwnIdentity) - if len(got) != 2 || !got[0].Key.Equal(signerPub) || !got[1].Key.Equal(otherPub) { - t.Fatalf("got %d keys, want the identity's signer and the newest key", len(got)) - } - if !n.signedOwnIdentity(signerPub) || n.signedOwnIdentity(otherPub) { - t.Fatal("signedOwnIdentity does not tell the signer from another key") - } -} - // TestHandleAuthHandshake covers the admission office: the relay ACL trusts // authPeers, so the cached instant must be the token's own expiry, and a token // that is expired or bound to another peer must leave no entry at all (#296). @@ -899,83 +862,3 @@ func TestFindProvidersSkipsRevoked(t *testing.T) { t.Errorf("revoked peer returned as provider: %v", providers) } } - -// TestStaleIdentityErrorUnwraps covers what a caller needs from a failed -// start: the refresh status when the control plane answered, and no status -// when it did not. -func TestStaleIdentityErrorUnwraps(t *testing.T) { - refused := &StaleIdentityError{Role: api.RoleNode, RoleErr: errors.New("biscuit: invalid signature"), RefreshErr: &RefreshError{StatusCode: 401, Message: "refused"}, RecoveryErr: errors.New("no refresh token")} - var re *RefreshError - if !errors.As(refused, &re) || re.StatusCode != 401 { - t.Fatalf("errors.As found no refresh status in %v", refused) - } - offline := &StaleIdentityError{Role: api.RoleNode, RoleErr: errors.New("biscuit: invalid signature"), RefreshErr: context.DeadlineExceeded} - if errors.As(offline, &re) || !errors.Is(offline, context.DeadlineExceeded) { - t.Fatalf("offline error unwraps wrong: %v", offline) - } -} - -// TestKeyPruningKeepsEveryLatestKey covers a /keys answer that vouched for -// a retiring and a current key at once, followed by an outage longer than -// the grace period: the answer's order says nothing about which key is -// current, so pruning keeps both rather than whichever came first. -func TestKeyPruningKeepsEveryLatestKey(t *testing.T) { - now := time.Now() - synced := now.Add(-48 * time.Hour) - retiring, _ := mustGenerateKey(t) - current, _ := mustGenerateKey(t) - dropped, _ := mustGenerateKey(t) - keys := []TrustedKey{{Key: retiring, ReceivedAt: synced}, {Key: current, ReceivedAt: synced}, {Key: dropped, ReceivedAt: synced.Add(-time.Hour)}} - got := pruneTrustedKeys(keys, now, 24*time.Hour, func(k ed25519.PublicKey) bool { return k.Equal(retiring) }) - if len(got) != 2 || !got[0].Key.Equal(retiring) || !got[1].Key.Equal(current) { - t.Fatalf("got %d keys, want the retiring and the current key of the last sync", len(got)) - } -} - -// TestFallbackKeyStaysOldThroughTheStore covers the configured key re-added -// next to persisted keys at a start: it must stay older than them after the -// set is saved and loaded again, or the next start would take it for the -// newest key and prune the real rotation key. -func TestFallbackKeyStaysOldThroughTheStore(t *testing.T) { - store, err := NewStore(t.TempDir()) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := store.Close(); err != nil { - t.Errorf("close store: %v", err) - } - }) - rotated, _ := mustGenerateKey(t) - configured, _ := mustGenerateKey(t) - learned := time.Now().Add(-30 * time.Hour).Truncate(time.Second) - if err := store.SaveTrustedKeys([]TrustedKey{{Key: rotated, ReceivedAt: learned}}); err != nil { - t.Fatal(err) - } - priv, _, err := crypto.GenerateEd25519Key(nil) - if err != nil { - t.Fatal(err) - } - n, err := NewAgentMeshNode(Options{PrivKey: priv, Store: store, ControlPlanePubKey: configured}) - if err != nil { - t.Fatal(err) - } - // A rotation event persists the set before any sync succeeds. - n.persistTrustedKeys(n.trustedKeys) - loaded, err := store.LoadTrustedKeys() - if err != nil { - t.Fatal(err) - } - for _, tk := range loaded { - switch { - case tk.Key.Equal(configured) && !tk.ReceivedAt.Equal(neverVouched): - t.Fatalf("configured key loaded as vouched for at %s", tk.ReceivedAt) - case tk.Key.Equal(rotated) && !tk.ReceivedAt.Equal(learned): - t.Fatalf("rotation key loaded with %s, want %s", tk.ReceivedAt, learned) - } - } - got := pruneTrustedKeys(loaded, time.Now(), 24*time.Hour, nil) - if len(got) != 1 || !got[0].Key.Equal(rotated) { - t.Fatalf("pruning kept %d keys, want only the rotation key", len(got)) - } -} diff --git a/sdk/js/src/gen/agentmesh_pb.ts b/sdk/js/src/gen/agentmesh_pb.ts index 7956a12f8..8e76b5c7c 100644 --- a/sdk/js/src/gen/agentmesh_pb.ts +++ b/sdk/js/src/gen/agentmesh_pb.ts @@ -2844,8 +2844,10 @@ export type TrustedSigningKey = Message<"agentmesh.v1.TrustedSigningKey"> & { publicKey: Uint8Array; /** - * When the member first learned the key. A key rotated out is dropped a - * grace period after this; unset means unknown and is read as now. + * When the control plane last vouched for the key: the last /keys answer + * that listed it, or the enrollment or rotation event that announced it. A + * member that prunes drops a key a grace period after this, unless no key + * has a later time; unset means unknown and is read as now. * * @generated from field: google.protobuf.Timestamp receive_time = 2; */ diff --git a/site/content/docs/reference/agentmesh-node.md b/site/content/docs/reference/agentmesh-node.md index c40a14387..cb4e609de 100644 --- a/site/content/docs/reference/agentmesh-node.md +++ b/site/content/docs/reference/agentmesh-node.md @@ -123,7 +123,7 @@ explains how to enroll. | `--backend-probe-timeout` | `2s` | How long an MCP or A2A backend may take to answer before the node declines to advertise it. Raise it for subprocesses that start slowly. | | `--secrets-dir` | `/etc/agentmesh/secrets` | Directory holding the credentials that the control plane's [egress destinations](../policy/#egress-destinations) name, one file per credential name. The platform puts the files there; the node reads a file on every request to the destination. | | `--control-plane-sync-interval` | `15m` | How often signing keys, the ban set, router addresses and the mesh policy are pulled from the control plane. Keep it well below the control plane's `--key-grace-period`; raise it on large meshes. | -| `--key-grace-period` | `24h` | How long a rotated-out control plane key is still accepted for verifying peers. | +| `--key-grace-period` | `24h` | How long the node keeps a control plane key after the control plane last confirmed it in a `/keys` answer or a rotation event. The keys of the latest confirmation always stay. A key that `/keys` no longer lists is removed at the next sync. | | `--monitor-bootstrap` | `2m` | Delay before the router-connection monitor starts. | | `--monitor-interval` | `1m` | How often the monitor checks that a router is connected. | | `--autorelay-min-interval`, `--autorelay-boot-delay`, `--autorelay-backoff` | `30s`, `0s`, `3s` | libp2p AutoRelay tuning. |