Skip to content

Agent Mesh

tests: know a node's identity before it starts

Antonio Ojea887b6287e970
diff --git a/tests/integration/a2a_test.go b/tests/integration/a2a_test.go
index 04963c90..cca8933d 100644
--- a/tests/integration/a2a_test.go
+++ b/tests/integration/a2a_test.go
@@ -19,7 +19,6 @@ import (
"iter"
"net/http"
"net/http/httptest"
- "path/filepath"
"strings"
"sync/atomic"
"testing"
@@ -103,25 +102,23 @@ func TestA2ACUJ(t *testing.T) {
defer agent.Close()
t.Log("Starting Node A (provider, region=eu)...")
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, hubAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
"--config", writeNodeConfig(t, homeA, map[string]string{"region": "eu"}, svcDecl{Type: "a2a", Name: "echo-agent", TargetURL: agent.URL}),
)
t.Log("Starting Node B (consumer)...")
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, hubAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
)
- apiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- apiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
- waitForAPI(t, apiAddrA)
- waitForAPI(t, apiAddrB)
+ apiAddrA := nodeA.waitForAPI(t)
+ apiAddrB := nodeB.waitForAPI(t)
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
connectPeer(t, apiAddrB, addrA)
waitForDHTPeers(t, apiAddrA)
diff --git a/tests/integration/agent_ingress_test.go b/tests/integration/agent_ingress_test.go
index 26422587..e7f408b5 100644
--- a/tests/integration/agent_ingress_test.go
+++ b/tests/integration/agent_ingress_test.go
@@ -104,13 +104,13 @@ func TestAgentIngressCUJ(t *testing.T) {
t.Fatalf("writing node config: %v", err)
}
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, hubAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
)
// Node B hosts the agent, and is the one that advertises its service.
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, hubAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
@@ -118,12 +118,10 @@ func TestAgentIngressCUJ(t *testing.T) {
"--config", cfgPath,
)
- apiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- apiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
- waitForAPI(t, apiAddrA)
- waitForAPI(t, apiAddrB)
+ apiAddrA := nodeA.waitForAPI(t)
+ apiAddrB := nodeB.waitForAPI(t)
- addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))
+ addrB := nodeB.p2pAddr
peerB := extractPeerID(addrB)
connectPeer(t, apiAddrA, addrB)
waitForDHTPeers(t, apiAddrB)
diff --git a/tests/integration/agent_policy_test.go b/tests/integration/agent_policy_test.go
index 087486c4..30911555 100644
--- a/tests/integration/agent_policy_test.go
+++ b/tests/integration/agent_policy_test.go
@@ -83,25 +83,23 @@ services:
t.Cleanup(func() { _ = os.RemoveAll(sockDir) })
nodeSocket := filepath.Join(sockDir, "node.sock")
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, hubAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
"--config", configA,
)
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, hubAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
"--socket-path", nodeSocket,
)
- apiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- apiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
- waitForAPI(t, apiAddrA)
- waitForAPI(t, apiAddrB)
+ apiAddrA := nodeA.waitForAPI(t)
+ apiAddrB := nodeB.waitForAPI(t)
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
connectPeer(t, apiAddrB, addrA)
waitForDHTPeers(t, apiAddrA)
diff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.go
index de8e2110..7a656514 100644
--- a/tests/integration/catalog_test.go
+++ b/tests/integration/catalog_test.go
@@ -20,7 +20,6 @@ import (
"fmt"
"net/http"
"os"
- "os/exec"
"path/filepath"
"sort"
"strings"
@@ -87,62 +86,6 @@ func writeNodeConfig(t *testing.T, dir string, labels map[string]string, service
return p
}
-func startBackgroundNode(t *testing.T, nodeBin string, routerAddr string, homeDir string, args ...string) *exec.Cmd {
- t.Helper()
- env := append(os.Environ(),
- "HOME="+homeDir,
- "XDG_CONFIG_HOME="+filepath.Join(homeDir, ".config"),
- "SAM_API_TOKEN=test-token", // per-test overrides use --api-token-path, which wins
- )
- allArgs := append([]string{"run", "--control-plane", routerAddr, "--jwt", "test-jwt", "--bind-addr", "127.0.0.1:0", "--allow-loopback"}, args...)
- cmd := exec.Command(nodeBin, allArgs...)
- cmd.Env = env
-
- logFile, err := os.Create(filepath.Join(homeDir, "node.log"))
- if err != nil {
- t.Fatalf("failed to create log file: %v", err)
- }
- cmd.Stdout = logFile
- cmd.Stderr = logFile
-
- if err := cmd.Start(); err != nil {
- t.Fatalf("failed to start background node: %v", err)
- }
-
- t.Cleanup(func() {
- if err := cmd.Process.Kill(); err != nil {
- t.Logf("warning: failed to kill background node: %v", err)
- }
- if err := logFile.Close(); err != nil {
- t.Logf("warning: failed to close log file: %v", err)
- }
- })
-
- return cmd
-}
-
-func waitForMCPAddr(t *testing.T, logPath string) string {
- t.Helper()
- // Generous under CI load; polling returns as soon as the line appears.
- deadline := time.Now().Add(10 * time.Second)
- for time.Now().Before(deadline) {
- data, _ := os.ReadFile(logPath)
- lines := strings.Split(string(data), "\n")
- for _, line := range lines {
- if strings.Contains(line, "Starting MCP server on TCP address ") {
- parts := strings.Split(line, "Starting MCP server on TCP address ")
- if len(parts) > 1 {
- return strings.TrimSpace(parts[1])
- }
- }
- }
- time.Sleep(100 * time.Millisecond)
- }
- data, _ := os.ReadFile(logPath)
- t.Fatalf("timeout waiting for MCP addr in log: %s\n--- log contents ---\n%s", logPath, string(data))
- return ""
-}
-
func callMCP(t *testing.T, mcpAddr string, toolName string, params map[string]any) string {
t.Helper()
ctx := context.Background()
@@ -201,36 +144,6 @@ func (a *authRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
return a.rt.RoundTrip(clone)
}
-func waitForPeerInfoInLog(t *testing.T, logPath string) string {
- t.Helper()
- deadline := time.Now().Add(5 * time.Second)
- for time.Now().Before(deadline) {
- data, _ := os.ReadFile(logPath)
- lines := strings.Split(string(data), "\n")
- var peerID string
- var tcpAddr string
- for _, line := range lines {
- if strings.HasPrefix(line, "PeerID: ") {
- peerID = strings.TrimPrefix(line, "PeerID: ")
- }
- if strings.Contains(line, "Listening on: ") {
- parts := strings.Split(line, " ")
- for _, p := range parts {
- if strings.Contains(p, "/tcp/") {
- tcpAddr = strings.Trim(p, "[]")
- }
- }
- }
- }
- if peerID != "" && tcpAddr != "" {
- return tcpAddr + "/p2p/" + peerID
- }
- time.Sleep(100 * time.Millisecond)
- }
- t.Fatalf("timeout waiting for peer info in log: %s", logPath)
- return ""
-}
-
func TestCatalogRoutingAndFailover(t *testing.T) {
nodeBin := buildBinary(t, "./cmd/sam-node")
_, routerAddr := startMockRouter(t)
@@ -241,25 +154,25 @@ func TestCatalogRoutingAndFailover(t *testing.T) {
// Start Node A (Client)
t.Log("Starting Node A...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeA, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
+ nodeA := startBackgroundNode(t, nodeBin, routerAddr, homeA, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
t.Log("Node A started.")
- // Wait for Node A to start and get its MCP address
- mcpAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
+ mcpAddrA := nodeA.waitForAPI(t)
// Start Node B (Provider 1)
t.Log("Starting Node B...")
- cmdB := startBackgroundNode(t, nodeBin, routerAddr, homeB, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
+ nodeB := startBackgroundNode(t, nodeBin, routerAddr, homeB, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
t.Log("Node B started.")
// Start Node C (Provider 2)
t.Log("Starting Node C...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeC, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
+ nodeC := startBackgroundNode(t, nodeBin, routerAddr, homeC, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")
t.Log("Node C started.")
- // Wait for Node B and C to start and get their addresses
- addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))
- addrC := waitForPeerInfoInLog(t, filepath.Join(homeC, "node.log"))
+ nodeB.waitForAPI(t)
+ nodeC.waitForAPI(t)
+ addrB := nodeB.p2pAddr
+ addrC := nodeC.p2pAddr
// Force Node A to connect to Node B and Node C
connectPeer(t, mcpAddrA, addrB)
@@ -329,9 +242,7 @@ func TestCatalogRoutingAndFailover(t *testing.T) {
t.Logf("First call response: %s", respData)
// Now kill Node B and assert failover to Node C
- if err := cmdB.Process.Kill(); err != nil {
- t.Fatalf("failed to kill Node B: %v", err)
- }
+ nodeB.kill()
// Wait a bit for catalog update or failover to happen on next call
time.Sleep(500 * time.Millisecond)
diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.go
index ab29075b..71b51400 100644
--- a/tests/integration/datapath_test.go
+++ b/tests/integration/datapath_test.go
@@ -48,34 +48,27 @@ func TestIntegrationStdioDatapath(t *testing.T) {
// Start Node A
t.Log("Starting Node A...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, routerAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
"--config", cfgA,
)
// Start Node B
t.Log("Starting Node B...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, routerAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
)
- // Resolve actual addresses from logs
- actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
+ nodeA.waitForAPI(t)
+ actualApiAddrB := nodeB.waitForAPI(t)
- // Wait for nodes to start sidecar API
- waitForAPI(t, actualApiAddrA)
- waitForAPI(t, actualApiAddrB)
-
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
peerIDA := getPeerIDFromAddr(addrA)
// Connect Node B to Node A
@@ -177,36 +170,29 @@ func TestIntegrationHTTPDatapath(t *testing.T) {
// Start Node A
t.Log("Starting Node A...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, routerAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
"--config", cfgA,
)
// Start Node B
t.Log("Starting Node B...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, routerAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
)
- // Resolve actual addresses from logs
- actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
-
- // Wait for nodes to start sidecar API
- waitForAPI(t, actualApiAddrA)
- waitForAPI(t, actualApiAddrB)
+ nodeA.waitForAPI(t)
+ actualApiAddrB := nodeB.waitForAPI(t)
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
peerIDA := getPeerIDFromAddr(addrA)
- addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))
+ addrB := nodeB.p2pAddr
peerIDB := getPeerIDFromAddr(addrB)
// Connect Node B to Node A
diff --git a/tests/integration/debug_endpoints_test.go b/tests/integration/debug_endpoints_test.go
index bf80a9a0..40d7587c 100644
--- a/tests/integration/debug_endpoints_test.go
+++ b/tests/integration/debug_endpoints_test.go
@@ -113,34 +113,26 @@ roles: []
// Start Node A
t.Log("Starting Node A...")
- _ = startBackgroundNode(t, nodeBin, controlPlaneURL, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, controlPlaneURL, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
"--jwt", nodeJWT,
)
// Start Node B
t.Log("Starting Node B...")
- _ = startBackgroundNode(t, nodeBin, controlPlaneURL, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, controlPlaneURL, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
"--jwt", nodeJWT,
)
- // Resolve actual local API address from log
- actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
+ actualApiAddrA := nodeA.waitForAPI(t)
+ actualApiAddrB := nodeB.waitForAPI(t)
- // Wait for nodes to start sidecar API
- waitForAPI(t, actualApiAddrA)
- waitForAPI(t, actualApiAddrB)
-
- // Resolve Peer addresses
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
// Connect Node B to Node A directly; exercises POST /debug/connect-peer
connectPeer(t, actualApiAddrB, addrA)
diff --git a/tests/integration/identity_evidence_test.go b/tests/integration/identity_evidence_test.go
index 1b58b187..af0d22db 100644
--- a/tests/integration/identity_evidence_test.go
+++ b/tests/integration/identity_evidence_test.go
@@ -56,24 +56,22 @@ func TestIdentityEvidenceOperatorFlow(t *testing.T) {
t.Cleanup(func() { _ = os.RemoveAll(socketDir) })
ownerSocket := filepath.Join(socketDir, "owner.sock")
- _ = startBackgroundNode(t, nodeBin, controlPlaneURL, ownerHome,
+ owner := startBackgroundNode(t, nodeBin, controlPlaneURL, ownerHome,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
"--socket-path", ownerSocket,
)
- _ = startBackgroundNode(t, nodeBin, controlPlaneURL, providerHome,
+ provider := startBackgroundNode(t, nodeBin, controlPlaneURL, providerHome,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
)
- ownerAPI := waitForMCPAddr(t, filepath.Join(ownerHome, "node.log"))
- providerAPI := waitForMCPAddr(t, filepath.Join(providerHome, "node.log"))
- waitForAPI(t, ownerAPI)
- waitForAPI(t, providerAPI)
+ ownerAPI := owner.waitForAPI(t)
+ provider.waitForAPI(t)
- providerAddr := waitForPeerInfoInLog(t, filepath.Join(providerHome, "node.log"))
+ providerAddr := provider.p2pAddr
providerPeerID := getPeerIDFromAddr(providerAddr)
if providerPeerID == "" {
t.Fatalf("provider address %q has no PeerID", providerAddr)
diff --git a/tests/integration/local_policy_test.go b/tests/integration/local_policy_test.go
index 41fb680f..21cdd1c6 100644
--- a/tests/integration/local_policy_test.go
+++ b/tests/integration/local_policy_test.go
@@ -17,7 +17,6 @@ package integration_test
import (
"fmt"
"os"
- "os/exec"
"path/filepath"
"strings"
"testing"
@@ -69,40 +68,21 @@ attenuation:
homeB := filepath.Join(tmpDir, "nodeB")
apiTokenB := "tokenB"
- apiPortB := getFreePort(t)
- cmdB := exec.Command(nodeBin, "run",
+ nodeB := launchNode(t, nodeBin, os.Environ(), homeB, "run",
"--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),
"--data-dir", homeB,
- "--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),
"--api-token-path", tokenPath(t, apiTokenB),
"--jwt", mintToken(map[string]interface{}{
"sub": "nodeB-user",
"roles": []string{api.RoleNode},
}),
- "--listen", "/ip4/127.0.0.1/tcp/0",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--allow-loopback",
"--config", nodeBPolicyFile,
)
- if err := os.MkdirAll(homeB, 0755); err != nil {
- t.Fatal(err)
- }
- logFileB, err := os.Create(filepath.Join(homeB, "node.log"))
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = logFileB.Close() }()
- cmdB.Stdout = logFileB
- cmdB.Stderr = logFileB
- if err := cmdB.Start(); err != nil {
- t.Fatalf("Failed to start Node B: %v", err)
- }
- defer func() { _ = cmdB.Process.Kill(); _ = cmdB.Wait() }()
-
- actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
- waitForAPI(t, actualApiAddrB)
- addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))
+ nodeB.waitForAPI(t)
+ addrB := nodeB.p2pAddr
parts := strings.Split(addrB, "/p2p/")
if len(parts) != 2 {
@@ -113,38 +93,19 @@ attenuation:
// Node A Config (unprivileged user)
homeA := filepath.Join(tmpDir, "nodeA")
apiTokenA := "tokenA"
- apiPortA := getFreePort(t)
- cmdA := exec.Command(nodeBin, "run",
+ nodeA := launchNode(t, nodeBin, os.Environ(), homeA, "run",
"--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),
"--data-dir", homeA,
- "--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),
"--api-token-path", tokenPath(t, apiTokenA),
"--jwt", mintToken(map[string]interface{}{
"sub": "unprivileged-user",
"roles": []string{api.RoleNode},
}),
- "--listen", "/ip4/127.0.0.1/tcp/0",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--allow-loopback",
)
- if err := os.MkdirAll(homeA, 0755); err != nil {
- t.Fatal(err)
- }
- logFileA, err := os.Create(filepath.Join(homeA, "node.log"))
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = logFileA.Close() }()
- cmdA.Stdout = logFileA
- cmdA.Stderr = logFileA
- if err := cmdA.Start(); err != nil {
- t.Fatalf("Failed to start Node A: %v", err)
- }
- defer func() { _ = cmdA.Process.Kill(); _ = cmdA.Wait() }()
-
- actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- waitForAPI(t, actualApiAddrA)
+ actualApiAddrA := nodeA.waitForAPI(t)
// Make request from Node A to Node B
// Even though Node A has no control plane permissions, Node B's local policy "allow if true;" should permit it.
@@ -215,40 +176,21 @@ attenuation:
homeB := filepath.Join(tmpDir, "nodeB")
apiTokenB := "tokenB"
- apiPortB := getFreePort(t)
- cmdB := exec.Command(nodeBin, "run",
+ nodeB := launchNode(t, nodeBin, os.Environ(), homeB, "run",
"--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),
"--data-dir", homeB,
- "--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),
"--api-token-path", tokenPath(t, apiTokenB),
"--jwt", mintToken(map[string]interface{}{
"sub": "nodeB-user",
"roles": []string{api.RoleNode},
}),
- "--listen", "/ip4/127.0.0.1/tcp/0",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--allow-loopback",
"--config", nodeBPolicyFile,
)
- if err := os.MkdirAll(homeB, 0755); err != nil {
- t.Fatal(err)
- }
- logFileB, err := os.Create(filepath.Join(homeB, "node.log"))
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = logFileB.Close() }()
- cmdB.Stdout = logFileB
- cmdB.Stderr = logFileB
- if err := cmdB.Start(); err != nil {
- t.Fatalf("Failed to start Node B: %v", err)
- }
- defer func() { _ = cmdB.Process.Kill(); _ = cmdB.Wait() }()
-
- actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
- waitForAPI(t, actualApiAddrB)
- addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))
+ nodeB.waitForAPI(t)
+ addrB := nodeB.p2pAddr
parts := strings.Split(addrB, "/p2p/")
if len(parts) != 2 {
@@ -259,38 +201,19 @@ attenuation:
// Node A Config (Client)
homeA := filepath.Join(tmpDir, "nodeA")
apiTokenA := "tokenA"
- apiPortA := getFreePort(t)
- cmdA := exec.Command(nodeBin, "run",
+ nodeA := launchNode(t, nodeBin, os.Environ(), homeA, "run",
"--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),
"--data-dir", homeA,
- "--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),
"--api-token-path", tokenPath(t, apiTokenA),
"--jwt", mintToken(map[string]interface{}{
"sub": "client-user",
"roles": []string{api.RoleNode},
}),
- "--listen", "/ip4/127.0.0.1/tcp/0",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--allow-loopback",
)
- if err := os.MkdirAll(homeA, 0755); err != nil {
- t.Fatal(err)
- }
- logFileA, err := os.Create(filepath.Join(homeA, "node.log"))
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = logFileA.Close() }()
- cmdA.Stdout = logFileA
- cmdA.Stderr = logFileA
- if err := cmdA.Start(); err != nil {
- t.Fatalf("Failed to start Node A: %v", err)
- }
- defer func() { _ = cmdA.Process.Kill(); _ = cmdA.Wait() }()
-
- actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- waitForAPI(t, actualApiAddrA)
+ actualApiAddrA := nodeA.waitForAPI(t)
// Node A attempts to call Node B.
// Node A's token allows calling "*" but restricts the target to "group:admin-only".
diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.go
index d2fe2dff..75cf7ec4 100644
--- a/tests/integration/minimal_helpers_test.go
+++ b/tests/integration/minimal_helpers_test.go
@@ -682,24 +682,6 @@ func writePolicyWithRouter(t *testing.T, path string, yamlContent string) {
}
}
-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):
- }
- }
-}
-
// injectPolicyYAML posts a policy fixture through the same conversion the console
// performs: YAML for readability, protojson on the wire. Going through JSON keeps
// this helper free of any field list, so a new PolicyRole field needs no change
diff --git a/tests/integration/node_helpers_test.go b/tests/integration/node_helpers_test.go
new file mode 100644
index 00000000..c66c9622
--- /dev/null
+++ b/tests/integration/node_helpers_test.go
@@ -0,0 +1,259 @@
+// 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 (
+ "fmt"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/sam/internal/node"
+ "github.com/libp2p/go-libp2p/core/peer"
+)
+
+// A node under test is observed through what it does, never through what it
+// prints: the log is kept for the failure message only. Its identity and
+// addresses are known before it starts, because the test chooses the ports
+// and the node's key lives in its store, so nothing has to be read back out.
+
+// backgroundNode is a `sam-node run` started by a test.
+type backgroundNode struct {
+ cmd *exec.Cmd
+ apiAddr string // host:port the sidecar API listens on
+ token string // API token, "" for a node running the enrollment sidecar
+ dataDir string // the node's store
+ peerID peer.ID // derived from the key in dataDir before the node started
+ p2pAddr string // a TCP address the node listens on, with /p2p/<id>
+ logPath string
+ exited chan error
+}
+
+// launchNode starts nodeBin with args plus a --bind-addr and a --listen the
+// test chose. Both are appended so they win over (bind) or add to (listen)
+// what args carry. The node's key is generated in its store first, so its
+// peer ID is known up front. Output goes to logDir/node.log.
+func launchNode(t *testing.T, nodeBin string, env []string, logDir string, args ...string) *backgroundNode {
+ t.Helper()
+ if err := os.MkdirAll(logDir, 0o755); err != nil {
+ t.Fatalf("create log dir: %v", err)
+ }
+ logPath := filepath.Join(logDir, "node.log")
+ logFile, err := os.Create(logPath)
+ if err != nil {
+ t.Fatalf("create node log: %v", err)
+ }
+
+ dataDir := nodeDataDir(env, args)
+ peerID := ensureNodeKey(t, dataDir)
+ apiAddr := fmt.Sprintf("127.0.0.1:%d", getFreePort(t))
+ p2pPort := getFreePort(t)
+
+ fullArgs := append(append([]string{}, args...),
+ "--bind-addr", apiAddr,
+ "--listen", fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", p2pPort),
+ )
+ cmd := exec.Command(nodeBin, fullArgs...)
+ cmd.Dir = repoRoot(t)
+ cmd.Env = env
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+ if err := cmd.Start(); err != nil {
+ _ = logFile.Close()
+ t.Fatalf("start sam-node: %v", err)
+ }
+ n := &backgroundNode{
+ cmd: cmd,
+ apiAddr: apiAddr,
+ token: nodeToken(t, env, args),
+ dataDir: dataDir,
+ peerID: peerID,
+ p2pAddr: fmt.Sprintf("/ip4/127.0.0.1/tcp/%d/p2p/%s", p2pPort, peerID),
+ logPath: logPath,
+ exited: make(chan error, 1),
+ }
+ go func() {
+ n.exited <- cmd.Wait()
+ _ = logFile.Close()
+ }()
+ t.Cleanup(n.kill)
+ return n
+}
+
+// nodeDataDir resolves the store the node will open, the way the binary
+// does: --data-dir, else the user config dir under XDG_CONFIG_HOME or HOME.
+func nodeDataDir(env []string, args []string) string {
+ for i, a := range args {
+ if a == "--data-dir" && i+1 < len(args) {
+ return args[i+1]
+ }
+ }
+ var home, xdg string
+ for _, e := range env {
+ if v, ok := strings.CutPrefix(e, "XDG_CONFIG_HOME="); ok {
+ xdg = v
+ }
+ if v, ok := strings.CutPrefix(e, "HOME="); ok {
+ home = v
+ }
+ }
+ if xdg != "" {
+ return filepath.Join(xdg, "sam-mesh")
+ }
+ return filepath.Join(home, ".config", "sam-mesh")
+}
+
+// ensureNodeKey creates the node's key in dataDir if there is none, exactly
+// as the node itself would, and returns the peer ID it implies. The store is
+// closed again before the node starts: bbolt holds an exclusive lock.
+func ensureNodeKey(t *testing.T, dataDir string) peer.ID {
+ t.Helper()
+ store, err := node.NewStore(dataDir)
+ if err != nil {
+ t.Fatalf("open node store %s: %v", dataDir, err)
+ }
+ priv := node.GetOrGenerateKey(store)
+ if err := store.Close(); err != nil {
+ t.Fatalf("close node store: %v", err)
+ }
+ id, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ t.Fatalf("peer ID from node key: %v", err)
+ }
+ return id
+}
+
+func nodeToken(t *testing.T, env []string, args []string) string {
+ t.Helper()
+ for i, a := range args {
+ if a == "--api-token-path" && i+1 < len(args) {
+ data, err := os.ReadFile(args[i+1])
+ if err != nil {
+ t.Fatalf("read api token: %v", err)
+ }
+ return strings.TrimSpace(string(data))
+ }
+ }
+ for _, e := range env {
+ if v, ok := strings.CutPrefix(e, "SAM_API_TOKEN="); ok {
+ return v
+ }
+ }
+ return ""
+}
+
+// startBackgroundNode is launchNode for a node that enrolls with --jwt
+// against routerAddr, with homeDir as its home and the shared test token.
+func startBackgroundNode(t *testing.T, nodeBin string, routerAddr string, homeDir string, args ...string) *backgroundNode {
+ t.Helper()
+ env := append(os.Environ(),
+ "HOME="+homeDir,
+ "XDG_CONFIG_HOME="+filepath.Join(homeDir, ".config"),
+ "SAM_API_TOKEN=test-token", // per-test overrides use --api-token-path, which wins
+ )
+ allArgs := append([]string{"run", "--control-plane", routerAddr, "--jwt", "test-jwt", "--allow-loopback"}, args...)
+ return launchNode(t, nodeBin, env, homeDir, allArgs...)
+}
+
+func (n *backgroundNode) kill() {
+ if n.cmd.Process != nil {
+ _ = n.cmd.Process.Kill()
+ }
+ <-n.exited
+ // Re-arm so a second kill (test cleanup after an explicit one) does not block.
+ n.exited <- nil
+}
+
+// log is the node's output, for failure messages only.
+func (n *backgroundNode) log() string {
+ data, err := os.ReadFile(n.logPath)
+ if err != nil {
+ return fmt.Sprintf("(no log: %v)", err)
+ }
+ return string(data)
+}
+
+// waitForAPI returns the API address once /healthz answers, which the node
+// only does after Start succeeded (enrolled, router authenticated), and fails
+// if the node exits first or does not come up in time.
+func (n *backgroundNode) waitForAPI(t *testing.T) string {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ client := &http.Client{Timeout: time.Second}
+ for time.Now().Before(deadline) {
+ select {
+ case err := <-n.exited:
+ n.exited <- err
+ t.Fatalf("sam-node exited (%v) before serving its API.\n--- node.log ---\n%s", err, n.log())
+ default:
+ }
+ resp, err := client.Get("http://" + n.apiAddr + "/healthz")
+ if err == nil {
+ _ = resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ return n.apiAddr
+ }
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ t.Fatalf("sam-node did not serve its API at %s in time.\n--- node.log ---\n%s", n.apiAddr, n.log())
+ return ""
+}
+
+// exitsWithin fails unless the node exits within d; it returns the exit error.
+func (n *backgroundNode) exitsWithin(t *testing.T, d time.Duration) error {
+ t.Helper()
+ select {
+ case err := <-n.exited:
+ n.exited <- err
+ return err
+ case <-time.After(d):
+ t.Fatalf("sam-node still running after %s.\n--- node.log ---\n%s", d, n.log())
+ return nil
+ }
+}
+
+// staysUp fails if the node exits within d.
+func (n *backgroundNode) staysUp(t *testing.T, d time.Duration) {
+ t.Helper()
+ select {
+ case err := <-n.exited:
+ n.exited <- err
+ t.Fatalf("sam-node exited (%v) within %s.\n--- node.log ---\n%s", err, d, n.log())
+ case <-time.After(d):
+ }
+}
+
+// waitForAPI polls addr's /healthz for a node the test started itself.
+func waitForAPI(t *testing.T, addr string) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ client := &http.Client{Timeout: time.Second}
+ for time.Now().Before(deadline) {
+ resp, err := client.Get("http://" + addr + "/healthz")
+ if err == nil {
+ _ = resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ return
+ }
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ t.Fatalf("timeout waiting for API at %s", addr)
+}
diff --git a/tests/integration/openai_facade_test.go b/tests/integration/openai_facade_test.go
index 729519dd..7db9438f 100644
--- a/tests/integration/openai_facade_test.go
+++ b/tests/integration/openai_facade_test.go
@@ -19,7 +19,6 @@ import (
"io"
"net/http"
"net/http/httptest"
- "path/filepath"
"strings"
"sync/atomic"
"testing"
@@ -75,7 +74,7 @@ func TestOpenAIFacadeCUJ(t *testing.T) {
defer backend.Close()
t.Log("Starting Node A (provider)...")
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, hubAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
@@ -83,18 +82,16 @@ func TestOpenAIFacadeCUJ(t *testing.T) {
"--config", writeNodeConfig(t, homeA, map[string]string{"region": "eu"}, svcDecl{Type: "inference", Name: "test-llm", TargetURL: backend.URL}),
)
t.Log("Starting Node B (consumer)...")
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, hubAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
)
- apiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- apiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
- waitForAPI(t, apiAddrA)
- waitForAPI(t, apiAddrB)
+ apiAddrA := nodeA.waitForAPI(t)
+ apiAddrB := nodeB.waitForAPI(t)
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
connectPeer(t, apiAddrB, addrA)
waitForDHTPeers(t, apiAddrA)
diff --git a/tests/integration/policy_permutations_test.go b/tests/integration/policy_permutations_test.go
index 6ae838df..b7caeeeb 100644
--- a/tests/integration/policy_permutations_test.go
+++ b/tests/integration/policy_permutations_test.go
@@ -19,7 +19,6 @@ import (
"fmt"
"net/http"
"os"
- "os/exec"
"path/filepath"
"strings"
"testing"
@@ -169,12 +168,10 @@ services:
homeB := filepath.Join(tmpDir, "nodeB")
apiTokenB := "tokenB"
- apiPortB := getFreePort(t)
- cmdB := exec.Command(nodeBin, "run",
+ nodeB := launchNode(t, nodeBin, os.Environ(), homeB, "run",
"--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),
"--data-dir", homeB,
- "--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),
"--api-token-path", tokenPath(t, apiTokenB),
"--jwt", mintToken(map[string]interface{}{
"sub": "bob-subject",
@@ -182,29 +179,12 @@ services:
"email": "[email protected]",
"groups": []string{"compute", "backend"},
}),
- "--listen", "/ip4/127.0.0.1/tcp/0",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--allow-loopback",
"--config", nodeBPolicyFile,
)
- if err := os.MkdirAll(homeB, 0755); err != nil {
- t.Fatal(err)
- }
- logFileB, err := os.Create(filepath.Join(homeB, "node.log"))
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = logFileB.Close() }()
- cmdB.Stdout = logFileB
- cmdB.Stderr = logFileB
- if err := cmdB.Start(); err != nil {
- t.Fatalf("Failed to start Node B: %v", err)
- }
- defer func() { _ = cmdB.Process.Kill(); _ = cmdB.Wait() }()
-
- actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
- waitForAPI(t, actualApiAddrB)
- addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))
+ nodeB.waitForAPI(t)
+ addrB := nodeB.p2pAddr
// 3. Test Permutations
tests := []struct {
@@ -264,39 +244,20 @@ services:
t.Run(tt.name, func(t *testing.T) {
homeA := filepath.Join(tmpDir, fmt.Sprintf("nodeA_%d", i))
apiTokenA := "tokenA"
- apiPortA := getFreePort(t)
// The seat comes from the sam:system:authenticated binding above,
// never from a roles claim naming sam:role:node.
jwtA := mintToken(tt.jwtClaims)
- cmdA := exec.Command(nodeBin, "run",
+ nodeA := launchNode(t, nodeBin, os.Environ(), homeA, "run",
"--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),
"--data-dir", homeA,
- "--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),
"--api-token-path", tokenPath(t, apiTokenA),
"--jwt", jwtA,
- "--listen", "/ip4/127.0.0.1/tcp/0",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--allow-loopback",
)
- if err := os.MkdirAll(homeA, 0755); err != nil {
- t.Fatal(err)
- }
- logFileA, err := os.Create(filepath.Join(homeA, "node.log"))
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = logFileA.Close() }()
- cmdA.Stdout = logFileA
- cmdA.Stderr = logFileA
- if err := cmdA.Start(); err != nil {
- t.Fatalf("Failed to start Node A: %v", err)
- }
- defer func() { _ = cmdA.Process.Kill(); _ = cmdA.Wait() }()
-
- actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- waitForAPI(t, actualApiAddrA)
+ actualApiAddrA := nodeA.waitForAPI(t)
parts := strings.Split(addrB, "/p2p/")
if len(parts) != 2 {
diff --git a/tests/integration/revocation_test.go b/tests/integration/revocation_test.go
index 14d015cb..3767843b 100644
--- a/tests/integration/revocation_test.go
+++ b/tests/integration/revocation_test.go
@@ -21,7 +21,6 @@ import (
"os"
"os/exec"
"path/filepath"
- "regexp"
"strings"
"testing"
"time"
@@ -113,97 +112,45 @@ roles:
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",
+ node1 := launchNode(t, nodeBin,
+ append(os.Environ(), "HOME="+node1Home, "XDG_CONFIG_HOME="+filepath.Join(node1Home, ".config")),
+ node1Home, "run",
"--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),
"--jwt", mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}}),
"--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-path", tokenPath(t, "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",
+ node2 := launchNode(t, nodeBin,
+ append(os.Environ(), "HOME="+node2Home, "XDG_CONFIG_HOME="+filepath.Join(node2Home, ".config")),
+ node2Home, "run",
"--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),
"--jwt", mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}}),
"--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-path", tokenPath(t, "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)
+ node1API := node1.waitForAPI(t)
+ node2.waitForAPI(t)
- // 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]
+ node2AddrStr := node2.p2pAddr
+ node2PeerID := node2.peerID.String()
// 6. Request Node 1 to connect to Node 2
- connectPeerWithToken(t, fmt.Sprintf("127.0.0.1:%d", node1ApiPort), "node1-token",
- fmt.Sprintf("%s/p2p/%s", node2TCPAddr, node2PeerID))
+ connectPeerWithToken(t, node1API, "node1-token", node2AddrStr)
// 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),
+ "-url", "http://"+node1API+"/mcp",
"-token", "node1-token",
"-tool", "get_mesh_info",
"-args", "{}",
@@ -259,26 +206,11 @@ roles:
}
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)
+ publishGossipEvent(t, node1.p2pAddr, event)
// 8. Wait for revocation event to propagate and Node 1 to disconnect Node 2 actively
- waitForNodeDisconnection(t, clientBin, node1ApiPort, node2PeerID)
+ waitForNodeDisconnection(t, clientBin, node1API, node2PeerID)
}
func publishGossipEvent(t *testing.T, routerAddrStr string, event *api.MeshEvent) {
@@ -350,7 +282,7 @@ func publishGossipEvent(t *testing.T, routerAddrStr string, event *api.MeshEvent
}
}
-func waitForNodeDisconnection(t *testing.T, clientBin string, node1ApiPort int, node2PeerID string) {
+func waitForNodeDisconnection(t *testing.T, clientBin string, node1API string, node2PeerID string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -358,7 +290,7 @@ func waitForNodeDisconnection(t *testing.T, clientBin string, node1ApiPort int,
for {
stdout, _, err := runCommand(t, repoRoot(t), 2*time.Second, nil, "",
clientBin,
- "-url", fmt.Sprintf("http://127.0.0.1:%d/mcp", node1ApiPort),
+ "-url", "http://"+node1API+"/mcp",
"-token", "node1-token",
"-tool", "get_mesh_info",
"-args", "{}",
diff --git a/tests/integration/rotation_test.go b/tests/integration/rotation_test.go
index a188900d..6681c600 100644
--- a/tests/integration/rotation_test.go
+++ b/tests/integration/rotation_test.go
@@ -148,7 +148,7 @@ roles:
}()
// Wait for Node to be online actively
- waitForNodeOnline(t, nodeLogPath)
+ waitForAPI(t, fmt.Sprintf("127.0.0.1:%d", nodeApiPort))
// Get initial keys
initialKeys := fetchPublicKeys(t, cpPort)
diff --git a/tests/integration/sandbox_boundary_test.go b/tests/integration/sandbox_boundary_test.go
index 782ea842..9f385c53 100644
--- a/tests/integration/sandbox_boundary_test.go
+++ b/tests/integration/sandbox_boundary_test.go
@@ -85,7 +85,7 @@ func TestSandboxBoundaryCUJ(t *testing.T) {
defer external.Close()
t.Log("Starting node A (provider) and node B (the gateway's node)...")
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, hubAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
@@ -93,19 +93,17 @@ func TestSandboxBoundaryCUJ(t *testing.T) {
svcDecl{Type: "inference", Name: "test-llm", TargetURL: inference.URL},
svcDecl{Type: "mcp", Name: "calc", TargetURL: tools.URL}),
)
- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, hubAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
"--socket-path", nodeSocket,
)
- apiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- apiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
- waitForAPI(t, apiAddrA)
- waitForAPI(t, apiAddrB)
+ apiAddrA := nodeA.waitForAPI(t)
+ apiAddrB := nodeB.waitForAPI(t)
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
peerA := extractPeerID(addrA)
connectPeer(t, apiAddrB, addrA)
waitForDHTPeers(t, apiAddrA)
diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.go
index 796120a1..3f53d210 100644
--- a/tests/integration/service_discovery_test.go
+++ b/tests/integration/service_discovery_test.go
@@ -20,7 +20,6 @@ import (
"io"
"net/http"
"net/http/httptest"
- "path/filepath"
"strings"
"testing"
"time"
@@ -48,34 +47,27 @@ func TestServiceDiscovery(t *testing.T) {
// Start Node A
t.Log("Starting Node A...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, routerAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
"--config", writeNodeConfig(t, homeA, nil, svcDecl{Type: "mcp", Name: serviceName, TargetURL: mockServer.URL}),
)
// Start Node B
t.Log("Starting Node B...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, routerAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
)
- // Resolve actual addresses from logs
- actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
+ actualApiAddrA := nodeA.waitForAPI(t)
+ actualApiAddrB := nodeB.waitForAPI(t)
- // Wait for nodes to start sidecar API
- waitForAPI(t, actualApiAddrA)
- waitForAPI(t, actualApiAddrB)
-
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
// Connect Node B to Node A (to ensure they are in same network)
// We use the multiplexed HTTP address for MCP calls too!
@@ -149,34 +141,27 @@ func TestServiceDiscoveryStreaming(t *testing.T) {
// Start Node A
t.Log("Starting Node A...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeA,
+ nodeA := startBackgroundNode(t, nodeBin, routerAddr, homeA,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
"--config", writeNodeConfig(t, homeA, nil, svcDecl{Type: "mcp", Name: serviceName, TargetURL: mockServer.URL}),
)
// Start Node B
t.Log("Starting Node B...")
- _ = startBackgroundNode(t, nodeBin, routerAddr, homeB,
+ nodeB := startBackgroundNode(t, nodeBin, routerAddr, homeB,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--discovery-interval", "100ms",
- "--bind-addr", "127.0.0.1:0",
"--api-token-path", tokenPath(t, apiToken),
)
- // Resolve actual addresses from logs
- actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
- actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
-
- // Wait for nodes to start sidecar API
- waitForAPI(t, actualApiAddrA)
- waitForAPI(t, actualApiAddrB)
+ actualApiAddrA := nodeA.waitForAPI(t)
+ actualApiAddrB := nodeB.waitForAPI(t)
- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ addrA := nodeA.p2pAddr
// Connect Node B to Node A
connectPeer(t, actualApiAddrB, addrA)
@@ -275,20 +260,6 @@ func TestServiceDiscoveryStreaming(t *testing.T) {
}
}
-func waitForAPI(t *testing.T, addr string) {
- t.Helper()
- deadline := time.Now().Add(5 * time.Second)
- for time.Now().Before(deadline) {
- resp, err := http.Get("http://" + addr + "/healthz")
- if err == nil && resp.StatusCode == http.StatusOK {
- _ = resp.Body.Close()
- return
- }
- time.Sleep(100 * time.Millisecond)
- }
- t.Fatalf("timeout waiting for API at %s", addr)
-}
-
func discoverService(t *testing.T, apiAddr, token, serviceName string) []peer.AddrInfo {
t.Helper()
req, _ := http.NewRequest("GET", "http://"+apiAddr+"/sam/service/discover?type=mcp&name="+serviceName, nil)