Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
controlplane: only sign the labels a node's role permits
Antonio Ojead85e795f6806
diff --git a/api/label_grants_test.go b/api/label_grants_test.gonew file mode 100644index 00000000..d9452919--- /dev/null+++ b/api/label_grants_test.go@@ -0,0 +1,136 @@+// 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 (+ "strings"+ "testing"+)++func TestValidateLabelPattern(t *testing.T) {+ tests := []struct {+ name string+ pattern string+ wantErr bool+ }{+ {name: "any label", pattern: "*"},+ {name: "any value of a key", pattern: "region=*"},+ {name: "exact pair", pattern: "region=us-east-1"},++ {name: "empty", pattern: "", wantErr: true},+ {name: "no separator", pattern: "region", wantErr: true},+ {name: "empty key", pattern: "=us-east-1", wantErr: true},+ {name: "empty value", pattern: "region=", wantErr: true},+ {name: "invalid key charset", pattern: "reg ion=us", wantErr: true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := ValidateLabelPattern(tt.pattern)+ if tt.wantErr && err == nil {+ t.Errorf("ValidateLabelPattern(%q) = nil, want an error", tt.pattern)+ }+ if !tt.wantErr && err != nil {+ t.Errorf("ValidateLabelPattern(%q) = %v, want nil", tt.pattern, err)+ }+ })+ }+}++// TestLabelPatternsAllow covers the gate that turns a self-declared label into+// one the control plane is willing to sign. Fail-closed: no grant means no+// label, because otherwise a node could declare region="us-east-1" and satisfy+// every peer that requires it.+func TestLabelPatternsAllow(t *testing.T) {+ tests := []struct {+ name string+ patterns []string+ labels map[string]string+ wantErr bool+ }{+ {+ name: "no labels declared needs no grant",+ labels: nil,+ },+ {+ name: "no grant refuses any label",+ labels: map[string]string{"region": "us-east-1"},+ wantErr: true,+ },+ {+ name: "exact grant admits the exact pair",+ patterns: []string{"region=us-east-1"},+ labels: map[string]string{"region": "us-east-1"},+ },+ {+ name: "exact grant refuses another value",+ patterns: []string{"region=us-east-1"},+ labels: map[string]string{"region": "eu-west-1"},+ wantErr: true,+ },+ {+ name: "key wildcard admits any value",+ patterns: []string{"region=*"},+ labels: map[string]string{"region": "eu-west-1"},+ },+ {+ name: "key wildcard does not admit another key",+ patterns: []string{"region=*"},+ labels: map[string]string{"team": "platform"},+ wantErr: true,+ },+ {+ name: "bare wildcard admits everything",+ patterns: []string{"*"},+ labels: map[string]string{"region": "eu-west-1", "team": "platform"},+ },+ {+ // Every declared label must be covered, not just one of them.+ name: "one uncovered label refuses the whole set",+ patterns: []string{"region=*"},+ labels: map[string]string{"region": "eu-west-1", "team": "platform"},+ wantErr: true,+ },+ {+ name: "grants from several roles combine",+ patterns: []string{"region=*", "team=platform"},+ labels: map[string]string{"region": "eu-west-1", "team": "platform"},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := LabelPatternsAllow(tt.patterns, tt.labels)+ if tt.wantErr && err == nil {+ t.Errorf("LabelPatternsAllow(%v, %v) = nil, want an error", tt.patterns, tt.labels)+ }+ if !tt.wantErr && err != nil {+ t.Errorf("LabelPatternsAllow(%v, %v) = %v, want nil", tt.patterns, tt.labels, err)+ }+ })+ }+}++// The error names the label that was refused, so an operator can tell which+// grant is missing rather than being told only that something was.+func TestLabelPatternsAllowNamesTheRefusedLabel(t *testing.T) {+ err := LabelPatternsAllow([]string{"region=*"}, map[string]string{"team": "platform"})+ if err == nil {+ t.Fatal("LabelPatternsAllow accepted an ungranted label")+ }+ if !strings.Contains(err.Error(), "team") || !strings.Contains(err.Error(), "platform") {+ t.Errorf("error %q does not name the refused label", err)+ }+}diff --git a/api/labels.go b/api/labels.goindex fd3a21b0..73349c71 100644--- a/api/labels.go+++ b/api/labels.go@@ -86,3 +86,69 @@ func ValidateLabels(labels map[string]string) error {}return nil}++// A node declares its own labels when it enrols, so on its own a label is a+// claim rather than an attestation. A role's allowed_labels is what makes it+// one: the control plane only signs a label the operator said that role may+// carry. Without it a node could declare region="us-east-1" and satisfy every+// peer that requires it.++// ValidateLabelPattern checks one entry of a role's allowed_labels. The forms+// are "*" for any label at all, "key=*" for any value of a key, and "key=value"+// for one exact pair.+func ValidateLabelPattern(pattern string) error {+ if pattern == "*" {+ return nil+ }+ key, value, found := strings.Cut(pattern, "=")+ if !found {+ return fmt.Errorf("invalid allowed_label %q: must be \"*\", \"key=*\" or \"key=value\"", pattern)+ }+ if err := ValidateLabelKey(key); err != nil {+ return fmt.Errorf("invalid allowed_label %q: %w", pattern, err)+ }+ if value == "*" {+ return nil+ }+ if err := ValidateLabelValue(value); err != nil {+ return fmt.Errorf("invalid allowed_label %q: %w", pattern, err)+ }+ return nil+}++// LabelPatternsAllow reports whether patterns permit every declared label,+// naming the first one they do not. Keys are visited in order so the error for+// a given input is stable.+func LabelPatternsAllow(patterns []string, labels map[string]string) error {+ if len(labels) == 0 {+ return nil+ }+ keys := make([]string, 0, len(labels))+ for k := range labels {+ keys = append(keys, k)+ }+ sort.Strings(keys)++ for _, key := range keys {+ if !labelAllowed(patterns, key, labels[key]) {+ return fmt.Errorf("label %q=%q is not permitted by this identity's roles", key, labels[key])+ }+ }+ return nil+}++func labelAllowed(patterns []string, key, value string) bool {+ for _, p := range patterns {+ if p == "*" {+ return true+ }+ pKey, pValue, found := strings.Cut(p, "=")+ if !found || pKey != key {+ continue+ }+ if pValue == "*" || pValue == value {+ return true+ }+ }+ return false+}diff --git a/internal/controlplane/label_grants_test.go b/internal/controlplane/label_grants_test.gonew file mode 100644index 00000000..ccf9ed11--- /dev/null+++ b/internal/controlplane/label_grants_test.go@@ -0,0 +1,156 @@+// 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 controlplane++import (+ "bytes"+ "context"+ "io"+ "net/http"+ "testing"+ "time"++ "github.com/google/sam/api"+ "github.com/libp2p/go-libp2p/core/crypto"+ "github.com/libp2p/go-libp2p/core/peer"+ "google.golang.org/protobuf/proto"+)++// A node declares its own labels in its enrollment request, and the control+// plane signs them into label() facts that peers then treat as attested. Peers+// gate on those facts (required_labels on call_remote_tool), so without this+// check any identity able to enrol could claim region="us-east-1" and satisfy+// every consumer requiring it. A role's allowed_labels is what makes a declared+// label worth signing.+func TestRegisterRefusesLabelsTheRoleDoesNotGrant(t *testing.T) {+ issuer, mintToken := startCustomMockOIDC(t)+ srv, store, baseURL := setupTestServer(t, issuer)+ defer func() {+ _ = srv.Close()+ _ = store.Close()+ }()++ ctx := context.Background()+ client := &http.Client{Timeout: 5 * time.Second}++ seedPolicy := func(t *testing.T, allowedLabels []string) {+ t.Helper()+ roles := []*api.PolicyRole{{+ Name: api.RoleNode,+ AllowedServices: []string{"mcp://*"},+ AllowedLabels: allowedLabels,+ }}+ bindings := []*api.PolicyBinding{{+ Role: api.RoleNode,+ Members: []string{api.SystemAuthenticated},+ }}+ if err := store.SaveMeshPolicy(ctx, roles, bindings); err != nil {+ t.Fatalf("SaveMeshPolicy: %v", err)+ }+ }++ // Each attempt uses a fresh peer so it is a first enrollment every time.+ register := func(t *testing.T, labels map[string]string) int {+ t.Helper()+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ t.Fatal(err)+ }+ pID, err := peer.IDFromPrivateKey(priv)+ if err != nil {+ t.Fatal(err)+ }+ pubBytes, err := crypto.MarshalPublicKey(priv.GetPublic())+ if err != nil {+ t.Fatal(err)+ }++ body, err := proto.Marshal(&api.EnrollRequest{+ Jwt: mintToken(map[string]interface{}{"sub": "node-alice"}),+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleNode,+ Labels: labels,+ })+ if err != nil {+ t.Fatal(err)+ }++ resp, err := client.Post(baseURL+"/register", "application/x-protobuf", bytes.NewReader(body))+ if err != nil {+ t.Fatalf("POST /register: %v", err)+ }+ _, _ = io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ return resp.StatusCode+ }++ t.Run("a role granting no labels refuses one", func(t *testing.T) {+ seedPolicy(t, nil)+ if got := register(t, map[string]string{"region": "us-east-1"}); got != http.StatusForbidden {+ t.Errorf("status = %d, want %d", got, http.StatusForbidden)+ }+ })++ t.Run("declaring no labels still enrols", func(t *testing.T) {+ seedPolicy(t, nil)+ if got := register(t, nil); got != http.StatusOK {+ t.Errorf("status = %d, want %d", got, http.StatusOK)+ }+ })++ t.Run("a granted label is accepted", func(t *testing.T) {+ seedPolicy(t, []string{"region=*"})+ if got := register(t, map[string]string{"region": "us-east-1"}); got != http.StatusOK {+ t.Errorf("status = %d, want %d", got, http.StatusOK)+ }+ })++ t.Run("a label outside the grant is refused", func(t *testing.T) {+ seedPolicy(t, []string{"region=*"})+ if got := register(t, map[string]string{"team": "platform"}); got != http.StatusForbidden {+ t.Errorf("status = %d, want %d", got, http.StatusForbidden)+ }+ })++ t.Run("an exact grant refuses another value", func(t *testing.T) {+ seedPolicy(t, []string{"region=us-east-1"})+ if got := register(t, map[string]string{"region": "eu-west-1"}); got != http.StatusForbidden {+ t.Errorf("status = %d, want %d", got, http.StatusForbidden)+ }+ })+}++func TestAllowedLabelPatternsCollectsEveryResolvedRole(t *testing.T) {+ policyRoles := []*api.PolicyRole{+ {Name: "a", AllowedLabels: []string{"region=*"}},+ {Name: "b", AllowedLabels: []string{"team=platform"}},+ {Name: "c", AllowedLabels: []string{"secret=*"}},+ nil,+ }++ got := allowedLabelPatterns([]string{"a", "b"}, policyRoles)+ if len(got) != 2 {+ t.Fatalf("allowedLabelPatterns = %v, want the grants of a and b only", got)+ }++ // A role the identity does not hold must not contribute its grants.+ if err := api.LabelPatternsAllow(got, map[string]string{"secret": "value"}); err == nil {+ t.Error("a grant from an unheld role was applied")+ }+ if err := api.LabelPatternsAllow(got, map[string]string{"region": "eu", "team": "platform"}); err != nil {+ t.Errorf("grants from held roles did not combine: %v", err)+ }+}diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 0abb2f8e..6e9f3edf 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -507,6 +507,14 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {finalRoles := []string{req.RequestedRole}finalRoles = append(finalRoles, customAccessRoles...)+ // The node declared these labels itself, so they are only worth signing if+ // a role it resolves to says it may carry them.+ if err := api.LabelPatternsAllow(allowedLabelPatterns(finalRoles, policyRoles), req.Labels); err != nil {+ logger.Warnw("Rejected undeclarable label at enrollment", "peer_id", req.PeerId, "error", err)+ http.Error(w, "Label not permitted: "+err.Error(), http.StatusForbidden)+ return+ }+// Mint token. A biscuit must never outlive the OIDC token that vouched// for it, so its expiration is capped at whichever comes first.biscuitExpiry := time.Now().Add(s.config.BiscuitTTL)@@ -1204,6 +1212,14 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {http.Error(w, "Internal server error", http.StatusInternalServerError)return}+ // Nobody reviews an auto-approved enrollment, so the role's+ // allowed_labels is the only thing standing between a self-declared+ // label and a signed one. Manual approval attests them separately.+ if err := api.LabelPatternsAllow(allowedLabelPatterns([]string{tokenRecord.Role}, policyRoles), req.Labels); err != nil {+ logger.Warnw("Rejected undeclarable label at bootstrap enrollment", "peer_id", req.PeerId, "error", err)+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Label not permitted: "+err.Error())+ return+ }biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(s.config.BiscuitTTL), policyRoles, req.Labels)if err != nil {logger.Errorf("Failed to mint bootstrap biscuit: %v", err)@@ -1933,6 +1949,23 @@ func (s *Server) HandleUserRevoke(w http.ResponseWriter, r *http.Request) {_, _ = w.Write([]byte("Node revoked successfully"))}+// allowedLabelPatterns collects the label grants of every role an identity+// resolves to. A role that names none contributes none, so an identity with no+// grant anywhere may declare no labels at all.+func allowedLabelPatterns(roles []string, policyRoles []*api.PolicyRole) []string {+ wanted := make(map[string]bool, len(roles))+ for _, r := range roles {+ wanted[r] = true+ }+ var patterns []string+ for _, pr := range policyRoles {+ if pr != nil && wanted[pr.Name] {+ patterns = append(patterns, pr.AllowedLabels...)+ }+ }+ return patterns+}+func resolveRoles(peerID string, claims jwt.MapClaims, bindings []*api.PolicyBinding) []string {if claims == nil {claims = make(jwt.MapClaims)@@ -2055,6 +2088,11 @@ func validatePolicyConfig(req *api.PolicyConfigUpdateRequest) error {return fmt.Errorf("invalid allowed_agent %q in role %s: %w", agent, r.Name, err)}}+ for _, label := range r.AllowedLabels {+ if err := api.ValidateLabelPattern(label); err != nil {+ return fmt.Errorf("in role %s: %w", r.Name, err)+ }+ }for _, dl := range r.CustomDatalog {trimmed := strings.TrimRight(strings.TrimSpace(dl), ";")if trimmed == "" {diff --git a/site/content/docs/user/control-plane-configuration.md b/site/content/docs/user/control-plane-configuration.mdindex a906b0ff..4e2a606a 100644--- a/site/content/docs/user/control-plane-configuration.md+++ b/site/content/docs/user/control-plane-configuration.md@@ -57,6 +57,7 @@ The 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_labels`**: The labels a node with this role may declare when it enrolls, as `*`, `key=*` or `key=value`. A node sends its own labels in its enrollment request, so this is what decides which of them the control plane is willing to sign into `label()` facts. A role granting none means a node holding it can declare none. Peers gate on those facts with `required_labels`, so a node that could declare anything could satisfy any such requirement.> **`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.diff --git a/site/content/docs/user/node-configuration.md b/site/content/docs/user/node-configuration.mdindex 086f7b3a..b41c5068 100644--- a/site/content/docs/user/node-configuration.md+++ b/site/content/docs/user/node-configuration.md@@ -99,7 +99,7 @@ Start the node with its operator-declared labels, a comma-separated `key=value`sam-node run --labels region=us-east-1,team=platform ...```-Labels are declared at enrollment and **attested by the control plane**: for bootstrap enrollments the administrator sees the declared labels on the pending request and approving it attests the claims. The control plane then mints one signed `label(key, value)` fact per declared label into the node's Biscuit. Matching is exact and case-sensitive; an empty value means no claim for that key.+Labels are declared at enrollment and **attested by the control plane**, but only the ones a role permits. Set `allowed_labels` on the node's role (see [control plane configuration](../control-plane-configuration/)); a role granting none means the node can declare none, and enrollment is refused if it tries. For bootstrap enrollments that wait for approval, the administrator also sees the declared labels on the pending request and approving it attests them. The control plane then mints one signed `label(key, value)` fact per declared label into the node's Biscuit. Matching is exact and case-sensitive; an empty value means no claim for that key.### Requiring labels (consumer)