Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node: share one handshake across concurrent first calls to a provider
Antonio Ojea667077f27adc
diff --git a/internal/node/labels_gate.go b/internal/node/labels_gate.goindex c237c257..cafc1a4a 100644--- a/internal/node/labels_gate.go+++ b/internal/node/labels_gate.go@@ -105,19 +105,31 @@ var ErrProviderUnreachable = errors.New("provider unreachable")// not who the policy says serves that name.var ErrProviderNotGranted = errors.New("provider not granted the service")+// ErrHandshakeRateLimited marks a provider that refused the credential+// handshake at its per-peer handshake rate limit: it is up, and answered+// by resetting the stream with network.StreamRateLimited. A caller that+// sees this sent more handshakes than the provider's budget, which the+// in-flight sharing in fetchPeerBiscuit is there to prevent.+var ErrHandshakeRateLimited = errors.New("provider refused the handshake at its rate limit")+// How reaching a provider for its credential went; the label values of// providerReachTotal. The caller sees one 502 for all of the failures, so// the counter tells them apart: the relay refusing the circuit, the dial// timing out (a relay's connection to the provider at its stream limit,// or a provider gone), no address to dial, the provider closing the-// stream before answering.+// stream before answering, the provider refusing the handshake at its+// rate limit. A call that found a handshake already in flight to the+// provider and waited for its verdict instead of opening its own is+// counted as shared.const (reachOK = "ok"+ reachShared = "shared"reachRelayRefused = "relay_refused"reachDialTimeout = "dial_timeout"reachNoAddress = "no_address"reachDialFailed = "dial_failed"reachNoAnswer = "no_answer"+ reachRateLimited = "rate_limited"reachAuthRejected = "auth_rejected"reachOtherFailure = "other"relayRefusedMarker = "error opening relay circuit"@@ -127,6 +139,8 @@ const (func reachFailure(err error) string {var dialErr *swarm.DialErrorswitch {+ case errors.Is(err, ErrHandshakeRateLimited):+ return reachRateLimitedcase errors.As(err, &dialErr):switch {case dialErr.Timeout(), errors.Is(err, context.DeadlineExceeded):@@ -255,10 +269,8 @@ func (n *AgentMeshNode) VerifyProvider(ctx context.Context, peerID peer.ID, requproviderBiscuit, err := n.fetchPeerBiscuit(ctx, peerID)if err != nil {- providerReachTotal.WithLabelValues(reachFailure(err)).Inc()return fmt.Errorf("provider %s labels unverifiable: %w: %w", peerID, ErrProviderUnreachable, err)}- providerReachTotal.WithLabelValues(reachOK).Inc()if err := n.checkProvider(providerBiscuit, peerID, required, service); err != nil {return err}@@ -349,14 +361,63 @@ func (n *AgentMeshNode) checkProvider(providerBiscuit []byte, peerID peer.ID, rereturn nil}+// peerBiscuitFetch is one credential handshake in flight to a peer. Every+// call that needs that peer's credential while it runs waits on done and+// reads the same outcome.+type peerBiscuitFetch struct {+ done chan struct{}+ biscuit []byte+ err error+}+// fetchPeerBiscuit obtains the peer's control-plane-minted identity via the// mutual auth handshake on AuthProtocolID, authenticating with our own.+//+// Concurrent calls for one peer share one handshake. The gate caches only a+// positive verdict, so until the first verdict is in every call would+// otherwise open its own /mesh/auth stream, and a burst of first calls to a+// provider would exceed the provider's per-peer handshake budget+// (ratelimit.PeerBurst) and be refused by it. The shared handshake runs on+// its own goroutine, detached from the context of the call that started it+// and bounded by labelGateDialTimeout, so that one caller leaving does not+// fail the others; each waiter still answers to its own context.func (n *AgentMeshNode) fetchPeerBiscuit(ctx context.Context, peerID peer.ID) ([]byte, error) {- observation, err := n.fetchPeerBiscuitEvidence(ctx, peerID)- if err != nil {- return nil, err+ n.peerBiscuitMu.Lock()+ if n.peerBiscuitInFlight == nil {+ n.peerBiscuitInFlight = make(map[peer.ID]*peerBiscuitFetch)+ }+ fetch, shared := n.peerBiscuitInFlight[peerID]+ if !shared {+ fetch = &peerBiscuitFetch{done: make(chan struct{})}+ n.peerBiscuitInFlight[peerID] = fetch+ }+ n.peerBiscuitMu.Unlock()++ if shared {+ providerReachTotal.WithLabelValues(reachShared).Inc()+ logger.Debugf("[Egress] Waiting for the credential handshake already in flight to %s", peerID)+ } else {+ go func() {+ observation, err := n.fetchPeerBiscuitEvidence(context.WithoutCancel(ctx), peerID)+ if err != nil {+ providerReachTotal.WithLabelValues(reachFailure(err)).Inc()+ } else {+ providerReachTotal.WithLabelValues(reachOK).Inc()+ }+ fetch.biscuit, fetch.err = observation.Biscuit, err+ n.peerBiscuitMu.Lock()+ delete(n.peerBiscuitInFlight, peerID)+ n.peerBiscuitMu.Unlock()+ close(fetch.done)+ }()+ }++ select {+ case <-fetch.done:+ return fetch.biscuit, fetch.err+ case <-ctx.Done():+ return nil, fmt.Errorf("waiting for the credential handshake to %s: %w", peerID, ctx.Err())}- return observation.Biscuit, nil}type peerBiscuitObservation struct {@@ -409,7 +470,7 @@ func (n *AgentMeshNode) fetchPeerBiscuitEvidence(ctx context.Context, peerID peereader := msgio.NewVarintReaderSize(s, 1024*64)msg, err := reader.ReadMsg()if err != nil {- return peerBiscuitObservation{}, fmt.Errorf("read auth response (peer may predate mutual auth): %w", err)+ return peerBiscuitObservation{}, authResponseError(err)}defer reader.ReleaseMsg(msg)@@ -425,3 +486,20 @@ func (n *AgentMeshNode) fetchPeerBiscuitEvidence(ctx context.Context, peerID peeConnectionPeer: connectionPeer,}, nil}++// authResponseError names what a failed read of the handshake answer says+// about the peer. A remote reset with network.StreamRateLimited is the+// peer refusing at its per-peer handshake budget (HandleAuthHandshake); any+// other remote reset is the peer cutting the stream without a reason; a+// clean close before an answer is the peer declining our credential, or a+// peer that predates the mutual handshake.+func authResponseError(err error) error {+ var reset *network.StreamError+ if errors.As(err, &reset) && reset.Remote {+ if reset.ErrorCode == network.StreamRateLimited {+ return fmt.Errorf("%w: %w", ErrHandshakeRateLimited, err)+ }+ return fmt.Errorf("read auth response (peer reset the stream): %w", err)+ }+ return fmt.Errorf("read auth response (peer closed without answering: it declined our credential, or predates mutual auth): %w", err)+}diff --git a/internal/node/labels_gate_test.go b/internal/node/labels_gate_test.goindex b163903b..aacee0a3 100644--- a/internal/node/labels_gate_test.go+++ b/internal/node/labels_gate_test.go@@ -19,7 +19,9 @@ import ("crypto/ed25519""errors""fmt"+ "io""net/http"+ "sync/atomic""testing""time"@@ -27,6 +29,7 @@ import ("github.com/eclipse-biscuit/biscuit-go/v2/datalog""github.com/google/agentmesh/api""github.com/google/agentmesh/internal/identity"+ "github.com/google/agentmesh/internal/ratelimit"lru "github.com/hashicorp/golang-lru/v2""github.com/libp2p/go-libp2p/core/network""github.com/libp2p/go-libp2p/core/peer"@@ -473,7 +476,9 @@ func TestReachFailureClassifiesWhatKeptTheProviderAway(t *testing.T) {{fmt.Errorf("failed to open auth stream: %w", &swarm.DialError{Peer: peerID, Cause: swarm.ErrNoAddresses}), reachNoAddress},{fmt.Errorf("failed to open auth stream: %w", &swarm.DialError{Peer: peerID, Cause: swarm.ErrAllDialsFailed, DialErrors: []swarm.TransportError{{Cause: errors.New("connection refused")}}}), reachDialFailed},{fmt.Errorf("failed to open auth stream: %w", context.DeadlineExceeded), reachDialTimeout},- {errors.New("read auth response (peer may predate mutual auth): EOF"), reachNoAnswer},+ {authResponseError(io.EOF), reachNoAnswer},+ {authResponseError(&network.StreamError{Remote: true}), reachNoAnswer},+ {authResponseError(&network.StreamError{Remote: true, ErrorCode: network.StreamRateLimited}), reachRateLimited},{errors.New("auth rejected: expired"), reachAuthRejected},{errors.New("something else"), reachOtherFailure},} {@@ -482,3 +487,125 @@ func TestReachFailureClassifiesWhatKeptTheProviderAway(t *testing.T) {}}}++// A burst of first calls to one provider is one handshake. Until the first+// verdict is cached every call needs the provider's credential, and each+// handshake a call opened on its own would count against the provider's+// per-peer handshake budget (ratelimit.PeerBurst): 20 concurrent first+// calls to one provider had up to half of them refused, and the caller+// reported each refusal as a destination that did not answer.+func TestVerifyProviderSharesOneHandshakeAcrossABurst(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ provider, cleanupProvider := startBareNode(t, ctx)+ defer cleanupProvider()+ caller, cleanupCaller := startBareNode(t, ctx)+ defer cleanupCaller()+ enrollUnderRoot(t, provider, caller)++ // The provider's handler is held until the whole burst has joined, so+ // that no call arrives after the first verdict is cached: the test is+ // about sharing a handshake in flight, not about the verdict cache.+ var handshakes atomic.Int32+ release := make(chan struct{})+ provider.Host.SetStreamHandler(api.AuthProtocolID, func(s network.Stream) {+ handshakes.Add(1)+ <-release+ provider.HandleAuthHandshake(s)+ })+ if err := caller.Host.Connect(ctx, peer.AddrInfo{ID: provider.Host.ID(), Addrs: provider.Host.Addrs()}); err != nil {+ t.Fatalf("Connect: %v", err)+ }++ shared := providerReachTotal.WithLabelValues(reachShared)+ sharedBefore := counterValue(t, shared)+ attempts := 3 * ratelimit.PeerBurst+ errs := make(chan error, attempts)+ for i := 0; i < attempts; i++ {+ go func() { errs <- caller.VerifyProvider(ctx, provider.Host.ID(), nil, "") }()+ }+ // Every call but the one that opened the handshake joins it, and says+ // so in the counter; that is the condition to wait on.+ wantJoined := float64(attempts - 1)+ for counterValue(t, shared)-sharedBefore < wantJoined {+ select {+ case <-ctx.Done():+ t.Fatalf("%v of %v calls joined the handshake in flight before the deadline", counterValue(t, shared)-sharedBefore, wantJoined)+ case <-time.After(5 * time.Millisecond):+ }+ }+ close(release)++ for i := 0; i < attempts; i++ {+ if err := <-errs; err != nil {+ t.Errorf("VerifyProvider: %v", err)+ }+ }+ if got := handshakes.Load(); got != 1 {+ t.Errorf("the provider saw %d handshakes for %d concurrent first calls, want 1", got, attempts)+ }+ if got := counterValue(t, shared) - sharedBefore; got != wantJoined {+ t.Errorf("shared = %v, want %v", got, wantJoined)+ }+}++// A waiter answers to its own context: the handshake it joined runs on,+// detached from the call that opened it, so one caller leaving fails+// neither the others nor the handshake.+func TestFetchPeerBiscuitWaiterLeavesOnItsOwnContext(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ provider, cleanupProvider := startBareNode(t, ctx)+ defer cleanupProvider()+ caller, cleanupCaller := startBareNode(t, ctx)+ defer cleanupCaller()+ enrollUnderRoot(t, provider, caller)++ release := make(chan struct{})+ provider.Host.SetStreamHandler(api.AuthProtocolID, func(s network.Stream) {+ <-release+ provider.HandleAuthHandshake(s)+ })+ if err := caller.Host.Connect(ctx, peer.AddrInfo{ID: provider.Host.ID(), Addrs: provider.Host.Addrs()}); err != nil {+ t.Fatalf("Connect: %v", err)+ }++ shared := providerReachTotal.WithLabelValues(reachShared)+ sharedBefore := counterValue(t, shared)+ leaderCtx, leaderCancel := context.WithCancel(ctx)+ leaderErr := make(chan error, 1)+ go func() {+ _, err := caller.fetchPeerBiscuit(leaderCtx, provider.Host.ID())+ leaderErr <- err+ }()+ followerErr := make(chan error, 1)+ go func() {+ _, err := caller.fetchPeerBiscuit(ctx, provider.Host.ID())+ followerErr <- err+ }()+ for counterValue(t, shared)-sharedBefore < 1 {+ select {+ case <-ctx.Done():+ t.Fatal("the second call did not join the handshake in flight before the deadline")+ case <-time.After(5 * time.Millisecond):+ }+ }++ // The call that opened the handshake leaves; the follower must still+ // get the credential once the provider answers.+ leaderCancel()+ if err := <-leaderErr; !errors.Is(err, context.Canceled) {+ t.Fatalf("leaving caller: err = %v, want context.Canceled", err)+ }+ select {+ case err := <-followerErr:+ t.Fatalf("follower returned %v before the provider answered", err)+ default:+ }+ close(release)+ if err := <-followerErr; err != nil {+ t.Errorf("follower: %v", err)+ }+}diff --git a/internal/node/node.go b/internal/node/node.goindex c37d2b8e..463c6954 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -216,6 +216,12 @@ type AgentMeshNode struct {delegatedBiscuitCache *lru.Cache[string, *api.TokenExchangeResponse]stsTokenCache *lru.Cache[string, *api.STSTokenResponse]peerLabelGate *lru.Cache[string, time.Time]+ // peerBiscuitInFlight is the credential fetch running to each peer, so+ // that concurrent first calls to one provider share one handshake+ // (fetchPeerBiscuit); nil until the first fetch, the map is created+ // under peerBiscuitMu because tests build AgentMeshNode directly.+ peerBiscuitInFlight map[peer.ID]*peerBiscuitFetch+ peerBiscuitMu sync.Mutex// authPeers is every peer that completed the handshake with this node,// keyed by peer.ID, with the instant its admission lapses. authRouters// holds the subset whose credential carried mesh:role:router, with the@@ -2087,25 +2093,32 @@ var authHandshakeTimeout = 10 * time.Second// HandleAuthHandshake is the core libp2p stream handler for /mesh/auth/1.0.0.// This is the "Admission Office" of the mesh node.func (n *AgentMeshNode) HandleAuthHandshake(s network.Stream) {- defer func() {+ closeStream := func() {if err := s.Close(); err != nil {logger.Errorf("[AuthN] Failed to close auth stream: %v", err)}- }()+ }remotePeer := s.Conn().RemotePeer()if n.revokedPeers != nil {if _, revoked := n.revokedPeers.Get(remotePeer.String()); revoked {logger.Warnf("[AuthN] Peer %s is revoked", remotePeer)+ closeStream()return}}+ // A reset stream cannot be closed, so this refusal returns before the+ // deferred Close: it is this node's decision, not an error. The code+ // tells the peer why, so it reports a refusal rather than a+ // destination that did not answer (authResponseError).if n.handshakeLimiter != nil && !n.handshakeLimiter.Allow(remotePeer.String()) {logger.Warnf("[AuthN] Handshake rate limit exceeded for %s", remotePeer)- _ = s.Reset()+ _ = s.ResetWithError(network.StreamRateLimited)return}+ defer closeStream()+if err := s.SetDeadline(time.Now().Add(authHandshakeTimeout)); err != nil {logger.Debugf("[AuthN] Failed to set handshake deadline for %s: %v", remotePeer, err)}diff --git a/internal/node/node_metrics.go b/internal/node/node_metrics.goindex 747ec2e4..b7a2dd60 100644--- a/internal/node/node_metrics.go+++ b/internal/node/node_metrics.go@@ -49,17 +49,19 @@ func init() {for _, result := range []string{lookupFound, lookupNotFound, lookupFailed} {peerLookupsTotal.WithLabelValues(result)}- for _, result := range []string{reachOK, reachRelayRefused, reachDialTimeout, reachNoAddress, reachDialFailed, reachNoAnswer, reachAuthRejected, reachOtherFailure} {+ for _, result := range []string{reachOK, reachShared, reachRelayRefused, reachDialTimeout, reachNoAddress, reachDialFailed, reachNoAnswer, reachRateLimited, reachAuthRejected, reachOtherFailure} {providerReachTotal.WithLabelValues(result)}}// providerReachTotal counts the attempts a call made to reach a provider// for its credential, by outcome; every failure is one 502 at the caller.+// A call that joined a handshake already in flight is counted as shared,+// so the ratio of shared to the rest is how much a burst was collapsed.var providerReachTotal = promauto.NewCounterVec(prometheus.CounterOpts{Name: "agentmesh_node_provider_reach_total",- Help: "Attempts to reach a provider for its credential before a call, by outcome: ok, relay_refused, dial_timeout, no_address, dial_failed, no_answer, auth_rejected, other",+ Help: "Attempts to reach a provider for its credential before a call, by outcome: ok, shared (joined a handshake in flight), relay_refused, dial_timeout, no_address, dial_failed, no_answer, rate_limited, auth_rejected, other",},[]string{"result"},)diff --git a/internal/node/node_test.go b/internal/node/node_test.goindex c8ba1e02..10a69334 100644--- a/internal/node/node_test.go+++ b/internal/node/node_test.go@@ -30,6 +30,7 @@ import (lru "github.com/hashicorp/golang-lru/v2""github.com/libp2p/go-libp2p""github.com/libp2p/go-libp2p/core/crypto"+ "github.com/libp2p/go-libp2p/core/network""github.com/libp2p/go-libp2p/core/peer""github.com/libp2p/go-libp2p/p2p/net/connmgr""github.com/libp2p/go-msgio"@@ -573,12 +574,21 @@ func TestHandleAuthHandshakeBoundsUnauthenticatedPeers(t *testing.T) {t.Fatal(err)}_ = s.SetDeadline(time.Now().Add(5 * time.Second))- if err := msgio.NewVarintWriter(s).WriteMsg(frame); err == nil {- if _, err := msgio.NewVarintReaderSize(s, 1024*64).ReadMsg(); err == nil {- answered++- }+ err = msgio.NewVarintWriter(s).WriteMsg(frame)+ if err == nil {+ _, err = msgio.NewVarintReaderSize(s, 1024*64).ReadMsg()}_ = s.Close()+ if err == nil {+ answered+++ continue+ }+ // A refusal names its reason, so the peer tells it apart from+ // a node that did not answer.+ var reset *network.StreamError+ if !errors.As(err, &reset) || !reset.Remote || reset.ErrorCode != network.StreamRateLimited {+ t.Errorf("handshake %d failed with %v, want a remote reset with StreamRateLimited", i, err)+ }}// The token is valid, so every answer is a success: the only reason// some go unanswered is the limiter.diff --git a/internal/router/router.go b/internal/router/router.goindex 4bc34d84..f6e323da 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -1863,7 +1863,8 @@ func (r *Router) HandleAuthHandshake(s network.Stream) {if r.handshakeLimiter != nil && !r.handshakeLimiter.Allow(remotePeer.String()) {logger.Warnf("[AuthN] Handshake rate limit exceeded for %s", remotePeer)authHandshakesTotal.WithLabelValues(handshakeRateLimited).Inc()- _ = s.Reset()+ // The code tells the peer it was refused, not left unanswered.+ _ = s.ResetWithError(network.StreamRateLimited)return}if err := s.SetDeadline(time.Now().Add(authHandshakeTimeout)); err != nil {diff --git a/internal/router/router_test.go b/internal/router/router_test.goindex 874a156a..cc87b632 100644--- a/internal/router/router_test.go+++ b/internal/router/router_test.go@@ -22,6 +22,7 @@ import ("crypto/rsa""encoding/base64""encoding/json"+ "errors""io""math/big""net/http"@@ -1229,12 +1230,21 @@ func TestHandleAuthHandshakeBoundsUnauthenticatedPeers(t *testing.T) {t.Fatal(err)}_ = s.SetDeadline(time.Now().Add(5 * time.Second))- if err := msgio.NewVarintWriter(s).WriteMsg(frame); err == nil {- if _, err := msgio.NewVarintReaderSize(s, 1024*64).ReadMsg(); err == nil {- answered++- }+ err = msgio.NewVarintWriter(s).WriteMsg(frame)+ if err == nil {+ _, err = msgio.NewVarintReaderSize(s, 1024*64).ReadMsg()}_ = s.Close()+ if err == nil {+ answered+++ continue+ }+ // A refusal names its reason, so the peer tells it apart from+ // a node that did not answer.+ var reset *network.StreamError+ if !errors.As(err, &reset) || !reset.Remote || reset.ErrorCode != network.StreamRateLimited {+ t.Errorf("handshake %d failed with %v, want a remote reset with StreamRateLimited", i, err)+ }}if answered < ratelimit.PeerBurst {t.Errorf("only %d of the first %d handshakes answered; limiter is too strict", answered, ratelimit.PeerBurst)diff --git a/site/content/docs/guides/scalability.md b/site/content/docs/guides/scalability.mdindex 87220d8b..43b125fe 100644--- a/site/content/docs/guides/scalability.md+++ b/site/content/docs/guides/scalability.md@@ -447,7 +447,7 @@ control plane serves Prometheus metrics on its HTTP listen address,| `agentmesh_node_inbound_connections_refused_total{reason}` against `agentmesh_node_conns_per_source_ip_limit` | On a provider: direct callers it turned away before the handshake. `per_ip_limit` is a fleet behind one address, `rate_limit` a burst from one address, `scope_limit` more callers at once than the node's connection budget, relayed ones included. The caller sees the connection close before TLS, or `CONNECTION_REFUSED` over QUIC, and nothing more. || `agentmesh_node_transit_handshakes_total{router,result}` | On a caller: handshakes with routers it did not hold, run to reach a peer through them. `router="unlisted"` is a router the node's catalog missed, which a member that started during a router rollout produces until its next sync; `result="failed"` rising is a router that refuses the node or is gone while peers still announce circuits through it. || `agentmesh_node_peer_lookups_total{result}` | On a caller: directory lookups for a peer it held no address for. `not_found` is a peer the directory does not carry, and the call falls back to circuits through the caller's own routers, which reach the peer only if it holds one of them; `failed` rising is no held router answering (`agentmesh_node_directory_requests_total{result="failed"}` rises with it). |-| `agentmesh_node_provider_reach_total{result}` | On a caller: attempts to reach a provider for its credential before a call; every failure is one 502 at the caller. `relay_refused` is a router that has not admitted the caller or the provider, `dial_timeout` a provider gone or a relay connection at its stream limit (below), `no_address` a provider the directory does not carry. |+| `agentmesh_node_provider_reach_total{result}` | On a caller: attempts to reach a provider for its credential before a call; every failure is one 502 at the caller. `relay_refused` is a router that has not admitted the caller or the provider, `dial_timeout` a provider gone or a relay connection at its stream limit (below), `no_address` a provider the directory does not carry, `rate_limited` a provider that refused the handshake at its per-peer handshake budget. Concurrent first calls to one provider share one handshake, and the ones that waited for it are `shared`; `rate_limited` rising on a caller while `shared` does not means the burst did not collapse. || `agentmesh_router_busiest_connection_streams{transport}`, `agentmesh_node_busiest_connection_streams{transport}` | The most streams any one connection carries. Every relayed connection is one stream on the relay's connection to each end, and a QUIC connection admits 256 streams: a provider reached through one router over QUIC has at most 256 callers through it at once, and the 257th waits until one leaves, which it sees as a dial that times out. Both ends log the connection once a minute while it is within a tenth of the limit. A provider that expects more callers than that listens on TCP as well, or holds more routers. || `libp2p_relaysvc_reservations_total{type="opened"}` minus `{type="closed"}`, against `agentmesh_router_relay_limit{limit="reservations"}` | Reservations in use against the budget. || `libp2p_relaysvc_connection_rejections_total{reason="resource limit exceeded"}` | A service has more callers than `--relay-max-circuits`. |