Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
tests: migrate key rotation and node revocation tests from slow E2E Bats to fast Go integration tests
Antonio Ojead436a1d6fac8
diff --git a/.gitignore b/.gitignoreindex be801a20..686e81be 100644--- a/.gitignore+++ b/.gitignore@@ -34,6 +34,7 @@ go.work.sum#bin/tests/e2e/logs/+tests/integration/logs/tests/integration/scratch/__pycache__/.venv/diff --git a/Makefile b/Makefileindex 414b65b0..edb105aa 100644--- a/Makefile+++ b/Makefile@@ -116,7 +116,7 @@ test-python-e2e: build docker-buildbats --verbose-run tests/e2e/python_sdk_test.batse2e-test: build docker-build- bats --verbose-run $(if $(WHAT),--filter "$(WHAT)") tests/e2e/+ bats -j 10 --verbose-run $(if $(WHAT),--filter "$(WHAT)") tests/e2e/test-e2e: build docker-build@command -v bats >/dev/null 2>&1 || { \diff --git a/internal/storage/sql_store.go b/internal/storage/sql_store.goindex fdb903cd..a7b7cfd8 100644--- a/internal/storage/sql_store.go+++ b/internal/storage/sql_store.go@@ -181,7 +181,7 @@ func (s *SQLStore) GetCurrentKey(ctx context.Context) (ed25519.PrivateKey, ed255// GetAllValidKeys implements Store.func (s *SQLStore) GetAllValidKeys(ctx context.Context) ([]KeyPair, error) {query := s.rebind(`SELECT private_key, public_key, expiration FROM keyring WHERE expiration IS NULL OR expiration > ?`)- rows, err := s.db.QueryContext(ctx, query, time.Now().Unix())+ rows, err := s.db.QueryContext(ctx, query, time.Now().UnixMilli())if err != nil {return nil, err}@@ -196,7 +196,7 @@ func (s *SQLStore) GetAllValidKeys(ctx context.Context) ([]KeyPair, error) {}var expiration time.Timeif exp.Valid {- expiration = time.Unix(exp.Int64, 0)+ expiration = time.UnixMilli(exp.Int64)}keys = append(keys, KeyPair{Private: ed25519.PrivateKey(priv),@@ -220,19 +220,19 @@ func (s *SQLStore) RotateKeys(ctx context.Context, newPriv ed25519.PrivateKey, n// Set expiration on the current active keyupdateQuery := s.rebind(`UPDATE keyring SET expiration = ? WHERE expiration IS NULL`)- if _, err := tx.ExecContext(ctx, updateQuery, expireTime.Unix()); err != nil {+ if _, err := tx.ExecContext(ctx, updateQuery, expireTime.UnixMilli()); err != nil {return err}// Insert the new keyinsertQuery := s.rebind(`INSERT INTO keyring (private_key, public_key, created_at) VALUES (?, ?, ?)`)- if _, err := tx.ExecContext(ctx, insertQuery, []byte(newPriv), []byte(newPub), now.Unix()); err != nil {+ if _, err := tx.ExecContext(ctx, insertQuery, []byte(newPriv), []byte(newPub), now.UnixMilli()); err != nil {return err}// Clean up expired keysdeleteQuery := s.rebind(`DELETE FROM keyring WHERE expiration <= ?`)- if _, err := tx.ExecContext(ctx, deleteQuery, now.Unix()); err != nil {+ if _, err := tx.ExecContext(ctx, deleteQuery, now.UnixMilli()); err != nil {return err}@@ -242,7 +242,7 @@ func (s *SQLStore) RotateKeys(ctx context.Context, newPriv ed25519.PrivateKey, n// SaveInitialKey implements Store.func (s *SQLStore) SaveInitialKey(ctx context.Context, priv ed25519.PrivateKey, pub ed25519.PublicKey) error {query := s.rebind(`INSERT INTO keyring (private_key, public_key, created_at) VALUES (?, ?, ?)`)- _, err := s.db.ExecContext(ctx, query, []byte(priv), []byte(pub), time.Now().Unix())+ _, err := s.db.ExecContext(ctx, query, []byte(priv), []byte(pub), time.Now().UnixMilli())return err}@@ -263,7 +263,7 @@ func (s *SQLStore) EnrollNode(ctx context.Context, peerID string, biscuit []byteDO UPDATE SET biscuit_token = excluded.biscuit_token, enrolled_at = excluded.enrolled_at, expires_at = excluded.expires_at`)}- _, err := s.db.ExecContext(ctx, query, peerID, biscuit, time.Now().Unix(), expiresAt.Unix())+ _, err := s.db.ExecContext(ctx, query, peerID, biscuit, time.Now().UnixMilli(), expiresAt.UnixMilli())return err}@@ -279,8 +279,8 @@ func (s *SQLStore) GetNode(ctx context.Context, peerID string) (*EnrolledNode, eif err != nil {return nil, err}- node.EnrolledAt = time.Unix(enrolledAtUnix, 0)- node.ExpiresAt = time.Unix(expiresAtUnix, 0)+ node.EnrolledAt = time.UnixMilli(enrolledAtUnix)+ node.ExpiresAt = time.UnixMilli(expiresAtUnix)return &node, nil}@@ -327,14 +327,14 @@ func (s *SQLStore) UpsertRouterLease(ctx context.Context, lease *RouterLease) erDO UPDATE SET multiaddresses = excluded.multiaddresses, last_lease_renewal = excluded.last_lease_renewal, expires_at = excluded.expires_at`)}- _, err = s.db.ExecContext(ctx, query, lease.PeerID, string(addrsBytes), lease.LastRenewal.Unix(), lease.ExpiresAt.Unix())+ _, err = s.db.ExecContext(ctx, query, lease.PeerID, string(addrsBytes), lease.LastRenewal.UnixMilli(), lease.ExpiresAt.UnixMilli())return err}// GetActiveRouters implements Store.func (s *SQLStore) GetActiveRouters(ctx context.Context) ([]RouterLease, error) {query := s.rebind(`SELECT peer_id, multiaddresses, last_lease_renewal, expires_at FROM routers WHERE expires_at > ?`)- rows, err := s.db.QueryContext(ctx, query, time.Now().Unix())+ rows, err := s.db.QueryContext(ctx, query, time.Now().UnixMilli())if err != nil {return nil, err}@@ -351,8 +351,8 @@ func (s *SQLStore) GetActiveRouters(ctx context.Context) ([]RouterLease, error)if err := json.Unmarshal([]byte(addrsStr), &l.Addresses); err != nil {return nil, err}- l.LastRenewal = time.Unix(lastRenewalUnix, 0)- l.ExpiresAt = time.Unix(expiresAtUnix, 0)+ l.LastRenewal = time.UnixMilli(lastRenewalUnix)+ l.ExpiresAt = time.UnixMilli(expiresAtUnix)leases = append(leases, l)}return leases, rows.Err()@@ -380,7 +380,7 @@ func (s *SQLStore) SavePolicy(ctx context.Context, policy *api.PolicyConfig) errDO UPDATE SET content = excluded.content, updated_at = excluded.updated_at`)}- _, err = s.db.ExecContext(ctx, query, string(data), time.Now().Unix())+ _, err = s.db.ExecContext(ctx, query, string(data), time.Now().UnixMilli())return err}diff --git a/tests/e2e/key_rotation_test.bats b/tests/e2e/key_rotation_test.batsdeleted file mode 100644index 72b3d43c..00000000--- a/tests/e2e/key_rotation_test.bats+++ /dev/null@@ -1,51 +0,0 @@-#!/usr/bin/env bats--load "lib/container_mesh.bash"--setup() {- mesh_setup_env-}--teardown() {- mesh_cleanup_env-}--@test "Key Rotation: Node receives rotation event and remains functional" {- run mesh_start_mock_oidc- echo "mock_oidc status: $status, output: $output"- [[ "$status" -eq 0 ]]-- # Start Hub with rotation enabled- local hub_name="${MESH_PREFIX}-hub"- local key- key="$(mesh_gen_hex32)"-- mesh_start_standalone_hub "${hub_name}" "5s" "2s"-- mesh_wait_for_log "${hub_name}" "Lease renewed successfully" 20-- local hub_peer_id- hub_peer_id=$(docker logs "${hub_name}" 2>&1 | grep -oE '12D3Koo[a-zA-Z0-9]+' | head -n 1)- echo "${hub_peer_id}" > "/tmp/${MESH_PREFIX}-hub-peer-id"-- # Start Node- mesh_start_node 1-- local node_name="${MESH_PREFIX}-node-1"- mesh_wait_for_log "${node_name}" "SAM Node Online" 20-- # Wait for rotation- sleep 10-- # Verify Node received rotation event- run mesh_wait_for_log "${node_name}" "Key rotation received" 10- if [[ "$status" -ne 0 ]]; then- echo "Node logs:"- docker logs "${node_name}"- fi- [[ "$status" -eq 0 ]]-- # Verify node is still running- run mesh_assert_container_running "${node_name}"- [[ "$status" -eq 0 ]]-}diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bashindex 4339cba8..2e91a924 100644--- a/tests/e2e/lib/container_mesh.bash+++ b/tests/e2e/lib/container_mesh.bash@@ -54,6 +54,16 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenfor c in "${MESH_CONTAINERS[@]}"; dodocker logs "${c}" > "tests/e2e/logs/${c}.log" 2>&1 || truedone+ local db_container=""+ for c in "${MESH_CONTAINERS[@]}"; do+ if [[ "${c}" == *"-db" ]]; then+ db_container="${c}"+ break+ fi+ done+ if [[ -n "${db_container}" ]]; then+ docker exec "${db_container}" pg_dump -U sam -d sam_mesh > "tests/e2e/logs/${db_container}.sql" 2>&1 || true+ fifilocal c@@ -375,96 +385,3 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenstate="$(docker inspect -f '{{.State.Running}}' "${name}" 2>/dev/null || true)"[[ "${state}" == "true" ]]}-- mesh_start_standalone_hub() {- local hub_name="$1"- local rotation_interval="${2:-0}"- local grace_period="${3:-0}"-- local policy_file="/tmp/${MESH_PREFIX}-policies.yaml"- cat <<EOF > "${policy_file}"-version: "v1alpha1"-bindings:- - members: ["group:routers", "user:system:serviceaccount:default:sam-router-sa"]- role: "router"- - members: ["system:authenticated"]- role: "admin"-roles:- admin:- allowed_services: ["*"]- allowed_targets: ["*"]- router:- allowed_services: ["*"]- allowed_targets: ["*"]-EOF-- # Create data volume for control plane- local cp_db_vol="${hub_name}-cp-data"- docker volume create "${cp_db_vol}" >/dev/null- CLEANUP_VOLUMES+=("${cp_db_vol}")-- # Start Control Plane- docker run -d \- --name "${hub_name}-cp" \- --network "${MESH_NETWORK}" \- --network-alias sam-control-plane \- $(mesh_get_add_hosts) \- -v "${policy_file}:/etc/sam/policies.yaml:ro" \- -v "${cp_db_vol}:/data" \- "sam-control-plane:local" \- --issuer "http://mock-oidc:18080" \- --allowed-audiences "sam-e2e,sam-hub-audience,sam-mesh-audience" \- --db-driver "sqlite" \- --db-dsn "/data/control-plane.db" \- --key-rotation-interval "${rotation_interval}" \- --key-grace-period "${grace_period}" \- --lease-duration "15s" \- --policy-file "/etc/sam/policies.yaml" >/dev/null-- MESH_CONTAINERS+=("${hub_name}-cp")-- # Get a mock token for the router- local router_token=""- local i- for ((i=0; i<15; i++)); do- router_token=$(docker run --rm --network "${MESH_NETWORK}" $(mesh_get_add_hosts) python:3.12 python3 -c "import urllib.request; import json; req = urllib.request.Request('http://mock-oidc:18080/token', data=b'client_id=router-client'); resp = urllib.request.urlopen(req); print(json.loads(resp.read().decode())['access_token'])" || true)- if [[ -n "${router_token}" && "${router_token}" != "null" ]]; then- break- fi- sleep 0.5- done- [[ -n "${router_token}" && "${router_token}" != "null" ]]-- # Write token to a temp path and mount it into the router- local token_dir- token_dir="/tmp/${MESH_PREFIX}-router-token"- mkdir -p "${token_dir}"- echo -n "${router_token}" > "${token_dir}/sa-token"-- # Create data volume for router- local router_data_vol="${hub_name}-router-data"- docker volume create "${router_data_vol}" >/dev/null- CLEANUP_VOLUMES+=("${router_data_vol}")-- # Start Router- docker run -d \- --name "${hub_name}" \- --network "${MESH_NETWORK}" \- --network-alias sam-hub \- $(mesh_get_add_hosts) \- -v "${token_dir}:/var/run/secrets/tokens:ro" \- -v "${router_data_vol}:/data" \- "sam-router:local" \- --control-plane "http://sam-control-plane:8080" \- --listen "/ip4/0.0.0.0/tcp/4002" \- --external-addr "/dns4/sam-hub/tcp/4002" \- --jwt-path "/var/run/secrets/tokens/sa-token" \- --keys-path "/data/router.key" \- --allow-loopback \- --lease-renew-interval 5s \- --keys-sync-interval 2s \- --log-level debug >/dev/null-- MESH_CONTAINERS+=("${hub_name}")- }-fidiff --git a/tests/e2e/revocation_test.bats b/tests/e2e/revocation_test.batsdeleted file mode 100644index af781c52..00000000--- a/tests/e2e/revocation_test.bats+++ /dev/null@@ -1,111 +0,0 @@-#!/usr/bin/env bats--load "lib/container_mesh.bash"--setup() {- mesh_setup_env-}--teardown() {- mesh_cleanup_env-}--@test "Revocation: Node disconnects from banned peer after receiving event" {- run mesh_start_mock_oidc- [[ "$status" -eq 0 ]]-- # Start Hub with a known key so we can sign events- local hub_name="${MESH_PREFIX}-hub"- local hub_key- hub_key="$(mesh_gen_hex32)"-- mesh_start_standalone_hub "${hub_name}"-- mesh_wait_for_log "${hub_name}" "Lease renewed successfully" 20-- local hub_peer_id- hub_peer_id=$(docker logs "${hub_name}" 2>&1 | grep -oE '12D3Koo[a-zA-Z0-9]+' | head -n 1)- echo "${hub_peer_id}" > "/tmp/${MESH_PREFIX}-hub-peer-id"-- # Start Node 1- echo "[$(date +%T)] Starting Node 1"- mesh_start_node 1 "--log-level debug"- local node1_name="${MESH_PREFIX}-node-1"- mesh_wait_for_log "${node1_name}" "SAM Node Online" 20- mesh_wait_for_mcp_ready 1 20-- local node1_peer_id- node1_peer_id=$(docker logs "${node1_name}" 2>&1 | grep "PeerID:" | head -n 1 | awk '{print $2}' | tr -d '\r')-- # Start Node 2- echo "[$(date +%T)] Starting Node 2"- mesh_start_node 2 "--log-level debug"- local node2_name="${MESH_PREFIX}-node-2"- mesh_wait_for_log "${node2_name}" "SAM Node Online" 20- mesh_wait_for_mcp_ready 2 20-- # Extract Node 2 Peer ID- local node2_peer_id- node2_peer_id=$(docker logs "${node2_name}" 2>&1 | grep "PeerID:" | head -n 1 | awk '{print $2}' | tr -d '\r')- [[ -n "${node2_peer_id}" ]]-- # Explicitly connect Node 1 to Node 2- echo "[$(date +%T)] Explicitly connecting Node 1 to Node 2"- local node2_addr="/dns4/${node2_name}/tcp/5002/p2p/${node2_peer_id}"- run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${node1_name}:8080/mcp" -tool "connect_peer" -args "{\"peer_addr\":\"${node2_addr}\"}"- [[ "$status" -eq 0 ]]-- # Verify Node 1 connects to Node 2- echo "[$(date +%T)] Waiting for connection"- run mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20- if [[ "$status" -ne 0 ]]; then- echo "Node 1 logs:"- docker logs "${node1_name}"- echo "Node 2 logs:"- docker logs "${node2_name}"- fi- [[ "$status" -eq 0 ]]-- # Publish ban event for Node 2- echo "[$(date +%T)] Publishing ban event"- run docker exec "${hub_name}-cp" /sam-control-plane admin ban --peer "${node2_peer_id}" --db-driver sqlite --db-dsn /data/control-plane.db-- echo "admin ban output: $output"- [[ "$status" -eq 0 ]]- if [[ "$output" != *"Successfully banned node"* ]]; then- echo "Control Plane logs:"- docker logs "${hub_name}-cp"- fi- [[ "$output" == *"Successfully banned node"* ]]-- # Verify Node 1 receives the ban event and logs it- run mesh_wait_for_log "${node1_name}" "Peer banned: ${node2_peer_id}" 20- if [[ "$status" -ne 0 ]]; then- echo "Node 1 logs:"- docker logs "${node1_name}"- fi- [[ "$status" -eq 0 ]]-- # Verify Node 1 disconnects from Node 2- echo "[$(date +%T)] Waiting for disconnection"- run mesh_wait_for_peer_disconnection 1 "${node2_peer_id}" 20- [[ "$status" -eq 0 ]]-- # Allow connection state to settle in libp2p swarm- sleep 2-- # Verify Node 1 cannot reconnect to Node 2- echo "[$(date +%T)] Attempting to reconnect (should fail)"- local node2_addr="/dns4/${node2_name}/tcp/5002/p2p/${node2_peer_id}"- run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${node1_name}:8080/mcp" -tool "connect_peer" -args "{\"peer_addr\":\"${node2_addr}\"}"- echo "Reconnect output: $output"-- local info_output- info_output="$(docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${node1_name}:8080/mcp" -tool "get_mesh_info" 2>/dev/null)"- echo "After reconnect mesh info: ${info_output}"- local connected- connected="$(echo "${info_output}" | jq -r --arg peer "${node2_peer_id}" '.connected_peers | index($peer) != null')"- echo "Connected after reconnect: ${connected}"; echo "NODE 1 LOGS:"; docker logs "${MESH_PREFIX}-node-1"-- [[ "$output" == *"gater disallows connection"* ]]-}diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex 7737a160..5ace784a 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -637,3 +637,21 @@ func writePolicyWithRouter(t *testing.T, path string, yamlContent string) {t.Fatal(err)}}++func waitForNodeOnline(t *testing.T, logPath string) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ for {+ data, err := os.ReadFile(logPath)+ if err == nil && strings.Contains(string(data), "SAM Node Online") {+ return+ }+ select {+ case <-ctx.Done():+ t.Fatalf("timed out waiting for node to go online")+ case <-time.After(100 * time.Millisecond):+ }+ }+}diff --git a/tests/integration/revocation_test.go b/tests/integration/revocation_test.gonew file mode 100644index 00000000..64f354b3--- /dev/null+++ b/tests/integration/revocation_test.go@@ -0,0 +1,360 @@+// 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"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "strings"+ "testing"+ "time"++ "github.com/google/sam/api"+ "github.com/google/sam/internal/storage"+ "github.com/libp2p/go-libp2p"+ pubsub "github.com/libp2p/go-libp2p-pubsub"+ "github.com/libp2p/go-libp2p/core/peer"+ "github.com/multiformats/go-multiaddr"+ "google.golang.org/protobuf/proto"+)++func TestNodeRevocationIntegration(t *testing.T) {+ cpBin := buildBinary(t, "./cmd/sam-control-plane")+ routerBin := buildBinary(t, "./cmd/sam-router")+ nodeBin := buildBinary(t, "./cmd/sam-node")+ clientBin := buildBinary(t, "./cmd/mcp-client")++ tmpDir := t.TempDir()++ // 1. Create a mock policy file granting "router" role+ policyFile := filepath.Join(tmpDir, "policies.yaml")+ policyContent := `version: "v1alpha1"+bindings:+ - members: ["user:mock-user"]+ role: admin+roles:+ admin:+ allowed_services: ["*"]+ allowed_targets: ["*"]+`+ writePolicyWithRouter(t, policyFile, policyContent)++ // Start Mock OIDC Server+ oidcURL, mintToken := startCustomMockOIDC(t)++ cpPort := getFreePort(t)+ routerPort := getFreePort(t)++ // 2. Start Control Plane (PostgreSQL is used in GKE/Kind, but SQLite is completely fine here for in-process integration test speed)+ cpCmd := exec.Command(cpBin,+ "--bind-address", fmt.Sprintf("127.0.0.1:%d", cpPort),+ "--policy-file", policyFile,+ "--db-dsn", filepath.Join(tmpDir, "cp-keys.db"),+ "--issuer", oidcURL,+ "--insecure-skip-tls-verify",+ )+ cpCmd.Stdout = os.Stdout+ cpCmd.Stderr = os.Stderr+ if err := cpCmd.Start(); err != nil {+ t.Fatalf("failed to start control plane: %v", err)+ }+ defer func() {+ _ = cpCmd.Process.Kill()+ _ = cpCmd.Wait()+ }()++ waitForControlPlane(t, cpPort)++ // 3. Start Router+ routerJWT := mintToken(map[string]interface{}{+ "sub": "router-integration-1",+ "groups": []string{"routers"},+ })++ routerCmd := exec.Command(routerBin,+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ "--listen", fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", routerPort),+ "--keys-path", filepath.Join(tmpDir, "router-keys.db"),+ "--allow-loopback",+ "--oidc-token", routerJWT,+ "--lease-renew-interval", "2s",+ "--keys-sync-interval", "1s",+ )+ routerCmd.Stdout = os.Stdout+ routerCmd.Stderr = os.Stderr+ if err := routerCmd.Start(); err != nil {+ t.Fatalf("failed to start router: %v", err)+ }+ defer func() {+ _ = routerCmd.Process.Kill()+ _ = routerCmd.Wait()+ }()++ fetchPeerID(t, cpPort)++ // 4. Start Node 1+ node1ApiPort := getFreePort(t)+ node1Home := filepath.Join(tmpDir, "node1_home")+ _ = os.MkdirAll(node1Home, 0755)++ logDir := filepath.Join(repoRoot(t), "tests/integration/logs")+ _ = os.MkdirAll(logDir, 0755)++ node1LogPath := filepath.Join(logDir, "node1.log")+ node1LogFile, _ := os.Create(node1LogPath)+ defer func() { _ = node1LogFile.Close() }()++ node1Cmd := exec.Command(nodeBin, "run",+ "--hub", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ "--jwt", mintToken(map[string]interface{}{"sub": "mock-user"}),+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--allow-loopback",+ "--bind-addr", fmt.Sprintf("127.0.0.1:%d", node1ApiPort),+ "--api-token", "node1-token",+ "--log-level", "debug",+ )+ node1Cmd.Env = append(os.Environ(), "HOME="+node1Home, "XDG_CONFIG_HOME="+filepath.Join(node1Home, ".config"))+ node1Cmd.Stdout = node1LogFile+ node1Cmd.Stderr = node1LogFile+ if err := node1Cmd.Start(); err != nil {+ t.Fatalf("failed to start node 1: %v", err)+ }+ defer func() {+ _ = node1Cmd.Process.Kill()+ _ = node1Cmd.Wait()+ }()++ // 5. Start Node 2+ node2ApiPort := getFreePort(t)+ node2Home := filepath.Join(tmpDir, "node2_home")+ _ = os.MkdirAll(node2Home, 0755)++ node2LogPath := filepath.Join(logDir, "node2.log")+ node2LogFile, _ := os.Create(node2LogPath)+ defer func() { _ = node2LogFile.Close() }()++ node2Cmd := exec.Command(nodeBin, "run",+ "--hub", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ "--jwt", mintToken(map[string]interface{}{"sub": "mock-user"}),+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--allow-loopback",+ "--bind-addr", fmt.Sprintf("127.0.0.1:%d", node2ApiPort),+ "--api-token", "node2-token",+ "--log-level", "debug",+ )+ node2Cmd.Env = append(os.Environ(), "HOME="+node2Home, "XDG_CONFIG_HOME="+filepath.Join(node2Home, ".config"))+ node2Cmd.Stdout = node2LogFile+ node2Cmd.Stderr = node2LogFile+ if err := node2Cmd.Start(); err != nil {+ t.Fatalf("failed to start node 2: %v", err)+ }+ defer func() {+ _ = node2Cmd.Process.Kill()+ _ = node2Cmd.Wait()+ }()++ // Wait for nodes to go online actively+ waitForNodeOnline(t, node1LogPath)+ waitForNodeOnline(t, node2LogPath)++ // Extract Node 2's PeerID and Address from its log+ node2LogData, _ := os.ReadFile(node2LogPath)+ rePeerID := regexp.MustCompile(`PeerID: (12D3Koo[a-zA-Z0-9]+)`)+ matches := rePeerID.FindStringSubmatch(string(node2LogData))+ if len(matches) < 2 {+ t.Fatalf("failed to find Node 2 peer ID in logs:\n%s", string(node2LogData))+ }+ node2PeerID := matches[1]++ reAddr := regexp.MustCompile(`Listening on: \[(/ip4/127.0.0.1/tcp/\d+)`)+ matchesAddr := reAddr.FindStringSubmatch(string(node2LogData))+ if len(matchesAddr) < 2 {+ t.Fatalf("failed to find Node 2 listening TCP address in logs:\n%s", string(node2LogData))+ }+ node2TCPAddr := matchesAddr[1]++ // 6. Request Node 1 to connect to Node 2+ connectArgs := fmt.Sprintf(`{"peer_addr":"%s/p2p/%s"}`, node2TCPAddr, node2PeerID)+ stdout, stderr, err := runCommand(t, repoRoot(t), 5*time.Second, nil, "",+ clientBin,+ "-url", fmt.Sprintf("http://127.0.0.1:%d/mcp", node1ApiPort),+ "-token", "node1-token",+ "-tool", "connect_peer",+ "-args", connectArgs,+ )+ if err != nil {+ t.Fatalf("connect_peer failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)+ }++ // Verify Node 1 is connected to Node 2+ time.Sleep(1 * time.Second)+ stdout, stderr, err = runCommand(t, repoRoot(t), 5*time.Second, nil, "",+ clientBin,+ "-url", fmt.Sprintf("http://127.0.0.1:%d/mcp", node1ApiPort),+ "-token", "node1-token",+ "-tool", "get_mesh_info",+ "-args", "{}",+ )+ if err != nil {+ t.Fatalf("get_mesh_info failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)+ }+ if !strings.Contains(stdout, node2PeerID) {+ t.Fatalf("Node 1 is not connected to Node 2. peers: %s", stdout)+ }++ // 7. Ban Node 2 using CP admin CLI tool+ banCmd := exec.Command(cpBin, "admin", "ban",+ "--peer", node2PeerID,+ "--db-dsn", filepath.Join(tmpDir, "cp-keys.db"),+ )+ banCmd.Stdout = os.Stdout+ banCmd.Stderr = os.Stderr+ if err := banCmd.Run(); err != nil {+ t.Fatalf("failed to ban node via admin CLI: %v", err)+ }++ // Fetch current signing private key from DB+ store, err := storage.NewSQLStore("sqlite", filepath.Join(tmpDir, "cp-keys.db"))+ if err != nil {+ t.Fatalf("failed to open cp database: %v", err)+ }+ validKeys, err := store.GetAllValidKeys(context.Background())+ _ = store.Close()+ if err != nil {+ t.Fatalf("failed to get valid keys: %v", err)+ }+ var cpPrivKey ed25519.PrivateKey+ for _, k := range validKeys {+ if len(k.Private) == ed25519.PrivateKeySize {+ cpPrivKey = k.Private+ break+ }+ }+ if cpPrivKey == nil {+ t.Fatal("no valid CP signing private key found in DB")+ }++ // Create and sign MeshEvent_BANNED+ event := &api.MeshEvent{+ Type: api.MeshEvent_BANNED,+ PeerId: node2PeerID,+ Timestamp: time.Now().UnixMilli(),+ }+ eventData, err := proto.Marshal(event)+ if err != nil {+ t.Fatalf("failed to marshal event: %v", err)+ }+ event.Signature = ed25519.Sign(cpPrivKey, eventData)++ // Extract Node 1's PeerID and Address from its log+ node1LogData, _ := os.ReadFile(node1LogPath)+ matches1 := rePeerID.FindStringSubmatch(string(node1LogData))+ if len(matches1) < 2 {+ t.Fatalf("failed to find Node 1 peer ID in logs:\n%s", string(node1LogData))+ }+ node1PeerID := matches1[1]++ matchesAddr1 := reAddr.FindStringSubmatch(string(node1LogData))+ if len(matchesAddr1) < 2 {+ t.Fatalf("failed to find Node 1 listening TCP address in logs:\n%s", string(node1LogData))+ }+ node1TCPAddr := matchesAddr1[1]++ // Publish Gossip event directly to Node 1+ node1AddrStr := fmt.Sprintf("%s/p2p/%s", node1TCPAddr, node1PeerID)+ publishGossipEvent(t, node1AddrStr, event)++ // 8. Wait for revocation event to propagate and Node 1 to disconnect Node 2 actively+ waitForNodeDisconnection(t, clientBin, node1ApiPort, node2PeerID)+}++func publishGossipEvent(t *testing.T, routerAddrStr string, event *api.MeshEvent) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))+ if err != nil {+ t.Fatalf("failed to create libp2p host: %v", err)+ }+ defer func() { _ = h.Close() }()++ ps, err := pubsub.NewGossipSub(ctx, h)+ if err != nil {+ t.Fatalf("failed to create gossipsub: %v", err)+ }++ topic, err := ps.Join(api.GossipEvents)+ if err != nil {+ t.Fatalf("failed to join topic: %v", err)+ }+ defer func() { _ = topic.Close() }()++ targetAddr, err := multiaddr.NewMultiaddr(routerAddrStr)+ if err != nil {+ t.Fatalf("failed to parse router addr: %v", err)+ }+ targetInfo, err := peer.AddrInfoFromP2pAddr(targetAddr)+ if err != nil {+ t.Fatalf("failed to get AddrInfo: %v", err)+ }++ if err := h.Connect(ctx, *targetInfo); err != nil {+ t.Fatalf("failed to connect to router: %v", err)+ }++ // Wait for connection to settle in mesh+ time.Sleep(3 * time.Second)++ data, err := proto.Marshal(event)+ if err != nil {+ t.Fatalf("failed to marshal event: %v", err)+ }++ if err := topic.Publish(ctx, data); err != nil {+ t.Fatalf("failed to publish event: %v", err)+ }+}++func waitForNodeDisconnection(t *testing.T, clientBin string, node1ApiPort int, node2PeerID string) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ for {+ stdout, _, err := runCommand(t, repoRoot(t), 2*time.Second, nil, "",+ clientBin,+ "-url", fmt.Sprintf("http://127.0.0.1:%d/mcp", node1ApiPort),+ "-token", "node1-token",+ "-tool", "get_mesh_info",+ "-args", "{}",+ )+ if err == nil && !strings.Contains(stdout, node2PeerID) {+ return+ }+ select {+ case <-ctx.Done():+ t.Fatalf("timed out waiting for Node 1 to disconnect Node 2")+ case <-time.After(200 * time.Millisecond):+ }+ }+}diff --git a/tests/integration/rotation_test.go b/tests/integration/rotation_test.gonew file mode 100644index 00000000..0147ec64--- /dev/null+++ b/tests/integration/rotation_test.go@@ -0,0 +1,231 @@+// 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 (+ "bytes"+ "context"+ "fmt"+ "io"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/google/sam/api"+ "google.golang.org/protobuf/proto"+)++func TestKeyRotationIntegration(t *testing.T) {+ cpBin := buildBinary(t, "./cmd/sam-control-plane")+ routerBin := buildBinary(t, "./cmd/sam-router")+ nodeBin := buildBinary(t, "./cmd/sam-node")++ tmpDir := t.TempDir()++ // 1. Create a mock policy file+ policyFile := filepath.Join(tmpDir, "policies.yaml")+ policyContent := `version: "v1alpha1"+bindings:+ - members: ["user:mock-user"]+ role: admin+roles:+ admin:+ allowed_services: ["*"]+ allowed_targets: ["*"]+`+ writePolicyWithRouter(t, policyFile, policyContent)++ // Start Mock OIDC Server+ oidcURL, mintToken := startCustomMockOIDC(t)++ cpPort := getFreePort(t)+ routerPort := getFreePort(t)++ // 2. Start Control Plane with aggressive key rotation+ cpCmd := exec.Command(cpBin,+ "--bind-address", fmt.Sprintf("127.0.0.1:%d", cpPort),+ "--policy-file", policyFile,+ "--db-dsn", filepath.Join(tmpDir, "cp-keys.db"),+ "--issuer", oidcURL,+ "--key-rotation-interval", "4s",+ "--key-grace-period", "2s",+ "--insecure-skip-tls-verify",+ )+ cpCmd.Stdout = os.Stdout+ cpCmd.Stderr = os.Stderr+ if err := cpCmd.Start(); err != nil {+ t.Fatalf("failed to start control plane: %v", err)+ }+ defer func() {+ _ = cpCmd.Process.Kill()+ _ = cpCmd.Wait()+ }()++ waitForControlPlane(t, cpPort)++ // 3. Start Router with aggressive key sync interval+ routerJWT := mintToken(map[string]interface{}{+ "sub": "router-integration-1",+ "groups": []string{"routers"},+ })++ routerCmd := exec.Command(routerBin,+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ "--listen", fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", routerPort),+ "--keys-path", filepath.Join(tmpDir, "router-keys.db"),+ "--allow-loopback",+ "--oidc-token", routerJWT,+ "--lease-renew-interval", "2s",+ "--keys-sync-interval", "1s",+ )+ routerCmd.Stdout = os.Stdout+ routerCmd.Stderr = os.Stderr+ if err := routerCmd.Start(); err != nil {+ t.Fatalf("failed to start router: %v", err)+ }+ defer func() {+ _ = routerCmd.Process.Kill()+ _ = routerCmd.Wait()+ }()++ fetchPeerID(t, cpPort)++ // 4. Start Node+ nodeJWT := mintToken(map[string]interface{}{+ "sub": "mock-user",+ })+ nodeApiPort := getFreePort(t)+ nodeHome := t.TempDir()++ nodeEnv := append(os.Environ(),+ "HOME="+nodeHome,+ "XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config"),+ )++ nodeLogPath := filepath.Join(tmpDir, "node.log")+ nodeLogFile, _ := os.Create(nodeLogPath)+ defer func() { _ = nodeLogFile.Close() }()++ nodeCmd := exec.Command(nodeBin, "run",+ "--hub", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ "--jwt", nodeJWT,+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--allow-loopback",+ "--bind-addr", fmt.Sprintf("127.0.0.1:%d", nodeApiPort),+ "--api-token", "dummy-token",+ "--log-level", "debug",+ )+ nodeCmd.Env = nodeEnv+ nodeCmd.Stdout = nodeLogFile+ nodeCmd.Stderr = nodeLogFile+ if err := nodeCmd.Start(); err != nil {+ t.Fatalf("failed to start node: %v", err)+ }+ defer func() {+ _ = nodeCmd.Process.Kill()+ _ = nodeCmd.Wait()+ }()++ // Wait for Node to be online actively+ waitForNodeOnline(t, nodeLogPath)++ // Get initial keys+ initialKeys := fetchPublicKeys(t, cpPort)++ // Wait for key rotation to happen actively+ waitForKeyRotation(t, cpPort, initialKeys)++ // 6. Verify Node is still active and can communicate (it should renew successfully and remain online)+ if nodeCmd.ProcessState != nil && nodeCmd.ProcessState.Exited() {+ t.Fatalf("node process exited unexpectedly")+ }++ // Double check by looking at the node's API or verifying it doesn't crash+ clientBin := buildBinary(t, "./cmd/mcp-client")+ stdout, stderr, err := runCommand(t, repoRoot(t), 5*time.Second, nil, "",+ clientBin,+ "-url", fmt.Sprintf("http://127.0.0.1:%d/mcp", nodeApiPort),+ "-token", "dummy-token",+ "-tool", "get_mesh_info",+ "-args", "{}",+ )+ if err != nil {+ t.Fatalf("failed to query node: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)+ }+ if !strings.Contains(stdout, "dht_size") {+ t.Fatalf("unexpected node response: %s", stdout)+ }+}++func fetchPublicKeys(t *testing.T, cpPort int) [][]byte {+ t.Helper()+ client := &http.Client{Timeout: 1 * time.Second}+ resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/keys", cpPort))+ if err != nil {+ t.Fatalf("failed to get initial keys: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ t.Fatalf("failed to read keys body: %v", err)+ }+ var keysResp api.KeysResponse+ if err := proto.Unmarshal(body, &keysResp); err != nil {+ t.Fatalf("failed to unmarshal KeysResponse: %v", err)+ }+ return keysResp.PublicKeys+}++func waitForKeyRotation(t *testing.T, cpPort int, initialKeys [][]byte) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ client := &http.Client{Timeout: 1 * time.Second}+ for {+ resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/keys", cpPort))+ if err == nil {+ body, err := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ if err == nil {+ var keysResp api.KeysResponse+ if err := proto.Unmarshal(body, &keysResp); err == nil {+ for _, pk := range keysResp.PublicKeys {+ found := false+ for _, ik := range initialKeys {+ if bytes.Equal(pk, ik) {+ found = true+ break+ }+ }+ if !found {+ return // Found a new key!+ }+ }+ }+ }+ }+ select {+ case <-ctx.Done():+ t.Fatalf("timed out waiting for key rotation")+ case <-time.After(200 * time.Millisecond):+ }+ }+}