diff --git a/api/agentmesh.pb.go b/api/agentmesh.pb.go index ecd9221a..0c99089c 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 b265be2a..6d0f04e6 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 ae7c039f..4635fcd6 100644 --- a/internal/node/controlplane.go +++ b/internal/node/controlplane.go @@ -15,7 +15,6 @@ package node import ( - "bytes" "context" "crypto/ed25519" "time" @@ -86,24 +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, preserving ReceivedAt for keys already known so local grace -// pruning keeps working across syncs. -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) - } - 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 5329c614..f0e31dfb 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 ad2e693b..765a4b5a 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(earlier) { - t.Errorf("known key must keep its ReceivedAt: 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 d65839c8..15c595f6 100644 --- a/internal/node/node.go +++ b/internal/node/node.go @@ -118,6 +118,9 @@ 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 @@ -1979,23 +1982,25 @@ 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. +// 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 } - 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 { active = append(active, tk) } } @@ -2014,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) - 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 10a69334..913769cd 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,6 +349,7 @@ 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 diff --git a/sdk/js/src/gen/agentmesh_pb.ts b/sdk/js/src/gen/agentmesh_pb.ts index 7956a12f..8e76b5c7 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 c40a1438..cb4e609d 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. |