Skip to content

Agent Mesh

api, cmd: use custom RFC 3986 and DNSName regex validations; clean up govalidator dependency

Antonio Ojea6e2b085ee895
diff --git a/api/network.go b/api/network.go
index c227ce91..0bb41245 100644
--- a/api/network.go
+++ b/api/network.go
@@ -16,7 +16,7 @@ package api
import (
"fmt"
- "net/url"
+ "regexp"
"strings"
"github.com/libp2p/go-libp2p/core/protocol"
@@ -46,6 +46,37 @@ const (
DefaultAudience = "sam-mesh-audience"
)
+// ============================================================================
+// SAM Custom HTTP Headers
+// ============================================================================
+
+const (
+ // HeaderSamBiscuit is the custom HTTP header used to carry the base64-encoded
+ // Biscuit token containing the node's identity credentials when forwarding requests
+ // over libp2p HTTP between nodes in the mesh.
+ //
+ // This header is internal to the SAM mesh datapath and is stripped before requests
+ // are forwarded to backend services.
+ HeaderSamBiscuit = "X-Sam-Biscuit"
+
+ // HeaderSamAuthorization is the custom HTTP header that a client can pass to a local
+ // SAM node's egress proxy to supply the Authorization header intended for the remote service.
+ //
+ // The egress proxy uses "Authorization: Bearer <token>" for its own local authentication.
+ // By specifying the target service's auth token in HeaderSamAuthorization, the client avoids
+ // stomping local authentication, and prevents the egress proxy from leaking the local sidecar
+ // authentication token to the remote peer. The egress proxy maps this header back to
+ // "Authorization" before transmitting the request to the destination node.
+ HeaderSamAuthorization = "X-Sam-Authorization"
+
+ // HeaderSamNoTrailingSlash is the custom HTTP header set by the ingress handler
+ // to indicate that the original request had no trailing slash.
+ //
+ // This helps backward-compatibility with services that strictly distinguish
+ // between a root path "/" and an empty path "".
+ HeaderSamNoTrailingSlash = "X-Sam-No-Trailing-Slash"
+)
+
// ============================================================================
// Service Classification & Namespaces
// ============================================================================
@@ -107,6 +138,26 @@ func ServiceTypeToString(t ServiceType) (string, error) {
// Parsing & Routing Utilities
// ============================================================================
+var (
+ // rfc3986URIRegex is the exact regular expression provided by RFC 3986 Appendix B
+ // for breaking down a well-formed URI reference into its components.
+ // Reference: https://tools.ietf.org/html/rfc3986#appendix-B
+ //
+ // Breaking down the regex:
+ // ^(([^:/?#]+):)? - Group 1 & 2: Scheme (optional, e.g. "mcp:")
+ // (//([^/?#]*))? - Group 3 & 4: Authority (optional, e.g. "//my-service")
+ // ([^?#]*) - Group 5: Path
+ // (\?([^#]*))? - Group 6 & 7: Query (optional)
+ // (#(.*))? - Group 8 & 9: Fragment (optional)
+ rfc3986URIRegex = regexp.MustCompile(`^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?`)
+
+ // dnsNameRegex is adapted from govalidator's DNSName pattern.
+ // Reference: https://github.com/asaskevich/govalidator/blob/3dd3875e2b081a20d6eed935913a482fea14ecd0/patterns.go#L29
+ // It is adapted to allow underscores and asterisks (wildcards).
+ // The asterisk '*' can only be at the very beginning (e.g., "*.example.com") or at the very end (e.g., "example.*").
+ dnsNameRegex = regexp.MustCompile(`^(\*\.)?([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*(\.\*)?[\._]?$`)
+)
+
// ParseServiceTarget parses a service target string into its type (scheme) and name components.
//
// Expected formats:
@@ -120,15 +171,64 @@ func ParseServiceTarget(target string) (svcType, svcName string) {
if target == "*" {
return "*", "*"
}
- u, err := url.Parse(target)
- if err != nil || u.Scheme == "" {
- return "", target
+
+ if strings.Contains(target, "://") {
+ matches := rfc3986URIRegex.FindStringSubmatch(target)
+ if len(matches) < 6 {
+ return "", target
+ }
+ scheme := matches[2]
+ hasAuthority := matches[3] != ""
+ authority := matches[4]
+ path := matches[5]
+
+ if scheme == "" || !hasAuthority {
+ return "", target
+ }
+ name := authority
+ if path != "" {
+ name = authority + path
+ }
+ return scheme, name
+ }
+
+ parts := strings.SplitN(target, ":", 2)
+ if len(parts) == 2 {
+ return parts[0], parts[1]
+ }
+ return "", target
+}
+
+// SplitToolName splits a fully qualified MCP tool name into its target service URI
+// and the original tool name.
+//
+// Expected format: "scheme://service/tool" (e.g., "mcp://my-service/my-tool").
+// If the input is empty or invalid, it returns an error. No default fallback is applied.
+func SplitToolName(toolName string) (targetService, originalToolName string, err error) {
+ if toolName == "" {
+ return "", "", fmt.Errorf("tool name cannot be empty")
}
- name := u.Host
- if u.Opaque != "" {
- name = u.Opaque
- } else if u.Path != "" {
- name = u.Host + u.Path
+
+ matches := rfc3986URIRegex.FindStringSubmatch(toolName)
+ if len(matches) < 6 {
+ return "", "", fmt.Errorf("invalid namespaced tool name %q: must follow explicit URI format 'scheme://service/tool'", toolName)
}
- return u.Scheme, name
+
+ scheme := matches[2]
+ hasAuthority := matches[3] != ""
+ authority := matches[4]
+ path := matches[5]
+
+ if scheme == "" || !hasAuthority || authority == "" || path == "" || path == "/" {
+ return "", "", fmt.Errorf("invalid namespaced tool name %q: must follow explicit URI format 'scheme://service/tool'", toolName)
+ }
+
+ // Reject query parameters or fragments in the tool name
+ if matches[6] != "" || matches[8] != "" {
+ return "", "", fmt.Errorf("invalid namespaced tool name %q: queries and fragments are not allowed", toolName)
+ }
+
+ targetService = scheme + "://" + authority
+ originalToolName = strings.TrimPrefix(path, "/")
+ return targetService, originalToolName, nil
}
diff --git a/api/network_test.go b/api/network_test.go
index 09d45a81..6e40187f 100644
--- a/api/network_test.go
+++ b/api/network_test.go
@@ -61,6 +61,30 @@ func TestParseServiceTarget(t *testing.T) {
wantType: "mcp",
wantName: "tool:subtool",
},
+ {
+ name: "Target with underscore",
+ target: "client_peer_id:value_with_underscore",
+ wantType: "client_peer_id",
+ wantName: "value_with_underscore",
+ },
+ {
+ name: "Wildcard fact",
+ target: "*:*",
+ wantType: "*",
+ wantName: "*",
+ },
+ {
+ name: "Hierarchical URI with path",
+ target: "mcp://my_service/tool",
+ wantType: "mcp",
+ wantName: "my_service/tool",
+ },
+ {
+ name: "Hierarchical URI with underscore",
+ target: "mcp://my_service_name",
+ wantType: "mcp",
+ wantName: "my_service_name",
+ },
}
for _, tt := range tests {
diff --git a/api/validation.go b/api/validation.go
index 35f58d51..74272723 100644
--- a/api/validation.go
+++ b/api/validation.go
@@ -2,10 +2,7 @@ package api
import (
"fmt"
- "net/url"
"strings"
-
- "github.com/asaskevich/govalidator"
)
// ValidateServiceFormat ensures the service string follows the explicit URI format.
@@ -13,20 +10,31 @@ func ValidateServiceFormat(svc string) error {
if svc == "*" {
return nil
}
- // We parse the service string as a URL to enforce hierarchical URIs (e.g., mcp://name).
- // - If no scheme is present (e.g., "mcp-service"), u.Scheme will be empty.
- // - If a legacy non-hierarchical format is used (e.g., "mcp:my-service"), url.Parse will parse the
- // part after the colon into u.Opaque. We reject u.Opaque != "" to ensure that the hierarchical
- // separator "://" is explicitly present (which maps the target name to u.Host instead of u.Opaque).
- // Without this check, "mcp:my-service.local" would parse successfully and be accepted since
- // "my-service.local" is a valid DNS name.
- u, err := url.Parse(svc)
- if err != nil || u.Scheme == "" || u.Opaque != "" {
+
+ matches := rfc3986URIRegex.FindStringSubmatch(svc)
+ if len(matches) < 6 {
+ return fmt.Errorf("invalid service format %q: must follow explicit URI format (e.g., mcp://name)", svc)
+ }
+
+ scheme := matches[2]
+ hasAuthority := matches[3] != ""
+ authority := matches[4]
+
+ if scheme == "" || !hasAuthority {
return fmt.Errorf("invalid service format %q: must follow explicit URI format (e.g., mcp://name)", svc)
}
- if u.User != nil {
+
+ if matches[6] != "" {
+ return fmt.Errorf("invalid service format %q: query parameters are not allowed in service URIs", svc)
+ }
+ if matches[8] != "" {
+ return fmt.Errorf("invalid service format %q: fragments are not allowed in service URIs", svc)
+ }
+
+ if strings.Contains(authority, "@") {
return fmt.Errorf("invalid service format %q: userinfo is not allowed in service URIs", svc)
}
+
typ, val := ParseServiceTarget(svc)
if typ == "" {
return fmt.Errorf("invalid service format %q: type cannot be empty", svc)
@@ -43,26 +51,7 @@ func ValidateServiceFormat(svc string) error {
parts := strings.SplitN(val, "/", 2)
host := parts[0]
- // Host validation
- if strings.Contains(host, "_") {
- return fmt.Errorf("invalid service format %q: host cannot contain underscores", svc)
- }
-
- // Normalize wildcards for DNS validation.
- // Note: We only support prefix wildcards starting with "*." (e.g., "*.service")
- // and suffix wildcards ending with ".*" (e.g., "service.*"). Both formats
- // strictly require a dot separator at the domain boundary.
- // Arbitrary partial matching (e.g., "dev-*", "*-prod", or "service*") is not
- // supported because the unnormalized "*" character will fail the DNS validation.
- h := host
- if strings.HasPrefix(h, "*.") {
- h = "wildcard." + h[2:]
- }
- if strings.HasSuffix(h, ".*") {
- h = h[:len(h)-2] + ".wildcard"
- }
-
- if !govalidator.IsDNSName(h) {
+ if !dnsNameRegex.MatchString(host) {
return fmt.Errorf("invalid service format %q: %q is not a valid DNS name", svc, host)
}
diff --git a/api/validation_test.go b/api/validation_test.go
index bb91126d..7c6a3de5 100644
--- a/api/validation_test.go
+++ b/api/validation_test.go
@@ -19,10 +19,13 @@ func TestValidateServiceFormat(t *testing.T) {
{"invalid fallback", "mcp-service", true},
{"invalid consecutive dots", "mcp://my..service", true},
{"invalid wildcard middle", "mcp://my.*.service", true},
- {"invalid invalid chars", "mcp://service_name", true},
+ {"valid with underscore", "mcp://service_name", false},
{"invalid suffix wildcard without dot", "mcp://service.inc*", true},
{"valid exact with path", "mcp://my-service/local", false},
{"invalid legacy mcp: format", "mcp:my-service.local", true},
+ {"invalid with query", "mcp://my-service?query=1", true},
+ {"invalid with fragment", "mcp://my-service#fragment", true},
+ {"invalid with query and fragment", "mcp://my-service?query=1#fragment", true},
}
for _, tt := range tests {
diff --git a/cmd/sam-node/config_test.go b/cmd/sam-node/config_test.go
index ea554ce1..3f2f356a 100644
--- a/cmd/sam-node/config_test.go
+++ b/cmd/sam-node/config_test.go
@@ -57,15 +57,24 @@ services:
},
},
{
- name: "Invalid service name containing underscores",
+ name: "Valid service name containing underscores",
yamlContent: `
version: "v1alpha1"
services:
- type: "mcp"
- name: "invalid_mcp_name"
+ name: "valid_mcp_name"
target_url: "http://localhost:8080"
`,
- wantErr: true,
+ wantErr: false,
+ verify: func(t *testing.T, config *NodeConfigComplete) {
+ if len(config.Services) != 1 {
+ t.Errorf("expected 1 service, got %d", len(config.Services))
+ }
+ s := config.Services[0]
+ if s.Type != "mcp" || s.Name != "valid_mcp_name" || s.TargetURL != "http://localhost:8080" {
+ t.Errorf("unexpected service: %+v", s)
+ }
+ },
},
{
name: "Invalid service name containing invalid DNS characters",
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index 99360089..99e23e9d 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -20,7 +20,6 @@ import (
"errors"
"fmt"
"net/http"
- "net/url"
"strings"
"time"
@@ -34,18 +33,19 @@ import (
"google.golang.org/protobuf/proto"
)
-// meshInstructions tells connecting clients a mesh is reachable here and how
-// the find → describe → call flow works. Sent at initialize time.
-const meshInstructions = `This MCP server connects this node to a SAM mesh: a network of remote agents that host their own MCP tools. The tools listed here are infrastructure for reaching tools on other peers when no local tool or capability covers the task.
+// meshInstructions tells connecting clients how the SAM mesh is composed and how
+// to discover and call remote tools/services. Sent at initialize time.
+const meshInstructions = `This MCP server connects this node to a SAM mesh: a network of remote agents that host their own services (e.g., MCP servers or inference services) and tools.
-Reach into the mesh only when the needed tool isn't available locally. To do so:
+The mesh allows you to discover these remote services, list their tools, and call them.
+To use these remote services and their tools, the client can use the following flow:
1. find_remote_tools — discover what tools exist across the mesh (returns peer_id + namespaced tool_name + description). Optionally narrow by service_name or peer_id.
2. describe_remote_tool — fetch a specific tool's input_schema before calling it. Always do this so you know the argument shape.
- 3. call_remote_tool — invoke it. Pass peer_id, the namespaced tool_name, and arguments as a JSON object whose keys match the input_schema from step 2 (not a stringified blob).
+ 3. call_remote_tool — invoke it. Pass peer_id, the namespaced tool_name (scheme://service/tool, e.g. 'mcp://code-reviewer/review_pr'), and arguments as a JSON object whose keys match the input_schema.
-Other useful tools: discover_remote_services browses services by type, get_mesh_info reports connected peers and mesh state, list_local_services shows what this node hosts.
+Other useful tools: discover_remote_services browses services by type (e.g. 'MCP' or 'Inference'), get_mesh_info reports connected peers and mesh state, list_local_services shows what this node hosts.
-Remote tool names are namespaced as 'scheme://service/tool' (e.g. 'mcp://code-reviewer/review_pr'). Prefer discovering and describing a tool before calling it rather than guessing arguments.`
+Tools on remote services are identified via the format 'scheme://service-name/tool-name' (where 'scheme://service-name' represents the well-known local address of the service, and 'tool-name' is the individual tool to execute on it. Tool names themselves can contain any characters).`
// NewMCPServer creates a new MCP server instance with all tools registered.
func NewMCPServer(node *SamNode) *mcp.Server {
@@ -364,7 +364,7 @@ func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, tar
}
func (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolName string, params any) (*mcp.CallToolResult, error) {
- targetService, originalToolName, err := splitToolName(toolName)
+ targetService, originalToolName, err := api.SplitToolName(toolName)
if err != nil {
return nil, err
}
@@ -554,23 +554,3 @@ func (n *SamNode) preparePeerAddrs(ctx context.Context, targetPeer peer.ID) {
logger.Debugf("[Discovery] Replaced addrs for %s with %d routable/circuit addrs", targetPeer, len(validAddrs))
}
}
-
-// splitToolName splits a fully qualified MCP tool name into its target service URI
-// and the original tool name to be invoked on that service.
-//
-// Expected format: "scheme://service-name/tool-name" (e.g., "mcp://my-service/my-tool").
-// If the input is empty or invalid, it returns an error. No default fallback is applied.
-func splitToolName(toolName string) (targetService, originalToolName string, err error) {
- if toolName == "" {
- return "", "", fmt.Errorf("tool name cannot be empty")
- }
-
- u, parseErr := url.Parse(toolName)
- if parseErr != nil || u.Scheme == "" || u.Host == "" || u.Path == "" || u.Opaque != "" {
- return "", "", fmt.Errorf("invalid namespaced tool name %q: must follow explicit URI format 'scheme://service/tool'", toolName)
- }
-
- targetService = u.Scheme + "://" + u.Host
- originalToolName = strings.TrimPrefix(u.Path, "/")
- return targetService, originalToolName, nil
-}
diff --git a/cmd/sam-node/mcp_handlers.go b/cmd/sam-node/mcp_handlers.go
index b1fc0a3f..16c02a17 100644
--- a/cmd/sam-node/mcp_handlers.go
+++ b/cmd/sam-node/mcp_handlers.go
@@ -470,7 +470,7 @@ func (n *SamNode) handleDescribeRemoteTool(ctx context.Context, req *mcp.CallToo
return nil, nil, fmt.Errorf("invalid peer_id: %w", err)
}
- serviceName, actualToolName, err := splitToolName(params.ToolName)
+ serviceName, actualToolName, err := api.SplitToolName(params.ToolName)
if err != nil {
return nil, nil, err
}
diff --git a/cmd/sam-node/mcp_test.go b/cmd/sam-node/mcp_test.go
index e7ca95d6..0220aaf7 100644
--- a/cmd/sam-node/mcp_test.go
+++ b/cmd/sam-node/mcp_test.go
@@ -22,6 +22,7 @@ import (
"testing"
"time"
+ "github.com/google/sam/api"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p/core/peerstore"
mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
@@ -207,9 +208,9 @@ func TestSplitToolName(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- gotSvc, gotTool, err := splitToolName(tt.input)
+ gotSvc, gotTool, err := api.SplitToolName(tt.input)
if (err != nil) != tt.wantErr {
- t.Errorf("splitToolName(%q) returned error: %v, wantErr: %v", tt.input, err, tt.wantErr)
+ t.Errorf("SplitToolName(%q) returned error: %v, wantErr: %v", tt.input, err, tt.wantErr)
}
if !tt.wantErr {
if gotSvc != tt.wantService || gotTool != tt.wantTool {
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index dd8e67c3..9beae91d 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -1512,7 +1512,7 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
}
// Extract biscuit from X-Sam-Biscuit header
- biscuitB64 := r.Header.Get("X-Sam-Biscuit")
+ biscuitB64 := r.Header.Get(api.HeaderSamBiscuit)
if biscuitB64 == "" {
http.Error(w, "Missing X-Sam-Biscuit header", http.StatusUnauthorized)
return
@@ -1545,7 +1545,7 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
}
// Strip the biscuit header so it doesn't leak to the backend service
- r.Header.Del("X-Sam-Biscuit")
+ r.Header.Del(api.HeaderSamBiscuit)
svc, ok := n.services.Get(serviceName)
if !ok {
@@ -1563,7 +1563,7 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
if upstreamPath == "" {
r.URL.Path = "/"
if len(parts) == 2 {
- r.Header.Set("X-Sam-No-Trailing-Slash", "true")
+ r.Header.Set(api.HeaderSamNoTrailingSlash, "true")
}
} else {
r.URL.Path = "/" + upstreamPath
diff --git a/cmd/sam-node/proxy_test.go b/cmd/sam-node/proxy_test.go
index 2d4ad559..9379a7b7 100644
--- a/cmd/sam-node/proxy_test.go
+++ b/cmd/sam-node/proxy_test.go
@@ -557,3 +557,227 @@ func TestStdioDatapathIntegration(t *testing.T) {
// Cancel context to close the SSE stream and allow server to close gracefully
cancel()
}
+
+func TestDatapathHeadersAndRoutingTable(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ privA, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ privB, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+
+ dirA := t.TempDir()
+ dirB := t.TempDir()
+
+ storeA, err := NewStore(dirA)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = storeA.Close() }()
+
+ storeB, err := NewStore(dirB)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = storeB.Close() }()
+
+ nodeA, err := NewSamNode(ctx, SamNodeConfig{
+ PrivKey: privA,
+ HubAddrs: nil,
+ Store: storeA,
+ MeshID: "test-mesh",
+ DiscoveryInterval: "1s",
+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
+ EnableRelay: false,
+ NodeConfig: &NodeConfigComplete{},
+ KeyGracePeriod: 24 * time.Hour,
+ AllowLoopback: true,
+ MonitorBootstrap: 2 * time.Minute,
+ MonitorInterval: 1 * time.Minute,
+ BiscuitTimeout: 500 * time.Millisecond,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ if err := nodeA.Host.Close(); err != nil {
+ t.Logf("failed to close nodeA host: %v", err)
+ }
+ }()
+
+ nodeB, err := NewSamNode(ctx, SamNodeConfig{
+ PrivKey: privB,
+ HubAddrs: nil,
+ Store: storeB,
+ MeshID: "test-mesh",
+ DiscoveryInterval: "1s",
+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
+ EnableRelay: false,
+ NodeConfig: &NodeConfigComplete{},
+ KeyGracePeriod: 24 * time.Hour,
+ AllowLoopback: true,
+ MonitorBootstrap: 2 * time.Minute,
+ MonitorInterval: 1 * time.Minute,
+ BiscuitTimeout: 500 * time.Millisecond,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ if err := nodeB.Host.Close(); err != nil {
+ t.Logf("failed to close nodeB host: %v", err)
+ }
+ }()
+
+ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("gen root: %v", err)
+ }
+ if err := buildAndSaveBiscuit(nodeB, rootPriv); err != nil {
+ t.Fatalf("buildAndSaveBiscuit: %v", err)
+ }
+ nodeA.keysMu.Lock()
+ nodeA.trustedKeys = append(nodeA.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
+ nodeA.keysMu.Unlock()
+
+ err = nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // We will record the HTTP request headers and URL received by the backend dummy service.
+ var lastReceivedHeaders http.Header
+ var lastReceivedPath string
+
+ dummyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ lastReceivedHeaders = r.Header.Clone()
+ lastReceivedPath = r.URL.Path
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer dummyServer.Close()
+
+ serviceName := "dummy-tool"
+ serviceInfo := &api.ServiceInfo{
+ Type: api.ServiceType_SERVICE_TYPE_MCP,
+ Name: serviceName,
+ }
+
+ _ = nodeA.RegisterService(ctx, &api.RegisterServiceRequest{
+ Service: serviceInfo,
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: dummyServer.URL},
+ })
+
+ handler, err := newReverseProxyHandler(dummyServer.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodeA.services.insertService(&testService{
+ info: serviceInfo,
+ handler: handler,
+ })
+
+ nodeB.BoundHTTPAddr = "127.0.0.1:0"
+
+ proxyHandler := createEgressProxy(nodeB)
+ proxyServer := httptest.NewServer(proxyHandler)
+ defer proxyServer.Close()
+
+ client := &http.Client{}
+
+ tests := []struct {
+ name string
+ pathSuffix string // e.g. "/api/v1/test" or ""
+ requestHeaders map[string]string
+ wantReceivedHeaders map[string]string // header key -> expected value. If value is "", header must be absent.
+ wantReceivedPathSuffix string
+ }{
+ {
+ name: "Auth mapping with X-Sam-Authorization",
+ pathSuffix: "/api/v1/test",
+ requestHeaders: map[string]string{
+ "Authorization": "Bearer local-token",
+ api.HeaderSamAuthorization: "Bearer upstream-token",
+ "X-Test-Request": "yes",
+ },
+ wantReceivedHeaders: map[string]string{
+ "Authorization": "Bearer upstream-token",
+ api.HeaderSamAuthorization: "", // Must be stripped
+ api.HeaderSamBiscuit: "", // Must be stripped
+ api.HeaderSamNoTrailingSlash: "", // Must be stripped
+ "X-Test-Request": "yes",
+ },
+ wantReceivedPathSuffix: "/api/v1/test",
+ },
+ {
+ name: "Auth stripping when X-Sam-Authorization is absent",
+ pathSuffix: "/api/v1/test",
+ requestHeaders: map[string]string{
+ "Authorization": "Bearer local-token",
+ "X-Test-Request": "yes",
+ },
+ wantReceivedHeaders: map[string]string{
+ "Authorization": "", // Must be stripped to avoid leaking local sidecar token
+ api.HeaderSamAuthorization: "",
+ api.HeaderSamBiscuit: "",
+ api.HeaderSamNoTrailingSlash: "",
+ "X-Test-Request": "yes",
+ },
+ wantReceivedPathSuffix: "/api/v1/test",
+ },
+ {
+ name: "Trailing slash handling with empty path",
+ pathSuffix: "", // Requesting the root of the service: .../dummy-tool
+ requestHeaders: map[string]string{
+ "Authorization": "Bearer local-token",
+ },
+ wantReceivedHeaders: map[string]string{
+ api.HeaderSamNoTrailingSlash: "", // Must be stripped
+ },
+ wantReceivedPathSuffix: "/", // Should be mapped to "/" without trailing slash issues
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ lastReceivedHeaders = nil
+ lastReceivedPath = ""
+
+ url := fmt.Sprintf("%s/sam/%s/mcp/%s%s", proxyServer.URL, nodeA.Host.ID().String(), serviceName, tt.pathSuffix)
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for k, v := range tt.requestHeaders {
+ req.Header.Set(k, v)
+ }
+
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("Expected 200 OK, got %d", resp.StatusCode)
+ }
+
+ // Verify received path
+ if lastReceivedPath != tt.wantReceivedPathSuffix {
+ t.Errorf("Expected received path to be %q, got %q", tt.wantReceivedPathSuffix, lastReceivedPath)
+ }
+
+ // Verify received headers
+ for k, expectedVal := range tt.wantReceivedHeaders {
+ actualVal := lastReceivedHeaders.Get(k)
+ if expectedVal == "" {
+ if _, present := lastReceivedHeaders[k]; present {
+ t.Errorf("Expected header %q to be absent, but got %q", k, actualVal)
+ }
+ } else {
+ if actualVal != expectedVal {
+ t.Errorf("Expected header %q to be %q, got %q", k, expectedVal, actualVal)
+ }
+ }
+ }
+ })
+ }
+}
diff --git a/cmd/sam-node/service.go b/cmd/sam-node/service.go
index 7b21ceb3..744c5005 100644
--- a/cmd/sam-node/service.go
+++ b/cmd/sam-node/service.go
@@ -56,16 +56,29 @@ func newReverseProxyHandler(targetURL string) (http.Handler, error) {
return nil, fmt.Errorf("invalid target URL: %w", err)
}
proxy := httputil.NewSingleHostReverseProxy(u)
- originalDirector := proxy.Director
- proxy.Director = func(req *http.Request) {
- noTrailingSlash := req.Header.Get("X-Sam-No-Trailing-Slash") == "true"
- req.Header.Del("X-Sam-No-Trailing-Slash")
- originalDirector(req)
-
- if noTrailingSlash && !strings.HasSuffix(u.Path, "/") && strings.HasSuffix(req.URL.Path, "/") {
- req.URL.Path = strings.TrimSuffix(req.URL.Path, "/")
+ if proxy.Rewrite != nil {
+ originalRewrite := proxy.Rewrite
+ proxy.Rewrite = func(pr *httputil.ProxyRequest) {
+ noTrailingSlash := pr.In.Header.Get(api.HeaderSamNoTrailingSlash) == "true"
+ pr.Out.Header.Del(api.HeaderSamNoTrailingSlash)
+ originalRewrite(pr)
+ if noTrailingSlash && !strings.HasSuffix(u.Path, "/") && strings.HasSuffix(pr.Out.URL.Path, "/") {
+ pr.Out.URL.Path = strings.TrimSuffix(pr.Out.URL.Path, "/")
+ }
+ logger.Debugf("[ReverseProxy] Forwarding to: %q", pr.Out.URL.String())
+ }
+ } else {
+ originalDirector := proxy.Director
+ proxy.Director = func(req *http.Request) {
+ noTrailingSlash := req.Header.Get(api.HeaderSamNoTrailingSlash) == "true"
+ req.Header.Del(api.HeaderSamNoTrailingSlash)
+ originalDirector(req)
+
+ if noTrailingSlash && !strings.HasSuffix(u.Path, "/") && strings.HasSuffix(req.URL.Path, "/") {
+ req.URL.Path = strings.TrimSuffix(req.URL.Path, "/")
+ }
+ logger.Debugf("[ReverseProxy] Forwarding to: %q", req.URL.String())
}
- logger.Debugf("[ReverseProxy] Forwarding to: %q", req.URL.String())
}
return proxy, nil
}
diff --git a/cmd/sam-node/sidecar.go b/cmd/sam-node/sidecar.go
index a9e6b610..27a7820e 100644
--- a/cmd/sam-node/sidecar.go
+++ b/cmd/sam-node/sidecar.go
@@ -444,8 +444,17 @@ func createEgressProxy(node *SamNode) http.Handler {
return
}
- r.Header.Del("Authorization")
- r.Header.Set("X-Sam-Biscuit", base64.StdEncoding.EncodeToString(biscuitBytes))
+ r.Header.Set(api.HeaderSamBiscuit, base64.StdEncoding.EncodeToString(biscuitBytes))
+
+ // Map X-Sam-Authorization to Authorization header for the remote service,
+ // and delete the local sidecar Authorization header to prevent leaking it.
+ if upstreamAuth := r.Header.Get(api.HeaderSamAuthorization); upstreamAuth != "" {
+ r.Header.Set("Authorization", upstreamAuth)
+ r.Header.Del(api.HeaderSamAuthorization)
+ } else {
+ r.Header.Del("Authorization")
+ }
+
proxy.ServeHTTP(w, r)
})
}
diff --git a/cmd/sam-node/store.go b/cmd/sam-node/store.go
index 41a7338e..a5e631bc 100644
--- a/cmd/sam-node/store.go
+++ b/cmd/sam-node/store.go
@@ -88,7 +88,11 @@ func (s *Store) LoadIdentity() ([]byte, error) {
var val []byte
_ = s.db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(bucketIdentity))
- val = b.Get([]byte(keyBiscuit))
+ dbVal := b.Get([]byte(keyBiscuit))
+ if len(dbVal) > 0 {
+ val = make([]byte, len(dbVal))
+ copy(val, dbVal)
+ }
return nil
})
if len(val) == 0 {
@@ -178,7 +182,11 @@ func (s *Store) LoadKey() ([]byte, error) {
var val []byte
_ = s.db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(bucketIdentity))
- val = b.Get([]byte(keyPrivKey))
+ dbVal := b.Get([]byte(keyPrivKey))
+ if len(dbVal) > 0 {
+ val = make([]byte, len(dbVal))
+ copy(val, dbVal)
+ }
return nil
})
return val, nil
@@ -200,7 +208,11 @@ func (s *Store) LoadHubConfig() ([]byte, []string, error) {
var addrs []string
err := s.db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(bucketIdentity))
- pubKey = b.Get([]byte("hub_public_key"))
+ dbVal := b.Get([]byte("hub_public_key"))
+ if len(dbVal) > 0 {
+ pubKey = make([]byte, len(dbVal))
+ copy(pubKey, dbVal)
+ }
addrsBytes := b.Get([]byte("hub_addresses"))
if len(addrsBytes) > 0 {
return json.Unmarshal(addrsBytes, &addrs)
diff --git a/go.mod b/go.mod
index 1da3ea21..73343ddf 100644
--- a/go.mod
+++ b/go.mod
@@ -36,7 +36,6 @@ require (
filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5 // indirect
filippo.io/keygen v0.0.0-20260114151900-8e2790ea4c5b // indirect
github.com/alecthomas/participle/v2 v2.1.4 // indirect
- github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/benbjohnson/clock v1.3.5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
diff --git a/go.sum b/go.sum
index 3a74c782..3966b25e 100644
--- a/go.sum
+++ b/go.sum
@@ -8,8 +8,6 @@ github.com/alecthomas/participle/v2 v2.1.4 h1:W/H79S8Sat/krZ3el6sQMvMaahJ+XcM9WS
github.com/alecthomas/participle/v2 v2.1.4/go.mod h1:8tqVbpTX20Ru4NfYQgZf4mP18eXPTBViyMWiArNEgGI=
github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=
github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
-github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
-github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o=
github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=