Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
feat(policy): implement strict explicit Datalog policy targeting over OIDC mapped Facts
Antonio Ojea66cc64631712
diff --git a/.github/k8s/sam-hub-template.yaml b/.github/k8s/sam-hub-template.yamlindex 744b805a..e83c7083 100644--- a/.github/k8s/sam-hub-template.yaml+++ b/.github/k8s/sam-hub-template.yaml@@ -115,11 +115,11 @@ data:role: "sam-canary"roles:sam-canary:- mcp:- allowed_servers:- - "/sam/mcp/1.0.0"- - "/sam/catalog"-+ allowed_services:+ - "/sam/mcp/1.0.0"+ - "/sam/catalog"+ - "inference:openrouter"+ - "*"---apiVersion: monitoring.googleapis.com/v1kind: PodMonitoringdiff --git a/.github/k8s/sam-node-cop-template.yaml b/.github/k8s/sam-node-cop-template.yamlindex 73c94667..a85b8c24 100644--- a/.github/k8s/sam-node-cop-template.yaml+++ b/.github/k8s/sam-node-cop-template.yaml@@ -8,8 +8,8 @@ data:version: "v1alpha1"attenuation:policies:- - 'allow if operation("mcp:cop");'- - 'allow if operation("/sam/catalog");'+ - 'allow if service("mcp", "cop");'+ - 'allow if service("system", "/sam/catalog");'checks: []rules: []services: []diff --git a/.github/k8s/sam-node-everything-template.yaml b/.github/k8s/sam-node-everything-template.yamlindex 59f725c0..1a31dab4 100644--- a/.github/k8s/sam-node-everything-template.yaml+++ b/.github/k8s/sam-node-everything-template.yaml@@ -8,8 +8,8 @@ data:version: "v1alpha1"attenuation:policies:- - 'allow if operation("mcp:everything");'- - 'allow if operation("/sam/catalog");'+ - 'allow if service("mcp", "everything");'+ - 'allow if service("system", "/sam/catalog");'checks: []rules: []services:diff --git a/.github/k8s/sam-node-openclaw-template.yaml b/.github/k8s/sam-node-openclaw-template.yamlindex 0ce717d1..8280250b 100644--- a/.github/k8s/sam-node-openclaw-template.yaml+++ b/.github/k8s/sam-node-openclaw-template.yaml@@ -8,8 +8,8 @@ data:version: "v1alpha1"attenuation:policies:- - 'allow if operation("mcp:openclaw");'- - 'allow if operation("/sam/catalog");'+ - 'allow if service("mcp", "openclaw");'+ - 'allow if service("system", "/sam/catalog");'checks: []rules: []services: []diff --git a/.github/k8s/sam-node-openrouter-template.yaml b/.github/k8s/sam-node-openrouter-template.yamlnew file mode 100644index 00000000..f2d284c6--- /dev/null+++ b/.github/k8s/sam-node-openrouter-template.yaml@@ -0,0 +1,87 @@+apiVersion: v1+kind: ConfigMap+metadata:+ name: sam-canary-openrouter-config-${ENV_NAME}+ namespace: sam-canary-${ENV_NAME}+data:+ sam-node.yaml: |+ version: "v1alpha1"+ attenuation:+ policies:+ - 'allow if service("inference", "openrouter");'+ - 'allow if service("system", "/sam/catalog");'+ checks: []+ rules: []+ services:+ - type: inference+ name: openrouter+ description: "OpenRouter Proxy Inference Service"+ target_url: "http://localhost:4000"+---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: openrouter-canary-${ENV_NAME}+ namespace: sam-canary-${ENV_NAME}+spec:+ replicas: 1+ selector:+ matchLabels:+ app: openrouter-canary-${ENV_NAME}+ template:+ metadata:+ labels:+ app: openrouter-canary-${ENV_NAME}+ spec:+ serviceAccountName: sam-node-sa+ containers:+ - name: openrouter-proxy+ image: ghcr.io/berriai/litellm:main-latest+ command:+ - "litellm"+ - "--model"+ - "openrouter/auto"+ - "--port"+ - "4000"+ env:+ - name: OPENROUTER_API_KEY+ value: "${OPENROUTER_API_KEY}"+ ports:+ - containerPort: 4000+ resources:+ requests:+ cpu: 100m+ memory: 256Mi+ - name: sam-node+ image: ghcr.io/google/sam-node:${IMAGE_TAG}+ args:+ - "run"+ - "--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"+ - "--api-token=secret-token"+ - "--bind-addr=127.0.0.1:8080"+ - "--trust-hub-rbac"+ ports:+ - containerPort: 8080+ resources:+ requests:+ cpu: 500m+ memory: 128Mi+ volumeMounts:+ - name: config-volume+ mountPath: /etc/sam+ - name: sam-token+ mountPath: /var/run/secrets/tokens+ readOnly: true+ volumes:+ - name: config-volume+ configMap:+ name: sam-canary-openrouter-config-${ENV_NAME}+ - name: sam-token+ projected:+ sources:+ - serviceAccountToken:+ path: sam-token+ expirationSeconds: 3600+ audience: "sam-hub-audience"diff --git a/.github/k8s/sam-node-vllm-template.yaml b/.github/k8s/sam-node-vllm-template.yamlindex 5ce9fc4d..2bdc282f 100644--- a/.github/k8s/sam-node-vllm-template.yaml+++ b/.github/k8s/sam-node-vllm-template.yaml@@ -20,8 +20,8 @@ data:version: "v1alpha1"attenuation:policies:- - 'allow if operation("inference:vllm-tpu"), user("system:serviceaccount:sam-canary-${ENV_NAME}:sam-node-sa");'- - 'allow if operation("/sam/catalog");'+ - 'allow if service("inference", "vllm-tpu"), user("system:serviceaccount:sam-canary-${ENV_NAME}:sam-node-sa");'+ - 'allow if service("system", "/sam/catalog");'checks: []rules: []services:diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yamlindex d5ef217d..3c1424cc 100644--- a/.github/workflows/deploy.yaml+++ b/.github/workflows/deploy.yaml@@ -294,7 +294,7 @@ jobs:export HF_TOKEN="${{ secrets.HF_TOKEN }}"# Read and indent banana bot playground script for the ConfigMap template- export BANANA_BOT_SCRIPT=$(cat docs/snippets/banana_bot_playground.py | sed 's/^/ /')+ export BANANA_BOT_SCRIPT=$(cat site/content/docs/snippets/banana_bot_playground.py | sed 's/^/ /')# Provision the openclaw-secret, preserving the gateway-token if it existsGATEWAY_TOKEN=$(kubectl get secret openclaw-secret-${ENV_NAME} -n ${CANARY_NAMESPACE} -o jsonpath="{.data.gateway-token}" 2>/dev/null | base64 -d || openssl rand -hex 16)kubectl create secret generic openclaw-secret-${ENV_NAME} \@@ -360,3 +360,48 @@ jobs:kubectl rollout status deployment/everything-canary-${ENV_NAME} -n ${CANARY_NAMESPACE} || trueexit 1}++ - name: Deploy OpenRouter Node to Testnet+ env:+ OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}+ run: |+ print_rollout_diagnostics() {+ local namespace="$1"+ local deployment="$2"+ local selector="$3"++ echo "Collecting diagnostics for deployment/${deployment} in namespace ${namespace}..."++ kubectl describe deployment/${deployment} -n ${namespace} || true+ kubectl get pods -n ${namespace} -l "${selector}" -o wide || true+ kubectl describe pods -n ${namespace} -l "${selector}" || true+ kubectl get events -n ${namespace} --sort-by=.lastTimestamp || true++ for pod in $(kubectl get pods -n ${namespace} -l "${selector}" -o name 2>/dev/null); do+ echo "==== Describe ${pod} ===="+ kubectl describe -n ${namespace} "${pod}" || true++ for container in $(kubectl get -n ${namespace} "${pod}" -o jsonpath='{.spec.containers[*].name}' 2>/dev/null); do+ echo "==== Logs for ${pod} container ${container} ===="+ kubectl logs -n ${namespace} "${pod#pod/}" -c "${container}" --tail=-1 || true+ done+ done+ }++ export ENV_NAME="${{ vars.ENV_NAME }}"+ export NAMESPACE="sam-${ENV_NAME}"+ export CANARY_NAMESPACE="sam-canary-${ENV_NAME}"+ export IMAGE_TAG="${{ env.IMAGE_TAG }}"++ # Substitute the API key and other variables into the template and apply it to the cluster+ envsubst < .github/k8s/sam-node-openrouter-template.yaml | kubectl apply -f -++ kubectl rollout status deployment/openrouter-canary-${ENV_NAME} -n ${CANARY_NAMESPACE} --timeout=120s || {+ echo "OpenRouter Canary Deployment failed!"+ print_rollout_diagnostics "${CANARY_NAMESPACE}" "openrouter-canary-${ENV_NAME}" "app=openrouter-canary-${ENV_NAME}"++ echo "Rolling back OpenRouter Canary deployment..."+ kubectl rollout undo deployment/openrouter-canary-${ENV_NAME} -n ${CANARY_NAMESPACE}+ kubectl rollout status deployment/openrouter-canary-${ENV_NAME} -n ${CANARY_NAMESPACE} || true+ exit 1+ }diff --git a/api/constants.go b/api/constants.goindex 30beeb15..cb6e01c3 100644--- a/api/constants.go+++ b/api/constants.go@@ -40,7 +40,7 @@ const (FactRole = "role"FactUser = "user"FactEmail = "email"- FactMCPServer = "allow_mcp_server"+ FactAllowService = "allow_service"FactNetworkTarget = "allow_network_target")diff --git a/api/policy.go b/api/policy.goindex f7dc7c2a..cfff47f7 100644--- a/api/policy.go+++ b/api/policy.go@@ -10,21 +10,32 @@ type PolicyConfig struct {type Binding struct {Group string `yaml:"group,omitempty"`User string `yaml:"user,omitempty"`+ Email string `yaml:"email,omitempty"`Role string `yaml:"role"`}+// RolePolicy defines the capabilities granted to a specific authorization role.+//+// AllowedTargets restricts the logical endpoints a peer can route connections to.+// Targets act similarly to Active Directory network groups and must be specified+// using the format of the resolved Biscuit facts. IP address ranges are NOT allowed.+// Valid examples:+// - "group:backend-nodes"+// - "user:[email protected]"+// - "role:developer"+// - "node:12D3KooW..."+//+// AllowedServices defines the application-level services a peer can invoke.+// Services are prefixed by their protocol/type to permit fine-grained scoping.+// Wildcards are supported (e.g., "mcp:*").+// Valid examples:+// - "mcp:local-shell-tools"+// - "inference:openrouter"+// - "system:query_db"type RolePolicy struct {- Network NetworkPolicy `yaml:"network"`- MCP MCPPolicy `yaml:"mcp"`- CustomDatalog []string `yaml:"custom_datalog"`-}--type NetworkPolicy struct {- AllowedTargets []string `yaml:"allowed_targets"`-}--type MCPPolicy struct {- AllowedServers []string `yaml:"allowed_servers"`+ AllowedTargets []string `yaml:"allowed_targets,omitempty"`+ AllowedServices []string `yaml:"allowed_services,omitempty"`+ CustomDatalog []string `yaml:"custom_datalog,omitempty"`}type ServiceConfig struct {diff --git a/cmd/sam-hub/biscuit.go b/cmd/sam-hub/biscuit.goindex 9223f50a..6b613088 100644--- a/cmd/sam-hub/biscuit.go+++ b/cmd/sam-hub/biscuit.go@@ -41,11 +41,12 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remoteoidcRoles := toStringSlice(claims["roles"])oidcGroups := toStringSlice(claims["groups"])oidcSub, _ := claims["sub"].(string)+ oidcEmail, _ := claims["email"].(string)// Resolve roles based on configured bindings and explicit OIDC rolesresolvedRoles := make(map[string]bool)if h.Policy != nil {- // 1. Map OIDC groups and users to roles via configured bindings (RBAC mapping)+ // 1. Map OIDC groups, users, and emails to roles via configured bindings (RBAC mapping)for _, b := range h.Policy.Bindings {if b.Group != "" {for _, cg := range oidcGroups {@@ -59,6 +60,11 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remoteresolvedRoles[b.Role] = true}}+ if b.Email != "" && oidcEmail != "" {+ if b.Email == oidcEmail {+ resolvedRoles[b.Role] = true+ }+ }}// 2. Validate and accept pre-resolved OIDC roles directly if defined in policy (Zero-Trust check)@@ -116,15 +122,22 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remoteif h.Policy != nil {if rolePolicy, ok := h.Policy.Roles[role]; ok {- for _, tool := range rolePolicy.MCP.AllowedServers {+ for _, svc := range rolePolicy.AllowedServices {+ parts := strings.SplitN(svc, ":", 2)+ svcType := "system"+ svcName := svc+ if len(parts) == 2 {+ svcType = parts[0]+ svcName = parts[1]+ }if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactMCPServer,- IDs: []biscuit.Term{biscuit.String(tool)},+ Name: api.FactAllowService,+ IDs: []biscuit.Term{biscuit.String(svcType), biscuit.String(svcName)},}}); err != nil {- errs = append(errs, fmt.Errorf("failed to add MCP tool fact for %s: %w", tool, err))+ errs = append(errs, fmt.Errorf("failed to add allowed service fact for %s: %w", svc, err))}}- for _, target := range rolePolicy.Network.AllowedTargets {+ for _, target := range rolePolicy.AllowedTargets {if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactNetworkTarget,IDs: []biscuit.Term{biscuit.String(target)},diff --git a/cmd/sam-hub/biscuit_benchmark_test.go b/cmd/sam-hub/biscuit_benchmark_test.goindex 58f52508..1d9d56c7 100644--- a/cmd/sam-hub/biscuit_benchmark_test.go+++ b/cmd/sam-hub/biscuit_benchmark_test.go@@ -47,12 +47,8 @@ func BenchmarkMintBiscuitToken(b *testing.B) {},Roles: map[string]api.RolePolicy{"developer-role": {- MCP: api.MCPPolicy{- AllowedServers: []string{"git-helper", "mcp-server-2"},- },- Network: api.NetworkPolicy{- AllowedTargets: []string{"target-1", "target-2"},- },+ AllowedServices: []string{"git-helper", "mcp-server-2"},+ AllowedTargets: []string{"target-1", "target-2"},CustomDatalog: []string{"department(\"analytics\");",},diff --git a/cmd/sam-hub/biscuit_test.go b/cmd/sam-hub/biscuit_test.goindex e096ad8b..81597fdb 100644--- a/cmd/sam-hub/biscuit_test.go+++ b/cmd/sam-hub/biscuit_test.go@@ -55,17 +55,11 @@ func TestMintBiscuitToken(t *testing.T) {},Roles: map[string]api.RolePolicy{"admin": {- MCP: api.MCPPolicy{- AllowedServers: []string{"read", "write"},- },- Network: api.NetworkPolicy{- AllowedTargets: []string{"target1"},- },+ AllowedServices: []string{"read", "write"},+ AllowedTargets: []string{"target1"},},"canary-role": {- MCP: api.MCPPolicy{- AllowedServers: []string{"/sam/mcp/1.0.0"},- },+ AllowedServices: []string{"/sam/mcp/1.0.0"},},},},@@ -301,9 +295,7 @@ func TestMintBiscuitToken_ClaimsTranslation(t *testing.T) {},Roles: map[string]api.RolePolicy{"developer-role": {- MCP: api.MCPPolicy{- AllowedServers: []string{"git-helper"},- },+ AllowedServices: []string{"git-helper"},},},},diff --git a/cmd/sam-hub/config.go b/cmd/sam-hub/config.goindex a093a529..199854f4 100644--- a/cmd/sam-hub/config.go+++ b/cmd/sam-hub/config.go@@ -51,11 +51,22 @@ func LoadPolicyConfig(path string) (*api.PolicyConfig, error) {// ValidatePolicyConfig ensures that no wildcards are used in policies, and that all referenced roles in bindings exist.func ValidatePolicyConfig(config *api.PolicyConfig) error {for _, b := range config.Bindings {- if b.Group == "" && b.User == "" {- return fmt.Errorf("binding must specify either 'group' or 'user'")+ if b.Group == "" && b.User == "" && b.Email == "" {+ return fmt.Errorf("binding must specify either 'group', 'user', or 'email'")}- if b.Group != "" && b.User != "" {- return fmt.Errorf("binding cannot specify both 'group' and 'user' concurrently")+ // A binding should only specify one of them+ count := 0+ if b.Group != "" {+ count+++ }+ if b.User != "" {+ count+++ }+ if b.Email != "" {+ count+++ }+ if count > 1 {+ return fmt.Errorf("binding cannot specify multiple identities (group/user/email) concurrently")}if b.Role == "" {return fmt.Errorf("binding role cannot be empty")@@ -64,18 +75,5 @@ func ValidatePolicyConfig(config *api.PolicyConfig) error {return fmt.Errorf("binding role %q does not exist in defined roles", b.Role)}}-- for role, rolePolicy := range config.Roles {- for _, target := range rolePolicy.Network.AllowedTargets {- if target == "*" {- return fmt.Errorf("wildcard target '*' is not allowed in role %q", role)- }- }- for _, tool := range rolePolicy.MCP.AllowedServers {- if tool == "*" {- return fmt.Errorf("wildcard tool '*' is not allowed in role %q", role)- }- }- }return nil}diff --git a/cmd/sam-hub/config_test.go b/cmd/sam-hub/config_test.goindex 10345977..e5827816 100644--- a/cmd/sam-hub/config_test.go+++ b/cmd/sam-hub/config_test.go@@ -12,10 +12,8 @@ func TestLoadPolicyConfig(t *testing.T) {version: "v1alpha1"roles:data-scientist:- network:- allowed_targets: ["db-agent.data-mesh"]- mcp:- allowed_servers: ["query_database"]+ allowed_targets: ["db-agent.data-mesh"]+ allowed_services: ["query_database"]custom_datalog:- 'department("analytics");'`@@ -36,11 +34,11 @@ roles:if !ok {t.Fatal("expected role data-scientist to exist")}- 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.AllowedTargets) != 1 || role.AllowedTargets[0] != "db-agent.data-mesh" {+ t.Errorf("unexpected allowed targets: %v", role.AllowedTargets)}- if len(role.MCP.AllowedServers) != 1 || role.MCP.AllowedServers[0] != "query_database" {- t.Errorf("unexpected allowed tools: %v", role.MCP.AllowedServers)+ if len(role.AllowedServices) != 1 || role.AllowedServices[0] != "query_database" {+ t.Errorf("unexpected allowed tools: %v", role.AllowedServices)}if len(role.CustomDatalog) != 1 || role.CustomDatalog[0] != `department("analytics");` {t.Errorf("unexpected custom datalog: %v", role.CustomDatalog)@@ -51,8 +49,7 @@ roles:version: "v1alpha1"roles:data-scientist:- network:- allowed_targets: [missing closing bracket+ allowed_targets: [missing closing bracket`invalidFile := filepath.Join(dir, "invalid.yaml")if err := os.WriteFile(invalidFile, []byte(invalidYAML), 0644); err != nil {@@ -95,24 +92,6 @@ roles:t.Error("expected error for invalid custom datalog, got nil")}- // 5. Test wildcard rejection- wildcardYAML := `-version: "v1alpha1"-roles:- admin:- network:- allowed_targets: ["*"]-`- wildcardFile := filepath.Join(dir, "wildcard.yaml")- if err := os.WriteFile(wildcardFile, []byte(wildcardYAML), 0644); err != nil {- t.Fatal(err)- }-- _, err = LoadPolicyConfig(wildcardFile)- if err == nil {- t.Error("expected error for wildcard target, got nil")- }-// 6. Test valid bindingsbindingsYAML := `version: "v1alpha1"@@ -121,8 +100,7 @@ bindings:role: "mesh-member"roles:mesh-member:- mcp:- allowed_tools: ["/sam/mcp/1.0.0"]+ allowed_services: ["/sam/mcp/1.0.0"]`bindingsFile := filepath.Join(dir, "bindings.yaml")if err := os.WriteFile(bindingsFile, []byte(bindingsYAML), 0644); err != nil {@@ -148,8 +126,7 @@ bindings:role: "non-existent-role"roles:mesh-member:- mcp:- allowed_tools: ["/sam/mcp/1.0.0"]+ allowed_services: ["/sam/mcp/1.0.0"]`invalidBindingFile := filepath.Join(dir, "invalid_binding.yaml")if err := os.WriteFile(invalidBindingFile, []byte(invalidBindingYAML), 0644); err != nil {@@ -169,8 +146,7 @@ bindings:role: "mesh-member"roles:mesh-member:- mcp:- allowed_tools: ["/sam/mcp/1.0.0"]+ allowed_services: ["/sam/mcp/1.0.0"]`userBindingFile := filepath.Join(dir, "user_binding.yaml")if err := os.WriteFile(userBindingFile, []byte(userBindingYAML), 0644); err != nil {@@ -195,8 +171,7 @@ bindings:- role: "mesh-member"roles:mesh-member:- mcp:- allowed_tools: ["/sam/mcp/1.0.0"]+ allowed_services: ["/sam/mcp/1.0.0"]`missingBothFile := filepath.Join(dir, "missing_both.yaml")if err := os.WriteFile(missingBothFile, []byte(missingBothYAML), 0644); err != nil {@@ -217,8 +192,7 @@ bindings:role: "mesh-member"roles:mesh-member:- mcp:- allowed_tools: ["/sam/mcp/1.0.0"]+ allowed_services: ["/sam/mcp/1.0.0"]`bothPopulatedFile := filepath.Join(dir, "both_populated.yaml")if err := os.WriteFile(bothPopulatedFile, []byte(bothPopulatedYAML), 0644); err != nil {diff --git a/cmd/sam-node/mcp_handlers_test.go b/cmd/sam-node/mcp_handlers_test.goindex eaafc8c6..2f020bec 100644--- a/cmd/sam-node/mcp_handlers_test.go+++ b/cmd/sam-node/mcp_handlers_test.go@@ -38,8 +38,8 @@ func buildAndSaveBiscuit(node *SamNode, rootPriv ed25519.PrivateKey) error {return err}if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactMCPServer,- IDs: []biscuit.Term{biscuit.String("*")},+ Name: api.FactAllowService,+ IDs: []biscuit.Term{biscuit.String("*"), biscuit.String("*")},}}); err != nil {return err}@@ -395,9 +395,15 @@ func buildAndSaveCustomBiscuit(node *SamNode, rootPriv ed25519.PrivateKey, allowreturn err}for _, svc := range allowedServices {+ parts := strings.SplitN(svc, ":", 2)+ opType := parts[0]+ opName := "*"+ if len(parts) > 1 {+ opName = parts[1]+ }if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactMCPServer,- IDs: []biscuit.Term{biscuit.String(svc)},+ Name: api.FactAllowService,+ IDs: []biscuit.Term{biscuit.String(opType), biscuit.String(opName)},}}); err != nil {return err}diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.goindex 3d638d42..93818daa 100644--- a/cmd/sam-node/middleware.go+++ b/cmd/sam-node/middleware.go@@ -20,6 +20,8 @@ import ("encoding/hex""fmt"+ "strings"+"github.com/biscuit-auth/biscuit-go/v2""github.com/biscuit-auth/biscuit-go/v2/datalog""github.com/biscuit-auth/biscuit-go/v2/parser"@@ -39,19 +41,19 @@ var (func init() {var err error- rule1Str := fmt.Sprintf(`allow if operation($op), %s($op)`, api.FactMCPServer)+ rule1Str := fmt.Sprintf(`allow if service($type, $name), %s($type, $name)`, api.FactAllowService)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.FactMCPServer)+ rule2Str := fmt.Sprintf(`allow if service($type, $name), %s("*", "*")`, api.FactAllowService)baselineRule2, err = parser.FromStringPolicy(rule2Str)if err != nil {panic(fmt.Sprintf("failed to parse baseline rule 2: %v", err))}- rule3Str := fmt.Sprintf(`allow if operation("%s")`, api.CatalogTarget)+ rule3Str := fmt.Sprintf(`allow if service("system", "%s")`, api.CatalogTarget)baselineRule3, err = parser.FromStringPolicy(rule3Str)if err != nil {panic(fmt.Sprintf("failed to parse baseline rule 3: %v", err))@@ -231,14 +233,21 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.}// Inject the current action context (Standard Vocabulary)- op := req.Protocol+ opType := "system"+ opName := req.Protocolif req.Target != "" {- op = req.Target+ parts := strings.SplitN(req.Target, ":", 2)+ if len(parts) == 2 {+ opType = parts[0]+ opName = parts[1]+ } else {+ opName = req.Target+ }}authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: "operation",- IDs: []biscuit.Term{biscuit.String(op)},+ Name: "service",+ IDs: []biscuit.Term{biscuit.String(opType), biscuit.String(opName)},},})diff --git a/cmd/sam-node/middleware_test.go b/cmd/sam-node/middleware_test.goindex 050daf8f..b83c83b8 100644--- a/cmd/sam-node/middleware_test.go+++ b/cmd/sam-node/middleware_test.go@@ -128,8 +128,8 @@ func TestAuthorize(t *testing.T) {// Add fact to match baseline ruleerr = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactMCPServer,- IDs: []biscuit.Term{biscuit.String("/test/proto")},+ Name: api.FactAllowService,+ IDs: []biscuit.Term{biscuit.String("system"), biscuit.String("/test/proto")},}})if err != nil {t.Fatal(err)@@ -180,7 +180,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_server("query_db")`)+ fact, err := parser.FromStringFact(`allow_service("system", "query_db")`)if err != nil {t.Fatal(err)}@@ -194,7 +194,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_server("query_db")`)+ fact, err := parser.FromStringFact(`allow_service("system", "query_db")`)if err != nil {t.Fatal(err)}@@ -208,7 +208,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_server("*")`)+ fact, err := parser.FromStringFact(`allow_service("*", "*")`)if err != nil {t.Fatal(err)}@@ -222,7 +222,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_server("*")`)+ fact1, err := parser.FromStringFact(`allow_service("*", "*")`)if err != nil {t.Fatal(err)}@@ -532,8 +532,8 @@ func TestAuthorizationCacheBypass(t *testing.T) {IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},}})_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: "allow_mcp_server",- IDs: []biscuit.Term{biscuit.String("query_db")},+ Name: "allow_service",+ IDs: []biscuit.Term{biscuit.String("system"), biscuit.String("query_db")},}})b, _ := builder.Build()@@ -585,12 +585,12 @@ func TestAuthorizationCacheBypass(t *testing.T) {}// 1. Authorized target should succeed- if !doRequest("query_db") {+ if !doRequest("system:query_db") {t.Fatal("Expected authorized target to succeed")}// 2. Unauthorized target with the same token should FAIL- if doRequest("reboot_server") {+ if doRequest("system:reboot_server") {t.Fatal("SECURITY BUG: Unauthorized target succeeded due to cache bypass!")}}diff --git a/development/examples/calc-mcp/sam-node-config.yaml b/development/examples/calc-mcp/sam-node-config.yamlindex 12a306b3..c707b183 100644--- a/development/examples/calc-mcp/sam-node-config.yaml+++ b/development/examples/calc-mcp/sam-node-config.yaml@@ -3,7 +3,7 @@ attenuation:# Allow cross-node MCP only when the caller's biscuit carries a# node($peer) fact — i.e. it was issued by our hub upon enrollment.policies:- - 'allow if operation("calculator"), node($peer)'+ - 'allow if service("mcp", "calculator"), node($peer)'services:- type: "mcp"name: "calculator"diff --git a/development/examples/code-reviewer-mcp/sam-node-config.yaml b/development/examples/code-reviewer-mcp/sam-node-config.yamlindex c47198e8..79f043b6 100644--- a/development/examples/code-reviewer-mcp/sam-node-config.yaml+++ b/development/examples/code-reviewer-mcp/sam-node-config.yaml@@ -1,7 +1,7 @@version: "v1alpha1"attenuation:policies:- - 'allow if operation("/sam/mcp/1.0.0"), node($peer)'+ - 'allow if service("system", "/sam/mcp/1.0.0"), node($peer)'services:- type: "mcp"name: "code-reviewer"diff --git a/development/examples/everything-mcp/sam-node-config.yaml b/development/examples/everything-mcp/sam-node-config.yamlindex 9f83ae72..e48372f7 100644--- a/development/examples/everything-mcp/sam-node-config.yaml+++ b/development/examples/everything-mcp/sam-node-config.yaml@@ -1,8 +1,8 @@version: "v1alpha1"attenuation:policies:- - 'allow if operation("mcp:everything");'- - 'allow if operation("/sam/catalog");'+ - 'allow if service("mcp", "everything");'+ - 'allow if service("system", "/sam/catalog");'services:- type: "mcp"name: "everything"diff --git a/development/examples/greeter-mcp/sam-node-config.yaml b/development/examples/greeter-mcp/sam-node-config.yamlindex 8ccaa8e9..9b95e9b3 100644--- a/development/examples/greeter-mcp/sam-node-config.yaml+++ b/development/examples/greeter-mcp/sam-node-config.yaml@@ -1,7 +1,7 @@version: "v1alpha1"attenuation:policies:- - 'allow if operation("greeter"), node($peer)'+ - 'allow if service("mcp", "greeter"), node($peer)'services:- type: "mcp"name: "greeter"diff --git a/site/content/docs/development/policy.md b/site/content/docs/development/policy.mdindex 31e4952b..fcd65933 100644--- a/site/content/docs/development/policy.md+++ b/site/content/docs/development/policy.md@@ -65,19 +65,28 @@ allow if group("engineering");```## 2. Hub Policy Schema (`policies.yaml`)-Admins define central permissions by mapping OIDC roles to specific capabilities.+Admins define central permissions by mapping OIDC roles to specific capabilities.-> [!IMPORTANT]-> Wildcards (e.g. `*`) are explicitly disallowed in policy definitions. All allowed network targets and MCP servers must be explicitly listed.+* **`allowed_targets`**: Defines which logical groups or specific peers a user can route messages to, analogous to Active Directory security groups. Target definitions must be formatted as resolved facts (e.g., `group:<name>`, `user:<sub-id>`, `email:<email>`, `role:<role-name>`, or `node:<peer-id>`).+* **`allowed_services`**: Defines the application-level tools or endpoints a user can access, prefixed by their service type.++> [!NOTE]+> Because `allowed_services` translates to the two-argument Biscuit fact `service($type, $name)`, policies natively support Datalog wildcards (e.g. `allow if service("mcp", $any);`). You can configure wildcard permissions in your policy files, or explicit granular permissions like `mcp:db-agent` and `inference:openrouter`.```yamlversion: "v1alpha1"roles:data-scientist:- network:- allowed_targets: ["db-agent.data-mesh"] # Who they can connect to- mcp:- allowed_servers: ["db-agent"] # Allowed MCP server names+ allowed_targets:+ - "node:12D3KooW..." # Specific peer ID+ - "group:backend-nodes" # Logical group of peers+ - "role:admin" # Nodes possessing the admin role+ - "user:auth0|123456" # Node bound to a specific user sub+ - "email:[email protected]" # Node bound to a specific email+ allowed_services:+ - "mcp:db-agent" # Access to specific MCP server+ - "inference:openrouter" # Access to inference endpoints+ - "mcp:*" # Wildcard access to all MCP serverscustom_datalog:- 'department("analytics");' # Raw injected facts```@@ -109,7 +118,7 @@ To allow remote peers to discover tools and query connectivity, each node hostsTo ensure tool discovery works out-of-the-box, the node automatically injects a baseline rule allowing all verified peers to access it:```datalog-allow if operation("/sam/catalog");+allow if service("system", "/sam/catalog");```> [!IMPORTANT]> Without this baseline rule (or if a custom local attenuation policy explicitly blocks it), remote nodes will not be able to retrieve this node's tool catalog. As a result, agents across the mesh will fail to discover or call any of this node's tools.diff --git a/site/content/docs/integrations/openclaw.md b/site/content/docs/integrations/openclaw.mdindex e8603d04..a61a3b57 100644--- a/site/content/docs/integrations/openclaw.md+++ b/site/content/docs/integrations/openclaw.md@@ -6,7 +6,7 @@ You can seamlessly integrate your `sam-node` as a remote MCP server in [OpenClaw## Overview-By configuring your `sam-node` as an MCP server, you enable your OpenClaw agents to access the P2P mesh, discovering tools from remote nodes and executing operations as if they were local.+By configuring your `sam-node` as an MCP server, you enable your OpenClaw agents to access the P2P mesh, discovering tools from remote nodes and executing services as if they were local.## Configurationdiff --git a/site/content/docs/integrations/openrouter.md b/site/content/docs/integrations/openrouter.mdnew file mode 100644index 00000000..ea6b971b--- /dev/null+++ b/site/content/docs/integrations/openrouter.md@@ -0,0 +1,95 @@+---+title: "Exposing Inference Services: OpenRouter"+linkTitle: "OpenRouter Inference"+description: "How to deploy OpenRouter as a secure, mesh-native inference service in SAM"+weight: 40+---++# Exposing Inference Services: OpenRouter++In the Sovereign Agent Mesh (SAM), large language models (LLMs) and foundational model APIs are exposed across the mesh as **Inference Services**, not just standard Model Context Protocol (MCP) servers. This allows your deployed agents to dynamically discover, route, and consume inference capabilities directly through the P2P network, utilizing SAM's decentralized authorization (Biscuit) for access control.++This guide explains how to expose [OpenRouter](https://openrouter.ai/) as an inference service to the mesh, completely shielding your API keys from external peers.++## 1. The Proxy Architecture++SAM enforces a Zero Trust architecture. Rather than distributing your `OPENROUTER_API_KEY` to every agent in the network, you deploy a local proxy container alongside a dedicated `sam-node`.++The `sam-node` handles the P2P routing and mesh identity (validating incoming requests from other mesh agents). The proxy container (such as [`litellm`](https://litellm.ai/) or standard Nginx) holds the API key and securely forwards the requests upstream to `https://openrouter.ai/api/v1`.++```mermaid+sequenceDiagram+ participant Agent as Remote Agent+ participant Node as sam-node+ participant Proxy as litellm Proxy+ participant OpenRouter as OpenRouter API++ Agent->>Node: P2P Inference Request (Biscuit Auth)+ Note over Node: Validates Biscuit Policy+ Node->>Proxy: Forward Request (Localhost)+ Note over Proxy: Injects OPENROUTER_API_KEY+ Proxy->>OpenRouter: API Call+ OpenRouter-->>Proxy: Streaming Response+ Proxy-->>Node:+ Node-->>Agent: P2P Response+```++## 2. Configuring the Inference Service++To expose the proxy to the mesh, you must define it as an `inference` service in your node's configuration (`sam-node.yaml`), and set the `target_url` to the proxy's local endpoint.++```yaml+version: "v1alpha1"+services:+ - type: inference+ name: openrouter+ description: "OpenRouter Proxy Inference Service"+ target_url: "http://localhost:4000" # Local endpoint of the proxy+```++## 3. Decentralized Authorization++By default, services on your node are completely locked down. To allow agents in the mesh to utilize your OpenRouter inference service, you must explicitly allow the service via the node's local `attenuation` policies.++The service format for an inference service is always `inference:<service-name>`.++To allow **any** authenticated mesh agent to use the service:+```yaml+version: "v1alpha1"+attenuation:+ policies:+ - 'allow if service("inference", "openrouter");'+ - 'allow if service("system", "/sam/catalog");' # Required for discovery+ checks: []+```++If you only want to allow specific identities or groups (e.g., agents belonging to the "research" group), you can restrict the policy based on the cryptographic facts injected by the Hub:+```yaml+ - 'allow if service("inference", "openrouter"), group("research");'+```++## 4. Deploying the Node++When deploying (for instance, via Kubernetes), you deploy both containers in the same Pod so they can communicate over `localhost`. The `sam-node` container runs with the `--trust-hub-rbac` flag to trust the identity facts from the Hub.++```yaml+ containers:+ # 1. The litellm Proxy holding the secret key+ - name: openrouter-proxy+ image: ghcr.io/berriai/litellm:main-stable+ command: ["litellm", "--model", "openrouter/auto", "--port", "4000"]+ env:+ - name: OPENROUTER_API_KEY+ value: "sk-or-v1-..."++ # 2. The SAM node enforcing P2P authorization+ - name: sam-node+ image: ghcr.io/google/sam-node:latest+ args:+ - "run"+ - "--config=/etc/sam/sam-node.yaml"+ - "--trust-hub-rbac"+ # ... (other required arguments like --jwt-path)+```++Once running, any authorized agent in the Sovereign Agent Mesh can discover the `inference` service via the catalog and route inference requests securely through your node!diff --git a/site/content/docs/snippets/banana_bot_playground.py b/site/content/docs/snippets/banana_bot_playground.pyindex 039d5d76..b851251d 100644--- a/site/content/docs/snippets/banana_bot_playground.py+++ b/site/content/docs/snippets/banana_bot_playground.py@@ -54,7 +54,15 @@ class SamClient:return resp.model_dump() if hasattr(resp, "model_dump") else respasync def __aenter__(self):- await self.connect()+ for attempt in range(1, 13):+ try:+ await self.connect()+ return self+ except Exception as e:+ if attempt == 12:+ raise+ print(f"[-] Failed to connect to SAM node (attempt {attempt}/12): {e}. Retrying in 5 seconds...")+ await asyncio.sleep(5.0)return selfasync def __aexit__(self, exc_type, exc_val, exc_tb):diff --git a/site/content/docs/user/hub-configuration.md b/site/content/docs/user/hub-configuration.mdindex 6b272297..9dfa81e9 100644--- a/site/content/docs/user/hub-configuration.md+++ b/site/content/docs/user/hub-configuration.md@@ -39,10 +39,14 @@ The hub is highly configurable. Each setting can be passed as a command-line fla## 3. Configuring Role-Based Policies (`policies.yaml`)-The hub dynamically issues permissions inside the Biscuit token based on identity claims (users or groups) mapped to specific roles in the policy file.+The hub dynamically issues permissions inside the Biscuit token based on identity claims (users or groups) mapped to specific roles in the policy file.-> [!IMPORTANT]-> For security reasons, wildcards (e.g. `*`) are explicitly disallowed in policy definitions. All allowed network targets and MCP servers must be explicitly listed.+The policy defines what endpoints and services agents are permitted to use:+* **`allowed_targets`**: Acts similar to Active Directory network groups. This restricts which logical endpoints the agent can route connections to. **Note: IP address ranges are not allowed.** Instead, use the format of the resolved Biscuit facts: `group:<name>`, `user:<sub-id>`, `email:<email>`, `role:<role-name>`, or `node:<peer-id>`.+* **`allowed_services`**: Restricts the application-level services the agent can invoke. Services are prefixed by their protocol type (e.g., `mcp:local-shell-tools` or `inference:openrouter`).++> [!NOTE]+> You can use wildcards (e.g. `mcp:*`) in `allowed_services` to grant broad access, or specify explicit service names for granular control.### Example Policy MappingCreate a `policies.yaml` file in the directory where you run `sam-hub`:@@ -53,30 +57,30 @@ version: v1alpha1# Define authorization roles and their specific network/tool permissionsroles:developer-role:- network:- allowed_targets:- - "10.0.0.0/8"- - "192.168.1.0/24"- mcp:- allowed_servers:- - "local-shell-tools"- - "git-helper"+ allowed_targets:+ - "group:dev-nodes"+ - "email:[email protected]"+ - "user:auth0|123456"+ - "node:12D3KooWSpecificDevNodeId"+ allowed_services:+ - "mcp:local-shell-tools"+ - "mcp:git-helper"+ - "inference:openrouter"admin-role:- network:- allowed_targets:- - "10.0.0.0/8"- - "172.16.0.0/12"- - "192.168.1.0/24"- mcp:- allowed_servers:- - "local-shell-tools"- - "git-helper"- - "db-agent"--# Bind OIDC user emails or group claims to roles+ allowed_targets:+ - "group:all-nodes"+ - "role:admin"+ allowed_services:+ - "mcp:*"+ - "inference:*"+ - "system:*"++# Bind OIDC user subs, emails, or group claims to rolesbindings:- - user: "[email protected]"+ - email: "[email protected]"+ role: "admin-role"+ - user: "auth0|123456"role: "admin-role"- group: "eng-team"role: "developer-role"diff --git a/tests/e2e/docker/calc-mcp/sam-node-config.yaml b/tests/e2e/docker/calc-mcp/sam-node-config.yamlindex fdc5562d..b01a5ac4 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($op), node($peer)'+ - 'allow if service($type, $name), node($peer)'services:- type: "mcp"name: "calculator"diff --git a/tests/e2e/policy.bats b/tests/e2e/policy.batsindex 7e0c0d15..8af5f0c1 100644--- a/tests/e2e/policy.bats+++ b/tests/e2e/policy.bats@@ -157,7 +157,7 @@ roles:local node_policy="version: \"v1alpha1\"attenuation:policies:- - 'deny if operation(\"delete_tables\");'"+ - 'deny if service("system", \"delete_tables\");'"docker run --rm -v "${POLICY_VOL}:/policies" busybox sh -c "cat <<'EOF' > /policies/policies.yaml${hub_policy}diff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.goindex 72760aa3..8b36f0ff 100644--- a/tests/integration/fallback_test.go+++ b/tests/integration/fallback_test.go@@ -164,6 +164,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {env := append(os.Environ(),"HOME="+tmpHome,"XDG_CONFIG_HOME="+filepath.Join(tmpHome, ".config"),+ "BROWSER=echo",)// Step 1: Enroll via Join (using mock OIDC)@@ -205,7 +206,10 @@ func TestSelfHealingHTTPFallback(t *testing.T) {if err := runCmd.Start(); err != nil {t.Fatal(err)}- defer func() { _ = runCmd.Process.Kill() }()+ defer func() {+ _ = runCmd.Process.Kill()+ _ = runCmd.Wait()+ }()// Wait for successful fallbacksuccess := falsediff --git a/tests/integration/login_test.go b/tests/integration/login_test.goindex b586161e..f9cad953 100644--- a/tests/integration/login_test.go+++ b/tests/integration/login_test.go@@ -32,6 +32,7 @@ func TestSamNodeJoin(t *testing.T) {env := append(os.Environ(),"HOME="+tmpHome,"XDG_CONFIG_HOME="+filepath.Join(tmpHome, ".config"),+ "BROWSER=echo",)// Mock OIDC server for device flowdiff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex 08280c0d..1c1d77c7 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -77,12 +77,23 @@ func runCommand(cmd := exec.CommandContext(ctx, name, args...)cmd.Dir = cwd+ tmpBin := filepath.Join(t.TempDir(), "bin")+ _ = os.MkdirAll(tmpBin, 0755)+ _ = os.WriteFile(filepath.Join(tmpBin, "xdg-open"), []byte("#!/bin/sh\nexit 0\n"), 0755)+ _ = os.WriteFile(filepath.Join(tmpBin, "open"), []byte("#!/bin/sh\nexit 0\n"), 0755)+var finalEnv []string+ finalEnv = append(finalEnv, "BROWSER=echo")for _, e := range append(os.Environ(), env...) {if !strings.HasPrefix(e, "SSH_CLIENT=") && !strings.HasPrefix(e, "SSH_TTY=") {finalEnv = append(finalEnv, e)}}+ for i, e := range finalEnv {+ if strings.HasPrefix(e, "PATH=") {+ finalEnv[i] = "PATH=" + tmpBin + string(os.PathListSeparator) + e[5:]+ }+ }cmd.Env = finalEnvif stdin != "" {cmd.Stdin = bytes.NewBufferString(stdin)@@ -157,12 +168,23 @@ func runCommandWithCallback(cmd := exec.CommandContext(ctx, name, args...)cmd.Dir = cwd+ tmpBin := filepath.Join(t.TempDir(), "bin")+ _ = os.MkdirAll(tmpBin, 0755)+ _ = os.WriteFile(filepath.Join(tmpBin, "xdg-open"), []byte("#!/bin/sh\nexit 0\n"), 0755)+ _ = os.WriteFile(filepath.Join(tmpBin, "open"), []byte("#!/bin/sh\nexit 0\n"), 0755)+var finalEnv []string+ finalEnv = append(finalEnv, "BROWSER=echo")for _, e := range append(os.Environ(), env...) {if !strings.HasPrefix(e, "SSH_CLIENT=") && !strings.HasPrefix(e, "SSH_TTY=") {finalEnv = append(finalEnv, e)}}+ for i, e := range finalEnv {+ if strings.HasPrefix(e, "PATH=") {+ finalEnv[i] = "PATH=" + tmpBin + string(os.PathListSeparator) + e[5:]+ }+ }cmd.Env = finalEnvif stdin != "" {cmd.Stdin = bytes.NewBufferString(stdin)diff --git a/tests/integration/mock_oidc_test.go b/tests/integration/mock_oidc_test.goindex 7d25c6ee..764aa0d5 100644--- a/tests/integration/mock_oidc_test.go+++ b/tests/integration/mock_oidc_test.go@@ -62,3 +62,58 @@ func startMockOIDC(t *testing.T) (string, string) {return issuer, jwtStr}++func startCustomMockOIDC(t *testing.T) (string, func(claims map[string]interface{}) string) {+ privKey, err := rsa.GenerateKey(rand.Reader, 2048)+ if err != nil {+ t.Fatalf("failed to generate rsa key: %v", err)+ }++ mux := http.NewServeMux()+ srv := httptest.NewServer(mux)+ issuer := srv.URL++ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]interface{}{+ "issuer": issuer,+ "jwks_uri": issuer + "/keys",+ })+ })++ mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]interface{}{+ "keys": []map[string]interface{}{+ {+ "kty": "RSA",+ "alg": "RS256",+ "use": "sig",+ "kid": "mock-key",+ "n": base64.RawURLEncoding.EncodeToString(privKey.N.Bytes()),+ "e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(privKey.E)).Bytes()),+ },+ },+ })+ })++ mintToken := func(customClaims map[string]interface{}) string {+ claims := jwt.MapClaims{+ "iss": issuer,+ "aud": "sam-mesh-audience",+ "exp": time.Now().Add(time.Hour).Unix(),+ }+ for k, v := range customClaims {+ claims[k] = v+ }+ token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)+ token.Header["kid"] = "mock-key"+ jwtStr, err := token.SignedString(privKey)+ if err != nil {+ t.Fatalf("failed to sign jwt: %v", err)+ }+ return jwtStr+ }++ return issuer, mintToken+}diff --git a/tests/integration/policy_permutations_test.go b/tests/integration/policy_permutations_test.gonew file mode 100644index 00000000..95bcf5b0--- /dev/null+++ b/tests/integration/policy_permutations_test.go@@ -0,0 +1,321 @@+package integration_test++import (+ "context"+ "fmt"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "github.com/modelcontextprotocol/go-sdk/mcp"+)++func callMCPAllowError(t *testing.T, mcpAddr string, apiToken string, toolName string, params map[string]any) (string, error) {+ t.Helper()+ ctx := context.Background()++ client := mcp.NewClient(&mcp.Implementation{+ Name: "test-client",+ Version: "0.1.0",+ }, nil)++ transport := http.DefaultTransport+ clientTransport := &mcp.StreamableClientTransport{+ Endpoint: "http://" + mcpAddr + "/mcp",+ HTTPClient: &http.Client{+ Transport: &authRoundTripper{+ token: apiToken,+ rt: transport,+ },+ },+ }++ session, err := client.Connect(ctx, clientTransport, nil)+ if err != nil {+ return "", fmt.Errorf("failed to connect: %v", err)+ }+ defer func() {+ _ = session.Close()+ }()++ res, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: toolName,+ Arguments: params,+ })+ if err != nil {+ return "", err+ }++ if res.IsError {+ var errText []string+ for _, c := range res.Content {+ if tc, ok := c.(*mcp.TextContent); ok {+ errText = append(errText, tc.Text)+ }+ }+ return "", fmt.Errorf("MCP error: %s", strings.Join(errText, " "))+ }++ if len(res.Content) > 0 {+ if textContent, ok := res.Content[0].(*mcp.TextContent); ok {+ return textContent.Text, nil+ }+ }+ return "", nil+}++func TestPolicyPermutations(t *testing.T) {+ hubBin := buildBinary(t, "./cmd/sam-hub")+ nodeBin := buildBinary(t, "./cmd/sam-node")++ tmpDir := t.TempDir()++ oidcURL, mintToken := startCustomMockOIDC(t)++ // 1. Hub Policies+ hubPolicyFile := filepath.Join(tmpDir, "policies.yaml")+ hubPolicyYAML := `version: "v1alpha1"+roles:+ role-user:+ allowed_services: ["mcp:test-user"]+ allowed_targets: ["user:bob-subject"]+ role-email:+ allowed_services: ["mcp:test-email"]+ allowed_targets: ["node:nodeB"]+ role-group:+ allowed_services: ["mcp:test-group"]+ allowed_targets: ["group:compute"]+ role-node:+ allowed_services: ["mcp:test-node"]+ allowed_targets: ["group:backend"]+ role-direct:+ allowed_services: ["mcp:test-role"]+ allowed_targets: ["node:nodeB"]+ admin:+ allowed_services: ["*"]+ allowed_targets: ["*"]++bindings:+ - role: role-user+ user: "bob-subject"+ - role: role-email+ email: "[email protected]"+ - role: role-group+ group: "eng-team"+ - role: role-node+ user: "node-user"+ - role: admin+ user: "admin-user"+ - role: admin+ user: "nodeB"+`+ if err := os.WriteFile(hubPolicyFile, []byte(hubPolicyYAML), 0644); err != nil {+ t.Fatal(err)+ }++ httpPortHub := getFreePort(t)+ p2pPortHub := getFreePort(t)++ cmdHub := exec.Command(hubBin,+ "--bind-address", fmt.Sprintf("127.0.0.1:%d", httpPortHub),+ "--listen", fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", p2pPortHub),+ "--policy-file", hubPolicyFile,+ "--keys-db", filepath.Join(tmpDir, "keys.db"),+ "--allow-loopback",+ "--issuer", oidcURL,+ "--insecure-skip-tls-verify",+ )+ cmdHub.Stdout = os.Stdout+ cmdHub.Stderr = os.Stderr+ if err := cmdHub.Start(); err != nil {+ t.Fatalf("Failed to start Hub: %v", err)+ }+ defer func() { _ = cmdHub.Process.Kill() }()+ fetchPeerID(t, httpPortHub)++ // 2. Node B (Target) Config+ nodeBPolicyFile := filepath.Join(tmpDir, "nodeB_config.yaml")+ nodeBPolicyYAML := `version: "v1alpha1"+attenuation:+ rules:+ - 'target("user:bob-subject") <- true'+ - 'target("node:nodeB") <- true'+ - 'target("group:compute") <- true'+ - 'target("group:backend") <- true'++services:+ - type: "mcp"+ name: "mcp:test-user"+ command: ["echo", "test-user"]+ - type: "mcp"+ name: "mcp:test-email"+ command: ["echo", "test-email"]+ - type: "mcp"+ name: "mcp:test-group"+ command: ["echo", "test-group"]+ - type: "mcp"+ name: "mcp:test-role"+ command: ["echo", "test-role"]+ - type: "mcp"+ name: "mcp:test-node"+ command: ["echo", "test-node"]+`+ if err := os.WriteFile(nodeBPolicyFile, []byte(nodeBPolicyYAML), 0644); err != nil {+ t.Fatal(err)+ }++ homeB := filepath.Join(tmpDir, "nodeB")+ apiTokenB := "tokenB"+ apiPortB := getFreePort(t)++ cmdB := exec.Command(nodeBin, "run",+ "--hub", fmt.Sprintf("http://127.0.0.1:%d", httpPortHub),+ "--data-dir", homeB,+ "--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),+ "--api-token", apiTokenB,+ "--jwt", mintToken(map[string]interface{}{"sub": "nodeB"}),+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--trust-hub-rbac",+ "--allow-loopback",+ "--config", nodeBPolicyFile,+ )+ os.MkdirAll(homeB, 0755)+ logFileB, err := os.Create(filepath.Join(homeB, "node.log"))+ if err != nil {+ t.Fatal(err)+ }+ defer logFileB.Close()+ cmdB.Stdout = logFileB+ cmdB.Stderr = logFileB+ if err := cmdB.Start(); err != nil {+ t.Fatalf("Failed to start Node B: %v", err)+ }+ defer func() { _ = cmdB.Process.Kill() }()++ actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))+ waitForAPI(t, actualApiAddrB)+ addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))++ // 3. Test Permutations+ tests := []struct {+ name string+ jwtClaims map[string]interface{}+ targetSvc string+ expectAllow bool+ expectHubErr bool+ }{+ {+ name: "Fact sub: user(bob-subject)",+ jwtClaims: map[string]interface{}{"sub": "bob-subject"},+ targetSvc: "mcp:test-user",+ expectAllow: true,+ },+ {+ name: "Fact email: email([email protected])",+ jwtClaims: map[string]interface{}{"sub": "some-id", "email": "[email protected]"},+ targetSvc: "mcp:test-email",+ expectAllow: true,+ },+ {+ name: "Fact groups: group(eng-team)",+ jwtClaims: map[string]interface{}{"sub": "some-id", "groups": []string{"eng-team"}},+ targetSvc: "mcp:test-group",+ expectAllow: true,+ },+ {+ name: "Fact roles: role(role-direct)",+ jwtClaims: map[string]interface{}{"sub": "some-id", "roles": []string{"role-direct"}},+ targetSvc: "mcp:test-role",+ expectAllow: true,+ },+ {+ name: "Fact node: node(peerID)",+ jwtClaims: map[string]interface{}{"sub": "node-user"},+ targetSvc: "mcp:test-node",+ expectAllow: true,+ },+ {+ name: "Unknown User / No Roles -> Hub Error",+ jwtClaims: map[string]interface{}{"sub": "unknown"},+ targetSvc: "mcp:test-user",+ expectAllow: false,+ },+ }++ for i, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ homeA := filepath.Join(tmpDir, fmt.Sprintf("nodeA_%d", i))+ apiTokenA := "tokenA"+ apiPortA := getFreePort(t)++ jwtA := mintToken(tt.jwtClaims)++ cmdA := exec.Command(nodeBin, "run",+ "--hub", fmt.Sprintf("http://127.0.0.1:%d", httpPortHub),+ "--data-dir", homeA,+ "--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),+ "--api-token", apiTokenA,+ "--jwt", jwtA,+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--trust-hub-rbac",+ "--allow-loopback",+ )+ os.MkdirAll(homeA, 0755)+ logFileA, err := os.Create(filepath.Join(homeA, "node.log"))+ if err != nil {+ t.Fatal(err)+ }+ defer logFileA.Close()+ cmdA.Stdout = logFileA+ cmdA.Stderr = logFileA+ if err := cmdA.Start(); err != nil {+ t.Fatalf("Failed to start Node A: %v", err)+ }+ defer func() { _ = cmdA.Process.Kill() }()++ actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))+ waitForAPI(t, actualApiAddrA)++ parts := strings.Split(addrB, "/p2p/")+ if len(parts) != 2 {+ t.Fatalf("unexpected addrB format: %s", addrB)+ }+ peerIDB := parts[1]++ // Use the local callMCPAllowError targeting Node A to hit Node B+ resp, callErr := callMCPAllowError(t, actualApiAddrA, apiTokenA, "call_remote_tool", map[string]any{+ "peer_id": peerIDB,+ "tool_name": tt.targetSvc + ".test_tool",+ "arguments": map[string]any{},+ })++ // call_remote_tool might return a JSON error inside resp, or callErr might be non-nil.+ failed := false+ if callErr != nil {+ if strings.Contains(callErr.Error(), "EOF") {+ // EOF means the 'echo' backend started and exited, which means AuthZ succeeded!+ failed = false+ } else {+ failed = true+ }+ } else if strings.Contains(resp, "Authorization failed") || strings.Contains(resp, "failed to connect") || strings.Contains(resp, "token lacks") || strings.Contains(resp, "denied") {+ failed = true+ }++ if tt.expectAllow {+ if failed {+ t.Errorf("expected success, got error: %v / %s", callErr, resp)+ }+ } else {+ if !failed {+ t.Errorf("expected failure, got success: %s", resp)+ }+ }+ })+ }+}