Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
policy: Datalog text is the contract every member evaluates
Antonio Ojeac036700e1e95
diff --git a/AGENTS.md b/AGENTS.mdindex 9fc0b954..16f900bb 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -5,7 +5,8 @@ You are an expert software engineering assistant helping to develop, maintain, a## 1. Architecture & Component Independence* **Decoupled Architecture:** The `sam-control-plane`, `sam-router` and `sam-node` components are strictly independent. They must not share internal state or tightly couple their logic.* **API Communication:** All data communication between `sam-control-plane`, `sam-router` and `sam-node` must happen exclusively via the common API defined in `api/sam.proto`.-* **Two API surfaces, two encodings:** the *mesh protocol* — anything a mesh component speaks (node, router, `sam-box`, the agent connector): enrollment, refresh, keys, leases, auth streams, policy sync — is protobuf from `api/sam.proto` (`application/x-protobuf`). The *operator plane* — what humans, the web console and admin CLIs call (`/admin/*`, `/users/*`) — is JSON, with its request and response types declared as Go structs in `api/` (e.g. `api.BootstrapTokenRequest`). Never define a wire shape as an anonymous struct or `map[string]any` inside a handler, and never serialize an `internal/storage` (or any other internal) type onto either surface; clients in `cmd/` and `internal/console` import `api/` only. A message that a mesh component consumes goes in the proto even if a console also reads it.+* **One schema, two encodings:** every request and response on any SAM surface is a message in `api/sam.proto`. The *mesh protocol* — anything a mesh component speaks (node, router, `sam-box`, the agent connector, the SDKs under `sdk/`): enrollment, refresh, keys, leases, auth streams, policy sync — is binary protobuf (`application/x-protobuf`). The *operator plane* — what humans, the web console and admin CLIs call (`/admin/*`, `/users/*`, `POST /policies`) — is protojson of the same messages, with `UseProtoNames` and unknown fields rejected. Never define a wire shape as a Go struct with `json` tags, an anonymous struct or `map[string]any`, and never serialize an `internal/storage` (or any other internal) type onto either surface. Use `google.protobuf.Timestamp` for instants so protojson renders them as RFC 3339. Clients in `cmd/`, `internal/console` and `sdk/` import `api/` or its generated bindings only.+* **Datalog text is the policy contract:** the control plane renders the mesh policy as Datalog rules (`PolicyConfigGetResponse.datalog_rules`); every member, in any language, adds that text to its authorizer and none derives rules from roles and bindings itself. Datalog must stay in the form every Biscuit implementation parses: a predicate carries at least one term (presence-only facts are `name(true)`, see `api.MarkerFact`).* **Secrets never travel as flag values:** binaries read credentials from a file (`--*-path`) or the environment, never from a command-line argument that would sit in `ps` output and shell history. Banners and logs name the source of an operator-supplied secret instead of echoing it.* **Sandbox Dataplane:** `sam-box` (one per sandbox) is the single egress policy enforcement point. It holds no libp2p host, no enrollment and no mesh identity, and reaches the mesh exclusively as a client of the local `sam-node` sidecar socket. `nano-init` (PID 1 inside the guest, its own Go module) owns the guest side; its datapath is the `tun2connect` library. The sandbox boundary is a Unix socket speaking named HTTP tunnels: CONNECT (TCP) and connect-udp (UDP) out, `CONNECT <port>` back in. The authoritative design is `site/content/docs/preview/agent-architecture.md`; do not contradict it.* **Enforcement over Convention:** never gate sandbox traffic on the agent's cooperation — no proxy environment variables, no `LD_PRELOAD` shims, no DNS spoofing. The agent harness stays unmodified and mesh-unaware; confinement is a route and a socket, built by the userspace launcher (`nano-init`) and judged in `sam-box`. An agent that must cooperate with its own confinement is not confined.diff --git a/api/datalog.go b/api/datalog.goindex 36f479e2..72a85102 100644--- a/api/datalog.go+++ b/api/datalog.go@@ -49,10 +49,17 @@ import (// - target_unrestricted: Fact injected in the token by the control plane indicating that// the client has unrestricted network access and bypasses target constraints.// - Target Check: Verified using the check:-// `check if allow_network_target($fact, $val) or target_unrestricted()`+// `check if allow_network_target($fact, $val) or target_unrestricted(true)`// If target_unrestricted is present, target checking succeeds immediately.// Otherwise, it requires a matching allow_network_target rule to succeed.//+// 3. Marker Facts:+// Facts that only signal presence (target_unrestricted, granted_service_all_types,+// agent_authorized, ...) carry the single term `true`, see MarkerFact. The Biscuit+// grammar requires at least one term per predicate; biscuit-go accepts an empty term+// list but the Rust, Python and JavaScript implementations reject it, and the SDKs+// evaluate this same Datalog.+//// ============================================================================// Biscuit fact names represent the Datalog predicates used in auth tokens and policy evaluation.@@ -129,8 +136,8 @@ const (FactEmail = "email"// FactGrantedServiceAllTypes allows access to all service types (e.g., mcp, inference) and all targets.- // Contains: (no terms)- // Example Datalog: allow if granted_service_all_types()+ // Contains: biscuit.Bool(true) (marker fact)+ // Example Datalog: allow if granted_service_all_types(true)FactGrantedServiceAllTypes = "granted_service_all_types"// FactGrantedServiceAll allows access to all targets under a specific service type.@@ -159,7 +166,7 @@ const (FactGrantedServiceSet = "granted_service_set"// FactGrantedTargetAllTypes allows target access to all network targets (unrestricted).- // Contains: (no terms)+ // Contains: biscuit.Bool(true) (marker fact)FactGrantedTargetAllTypes = "granted_target_all_types"// FactGrantedTargetAll allows target access to all values of a specific fact.@@ -180,7 +187,7 @@ const (FactGrantedTargetExact = "granted_target_exact"// FactGrantedTargetAllFacts allows target access to any fact name and value combination.- // Contains: (no terms)+ // Contains: biscuit.Bool(true) (marker fact)FactGrantedTargetAllFacts = "granted_target_all_facts"// FactGrantedTargetSet allows target access to a Set of exact values for a specific fact name.@@ -217,12 +224,12 @@ const (FactGrantedAgentSuffix = "granted_agent_suffix"// FactGrantedAgentAll allows the holder to act for any agent at all.- // Contains: (no terms)+ // Contains: biscuit.Bool(true) (marker fact)FactGrantedAgentAll = "granted_agent_all"// FactAgentAuthorized is derived when an agent claim falls inside one of the// holder's granted_agent_* namespaces.- // Contains: (no terms)+ // Contains: biscuit.Bool(true) (marker fact)FactAgentAuthorized = "agent_authorized"// FactConnectionPeerID defines the actual PeerID of the remote peer making the connection.@@ -241,12 +248,12 @@ const (FactAllowNetworkTarget = "allow_network_target"// FactTargetUnrestricted indicates that target authorization checks are bypassed.- // Contains: (no terms)- // Example Datalog: check if allow_network_target($fact, $val) or target_unrestricted()+ // Contains: biscuit.Bool(true) (marker fact)+ // Example Datalog: check if allow_network_target($fact, $val) or target_unrestricted(true)FactTargetUnrestricted = "target_unrestricted"// FactTargetRestricted indicates that target authorization checks must be enforced.- // Contains: (no terms)+ // Contains: biscuit.Bool(true) (marker fact)FactTargetRestricted = "target_restricted"// FactService represents the service target that a node is requesting access to.@@ -272,6 +279,17 @@ const (FactTime = "time")+// MarkerTerm is the single term every marker fact carries, written `true` in+// Datalog text. See MarkerFact.+var MarkerTerm biscuit.Term = biscuit.Bool(true)++// MarkerFact returns the presence-only fact name(true). The Biscuit grammar+// requires at least one term per predicate, so a fact whose only meaning is+// "this grant exists" carries MarkerTerm and is matched as name(true).+func MarkerFact(name string) biscuit.Fact {+ return biscuit.Fact{Predicate: biscuit.Predicate{Name: name, IDs: []biscuit.Term{MarkerTerm}}}+}+var oidcClaimToFact = map[string]string{"sub": FactUser,"email": FactEmail,@@ -343,11 +361,39 @@ var (// AllowIfTruePolicy is the static policy "allow if true" used during token verification.AllowIfTruePolicy biscuit.Policy++ // BaselineSources is the Datalog text every variable above is parsed from.+ // The SDKs embed this text (see hack/gen-sdk-datalog) so that a provider+ // written in another language evaluates the same authorizer as sam-node.+ BaselineSources DatalogSources)+// DatalogSources is the source text of the baseline Datalog, one string per+// item, in the form every Biscuit implementation parses.+type DatalogSources struct {+ // Policies are the service allow policies (BaselinePolicies).+ Policies []string `json:"policies"`+ // Rules derive allow_network_target from target grants (BaselineRules).+ Rules []string `json:"rules"`+ // AgentRules derive agent_authorized from agent grants (BaselineAgentRules).+ AgentRules []string `json:"agent_rules"`+ // TargetFactRules map identity facts to target_fact (TargetFactRules).+ TargetFactRules []string `json:"target_fact_rules"`+ // ReplayCheck is BaselineReplayCheck.+ ReplayCheck string `json:"replay_check"`+ // TargetCheck is BaselineTargetCheck.+ TargetCheck string `json:"target_check"`+ // AgentCheck is BaselineAgentCheck.+ AgentCheck string `json:"agent_check"`+ // TimeCheck is ControlPlaneStaticTimeCheck.+ TimeCheck string `json:"time_check"`+ // AllowIfTrue is AllowIfTruePolicy.+ AllowIfTrue string `json:"allow_if_true"`+}+func init() {// 1. Service Allow Policies- policyStrs := []string{+ BaselineSources.Policies = []string{// Exact Match: Allows access if the token possesses a granted_service_exact fact// that perfectly matches both the protocol type (e.g. "mcp") and the service name (e.g. "calculator").fmt.Sprintf(`allow if %s($type, $name), %s($type, $name)`, FactService, FactGrantedServiceExact),@@ -370,10 +416,10 @@ func init() {// Global Wildcard: Allows access if the token possesses a granted_service_all_types fact,// granting access to literally any service in any namespace (equivalent to '*').- fmt.Sprintf(`allow if %s($type, $name), %s()`, FactService, FactGrantedServiceAllTypes),+ fmt.Sprintf(`allow if %s($type, $name), %s(true)`, FactService, FactGrantedServiceAllTypes),}- for i, pStr := range policyStrs {+ for i, pStr := range BaselineSources.Policies {p, err := parser.FromStringPolicy(pStr)if err != nil {panic(fmt.Sprintf("failed to parse baseline policy %d: %v", i, err))@@ -383,7 +429,7 @@ func init() {// 2. Target Evaluation Rules// These rules satisfy the check if allow_network_target($fact, $val) injected by the control plane.- ruleStrs := []string{+ BaselineSources.Rules = []string{// Exact Match: Derives allow_network_target if the token has a granted_target_exact fact matching a target_fact exactly.fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s($fact, $val)`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetExact),@@ -401,10 +447,10 @@ func init() {fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s($fact)`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetAll),// Global Wildcard Match: Derives allow_network_target if the token has a granted_target_all_facts fact, unconditionally allowing any target_fact.- fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s()`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetAllFacts),+ fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s(true)`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetAllFacts),}- for i, rStr := range ruleStrs {+ for i, rStr := range BaselineSources.Rules {r, err := parser.FromStringRule(rStr)if err != nil {panic(fmt.Sprintf("failed to parse baseline rule %d: %v", i, err))@@ -416,14 +462,16 @@ func init() {// BaselineReplayCheck prevents token theft/replay by ensuring the client_peer_id fact (embedded by the control plane during issuance)// perfectly matches the connection_peer_id fact (provided by the local node verifying the incoming libp2p connection).- BaselineReplayCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($id), %s($id)`, FactClientPeerID, FactConnectionPeerID))+ BaselineSources.ReplayCheck = fmt.Sprintf(`check if %s($id), %s($id)`, FactClientPeerID, FactConnectionPeerID)+ BaselineReplayCheck, err = parser.FromStringCheck(BaselineSources.ReplayCheck)if err != nil {panic(fmt.Sprintf("failed to parse replay check: %v", err))}// BaselineTargetCheck enforces network target restrictions. The token must either have an unrestricted target,// or one of the Target Evaluation Rules must have successfully derived an allow_network_target fact.- BaselineTargetCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($fact, $val) or %s()`, FactAllowNetworkTarget, FactTargetUnrestricted))+ BaselineSources.TargetCheck = fmt.Sprintf(`check if %s($fact, $val) or %s(true)`, FactAllowNetworkTarget, FactTargetUnrestricted)+ BaselineTargetCheck, err = parser.FromStringCheck(BaselineSources.TargetCheck)if err != nil {panic(fmt.Sprintf("failed to parse target check: %v", err))}@@ -432,14 +480,14 @@ func init() {// 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 {+ BaselineSources.AgentRules = []string{+ fmt.Sprintf(`%s(true) <- %s($a), %s($a)`, FactAgentAuthorized, FactAgent, FactGrantedAgentExact),+ fmt.Sprintf(`%s(true) <- %s($a), %s($set), $set.contains($a)`, FactAgentAuthorized, FactAgent, FactGrantedAgentSet),+ fmt.Sprintf(`%s(true) <- %s($a), %s($prefix), $a.starts_with($prefix)`, FactAgentAuthorized, FactAgent, FactGrantedAgentPrefix),+ fmt.Sprintf(`%s(true) <- %s($a), %s($suffix), $a.ends_with($suffix)`, FactAgentAuthorized, FactAgent, FactGrantedAgentSuffix),+ fmt.Sprintf(`%s(true) <- %s($a), %s(true)`, FactAgentAuthorized, FactAgent, FactGrantedAgentAll),+ }+ for i, rStr := range BaselineSources.AgentRules {r, err := parser.FromStringRule(rStr)if err != nil {panic(fmt.Sprintf("failed to parse baseline agent rule %d: %v", i, err))@@ -449,15 +497,19 @@ func init() {// 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))+ BaselineSources.AgentCheck = fmt.Sprintf(`check if %s(true)`, FactAgentAuthorized)+ BaselineAgentCheck, err = parser.FromStringCheck(BaselineSources.AgentCheck)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() {- ruleStr := fmt.Sprintf(`%s(%q, $val) <- %s($val)`, FactTargetFact, val, val)+ // Node PeerID Target Fact: Ensures the target node's PeerID is also evaluated as a standard target_fact.+ for _, name := range TargetFactNames() {+ BaselineSources.TargetFactRules = append(BaselineSources.TargetFactRules, fmt.Sprintf(`%s(%q, $val) <- %s($val)`, FactTargetFact, name, name))+ }+ for _, ruleStr := range BaselineSources.TargetFactRules {r, err := parser.FromStringRule(ruleStr)if err != nil {panic(fmt.Sprintf("failed to parse target fact rule: %v", err))@@ -465,15 +517,9 @@ func init() {TargetFactRules = append(TargetFactRules, r)}- // Node PeerID Target Fact: Ensures the target node's PeerID is also evaluated as a standard target_fact.- r, err := parser.FromStringRule(fmt.Sprintf(`%s(%q, $val) <- %s($val)`, FactTargetFact, FactNode, FactNode))- if err != nil {- panic(fmt.Sprintf("failed to parse node fact rule: %v", err))- }- TargetFactRules = append(TargetFactRules, r)-// ControlPlaneStaticTimeCheck ensures the token is not expired at the time of evaluation.- ControlPlaneStaticTimeCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($time), %s($exp), $time <= $exp`, FactTime, FactExpiration))+ BaselineSources.TimeCheck = fmt.Sprintf(`check if %s($time), %s($exp), $time <= $exp`, FactTime, FactExpiration)+ ControlPlaneStaticTimeCheck, err = parser.FromStringCheck(BaselineSources.TimeCheck)if err != nil {panic(fmt.Sprintf("failed to parse static time check: %v", err))}@@ -482,7 +528,8 @@ func init() {// Note that this does NOT mean all requests are automatically allowed. Biscuit requires at least one policy// to evaluate to true AND all checks to pass. This simply satisfies the policy requirement, effectively// deferring entirely to the control plane's checks and granted facts without imposing extra local restrictions.- AllowIfTruePolicy, err = parser.FromStringPolicy("allow if true")+ BaselineSources.AllowIfTrue = "allow if true"+ AllowIfTruePolicy, err = parser.FromStringPolicy(BaselineSources.AllowIfTrue)if err != nil {panic(fmt.Sprintf("failed to parse static allow policy: %v", err))}@@ -492,10 +539,7 @@ func init() {func BuildServiceDatalogFact(serviceStr string) biscuit.Fact {svcType, svcName := ParseServiceTarget(serviceStr)if svcType == "*" && svcName == "*" {- return biscuit.Fact{Predicate: biscuit.Predicate{- Name: FactGrantedServiceAllTypes,- IDs: []biscuit.Term{},- }}+ return MarkerFact(FactGrantedServiceAllTypes)} else if svcName == "*" {return biscuit.Fact{Predicate: biscuit.Predicate{Name: FactGrantedServiceAll,@@ -525,10 +569,7 @@ func BuildTargetDatalogFact(targetStr string) biscuit.Fact {tFact = FactNode}if tFact == "*" && tVal == "*" {- return biscuit.Fact{Predicate: biscuit.Predicate{- Name: FactGrantedTargetAllFacts,- IDs: []biscuit.Term{},- }}+ return MarkerFact(FactGrantedTargetAllFacts)} else if tVal == "*" {return biscuit.Fact{Predicate: biscuit.Predicate{Name: FactGrantedTargetAll,@@ -696,7 +737,7 @@ func BuildAgentDatalogFact(pattern string) biscuit.Fact {pattern = strings.TrimPrefix(pattern, FactAgent+":")switch {case pattern == "*":- return biscuit.Fact{Predicate: biscuit.Predicate{Name: FactGrantedAgentAll}}+ return MarkerFact(FactGrantedAgentAll)case strings.HasPrefix(pattern, "*."):return biscuit.Fact{Predicate: biscuit.Predicate{Name: FactGrantedAgentSuffix,diff --git a/api/datalog_test.go b/api/datalog_test.goindex 1f784ed5..cee99186 100644--- a/api/datalog_test.go+++ b/api/datalog_test.go@@ -112,7 +112,7 @@ func TestBaselinePolicies(t *testing.T) {{name: "Global wildcard allows everything",tokenFacts: []biscuit.Fact{- {Predicate: biscuit.Predicate{Name: FactGrantedServiceAllTypes, IDs: []biscuit.Term{}}},+ MarkerFact(FactGrantedServiceAllTypes),},requestTarget: "mcp://calculator",expectAllow: true,@@ -233,7 +233,7 @@ func TestBaselineTargetCheck(t *testing.T) {{name: "Exact target matching allows",tokenFacts: []biscuit.Fact{- {Predicate: biscuit.Predicate{Name: FactTargetRestricted}},+ MarkerFact(FactTargetRestricted),{Predicate: biscuit.Predicate{Name: FactGrantedTargetExact, IDs: []biscuit.Term{biscuit.String("group"), biscuit.String("backend")}}},},targetFact: "group",@@ -243,7 +243,7 @@ func TestBaselineTargetCheck(t *testing.T) {{name: "Mismatched target denied when restricted",tokenFacts: []biscuit.Fact{- {Predicate: biscuit.Predicate{Name: FactTargetRestricted}},+ MarkerFact(FactTargetRestricted),{Predicate: biscuit.Predicate{Name: FactGrantedTargetExact, IDs: []biscuit.Term{biscuit.String("group"), biscuit.String("backend")}}},},targetFact: "group",@@ -253,7 +253,7 @@ func TestBaselineTargetCheck(t *testing.T) {{name: "Any target allowed when target_unrestricted",tokenFacts: []biscuit.Fact{- {Predicate: biscuit.Predicate{Name: FactTargetUnrestricted}},+ MarkerFact(FactTargetUnrestricted),},targetFact: "group",targetVal: "any-group",@@ -393,7 +393,7 @@ func TestBuildServiceDatalogFact(t *testing.T) {}{{input: "*",- expected: biscuit.Fact{Predicate: biscuit.Predicate{Name: FactGrantedServiceAllTypes, IDs: []biscuit.Term{}}},+ expected: MarkerFact(FactGrantedServiceAllTypes),},{input: "mcp://*",@@ -428,7 +428,7 @@ func TestBuildTargetDatalogFact(t *testing.T) {}{{input: "*",- expected: biscuit.Fact{Predicate: biscuit.Predicate{Name: FactGrantedTargetAllFacts, IDs: []biscuit.Term{}}},+ expected: MarkerFact(FactGrantedTargetAllFacts),},{input: "user:*",diff --git a/api/policy_rules.go b/api/policy_rules.gonew file mode 100644index 00000000..092b3622--- /dev/null+++ b/api/policy_rules.go@@ -0,0 +1,165 @@+// 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 (+ "fmt"+ "strings"++ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/biscuit-auth/biscuit-go/v2/parser"+)++// PolicyRule is one mesh policy rule in both the form biscuit-go evaluates+// and the Datalog text every other Biscuit implementation parses.+type PolicyRule struct {+ Rule biscuit.Rule+ Text string+}++// BuildPolicyRules turns the mesh policy into the Datalog rules a provider+// adds to its authorizer: bindings grant role() from attested identity facts,+// roles grant granted_* facts from role(). Warnings name entries that were+// skipped or that widen the mesh more than an operator may expect; the caller+// decides how to surface them.+func BuildPolicyRules(roles []*PolicyRole, bindings []*PolicyBinding) (rules []PolicyRule, warnings []string) {+ add := func(head biscuit.Predicate, body ...biscuit.Predicate) {+ r := biscuit.Rule{Head: head, Body: body}+ rules = append(rules, PolicyRule{Rule: r, Text: renderRule(r)})+ }++ // A binding member becomes the body of a rule that grants a mesh role,+ // so only facts the control plane attests in the authority block may+ // appear there: agent() is the caller's own claim, and role() would+ // grant a role from a role.+ allowedMemberPrefix := make(map[string]bool)+ for _, p := range BindingMemberPrefixes() {+ allowedMemberPrefix[p] = true+ }++ for _, b := range bindings {+ if b == nil {+ continue+ }+ roleHead := biscuit.Predicate{Name: FactRole, IDs: []biscuit.Term{biscuit.String(b.Role)}}+ for _, m := range b.Members {+ if m == SystemAuthenticated {+ add(roleHead)+ continue+ }+ parts := strings.SplitN(m, ":", 2)+ if len(parts) == 2 && allowedMemberPrefix[parts[0]] {+ add(roleHead, biscuit.Predicate{Name: parts[0], IDs: []biscuit.Term{biscuit.String(parts[1])}})+ }+ }+ }++ for _, role := range roles {+ if role == nil {+ continue+ }+ roleName := role.Name+ fromRole := biscuit.Predicate{Name: FactRole, IDs: []biscuit.Term{biscuit.String(roleName)}}++ for _, fact := range BuildServiceDatalogFacts(role.AllowedServices) {+ add(fact.Predicate, fromRole)+ }++ hasUnrestricted := false+ var nonWildcardTargets []string+ for _, t := range role.AllowedTargets {+ if t == "*" {+ hasUnrestricted = true+ } else {+ nonWildcardTargets = append(nonWildcardTargets, t)+ }+ }+ if hasUnrestricted {+ add(MarkerFact(FactTargetUnrestricted).Predicate, fromRole)+ }+ if len(nonWildcardTargets) > 0 {+ add(MarkerFact(FactTargetRestricted).Predicate, fromRole)+ }+ for _, fact := range BuildTargetDatalogFacts(nonWildcardTargets) {+ add(fact.Predicate, fromRole)+ }++ for _, fact := range BuildAgentDatalogFacts(role.AllowedAgents) {+ if fact.Name == FactGrantedAgentAll {+ warnings = append(warnings, fmt.Sprintf("Role %s may speak for any agent; any peer holding it can name any agent identity in the mesh", roleName))+ }+ add(fact.Predicate, fromRole)+ }++ // Custom entries keep their source text: it may carry expressions,+ // which biscuit-go cannot print back.+ for _, dl := range role.CustomDatalog {+ trimmed := strings.TrimRight(strings.TrimSpace(dl), ";")+ if trimmed == "" {+ continue+ }+ r, err := parser.FromStringRule(trimmed)+ if err == nil {+ rules = append(rules, PolicyRule{Rule: r, Text: trimmed})+ continue+ }+ f, err2 := parser.FromStringFact(trimmed)+ if err2 == nil {+ add(f.Predicate)+ continue+ }+ warnings = append(warnings, fmt.Sprintf("Failed to parse custom Datalog rule/fact %q for role %s: rule_err=%v, fact_err=%v", dl, roleName, err, err2))+ }+ }++ return rules, warnings+}++// renderRule writes a predicate-only rule as Datalog text. An unconditional+// rule is written `head <- true` so that it stays a rule for every parser.+func renderRule(r biscuit.Rule) string {+ if len(r.Body) == 0 {+ return r.Head.String() + " <- true"+ }+ parts := make([]string, 0, len(r.Body))+ for _, p := range r.Body {+ parts = append(parts, p.String())+ }+ return r.Head.String() + " <- " + strings.Join(parts, ", ")+}++// PolicyRuleTexts is the Datalog text of rules, one entry per rule.+func PolicyRuleTexts(rules []PolicyRule) []string {+ out := make([]string, 0, len(rules))+ for _, r := range rules {+ out = append(out, r.Text)+ }+ return out+}++// ParseDatalogRules parses PolicyConfigGetResponse.datalog_rules. One+// unparseable entry fails the whole set: a provider that silently dropped a+// rule would enforce a policy the operator never wrote.+func ParseDatalogRules(texts []string) ([]biscuit.Rule, error) {+ rules := make([]biscuit.Rule, 0, len(texts))+ for i, text := range texts {+ r, err := parser.FromStringRule(text)+ if err != nil {+ return nil, fmt.Errorf("datalog_rules[%d] %q: %w", i, text, err)+ }+ rules = append(rules, r)+ }+ return rules, nil+}diff --git a/api/policy_rules_test.go b/api/policy_rules_test.gonew file mode 100644index 00000000..6f44a550--- /dev/null+++ b/api/policy_rules_test.go@@ -0,0 +1,106 @@+// 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/parser"+)++func TestBuildPolicyRules(t *testing.T) {+ roles := []*PolicyRole{+ {+ Name: "test-role",+ AllowedTargets: []string{"*", "node:peer-abc", "custom-fact:custom-val", "legacy-peer"},+ AllowedServices: []string{"*:*", "mcp:*", "mcp:*.suffix", "mcp:prefix.*", "mcp:exact"},+ AllowedAgents: []string{"*"},+ CustomDatalog: []string{+ "custom_rule($x) <- fact($x), $x > 3;",+ "custom_fact(\"hello\")",+ "not datalog at all(",+ },+ },+ }+ bindings := []*PolicyBinding{+ {+ Role: "test-role",+ Members: []string{"sam:system:authenticated", "user:alice", "role:admin", "agent:spoofed"},+ },+ }++ rules, warnings := BuildPolicyRules(roles, bindings)++ expectedStrings := map[string]bool{+ "role(\"test-role\") <- true": false,+ "role(\"test-role\") <- user(\"alice\")": false,+ "granted_service_all_types(true) <- role(\"test-role\")": false,+ "granted_service_all(\"mcp\") <- role(\"test-role\")": false,+ "granted_service_suffix(\"mcp\", \".suffix\") <- role(\"test-role\")": false,+ "granted_service_prefix(\"mcp\", \"prefix.\") <- role(\"test-role\")": false,+ "granted_service_set(\"mcp\", [\"exact\"]) <- role(\"test-role\")": false,+ "target_unrestricted(true) <- role(\"test-role\")": false,+ "target_restricted(true) <- role(\"test-role\")": false,+ "granted_target_set(\"node\", [\"legacy-peer\", \"peer-abc\"]) <- role(\"test-role\")": false,+ "granted_target_set(\"custom-fact\", [\"custom-val\"]) <- role(\"test-role\")": false,+ "granted_agent_all(true) <- role(\"test-role\")": false,+ "custom_rule($x) <- fact($x), $x > 3": false,+ "custom_fact(\"hello\") <- true": false,+ }++ for _, rule := range rules {+ if _, ok := expectedStrings[rule.Text]; !ok {+ t.Errorf("Unexpected rule generated: %q", rule.Text)+ continue+ }+ expectedStrings[rule.Text] = true+ // The text is what other implementations parse; it must round-trip here too.+ if _, err := parser.FromStringRule(rule.Text); err != nil {+ t.Errorf("rendered rule %q does not parse: %v", rule.Text, err)+ }+ }++ for k, v := range expectedStrings {+ if !v {+ t.Errorf("Expected rule was not generated: %q", k)+ }+ }++ if len(warnings) != 2 {+ t.Fatalf("warnings = %q, want one for granted_agent_all and one for the unparseable entry", warnings)+ }++ // The text is the contract every member evaluates; it must yield the same+ // rules here as the structured form does.+ parsed, err := ParseDatalogRules(PolicyRuleTexts(rules))+ if err != nil {+ t.Fatalf("ParseDatalogRules: %v", err)+ }+ if len(parsed) != len(rules) {+ t.Fatalf("parsed %d rules from text, built %d", len(parsed), len(rules))+ }+ for i := range rules {+ if parsed[i].Head.String() != rules[i].Rule.Head.String() {+ t.Errorf("rule %d head: text %s, built %s", i, parsed[i].Head.String(), rules[i].Rule.Head.String())+ }+ }+}++func TestParseDatalogRulesRejectsWholeSet(t *testing.T) {+ _, err := ParseDatalogRules([]string{`role("a") <- user("b")`, `broken(`})+ if err == nil {+ t.Fatal("expected an error for an unparseable rule")+ }+}diff --git a/api/sam.pb.go b/api/sam.pb.goindex 3ab2d1fe..f0cd4e4d 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -1525,26 +1525,32 @@ func (x *PolicyBinding) GetMembers() []string {return nil}-type PolicyConfigGetRequest struct {+// PolicyConfig is the mesh policy as the operator writes it: roles and+// bindings. It is the body of POST /policies and the answer of+// GET /admin/policy, both protojson. Only the control plane reads it, to+// mint tokens and to render PolicyConfigGetResponse.+type PolicyConfig struct {state protoimpl.MessageState `protogen:"open.v1"`+ Roles []*PolicyRole `protobuf:"bytes,1,rep,name=roles,proto3" json:"roles,omitempty"`+ Bindings []*PolicyBinding `protobuf:"bytes,2,rep,name=bindings,proto3" json:"bindings,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *PolicyConfigGetRequest) Reset() {- *x = PolicyConfigGetRequest{}+func (x *PolicyConfig) Reset() {+ *x = PolicyConfig{}mi := &file_api_sam_proto_msgTypes[17]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *PolicyConfigGetRequest) String() string {+func (x *PolicyConfig) String() string {return protoimpl.X.MessageStringOf(x)}-func (*PolicyConfigGetRequest) ProtoMessage() {}+func (*PolicyConfig) ProtoMessage() {}-func (x *PolicyConfigGetRequest) ProtoReflect() protoreflect.Message {+func (x *PolicyConfig) ProtoReflect() protoreflect.Message {mi := &file_api_sam_proto_msgTypes[17]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -1556,33 +1562,45 @@ func (x *PolicyConfigGetRequest) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use PolicyConfigGetRequest.ProtoReflect.Descriptor instead.-func (*PolicyConfigGetRequest) Descriptor() ([]byte, []int) {+// Deprecated: Use PolicyConfig.ProtoReflect.Descriptor instead.+func (*PolicyConfig) Descriptor() ([]byte, []int) {return file_api_sam_proto_rawDescGZIP(), []int{17}}-type PolicyConfigGetResponse struct {+func (x *PolicyConfig) GetRoles() []*PolicyRole {+ if x != nil {+ return x.Roles+ }+ return nil+}++func (x *PolicyConfig) GetBindings() []*PolicyBinding {+ if x != nil {+ return x.Bindings+ }+ return nil+}++type PolicyConfigGetRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- Roles []*PolicyRole `protobuf:"bytes,1,rep,name=roles,proto3" json:"roles,omitempty"`- Bindings []*PolicyBinding `protobuf:"bytes,2,rep,name=bindings,proto3" json:"bindings,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *PolicyConfigGetResponse) Reset() {- *x = PolicyConfigGetResponse{}+func (x *PolicyConfigGetRequest) Reset() {+ *x = PolicyConfigGetRequest{}mi := &file_api_sam_proto_msgTypes[18]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *PolicyConfigGetResponse) String() string {+func (x *PolicyConfigGetRequest) String() string {return protoimpl.X.MessageStringOf(x)}-func (*PolicyConfigGetResponse) ProtoMessage() {}+func (*PolicyConfigGetRequest) ProtoMessage() {}-func (x *PolicyConfigGetResponse) ProtoReflect() protoreflect.Message {+func (x *PolicyConfigGetRequest) ProtoReflect() protoreflect.Message {mi := &file_api_sam_proto_msgTypes[18]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -1594,47 +1612,36 @@ func (x *PolicyConfigGetResponse) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use PolicyConfigGetResponse.ProtoReflect.Descriptor instead.-func (*PolicyConfigGetResponse) Descriptor() ([]byte, []int) {+// Deprecated: Use PolicyConfigGetRequest.ProtoReflect.Descriptor instead.+func (*PolicyConfigGetRequest) Descriptor() ([]byte, []int) {return file_api_sam_proto_rawDescGZIP(), []int{18}}-func (x *PolicyConfigGetResponse) GetRoles() []*PolicyRole {- if x != nil {- return x.Roles- }- return nil-}--func (x *PolicyConfigGetResponse) GetBindings() []*PolicyBinding {- if x != nil {- return x.Bindings- }- return nil-}--type PolicyConfigUpdateRequest struct {- state protoimpl.MessageState `protogen:"open.v1"`- Roles []*PolicyRole `protobuf:"bytes,1,rep,name=roles,proto3" json:"roles,omitempty"`- Bindings []*PolicyBinding `protobuf:"bytes,2,rep,name=bindings,proto3" json:"bindings,omitempty"`+// PolicyConfigGetResponse answers GET /policies for a mesh member holding a+// biscuit. It carries the policy only as Datalog text: this is the contract+// every member evaluates, and none derives rules from roles and bindings.+type PolicyConfigGetResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // One rule per entry, rendered by the control plane with api.BuildPolicyRules.+ DatalogRules []string `protobuf:"bytes,3,rep,name=datalog_rules,json=datalogRules,proto3" json:"datalog_rules,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *PolicyConfigUpdateRequest) Reset() {- *x = PolicyConfigUpdateRequest{}+func (x *PolicyConfigGetResponse) Reset() {+ *x = PolicyConfigGetResponse{}mi := &file_api_sam_proto_msgTypes[19]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *PolicyConfigUpdateRequest) String() string {+func (x *PolicyConfigGetResponse) String() string {return protoimpl.X.MessageStringOf(x)}-func (*PolicyConfigUpdateRequest) ProtoMessage() {}+func (*PolicyConfigGetResponse) ProtoMessage() {}-func (x *PolicyConfigUpdateRequest) ProtoReflect() protoreflect.Message {+func (x *PolicyConfigGetResponse) ProtoReflect() protoreflect.Message {mi := &file_api_sam_proto_msgTypes[19]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -1646,21 +1653,14 @@ func (x *PolicyConfigUpdateRequest) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use PolicyConfigUpdateRequest.ProtoReflect.Descriptor instead.-func (*PolicyConfigUpdateRequest) Descriptor() ([]byte, []int) {+// Deprecated: Use PolicyConfigGetResponse.ProtoReflect.Descriptor instead.+func (*PolicyConfigGetResponse) Descriptor() ([]byte, []int) {return file_api_sam_proto_rawDescGZIP(), []int{19}}-func (x *PolicyConfigUpdateRequest) GetRoles() []*PolicyRole {+func (x *PolicyConfigGetResponse) GetDatalogRules() []string {if x != nil {- return x.Roles- }- return nil-}--func (x *PolicyConfigUpdateRequest) GetBindings() []*PolicyBinding {- if x != nil {- return x.Bindings+ return x.DatalogRules}return nil}@@ -3152,14 +3152,13 @@ const file_api_sam_proto_rawDesc = "" +"\x0eallowed_labels\x18\x06 \x03(\tR\rallowedLabels\"=\n" +"\rPolicyBinding\x12\x12\n" +"\x04role\x18\x01 \x01(\tR\x04role\x12\x18\n" +- "\amembers\x18\x02 \x03(\tR\amembers\"\x18\n" +- "\x16PolicyConfigGetRequest\"v\n" +- "\x17PolicyConfigGetResponse\x12(\n" +- "\x05roles\x18\x01 \x03(\v2\x12.sam.v1.PolicyRoleR\x05roles\x121\n" +- "\bbindings\x18\x02 \x03(\v2\x15.sam.v1.PolicyBindingR\bbindings\"x\n" +- "\x19PolicyConfigUpdateRequest\x12(\n" ++ "\amembers\x18\x02 \x03(\tR\amembers\"k\n" ++ "\fPolicyConfig\x12(\n" +"\x05roles\x18\x01 \x03(\v2\x12.sam.v1.PolicyRoleR\x05roles\x121\n" +- "\bbindings\x18\x02 \x03(\v2\x15.sam.v1.PolicyBindingR\bbindings\"L\n" ++ "\bbindings\x18\x02 \x03(\v2\x15.sam.v1.PolicyBindingR\bbindings\"\x18\n" ++ "\x16PolicyConfigGetRequest\"[\n" ++ "\x17PolicyConfigGetResponse\x12#\n" ++ "\rdatalog_rules\x18\x03 \x03(\tR\fdatalogRulesJ\x04\b\x01\x10\x02J\x04\b\x02\x10\x03R\x05rolesR\bbindings\"L\n" +"\x1aPolicyConfigUpdateResponse\x12\x18\n" +"\asuccess\x18\x01 \x01(\bR\asuccess\x12\x14\n" +"\x05error\x18\x02 \x01(\tR\x05error\"m\n" +@@ -3307,9 +3306,9 @@ var file_api_sam_proto_goTypes = []any{(*RouterLeaseResponse)(nil), // 17: sam.v1.RouterLeaseResponse(*PolicyRole)(nil), // 18: sam.v1.PolicyRole(*PolicyBinding)(nil), // 19: sam.v1.PolicyBinding- (*PolicyConfigGetRequest)(nil), // 20: sam.v1.PolicyConfigGetRequest- (*PolicyConfigGetResponse)(nil), // 21: sam.v1.PolicyConfigGetResponse- (*PolicyConfigUpdateRequest)(nil), // 22: sam.v1.PolicyConfigUpdateRequest+ (*PolicyConfig)(nil), // 20: sam.v1.PolicyConfig+ (*PolicyConfigGetRequest)(nil), // 21: sam.v1.PolicyConfigGetRequest+ (*PolicyConfigGetResponse)(nil), // 22: sam.v1.PolicyConfigGetResponse(*PolicyConfigUpdateResponse)(nil), // 23: sam.v1.PolicyConfigUpdateResponse(*KeysResponse)(nil), // 24: sam.v1.KeysResponse(*TokenRefreshRequest)(nil), // 25: sam.v1.TokenRefreshRequest@@ -3349,24 +3348,22 @@ var file_api_sam_proto_depIdxs = []int32{11, // 7: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend1, // 8: sam.v1.ServiceAnnounce.type:type_name -> sam.v1.ServiceType48, // 9: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry- 18, // 10: sam.v1.PolicyConfigGetResponse.roles:type_name -> sam.v1.PolicyRole- 19, // 11: sam.v1.PolicyConfigGetResponse.bindings:type_name -> sam.v1.PolicyBinding- 18, // 12: sam.v1.PolicyConfigUpdateRequest.roles:type_name -> sam.v1.PolicyRole- 19, // 13: sam.v1.PolicyConfigUpdateRequest.bindings:type_name -> sam.v1.PolicyBinding- 10, // 14: sam.v1.NodeCatalogReport.services:type_name -> sam.v1.ServiceInfo- 30, // 15: sam.v1.AgentEgress.secrets:type_name -> sam.v1.AgentSecret- 1, // 16: sam.v1.AgentIngress.type:type_name -> sam.v1.ServiceType- 31, // 17: sam.v1.AgentBundle.egress:type_name -> sam.v1.AgentEgress- 32, // 18: sam.v1.AgentBundle.ingress:type_name -> sam.v1.AgentIngress- 33, // 19: sam.v1.AgentAttachRequest.bundle:type_name -> sam.v1.AgentBundle- 32, // 20: sam.v1.AgentStatus.ingress:type_name -> sam.v1.AgentIngress- 41, // 21: sam.v1.AgentStatusResponse.agents:type_name -> sam.v1.AgentStatus- 49, // 22: sam.v1.PeerEvidenceResponse.labels:type_name -> sam.v1.PeerEvidenceResponse.LabelsEntry- 23, // [23:23] is the sub-list for method output_type- 23, // [23:23] is the sub-list for method input_type- 23, // [23:23] is the sub-list for extension type_name- 23, // [23:23] is the sub-list for extension extendee- 0, // [0:23] is the sub-list for field type_name+ 18, // 10: sam.v1.PolicyConfig.roles:type_name -> sam.v1.PolicyRole+ 19, // 11: sam.v1.PolicyConfig.bindings:type_name -> sam.v1.PolicyBinding+ 10, // 12: sam.v1.NodeCatalogReport.services:type_name -> sam.v1.ServiceInfo+ 30, // 13: sam.v1.AgentEgress.secrets:type_name -> sam.v1.AgentSecret+ 1, // 14: sam.v1.AgentIngress.type:type_name -> sam.v1.ServiceType+ 31, // 15: sam.v1.AgentBundle.egress:type_name -> sam.v1.AgentEgress+ 32, // 16: sam.v1.AgentBundle.ingress:type_name -> sam.v1.AgentIngress+ 33, // 17: sam.v1.AgentAttachRequest.bundle:type_name -> sam.v1.AgentBundle+ 32, // 18: sam.v1.AgentStatus.ingress:type_name -> sam.v1.AgentIngress+ 41, // 19: sam.v1.AgentStatusResponse.agents:type_name -> sam.v1.AgentStatus+ 49, // 20: sam.v1.PeerEvidenceResponse.labels:type_name -> sam.v1.PeerEvidenceResponse.LabelsEntry+ 21, // [21:21] is the sub-list for method output_type+ 21, // [21:21] is the sub-list for method input_type+ 21, // [21:21] is the sub-list for extension type_name+ 21, // [21:21] is the sub-list for extension extendee+ 0, // [0:21] is the sub-list for field type_name}func init() { file_api_sam_proto_init() }diff --git a/api/sam.proto b/api/sam.protoindex b89bb3ad..6610b10b 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -230,16 +230,27 @@ message PolicyBinding {repeated string members = 2;}-message PolicyConfigGetRequest {}--message PolicyConfigGetResponse {+// PolicyConfig is the mesh policy as the operator writes it: roles and+// bindings. It is the body of POST /policies and the answer of+// GET /admin/policy, both protojson. Only the control plane reads it, to+// mint tokens and to render PolicyConfigGetResponse.+message PolicyConfig {repeated PolicyRole roles = 1;repeated PolicyBinding bindings = 2;}-message PolicyConfigUpdateRequest {- repeated PolicyRole roles = 1;- repeated PolicyBinding bindings = 2;+message PolicyConfigGetRequest {}++// PolicyConfigGetResponse answers GET /policies for a mesh member holding a+// biscuit. It carries the policy only as Datalog text: this is the contract+// every member evaluates, and none derives rules from roles and bindings.+message PolicyConfigGetResponse {+ // roles and bindings once travelled here; they are the operator's document+ // now (PolicyConfig). Reserved so an old sender is detected, not misread.+ reserved 1, 2;+ reserved "roles", "bindings";+ // One rule per entry, rendered by the control plane with api.BuildPolicyRules.+ repeated string datalog_rules = 3;}message PolicyConfigUpdateResponse {diff --git a/cmd/sam-one/main.go b/cmd/sam-one/main.goindex 8a859f78..0eeebb0f 100644--- a/cmd/sam-one/main.go+++ b/cmd/sam-one/main.go@@ -196,7 +196,7 @@ func main() {rootCmd.Flags().StringVar(&joinTokenPath, "token-path", "", "File containing the cluster join token (or env SAM_TOKEN; auto-generated and persisted in --data-dir if neither is set)")rootCmd.Flags().BoolVar(&noJoinToken, "no-join-token", false, "Run without a standing join token; devices enroll only with minted bootstrap tokens (token create/qr) or OIDC")rootCmd.Flags().StringVar(&adminTokenPath, "admin-token-path", "", "File containing the admin API bearer token (or env SAM_ADMIN_TOKEN; auto-generated and persisted in --data-dir if neither is set)")- rootCmd.Flags().StringVar(&policyFile, "policy-file", "", "Path to a protojson PolicyConfigUpdateRequest seeding the mesh policy on first boot only")+ rootCmd.Flags().StringVar(&policyFile, "policy-file", "", "Path to a protojson PolicyConfig seeding the mesh policy on first boot only")rootCmd.Flags().StringVar(&oidcIssuer, "issuer", "", "Optional external OIDC issuer URL (comma-separated)")rootCmd.Flags().StringVar(&oidcClientID, "oidc-client-id", "", "OAuth client id advertised via /info (defaults to the first allowed audience)")rootCmd.Flags().StringVar(&allowedAudiencesFlag, "allowed-audiences", api.DefaultAudience, "Comma-separated list of allowed OIDC audiences")diff --git a/hack/gen-sdk-datalog/main.go b/hack/gen-sdk-datalog/main.gonew file mode 100644index 00000000..39172347--- /dev/null+++ b/hack/gen-sdk-datalog/main.go@@ -0,0 +1,84 @@+// 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.++// Command gen-sdk-datalog writes the baseline Datalog a mesh member evaluates+// when it authorizes a caller, as api/datalog.go defines it, into the JSON+// artifact the native SDKs embed. Go stays the source of truth;+// hack/verify-sdk-generated.sh fails when the artifact is stale.+package main++import (+ "bytes"+ "encoding/json"+ "fmt"+ "os"+ "strings"++ "github.com/google/sam/api"+)++type artifact struct {+ Comment string `json:"_comment"`+ api.DatalogSources+ FactService string `json:"fact_service"`+ FactConnectionPeer string `json:"fact_connection_peer_id"`+ FactAgent string `json:"fact_agent"`+ FactTime string `json:"fact_time"`+ FactRole string `json:"fact_role"`+ FactTargetFact string `json:"fact_target_fact"`+ MarkerTerm string `json:"marker_term"`+ SystemNamespace string `json:"system_namespace"`+ BindingPrefixes []string `json:"binding_member_prefixes"`+ SystemAuthenticated string `json:"system_authenticated_member"`+}++func main() {+ if len(os.Args) != 3 {+ fmt.Fprintln(os.Stderr, "usage: gen-sdk-datalog <output.json> <output.ts>")+ os.Exit(2)+ }+ a := artifact{+ Comment: "Generated by hack/gen-sdk-datalog from api/datalog.go; do not edit.",+ DatalogSources: api.BaselineSources,+ FactService: api.FactService,+ FactConnectionPeer: api.FactConnectionPeerID,+ FactAgent: api.FactAgent,+ FactTime: api.FactTime,+ FactRole: api.FactRole,+ FactTargetFact: api.FactTargetFact,+ MarkerTerm: api.MarkerTerm.String(),+ SystemNamespace: api.SystemNamespace,+ BindingPrefixes: api.BindingMemberPrefixes(),+ SystemAuthenticated: api.SystemAuthenticated,+ }+ var buf bytes.Buffer+ enc := json.NewEncoder(&buf)+ enc.SetEscapeHTML(false)+ enc.SetIndent("", " ")+ if err := enc.Encode(a); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ if err := os.WriteFile(os.Args[1], buf.Bytes(), 0o644); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ ts := "// Code generated by hack/gen-sdk-datalog from api/datalog.go; DO NOT EDIT.\n\n" ++ "/** The Datalog a provider evaluates against a caller's biscuit. */\n" ++ "export const BASELINE_DATALOG = " + strings.TrimRight(buf.String(), "\n") + " as const;\n"+ if err := os.WriteFile(os.Args[2], []byte(ts), 0o644); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+}diff --git a/hack/gen-sdk-proto.sh b/hack/gen-sdk-proto.shindex 1ee24c46..f2edf889 100755--- a/hack/gen-sdk-proto.sh+++ b/hack/gen-sdk-proto.sh@@ -14,8 +14,9 @@# limitations under the License.# Regenerates the protobuf bindings the native SDKs under sdk/ ship for-# api/sam.proto. The Go bindings are gen-proto.sh's job. Requires protoc-# and, for JavaScript, an `npm install` in sdk/js (protoc-gen-es).+# api/sam.proto, and the baseline Datalog artifact from api/datalog.go. The+# Go bindings are gen-proto.sh's job. Requires protoc and, for JavaScript,+# an `npm install` in sdk/js (protoc-gen-es).set -o errexitset -o nounset@@ -26,6 +27,7 @@ cd "${REPO_ROOT}"JS_GEN_DIR="sdk/js/src/gen"PY_GEN_DIR="sdk/python/src/agent_mesh/_proto"+PY_DATALOG_DIR="sdk/python/src/agent_mesh/_gen"PROTOC_GEN_ES="sdk/js/node_modules/.bin/protoc-gen-es"if [[ ! -x "${PROTOC_GEN_ES}" ]]; then@@ -54,4 +56,8 @@ protoc -I sdk/python/proto \--pyi_out="${PY_GEN_DIR}" \sdk/python/proto/circuit.proto+echo "Generating baseline Datalog artifact..."+mkdir -p "${PY_DATALOG_DIR}"+go run ./hack/gen-sdk-datalog "${PY_DATALOG_DIR}/datalog.json" "${JS_GEN_DIR}/datalog.ts"+echo "SDK protobuf generation complete."diff --git a/hack/verify-sdk-generated.sh b/hack/verify-sdk-generated.shindex 24763980..1c469ad7 100755--- a/hack/verify-sdk-generated.sh+++ b/hack/verify-sdk-generated.sh@@ -13,8 +13,9 @@# See the License for the specific language governing permissions and# limitations under the License.-# Fails when the protobuf bindings the SDKs ship are stale relative to-# api/sam.proto. Regenerates in place, so run it on a clean checkout.+# Fails when the protobuf bindings or the baseline Datalog artifact the SDKs+# ship are stale relative to api/. Regenerates in place, so run it on a+# clean checkout.set -o errexitset -o nounset@@ -23,13 +24,13 @@ set -o pipefailREPO_ROOT=$(git rev-parse --show-toplevel)cd "${REPO_ROOT}"-GENERATED=(sdk/js/src/gen sdk/python/src/agent_mesh/_proto)+GENERATED=(sdk/js/src/gen sdk/python/src/agent_mesh/_proto sdk/python/src/agent_mesh/_gen)./hack/gen-sdk-proto.shif ! git diff --exit-code -- "${GENERATED[@]}"; then- echo "ERROR: SDK protobuf bindings are not up to date."+ echo "ERROR: SDK generated files are not up to date."echo "Run ./hack/gen-sdk-proto.sh and commit the result."exit 1fi-echo "SDK protobuf bindings are up to date."+echo "SDK generated files are up to date."diff --git a/internal/controlplane/client/client.go b/internal/controlplane/client/client.goindex 723cbdf0..4aa46304 100644--- a/internal/controlplane/client/client.go+++ b/internal/controlplane/client/client.go@@ -131,7 +131,7 @@ func (c *Client) FetchKeys(ctx context.Context, trusted []ed25519.PublicKey) ([]}// FetchPolicy is GET /policies, authenticated with the caller's biscuit: the-// roles and bindings a node compiles into its authorization rules.+// mesh policy as the Datalog rules a member adds to its authorizer.func (c *Client) FetchPolicy(ctx context.Context, biscuit []byte) (*api.PolicyConfigGetResponse, error) {var policy api.PolicyConfigGetResponseif err := c.get(ctx, "/policies", biscuit, &policy); err != nil {diff --git a/internal/controlplane/client/client_test.go b/internal/controlplane/client/client_test.goindex cd949070..8bcd3978 100644--- a/internal/controlplane/client/client_test.go+++ b/internal/controlplane/client/client_test.go@@ -268,8 +268,7 @@ func TestLargeAnswersArriveWhole(t *testing.T) {func TestFetchPolicy(t *testing.T) {want := &api.PolicyConfigGetResponse{- Roles: []*api.PolicyRole{{Name: "developer", AllowedServices: []string{"mcp://*"}}},- Bindings: []*api.PolicyBinding{{Role: "developer", Members: []string{"group:eng"}}},+ DatalogRules: []string{`role("developer") <- group("eng")`, `granted_service_all("mcp") <- role("developer")`},}var gotAuth stringsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/internal/controlplane/identity_lifecycle_test.go b/internal/controlplane/identity_lifecycle_test.goindex 441a6d14..6ecb1eec 100644--- a/internal/controlplane/identity_lifecycle_test.go+++ b/internal/controlplane/identity_lifecycle_test.go@@ -569,7 +569,7 @@ func TestNoPolicyMintsNoGrants(t *testing.T) {}for _, open := range []string{api.FactGrantedServiceAllTypes, api.FactTargetUnrestricted} {if authorityHasFact(t, data, open+"(") {- t.Errorf("token minted under an empty policy carries %s()", open)+ t.Errorf("token minted under an empty policy carries %s(true)", open)}}if !authorityHasFact(t, data, api.FactRole+`("`+api.RoleNode+`")`) {diff --git a/internal/controlplane/policies_admission_test.go b/internal/controlplane/policies_admission_test.goindex bf034161..9b146044 100644--- a/internal/controlplane/policies_admission_test.go+++ b/internal/controlplane/policies_admission_test.go@@ -20,6 +20,7 @@ import ("encoding/base64""io""net/http"+ "slices""testing""time"@@ -104,7 +105,21 @@ func TestPoliciesRequiresAnAdmissibleNode(t *testing.T) {if err != nil {t.Fatalf("GET /policies failed: %v", err)}+ body, _ := io.ReadAll(resp.Body)_ = resp.Body.Close()+ if resp.StatusCode == http.StatusOK {+ // What a member receives is the policy as Datalog text and nothing else.+ var policy api.PolicyConfigGetResponse+ if err := proto.Unmarshal(body, &policy); err != nil {+ t.Fatalf("decoding PolicyConfigGetResponse: %v", err)+ }+ if want := `role("sam:role:node") <- group("users")`; !slices.Contains(policy.DatalogRules, want) {+ t.Errorf("datalog_rules = %q, want it to contain %q", policy.DatalogRules, want)+ }+ if len(policy.ProtoReflect().GetUnknown()) > 0 {+ t.Errorf("policy response carries fields outside the contract: %x", policy.ProtoReflect().GetUnknown())+ }+ }return resp.StatusCode}diff --git a/internal/controlplane/policy_scale_test.go b/internal/controlplane/policy_scale_test.goindex 3dc277c9..974f6f86 100644--- a/internal/controlplane/policy_scale_test.go+++ b/internal/controlplane/policy_scale_test.go@@ -93,7 +93,7 @@ func TestPolicyScale(t *testing.T) {Members: []string{"node:" + nodePeer.String()},})}- req := &api.PolicyConfigUpdateRequest{Roles: roles, Bindings: bindings}+ req := &api.PolicyConfig{Roles: roles, Bindings: bindings}start := time.Now()if err := validatePolicyConfig(req); err != nil {@@ -194,7 +194,7 @@ func TestPolicyScaleSetEncoding(t *testing.T) {// admin-time fact budget guard, since Set-based encoding collapses it// to a couple of facts regardless of entry count.bindings := []*api.PolicyBinding{{Role: "bulk-role", Members: []string{"node:" + nodePeer.String()}}}- if err := validatePolicyConfig(&api.PolicyConfigUpdateRequest{Roles: roles, Bindings: bindings}); err != nil {+ if err := validatePolicyConfig(&api.PolicyConfig{Roles: roles, Bindings: bindings}); err != nil {t.Fatalf("validatePolicyConfig unexpectedly rejected a single bulk role with n=%d exact entries: %v", n, err)}@@ -242,7 +242,7 @@ func TestValidatePolicyConfigFactBudget(t *testing.T) {t.Run("rejects a config that could push a single identity over the fact budget", func(t *testing.T) {roles, bindings := newRoles(500)- err := validatePolicyConfig(&api.PolicyConfigUpdateRequest{Roles: roles, Bindings: bindings})+ err := validatePolicyConfig(&api.PolicyConfig{Roles: roles, Bindings: bindings})if err == nil {t.Fatal("expected validatePolicyConfig to reject an over-budget config, got nil error")}@@ -253,7 +253,7 @@ func TestValidatePolicyConfigFactBudget(t *testing.T) {t.Run("accepts a config comfortably under the fact budget", func(t *testing.T) {roles, bindings := newRoles(50)- if err := validatePolicyConfig(&api.PolicyConfigUpdateRequest{Roles: roles, Bindings: bindings}); err != nil {+ if err := validatePolicyConfig(&api.PolicyConfig{Roles: roles, Bindings: bindings}); err != nil {t.Errorf("expected a small config to pass validation, got: %v", err)}})diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 54023db8..60bf8f60 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -245,6 +245,7 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {handle("/admin/nodes/", noStore(s.HandleAdminNodeAction))handle("/admin/revoke", noStore(s.HandleAdminRevoke))handle("/admin/status", noStore(s.HandleAdminStatus))+ handle("/admin/policy", noStore(s.HandleAdminPolicy))handle("/user/status", noStore(s.HandleUserStatus))handle("/user/bootstrap-tokens", noStore(s.HandleUserBootstrapTokens))handle("/user/revoke", noStore(s.HandleUserRevoke))@@ -1152,36 +1153,13 @@ func (s *Server) HandleRouterLease(w http.ResponseWriter, r *http.Request) {// HandlePolicies HTTP GET/POST/PUT `/policies`func (s *Server) HandlePolicies(w http.ResponseWriter, r *http.Request) {- // Simple HTTP admin methods for policiesswitch r.Method {case http.MethodGet:- // Nodes fetch policies with their biscuit, admins with the admin token- // or an ID token. The biscuit is tried first: running OIDC- // verification on a biscuit logs a failure and would auto-register- // whoever's ID token lands here.- isNode := false- if authHeader := r.Header.Get("Authorization"); strings.HasPrefix(authHeader, "Bearer ") {- if biscuitBytes, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Bearer ")); err == nil {- if trustedKeys, err := s.store.GetAllValidPublicKeys(r.Context()); err == nil {- if peerID, err := identity.VerifyAndExtractPeerID(trustedKeys, biscuitBytes, s.config.BiscuitTimeout); err == nil {- nodeRecord, nodeErr := s.store.GetNode(r.Context(), peerID.String())- if nodeErr == nil && nodeRecord != nil && nodeRecord.CheckAdmission(time.Now()) == nil {- isNode = true- }- }- }- }- }-- isAdmin := false- if !isNode {- if user, err := s.authenticateUser(r); err == nil && user.Role == "admin" {- isAdmin = true- }- }-- if !isAdmin && !isNode {- http.Error(w, "Unauthorized: Admin or Node authentication required", http.StatusUnauthorized)+ // Mesh protocol: an admitted member fetches the policy with its biscuit+ // and receives it as Datalog text only. Operators read the document at+ // GET /admin/policy.+ if !s.isAdmittedNodeRequest(r) {+ http.Error(w, "Unauthorized: node credential required", http.StatusUnauthorized)return}@@ -1192,11 +1170,11 @@ func (s *Server) HandlePolicies(w http.ResponseWriter, r *http.Request) {return}- resp := &api.PolicyConfigGetResponse{- Roles: roles,- Bindings: bindings,+ policyRules, warnings := api.BuildPolicyRules(roles, bindings)+ for _, warning := range warnings {+ logger.Warnf("mesh policy: %s", warning)}- respData, _ := proto.Marshal(resp)+ respData, _ := proto.Marshal(&api.PolicyConfigGetResponse{DatalogRules: api.PolicyRuleTexts(policyRules)})w.Header().Set("Content-Type", "application/x-protobuf")w.WriteHeader(http.StatusOK)_, _ = w.Write(respData)@@ -1213,8 +1191,9 @@ func (s *Server) HandlePolicies(w http.ResponseWriter, r *http.Request) {}defer func() { _ = r.Body.Close() }()- req := &api.PolicyConfigUpdateRequest{}- if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {+ req := &api.PolicyConfig{}+ isJSON := strings.HasPrefix(r.Header.Get("Content-Type"), "application/json")+ if isJSON {// Strict: an unknown field here is a typo like "allowed_service", and// discarding it would quietly drop the permission it was meant to grant.if err := protojson.Unmarshal(body, req); err != nil {@@ -1244,6 +1223,10 @@ func (s *Server) HandlePolicies(w http.ResponseWriter, r *http.Request) {}resp := &api.PolicyConfigUpdateResponse{Success: true}+ if isJSON {+ writeProtoJSON(w, resp)+ return+ }respData, _ := proto.Marshal(resp)w.Header().Set("Content-Type", "application/x-protobuf")w.WriteHeader(http.StatusOK)@@ -1254,6 +1237,64 @@ func (s *Server) HandlePolicies(w http.ResponseWriter, r *http.Request) {}}+// isAdmittedNodeRequest reports whether the bearer credential is a biscuit of+// an enrolled, admitted node. It never falls through to OIDC: running ID token+// verification on a biscuit logs a failure and would auto-register whoever's+// ID token lands here.+func (s *Server) isAdmittedNodeRequest(r *http.Request) bool {+ authHeader := r.Header.Get("Authorization")+ if !strings.HasPrefix(authHeader, "Bearer ") {+ return false+ }+ biscuitBytes, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Bearer "))+ if err != nil {+ return false+ }+ trustedKeys, err := s.store.GetAllValidPublicKeys(r.Context())+ if err != nil {+ return false+ }+ peerID, err := identity.VerifyAndExtractPeerID(trustedKeys, biscuitBytes, s.config.BiscuitTimeout)+ if err != nil {+ return false+ }+ nodeRecord, err := s.store.GetNode(r.Context(), peerID.String())+ return err == nil && nodeRecord != nil && nodeRecord.CheckAdmission(time.Now()) == nil+}++// HandleAdminPolicy HTTP GET `/admin/policy`: the mesh policy as the operator+// wrote it, protojson of PolicyConfig, the same document POST /policies takes.+func (s *Server) HandleAdminPolicy(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ if !s.checkAdminAuth(w, r) {+ return+ }+ roles, bindings, err := s.store.GetMeshPolicy(r.Context())+ if err != nil && err != storage.ErrNotFound {+ logger.Errorf("Failed to load policy: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }+ writeProtoJSON(w, &api.PolicyConfig{Roles: roles, Bindings: bindings})+}++// writeProtoJSON answers an operator-plane request with protojson of msg,+// using the proto field names the console and the docs show.+func writeProtoJSON(w http.ResponseWriter, msg proto.Message) {+ out, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(msg)+ if err != nil {+ logger.Errorf("Failed to render %T: %v", msg, err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(out)+}+// Close shuts down background loops and HTTP server.func (s *Server) Close() error {s.shutdown = true@@ -2845,7 +2886,7 @@ func toStringSlice(val any) []string {// PolicyRole silently drops any field it forgets, which is how custom_datalog// went missing from the console for so long.func marshalPolicyJSON(roles []*api.PolicyRole, bindings []*api.PolicyBinding) (string, error) {- resp := &api.PolicyConfigGetResponse{Roles: roles, Bindings: bindings}+ resp := &api.PolicyConfig{Roles: roles, Bindings: bindings}marshaler := protojson.MarshalOptions{UseProtoNames: true, Multiline: true, Indent: " "}out, err := marshaler.Marshal(resp)if err != nil {@@ -2864,11 +2905,11 @@ const maxIdentityFactBudget = 900// ValidatePolicyConfig checks a mesh policy the way POST /policies does; any// other writer of the policy (e.g. a seed file) must run it too.-func ValidatePolicyConfig(req *api.PolicyConfigUpdateRequest) error {+func ValidatePolicyConfig(req *api.PolicyConfig) error {return validatePolicyConfig(req)}-func validatePolicyConfig(req *api.PolicyConfigUpdateRequest) error {+func validatePolicyConfig(req *api.PolicyConfig) error {roleNames := make(map[string]bool)factBudget := 0for _, r := range req.Roles {diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.goindex a36407a0..f66ab779 100644--- a/internal/controlplane/server_test.go+++ b/internal/controlplane/server_test.go@@ -593,7 +593,7 @@ func TestMarshalPolicyJSONRoundTrip(t *testing.T) {}// Exactly what the console posts back.- parsed := &api.PolicyConfigUpdateRequest{}+ parsed := &api.PolicyConfig{}if err := protojson.Unmarshal([]byte(rendered), parsed); err != nil {t.Fatalf("parsing back the rendered policy: %v\n%s", err, rendered)}@@ -768,20 +768,42 @@ func TestPoliciesConfigurationREST(t *testing.T) {}_ = resp.Body.Close()- // 3. Get policies with correct token (should return 404 since none exists)+ // 3. The admin token is not a node credential: GET /policies is the mesh+ // protocol, operators read the document at GET /admin/policy.req, _ = http.NewRequest(http.MethodGet, baseURL+"/policies", nil)req.Header.Set("Authorization", "Bearer super-secret-admin-token")resp, err = client.Do(req)if err != nil {t.Fatalf("GET /policies failed: %v", err)}+ if resp.StatusCode != http.StatusUnauthorized {+ t.Errorf("expected 401 for admin token at GET /policies, got %d", resp.StatusCode)+ }+ _ = resp.Body.Close()++ req, _ = http.NewRequest(http.MethodGet, baseURL+"/admin/policy", nil)+ resp, err = client.Do(req)+ if err != nil {+ t.Fatalf("GET /admin/policy failed: %v", err)+ }+ if resp.StatusCode != http.StatusUnauthorized {+ t.Errorf("expected 401 for unauthenticated GET /admin/policy, got %d", resp.StatusCode)+ }+ _ = resp.Body.Close()++ req, _ = http.NewRequest(http.MethodGet, baseURL+"/admin/policy", nil)+ req.Header.Set("Authorization", "Bearer super-secret-admin-token")+ resp, err = client.Do(req)+ if err != nil {+ t.Fatalf("GET /admin/policy failed: %v", err)+ }if resp.StatusCode != http.StatusOK {t.Errorf("expected 200 for empty policy, got %d", resp.StatusCode)}_ = resp.Body.Close()// 4. Put policies (should succeed)- updateReq := &api.PolicyConfigUpdateRequest{+ updateReq := &api.PolicyConfig{Roles: []*api.PolicyRole{{Name: "dev",@@ -807,29 +829,32 @@ func TestPoliciesConfigurationREST(t *testing.T) {}_ = resp.Body.Close()- // 5. Get policies again with correct token (verify content)- req, _ = http.NewRequest(http.MethodGet, baseURL+"/policies", nil)+ // 5. Read the document back as the operator sees it: protojson of+ // PolicyConfig, which is exactly what POST /policies accepts.+ req, _ = http.NewRequest(http.MethodGet, baseURL+"/admin/policy", nil)req.Header.Set("Authorization", "Bearer super-secret-admin-token")resp, err = client.Do(req)if err != nil {- t.Fatalf("GET /policies failed: %v", err)+ t.Fatalf("GET /admin/policy failed: %v", err)}if resp.StatusCode != http.StatusOK {- t.Fatalf("GET /policies status failed: %s", resp.Status)+ t.Fatalf("GET /admin/policy status failed: %s", resp.Status)+ }+ if ct := resp.Header.Get("Content-Type"); ct != "application/json" {+ t.Errorf("GET /admin/policy Content-Type = %q, want application/json", ct)}body, _ := io.ReadAll(resp.Body)_ = resp.Body.Close()- var getResp api.PolicyConfigGetResponse- if err := proto.Unmarshal(body, &getResp); err != nil {- t.Fatalf("failed to unmarshal PolicyConfigGetResponse: %v", err)+ var getResp api.PolicyConfig+ if err := protojson.Unmarshal(body, &getResp); err != nil {+ t.Fatalf("failed to unmarshal PolicyConfig: %v\n%s", err, body)}-- if len(getResp.Roles) == 0 || getResp.Roles[0].Name != "dev" {- t.Errorf("returned policy content mismatch: %+v", getResp.Roles)+ if !strings.Contains(string(body), "allowed_services") {+ t.Errorf("GET /admin/policy does not use proto field names:\n%s", body)}- if len(getResp.Bindings) == 0 || getResp.Bindings[0].Members[0] != "group:developers" {- t.Errorf("returned policy content mismatch: %+v", getResp.Bindings)+ if !proto.Equal(&getResp, updateReq) {+ t.Errorf("GET /admin/policy = %v, want the posted document %v", &getResp, updateReq)}}diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.goindex 73247c39..f4556274 100644--- a/internal/identity/biscuit.go+++ b/internal/identity/biscuit.go@@ -258,10 +258,7 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []stri}}); err != nil {errs = append(errs, fmt.Errorf("failed to add relay right: %w", err))}- if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactTargetUnrestricted,- IDs: []biscuit.Term{},- }}); err != nil {+ if err := addFact(api.MarkerFact(api.FactTargetUnrestricted)); err != nil {errs = append(errs, fmt.Errorf("failed to add target unrestricted: %w", err))}continuediff --git a/internal/identity/biscuit_test.go b/internal/identity/biscuit_test.goindex aef24b6b..ec523f6d 100644--- a/internal/identity/biscuit_test.go+++ b/internal/identity/biscuit_test.go@@ -481,7 +481,7 @@ func TestMintBiscuitToken_WithPolicyRoles(t *testing.T) {// Verify target_unrestricted and granted_service_all_types are NOT presentauthorizer.AddCheck(biscuit.Check{Queries: []biscuit.Rule{- {Body: []biscuit.Predicate{{Name: api.FactTargetUnrestricted, IDs: []biscuit.Term{}}}},+ {Body: []biscuit.Predicate{api.MarkerFact(api.FactTargetUnrestricted).Predicate}},}})authorizer.AddPolicy(api.AllowIfTruePolicy)diff --git a/internal/node/agent_namespace_test.go b/internal/node/agent_namespace_test.goindex 8c668ab2..f899dbbe 100644--- a/internal/node/agent_namespace_test.go+++ b/internal/node/agent_namespace_test.go@@ -41,7 +41,7 @@ func TestAuthorizeBoundsTheAgentClaimToTheGrantedNamespace(t *testing.T) {t.Helper()builder := biscuit.NewBuilder(priv)facts := []biscuit.Fact{- {Predicate: biscuit.Predicate{Name: api.FactTargetUnrestricted}},+ api.MarkerFact(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")}}},diff --git a/internal/node/controlplane_test.go b/internal/node/controlplane_test.goindex 97b491c7..5c7e4154 100644--- a/internal/node/controlplane_test.go+++ b/internal/node/controlplane_test.go@@ -283,6 +283,84 @@ func TestSyncControlPlane(t *testing.T) {}}+// datalog_rules is the only source of mesh policy rules: the node evaluates+// the text as it arrives and never derives rules from roles and bindings, so+// a control plane that still sends those is reported instead of tolerated.+func TestSyncMeshPolicyUsesDatalogRules(t *testing.T) {+ // What a control plane from before the contract sends: roles and bindings+ // in the field numbers PolicyConfigGetResponse now reserves.+ oldPolicy := &api.PolicyConfigGetResponse{}+ oldWire, err := proto.Marshal(&api.PolicyConfig{+ Roles: []*api.PolicyRole{{Name: "dev", AllowedServices: []string{"mcp://git"}}},+ Bindings: []*api.PolicyBinding{{Role: "dev", Members: []string{"group:developers"}}},+ })+ if err != nil {+ t.Fatal(err)+ }+ oldPolicy.ProtoReflect().SetUnknown(oldWire)++ tests := []struct {+ name string+ resp *api.PolicyConfigGetResponse+ wantRules int+ wantErr string+ }{+ {+ name: "text rules are adopted as sent",+ resp: &api.PolicyConfigGetResponse{DatalogRules: []string{`role("dev") <- group("developers")`}},+ wantRules: 1,+ },+ {+ name: "roles and bindings name an old control plane",+ resp: oldPolicy,+ wantErr: "predates datalog_rules",+ },+ {+ name: "one unparseable rule rejects the whole set",+ resp: &api.PolicyConfigGetResponse{DatalogRules: []string{`role("dev") <- group("developers")`, `broken(`}},+ wantErr: "unparseable rule",+ },+ {+ name: "empty policy is empty",+ resp: &api.PolicyConfigGetResponse{},+ wantRules: 0,+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ mux := http.NewServeMux()+ mux.HandleFunc("/policies", protoHandler(t, tt.resp))+ srv := httptest.NewServer(mux)+ defer srv.Close()++ store, err := NewStore(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = store.Close() }()+ if err := store.SaveControlPlaneURL(srv.URL); err != nil {+ t.Fatal(err)+ }+ n := &SamNode{Store: store}+ n.SetIdentityCache([]byte("identity"))++ err = n.syncMeshPolicy(context.Background())+ if tt.wantErr != "" {+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {+ t.Fatalf("syncMeshPolicy error = %v, want one containing %q", err, tt.wantErr)+ }+ return+ }+ if err != nil {+ t.Fatalf("syncMeshPolicy: %v", err)+ }+ if got := len(n.MeshPolicyRules); got != tt.wantRules {+ t.Fatalf("adopted %d rules, want %d", got, tt.wantRules)+ }+ })+ }+}+// The loop is what turns a missed gossip event into a delay rather than a// permanent split: a running node picks the successor key up on its own, and// a trigger brings the next pull forward.diff --git a/internal/node/enroll_test.go b/internal/node/enroll_test.goindex 4e8628a5..b5eae163 100644--- a/internal/node/enroll_test.go+++ b/internal/node/enroll_test.go@@ -123,7 +123,7 @@ func startMockRouterWithKey(t *testing.T, cpPriv ed25519.PrivateKey, role string{Predicate: biscuit.Predicate{Name: api.FactNode, IDs: []biscuit.Term{biscuit.String(h.ID().String())}}},{Predicate: biscuit.Predicate{Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(role)}}},{Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(time.Now().Add(24 * time.Hour))}}},- {Predicate: biscuit.Predicate{Name: api.FactTargetUnrestricted}},+ api.MarkerFact(api.FactTargetUnrestricted),} {if err := builder.AddAuthorityFact(f); err != nil {t.Fatalf("failed to add router fact: %v", err)diff --git a/internal/node/mcp_handlers_test.go b/internal/node/mcp_handlers_test.goindex f53f66fa..ade4e0de 100644--- a/internal/node/mcp_handlers_test.go+++ b/internal/node/mcp_handlers_test.go@@ -43,7 +43,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"}})+ _ = builder.AddAuthorityFact(api.MarkerFact(api.FactTargetUnrestricted))if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "node",IDs: []biscuit.Term{biscuit.String(callerID)},@@ -62,10 +62,7 @@ func buildAndSaveBiscuit(node *SamNode, rootPriv ed25519.PrivateKey) error {}}); err != nil {return err}- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: "granted_service_all_types",- IDs: []biscuit.Term{},- }}); err != nil {+ if err := builder.AddAuthorityFact(api.MarkerFact(api.FactGrantedServiceAllTypes)); err != nil {return err}if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{@@ -440,7 +437,7 @@ func TestHandleFindRemoteTools_PartialFailure(t *testing.T) {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"}})+ err := builder.AddAuthorityFact(api.MarkerFact(api.FactTargetUnrestricted))if err != nil {return err}diff --git a/internal/node/middleware_test.go b/internal/node/middleware_test.goindex 374cdd40..5c23f2ba 100644--- a/internal/node/middleware_test.go+++ b/internal/node/middleware_test.go@@ -112,7 +112,7 @@ func TestAuthorize(t *testing.T) {}builder := biscuit.NewBuilder(priv)- _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})+ _ = builder.AddAuthorityFact(api.MarkerFact(api.FactTargetUnrestricted))dummyPeer := peer.ID("dummy-peer")// Bind to peer@@ -205,7 +205,7 @@ func TestAuthorizeRejectsExpiredBiscuit(t *testing.T) {dummyPeer := peer.ID("dummy-peer")builder := biscuit.NewBuilder(priv)- _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactTargetUnrestricted}})+ _ = builder.AddAuthorityFact(api.MarkerFact(api.FactTargetUnrestricted))_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "node",IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},@@ -265,7 +265,7 @@ func TestAuthorizeRejectsAppendedPeerBinding(t *testing.T) {builder := biscuit.NewBuilder(priv)for _, f := range []biscuit.Fact{- {Predicate: biscuit.Predicate{Name: api.FactTargetUnrestricted}},+ api.MarkerFact(api.FactTargetUnrestricted),{Predicate: biscuit.Predicate{Name: api.FactNode, IDs: []biscuit.Term{biscuit.String(victim.String())}}},{Predicate: biscuit.Predicate{Name: api.FactClientPeerID, IDs: []biscuit.Term{biscuit.String(attacker.String())}}},{Predicate: biscuit.Predicate{Name: api.FactGrantedServiceExact, IDs: []biscuit.Term{biscuit.String(api.SystemNamespace), biscuit.String("/test/proto")}}},@@ -359,7 +359,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.FactGrantedServiceAllTypes)+ factStr := fmt.Sprintf(`%s(true)`, api.FactGrantedServiceAllTypes)fact, _ := parser.FromStringFact(factStr)_ = builder.AddAuthorityFact(fact)},@@ -411,7 +411,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(api.MarkerFact(api.FactTargetUnrestricted))_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "node",IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},@@ -501,7 +501,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {{name: "Case 3 (Wildcard Access)",mintToken: func(t *testing.T, builder biscuit.Builder) {- fact, err := parser.FromStringFact(fmt.Sprintf(`%s()`, api.FactGrantedServiceAllTypes))+ fact, err := parser.FromStringFact(fmt.Sprintf(`%s(true)`, api.FactGrantedServiceAllTypes))if err != nil {t.Fatal(err)}@@ -515,7 +515,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {{name: "Case 4 (Local Attenuation Override)",mintToken: func(t *testing.T, builder biscuit.Builder) {- fact1, err := parser.FromStringFact(fmt.Sprintf(`%s()`, api.FactGrantedServiceAllTypes))+ fact1, err := parser.FromStringFact(fmt.Sprintf(`%s(true)`, api.FactGrantedServiceAllTypes))if err != nil {t.Fatal(err)}@@ -544,7 +544,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: api.FactTargetUnrestricted}})+ _ = builder.AddAuthorityFact(api.MarkerFact(api.FactTargetUnrestricted))err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactNode,@@ -631,7 +631,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"}})+ _ = builder.AddAuthorityFact(api.MarkerFact(api.FactTargetUnrestricted))err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "node",IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},@@ -724,8 +724,8 @@ func TestWithBiscuitAuth_MutualBiscuit(t *testing.T) {for _, f := range []biscuit.Fact{{Predicate: biscuit.Predicate{Name: "node", IDs: []biscuit.Term{biscuit.String(clientPeer.String())}}},{Predicate: biscuit.Predicate{Name: "client_peer_id", IDs: []biscuit.Term{biscuit.String(clientPeer.String())}}},- {Predicate: biscuit.Predicate{Name: "granted_service_all_types"}},- {Predicate: biscuit.Predicate{Name: "target_unrestricted"}},+ api.MarkerFact(api.FactGrantedServiceAllTypes),+ api.MarkerFact(api.FactTargetUnrestricted),{Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(time.Now().Add(time.Hour))}}},} {if err := builder.AddAuthorityFact(f); err != nil {diff --git a/internal/node/node.go b/internal/node/node.goindex 972011eb..e45dce19 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -2303,13 +2303,22 @@ func (n *SamNode) syncMeshPolicy(ctx context.Context) error {return fmt.Errorf("failed to fetch mesh policy: %w", err)}- rules := BuildPolicyRules(policyResp.Roles, policyResp.Bindings)+ // The rendered text is the contract every member evaluates; a node does+ // not derive rules from roles and bindings itself. A control plane that+ // still sends those fields predates the contract.+ if len(policyResp.ProtoReflect().GetUnknown()) > 0 {+ return fmt.Errorf("control plane %s predates datalog_rules in its policy response; upgrade the control plane", controlPlaneURL)+ }+ rules, err := api.ParseDatalogRules(policyResp.DatalogRules)+ if err != nil {+ return fmt.Errorf("mesh policy carries an unparseable rule: %w", err)+ }n.MeshPolicyMu.Lock()n.MeshPolicyRules = rulesn.MeshPolicyMu.Unlock()- logger.Infof("Successfully synchronized mesh policy (generated %d rules)", len(rules))+ logger.Infof("Successfully synchronized mesh policy (%d rules)", len(rules))return nil}diff --git a/internal/node/policy.go b/internal/node/policy.godeleted file mode 100644index 112a4c7c..00000000--- a/internal/node/policy.go+++ /dev/null@@ -1,168 +0,0 @@-// 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 (- "strings"-- "github.com/biscuit-auth/biscuit-go/v2"- "github.com/biscuit-auth/biscuit-go/v2/parser"- "github.com/google/sam/api"-)--func BuildPolicyRules(roles []*api.PolicyRole, bindings []*api.PolicyBinding) []biscuit.Rule {- var rules []biscuit.Rule-- // A binding member becomes the body of a rule that grants a mesh role,- // so only facts the control plane attests in the authority block may- // appear there: agent() is the caller's own claim, and role() would- // grant a role from a role.- allowedMemberPrefix := make(map[string]bool)- for _, p := range api.BindingMemberPrefixes() {- allowedMemberPrefix[p] = true- }-- for _, b := range bindings {- if b == nil {- continue- }- for _, m := range b.Members {- if m == api.SystemAuthenticated {- rules = append(rules, biscuit.Rule{- Head: biscuit.Predicate{- Name: api.FactRole,- IDs: []biscuit.Term{biscuit.String(b.Role)},- },- Body: []biscuit.Predicate{},- })- continue- }- parts := strings.SplitN(m, ":", 2)- if len(parts) == 2 && allowedMemberPrefix[parts[0]] {- memberType := parts[0]- memberVal := parts[1]- rules = append(rules, biscuit.Rule{- Head: biscuit.Predicate{- Name: api.FactRole,- IDs: []biscuit.Term{biscuit.String(b.Role)},- },- Body: []biscuit.Predicate{- {Name: memberType, IDs: []biscuit.Term{biscuit.String(memberVal)}},- },- })- }- }- }-- for _, role := range roles {- if role == nil {- continue- }- roleName := role.Name-- for _, fact := range api.BuildServiceDatalogFacts(role.AllowedServices) {- rules = append(rules, biscuit.Rule{- Head: fact.Predicate,- Body: []biscuit.Predicate{- {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(roleName)}},- },- })- }-- hasUnrestricted := false- hasSpecificTargets := false- for _, t := range role.AllowedTargets {- if t == "*" {- hasUnrestricted = true- } else {- hasSpecificTargets = true- }- }-- if hasUnrestricted {- rules = append(rules, biscuit.Rule{- Head: biscuit.Predicate{- Name: api.FactTargetUnrestricted,- IDs: []biscuit.Term{},- },- Body: []biscuit.Predicate{- {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(roleName)}},- },- })- }-- if hasSpecificTargets {- rules = append(rules, biscuit.Rule{- Head: biscuit.Predicate{- Name: api.FactTargetRestricted,- IDs: []biscuit.Term{},- },- Body: []biscuit.Predicate{- {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(roleName)}},- },- })- }-- nonWildcardTargets := make([]string, 0, len(role.AllowedTargets))- for _, t := range role.AllowedTargets {- if t != "*" {- nonWildcardTargets = append(nonWildcardTargets, t)- }- }- for _, fact := range api.BuildTargetDatalogFacts(nonWildcardTargets) {- rules = append(rules, biscuit.Rule{- Head: fact.Predicate,- Body: []biscuit.Predicate{- {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(roleName)}},- },- })- }-- 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 == "" {- continue- }- r, err := parser.FromStringRule(trimmed)- if err == nil {- rules = append(rules, r)- } else {- f, err2 := parser.FromStringFact(trimmed)- if err2 == nil {- rules = append(rules, biscuit.Rule{- Head: f.Predicate,- Body: []biscuit.Predicate{},- })- } else {- logger.Warnf("Failed to parse custom Datalog rule/fact %q for role %s: rule_err=%v, fact_err=%v", dl, roleName, err, err2)- }- }- }- }-- return rules-}diff --git a/internal/node/policy_test.go b/internal/node/policy_test.godeleted file mode 100644index 916bfde5..00000000--- a/internal/node/policy_test.go+++ /dev/null@@ -1,94 +0,0 @@-// 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 (- "strings"- "testing"-- "github.com/biscuit-auth/biscuit-go/v2"- "github.com/google/sam/api"-)--func ruleToString(r biscuit.Rule) string {- head := r.Head.String()- if len(r.Body) == 0 {- return head- }- var bodyParts []string- for _, b := range r.Body {- bodyParts = append(bodyParts, b.String())- }- return head + " <- " + strings.Join(bodyParts, ", ")-}--func TestBuildPolicyRules(t *testing.T) {- roles := []*api.PolicyRole{- {- Name: "test-role",- AllowedTargets: []string{"*", "node:peer-abc", "custom-fact:custom-val", "legacy-peer"},- AllowedServices: []string{"*:*", "mcp:*", "mcp:*.suffix", "mcp:prefix.*", "mcp:exact"},- CustomDatalog: []string{- "custom_rule($x) <- fact($x);",- "custom_fact(\"hello\")",- },- },- }- bindings := []*api.PolicyBinding{- {- Role: "test-role",- Members: []string{"sam:system:authenticated", "user:alice"},- },- }-- rules := BuildPolicyRules(roles, bindings)-- expectedStrings := map[string]bool{- "role(\"test-role\")": false,- "role(\"test-role\") <- user(\"alice\")": false,- "granted_service_all_types() <- role(\"test-role\")": false,- "granted_service_all(\"mcp\") <- role(\"test-role\")": false,- "granted_service_suffix(\"mcp\", \".suffix\") <- role(\"test-role\")": false,- "granted_service_prefix(\"mcp\", \"prefix.\") <- role(\"test-role\")": false,- "granted_service_set(\"mcp\", [\"exact\"]) <- role(\"test-role\")": false,- "target_unrestricted() <- role(\"test-role\")": false,- "target_restricted() <- role(\"test-role\")": false,- "granted_target_set(\"node\", [\"legacy-peer\", \"peer-abc\"]) <- role(\"test-role\")": false,- "granted_target_set(\"custom-fact\", [\"custom-val\"]) <- role(\"test-role\")": false,- "custom_rule($x) <- fact($x)": false,- "custom_fact(\"hello\")": false,- }-- for _, rule := range rules {- rStr := ruleToString(rule)- found := false- for k := range expectedStrings {- if rStr == k {- expectedStrings[k] = true- found = true- break- }- }- if !found {- t.Errorf("Unexpected rule generated: %q", rStr)- }- }-- for k, v := range expectedStrings {- if !v {- t.Errorf("Expected rule was not generated: %q", k)- }- }-}diff --git a/internal/node/router_auth_dedupe_test.go b/internal/node/router_auth_dedupe_test.goindex 5f47a4bf..13207618 100644--- a/internal/node/router_auth_dedupe_test.go+++ b/internal/node/router_auth_dedupe_test.go@@ -58,7 +58,7 @@ func newFakeRouter(t *testing.T, listenAddrs ...string) *fakeRouter {{Predicate: biscuit.Predicate{Name: api.FactNode, IDs: []biscuit.Term{biscuit.String(peerID)}}},{Predicate: biscuit.Predicate{Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(role)}}},{Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(time.Now().Add(24 * time.Hour))}}},- {Predicate: biscuit.Predicate{Name: api.FactTargetUnrestricted}},+ api.MarkerFact(api.FactTargetUnrestricted),} {if err := b.AddAuthorityFact(f); err != nil {t.Fatal(err)diff --git a/internal/node/static_service_test.go b/internal/node/static_service_test.goindex 3a6c0e7e..94e12448 100644--- a/internal/node/static_service_test.go+++ b/internal/node/static_service_test.go@@ -71,9 +71,7 @@ func startMockRouter(t *testing.T) (peer.ID, string) {Name: api.FactExpiration,IDs: []biscuit.Term{biscuit.Date(time.Now().Add(24 * time.Hour))},}})- _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactTargetUnrestricted,- }})+ _ = builder.AddAuthorityFact(api.MarkerFact(api.FactTargetUnrestricted))tok, err := builder.Build()if err != nil {t.Fatalf("failed to build mock router biscuit: %v", err)diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.goindex 9bcc8ee6..1578b32e 100644--- a/internal/standalone/standalone.go+++ b/internal/standalone/standalone.go@@ -102,7 +102,7 @@ type Options struct {// DataDir when empty.AdminToken string// PolicyFile optionally seeds the mesh policy on first boot from a- // protojson PolicyConfigUpdateRequest payload.+ // protojson PolicyConfig payload.PolicyFile string// OIDCIssuer optionally enables full OIDC enrollment.OIDCIssuer string@@ -457,14 +457,14 @@ func (s *Server) seedPolicyOnFirstBoot(ctx context.Context) error {return nil}- var seed api.PolicyConfigUpdateRequest+ var seed api.PolicyConfigif s.opts.PolicyFile != "" {data, err := os.ReadFile(s.opts.PolicyFile)if err != nil {return fmt.Errorf("failed to read policy file: %w", err)}if err := protojson.Unmarshal(data, &seed); err != nil {- return fmt.Errorf("failed to parse policy file %s (expects protojson PolicyConfigUpdateRequest): %w", s.opts.PolicyFile, err)+ return fmt.Errorf("failed to parse policy file %s (expects protojson PolicyConfig): %w", s.opts.PolicyFile, err)}logger.Infof("Seeding mesh policy from %s", s.opts.PolicyFile)} else {diff --git a/sdk/README.md b/sdk/README.mdindex 6ca2fb48..71f4287a 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -107,6 +107,7 @@ messages in `api/sam.proto`. Bodies are capped at 1 MiB on both sides.| `POST /register` | `EnrollRequest` | `EnrollResponse` | sign `sam:register:<peer_id>:<ts>` || `POST /refresh` | `TokenRefreshRequest`, header `Authorization: Bearer <base64 biscuit>` | `TokenRefreshResponse` | sign `sam:refresh:<peer_id>:<ts>` || `GET /keys` | — | `KeysResponse` | none; see below |+| `GET /policies` | header `Authorization: Bearer <base64 biscuit>` | `PolicyConfigGetResponse{datalog_rules}` | none; the biscuit must belong to an admitted node |- `<ts>` is unix milliseconds and must be within 5 minutes of the controlplane's clock (`challengeMaxAge`). Challenges are defined in@@ -181,11 +182,30 @@ interest-scoped updates; the DHT is the source of truth.A node that serves a tool evaluates the caller's biscuit with an authorizerthat has, in this order: the biscuit's own authority facts (`node`, `role`,`label`, `agent`), injected facts `service(<type>, <name>)`,-`connection_peer_id(<peer>)` and optionally `agent(<claim>)`, the baseline-checks, rules and policies from `api/datalog.go`, the facts from the-provider's own biscuit, and the mesh policy rules the control plane-publishes (`BuildPolicyRules` over `PolicyConfigGetResponse`). Deny by-default.+`connection_peer_id(<peer>)`, `time(<now>)` and optionally `agent(<claim>)`,+the baseline checks, rules and policies from `api/datalog.go`, the+`target_fact` facts derived from the provider's own biscuit, and the mesh+policy rules. Deny by default.++All of that Datalog is text every Biscuit implementation parses, and none+of it is derived in the SDK:++- The baseline (checks, rules, policies, fact names) is generated from+ `api/datalog.go` by `hack/gen-sdk-datalog` into `sdk/js/src/gen/datalog.ts`+ and `sdk/python/src/agent_mesh/_gen/datalog.json`;+ `hack/verify-sdk-generated.sh` fails when they are stale.+- The mesh policy arrives rendered: `GET /policies` answers+ `PolicyConfigGetResponse{datalog_rules}`, one rule per entry, rendered by+ the control plane with `api.BuildPolicyRules`. `sam-node` adds the same+ text; no member compiles roles and bindings itself. An unparseable entry+ rejects the whole response.+- Presence-only facts carry the single term `true`+ (`target_unrestricted(true)`, `granted_service_all_types(true)`,+ `agent_authorized(true)`, …). biscuit-go accepts a predicate with no+ terms; biscuit-rust, and so biscuit-python and biscuit-wasm, do not.+- An unconditional rule is written `head <- true`, which every parser+ accepts as a rule (`role("dev") <- true` for a+ `sam:system:authenticated` binding).## Plan@@ -264,16 +284,21 @@ holds against the control plane's records.### Milestone 4 — serve tools+- Datalog as the contract (done, Go side): the baseline moved into a+ generated artifact both SDKs embed, the control plane renders the mesh+ policy as `datalog_rules`, and `sam-node` consumes that text like any+ other member. See the authorization section above.+- Provider authorizer in each SDK, built from the artifact and+ `datalog_rules`, evaluated on every inbound `AuthFrame`.- `/sam/mcp/1.0.0` server: read the `AuthFrame`, run the authorizer, answer,then hand the stream to an in-process MCP server.-- The authorizer needs the baseline Datalog from `api/datalog.go` and the- mesh policy from `GET /policies`. Before this milestone the baseline- Datalog moves out of Go string constants into a language-neutral artifact- that the Go build and both SDKs embed, so it is written once.+- `/libp2p-http` ingress for inference and A2A backends, forwarding+ authorized requests to a local URL, and the client side to call them.- DHT provide for each registered service, reprovided on the node'sinterval; `POST /nodes/catalog` self-report.-- Test: a `sam-node` calls a tool served by the SDK member, and a denied- caller is refused at the `AuthResponse`.+- Test: a `sam-node` calls a tool and an inference endpoint served by each+ SDK member, the SDK members call each other, and a caller whose role+ grants nothing is refused at the `AuthResponse`.### Milestone 5 — parity and release@@ -297,7 +322,8 @@ holds against the control plane's records.## Working on the SDKs```bash-# Regenerate protobuf bindings after editing api/sam.proto+# Regenerate protobuf bindings and the Datalog artifact after editing+# api/sam.proto or api/datalog.go./hack/gen-sdk-proto.sh# JavaScriptdiff --git a/sdk/js/src/gen/datalog.ts b/sdk/js/src/gen/datalog.tsnew file mode 100644index 00000000..547b732b--- /dev/null+++ b/sdk/js/src/gen/datalog.ts@@ -0,0 +1,57 @@+// Code generated by hack/gen-sdk-datalog from api/datalog.go; DO NOT EDIT.++/** The Datalog a provider evaluates against a caller's biscuit. */+export const BASELINE_DATALOG = {+ "_comment": "Generated by hack/gen-sdk-datalog from api/datalog.go; do not edit.",+ "policies": [+ "allow if service($type, $name), granted_service_exact($type, $name)",+ "allow if service($type, $name), granted_service_set($type, $set), $set.contains($name)",+ "allow if service($type, $name), granted_service_prefix($type, $prefix), $name.starts_with($prefix)",+ "allow if service($type, $name), granted_service_suffix($type, $suffix), $name.ends_with($suffix)",+ "allow if service($type, $name), granted_service_all($type)",+ "allow if service($type, $name), granted_service_all_types(true)"+ ],+ "rules": [+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_exact($fact, $val)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_set($fact, $set), $set.contains($val)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_prefix($fact, $prefix), $val.starts_with($prefix)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_suffix($fact, $suffix), $val.ends_with($suffix)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_all($fact)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_all_facts(true)"+ ],+ "agent_rules": [+ "agent_authorized(true) <- agent($a), granted_agent_exact($a)",+ "agent_authorized(true) <- agent($a), granted_agent_set($set), $set.contains($a)",+ "agent_authorized(true) <- agent($a), granted_agent_prefix($prefix), $a.starts_with($prefix)",+ "agent_authorized(true) <- agent($a), granted_agent_suffix($suffix), $a.ends_with($suffix)",+ "agent_authorized(true) <- agent($a), granted_agent_all(true)"+ ],+ "target_fact_rules": [+ "target_fact(\"email\", $val) <- email($val)",+ "target_fact(\"group\", $val) <- group($val)",+ "target_fact(\"idp_role\", $val) <- idp_role($val)",+ "target_fact(\"node\", $val) <- node($val)",+ "target_fact(\"user\", $val) <- user($val)"+ ],+ "replay_check": "check if client_peer_id($id), connection_peer_id($id)",+ "target_check": "check if allow_network_target($fact, $val) or target_unrestricted(true)",+ "agent_check": "check if agent_authorized(true)",+ "time_check": "check if time($time), expiration($exp), $time <= $exp",+ "allow_if_true": "allow if true",+ "fact_service": "service",+ "fact_connection_peer_id": "connection_peer_id",+ "fact_agent": "agent",+ "fact_time": "time",+ "fact_role": "role",+ "fact_target_fact": "target_fact",+ "marker_term": "true",+ "system_namespace": "sam:system",+ "binding_member_prefixes": [+ "email",+ "group",+ "idp_role",+ "node",+ "user"+ ],+ "system_authenticated_member": "sam:system:authenticated"+} as const;diff --git a/sdk/js/src/gen/sam_pb.ts b/sdk/js/src/gen/sam_pb.tsindex 62354e6c..d7b4bd9c 100644--- a/sdk/js/src/gen/sam_pb.ts+++ b/sdk/js/src/gen/sam_pb.ts@@ -24,7 +24,7 @@ import type { Message } from "@bufbuild/protobuf";* Describes the file sam.proto.*/export const file_sam: GenFile = /*@__PURE__*/- fileDesc("CglzYW0ucHJvdG8SBnNhbS52MSJDCglBdXRoRnJhbWUSDwoHYmlzY3VpdBgBIAEoDBIWCg50YXJnZXRfc2VydmljZRgCIAEoCRINCgVhZ2VudBgDIAEoCSI/CgxBdXRoUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCRIPCgdiaXNjdWl0GAMgASgMIrkBCglNZXNoRXZlbnQSJAoEdHlwZRgBIAEoDjIWLnNhbS52MS5NZXNoRXZlbnQuVHlwZRIPCgdwZWVyX2lkGAIgASgJEhEKCXRpbWVzdGFtcBgDIAEoAxIWCg5uZXdfcHVibGljX2tleRgEIAEoDBIRCglzaWduYXR1cmUYBSABKAwiNwoEVHlwZRIKCgZCQU5ORUQQABIQCgxLRVlfUk9UQVRJT04QARIRCg1QT0xJQ1lfVVBEQVRFEAIi6wEKDUVucm9sbFJlcXVlc3QSCwoDand0GAEgASgJEg8KB3BlZXJfaWQYAiABKAkSEgoKcHVibGljX2tleRgDIAEoDBIWCg5yZXF1ZXN0ZWRfcm9sZRgEIAEoCRIxCgZsYWJlbHMYBSADKAsyIS5zYW0udjEuRW5yb2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lbnRpdHlFdmlkZW5jZVJlc3BvbnNlEg8KB3BlZXJfaWQYASABKAkSDwoHYmlzY3VpdBgCIAEoDBIaChJiaXNjdWl0X2V4cGlyZXNfYXQYAyABKAMSGQoRY29udHJvbF9wbGFuZV91cmwYBCABKAkSIgoadHJ1c3RlZF9jb250cm9sX3BsYW5lX2tleXMYBSADKAwSEgoKY2hlY2tlZF9hdBgGIAEoAyKHAgoUUGVlckV2aWRlbmNlUmVzcG9uc2USDwoHcGVlcl9pZBgBIAEoCRIPCgdiaXNjdWl0GAIgASgMEhUKDXZlcmlmeWluZ19rZXkYAyABKAwSDQoFcm9sZXMYBCADKAkSOAoGbGFiZWxzGAUgAygLMiguc2FtLnYxLlBlZXJFdmlkZW5jZVJlc3BvbnNlLkxhYmVsc0VudHJ5EhIKCmV4cGlyYXRpb24YBiABKAMSFgoOcmV2b2NhdGlvbl9pZHMYByADKAkSEgoKY2hlY2tlZF9hdBgIIAEoAxotCgtMYWJlbHNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBKpQBChBFbnJvbGxtZW50U3RhdHVzEiEKHUVOUk9MTE1FTlRfU1RBVFVTX1VOU1BFQ0lGSUVEEAASHQoZRU5ST0xMTUVOVF9TVEFUVVNfUEVORElORxABEh4KGkVOUk9MTE1FTlRfU1RBVFVTX0FQUFJPVkVEEAISHgoaRU5ST0xMTUVOVF9TVEFUVVNfUkVKRUNURUQQAypzCgtTZXJ2aWNlVHlwZRIcChhTRVJWSUNFX1RZUEVfVU5TUEVDSUZJRUQQABIUChBTRVJWSUNFX1RZUEVfTUNQEAESGgoWU0VSVklDRV9UWVBFX0lORkVSRU5DRRACEhQKEFNFUlZJQ0VfVFlQRV9BMkEQA0IbWhlnaXRodWIuY29tL2dvb2dsZS9zYW0vYXBpYgZwcm90bzM");/*** @generated from message sam.v1.AuthFrame@@ -749,22 +749,14 @@ export const PolicyBindingSchema: GenMessage<PolicyBinding> = /*@__PURE__*/messageDesc(file_sam, 16);/**- * @generated from message sam.v1.PolicyConfigGetRequest- */-export type PolicyConfigGetRequest = Message<"sam.v1.PolicyConfigGetRequest"> & {-};--/**- * Describes the message sam.v1.PolicyConfigGetRequest.- * Use `create(PolicyConfigGetRequestSchema)` to create a new message.- */-export const PolicyConfigGetRequestSchema: GenMessage<PolicyConfigGetRequest> = /*@__PURE__*/- messageDesc(file_sam, 17);--/**- * @generated from message sam.v1.PolicyConfigGetResponse+ * PolicyConfig is the mesh policy as the operator writes it: roles and+ * bindings. It is the body of POST /policies and the answer of+ * GET /admin/policy, both protojson. Only the control plane reads it, to+ * mint tokens and to render PolicyConfigGetResponse.+ *+ * @generated from message sam.v1.PolicyConfig*/-export type PolicyConfigGetResponse = Message<"sam.v1.PolicyConfigGetResponse"> & {+export type PolicyConfig = Message<"sam.v1.PolicyConfig"> & {/*** @generated from field: repeated sam.v1.PolicyRole roles = 1;*/@@ -777,32 +769,46 @@ export type PolicyConfigGetResponse = Message<"sam.v1.PolicyConfigGetResponse">};/**- * Describes the message sam.v1.PolicyConfigGetResponse.- * Use `create(PolicyConfigGetResponseSchema)` to create a new message.+ * Describes the message sam.v1.PolicyConfig.+ * Use `create(PolicyConfigSchema)` to create a new message.*/-export const PolicyConfigGetResponseSchema: GenMessage<PolicyConfigGetResponse> = /*@__PURE__*/- messageDesc(file_sam, 18);+export const PolicyConfigSchema: GenMessage<PolicyConfig> = /*@__PURE__*/+ messageDesc(file_sam, 17);/**- * @generated from message sam.v1.PolicyConfigUpdateRequest+ * @generated from message sam.v1.PolicyConfigGetRequest*/-export type PolicyConfigUpdateRequest = Message<"sam.v1.PolicyConfigUpdateRequest"> & {- /**- * @generated from field: repeated sam.v1.PolicyRole roles = 1;- */- roles: PolicyRole[];+export type PolicyConfigGetRequest = Message<"sam.v1.PolicyConfigGetRequest"> & {+};++/**+ * Describes the message sam.v1.PolicyConfigGetRequest.+ * Use `create(PolicyConfigGetRequestSchema)` to create a new message.+ */+export const PolicyConfigGetRequestSchema: GenMessage<PolicyConfigGetRequest> = /*@__PURE__*/+ messageDesc(file_sam, 18);+/**+ * PolicyConfigGetResponse answers GET /policies for a mesh member holding a+ * biscuit. It carries the policy only as Datalog text: this is the contract+ * every member evaluates, and none derives rules from roles and bindings.+ *+ * @generated from message sam.v1.PolicyConfigGetResponse+ */+export type PolicyConfigGetResponse = Message<"sam.v1.PolicyConfigGetResponse"> & {/**- * @generated from field: repeated sam.v1.PolicyBinding bindings = 2;+ * One rule per entry, rendered by the control plane with api.BuildPolicyRules.+ *+ * @generated from field: repeated string datalog_rules = 3;*/- bindings: PolicyBinding[];+ datalogRules: string[];};/**- * Describes the message sam.v1.PolicyConfigUpdateRequest.- * Use `create(PolicyConfigUpdateRequestSchema)` to create a new message.+ * Describes the message sam.v1.PolicyConfigGetResponse.+ * Use `create(PolicyConfigGetResponseSchema)` to create a new message.*/-export const PolicyConfigUpdateRequestSchema: GenMessage<PolicyConfigUpdateRequest> = /*@__PURE__*/+export const PolicyConfigGetResponseSchema: GenMessage<PolicyConfigGetResponse> = /*@__PURE__*/messageDesc(file_sam, 19);/**diff --git a/sdk/python/src/agent_mesh/_gen/__init__.py b/sdk/python/src/agent_mesh/_gen/__init__.pynew file mode 100644index 00000000..09bac1cb--- /dev/null+++ b/sdk/python/src/agent_mesh/_gen/__init__.py@@ -0,0 +1 @@+"""Generated artifacts; see hack/gen-sdk-proto.sh."""diff --git a/sdk/python/src/agent_mesh/_gen/datalog.json b/sdk/python/src/agent_mesh/_gen/datalog.jsonnew file mode 100644index 00000000..f7d67abf--- /dev/null+++ b/sdk/python/src/agent_mesh/_gen/datalog.json@@ -0,0 +1,54 @@+{+ "_comment": "Generated by hack/gen-sdk-datalog from api/datalog.go; do not edit.",+ "policies": [+ "allow if service($type, $name), granted_service_exact($type, $name)",+ "allow if service($type, $name), granted_service_set($type, $set), $set.contains($name)",+ "allow if service($type, $name), granted_service_prefix($type, $prefix), $name.starts_with($prefix)",+ "allow if service($type, $name), granted_service_suffix($type, $suffix), $name.ends_with($suffix)",+ "allow if service($type, $name), granted_service_all($type)",+ "allow if service($type, $name), granted_service_all_types(true)"+ ],+ "rules": [+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_exact($fact, $val)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_set($fact, $set), $set.contains($val)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_prefix($fact, $prefix), $val.starts_with($prefix)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_suffix($fact, $suffix), $val.ends_with($suffix)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_all($fact)",+ "allow_network_target($fact, $val) <- target_fact($fact, $val), granted_target_all_facts(true)"+ ],+ "agent_rules": [+ "agent_authorized(true) <- agent($a), granted_agent_exact($a)",+ "agent_authorized(true) <- agent($a), granted_agent_set($set), $set.contains($a)",+ "agent_authorized(true) <- agent($a), granted_agent_prefix($prefix), $a.starts_with($prefix)",+ "agent_authorized(true) <- agent($a), granted_agent_suffix($suffix), $a.ends_with($suffix)",+ "agent_authorized(true) <- agent($a), granted_agent_all(true)"+ ],+ "target_fact_rules": [+ "target_fact(\"email\", $val) <- email($val)",+ "target_fact(\"group\", $val) <- group($val)",+ "target_fact(\"idp_role\", $val) <- idp_role($val)",+ "target_fact(\"node\", $val) <- node($val)",+ "target_fact(\"user\", $val) <- user($val)"+ ],+ "replay_check": "check if client_peer_id($id), connection_peer_id($id)",+ "target_check": "check if allow_network_target($fact, $val) or target_unrestricted(true)",+ "agent_check": "check if agent_authorized(true)",+ "time_check": "check if time($time), expiration($exp), $time <= $exp",+ "allow_if_true": "allow if true",+ "fact_service": "service",+ "fact_connection_peer_id": "connection_peer_id",+ "fact_agent": "agent",+ "fact_time": "time",+ "fact_role": "role",+ "fact_target_fact": "target_fact",+ "marker_term": "true",+ "system_namespace": "sam:system",+ "binding_member_prefixes": [+ "email",+ "group",+ "idp_role",+ "node",+ "user"+ ],+ "system_authenticated_member": "sam:system:authenticated"+}diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.py b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyindex 450b8e74..f3fa586e 100644--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.py+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.py@@ -13,7 +13,7 @@ _sym_db = _symbol_database.Default()-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tsam.proto\x12\x06sam.v1\"C\n\tAuthFrame\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x16\n\x0etarget_service\x18\x02 \x01(\t\x12\r\n\x05\x61gent\x18\x03 \x01(\t\"?\n\x0c\x41uthResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\"\xb9\x01\n\tMeshEvent\x12$\n\x04type\x18\x01 \x01(\x0e\x32\x16.sam.v1.MeshEvent.Type\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x11\n\ttimestamp\x18\x03 \x01(\x03\x12\x16\n\x0enew_public_key\x18\x04 \x01(\x0c\x12\x11\n\tsignature\x18\x05 \x01(\x0c\"7\n\x04Type\x12\n\n\x06\x42\x41NNED\x10\x00\x12\x10\n\x0cKEY_ROTATION\x10\x01\x12\x11\n\rPOLICY_UPDATE\x10\x02\"\xeb\x01\n\rEnrollRequest\x12\x0b\n\x03jwt\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12\x31\n\x06labels\x18\x05 \x03(\x0b\x32!.sam.v1.EnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8e\x01\n\x0e\x45nrollResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x15\n\rerror_message\x18\x02 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x03 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x12\n\nexpiration\x18\x05 \x01(\x03\"\x89\x02\n\x16\x42ootstrapEnrollRequest\x12\x17\n\x0f\x62ootstrap_token\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12:\n\x06labels\x18\x05 \x03(\x0b\x32*.sam.v1.BootstrapEnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xe0\x01\n\x17\x42ootstrapEnrollResponse\x12(\n\x06status\x18\x01 \x01(\x0e\x32\x18.sam.v1.EnrollmentStatus\x12\x15\n\rbiscuit_token\x18\x02 \x01(\x0c\x12\x1d\n\x15poll_interval_seconds\x18\x03 \x01(\x05\x12\x15\n\rerror_message\x18\x04 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x05 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x06 \x03(\t\x12\x12\n\nexpiration\x18\x07 \x01(\x03\"S\n\x0bServiceInfo\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\"{\n\x0e\x43ommandBackend\x12\x0f\n\x07\x63ommand\x18\x01 \x03(\t\x12,\n\x03\x65nv\x18\x02 \x03(\x0b\x32\x1f.sam.v1.CommandBackend.EnvEntry\x1a*\n\x08\x45nvEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8a\x01\n\x16RegisterServiceRequest\x12$\n\x07service\x18\x01 \x01(\x0b\x32\x13.sam.v1.ServiceInfo\x12\x14\n\ntarget_url\x18\x02 \x01(\tH\x00\x12)\n\x07\x63ommand\x18\x03 \x01(\x0b\x32\x16.sam.v1.CommandBackendH\x00\x42\t\n\x07\x62\x61\x63kend\"i\n\x12\x44iscoveredProvider\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x17\n\x0flocal_proxy_url\x18\x02 \x01(\t\x12\x10\n\x08srv_name\x18\x03 \x01(\t\x12\x17\n\x0fsrv_description\x18\x04 \x01(\t\"\x92\x02\n\x0fServiceAnnounce\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12!\n\x04type\x18\x02 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x14\n\x0cservice_name\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x33\n\x06labels\x18\x05 \x03(\x0b\x32#.sam.v1.ServiceAnnounce.LabelsEntry\x12\x17\n\x0f\x61\x63tive_requests\x18\x06 \x01(\r\x12\x17\n\x0flatency_ewma_ms\x18\x07 \x01(\x01\x12\x11\n\ttimestamp\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x87\x01\n\x18\x43ontrolPlaneInfoResponse\x12\x13\n\x0boidc_issuer\x18\x01 \x01(\t\x12\x11\n\tclient_id\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x17\n\x0f\x62\x61nned_peer_ids\x18\x05 \x03(\t\"\xa4\x01\n\x12RouterLeaseRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\x12\x17\n\x0f\x63onnected_peers\x18\x04 \x03(\t\x12\x10\n\x08\x64ht_size\x18\x05 \x01(\x05\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\"I\n\x13RouterLeaseResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"\x95\x01\n\nPolicyRole\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0f\x61llowed_targets\x18\x02 \x03(\t\x12\x18\n\x10\x61llowed_services\x18\x03 \x03(\t\x12\x16\n\x0e\x63ustom_datalog\x18\x04 \x03(\t\x12\x16\n\x0e\x61llowed_agents\x18\x05 \x03(\t\x12\x16\n\x0e\x61llowed_labels\x18\x06 \x03(\t\".\n\rPolicyBinding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\t\"\x18\n\x16PolicyConfigGetRequest\"e\n\x17PolicyConfigGetResponse\x12!\n\x05roles\x18\x01 \x03(\x0b\x32\x12.sam.v1.PolicyRole\x12\'\n\x08\x62indings\x18\x02 \x03(\x0b\x32\x15.sam.v1.PolicyBinding\"g\n\x19PolicyConfigUpdateRequest\x12!\n\x05roles\x18\x01 \x03(\x0b\x32\x12.sam.v1.PolicyRole\x12\'\n\x08\x62indings\x18\x02 \x03(\x0b\x32\x15.sam.v1.PolicyBinding\"<\n\x1aPolicyConfigUpdateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"J\n\x0cKeysResponse\x12\x13\n\x0bpublic_keys\x18\x01 \x03(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x12\n\nsignatures\x18\x03 \x03(\x0c\"V\n\x13TokenRefreshRequest\x12\x1b\n\x13\x63hallenge_signature\x18\x01 \x01(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x0f\n\x07peer_id\x18\x03 \x01(\t\"X\n\x14TokenRefreshResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x12\n\nexpires_at\x18\x02 \x01(\x03\x12\x15\n\rerror_message\x18\x03 \x01(\t\":\n\x11NodeCatalogReport\x12%\n\x08services\x18\x01 \x03(\x0b\x32\x13.sam.v1.ServiceInfo\"%\n\x12TokenRevokeRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\"5\n\x13TokenRevokeResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"R\n\x0b\x41gentSecret\x12\x0c\n\x04host\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x13\n\x0bheader_name\x18\x03 \x01(\t\x12\x12\n\nvalue_path\x18\x04 \x01(\t\"B\n\x0b\x41gentEgress\x12\r\n\x05\x61llow\x18\x01 \x03(\t\x12$\n\x07secrets\x18\x02 \x03(\x0b\x32\x13.sam.v1.AgentSecret\"b\n\x0c\x41gentIngress\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0c\n\x04port\x18\x03 \x01(\r\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t\"\xaa\x01\n\x0b\x41gentBundle\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x10\n\x08\x61gent_id\x18\x02 \x01(\t\x12\x13\n\x0b\x65xternal_id\x18\x03 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x04 \x01(\t\x12#\n\x06\x65gress\x18\x05 \x01(\x0b\x32\x13.sam.v1.AgentEgress\x12%\n\x07ingress\x18\x06 \x03(\x0b\x32\x14.sam.v1.AgentIngress\"9\n\x12\x41gentAttachRequest\x12#\n\x06\x62undle\x18\x01 \x01(\x0b\x32\x13.sam.v1.AgentBundle\"S\n\x13\x41gentAttachResponse\x12\x15\n\regress_socket\x18\x01 \x01(\t\x12\x16\n\x0eingress_socket\x18\x02 \x01(\t\x12\r\n\x05\x65rror\x18\x03 \x01(\t\"&\n\x12\x41gentDetachRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"5\n\x13\x41gentDetachResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"@\n\x13\x41gentRefreshRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x02 \x01(\t\"J\n\x14\x41gentRefreshResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"&\n\x12\x41gentStatusRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"w\n\x0b\x41gentStatus\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x10\n\x08\x61ttached\x18\x02 \x01(\x08\x12%\n\x07ingress\x18\x03 \x03(\x0b\x32\x14.sam.v1.AgentIngress\x12\x1d\n\x15\x63redential_expires_at\x18\x04 \x01(\x03\"I\n\x13\x41gentStatusResponse\x12#\n\x06\x61gents\x18\x01 \x03(\x0b\x32\x13.sam.v1.AgentStatus\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"\xab\x01\n\x18IdentityEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x1a\n\x12\x62iscuit_expires_at\x18\x03 \x01(\x03\x12\x19\n\x11\x63ontrol_plane_url\x18\x04 \x01(\t\x12\"\n\x1atrusted_control_plane_keys\x18\x05 \x03(\x0c\x12\x12\n\nchecked_at\x18\x06 \x01(\x03\"\x87\x02\n\x14PeerEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x15\n\rverifying_key\x18\x03 \x01(\x0c\x12\r\n\x05roles\x18\x04 \x03(\t\x12\x38\n\x06labels\x18\x05 \x03(\x0b\x32(.sam.v1.PeerEvidenceResponse.LabelsEntry\x12\x12\n\nexpiration\x18\x06 \x01(\x03\x12\x16\n\x0erevocation_ids\x18\x07 \x03(\t\x12\x12\n\nchecked_at\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01*\x94\x01\n\x10\x45nrollmentStatus\x12!\n\x1d\x45NROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n\x19\x45NROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n\x1a\x45NROLLMENT_STATUS_APPROVED\x10\x02\x12\x1e\n\x1a\x45NROLLMENT_STATUS_REJECTED\x10\x03*s\n\x0bServiceType\x12\x1c\n\x18SERVICE_TYPE_UNSPECIFIED\x10\x00\x12\x14\n\x10SERVICE_TYPE_MCP\x10\x01\x12\x1a\n\x16SERVICE_TYPE_INFERENCE\x10\x02\x12\x14\n\x10SERVICE_TYPE_A2A\x10\x03\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tsam.proto\x12\x06sam.v1\"C\n\tAuthFrame\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x16\n\x0etarget_service\x18\x02 \x01(\t\x12\r\n\x05\x61gent\x18\x03 \x01(\t\"?\n\x0c\x41uthResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\"\xb9\x01\n\tMeshEvent\x12$\n\x04type\x18\x01 \x01(\x0e\x32\x16.sam.v1.MeshEvent.Type\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x11\n\ttimestamp\x18\x03 \x01(\x03\x12\x16\n\x0enew_public_key\x18\x04 \x01(\x0c\x12\x11\n\tsignature\x18\x05 \x01(\x0c\"7\n\x04Type\x12\n\n\x06\x42\x41NNED\x10\x00\x12\x10\n\x0cKEY_ROTATION\x10\x01\x12\x11\n\rPOLICY_UPDATE\x10\x02\"\xeb\x01\n\rEnrollRequest\x12\x0b\n\x03jwt\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12\x31\n\x06labels\x18\x05 \x03(\x0b\x32!.sam.v1.EnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8e\x01\n\x0e\x45nrollResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x15\n\rerror_message\x18\x02 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x03 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x12\n\nexpiration\x18\x05 \x01(\x03\"\x89\x02\n\x16\x42ootstrapEnrollRequest\x12\x17\n\x0f\x62ootstrap_token\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12:\n\x06labels\x18\x05 \x03(\x0b\x32*.sam.v1.BootstrapEnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xe0\x01\n\x17\x42ootstrapEnrollResponse\x12(\n\x06status\x18\x01 \x01(\x0e\x32\x18.sam.v1.EnrollmentStatus\x12\x15\n\rbiscuit_token\x18\x02 \x01(\x0c\x12\x1d\n\x15poll_interval_seconds\x18\x03 \x01(\x05\x12\x15\n\rerror_message\x18\x04 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x05 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x06 \x03(\t\x12\x12\n\nexpiration\x18\x07 \x01(\x03\"S\n\x0bServiceInfo\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\"{\n\x0e\x43ommandBackend\x12\x0f\n\x07\x63ommand\x18\x01 \x03(\t\x12,\n\x03\x65nv\x18\x02 \x03(\x0b\x32\x1f.sam.v1.CommandBackend.EnvEntry\x1a*\n\x08\x45nvEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8a\x01\n\x16RegisterServiceRequest\x12$\n\x07service\x18\x01 \x01(\x0b\x32\x13.sam.v1.ServiceInfo\x12\x14\n\ntarget_url\x18\x02 \x01(\tH\x00\x12)\n\x07\x63ommand\x18\x03 \x01(\x0b\x32\x16.sam.v1.CommandBackendH\x00\x42\t\n\x07\x62\x61\x63kend\"i\n\x12\x44iscoveredProvider\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x17\n\x0flocal_proxy_url\x18\x02 \x01(\t\x12\x10\n\x08srv_name\x18\x03 \x01(\t\x12\x17\n\x0fsrv_description\x18\x04 \x01(\t\"\x92\x02\n\x0fServiceAnnounce\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12!\n\x04type\x18\x02 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x14\n\x0cservice_name\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x33\n\x06labels\x18\x05 \x03(\x0b\x32#.sam.v1.ServiceAnnounce.LabelsEntry\x12\x17\n\x0f\x61\x63tive_requests\x18\x06 \x01(\r\x12\x17\n\x0flatency_ewma_ms\x18\x07 \x01(\x01\x12\x11\n\ttimestamp\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x87\x01\n\x18\x43ontrolPlaneInfoResponse\x12\x13\n\x0boidc_issuer\x18\x01 \x01(\t\x12\x11\n\tclient_id\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x17\n\x0f\x62\x61nned_peer_ids\x18\x05 \x03(\t\"\xa4\x01\n\x12RouterLeaseRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\x12\x17\n\x0f\x63onnected_peers\x18\x04 \x03(\t\x12\x10\n\x08\x64ht_size\x18\x05 \x01(\x05\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\"I\n\x13RouterLeaseResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"\x95\x01\n\nPolicyRole\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0f\x61llowed_targets\x18\x02 \x03(\t\x12\x18\n\x10\x61llowed_services\x18\x03 \x03(\t\x12\x16\n\x0e\x63ustom_datalog\x18\x04 \x03(\t\x12\x16\n\x0e\x61llowed_agents\x18\x05 \x03(\t\x12\x16\n\x0e\x61llowed_labels\x18\x06 \x03(\t\".\n\rPolicyBinding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\t\"Z\n\x0cPolicyConfig\x12!\n\x05roles\x18\x01 \x03(\x0b\x32\x12.sam.v1.PolicyRole\x12\'\n\x08\x62indings\x18\x02 \x03(\x0b\x32\x15.sam.v1.PolicyBinding\"\x18\n\x16PolicyConfigGetRequest\"M\n\x17PolicyConfigGetResponse\x12\x15\n\rdatalog_rules\x18\x03 \x03(\tJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03R\x05rolesR\x08\x62indings\"<\n\x1aPolicyConfigUpdateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"J\n\x0cKeysResponse\x12\x13\n\x0bpublic_keys\x18\x01 \x03(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x12\n\nsignatures\x18\x03 \x03(\x0c\"V\n\x13TokenRefreshRequest\x12\x1b\n\x13\x63hallenge_signature\x18\x01 \x01(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x0f\n\x07peer_id\x18\x03 \x01(\t\"X\n\x14TokenRefreshResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x12\n\nexpires_at\x18\x02 \x01(\x03\x12\x15\n\rerror_message\x18\x03 \x01(\t\":\n\x11NodeCatalogReport\x12%\n\x08services\x18\x01 \x03(\x0b\x32\x13.sam.v1.ServiceInfo\"%\n\x12TokenRevokeRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\"5\n\x13TokenRevokeResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"R\n\x0b\x41gentSecret\x12\x0c\n\x04host\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x13\n\x0bheader_name\x18\x03 \x01(\t\x12\x12\n\nvalue_path\x18\x04 \x01(\t\"B\n\x0b\x41gentEgress\x12\r\n\x05\x61llow\x18\x01 \x03(\t\x12$\n\x07secrets\x18\x02 \x03(\x0b\x32\x13.sam.v1.AgentSecret\"b\n\x0c\x41gentIngress\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0c\n\x04port\x18\x03 \x01(\r\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t\"\xaa\x01\n\x0b\x41gentBundle\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x10\n\x08\x61gent_id\x18\x02 \x01(\t\x12\x13\n\x0b\x65xternal_id\x18\x03 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x04 \x01(\t\x12#\n\x06\x65gress\x18\x05 \x01(\x0b\x32\x13.sam.v1.AgentEgress\x12%\n\x07ingress\x18\x06 \x03(\x0b\x32\x14.sam.v1.AgentIngress\"9\n\x12\x41gentAttachRequest\x12#\n\x06\x62undle\x18\x01 \x01(\x0b\x32\x13.sam.v1.AgentBundle\"S\n\x13\x41gentAttachResponse\x12\x15\n\regress_socket\x18\x01 \x01(\t\x12\x16\n\x0eingress_socket\x18\x02 \x01(\t\x12\r\n\x05\x65rror\x18\x03 \x01(\t\"&\n\x12\x41gentDetachRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"5\n\x13\x41gentDetachResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"@\n\x13\x41gentRefreshRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x02 \x01(\t\"J\n\x14\x41gentRefreshResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"&\n\x12\x41gentStatusRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"w\n\x0b\x41gentStatus\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x10\n\x08\x61ttached\x18\x02 \x01(\x08\x12%\n\x07ingress\x18\x03 \x03(\x0b\x32\x14.sam.v1.AgentIngress\x12\x1d\n\x15\x63redential_expires_at\x18\x04 \x01(\x03\"I\n\x13\x41gentStatusResponse\x12#\n\x06\x61gents\x18\x01 \x03(\x0b\x32\x13.sam.v1.AgentStatus\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"\xab\x01\n\x18IdentityEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x1a\n\x12\x62iscuit_expires_at\x18\x03 \x01(\x03\x12\x19\n\x11\x63ontrol_plane_url\x18\x04 \x01(\t\x12\"\n\x1atrusted_control_plane_keys\x18\x05 \x03(\x0c\x12\x12\n\nchecked_at\x18\x06 \x01(\x03\"\x87\x02\n\x14PeerEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x15\n\rverifying_key\x18\x03 \x01(\x0c\x12\r\n\x05roles\x18\x04 \x03(\t\x12\x38\n\x06labels\x18\x05 \x03(\x0b\x32(.sam.v1.PeerEvidenceResponse.LabelsEntry\x12\x12\n\nexpiration\x18\x06 \x01(\x03\x12\x16\n\x0erevocation_ids\x18\x07 \x03(\t\x12\x12\n\nchecked_at\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01*\x94\x01\n\x10\x45nrollmentStatus\x12!\n\x1d\x45NROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n\x19\x45NROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n\x1a\x45NROLLMENT_STATUS_APPROVED\x10\x02\x12\x1e\n\x1a\x45NROLLMENT_STATUS_REJECTED\x10\x03*s\n\x0bServiceType\x12\x1c\n\x18SERVICE_TYPE_UNSPECIFIED\x10\x00\x12\x14\n\x10SERVICE_TYPE_MCP\x10\x01\x12\x1a\n\x16SERVICE_TYPE_INFERENCE\x10\x02\x12\x14\n\x10SERVICE_TYPE_A2A\x10\x03\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sam_pb2', globals())@@ -31,10 +31,10 @@ if _descriptor._USE_C_DESCRIPTORS == False:_SERVICEANNOUNCE_LABELSENTRY._serialized_options = b'8\001'_PEEREVIDENCERESPONSE_LABELSENTRY._options = None_PEEREVIDENCERESPONSE_LABELSENTRY._serialized_options = b'8\001'- _ENROLLMENTSTATUS._serialized_start=4723- _ENROLLMENTSTATUS._serialized_end=4871- _SERVICETYPE._serialized_start=4873- _SERVICETYPE._serialized_end=4988+ _ENROLLMENTSTATUS._serialized_start=4686+ _ENROLLMENTSTATUS._serialized_end=4834+ _SERVICETYPE._serialized_start=4836+ _SERVICETYPE._serialized_end=4951_AUTHFRAME._serialized_start=21_AUTHFRAME._serialized_end=88_AUTHRESPONSE._serialized_start=90@@ -79,56 +79,56 @@ if _descriptor._USE_C_DESCRIPTORS == False:_POLICYROLE._serialized_end=2486_POLICYBINDING._serialized_start=2488_POLICYBINDING._serialized_end=2534- _POLICYCONFIGGETREQUEST._serialized_start=2536- _POLICYCONFIGGETREQUEST._serialized_end=2560- _POLICYCONFIGGETRESPONSE._serialized_start=2562- _POLICYCONFIGGETRESPONSE._serialized_end=2663- _POLICYCONFIGUPDATEREQUEST._serialized_start=2665- _POLICYCONFIGUPDATEREQUEST._serialized_end=2768- _POLICYCONFIGUPDATERESPONSE._serialized_start=2770- _POLICYCONFIGUPDATERESPONSE._serialized_end=2830- _KEYSRESPONSE._serialized_start=2832- _KEYSRESPONSE._serialized_end=2906- _TOKENREFRESHREQUEST._serialized_start=2908- _TOKENREFRESHREQUEST._serialized_end=2994- _TOKENREFRESHRESPONSE._serialized_start=2996- _TOKENREFRESHRESPONSE._serialized_end=3084- _NODECATALOGREPORT._serialized_start=3086- _NODECATALOGREPORT._serialized_end=3144- _TOKENREVOKEREQUEST._serialized_start=3146- _TOKENREVOKEREQUEST._serialized_end=3183- _TOKENREVOKERESPONSE._serialized_start=3185- _TOKENREVOKERESPONSE._serialized_end=3238- _AGENTSECRET._serialized_start=3240- _AGENTSECRET._serialized_end=3322- _AGENTEGRESS._serialized_start=3324- _AGENTEGRESS._serialized_end=3390- _AGENTINGRESS._serialized_start=3392- _AGENTINGRESS._serialized_end=3490- _AGENTBUNDLE._serialized_start=3493- _AGENTBUNDLE._serialized_end=3663- _AGENTATTACHREQUEST._serialized_start=3665- _AGENTATTACHREQUEST._serialized_end=3722- _AGENTATTACHRESPONSE._serialized_start=3724- _AGENTATTACHRESPONSE._serialized_end=3807- _AGENTDETACHREQUEST._serialized_start=3809- _AGENTDETACHREQUEST._serialized_end=3847- _AGENTDETACHRESPONSE._serialized_start=3849- _AGENTDETACHRESPONSE._serialized_end=3902- _AGENTREFRESHREQUEST._serialized_start=3904- _AGENTREFRESHREQUEST._serialized_end=3968- _AGENTREFRESHRESPONSE._serialized_start=3970- _AGENTREFRESHRESPONSE._serialized_end=4044- _AGENTSTATUSREQUEST._serialized_start=4046- _AGENTSTATUSREQUEST._serialized_end=4084- _AGENTSTATUS._serialized_start=4086- _AGENTSTATUS._serialized_end=4205- _AGENTSTATUSRESPONSE._serialized_start=4207- _AGENTSTATUSRESPONSE._serialized_end=4280- _IDENTITYEVIDENCERESPONSE._serialized_start=4283- _IDENTITYEVIDENCERESPONSE._serialized_end=4454- _PEEREVIDENCERESPONSE._serialized_start=4457- _PEEREVIDENCERESPONSE._serialized_end=4720+ _POLICYCONFIG._serialized_start=2536+ _POLICYCONFIG._serialized_end=2626+ _POLICYCONFIGGETREQUEST._serialized_start=2628+ _POLICYCONFIGGETREQUEST._serialized_end=2652+ _POLICYCONFIGGETRESPONSE._serialized_start=2654+ _POLICYCONFIGGETRESPONSE._serialized_end=2731+ _POLICYCONFIGUPDATERESPONSE._serialized_start=2733+ _POLICYCONFIGUPDATERESPONSE._serialized_end=2793+ _KEYSRESPONSE._serialized_start=2795+ _KEYSRESPONSE._serialized_end=2869+ _TOKENREFRESHREQUEST._serialized_start=2871+ _TOKENREFRESHREQUEST._serialized_end=2957+ _TOKENREFRESHRESPONSE._serialized_start=2959+ _TOKENREFRESHRESPONSE._serialized_end=3047+ _NODECATALOGREPORT._serialized_start=3049+ _NODECATALOGREPORT._serialized_end=3107+ _TOKENREVOKEREQUEST._serialized_start=3109+ _TOKENREVOKEREQUEST._serialized_end=3146+ _TOKENREVOKERESPONSE._serialized_start=3148+ _TOKENREVOKERESPONSE._serialized_end=3201+ _AGENTSECRET._serialized_start=3203+ _AGENTSECRET._serialized_end=3285+ _AGENTEGRESS._serialized_start=3287+ _AGENTEGRESS._serialized_end=3353+ _AGENTINGRESS._serialized_start=3355+ _AGENTINGRESS._serialized_end=3453+ _AGENTBUNDLE._serialized_start=3456+ _AGENTBUNDLE._serialized_end=3626+ _AGENTATTACHREQUEST._serialized_start=3628+ _AGENTATTACHREQUEST._serialized_end=3685+ _AGENTATTACHRESPONSE._serialized_start=3687+ _AGENTATTACHRESPONSE._serialized_end=3770+ _AGENTDETACHREQUEST._serialized_start=3772+ _AGENTDETACHREQUEST._serialized_end=3810+ _AGENTDETACHRESPONSE._serialized_start=3812+ _AGENTDETACHRESPONSE._serialized_end=3865+ _AGENTREFRESHREQUEST._serialized_start=3867+ _AGENTREFRESHREQUEST._serialized_end=3931+ _AGENTREFRESHRESPONSE._serialized_start=3933+ _AGENTREFRESHRESPONSE._serialized_end=4007+ _AGENTSTATUSREQUEST._serialized_start=4009+ _AGENTSTATUSREQUEST._serialized_end=4047+ _AGENTSTATUS._serialized_start=4049+ _AGENTSTATUS._serialized_end=4168+ _AGENTSTATUSRESPONSE._serialized_start=4170+ _AGENTSTATUSRESPONSE._serialized_end=4243+ _IDENTITYEVIDENCERESPONSE._serialized_start=4246+ _IDENTITYEVIDENCERESPONSE._serialized_end=4417+ _PEEREVIDENCERESPONSE._serialized_start=4420+ _PEEREVIDENCERESPONSE._serialized_end=4683_PEEREVIDENCERESPONSE_LABELSENTRY._serialized_start=534_PEEREVIDENCERESPONSE_LABELSENTRY._serialized_end=579# @@protoc_insertion_point(module_scope)diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyiindex a3a8d51e..5e2c4816 100644--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi@@ -365,11 +365,7 @@ class PolicyBinding(_message.Message):role: strdef __init__(self, role: _Optional[str] = ..., members: _Optional[_Iterable[str]] = ...) -> None: ...-class PolicyConfigGetRequest(_message.Message):- __slots__ = []- def __init__(self) -> None: ...--class PolicyConfigGetResponse(_message.Message):+class PolicyConfig(_message.Message):__slots__ = ["bindings", "roles"]BINDINGS_FIELD_NUMBER: _ClassVar[int]ROLES_FIELD_NUMBER: _ClassVar[int]@@ -377,13 +373,15 @@ class PolicyConfigGetResponse(_message.Message):roles: _containers.RepeatedCompositeFieldContainer[PolicyRole]def __init__(self, roles: _Optional[_Iterable[_Union[PolicyRole, _Mapping]]] = ..., bindings: _Optional[_Iterable[_Union[PolicyBinding, _Mapping]]] = ...) -> None: ...-class PolicyConfigUpdateRequest(_message.Message):- __slots__ = ["bindings", "roles"]- BINDINGS_FIELD_NUMBER: _ClassVar[int]- ROLES_FIELD_NUMBER: _ClassVar[int]- bindings: _containers.RepeatedCompositeFieldContainer[PolicyBinding]- roles: _containers.RepeatedCompositeFieldContainer[PolicyRole]- def __init__(self, roles: _Optional[_Iterable[_Union[PolicyRole, _Mapping]]] = ..., bindings: _Optional[_Iterable[_Union[PolicyBinding, _Mapping]]] = ...) -> None: ...+class PolicyConfigGetRequest(_message.Message):+ __slots__ = []+ def __init__(self) -> None: ...++class PolicyConfigGetResponse(_message.Message):+ __slots__ = ["datalog_rules"]+ DATALOG_RULES_FIELD_NUMBER: _ClassVar[int]+ datalog_rules: _containers.RepeatedScalarFieldContainer[str]+ def __init__(self, datalog_rules: _Optional[_Iterable[str]] = ...) -> None: ...class PolicyConfigUpdateResponse(_message.Message):__slots__ = ["error", "success"]diff --git a/site/content/docs/concepts/authorization.md b/site/content/docs/concepts/authorization.mdindex 6de4c2ad..e698e18e 100644--- a/site/content/docs/concepts/authorization.md+++ b/site/content/docs/concepts/authorization.md@@ -93,16 +93,17 @@ becomes `granted_service_exact("mcp", "calculator")`, `mcp://*` becomes`granted_service_suffix("mcp", ".internal")`. Wildcards keep their dot, so`*.acme.example` matches `svc.acme.example` but not `evil-acme.example`.-Nodes also fetch the policy themselves, every `--control-plane-sync-interval`-(15 minutes by default, sooner when a policy update event reaches them), and-compile it into rules such as+The control plane also renders the policy as Datalog rules such as`role("developer") <- group("eng")` and-`granted_service_exact("mcp", "calculator") <- role("developer")`. When a-node verifies a credential, these rules run against the identity facts in it.-A grant added to the policy therefore reaches every node within the sync-interval, with no need to reissue credentials. Removing a grant takes effect-through the credential instead: the facts already in a token stay valid until-the token is refreshed, which happens within its TTL (24 hours by default).+`granted_service_exact("mcp", "calculator") <- role("developer")`. Nodes+fetch this text every `--control-plane-sync-interval` (15 minutes by default,+sooner when a policy update event reaches them) and add it to their+authorizer as it arrives. When a node verifies a credential, these rules run+against the identity facts in it. A grant added to the policy therefore+reaches every node within the sync interval, with no need to reissue+credentials. Removing a grant takes effect through the credential instead:+the facts already in a token stay valid until the token is refreshed, which+happens within its TTL (24 hours by default).## What the hosting node checks@@ -127,7 +128,7 @@ Biscuit authorizer and adds the following, in this order:5. **The baseline policies**: `allow if service($t,$n), granted_service_exact($t,$n)`and the equivalent policies for sets, prefixes, suffixes, per-type andglobal wildcards, plus the target check- `allow_network_target(...) or target_unrestricted()`.+ `allow_network_target(...) or target_unrestricted(true)`.6. **The synced mesh policy rules** described above.Biscuit evaluates every `check` and requires all of them to pass. It thendiff --git a/site/content/docs/preview/agent-architecture.md b/site/content/docs/preview/agent-architecture.mdindex 0f5a4788..7a8b679e 100644--- a/site/content/docs/preview/agent-architecture.md+++ b/site/content/docs/preview/agent-architecture.md@@ -292,7 +292,7 @@ round trip and no central state.**Policy is written over namespaces.** The same machinery that compiles`allowed_services` wildcards compiles `allowed_agents` into`granted_agent_prefix`, `_suffix`, `_set` and `_exact`, and the destination-derives `agent_authorized()` from them. "Foo yes, bar no" is a namespace, a+derives `agent_authorized(true)` from them. "Foo yes, bar no" is a namespace, aset or a prefix, never a list of a billion names.**Revocation has three levels.**diff --git a/site/content/docs/reference/control-plane.md b/site/content/docs/reference/control-plane.mdindex 074ee299..0f517032 100644--- a/site/content/docs/reference/control-plane.md+++ b/site/content/docs/reference/control-plane.md@@ -40,9 +40,12 @@ sam-control-plane admin unban --peer <id> lift a ban## HTTP API-Two encodings are in use. Routes that mesh components call use protobuf-(`application/x-protobuf`), with messages defined in `api/sam.proto`. Routes-for operators and the console use JSON. `POST /policies` accepts either.+Every request and response is a message in `api/sam.proto`, in one of two+encodings. Routes that mesh components call use binary protobuf+(`application/x-protobuf`). Routes for operators and the console use+protojson of the same messages, with proto field names; unknown fields are+rejected. `POST /policies` accepts either and answers in the encoding of the+request.Responses that carry credentials are sent with `Cache-Control: no-store`.@@ -70,7 +73,7 @@ caller holds the key behind the peer ID it names.| `GET /enroll/status?peer_id=` | headers `X-Sam-Challenge-Ts`, `X-Sam-Challenge-Sig` | Poll a pending enrollment. Any authentication failure answers `401`, so the credential is released only to the enrollee. || `POST /refresh` | `TokenRefreshRequest`, current credential as `Authorization: Bearer <base64>` | Exchange a credential for a new one. Refuses a replayed (superseded) credential, a banned node, an expired session, and a credential signed by a retired key unless the node has `autonomous_recovery`. || `POST /routers/lease` | `RouterLeaseRequest` (credential, addresses, telemetry) | Register or renew a router lease. Requires `role("sam:role:router")`. Announced addresses must end in the router's own peer ID. |-| `GET /policies` | credential as `Authorization: Bearer <base64>` | The mesh policy as `PolicyConfigGetResponse`. Also accepts the admin token. |+| `GET /policies` | credential as `Authorization: Bearer <base64>` | The mesh policy as `PolicyConfigGetResponse`: the Datalog rules a member adds to its authorizer, one per entry. Operators read the document at `GET /admin/policy`. || `POST /nodes/catalog` | `NodeCatalogReport`, credential as bearer | A node's report of the services it publishes, for the console. Display only. Never used for authorization. |### Admin@@ -80,7 +83,8 @@ All routes require `Authorization: Bearer <admin-token>` and use JSON.| Route | Purpose ||---|---|| `GET /admin/status` | Everything the console shows: routers, nodes, enrollment requests, tokens, users, and the policy as JSON. |-| `POST /policies`, `PUT /policies` | Replace the mesh policy. The JSON body is protojson of `PolicyConfigUpdateRequest`. Unknown fields are rejected, so a misspelt grant fails instead of being dropped. |+| `GET /admin/policy` | The mesh policy as protojson of `PolicyConfig`, the same document `POST /policies` takes. |+| `POST /policies`, `PUT /policies` | Replace the mesh policy. The JSON body is protojson of `PolicyConfig`. Unknown fields are rejected, so a misspelt grant fails instead of being dropped. || `POST /admin/bootstrap-tokens` | Mint a token. Body: `role` (required), `ttl_hours` (default 24), `max_usages` (default 1), `description`, `autonomous_recovery` (default false). Returns `201` with `id`, `token` (shown once), `role`, `expires_at`. || `DELETE /admin/bootstrap-tokens/{id}` | Revoke a token. Can be repeated. The token stays in the list, marked as revoked. || `GET /admin/enrollments` | Pending bootstrap enrollment requests. |diff --git a/site/content/docs/reference/policy.md b/site/content/docs/reference/policy.mdindex cc752b4f..11157ad9 100644--- a/site/content/docs/reference/policy.md+++ b/site/content/docs/reference/policy.md@@ -7,9 +7,9 @@ aliases:---The mesh policy is one document held by the control plane: a list of roles-and a list of bindings. It is posted as JSON (protojson of-`PolicyConfigUpdateRequest` in `api/sam.proto`) to `POST /policies`, edited-in the console, or given to `sam-one --policy-file` for first boot.+and a list of bindings. It is posted as JSON (protojson of `PolicyConfig` in+`api/sam.proto`) to `POST /policies`, read back from `GET /admin/policy`,+edited in the console, or given to `sam-one --policy-file` for first boot.```json{@@ -60,7 +60,12 @@ notice.| `mcp://*.internal` | `granted_service_suffix("mcp", ".internal")` | `a.internal` and `b.c.internal`, but not `xinternal` || `mcp://build.*` | `granted_service_prefix("mcp", "build.")` | `build.runner`, but not `builder` || `mcp://*` | `granted_service_all("mcp")` | every MCP service |-| `*` | `granted_service_all_types()` | every service |+| `*` | `granted_service_all_types(true)` | every service |++A fact whose only meaning is that a grant exists carries the single term+`true`, because the Biscuit grammar requires at least one term per predicate.+The same holds for `target_unrestricted(true)`, `granted_agent_all(true)` and+`agent_authorized(true)` below.`system://sam.catalog` is the built-in discovery service that every noderuns. A role that should be able to list the tools of a node needs it.@@ -144,25 +149,29 @@ must be on the role itself.At enrollment and at refresh, the control plane resolves the identity's rolesfrom the bindings and mints into the credential one `role()` fact per role-and the compiled `granted_*` facts of every role. Nodes also fetch the policy-(`--control-plane-sync-interval`, 15 minutes) and compile it into rules such as+and the compiled `granted_*` facts of every role. The control plane also+renders the policy as Datalog rules such as`role("developer") <- group("engineering")` and-`granted_service_exact("mcp","code-reviewer") <- role("developer")`. These-rules run at verification time. Additions therefore reach nodes within the-sync interval, and removals within the credential TTL.+`granted_service_exact("mcp","code-reviewer") <- role("developer")`, served+as `datalog_rules` at `GET /policies`. Nodes fetch this text+(`--control-plane-sync-interval`, 15 minutes) and add it to their authorizer+as it arrives; no member derives rules from roles and bindings itself, so a+node written in any language evaluates the same rules. These rules run at+verification time. Additions therefore reach nodes within the sync interval,+and removals within the credential TTL.At the destination node, in this order:1. Facts for the request: `service($type, $name)`, `connection_peer_id($id)`,`time($now)`, and `agent($id)` if a claim was made.2. Checks that always apply: `client_peer_id($id), connection_peer_id($id)`,- `time($t), expiration($e), $t <= $e`, and `agent_authorized()` when an+ `time($t), expiration($e), $t <= $e`, and `agent_authorized(true)` when anagent was named.3. The node's own identity as `target_fact($name, $value)` facts.4. The node's `attenuation` rules, checks and policies.5. Baseline policies: `allow if service($t,$n), granted_service_exact($t,$n)`and the set, prefix, suffix, per-type and global variants; the check- `allow_network_target($f,$v) or target_unrestricted()`.+ `allow_network_target($f,$v) or target_unrestricted(true)`.6. The synced mesh policy rules.All checks must hold, and the first matching policy decides. Without adiff --git a/site/content/docs/reference/sam-one.md b/site/content/docs/reference/sam-one.mdindex cf52425e..10217f02 100644--- a/site/content/docs/reference/sam-one.md+++ b/site/content/docs/reference/sam-one.md@@ -38,7 +38,7 @@ downloaded tunnel connector.| `--token-path` | | File containing the standing join token. Can also be set with `SAM_TOKEN`. Generated and saved to the data directory when neither is set. || `--no-join-token` | `false` | Run without a standing join token. Devices can then enroll only with minted tokens or OIDC. || `--admin-token-path` | | File containing the admin token. Can also be set with `SAM_ADMIN_TOKEN`. Generated and saved to the data directory when neither is set. |-| `--policy-file` | | Protojson `PolicyConfigUpdateRequest` that seeds the mesh policy on first boot. Ignored once the database has a policy. Without it, first boot seeds an open development policy and logs a warning. |+| `--policy-file` | | Protojson `PolicyConfig` that seeds the mesh policy on first boot. Ignored once the database has a policy. Without it, first boot seeds an open development policy and logs a warning. || `--issuer` | | External OIDC issuer(s), comma-separated. Optional. Without an issuer, enrollment works by token only. || `--oidc-client-id` | first audience | Client ID advertised on `/info`. || `--allowed-audiences` | `sam-mesh-audience` | Accepted OIDC audiences. |diff --git a/tests/integration/biscuit_expiry_test.go b/tests/integration/biscuit_expiry_test.goindex 1e0eb464..6af4a691 100644--- a/tests/integration/biscuit_expiry_test.go+++ b/tests/integration/biscuit_expiry_test.go@@ -84,7 +84,7 @@ func TestBiscuitExpiryIsEnforcedOnEveryPath(t *testing.T) {// The grants mirror the shape this test always ran with (the no-policy// mint fallback): unrestricted, because the subject here is expiry.policyFile := filepath.Join(tmpDir, "policies.yaml")- policyYAML := "roles:\n - name: sam:role:node\n allowed_services: [\"*\"]\n allowed_targets: []\n custom_datalog: [\"target_unrestricted();\"]\nbindings:\n - role: sam:role:node\n members: [\"user:expiry-user\"]\n"+ policyYAML := "roles:\n - name: sam:role:node\n allowed_services: [\"*\"]\n allowed_targets: []\n custom_datalog: [\"target_unrestricted(true);\"]\nbindings:\n - role: sam:role:node\n members: [\"user:expiry-user\"]\n"if err := os.WriteFile(policyFile, []byte(policyYAML), 0644); err != nil {t.Fatal(err)}diff --git a/tests/integration/controlplane_pubsub_integration_test.go b/tests/integration/controlplane_pubsub_integration_test.goindex 2af22112..b545d170 100644--- a/tests/integration/controlplane_pubsub_integration_test.go+++ b/tests/integration/controlplane_pubsub_integration_test.go@@ -121,7 +121,7 @@ func TestControlPlanePubSubEventIntegration(t *testing.T) {time.Sleep(500 * time.Millisecond)// 4. Trigger POST /policies on Control Plane- policyReq := &api.PolicyConfigUpdateRequest{+ policyReq := &api.PolicyConfig{Roles: []*api.PolicyRole{{Name: "developer",diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex abb51d21..770df890 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -329,7 +329,7 @@ func startMockRouterWithControlPlaneKey(t *testing.T) (peer.ID, string, ed25519.func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKey, role string, labels map[string]string) []byte {builder := biscuit.NewBuilder(priv)- err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})+ err := builder.AddAuthorityFact(api.MarkerFact(api.FactTargetUnrestricted))if err != nil {t.Fatalf("failed to add target_unrestricted: %v", err)}@@ -384,9 +384,7 @@ func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKeyt.Fatalf("failed to add client_peer_id fact: %v", err)}- err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: "granted_service_all_types",- }})+ err = builder.AddAuthorityFact(api.MarkerFact(api.FactGrantedServiceAllTypes))if err != nil {t.Fatalf("failed to add granted_service_all_types fact: %v", err)}diff --git a/tests/integration/policy_grants_test.go b/tests/integration/policy_grants_test.goindex b04f87a4..fe4d9367 100644--- a/tests/integration/policy_grants_test.go+++ b/tests/integration/policy_grants_test.go@@ -33,6 +33,7 @@ import ("github.com/google/sam/internal/identity""github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer"+ "google.golang.org/protobuf/encoding/protojson""google.golang.org/protobuf/proto")@@ -86,7 +87,7 @@ func TestPolicyGrantsReachTheMintedToken(t *testing.T) {AllowedAgents: []string{"*.prod.acme.example"},AllowedLabels: []string{"region=*"},}- policyBody, err := proto.Marshal(&api.PolicyConfigUpdateRequest{+ policyBody, err := proto.Marshal(&api.PolicyConfig{Roles: []*api.PolicyRole{wantRole},Bindings: []*api.PolicyBinding{{Role: api.RoleNode,@@ -114,23 +115,23 @@ func TestPolicyGrantsReachTheMintedToken(t *testing.T) {}t.Run("every grant survives the policy store", func(t *testing.T) {- req, err := http.NewRequest(http.MethodGet, baseURL+"/policies", nil)+ req, err := http.NewRequest(http.MethodGet, baseURL+"/admin/policy", nil)if err != nil {t.Fatal(err)}req.Header.Set("Authorization", "Bearer "+adminToken)resp, err := client.Do(req)if err != nil {- t.Fatalf("GET /policies: %v", err)+ t.Fatalf("GET /admin/policy: %v", err)}body, _ := io.ReadAll(resp.Body)_ = resp.Body.Close()if resp.StatusCode != http.StatusOK {- t.Fatalf("GET /policies status %d: %s", resp.StatusCode, body)+ t.Fatalf("GET /admin/policy status %d: %s", resp.StatusCode, body)}- var got api.PolicyConfigGetResponse- if err := proto.Unmarshal(body, &got); err != nil {+ var got api.PolicyConfig+ if err := protojson.Unmarshal(body, &got); err != nil {t.Fatalf("unmarshal policy: %v", err)}if len(got.Roles) != 1 {