Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions api/agentmesh.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions api/agentmesh.proto
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
19 changes: 0 additions & 19 deletions internal/node/controlplane.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package node

import (
"bytes"
"context"
"crypto/ed25519"
"time"
Expand Down Expand Up @@ -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 {
Expand Down
15 changes: 11 additions & 4 deletions internal/node/controlplane_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
}
Comment on lines +146 to +149

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since the size of keys is exactly known, we can pre-allocate the slice with the correct length and assign elements directly by index instead of using append. This avoids slice growth checks and is more efficient.

Suggested change
synced := make([]TrustedKey, 0, len(keys))
for _, key := range keys {
synced = append(synced, TrustedKey{Key: key, ReceivedAt: now})
}
synced := make([]TrustedKey, len(keys))
for i, key := range keys {
synced[i] = 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
}

Expand Down
52 changes: 23 additions & 29 deletions internal/node/controlplane_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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")
}
Comment on lines +141 to +143

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

According to Section 3, Rule 8 of the Repository Style Guide, assertion messages must state both the observed and the expected value. Let's update the assertion message to explicitly show what was observed and what was expected.

Suggested change
if containsTrustedKey(n.trustedKeys, expiredPub) {
t.Error("a key /keys does not list stayed in the trust set")
}
if containsTrustedKey(n.trustedKeys, expiredPub) {
t.Errorf("syncTrustedKeys kept expired key %x, want it removed", expiredPub)
}
References
  1. Section 3, Rule 8 of the Repository Style Guide requires assertion messages to state both the observed and the expected value. (link)

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))
}
Comment on lines +145 to +147

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

According to Section 3, Rule 8 of the Repository Style Guide, assertion messages must state both the observed and the expected value. Let's update this assertion message to explicitly show the observed number of keys and the expected keys.

Suggested change
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))
}
if len(got) != 2 || !containsTrustedKey(got, retiredPub) || !containsTrustedKey(got, currentPub) {
t.Errorf("pruning kept %d keys (%v), want 2 keys: retired (%x) and current (%x)", len(got), got, retiredPub, currentPub)
}
References
  1. Section 3, Rule 8 of the Repository Style Guide requires assertion messages to state both the observed and the expected value. (link)

})

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()
Expand Down
35 changes: 23 additions & 12 deletions internal/node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}
Expand All @@ -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)
}
Expand Down
2 changes: 2 additions & 0 deletions internal/node/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
6 changes: 4 additions & 2 deletions sdk/js/src/gen/agentmesh_pb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
*/
Expand Down
2 changes: 1 addition & 1 deletion site/content/docs/reference/agentmesh-node.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
Loading