Skip to content

Agent Mesh

fix(security): recover from panics in libp2p stream handlers

Antonio Ojea40b4c51f7923
diff --git a/internal/node/middleware.go b/internal/node/middleware.go
index 9baeb439..34eee8c4 100644
--- a/internal/node/middleware.go
+++ b/internal/node/middleware.go
@@ -37,6 +37,20 @@ type RequestContext struct {
Target string
}
+// recoverStreamHandler isolates a panic while processing untrusted peer bytes
+// to the single stream, resetting it instead of crashing the whole node.
+func recoverStreamHandler(name string, next network.StreamHandler) network.StreamHandler {
+ return func(s network.Stream) {
+ defer func() {
+ if r := recover(); r != nil {
+ logger.Errorf("[%s] panic recovered from peer %s: %v", name, s.Conn().RemotePeer(), r)
+ _ = s.Reset()
+ }
+ }()
+ next(s)
+ }
+}
+
// trackingStream wraps a network.Stream to count bytes read and written.
type trackingStream struct {
network.Stream
diff --git a/internal/node/node.go b/internal/node/node.go
index c7e18bb3..89790866 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -527,10 +527,10 @@ func (n *SamNode) Start(ctx context.Context) error {
go n.startDiscovery(ctx, n.config.MeshID, interval)
// Layer 3: Open the Lobby Door (Auth Protocol is bypassed by Layer 4)
- n.Host.SetStreamHandler(api.AuthProtocolID, n.HandleAuthHandshake)
+ n.Host.SetStreamHandler(api.AuthProtocolID, recoverStreamHandler("AuthHandshake", n.HandleAuthHandshake))
// Layer 3: Wire up MCP handler wrapped in middleware
- n.Host.SetStreamHandler(api.MCPProtocolID, n.WithBiscuitAuth(n.HandleMCPStream))
+ n.Host.SetStreamHandler(api.MCPProtocolID, recoverStreamHandler("MCP", n.WithBiscuitAuth(n.HandleMCPStream)))
// Start key pruning
n.startKeyPruning(ctx, n.config.KeyGracePeriod)
diff --git a/internal/router/router.go b/internal/router/router.go
index 45f702a1..80f5d20c 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -254,7 +254,7 @@ func (r *Router) Start() error {
r.EventTopic = topic
// Setup authentication stream handler
- hostNode.SetStreamHandler(api.AuthProtocolID, r.HandleAuthHandshake)
+ hostNode.SetStreamHandler(api.AuthProtocolID, recoverStreamHandler("AuthHandshake", r.HandleAuthHandshake))
// Clean authenticated status on peer disconnection
hostNode.Network().Notify(&network.NotifyBundle{
@@ -823,6 +823,20 @@ func (r *Router) connectBootstrapRouters() {
}
}
+// recoverStreamHandler isolates a panic while processing untrusted peer bytes
+// to the single stream, resetting it instead of crashing the whole router.
+func recoverStreamHandler(name string, next network.StreamHandler) network.StreamHandler {
+ return func(s network.Stream) {
+ defer func() {
+ if rec := recover(); rec != nil {
+ logger.Errorf("[%s] panic recovered from peer %s: %v", name, s.Conn().RemotePeer(), rec)
+ _ = s.Reset()
+ }
+ }()
+ next(s)
+ }
+}
+
// HandleAuthHandshake processes incoming auth connections.
// It is part of mutual auth:
// 1. Receives client's Biscuit.