Skip to content

Agent Mesh

Fix security gap in HTTP Datapath ingress and proxy token leak

Antonio Ojea433bc99d2a2c
diff --git a/.github/k8s/sam-hub-template.yaml b/.github/k8s/sam-hub-template.yaml
index e83c7083..6d029684 100644
--- a/.github/k8s/sam-hub-template.yaml
+++ b/.github/k8s/sam-hub-template.yaml
@@ -116,10 +116,9 @@ data:
roles:
sam-canary:
allowed_services:
- - "/sam/mcp/1.0.0"
- - "/sam/catalog"
- - "inference:openrouter"
- - "*"
+ - "*:*"
+ allowed_targets:
+ - "*:*"
---
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
diff --git a/.github/k8s/sam-node-everything-template.yaml b/.github/k8s/sam-node-everything-template.yaml
index 1a31dab4..2054d206 100644
--- a/.github/k8s/sam-node-everything-template.yaml
+++ b/.github/k8s/sam-node-everything-template.yaml
@@ -7,9 +7,7 @@ data:
sam-node.yaml: |
version: "v1alpha1"
attenuation:
- policies:
- - 'allow if service("mcp", "everything");'
- - 'allow if service("system", "/sam/catalog");'
+ policies: []
checks: []
rules: []
services:
diff --git a/.github/k8s/sam-node-openrouter-template.yaml b/.github/k8s/sam-node-openrouter-template.yaml
index f2d284c6..1dfb2f74 100644
--- a/.github/k8s/sam-node-openrouter-template.yaml
+++ b/.github/k8s/sam-node-openrouter-template.yaml
@@ -61,7 +61,6 @@ spec:
- "--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:
diff --git a/.github/k8s/sam-node-template.yaml b/.github/k8s/sam-node-template.yaml
index 1c33cbf1..40ad62ed 100644
--- a/.github/k8s/sam-node-template.yaml
+++ b/.github/k8s/sam-node-template.yaml
@@ -44,7 +44,6 @@ 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/api/types.go b/api/types.go
index dd4b7780..e4cf5111 100644
--- a/api/types.go
+++ b/api/types.go
@@ -29,7 +29,7 @@ const GossipHubSync = "/sam/hub/sync/v1"
const AuthProtocolID protocol.ID = "/sam/auth/1.0.0"
// CatalogTarget is the special target service name used to retrieve tool catalogs from remote nodes.
-const CatalogTarget = "/sam/catalog"
+const CatalogTarget = "sam.catalog"
// DefaultServiceType is the default type for services without a namespace.
const DefaultServiceType = "system"
@@ -44,15 +44,25 @@ const MCPServicePrefix = "mcp:"
// Biscuit fact names
const (
- FactExpiration = "expiration"
- FactNode = "node"
- FactClientPeerID = "client_peer_id"
- FactGroup = "group"
- FactRole = "role"
- FactUser = "user"
- FactEmail = "email"
- FactAllowService = "allow_service"
- FactNetworkTarget = "allow_network_target"
+ FactExpiration = "expiration"
+ FactNode = "node"
+ FactClientPeerID = "client_peer_id"
+ FactGroup = "group"
+ FactRole = "role"
+ FactUser = "user"
+ FactEmail = "email"
+ FactGrantedServiceAllTypes = "granted_service_all_types"
+ FactGrantedServiceAll = "granted_service_all"
+ FactGrantedServiceSuffix = "granted_service_suffix"
+ FactGrantedServicePrefix = "granted_service_prefix"
+ FactGrantedServiceExact = "granted_service_exact"
+
+ FactGrantedTargetAllTypes = "granted_target_all_types"
+ FactGrantedTargetAll = "granted_target_all"
+ FactGrantedTargetSuffix = "granted_target_suffix"
+ FactGrantedTargetPrefix = "granted_target_prefix"
+ FactGrantedTargetExact = "granted_target_exact"
+ FactGrantedTargetAllFacts = "granted_target_all_facts"
)
// oidcClaimToFact maps standard OIDC claims to their corresponding Biscuit facts.
diff --git a/api/validation.go b/api/validation.go
new file mode 100644
index 00000000..a04768bf
--- /dev/null
+++ b/api/validation.go
@@ -0,0 +1,45 @@
+package api
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+)
+
+// The value can be a domain label, allowing prefix/suffix wildcards (e.g. *.foo.bar or foo.*)
+var domainLabelRegex = regexp.MustCompile(`^(?:\*\.)?(?:[a-zA-Z0-9-]+\.)*(?:[a-zA-Z0-9-]+)(?:\.\*)?$|^\*$`)
+
+// ValidateServiceFormat ensures the service string follows the explicit type:value format.
+func ValidateServiceFormat(svc string) error {
+ parts := strings.SplitN(svc, ":", 2)
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid service format %q: must be type:value (e.g., mcp:foo)", svc)
+ }
+ typ, val := parts[0], parts[1]
+ if typ == "" {
+ return fmt.Errorf("invalid service format %q: type cannot be empty", svc)
+ }
+ if val == "" {
+ return fmt.Errorf("invalid service format %q: value cannot be empty", svc)
+ }
+ if !domainLabelRegex.MatchString(val) {
+ return fmt.Errorf("invalid service format %q: value must be a valid domain label with optional prefix/suffix wildcard", svc)
+ }
+ return nil
+}
+
+// ValidateTargetFormat ensures the target string follows the explicit fact:value format.
+func ValidateTargetFormat(target string) error {
+ parts := strings.SplitN(target, ":", 2)
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid target format %q: must be fact:value (e.g., group:backend)", target)
+ }
+ fact, val := parts[0], parts[1]
+ if fact == "" {
+ return fmt.Errorf("invalid target format %q: fact cannot be empty", target)
+ }
+ if val == "" {
+ return fmt.Errorf("invalid target format %q: value cannot be empty", target)
+ }
+ return nil
+}
diff --git a/api/validation_test.go b/api/validation_test.go
new file mode 100644
index 00000000..d8d57c62
--- /dev/null
+++ b/api/validation_test.go
@@ -0,0 +1,57 @@
+package api
+
+import (
+ "testing"
+)
+
+func TestValidateServiceFormat(t *testing.T) {
+ tests := []struct {
+ name string
+ svc string
+ wantErr bool
+ }{
+ {"valid exact", "mcp:my-service.local", false},
+ {"valid prefix wildcard", "mcp:*.service.local", false},
+ {"valid suffix wildcard", "mcp:service.*", false},
+ {"valid just wildcard", "mcp:*", false},
+ {"valid subdomains", "mcp:a.b.c.d", false},
+ {"invalid no type", ":my-service", true},
+ {"invalid no colon", "mcp-service", true},
+ {"invalid consecutive dots", "mcp:my..service", true},
+ {"invalid wildcard middle", "mcp:my.*.service", true},
+ {"invalid invalid chars", "mcp:service_name", true},
+ {"invalid exact with path", "mcp:my-service/local", true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateServiceFormat(tt.svc)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("ValidateServiceFormat() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestValidateTargetFormat(t *testing.T) {
+ tests := []struct {
+ name string
+ target string
+ wantErr bool
+ }{
+ {"valid target", "group:backend", false},
+ {"valid email", "email:[email protected]", false},
+ {"invalid no colon", "group-backend", true},
+ {"invalid empty fact", ":backend", true},
+ {"invalid empty value", "group:", true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateTargetFormat(tt.target)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("ValidateTargetFormat() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
diff --git a/cmd/sam-hub/biscuit.go b/cmd/sam-hub/biscuit.go
index b7baa81a..b9b33bd4 100644
--- a/cmd/sam-hub/biscuit.go
+++ b/cmd/sam-hub/biscuit.go
@@ -124,19 +124,86 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remote
if rolePolicy, ok := h.Policy.Roles[role]; ok {
for _, svc := range rolePolicy.AllowedServices {
svcType, svcName := api.ParseServiceTarget(svc)
- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactAllowService,
- IDs: []biscuit.Term{biscuit.String(svcType), biscuit.String(svcName)},
- }}); err != nil {
- errs = append(errs, fmt.Errorf("failed to add allowed service fact for %s: %w", svc, err))
+
+ if svcType == "*" && svcName == "*" {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedServiceAllTypes,
+ IDs: []biscuit.Term{},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_service_all_types fact: %w", err))
+ }
+ } else if svcName == "*" {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedServiceAll,
+ IDs: []biscuit.Term{biscuit.String(svcType)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_service_all fact: %w", err))
+ }
+ } else if strings.HasPrefix(svcName, "*.") {
+ suffix := svcName[1:]
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedServiceSuffix,
+ IDs: []biscuit.Term{biscuit.String(svcType), biscuit.String(suffix)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_service_suffix fact: %w", err))
+ }
+ } else if strings.HasSuffix(svcName, ".*") {
+ prefix := svcName[:len(svcName)-1]
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedServicePrefix,
+ IDs: []biscuit.Term{biscuit.String(svcType), biscuit.String(prefix)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_service_prefix fact: %w", err))
+ }
+ } else {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedServiceExact,
+ IDs: []biscuit.Term{biscuit.String(svcType), biscuit.String(svcName)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_service_exact fact: %w", err))
+ }
}
}
for _, target := range rolePolicy.AllowedTargets {
- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactNetworkTarget,
- IDs: []biscuit.Term{biscuit.String(target)},
- }}); err != nil {
- errs = append(errs, fmt.Errorf("failed to add network target fact for %s: %w", target, err))
+ targetFact, targetVal := api.ParseServiceTarget(target)
+
+ if targetFact == "*" && targetVal == "*" {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedTargetAllFacts,
+ IDs: []biscuit.Term{},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_target_all_facts fact: %w", err))
+ }
+ } else if targetVal == "*" {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedTargetAll,
+ IDs: []biscuit.Term{biscuit.String(targetFact)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_target_all fact: %w", err))
+ }
+ } else if strings.HasPrefix(targetVal, "*.") {
+ suffix := targetVal[1:]
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedTargetSuffix,
+ IDs: []biscuit.Term{biscuit.String(targetFact), biscuit.String(suffix)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_target_suffix fact: %w", err))
+ }
+ } else if strings.HasSuffix(targetVal, ".*") {
+ prefix := targetVal[:len(targetVal)-1]
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedTargetPrefix,
+ IDs: []biscuit.Term{biscuit.String(targetFact), biscuit.String(prefix)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_target_prefix fact: %w", err))
+ }
+ } else {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactGrantedTargetExact,
+ IDs: []biscuit.Term{biscuit.String(targetFact), biscuit.String(targetVal)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add granted_target_exact fact: %w", err))
+ }
}
}
for _, customFact := range rolePolicy.CustomDatalog {
@@ -168,6 +235,27 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remote
}
}
+ hasTargets := false
+ for _, role := range roles {
+ if h.Policy != nil {
+ if rolePolicy, ok := h.Policy.Roles[role]; ok {
+ if len(rolePolicy.AllowedTargets) > 0 {
+ hasTargets = true
+ break
+ }
+ }
+ }
+ }
+ if hasTargets {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_restricted"}}); err != nil {
+ errs = append(errs, err)
+ }
+ } else {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}}); err != nil {
+ errs = append(errs, err)
+ }
+ }
+
if len(errs) > 0 {
return nil, fmt.Errorf("biscuit policy validation failed: %w", errors.Join(errs...))
}
diff --git a/cmd/sam-hub/biscuit_benchmark_test.go b/cmd/sam-hub/biscuit_benchmark_test.go
index 1d9d56c7..a582b2f9 100644
--- a/cmd/sam-hub/biscuit_benchmark_test.go
+++ b/cmd/sam-hub/biscuit_benchmark_test.go
@@ -47,7 +47,7 @@ func BenchmarkMintBiscuitToken(b *testing.B) {
},
Roles: map[string]api.RolePolicy{
"developer-role": {
- AllowedServices: []string{"git-helper", "mcp-server-2"},
+ AllowedServices: []string{"mcp:git-helper", "mcp: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.go
index 81597fdb..61dc473b 100644
--- a/cmd/sam-hub/biscuit_test.go
+++ b/cmd/sam-hub/biscuit_test.go
@@ -55,11 +55,11 @@ func TestMintBiscuitToken(t *testing.T) {
},
Roles: map[string]api.RolePolicy{
"admin": {
- AllowedServices: []string{"read", "write"},
- AllowedTargets: []string{"target1"},
+ AllowedServices: []string{"mcp:read", "mcp:write"},
+ AllowedTargets: []string{"mcp:target1"},
},
"canary-role": {
- AllowedServices: []string{"/sam/mcp/1.0.0"},
+ AllowedServices: []string{"mcp:1.0.0"},
},
},
},
@@ -108,6 +108,10 @@ func TestMintBiscuitToken(t *testing.T) {
},
}, Kind: biscuit.PolicyKindAllow}
authorizer1.AddPolicy(rule1)
+ authorizer1.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "allow_network_target",
+ IDs: []biscuit.Term{biscuit.String("mcp"), biscuit.String("target1")},
+ }})
if err := authorizer1.Authorize(); err != nil {
t.Errorf("Expected direct role 'admin' to be authorized: %v", err)
}
@@ -295,7 +299,7 @@ func TestMintBiscuitToken_ClaimsTranslation(t *testing.T) {
},
Roles: map[string]api.RolePolicy{
"developer-role": {
- AllowedServices: []string{"git-helper"},
+ AllowedServices: []string{"mcp:git-helper"},
},
},
},
diff --git a/cmd/sam-hub/config.go b/cmd/sam-hub/config.go
index 199854f4..1885a0ad 100644
--- a/cmd/sam-hub/config.go
+++ b/cmd/sam-hub/config.go
@@ -75,5 +75,18 @@ 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 _, svc := range rolePolicy.AllowedServices {
+ if err := api.ValidateServiceFormat(svc); err != nil {
+ return fmt.Errorf("invalid allowed service in role %q: %w", role, err)
+ }
+ }
+ for _, target := range rolePolicy.AllowedTargets {
+ if err := api.ValidateTargetFormat(target); err != nil {
+ return fmt.Errorf("invalid allowed target in role %q: %w", role, err)
+ }
+ }
+ }
return nil
}
diff --git a/cmd/sam-hub/config_test.go b/cmd/sam-hub/config_test.go
index e5827816..9bd56270 100644
--- a/cmd/sam-hub/config_test.go
+++ b/cmd/sam-hub/config_test.go
@@ -12,8 +12,8 @@ func TestLoadPolicyConfig(t *testing.T) {
version: "v1alpha1"
roles:
data-scientist:
- allowed_targets: ["db-agent.data-mesh"]
- allowed_services: ["query_database"]
+ allowed_targets: ["node:db-agent.data-mesh"]
+ allowed_services: ["system:query-database"]
custom_datalog:
- 'department("analytics");'
`
@@ -34,10 +34,10 @@ roles:
if !ok {
t.Fatal("expected role data-scientist to exist")
}
- if len(role.AllowedTargets) != 1 || role.AllowedTargets[0] != "db-agent.data-mesh" {
+ if len(role.AllowedTargets) != 1 || role.AllowedTargets[0] != "node:db-agent.data-mesh" {
t.Errorf("unexpected allowed targets: %v", role.AllowedTargets)
}
- if len(role.AllowedServices) != 1 || role.AllowedServices[0] != "query_database" {
+ if len(role.AllowedServices) != 1 || role.AllowedServices[0] != "system:query-database" {
t.Errorf("unexpected allowed tools: %v", role.AllowedServices)
}
if len(role.CustomDatalog) != 1 || role.CustomDatalog[0] != `department("analytics");` {
@@ -100,7 +100,7 @@ bindings:
role: "mesh-member"
roles:
mesh-member:
- allowed_services: ["/sam/mcp/1.0.0"]
+ allowed_services: ["mcp:1.0.0"]
`
bindingsFile := filepath.Join(dir, "bindings.yaml")
if err := os.WriteFile(bindingsFile, []byte(bindingsYAML), 0644); err != nil {
@@ -126,7 +126,7 @@ bindings:
role: "non-existent-role"
roles:
mesh-member:
- allowed_services: ["/sam/mcp/1.0.0"]
+ allowed_services: ["mcp:1.0.0"]
`
invalidBindingFile := filepath.Join(dir, "invalid_binding.yaml")
if err := os.WriteFile(invalidBindingFile, []byte(invalidBindingYAML), 0644); err != nil {
@@ -146,7 +146,7 @@ bindings:
role: "mesh-member"
roles:
mesh-member:
- allowed_services: ["/sam/mcp/1.0.0"]
+ allowed_services: ["mcp:1.0.0"]
`
userBindingFile := filepath.Join(dir, "user_binding.yaml")
if err := os.WriteFile(userBindingFile, []byte(userBindingYAML), 0644); err != nil {
@@ -171,7 +171,7 @@ bindings:
- role: "mesh-member"
roles:
mesh-member:
- allowed_services: ["/sam/mcp/1.0.0"]
+ allowed_services: ["mcp:1.0.0"]
`
missingBothFile := filepath.Join(dir, "missing_both.yaml")
if err := os.WriteFile(missingBothFile, []byte(missingBothYAML), 0644); err != nil {
@@ -192,7 +192,7 @@ bindings:
role: "mesh-member"
roles:
mesh-member:
- allowed_services: ["/sam/mcp/1.0.0"]
+ allowed_services: ["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/config.go b/cmd/sam-node/config.go
index 814f299e..ccbe6cbd 100644
--- a/cmd/sam-node/config.go
+++ b/cmd/sam-node/config.go
@@ -39,6 +39,12 @@ func LoadNodeConfig(path string) (*NodeConfigComplete, error) {
Services: config.Services,
}
+ for i, svc := range config.Services {
+ if err := api.ValidateServiceFormat(svc.Type + ":" + svc.Name); err != nil {
+ return nil, fmt.Errorf("invalid service config at index %d: %w", i, err)
+ }
+ }
+
for _, pStr := range config.Attenuation.Policies {
trimmed := strings.TrimRight(strings.TrimSpace(pStr), ";")
p, err := parser.FromStringPolicy(trimmed)
diff --git a/cmd/sam-node/gate_test.go b/cmd/sam-node/gate_test.go
index c14ca7b7..7d1c541c 100644
--- a/cmd/sam-node/gate_test.go
+++ b/cmd/sam-node/gate_test.go
@@ -125,7 +125,6 @@ func startBareNode(t *testing.T, ctx context.Context) (*SamNode, func()) {
AllowLoopback: true,
MonitorBootstrap: 2 * time.Minute,
MonitorInterval: 1 * time.Minute,
- TrustHubRBAC: true,
BiscuitTimeout: 500 * time.Millisecond,
})
if err != nil {
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 9c8b9156..68223fb4 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -79,11 +79,10 @@ var (
autoRelayBootDelayFlag time.Duration
autoRelayBackoffFlag time.Duration
- apiTokenFlag string
- tlsCertFlag string
- tlsKeyFlag string
- tlsCAFlag string
- trustHubRBACFlag bool
+ apiTokenFlag string
+ tlsCertFlag string
+ tlsKeyFlag string
+ tlsCAFlag string
)
var logger = golog.Logger("sam-node")
@@ -220,7 +219,6 @@ func main() {
AutoRelayMinInterval: autoRelayMinIntervalFlag,
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
- TrustHubRBAC: trustHubRBACFlag,
})
if err != nil {
logger.Fatalf("Failed to start mesh node: %v", err)
@@ -276,7 +274,6 @@ func main() {
AutoRelayMinInterval: autoRelayMinIntervalFlag,
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
- TrustHubRBAC: trustHubRBACFlag,
})
if err != nil {
enrollCancel()
@@ -324,7 +321,6 @@ func main() {
AutoRelayMinInterval: autoRelayMinIntervalFlag,
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
- TrustHubRBAC: trustHubRBACFlag,
})
if err != nil {
logger.Fatalf("Failed to start mesh node after enrollment: %v", err)
@@ -472,7 +468,6 @@ 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)
@@ -518,7 +513,6 @@ 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")
@@ -645,6 +639,7 @@ func (n *SamNode) Enroll(ctx context.Context, jwt string) error {
if err := n.Store.SaveIdentity(enrollResp.BiscuitToken); err != nil {
return fmt.Errorf("failed to save identity: %v", err)
}
+ n.SetIdentityCache(enrollResp.BiscuitToken)
if err := n.Store.SaveIdentityExpiration(enrollResp.Expiration); err != nil {
return fmt.Errorf("failed to save identity expiration: %v", err)
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index c93a5ec2..55e695d8 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -44,7 +44,7 @@ Reach into the mesh only when the needed tool isn't available locally. To do so:
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.
-Remote tool names are namespaced as '<service>.<tool>' (e.g. 'code-reviewer.review_pr'). Prefer discovering and describing a tool before calling it rather than guessing arguments.`
+Remote tool names are namespaced as '<service>/<tool>' (e.g. 'code-reviewer/review_pr'). Prefer discovering and describing a tool before calling it rather than guessing arguments.`
// NewMCPServer creates a new MCP server instance with all tools registered.
func NewMCPServer(node *SamNode) *mcp.Server {
@@ -365,7 +365,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 := api.CatalogTarget
originalToolName := toolName
- if parts := strings.SplitN(toolName, ".", 2); len(parts) == 2 {
+ if parts := strings.SplitN(toolName, "/", 2); len(parts) == 2 {
targetService = parts[0]
originalToolName = parts[1]
}
diff --git a/cmd/sam-node/mcp_handlers.go b/cmd/sam-node/mcp_handlers.go
index ba712489..1bef0aef 100644
--- a/cmd/sam-node/mcp_handlers.go
+++ b/cmd/sam-node/mcp_handlers.go
@@ -362,8 +362,8 @@ func (n *SamNode) fetchRemoteToolCatalogue(ctx context.Context, targetPeer peer.
if t == nil {
continue
}
- t.Name = connectService + "." + t.Name
- if serviceNameFilter != "" && !strings.HasPrefix(t.Name, serviceNameFilter+".") {
+ t.Name = connectService + "/" + t.Name
+ if serviceNameFilter != "" && !strings.HasPrefix(t.Name, serviceNameFilter+"/") {
continue
}
rows = append(rows, remoteToolRow{
@@ -453,7 +453,7 @@ type remoteToolDescription struct {
// sidecar tool.
type DescribeRemoteToolParams struct {
PeerID string `json:"peer_id" jsonschema:"Peer ID of the node hosting the server. Required."`
- ToolName string `json:"tool_name" jsonschema:"Namespaced server name as returned by find_remote_tools (e.g. 'code-reviewer.review_pr'). Required."`
+ ToolName string `json:"tool_name" jsonschema:"Namespaced server name as returned by find_remote_tools (e.g. 'code-reviewer/review_pr'). Required."`
}
// handleDescribeRemoteTool implements the describe_remote_tool client-facing tool.
@@ -470,9 +470,9 @@ func (n *SamNode) handleDescribeRemoteTool(ctx context.Context, req *mcp.CallToo
return nil, nil, fmt.Errorf("invalid peer_id: %w", err)
}
- parts := strings.SplitN(params.ToolName, ".", 2)
+ parts := strings.SplitN(params.ToolName, "/", 2)
if len(parts) != 2 {
- return nil, nil, fmt.Errorf("invalid tool_name format, expected 'service.tool'")
+ return nil, nil, fmt.Errorf("invalid tool_name format, expected 'service/tool'")
}
serviceName := parts[0]
actualToolName := parts[1]
diff --git a/cmd/sam-node/mcp_handlers_test.go b/cmd/sam-node/mcp_handlers_test.go
index 95fea73f..acfe4079 100644
--- a/cmd/sam-node/mcp_handlers_test.go
+++ b/cmd/sam-node/mcp_handlers_test.go
@@ -25,6 +25,7 @@ import (
func buildAndSaveBiscuit(node *SamNode, rootPriv ed25519.PrivateKey) error {
callerID := node.Host.ID().String()
builder := biscuit.NewBuilder(rootPriv)
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: "node",
IDs: []biscuit.Term{biscuit.String(callerID)},
@@ -38,8 +39,8 @@ func buildAndSaveBiscuit(node *SamNode, rootPriv ed25519.PrivateKey) error {
return err
}
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactAllowService,
- IDs: []biscuit.Term{biscuit.String("*"), biscuit.String("*")},
+ Name: "granted_service_all_types",
+ IDs: []biscuit.Term{},
}}); err != nil {
return err
}
@@ -160,8 +161,8 @@ func TestHandleFindRemoteTools_SinglePeer(t *testing.T) {
}
wantNames := map[string]bool{
- "mcp:code-reviewer.review_pr": false,
- "mcp:code-reviewer.add_comment": false,
+ "mcp:code-reviewer/review_pr": false,
+ "mcp:code-reviewer/add_comment": false,
}
for _, row := range rows {
if row.PeerID != nodeB.Host.ID().String() {
@@ -265,76 +266,16 @@ func TestHandleFindRemoteTools_MeshWide(t *testing.T) {
}
// Test permutation 1: no prefix gets "mcp:" automatically prepended.
- if !gotNames["mcp:code-reviewer.review_pr"] {
- t.Errorf("missing mcp:code-reviewer.review_pr; got %v", gotNames)
+ if !gotNames["mcp:code-reviewer/review_pr"] {
+ t.Errorf("missing mcp:code-reviewer/review_pr; got %v", gotNames)
}
// Test permutation 2: "mcp:" prefix is preserved.
- if !gotNames["mcp:summarizer.summarize"] {
- t.Errorf("missing mcp:summarizer.summarize; got %v", gotNames)
+ if !gotNames["mcp:summarizer/summarize"] {
+ t.Errorf("missing mcp:summarizer/summarize; got %v", gotNames)
}
// Test permutation 3: custom namespace prefix is preserved.
- if !gotNames["plugin:linter.lint"] {
- t.Errorf("missing plugin:linter.lint; got %v", gotNames)
- }
-}
-
-func TestHandleFindRemoteTools_MeshWideViaHandler(t *testing.T) {
- t.Skip("requires DHT convergence; isolated libp2p hosts cannot form a functional provider store. Covered by e2e tests.")
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
- bSrv := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{
- {Name: "review_pr", Description: "x", InputSchema: map[string]any{"type": "object"}},
- }))
- defer bSrv.Close()
-
- nodeA, cleanupA := startBareNode(t, ctx)
- defer cleanupA()
- nodeB, cleanupB := startBareNode(t, ctx)
- defer cleanupB()
-
- rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
- if err != nil {
- t.Fatal(err)
- }
- if err := buildAndSaveBiscuit(nodeA, rootPriv); err != nil {
- t.Fatalf("buildAndSaveBiscuit: %v", err)
- }
- if err := nodeA.Host.Connect(ctx, peer.AddrInfo{ID: nodeB.Host.ID(), Addrs: nodeB.Host.Addrs()}); err != nil {
- t.Fatal(err)
- }
- nodeB.keysMu.Lock()
- nodeB.trustedKeys = append(nodeB.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
- nodeB.keysMu.Unlock()
-
- if err := nodeB.RegisterService(ctx, &api.RegisterServiceRequest{
- Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},
- Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: bSrv.URL},
- }); err != nil {
- t.Fatalf("RegisterService: %v", err)
- }
-
- // Give the DHT a moment to record the provider.
- time.Sleep(500 * time.Millisecond)
-
- res, _, err := nodeA.handleFindRemoteTools(ctx, &mcp.CallToolRequest{}, FindRemoteToolsParams{})
- if err != nil {
- t.Fatalf("handler: %v", err)
- }
- tc := res.Content[0].(*mcp.TextContent)
- var rows []remoteToolRow
- if err := json.Unmarshal([]byte(tc.Text), &rows); err != nil {
- t.Fatal(err)
- }
-
- found := false
- for _, r := range rows {
- if r.ToolName == "code-reviewer.review_pr" && r.PeerID == nodeB.Host.ID().String() {
- found = true
- }
- }
- if !found {
- t.Errorf("expected code-reviewer.review_pr from B; got rows=%+v", rows)
+ if !gotNames["plugin:linter/lint"] {
+ t.Errorf("missing plugin:linter/lint; got %v", gotNames)
}
}
@@ -392,18 +333,22 @@ func TestHandleFindRemoteTools_PartialFailure(t *testing.T) {
gotSummarizer := false
for _, r := range rows {
- if r.ToolName == "mcp:summarizer.summarize" {
+ if r.ToolName == "mcp:summarizer/summarize" {
gotSummarizer = true
}
}
if !gotSummarizer {
- t.Errorf("expected mcp:summarizer.summarize from C even with B unreachable; got %+v", rows)
+ t.Errorf("expected mcp:summarizer/summarize from C even with B unreachable; got %+v", rows)
}
}
func buildAndSaveCustomBiscuit(node *SamNode, rootPriv ed25519.PrivateKey, allowedServices []string) error {
callerID := node.Host.ID().String()
builder := biscuit.NewBuilder(rootPriv)
+ err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
+ if err != nil {
+ return err
+ }
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: "node",
IDs: []biscuit.Term{biscuit.String(callerID)},
@@ -424,7 +369,7 @@ func buildAndSaveCustomBiscuit(node *SamNode, rootPriv ed25519.PrivateKey, allow
opName = parts[1]
}
if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactAllowService,
+ Name: "granted_service_exact",
IDs: []biscuit.Term{biscuit.String(opType), biscuit.String(opName)},
}}); err != nil {
return err
@@ -546,7 +491,7 @@ func TestHandleDescribeRemoteTool_EmptyPeerID(t *testing.T) {
defer cleanup()
_, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
- ToolName: "code-reviewer.review_pr",
+ ToolName: "code-reviewer/review_pr",
})
if err == nil {
t.Fatal("expected error for empty peer_id")
@@ -582,7 +527,7 @@ func TestHandleDescribeRemoteTool_NonNamespacedRejected(t *testing.T) {
if err == nil {
t.Fatal("expected error for tool_name without '.'")
}
- if !strings.Contains(err.Error(), "service.tool") {
+ if !strings.Contains(err.Error(), "service/tool") {
t.Errorf("error %q does not explain the namespacing requirement", err.Error())
}
}
@@ -596,7 +541,7 @@ func TestHandleDescribeRemoteTool_SelfPeerRejected(t *testing.T) {
_, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
PeerID: node.Host.ID().String(),
- ToolName: "code-reviewer.review_pr",
+ ToolName: "code-reviewer/review_pr",
})
if err == nil {
t.Fatal("expected error when peer_id equals self peer ID")
@@ -612,7 +557,7 @@ func TestHandleDescribeRemoteTool_InvalidPeerID(t *testing.T) {
_, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
PeerID: "not-a-valid-peer-id",
- ToolName: "code-reviewer.review_pr",
+ ToolName: "code-reviewer/review_pr",
})
if err == nil {
t.Fatal("expected error for malformed peer_id")
@@ -676,7 +621,7 @@ func TestHandleDescribeRemoteTool_RoundTrip(t *testing.T) {
res, _, err := nodeA.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
PeerID: nodeB.Host.ID().String(),
- ToolName: "code-reviewer.review_pr",
+ ToolName: "code-reviewer/review_pr",
})
if err != nil {
t.Fatalf("handleDescribeRemoteTool: %v", err)
@@ -693,8 +638,8 @@ func TestHandleDescribeRemoteTool_RoundTrip(t *testing.T) {
if desc.PeerID != nodeB.Host.ID().String() {
t.Errorf("PeerID = %q, want %q", desc.PeerID, nodeB.Host.ID().String())
}
- if desc.ToolName != "code-reviewer.review_pr" {
- t.Errorf("ToolName = %q, want %q", desc.ToolName, "code-reviewer.review_pr")
+ if desc.ToolName != "code-reviewer/review_pr" {
+ t.Errorf("ToolName = %q, want %q", desc.ToolName, "code-reviewer/review_pr")
}
if desc.Description != "Run a code review" {
t.Errorf("Description = %q, want %q", desc.Description, "Run a code review")
@@ -754,7 +699,7 @@ func TestHandleDescribeRemoteTool_RoundTrip_UnknownTool(t *testing.T) {
_, _, err = nodeA.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
PeerID: nodeB.Host.ID().String(),
- ToolName: "code-reviewer.does-not-exist",
+ ToolName: "code-reviewer/does-not-exist",
})
if err == nil {
t.Fatal("expected error from peer when tool is not registered")
diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.go
index 154ffc3a..54b977f0 100644
--- a/cmd/sam-node/middleware.go
+++ b/cmd/sam-node/middleware.go
@@ -16,8 +16,6 @@ package main
import (
"crypto/ed25519"
- "crypto/sha256"
- "encoding/hex"
"fmt"
"github.com/biscuit-auth/biscuit-go/v2"
@@ -31,52 +29,77 @@ import (
)
var (
- baselineRule1 biscuit.Policy
- baselineRule2 biscuit.Policy
- baselineRule3 biscuit.Policy
- baselineRule4 biscuit.Policy
+ baselinePolicies []biscuit.Policy
+ baselineRules []biscuit.Rule
baselineReplayCheck biscuit.Check
+ baselineTargetCheck biscuit.Check
+ targetFactRules []biscuit.Rule
)
-// init compiles the baseline Datalog rules and checks for the node.
-// These rules are loaded at initialization to avoid runtime parsing overhead.
-// Baseline Rules:
-// 1. Exact Match: Allows the request if the token explicitly allows the specific service type and name.
-// 2. Global Wildcard: Allows the request if the token explicitly grants access to all services ("*", "*").
-// 3. Catalog Target: Allows access to the service discovery catalog ("system", "catalog").
-// 4. Type Wildcard: Allows the request if the token explicitly grants access to all names under a specific service type ($type, "*").
-// 5. Replay Check: Enforces that the peer identity bound in the token matches the physical connection peer ID.
+// init compiles the baseline Datalog rules, policies, and checks for the node.
+// These are loaded at initialization to avoid runtime parsing overhead.
func init() {
- var err error
- 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))
+ // 1. Service Allow Policies
+ policyStrs := []string{
+ fmt.Sprintf(`allow if service($type, $name), %s($type, $name)`, api.FactGrantedServiceExact),
+ fmt.Sprintf(`allow if service($type, $name), %s($type, $prefix), $name.starts_with($prefix)`, api.FactGrantedServicePrefix),
+ fmt.Sprintf(`allow if service($type, $name), %s($type, $suffix), $name.ends_with($suffix)`, api.FactGrantedServiceSuffix),
+ fmt.Sprintf(`allow if service($type, $name), %s($type)`, api.FactGrantedServiceAll),
+ fmt.Sprintf(`allow if service($type, $name), %s()`, api.FactGrantedServiceAllTypes),
+ fmt.Sprintf(`allow if service("system", "%s")`, api.CatalogTarget),
}
- 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))
+ for i, pStr := range policyStrs {
+ p, err := parser.FromStringPolicy(pStr)
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse baseline policy %d: %v", i, err))
+ }
+ baselinePolicies = append(baselinePolicies, p)
}
- rule3Str := fmt.Sprintf(`allow if service("system", "%s")`, api.CatalogTarget)
- baselineRule3, err = parser.FromStringPolicy(rule3Str)
+ // 2. Target Evaluation Rules
+ // These rules satisfy the check if allow_network_target($fact, $val) injected by the Hub.
+ ruleStrs := []string{
+ fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s($fact, $val)`, api.FactGrantedTargetExact),
+ fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s($fact, $prefix), $val.starts_with($prefix)`, api.FactGrantedTargetPrefix),
+ fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s($fact, $suffix), $val.ends_with($suffix)`, api.FactGrantedTargetSuffix),
+ fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s($fact)`, api.FactGrantedTargetAll),
+ fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s()`, api.FactGrantedTargetAllFacts),
+ }
+
+ for i, rStr := range ruleStrs {
+ r, err := parser.FromStringRule(rStr)
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse baseline rule %d: %v", i, err))
+ }
+ baselineRules = append(baselineRules, r)
+ }
+
+ var err error
+ baselineReplayCheck, err = parser.FromStringCheck(`check if client_peer_id($id), connection_peer_id($id)`)
if err != nil {
- panic(fmt.Sprintf("failed to parse baseline rule 3: %v", err))
+ panic(fmt.Sprintf("failed to parse replay check: %v", err))
}
- rule4Str := fmt.Sprintf(`allow if service($type, $name), %s($type, "*")`, api.FactAllowService)
- baselineRule4, err = parser.FromStringPolicy(rule4Str)
+ baselineTargetCheck, err = parser.FromStringCheck(`check if allow_network_target($fact, $val) or target_unrestricted()`)
if err != nil {
- panic(fmt.Sprintf("failed to parse baseline rule 4: %v", err))
+ panic(fmt.Sprintf("failed to parse target check: %v", err))
+ }
+
+ for _, val := range api.OIDCClaimToFact() {
+ ruleStr := fmt.Sprintf(`target_fact(%q, $val) <- %s($val)`, val, val)
+ r, err := parser.FromStringRule(ruleStr)
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse target fact rule: %v", err))
+ }
+ targetFactRules = append(targetFactRules, r)
}
- replayCheckStr := `check if client_peer_id($id), connection_peer_id($id)`
- baselineReplayCheck, err = parser.FromStringCheck(replayCheckStr)
+ r, err := parser.FromStringRule(`target_fact("node", $val) <- node($val)`)
if err != nil {
- panic(fmt.Sprintf("failed to parse replay check: %v", err))
+ panic(fmt.Sprintf("failed to parse node fact rule: %v", err))
}
+ targetFactRules = append(targetFactRules, r)
}
// RequestContext carries the security metadata for a specific stream request
@@ -127,85 +150,15 @@ func (n *SamNode) WithBiscuitAuth(next func(network.Stream, RequestContext)) net
writer := msgio.NewVarintWriter(s)
- // Check revocation cache
- if _, isRevoked := n.revokedPeers.Get(remotePeer.String()); isRevoked {
- logger.Warnf("[Auth] Peer %s is revoked", remotePeer)
- resp := &api.AuthResponse{Success: false, Error: "Peer is revoked"}
- respBytes, err := proto.Marshal(resp)
- if err != nil {
- logger.Errorf("[Auth] Failed to marshal revocation response: %v", err)
- return
- }
- _ = writer.WriteMsg(respBytes)
- return
- }
-
- // Check verification cache
- tokenHash := sha256.Sum256(authFrame.Biscuit)
- hashStr := hex.EncodeToString(tokenHash[:]) + "\x00" + remotePeer.String() + "\x00" + reqCtx.Protocol + "\x00" + reqCtx.Target
-
- if pubKeyStr, ok := n.verificationCache.Get(hashStr); ok {
- n.keysMu.RLock()
- keys := n.trustedKeys
- n.keysMu.RUnlock()
-
- trusted := false
- for _, tk := range keys {
- if hex.EncodeToString(tk.Key) == pubKeyStr {
- trusted = true
- break
- }
- }
- if trusted {
- logger.Infof("[Auth] Token cache hit for %s", remotePeer)
- // Valid
- resp := &api.AuthResponse{Success: true}
- respBytes, err := proto.Marshal(resp)
- if err != nil {
- logger.Errorf("[Auth] Failed to marshal ACK response: %v", err)
- return
- }
- if err := writer.WriteMsg(respBytes); err != nil {
- logger.Errorf("[Auth] Failed to write ACK to %s: %v", remotePeer, err)
- return
- }
- next(s, reqCtx)
- return
- }
- }
-
- n.keysMu.RLock()
- keys := n.trustedKeys
- n.keysMu.RUnlock()
-
- var authorized bool
- var lastErr error
- var successfulKey ed25519.PublicKey
- for _, pubKey := range keys {
- logger.Infof("[Auth] Trying key: %x", pubKey.Key)
- if err := n.Authorize(authFrame.Biscuit, reqCtx, pubKey.Key); err == nil {
- authorized = true
- successfulKey = pubKey.Key
- break
- } else {
- lastErr = err
- }
- }
-
- if !authorized {
- logger.Warnf("[Auth] AuthZ Denied %s: %v", remotePeer, lastErr)
- resp := &api.AuthResponse{Success: false, Error: "Authorization failed"}
- if lastErr != nil {
- resp.Error = lastErr.Error()
- }
+ err = n.VerifyBiscuitToken(authFrame.Biscuit, reqCtx)
+ if err != nil {
+ logger.Warnf("[Auth] AuthZ Denied %s: %v", remotePeer, err)
+ resp := &api.AuthResponse{Success: false, Error: err.Error()}
respBytes, _ := proto.Marshal(resp)
_ = writer.WriteMsg(respBytes)
return
}
- // Cache successful verification
- n.verificationCache.Add(hashStr, hex.EncodeToString(successfulKey))
-
// Valid
resp := &api.AuthResponse{Success: true}
respBytes, _ := proto.Marshal(resp)
@@ -218,6 +171,44 @@ func (n *SamNode) WithBiscuitAuth(next func(network.Stream, RequestContext)) net
}
}
+// VerifyBiscuitToken checks revocation, cache, and evaluates the token against trusted keys and local policies.
+func (n *SamNode) VerifyBiscuitToken(biscuitBytes []byte, reqCtx RequestContext) error {
+ remotePeer := reqCtx.PeerID
+
+ // Check revocation cache
+ if n.revokedPeers != nil {
+ if _, isRevoked := n.revokedPeers.Get(remotePeer.String()); isRevoked {
+ logger.Warnf("[Auth] Peer %s is revoked", remotePeer)
+ return fmt.Errorf("peer is revoked")
+ }
+ }
+
+ n.keysMu.RLock()
+ keys := n.trustedKeys
+ n.keysMu.RUnlock()
+
+ var authorized bool
+ var lastErr error
+ for _, pubKey := range keys {
+ logger.Infof("[Auth] Trying key: %x", pubKey.Key)
+ if err := n.Authorize(biscuitBytes, reqCtx, pubKey.Key); err == nil {
+ authorized = true
+ break
+ } else {
+ lastErr = err
+ }
+ }
+
+ if !authorized {
+ if lastErr != nil {
+ return lastErr
+ }
+ return fmt.Errorf("authorization failed")
+ }
+
+ return nil
+}
+
func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.PublicKey) error {
if len(pubKey) != ed25519.PublicKeySize {
return fmt.Errorf("invalid public key size: %d", len(pubKey))
@@ -271,7 +262,9 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
// Enforce client_peer_id matches connection_peer_id
authorizer.AddCheck(baselineReplayCheck)
- // Apply Pre-compiled Local Attenuation
+ // Inject facts from our own identity token to support target matching
+ n.injectIdentityFacts(authorizer, pubKey)
+
if n.LocalPolicy != nil {
for _, p := range n.LocalPolicy.Policies {
authorizer.AddPolicy(p)
@@ -284,18 +277,66 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
}
}
- // Baseline Rules
- if n.TrustHubRBAC {
- authorizer.AddPolicy(baselineRule1)
- authorizer.AddPolicy(baselineRule2)
- authorizer.AddPolicy(baselineRule3)
- authorizer.AddPolicy(baselineRule4)
+ // Apply Baseline Policies and Rules
+ authorizer.AddCheck(baselineTargetCheck)
+ for _, p := range baselinePolicies {
+ authorizer.AddPolicy(p)
+ }
+ for _, r := range baselineRules {
+ authorizer.AddRule(r)
}
err = authorizer.Authorize()
if err != nil {
- logger.Errorf("Authorizer failure: %v", err)
+ logger.Errorf("Authorizer failure: %v, token: %s", err, b.String())
logger.Debugf("Authorizer state: %s", authorizer.PrintWorld())
}
return err
}
+
+func (n *SamNode) injectIdentityFacts(authorizer biscuit.Authorizer, pubKey ed25519.PublicKey) {
+ ourIdentity := n.GetIdentity()
+ if ourIdentity == nil {
+ return
+ }
+
+ ourB, err := biscuit.Unmarshal(ourIdentity)
+ if err != nil {
+ logger.Warnf("Failed to unmarshal our own identity: %v", err)
+ return
+ }
+
+ n.keysMu.RLock()
+ keys := n.trustedKeys
+ n.keysMu.RUnlock()
+
+ var auth biscuit.Authorizer
+ var authErr error
+ for _, tk := range keys {
+ if a, err := ourB.Authorizer(tk.Key); err == nil {
+ auth = a
+ break
+ } else {
+ authErr = err
+ }
+ }
+
+ if auth == nil {
+ logger.Warnf("Failed to create authorizer for our own identity: %v", authErr)
+ return
+ }
+
+ // We must Authorize() to evaluate the token's facts into the world
+ if err := auth.Authorize(); err != nil {
+ logger.Warnf("Failed to authorize our own identity token: %v", err)
+ // we continue anyway, as we just want the facts, but ideally it shouldn't fail
+ }
+
+ for _, rule := range targetFactRules {
+ if factSet, err := auth.Query(rule); err == nil {
+ for _, fact := range factSet {
+ authorizer.AddFact(fact)
+ }
+ }
+ }
+}
diff --git a/cmd/sam-node/middleware_test.go b/cmd/sam-node/middleware_test.go
index db1e675f..35cc5ee7 100644
--- a/cmd/sam-node/middleware_test.go
+++ b/cmd/sam-node/middleware_test.go
@@ -17,9 +17,7 @@ package main
import (
"context"
"crypto/ed25519"
- "crypto/sha256"
- "encoding/hex"
- "fmt"
+
"io"
"os"
"path/filepath"
@@ -107,6 +105,7 @@ func TestAuthorize(t *testing.T) {
}
builder := biscuit.NewBuilder(priv)
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
dummyPeer := peer.ID("dummy-peer")
// Bind to peer
@@ -129,7 +128,7 @@ func TestAuthorize(t *testing.T) {
// Add fact to match baseline rule
err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactAllowService,
+ Name: "granted_service_exact",
IDs: []biscuit.Term{biscuit.String("system"), biscuit.String("/test/proto")},
}})
if err != nil {
@@ -149,7 +148,6 @@ func TestAuthorize(t *testing.T) {
node := &SamNode{
Store: store,
trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
- TrustHubRBAC: true,
BiscuitTimeout: 500 * time.Millisecond,
}
@@ -181,7 +179,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Rule 1: Exact Match",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := fmt.Sprintf(`%s("mcp", "test_tool")`, api.FactAllowService)
+ factStr := `granted_service_exact("mcp", "test_tool")`
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
},
@@ -192,7 +190,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Rule 2: Global Wildcard",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := fmt.Sprintf(`%s("*", "*")`, api.FactAllowService)
+ factStr := `granted_service_all_types()`
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
},
@@ -212,7 +210,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Rule 4: Type Wildcard",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := fmt.Sprintf(`%s("mcp", "*")`, api.FactAllowService)
+ factStr := `granted_service_all("mcp")`
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
},
@@ -223,7 +221,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Rule Rejection: Type Wildcard does not allow other types",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := fmt.Sprintf(`%s("mcp", "*")`, api.FactAllowService)
+ factStr := `granted_service_all("mcp")`
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
},
@@ -234,7 +232,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Replay Check Rejection: mismatched peer ID",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := fmt.Sprintf(`%s("mcp", "test_tool")`, api.FactAllowService)
+ factStr := `granted_service_exact("mcp", "test_tool")`
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
// deliberately add a different client_peer_id than the connection peer ID
@@ -252,6 +250,7 @@ func TestBaselineRules(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
builder := biscuit.NewBuilder(priv)
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: "node",
IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
@@ -272,7 +271,6 @@ func TestBaselineRules(t *testing.T) {
node := &SamNode{
trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
- TrustHubRBAC: true,
BiscuitTimeout: 500 * time.Millisecond,
}
@@ -310,7 +308,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 1 (Happy Path)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`allow_service("system", "query_db")`)
+ fact, err := parser.FromStringFact(`granted_service_exact("system", "query_db")`)
if err != nil {
t.Fatal(err)
}
@@ -324,7 +322,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 2 (Unauthorized Tool)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`allow_service("system", "query_db")`)
+ fact, err := parser.FromStringFact(`granted_service_exact("system", "query_db")`)
if err != nil {
t.Fatal(err)
}
@@ -338,7 +336,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 3 (Wildcard Access)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`allow_service("*", "*")`)
+ fact, err := parser.FromStringFact(`granted_service_all_types()`)
if err != nil {
t.Fatal(err)
}
@@ -352,7 +350,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_service("*", "*")`)
+ fact1, err := parser.FromStringFact(`granted_service_all_types()`)
if err != nil {
t.Fatal(err)
}
@@ -381,6 +379,7 @@ attenuation:
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
builder := biscuit.NewBuilder(priv)
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: "node",
@@ -428,7 +427,6 @@ attenuation:
node := &SamNode{
trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
LocalPolicy: localPolicy,
- TrustHubRBAC: true,
BiscuitTimeout: 500 * time.Millisecond,
}
@@ -460,6 +458,7 @@ func TestRevocation(t *testing.T) {
dummyPeer := peer.ID("dummy-peer-id") // Must match mockStream.Conn().RemotePeer()
builder := biscuit.NewBuilder(priv)
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: "node",
IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
@@ -533,8 +532,8 @@ func TestRevocation(t *testing.T) {
if resp.Success {
t.Error("expected failure for revoked peer, got success")
}
- if resp.Error != "Peer is revoked" {
- t.Errorf("expected error 'Peer is revoked', got %q", resp.Error)
+ if resp.Error != "peer is revoked" {
+ t.Errorf("expected error 'peer is revoked', got %q", resp.Error)
}
}
@@ -581,146 +580,121 @@ func TestVerifyEvent(t *testing.T) {
}
}
-func TestVerifyBiscuitCache(t *testing.T) {
+func TestMiddlewareTargetChecks(t *testing.T) {
pub, priv, err := ed25519.GenerateKey(nil)
if err != nil {
- t.Fatal(err)
- }
-
- dummyPeer := peer.ID("dummy-peer-id")
-
- builder := biscuit.NewBuilder(priv)
- err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "node",
- IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
- }})
- if err != nil {
- t.Fatal(err)
- }
-
- b, err := builder.Build()
- if err != nil {
- t.Fatal(err)
- }
-
- tokenBytes, err := b.Serialize()
- if err != nil {
- t.Fatal(err)
- }
-
- cache, _ := lru.New[string, string](10)
-
- node := &SamNode{
- trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
- verificationCache: cache,
- BiscuitTimeout: 500 * time.Millisecond,
- }
-
- // Case 1: Fresh verification (uncached)
- _, err = node.verifyBiscuit(tokenBytes, dummyPeer)
- if err != nil {
- t.Fatalf("Expected verifyBiscuit to succeed, got err: %v", err)
+ t.Fatalf("failed to generate key: %v", err)
}
+ dummyPeer := peer.ID("dummy-peer")
- tokenHash := sha256.Sum256(tokenBytes)
- hashStr := hex.EncodeToString(tokenHash[:]) + ":" + dummyPeer.String()
-
- if pubKeyStr, ok := cache.Get(hashStr); !ok || pubKeyStr != hex.EncodeToString(pub) {
- t.Fatal("Expected token to be in verification cache with correct key")
+ tests := []struct {
+ name string
+ mintToken func(t *testing.T, builder biscuit.Builder)
+ req RequestContext
+ expectSuccess bool
+ }{
+ {
+ name: "Target Check: Allowed by User Fact",
+ mintToken: func(t *testing.T, builder biscuit.Builder) {
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "granted_target_exact",
+ IDs: []biscuit.Term{biscuit.String("user"), biscuit.String("bob")},
+ }})
+ },
+ req: RequestContext{
+ PeerID: dummyPeer,
+ Protocol: "test_tool",
+ Target: "mcp:test_tool",
+ User: "bob",
+ },
+ expectSuccess: true,
+ },
+ {
+ name: "Target Check: Rejected by wrong User Fact",
+ mintToken: func(t *testing.T, builder biscuit.Builder) {
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "granted_target_exact",
+ IDs: []biscuit.Term{biscuit.String("user"), biscuit.String("alice")},
+ }})
+ },
+ req: RequestContext{
+ PeerID: dummyPeer,
+ Protocol: "test_tool",
+ Target: "mcp:test_tool",
+ User: "bob",
+ },
+ expectSuccess: false,
+ },
+ {
+ name: "Target Check: Allowed by Group Fact",
+ mintToken: func(t *testing.T, builder biscuit.Builder) {
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "granted_target_exact",
+ IDs: []biscuit.Term{biscuit.String("group"), biscuit.String("eng")},
+ }})
+ },
+ req: RequestContext{
+ PeerID: dummyPeer,
+ Protocol: "test_tool",
+ Target: "mcp:test_tool",
+ Group: "eng",
+ },
+ expectSuccess: true,
+ },
}
- // Case 2: Key rotation - corrupt keys and try again.
- // Even if the token is in the cache, it should fail if the key that verified it is no longer trusted.
- node.keysMu.Lock()
- invalidKey := make([]byte, ed25519.PublicKeySize)
- copy(invalidKey, []byte("invalid-key"))
- node.trustedKeys = []TrustedKey{{Key: invalidKey, ReceivedAt: time.Now()}}
- node.keysMu.Unlock()
-
- _, err = node.verifyBiscuit(tokenBytes, dummyPeer)
- if err == nil {
- t.Fatal("Expected verifyBiscuit to FAIL after key rotation, but it succeeded")
- }
-}
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ builder := biscuit.NewBuilder(priv)
+ // Required basic facts
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "client_peer_id",
+ IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
+ }})
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "node",
+ IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
+ }})
+ // Allow exact service
+ factStr := `granted_service_exact("mcp", "test_tool")`
+ fact, _ := parser.FromStringFact(factStr)
+ _ = builder.AddAuthorityFact(fact)
-func TestAuthorizationCacheBypass(t *testing.T) {
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatal(err)
- }
+ tt.mintToken(t, builder)
- dummyPeer := peer.ID("dummy-peer-id")
+ b, _ := builder.Build()
+ tokenBytes, _ := b.Serialize()
- // Mint token allowing ONLY query_db
- builder := biscuit.NewBuilder(priv)
- _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "node",
- IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
- }})
- _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "client_peer_id",
- IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
- }})
- _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "allow_service",
- IDs: []biscuit.Term{biscuit.String("system"), biscuit.String("query_db")},
- }})
+ // Build the Node Identity Token
+ idBuilder := biscuit.NewBuilder(priv)
+ if tt.req.User != "" {
+ _ = idBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "user",
+ IDs: []biscuit.Term{biscuit.String(tt.req.User)},
+ }})
+ }
+ if tt.req.Group != "" {
+ _ = idBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "group",
+ IDs: []biscuit.Term{biscuit.String(tt.req.Group)},
+ }})
+ }
+ idB, _ := idBuilder.Build()
+ idTokenBytes, _ := idB.Serialize()
- b, _ := builder.Build()
- tokenBytes, _ := b.Serialize()
+ node := &SamNode{
+ trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
+ BiscuitTimeout: 500 * time.Millisecond,
+ }
+ node.SetIdentityCache(idTokenBytes)
- cache, _ := lru.New[string, string](10)
- revCache, _ := lru.New[string, int64](10)
- rl, _ := NewPeerRateLimiter(100)
- node := &SamNode{
- trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},
- verificationCache: cache,
- revokedPeers: revCache,
- rateLimiter: rl,
- TrustHubRBAC: true,
- BiscuitTimeout: 500 * time.Millisecond,
- }
-
- // Helper to simulate request
- doRequest := func(target string) bool {
- pr1, pw1 := io.Pipe()
- pr2, pw2 := io.Pipe()
- serverStream := &mockStream{r: pr1, w: pw2, protocol: protocol.ID("mcp"), conn: &mockConn{remotePeer: dummyPeer}}
-
- done := make(chan bool, 1)
- go func() {
- handler := node.WithBiscuitAuth(func(s network.Stream, reqCtx RequestContext) {
- done <- true
- })
- handler(serverStream)
- close(done)
- }()
-
- writer := msgio.NewVarintWriter(pw1)
- authFrame := &api.AuthFrame{Biscuit: tokenBytes, TargetService: target}
- data, _ := proto.Marshal(authFrame)
- _ = writer.WriteMsg(data)
- pw1.Close() //nolint:errcheck
-
- reader := msgio.NewVarintReaderSize(pr2, 1024*64)
- msg, err := reader.ReadMsg()
- if err != nil {
- return false
- }
- var resp api.AuthResponse
- _ = proto.Unmarshal(msg, &resp)
-
- success := <-done
- return resp.Success && success
- }
-
- // 1. Authorized target should succeed
- if !doRequest("system:query_db") {
- t.Fatal("Expected authorized target to succeed")
- }
-
- // 2. Unauthorized target with the same token should FAIL
- if doRequest("system:reboot_server") {
- t.Fatal("SECURITY BUG: Unauthorized target succeeded due to cache bypass!")
+ err = node.Authorize(tokenBytes, tt.req, pub)
+ if tt.expectSuccess && err != nil {
+ t.Errorf("expected success, got error: %v", err)
+ }
+ if !tt.expectSuccess && err == nil {
+ t.Errorf("expected failure, got success")
+ }
+ })
}
}
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index 7173e42a..47e5279e 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -22,8 +22,7 @@ import (
"bytes"
"context"
"crypto/ed25519"
- "crypto/sha256"
- "encoding/hex"
+ "encoding/base64"
"errors"
"fmt"
"net"
@@ -31,6 +30,7 @@ import (
"os"
"strings"
"sync"
+ "sync/atomic"
"time"
@@ -123,7 +123,6 @@ type SamNode struct {
mu sync.Mutex
LocalPolicy *NodeConfigComplete
revokedPeers *lru.Cache[string, int64]
- verificationCache *lru.Cache[string, string]
authPeers sync.Map
trustedKeys []TrustedKey
keysMu sync.RWMutex
@@ -131,12 +130,13 @@ type SamNode struct {
services *ServiceRegistry
BoundHTTPAddr string
AllowLoopback bool
- TrustHubRBAC bool
- authSuccess chan struct{}
- authOnce sync.Once
- currentRelays []peer.AddrInfo
- reprovideTrigger chan struct{}
- BiscuitTimeout time.Duration
+
+ authSuccess chan struct{}
+ authOnce sync.Once
+ currentRelays []peer.AddrInfo
+ reprovideTrigger chan struct{}
+ BiscuitTimeout time.Duration
+ cachedIdentity atomic.Value
}
// UpdateRelays updates the current relays used by AutoRelay.
@@ -160,6 +160,30 @@ func (n *SamNode) UpdateRelays(addrs []multiaddr.Multiaddr) {
logger.Infof("[Relay] Updated current relays for AutoRelay: %v", newRelays)
}
+// GetIdentity returns the node's biscuit identity, caching it in memory.
+func (n *SamNode) GetIdentity() []byte {
+ if val := n.cachedIdentity.Load(); val != nil {
+ b := val.([]byte)
+ if len(b) > 0 {
+ return b
+ }
+ }
+ if n.Store != nil {
+ if biscuitBytes, err := n.Store.LoadIdentity(); err == nil && len(biscuitBytes) > 0 {
+ n.cachedIdentity.Store(biscuitBytes)
+ return biscuitBytes
+ }
+ }
+ return nil
+}
+
+// SetIdentityCache explicitly updates the cached identity.
+func (n *SamNode) SetIdentityCache(b []byte) {
+ if len(b) > 0 {
+ n.cachedIdentity.Store(b)
+ }
+}
+
func stripP2pFromDnsaddr(addr multiaddr.Multiaddr) multiaddr.Multiaddr {
_, err := addr.ValueForProtocol(multiaddr.P_DNSADDR)
if err != nil {
@@ -204,8 +228,8 @@ type SamNodeConfig struct {
AutoRelayMinInterval time.Duration
AutoRelayBootDelay time.Duration
AutoRelayBackoff time.Duration
- TrustHubRBAC bool
- BiscuitTimeout time.Duration
+
+ BiscuitTimeout time.Duration
}
// NewSamNode creates a new Agent instance secured with the 4-layer pipeline.
@@ -224,9 +248,9 @@ func NewSamNode(ctx context.Context, cfg SamNodeConfig) (*SamNode, error) {
authenticatedHubs: make(map[peer.ID]bool),
LocalPolicy: cfg.NodeConfig,
AllowLoopback: cfg.AllowLoopback,
- TrustHubRBAC: cfg.TrustHubRBAC,
- authSuccess: make(chan struct{}),
- reprovideTrigger: make(chan struct{}, 1),
+
+ authSuccess: make(chan struct{}),
+ reprovideTrigger: make(chan struct{}, 1),
}
node.BiscuitTimeout = cfg.BiscuitTimeout
@@ -241,11 +265,6 @@ func NewSamNode(ctx context.Context, cfg SamNodeConfig) (*SamNode, error) {
return nil, fmt.Errorf("failed to create revocation cache: %w", err)
}
- node.verificationCache, err = lru.New[string, string](VerificationCacheSize)
- if err != nil {
- return nil, fmt.Errorf("failed to create verification cache: %w", err)
- }
-
// Layer 2: Attach the Bouncer (Gater)
gater := &nodeConnGate{node: node}
@@ -1167,21 +1186,6 @@ func (n *SamNode) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscui
return nil, fmt.Errorf("malformed biscuit: %w", err)
}
- tokenHash := sha256.Sum256(biscuitData)
- hashStr := hex.EncodeToString(tokenHash[:]) + ":" + remotePeer.String()
-
- if pubKeyStr, ok := n.verificationCache.Get(hashStr); ok {
- n.keysMu.RLock()
- keys := n.trustedKeys
- n.keysMu.RUnlock()
-
- for _, tk := range keys {
- if hex.EncodeToString(tk.Key) == pubKeyStr {
- return b, nil
- }
- }
- }
-
n.keysMu.RLock()
keys := n.trustedKeys
n.keysMu.RUnlock()
@@ -1207,7 +1211,6 @@ func (n *SamNode) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscui
authorizer.AddPolicy(rule)
if err := authorizer.Authorize(); err == nil {
- n.verificationCache.Add(hashStr, hex.EncodeToString(tk.Key))
return b, nil
} else {
lastErr = fmt.Errorf("authorize error: %w", err)
@@ -1514,6 +1517,42 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
return
}
+ // Extract biscuit from X-Sam-Biscuit header
+ biscuitB64 := r.Header.Get("X-Sam-Biscuit")
+ if biscuitB64 == "" {
+ http.Error(w, "Missing X-Sam-Biscuit header", http.StatusUnauthorized)
+ return
+ }
+ biscuitBytes, err := base64.StdEncoding.DecodeString(biscuitB64)
+ if err != nil {
+ http.Error(w, "Invalid X-Sam-Biscuit encoding", http.StatusBadRequest)
+ return
+ }
+
+ // Parse remote peer from RemoteAddr
+ remotePeer, err := peer.Decode(r.RemoteAddr)
+ if err != nil {
+ http.Error(w, "Invalid remote peer", http.StatusBadRequest)
+ return
+ }
+
+ reqCtx := RequestContext{
+ PeerID: remotePeer,
+ User: "", // Extracted implicitly if needed, or left empty
+ Protocol: "/libp2p-http",
+ Target: strings.ToLower(serviceTypeStr) + ":" + serviceName,
+ }
+
+ // Verify authorization
+ if err := n.VerifyBiscuitToken(biscuitBytes, reqCtx); err != nil {
+ logger.Warnf("[Ingress] AuthZ Denied for %s: %v", remotePeer, err)
+ http.Error(w, "Authorization failed", http.StatusForbidden)
+ return
+ }
+
+ // Strip the biscuit header so it doesn't leak to the backend service
+ r.Header.Del("X-Sam-Biscuit")
+
svc, ok := n.services.Get(serviceName)
if !ok {
logger.Errorf("[Ingress] Service not found: %s", serviceName)
diff --git a/cmd/sam-node/proxy_test.go b/cmd/sam-node/proxy_test.go
index 00e2aa8e..2d4ad559 100644
--- a/cmd/sam-node/proxy_test.go
+++ b/cmd/sam-node/proxy_test.go
@@ -4,6 +4,8 @@ import (
"bufio"
"bytes"
"context"
+ "crypto/ed25519"
+ "crypto/rand"
"fmt"
"io"
"net/http"
@@ -101,6 +103,18 @@ func TestDatapathIntegration(t *testing.T) {
}
}()
+ // Setup identity for Node B (the caller proxy) and trust it on Node A
+ 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()
+
// Connect Node B to Node A directly
err = nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()})
if err != nil {
@@ -217,6 +231,148 @@ func TestDatapathIntegration(t *testing.T) {
}
}
+func TestDatapathIntegration_Unauthenticated(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)
+ }
+ }()
+
+ // NOTE: We do NOT setup an identity for Node B (caller).
+ // This means the Egress Proxy will not inject an X-Sam-Biscuit header,
+ // and the request should be rejected by Node A's ingress server.
+
+ // Connect Node B to Node A directly
+ err = nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ dummyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"status":"success"}`))
+ }))
+ 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},
+ })
+
+ targetURL, _ := url.Parse(dummyServer.URL)
+ nodeA.services.insertService(&testService{
+ info: serviceInfo,
+ handler: httputil.NewSingleHostReverseProxy(targetURL),
+ })
+
+ nodeB.BoundHTTPAddr = "127.0.0.1:0"
+
+ proxyHandler := createEgressProxy(nodeB)
+ proxyServer := httptest.NewServer(proxyHandler)
+ defer proxyServer.Close()
+
+ url := fmt.Sprintf("%s/sam/%s/mcp/%s/api/v1/test", proxyServer.URL, nodeA.Host.ID().String(), serviceName)
+
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ client := &http.Client{}
+
+ var resp *http.Response
+ for i := 0; i < 3; i++ {
+ resp, err = client.Do(req)
+ if err == nil {
+ break
+ }
+ t.Logf("Attempt %d failed: %v", i+1, err)
+ time.Sleep(1 * time.Second)
+ }
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ _ = resp.Body.Close()
+ }()
+
+ // ASSERTION: Should be service unavailable because the local node has no identity to send
+ if resp.StatusCode != http.StatusServiceUnavailable {
+ t.Fatalf("Expected status ServiceUnavailable (503), got %d", resp.StatusCode)
+ }
+}
+
func TestStdioDatapathIntegration(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -280,6 +436,18 @@ func TestStdioDatapathIntegration(t *testing.T) {
}
defer func() { _ = nodeB.Host.Close() }()
+ // Setup identity for Node B (the caller proxy) and trust it on Node A
+ 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()
+
// Connect Node B to Node A directly
err = nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()})
if err != nil {
diff --git a/cmd/sam-node/service.go b/cmd/sam-node/service.go
index c1e996cf..7b21ceb3 100644
--- a/cmd/sam-node/service.go
+++ b/cmd/sam-node/service.go
@@ -152,7 +152,6 @@ func buildRegisterRequest(sCfg api.ServiceConfig) (*api.RegisterServiceRequest,
return req, nil
}
-
// serviceKeyToCID hashes "sam:service[:part]..." into a DHT rendezvous CID.
func serviceKeyToCID(parts ...string) (cid.Cid, error) {
srvKey := strings.Join(append([]string{"sam:service"}, parts...), ":")
diff --git a/cmd/sam-node/sidecar.go b/cmd/sam-node/sidecar.go
index af7a70ec..a9e6b610 100644
--- a/cmd/sam-node/sidecar.go
+++ b/cmd/sam-node/sidecar.go
@@ -18,6 +18,7 @@ import (
"context"
"crypto/tls"
"crypto/x509"
+ "encoding/base64"
"encoding/json"
"fmt"
"io"
@@ -430,5 +431,21 @@ func createEgressProxy(node *SamNode) http.Handler {
Transport: transport,
}
- return proxy
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if node == nil {
+ logger.Errorf("[Proxy] Node is nil, rejecting egress request.")
+ http.Error(w, "Service Unavailable: Node Not Initialized", http.StatusServiceUnavailable)
+ return
+ }
+ biscuitBytes := node.GetIdentity()
+ if biscuitBytes == nil {
+ logger.Errorf("[Proxy] Failed to load node identity for egress request, rejecting.")
+ http.Error(w, "Service Unavailable: Missing Node Identity", http.StatusServiceUnavailable)
+ return
+ }
+
+ r.Header.Del("Authorization")
+ r.Header.Set("X-Sam-Biscuit", base64.StdEncoding.EncodeToString(biscuitBytes))
+ proxy.ServeHTTP(w, r)
+ })
}
diff --git a/development/examples/calc-mcp/sam-node-config.yaml b/development/examples/calc-mcp/sam-node-config.yaml
index c707b183..a06e55de 100644
--- a/development/examples/calc-mcp/sam-node-config.yaml
+++ b/development/examples/calc-mcp/sam-node-config.yaml
@@ -3,7 +3,6 @@ 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 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.yaml
index 79f043b6..bad855af 100644
--- a/development/examples/code-reviewer-mcp/sam-node-config.yaml
+++ b/development/examples/code-reviewer-mcp/sam-node-config.yaml
@@ -1,7 +1,6 @@
version: "v1alpha1"
attenuation:
- policies:
- - 'allow if service("system", "/sam/mcp/1.0.0"), node($peer)'
+ policies: []
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.yaml
index e48372f7..af7e33f7 100644
--- a/development/examples/everything-mcp/sam-node-config.yaml
+++ b/development/examples/everything-mcp/sam-node-config.yaml
@@ -2,7 +2,7 @@ version: "v1alpha1"
attenuation:
policies:
- 'allow if service("mcp", "everything");'
- - 'allow if service("system", "/sam/catalog");'
+ - '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.yaml
index 9b95e9b3..4b52f7b2 100644
--- a/development/examples/greeter-mcp/sam-node-config.yaml
+++ b/development/examples/greeter-mcp/sam-node-config.yaml
@@ -1,7 +1,6 @@
version: "v1alpha1"
attenuation:
policies:
- - 'allow if service("mcp", "greeter"), node($peer)'
services:
- type: "mcp"
name: "greeter"
diff --git a/development/kind/10-hub.yaml b/development/kind/10-hub.yaml
index 2565e410..b8bf9efe 100644
--- a/development/kind/10-hub.yaml
+++ b/development/kind/10-hub.yaml
@@ -97,6 +97,6 @@ data:
roles:
sam-admin:
allowed_services:
- - "*"
+ - "*:*"
allowed_targets:
- - "*"
+ - "*:*"
diff --git a/development/kind/node.template.yaml b/development/kind/node.template.yaml
index b6fe40be..ef29f690 100644
--- a/development/kind/node.template.yaml
+++ b/development/kind/node.template.yaml
@@ -33,7 +33,6 @@ spec:
- "--api-token=devtoken"
- "--bind-addr=0.0.0.0:8080"
- "--discovery-interval=200ms"
- - "--trust-hub-rbac"
${CONFIG_ARG}
ports:
- { containerPort: 8080, name: mcp, protocol: TCP }
diff --git a/development/kind/test-mesh-e2e.sh b/development/kind/test-mesh-e2e.sh
index 0c572186..828a4a02 100755
--- a/development/kind/test-mesh-e2e.sh
+++ b/development/kind/test-mesh-e2e.sh
@@ -49,11 +49,11 @@ for i in $(seq 1 90); do
echo "discover attempt $i: $tools"
peer="$(printf '%s' "$tools" \
- | jq -r '.[]? | select(.tool_name=="mcp:calculator.add") | .peer_id' 2>/dev/null \
+ | jq -r '.[]? | select(.tool_name=="mcp:calculator/add") | .peer_id' 2>/dev/null \
| head -n1 || true)"
if [ -n "$peer" ]; then
- echo "mcp:calculator.add discovered on peer: $peer (attempt $i)"
+ echo "mcp:calculator/add discovered on peer: $peer (attempt $i)"
break
fi
@@ -75,12 +75,12 @@ done
exit 1
}
-echo "== call mcp:calculator.add(2,3) =="
+echo "== call mcp:calculator/add(2,3) =="
result=$(mcp -tool call_remote_tool \
- -args "{\"peer_id\":\"$peer\",\"tool_name\":\"mcp:calculator.add\",\"arguments\":{\"a\":2,\"b\":3}}")
+ -args "{\"peer_id\":\"$peer\",\"tool_name\":\"mcp:calculator/add\",\"arguments\":{\"a\":2,\"b\":3}}")
echo "result: $result"
if [[ "$result" != *"5"* ]]; then
- echo "calculator.add did not return 5"
+ echo "calculator/add did not return 5"
exit 1
fi
-echo "OK: calculator.add(2,3) == 5"
+echo "OK: calculator/add(2,3) == 5"
diff --git a/site/content/docs/development/policy.md b/site/content/docs/development/policy.md
index 9e601aae..dfa597fc 100644
--- a/site/content/docs/development/policy.md
+++ b/site/content/docs/development/policy.md
@@ -67,15 +67,13 @@ allow if group("engineering");
## 2. Hub Policy Schema (`policies.yaml`)
Admins define central permissions by mapping OIDC roles to specific capabilities.
-* **`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>`). *Note: These are evaluated exclusively by the destination node (see Section 3.1).*
+* **`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>`). *Note: These are evaluated dynamically at the destination node using its own identity (see Section 3.1).*
* **`allowed_services`**: Defines the application-level tools or endpoints a user can access. Services use a strict `type:name` convention (e.g., `mcp:db-agent` or `inference:openrouter`).
- * **Default Namespace (`system`)**: If a service string does not contain a `:` separator (e.g., `my-tool`), it automatically defaults to the `system` type (parsed as `system:my-tool`).
- * **Wildcards**: Because `allowed_services` translates to the two-argument Biscuit fact `service($type, $name)`, SAM natively supports wildcards. You can grant access to an entire type via `type:*` (e.g., `mcp:*`), or grant global access to everything via `*`.
- * **MCP Namespace Convention**: The `mcp:` prefix (`api.MCPServicePrefix`) is the explicit convention for all Model Context Protocol targets. When remote nodes query local nodes for tool catalogs, if the local service is an MCP server and is missing the `mcp:` prefix in its name, the proxy layer will automatically prepend `mcp:` prior to enforcing the authorization policy to prevent it from accidentally falling back into the `system:` namespace.
- * **Custom Namespaces & Authorization Boundaries**: The system allows arbitrary prefixes (e.g., `plugin:my-tool`). The string is strictly split at the *first* colon. The left side (`plugin`) becomes the namespace used exclusively for Biscuit authorization checks (`service("plugin", "my-tool")`). If an administrator registers a service as `system:my-tool`, they are intentionally placing it behind the strict `system` authorization policy. Users cannot bypass security by adding prefixes—they only restrict access further.
- * **Service Routing Fallback**: When authorizing a connection, the node first looks up the stripped target name (`my-tool`). If it fails, it explicitly falls back to the full original target string (`system:my-tool`). This allows users to register custom namespaced tools (e.g., `Name: "plugin:linter"`) and route to them securely while still strictly enforcing the `plugin` authorization policy.
+ * **Strict Namespaces**: There are no implicit fallbacks. `system:...` is used for internal services, `mcp:...` for node services, `inference:...` for AI models, etc. Service names must be valid domain labels (e.g. `value1.value2.value3`).
+ * **Wildcards**: SAM natively supports prefix and suffix wildcards to build complex policies. The hub generates specific facts like `granted_service_exact($type, $name)`, `granted_service_prefix($type, $prefix)`, `granted_service_suffix($type, $suffix)`, `granted_service_all_in_type($type)`, or `granted_service_all_types()`. You can grant access to an entire type via `mcp:*`, allow prefix matching like `mcp:dev-*`, suffix matching like `mcp:*-prod`, or global access to everything via `*`.
+ * **MCP Namespace Convention**: The `mcp:` prefix (`api.MCPServicePrefix`) is the explicit convention for all Model Context Protocol targets. When remote nodes query local nodes for tool catalogs, if the local service is an MCP server, the proxy layer strictly enforces the authorization policy against the `mcp:` prefix.
> [!NOTE]
-> The `*` global wildcard is a special case. It maps exactly to type `*` and name `*`. It does *not* default to the `system` type.
+> The `*` global wildcard is a special case. It grants `granted_service_all_types()` fact, allowing the caller to invoke any tool regardless of its namespace or name.
```yaml
version: "v1alpha1"
@@ -108,32 +106,22 @@ attenuation:
```
### 3.1 Evaluating `allowed_targets` at the Destination
-The SAM network operates on a Zero Trust architecture. The origin node does not police its own traffic. When the Hub injects an `allowed_targets` permission (like `- "group:backend-nodes"`) into the token, it creates a `network_target("group:backend-nodes")` capability fact.
+The SAM network operates on a Zero Trust architecture. The origin node does not police its own traffic. When the Hub injects `allowed_targets` permissions (like `- "group:backend-nodes"`) into the token, it creates `granted_target_group("backend-nodes")` capability facts and seals the token with a `target_restricted()` fact. If no targets are specified, the Hub mints a `target_unrestricted()` fact.
-It is up to the **destination node** to mathematically prove that it is the intended target. To do this, the destination node injects its own identity into its local config using `rules`, and enforces the match using `policies`:
+It is up to the **destination node** to mathematically prove that it is the intended target. To do this, the destination node automatically injects its own identity into the local authorization context as target facts (e.g., `target_fact("group", "backend-nodes")`).
-```yaml
-version: "v1alpha1"
-attenuation:
- rules:
- # 1. The destination defines what it "is" locally
- - 'target("group:backend-nodes") <- true;'
- - 'target("email:[email protected]") <- true;'
- policies:
- # 2. The destination strictly enforces that the token contains the matching network_target
- - 'allow if target($t), network_target($t);'
+The destination node enforces this via a baseline check:
+```datalog
+check if allow_network_target($fact, $val) or target_unrestricted();
```
-If the calling node's token does not contain a `network_target` fact that exactly matches one of the destination's `target` rules, the destination node's authorization middleware will reject the connection.
+Because the target logic is baked directly into the node's middleware, you don't need to write manual Datalog rules for it. The node dynamically deduces `allow_network_target($fact, $val)` if any of its injected `target_fact`s match the `granted_target_*` facts presented in the incoming token.
+
+If the token is `target_restricted()` and the destination node does not possess an identity matching the granted targets, the connection is instantly rejected.
-> [!WARNING]
-> **What happens if a node does not set any local target policies?**
-> If a node does not define any `target` rules or `allow if target($t), network_target($t);` policies in its local configuration, it defaults to relying strictly on the Hub's **Baseline Security Rules** (Section 4). In this default state, the node is "open" to *any* peer in the mesh, provided the peer possesses the explicit `allow_service` permissions required to execute the tool. In other words, `allowed_targets` is an *opt-in* mechanism for the destination to attenuate traffic further; without it, the destination trusts the Hub's `allowed_services` whitelist implicitly.
->
-> **Does this mean the mesh is insecure by default?**
-> No. By default, `sam-hub` operates in a **Default-Deny** state. If a user is not explicitly mapped to a role in the Hub's `policies.yaml`, or if their role does not explicitly grant an `allowed_service` capability, their token will contain no service permissions. Because the destination node's Baseline Rules require an explicit `allow_service` fact to execute any tool, the connection will be instantly denied (even if no targets are defined).
->
-> It is entirely a **Mesh Operator decision** how the mesh behaves. Operators can choose to rely solely on service whitelists (granting broad mesh-wide execution), or strictly partition the network into isolated zones by injecting `allowed_targets` and enforcing them locally on the nodes.
+> [!NOTE]
+> **Policy Evaluation Precedence**
+> Local policies defined in `sam-node-config.yaml` are evaluated **before** baseline rules. This means local administrators can write rules that explicitly `deny` access based on custom logic, effectively overriding any broad access granted by the Hub's baseline policies. Local policies can only attenuate (restrict) access, never expand it beyond what the Hub allowed.
## 4. Node Baseline Security Rules
@@ -145,12 +133,12 @@ Every request must prove that the libp2p cryptographic peer ID of the connection
check if client_peer_id($id), connection_peer_id($id);
```
-### 4.2 The Catalog Service (`/sam/catalog`)
-To allow remote peers to discover tools and query connectivity, each node hosts a built-in catalog service at the special target `/sam/catalog`. This service exposes local metadata tools (e.g. `list_local_services`, `get_mesh_info`).
+### 4.2 The Catalog Service (`sam.catalog`)
+To allow remote peers to discover tools and query connectivity, each node hosts a built-in catalog service at the special target `sam.catalog`. This service exposes local metadata tools (e.g. `list_local_services`, `get_mesh_info`).
To 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 service("system", "/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/openrouter.md b/site/content/docs/integrations/openrouter.md
index ea6b971b..558c77a5 100644
--- a/site/content/docs/integrations/openrouter.md
+++ b/site/content/docs/integrations/openrouter.md
@@ -53,24 +53,19 @@ By default, services on your node are completely locked down. To allow agents in
The service format for an inference service is always `inference:<service-name>`.
-To allow **any** authenticated mesh agent to use the service:
+To allow **any** authenticated mesh agent to use the service, no local attenuation policies are necessary—the Hub will manage access centrally based on the node's assigned roles.
+
+If you only want to allow specific identities or groups (e.g., agents belonging to the "research" group) and want to enforce this restriction locally at the node (regardless of Hub configuration), you can add a local check based on the cryptographic facts injected by the Hub:
```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");'
+ checks:
+ - 'check if 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.
+When deploying (for instance, via Kubernetes), you deploy both containers in the same Pod so they can communicate over `localhost`.
```yaml
containers:
@@ -88,7 +83,6 @@ When deploying (for instance, via Kubernetes), you deploy both containers in the
args:
- "run"
- "--config=/etc/sam/sam-node.yaml"
- - "--trust-hub-rbac"
# ... (other required arguments like --jwt-path)
```
diff --git a/site/content/docs/user/hub-configuration.md b/site/content/docs/user/hub-configuration.md
index 9dfa81e9..d4f80334 100644
--- a/site/content/docs/user/hub-configuration.md
+++ b/site/content/docs/user/hub-configuration.md
@@ -46,7 +46,7 @@ The policy defines what endpoints and services agents are permitted to use:
* **`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.
+> SAM natively supports prefix and suffix wildcards in `allowed_services`. You can grant access to an entire type via `mcp:*`, allow prefix matching like `mcp:dev-*`, suffix matching like `mcp:*-prod`, or grant global access to everything via `*`.
### Example Policy Mapping
Create a `policies.yaml` file in the directory where you run `sam-hub`:
diff --git a/site/content/docs/user/kubernetes-deployment.md b/site/content/docs/user/kubernetes-deployment.md
index d64e0795..592e9ef7 100644
--- a/site/content/docs/user/kubernetes-deployment.md
+++ b/site/content/docs/user/kubernetes-deployment.md
@@ -116,9 +116,8 @@ data:
roles:
node-role:
mcp:
- allowed_servers:
- - "/sam/mcp/1.0.0"
- - "/sam/catalog"
+ allowed_services:
+ - "system:sam.catalog"
```
```bash
kubectl apply -f policies-configmap.yaml
@@ -222,9 +221,9 @@ data:
command: ["echo", "placeholder db-agent service"]
attenuation:
rules:
- - 'target("group:backend-nodes") <- true;'
+ - 'department("analytics") <- true;'
policies:
- - 'allow if target($t), network_target($t);'
+ - 'deny if user("untrusted_user");'
```
### 3. Deploy Nodes using Token Projection
@@ -246,7 +245,6 @@ spec:
image: ghcr.io/google/sam-node:latest
args:
- "run"
- - "--trust-hub-rbac"
- "--config=/etc/sam/sam-node.yaml"
- "--hub=http://sam-hub.sam.svc.cluster.local:9090"
- "--jwt-path=/var/run/secrets/tokens/sam-token"
diff --git a/site/content/docs/user/node-configuration.md b/site/content/docs/user/node-configuration.md
index 25197188..21bbf115 100644
--- a/site/content/docs/user/node-configuration.md
+++ b/site/content/docs/user/node-configuration.md
@@ -40,19 +40,18 @@ services:
# 2. Define Local Security Identity (Zero Trust)
attenuation:
rules:
- # Explicitly define this node's identity in the mesh
- - 'target("group:backend-nodes") <- true;'
- - 'target("email:[email protected]") <- true;'
+ # Example: Inject custom Datalog facts asserting local node state
+ - 'time(2026-06-30T00:00:00Z) <- true;'
policies:
- # Enforce that the incoming caller's token contains a matching network_target
- - 'allow if target($t), network_target($t);'
+ # Example: Custom local deny rule restricting access from untrusted users
+ - 'deny if user("untrusted_sub_id");'
```
---
## 2. Defining Local Services
-The `services` array allows you to register endpoints that remote peers in the SAM Network can discover and execute (provided they possess the proper `allow_service` credentials issued by the Hub).
+The `services` array allows you to register endpoints that remote peers in the SAM Network can discover and execute (provided they possess the proper `granted_service_*` credentials issued by the Hub).
| Property | Description |
| :--- | :--- |
@@ -67,13 +66,14 @@ The `services` array allows you to register endpoints that remote peers in the S
## 3. Defining Local Security (Target Attenuation)
-In a Zero Trust architecture, the destination node is entirely responsible for verifying that it is the intended recipient of an incoming request.
+In a Zero Trust architecture, the destination node is entirely responsible for verifying that it is the intended recipient of an incoming request.
-While the Hub injects routing boundaries (like `network_target("group:backend-nodes")`) into the caller's token, the destination node will **ignore these targets by default** (relying solely on the Hub's service whitelist) unless you explicitly configure the node's local identity.
+While the Hub limits token capabilities based on target restrictions (e.g., `target_restricted()` or `target_unrestricted()`), the destination node evaluates these dynamically. The node automatically resolves its local identity context based on its configuration, generating facts internally (such as `allow_network_target($fact, $value)`).
-If your mesh operator utilizes `allowed_targets` to partition the network, your node **must** define its identity in the `attenuation` block to accept traffic:
+If the caller's token has target restrictions, the connection will only be allowed if the token's `granted_target_*` facts match the dynamically injected identity of the node. You do **not** need to write manual Datalog rules to enforce this mechanism; it is baked directly into the node middleware via baseline policies.
-1. **`rules`**: Inject Datalog facts asserting the node's identity (e.g. `target("group:backend-nodes") <- true;`).
-2. **`policies`**: Add a local policy strictly enforcing that the incoming token possesses the matching capability (e.g. `allow if target($t), network_target($t);`).
+### Local Custom Policies
+You can further restrict access using the `attenuation` block. Local policies defined here are evaluated **before** the baseline rules. This means local administrators can write custom rules that explicitly `deny` access based on custom logic, overriding broad access granted by the Hub.
-If a calling node attempts to connect and its token does not contain the required `network_target` matching your local `target` rules, the connection will be cryptographically rejected.
+1. **`rules`**: Inject custom Datalog facts asserting local node state (e.g., `time($time)`).
+2. **`policies`**: Add local restrictions (e.g., `deny if user("banned_user");`).
diff --git a/tests/e2e/docker/calc-mcp/sam-node-config.yaml b/tests/e2e/docker/calc-mcp/sam-node-config.yaml
index b01a5ac4..60744a5d 100644
--- a/tests/e2e/docker/calc-mcp/sam-node-config.yaml
+++ b/tests/e2e/docker/calc-mcp/sam-node-config.yaml
@@ -3,7 +3,6 @@ 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 service($type, $name), node($peer)'
services:
- type: "mcp"
name: "calculator"
diff --git a/tests/e2e/fixtures/default-policy.yaml b/tests/e2e/fixtures/default-policy.yaml
new file mode 100644
index 00000000..0050fe06
--- /dev/null
+++ b/tests/e2e/fixtures/default-policy.yaml
@@ -0,0 +1,10 @@
+version: v1alpha1
+bindings:
+ - group: "*"
+ role: admin
+roles:
+ admin:
+ allowed_services:
+ - "*:*"
+ allowed_targets:
+ - "*:*"
diff --git a/tests/e2e/fixtures/sam-hub.yaml b/tests/e2e/fixtures/sam-hub.yaml
index 70ee5787..6df6e0d7 100644
--- a/tests/e2e/fixtures/sam-hub.yaml
+++ b/tests/e2e/fixtures/sam-hub.yaml
@@ -6,6 +6,17 @@ data:
SAM_OIDC_ISSUER: "${ISSUER}"
SAM_OIDC_ID: "sam-mesh-audience"
SAM_HUB_KEY: "0000000000000000000000000000000000000000000000000000000000000000"
+ policy.yaml: |
+ version: v1alpha1
+ bindings:
+ - group: "*"
+ role: admin
+ roles:
+ admin:
+ allowed_services:
+ - "*:*"
+ allowed_targets:
+ - "*:*"
---
apiVersion: v1
kind: Service
@@ -46,19 +57,6 @@ spec:
containers:
- name: sam-hub
image: sam-hub:local
- args:
- - "--issuer"
- - "${ISSUER}"
- - "--key"
- - "0000000000000000000000000000000000000000000000000000000000000000"
- - "--insecure-skip-tls-verify"
- - "--listen=/ip4/0.0.0.0/tcp/4501"
- - "--listen=/ip4/0.0.0.0/udp/4501/quic-v1"
- - "--external-multiaddr=/dns4/sam-hub.default.svc.cluster.local/tcp/4501"
- - "--external-multiaddr=/dns4/sam-hub.default.svc.cluster.local/udp/4501/quic-v1"
- - "--external-multiaddr=http://sam-hub-0.sam-hub.default.svc.cluster.local:9090"
- - "--external-multiaddr=http://sam-hub-1.sam-hub.default.svc.cluster.local:9090"
- - "--allow-loopback"
envFrom:
- configMapRef:
name: sam-hub-config
@@ -72,3 +70,24 @@ spec:
- containerPort: 4501
hostPort: 4501
protocol: UDP
+ args:
+ - "--issuer"
+ - "${ISSUER}"
+ - "--key"
+ - "0000000000000000000000000000000000000000000000000000000000000000"
+ - "--insecure-skip-tls-verify"
+ - "--policy-file=/etc/sam/policy.yaml"
+ - "--listen=/ip4/0.0.0.0/tcp/4501"
+ - "--listen=/ip4/0.0.0.0/udp/4501/quic-v1"
+ - "--external-multiaddr=/dns4/sam-hub.default.svc.cluster.local/tcp/4501"
+ - "--external-multiaddr=/dns4/sam-hub.default.svc.cluster.local/udp/4501/quic-v1"
+ - "--external-multiaddr=http://sam-hub-0.sam-hub.default.svc.cluster.local:9090"
+ - "--external-multiaddr=http://sam-hub-1.sam-hub.default.svc.cluster.local:9090"
+ volumeMounts:
+ - name: config-volume
+ mountPath: /etc/sam/policy.yaml
+ subPath: policy.yaml
+ volumes:
+ - name: config-volume
+ configMap:
+ name: sam-hub-config
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index 6947afeb..a9669cd4 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -206,6 +206,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
}
mesh_start_hub() {
+ local config_path="${1:-tests/e2e/fixtures/default-policy.yaml}"
local name="${MESH_PREFIX}-hub"
if docker inspect -f '{{.State.Running}}' "${name}" 2>/dev/null | grep -q "true"; then
return 0
@@ -217,6 +218,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
--name "${name}" \
--network "${MESH_NETWORK}" \
--network-alias sam-hub \
+ -v "$(pwd)/${config_path}:/etc/sam/hub-config.yaml:ro" \
"sam-hub:local" \
--issuer "http://mock-oidc:18080" \
--client-id "sam-e2e" \
@@ -224,6 +226,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
--key "${key}" \
--listen "/ip4/0.0.0.0/tcp/4002" \
--external-multiaddr "/dns4/sam-hub/tcp/4002" \
+ --policy-file "/etc/sam/hub-config.yaml" \
--mesh "e2e-mesh" >/dev/null
MESH_CONTAINERS+=("${name}")
diff --git a/tests/e2e/watch.bats b/tests/e2e/watch.bats
index 4c4fbef1..3f29ff45 100644
--- a/tests/e2e/watch.bats
+++ b/tests/e2e/watch.bats
@@ -19,7 +19,7 @@ teardown() {
rm -rf "$TEST_TMPDIR"
}
-@test "sam-node run --trust-hub-rbac with stored identity fails if hub is unreachable" {
+@test "sam-node run 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 6eb8d897..a8f0c317 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", "--trust-hub-rbac", "--help")
+ stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, nil, "", nodeBin, "run", "--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 30344fb1..9fe87fe8 100644
--- a/tests/integration/catalog_test.go
+++ b/tests/integration/catalog_test.go
@@ -20,7 +20,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", "--trust-hub-rbac", "--hub", hubAddr, "--jwt", "test-jwt", "--bind-addr", "127.0.0.1:0", "--api-token", "test-token", "--allow-loopback"}, args...)
+ allArgs := append([]string{"run", "--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 52e94d1d..d18685dc 100644
--- a/tests/integration/cuj_test.go
+++ b/tests/integration/cuj_test.go
@@ -39,8 +39,7 @@ func TestSamNodeRunWithManualTokenStarts(t *testing.T) {
env,
"",
nodeBin,
- "run", "--trust-hub-rbac",
- "--hub", hubAddr,
+ "run", "--hub", hubAddr,
"--jwt", "test-jwt",
"--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
"--listen", "/ip4/127.0.0.1/tcp/0",
diff --git a/tests/integration/failover_test.go b/tests/integration/failover_test.go
index 3b0e2965..388f5463 100644
--- a/tests/integration/failover_test.go
+++ b/tests/integration/failover_test.go
@@ -134,8 +134,7 @@ roles: {}
"HOME="+nodeHome,
"XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config"),
)
- cmdNode := exec.Command(nodeBin, "run", "--trust-hub-rbac",
- "--hub", lb.URL,
+ cmdNode := exec.Command(nodeBin, "run", "--hub", lb.URL,
"--listen", "/ip4/127.0.0.1/tcp/0",
"--jwt-path", jwtPath,
"--bind-addr", "127.0.0.1:0",
diff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.go
index 8b36f0ff..9730853e 100644
--- a/tests/integration/fallback_test.go
+++ b/tests/integration/fallback_test.go
@@ -197,7 +197,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {
mu.Unlock()
// Step 3: Start sam-node run
- runCmd := exec.Command(nodeBin, "run", "--trust-hub-rbac", "--listen", "/ip4/127.0.0.1/tcp/0", "--bind-addr", "127.0.0.1:0")
+ runCmd := exec.Command(nodeBin, "run", "--listen", "/ip4/127.0.0.1/tcp/0", "--bind-addr", "127.0.0.1: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 9eef8cfa..b153deee 100644
--- a/tests/integration/federation_test.go
+++ b/tests/integration/federation_test.go
@@ -114,8 +114,7 @@ roles:
// Node A connects to Hub A
apiPortA := getFreePort(t)
- nodeACmd := exec.Command(nodeBin, "run", "--trust-hub-rbac",
- "--hub", fmt.Sprintf("http://127.0.0.1:%d", portA),
+ nodeACmd := exec.Command(nodeBin, "run", "--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),
"--api-token", "tokenA",
@@ -136,8 +135,7 @@ roles:
// Node B connects to Hub B
apiPortB := getFreePort(t)
- nodeBCmd := exec.Command(nodeBin, "run", "--trust-hub-rbac",
- "--hub", fmt.Sprintf("http://127.0.0.1:%d", portB),
+ nodeBCmd := exec.Command(nodeBin, "run", "--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),
"--api-token", "tokenB",
diff --git a/tests/integration/login_test.go b/tests/integration/login_test.go
index f9cad953..1c085917 100644
--- a/tests/integration/login_test.go
+++ b/tests/integration/login_test.go
@@ -102,8 +102,7 @@ func TestSamNodeJoin(t *testing.T) {
env,
"",
nodeBin,
- "run", "--trust-hub-rbac",
- "--hub", hubAddr,
+ "run", "--hub", hubAddr,
"--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/mcp_local_tools_test.go b/tests/integration/mcp_local_tools_test.go
index fcde6ccd..a1473f1f 100644
--- a/tests/integration/mcp_local_tools_test.go
+++ b/tests/integration/mcp_local_tools_test.go
@@ -80,7 +80,6 @@ roles: {}
"--bind-addr", "127.0.0.1:0",
"--api-token", apiToken,
"--jwt", jwtTokenStr,
- "--trust-hub-rbac",
)
// Start Node B
@@ -91,7 +90,6 @@ roles: {}
"--bind-addr", "127.0.0.1:0",
"--api-token", apiToken,
"--jwt", jwtTokenStr,
- "--trust-hub-rbac",
)
// Resolve actual MCP address from log
diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.go
index 1c1d77c7..9dc12465 100644
--- a/tests/integration/minimal_helpers_test.go
+++ b/tests/integration/minimal_helpers_test.go
@@ -26,11 +26,14 @@ import (
"testing"
"time"
+ "crypto/ed25519"
+ "crypto/rand"
"io"
"net/http"
"net/http/httptest"
"net/url"
+ "github.com/biscuit-auth/biscuit-go/v2"
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
@@ -231,6 +234,11 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {
}
// Start HTTP server for enrollment
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("Failed to generate hub key: %v", err)
+ }
+
mux := http.NewServeMux()
mux.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -249,8 +257,8 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {
}
resp := &api.EnrollResponse{
- BiscuitToken: []byte("mock-biscuit-token"),
- HubPublicKey: []byte("mock-hub-pub-key"),
+ BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv),
+ HubPublicKey: pub,
HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},
}
data, err := proto.Marshal(resp)
@@ -303,6 +311,11 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, st
}
// Start HTTP server for enrollment and info
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("Failed to generate hub key: %v", err)
+ }
+
mux := http.NewServeMux()
mux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
@@ -340,8 +353,8 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, st
}
resp := &api.EnrollResponse{
- BiscuitToken: []byte("mock-biscuit-token"),
- HubPublicKey: []byte("mock-hub-pub-key"),
+ BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv),
+ HubPublicKey: pub,
HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},
}
data, err := proto.Marshal(resp)
@@ -364,3 +377,41 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, st
return h.ID(), httpServer.URL
}
+
+func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKey) []byte {
+ builder := biscuit.NewBuilder(priv)
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
+
+ err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "node",
+ IDs: []biscuit.Term{biscuit.String(peerID)},
+ }})
+ if err != nil {
+ t.Fatalf("failed to add node fact: %v", err)
+ }
+
+ err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "client_peer_id",
+ IDs: []biscuit.Term{biscuit.String(peerID)},
+ }})
+ if err != nil {
+ t.Fatalf("failed to add client_peer_id fact: %v", err)
+ }
+
+ err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "granted_service_all_types",
+ }})
+ if err != nil {
+ t.Fatalf("failed to add granted_service_all_types fact: %v", err)
+ }
+
+ b, err := builder.Build()
+ if err != nil {
+ t.Fatalf("failed to build biscuit: %v", err)
+ }
+ serialized, err := b.Serialize()
+ if err != nil {
+ t.Fatalf("failed to serialize biscuit: %v", err)
+ }
+ return serialized
+}
diff --git a/tests/integration/p2p_test.go b/tests/integration/p2p_test.go
index cfb30112..ac8a89a8 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", "--trust-hub-rbac")
+ stdout, stderr, err := runCommand(t, repoRoot(t), 10*time.Second, append(os.Environ(), env...), "", nodeBin, "run")
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/policy_permutations_test.go b/tests/integration/policy_permutations_test.go
index 9067aeba..bbdbc999 100644
--- a/tests/integration/policy_permutations_test.go
+++ b/tests/integration/policy_permutations_test.go
@@ -84,7 +84,7 @@ roles:
allowed_targets: ["user:bob-subject"]
role-email:
allowed_services: ["mcp:test-email"]
- allowed_targets: ["node:nodeB"]
+ allowed_targets: ["email:[email protected]"]
role-group:
allowed_services: ["mcp:test-group"]
allowed_targets: ["group:compute"]
@@ -93,10 +93,10 @@ roles:
allowed_targets: ["group:backend"]
role-direct:
allowed_services: ["mcp:test-role"]
- allowed_targets: ["node:nodeB"]
+ allowed_targets: ["group:compute"]
admin:
- allowed_services: ["*"]
- allowed_targets: ["*"]
+ allowed_services: ["*:*"]
+ allowed_targets: ["*:*"]
bindings:
- role: role-user
@@ -139,28 +139,21 @@ bindings:
// 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"
+ name: "test-user"
command: ["echo", "test-user"]
- type: "mcp"
- name: "mcp:test-email"
+ name: "test-email"
command: ["echo", "test-email"]
- type: "mcp"
- name: "mcp:test-group"
+ name: "test-group"
command: ["echo", "test-group"]
- type: "mcp"
- name: "mcp:test-role"
+ name: "test-role"
command: ["echo", "test-role"]
- type: "mcp"
- name: "mcp:test-node"
+ name: "test-node"
command: ["echo", "test-node"]
`
if err := os.WriteFile(nodeBPolicyFile, []byte(nodeBPolicyYAML), 0644); err != nil {
@@ -176,10 +169,13 @@ services:
"--data-dir", homeB,
"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),
"--api-token", apiTokenB,
- "--jwt", mintToken(map[string]interface{}{"sub": "nodeB"}),
+ "--jwt", mintToken(map[string]interface{}{
+ "sub": "bob-subject",
+ "email": "[email protected]",
+ "groups": []string{"compute", "backend"},
+ }),
"--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,
)
@@ -264,7 +260,6 @@ services:
"--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",
)
if err := os.MkdirAll(homeA, 0755); err != nil {
@@ -294,7 +289,7 @@ services:
// 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",
+ "tool_name": tt.targetSvc + "/test_tool",
"arguments": map[string]any{},
})
diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.go
index 1ac8eddc..56afff77 100644
--- a/tests/integration/proxy_test.go
+++ b/tests/integration/proxy_test.go
@@ -76,8 +76,7 @@ func TestSamNodeRunWithStoredIdentity(t *testing.T) {
env,
"",
nodeBin,
- "run", "--trust-hub-rbac",
- "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
+ "run", "--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",
"--api-token", "dummy-token",
diff --git a/tests/integration/pubsub_test.go b/tests/integration/pubsub_test.go
index 5f8373b1..f358cf28 100644
--- a/tests/integration/pubsub_test.go
+++ b/tests/integration/pubsub_test.go
@@ -44,7 +44,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", "--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", "test-token", "--allow-loopback")
+ 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", "test-token", "--allow-loopback")
cmd1.Env = env1
logFile1, err := os.Create(filepath.Join(tmpHome1, "node1.log"))
if err != nil {
@@ -59,7 +59,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", "--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", "test-token", "--allow-loopback")
+ 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", "test-token", "--allow-loopback")
cmd2.Env = env2
logFile2, err := os.Create(filepath.Join(tmpHome2, "node2.log"))
if err != nil {