Skip to content

Agent Mesh

node: type-bound dispatch, per-request bridge routing, proxy hygiene (audit PR 4)

Antonio Ojea3bccddcc1b73
diff --git a/internal/node/gate.go b/internal/node/gate.go
index f83c38ac..84ab2181 100644
--- a/internal/node/gate.go
+++ b/internal/node/gate.go
@@ -75,27 +75,24 @@ func (g *nodeConnGate) InterceptSecured(dir network.Direction, p peer.ID, n netw
func (n *SamNode) HandleMCPStream(s network.Stream, reqCtx RequestContext) {
// If the TargetService is for a registered local backend, dumb-pipe proxy to it.
target := reqCtx.Target
- _, targetName := api.ParseServiceTarget(target)
+ targetType, targetName := api.ParseServiceTarget(target)
if target != "" && targetName != api.CatalogTarget {
if n.services == nil {
logger.Errorf("[MCP] Service registry is not initialized")
_ = s.Reset()
return
}
- svc, ok := n.services.Get(targetName)
- if !ok && targetName != target {
- svc, ok = n.services.Get(target)
- }
- if ok {
- mcpSvc, isMcp := svc.(*MCPService)
- if isMcp {
- mcpSvc.HandleStreamPassThrough(s)
- return
+ // The policy passed on the type the caller named; this stream only
+ // carries MCP, so anything else is a type-confusion attempt.
+ if t, err := api.ParseServiceType(targetType); err == nil && t == api.ServiceType_SERVICE_TYPE_MCP {
+ if svc, ok := n.services.GetTyped(t, targetName); ok {
+ if mcpSvc, isMcp := svc.(*MCPService); isMcp {
+ mcpSvc.HandleStreamPassThrough(s)
+ return
+ }
}
}
- // If service not found or not an MCPService, we fall through or close it.
- // For now, close the stream if target is invalid.
- logger.Warnf("[MCP] Client requested unknown target service %q, closing stream", target)
+ logger.Warnf("[MCP] Client requested unknown target service %q, closing stream", truncateForLog(target))
_ = s.Reset()
return
}
@@ -121,7 +118,7 @@ func (n *SamNode) HandleMCPStream(s network.Stream, reqCtx RequestContext) {
mcp.AddTool(server, &mcp.Tool{
Name: "get_mesh_info",
Description: "Get information about the mesh network",
- }, n.handleGetMeshInfo)
+ }, n.handleGetMeshInfoRemote)
ctx := context.Background()
if err := server.Run(ctx, transport); err != nil {
diff --git a/internal/node/gate_test.go b/internal/node/gate_test.go
index 8b8e87b7..121ca3d3 100644
--- a/internal/node/gate_test.go
+++ b/internal/node/gate_test.go
@@ -217,7 +217,7 @@ func TestHandleMCPStream_DumbPipeProxy(t *testing.T) {
// Bypass biscuit auth by exposing HandleMCPStream on a test-only protocol.
nodeA.Host.SetStreamHandler(testMCPProtocol, func(s network.Stream) {
- nodeA.HandleMCPStream(s, RequestContext{Target: "code-reviewer"})
+ nodeA.HandleMCPStream(s, RequestContext{Target: "mcp://code-reviewer"})
})
if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil {
@@ -291,7 +291,7 @@ func TestHandleMCPStream_ForwarderRoutesCalls(t *testing.T) {
t.Cleanup(func() { _ = svc.Teardown() })
nodeA.Host.SetStreamHandler(testMCPProtocol, func(s network.Stream) {
- nodeA.HandleMCPStream(s, RequestContext{Target: "svc"})
+ nodeA.HandleMCPStream(s, RequestContext{Target: "mcp://svc"})
})
if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil {
@@ -431,7 +431,7 @@ func TestHandleStreamPassThrough_BackendEOFDoesNotDropInFlightResponse(t *testin
t.Cleanup(func() { _ = svc.Teardown() })
nodeA.Host.SetStreamHandler(testMCPProtocol, func(s network.Stream) {
- nodeA.HandleMCPStream(s, RequestContext{Target: "svc"})
+ nodeA.HandleMCPStream(s, RequestContext{Target: "mcp://svc"})
})
if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil {
@@ -514,7 +514,7 @@ func TestHandleStreamPassThrough_SlowBackendDoesNotHitDrainTimeout(t *testing.T)
t.Cleanup(func() { _ = svc.Teardown() })
nodeA.Host.SetStreamHandler(testMCPProtocol, func(s network.Stream) {
- nodeA.HandleMCPStream(s, RequestContext{Target: "slow-svc"})
+ nodeA.HandleMCPStream(s, RequestContext{Target: "mcp://slow-svc"})
})
if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil {
diff --git a/internal/node/inference_service.go b/internal/node/inference_service.go
index 3d27ae0d..6c94682b 100644
--- a/internal/node/inference_service.go
+++ b/internal/node/inference_service.go
@@ -128,6 +128,11 @@ type inferenceTransport struct {
func (t *inferenceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
attemptReq := req.Clone(req.Context())
attemptReq.Header.Del("Accept-Encoding") // Prevent gzipped response from breaking token tracking
+ // A Director proxy does not manage X-Forwarded-For, and RemoteAddr here is
+ // a peer id, so an inbound value would reach the backend as-is.
+ attemptReq.Header.Del("X-Forwarded-For")
+ attemptReq.Header.Del("X-Forwarded-Host")
+ attemptReq.Header.Del("X-Forwarded-Proto")
attemptReq.URL.Scheme = t.backend.Scheme
attemptReq.URL.Host = t.backend.Host
diff --git a/internal/node/mcp_handlers.go b/internal/node/mcp_handlers.go
index 1246b1df..60e081ae 100644
--- a/internal/node/mcp_handlers.go
+++ b/internal/node/mcp_handlers.go
@@ -203,6 +203,26 @@ func (n *SamNode) handleGetMeshInfo(ctx context.Context, req *mcp.CallToolReques
}, nil, nil
}
+// handleGetMeshInfoRemote is get_mesh_info as served to other peers over the
+// catalog stream: the local socket path, the router and the connected-peer
+// list are this node's business, not a remote caller's.
+func (n *SamNode) handleGetMeshInfoRemote(ctx context.Context, req *mcp.CallToolRequest, params GetMeshInfoParams) (*mcp.CallToolResult, any, error) {
+ full, err := n.meshInfo()
+ if err != nil {
+ return nil, nil, err
+ }
+ responseBytes, err := json.Marshal(struct {
+ PeerID string `json:"peer_id"`
+ DHTSize int `json:"dht_size"`
+ }{PeerID: full.PeerID, DHTSize: full.DHTSize})
+ if err != nil {
+ return nil, nil, err
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: string(responseBytes)}},
+ }, nil, nil
+}
+
// CallRemoteToolParams defines the parameters for the call_remote_tool tool.
//
// Arguments is a JSON object whose shape matches the target server's
diff --git a/internal/node/mcp_handlers_test.go b/internal/node/mcp_handlers_test.go
index 345b624a..4ea0a7e8 100644
--- a/internal/node/mcp_handlers_test.go
+++ b/internal/node/mcp_handlers_test.go
@@ -333,17 +333,27 @@ func TestHandleFindRemoteTools_MeshWide(t *testing.T) {
t.Fatalf("RegisterService B: %v", err)
}
if err := nodeC.RegisterService(ctx, &api.RegisterServiceRequest{
- Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "mcp://summarizer"},
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "summarizer"},
Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: cSrv.URL},
}); err != nil {
t.Fatalf("RegisterService C: %v", err)
}
if err := nodeD.RegisterService(ctx, &api.RegisterServiceRequest{
- Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "plugin://linter"},
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "linter"},
Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: dSrv.URL},
}); err != nil {
t.Fatalf("RegisterService D: %v", err)
}
+ // A name that carries its own scheme used to be accepted and reached via
+ // a name-only fallback that ignored the type the policy was evaluated on.
+ for _, legacy := range []string{"mcp://summarizer", "plugin://linter"} {
+ if err := nodeD.RegisterService(ctx, &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: legacy},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: dSrv.URL},
+ }); err == nil {
+ t.Errorf("service name %q was accepted", legacy)
+ }
+ }
// Direct fan-out test: invoke fetchRemoteToolCatalogue for peers,
// confirm they return their tools.
@@ -365,17 +375,10 @@ func TestHandleFindRemoteTools_MeshWide(t *testing.T) {
gotNames[tool.ToolName] = true
}
- // Test permutation 1: no prefix gets "mcp://" automatically prepended.
- if !gotNames["mcp://code-reviewer/review_pr"] {
- t.Errorf("missing mcp://code-reviewer/review_pr; got %v", gotNames)
- }
- // Test permutation 2: "mcp://" prefix is preserved.
- if !gotNames["mcp://summarizer/summarize"] {
- t.Errorf("missing mcp://summarizer/summarize; got %v", gotNames)
- }
- // Test permutation 3: custom namespace prefix is preserved.
- if !gotNames["plugin://linter/lint"] {
- t.Errorf("missing plugin://linter/lint; got %v", gotNames)
+ for _, want := range []string{"mcp://code-reviewer/review_pr", "mcp://summarizer/summarize", "mcp://linter/lint"} {
+ if !gotNames[want] {
+ t.Errorf("missing %s; got %v", want, gotNames)
+ }
}
}
diff --git a/internal/node/node.go b/internal/node/node.go
index 7a336e60..f2c91186 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -2011,6 +2011,12 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
// The path is remote-controlled and the peer is not yet authorized:
// it is logged only after VerifyBiscuitToken passes.
path := r.URL.Path
+ // Policy is decided on the /{type}/{name} prefix; a ".." segment in
+ // what follows could resolve to a sibling service on a shared backend.
+ if hasDotSegment(path) {
+ http.Error(w, "Invalid path", http.StatusBadRequest)
+ return
+ }
parts := strings.SplitN(strings.TrimPrefix(path, "/"), "/", 3)
if len(parts) < 2 {
http.Error(w, "Invalid path", http.StatusBadRequest)
@@ -2074,9 +2080,11 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
r.Header.Del(api.HeaderSamNoTrailingSlash)
r.Header.Set(api.HeaderPeerID, remotePeer.String())
- svc, ok := n.services.Get(serviceName)
+ // Under the type the policy was evaluated on: a same-named service
+ // of another type is not what the caller was granted.
+ svc, ok := n.services.GetTyped(serviceType, serviceName)
if !ok {
- logger.Errorf("[Ingress] Service not found: %s", truncateForLog(serviceName))
+ logger.Errorf("[Ingress] Service not found: %s", truncateForLog(target))
http.Error(w, "Service not found", http.StatusNotFound)
return
}
diff --git a/internal/node/proxy_test.go b/internal/node/proxy_test.go
index b17885fd..c9cc5c35 100644
--- a/internal/node/proxy_test.go
+++ b/internal/node/proxy_test.go
@@ -15,18 +15,17 @@
package node
import (
- "bufio"
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
+ "encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
- "strings"
"testing"
"time"
@@ -531,63 +530,53 @@ func TestStdioDatapathIntegration(t *testing.T) {
// Construct URLs
// http://localhost:<port>/sam/{peer_id}/{service_type}/{service_name}/{upstream_path}
- sseURL := fmt.Sprintf("%s/sam/%s/mcp/%s/", proxyServer.URL, nodeA.Host.ID().String(), serviceName)
postURL := fmt.Sprintf("%s/sam/%s/mcp/%s/", proxyServer.URL, nodeA.Host.ID().String(), serviceName)
client := &http.Client{}
- // Wait for DHT/routing to settle (retry mechanism)
- var sseResp *http.Response
- for i := 0; i < 3; i++ {
- sseResp, err = client.Get(sseURL)
- if err == nil && sseResp.StatusCode == http.StatusOK {
- break
- }
- t.Logf("SSE Connect Attempt %d failed: %v, status: %v", i+1, err, sseResp)
- time.Sleep(1 * time.Second)
- }
-
+ // The bridge has no GET side any more: the legacy SSE stream broadcast
+ // every backend line to every caller.
+ getResp, err := client.Get(postURL)
if err != nil {
t.Fatal(err)
}
- defer func() { _ = sseResp.Body.Close() }()
-
- if sseResp.StatusCode != http.StatusOK {
- t.Fatalf("Expected SSE status OK, got %d", sseResp.StatusCode)
+ _ = getResp.Body.Close()
+ if getResp.StatusCode != http.StatusMethodNotAllowed {
+ t.Fatalf("GET on a command-backed service: got %d, want 405", getResp.StatusCode)
}
- // Send a message via POST
+ // The backend is `cat`, so the request comes straight back as the reply;
+ // the bridge rewrote the id on the way in and must restore it on the way
+ // out. Retried while DHT/routing settles.
testMessage := `{"jsonrpc":"2.0","method":"ping","id":1}`
- postResp, err := client.Post(postURL, "application/json", bytes.NewBufferString(testMessage))
+ var postResp *http.Response
+ for i := 0; i < 3; i++ {
+ postResp, err = client.Post(postURL, "application/json", bytes.NewBufferString(testMessage))
+ if err == nil && postResp.StatusCode == http.StatusOK {
+ break
+ }
+ t.Logf("POST attempt %d failed: %v, status: %v", i+1, err, postResp)
+ time.Sleep(1 * time.Second)
+ }
if err != nil {
t.Fatal(err)
}
defer func() { _ = postResp.Body.Close() }()
-
if postResp.StatusCode != http.StatusOK {
t.Fatalf("Expected POST status OK, got %d", postResp.StatusCode)
}
- // Read from SSE stream
- reader := bufio.NewReader(sseResp.Body)
- line, err := reader.ReadString('\n')
- if err != nil {
+ var echoed map[string]any
+ if err := json.NewDecoder(postResp.Body).Decode(&echoed); err != nil {
t.Fatal(err)
}
-
- expectedPrefix := "data: "
- if !strings.HasPrefix(line, expectedPrefix) {
- t.Fatalf("Expected line to start with %q, got %q", expectedPrefix, line)
+ if echoed["method"] != "ping" || echoed["jsonrpc"] != "2.0" {
+ t.Fatalf("echoed message = %v, want the ping request", echoed)
}
-
- receivedMessage := strings.TrimPrefix(line, expectedPrefix)
- receivedMessage = strings.TrimSpace(receivedMessage)
-
- if receivedMessage != testMessage {
- t.Fatalf("Expected to receive %q, got %q", testMessage, receivedMessage)
+ if id, _ := echoed["id"].(float64); id != 1 {
+ t.Fatalf("echoed id = %v, want the caller's 1 (bridge id not restored)", echoed["id"])
}
- // Cancel context to close the SSE stream and allow server to close gracefully
cancel()
}
diff --git a/internal/node/service.go b/internal/node/service.go
index 2654cc5b..28487857 100644
--- a/internal/node/service.go
+++ b/internal/node/service.go
@@ -59,8 +59,9 @@ func newReverseProxyHandler(targetURL string) (http.Handler, error) {
Rewrite: func(pr *httputil.ProxyRequest) {
noTrailingSlash := pr.In.Header.Get(api.HeaderSamNoTrailingSlash) == "true"
pr.SetURL(u)
- // Preserve the Host behavior of NewSingleHostReverseProxy.
- pr.Out.Host = pr.In.Host
+ // The inbound Host is whatever the remote peer sent; the backend
+ // is addressed by its configured URL.
+ pr.Out.Host = u.Host
pr.Out.Header.Del(api.HeaderSamNoTrailingSlash)
if noTrailingSlash && !strings.HasSuffix(u.Path, "/") && strings.HasSuffix(pr.Out.URL.Path, "/") {
pr.Out.URL.Path = strings.TrimSuffix(pr.Out.URL.Path, "/")
diff --git a/internal/node/service_registry.go b/internal/node/service_registry.go
index 398583ce..04ea0a27 100644
--- a/internal/node/service_registry.go
+++ b/internal/node/service_registry.go
@@ -111,6 +111,27 @@ func (r *ServiceRegistry) Register(ctx context.Context, svc Service) error {
if info.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {
return fmt.Errorf("cannot register service with unspecified type")
}
+ // The same check the config loader runs, for services that arrive by
+ // other routes (FFI, tests): a name carrying its own scheme, such as
+ // "plugin://x", would be addressed as type://plugin://x and dispatch
+ // could no longer tell which type the policy was evaluated on.
+ typeStr, err := api.ServiceTypeToString(info.Type)
+ if err != nil {
+ return err
+ }
+ if err := api.ValidateServiceFormat(typeStr + "://" + info.Name); err != nil {
+ return fmt.Errorf("invalid service name %q: %w", info.Name, err)
+ }
+
+ // Policy is evaluated on type://name and the registry is keyed on name,
+ // so a second type under the same name would let a grant for one reach
+ // the other. One name, one service.
+ r.mu.RLock()
+ existing, taken := r.services[info.Name]
+ r.mu.RUnlock()
+ if taken && existing.Info().Type != info.Type {
+ return fmt.Errorf("service name %q is already registered as %s; a name cannot serve two types", info.Name, existing.Info().Type)
+ }
if err := svc.Init(ctx); err != nil {
return fmt.Errorf("init %s: %w", info.Name, err)
@@ -179,6 +200,18 @@ func (r *ServiceRegistry) Get(name string) (Service, bool) {
return svc, ok
}
+// GetTyped returns the service registered under name only if it is of type
+// t. Dispatch after authorization must use this: the policy was evaluated
+// on t://name, and a service of another type under that name is not what
+// the caller was granted.
+func (r *ServiceRegistry) GetTyped(t api.ServiceType, name string) (Service, bool) {
+ svc, ok := r.Get(name)
+ if !ok || svc.Info().Type != t {
+ return nil, false
+ }
+ return svc, true
+}
+
// List returns the ServiceInfo for every registered service, optionally
// filtered by type. SERVICE_TYPE_UNSPECIFIED means "all types."
func (r *ServiceRegistry) List(typeFilter api.ServiceType) []*api.ServiceInfo {
diff --git a/internal/node/service_registry_test.go b/internal/node/service_registry_test.go
index dfbd2a3f..f2a6a8ee 100644
--- a/internal/node/service_registry_test.go
+++ b/internal/node/service_registry_test.go
@@ -110,6 +110,43 @@ func TestServiceRegistry_InitErrorBlocksProvideAndInsertion(t *testing.T) {
}
}
+// H2: policy is evaluated on type://name and the registry was keyed on name
+// alone, so a peer granted a2a://reports reached mcp://reports. A name now
+// belongs to one type, and dispatch looks it up under the granted type.
+func TestServiceRegistry_OneNameOneType(t *testing.T) {
+ r := newServiceRegistryForTest(&fakeDHT{})
+ ctx := context.Background()
+
+ mcpSvc := newFakeSvc("reports", api.ServiceType_SERVICE_TYPE_MCP)
+ if err := r.Register(ctx, mcpSvc); err != nil {
+ t.Fatalf("Register mcp://reports: %v", err)
+ }
+
+ a2aSvc := newFakeSvc("reports", api.ServiceType_SERVICE_TYPE_A2A)
+ if err := r.Register(ctx, a2aSvc); err == nil {
+ t.Fatal("a2a://reports registered beside mcp://reports")
+ }
+ if a2aSvc.initCalls != 0 {
+ t.Error("the refused service was initialised")
+ }
+ if svc, _ := r.Get("reports"); svc != mcpSvc {
+ t.Error("the refused registration replaced the existing service")
+ }
+
+ // Re-registering the same name under the same type is the normal
+ // re-declare path and stays allowed.
+ if err := r.Register(ctx, newFakeSvc("reports", api.ServiceType_SERVICE_TYPE_MCP)); err != nil {
+ t.Errorf("same-type re-registration refused: %v", err)
+ }
+
+ if _, ok := r.GetTyped(api.ServiceType_SERVICE_TYPE_MCP, "reports"); !ok {
+ t.Error("GetTyped(mcp, reports) missed the registered service")
+ }
+ if _, ok := r.GetTyped(api.ServiceType_SERVICE_TYPE_A2A, "reports"); ok {
+ t.Error("GetTyped(a2a, reports) returned the mcp service: a grant for one type would reach the other")
+ }
+}
+
func TestServiceRegistry_UnregisterRemovesAndCallsTeardown(t *testing.T) {
dht := &fakeDHT{}
r := newServiceRegistryForTest(dht)
diff --git a/internal/node/service_test.go b/internal/node/service_test.go
index 03ec100f..f3692b43 100644
--- a/internal/node/service_test.go
+++ b/internal/node/service_test.go
@@ -129,8 +129,10 @@ func TestNewReverseProxyHandler_RewritesRequests(t *testing.T) {
if got := forwarded.URL.String(); got != tc.wantURL {
t.Errorf("upstream URL = %q, want %q", got, tc.wantURL)
}
- if forwarded.Host != req.Host {
- t.Errorf("upstream Host = %q, want %q", forwarded.Host, req.Host)
+ // The peer chose req.Host; the backend is addressed by its
+ // configured URL, and the original stays in X-Forwarded-Host.
+ if forwarded.Host != "backend.example" {
+ t.Errorf("upstream Host = %q, want %q", forwarded.Host, "backend.example")
}
for name, want := range map[string]string{
api.HeaderSamNoTrailingSlash: "",
diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go
index c8a2ffa6..38ee0af3 100644
--- a/internal/node/sidecar.go
+++ b/internal/node/sidecar.go
@@ -387,6 +387,7 @@ func withAuth(token string, allowAuthorizationFallback bool, next http.Handler)
// Reaching the socket at all already proves the caller is the user
// who owns it, which is the same bar as reading the token file.
r.Header.Del(api.HeaderSamAuthentication)
+ stripSidecarTokenFromAuthorization(r, token)
next.ServeHTTP(w, r)
return
}
@@ -427,13 +428,42 @@ func withAuth(token string, allowAuthorizationFallback bool, next http.Handler)
// The gate credential is local-only: strip exactly the header it came in
// on so it can never flow past the gate. Anything left (e.g. Authorization
// when the gate was passed via X-Sam-Authentication) is the destination
- // service's own credential and passes through untouched.
+ // service's own credential and passes through untouched, unless it is
+ // this same token sent twice, which an SDK configured with the sidecar
+ // token as api_key plus a default header will do.
r.Header.Del(headerName)
+ stripSidecarTokenFromAuthorization(r, token)
next.ServeHTTP(w, r)
})
}
+// stripSidecarTokenFromAuthorization drops an Authorization header whose
+// bearer value is the sidecar token: it is the local gate credential, not the
+// destination's, and must not travel to a remote provider.
+func stripSidecarTokenFromAuthorization(r *http.Request, token string) {
+ if token == "" {
+ return
+ }
+ parts := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
+ if len(parts) == 2 && strings.EqualFold(parts[0], "bearer") && constantTimeEqual(parts[1], token) {
+ r.Header.Del("Authorization")
+ }
+}
+
+// hasDotSegment reports whether any path segment is "." or "..". Go's
+// ServeMux canonicalizes these with a redirect, but the mesh proxies pass
+// paths through to backends that may resolve them against a different
+// service prefix than the one authorization was decided on.
+func hasDotSegment(p string) bool {
+ for _, seg := range strings.Split(p, "/") {
+ if seg == "." || seg == ".." {
+ return true
+ }
+ }
+ return false
+}
+
// constantTimeEqual compares two secrets without leaking their contents through
// timing. Hashing first keeps the comparison length-independent, so a mismatched
// length is no more distinguishable than a mismatched byte. This mirrors how the
@@ -705,6 +735,12 @@ func createEgressProxy(node *SamNode) http.Handler {
http.Error(w, "Service Unavailable: Missing Node Identity", http.StatusServiceUnavailable)
return
}
+ // The remote's policy is decided on the /{type}/{name} prefix this
+ // proxy forwards verbatim; a ".." in the rest is not ours to send.
+ if hasDotSegment(r.URL.Path) {
+ http.Error(w, "Bad Request: path must not contain dot segments", http.StatusBadRequest)
+ return
+ }
r, ok := applyEgressMiddleware(node, w, r)
if !ok {
diff --git a/internal/node/sidecar_hygiene_test.go b/internal/node/sidecar_hygiene_test.go
new file mode 100644
index 00000000..30632d71
--- /dev/null
+++ b/internal/node/sidecar_hygiene_test.go
@@ -0,0 +1,93 @@
+// 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 node
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/google/sam/api"
+)
+
+// L32: a ".." after the authorized /{type}/{name} prefix travelled to the
+// backend verbatim, where a server that resolves dot segments could serve a
+// sibling service the caller was not granted.
+func TestHasDotSegment(t *testing.T) {
+ for path, want := range map[string]bool{
+ "/mcp/a/tools": false,
+ "/mcp/a/../b/tools": true,
+ "/mcp/a/./tools": true,
+ "/mcp/a/..": true,
+ "/mcp/a/x..y/tools": false, // ".." inside a segment is just a name
+ "/mcp/a/tools/...": false,
+ "/sam/p/mcp/a/../b/x": true,
+ } {
+ if got := hasDotSegment(path); got != want {
+ t.Errorf("hasDotSegment(%q) = %v, want %v", path, got, want)
+ }
+ }
+}
+
+// L30: an OpenAI SDK pointed at the sidecar with api_key=<sidecar token> plus
+// X-Sam-Authentication as a default header sends the token twice. The gate
+// stripped only the header it consumed and forwarded the other copy to the
+// remote inference provider.
+func TestWithAuthStripsDuplicateSidecarToken(t *testing.T) {
+ const token = "sidecar-token"
+ var seen http.Header
+ h := withAuth(token, true, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ seen = r.Header.Clone()
+ }))
+
+ cases := map[string]struct {
+ samAuth, authorization string
+ wantAuthorization string
+ }{
+ "token in both headers": {
+ samAuth: "Bearer " + token, authorization: "Bearer " + token, wantAuthorization: "",
+ },
+ "token via X-Sam, provider key in Authorization": {
+ samAuth: "Bearer " + token, authorization: "Bearer provider-key", wantAuthorization: "Bearer provider-key",
+ },
+ "token via Authorization only": {
+ samAuth: "", authorization: "Bearer " + token, wantAuthorization: "",
+ },
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ seen = nil
+ req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
+ req.RemoteAddr = "127.0.0.1:12345"
+ if tc.samAuth != "" {
+ req.Header.Set(api.HeaderSamAuthentication, tc.samAuth)
+ }
+ if tc.authorization != "" {
+ req.Header.Set("Authorization", tc.authorization)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status %d", rec.Code)
+ }
+ if got := seen.Get("Authorization"); got != tc.wantAuthorization {
+ t.Errorf("Authorization reaching the handler = %q, want %q", got, tc.wantAuthorization)
+ }
+ if seen.Get(api.HeaderSamAuthentication) != "" {
+ t.Error("X-Sam-Authentication reached the handler")
+ }
+ })
+ }
+}
diff --git a/internal/node/stdio_bridge.go b/internal/node/stdio_bridge.go
index 9de30e86..3928cfb9 100644
--- a/internal/node/stdio_bridge.go
+++ b/internal/node/stdio_bridge.go
@@ -17,63 +17,52 @@ package node
import (
"bufio"
"encoding/json"
- "fmt"
"io"
"net/http"
"os/exec"
+ "strconv"
"sync"
"github.com/google/sam/api"
)
-// StdioBridge backs the local SSE/POST HTTP ingress route for a
-// command-backed service (registered via baseService.Init). It is not used
-// for mesh sessions - see MCPService.backendTransport, which gives those
-// their own subprocess instead of sharing this one.
+// StdioBridge backs the POST HTTP ingress route for a command-backed service
+// (registered via baseService.Init). It is not used for mesh sessions - see
+// MCPService.backendTransport, which gives those their own subprocess
+// instead of sharing this one.
+//
+// One backend process serves every authorized caller, so the bridge owns the
+// JSON-RPC id space: each request's id is replaced with a bridge-assigned
+// one before it reaches the backend and restored on the way out, and a
+// response is delivered only to the request it answers. Two callers sending
+// the same id can no longer receive each other's replies. There is no
+// broadcast (SSE) side: with a shared process, a server-initiated message
+// cannot be attributed to a caller, so it is not delivered to any of them.
type StdioBridge struct {
- cmd *exec.Cmd
- stdin io.WriteCloser
- stdout io.ReadCloser
- mu sync.Mutex
- clients map[chan string]bool
- calls map[string]chan string
+ cmd *exec.Cmd
+ stdin io.WriteCloser
+ stdout io.ReadCloser
+ mu sync.Mutex
+ nextID uint64
+ // calls maps a bridge-assigned id to the request waiting on it.
+ calls map[uint64]*pendingCall
// closed is set once the stdout reader has stopped; the backend can no
// longer answer, so requests are refused instead of hanging.
closed bool
}
+type pendingCall struct {
+ originalID json.RawMessage
+ reply chan []byte
+}
+
func (b *StdioBridge) Start() {
- b.clients = make(map[chan string]bool)
- b.calls = make(map[string]chan string)
+ b.calls = make(map[uint64]*pendingCall)
go func() {
scanner := bufio.NewScanner(b.stdout)
scanner.Buffer(make([]byte, 0, 64<<10), maxRequestBodyBytes)
for scanner.Scan() {
- line := scanner.Text()
-
- b.mu.Lock()
- if len(line) > 0 && line[0] == '{' {
- var msg map[string]any
- if err := json.Unmarshal([]byte(line), &msg); err == nil {
- if idVal, ok := msg["id"]; ok {
- reqIDStr := fmt.Sprintf("%v", idVal)
- if ch, found := b.calls[reqIDStr]; found {
- select {
- case ch <- line:
- default:
- }
- }
- }
- }
- }
-
- for ch := range b.clients {
- select {
- case ch <- line:
- default:
- }
- }
- b.mu.Unlock()
+ b.deliver(scanner.Bytes())
}
if err := scanner.Err(); err != nil {
@@ -87,148 +76,138 @@ func (b *StdioBridge) Start() {
b.mu.Lock()
b.closed = true
- for ch := range b.clients {
- close(ch)
- delete(b.clients, ch)
- }
- for _, ch := range b.calls {
- close(ch)
+ for id, call := range b.calls {
+ close(call.reply)
+ delete(b.calls, id)
}
- b.calls = make(map[string]chan string)
b.mu.Unlock()
}()
}
+// deliver routes one backend line to the call it answers. Lines that carry
+// no bridge id (notifications, requests from the backend, non-JSON output)
+// have no owner and are dropped.
+func (b *StdioBridge) deliver(line []byte) {
+ if len(line) == 0 || line[0] != '{' {
+ return
+ }
+ var msg map[string]json.RawMessage
+ if err := json.Unmarshal(line, &msg); err != nil {
+ return
+ }
+ rawID, ok := msg["id"]
+ if !ok {
+ return
+ }
+ bridgeID, err := strconv.ParseUint(string(rawID), 10, 64)
+ if err != nil {
+ return
+ }
+
+ b.mu.Lock()
+ call, found := b.calls[bridgeID]
+ if found {
+ delete(b.calls, bridgeID)
+ }
+ b.mu.Unlock()
+ if !found {
+ return
+ }
+
+ msg["id"] = call.originalID
+ restored, err := json.Marshal(msg)
+ if err != nil {
+ close(call.reply)
+ return
+ }
+ call.reply <- restored
+ close(call.reply)
+}
+
func (b *StdioBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- switch r.Method {
- case http.MethodGet:
- flusher, ok := w.(http.Flusher)
- if !ok {
- http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
- return
- }
+ if r.Method != http.MethodPost {
+ // No GET: the legacy SSE stream broadcast every backend line to every
+ // reader, i.e. every caller's tool output to every other caller.
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
+ defer func() { _ = r.Body.Close() }()
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, "Failed to read body", http.StatusBadRequest)
+ return
+ }
+
+ var msg map[string]json.RawMessage
+ if err := json.Unmarshal(body, &msg); err != nil {
+ http.Error(w, "Body must be a JSON-RPC message", http.StatusBadRequest)
+ return
+ }
+ originalID, isCall := msg["id"]
- ch := make(chan string, 10)
+ var call *pendingCall
+ var toBackend []byte
+ if isCall {
+ call = &pendingCall{originalID: originalID, reply: make(chan []byte, 1)}
b.mu.Lock()
if b.closed {
b.mu.Unlock()
http.Error(w, "Backend process is no longer running", http.StatusServiceUnavailable)
return
}
- b.clients[ch] = true
+ b.nextID++
+ bridgeID := b.nextID
+ b.calls[bridgeID] = call
b.mu.Unlock()
-
- w.Header().Set("Content-Type", "text/event-stream")
- w.Header().Set("Cache-Control", "no-cache")
- w.Header().Set("Connection", "keep-alive")
- // Flush headers immediately to establish the stream
- w.WriteHeader(http.StatusOK)
- flusher.Flush()
-
defer func() {
b.mu.Lock()
- delete(b.clients, ch)
+ delete(b.calls, bridgeID)
b.mu.Unlock()
- close(ch)
}()
- ctx := r.Context()
- for {
- select {
- case <-ctx.Done():
- return
- case line, ok := <-ch:
- if !ok {
- return
- }
- if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {
- logger.Errorf("Failed to write to SSE client: %v", err)
- return
- }
- flusher.Flush()
- }
- }
- case http.MethodPost:
- r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
- defer func() { _ = r.Body.Close() }()
- body, err := io.ReadAll(r.Body)
+ msg["id"] = json.RawMessage(strconv.FormatUint(bridgeID, 10))
+ toBackend, err = json.Marshal(msg)
if err != nil {
- http.Error(w, "Failed to read body", http.StatusInternalServerError)
+ http.Error(w, "Failed to encode request", http.StatusInternalServerError)
return
}
+ } else {
+ toBackend = body
+ }
- var msg map[string]any
- isCall := false
- var reqID any
- if err := json.Unmarshal(body, &msg); err == nil {
- if id, ok := msg["id"]; ok {
- isCall = true
- reqID = id
- }
- }
-
- var ch <-chan string
- var unsub func()
- if isCall {
- reqIDStr := fmt.Sprintf("%v", reqID)
- callCh := make(chan string, 1)
- b.mu.Lock()
- if b.closed {
- b.mu.Unlock()
- http.Error(w, "Backend process is no longer running", http.StatusServiceUnavailable)
- return
- }
- b.calls[reqIDStr] = callCh
- b.mu.Unlock()
- ch = callCh
- unsub = func() {
- b.mu.Lock()
- if existing, ok := b.calls[reqIDStr]; ok && existing == callCh {
- delete(b.calls, reqIDStr)
- close(callCh)
- }
- b.mu.Unlock()
- }
- defer unsub()
- }
-
- b.mu.Lock()
- if b.closed {
- b.mu.Unlock()
- http.Error(w, "Backend process is no longer running", http.StatusServiceUnavailable)
- return
- }
- _, err = b.stdin.Write(append(body, '\n'))
+ b.mu.Lock()
+ if b.closed {
b.mu.Unlock()
+ http.Error(w, "Backend process is no longer running", http.StatusServiceUnavailable)
+ return
+ }
+ _, err = b.stdin.Write(append(toBackend, '\n'))
+ b.mu.Unlock()
+ if err != nil {
+ http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError)
+ return
+ }
- if err != nil {
- http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Mcp-Session-Id", "stdio-bridge")
+ w.Header().Set("Mcp-Session-Id", "stdio-bridge")
- if !isCall {
- w.WriteHeader(http.StatusAccepted)
- return
- }
+ if !isCall {
+ w.WriteHeader(http.StatusAccepted)
+ return
+ }
- ctx := r.Context()
- select {
- case <-ctx.Done():
- return
- case line, ok := <-ch:
- if !ok {
- http.Error(w, "Backend process exited before answering", http.StatusServiceUnavailable)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusOK)
- _, _ = w.Write([]byte(line))
+ select {
+ case <-r.Context().Done():
+ return
+ case line, ok := <-call.reply:
+ if !ok {
+ http.Error(w, "Backend process exited before answering", http.StatusServiceUnavailable)
return
}
- default:
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(line)
}
}
diff --git a/internal/node/stdio_bridge_test.go b/internal/node/stdio_bridge_test.go
index b8f24827..6a53dd12 100644
--- a/internal/node/stdio_bridge_test.go
+++ b/internal/node/stdio_bridge_test.go
@@ -16,7 +16,7 @@ package node
import (
"bytes"
- "context"
+ "encoding/json"
"io"
"net/http"
"net/http/httptest"
@@ -54,58 +54,29 @@ func waitFor(t *testing.T, what string, cond func() bool) {
}
}
-// writeSignalRecorder is a ResponseRecorder that reports each body Write on
-// wrote, so a test can tell the handler has emitted a line without reading
-// rec.Body while the handler goroutine is still writing to it.
-type writeSignalRecorder struct {
- *httptest.ResponseRecorder
- wrote chan struct{}
-}
-
-func (r *writeSignalRecorder) Write(p []byte) (int, error) {
- n, err := r.ResponseRecorder.Write(p)
- select {
- case r.wrote <- struct{}{}:
- default:
- }
- return n, err
-}
-
-func TestStdioBridge_ServeHTTP_GETStreamsBroadcastLines(t *testing.T) {
+// GET was the legacy SSE stream: every backend line to every reader, i.e.
+// every caller's tool output to every other authorized caller. Refused.
+func TestStdioBridge_ServeHTTP_GETIsRefused(t *testing.T) {
b, stdoutWriter, _ := newPipeBridge()
defer func() { _ = stdoutWriter.Close() }()
- ctx, cancel := context.WithCancel(context.Background())
- req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
- rec := &writeSignalRecorder{ResponseRecorder: httptest.NewRecorder(), wrote: make(chan struct{}, 1)}
- done := make(chan struct{})
- go func() {
- b.ServeHTTP(rec, req)
- close(done)
- }()
-
- waitFor(t, "SSE client registration", func() bool {
- b.mu.Lock()
- defer b.mu.Unlock()
- return len(b.clients) > 0
- })
- _, _ = stdoutWriter.Write([]byte("hello\n"))
- select {
- case <-rec.wrote:
- case <-time.After(2 * time.Second):
- t.Fatal("timed out waiting for the SSE line to be written")
- }
- cancel()
-
- select {
- case <-done:
- case <-time.After(2 * time.Second):
- t.Fatal("ServeHTTP did not return after ctx was cancelled")
+ rec := httptest.NewRecorder()
+ b.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Fatalf("GET status = %d, want 405", rec.Code)
}
+}
- if got := rec.Body.String(); !strings.Contains(got, "data: hello\n\n") {
- t.Fatalf("SSE body = %q, want it to contain %q", got, "data: hello\n\n")
+// bridgeIDOf returns the id the bridge assigned to the most recent request it
+// wrote to the backend's stdin, so a test can answer as the backend would.
+func bridgeIDOf(t *testing.T, stdinBuf *bytes.Buffer) string {
+ t.Helper()
+ lines := strings.Split(strings.TrimSpace(stdinBuf.String()), "\n")
+ var msg map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(lines[len(lines)-1]), &msg); err != nil {
+ t.Fatalf("stdin line is not JSON: %v", err)
}
+ return string(msg["id"])
}
func TestStdioBridge_ServeHTTP_POSTNotificationReturnsAccepted(t *testing.T) {
@@ -126,10 +97,10 @@ func TestStdioBridge_ServeHTTP_POSTNotificationReturnsAccepted(t *testing.T) {
}
func TestStdioBridge_ServeHTTP_POSTCallWaitsForMatchingReply(t *testing.T) {
- b, stdoutWriter, _ := newPipeBridge()
+ b, stdoutWriter, stdinBuf := newPipeBridge()
defer func() { _ = stdoutWriter.Close() }()
- body := `{"jsonrpc":"2.0","id":1,"method":"ping"}`
+ body := `{"jsonrpc":"2.0","id":"caller-7","method":"ping"}`
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
rec := httptest.NewRecorder()
@@ -144,8 +115,12 @@ func TestStdioBridge_ServeHTTP_POSTCallWaitsForMatchingReply(t *testing.T) {
defer b.mu.Unlock()
return len(b.calls) > 0
})
- reply := `{"jsonrpc":"2.0","id":1,"result":{}}`
- _, _ = stdoutWriter.Write([]byte(reply + "\n"))
+ // The backend never sees the caller's id, only the bridge's.
+ bridgeID := bridgeIDOf(t, stdinBuf)
+ if bridgeID == `"caller-7"` {
+ t.Fatal("caller id reached the backend unrewritten")
+ }
+ _, _ = stdoutWriter.Write([]byte(`{"jsonrpc":"2.0","id":` + bridgeID + `,"result":{}}` + "\n"))
select {
case <-done:
@@ -156,15 +131,82 @@ func TestStdioBridge_ServeHTTP_POSTCallWaitsForMatchingReply(t *testing.T) {
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
- if got := rec.Body.String(); got != reply {
- t.Fatalf("body = %q, want %q", got, reply)
+ var got map[string]json.RawMessage
+ if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if string(got["id"]) != `"caller-7"` {
+ t.Fatalf("reply id = %s, want the caller's own \"caller-7\"", got["id"])
+ }
+}
+
+// M18: with one backend process behind every authorized caller, two callers
+// using the same JSON-RPC id used to collide in the bridge's routing table,
+// and one caller's reply was handed to the other. Each reply goes to the
+// request it answers, and a line with no owner goes to nobody.
+func TestStdioBridge_ServeHTTP_SameIDFromTwoCallersDoesNotCrossWires(t *testing.T) {
+ b, stdoutWriter, stdinBuf := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ type result struct {
+ rec *httptest.ResponseRecorder
+ done chan struct{}
+ }
+ start := func(method string) result {
+ r := result{rec: httptest.NewRecorder(), done: make(chan struct{})}
+ req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"`+method+`"}`))
+ go func() {
+ b.ServeHTTP(r.rec, req)
+ close(r.done)
+ }()
+ return r
+ }
+ a := start("secret-for-a")
+ waitFor(t, "first call registered", func() bool {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return len(b.calls) == 1
+ })
+ idA := bridgeIDOf(t, stdinBuf)
+ bb := start("secret-for-b")
+ waitFor(t, "second call registered", func() bool {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return len(b.calls) == 2
+ })
+ idB := bridgeIDOf(t, stdinBuf)
+ if idA == idB {
+ t.Fatalf("both callers got bridge id %s", idA)
+ }
+
+ // A backend notification has no owner: nobody receives it.
+ _, _ = stdoutWriter.Write([]byte(`{"jsonrpc":"2.0","method":"notifications/progress"}` + "\n"))
+ // Answer B first, then A.
+ _, _ = stdoutWriter.Write([]byte(`{"jsonrpc":"2.0","id":` + idB + `,"result":"for-b"}` + "\n"))
+ _, _ = stdoutWriter.Write([]byte(`{"jsonrpc":"2.0","id":` + idA + `,"result":"for-a"}` + "\n"))
+
+ for name, r := range map[string]result{"a": a, "b": bb} {
+ select {
+ case <-r.done:
+ case <-time.After(2 * time.Second):
+ t.Fatalf("caller %s never got its reply", name)
+ }
+ if r.rec.Code != http.StatusOK {
+ t.Fatalf("caller %s: status %d", name, r.rec.Code)
+ }
+ if !strings.Contains(r.rec.Body.String(), `"for-`+name+`"`) {
+ t.Errorf("caller %s received %s", name, r.rec.Body.String())
+ }
+ if !strings.Contains(r.rec.Body.String(), `"id":1`) {
+ t.Errorf("caller %s: id not restored: %s", name, r.rec.Body.String())
+ }
}
}
// A single backend line larger than bufio.Scanner's 64 KiB default used to
// stop the reader for good; results up to the request-body cap must flow.
func TestStdioBridge_ServeHTTP_LargeReplyIsDelivered(t *testing.T) {
- b, stdoutWriter, _ := newPipeBridge()
+ b, stdoutWriter, stdinBuf := newPipeBridge()
defer func() { _ = stdoutWriter.Close() }()
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"jsonrpc":"2.0","id":7,"method":"big"}`))
@@ -180,16 +222,16 @@ func TestStdioBridge_ServeHTTP_LargeReplyIsDelivered(t *testing.T) {
return len(b.calls) > 0
})
- reply := `{"jsonrpc":"2.0","id":7,"result":"` + strings.Repeat("x", 100<<10) + `"}`
- _, _ = stdoutWriter.Write([]byte(reply + "\n"))
+ payload := strings.Repeat("x", 100<<10)
+ _, _ = stdoutWriter.Write([]byte(`{"jsonrpc":"2.0","id":` + bridgeIDOf(t, stdinBuf) + `,"result":"` + payload + `"}` + "\n"))
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("ServeHTTP did not return after a >64 KiB reply")
}
- if rec.Code != http.StatusOK || rec.Body.String() != reply {
- t.Fatalf("status %d, body len %d; want 200 and %d bytes", rec.Code, rec.Body.Len(), len(reply))
+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), payload) || !strings.Contains(rec.Body.String(), `"id":7`) {
+ t.Fatalf("status %d, body len %d; want 200 with the %d-byte payload and the caller's id", rec.Code, rec.Body.Len(), len(payload))
}
}
@@ -227,11 +269,9 @@ func TestStdioBridge_ServeHTTP_RefusesAfterBackendExit(t *testing.T) {
defer b.mu.Unlock()
return b.closed
})
- for _, method := range []string{http.MethodPost, http.MethodGet} {
- rec := httptest.NewRecorder()
- b.ServeHTTP(rec, httptest.NewRequest(method, "/", strings.NewReader(`{"jsonrpc":"2.0","id":2,"method":"ping"}`)))
- if rec.Code != http.StatusServiceUnavailable {
- t.Errorf("%s after exit: status = %d, want 503", method, rec.Code)
- }
+ rec = httptest.NewRecorder()
+ b.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"jsonrpc":"2.0","id":2,"method":"ping"}`)))
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Errorf("POST after exit: status = %d, want 503", rec.Code)
}
}
diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.go
index b107cca2..ab29075b 100644
--- a/tests/integration/datapath_test.go
+++ b/tests/integration/datapath_test.go
@@ -16,12 +16,14 @@ package integration_test
import (
"bytes"
+ "encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
+ "reflect"
"strings"
"sync"
"testing"
@@ -124,9 +126,18 @@ func TestIntegrationStdioDatapath(t *testing.T) {
t.Fatal(err)
}
- receivedMessage := strings.TrimSpace(string(bodyBytes))
- if receivedMessage != testMessage {
- t.Fatalf("Expected to receive %q in POST response, got %q", testMessage, receivedMessage)
+ // The bridge rewrites the JSON-RPC id on the way to the backend and
+ // restores it on the way back, so the echo is the same message
+ // re-serialized, not the same bytes.
+ var want, got map[string]any
+ if err := json.Unmarshal([]byte(testMessage), &want); err != nil {
+ t.Fatal(err)
+ }
+ if err := json.Unmarshal(bodyBytes, &got); err != nil {
+ t.Fatalf("POST response is not JSON: %v (%q)", err, bodyBytes)
+ }
+ if !reflect.DeepEqual(want, got) {
+ t.Fatalf("Expected to receive %v in POST response, got %v", want, got)
}
}