Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
api: limit an agent claim to the namespaces a node was granted
Antonio Ojea70ef74474301
diff --git a/api/agent.go b/api/agent.goindex 20125996..1b79b60e 100644--- a/api/agent.go+++ b/api/agent.go@@ -116,3 +116,52 @@ func AgentMember(id string) (string, error) {}return FactAgent + ":" + id, nil}++// ValidateAgentPattern checks one entry of a role's allowed_agents: an agent+// namespace the holder can act for. Unlike ValidateAgentID it allows the+// wildcard forms, because a namespace grant is a pattern.+//+// A bare "*" is accepted and means any agent, which lets every holder of the+// role name any agent in the mesh. Some meshes have a single tenant, so it+// stays expressible, but callers should warn when they see it.+func ValidateAgentPattern(pattern string) error {+ p := strings.TrimPrefix(pattern, FactAgent+":")+ if p == "" {+ return fmt.Errorf("agent namespace cannot be empty")+ }+ if p == "*" {+ return nil+ }+ switch {+ case strings.HasPrefix(p, "*."):+ // Validate the remaining labels, which must still be a real authority.+ return validateAgentLabels(p[2:], pattern)+ case strings.HasSuffix(p, ".*"):+ return validateAgentLabels(p[:len(p)-2], pattern)+ }+ if strings.Contains(p, "*") {+ return fmt.Errorf("agent namespace %q may only use a wildcard as a leading %q or trailing %q label", pattern, "*.", ".*")+ }+ return ValidateAgentID(p)+}++// validateAgentLabels applies the identifier's label rules to the non-wildcard+// part of a pattern, so "*.PROD.acme" or "*..acme" is rejected at config time+// rather than silently matching nothing.+func validateAgentLabels(rest, pattern string) error {+ if rest == "" {+ return fmt.Errorf("agent namespace %q must keep at least one label beside the wildcard", pattern)+ }+ if rest != strings.ToLower(rest) {+ return fmt.Errorf("agent namespace %q must be lowercase", pattern)+ }+ if strings.Contains(rest, "*") {+ return fmt.Errorf("agent namespace %q may only use one wildcard", pattern)+ }+ for _, label := range strings.Split(rest, ".") {+ if err := validateAgentLabel(label); err != nil {+ return fmt.Errorf("agent namespace %q: %w", pattern, err)+ }+ }+ return nil+}diff --git a/api/agent_namespace_test.go b/api/agent_namespace_test.gonew file mode 100644index 00000000..cfa23b76--- /dev/null+++ b/api/agent_namespace_test.go@@ -0,0 +1,123 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package api++import (+ "testing"++ "github.com/biscuit-auth/biscuit-go/v2"+)++func TestValidateAgentPattern(t *testing.T) {+ tests := []struct {+ name string+ pattern string+ wantErr bool+ }{+ {name: "exact id", pattern: "reviewer-7.prod.acme.example"},+ {name: "with the agent prefix", pattern: "agent:reviewer-7.prod.acme.example"},+ {name: "suffix wildcard", pattern: "*.prod.acme.example"},+ {name: "prefix wildcard", pattern: "acme.*"},+ {name: "bare wildcard grants everything", pattern: "*"},++ {name: "empty", pattern: "", wantErr: true},+ {name: "wildcard alone beside a dot", pattern: "*.", wantErr: true},+ {name: "wildcard in the middle", pattern: "reviewer.*.acme.example", wantErr: true},+ {name: "two wildcards", pattern: "*.acme.*", wantErr: true},+ {name: "uppercase", pattern: "*.PROD.acme.example", wantErr: true},+ {name: "empty label", pattern: "*..acme.example", wantErr: true},+ // An unqualified id has no authority, so it would collide across tenants.+ {name: "exact id with no authority", pattern: "reviewer-7", wantErr: true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := ValidateAgentPattern(tt.pattern)+ if tt.wantErr && err == nil {+ t.Errorf("ValidateAgentPattern(%q) = nil, want an error", tt.pattern)+ }+ if !tt.wantErr && err != nil {+ t.Errorf("ValidateAgentPattern(%q) = %v, want nil", tt.pattern, err)+ }+ })+ }+}++// TestBuildAgentDatalogFactKeepsTheWildcardAnchored pins the property the whole+// namespace bound rests on: a suffix grant keeps its leading dot, so+// "evil-prod.acme.example" is a different namespace from "*.prod.acme.example"+// rather than a match for it.+func TestBuildAgentDatalogFactKeepsTheWildcardAnchored(t *testing.T) {+ tests := []struct {+ pattern string+ wantName string+ wantVal string+ }{+ {"*.prod.acme.example", FactGrantedAgentSuffix, ".prod.acme.example"},+ {"acme.*", FactGrantedAgentPrefix, "acme."},+ {"reviewer-7.prod.acme.example", FactGrantedAgentExact, "reviewer-7.prod.acme.example"},+ }++ for _, tt := range tests {+ t.Run(tt.pattern, func(t *testing.T) {+ fact := BuildAgentDatalogFact(tt.pattern)+ if fact.Name != tt.wantName {+ t.Fatalf("BuildAgentDatalogFact(%q) name = %q, want %q", tt.pattern, fact.Name, tt.wantName)+ }+ got, ok := fact.IDs[0].(biscuit.String)+ if !ok || string(got) != tt.wantVal {+ t.Errorf("BuildAgentDatalogFact(%q) value = %v, want %q", tt.pattern, fact.IDs[0], tt.wantVal)+ }+ })+ }++ if got := BuildAgentDatalogFact("*").Name; got != FactGrantedAgentAll {+ t.Errorf(`BuildAgentDatalogFact("*") name = %q, want %q`, got, FactGrantedAgentAll)+ }+}++// TestBuildAgentDatalogFactsMergesExactGrants keeps a role naming many agents+// from costing one world fact each, the same way service and target grants are+// merged: the authorizer rejects worlds beyond ~1000 facts.+func TestBuildAgentDatalogFactsMergesExactGrants(t *testing.T) {+ facts := BuildAgentDatalogFacts([]string{+ "a.acme.example",+ "b.acme.example",+ "c.acme.example",+ "*.prod.acme.example",+ })++ var sets, suffixes int+ for _, f := range facts {+ switch f.Name {+ case FactGrantedAgentSet:+ sets+++ set, ok := f.IDs[0].(biscuit.Set)+ if !ok {+ t.Fatalf("granted_agent_set term is %T, want biscuit.Set", f.IDs[0])+ }+ if len(set) != 3 {+ t.Errorf("granted_agent_set holds %d ids, want 3", len(set))+ }+ case FactGrantedAgentSuffix:+ suffixes+++ default:+ t.Errorf("unexpected fact %q", f.Name)+ }+ }+ if sets != 1 || suffixes != 1 {+ t.Errorf("got %d set facts and %d suffix facts, want 1 and 1", sets, suffixes)+ }+}diff --git a/api/datalog.go b/api/datalog.goindex d10134cb..887cbc3d 100644--- a/api/datalog.go+++ b/api/datalog.go@@ -177,6 +177,42 @@ const (// Contains: biscuit.String(factName), biscuit.Set of biscuit.String(factValue)FactGrantedTargetSet = "granted_target_set"+ // The granted_agent_* family answers a different question from the+ // granted_target_* family above. A target grant says which destinations the+ // holder can reach. An agent grant says which agent identities the holder+ // can act for. A target grant must never satisfy an agent claim: being+ // allowed to call an agent is not being allowed to impersonate it.++ // FactGrantedAgentExact allows the holder to act for one exact agent id.+ // Contains: biscuit.String(agentID)+ FactGrantedAgentExact = "granted_agent_exact"++ // FactGrantedAgentSet allows the holder to act for a Set of exact agent ids,+ // so many exact grants cost one fact instead of one fact each.+ // Contains: biscuit.Set of biscuit.String(agentID)+ FactGrantedAgentSet = "granted_agent_set"++ // FactGrantedAgentPrefix allows the holder to act for any agent id starting+ // with the prefix, e.g. "reviewer.*" -> "reviewer.".+ // Contains: biscuit.String(prefix)+ FactGrantedAgentPrefix = "granted_agent_prefix"++ // FactGrantedAgentSuffix allows the holder to act for any agent id ending+ // with the suffix, e.g. "*.prod.acme.example" -> ".prod.acme.example". The+ // leading dot is kept so the wildcard lands on a label boundary and+ // "evil-acme.example" cannot match "*.acme.example".+ // Contains: biscuit.String(suffix)+ FactGrantedAgentSuffix = "granted_agent_suffix"++ // FactGrantedAgentAll allows the holder to act for any agent at all.+ // Contains: (no terms)+ FactGrantedAgentAll = "granted_agent_all"++ // FactAgentAuthorized is derived when an agent claim falls inside one of the+ // holder's granted_agent_* namespaces.+ // Contains: (no terms)+ FactAgentAuthorized = "agent_authorized"+// FactConnectionPeerID defines the actual PeerID of the remote peer making the connection.// Contains: biscuit.String(connectionPeerID)// Example Datalog: check if client_peer_id($id), connection_peer_id($id)@@ -237,6 +273,21 @@ func OIDCClaimToFact() map[string]string {return maps.Clone(oidcClaimToFact)}+// TargetFactNames returns the fact names an allowed_targets entry can use.+//+// It is derived from the same source as TargetFactRules, which is the point: a+// target naming any other fact mints a granted_target_* fact that no+// target_fact will ever match, so the grant silently denies instead of failing+// at config time. Deriving both from one place keeps them from drifting apart.+func TargetFactNames() []string {+ names := []string{FactNode}+ for _, fact := range OIDCClaimToFact() {+ names = append(names, fact)+ }+ sort.Strings(names)+ return names+}+var (// BaselinePolicies are the pre-compiled authorization policies for the node middleware.BaselinePolicies []biscuit.Policy@@ -250,6 +301,13 @@ var (// BaselineTargetCheck verifies that the target matches one of the allowed network targets.BaselineTargetCheck biscuit.Check+ // BaselineAgentRules derive agent_authorized from the holder's granted_agent_* facts.+ BaselineAgentRules []biscuit.Rule++ // BaselineAgentCheck verifies that the holder may speak for the agent it named.+ // Only added when a request carries an agent claim; see node.SamNode.Authorize.+ BaselineAgentCheck biscuit.Check+// TargetFactRules maps node and OIDC claims to target_fact datalog facts.TargetFactRules []biscuit.Rule@@ -345,6 +403,32 @@ func init() {panic(fmt.Sprintf("failed to parse target check: %v", err))}+ // 3. Agent Namespace Rules.+ // An agent claim is the calling node's word, so it is only worth what the+ // control plane attested about that node. These derive agent_authorized when+ // the claim falls inside a namespace the caller's own token grants.+ agentRuleStrs := []string{+ fmt.Sprintf(`%s() <- %s($a), %s($a)`, FactAgentAuthorized, FactAgent, FactGrantedAgentExact),+ fmt.Sprintf(`%s() <- %s($a), %s($set), $set.contains($a)`, FactAgentAuthorized, FactAgent, FactGrantedAgentSet),+ fmt.Sprintf(`%s() <- %s($a), %s($prefix), $a.starts_with($prefix)`, FactAgentAuthorized, FactAgent, FactGrantedAgentPrefix),+ fmt.Sprintf(`%s() <- %s($a), %s($suffix), $a.ends_with($suffix)`, FactAgentAuthorized, FactAgent, FactGrantedAgentSuffix),+ fmt.Sprintf(`%s() <- %s($a), %s()`, FactAgentAuthorized, FactAgent, FactGrantedAgentAll),+ }+ for i, rStr := range agentRuleStrs {+ r, err := parser.FromStringRule(rStr)+ if err != nil {+ panic(fmt.Sprintf("failed to parse baseline agent rule %d: %v", i, err))+ }+ BaselineAgentRules = append(BaselineAgentRules, r)+ }++ // A token carrying no granted_agent_* fact derives nothing, so this fails+ // closed: naming an agent you were never granted denies the request.+ BaselineAgentCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s()`, FactAgentAuthorized))+ if err != nil {+ panic(fmt.Sprintf("failed to parse agent check: %v", err))+ }+// OIDC Claims to Target Facts: Maps dynamically generated OIDC facts (like `user("alice")`)// into standard `target_fact("user", "alice")` facts for unified evaluation against network target policies.for _, val := range OIDCClaimToFact() {@@ -520,6 +604,65 @@ func isExactTarget(targetStr string) (tFact, tVal string, exact bool) {return tFact, tVal, true}+// BuildAgentDatalogFact translates one agent namespace pattern into a Datalog fact.+// Patterns are the agent id shapes of §8.8: "*", "*.suffix", "prefix.*" or an exact id.+func BuildAgentDatalogFact(pattern string) biscuit.Fact {+ pattern = strings.TrimPrefix(pattern, FactAgent+":")+ switch {+ case pattern == "*":+ return biscuit.Fact{Predicate: biscuit.Predicate{Name: FactGrantedAgentAll}}+ case strings.HasPrefix(pattern, "*."):+ return biscuit.Fact{Predicate: biscuit.Predicate{+ Name: FactGrantedAgentSuffix,+ IDs: []biscuit.Term{biscuit.String(pattern[1:])},+ }}+ case strings.HasSuffix(pattern, ".*"):+ return biscuit.Fact{Predicate: biscuit.Predicate{+ Name: FactGrantedAgentPrefix,+ IDs: []biscuit.Term{biscuit.String(pattern[:len(pattern)-1])},+ }}+ }+ return biscuit.Fact{Predicate: biscuit.Predicate{+ Name: FactGrantedAgentExact,+ IDs: []biscuit.Term{biscuit.String(pattern)},+ }}+}++// BuildAgentDatalogFacts translates a list of agent namespace patterns into a+// minimal set of facts, merging exact ids into one granted_agent_set so a role+// naming many agents still costs one fact.+func BuildAgentDatalogFacts(patterns []string) []biscuit.Fact {+ facts := make([]biscuit.Fact, 0, len(patterns))+ exact := make(map[string]bool)+ for _, p := range patterns {+ trimmed := strings.TrimPrefix(p, FactAgent+":")+ if trimmed == "" {+ continue+ }+ if trimmed == "*" || strings.HasPrefix(trimmed, "*.") || strings.HasSuffix(trimmed, ".*") {+ facts = append(facts, BuildAgentDatalogFact(trimmed))+ continue+ }+ exact[trimmed] = true+ }+ if len(exact) > 0 {+ ids := make([]string, 0, len(exact))+ for id := range exact {+ ids = append(ids, id)+ }+ sort.Strings(ids)+ bset := make(biscuit.Set, 0, len(ids))+ for _, id := range ids {+ bset = append(bset, biscuit.String(id))+ }+ facts = append(facts, biscuit.Fact{Predicate: biscuit.Predicate{+ Name: FactGrantedAgentSet,+ IDs: []biscuit.Term{bset},+ }})+ }+ return facts+}+// BuildServiceDatalogFacts translates a list of service patterns into a minimal set of Datalog facts.// Exact-match entries are grouped by service type into a single granted_service_set fact each, so// token/world fact counts stay flat regardless of how many exact services a role grants. Wildcard,diff --git a/api/sam.pb.go b/api/sam.pb.goindex 43998b02..ea636943 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -1300,8 +1300,13 @@ type PolicyRole struct {AllowedTargets []string `protobuf:"bytes,2,rep,name=allowed_targets,json=allowedTargets,proto3" json:"allowed_targets,omitempty"`AllowedServices []string `protobuf:"bytes,3,rep,name=allowed_services,json=allowedServices,proto3" json:"allowed_services,omitempty"`CustomDatalog []string `protobuf:"bytes,4,rep,name=custom_datalog,json=customDatalog,proto3" json:"custom_datalog,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // Agent namespaces the holder may speak for, e.g. "*.prod.acme.example".+ // An agent claim is the calling node's word, so it is only worth what the+ // control plane attested about that node. Distinct from allowed_targets:+ // being allowed to call an agent is not being allowed to impersonate it.+ AllowedAgents []string `protobuf:"bytes,5,rep,name=allowed_agents,json=allowedAgents,proto3" json:"allowed_agents,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *PolicyRole) Reset() {@@ -1362,6 +1367,13 @@ func (x *PolicyRole) GetCustomDatalog() []string {return nil}+func (x *PolicyRole) GetAllowedAgents() []string {+ if x != nil {+ return x.AllowedAgents+ }+ return nil+}+type PolicyBinding struct {state protoimpl.MessageState `protogen:"open.v1"`Role string `protobuf:"bytes,1,opt,name=role,proto3" json:"role,omitempty"`@@ -2749,13 +2761,14 @@ const file_api_sam_proto_rawDesc = "" +"\asuccess\x18\x01 \x01(\bR\asuccess\x12\x14\n" +"\x05error\x18\x02 \x01(\tR\x05error\x12\x1d\n" +"\n" +- "expires_at\x18\x03 \x01(\x03R\texpiresAt\"\x9b\x01\n" ++ "expires_at\x18\x03 \x01(\x03R\texpiresAt\"\xc2\x01\n" +"\n" +"PolicyRole\x12\x12\n" +"\x04name\x18\x01 \x01(\tR\x04name\x12'\n" +"\x0fallowed_targets\x18\x02 \x03(\tR\x0eallowedTargets\x12)\n" +"\x10allowed_services\x18\x03 \x03(\tR\x0fallowedServices\x12%\n" +- "\x0ecustom_datalog\x18\x04 \x03(\tR\rcustomDatalog\"=\n" ++ "\x0ecustom_datalog\x18\x04 \x03(\tR\rcustomDatalog\x12%\n" ++ "\x0eallowed_agents\x18\x05 \x03(\tR\rallowedAgents\"=\n" +"\rPolicyBinding\x12\x12\n" +"\x04role\x18\x01 \x01(\tR\x04role\x12\x18\n" +"\amembers\x18\x02 \x03(\tR\amembers\"\x18\n" +diff --git a/api/sam.proto b/api/sam.protoindex d956ed72..4e586aad 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -177,6 +177,11 @@ message PolicyRole {repeated string allowed_targets = 2;repeated string allowed_services = 3;repeated string custom_datalog = 4;+ // Agent namespaces the holder may speak for, e.g. "*.prod.acme.example".+ // An agent claim is the calling node's word, so it is only worth what the+ // control plane attested about that node. Distinct from allowed_targets:+ // being allowed to call an agent is not being allowed to impersonate it.+ repeated string allowed_agents = 5;}message PolicyBinding {diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 9737c908..2fc3b28b 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -2062,6 +2062,11 @@ func validatePolicyConfig(req *api.PolicyConfigUpdateRequest) error {return fmt.Errorf("invalid allowed_target %q in role %s: %w", target, r.Name, err)}}+ for _, agent := range r.AllowedAgents {+ if err := api.ValidateAgentPattern(agent); err != nil {+ return fmt.Errorf("invalid allowed_agent %q in role %s: %w", agent, r.Name, err)+ }+ }for _, dl := range r.CustomDatalog {trimmed := strings.TrimRight(strings.TrimSpace(dl), ";")if trimmed == "" {@@ -2080,6 +2085,7 @@ func validatePolicyConfig(req *api.PolicyConfigUpdateRequest) error {// which roles are mutually exclusive for a given identity.factBudget += len(api.BuildServiceDatalogFacts(r.AllowedServices))factBudget += len(api.BuildTargetDatalogFacts(r.AllowedTargets))+ factBudget += len(api.BuildAgentDatalogFacts(r.AllowedAgents))factBudget += len(r.CustomDatalog)}diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.goindex 4d9f2f17..934971df 100644--- a/internal/identity/biscuit.go+++ b/internal/identity/biscuit.go@@ -202,6 +202,10 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []stri// stay siloed per role, and merging keeps fact counts flat regardless of how many roles match.var allServices []stringvar allTargets []string+ // Agent namespaces this holder can act for. No grant means no agent claim+ // is accepted, which is what stops an unconfigured mesh from letting any+ // peer name any agent.+ var allAgents []stringfor _, role := range roles {if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactRole,@@ -240,6 +244,8 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []striallTargets = append(allTargets, pr.AllowedTargets...)}+ allAgents = append(allAgents, pr.AllowedAgents...)+for _, customEntry := range pr.CustomDatalog {trimmed := strings.TrimRight(strings.TrimSpace(customEntry), ";")if trimmed == "" {@@ -273,6 +279,11 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []strierrs = append(errs, fmt.Errorf("failed to add target fact: %w", err))}}+ for _, fact := range api.BuildAgentDatalogFacts(allAgents) {+ if err := addFact(fact); err != nil {+ errs = append(errs, fmt.Errorf("failed to add agent namespace fact: %w", err))+ }+ }if !hasServices && len(policyRoles) == 0 {if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{diff --git a/internal/node/agent_namespace_test.go b/internal/node/agent_namespace_test.gonew file mode 100644index 00000000..8c668ab2--- /dev/null+++ b/internal/node/agent_namespace_test.go@@ -0,0 +1,150 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package node++import (+ "crypto/ed25519"+ "testing"+ "time"++ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/google/sam/api"+ "github.com/libp2p/go-libp2p/core/peer"+)++// An agent claim travels beside the token as the calling node's word, so the+// only thing limiting it is the namespace grant in that node's own token.+// Without the limit, any authenticated peer could name any agent and pick up+// whatever role an agent: binding gives it, choosing its own principal. These+// tests cover the limit at the point it is applied.+func TestAuthorizeBoundsTheAgentClaimToTheGrantedNamespace(t *testing.T) {+ pub, priv, err := ed25519.GenerateKey(nil)+ if err != nil {+ t.Fatal(err)+ }+ callerPeer := peer.ID("caller-peer")++ // grants is what the caller's own token attests it may speak for.+ mint := func(t *testing.T, grants []string) []byte {+ t.Helper()+ builder := biscuit.NewBuilder(priv)+ facts := []biscuit.Fact{+ {Predicate: biscuit.Predicate{Name: api.FactTargetUnrestricted}},+ {Predicate: biscuit.Predicate{Name: api.FactNode, IDs: []biscuit.Term{biscuit.String(callerPeer.String())}}},+ {Predicate: biscuit.Predicate{Name: api.FactClientPeerID, IDs: []biscuit.Term{biscuit.String(callerPeer.String())}}},+ {Predicate: biscuit.Predicate{Name: api.FactGrantedServiceExact, IDs: []biscuit.Term{biscuit.String(api.SystemNamespace), biscuit.String("/test/proto")}}},+ {Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(time.Now().Add(time.Hour))}}},+ }+ facts = append(facts, api.BuildAgentDatalogFacts(grants)...)+ for _, f := range facts {+ if err := builder.AddAuthorityFact(f); err != nil {+ t.Fatal(err)+ }+ }+ b, err := builder.Build()+ if err != nil {+ t.Fatal(err)+ }+ data, err := b.Serialize()+ if err != nil {+ t.Fatal(err)+ }+ return data+ }++ node := &SamNode{+ trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},+ BiscuitTimeout: 500 * time.Millisecond,+ }++ authorize := func(t *testing.T, grants []string, agent string) error {+ t.Helper()+ return node.Authorize(mint(t, grants), RequestContext{+ PeerID: callerPeer,+ Protocol: "/test/proto",+ Agent: agent,+ }, pub)+ }++ tests := []struct {+ name string+ grants []string+ agent string+ wantErr bool+ }{+ {+ name: "claim inside the granted suffix",+ grants: []string{"*.prod.acme.example"},+ agent: "reviewer-7.prod.acme.example",+ },+ {+ name: "claim outside the granted suffix",+ grants: []string{"*.prod.acme.example"},+ agent: "auditor-1.staging.acme.example",+ wantErr: true,+ },+ {+ // The reason agent ids are dot-anchored: a suffix grant keeps its+ // leading dot, so a lookalike authority is a different namespace.+ name: "lookalike authority does not satisfy a suffix grant",+ grants: []string{"*.prod.acme.example"},+ agent: "intruder.evil-prod.acme.example",+ wantErr: true,+ },+ {+ name: "no grant at all",+ grants: nil,+ agent: "reviewer-7.prod.acme.example",+ wantErr: true,+ },+ {+ name: "exact grant matches exactly",+ grants: []string{"reviewer-7.prod.acme.example"},+ agent: "reviewer-7.prod.acme.example",+ },+ {+ name: "exact grant does not cover a sibling",+ grants: []string{"reviewer-7.prod.acme.example"},+ agent: "reviewer-8.prod.acme.example",+ wantErr: true,+ },+ {+ name: "wildcard grant covers anything",+ grants: []string{"*"},+ agent: "anyone.anywhere.example",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := authorize(t, tt.grants, tt.agent)+ if tt.wantErr && err == nil {+ t.Errorf("peer speaking for %q with grants %v was allowed; the claim is unbounded", tt.agent, tt.grants)+ }+ if !tt.wantErr && err != nil {+ t.Errorf("peer speaking for %q with grants %v was refused: %v", tt.agent, tt.grants, err)+ }+ })+ }++ // A node's own housekeeping acts for no agent. Requiring a grant+ // unconditionally would refuse it, and its models would stop appearing in+ // peers' catalogues.+ t.Run("no agent claim needs no grant", func(t *testing.T) {+ if err := authorize(t, nil, ""); err != nil {+ t.Errorf("unattributed request refused: %v", err)+ }+ })+}diff --git a/internal/node/middleware.go b/internal/node/middleware.goindex a94c0cb8..7053140f 100644--- a/internal/node/middleware.go+++ b/internal/node/middleware.go@@ -245,6 +245,12 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.// The calling node's claim about which agent it speaks for. Injected here// rather than trusted from the token, so it is visible to policy while// staying plainly what it is: an assertion by the peer at the other end.+ //+ // The claim is limited to the agent namespaces the caller's own token+ // grants. Without that limit any authenticated peer could name any agent+ // and pick up whatever role an agent: binding gives it. The check runs only+ // when a claim is present, because a node's own housekeeping acts for no+ // agent and would otherwise be refused.if req.Agent != "" {authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{@@ -252,6 +258,10 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.IDs: []biscuit.Term{biscuit.String(req.Agent)},},})+ for _, r := range api.BaselineAgentRules {+ authorizer.AddRule(r)+ }+ authorizer.AddCheck(api.BaselineAgentCheck)}// Enforce client_peer_id matches connection_peer_iddiff --git a/internal/node/policy.go b/internal/node/policy.goindex dd6bf1d1..720a60b8 100644--- a/internal/node/policy.go+++ b/internal/node/policy.go@@ -121,6 +121,18 @@ func BuildPolicyRules(roles []*api.PolicyRole, bindings []*api.PolicyBinding) []})}+ for _, fact := range api.BuildAgentDatalogFacts(role.AllowedAgents) {+ if fact.Name == api.FactGrantedAgentAll {+ logger.Warnf("Role %s may speak for any agent; any peer holding it can name any agent identity in the mesh", roleName)+ }+ rules = append(rules, biscuit.Rule{+ Head: fact.Predicate,+ Body: []biscuit.Predicate{+ {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(roleName)}},+ },+ })+ }+for _, dl := range role.CustomDatalog {trimmed := strings.TrimRight(strings.TrimSpace(dl), ";")if trimmed == "" {diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.mdindex 77aac138..1d7d181d 100644--- a/site/content/docs/agent-architecture.md+++ b/site/content/docs/agent-architecture.md@@ -208,10 +208,11 @@ component there verifies the same workload credential and asserts the same`agent:` name. Nothing downstream notices the move.The residual trust, stated plainly: an enrolled node asserts its own agents.-Mesh policy bounds that by binding namespaces to node attestation — only nodes-attested `cluster=c1.acme` may assert `agent:*.c1.acme` — which the existing-target-fact machinery already expresses. Non-repudiation *by the agent itself*-needs proof of possession, which stays an upgrade path (§8.6).+Mesh policy limits this with a role's `allowed_agents`, which lists the+namespaces a node is allowed to use. Only a node whose role grants `*.c1.acme`+can claim an agent in that namespace, and a node with no grant cannot name any+agent at all. Non-repudiation *by the agent itself* needs proof of possession,+which stays an upgrade path (§8.6).## 4. Where the gateway lives: `sam-box`, without a libp2p host@@ -646,11 +647,26 @@ in-band afterwards:### 8.6 The honest limit-An enrolled node asserts its own agents, so a compromised node can assert any-agent identity **within the namespaces its own attestation permits**. That bound-is the mitigation, and it is enforced by the same policy machinery as everything-else; without the namespace binding, a single compromised node could impersonate-any agent anywhere, which is why it is not optional.+An enrolled node asserts its own agents, so a compromised node can claim any+agent identity inside the namespaces its role allows (`allowed_agents`, §3).+That limit is the mitigation, and the same policy machinery enforces it. Without+it, one compromised node could impersonate any agent anywhere. A node that holds+no grant cannot name any agent.++The grant is keyed on the node's **role**, not on its labels. Nodes declare+their own labels at OIDC enrollment and the control plane only checks the+syntax, so a namespace derived from a label would be one the node picked for+itself. Roles are resolved from verified OIDC claims against bindings the admin+wrote, so that chain holds all the way back.++Two things follow:++* How tight the limit is depends on the connector's naming (§8.8, property 5).+ If a name has no label for the boundary it runs in, the only grant you can+ write is a tenant-wide one.+* `allowed_agents: ["*"]` goes back to the old, unlimited behaviour. It is+ allowed because some meshes have a single tenant, and nodes log a warning so+ it is never silent.Removing the residue entirely requires proof of possession: the agent holds akey and signs a per-request binding. That needs either a mesh-aware harness@@ -706,6 +722,14 @@ worth writing down because "without losing capabilities" lives here:4. **Auditable** — the original identifier travels verbatim alongside thetranslated one. Where translation cannot round-trip, the verbatim value iswhat an auditor reads.+5. **Bounded** — the name must include a label for the boundary where the+ agent's workload credential stops being valid, usually the cluster or trust+ domain. Node grants (`allowed_agents`, §8.6) are written against that label.+ A mapping can satisfy properties 1–4 and still fail this one: a flat+ `spiffe://acme.example/prod/reviewer-7` → `reviewer-7.prod.acme.example` has+ no cluster label, so every node hosting these agents needs a tenant-wide+ grant and the limit gets much weaker. The Kubernetes and Substrate rows+ below keep the cluster in the name, so their grants stay tight.| foreign identity | mesh identifier ||---|---|diff --git a/site/content/docs/development/policy.md b/site/content/docs/development/policy.mdindex 1bc4ff82..b9cf8692 100644--- a/site/content/docs/development/policy.md+++ b/site/content/docs/development/policy.md@@ -76,6 +76,7 @@ Admins manage central permissions dynamically via the Control Plane REST API. Th* **Roles**: Define specific capabilities (allowed destinations and services).* `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_agents`: The agent namespaces a node with this role can act for, such as `*.prod.acme.example`. When a node forwards a request for a sandboxed agent, it sends the agent's name alongside the token (see `internal/node/agent.go`). The receiving node accepts that name only if it matches one of these namespaces, and a node with no grant cannot name any agent. You can also use `agent:<id>` as a binding member to give a role to a named agent, but that is only as reliable as the namespace grant held by the node making the claim.* `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`).* **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 domain-level wildcards to build complex policies. The control plane 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-based wildcard matching like `mcp://*.service.local` (which matches services ending in `.service.local`), suffix-based wildcard matching like `mcp://service.*` (which matches services starting with `service.`), or global access to everything via `*`.diff --git a/site/content/docs/user/control-plane-configuration.md b/site/content/docs/user/control-plane-configuration.mdindex 725e7e38..a906b0ff 100644--- a/site/content/docs/user/control-plane-configuration.md+++ b/site/content/docs/user/control-plane-configuration.md@@ -56,6 +56,9 @@ The Control Plane dynamically issues permissions inside the Biscuit token basedThe policy defines what endpoints and services agents are permitted to use:* **`allowed_targets`**: Restricts which logical endpoints the agent can route connections to. Use resolved Biscuit facts: `group:<name>`, `user:<sub-id>`, `email:<email>`, `role:<role-name>`, or `node:<peer-id>`.* **`allowed_services`**: Restricts the application-level services the agent can invoke. Services are prefixed by their protocol type and URI scheme (e.g., `mcp://local-shell-tools` or `inference://openrouter`). Wildcards are supported (e.g., `mcp://*`).+* **`allowed_agents`**: The agent namespaces a node with this role can use. When a node forwards a request for a sandboxed agent, it sends the agent's name with it. The receiving node accepts that name only if it falls inside one of these namespaces. A node with no `allowed_agents` grant cannot name any agent. Accepted patterns are `*.prod.acme.example`, `acme.*`, an exact ID such as `reviewer-7.prod.acme.example`, or `*` for any agent.++> **`allowed_agents` and `allowed_targets` do different things.** `allowed_targets` controls which agents a node can send requests *to*. `allowed_agents` controls which agents a node can claim to be acting *for*. Setting `allowed_agents` to `*` lets any node with that role claim any agent identity in the mesh, so nodes log a warning when they receive such a grant.### Seeding Policies via REST APIAdmins manage policies by sending a JSON payload to the `/policies` endpoint.@@ -66,7 +69,8 @@ Admins manage policies by sending a JSON payload to the `/policies` endpoint.{"name": "developer-role","allowed_targets": ["group:dev-nodes", "email:[email protected]", "user:auth0|123456", "node:12D3KooWSpecificDevNodeId"],- "allowed_services": ["mcp://local-shell-tools", "mcp://git-helper", "inference://openrouter"]+ "allowed_services": ["mcp://local-shell-tools", "mcp://git-helper", "inference://openrouter"],+ "allowed_agents": ["*.dev.example.com"]},{"name": "admin-role",diff --git a/site/content/docs/user/running-agents.md b/site/content/docs/user/running-agents.mdindex 470ea4d8..c440f562 100644--- a/site/content/docs/user/running-agents.md+++ b/site/content/docs/user/running-agents.md@@ -117,6 +117,20 @@ On every request the gateway asserts the agent to the node, overwritinganything the sandbox tried to set. Mesh policy can then be written about theagent rather than about the host it happens to run on.+The agent ID in the bundle is not free-form. Every node has a set of agent+namespaces it is allowed to use, set by its mesh role (`allowed_agents`, see+[control plane configuration](../control-plane-configuration/)). The `agent.id`+in the bundle has to fall inside one of them.++For example, if the node is granted `*.c1.acme.example` and the bundle says+`researcher-1.prod.acme.example`, other nodes reject the request, because the+node is claiming an agent it has no grant for. A node with no grant cannot name+any agent at all.++The namespace belongs to the node and the identifier belongs to the agent. That+is why an agent keeps its name when it moves: pause it, migrate it, resume it+behind another node in the same namespace, and nothing downstream changes.+## The architecture```mermaiddiff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex f359ea1c..e7646350 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -423,6 +423,15 @@ func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKeyt.Fatalf("failed to add role fact: %v", err)}+ // The namespace this node may speak agents for, as a real control plane+ // would mint from a role's allowed_agents. Every agent in these tests is+ // under acme.example, so enforcement stays live: a claim outside it is+ // still refused.+ err = builder.AddAuthorityFact(api.BuildAgentDatalogFact("*.acme.example"))+ if err != nil {+ t.Fatalf("failed to add agent namespace fact: %v", err)+ }+err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "node",IDs: []biscuit.Term{biscuit.String(peerID)},