Skip to content

Agent Mesh

remove tool mcp granularity

Antonio Ojeab0b7c9878dc8
diff --git a/.github/k8s/sam-node-openclaw-template.yaml b/.github/k8s/sam-node-openclaw-template.yaml
index 27c1656e..a30d8bf4 100644
--- a/.github/k8s/sam-node-openclaw-template.yaml
+++ b/.github/k8s/sam-node-openclaw-template.yaml
@@ -7,7 +7,9 @@ data:
sam-node.yaml: |
version: "v1alpha1"
attenuation:
- policies: []
+ policies:
+ - 'allow if operation("mcp:openclaw");'
+ - 'allow if operation("/sam/catalog");'
checks: []
rules: []
services:
diff --git a/.github/k8s/sam-node-template.yaml b/.github/k8s/sam-node-template.yaml
index 40ad62ed..1c33cbf1 100644
--- a/.github/k8s/sam-node-template.yaml
+++ b/.github/k8s/sam-node-template.yaml
@@ -44,6 +44,7 @@ spec:
image: ghcr.io/google/sam-node:${IMAGE_TAG}
args:
- "run"
+ - "--trust-hub-rbac"
- "--config=/etc/sam/sam-node.yaml"
- "--hub=http://sam-hub-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:9090"
- "--jwt-path=/var/run/secrets/tokens/sam-token"
diff --git a/.github/k8s/sam-node-vllm-template.yaml b/.github/k8s/sam-node-vllm-template.yaml
index fba091a2..4434b32b 100644
--- a/.github/k8s/sam-node-vllm-template.yaml
+++ b/.github/k8s/sam-node-vllm-template.yaml
@@ -19,7 +19,8 @@ data:
sam-node.yaml: |
version: "v1alpha1"
attenuation:
- policies: []
+ policies:
+ - 'allow if operation("inference:vllm-tpu"), user("system:serviceaccount:sam-canary-${ENV_NAME}:sam-node-sa");'
checks: []
rules: []
services:
diff --git a/api/constants.go b/api/constants.go
index 84ca5b8e..c2603682 100644
--- a/api/constants.go
+++ b/api/constants.go
@@ -32,6 +32,6 @@ const (
FactGroup = "group"
FactRole = "role"
FactUser = "user"
- FactMCPTool = "allow_mcp_tool"
+ FactMCPServer = "allow_mcp_server"
FactNetworkTarget = "allow_network_target"
)
diff --git a/api/policy.go b/api/policy.go
index 2c9b92ee..f7dc7c2a 100644
--- a/api/policy.go
+++ b/api/policy.go
@@ -24,7 +24,7 @@ type NetworkPolicy struct {
}
type MCPPolicy struct {
- AllowedTools []string `yaml:"allowed_tools"`
+ AllowedServers []string `yaml:"allowed_servers"`
}
type ServiceConfig struct {
diff --git a/api/sam.pb.go b/api/sam.pb.go
index 8aa9d233..28ef1be7 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -133,6 +133,7 @@ func (MeshEvent_Type) EnumDescriptor() ([]byte, []int) {
type AuthFrame struct {
state protoimpl.MessageState `protogen:"open.v1"`
Biscuit []byte `protobuf:"bytes,1,opt,name=biscuit,proto3" json:"biscuit,omitempty"`
+ TargetService string `protobuf:"bytes,2,opt,name=target_service,json=targetService,proto3" json:"target_service,omitempty"` // Optional: specific service requested
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -174,6 +175,13 @@ func (x *AuthFrame) GetBiscuit() []byte {
return nil
}
+func (x *AuthFrame) GetTargetService() string {
+ if x != nil {
+ return x.TargetService
+ }
+ return ""
+}
+
type AuthResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"`
@@ -772,9 +780,10 @@ var File_api_sam_proto protoreflect.FileDescriptor
const file_api_sam_proto_rawDesc = "" +
"\n" +
- "\rapi/sam.proto\x12\x06sam.v1\"%\n" +
+ "\rapi/sam.proto\x12\x06sam.v1\"L\n" +
"\tAuthFrame\x12\x18\n" +
- "\abiscuit\x18\x01 \x01(\fR\abiscuit\">\n" +
+ "\abiscuit\x18\x01 \x01(\fR\abiscuit\x12%\n" +
+ "\x0etarget_service\x18\x02 \x01(\tR\rtargetService\">\n" +
"\fAuthResponse\x12\x18\n" +
"\asuccess\x18\x01 \x01(\bR\asuccess\x12\x14\n" +
"\x05error\x18\x02 \x01(\tR\x05error\"\xd8\x01\n" +
diff --git a/api/sam.proto b/api/sam.proto
index 9b49a9af..8aa775a1 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -20,6 +20,7 @@ option go_package = "github.com/google/sam/api";
message AuthFrame {
bytes biscuit = 1;
+ string target_service = 2; // Optional: specific service requested
}
message AuthResponse {
diff --git a/cmd/sam-hub/config.go b/cmd/sam-hub/config.go
index fe488fc3..a093a529 100644
--- a/cmd/sam-hub/config.go
+++ b/cmd/sam-hub/config.go
@@ -71,7 +71,7 @@ func ValidatePolicyConfig(config *api.PolicyConfig) error {
return fmt.Errorf("wildcard target '*' is not allowed in role %q", role)
}
}
- for _, tool := range rolePolicy.MCP.AllowedTools {
+ for _, tool := range rolePolicy.MCP.AllowedServers {
if tool == "*" {
return fmt.Errorf("wildcard tool '*' is not allowed in role %q", role)
}
diff --git a/cmd/sam-hub/config_test.go b/cmd/sam-hub/config_test.go
index 8588a7fe..10345977 100644
--- a/cmd/sam-hub/config_test.go
+++ b/cmd/sam-hub/config_test.go
@@ -15,7 +15,7 @@ roles:
network:
allowed_targets: ["db-agent.data-mesh"]
mcp:
- allowed_tools: ["query_database"]
+ allowed_servers: ["query_database"]
custom_datalog:
- 'department("analytics");'
`
@@ -39,8 +39,8 @@ roles:
if len(role.Network.AllowedTargets) != 1 || role.Network.AllowedTargets[0] != "db-agent.data-mesh" {
t.Errorf("unexpected allowed targets: %v", role.Network.AllowedTargets)
}
- if len(role.MCP.AllowedTools) != 1 || role.MCP.AllowedTools[0] != "query_database" {
- t.Errorf("unexpected allowed tools: %v", role.MCP.AllowedTools)
+ if len(role.MCP.AllowedServers) != 1 || role.MCP.AllowedServers[0] != "query_database" {
+ t.Errorf("unexpected allowed tools: %v", role.MCP.AllowedServers)
}
if len(role.CustomDatalog) != 1 || role.CustomDatalog[0] != `department("analytics");` {
t.Errorf("unexpected custom datalog: %v", role.CustomDatalog)
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.go
index 3bc37b94..6e2177d1 100644
--- a/cmd/sam-hub/main.go
+++ b/cmd/sam-hub/main.go
@@ -480,9 +480,9 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remote
if h.Policy != nil {
if rolePolicy, ok := h.Policy.Roles[role]; ok {
- for _, tool := range rolePolicy.MCP.AllowedTools {
+ for _, tool := range rolePolicy.MCP.AllowedServers {
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactMCPTool,
+ Name: api.FactMCPServer,
IDs: []biscuit.Term{biscuit.String(tool)},
}}); err != nil {
logger.Errorw("Failed to add MCP tool fact to biscuit", "peer_id", remotePeer, "tool", tool, "error", err)
diff --git a/cmd/sam-hub/main_test.go b/cmd/sam-hub/main_test.go
index 3b089460..6274c154 100644
--- a/cmd/sam-hub/main_test.go
+++ b/cmd/sam-hub/main_test.go
@@ -58,7 +58,7 @@ func TestMintBiscuitToken(t *testing.T) {
Roles: map[string]api.RolePolicy{
"admin": {
MCP: api.MCPPolicy{
- AllowedTools: []string{"read", "write"},
+ AllowedServers: []string{"read", "write"},
},
Network: api.NetworkPolicy{
AllowedTargets: []string{"target1"},
@@ -66,7 +66,7 @@ func TestMintBiscuitToken(t *testing.T) {
},
"canary-role": {
MCP: api.MCPPolicy{
- AllowedTools: []string{"/sam/mcp/1.0.0"},
+ AllowedServers: []string{"/sam/mcp/1.0.0"},
},
},
},
diff --git a/cmd/sam-node/gate_test.go b/cmd/sam-node/gate_test.go
index 5e9e2341..d00a899b 100644
--- a/cmd/sam-node/gate_test.go
+++ b/cmd/sam-node/gate_test.go
@@ -124,6 +124,7 @@ func startBareNode(t *testing.T, ctx context.Context) (*SamNode, func()) {
AllowLoopback: true,
MonitorBootstrap: 2 * time.Minute,
MonitorInterval: 1 * time.Minute,
+ TrustHubRBAC: true,
})
if err != nil {
t.Fatal(err)
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 42bd7f95..e6027520 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -78,10 +78,11 @@ var (
autoRelayBootDelayFlag time.Duration
autoRelayBackoffFlag time.Duration
- apiTokenFlag string
- tlsCertFlag string
- tlsKeyFlag string
- tlsCAFlag string
+ apiTokenFlag string
+ tlsCertFlag string
+ tlsKeyFlag string
+ tlsCAFlag string
+ trustHubRBACFlag bool
)
var logger = golog.Logger("sam-node")
@@ -183,13 +184,13 @@ func main() {
}
priv := getOrGenerateKey(store)
node, err = NewSamNode(context.Background(), SamNodeConfig{
- PrivKey: priv,
- HubPubKey: hubPubKey,
- HubAddrs: hubAddrs,
- Store: store,
- MeshID: meshFlag,
- DiscoveryInterval: discoveryIntervalFlag,
- ListenAddrs: listenAddrs,
+ PrivKey: priv,
+ HubPubKey: hubPubKey,
+ HubAddrs: hubAddrs,
+ Store: store,
+ MeshID: meshFlag,
+ DiscoveryInterval: discoveryIntervalFlag,
+ ListenAddrs: listenAddrs,
EnableRelay: enableRelayFlag,
NodeConfig: nodeConfig,
KeyGracePeriod: keyGracePeriodFlag,
@@ -199,6 +200,7 @@ func main() {
AutoRelayMinInterval: autoRelayMinIntervalFlag,
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
+ TrustHubRBAC: trustHubRBACFlag,
})
if err != nil {
logger.Fatalf("Failed to start mesh node: %v", err)
@@ -239,13 +241,13 @@ func main() {
priv := getOrGenerateKey(store)
enrollCtx, enrollCancel := context.WithCancel(context.Background())
node, err = NewSamNode(enrollCtx, SamNodeConfig{
- PrivKey: priv,
- HubAddrs: initHubAddrs,
- Store: store,
- MeshID: meshFlag,
- DiscoveryInterval: discoveryIntervalFlag,
- ListenAddrs: listenAddrs,
- EnableRelay: enableRelayFlag,
+ PrivKey: priv,
+ HubAddrs: initHubAddrs,
+ Store: store,
+ MeshID: meshFlag,
+ DiscoveryInterval: discoveryIntervalFlag,
+ ListenAddrs: listenAddrs,
+ EnableRelay: enableRelayFlag,
NodeConfig: nodeConfig,
KeyGracePeriod: keyGracePeriodFlag,
AllowLoopback: allowLoopbackFlag,
@@ -254,6 +256,7 @@ func main() {
AutoRelayMinInterval: autoRelayMinIntervalFlag,
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
+ TrustHubRBAC: trustHubRBACFlag,
})
if err != nil {
enrollCancel()
@@ -285,14 +288,14 @@ func main() {
logger.Debugf("listenAddrs: %v, allowLoopback: %v", listenAddrs, allowLoopbackFlag)
node, err = NewSamNode(context.Background(), SamNodeConfig{
- PrivKey: priv,
- HubPubKey: hubPubKey,
- HubAddrs: newHubAddrs,
- Store: store,
- MeshID: meshFlag,
- DiscoveryInterval: discoveryIntervalFlag,
- ListenAddrs: listenAddrs,
- EnableRelay: enableRelayFlag,
+ PrivKey: priv,
+ HubPubKey: hubPubKey,
+ HubAddrs: newHubAddrs,
+ Store: store,
+ MeshID: meshFlag,
+ DiscoveryInterval: discoveryIntervalFlag,
+ ListenAddrs: listenAddrs,
+ EnableRelay: enableRelayFlag,
NodeConfig: nodeConfig,
KeyGracePeriod: keyGracePeriodFlag,
AllowLoopback: allowLoopbackFlag,
@@ -301,6 +304,7 @@ func main() {
AutoRelayMinInterval: autoRelayMinIntervalFlag,
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
+ TrustHubRBAC: trustHubRBACFlag,
})
if err != nil {
logger.Fatalf("Failed to start mesh node after enrollment: %v", err)
@@ -433,13 +437,13 @@ func main() {
priv := getOrGenerateKey(store)
node, err := NewSamNode(context.Background(), SamNodeConfig{
- PrivKey: priv,
- HubAddrs: initHubAddrs,
- Store: store,
- MeshID: meshFlag,
- DiscoveryInterval: discoveryIntervalFlag,
- ListenAddrs: []string{"/ip4/0.0.0.0/udp/0/quic-v1", "/ip4/0.0.0.0/tcp/0"},
- EnableRelay: enableRelayFlag,
+ PrivKey: priv,
+ HubAddrs: initHubAddrs,
+ Store: store,
+ MeshID: meshFlag,
+ DiscoveryInterval: discoveryIntervalFlag,
+ ListenAddrs: []string{"/ip4/0.0.0.0/udp/0/quic-v1", "/ip4/0.0.0.0/tcp/0"},
+ EnableRelay: enableRelayFlag,
NodeConfig: nodeConfig,
KeyGracePeriod: keyGracePeriodFlag,
AllowLoopback: allowLoopbackFlag,
@@ -448,6 +452,7 @@ func main() {
AutoRelayMinInterval: 30 * time.Second,
AutoRelayBootDelay: 0 * time.Second,
AutoRelayBackoff: 3 * time.Second,
+ TrustHubRBAC: false,
})
if err != nil {
logger.Fatalf("Failed to initialize node for enrollment: %v", err)
@@ -489,6 +494,7 @@ func main() {
runCmd.Flags().StringVar(&tlsCertFlag, "tls-cert", "", "Path to TLS certificate for sidecar API")
runCmd.Flags().StringVar(&tlsKeyFlag, "tls-key", "", "Path to TLS key for sidecar API")
runCmd.Flags().StringVar(&tlsCAFlag, "tls-ca", "", "Path to TLS CA for sidecar API mTLS")
+ runCmd.Flags().BoolVar(&trustHubRBACFlag, "trust-hub-rbac", false, "Apply baseline rules to trust the hub's RBAC")
rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", DefaultHubURL, "Hub URL")
rootCmd.PersistentFlags().StringVar(&configFile, "config", DefaultConfigFile, "Path to sam-node.yaml configuration file")
rootCmd.PersistentFlags().StringVar(&oidcIssuerFlag, "oidc-issuer", "", "OIDC Issuer URL")
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index 73b6d721..32adf2e9 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -196,9 +196,16 @@ func (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolN
return nil, fmt.Errorf("failed to load identity biscuit: %w", err)
}
+ // Extract target service if it's a federated tool call (service.tool)
+ targetService := toolName
+ if parts := strings.SplitN(toolName, ".", 2); len(parts) == 2 {
+ targetService = parts[0]
+ }
+
// Marshal AuthFrame
authFrame := api.AuthFrame{
- Biscuit: biscuitBytes,
+ Biscuit: biscuitBytes,
+ TargetService: targetService,
}
authBytes, _ := proto.Marshal(&authFrame)
diff --git a/cmd/sam-node/mcp_handlers_test.go b/cmd/sam-node/mcp_handlers_test.go
index fd0dddfa..f118bc73 100644
--- a/cmd/sam-node/mcp_handlers_test.go
+++ b/cmd/sam-node/mcp_handlers_test.go
@@ -20,7 +20,7 @@ import (
)
// buildAndSaveBiscuit builds a biscuit signed with rootPriv that identifies
-// node as caller, grants allow_mcp_tool("*"), and saves it to node's store.
+// node as caller, grants allow_mcp_server("*"), and saves it to node's store.
func buildAndSaveBiscuit(node *SamNode, rootPriv ed25519.PrivateKey) error {
callerID := node.Host.ID().String()
builder := biscuit.NewBuilder(rootPriv)
@@ -37,7 +37,7 @@ func buildAndSaveBiscuit(node *SamNode, rootPriv ed25519.PrivateKey) error {
return err
}
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactMCPTool,
+ Name: api.FactMCPServer,
IDs: []biscuit.Term{biscuit.String("*")},
}}); err != nil {
return err
diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.go
index 71873c20..83ddb54f 100644
--- a/cmd/sam-node/middleware.go
+++ b/cmd/sam-node/middleware.go
@@ -28,27 +28,26 @@ import (
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
- "github.com/libp2p/go-libp2p/core/protocol"
"github.com/libp2p/go-msgio"
"google.golang.org/protobuf/proto"
)
var (
- baselineRule1 biscuit.Policy
- baselineRule2 biscuit.Policy
- baselineRule3 biscuit.Policy
+ baselineRule1 biscuit.Policy
+ baselineRule2 biscuit.Policy
+ baselineRule3 biscuit.Policy
baselineReplayCheck biscuit.Check
)
func init() {
var err error
- rule1Str := fmt.Sprintf(`allow if operation($op), %s($op)`, api.FactMCPTool)
+ rule1Str := fmt.Sprintf(`allow if operation($op), %s($op)`, api.FactMCPServer)
baselineRule1, err = parser.FromStringPolicy(rule1Str)
if err != nil {
panic(fmt.Sprintf("failed to parse baseline rule 1: %v", err))
}
- rule2Str := fmt.Sprintf(`allow if operation($op), %s("*")`, api.FactMCPTool)
+ rule2Str := fmt.Sprintf(`allow if operation($op), %s("*")`, api.FactMCPServer)
baselineRule2, err = parser.FromStringPolicy(rule2Str)
if err != nil {
panic(fmt.Sprintf("failed to parse baseline rule 2: %v", err))
@@ -71,7 +70,8 @@ type RequestContext struct {
PeerID peer.ID
User string
Group string
- Protocol protocol.ID
+ Protocol string
+ Target string
}
// WithBiscuitAuth enforces a Protobuf handshake on a stream before calling the next handler.
@@ -107,7 +107,8 @@ func (n *SamNode) WithBiscuitAuth(next network.StreamHandler) network.StreamHand
reqCtx := RequestContext{
PeerID: remotePeer,
User: "", // Not used in Authorize
- Protocol: s.Protocol(),
+ Protocol: string(s.Protocol()),
+ Target: authFrame.TargetService,
}
writer := msgio.NewVarintWriter(s)
@@ -274,10 +275,14 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
}
// Inject the current action context (Standard Vocabulary)
+ op := req.Protocol
+ if req.Target != "" {
+ op = req.Target
+ }
authorizer.AddFact(biscuit.Fact{
Predicate: biscuit.Predicate{
Name: "operation",
- IDs: []biscuit.Term{biscuit.String(req.Protocol)},
+ IDs: []biscuit.Term{biscuit.String(op)},
},
})
@@ -306,9 +311,15 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
}
// Baseline Rules
- authorizer.AddPolicy(baselineRule1)
- authorizer.AddPolicy(baselineRule2)
- authorizer.AddPolicy(baselineRule3)
+ if n.TrustHubRBAC {
+ authorizer.AddPolicy(baselineRule1)
+ authorizer.AddPolicy(baselineRule2)
+ authorizer.AddPolicy(baselineRule3)
+ }
- return authorizer.Authorize()
+ err = authorizer.Authorize()
+ if err != nil {
+ logger.Errorf("Authorizer failure: %v\nState: %s", err, authorizer.PrintWorld())
+ }
+ return err
}
diff --git a/cmd/sam-node/middleware_test.go b/cmd/sam-node/middleware_test.go
index 78b280c0..b3aebb49 100644
--- a/cmd/sam-node/middleware_test.go
+++ b/cmd/sam-node/middleware_test.go
@@ -128,7 +128,7 @@ func TestAuthorize(t *testing.T) {
// Add fact to match baseline rule
err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactMCPTool,
+ Name: api.FactMCPServer,
IDs: []biscuit.Term{biscuit.String("/test/proto")},
}})
if err != nil {
@@ -146,8 +146,9 @@ func TestAuthorize(t *testing.T) {
}
node := &SamNode{
- Store: store,
- trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
+ Store: store,
+ trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
+ TrustHubRBAC: true,
}
req := RequestContext{
@@ -178,7 +179,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 1 (Happy Path)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`allow_mcp_tool("query_db")`)
+ fact, err := parser.FromStringFact(`allow_mcp_server("query_db")`)
if err != nil {
t.Fatal(err)
}
@@ -192,7 +193,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 2 (Unauthorized Tool)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`allow_mcp_tool("query_db")`)
+ fact, err := parser.FromStringFact(`allow_mcp_server("query_db")`)
if err != nil {
t.Fatal(err)
}
@@ -206,7 +207,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 3 (Wildcard Access)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`allow_mcp_tool("*")`)
+ fact, err := parser.FromStringFact(`allow_mcp_server("*")`)
if err != nil {
t.Fatal(err)
}
@@ -220,7 +221,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 4 (Local Attenuation Override)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact1, err := parser.FromStringFact(`allow_mcp_tool("*")`)
+ fact1, err := parser.FromStringFact(`allow_mcp_server("*")`)
if err != nil {
t.Fatal(err)
}
@@ -294,13 +295,14 @@ attenuation:
}
node := &SamNode{
- trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
- LocalPolicy: localPolicy,
+ trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
+ LocalPolicy: localPolicy,
+ TrustHubRBAC: true,
}
req := RequestContext{
PeerID: dummyPeer,
- Protocol: protocol.ID(tt.operation),
+ Protocol: string(tt.operation),
}
err = node.Authorize(tokenBytes, req, pub)
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index ed0ac4aa..2771a986 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -114,6 +114,7 @@ type SamNode struct {
services *ServiceRegistry
BoundHTTPAddr string
AllowLoopback bool
+ TrustHubRBAC bool
authSuccess chan struct{}
authOnce sync.Once
currentRelays []peer.AddrInfo
@@ -152,6 +153,7 @@ type SamNodeConfig struct {
AutoRelayMinInterval time.Duration
AutoRelayBootDelay time.Duration
AutoRelayBackoff time.Duration
+ TrustHubRBAC bool
}
// NewSamNode creates a new Agent instance secured with the 4-layer pipeline.
@@ -169,6 +171,7 @@ func NewSamNode(ctx context.Context, cfg SamNodeConfig) (*SamNode, error) {
topics: make(map[string]*pubsub.Topic),
LocalPolicy: cfg.NodeConfig,
AllowLoopback: cfg.AllowLoopback,
+ TrustHubRBAC: cfg.TrustHubRBAC,
authSuccess: make(chan struct{}),
}
diff --git a/cmd/sam-node/service_registry.go b/cmd/sam-node/service_registry.go
index ddc8715c..fc8c6075 100644
--- a/cmd/sam-node/service_registry.go
+++ b/cmd/sam-node/service_registry.go
@@ -18,6 +18,7 @@ import (
"context"
"fmt"
"sync"
+ "time"
"github.com/google/sam/api"
"github.com/ipfs/go-cid"
@@ -65,10 +66,13 @@ func (r *ServiceRegistry) Register(ctx context.Context, svc Service) error {
return err
}
- if err := r.dht.Provide(ctx, srvNameCID, true); err != nil {
+ provideCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+
+ if err := r.dht.Provide(provideCtx, srvNameCID, true); err != nil {
logger.Warnf("[ServiceRegistry] DHT Provide (name) for %s: %v", info.Name, err)
}
- if err := r.dht.Provide(ctx, srvTypeCID, true); err != nil {
+ if err := r.dht.Provide(provideCtx, srvTypeCID, true); err != nil {
logger.Warnf("[ServiceRegistry] DHT Provide (type) for %s: %v", info.Name, err)
}
diff --git a/tests/e2e/docker/calc-mcp/sam-node-config.yaml b/tests/e2e/docker/calc-mcp/sam-node-config.yaml
index fb4809ff..fdc5562d 100644
--- a/tests/e2e/docker/calc-mcp/sam-node-config.yaml
+++ b/tests/e2e/docker/calc-mcp/sam-node-config.yaml
@@ -3,7 +3,7 @@ attenuation:
# Receiver-side: allow MCP only when the caller's biscuit was minted by
# our hub for some peer (zero-trust narrow than "any valid OIDC token").
policies:
- - 'allow if operation("/sam/mcp/1.0.0"), node($peer)'
+ - 'allow if operation($op), node($peer)'
services:
- type: "mcp"
name: "calculator"
diff --git a/tests/e2e/policy.bats b/tests/e2e/policy.bats
index 3f96f1ab..a29c2523 100644
--- a/tests/e2e/policy.bats
+++ b/tests/e2e/policy.bats
@@ -150,7 +150,7 @@ bindings:
roles:
mesh-member:
mcp:
- allowed_tools:
+ allowed_servers:
- \"query_database\"
- \"delete_tables\""
diff --git a/tests/e2e/sam.bats b/tests/e2e/sam.bats
index 5b636d4e..2b7af2f2 100644
--- a/tests/e2e/sam.bats
+++ b/tests/e2e/sam.bats
@@ -26,7 +26,7 @@ teardown() {
-@test "sam-node run without identity fails" {
+@test "sam-node run --trust-hub-rbac without identity fails" {
run "$SAM_NODE_BINARY" run
[[ "$status" -ne 0 ]]
[[ "$output" == *"No JWT or stored identity found"* ]]
diff --git a/tests/e2e/watch.bats b/tests/e2e/watch.bats
index 3f29ff45..4c4fbef1 100644
--- a/tests/e2e/watch.bats
+++ b/tests/e2e/watch.bats
@@ -19,7 +19,7 @@ teardown() {
rm -rf "$TEST_TMPDIR"
}
-@test "sam-node run with stored identity fails if hub is unreachable" {
+@test "sam-node run --trust-hub-rbac with stored identity fails if hub is unreachable" {
run "$SAM_NODE_BINARY" run --listen /ip4/127.0.0.1/udp/0/quic-v1 --listen /ip4/127.0.0.1/tcp/0
if [[ "$status" -eq 0 ]]; then
diff --git a/tests/integration/call_test.go b/tests/integration/call_test.go
index a8f0c317..6eb8d897 100644
--- a/tests/integration/call_test.go
+++ b/tests/integration/call_test.go
@@ -22,7 +22,7 @@ import (
func TestSamNodeRunHelp(t *testing.T) {
nodeBin := buildBinary(t, "./cmd/sam-node")
- stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, nil, "", nodeBin, "run", "--help")
+ stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, nil, "", nodeBin, "run", "--trust-hub-rbac", "--help")
if err != nil {
t.Fatalf("sam-node run --help failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
diff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.go
index 921f9fdb..38a2229a 100644
--- a/tests/integration/catalog_test.go
+++ b/tests/integration/catalog_test.go
@@ -19,7 +19,7 @@ func startBackgroundNode(t *testing.T, nodeBin string, hubAddr string, homeDir s
"HOME="+homeDir,
"XDG_CONFIG_HOME="+filepath.Join(homeDir, ".config"),
)
- allArgs := append([]string{"run", "--hub", hubAddr, "--jwt", "test-jwt", "--bind-addr", "127.0.0.1:0", "--api-token", "test-token", "--allow-loopback"}, args...)
+ allArgs := append([]string{"run", "--trust-hub-rbac", "--hub", hubAddr, "--jwt", "test-jwt", "--bind-addr", "127.0.0.1:0", "--api-token", "test-token", "--allow-loopback"}, args...)
cmd := exec.Command(nodeBin, allArgs...)
cmd.Env = env
diff --git a/tests/integration/cuj_test.go b/tests/integration/cuj_test.go
index 92dbfde6..52e94d1d 100644
--- a/tests/integration/cuj_test.go
+++ b/tests/integration/cuj_test.go
@@ -39,7 +39,7 @@ func TestSamNodeRunWithManualTokenStarts(t *testing.T) {
env,
"",
nodeBin,
- "run",
+ "run", "--trust-hub-rbac",
"--hub", hubAddr,
"--jwt", "test-jwt",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
diff --git a/tests/integration/failover_test.go b/tests/integration/failover_test.go
index 57e3c835..0666822b 100644
--- a/tests/integration/failover_test.go
+++ b/tests/integration/failover_test.go
@@ -134,7 +134,7 @@ roles: {}
"HOME="+nodeHome,
"XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config"),
)
- cmdNode := exec.Command(nodeBin, "run",
+ cmdNode := exec.Command(nodeBin, "run", "--trust-hub-rbac",
"--hub", lb.URL,
"--listen", "/ip4/127.0.0.1/tcp/0",
"--jwt-path", jwtPath,
diff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.go
index c60c2285..3357a897 100644
--- a/tests/integration/fallback_test.go
+++ b/tests/integration/fallback_test.go
@@ -83,7 +83,7 @@ func TestFallbackReEnrollment(t *testing.T) {
t.Fatal(err)
}
- toolFact, _ := parser.FromStringFact(`allow_mcp_tool("*")`)
+ toolFact, _ := parser.FromStringFact(`allow_mcp_server("*")`)
if err := builder.AddAuthorityFact(toolFact); err != nil {
t.Fatal(err)
}
@@ -119,7 +119,7 @@ func TestFallbackReEnrollment(t *testing.T) {
}
// 5. Run Node in background
- cmd := exec.Command(nodeBin, "run", "--hub", hubAddr, "--listen", "/ip4/127.0.0.1/tcp/0", "--jwt-path", jwtPath, "--bind-addr", "127.0.0.1:0", "--api-token", "dummy-token", "--allow-loopback")
+ cmd := exec.Command(nodeBin, "run", "--trust-hub-rbac", "--hub", hubAddr, "--listen", "/ip4/127.0.0.1/tcp/0", "--jwt-path", jwtPath, "--bind-addr", "127.0.0.1:0", "--api-token", "dummy-token", "--allow-loopback")
cmd.Dir = repoRoot(t)
cmd.Env = env
@@ -482,7 +482,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {
mu.Unlock()
// Step 3: Start sam-node run
- runCmd := exec.Command(nodeBin, "run", "--listen", "/ip4/127.0.0.1/tcp/0")
+ runCmd := exec.Command(nodeBin, "run", "--trust-hub-rbac", "--listen", "/ip4/127.0.0.1/tcp/0")
runCmd.Env = env
var stdout safeBuffer
runCmd.Stdout = &stdout
diff --git a/tests/integration/federation_test.go b/tests/integration/federation_test.go
index d6e34700..9fede8cd 100644
--- a/tests/integration/federation_test.go
+++ b/tests/integration/federation_test.go
@@ -35,7 +35,7 @@ bindings:
roles:
admin:
mcp:
- allowed_tools:
+ allowed_servers:
- "/sam/mcp/1.0.0"
- "list_local_services"
- "discover_remote_services"
@@ -118,7 +118,7 @@ roles:
// Node A connects to Hub A
apiPortA := getFreePort(t)
- nodeACmd := exec.Command(nodeBin, "run",
+ nodeACmd := exec.Command(nodeBin, "run", "--trust-hub-rbac",
"--hub", fmt.Sprintf("http://127.0.0.1:%d", portA),
"--data-dir", filepath.Join(tmpDir, "nodeA"),
"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),
@@ -140,7 +140,7 @@ roles:
// Node B connects to Hub B
apiPortB := getFreePort(t)
- nodeBCmd := exec.Command(nodeBin, "run",
+ nodeBCmd := exec.Command(nodeBin, "run", "--trust-hub-rbac",
"--hub", fmt.Sprintf("http://127.0.0.1:%d", portB),
"--data-dir", filepath.Join(tmpDir, "nodeB"),
"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),
diff --git a/tests/integration/login_test.go b/tests/integration/login_test.go
index acbd808d..b586161e 100644
--- a/tests/integration/login_test.go
+++ b/tests/integration/login_test.go
@@ -101,7 +101,7 @@ func TestSamNodeJoin(t *testing.T) {
env,
"",
nodeBin,
- "run",
+ "run", "--trust-hub-rbac",
"--hub", hubAddr,
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
diff --git a/tests/integration/p2p_test.go b/tests/integration/p2p_test.go
index b667dfc1..19c86b20 100644
--- a/tests/integration/p2p_test.go
+++ b/tests/integration/p2p_test.go
@@ -29,7 +29,7 @@ func TestSamNodeRunWithoutIdentity(t *testing.T) {
"HOME=" + tmpHome,
"XDG_CONFIG_HOME=" + filepath.Join(tmpHome, ".config"),
}
- stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, append(os.Environ(), env...), "", nodeBin, "run")
+ stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, append(os.Environ(), env...), "", nodeBin, "run", "--trust-hub-rbac")
if err == nil {
t.Fatalf("expected sam-node run without identity to fail, but it succeeded\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
}
diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.go
index 6a09a78a..1ac8eddc 100644
--- a/tests/integration/proxy_test.go
+++ b/tests/integration/proxy_test.go
@@ -76,7 +76,7 @@ func TestSamNodeRunWithStoredIdentity(t *testing.T) {
env,
"",
nodeBin,
- "run",
+ "run", "--trust-hub-rbac",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
"--bind-addr", "127.0.0.1:0",
diff --git a/tests/integration/pubsub_test.go b/tests/integration/pubsub_test.go
index 2086a638..a4afb274 100644
--- a/tests/integration/pubsub_test.go
+++ b/tests/integration/pubsub_test.go
@@ -46,7 +46,7 @@ func TestPubSubTools(t *testing.T) {
// Start Node 1
env1 := append(os.Environ(), "HOME="+tmpHome1, "XDG_CONFIG_HOME="+filepath.Join(tmpHome1, ".config"))
- cmd1 := exec.CommandContext(ctx, nodeBin, "run", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5003/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5004", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "dummy-token", "--allow-loopback")
+ cmd1 := exec.CommandContext(ctx, nodeBin, "run", "--trust-hub-rbac", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5003/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5004", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "dummy-token", "--allow-loopback")
cmd1.Env = env1
logFile1, err := os.Create(filepath.Join(tmpHome1, "node1.log"))
if err != nil {
@@ -61,7 +61,7 @@ func TestPubSubTools(t *testing.T) {
// Start Node 2
env2 := append(os.Environ(), "HOME="+tmpHome2, "XDG_CONFIG_HOME="+filepath.Join(tmpHome2, ".config"))
- cmd2 := exec.CommandContext(ctx, nodeBin, "run", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5005/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5006", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "dummy-token", "--allow-loopback")
+ cmd2 := exec.CommandContext(ctx, nodeBin, "run", "--trust-hub-rbac", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5005/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5006", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "dummy-token", "--allow-loopback")
cmd2.Env = env2
logFile2, err := os.Create(filepath.Join(tmpHome2, "node2.log"))
if err != nil {
diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.go
index c5d2e021..d5fa9337 100644
--- a/tests/integration/service_discovery_test.go
+++ b/tests/integration/service_discovery_test.go
@@ -21,6 +21,7 @@ import (
"google.golang.org/protobuf/encoding/protojson"
"io"
"net/http"
+ "net/http/httptest"
"path/filepath"
"strings"
"testing"
@@ -93,9 +94,14 @@ func TestServiceDiscovery(t *testing.T) {
t.Fatalf("DHT not ready on Node A (size 0)")
}
+ mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "Not found", http.StatusNotFound)
+ }))
+ defer mockServer.Close()
+
// Agent A registers a service
serviceName := "mcp:github-tools"
- registerService(t, actualApiAddrA, apiToken, serviceName, "http://localhost:8080")
+ registerService(t, actualApiAddrA, apiToken, serviceName, mockServer.URL)
// Wait for DHT propagation
t.Log("Waiting for DHT propagation...")
@@ -191,9 +197,14 @@ func TestServiceDiscoveryStreaming(t *testing.T) {
t.Fatalf("DHT not ready on Node A")
}
+ mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "Not found", http.StatusNotFound)
+ }))
+ defer mockServer.Close()
+
// Agent A registers a service
serviceName := "mcp:github-tools"
- registerService(t, actualApiAddrA, apiToken, serviceName, "http://localhost:8080")
+ registerService(t, actualApiAddrA, apiToken, serviceName, mockServer.URL)
// Wait for DHT propagation
t.Log("Waiting for DHT propagation...")