Skip to content

Agent Mesh

controlplane: hand the routers out in a random order

Antonio Ojeafe2141c28b73
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index afbf8ed2..338227f6 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -27,6 +27,7 @@ import (
"errors"
"fmt"
"io"
+ mathrand "math/rand/v2"
"net"
"net/http"
"slices"
@@ -54,6 +55,22 @@ import (
var logger = golog.Logger("sam-control-plane")
+// routerAddresses is the router list a member receives: every active router's
+// addresses, the routers in a fresh random order per response and each
+// router's addresses together. A member reserves its relay slot on the first
+// router that admits it, so the order decides which router carries it; one
+// order for everyone would put every member on the same router. Reaching a
+// peer does not depend on the order: a caller tries every router it joined
+// through and looks the peer up in the routers' DHT otherwise.
+func routerAddresses(routers []storage.RouterLease) []string {
+ mathrand.Shuffle(len(routers), func(i, j int) { routers[i], routers[j] = routers[j], routers[i] })
+ var addrs []string
+ for _, r := range routers {
+ addrs = append(addrs, r.Addresses...)
+ }
+ return addrs
+}
+
const (
EnrollRateLimit = 10
EnrollBurst = 20
@@ -473,11 +490,7 @@ func (s *Server) HandleInfo(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
-
- var routerAddrs []string
- for _, r := range activeRouters {
- routerAddrs = append(routerAddrs, r.Addresses...)
- }
+ routerAddrs := routerAddresses(activeRouters)
// The ban set is published here, rather than only as a MeshEvent, because
// the event is broadcast once and gossip has no replay: a node or router
@@ -722,11 +735,7 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
-
- var routerAddrs []string
- for _, r := range activeRouters {
- routerAddrs = append(routerAddrs, r.Addresses...)
- }
+ routerAddrs := routerAddresses(activeRouters)
resp := &api.EnrollResponse{
BiscuitToken: biscuitData,
@@ -2604,11 +2613,7 @@ func (s *Server) buildApprovedBootstrapEnrollResponse(ctx context.Context, biscu
if err != nil {
return nil, fmt.Errorf("failed to retrieve active routers: %w", err)
}
-
- var routerAddrs []string
- for _, r := range activeRouters {
- routerAddrs = append(routerAddrs, r.Addresses...)
- }
+ routerAddrs := routerAddresses(activeRouters)
expiration := time.Now().Add(s.config.BiscuitTTL)
if resolvedAt != nil {
diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.go
index 250987e8..d029b2cb 100644
--- a/internal/controlplane/server_test.go
+++ b/internal/controlplane/server_test.go
@@ -564,6 +564,43 @@ func TestNodeAndRouterRegistrationFlow(t *testing.T) {
// so anything the render drops is silently deleted from the mesh policy on the
// next save. protojson is generated, which is the point: a hand-written renderer
// is what lost custom_datalog before.
+// Members reserve on the first router they are handed, so every router has
+// to come first for some of them, and a router's addresses have to stay
+// together so "the first router" is one router.
+func TestRouterAddressesSpreadMembersAcrossRouters(t *testing.T) {
+ routers := func() []storage.RouterLease {
+ return []storage.RouterLease{
+ {PeerID: "a", Addresses: []string{"/ip4/10.0.0.1/tcp/4501/p2p/a", "/ip4/10.0.0.1/udp/4501/quic-v1/p2p/a"}},
+ {PeerID: "b", Addresses: []string{"/ip4/10.0.0.2/tcp/4501/p2p/b", "/ip4/10.0.0.2/udp/4501/quic-v1/p2p/b"}},
+ {PeerID: "c", Addresses: []string{"/ip4/10.0.0.3/tcp/4501/p2p/c"}},
+ }
+ }
+ routerOf := func(addr string) string { return addr[strings.LastIndex(addr, "/")+1:] }
+ first := map[string]int{}
+ for i := 0; i < 300; i++ {
+ addrs := routerAddresses(routers())
+ if len(addrs) != 5 {
+ t.Fatalf("got %d addresses, want every router's 5", len(addrs))
+ }
+ first[routerOf(addrs[0])]++
+ // Once a router's run of addresses ends, that router is not seen again.
+ seen := map[string]bool{}
+ for j, addr := range addrs {
+ id := routerOf(addr)
+ if seen[id] && routerOf(addrs[j-1]) != id {
+ t.Fatalf("router %s's addresses are split in %v", id, addrs)
+ }
+ seen[id] = true
+ }
+ }
+ // (2/3)^300 that a router never comes first by chance.
+ for _, id := range []string{"a", "b", "c"} {
+ if first[id] == 0 {
+ t.Errorf("router %s never came first in 300 responses: %v", id, first)
+ }
+ }
+}
+
func TestMarshalPolicyJSONRoundTrip(t *testing.T) {
roles := []*api.PolicyRole{
{
diff --git a/internal/storage/sql_store.go b/internal/storage/sql_store.go
index 27944418..fc5465b6 100644
--- a/internal/storage/sql_store.go
+++ b/internal/storage/sql_store.go
@@ -976,9 +976,9 @@ func (s *SQLStore) UpsertRouterLease(ctx context.Context, lease *RouterLease) er
return err
}
-// GetActiveRouters implements Store. The order is by peer ID, so every
-// member handed the list picks the same first router to reserve a relay on
-// and a caller finds a peer's reservation where it looks first.
+// GetActiveRouters implements Store. The order is by peer ID, so the store
+// reads the same to every replica and caller; the control plane shuffles the
+// list it hands members (routerAddresses) so they spread across the routers.
func (s *SQLStore) GetActiveRouters(ctx context.Context) ([]RouterLease, error) {
query := s.rebind(`SELECT peer_id, multiaddresses, last_lease_renewal, expires_at, connected_peers, dht_size FROM routers WHERE expires_at > ? ORDER BY peer_id`)
rows, err := s.db.QueryContext(ctx, query, time.Now().UnixMilli())
diff --git a/internal/storage/sql_store_test.go b/internal/storage/sql_store_test.go
index 0f83635f..87bd0ec4 100644
--- a/internal/storage/sql_store_test.go
+++ b/internal/storage/sql_store_test.go
@@ -483,8 +483,8 @@ func TestRouterLeaseOps(t *testing.T) {
}
// More routers come back in one order, by peer ID, whatever the order
- // they leased in: members reserve on the first and callers try them in
- // turn, so both sides must see the same list.
+ // they leased in: the store reads the same to every replica, and what a
+ // member is handed is shuffled from this by the control plane.
for _, id := range []string{"12D3KooWZzzLastRouter", "12D3KooWAaaFirstRouter"} {
if err := store.UpsertRouterLease(ctx, &RouterLease{
PeerID: id,
diff --git a/tests/integration/noise_test.go b/tests/integration/noise_test.go
index 18330b6e..0000a070 100644
--- a/tests/integration/noise_test.go
+++ b/tests/integration/noise_test.go
@@ -17,6 +17,7 @@ package integration_test
import (
"context"
"crypto/ed25519"
+ "fmt"
"strings"
"testing"
"time"
@@ -69,11 +70,33 @@ func TestNoiseOnlyPeer(t *testing.T) {
}
nodeID := mesh.samNode.peerID
- relayed := multiaddr.StringCast(mesh.routerAddr + "/p2p-circuit/p2p/" + nodeID.String())
- // A relayed connection reports no security protocol in its ConnState;
- // that this peer, which has Noise alone, gets one at all is the check.
- if err := h.Connect(network.WithAllowLimitedConn(ctx, "test"), peer.AddrInfo{ID: nodeID, Addrs: []multiaddr.Multiaddr{relayed}}); err != nil {
- t.Fatalf("noise-only peer could not reach the node through the router: %v", err)
+ // The node reserved on a router of its choosing; a relayed connection
+ // reports no security protocol in its ConnState, so that this peer, which
+ // has Noise alone, gets one at all is the check. The peer must have passed
+ // the handshake with the router it dials through.
+ var relayErrs []string
+ connected := false
+ for _, routerAddr := range mesh.routerAddrs {
+ via, err := peer.AddrInfoFromString(routerAddr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if via.ID != router.ID {
+ if err := h.Connect(ctx, *via); err != nil {
+ t.Fatalf("noise-only peer could not connect to router %s: %v", routerAddr, err)
+ }
+ authHandshake(t, ctx, h, via.ID, biscuit)
+ }
+ relayed := multiaddr.StringCast(routerAddr + "/p2p-circuit/p2p/" + nodeID.String())
+ if err := h.Connect(network.WithAllowLimitedConn(ctx, "test"), peer.AddrInfo{ID: nodeID, Addrs: []multiaddr.Multiaddr{relayed}}); err != nil {
+ relayErrs = append(relayErrs, fmt.Sprintf("%s: %v", routerAddr, err))
+ continue
+ }
+ connected = true
+ break
+ }
+ if !connected {
+ t.Fatalf("noise-only peer could not reach the node through any router:\n %s", strings.Join(relayErrs, "\n "))
}
nodeBiscuit := authHandshake(t, ctx, h, nodeID, biscuit)
if err := identity.VerifyBiscuitRole(nodeBiscuit, mesh.cpPriv.Public().(ed25519.PublicKey), api.RoleNode, 5*time.Second); err != nil {
@@ -87,7 +110,7 @@ func TestNoiseOnlyPeer(t *testing.T) {
}
// The TLS peer of the other tests is unchanged: TLS is offered first.
- tlsPeer := newAdmittedGoPeer(t, ctx, mesh.cpPriv, mesh.routerAddr)
+ tlsPeer := newAdmittedGoPeer(t, ctx, mesh.cpPriv, mesh.routerAddrs)
if got := securityOf(tlsPeer, router.ID); !strings.HasPrefix(got, "/tls/") {
t.Fatalf("TLS peer's connection to the router is %q, want /tls/...", got)
}
diff --git a/tests/integration/sdk_mesh_test.go b/tests/integration/sdk_mesh_test.go
index e73fb31f..e64adca0 100644
--- a/tests/integration/sdk_mesh_test.go
+++ b/tests/integration/sdk_mesh_test.go
@@ -68,8 +68,9 @@ type sdkMesh struct {
cpPub ed25519.PublicKey
routerAddr string
routerPeer string
- // routerAddrs lists every router, in the order the control plane hands them
- // out (by peer ID); routerAddr is the first, where members reserve.
+ // routerAddrs lists every router; routerAddr is one of them, for tests
+ // that need a router. The control plane hands them out in a random order
+ // per response, so members spread across them.
routerAddrs []string
samNode *backgroundNode
nodeAPI string
@@ -192,12 +193,11 @@ egress:
// Two routers, as the testnets run several: a member authenticates with
// every one and reserves a relay slot on the first the control plane
- // lists, so a caller finds a peer's reservation where it looks first.
+ // lists for it, a different one from member to member.
routerA, _ := startRouter(t, t.TempDir(), cpPort, mintToken, "router-a")
routerB, _ := startRouter(t, t.TempDir(), cpPort, mintToken, "router-b")
routerAddrs := []string{routerA, routerB}
- sort.Slice(routerAddrs, func(i, j int) bool { return extractPeerID(routerAddrs[i]) < extractPeerID(routerAddrs[j]) })
- routerAddr := routerAddrs[0]
+ routerAddr := routerA
cpPriv, cpPub, err := store.GetCurrentKey(context.Background())
if err != nil {
@@ -376,7 +376,7 @@ func TestNativeSDKsMesh(t *testing.T) {
waitForPeerOnRouter(t, cpPort, adminToken, m.report.PeerID, 5*time.Second)
}
- goPeer := newAdmittedGoPeer(t, ctx, cpPriv, routerAddr)
+ goPeer := newAdmittedGoPeer(t, ctx, cpPriv, mesh.routerAddrs)
for _, m := range members {
m := m
@@ -443,7 +443,10 @@ func TestNativeSDKsMesh(t *testing.T) {
if len(providers) != 1 {
t.Fatalf("%s discovered %+v for %s, want only the node", m.name, providers, serviceName)
}
- nodeRelayAddr := routerAddr + "/p2p-circuit/p2p/" + samNode.peerID.String()
+ // By peer ID: the node reserved on a router of its choosing, and
+ // the member finds the relayed path through whichever of the
+ // routers it joined through relays for the node.
+ nodeRelayAddr := samNode.peerID.String()
if tools := m.tools(t, nodeRelayAddr, "mcp://"+serviceName); !contains(tools, "add") {
t.Fatalf("%s listed %v on mcp://%s, want add", m.name, tools, serviceName)
}
@@ -479,7 +482,7 @@ func TestNativeSDKsMesh(t *testing.T) {
}
for _, tc := range sdkMeshLabelRequirements {
t.Run(tc.name, func(t *testing.T) {
- nodeRelayAddr := routerAddr + "/p2p-circuit/p2p/" + samNode.peerID.String()
+ nodeRelayAddr := samNode.peerID.String()
for _, m := range members {
res := m.toolsRequiring(t, nodeRelayAddr, "mcp://"+serviceName, tc.required)
if res.OK != tc.allowed {
@@ -500,7 +503,7 @@ func TestNativeSDKsMesh(t *testing.T) {
for _, m := range members {
m.accept(t, "agent")
}
- guest := newGuestGoPeer(t, ctx, cpPriv, routerAddr)
+ guest := newGuestGoPeer(t, ctx, cpPriv, mesh.routerAddrs)
for _, m := range members {
m := m
t.Run(m.name+"-accepts", func(t *testing.T) {
@@ -599,7 +602,7 @@ func TestNativeSDKsMesh(t *testing.T) {
t.Run("ban-and-rotation", func(t *testing.T) {
// An enrolled peer the control plane can ban: a node record, admitted
// by every member over the router.
- outcast := newAdmittedGoPeer(t, ctx, cpPriv, routerAddr)
+ outcast := newAdmittedGoPeer(t, ctx, cpPriv, mesh.routerAddrs)
outcastBiscuit := goHostBiscuit(t, cpPriv, outcast.ID())
outcastPub, err := crypto.MarshalPublicKey(outcast.Peerstore().PubKey(outcast.ID()))
if err != nil {
@@ -813,12 +816,9 @@ func routerIDs(report sdkJoinReport) []string {
func startSDKMember(t *testing.T, name string, cmd *exec.Cmd, root, baseURL, adminToken string, routerAddrs []string) *sdkMember {
t.Helper()
- routerAddr, routerPeer := routerAddrs[0], extractPeerID(routerAddrs[0])
m := launchSDKMember(t, name, cmd, root, baseURL, adminToken, "SAM_SDK_LISTEN_ADDRS=/ip4/127.0.0.1/tcp/0")
- // Every router the control plane named admitted the member, in the
- // control plane's order: a peer reserves on the first, and a caller that
- // knew only its own first router could not reach a peer whose list
- // started elsewhere.
+ // Every router the control plane named admitted the member, in whatever
+ // order it was handed them; it reserved on the first of its own list.
var admitted []string
for _, r := range m.report.Routers {
admitted = append(admitted, r.PeerID)
@@ -830,15 +830,18 @@ func startSDKMember(t *testing.T, name string, cmd *exec.Cmd, root, baseURL, adm
for _, a := range routerAddrs {
want = append(want, extractPeerID(a))
}
+ sort.Strings(admitted)
+ sort.Strings(want)
if !reflect.DeepEqual(admitted, want) {
t.Fatalf("%s report routers %v, want every router the control plane listed %v", name, admitted, want)
}
if len(m.report.RelayAddresses) == 0 {
t.Fatalf("%s: no relay address, the router did not grant a reservation", name)
}
+ first := m.report.Routers[0]
for _, a := range m.report.RelayAddresses {
- if !strings.HasPrefix(a, routerAddr) || !strings.HasSuffix(a, "/p2p-circuit/p2p/"+m.report.PeerID) {
- t.Fatalf("%s relay address %s is not <router>/p2p-circuit/p2p/<self> for the first router %s (%s)", name, a, routerPeer, routerAddr)
+ if !strings.HasPrefix(a, first.Addr) || !strings.HasSuffix(a, "/p2p-circuit/p2p/"+m.report.PeerID) {
+ t.Fatalf("%s relay address %s is not <router>/p2p-circuit/p2p/<self> for its first router %s (%s)", name, a, first.PeerID, first.Addr)
}
}
return m
@@ -1222,8 +1225,8 @@ func (m *sdkMember) readLine(t *testing.T, timeout time.Duration) []byte {
}
// newAdmittedGoPeer is a libp2p host configured like sam-node's, connected
-// to the router and past its auth handshake, so the router relays for it.
-func newAdmittedGoPeer(t *testing.T, ctx context.Context, cpPriv ed25519.PrivateKey, routerAddr string) host.Host {
+// to every router and past their auth handshakes, so each relays for it.
+func newAdmittedGoPeer(t *testing.T, ctx context.Context, cpPriv ed25519.PrivateKey, routerAddrs []string) host.Host {
t.Helper()
h, err := libp2p.New(
libp2p.NoListenAddrs,
@@ -1234,18 +1237,21 @@ func newAdmittedGoPeer(t *testing.T, ctx context.Context, cpPriv ed25519.Private
t.Fatalf("failed to create go peer: %v", err)
}
t.Cleanup(func() { _ = h.Close() })
- info, err := peer.AddrInfoFromString(routerAddr)
- if err != nil {
- t.Fatalf("router address %s: %v", routerAddr, err)
- }
- connectCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
- defer cancel()
- if err := h.Connect(connectCtx, *info); err != nil {
- t.Fatalf("go peer could not connect to the router: %v", err)
- }
- routerBiscuit := authHandshake(t, ctx, h, info.ID, goHostBiscuit(t, cpPriv, h.ID()))
- if err := identity.VerifyBiscuitRole(routerBiscuit, cpPriv.Public().(ed25519.PublicKey), api.RoleRouter, 5*time.Second); err != nil {
- t.Fatalf("router credential lacks the router role: %v", err)
+ for _, routerAddr := range routerAddrs {
+ info, err := peer.AddrInfoFromString(routerAddr)
+ if err != nil {
+ t.Fatalf("router address %s: %v", routerAddr, err)
+ }
+ connectCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ err = h.Connect(connectCtx, *info)
+ cancel()
+ if err != nil {
+ t.Fatalf("go peer could not connect to router %s: %v", routerAddr, err)
+ }
+ routerBiscuit := authHandshake(t, ctx, h, info.ID, goHostBiscuit(t, cpPriv, h.ID()))
+ if err := identity.VerifyBiscuitRole(routerBiscuit, cpPriv.Public().(ed25519.PublicKey), api.RoleRouter, 5*time.Second); err != nil {
+ t.Fatalf("router credential lacks the router role: %v", err)
+ }
}
return h
}
@@ -1270,11 +1276,11 @@ func guestHostBiscuit(t *testing.T, cpPriv ed25519.PrivateKey, id peer.ID) []byt
return b
}
-// newGuestGoPeer is a Go peer admitted by the router with a node-role token;
+// newGuestGoPeer is a Go peer admitted by the routers with a node-role token;
// what it presents to providers is chosen per request.
-func newGuestGoPeer(t *testing.T, ctx context.Context, cpPriv ed25519.PrivateKey, routerAddr string) host.Host {
+func newGuestGoPeer(t *testing.T, ctx context.Context, cpPriv ed25519.PrivateKey, routerAddrs []string) host.Host {
t.Helper()
- return newAdmittedGoPeer(t, ctx, cpPriv, routerAddr)
+ return newAdmittedGoPeer(t, ctx, cpPriv, routerAddrs)
}
// tryMCPStream opens /sam/mcp/1.0.0 to target through addr and reports