Skip to content

Agent Mesh

harden: validate key size and avoid duplicate keys in node key rotation handler

Antonio Ojead5b09a0d2241
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index 7f3db553..a5a8a01b 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -15,6 +15,7 @@
package main
import (
+ "bytes"
"context"
"crypto/ed25519"
"crypto/sha256"
@@ -549,10 +550,19 @@ func (n *SamNode) handleBannedEvent(event *api.MeshEvent) {
}
func (n *SamNode) handleKeyRotationEvent(event *api.MeshEvent) {
+ if len(event.NewPublicKey) != ed25519.PublicKeySize {
+ logger.Errorf("[Mesh Event] Key rotation failed: invalid public key size %d, expected %d", len(event.NewPublicKey), ed25519.PublicKeySize)
+ return
+ }
logger.Infof("[Mesh Event] Key rotation received")
n.keysMu.Lock()
+ defer n.keysMu.Unlock()
+ for _, tk := range n.trustedKeys {
+ if bytes.Equal(tk.Key, event.NewPublicKey) {
+ return // Ignore duplicate
+ }
+ }
n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(event.NewPublicKey), ReceivedAt: time.Now()})
- n.keysMu.Unlock()
}
func (n *SamNode) startKeyPruning(ctx context.Context, gracePeriod time.Duration) {
diff --git a/cmd/sam-node/node_test.go b/cmd/sam-node/node_test.go
index 74c24dcc..312e3a97 100644
--- a/cmd/sam-node/node_test.go
+++ b/cmd/sam-node/node_test.go
@@ -90,7 +90,10 @@ func TestHandleBannedEvent(t *testing.T) {
func TestHandleKeyRotationEvent(t *testing.T) {
node := &SamNode{}
- _, pub, _ := ed25519.GenerateKey(nil)
+ pub, _, err := ed25519.GenerateKey(nil)
+ if err != nil {
+ t.Fatalf("Failed to generate key: %v", err)
+ }
event := &api.MeshEvent{
Type: api.MeshEvent_KEY_ROTATION,
@@ -104,4 +107,3 @@ func TestHandleKeyRotationEvent(t *testing.T) {
t.Errorf("Expected 1 trusted key, got %d", len(node.trustedKeys))
}
}
-