Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node, sdk: present a refreshed credential to the routers already connected
Antonio Ojea61f31c6a6e02
diff --git a/internal/node/enroll.go b/internal/node/enroll.goindex e98bd3b5..0210dac1 100644--- a/internal/node/enroll.go+++ b/internal/node/enroll.go@@ -79,6 +79,9 @@ func (n *SamNode) Enroll(ctx context.Context, controlPlaneURL string, jwt stringreturn err}+ // Routers already holding a session are shown the new credential;+ // connectToRouters skips them, as their sessions are live.+ n.readmitRouters(ctx)return n.connectToRouters(ctx, enrollResp.RouterAddresses)}diff --git a/internal/node/node.go b/internal/node/node.goindex 60927a25..d924de78 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -1028,36 +1028,16 @@ func (n *SamNode) ConnectAndAuthWithRouter(ctx context.Context, addr multiaddr.Mcontinue}- // Open auth stream- s, err := n.Host.NewStream(replicaCtx, addrInfo.ID, api.AuthProtocolID)- if err != nil {- cancel()- errs = append(errs, fmt.Errorf("failed to open auth stream to router %s: %w", resolved, err))- continue- }- _ = s.SetDeadline(time.Now().Add(5 * time.Second))-- success, err := n.performRouterAuthHandshake(s, biscuitBytes, addrInfo.ID)+ err = n.authenticateRouterSession(replicaCtx, addrInfo.ID, biscuitBytes)+ cancel()if err != nil {- _ = s.Reset()- cancel()- errs = append(errs, fmt.Errorf("handshake failed with router %s: %w", resolved, err))+ errs = append(errs, fmt.Errorf("router %s: %w", resolved, err))if errors.Is(err, ErrFatalAuth) {lastFatalErr = err}continue}- _ = s.Close()- cancel()-- if success {- n.mu.Lock()- n.authenticatedRouters[addrInfo.ID] = true- n.RouterPeerID = addrInfo.ID- n.mu.Unlock()- logger.Infof("[AuthN] Successfully authenticated with router via libp2p: %s", addrInfo.ID)- connected = true- }+ connected = true}if connected {@@ -1073,6 +1053,57 @@ func (n *SamNode) ConnectAndAuthWithRouter(ctx context.Context, addr multiaddr.Mreturn fmt.Errorf("failed to authenticate with any router addresses: %w", errors.Join(errs...))}+// authenticateRouterSession runs the auth handshake with a router this host+// is connected to and records the session.+func (n *SamNode) authenticateRouterSession(ctx context.Context, router peer.ID, biscuitBytes []byte) error {+ s, err := n.Host.NewStream(ctx, router, api.AuthProtocolID)+ if err != nil {+ return fmt.Errorf("failed to open auth stream: %w", err)+ }+ _ = s.SetDeadline(time.Now().Add(5 * time.Second))++ if _, err := n.performRouterAuthHandshake(s, biscuitBytes, router); err != nil {+ _ = s.Reset()+ return fmt.Errorf("handshake failed: %w", err)+ }+ _ = s.Close()++ n.mu.Lock()+ n.authenticatedRouters[router] = true+ n.RouterPeerID = router+ n.mu.Unlock()+ logger.Infof("[AuthN] Successfully authenticated with router via libp2p: %s", router)+ return nil+}++// readmitRouters presents the current credential to every router this node+// holds an authenticated session with. A router admits a peer until the+// biscuit it was shown expires, whatever the connection does, so a refreshed+// credential must be shown on the live session or relay circuits to this+// node are refused once the old one lapses. A router that refuses is+// dropped from the authenticated set; the connection monitor then dials and+// handshakes afresh.+func (n *SamNode) readmitRouters(ctx context.Context) {+ if n.Host == nil {+ return+ }+ biscuitBytes := n.GetIdentity()+ if len(biscuitBytes) == 0 {+ return+ }+ for _, router := range n.authenticatedRouterIDs() {+ routerCtx, cancel := context.WithTimeout(ctx, n.config.RouterConnectTimeout)+ err := n.authenticateRouterSession(routerCtx, router, biscuitBytes)+ cancel()+ if err != nil {+ logger.Warnf("[AuthN] Router %s did not accept the refreshed credential; the connection monitor will re-handshake: %v", router, err)+ n.mu.Lock()+ delete(n.authenticatedRouters, router)+ n.mu.Unlock()+ }+ }+}+func (n *SamNode) performRouterAuthHandshake(s network.Stream, biscuitBytes []byte, expectedRouter peer.ID) (bool, error) {writer := msgio.NewVarintWriter(s)authFrame := &api.AuthFrame{Biscuit: biscuitBytes}@@ -1361,6 +1392,7 @@ func (n *SamNode) RefreshEnrollment(ctx context.Context) error {return fmt.Errorf("failed to save refreshed expiration: %w", err)}n.recordIdentityKeySet()+ n.readmitRouters(ctx)return nil}diff --git a/internal/node/router_auth_dedupe_test.go b/internal/node/router_auth_dedupe_test.goindex 13207618..434d38aa 100644--- a/internal/node/router_auth_dedupe_test.go+++ b/internal/node/router_auth_dedupe_test.go@@ -15,8 +15,12 @@package nodeimport (+ "bytes""context""crypto/ed25519"+ "io"+ "net/http"+ "net/http/httptest""sync/atomic""testing""time"@@ -30,15 +34,19 @@ import ("github.com/libp2p/go-msgio""github.com/multiformats/go-multiaddr""google.golang.org/protobuf/proto"+ "google.golang.org/protobuf/types/known/timestamppb")// fakeRouter is a libp2p host answering the SAM auth protocol. It counts-// handshakes so a test can tell a fresh session from a reused one.+// handshakes so a test can tell a fresh session from a reused one, and keeps+// the last biscuit it was shown.type fakeRouter struct {h host.HostrouterAddrs []multiaddr.Multiaddrhandshakes *atomic.Int32+ lastBiscuit *atomic.Pointer[[]byte]cpPub ed25519.PublicKey+ cpPriv ed25519.PrivateKeymint func(peerID, role string) []byte}@@ -77,6 +85,7 @@ func newFakeRouter(t *testing.T, listenAddrs ...string) *fakeRouter {routerBiscuit := mint(h.ID().String(), api.RoleRouter)var handshakes atomic.Int32+ var lastBiscuit atomic.Pointer[[]byte]h.SetStreamHandler(api.AuthProtocolID, func(s network.Stream) {defer func() { _ = s.Close() }()handshakes.Add(1)@@ -85,6 +94,11 @@ func newFakeRouter(t *testing.T, listenAddrs ...string) *fakeRouter {if err != nil {return}+ var frame api.AuthFrame+ if err := proto.Unmarshal(msg, &frame); err == nil {+ shown := append([]byte(nil), frame.Biscuit...)+ lastBiscuit.Store(&shown)+ }reader.ReleaseMsg(msg)data, _ := proto.Marshal(&api.AuthResponse{Success: true, Biscuit: routerBiscuit})_ = msgio.NewVarintWriter(s).WriteMsg(data)@@ -99,7 +113,7 @@ func newFakeRouter(t *testing.T, listenAddrs ...string) *fakeRouter {routerAddrs = append(routerAddrs, ma)}- return &fakeRouter{h: h, routerAddrs: routerAddrs, handshakes: &handshakes, cpPub: cpPub, mint: mint}+ return &fakeRouter{h: h, routerAddrs: routerAddrs, handshakes: &handshakes, lastBiscuit: &lastBiscuit, cpPub: cpPub, cpPriv: cpPriv, mint: mint}}// startNode brings up a node enrolled against this router and authenticated.@@ -257,3 +271,55 @@ func TestRouterDisconnectClearsAuthenticatedSession(t *testing.T) {t.Fatal("node does not report an authenticated router connection after re-auth")}}++// A router admits a peer until the biscuit it was shown expires, whatever+// the connection does; once that passes it refuses relay circuits to the+// peer. A credential refreshed with the control plane therefore has to be+// presented to every router on the live session, or the node turns+// unreachable an hour after it started while every connection looks fine.+func TestRefreshEnrollmentReadmitsConnectedRouters(t *testing.T) {+ r := newFakeRouter(t, "/ip4/127.0.0.1/tcp/0")++ var refreshed []byte+ mux := http.NewServeMux()+ mux.HandleFunc("/refresh", func(w http.ResponseWriter, req *http.Request) {+ var body api.TokenRefreshRequest+ data, _ := io.ReadAll(req.Body)+ if err := proto.Unmarshal(data, &body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ refreshed = r.mint(body.PeerId, api.RoleNode)+ out, _ := proto.Marshal(&api.TokenRefreshResponse{BiscuitToken: refreshed, ExpireTime: timestamppb.New(time.Now().Add(24 * time.Hour))})+ w.Header().Set("Content-Type", "application/x-protobuf")+ _, _ = w.Write(out)+ })+ srv := httptest.NewServer(mux)+ t.Cleanup(srv.Close)++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ node := r.startNode(t, ctx, r.routerAddrs)+ if err := node.Store.SaveControlPlaneURL(srv.URL); err != nil {+ t.Fatal(err)+ }+ if got := r.handshakes.Load(); got != 1 {+ t.Fatalf("handshakes after Start: %d, want 1", got)+ }++ if err := node.RefreshEnrollment(ctx); err != nil {+ t.Fatalf("RefreshEnrollment: %v", err)+ }++ if got := r.handshakes.Load(); got != 2 {+ t.Fatalf("handshakes after refresh: %d, want 2 (the refreshed credential was not presented)", got)+ }+ shown := r.lastBiscuit.Load()+ if shown == nil || !bytes.Equal(*shown, refreshed) {+ t.Fatal("router was not shown the refreshed biscuit")+ }+ if !node.IsConnected() {+ t.Fatal("node does not report an authenticated router connection after refresh")+ }+ waitForConnectedness(t, node, r.h.ID(), network.Connected)+}diff --git a/internal/router/router.go b/internal/router/router.goindex 0c552c6b..d7045fbc 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -169,6 +169,18 @@ func (r *Router) isPeerAuthenticated(p peer.ID) bool {}}+// AdmittedUntil reports when this router's admission of p lapses: the+// expiry of the biscuit p last presented on the auth handshake. A peer that+// never authenticated, or whose admission has lapsed, is not admitted.+func (r *Router) AdmittedUntil(p peer.ID) (until time.Time, admitted bool) {+ v, ok := r.authenticatedPeers.Load(p)+ if !ok {+ return time.Time{}, false+ }+ exp, isTime := v.(time.Time)+ return exp, isTime && time.Now().Before(exp)+}+// credential is the router's own mesh identity as the control plane issued// it. issuedUnder is the trusted key set at issuance: a trusted key outside// it is a rotation the biscuit predates, so the biscuit must be refresheddiff --git a/sdk/js/src/conformance-join.ts b/sdk/js/src/conformance-join.tsindex 3b3d8e3a..c4c1aee4 100644--- a/sdk/js/src/conformance-join.ts+++ b/sdk/js/src/conformance-join.ts@@ -189,7 +189,13 @@ async function handle(session: MeshSession, command: Command): Promise<unknown>async function main(): Promise<void> {const controlPlaneUrl = requireEnv("SAM_CONTROL_PLANE_URL");- const bootstrapTokenPath = requireEnv("SAM_BOOTSTRAP_TOKEN_PATH");+ // Enrollment is with a bootstrap token or a platform JWT, as the examples+ // offer; a JWT file is read again at every refresh.+ const bootstrapTokenPath = process.env.SAM_BOOTSTRAP_TOKEN_PATH;+ const jwtPath = process.env.SAM_JWT_PATH;+ if ((bootstrapTokenPath === undefined) === (jwtPath === undefined)) {+ throw new Error("exactly one of SAM_BOOTSTRAP_TOKEN_PATH or SAM_JWT_PATH is required");+ }const stateDir = requireEnv("SAM_SDK_STATE_DIR");const allowInsecure = process.env.SAM_INSECURE_CONTROL_PLANE === "1";const listenAddrs = (process.env.SAM_SDK_LISTEN_ADDRS ?? "").split(",").filter((a) => a !== "");@@ -209,6 +215,7 @@ async function main(): Promise<void> {allowInsecure,stateDir,bootstrapTokenPath,+ jwtPath,pollIntervalMs: 200,...(Object.keys(labels).length > 0 ? { labels } : {}),});diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.tsindex 31fb16ae..cf0033ab 100644--- a/sdk/js/src/session.ts+++ b/sdk/js/src/session.ts@@ -572,10 +572,44 @@ export class MeshSession {/** Refreshes now and reschedules; exposed so a caller can force it. */async refresh(): Promise<void> {- await this.mesh.refresh();+ await this.#refreshCredential();this.#scheduleRefresh();}+ /**+ * Trades the credential for a fresh one and shows it to every router this+ * member is connected to. A router admits a peer until the biscuit it was+ * shown expires, whatever the connection does; a refreshed credential it+ * never sees leaves it refusing relay circuits to this member once the+ * old one lapses, with every connection still open.+ */+ async #refreshCredential(): Promise<void> {+ await this.mesh.refresh();+ await this.#readmitRouters();+ }++ /**+ * Runs the handshake again on the open connection to each admitted+ * router; the router records the expiry of the credential it is shown.+ * A router without an open connection is left to keepRelay and the+ * connection:open listener, which handshake on the next connection.+ */+ async #readmitRouters(): Promise<void> {+ await Promise.all(+ this.routers.map(async (r) => {+ const conn = this.node.getConnections(peerIdFromString(r.peerId)).find((c) => c.status === "open");+ if (conn === undefined) {+ return;+ }+ try {+ await authenticateWithPeer(conn, this.mesh.authFrame(), this.mesh.credential.controlPlaneKeys);+ } catch {+ // The router keeps the admission it has until the old credential lapses.+ }+ }),+ );+ }+/*** Pulls keys, bans and router addresses from the control plane now, and* the mesh policy when accepting callers, then applies them: a newly@@ -592,6 +626,9 @@ export class MeshSession {async #syncOnce(): Promise<ControlPlaneSync> {const result = await this.mesh.syncControlPlane();+ if (result.refreshed) {+ await this.#readmitRouters();+ }if (result.bannedPeerIds !== undefined) {const { banned } = this.banned.reconcile(canonicalPeerIds(result.bannedPeerIds), result.fetchedAt);await Promise.all(banned.map((peerId) => this.#evict(peerId)));@@ -783,7 +820,7 @@ export class MeshSession {const dueMs = this.mesh.credential.expiration * 1000 - this.#refreshLeadMs - Date.now();const delay = Math.max(MIN_REFRESH_DELAY_MS, dueMs);this.#refreshTimer = setTimeout(() => {- this.mesh.refresh().then(+ this.#refreshCredential().then(() => this.#scheduleRefresh(),() => {if (!this.#closed) {diff --git a/sdk/python/src/agent_mesh/conformance_join.py b/sdk/python/src/agent_mesh/conformance_join.pyindex 2473f878..8e11f03e 100644--- a/sdk/python/src/agent_mesh/conformance_join.py+++ b/sdk/python/src/agent_mesh/conformance_join.py@@ -172,7 +172,12 @@ async def main() -> None:# stdout carries the protocol lines only; every log goes to stderr.logging.basicConfig(stream=sys.stderr, level=logging.WARNING, force=True)control_plane_url = _require_env("SAM_CONTROL_PLANE_URL")- bootstrap_token_path = _require_env("SAM_BOOTSTRAP_TOKEN_PATH")+ # Enrollment is with a bootstrap token or a platform JWT, as the examples+ # offer; a JWT file is read again at every refresh.+ bootstrap_token_path = os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH")+ jwt_path = os.environ.get("SAM_JWT_PATH")+ if (bootstrap_token_path is None) == (jwt_path is None):+ raise RuntimeError("exactly one of SAM_BOOTSTRAP_TOKEN_PATH or SAM_JWT_PATH is required")state_dir = _require_env("SAM_SDK_STATE_DIR")allow_insecure = os.environ.get("SAM_INSECURE_CONTROL_PLANE") == "1"listen = [a for a in os.environ.get("SAM_SDK_LISTEN_ADDRS", "").split(",") if a]@@ -190,6 +195,7 @@ async def main() -> None:mesh = AgentMesh.enroll(control_plane_url,bootstrap_token_path=bootstrap_token_path,+ jwt_path=jwt_path,state_dir=state_dir,allow_insecure=allow_insecure,labels=labels or None,diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.pyindex 14411a1a..e17158e7 100644--- a/sdk/python/src/agent_mesh/session.py+++ b/sdk/python/src/agent_mesh/session.py@@ -444,6 +444,8 @@ class MeshSession:are in the result."""async with self._sync_lock:result = await trio.to_thread.run_sync(self.mesh.sync_control_plane)+ if result.refreshed:+ await self._readmit_routers()if result.banned_peer_ids is not None:newly_banned, _ = self.banned.reconcile(canonical_peer_ids(result.banned_peer_ids), result.fetched_at)for peer in newly_banned:@@ -459,6 +461,43 @@ class MeshSession:"""Asks for a pull soon, after a random delay so a fleet told at once does not pull at once."""self._sync_trigger.set()+ async def refresh(self) -> None:+ """Trades the credential for a fresh one now and shows it to every+ router this member is connected to. A router admits a peer until the+ biscuit it was shown expires, whatever the connection does; a refreshed+ credential it never sees leaves it refusing relay circuits to this+ member once the old one lapses, with every connection still open."""+ # The control plane client is synchronous; keep the loop free.+ await trio.to_thread.run_sync(self.mesh.refresh)+ await self._readmit_routers()++ async def _readmit_routers(self) -> None:+ """Runs the handshake again on the open connection to each admitted+ router; the router records the expiry of the credential it is shown.+ A router without a connection is left to the reservation loop, which+ dials and authenticates it again."""+ connected = self.host.get_connected_peers()+ for i, r in enumerate(self.routers):+ peer_id = ID.from_base58(r.peer_id)+ if peer_id not in connected:+ continue+ try:+ credential = await _authenticate_router(self.host, self.mesh, peer_id)+ except Exception as err: # noqa: BLE001 - the router keeps the admission it has until the old credential lapses+ logger.warning("router %s did not accept the refreshed credential: %s", r.peer_id, err)+ continue+ self.routers[i] = replace(r, credential=credential)++ async def _refresh_loop(self, lead: float, retry: float) -> None:+ while True:+ due = self.mesh.credential.expiration - lead - time.time()+ await trio.sleep(max(MIN_REFRESH_DELAY, due))+ try:+ await self.refresh()+ except Exception as err: # noqa: BLE001 - a failed refresh is retried, the session stays up+ logger.warning("credential refresh failed, retrying in %.0fs: %s", retry, err)+ await trio.sleep(retry)+async def _evict(self, banned_peer: str) -> None:"""Drops a banned peer: its admission and its connections."""self.authenticated_peers.pop(banned_peer, None)@@ -615,18 +654,6 @@ class MeshSession:logger.warning("mesh policy sync failed: %s", err)-async def _refresh_loop(mesh: "AgentMesh", lead: float, retry: float) -> None:- while True:- due = mesh.credential.expiration - lead - time.time()- await trio.sleep(max(MIN_REFRESH_DELAY, due))- try:- # The control plane client is synchronous; keep the loop free.- await trio.to_thread.run_sync(mesh.refresh)- except Exception as err: # noqa: BLE001 - a failed refresh is retried, the session stays up- logger.warning("credential refresh failed, retrying in %.0fs: %s", retry, err)- await trio.sleep(retry)--def _single_cause(group: BaseException) -> BaseException:"""trio wraps a failure inside `host.run` in one ExceptionGroup per nursery.A join that failed for one reason should raise that reason."""@@ -696,7 +723,6 @@ async def join_mesh(await pubsub.wait_until_ready()admitted = await _admit(host, mesh, router_addrs, reserve)async with trio.open_nursery() as nursery:- nursery.start_soon(_refresh_loop, mesh, refresh_lead, refresh_retry)session = MeshSession(mesh=mesh,host=host,@@ -712,6 +738,7 @@ async def join_mesh(reservation_check_interval=reservation_check_interval,_nursery=nursery,)+ nursery.start_soon(session._refresh_loop, refresh_lead, refresh_retry) # noqa: SLF001nursery.start_soon(session._events_loop, pubsub) # noqa: SLF001nursery.start_soon(session._sync_loop) # noqa: SLF001nursery.start_soon(session._reservation_loop) # noqa: SLF001diff --git a/tests/integration/readmission_test.go b/tests/integration/readmission_test.gonew file mode 100644index 00000000..984ba273--- /dev/null+++ b/tests/integration/readmission_test.go@@ -0,0 +1,325 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package integration_test++import (+ "context"+ "crypto/ed25519"+ "fmt"+ "net"+ "os"+ "path/filepath"+ "strconv"+ "testing"+ "time"++ "github.com/google/sam/api"+ "github.com/google/sam/internal/controlplane"+ "github.com/google/sam/internal/identity"+ "github.com/google/sam/internal/router"+ "github.com/google/sam/internal/storage"+ "github.com/libp2p/go-libp2p/core/network"+ "github.com/libp2p/go-libp2p/core/peer"+ "github.com/multiformats/go-multiaddr"+)++// A router admits a peer until the biscuit it was shown on the auth+// handshake expires, whatever the connection does, and refuses relay+// circuits to it after that. A member whose platform token is short-lived+// (a projected service account token lasts an hour) gets a credential capped+// to it, refreshes that credential with the control plane well before it+// lapses, and must show the new one to every router it is connected to:+// otherwise the router keeps the first expiry and the member turns+// unreachable an hour after it started while every connection looks fine.+// Every member implementation is run against a real router: sam-node, whose+// own renewal loop refreshes, and each SDK, which refreshes right after+// joining since the credential is shorter than its refresh lead. Two things+// are checked for each: the router's admission of the member moves to the+// refreshed credential, and once the first credential has lapsed a peer+// still opens a relay circuit to the member through the router and gets the+// refreshed credential back on the handshake.+func TestMembersStayAdmittedAcrossCredentialRefresh(t *testing.T) {+ // Parallel subtests outlive this function's body.+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ t.Cleanup(cancel)+ mesh := startReadmissionMesh(t, ctx)+ nodeBin := buildBinary(t, "./cmd/sam-node")++ // How long the token every member joins with vouches for it: past each+ // runner's startup, short enough for sam-node's renewal loop, which+ // refreshes halfway through a credential this short, and for the test to+ // outlive it.+ const lifetime = 10 * time.Second++ t.Run("sam-node", func(t *testing.T) {+ t.Parallel()+ jwtFile := writeJWTFile(t, mesh.memberJWT("node-member", lifetime))+ home := t.TempDir()+ firstExpiry := time.Now().Add(lifetime)+ samNode := launchNode(t, nodeBin,+ append(os.Environ(), "HOME="+home, "XDG_CONFIG_HOME="+filepath.Join(home, ".config")),+ home, "run",+ "--control-plane", mesh.baseURL,+ "--jwt-path", jwtFile,+ "--allow-loopback",+ "--api-token-path", tokenPath(t, "node-token"),+ )+ samNode.waitForAPI(t)+ mesh.requireAdmittedUntil(t, samNode.peerID, firstExpiry)+ // The platform rotated the token file, as kubelet does, before the+ // node's renewal reads it.+ rewriteJWTFile(t, jwtFile, mesh.memberJWT("node-member", time.Hour))+ mesh.waitForReadmission(t, samNode.peerID, firstExpiry)+ mesh.requireReachableAcrossExpiry(t, ctx, samNode.peerID, firstExpiry)+ })++ for _, runner := range sdkMemberLaunchers {+ t.Run(runner.name, func(t *testing.T) {+ t.Parallel()+ cmd, skip := runner.cmd(mesh.root)+ if cmd == nil {+ t.Skip(skip)+ }+ jwtFile := writeJWTFile(t, mesh.memberJWT(runner.name+"-member", lifetime))+ firstExpiry := time.Now().Add(lifetime)+ m := launchSDKRunner(t, runner.name, cmd, mesh.root, mesh.baseURL, "SAM_JWT_PATH="+jwtFile, "SAM_SDK_LISTEN_ADDRS=/ip4/127.0.0.1/tcp/0")+ rewriteJWTFile(t, jwtFile, mesh.memberJWT(runner.name+"-member", time.Hour))+ peerID, err := peer.Decode(m.report.PeerID)+ if err != nil {+ t.Fatal(err)+ }+ mesh.requireAdmittedUntil(t, peerID, firstExpiry)+ mesh.waitForReadmission(t, peerID, firstExpiry)+ mesh.requireReachableAcrossExpiry(t, ctx, peerID, firstExpiry)+ })+ }+}++// readmissionMesh is a control plane and one router, both in this process,+// so the test can read the router's admission of each member.+type readmissionMesh struct {+ root string+ baseURL string+ router *router.Router+ routerAddr string+ cpPriv ed25519.PrivateKey+ mintToken func(map[string]interface{}) string+}++func startReadmissionMesh(t *testing.T, ctx context.Context) *readmissionMesh {+ t.Helper()+ oidcURL, mintToken := startCustomMockOIDC(t)+ tmp := t.TempDir()+ store, err := storage.NewSQLStore("sqlite", filepath.Join(tmp, "cp.db"))+ if err != nil {+ t.Fatalf("failed to create store: %v", err)+ }+ t.Cleanup(func() { _ = store.Close() })+ // Members hold the node role through group "users", the router its role+ // through group "routers"; what either may reach is not the subject here.+ roles := []*api.PolicyRole{+ {Name: api.RoleRouter, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}},+ {Name: api.RoleNode, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}},+ }+ bindings := []*api.PolicyBinding{+ {Role: api.RoleRouter, Members: []string{"group:routers"}},+ {Role: api.RoleNode, Members: []string{"group:users"}},+ }+ if err := store.SaveMeshPolicy(ctx, roles, bindings); err != nil {+ t.Fatalf("failed to save policy: %v", err)+ }+ cp, err := controlplane.NewServer(controlplane.Options{+ ListenAddr: "127.0.0.1:0",+ OIDCIssuer: oidcURL,+ AllowedAudiences: []string{"sam-mesh-audience"},+ LeaseDuration: 5 * time.Second,+ InsecureSkipTLSVerify: true,+ }, store)+ if err != nil {+ t.Fatalf("failed to create control plane: %v", err)+ }+ if err := cp.Start(); err != nil {+ t.Fatalf("failed to start control plane: %v", err)+ }+ t.Cleanup(func() { _ = cp.Close() })+ baseURL := "http://" + cp.Addr()+ _, portStr, _ := net.SplitHostPort(cp.Addr())+ cpPort, _ := strconv.Atoi(portStr)++ rtr, err := router.NewRouter(ctx, router.Options{+ ControlPlaneURL: baseURL,+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},+ KeysDBPath: filepath.Join(tmp, "router.key"),+ OIDCToken: mintToken(map[string]interface{}{"sub": "router", "groups": []string{"routers"}, "roles": []string{api.RoleRouter}}),+ AllowLoopback: true,+ KeysSyncInterval: 20 * time.Second,+ LeaseRenewInterval: 500 * time.Millisecond,+ BiscuitTimeout: time.Second,+ })+ if err != nil {+ t.Fatalf("failed to create router: %v", err)+ }+ if err := rtr.Start(); err != nil {+ t.Fatalf("failed to start router: %v", err)+ }+ t.Cleanup(func() { _ = rtr.Close() })+ routerAddr := ""+ for _, a := range rtr.Host.Addrs() {+ if _, err := a.ValueForProtocol(multiaddr.P_TCP); err == nil {+ routerAddr = a.String() + "/p2p/" + rtr.Host.ID().String()+ break+ }+ }+ if routerAddr == "" {+ t.Fatalf("router advertises no tcp address, got %v", rtr.Host.Addrs())+ }+ // Members learn the router from the control plane, which knows it from+ // its first lease.+ waitForActiveRouters(t, cpPort, 1, 10*time.Second)++ cpPriv, _, err := store.GetCurrentKey(ctx)+ if err != nil {+ t.Fatalf("failed to load control plane signing key: %v", err)+ }+ return &readmissionMesh{+ root: repoRoot(t),+ baseURL: baseURL,+ router: rtr,+ routerAddr: routerAddr,+ cpPriv: cpPriv,+ mintToken: mintToken,+ }+}++// memberJWT is a platform token for a member, vouching for it for lifetime;+// the control plane caps the credential it issues to that.+func (m *readmissionMesh) memberJWT(subject string, lifetime time.Duration) string {+ return m.mintToken(map[string]interface{}{+ "sub": subject,+ "groups": []string{"users"},+ "roles": []string{api.RoleNode},+ "exp": time.Now().Add(lifetime).Unix(),+ })+}++// requireAdmittedUntil checks the premise: the router admitted member on+// the credential it joined with, which expires no later than firstExpiry.+// Biscuit dates carry whole seconds.+func (m *readmissionMesh) requireAdmittedUntil(t *testing.T, member peer.ID, firstExpiry time.Time) {+ t.Helper()+ until, admitted := m.router.AdmittedUntil(member)+ if !admitted {+ t.Fatalf("router does not admit %s after it joined", member)+ }+ if until.After(firstExpiry.Add(time.Second)) {+ t.Fatalf("router admits %s until %s, past the %s expiry of the credential it joined with: the member refreshed before its first handshake, so this test proves nothing",+ member, until.Format(time.RFC3339), firstExpiry.Format(time.RFC3339))+ }+}++// waitForReadmission waits until the router's admission of member outlasts+// firstExpiry, the expiry of the credential the member joined with. A member+// that refreshed without showing the router keeps the first expiry. This is+// the router's own state, read directly, so a member that never re-presents+// is named within seconds rather than when the credential lapses.+func (m *readmissionMesh) waitForReadmission(t *testing.T, member peer.ID, firstExpiry time.Time) {+ t.Helper()+ deadline := time.Now().Add(15 * time.Second)+ for {+ until, admitted := m.router.AdmittedUntil(member)+ if admitted && until.After(firstExpiry.Add(time.Minute)) {+ t.Logf("router admits %s until %s, %s past the credential it joined with", member, until.Format(time.RFC3339), until.Sub(firstExpiry).Round(time.Second))+ return+ }+ if time.Now().After(deadline) {+ t.Fatalf("router still admits %s until %s (admitted=%v), the credential it was shown at join expired at %s: the refreshed credential was not presented",+ member, until.Format(time.RFC3339), admitted, firstExpiry.Format(time.RFC3339))+ }+ time.Sleep(100 * time.Millisecond)+ }+}++// requireReachableAcrossExpiry is the data plane's answer to the same+// question. Before firstExpiry a peer reaches member through the router, as+// it would with or without a refresh. Once firstExpiry has passed, a peer+// that was not connected before opens a relay circuit to member through the+// router, runs the auth handshake over it and is answered with a credential+// that outlives firstExpiry: the refreshed one. A router still holding the+// first expiry refuses that circuit with PERMISSION_DENIED.+func (m *readmissionMesh) requireReachableAcrossExpiry(t *testing.T, ctx context.Context, member peer.ID, firstExpiry time.Time) {+ t.Helper()+ // The member's reservation on the router is made shortly after it joins.+ var before time.Time+ var err error+ for {+ if before, err = m.handshakeThroughRelay(t, ctx, member); err == nil {+ break+ }+ if time.Now().After(firstExpiry.Add(-time.Second)) {+ t.Fatalf("no relay circuit to %s through the router before its first credential expired: %v", member, err)+ }+ time.Sleep(200 * time.Millisecond)+ }++ // Strictly after the expiry: the router compares against the biscuit's+ // whole-second date.+ time.Sleep(time.Until(firstExpiry.Add(time.Second)))+ after, err := m.handshakeThroughRelay(t, ctx, member)+ if err != nil {+ t.Fatalf("no relay circuit to %s through the router once the credential it joined with expired (it presented one valid until %s before): %v", member, before.Format(time.RFC3339), err)+ }+ if !after.After(firstExpiry) {+ t.Fatalf("%s answered the handshake with a credential expiring %s, not a refreshed one past %s", member, after.Format(time.RFC3339), firstExpiry.Format(time.RFC3339))+ }+ t.Logf("%s reached through the router after its first credential expired; it presents one valid until %s", member, after.Format(time.RFC3339))+}++// handshakeThroughRelay opens a relay circuit to member through the router+// from a freshly admitted peer, so no earlier connection is reused, and runs+// the auth handshake over it, the exchange every member answers. It returns+// the expiry of the credential member presented.+func (m *readmissionMesh) handshakeThroughRelay(t *testing.T, ctx context.Context, member peer.ID) (time.Time, error) {+ t.Helper()+ caller := newAdmittedGoPeer(t, ctx, m.cpPriv, []string{m.routerAddr})+ relayed := multiaddr.StringCast(m.routerAddr + "/p2p-circuit/p2p/" + member.String())+ dialCtx, cancel := context.WithTimeout(network.WithAllowLimitedConn(ctx, "test"), 10*time.Second)+ defer cancel()+ if err := caller.Connect(dialCtx, peer.AddrInfo{ID: member, Addrs: []multiaddr.Multiaddr{relayed}}); err != nil {+ return time.Time{}, err+ }+ presented := authHandshake(t, ctx, caller, member, goHostBiscuit(t, m.cpPriv, caller.ID()))+ return identity.VerifyBiscuitAndGetExpiry(presented, member, []ed25519.PublicKey{m.cpPriv.Public().(ed25519.PublicKey)}, 5*time.Second)+}++// writeJWTFile writes token where a member reads its platform token from.+func writeJWTFile(t *testing.T, token string) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), "jwt")+ rewriteJWTFile(t, path, token)+ return path+}++// rewriteJWTFile replaces the token at path in one step, as a platform+// rotating a projected token does, so a member never reads half a token.+func rewriteJWTFile(t *testing.T, path, token string) {+ t.Helper()+ tmp := fmt.Sprintf("%s.%d.tmp", path, time.Now().UnixNano())+ if err := os.WriteFile(tmp, []byte(token+"\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Rename(tmp, path); err != nil {+ t.Fatal(err)+ }+}diff --git a/tests/integration/sdk_mesh_test.go b/tests/integration/sdk_mesh_test.goindex 82703ce9..4d000ab5 100644--- a/tests/integration/sdk_mesh_test.go+++ b/tests/integration/sdk_mesh_test.go@@ -1103,12 +1103,20 @@ func launchSDKMember(t *testing.T, name string, cmd *exec.Cmd, root, baseURL, adif err := os.WriteFile(tokenPath, []byte(mintBootstrapToken(t, baseURL, adminToken)+"\n"), 0o600); err != nil {t.Fatalf("failed to write bootstrap token: %v", err)}+ return launchSDKRunner(t, name, cmd, root, baseURL, append([]string{+ "SAM_BOOTSTRAP_TOKEN_PATH=" + tokenPath,+ "SAM_SDK_LABELS=" + labelsEnv(sdkMeshLabels),+ "SAM_SDK_EGRESS_REQUIRE_LABELS=region=" + sdkMeshLabels["region"],+ }, env...)...)+}++// launchSDKRunner starts a conformance-join runner against baseURL with env+// naming how it enrolls (a later entry wins), and reads its join report.+func launchSDKRunner(t *testing.T, name string, cmd *exec.Cmd, root, baseURL string, env ...string) *sdkMember {+ t.Helper()cmd.Env = append(append(os.Environ(),"SAM_CONTROL_PLANE_URL="+baseURL,- "SAM_BOOTSTRAP_TOKEN_PATH="+tokenPath,"SAM_SDK_STATE_DIR="+filepath.Join(t.TempDir(), "state"),- "SAM_SDK_LABELS="+labelsEnv(sdkMeshLabels),- "SAM_SDK_EGRESS_REQUIRE_LABELS=region="+sdkMeshLabels["region"],), env...)cmd.Dir = rootm := &sdkMember{name: name, cmd: cmd, stderr: &bytes.Buffer{}}