Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node: services are declared in configuration, never registered at runtime
Antonio Ojea36fd89f2fb6c
diff --git a/.github/k8s/sam-box-canary-template.yaml b/.github/k8s/sam-box-canary-template.yamlindex 7fa5ed01..de5b4bef 100644--- a/.github/k8s/sam-box-canary-template.yaml+++ b/.github/k8s/sam-box-canary-template.yaml@@ -147,7 +147,7 @@ spec:echo "the sandbox's interfaces (expect lo and tun0 only): $(ip -o link show | cut -d: -f2 | tr -d ' ' | paste -sd,)"while true; doecho "allowlisted destination (expect 200): $(curl -s -o /dev/null -w '%{http_code}' http://example.com/)"- echo "the node's own API (expect 403): $(curl -s -o /dev/null -w '%{http_code}' http://mesh.sam.alt/sam/service/register)"+ echo "the node's own API (expect 403): $(curl -s -o /dev/null -w '%{http_code}' http://mesh.sam.alt/sam/service/discover)"curl -s -o /dev/null http://blocked.example/ && echo "unlisted destination was NOT refused" || echo "unlisted destination refused (expected)"sleep 30donediff --git a/internal/node/node.go b/internal/node/node.goindex 28daa019..7c919c2c 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -1580,6 +1580,15 @@ func (n *SamNode) HandleAuthHandshake(s network.Stream) {}func (n *SamNode) RegisterService(ctx context.Context, req *api.RegisterServiceRequest) error {+ if req.Service == nil {+ return fmt.Errorf("service field is required")+ }+ if req.Service.Name == "" || req.Service.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {+ return fmt.Errorf("service name and type are required")+ }+ if req.Backend == nil {+ return fmt.Errorf("service backend is required")+ }svc, err := NewServiceFromRequest(req)if err != nil {return errdiff --git a/internal/node/sidecar.go b/internal/node/sidecar.goindex b88d5bf4..c2429858 100644--- a/internal/node/sidecar.go+++ b/internal/node/sidecar.go@@ -23,7 +23,6 @@ import ("encoding/base64""encoding/json""fmt"- "io""net""net/http""net/http/httputil"@@ -38,7 +37,6 @@ import ("github.com/libp2p/go-libp2p/core/network""github.com/libp2p/go-libp2p/core/peer""github.com/prometheus/client_golang/prometheus/promhttp"- "google.golang.org/protobuf/encoding/protojson")// StartSidecarServer serves the node's local API on a TCP address, on a Unix@@ -57,12 +55,10 @@ func StartSidecarServer(node *SamNode, addr, socketPath, token, certFile, keyFil// Protected endpoints. allowAuthorizationFallback=true is safe here: none of// these ever forward the inbound Authorization header to another service.- mux.Handle("/sam/service/register", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- handleRegisterService(node, w, r)- }))))- mux.Handle("/sam/service/unregister", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- handleUnregisterService(node, w, r)- }))))+ // Services are declared in the node's configuration and registered at+ // startup; there is deliberately no runtime registration surface, so no+ // credential held by an agent can point the mesh at a new backend or+ // withdraw a sibling service.mux.Handle("/sam/service/discover", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {handleDiscoverService(node, w, r)}))))@@ -448,90 +444,10 @@ func constantTimeEqual(got, want string) bool {return subtle.ConstantTimeCompare(gotHash[:], wantHash[:]) == 1}-type ServiceRequest struct {- ServiceName string `json:"service_name"`-}-// maxRequestBodyBytes caps request bodies read into memory to guard// against memory-exhaustion from oversized payloads.const maxRequestBodyBytes = 1 << 20 // 1 MiB-func handleRegisterService(node *SamNode, w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)- body, err := io.ReadAll(r.Body)- if err != nil {- http.Error(w, "Failed to read request body", http.StatusInternalServerError)- return- }- _ = r.Body.Close()-- var req api.RegisterServiceRequest- if err := protojson.Unmarshal(body, &req); err != nil {- http.Error(w, fmt.Sprintf("Invalid request body: %v", err), http.StatusBadRequest)- return- }-- if req.Service == nil {- http.Error(w, "service field is required", http.StatusBadRequest)- return- }-- if req.Service.Name == "" || req.Service.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {- http.Error(w, "name and type are required", http.StatusBadRequest)- return- }-- if req.Backend == nil {- http.Error(w, "backend is required", http.StatusBadRequest)- return- }-- if err := node.RegisterService(r.Context(), &req); err != nil {- logger.Errorf("Failed to register service: %v", err)- http.Error(w, fmt.Sprintf("Failed to register service: %v", err), http.StatusInternalServerError)- return- }-- w.WriteHeader(http.StatusOK)- if _, err := w.Write([]byte("Service registered")); err != nil {- logger.Errorf("Failed to write response: %v", err)- }-}--func handleUnregisterService(node *SamNode, w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- var req api.ServiceInfo- r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)- return- }-- if req.Name == "" {- http.Error(w, "name is required", http.StatusBadRequest)- return- }-- if err := node.UnregisterService(r.Context(), req.Name); err != nil {- http.Error(w, fmt.Sprintf("Failed to unregister service: %v", err), http.StatusInternalServerError)- return- }-- w.WriteHeader(http.StatusOK)- if _, err := w.Write([]byte("Service unregistered")); err != nil {- logger.Errorf("Failed to write response: %v", err)- }-}-func handleDiscoverService(node *SamNode, w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)diff --git a/internal/node/sidecar_test.go b/internal/node/sidecar_test.goindex 62ad8dbb..e8d8986e 100644--- a/internal/node/sidecar_test.go+++ b/internal/node/sidecar_test.go@@ -15,7 +15,6 @@package nodeimport (- "bytes""context""encoding/json""net"@@ -34,7 +33,6 @@ import ("github.com/libp2p/go-libp2p/core/host""github.com/libp2p/go-libp2p/core/peer""github.com/modelcontextprotocol/go-sdk/mcp"- "google.golang.org/protobuf/encoding/protojson")// socketClient talks HTTP over a Unix socket; the host in the URL is ignored.@@ -406,15 +404,16 @@ func TestSidecarServerAuthEnforcement(t *testing.T) {{"readyz is public", "GET", "/readyz", http.StatusOK, false},// Liveness says nothing; metrics name peers and count their traffic.{"metrics is protected", "GET", "/metrics", http.StatusUnauthorized, false},- {"register is protected", "POST", "/sam/service/register", http.StatusUnauthorized, false},- {"unregister is protected", "POST", "/sam/service/unregister", http.StatusUnauthorized, false},+ // Services are declared in configuration only: the former runtime+ // mutation endpoints are gone, so these paths are plain egress-proxy+ // paths (503: not connected) with no special handling.+ {"register does not exist", "POST", "/sam/service/register", http.StatusServiceUnavailable, true},+ {"unregister does not exist", "POST", "/sam/service/unregister", http.StatusServiceUnavailable, true},{"discover is protected", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusUnauthorized, false},{"egress proxy is protected", "GET", "/sam/", http.StatusUnauthorized, false},{"mcp root is protected", "GET", "/mcp", http.StatusUnauthorized, false},- {"register with token (bad req)", "POST", "/sam/service/register", http.StatusServiceUnavailable, true},{"metrics with token", "GET", "/metrics", http.StatusOK, true},- {"unregister with token (bad req)", "POST", "/sam/service/unregister", http.StatusServiceUnavailable, true},// /sam/service/discover without mesh connection will return 503 instead of 400 since node is not connected,// but as long as it gets past auth, that's what we want to verify.{"discover with token", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusServiceUnavailable, true},@@ -514,7 +513,7 @@ func TestSidecarAuthorizationFallbackScope(t *testing.T) {}}-func TestHandleRegisterService(t *testing.T) {+func TestRegisterService(t *testing.T) {h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))if err != nil {t.Fatal(err)@@ -555,22 +554,12 @@ func TestHandleRegisterService(t *testing.T) {upstream := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{}))defer upstream.Close()- reqBody := &api.RegisterServiceRequest{+ req := &api.RegisterServiceRequest{Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "test-service", Description: "test desc"},Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL},}- body, err := protojson.Marshal(reqBody)- if err != nil {- t.Fatalf("Failed to marshal request body: %v", err)- }-- req := httptest.NewRequest("POST", "/sam/service/register", bytes.NewBuffer(body))- rr := httptest.NewRecorder()-- handleRegisterService(node, rr, req)-- if rr.Code != http.StatusOK {- t.Errorf("expected status OK, got %d, body: %s", rr.Code, rr.Body.String())+ if err := node.RegisterService(context.Background(), req); err != nil {+ t.Fatalf("RegisterService: %v", err)}if !node.IsServiceRegistered("test-service") {@@ -584,25 +573,14 @@ func TestHandleRegisterService(t *testing.T) {}}-func TestHandleUnregisterService(t *testing.T) {+func TestUnregisterService(t *testing.T) {node := &SamNode{BiscuitTimeout: 500 * time.Millisecond,services: NewServiceRegistry(&fakeDHT{}),}node.services.insertService(&testService{info: &api.ServiceInfo{Name: "test-service"}})- reqBody := &api.ServiceInfo{Name: "test-service"}- body, err := json.Marshal(reqBody)- if err != nil {- t.Fatalf("Failed to marshal request body: %v", err)- }-- req := httptest.NewRequest("POST", "/sam/service/unregister", bytes.NewBuffer(body))- rr := httptest.NewRecorder()-- handleUnregisterService(node, rr, req)-- if rr.Code != http.StatusOK {- t.Errorf("expected status OK, got %d", rr.Code)+ if err := node.UnregisterService(context.Background(), "test-service"); err != nil {+ t.Fatalf("UnregisterService: %v", err)}if node.IsServiceRegistered("test-service") {@@ -797,22 +775,20 @@ func TestServiceKeyToCID_Equivalence(t *testing.T) {}}-func TestHandleRegisterService_Validation(t *testing.T) {+func TestRegisterService_Validation(t *testing.T) {node := &SamNode{BiscuitTimeout: 500 * time.Millisecond,services: NewServiceRegistry(&fakeDHT{}),}tests := []struct {- name string- reqBody *api.RegisterServiceRequest- expectedStatus int+ name string+ reqBody *api.RegisterServiceRequest}{{name: "Missing service",reqBody: &api.RegisterServiceRequest{Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},},- expectedStatus: http.StatusBadRequest,},{name: "Missing name",@@ -820,7 +796,6 @@ func TestHandleRegisterService_Validation(t *testing.T) {Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP},Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},},- expectedStatus: http.StatusBadRequest,},{name: "Unspecified type",@@ -828,30 +803,19 @@ func TestHandleRegisterService_Validation(t *testing.T) {Service: &api.ServiceInfo{Name: "test-service", Type: api.ServiceType_SERVICE_TYPE_UNSPECIFIED},Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},},- expectedStatus: http.StatusBadRequest,},{name: "Missing backend",reqBody: &api.RegisterServiceRequest{Service: &api.ServiceInfo{Name: "test-service", Type: api.ServiceType_SERVICE_TYPE_MCP},},- expectedStatus: http.StatusBadRequest,},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- body, err := protojson.Marshal(tt.reqBody)- if err != nil {- t.Fatal(err)- }- req := httptest.NewRequest("POST", "/sam/service/register", bytes.NewBuffer(body))- rr := httptest.NewRecorder()-- handleRegisterService(node, rr, req)-- if rr.Code != tt.expectedStatus {- t.Errorf("expected status %d, got %d, body: %s", tt.expectedStatus, rr.Code, rr.Body.String())+ if err := node.RegisterService(context.Background(), tt.reqBody); err == nil {+ t.Errorf("expected RegisterService to reject invalid request")}})}diff --git a/mobile/mobile_e2e.sh b/mobile/mobile_e2e.shindex 15726612..64d165ca 100755--- a/mobile/mobile_e2e.sh+++ b/mobile/mobile_e2e.sh@@ -141,28 +141,9 @@ mkdir -p /tmp/host-node-dataHOST_JWT=$(curl -s -X POST -d "grant_type=client_credentials&client_id=test-client&client_secret=test-secret" http://127.0.0.1:18080/token | jq -r .access_token)-docker run --name host-node \- --network sam-net \- -p 8081:8081 \- --user "$(id -u):$(id -g)" \- -v /tmp/host-node-data:/data \- --add-host=host.docker.internal:host-gateway \- -e SAM_API_TOKEN=host-token \- -d --rm \- sam-node:local \- run \- --data-dir /data \- --control-plane http://sam-control-plane:37001 \- --jwt "$HOST_JWT" \- --bind-addr 0.0.0.0:8081 \- --allow-loopback \- --enable-relay \- --log-level debug--# Wait for external node to be ready-timeout 15s bash -c 'until curl -s -X POST -H "Authorization: Bearer host-token" -d "{\"jsonrpc\":\"2.0\",\"method\":\"ping\",\"id\":1}" http://127.0.0.1:8081/mcp >/dev/null; do sleep 0.5; done'--# Start a local Mock MCP Server container on port 9091+# Start a local Mock MCP Server container on port 9091. The backend exists+# before the node: services are declared in the node's configuration, there+# is no runtime registration endpoint.docker run --name host-mock-mcp \--network sam-net \-p 9091:9091 \@@ -237,7 +218,7 @@ HTTPServer(("0.0.0.0", 9091), S).serve_forever()'# The node probes a backend before advertising it, so the mock has to be-# listening before the service below is registered.+# listening before the node that declares the service starts.for _ in $(seq 1 30); docurl -sf -o /dev/null -X POST -H "Content-Type: application/json" \-d '{"jsonrpc":"2.0","id":1,"method":"initialize"}' \@@ -245,12 +226,38 @@ for _ in $(seq 1 30); dosleep 1done-# Register a dummy MCP service on the host node pointing to the local mock server container (using container name)-curl -s -X POST \- -H "Content-Type: application/json" \- -H "Authorization: Bearer host-token" \- -d '{"service":{"type":"SERVICE_TYPE_MCP","name":"host-tool","description":"test tool on host"},"targetUrl":"http://host-mock-mcp:9091"}' \- http://127.0.0.1:8081/sam/service/register+# The host node declares the dummy MCP service in its config, pointing at the+# mock server container (using container name).+cat > /tmp/host-node-data/services.yaml <<'EOF'+version: "v1alpha1"+services:+ - type: "mcp"+ name: "host-tool"+ description: "test tool on host"+ target_url: "http://host-mock-mcp:9091"+EOF++docker run --name host-node \+ --network sam-net \+ -p 8081:8081 \+ --user "$(id -u):$(id -g)" \+ -v /tmp/host-node-data:/data \+ --add-host=host.docker.internal:host-gateway \+ -e SAM_API_TOKEN=host-token \+ -d --rm \+ sam-node:local \+ run \+ --data-dir /data \+ --control-plane http://sam-control-plane:37001 \+ --jwt "$HOST_JWT" \+ --bind-addr 0.0.0.0:8081 \+ --allow-loopback \+ --enable-relay \+ --config /data/services.yaml \+ --log-level debug++# Wait for external node to be ready+timeout 15s bash -c 'until curl -s -X POST -H "Authorization: Bearer host-token" -d "{\"jsonrpc\":\"2.0\",\"method\":\"ping\",\"id\":1}" http://127.0.0.1:8081/mcp >/dev/null; do sleep 0.5; done'}run_test() {diff --git a/mobile/sam-node-app/integration_test/e2e_test.dart b/mobile/sam-node-app/integration_test/e2e_test.dartindex 14b2dfb0..ba7adeaa 100644--- a/mobile/sam-node-app/integration_test/e2e_test.dart+++ b/mobile/sam-node-app/integration_test/e2e_test.dart@@ -47,28 +47,10 @@ void main() {final enrollErr = samLib.enroll(dataDir, controlPlaneURL, jwt, true);expect(enrollErr, isNull);- // 4. Start Node- final startErr = samLib.start({- 'dataDir': dataDir,- 'controlPlaneURL': controlPlaneURL,- 'meshID': 'public-mesh',- 'bindAddr': '0.0.0.0:8080', // sidecar HTTP server inside phone- 'apiToken': 'test-token',- 'allowLoopback': true,- 'enableRelay': true,- 'logLevel': 'debug',- });- expect(startErr, isNull);-- // Wait for node to initialize host connection- await Future.delayed(const Duration(seconds: 5));-- final nodeID = samLib.getNodeID();- expect(nodeID, isNotNull);- expect(nodeID, isNotEmpty);- expect(nodeID, isNot('unauthenticated'));-- // Start local Mock MCP Server inside the Android emulator+ // Start local Mock MCP Server inside the Android emulator. It must be+ // listening before the node starts: the service it backs is declared in+ // the start configuration below and probed at startup; there is no+ // runtime registration.final mockMcpServer = await HttpServer.bind(InternetAddress.loopbackIPv4, 9090);mockMcpServer.listen((HttpRequest request) async {if (request.method == 'GET') {@@ -126,24 +108,35 @@ void main() {}});- // Register a dummy MCP service inside the Android emulator- const registerUrl = 'http://127.0.0.1:8080/sam/service/register';- final regResponse = await http.post(- Uri.parse(registerUrl),- headers: {- 'Content-Type': 'application/json',- 'Authorization': 'Bearer test-token',- },- body: jsonEncode({- 'service': {- 'type': 'SERVICE_TYPE_MCP',+ // 4. Start Node, declaring the emulator's MCP service in the start+ // configuration.+ final startErr = samLib.start({+ 'dataDir': dataDir,+ 'controlPlaneURL': controlPlaneURL,+ 'meshID': 'public-mesh',+ 'bindAddr': '0.0.0.0:8080', // sidecar HTTP server inside phone+ 'apiToken': 'test-token',+ 'allowLoopback': true,+ 'enableRelay': true,+ 'logLevel': 'debug',+ 'services': [+ {+ 'type': 'mcp','name': 'emulator-tool',- 'description': 'test tool inside emulator'- },- 'targetUrl': 'http://127.0.0.1:9090' // point to local Dart mock server- }),- );- expect(regResponse.statusCode, equals(200));+ 'description': 'test tool inside emulator',+ 'targetUrl': 'http://127.0.0.1:9090' // point to local Dart mock server+ }+ ],+ });+ expect(startErr, isNull);++ // Wait for node to initialize host connection+ await Future.delayed(const Duration(seconds: 5));++ final nodeID = samLib.getNodeID();+ expect(nodeID, isNotNull);+ expect(nodeID, isNotEmpty);+ expect(nodeID, isNot('unauthenticated'));// Discover host-tool from inside the emulator via its local MCP API using McpClientfinal client = McpClient('http://127.0.0.1:8080/mcp', 'test-token');diff --git a/mobile/sam-node-app/lib/main.dart b/mobile/sam-node-app/lib/main.dartindex 35cb9755..cf6f005e 100644--- a/mobile/sam-node-app/lib/main.dart+++ b/mobile/sam-node-app/lib/main.dart@@ -90,11 +90,11 @@ class _NodeControlPageState extends State<NodeControlPage> {bool _exposeBattery = false;bool _exposeLocation = false;- // External MCP Bridging State+ // External MCP Bridging State: read when the node starts, since services+ // are declared in the start configuration.final _externalMcpUrlController = TextEditingController(text: 'http://127.0.0.1:8080');final _externalMcpNameController = TextEditingController(text: 'android-remote');final _externalMcpDescController = TextEditingController(text: 'External Android Remote Control MCP');- bool _externalMcpRegistered = false;late SamDartMcpServer _embeddedMcpServer;int _selectedTab = 0; // 0 = Dashboard, 1 = Services@@ -625,6 +625,29 @@ class _NodeControlPageState extends State<NodeControlPage> {final appDir = await getApplicationDocumentsDirectory();final dataDir = '${appDir.path}/sam_data';+ // The embedded MCP backend must be listening before the node starts:+ // services are declared in the start configuration and probed at startup,+ // there is no runtime registration.+ await _embeddedMcpServer.start(port: 9090);++ final services = <Map<String, String>>[+ {+ 'type': 'mcp',+ 'name': 'phone-sensors',+ 'description':+ 'Exposes phone sensors like battery and location to the SAM mesh',+ 'targetUrl': 'http://127.0.0.1:9090',+ },+ if (_externalMcpUrlController.text.isNotEmpty &&+ _externalMcpNameController.text.isNotEmpty)+ {+ 'type': 'mcp',+ 'name': _externalMcpNameController.text,+ 'description': _externalMcpDescController.text,+ 'targetUrl': _externalMcpUrlController.text,+ },+ ];+final err = _samLib.start({'dataDir': dataDir,'controlPlaneURL': _controlPlaneController.text,@@ -633,9 +656,11 @@ class _NodeControlPageState extends State<NodeControlPage> {'apiToken': _tokenController.text,'allowLoopback': true,'enableRelay': false,+ 'services': services,});if (err != null) {+ await _embeddedMcpServer.stop();setState(() {_status = 'Start failed: $err';});@@ -655,12 +680,6 @@ class _NodeControlPageState extends State<NodeControlPage> {_status = 'Running';_nodeID = _samLib.getNodeID() ?? 'unknown';});-- // Start embedded MCP server- await _embeddedMcpServer.start(- goSidecarPort: '5005',- apiToken: _tokenController.text,- );_startPolling();}@@ -843,9 +862,17 @@ class _NodeControlPageState extends State<NodeControlPage> {children: [const Text('Bridge External Local MCP to Mesh',style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),+ const SizedBox(height: 6),+ const Text(+ 'Services are declared when the node starts. Fill these '+ 'fields before pressing Start; there is no runtime '+ 'registration.',+ style: TextStyle(fontSize: 12, color: Colors.grey),+ ),const SizedBox(height: 10),TextFormField(controller: _externalMcpUrlController,+ enabled: !isRunning,decoration: const InputDecoration(labelText: 'External MCP Server URL',hintText: 'http://127.0.0.1:8080',@@ -853,55 +880,19 @@ class _NodeControlPageState extends State<NodeControlPage> {),),const SizedBox(height: 10),- Row(- children: [- Expanded(- child: TextFormField(- controller: _externalMcpNameController,- decoration: const InputDecoration(- labelText: 'Service Name',- hintText: 'android-remote',- border: OutlineInputBorder(),- ),- ),- ),- const SizedBox(width: 10),- ElevatedButton(- onPressed: !isRunning ? null : () async {- if (_externalMcpRegistered) {- ScaffoldMessenger.of(context).showSnackBar(- const SnackBar(content: Text('Unregister not fully supported yet in UI')),- );- } else {- final success = await SamDartMcpServer.registerService(- goSidecarPort: '5005',- apiToken: _tokenController.text,- serviceName: _externalMcpNameController.text,- targetUrl: _externalMcpUrlController.text,- description: _externalMcpDescController.text,- );- if (!mounted) return;- if (success) {- setState(() {- _externalMcpRegistered = true;- });- ScaffoldMessenger.of(context).showSnackBar(- const SnackBar(content: Text('External MCP Registered!')),- );- } else {- ScaffoldMessenger.of(context).showSnackBar(- const SnackBar(content: Text('Failed to register external MCP')),- );- }- }- },- child: Text(_externalMcpRegistered ? 'Registered' : 'Register'),- ),- ],+ TextFormField(+ controller: _externalMcpNameController,+ enabled: !isRunning,+ decoration: const InputDecoration(+ labelText: 'Service Name',+ hintText: 'android-remote',+ border: OutlineInputBorder(),+ ),),- const SizedBox(height: 10),- TextFormField(+ const SizedBox(height: 10),+ TextFormField(controller: _externalMcpDescController,+ enabled: !isRunning,decoration: const InputDecoration(labelText: 'Description',border: OutlineInputBorder(),diff --git a/mobile/sam-node-app/lib/mcp_server.dart b/mobile/sam-node-app/lib/mcp_server.dartindex fc6b6d4c..fd8b32f8 100644--- a/mobile/sam-node-app/lib/mcp_server.dart+++ b/mobile/sam-node-app/lib/mcp_server.dart@@ -2,7 +2,6 @@ import 'dart:io';import 'dart:convert';import 'package:flutter/services.dart';import 'package:flutter/foundation.dart';-import 'package:http/http.dart' as http;class SamDartMcpServer {static const MethodChannel _channel = MethodChannel('com.example.sam_agent/mesh_expose');@@ -18,8 +17,11 @@ class SamDartMcpServer {required this.isLocationEnabled,});- /// Starts the Dart HTTP Server acting as an MCP backend- Future<void> start({int port = 9090, required String goSidecarPort, required String apiToken}) async {+ /// Starts the Dart HTTP Server acting as an MCP backend. The service it+ /// backs is declared in the node's start configuration; there is no+ /// runtime registration, so this server must be listening before the node+ /// starts and probes it.+ Future<void> start({int port = 9090}) async {try {_server = await HttpServer.bind(InternetAddress.loopbackIPv4, port);debugPrint('SAM Dart MCP Server listening on port $port');@@ -35,16 +37,6 @@ class SamDartMcpServer {await request.response.close();}});-- // Register this service with the local SAM Go Node- await registerService(- goSidecarPort: goSidecarPort,- apiToken: apiToken,- serviceName: 'phone-sensors',- targetUrl: 'http://127.0.0.1:$port',- description: 'Exposes phone sensors like battery and location to the SAM mesh',- );-} catch (e) {debugPrint('Failed to start Dart MCP Server: $e');}@@ -237,52 +229,4 @@ class SamDartMcpServer {request.response.write(jsonEncode(response));await request.response.close();}-- /// Static helper to register any service (Embedded or External)- static Future<bool> registerService({- required String goSidecarPort,- required String apiToken,- required String serviceName,- required String targetUrl,- required String description,- }) async {- final url = 'http://127.0.0.1:$goSidecarPort/sam/service/register';-- int retries = 5;- while (retries > 0) {- try {- final response = await http.post(- Uri.parse(url),- headers: {- 'Authorization': 'Bearer $apiToken',- 'Content-Type': 'application/json',- },- body: jsonEncode({- 'service': {- 'type': 'SERVICE_TYPE_MCP',- 'name': serviceName,- 'description': description- },- 'targetUrl': targetUrl- }),- );-- if (response.statusCode == 200) {- debugPrint('Service "$serviceName" registered successfully with SAM Go Node!');- return true;- } else {- debugPrint('Failed to register service "$serviceName": ${response.statusCode} - ${response.body}');- return false;- }- } catch (e) {- retries--;- if (retries == 0) {- debugPrint('Error registering service "$serviceName": $e');- return false;- }- await Future.delayed(const Duration(milliseconds: 500));- }- }- return false;- }}diff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.goindex 6d1e3969..26e05db2 100644--- a/mobile/sam-node-ffi/ffi/ffi.go+++ b/mobile/sam-node-ffi/ffi/ffi.go@@ -27,6 +27,7 @@ import ("sync""time"+ "github.com/google/sam/api""github.com/google/sam/internal/node"golog "github.com/ipfs/go-log/v2""github.com/libp2p/go-libp2p/core/peer"@@ -55,6 +56,17 @@ type MobileConfig struct {ListenAddrs string `json:"listenAddrs"` // comma-separatedAllowLoopback bool `json:"allowLoopback"`EnableRelay bool `json:"enableRelay"`+ // Services this node exposes, declared at start like the node config+ // file's services block; there is no runtime registration.+ Services []MobileService `json:"services,omitempty"`+}++// MobileService is one statically declared service.+type MobileService struct {+ Type string `json:"type"`+ Name string `json:"name"`+ Description string `json:"description"`+ TargetURL string `json:"targetUrl"`}// StartNode starts the mesh node and the local sidecar API server.@@ -157,6 +169,21 @@ func StartNode(configJSON string) error {}// Create and initialize the node+ var services []api.ServiceConfig+ for i, svc := range config.Services {+ if err := api.ValidateServiceFormat(svc.Type + "://" + svc.Name); err != nil {+ _ = store.Close()+ activeStore = nil+ return fmt.Errorf("invalid service at index %d: %w", i, err)+ }+ services = append(services, api.ServiceConfig{+ Type: svc.Type,+ Name: svc.Name,+ Description: svc.Description,+ TargetURL: svc.TargetURL,+ })+ }+samNode, err := node.NewSamNode(node.Options{PrivKey: priv,ControlPlanePubKey: controlPlanePubKey,@@ -167,6 +194,7 @@ func StartNode(configJSON string) error {ListenAddrs: listenAddrs,EnableRelay: config.EnableRelay,AllowLoopback: config.AllowLoopback,+ NodeConfig: &node.NodeConfigComplete{Services: services},MonitorBootstrap: 2 * time.Minute,MonitorInterval: 1 * time.Minute,AutoRelayMinInterval: 30 * time.Second,diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.mdindex 10e34f67..da595643 100644--- a/site/content/docs/agent-architecture.md+++ b/site/content/docs/agent-architecture.md@@ -721,7 +721,8 @@ blocks in `biscuit-go` to be attributable. It is a clean upgrade, not a rewrite.* `internal/node` — **nothing** for authorization: appended blocks are alreadyverified and evaluated. Only the namespace-binding policy is new.* `internal/sambox` — holds the bundle, attaches it per flow, per socket or per- tunnel connection; serves the §10 control socket and the §9 ingress endpoint.+ tunnel connection; serves the §10 control socket and routes the §9 serving+ channel.* `cmd/nano-init` — owns the guest side of the ingress channel (§9.2).* Sidecar — propagates the agent header on egress alongside `X-Sam-Biscuit`.* Tests — the CUJ that demonstrates the selling point belongs at integration@@ -784,43 +785,42 @@ attested label machinery (`api/labels.go`) is for.## 9. Ingress: agents that serve-An agent must be able to say "route traffic for this name to me". Two things-make this smaller than it looks.--**It is not a new namespace.** `code-reviewer.mcp.sam.alt` is already the name-(Decision 4); serving it just means being its provider. And **the registration-API already exists**: `RegisterServiceRequest{service{type,name,description},-target_url}` on `/sam/service/register`.--### 9.1 Declaring: autoregistration through the gateway--The agent does **not** call the node. `/sam/service/register` is part of the-operator surface an agent never reaches (§5.2), for two independent reasons: the-request carries a `target_url`, so an agent could point the mesh at anything and-turn its node into an open relay; and it carries a service *name*, so an agent-could advertise itself as `code-reviewer` under the node's identity and take-over somebody else's traffic.--Both are properties of *that* API, not of the capability. So the gateway offers-the capability without the API:--```http-POST http://mesh.sam.alt/ingress-{"type": "mcp", "name": "code-reviewer", "port": 8080}-```--`sam-box` serves this itself — it is never forwarded — and then registers with-the node on the agent's behalf. Two things make that safe:--* **`target_url` is not the agent's to give.** `sam-box` always substitutes its- own per-agent ingress endpoint, so the field an agent could abuse is one it- never supplies.-* **The name must be one the agent already had.** The bundle enumerates what it- may serve (§10.1 `ingress`), and a name outside that list is not expressible- rather than merely rejected.--The bundle declares `{name, type}` only. The port is the agent's to choose at-runtime, because that is what it actually knows.+An agent serves exactly one thing: itself, over A2A. `code-reviewer.a2a.sam.alt`+is already the name (Decision 4); serving it just means being its provider.+MCP and inference services are operator services, declared in a node's+configuration — an agent is not a generic backend and never advertises one.++### 9.1 Declaring: a static contract, no runtime registration++The agent does **not** declare anything, to anyone, ever. There is no+registration API on the node — services only exist by declaration in the+node's configuration at startup — and there is no announce endpoint on the+gateway. Both facts follow from the same rule: anything an agent can request+at runtime is an interface it can abuse. A runtime declaration carries a+*name*, so an agent could advertise itself as `code-reviewer` under the+node's identity and take over somebody else's traffic; give it a+`target_url` and it can point the mesh at anything and turn its node into an+open relay.++So the whole route is contracted before the agent runs:++* **The bundle names what the agent serves** (§10.1 `serves`): one name, one+ port. `sam-box` routes that name to that port inside the sandbox from+ startup, over the reverse channel (§9.2). A name outside the contract is+ not expressible rather than merely rejected.+* **The node's configuration declares the service** — `type: a2a`, the+ contracted name, `target_url` pointing at the gateway's serving listener.+* **Advertisement is gated on the probe.** The node fetches the agent's card+ (`/.well-known/agent-card.json`) through the gateway before advertising,+ and keeps re-probing. An agent that is not up yet, or has died, is simply+ not discoverable; when it answers, it is. Readiness is observed, never+ asserted.++The agent runs a stock A2A server on its contracted port and knows nothing+else. Its card can claim any address it likes — the mesh regenerates the+card at the consumer edge (interfaces rewritten to the mesh path, stale+signatures dropped), so nothing the agent writes in its own card escapes the+sandbox unverified.**Implemented, including delivery into an isolated sandbox.** Reaching back incannot be done by dialling the agent: every sandbox has a network namespace of@@ -831,42 +831,42 @@ rather than from any one runtime.The way in is the way out. Egress crosses the boundary over a pathname Unixsocket, which network namespaces do not apply to because it is a filesystemobject. Ingress uses a second one: `nano-init --ingress-socket` serves it from-inside the sandbox, where it can reach the agent at the address the gateway-meant, and `sam-box --agent-ingress-socket` dials it. The handshake is-Firecracker's — `CONNECT <port>`, then `OK` — so a microVM can offer the same-protocol over vsock without the gateway learning the difference.+inside the sandbox, where it can reach the agent at the contracted port, and+`sam-box --agent-ingress-socket` dials it. The handshake is Firecracker's —+`CONNECT <port>`, then `OK` — so a microVM can offer the same protocol over+vsock without the gateway learning the difference.`TestSandboxServesThroughTheReverseChannel` drives a real sandbox and assertsboth halves: that dialling the agent directly from outside fails, and that the-same agent answers through the channel. The older ingress tests supply their-own `AgentAddr` and so cover the declaration, the policy check and the-forwarding logic, but not the hop that depends on where the agent is.+same agent answers through the channel. `TestAgentIngressCUJ` covers the+mesh-facing half with a stock A2A SDK on both ends: the card is regenerated at+the consumer, the message round-trips, and the agent has no serving surface to+ask anything of.### 9.1.1 Why this is also the better UX-This is not only the safe shape, it is the one that matches how agents actually-start:--* **The platform knows *what* an agent may serve; only the agent knows *when*.**- A statically declared route advertises a service that is not listening yet, so- the mesh routes to it and fails. Splitting the declaration from the readiness- signal removes that window without a health-check protocol.-* **The port is usually the agent's own business**, chosen at runtime by the- framework it happens to use.-* **Lifetime is tied to the sandbox.** `sam-box` unregisters when the agent's- channel drops or the platform detaches it, so a suspended agent stops being- advertised without anyone reconciling anything.-* **Resume is automatic.** On another host, the new `sam-box` re-registers the- same name against a different peer, and discovery re-points. That is exactly- the property §8 exists to provide, and it would be lost if routes lived in- static platform config.--The bundle stays the authority (what may be served), and the agent supplies only-liveness and a port. An agent that declares nothing serves nothing.--Still to fix before this is built: whether an agent may re-register under a-changed port (flapping needs a rate limit), and whether `sam-box` should probe-the port before advertising rather than trusting the agent's claim.+The runtime-announcement design this replaces argued that only the agent+knows *when* it is ready and *which port* it chose. Both turned out to be+better served without an API:++* **Readiness is the probe's job.** A declared-but-dead service is registered+ yet withheld from discovery until its card answers. That closes the+ advertise-before-listening window without a health-check protocol — and+ without trusting the agent's claim, which the old design listed as an open+ problem.+* **The port is part of the contract.** An agent that must be told nothing+ can still be told one thing by its environment (every serverless platform+ does exactly this); in exchange, port flapping and re-registration rate+ limits stop being problems because re-registration does not exist.+* **Lifetime is tied to the sandbox, structurally.** The gateway's serving+ listener closes when the sandbox goes; the probe fails; discovery+ converges. Nothing unregisters because nothing registered.+* **Resume is still automatic.** The bundle travels with the agent (§8.4), so+ `Attach` on another host renders the same contract: the new gateway routes+ the same name, the new node declares the same service, and the probe+ re-points discovery to the new peer. The property §8 exists to provide+ survives — it never needed a runtime API, only a declaration that moves+ with the agent.### 9.2 The reverse channel@@ -906,8 +906,9 @@ by portable identities rather than by hosts.### 9.4 Migration-The ingress declaration is part of what travels (§8.4). On resume, `sam-box` on-node B registers the same name and discovery re-points to node B. The name is+The serving contract is part of what travels (§8.4). On resume, `sam-box` on+node B routes the same contracted name, node B's configuration declares the+same service, and the probe re-points discovery to node B. The name isstable because it belongs to the agent, not to the node — which is the wholepoint of §8.@@ -933,8 +934,9 @@ egress:allow: ["api.github.com", "*.pypi.org"]secrets:"api.github.com": {kind: bearer, value_from: /etc/sam/secrets/github}-ingress:- - {name: code-reviewer, type: mcp}+serves:+ name: code-reviewer # the agent's A2A name; routed to its contracted port+ port: 8080```### 10.2 Operations@@ -945,9 +947,9 @@ the sandbox:| operation | meaning ||---|---|| `Attach(bundle)` | admit an agent; returns the egress and ingress endpoints to wire into the sandbox |-| `Detach(agent_id)` | stop it: unregister ingress, close channels, drop credentials |+| `Detach(agent_id)` | stop it: close the serving listener and channels, drop credentials || `Refresh(agent_id, credential)` | hand in a rotated workload credential (§8.3) |-| `Status(agent_id)` | what is registered and connected, for the scheduler's reconcile loop |+| `Status(agent_id)` | what is routed and connected, for the scheduler's reconcile loop |### 10.3 Guarantees the interface owes a connectordiff --git a/site/content/docs/user/cloud-run-deployment.md b/site/content/docs/user/cloud-run-deployment.mdindex b34e8cec..dfb1b1e7 100644--- a/site/content/docs/user/cloud-run-deployment.md+++ b/site/content/docs/user/cloud-run-deployment.md@@ -107,29 +107,31 @@ nodes on different networks, neither reachable from the other(`--announce-private=false` withholds their private addresses, forcing alltraffic through the Cloud Run relay).-On the **provider** machine, run a node and any local HTTP backend:+On the **provider** machine, start any local HTTP backend, declare it in a+node config file, and run a node with that config. Services only exist by+declaration at startup — there is no runtime registration endpoint — so+the backend comes up first and the node probes it before advertising:```bash-sam-node run --control-plane "$URL" --bootstrap-token "$JOIN_TOKEN" \- --data-dir ~/provider --announce-private=false &-mkdir -p /tmp/www && echo "hello from provider" > /tmp/www/hello.txtpython3 -m http.server 9000 --bind 127.0.0.1 --directory /tmp/www &-```-Register the backend as a mesh service through the node's local sidecar-socket (owner-only permissions replace the API token) and note the node's-PeerID from its startup output:+cat > ~/provider-services.yaml <<'EOF'+version: "v1alpha1"+services:+ - type: "mcp"+ name: "hello"+ description: "example"+ target_url: "http://127.0.0.1:9000"+EOF-```bash-curl --unix-socket ~/provider/sam.sock -X POST \- -H "Content-Type: application/json" \- -d '{"service":{"type":"SERVICE_TYPE_MCP","name":"hello","description":"example"},- "targetUrl":"http://127.0.0.1:9000"}' \- http://localhost/sam/service/register-# -> Service registered+sam-node run --control-plane "$URL" --bootstrap-token "$JOIN_TOKEN" \+ --data-dir ~/provider --announce-private=false \+ --config ~/provider-services.yaml &```+Note the node's PeerID from its startup output.+On the **consumer** machine, run a node the same way, then call theservice by peer and name through the local egress proxy:@@ -144,8 +146,8 @@ curl --unix-socket ~/consumer/sam.sock \The request crosses consumer → Cloud Run router (relay circuit) →provider → backend, with mutual Biscuit authentication between the nodes-and policy enforced on the service name. Allow a few seconds after-registration for propagation on first call.+and policy enforced on the service name. Allow a few seconds after the+provider starts for propagation on first call.## 6. Operate with the CLIdiff --git a/tests/e2e/datapath.bats b/tests/e2e/datapath.batsindex 6c49a0cb..c692d140 100644--- a/tests/e2e/datapath.bats+++ b/tests/e2e/datapath.bats@@ -22,38 +22,8 @@ teardown() {local router_peer_idrouter_peer_id=$(cat "/tmp/${MESH_PREFIX}-router-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-- local node2_peer_id- node2_peer_id=$(docker logs "${node2_name}" 2>&1 | grep "PeerID:" | head -n 1 | awk '{print $2}' | tr -d '\r')-- # Explicitly connect Node 1 to Node 2 (DHT auto-discovery is slow/unreliable in this E2E setup)- echo "[$(date +%T)] Explicitly connecting Node 1 to Node 2"- local node2_addr="/dns4/${node2_name}/tcp/5002/p2p/${node2_peer_id}"- run mesh_connect_peer 1 "${node2_addr}"- [[ "$status" -eq 0 ]]-- # Verify connection- mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20- [[ "$status" -eq 0 ]]-- # 1. Setup HTTP Service on Node 1 side- # Start a dummy HTTP server in a separate container+ # Backends exist before the nodes: services are declared in each node's+ # configuration, there is no runtime registration endpoint.echo "[$(date +%T)] Starting dummy HTTP service"docker run -d \--name http-service \@@ -79,71 +49,58 @@ HTTPServer(("0.0.0.0", 8000), S).serve_forever()sleep 1done- # Register HTTP service on Node 1- echo "[$(date +%T)] Registering HTTP service on Node 1"- run docker run --rm --network "${MESH_NETWORK}" python:3.12 python3 -c "-import urllib.request-import json--data = {- \"service\": {- \"type\": \"SERVICE_TYPE_MCP\",- \"name\": \"http-tool\",- \"description\": \"test http service\"- },- \"targetUrl\": \"http://http-service:8000\"-}+ local node1_cfg="${BATS_TEST_TMPDIR}/node1-services.yaml"+ cat > "${node1_cfg}" <<'EOF'+version: "v1alpha1"+services:+ - type: "mcp"+ name: "http-tool"+ description: "test http service"+ target_url: "http://http-service:8000"+EOF++ local node2_cfg="${BATS_TEST_TMPDIR}/node2-services.yaml"+ cat > "${node2_cfg}" <<'EOF'+version: "v1alpha1"+services:+ - type: "mcp"+ name: "stdio-tool"+ description: "test stdio service"+ command: ["sh", "-c", "sleep 1; cat"]+EOF+ # The node container runs as a non-root user; a restrictive umask would+ # otherwise make the mounted config unreadable inside it.+ chmod 644 "${node1_cfg}" "${node2_cfg}"-req = urllib.request.Request(- \"http://${node1_name}:8080/sam/service/register\",- data=json.dumps(data).encode(\"utf-8\"),- headers={- \"X-Sam-Authentication\": \"Bearer secret-token\",- \"Content-Type\": \"application/json\"- }-)-with urllib.request.urlopen(req) as response:- print(response.read().decode(\"utf-8\"))-"- echo "Register HTTP output: $output"- [[ "$status" -eq 0 ]]- [[ "$output" == *"Service registered"* ]]+ # Start Node 1+ echo "[$(date +%T)] Starting Node 1"+ mesh_start_node 1 "--log-level debug" "${node1_cfg}"+ 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')- # 2. Setup Stdio Service on Node 2 side- # Register Stdio service (cat) on Node 2- echo "[$(date +%T)] Registering Stdio service on Node 2"- run docker run --rm --network "${MESH_NETWORK}" python:3.12 python3 -c "-import urllib.request-import json--data = {- 'service': {- 'type': 'SERVICE_TYPE_MCP',- 'name': 'stdio-tool',- 'description': 'test stdio service'- },- 'command': {- 'command': ['sh', '-c', 'sleep 1; cat']- }-}+ # Start Node 2+ echo "[$(date +%T)] Starting Node 2"+ mesh_start_node 2 "--log-level debug" "${node2_cfg}"+ local node2_name="${MESH_PREFIX}-node-2"+ mesh_wait_for_log "${node2_name}" "SAM Node Online" 20+ mesh_wait_for_mcp_ready 2 20-req = urllib.request.Request(- 'http://${node2_name}:8080/sam/service/register',- data=json.dumps(data).encode('utf-8'),- headers={- 'X-Sam-Authentication': 'Bearer secret-token',- 'Content-Type': 'application/json'- }-)-with urllib.request.urlopen(req) as response:- print(response.read().decode('utf-8'))-"- if [[ "$status" -ne 0 ]]; then- echo "Node 2 logs:"- docker logs "${node2_name}"- fi+ local node2_peer_id+ node2_peer_id=$(docker logs "${node2_name}" 2>&1 | grep "PeerID:" | head -n 1 | awk '{print $2}' | tr -d '\r')++ # Explicitly connect Node 1 to Node 2 (DHT auto-discovery is slow/unreliable in this E2E setup)+ echo "[$(date +%T)] Explicitly connecting Node 1 to Node 2"+ local node2_addr="/dns4/${node2_name}/tcp/5002/p2p/${node2_peer_id}"+ run mesh_connect_peer 1 "${node2_addr}"+ [[ "$status" -eq 0 ]]++ # Verify connection+ mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20[[ "$status" -eq 0 ]]- [[ "$output" == *"Service registered"* ]]# 3. Test HTTP Datapath: Node 2 calls Node 1's HTTP serviceecho "[$(date +%T)] Testing HTTP Datapath from Node 2 to Node 1"diff --git a/tests/e2e/relay.bats b/tests/e2e/relay.batsindex 316ba65e..bed05813 100644--- a/tests/e2e/relay.bats+++ b/tests/e2e/relay.bats@@ -74,7 +74,47 @@ teardown() {DISCONNECT_CONTAINERS+=("${oidc_node}:${MESH_NETWORK_2}")fi- mesh_start_node "1" "--enable-relay=true --log-level=debug"+ # HTTP backend on Node 1's side (default network). It exists before the+ # node: services are declared in the node's configuration, there is no+ # runtime registration endpoint.+ docker run -d \+ --name "${MESH_PREFIX}-http-service" \+ --network "${MESH_NETWORK}" \+ python:3.12 python3 -c '+from http.server import HTTPServer, BaseHTTPRequestHandler+class S(BaseHTTPRequestHandler):+ def do_GET(self):+ self.send_response(200)+ self.send_header("Content-type", "application/json")+ self.end_headers()+ self.wfile.write(b"{\"status\":\"success\"}")+HTTPServer(("0.0.0.0", 8000), S).serve_forever()+'+ MESH_CONTAINERS+=("${MESH_PREFIX}-http-service")++ # Wait for http-service to be listening+ local i+ for ((i=0; i<30; i++)); do+ if docker run --rm --network "${MESH_NETWORK}" python:3.12 python3 -c "import urllib.request; urllib.request.urlopen('http://${MESH_PREFIX}-http-service:8000')" >/dev/null 2>&1; then+ break+ fi+ sleep 1+ done++ local node1_cfg="${BATS_TEST_TMPDIR}/node1-services.yaml"+ cat > "${node1_cfg}" <<EOF+version: "v1alpha1"+services:+ - type: "mcp"+ name: "http-tool"+ description: "test http service"+ target_url: "http://${MESH_PREFIX}-http-service:8000"+EOF+ # The node container runs as a non-root user; a restrictive umask would+ # otherwise make the mounted config unreadable inside it.+ chmod 644 "${node1_cfg}"++ mesh_start_node "1" "--enable-relay=true --log-level=debug" "${node1_cfg}"OLD_NET=$MESH_NETWORKMESH_NETWORK=$MESH_NETWORK_2@@ -111,60 +151,6 @@ teardown() {[[ "$status" -eq 0 ]]MESH_NETWORK=$OLD_NET- # 1. Setup HTTP Service on Node 1 side (default network)- docker run -d \- --name "${MESH_PREFIX}-http-service" \- --network "${MESH_NETWORK}" \- python:3.12 python3 -c '-from http.server import HTTPServer, BaseHTTPRequestHandler-class S(BaseHTTPRequestHandler):- def do_GET(self):- self.send_response(200)- self.send_header("Content-type", "application/json")- self.end_headers()- self.wfile.write(b"{\"status\":\"success\"}")-HTTPServer(("0.0.0.0", 8000), S).serve_forever()-'- MESH_CONTAINERS+=("${MESH_PREFIX}-http-service")-- # Wait for http-service to be listening- local i- for ((i=0; i<30; i++)); do- if docker run --rm --network "${MESH_NETWORK}" python:3.12 python3 -c "import urllib.request; urllib.request.urlopen('http://${MESH_PREFIX}-http-service:8000')" >/dev/null 2>&1; then- break- fi- sleep 1- done-- # Register HTTP service on Node 1- run docker run --rm --network "${MESH_NETWORK}" python:3.12 python3 -c "-import urllib.request-import json--data = {- \"service\": {- \"type\": \"SERVICE_TYPE_MCP\",- \"name\": \"http-tool\",- \"description\": \"test http service\"- },- \"targetUrl\": \"http://${MESH_PREFIX}-http-service:8000\"-}--req = urllib.request.Request(- \"http://${MESH_PREFIX}-node-1:8080/sam/service/register\",- data=json.dumps(data).encode('utf-8'),- headers={- \"Content-Type\": \"application/json\",- \"X-Sam-Authentication\": \"Bearer secret-token\"- },- method=\"POST\"-)-with urllib.request.urlopen(req) as response:- print(response.read().decode('utf-8'))-"- [[ "$status" -eq 0 ]]- [[ "$output" == *"Service registered"* ]]-# 2. Test HTTP Datapath: Node 2 calls Node 1's HTTP service via Node 2's egress proxy (isolated network 2)for ((i=0; i<15; i++)); dorun docker run --rm --network "${MESH_NETWORK_2}" python:3.12 python3 -c "diff --git a/tests/e2e/standalone.bats b/tests/e2e/standalone.batsindex 99ebc059..ebfd4964 100644--- a/tests/e2e/standalone.bats+++ b/tests/e2e/standalone.bats@@ -3,7 +3,7 @@# Black-box CUJ for the sam-one all-in-one binary: boot on a random port# published in the banner, join real sam-nodes through it, drive the admin CLI# against the live server, and push a request across the dataplane from node B-# to a smoke HTTP service registered on node A (egress proxy -> router -> A).+# to a smoke HTTP service declared in node A's configuration (egress proxy -> router -> A).# In-process coverage lives in tests/integration/standalone_test.go; this file# only exercises what needs the real binaries.@@ -54,15 +54,17 @@ wait_for_log() {# NODE_<NAME>_PID for teardown. The sidecar serves only on the Unix socket so# two nodes on one host never fight over the default TCP bind, and loopback# addresses must be publishable or peers on one host cannot dial each other.+# Extra arguments are passed through to the node (e.g. --config).start_node() {local name="$1"+ shiftSAM_API_TOKEN=e2e-secret "$SAM_NODE_BINARY" run \--control-plane "$SAM_ONE_URL" \--bootstrap-token "$JOIN_TOKEN" \--data-dir "$TEST_TMPDIR/node-$name" \--bind-addr= \--allow-loopback \- --listen "/ip4/127.0.0.1/tcp/0" > "$TEST_TMPDIR/node-$name.log" 2>&1 &+ --listen "/ip4/127.0.0.1/tcp/0" "$@" > "$TEST_TMPDIR/node-$name.log" 2>&1 &eval "NODE_${name^^}_PID=$!"}@@ -87,14 +89,10 @@ start_node() {# Two real nodes join through the single port with the persisted join token.JOIN_TOKEN="$(cat "$SAM_ONE_DATA/join-token")"[[ "$JOIN_TOKEN" == sam_tok_* ]]- start_node a- start_node b- wait_for_log "$TEST_TMPDIR/node-a.log" "SAM Node Online"- wait_for_log "$TEST_TMPDIR/node-b.log" "SAM Node Online"- peer_a="$(grep -oE 'PeerID: [A-Za-z0-9]+' "$TEST_TMPDIR/node-a.log" | head -1 | cut -d' ' -f2)"- [[ -n "$peer_a" ]]- # Smoke HTTP backend on node A's host, registered as a URL-backed service.+ # Smoke HTTP backend on node A's host, declared as a URL-backed service in+ # node A's configuration: services only exist by declaration at startup,+ # there is no runtime registration endpoint.# -u: unbuffered, or the "Serving HTTP" banner never flushes to the log.mkdir -p "$TEST_TMPDIR/www"echo "sam-one dataplane ok" > "$TEST_TMPDIR/www/hello.txt"@@ -104,14 +102,25 @@ start_node() {wait_for_log "$TEST_TMPDIR/backend.log" "Serving HTTP"backend_port="$(grep -oE 'port [0-9]+' "$TEST_TMPDIR/backend.log" | grep -oE '[0-9]+')"+ cat > "$TEST_TMPDIR/node-a-services.yaml" <<EOF+version: "v1alpha1"+services:+ - type: "mcp"+ name: "smoke"+ description: "e2e smoke backend"+ target_url: "http://127.0.0.1:${backend_port}"+EOF++ start_node a --config "$TEST_TMPDIR/node-a-services.yaml"+ start_node b+ wait_for_log "$TEST_TMPDIR/node-a.log" "SAM Node Online"+ wait_for_log "$TEST_TMPDIR/node-b.log" "SAM Node Online"+ peer_a="$(grep -oE 'PeerID: [A-Za-z0-9]+' "$TEST_TMPDIR/node-a.log" | head -1 | cut -d' ' -f2)"+ [[ -n "$peer_a" ]]+sock_a="$TEST_TMPDIR/node-a/sam.sock"sock_b="$TEST_TMPDIR/node-b/sam.sock"[[ -S "$sock_a" && -S "$sock_b" ]]- register_payload="{\"service\":{\"type\":\"SERVICE_TYPE_MCP\",\"name\":\"smoke\",\"description\":\"e2e smoke backend\"},\"targetUrl\":\"http://127.0.0.1:${backend_port}\"}"- run curl -sf --unix-socket "$sock_a" -X POST \- -H "Content-Type: application/json" -d "$register_payload" \- http://localhost/sam/service/register- [[ "$status" -eq 0 ]]# Node B reaches the service on node A through its egress proxy: the request# crosses B -> router -> A over the mesh, exercising the full dataplane.diff --git a/tests/integration/a2a_test.go b/tests/integration/a2a_test.goindex 06ef32f2..58df896d 100644--- a/tests/integration/a2a_test.go+++ b/tests/integration/a2a_test.go@@ -15,9 +15,7 @@package integration_testimport (- "bytes""context"- "io""iter""net/http""net/http/httptest"@@ -27,8 +25,6 @@ import ("testing""time"- "google.golang.org/protobuf/encoding/protojson"-"github.com/a2aproject/a2a-go/v2/a2a""github.com/a2aproject/a2a-go/v2/a2aclient""github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"@@ -71,39 +67,11 @@ func TestA2ACUJ(t *testing.T) {homeB := t.TempDir()apiToken := "test-token"- t.Log("Starting Node A (provider, region=eu)...")- _ = 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",- "--labels", "region=eu",- )- t.Log("Starting Node B (consumer)...")- _ = 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)-- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))- connectPeer(t, apiAddrB, addrA)- waitForDHTPeers(t, apiAddrA)-- idx := strings.LastIndex(addrA, "/p2p/")- if idx < 0 {- t.Fatalf("no /p2p/ component in peer addr %q", addrA)- }- peerA := addrA[idx+len("/p2p/"):]-// Stock-SDK A2A agent on node A's side: a2asrv serving its card and// echoing message/send. The card deliberately advertises a gRPC// interface, streaming, and a stale signature: the mesh must drop all- // three on regeneration.+ // three on regeneration. The backend exists before the node: services+ // are declared in the node's configuration, never registered at runtime.var sendCount atomic.Int32var sawLabelsHeader atomic.Boolecho := a2asrv.AgentExecutorFunc(func(ctx context.Context, ec *a2asrv.ExecutorContext) iter.Seq2[a2a.Event, error] {@@ -134,7 +102,35 @@ func TestA2ACUJ(t *testing.T) {}))defer agent.Close()- registerA2AService(t, apiAddrA, apiToken, "echo-agent", agent.URL)+ t.Log("Starting Node A (provider, region=eu)...")+ _ = 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",+ "--labels", "region=eu",+ "--config", writeServicesConfig(t, homeA, svcDecl{Type: "a2a", Name: "echo-agent", TargetURL: agent.URL}),+ )+ t.Log("Starting Node B (consumer)...")+ _ = 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)++ addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))+ connectPeer(t, apiAddrB, addrA)+ waitForDHTPeers(t, apiAddrA)++ idx := strings.LastIndex(addrA, "/p2p/")+ if idx < 0 {+ t.Fatalf("no /p2p/ component in peer addr %q", addrA)+ }+ peerA := addrA[idx+len("/p2p/"):]meshBase := "http://" + apiAddrB + "/sam/" + peerA + "/a2a/echo-agent"ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)@@ -219,32 +215,3 @@ func TestA2ACUJ(t *testing.T) {t.Log("A2A CUJ test passed.")}--func registerA2AService(t *testing.T, apiAddr, token, serviceName, targetURL string) {- t.Helper()- reqData := &api.RegisterServiceRequest{- Service: &api.ServiceInfo{- Type: api.ServiceType_SERVICE_TYPE_A2A,- Name: serviceName,- Description: "test a2a agent",- },- Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: targetURL},- }- body, err := protojson.Marshal(reqData)- if err != nil {- t.Fatal(err)- }- req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/register", bytes.NewBuffer(body))- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)- req.Header.Set("Content-Type", "application/json")-- resp, err := http.DefaultClient.Do(req)- if err != nil {- t.Fatalf("Failed to register a2a service: %v", err)- }- defer func() { _ = resp.Body.Close() }()- if resp.StatusCode != http.StatusOK {- bodyBytes, _ := io.ReadAll(resp.Body)- t.Fatalf("Register a2a service failed with status: %d, body: %s", resp.StatusCode, string(bodyBytes))- }-}diff --git a/tests/integration/agent_policy_test.go b/tests/integration/agent_policy_test.goindex a91fdca3..087486c4 100644--- a/tests/integration/agent_policy_test.go+++ b/tests/integration/agent_policy_test.go@@ -45,6 +45,16 @@ func TestAgentPolicyCUJ(t *testing.T) {homeB := t.TempDir()apiToken := "test-token"+ // Backends exist before the node: services are declared in node A's+ // configuration alongside its attenuation, never registered at runtime.+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(`{"object":"list","data":[{"id":"test-model"}]}`))+ }))+ defer backend.Close()++ tools := httptest.NewServer(newBoundaryMCPHandler(t))+ defer tools.Close()+// Only agents under prod.acme.example may reach this node's services. The// suffix is matched with a leading dot so a lookalike authority such as// "evil-prod.acme.example" cannot satisfy it.@@ -53,6 +63,15 @@ func TestAgentPolicyCUJ(t *testing.T) {attenuation:checks:- 'check if agent($a), $a.ends_with(".prod.acme.example")'+services:+ - type: "inference"+ name: "test-llm"+ description: "test inference backend"+ target_url: "`+backend.URL+`"+ - type: "mcp"+ name: "calc"+ description: "test mcp backend"+ target_url: "`+tools.URL+`"`), 0600); err != nil {t.Fatalf("WriteFile: %v", err)}@@ -86,13 +105,6 @@ attenuation:connectPeer(t, apiAddrB, addrA)waitForDHTPeers(t, apiAddrA)- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte(`{"object":"list","data":[{"id":"test-model"}]}`))- }))- defer backend.Close()-- registerInferenceService(t, apiAddrA, apiToken, "test-llm", backend.URL)-// Not waitForFacadeModel: node A's own catalog probe carries no agent, so a// provider demanding one refuses it and its models never appear in a peer's// /v1/models listing. That is a real consequence of this policy shape, not a@@ -153,10 +165,6 @@ attenuation:// AuthFrame rather than HTTP headers, so this is a genuinely separate path// and used to be unattributed while inference was not.t.Run("tool calls carry the agent too", func(t *testing.T) {- tools := httptest.NewServer(newBoundaryMCPHandler(t))- defer tools.Close()- registerService(t, apiAddrA, apiToken, "calc", tools.URL)-peerA := extractPeerID(addrA)for i, tc := range []struct {diff --git a/tests/integration/auth_test.go b/tests/integration/auth_test.goindex 71a3d34d..39aa533c 100644--- a/tests/integration/auth_test.go+++ b/tests/integration/auth_test.go@@ -91,14 +91,14 @@ func TestNodeAuthEnforcementIntegration(t *testing.T) {}{{"healthz is public", "GET", "/healthz", http.StatusOK, false},{"readyz is public", "GET", "/readyz", http.StatusOK, false},- {"register is protected", "POST", "/sam/service/register", http.StatusUnauthorized, false},- {"unregister is protected", "POST", "/sam/service/unregister", http.StatusUnauthorized, false},+ // Services are declared in configuration only: the former runtime+ // registration endpoints are gone, so /sam/service/register is just+ // another egress-proxy path behind auth like any /sam/ path.{"discover is protected", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusUnauthorized, false},{"egress proxy is protected", "GET", "/sam/", http.StatusUnauthorized, false},+ {"register path is protected like any egress path", "POST", "/sam/service/register", http.StatusUnauthorized, false},{"mcp root is protected", "GET", "/mcp", http.StatusUnauthorized, false},- {"register with token (bad req)", "POST", "/sam/service/register", http.StatusBadRequest, true},- {"unregister with token (bad req)", "POST", "/sam/service/unregister", http.StatusBadRequest, true},// /sam/service/discover expects node to be connected.{"discover with token", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusOK, true},{"mcp root with token", "GET", "/mcp", http.StatusBadRequest, true},diff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.goindex ba976ced..59db9619 100644--- a/tests/integration/catalog_test.go+++ b/tests/integration/catalog_test.go@@ -17,6 +17,7 @@ package integration_testimport ("context""encoding/json"+ "fmt""net/http""os""os/exec"@@ -40,6 +41,40 @@ func tokenPath(t *testing.T, secret string) string {return p}+// svcDecl is one service entry for writeServicesConfig.+type svcDecl struct {+ Type string+ Name string+ TargetURL string+ Command []string+}++// writeServicesConfig renders a node config file declaring the given+// services. Services only exist by declaration at startup: there is no+// runtime registration surface, so backends must be up before the node.+func writeServicesConfig(t *testing.T, dir string, services ...svcDecl) string {+ t.Helper()+ var b strings.Builder+ b.WriteString("version: \"v1alpha1\"\nservices:\n")+ for _, s := range services {+ fmt.Fprintf(&b, " - type: %q\n name: %q\n description: \"integration test service\"\n", s.Type, s.Name)+ if s.TargetURL != "" {+ fmt.Fprintf(&b, " target_url: %q\n", s.TargetURL)+ }+ if len(s.Command) > 0 {+ b.WriteString(" command:\n")+ for _, c := range s.Command {+ fmt.Fprintf(&b, " - %q\n", c)+ }+ }+ }+ p := filepath.Join(dir, "services-config.yaml")+ if err := os.WriteFile(p, []byte(b.String()), 0o600); err != nil {+ t.Fatalf("write services config: %v", err)+ }+ return p+}+func startBackgroundNode(t *testing.T, nodeBin string, routerAddr string, homeDir string, args ...string) *exec.Cmd {t.Helper()env := append(os.Environ(),diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.goindex 6b60ed82..2453dfdc 100644--- a/tests/integration/datapath_test.go+++ b/tests/integration/datapath_test.go@@ -28,7 +28,6 @@ import ("time""github.com/google/sam/api"- "google.golang.org/protobuf/encoding/protojson")func TestIntegrationStdioDatapath(t *testing.T) {@@ -40,6 +39,11 @@ func TestIntegrationStdioDatapath(t *testing.T) {apiToken := "test-token"+ // The stdio service is declared in node A's configuration; there is no+ // runtime registration.+ serviceName := "stdio-tool"+ cfgA := writeServicesConfig(t, homeA, svcDecl{Type: "mcp", Name: serviceName, Command: []string{"cat"}})+// Start Node At.Log("Starting Node A...")_ = startBackgroundNode(t, nodeBin, routerAddr, homeA,@@ -48,6 +52,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {"--discovery-interval", "100ms","--bind-addr", "127.0.0.1:0","--api-token-path", tokenPath(t, apiToken),+ "--config", cfgA,)// Start Node B@@ -74,38 +79,6 @@ func TestIntegrationStdioDatapath(t *testing.T) {// Connect Node B to Node AconnectPeer(t, actualApiAddrB, addrA)- // Register Stdio service on Node A- serviceName := "stdio-tool"- reqData := &api.RegisterServiceRequest{- Service: &api.ServiceInfo{- Type: api.ServiceType_SERVICE_TYPE_MCP,- Name: serviceName,- Description: "test stdio service",- },- Backend: &api.RegisterServiceRequest_Command{- Command: &api.CommandBackend{- Command: []string{"cat"},- },- },- }- body, err := protojson.Marshal(reqData)- if err != nil {- t.Fatal(err)- }-- req, _ := http.NewRequest("POST", "http://"+actualApiAddrA+"/sam/service/register", bytes.NewBuffer(body))- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)- req.Header.Set("Content-Type", "application/json")-- resp, err := http.DefaultClient.Do(req)- if err != nil {- t.Fatal(err)- }- _ = resp.Body.Close()- if resp.StatusCode != http.StatusOK {- t.Fatalf("Failed to register service: %d", resp.StatusCode)- }-// Wait for propagation (optional, but safe)time.Sleep(1 * time.Second)@@ -120,6 +93,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {testMessage := `{"jsonrpc":"2.0","method":"ping","id":1}`var postResp *http.Response+ var err errorfor i := 0; i < 3; i++ {postReq, _ := http.NewRequest("POST", postURL, bytes.NewBufferString(testMessage))postReq.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)@@ -165,6 +139,31 @@ func TestIntegrationHTTPDatapath(t *testing.T) {apiToken := "test-token"+ // Start a dummy HTTP server on Node A's host (simulating local service).+ // It captures the headers it receives so we can assert what actually+ // crosses the mesh: verified caller identity in, biscuit stripped. The+ // backend exists before the node: services are declared in the node's+ // configuration, never registered at runtime.+ expectedBody := `{"status":"success"}`+ var (+ hdrMu sync.Mutex+ gotPeerID string+ gotBiscuit string+ )+ dummyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hdrMu.Lock()+ gotPeerID = r.Header.Get(api.HeaderPeerID)+ gotBiscuit = r.Header.Get(api.HeaderSamBiscuit)+ hdrMu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(expectedBody))+ }))+ defer dummyServer.Close()++ serviceName := "http-tool"+ cfgA := writeServicesConfig(t, homeA, svcDecl{Type: "mcp", Name: serviceName, TargetURL: dummyServer.URL})+// Start Node At.Log("Starting Node A...")_ = startBackgroundNode(t, nodeBin, routerAddr, homeA,@@ -173,6 +172,7 @@ func TestIntegrationHTTPDatapath(t *testing.T) {"--discovery-interval", "100ms","--bind-addr", "127.0.0.1:0","--api-token-path", tokenPath(t, apiToken),+ "--config", cfgA,)// Start Node B@@ -201,54 +201,6 @@ func TestIntegrationHTTPDatapath(t *testing.T) {// Connect Node B to Node AconnectPeer(t, actualApiAddrB, addrA)- // Start a dummy HTTP server on Node A's host (simulating local service).- // It captures the headers it receives so we can assert what actually- // crosses the mesh: verified caller identity in, biscuit stripped.- expectedBody := `{"status":"success"}`- var (- hdrMu sync.Mutex- gotPeerID string- gotBiscuit string- )- dummyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- hdrMu.Lock()- gotPeerID = r.Header.Get(api.HeaderPeerID)- gotBiscuit = r.Header.Get(api.HeaderSamBiscuit)- hdrMu.Unlock()- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusOK)- _, _ = w.Write([]byte(expectedBody))- }))- defer dummyServer.Close()-- // Register HTTP service on Node A- serviceName := "http-tool"- reqData := &api.RegisterServiceRequest{- Service: &api.ServiceInfo{- Type: api.ServiceType_SERVICE_TYPE_MCP,- Name: serviceName,- Description: "test http service",- },- Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: dummyServer.URL},- }- body, err := protojson.Marshal(reqData)- if err != nil {- t.Fatal(err)- }-- req, _ := http.NewRequest("POST", "http://"+actualApiAddrA+"/sam/service/register", bytes.NewBuffer(body))- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)- req.Header.Set("Content-Type", "application/json")-- resp, err := http.DefaultClient.Do(req)- if err != nil {- t.Fatal(err)- }- _ = resp.Body.Close()- if resp.StatusCode != http.StatusOK {- t.Fatalf("Failed to register service: %d", resp.StatusCode)- }-// Wait for propagationtime.Sleep(1 * time.Second)@@ -257,6 +209,7 @@ func TestIntegrationHTTPDatapath(t *testing.T) {client := &http.Client{}var httpResp *http.Response+ var err errorfor i := 0; i < 3; i++ {req, _ := http.NewRequest("GET", url, nil)req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)diff --git a/tests/integration/federation_test.go b/tests/integration/federation_test.goindex f587d212..d8b5aed3 100644--- a/tests/integration/federation_test.go+++ b/tests/integration/federation_test.go@@ -191,6 +191,23 @@ roles:"roles": []string{api.RoleNode},})+ // A real MCP backend: the node probes it before advertising, so a stub+ // returning a canned JSON-RPC body is deliberately never discoverable.+ // Backends exist before node A: its services are declared in+ // configuration, never registered at runtime.+ mcpServer := httptest.NewServer(newBoundaryMCPHandler(t))+ t.Cleanup(func() { mcpServer.Close() })++ // A backend that is not an MCP server. It is never advertised, but stays+ // reachable when addressed explicitly, which is what the datapath below+ // exercises: the proxy is a pipe and does not interpret what it carries.+ rawServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"jsonrpc": "2.0", "id": 1, "result": {"success": true}}`))+ }))+ t.Cleanup(func() { rawServer.Close() })+// Node A connects to Router A (via shared CP)apiPortA := getFreePort(t)nodeACmd := exec.Command(nodeBin, "run", "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),@@ -203,6 +220,9 @@ roles:"--discovery-interval", "100ms","--enable-relay=true","--allow-loopback=true",+ "--config", writeServicesConfig(t, tmpDir,+ svcDecl{Type: "mcp", Name: "federated-tool", TargetURL: mcpServer.URL},+ svcDecl{Type: "mcp", Name: "raw-pipe", TargetURL: rawServer.URL}),)nodeACmd.Env = append(os.Environ(), "SAM_TEST_DNS_SERVER="+dnsServer.conn.LocalAddr().String())var nodeStdoutA, nodeStderrA safeBuffer@@ -238,25 +258,7 @@ roles:waitForDHTReady(t, clientBin, apiPortA, "tokenA")waitForDHTReady(t, clientBin, apiPortB, "tokenB")- // A real MCP backend: the node probes it before advertising, so a stub- // returning a canned JSON-RPC body is deliberately never discoverable.- mcpServer := httptest.NewServer(newBoundaryMCPHandler(t))- t.Cleanup(func() { mcpServer.Close() })-- // A backend that is not an MCP server. It is never advertised, but stays- // reachable when addressed explicitly, which is what the datapath below- // exercises: the proxy is a pipe and does not interpret what it carries.- rawServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusOK)- _, _ = w.Write([]byte(`{"jsonrpc": "2.0", "id": 1, "result": {"success": true}}`))- }))- t.Cleanup(func() { rawServer.Close() })-- // Publish a service on Node A- t.Log("Publishing tool on Node A...")- registerService(t, fmt.Sprintf("127.0.0.1:%d", apiPortA), "tokenA", "federated-tool", mcpServer.URL)- registerService(t, fmt.Sprintf("127.0.0.1:%d", apiPortA), "tokenA", "raw-pipe", rawServer.URL)+ t.Log("Waiting for Node A's declared services to propagate...")time.Sleep(2 * time.Second)// Search for the service from Node Bdiff --git a/tests/integration/openai_facade_test.go b/tests/integration/openai_facade_test.goindex 1f90706b..59578700 100644--- a/tests/integration/openai_facade_test.go+++ b/tests/integration/openai_facade_test.go@@ -15,7 +15,6 @@package integration_testimport (- "bytes""encoding/json""io""net/http"@@ -26,8 +25,6 @@ import ("testing""time"- "google.golang.org/protobuf/encoding/protojson"-"github.com/google/sam/api")@@ -43,30 +40,9 @@ func TestOpenAIFacadeCUJ(t *testing.T) {homeB := t.TempDir()apiToken := "test-token"- t.Log("Starting Node A (provider)...")- _ = 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",- "--labels", "region=eu", // exercise the operator label claim end to end- )- t.Log("Starting Node B (consumer)...")- _ = 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)-- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))- connectPeer(t, apiAddrB, addrA)- waitForDHTPeers(t, apiAddrA)-- // Fake OpenAI-compatible backend on node A's side.+ // Fake OpenAI-compatible backend on node A's side. The backend exists+ // before the node: services are declared in the node's configuration,+ // never registered at runtime.var sawSidecarToken, sawSamAuthHeader atomic.Boolbackend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if strings.Contains(r.Header.Get("Authorization"), apiToken) {@@ -98,7 +74,29 @@ func TestOpenAIFacadeCUJ(t *testing.T) {}))defer backend.Close()- registerInferenceService(t, apiAddrA, apiToken, "test-llm", backend.URL)+ t.Log("Starting Node A (provider)...")+ _ = 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",+ "--labels", "region=eu", // exercise the operator label claim end to end+ "--config", writeServicesConfig(t, homeA, svcDecl{Type: "inference", Name: "test-llm", TargetURL: backend.URL}),+ )+ t.Log("Starting Node B (consumer)...")+ _ = 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)++ addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))+ connectPeer(t, apiAddrB, addrA)+ waitForDHTPeers(t, apiAddrA)// CUJ step 1: the model shows up on the consumer's /v1/models.waitForFacadeModel(t, apiAddrB, apiToken, "test-model")@@ -197,35 +195,6 @@ func TestOpenAIFacadeCUJ(t *testing.T) {t.Log("OpenAI facade CUJ test passed.")}-func registerInferenceService(t *testing.T, apiAddr, token, serviceName, targetURL string) {- t.Helper()- reqData := &api.RegisterServiceRequest{- Service: &api.ServiceInfo{- Type: api.ServiceType_SERVICE_TYPE_INFERENCE,- Name: serviceName,- Description: "test inference backend",- },- Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: targetURL},- }- body, err := protojson.Marshal(reqData)- if err != nil {- t.Fatal(err)- }- req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/register", bytes.NewBuffer(body))- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)- req.Header.Set("Content-Type", "application/json")-- resp, err := http.DefaultClient.Do(req)- if err != nil {- t.Fatalf("Failed to register inference service: %v", err)- }- defer func() { _ = resp.Body.Close() }()- if resp.StatusCode != http.StatusOK {- bodyBytes, _ := io.ReadAll(resp.Body)- t.Fatalf("Register inference service failed with status: %d, body: %s", resp.StatusCode, string(bodyBytes))- }-}-// waitForDHTPeers polls get_mesh_info until the node sees DHT peers.func waitForDHTPeers(t *testing.T, apiAddr string) {t.Helper()diff --git a/tests/integration/sandbox_boundary_test.go b/tests/integration/sandbox_boundary_test.goindex 8ad453ec..df69500d 100644--- a/tests/integration/sandbox_boundary_test.go+++ b/tests/integration/sandbox_boundary_test.go@@ -60,29 +60,8 @@ func TestSandboxBoundaryCUJ(t *testing.T) {nodeSocket := filepath.Join(sockDir, "node.sock")agentSocket := filepath.Join(sockDir, "agent.sock")- t.Log("Starting node A (provider) and node B (the gateway's node)...")- _ = 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",- )- _ = 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)-- addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))- peerA := extractPeerID(addrA)- connectPeer(t, apiAddrB, addrA)- waitForDHTPeers(t, apiAddrA)-+ // Backends exist before node A: its services are declared in+ // configuration, never registered at runtime.inference := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {case "/v1/models":@@ -105,11 +84,35 @@ func TestSandboxBoundaryCUJ(t *testing.T) {}))defer external.Close()- registerInferenceService(t, apiAddrA, apiToken, "test-llm", inference.URL)- registerService(t, apiAddrA, apiToken, "calc", tools.URL)+ t.Log("Starting node A (provider) and node B (the gateway's node)...")+ _ = 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", writeServicesConfig(t, homeA,+ svcDecl{Type: "inference", Name: "test-llm", TargetURL: inference.URL},+ svcDecl{Type: "mcp", Name: "calc", TargetURL: tools.URL}),+ )+ _ = 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)++ addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))+ peerA := extractPeerID(addrA)+ connectPeer(t, apiAddrB, addrA)+ waitForDHTPeers(t, apiAddrA)- // The model reaching node B's facade means A's registration has propagated,- // so the boundary cases below do not each have to wait for discovery.+ // The model reaching node B's facade means A's declared services have+ // propagated, so the boundary cases below do not each have to wait for+ // discovery.waitForFacadeModel(t, apiAddrB, apiToken, "test-model")startBoundary(t, agentSocket, nodeSocket, "127.0.0.1")diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.goindex 403f31db..e6981b70 100644--- a/tests/integration/service_discovery_test.go+++ b/tests/integration/service_discovery_test.go@@ -16,7 +16,6 @@ package integration_testimport ("bufio"- "bytes""encoding/json""io""net/http"@@ -26,8 +25,6 @@ import ("testing""time"- "google.golang.org/protobuf/encoding/protojson"-"github.com/google/sam/api""github.com/libp2p/go-libp2p/core/peer")@@ -41,6 +38,14 @@ func TestServiceDiscovery(t *testing.T) {apiToken := "test-token"+ // A real MCP backend: the node probes it before advertising, so a stub that+ // cannot complete an initialize is deliberately never discoverable. It+ // exists before node A: services are declared in configuration, never+ // registered at runtime.+ mockServer := httptest.NewServer(newBoundaryMCPHandler(t))+ defer mockServer.Close()+ serviceName := "github-tools"+// Start Node At.Log("Starting Node A...")_ = startBackgroundNode(t, nodeBin, routerAddr, homeA,@@ -49,6 +54,7 @@ func TestServiceDiscovery(t *testing.T) {"--discovery-interval", "100ms","--bind-addr", "127.0.0.1:0","--api-token-path", tokenPath(t, apiToken),+ "--config", writeServicesConfig(t, homeA, svcDecl{Type: "mcp", Name: serviceName, TargetURL: mockServer.URL}),)// Start Node B@@ -95,15 +101,6 @@ func TestServiceDiscovery(t *testing.T) {t.Fatalf("DHT not ready on Node A (size 0)")}- // A real MCP backend: the node probes it before advertising, so a stub that- // cannot complete an initialize is deliberately never discoverable.- mockServer := httptest.NewServer(newBoundaryMCPHandler(t))- defer mockServer.Close()-- // Agent A registers a service- serviceName := "mcp:github-tools"- registerService(t, actualApiAddrA, apiToken, serviceName, mockServer.URL)-// Wait for DHT propagationt.Log("Waiting for DHT propagation...")time.Sleep(2 * time.Second)@@ -130,9 +127,6 @@ func TestServiceDiscovery(t *testing.T) {t.Fatalf("Agent B did not discover Agent A as provider. Providers: %v", providers)}- // Agent A unregisters the service- unregisterService(t, actualApiAddrA, apiToken, serviceName)-t.Log("Service discovery test passed.")}@@ -145,6 +139,14 @@ func TestServiceDiscoveryStreaming(t *testing.T) {apiToken := "test-token"+ // A real MCP backend: the node probes it before advertising, so a stub that+ // cannot complete an initialize is deliberately never discoverable. It+ // exists before node A: services are declared in configuration, never+ // registered at runtime.+ mockServer := httptest.NewServer(newBoundaryMCPHandler(t))+ defer mockServer.Close()+ serviceName := "github-tools"+// Start Node At.Log("Starting Node A...")_ = startBackgroundNode(t, nodeBin, routerAddr, homeA,@@ -153,6 +155,7 @@ func TestServiceDiscoveryStreaming(t *testing.T) {"--discovery-interval", "100ms","--bind-addr", "127.0.0.1:0","--api-token-path", tokenPath(t, apiToken),+ "--config", writeServicesConfig(t, homeA, svcDecl{Type: "mcp", Name: serviceName, TargetURL: mockServer.URL}),)// Start Node B@@ -198,15 +201,6 @@ func TestServiceDiscoveryStreaming(t *testing.T) {t.Fatalf("DHT not ready on Node A")}- // A real MCP backend: the node probes it before advertising, so a stub that- // cannot complete an initialize is deliberately never discoverable.- mockServer := httptest.NewServer(newBoundaryMCPHandler(t))- defer mockServer.Close()-- // Agent A registers a service- serviceName := "mcp:github-tools"- registerService(t, actualApiAddrA, apiToken, serviceName, mockServer.URL)-// Wait for DHT propagationt.Log("Waiting for DHT propagation...")time.Sleep(2 * time.Second)@@ -279,9 +273,6 @@ func TestServiceDiscoveryStreaming(t *testing.T) {if !foundStreamed {t.Fatalf("Failed to stream and find provider Node A in SSE results")}-- // Agent A unregisters the service- unregisterService(t, actualApiAddrA, apiToken, serviceName)}func waitForAPI(t *testing.T, addr string) {@@ -298,53 +289,6 @@ func waitForAPI(t *testing.T, addr string) {t.Fatalf("timeout waiting for API at %s", addr)}-func registerService(t *testing.T, apiAddr, token, serviceName, targetURL string) {- t.Helper()- reqData := &api.RegisterServiceRequest{- Service: &api.ServiceInfo{- Type: api.ServiceType_SERVICE_TYPE_MCP,- Name: serviceName,- Description: "test desc",- },- Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: targetURL},- }- body, err := protojson.Marshal(reqData)- if err != nil {- t.Fatal(err)- }- req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/register", bytes.NewBuffer(body))- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)- req.Header.Set("Content-Type", "application/json")-- resp, err := http.DefaultClient.Do(req)- if err != nil {- t.Fatalf("Failed to register service: %v", err)- }- defer func() { _ = resp.Body.Close() }()- if resp.StatusCode != http.StatusOK {- bodyBytes, _ := io.ReadAll(resp.Body)- t.Fatalf("Register service failed with status: %d, body: %s", resp.StatusCode, string(bodyBytes))- }-}--func unregisterService(t *testing.T, apiAddr, token, serviceName string) {- t.Helper()- reqBody := map[string]string{"Name": serviceName}- body, _ := json.Marshal(reqBody)- req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/unregister", bytes.NewBuffer(body))- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)- req.Header.Set("Content-Type", "application/json")-- resp, err := http.DefaultClient.Do(req)- if err != nil {- t.Fatalf("Failed to unregister service: %v", err)- }- defer func() { _ = resp.Body.Close() }()- if resp.StatusCode != http.StatusOK {- t.Fatalf("Unregister service failed with status: %d", resp.StatusCode)- }-}-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)