Skip to content

Agent Mesh

feat(auth,node): add wildcard bindings, workload issuer containment, refresh re-attestation, and security architecture docs

Antonio Ojea3966a01cdad0
diff --git a/AGENTS.md b/AGENTS.md
index 73812c78..35169d1f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,8 +9,8 @@ You are an expert software engineering assistant helping to develop, maintain, a
* **Instants are `google.protobuf.Timestamp`, named `*_time`** (`expire_time`, `sign_time`, `event_time`), never `int64` seconds or milliseconds. `Timestamp` has fixed units, an explicit unset, renders as RFC 3339 in protojson (an `int64` renders as a quoted decimal string), and has a first-class conversion in Go, JavaScript, Python and Dart. A receiver treats an unset instant as invalid, never as the epoch. The one exception is a proof-of-possession value: it is the number that appears in the signed text (`sam:<endpoint>:<peer_id>:<n>`), so it stays an `int64` named `challenge_unix_ms`, the unit in the name. What a member persists between runs is also a message here (`MemberCredential`), so a state directory written by one implementation loads in another.
* **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.
-* **Task-Scoped Authorization & Safe Biscuit Attenuation (`tar_block`):** SAM acts as the Authority, Policy Decision Point (PDP), and Task-Scoped Credential Layer (`sts.md`). Never add Datalog rules or checks to non-authority Biscuit blocks (`block_idx >= 1`). Appended blocks must contain 0 rules, 0 checks, and exactly 1 `tar_block("<base64url-proto>")` fact encoding a serialized `api.TaskAuthorizationRule`. Verifiers enforce the intersection of Block 0 Datalog RBAC and every appended `TaskAuthorizationRule` in Go, TypeScript, and Python.
-* **Two-Token Model & Complementary Gateway/PEP Integration:** Inside the mesh, credentials are Biscuits; at both borders, credentials are standard JWTs (`sts.md`). Inbound platform credentials (OIDC, K8s SA, SPIFFE JWT-SVID) exchange into delegated Biscuits (`POST /token/exchange`); outbound verified Biscuits mint short-lived ES256 JWTs at the control plane (`POST /sts/token`) that the egress node exchanges at cloud STS endpoints (`CloudTokenExchanger`). `sam-node` integrates with existing gateways (`agentgateway`, Istio, Envoy) via Envoy `ext_authz` / `ext_proc` and RFC 8693 `/oauth/token`, while native SDKs (`sdk/js`, `sdk/python`) attenuate and seal Biscuits in memory.
+* **Task-Scoped Authorization & Safe Biscuit Attenuation (`tar_block`):** SAM acts as the Authority, Policy Decision Point (PDP), and Task-Scoped Credential Layer (`site/content/docs/contributing/security-architecture.md`). Never add Datalog rules or checks to non-authority Biscuit blocks (`block_idx >= 1`). Appended blocks must contain 0 rules, 0 checks, and exactly 1 `tar_block("<base64url-proto>")` fact encoding a serialized `api.TaskAuthorizationRule`. Verifiers enforce the intersection of Block 0 Datalog RBAC and every appended `TaskAuthorizationRule` in Go, TypeScript, and Python.
+* **Two-Token Model & Complementary Gateway/PEP Integration:** Inside the mesh, credentials are Biscuits; at both borders, credentials are standard JWTs (`site/content/docs/contributing/security-architecture.md`). Inbound platform credentials (OIDC, K8s SA, SPIFFE JWT-SVID) exchange into delegated Biscuits (`POST /token/exchange`); outbound verified Biscuits mint short-lived ES256 JWTs at the control plane (`POST /sts/token`) that the egress node exchanges at cloud STS endpoints (`CloudTokenExchanger`). `sam-node` integrates with existing gateways (`agentgateway`, Istio, Envoy) via Envoy `ext_authz` / `ext_proc` and RFC 8693 `/oauth/token`, while native SDKs (`sdk/js`, `sdk/python`) attenuate and seal Biscuits in memory.
* **Policy on Names:** egress policy, secret injection and routing decisions are made on the destination *name*, never on an IP. Deny by default.
* **Zero Trust:** Enforce a Zero Trust architecture. Assume no implicit trust between nodes, control planes, routers, or external actors. All data passing through the API must be authenticated, authorized, and validated.
* **Simple UX:** Maintain a very simple User Experience. Configuration, CLI usage, and error messages must be intuitive, minimal, and explicitly clear.
diff --git a/api/policy_rules.go b/api/policy_rules.go
index 7273e36a..c0441c5b 100644
--- a/api/policy_rules.go
+++ b/api/policy_rules.go
@@ -16,13 +16,104 @@ package api
import (
"fmt"
+ "slices"
+ "strconv"
"strings"
+ "unicode"
"github.com/biscuit-auth/biscuit-go/v2"
"github.com/biscuit-auth/biscuit-go/v2/parser"
"github.com/libp2p/go-libp2p/core/peer"
)
+func validateBindingMemberCharset(s string) error {
+ for _, r := range s {
+ if unicode.IsControl(r) || r == '"' || r == '\\' {
+ return fmt.Errorf("contains disallowed character %q", r)
+ }
+ }
+ return nil
+}
+
+// ValidateRoleName checks that a PolicyRole.name is non-empty and free of
+// characters that could break or inject Datalog rules.
+func ValidateRoleName(name string) error {
+ if strings.TrimSpace(name) == "" {
+ return fmt.Errorf("role name cannot be empty")
+ }
+ if err := validateBindingMemberCharset(name); err != nil {
+ return fmt.Errorf("role name %q is invalid: %w", name, err)
+ }
+ return nil
+}
+
+// ValidateBindingMember checks a single PolicyBinding.members entry.
+// It permits sam:system:authenticated, exact "<prefix>:<value>" members, and
+// a single leading "*<suffix>" or trailing "<prefix>*" wildcard on non-node
+// prefixes. Bare "<prefix>:*" is rejected as a disguised sam:system:authenticated,
+// and values containing '"', '\', or control characters are rejected to
+// prevent Datalog rule injection.
+func ValidateBindingMember(member string, role string) error {
+ if member == SystemAuthenticated {
+ return nil
+ }
+ parts := strings.SplitN(member, ":", 2)
+ if len(parts) != 2 || strings.TrimSpace(parts[1]) == "" {
+ return fmt.Errorf("member %q in binding for role %q is invalid, must be in format 'type:value' or %q", member, role, SystemAuthenticated)
+ }
+ prefix, value := parts[0], parts[1]
+ if !slices.Contains(BindingMemberPrefixes(), prefix) {
+ return fmt.Errorf("member prefix %q in member %q is invalid", prefix, member)
+ }
+ if err := validateBindingMemberCharset(value); err != nil {
+ return fmt.Errorf("member %q in binding for role %q is invalid: %w", member, role, err)
+ }
+ if strings.Contains(value, "*") {
+ if prefix == FactNode {
+ return fmt.Errorf("wildcard is not permitted in node binding member %q for role %q", member, role)
+ }
+ if value == "*" {
+ return fmt.Errorf("bare wildcard %q in binding for role %q is not permitted; use %q to match every authenticated identity", member, role, SystemAuthenticated)
+ }
+ leading := strings.HasPrefix(value, "*") && !strings.Contains(value[1:], "*")
+ trailing := strings.HasSuffix(value, "*") && !strings.Contains(value[:len(value)-1], "*")
+ if !leading && !trailing {
+ return fmt.Errorf("wildcard in binding member %q for role %q must be a single leading or trailing '*'", member, role)
+ }
+ }
+ return nil
+}
+
+// MatchBindingMemberValue reports whether any candidate claim value satisfies
+// pattern (exact match, "<prefix>*" starts_with, or "*<suffix>" ends_with).
+func MatchBindingMemberValue(candidates []string, pattern string) bool {
+ if pattern == "" || pattern == "*" {
+ return false
+ }
+ if strings.Contains(pattern, "*") {
+ if strings.HasSuffix(pattern, "*") && !strings.Contains(pattern[:len(pattern)-1], "*") {
+ prefix := pattern[:len(pattern)-1]
+ for _, c := range candidates {
+ if strings.HasPrefix(c, prefix) {
+ return true
+ }
+ }
+ return false
+ }
+ if strings.HasPrefix(pattern, "*") && !strings.Contains(pattern[1:], "*") {
+ suffix := pattern[1:]
+ for _, c := range candidates {
+ if strings.HasSuffix(c, suffix) {
+ return true
+ }
+ }
+ return false
+ }
+ return false
+ }
+ return slices.Contains(candidates, pattern)
+}
+
// 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 {
@@ -54,6 +145,10 @@ func BuildPolicyRules(roles []*PolicyRole, bindings []*PolicyBinding) (rules []P
if b == nil {
continue
}
+ if err := ValidateRoleName(b.Role); err != nil {
+ warnings = append(warnings, fmt.Sprintf("Binding has invalid role %q: %v", b.Role, err))
+ continue
+ }
roleHead := biscuit.Predicate{Name: FactRole, IDs: []biscuit.Term{biscuit.String(b.Role)}}
for _, m := range b.Members {
if m == SystemAuthenticated {
@@ -64,18 +159,49 @@ func BuildPolicyRules(roles []*PolicyRole, bindings []*PolicyBinding) (rules []P
if len(parts) != 2 || !allowedMemberPrefix[parts[0]] {
continue
}
- value := parts[1]
+ prefix, value := parts[0], parts[1]
// A token carries node() in peer.ID.String() form; an operator may
// have written any encoding peer.Decode accepts.
- if parts[0] == FactNode {
+ if prefix == FactNode {
id, err := peer.Decode(value)
if err != nil {
warnings = append(warnings, fmt.Sprintf("Binding member %q is not a peer ID and grants role %s to nobody: %v", m, b.Role, err))
continue
}
value = id.String()
+ add(roleHead, biscuit.Predicate{Name: prefix, IDs: []biscuit.Term{biscuit.String(value)}})
+ continue
}
- add(roleHead, biscuit.Predicate{Name: parts[0], IDs: []biscuit.Term{biscuit.String(value)}})
+ if strings.Contains(value, "*") {
+ if err := validateBindingMemberCharset(value); err != nil {
+ warnings = append(warnings, fmt.Sprintf("Binding member %q for role %s %v and grants role to nobody", m, b.Role, err))
+ continue
+ }
+ var text string
+ roleLiteral := fmt.Sprintf("%s(%s)", FactRole, strconv.Quote(b.Role))
+ switch {
+ case value == "*":
+ warnings = append(warnings, fmt.Sprintf("Binding member %q has a bare wildcard and grants role %s to nobody", m, b.Role))
+ continue
+ case strings.HasSuffix(value, "*") && !strings.Contains(value[:len(value)-1], "*"):
+ affix := value[:len(value)-1]
+ text = fmt.Sprintf("%s <- %s($v), $v.starts_with(%s)", roleLiteral, prefix, strconv.Quote(affix))
+ case strings.HasPrefix(value, "*") && !strings.Contains(value[1:], "*"):
+ affix := value[1:]
+ text = fmt.Sprintf("%s <- %s($v), $v.ends_with(%s)", roleLiteral, prefix, strconv.Quote(affix))
+ default:
+ warnings = append(warnings, fmt.Sprintf("Binding member %q has an invalid wildcard and grants role %s to nobody", m, b.Role))
+ continue
+ }
+ r, err := parser.FromStringRule(text)
+ if err != nil {
+ warnings = append(warnings, fmt.Sprintf("Failed to parse wildcard binding rule %q for role %s: %v", text, b.Role, err))
+ continue
+ }
+ rules = append(rules, PolicyRule{Rule: r, Text: text})
+ continue
+ }
+ add(roleHead, biscuit.Predicate{Name: prefix, IDs: []biscuit.Term{biscuit.String(value)}})
}
}
@@ -83,6 +209,10 @@ func BuildPolicyRules(roles []*PolicyRole, bindings []*PolicyBinding) (rules []P
if role == nil {
continue
}
+ if err := ValidateRoleName(role.Name); err != nil {
+ warnings = append(warnings, fmt.Sprintf("Role has invalid name %q: %v", role.Name, err))
+ continue
+ }
roleName := role.Name
fromRole := biscuit.Predicate{Name: FactRole, IDs: []biscuit.Term{biscuit.String(roleName)}}
diff --git a/api/policy_rules_test.go b/api/policy_rules_test.go
index b0d2c427..d14673fc 100644
--- a/api/policy_rules_test.go
+++ b/api/policy_rules_test.go
@@ -15,6 +15,7 @@
package api
import (
+ "slices"
"strings"
"testing"
@@ -120,3 +121,132 @@ func TestParseDatalogRulesRejectsWholeSet(t *testing.T) {
t.Fatal("expected an error for an unparseable rule")
}
}
+
+func TestValidateBindingMemberAndRoleName(t *testing.T) {
+ validMembers := []string{
+ SystemAuthenticated,
+ "email:*@example.com",
+ "user:system:serviceaccount:payments:*",
+ "user:spiffe://cluster.local/ns/payments/sa/*",
+ "group:eng-*",
+ "group:Engineering Team",
+ "group:Engineering *",
+ "group:Équipe Ingénierie",
+ "group:team;ops",
+ "idp_role:*-worker",
+ "node:12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",
+ }
+ for _, m := range validMembers {
+ if err := ValidateBindingMember(m, "payments"); err != nil {
+ t.Errorf("ValidateBindingMember(%q) unexpected error: %v", m, err)
+ }
+ }
+
+ invalidMembers := []string{
+ "",
+ "user:",
+ "unknown:alice",
+ "user:*",
+ "email:*",
+ "group:*",
+ "node:*",
+ "node:12D3KooW*",
+ "user:system:serviceaccount:*:worker",
+ "user:*middle*",
+ `user:foo"); role("admin") <- true; //`,
+ `user:alice\bob`,
+ "user:alice\nbob",
+ "user:alice\x00bob",
+ "user:alice\x7fbob",
+ }
+ for _, m := range invalidMembers {
+ if err := ValidateBindingMember(m, "payments"); err == nil {
+ t.Errorf("ValidateBindingMember(%q) expected error, got nil", m)
+ }
+ }
+
+ for _, validRole := range []string{"payments-worker_1", "Engineering Team", "Équipe;Ops"} {
+ if err := ValidateRoleName(validRole); err != nil {
+ t.Errorf("ValidateRoleName(%q) unexpected error: %v", validRole, err)
+ }
+ }
+ for _, badRole := range []string{"", " ", `admin") <- true; //`, `role\slash`, "role\nnewline"} {
+ if err := ValidateRoleName(badRole); err == nil {
+ t.Errorf("ValidateRoleName(%q) expected error, got nil", badRole)
+ }
+ }
+}
+
+func TestMatchBindingMemberValue(t *testing.T) {
+ candidates := []string{
+ "system:serviceaccount:payments:worker-a",
+ }
+ cases := []struct {
+ pattern string
+ want bool
+ }{
+ {"system:serviceaccount:payments:worker-a", true},
+ {"system:serviceaccount:payments:worker-b", false},
+ {"system:serviceaccount:payments:*", true},
+ {"system:serviceaccount:billing:*", false},
+ {"*@proj.iam.gserviceaccount.com", true},
+ {"*@other.iam.gserviceaccount.com", false},
+ {"*", false},
+ {"system:serviceaccount:*:worker-a", false},
+ {"", false},
+ }
+ for _, tc := range cases {
+ if got := MatchBindingMemberValue(candidates, tc.pattern); got != tc.want {
+ t.Errorf("MatchBindingMemberValue(%q) = %v, want %v", tc.pattern, got, tc.want)
+ }
+ }
+}
+
+func TestBuildPolicyRulesWildcardsAndInjectionDefense(t *testing.T) {
+ roles := []*PolicyRole{
+ {
+ Name: "payments",
+ AllowedServices: []string{"mcp:Echo"},
+ },
+ }
+ bindings := []*PolicyBinding{
+ {
+ Role: "payments",
+ Members: []string{
+ "user:system:serviceaccount:payments:*",
+ "email:*@proj.iam.gserviceaccount.com",
+ "group:Engineering Team",
+ "group:Équipe Ingénierie",
+ "group:team;ops",
+ "user:*",
+ "user:system:*:Invalid",
+ `user:foo")*`,
+ },
+ },
+ }
+
+ rules, warnings := BuildPolicyRules(roles, bindings)
+ if len(warnings) != 3 {
+ t.Fatalf("warnings = %v, want 3 warnings for rejected wildcard entries", warnings)
+ }
+
+ texts := PolicyRuleTexts(rules)
+ wantRules := []string{
+ `role("payments") <- user($v), $v.starts_with("system:serviceaccount:payments:")`,
+ `role("payments") <- email($v), $v.ends_with("@proj.iam.gserviceaccount.com")`,
+ `role("payments") <- group("Engineering Team")`,
+ `role("payments") <- group("Équipe Ingénierie")`,
+ `role("payments") <- group("team;ops")`,
+ }
+ for _, want := range wantRules {
+ if !slices.Contains(texts, want) {
+ t.Errorf("missing expected rule %q in %v", want, texts)
+ }
+ }
+
+ if _, err := ParseDatalogRules(texts); err != nil {
+ t.Fatalf("ParseDatalogRules failed on generated rules: %v", err)
+ }
+}
diff --git a/api/sam.pb.go b/api/sam.pb.go
index 087f8150..6a78d874 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -2991,7 +2991,12 @@ type TokenRefreshRequest struct {
// if the node was opted in to autonomous recovery, accepts the request
// when the presented biscuit is byte-identical to the last one it
// issued and the challenge verifies against the stored public key.
- PeerId string `protobuf:"bytes,3,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
+ PeerId string `protobuf:"bytes,3,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
+ // Optional fresh platform JWT for an OIDC-enrolled node. When set, the
+ // control plane verifies the JWT, confirms that iss|sub matches the
+ // stored enrollment's identity, and renews the stored claims and session
+ // expiry in place before minting the refreshed biscuit.
+ Jwt string `protobuf:"bytes,4,opt,name=jwt,proto3" json:"jwt,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -3047,6 +3052,13 @@ func (x *TokenRefreshRequest) GetPeerId() string {
return ""
}
+func (x *TokenRefreshRequest) GetJwt() string {
+ if x != nil {
+ return x.Jwt
+ }
+ return ""
+}
+
type TokenRefreshResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
BiscuitToken []byte `protobuf:"bytes,1,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"`
@@ -4495,11 +4507,12 @@ const file_api_sam_proto_rawDesc = "" +
"\tsign_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\bsignTime\x12\x1e\n" +
"\n" +
"signatures\x18\x03 \x03(\fR\n" +
- "signatures\"\x8b\x01\n" +
+ "signatures\"\x9d\x01\n" +
"\x13TokenRefreshRequest\x12/\n" +
"\x13challenge_signature\x18\x01 \x01(\fR\x12challengeSignature\x12*\n" +
"\x11challenge_unix_ms\x18\x02 \x01(\x03R\x0fchallengeUnixMs\x12\x17\n" +
- "\apeer_id\x18\x03 \x01(\tR\x06peerId\"\x9d\x01\n" +
+ "\apeer_id\x18\x03 \x01(\tR\x06peerId\x12\x10\n" +
+ "\x03jwt\x18\x04 \x01(\tR\x03jwt\"\x9d\x01\n" +
"\x14TokenRefreshResponse\x12#\n" +
"\rbiscuit_token\x18\x01 \x01(\fR\fbiscuitToken\x12;\n" +
"\vexpire_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\n" +
diff --git a/api/sam.proto b/api/sam.proto
index ccc8a5f4..db1ff822 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -474,6 +474,11 @@ message TokenRefreshRequest {
// when the presented biscuit is byte-identical to the last one it
// issued and the challenge verifies against the stored public key.
string peer_id = 3;
+ // Optional fresh platform JWT for an OIDC-enrolled node. When set, the
+ // control plane verifies the JWT, confirms that iss|sub matches the
+ // stored enrollment's identity, and renews the stored claims and session
+ // expiry in place before minting the refreshed biscuit.
+ string jwt = 4;
}
message TokenRefreshResponse {
diff --git a/charts/sam-mesh/README.md b/charts/sam-mesh/README.md
index ba3a017d..6f78f479 100644
--- a/charts/sam-mesh/README.md
+++ b/charts/sam-mesh/README.md
@@ -66,6 +66,18 @@ administrator to approve each enrollment via `/admin/enrollments` before a
node can join — see the
[Headless enrollment guide](https://sam-mesh.dev/docs/guides/headless-enrollment/).
+## `controlPlane.workloadIssuer` and `controlPlane.workloadSessionTtl`
+
+When `controlPlane.oidcIssuer` includes a workload identity provider alongside a
+human identity provider (for example the Kubernetes API server issuer
+`https://kubernetes.default.svc.cluster.local`, a SPIRE OIDC Discovery Provider,
+or `https://accounts.google.com=.gserviceaccount.com` for Google Cloud service
+accounts), list it in `controlPlane.workloadIssuer` so those machine tokens are
+accepted at `/register`, `/refresh`, and `/token/exchange` and refused at the
+human surfaces (`/user/*`, `/oauth/authorize`). `controlPlane.workloadSessionTtl`
+overrides the default `48h` workload session lifetime (which nodes and routers
+extend in place on `/refresh` by re-presenting their current workload JWT).
+
## Gateway API (`gateway.enabled`)
Disabled by default. When enabled the chart creates one `Gateway` fronting
diff --git a/charts/sam-mesh/templates/control-plane-deployment.yaml b/charts/sam-mesh/templates/control-plane-deployment.yaml
index 96d76d8d..3f449c0b 100644
--- a/charts/sam-mesh/templates/control-plane-deployment.yaml
+++ b/charts/sam-mesh/templates/control-plane-deployment.yaml
@@ -93,6 +93,12 @@ spec:
- "--db-dsn=/data/control-plane.db"
{{- end }}
- "--issuer={{ .Values.controlPlane.oidcIssuer }}"
+ {{- if .Values.controlPlane.workloadIssuer }}
+ - "--workload-issuer={{ .Values.controlPlane.workloadIssuer }}"
+ {{- end }}
+ {{- if .Values.controlPlane.workloadSessionTtl }}
+ - "--workload-session-ttl={{ .Values.controlPlane.workloadSessionTtl }}"
+ {{- end }}
- "--allowed-audiences={{ .Values.controlPlane.allowedAudiences }}"
{{- if .Values.controlPlane.autoApproveEnrollment }}
- "--auto-approve-enrollment"
diff --git a/charts/sam-mesh/tests/control-plane-deployment_test.yaml b/charts/sam-mesh/tests/control-plane-deployment_test.yaml
index 238f010b..69385e10 100644
--- a/charts/sam-mesh/tests/control-plane-deployment_test.yaml
+++ b/charts/sam-mesh/tests/control-plane-deployment_test.yaml
@@ -75,3 +75,17 @@ tests:
path: spec.template.spec.tolerations
content:
key: dedicated
+
+ - it: passes workload issuer and session ttl flags when configured
+ template: templates/control-plane-deployment.yaml
+ set:
+ controlPlane.workloadIssuer: "https://kubernetes.default.svc.cluster.local"
+ controlPlane.workloadSessionTtl: "48h"
+ asserts:
+ - contains:
+ path: spec.template.spec.containers[0].args
+ content: "--workload-issuer=https://kubernetes.default.svc.cluster.local"
+ - contains:
+ path: spec.template.spec.containers[0].args
+ content: "--workload-session-ttl=48h"
+
diff --git a/charts/sam-mesh/values.yaml b/charts/sam-mesh/values.yaml
index 9a013dfa..e2bdce13 100644
--- a/charts/sam-mesh/values.yaml
+++ b/charts/sam-mesh/values.yaml
@@ -41,6 +41,14 @@ controlPlane:
# Required: the chart bundles no identity provider. Point it at your OIDC issuer
# (comma-separated for more than one); the control plane refuses to start without one.
oidcIssuer: ""
+ # Optional: comma-separated list of workload OIDC issuers (subset of or addition
+ # to oidcIssuer, optionally "<issuer>=<email-suffix>"). Tokens from a workload
+ # issuer are accepted at /register, /refresh, and /token/exchange, and refused
+ # at /user/* and /oauth/authorize.
+ workloadIssuer: ""
+ # Optional: session TTL for workload OIDC enrollments (e.g. "48h"); empty uses
+ # the control plane default (48h).
+ workloadSessionTtl: ""
allowedAudiences: "sam-mesh-audience,sam-control-plane-audience"
nodeSelector: {}
tolerations: []
diff --git a/cmd/sam-control-plane/main.go b/cmd/sam-control-plane/main.go
index ddf353af..55a9ba6d 100644
--- a/cmd/sam-control-plane/main.go
+++ b/cmd/sam-control-plane/main.go
@@ -38,6 +38,7 @@ var (
dbDSN string
dbDSNPath string
oidcIssuer string
+ workloadIssuer string
oidcClientID string
allowedAudiencesFlag string
keyRotationInterval time.Duration
@@ -45,6 +46,7 @@ var (
leaseDuration time.Duration
biscuitTTL time.Duration
oidcSessionTTL time.Duration
+ workloadSessionTTL time.Duration
nodeRetention time.Duration
meshReconnectInterval time.Duration
adminTokenPath string
@@ -83,8 +85,8 @@ func main() {
}
}
- if oidcIssuer == "" {
- logger.Fatalf("OIDC issuer is required (use --issuer flag)")
+ if oidcIssuer == "" && workloadIssuer == "" {
+ logger.Fatalf("OIDC issuer is required (use --issuer or --workload-issuer flag)")
}
adminToken, err := secrets.FromPathOrEnv("admin-token", adminTokenPath, "SAM_ADMIN_TOKEN")
@@ -119,6 +121,7 @@ func main() {
DriverName: dbDriver,
DataSourceName: dbDSN,
OIDCIssuer: oidcIssuer,
+ WorkloadIssuer: workloadIssuer,
OIDCClientID: oidcClientID,
AllowedAudiences: auds,
LeaseDuration: leaseDuration,
@@ -128,6 +131,7 @@ func main() {
BiscuitTimeout: 10 * time.Second,
BiscuitTTL: biscuitTTL,
OIDCSessionTTL: oidcSessionTTL,
+ WorkloadSessionTTL: workloadSessionTTL,
NodeRetention: nodeRetention,
AdminToken: adminToken,
AutoApproveEnrollment: autoApproveEnrollment,
@@ -170,6 +174,7 @@ func main() {
rootCmd.PersistentFlags().StringVar(&dbDSN, "db-dsn", "control-plane.db", "Database DSN/Connection URL (avoid for postgres: embeds a password; prefer --db-dsn-path or SAM_DB_DSN)")
rootCmd.PersistentFlags().StringVar(&dbDSNPath, "db-dsn-path", "", "Path to file containing the database DSN/Connection URL (overrides --db-dsn; or env SAM_DB_DSN)")
rootCmd.Flags().StringVar(&oidcIssuer, "issuer", "", "OIDC Issuer URL (comma-separated)")
+ rootCmd.Flags().StringVar(&workloadIssuer, "workload-issuer", "", "Workload OIDC Issuer URL or '<issuer>=<email-suffix>' (comma-separated); accepted at /register, /refresh and /token/exchange, refused at /user/* and /oauth/authorize")
rootCmd.Flags().StringVar(&oidcClientID, "oidc-client-id", "", "OAuth client ID advertised to joining nodes via /info (defaults to the first allowed audience)")
rootCmd.Flags().StringVar(&allowedAudiencesFlag, "allowed-audiences", api.DefaultAudience, "Comma-separated list of allowed OIDC audiences")
rootCmd.Flags().DurationVar(&keyRotationInterval, "key-rotation-interval", 24*time.Hour, "Key rotation interval (e.g. 24h). 0 disables rotation.")
@@ -177,6 +182,7 @@ func main() {
rootCmd.Flags().DurationVar(&leaseDuration, "lease-duration", 15*time.Minute, "Router lease registration TTL.")
rootCmd.Flags().DurationVar(&biscuitTTL, "biscuit-ttl", api.BiscuitTokenTTL, "Lifespan minted into every issued Biscuit's expiration fact. Capped to the OIDC token's own expiry when shorter.")
rootCmd.Flags().DurationVar(&oidcSessionTTL, "oidc-session-ttl", api.OIDCSessionTTL, "How long an OIDC enrollment stays refreshable before the identity must re-authenticate with the OIDC provider. Shorter values keep the provider authoritative for offboarding at the cost of more frequent interactive re-enrollment.")
+ rootCmd.Flags().DurationVar(&workloadSessionTTL, "workload-session-ttl", controlplane.DefaultWorkloadSessionTTL, "How long a workload-issuer enrollment stays refreshable without presenting a fresh platform JWT on /refresh.")
rootCmd.Flags().DurationVar(&nodeRetention, "node-retention", controlplane.DefaultNodeRetention, "How long an enrolled node's record is kept after its session expired before it is deleted. Banned nodes are always kept. 0 keeps every record forever.")
rootCmd.Flags().DurationVar(&meshReconnectInterval, "mesh-reconnect-interval", controlplane.DefaultMeshReconnectInterval, "How often the event publisher re-reads the router leases and dials any router it is not connected to.")
rootCmd.Flags().StringVar(&adminTokenPath, "admin-token-path", "", "Path to file containing the token for authenticating policy REST API requests (or env SAM_ADMIN_TOKEN)")
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index f64389a8..7acb15e4 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -105,6 +105,7 @@ var (
backendProbeTimeoutFlag time.Duration
secretsDirFlag string
controlPlaneSyncIntervalFlag time.Duration
+ cloudProviderFlag string
)
var logger = golog.Logger("sam-node-cli")
@@ -372,26 +373,28 @@ func main() {
var jwtStr string
var controlPlaneInfo *api.ControlPlaneInfoResponse
+ var liveTokenSource node.TokenSource
if jwtFlag != "" {
jwtStr = jwtFlag
- } else if jwtPathFlag != "" {
- data, err := os.ReadFile(jwtPathFlag)
- if err != nil {
- logger.Fatalf("Failed to read JWT file: %v", err)
- }
- jwtStr = strings.TrimSpace(string(data))
- } else if oidcIssuerFlag != "" {
- logger.Info("Discovering OIDC endpoints...")
- dummyNode := &node.SamNode{}
- tokenURL, err := dummyNode.DiscoverTokenURL(context.Background(), oidcIssuerFlag)
+ } else if jwtPathFlag != "" || oidcIssuerFlag != "" || cloudProviderFlag != "" {
+ src, continuous, err := node.ResolveTokenSource(ctx, node.TokenSourceConfig{
+ IssuerURL: oidcIssuerFlag,
+ ClientID: clientIDFlag,
+ ClientSecret: clientSecretFlag,
+ JWTPath: jwtPathFlag,
+ CloudProvider: cloudProviderFlag,
+ Audience: audienceFlag,
+ })
if err != nil {
- logger.Fatalf("Failed to discover OIDC endpoints: %v", err)
+ logger.Fatalf("Invalid token source configuration: %v", err)
}
- logger.Info("Fetching JWT via OIDC Client Credentials...")
- jwtStr, err = dummyNode.FetchJWT(context.Background(), tokenURL, clientIDFlag, clientSecretFlag)
- if err != nil {
- logger.Fatalf("Failed to fetch JWT: %v", err)
+ if continuous {
+ liveTokenSource = src
+ jwtStr, err = src.FetchToken(ctx)
+ if err != nil {
+ logger.Fatalf("Failed to fetch platform JWT: %v", err)
+ }
}
}
@@ -657,7 +660,12 @@ func main() {
}
// Start renewal loop
- meshNode.StartRenewalLoop(ctx, oidcIssuerFlag, clientIDFlag, clientSecretFlag, jwtPathFlag)
+ if liveTokenSource != nil {
+ meshNode.SetTokenSource(liveTokenSource)
+ meshNode.StartRenewalLoopWithSource(ctx, liveTokenSource)
+ } else {
+ meshNode.StartRenewalLoop(ctx, oidcIssuerFlag, clientIDFlag, clientSecretFlag, jwtPathFlag)
+ }
// Start Sidecar API Server (multiplexed with MCP)
sidecarSrv, err := node.StartSidecarServer(meshNode, bindAddrFlag, resolveSocketPath(cmd), apiTokenFlag, tlsCertFlag, tlsKeyFlag, tlsCAFlag)
@@ -863,6 +871,7 @@ func main() {
runCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/5001/quic-v1", "/ip4/0.0.0.0/tcp/5002"}, "libp2p Listen Addrs")
runCmd.Flags().StringVar(&jwtFlag, "jwt", "", "Pre-fetched JWT token")
runCmd.Flags().StringVar(&jwtPathFlag, "jwt-path", "", "Path to file containing JWT token")
+ runCmd.Flags().StringVar(&cloudProviderFlag, "cloud-provider", "", "Platform metadata identity provider for enrollment and renewal: gcp or auto")
runCmd.Flags().BoolVar(&joinFlag, "join", false, "Enroll interactively on first run if no identity exists yet (requires --control-plane or a previously stored mesh); a no-op on later restarts")
runCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")
runCmd.Flags().StringVar(&bootstrapTokenPathFlag, "bootstrap-token-path", "", "Path to file containing the bootstrap token (recommended over --bootstrap-token)")
diff --git a/cmd/sam-one/main.go b/cmd/sam-one/main.go
index e2349de4..66236cb3 100644
--- a/cmd/sam-one/main.go
+++ b/cmd/sam-one/main.go
@@ -51,6 +51,7 @@ func main() {
adminTokenPath string
policyFile string
oidcIssuer string
+ workloadIssuer string
oidcClientID string
allowedAudiencesFlag string
logLevel string
@@ -161,6 +162,7 @@ func main() {
AdminToken: adminToken,
PolicyFile: policyFile,
OIDCIssuer: oidcIssuer,
+ WorkloadIssuer: workloadIssuer,
OIDCClientID: oidcClientID,
AllowedAudiences: auds,
ControlPlane: cpTunables,
@@ -208,6 +210,7 @@ func main() {
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 PolicyConfig seeding the mesh policy on first boot only")
rootCmd.Flags().StringVar(&oidcIssuer, "issuer", "", "Optional external OIDC issuer URL (comma-separated)")
+ rootCmd.Flags().StringVar(&workloadIssuer, "workload-issuer", "", "Optional workload OIDC issuer URL or '<issuer>=<email-suffix>' (comma-separated); accepted at /register, /refresh and /token/exchange, refused at /user/* and /oauth/authorize")
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")
rootCmd.Flags().StringVar(&logLevel, "log-level", "", "Log level: debug, info, warn, error")
@@ -223,6 +226,7 @@ func main() {
rootCmd.Flags().DurationVar(&cpTunables.KeyRotationInterval, "control-plane-key-rotation-interval", 0, "Biscuit signing key rotation interval (0 keeps the component default)")
rootCmd.Flags().DurationVar(&cpTunables.KeyGracePeriod, "control-plane-key-grace-period", 0, "How long rotated-out keys stay valid for verification (0 keeps the component default)")
rootCmd.Flags().DurationVar(&cpTunables.BiscuitTTL, "control-plane-biscuit-ttl", 0, "Lifespan minted into issued biscuits (0 keeps the component default)")
+ rootCmd.Flags().DurationVar(&cpTunables.WorkloadSessionTTL, "control-plane-workload-session-ttl", 0, "How long a workload-issuer enrollment stays refreshable without presenting a fresh platform JWT on /refresh (0 keeps the component default)")
rootCmd.Flags().BoolVar(&cpTunables.ManualEnrollment, "control-plane-manual-enrollment", false, "Queue bootstrap enrollments for admin approval instead of auto-approving")
// Embedded router tunables.
diff --git a/internal/controlplane/client/tokensource.go b/internal/controlplane/client/tokensource.go
new file mode 100644
index 00000000..b961110f
--- /dev/null
+++ b/internal/controlplane/client/tokensource.go
@@ -0,0 +1,56 @@
+// 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 client
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+)
+
+// TokenSource fetches a fresh platform or OIDC JWT for enrollment, continuous
+// attestation at POST /refresh, or fallback re-enrollment.
+type TokenSource interface {
+ FetchToken(ctx context.Context) (string, error)
+}
+
+// FileTokenSource reads a JWT from a file path (e.g. a Kubernetes projected
+// ServiceAccount token volume or a SPIRE spiffe-helper JWT-SVID file).
+type FileTokenSource struct {
+ path string
+}
+
+// NewFileTokenSource creates a TokenSource that reads path on every FetchToken call.
+func NewFileTokenSource(path string) *FileTokenSource {
+ return &FileTokenSource{path: path}
+}
+
+// FetchToken reads and trims the JWT from disk.
+func (s *FileTokenSource) FetchToken(_ context.Context) (string, error) {
+ if strings.TrimSpace(s.path) == "" {
+ return "", errors.New("jwt file path is empty")
+ }
+ data, err := os.ReadFile(s.path)
+ if err != nil {
+ return "", fmt.Errorf("failed to read JWT file: %w", err)
+ }
+ tok := strings.TrimSpace(string(data))
+ if tok == "" {
+ return "", fmt.Errorf("JWT file %s is empty", s.path)
+ }
+ return tok, nil
+}
diff --git a/internal/controlplane/config.go b/internal/controlplane/config.go
index 27806723..c0f2f54c 100644
--- a/internal/controlplane/config.go
+++ b/internal/controlplane/config.go
@@ -23,10 +23,16 @@ import (
// Options holds configuration for the control plane.
type Options struct {
- ListenAddr string
- DriverName string
- DataSourceName string
- OIDCIssuer string
+ ListenAddr string
+ DriverName string
+ DataSourceName string
+ OIDCIssuer string
+ // WorkloadIssuer is a comma-separated list of OIDC issuers (subset of or
+ // addition to OIDCIssuer) that issue machine/workload tokens rather than
+ // human user tokens. Tokens from a workload issuer are accepted at
+ // /register, /refresh, and /token/exchange, and refused at /user/* and
+ // /oauth/authorize.
+ WorkloadIssuer string
OIDCClientID string // OAuth client id advertised via /info; defaults to the first allowed audience
AllowedAudiences []string
LeaseDuration time.Duration
@@ -36,6 +42,7 @@ type Options struct {
BiscuitTimeout time.Duration
BiscuitTTL time.Duration // Lifespan minted into every issued Biscuit's expiration() fact; defaults to api.BiscuitTokenTTL
OIDCSessionTTL time.Duration // How long an OIDC enrollment stays refreshable before the identity must re-authenticate interactively; defaults to api.OIDCSessionTTL
+ WorkloadSessionTTL time.Duration // Session TTL for enrollments from a WorkloadIssuer; defaults to DefaultWorkloadSessionTTL (48h)
// NodeRetention is how long an enrolled node's row is kept after its
// session expired before being deleted; 0 keeps rows forever. Every
// pod restart without a persistent data dir enrolls a fresh identity,
@@ -70,6 +77,10 @@ const (
STSRateLimitDefault = 100
// STSRateBurstDefault sizes per-node STS burst capacity.
STSRateBurstDefault = 200
+ // DefaultWorkloadSessionTTL is the default session TTL for workload OIDC
+ // issuers (48h, twice BiscuitTokenTTL so a single missed refresh does not
+ // sever the node).
+ DefaultWorkloadSessionTTL = 48 * time.Hour
)
// Default sets default values for control plane options.
@@ -96,6 +107,9 @@ func (o *Options) Default() {
if o.OIDCSessionTTL <= 0 {
o.OIDCSessionTTL = api.OIDCSessionTTL
}
+ if o.WorkloadSessionTTL <= 0 {
+ o.WorkloadSessionTTL = DefaultWorkloadSessionTTL
+ }
if o.DelegatedBiscuitTTL <= 0 {
o.DelegatedBiscuitTTL = 1 * time.Hour
}
diff --git a/internal/controlplane/resolve_roles_test.go b/internal/controlplane/resolve_roles_test.go
index 3ad39db1..beb0cad2 100644
--- a/internal/controlplane/resolve_roles_test.go
+++ b/internal/controlplane/resolve_roles_test.go
@@ -63,3 +63,63 @@ func TestResolveRolesMatchesNodeOnThePeerID(t *testing.T) {
t.Errorf("non-matching peer resolved %v, want none", got)
}
}
+
+func TestResolveRolesWildcardsAndValidation(t *testing.T) {
+ bindings := []*api.PolicyBinding{
+ {
+ Role: "k8s-payments",
+ Members: []string{
+ "user:system:serviceaccount:payments:*",
+ "user:spiffe://cluster.local/ns/payments/sa/*",
+ },
+ },
+ {
+ Role: "gcp-sa",
+ Members: []string{
+ "email:*@proj-123.iam.gserviceaccount.com",
+ },
+ },
+ }
+
+ if got := resolveRoles("peer-1", jwt.MapClaims{"sub": "system:serviceaccount:payments:worker-a"}, bindings); len(got) != 1 || got[0] != "k8s-payments" {
+ t.Errorf("k8s SA prefix wildcard resolved %v, want [k8s-payments]", got)
+ }
+ if got := resolveRoles("peer-1", jwt.MapClaims{"sub": "spiffe://cluster.local/ns/payments/sa/worker-b"}, bindings); len(got) != 1 || got[0] != "k8s-payments" {
+ t.Errorf("spiffe prefix wildcard resolved %v, want [k8s-payments]", got)
+ }
+ if got := resolveRoles("peer-1", jwt.MapClaims{"sub": "system:serviceaccount:other:worker-a"}, bindings); len(got) != 0 {
+ t.Errorf("non-matching namespace resolved %v, want none", got)
+ }
+ if got := resolveRoles("peer-1", jwt.MapClaims{"email": "[email protected]"}, bindings); len(got) != 1 || got[0] != "gcp-sa" {
+ t.Errorf("email suffix wildcard resolved %v, want [gcp-sa]", got)
+ }
+
+ validCfg := &api.PolicyConfig{
+ Roles: []*api.PolicyRole{
+ {Name: "k8s-payments", AllowedServices: []string{"mcp://Echo"}},
+ {Name: "gcp-sa", AllowedServices: []string{"mcp://Echo"}},
+ },
+ Bindings: bindings,
+ }
+ if err := ValidatePolicyConfig(validCfg); err != nil {
+ t.Fatalf("ValidatePolicyConfig rejected valid wildcard bindings: %v", err)
+ }
+
+ invalidMembers := []string{
+ "user:*",
+ "email:*",
+ "node:*",
+ "node:12D3KooW*",
+ "user:system:*:worker",
+ `user:foo"); role("admin") <- true; //`,
+ }
+ for _, bad := range invalidMembers {
+ cfg := &api.PolicyConfig{
+ Roles: []*api.PolicyRole{{Name: "r1", AllowedServices: []string{"mcp://Echo"}}},
+ Bindings: []*api.PolicyBinding{{Role: "r1", Members: []string{bad}}},
+ }
+ if err := ValidatePolicyConfig(cfg); err == nil {
+ t.Errorf("ValidatePolicyConfig accepted invalid member %q", bad)
+ }
+ }
+}
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 337f1f08..df75ee54 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -30,7 +30,6 @@ import (
mathrand "math/rand/v2"
"net"
"net/http"
- "slices"
"strconv"
"strings"
"sync"
@@ -110,8 +109,10 @@ type Server struct {
meshMu sync.RWMutex
mesh MeshAdapter
- providersMu sync.RWMutex
- providers map[string]*oidc.Provider
+ providersMu sync.RWMutex
+ providers map[string]*oidc.Provider
+ workloadIssuers map[string]bool
+ workloadEmailSuffixes map[string][]string
// catalogMu/catalog cache each node's self-reported local service list
// (see HandleNodeCatalog), keyed by peer ID. In-memory only: this is a
@@ -130,6 +131,27 @@ type Server struct {
shutdown bool
}
+func parseWorkloadIssuers(raw string) (map[string]bool, map[string][]string) {
+ issuers := make(map[string]bool)
+ suffixes := make(map[string][]string)
+ for _, entry := range strings.Split(raw, ",") {
+ entry = strings.TrimSpace(entry)
+ if entry == "" {
+ continue
+ }
+ if iss, suffix, ok := strings.Cut(entry, "="); ok {
+ iss = strings.TrimSpace(iss)
+ suffix = strings.TrimSpace(suffix)
+ if iss != "" && suffix != "" {
+ suffixes[iss] = append(suffixes[iss], suffix)
+ }
+ continue
+ }
+ issuers[entry] = true
+ }
+ return issuers, suffixes
+}
+
// NewServer initializes the control plane server and stores configuration.
func NewServer(config Options, store storage.Store) (*Server, error) {
config.Default()
@@ -155,20 +177,24 @@ func NewServer(config Options, store storage.Store) (*Server, error) {
reg := prometheus.NewRegistry()
reg.MustRegister(newMeshStateCollector(store))
+ workloadIssuers, workloadEmailSuffixes := parseWorkloadIssuers(config.WorkloadIssuer)
+
return &Server{
- config: config,
- store: store,
- mesh: NewNopMeshAdapter(),
- limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),
- stsLimiter: stsLimiter,
- oidcSigner: signer,
- revokedBiscuits: make(map[string]time.Time),
- oauthCodes: make(map[string]*oauthAuthCode),
- providers: make(map[string]*oidc.Provider),
- catalog: make(map[string]nodeCatalogEntry),
- metricsRegistry: reg,
- ctx: ctx,
- cancel: cancel,
+ config: config,
+ store: store,
+ mesh: NewNopMeshAdapter(),
+ limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),
+ stsLimiter: stsLimiter,
+ oidcSigner: signer,
+ revokedBiscuits: make(map[string]time.Time),
+ oauthCodes: make(map[string]*oauthAuthCode),
+ providers: make(map[string]*oidc.Provider),
+ workloadIssuers: workloadIssuers,
+ workloadEmailSuffixes: workloadEmailSuffixes,
+ catalog: make(map[string]nodeCatalogEntry),
+ metricsRegistry: reg,
+ ctx: ctx,
+ cancel: cancel,
}, nil
}
@@ -337,12 +363,26 @@ func (s *Server) discoverProviders() error {
s.providersMu.Lock()
defer s.providersMu.Unlock()
- issuers := strings.Split(s.config.OIDCIssuer, ",")
- for _, iss := range issuers {
+ var issuers []string
+ seen := make(map[string]bool)
+ addIssuer := func(iss string) {
iss = strings.TrimSpace(iss)
- if iss == "" {
- continue
+ if iss != "" && !seen[iss] {
+ seen[iss] = true
+ issuers = append(issuers, iss)
}
+ }
+ for _, iss := range strings.Split(s.config.OIDCIssuer, ",") {
+ addIssuer(iss)
+ }
+ for iss := range s.workloadIssuers {
+ addIssuer(iss)
+ }
+ for iss := range s.workloadEmailSuffixes {
+ addIssuer(iss)
+ }
+
+ for _, iss := range issuers {
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: s.config.InsecureSkipTLSVerify}
client := &http.Client{
@@ -359,6 +399,45 @@ func (s *Server) discoverProviders() error {
return nil
}
+// isWorkloadClaims reports whether verified JWT claims belong to a machine or
+// workload identity rather than a human operator:
+// 1. The token's iss is a dedicated workload issuer (--workload-issuer=<iss>),
+// 2. The token's iss has a configured email suffix (--workload-issuer=<iss>=<suffix>)
+// matched by the token's email claim, or
+// 3. The token was issued by https://accounts.google.com and carries a
+// google.compute_engine attestation claim (GCE / Cloud Run format=full).
+func (s *Server) isWorkloadClaims(claims jwt.MapClaims) bool {
+ if claims == nil {
+ return false
+ }
+ iss, _ := claims["iss"].(string)
+ iss = strings.TrimSpace(iss)
+ if s.workloadIssuers[iss] {
+ return true
+ }
+ if suffixes := s.workloadEmailSuffixes[iss]; len(suffixes) > 0 {
+ email, _ := claims["email"].(string)
+ for _, suffix := range suffixes {
+ if strings.HasSuffix(email, suffix) {
+ return true
+ }
+ }
+ }
+ if iss == "https://accounts.google.com" {
+ if g, ok := claims["google"].(map[string]any); ok && g["compute_engine"] != nil {
+ return true
+ }
+ }
+ return false
+}
+
+func (s *Server) sessionTTLForClaims(claims jwt.MapClaims) time.Duration {
+ if s.isWorkloadClaims(claims) {
+ return s.config.WorkloadSessionTTL
+ }
+ return s.config.OIDCSessionTTL
+}
+
// Defaults for discoverProviderWithRetry; kept small enough that a real outage still
// surfaces quickly (worst case ~15s) while riding out a transient hiccup during rollouts.
const (
@@ -499,10 +578,23 @@ func (s *Server) HandleInfo(w http.ResponseWriter, r *http.Request) {
return
}
- issuer := s.config.OIDCIssuer
- if strings.Contains(issuer, ",") {
- parts := strings.Split(issuer, ",")
- issuer = strings.TrimSpace(parts[0])
+ var issuer string
+ var firstIssuer string
+ for _, part := range strings.Split(s.config.OIDCIssuer, ",") {
+ part = strings.TrimSpace(part)
+ if part == "" {
+ continue
+ }
+ if firstIssuer == "" {
+ firstIssuer = part
+ }
+ if !s.workloadIssuers[part] {
+ issuer = part
+ break
+ }
+ }
+ if issuer == "" {
+ issuer = firstIssuer
}
aud := api.DefaultAudience
@@ -714,8 +806,9 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {
// The session bounds how long refresh works without the identity proving
// itself to the issuer again, so its length is the operator's re-auth
- // cadence decision (--oidc-session-ttl), not a constant.
- sessionExpiresAt := time.Now().Add(s.config.OIDCSessionTTL)
+ // cadence decision (--oidc-session-ttl for human identities,
+ // --workload-session-ttl for workload identities), not a constant.
+ sessionExpiresAt := time.Now().Add(s.sessionTTLForClaims(claims))
// Mint token. A biscuit must never outlive the OIDC token that vouched
// for it, nor the session it belongs to; its expiration is capped at
@@ -892,9 +985,14 @@ func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Node is banned", http.StatusForbidden)
return
}
- logger.Warnw("Session expired for node", "peer_id", canonical, "expires_at", nodeRecord.ExpiresAt)
- unauthorized("Session expired, please re-enroll interactively")
- return
+ // When a fresh platform JWT is presented on an OIDC enrollment, a
+ // lapsed session can be renewed in place once the challenge, last
+ // biscuit, and JWT identity all verify below.
+ if req.Jwt == "" || nodeRecord.EnrollmentType != "OIDC" {
+ logger.Warnw("Session expired for node", "peer_id", canonical, "expires_at", nodeRecord.ExpiresAt)
+ unauthorized("Session expired, please re-enroll interactively")
+ return
+ }
}
// Verify challenge signature using stored node public key
@@ -938,6 +1036,58 @@ func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {
logger.Infow("Autonomous recovery: re-issuing a biscuit whose signing key was retired", "peer_id", canonical, "error", verifyErr)
}
+ // Continuous platform attestation: when the node presents a fresh JWT on
+ // refresh, verify it against the configured OIDC providers, require the
+ // same iss|sub identity as the enrolled node record, and renew ClaimsJSON
+ // and the session expiry in place.
+ if req.Jwt != "" {
+ if nodeRecord.EnrollmentType != "OIDC" {
+ http.Error(w, "JWT refresh attestation is only supported for OIDC-enrolled nodes", http.StatusBadRequest)
+ return
+ }
+ verifyCtx, cancel := context.WithTimeout(ctx, JWTVerificationTimeout)
+ freshClaims, _, err := identity.VerifyJWT(verifyCtx, req.Jwt, s.config.AllowedAudiences, s.getProviders())
+ cancel()
+ if err != nil {
+ logger.Warnw("Refresh JWT verification failed", "peer_id", canonical, "error", err)
+ http.Error(w, "JWT validation failed: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+ if verifiedEmail(freshClaims) == "" {
+ delete(freshClaims, "email")
+ }
+ var storedClaims jwt.MapClaims
+ if err := json.Unmarshal([]byte(nodeRecord.ClaimsJSON), &storedClaims); err != nil {
+ logger.Errorf("Failed to unmarshal stored OIDC claims for node %s: %v", nodeRecord.PeerID, err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ freshKey := oidcIdentityKey(freshClaims)
+ storedKey := oidcIdentityKey(storedClaims)
+ if freshKey == "" || freshKey != storedKey {
+ logger.Warnw("Refresh JWT identity mismatch", "peer_id", canonical, "expected", storedKey, "got", freshKey)
+ http.Error(w, "JWT identity does not match enrolled node identity", http.StatusForbidden)
+ return
+ }
+ if banned, err := s.store.IsIdentityBanned(ctx, freshKey); err != nil {
+ logger.Errorf("Failed to check identity ban for %s: %v", canonical, err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ } else if banned {
+ logger.Warnw("Banned identity attempted refresh", "peer_id", canonical, "identity", freshKey)
+ http.Error(w, "Identity is banned", http.StatusForbidden)
+ return
+ }
+ claimsBytes, err := json.Marshal(freshClaims)
+ if err != nil {
+ logger.Errorf("Failed to marshal refreshed OIDC claims for node %s: %v", nodeRecord.PeerID, err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ nodeRecord.ClaimsJSON = string(claimsBytes)
+ nodeRecord.ExpiresAt = time.Now().Add(s.sessionTTLForClaims(freshClaims))
+ }
+
// Fetch current signing private key and policy config
privKey, _, err := s.store.GetCurrentKey(ctx)
if err != nil {
@@ -954,8 +1104,8 @@ func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {
}
var biscuitBytes []byte
- // No live OIDC token is presented on refresh, so the session record is what
- // vouches for this node. The biscuit must not outlive it.
+ // Unless a live OIDC token just renewed it above, the session record is
+ // what vouches for this node. The biscuit must not outlive it.
biscuitExpiry := time.Now().Add(s.config.BiscuitTTL)
if !nodeRecord.ExpiresAt.IsZero() && nodeRecord.ExpiresAt.Before(biscuitExpiry) {
biscuitExpiry = nodeRecord.ExpiresAt
@@ -1946,6 +2096,12 @@ func (s *Server) HandleEnrollStatus(w http.ResponseWriter, r *http.Request) {
// is fine, the identity is not welcome.
var errIdentityBanned = errors.New("identity is banned")
+// errWorkloadIdentity is authenticateUser's answer for a valid OIDC token from
+// a workload issuer or workload claim subset. Workload tokens may enroll and
+// refresh nodes or exchange at /token/exchange, never act as a human user on
+// /user/* or /admin/*.
+var errWorkloadIdentity = errors.New("workload tokens are not permitted on user endpoints")
+
func (s *Server) authenticateUser(r *http.Request) (*storage.User, error) {
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
@@ -1995,6 +2151,11 @@ func (s *Server) authenticateUser(r *http.Request) (*storage.User, error) {
return nil, errIdentityBanned
}
+ if s.isWorkloadClaims(claims) {
+ logger.Warnw("Workload token presented on user endpoint", "issuer", iss, "sub", sub, "email", email)
+ return nil, errWorkloadIdentity
+ }
+
// Fetch or auto-register user
user, err := s.store.GetUser(ctx, sub)
switch {
@@ -2051,6 +2212,10 @@ func (s *Server) requireUser(w http.ResponseWriter, r *http.Request) (*storage.U
http.Error(w, "Forbidden: identity is banned", http.StatusForbidden)
return nil, false
}
+ if errors.Is(err, errWorkloadIdentity) {
+ http.Error(w, "Forbidden: workload tokens are not permitted on user endpoints", http.StatusForbidden)
+ return nil, false
+ }
logger.Debugf("User authentication failed: %v", err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return nil, false
@@ -3052,7 +3217,7 @@ func resolveRoles(peerID string, claims jwt.MapClaims, bindings []*api.PolicyBin
}
continue
}
- if slices.Contains(factValues[prefix], value) {
+ if api.MatchBindingMemberValue(factValues[prefix], value) {
resolvedRoles[b.Role] = true
}
}
@@ -3123,8 +3288,8 @@ func validatePolicyConfig(req *api.PolicyConfig) error {
if r == nil {
continue
}
- if strings.TrimSpace(r.Name) == "" {
- return fmt.Errorf("role name cannot be empty")
+ if err := api.ValidateRoleName(r.Name); err != nil {
+ return err
}
if roleNames[r.Name] {
return fmt.Errorf("duplicate role name: %s", r.Name)
@@ -3182,11 +3347,6 @@ func validatePolicyConfig(req *api.PolicyConfig) error {
return fmt.Errorf("policy config would allow a single identity (via overlapping bindings) to accumulate up to %d Datalog facts across all roles, exceeding the safe budget of %d; biscuit-go's authorizer rejects tokens/checks beyond ~1000 world facts, so requests would start failing at authorization time instead of at config validation. Reduce the number of roles, grants, or custom_datalog entries", factBudget, maxIdentityFactBudget)
}
- validPrefixes := make(map[string]bool)
- for _, p := range api.BindingMemberPrefixes() {
- validPrefixes[p] = true
- }
-
for _, b := range req.Bindings {
if b == nil {
continue
@@ -3201,16 +3361,8 @@ func validatePolicyConfig(req *api.PolicyConfig) error {
return fmt.Errorf("binding for role %q must specify at least one member", b.Role)
}
for _, member := range b.Members {
- if member == api.SystemAuthenticated {
- continue
- }
- parts := strings.SplitN(member, ":", 2)
- if len(parts) != 2 || strings.TrimSpace(parts[1]) == "" {
- return fmt.Errorf("member %q in binding for role %q is invalid, must be in format 'type:value' or %q", member, b.Role, api.SystemAuthenticated)
- }
- prefix := parts[0]
- if !validPrefixes[prefix] {
- return fmt.Errorf("member prefix %q in member %q is invalid", prefix, member)
+ if err := api.ValidateBindingMember(member, b.Role); err != nil {
+ return err
}
}
}
diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.go
index afafe6fa..40724c07 100644
--- a/internal/controlplane/server_test.go
+++ b/internal/controlplane/server_test.go
@@ -4062,3 +4062,360 @@ func TestAutonomousRecovery(t *testing.T) {
}
})
}
+
+func TestWorkloadIssuerContainment(t *testing.T) {
+ workloadIss, mintWorkload := startCustomMockOIDC(t)
+ sharedIss, mintShared := startCustomMockOIDC(t)
+
+ store, err := storage.NewSQLStore("sqlite", ":memory:")
+ if err != nil {
+ t.Fatalf("NewSQLStore: %v", err)
+ }
+ defer func() { _ = store.Close() }()
+
+ const (
+ humanTTL = 720 * time.Hour
+ workloadTTL = 36 * time.Hour
+ )
+ srv, err := NewServer(Options{
+ ListenAddr: "127.0.0.1:0",
+ OIDCIssuer: sharedIss,
+ WorkloadIssuer: workloadIss + "," + sharedIss + "=.gserviceaccount.com",
+ AllowedAudiences: []string{"sam-mesh-audience"},
+ OIDCSessionTTL: humanTTL,
+ WorkloadSessionTTL: workloadTTL,
+ AdminToken: "admin-secret",
+ }, store)
+ if err != nil {
+ t.Fatalf("NewServer: %v", err)
+ }
+ if err := srv.Start(); err != nil {
+ t.Fatalf("Start: %v", err)
+ }
+ defer func() { _ = srv.Close() }()
+ baseURL := "http://" + srv.Addr()
+
+ // Seed wildcard bindings for both Kubernetes SAs and GCP service accounts,
+ // plus an exact human binding.
+ ctx := context.Background()
+ roles := []*api.PolicyRole{{
+ Name: api.RoleNode,
+ AllowedTargets: []string{"*"},
+ }}
+ bindings := []*api.PolicyBinding{{
+ Role: api.RoleNode,
+ Members: []string{
+ "user:system:serviceaccount:payments:*",
+ "email:*@proj-1.iam.gserviceaccount.com",
+ },
+ }}
+ if err := store.SaveMeshPolicy(ctx, roles, bindings); err != nil {
+ t.Fatalf("SaveMeshPolicy: %v", err)
+ }
+
+ enrollWithJWT := func(t *testing.T, tok string) (*storage.EnrolledNode, int) {
+ t.Helper()
+ priv, pub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pubBytes, err := crypto.MarshalPublicKey(pub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pID, err := peer.IDFromPublicKey(pub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ts := time.Now().UnixMilli()
+ sig, err := priv.Sign(api.RegisterChallenge(pID.String(), ts))
+ if err != nil {
+ t.Fatal(err)
+ }
+ reqBytes, err := proto.Marshal(&api.EnrollRequest{
+ PeerId: pID.String(),
+ Jwt: tok,
+ PublicKey: pubBytes,
+ RequestedRole: api.RoleNode,
+ ChallengeUnixMs: ts,
+ ChallengeSignature: sig,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := (&http.Client{Timeout: 5 * time.Second}).Post(baseURL+"/register", "application/x-protobuf", bytes.NewReader(reqBytes))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode != http.StatusOK {
+ return nil, resp.StatusCode
+ }
+ nodeRec, err := store.GetNode(ctx, pID.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return nodeRec, resp.StatusCode
+ }
+
+ k8sJWT := mintWorkload(map[string]any{
+ "iss": workloadIss,
+ "sub": "system:serviceaccount:payments:worker-1",
+ "aud": "sam-mesh-audience",
+ })
+ gcpSAJWT := mintShared(map[string]any{
+ "iss": sharedIss,
+ "sub": "10987654321",
+ "email": "[email protected]",
+ "aud": "sam-mesh-audience",
+ })
+ humanJWT := mintShared(map[string]any{
+ "iss": sharedIss,
+ "sub": "human-alice-1",
+ "email": "[email protected]",
+ "aud": "sam-mesh-audience",
+ })
+
+ // 1. Both workload tokens enroll via wildcard bindings and receive WorkloadSessionTTL.
+ for name, tok := range map[string]string{"k8s-sa": k8sJWT, "gcp-sa": gcpSAJWT} {
+ rec, code := enrollWithJWT(t, tok)
+ if code != http.StatusOK {
+ t.Fatalf("%s /register: status = %d, want 200", name, code)
+ }
+ rem := time.Until(rec.ExpiresAt)
+ if rem <= 0 || rem > workloadTTL+time.Minute {
+ t.Errorf("%s session remaining = %v, want <= %v (WorkloadSessionTTL)", name, rem, workloadTTL)
+ }
+ }
+
+ // 2. Human token from the shared issuer receives OIDCSessionTTL and succeeds at /user/status.
+ humanRec, code := enrollWithJWT(t, humanJWT)
+ if code != http.StatusOK {
+ t.Fatalf("human /register: status = %d, want 200", code)
+ }
+ if rem := time.Until(humanRec.ExpiresAt); rem < humanTTL-time.Hour {
+ t.Errorf("human session remaining = %v, want ~%v (OIDCSessionTTL)", rem, humanTTL)
+ }
+
+ client := &http.Client{Timeout: 5 * time.Second}
+ for name, tok := range map[string]string{"k8s-sa": k8sJWT, "gcp-sa": gcpSAJWT} {
+ // Refused at /user/status
+ req, _ := http.NewRequest(http.MethodGet, baseURL+"/user/status", nil)
+ req.Header.Set("Authorization", "Bearer "+tok)
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = resp.Body.Close()
+ if resp.StatusCode != http.StatusForbidden {
+ t.Errorf("%s GET /user/status: got %d, want 403 Forbidden", name, resp.StatusCode)
+ }
+
+ // Refused at /user/bootstrap-tokens
+ reqBT, _ := http.NewRequest(http.MethodPost, baseURL+"/user/bootstrap-tokens", strings.NewReader(`{"role":"sam:role:node"}`))
+ reqBT.Header.Set("Authorization", "Bearer "+tok)
+ reqBT.Header.Set("Content-Type", "application/json")
+ respBT, err := client.Do(reqBT)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = respBT.Body.Close()
+ if respBT.StatusCode != http.StatusForbidden {
+ t.Errorf("%s POST /user/bootstrap-tokens: got %d, want 403 Forbidden", name, respBT.StatusCode)
+ }
+
+ // Refused at /oauth/authorize
+ authURL := baseURL + "/oauth/authorize?response_type=code&client_id=test-client&redirect_uri=http://127.0.0.1:9999/cb&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256"
+ reqOA, _ := http.NewRequest(http.MethodGet, authURL, nil)
+ reqOA.Header.Set("Authorization", "Bearer "+tok)
+ respOA, err := client.Do(reqOA)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = respOA.Body.Close()
+ if respOA.StatusCode != http.StatusForbidden {
+ t.Errorf("%s GET /oauth/authorize: got %d, want 403 Forbidden", name, respOA.StatusCode)
+ }
+ }
+
+ // Human token succeeds at /user/status.
+ reqHuman, _ := http.NewRequest(http.MethodGet, baseURL+"/user/status", nil)
+ reqHuman.Header.Set("Authorization", "Bearer "+humanJWT)
+ respHuman, err := client.Do(reqHuman)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = respHuman.Body.Close()
+ if respHuman.StatusCode != http.StatusOK {
+ t.Errorf("human GET /user/status: got %d, want 200 OK", respHuman.StatusCode)
+ }
+
+ // Verify google.compute_engine claim detection for https://accounts.google.com.
+ gceClaims := jwt.MapClaims{
+ "iss": "https://accounts.google.com",
+ "sub": "12345",
+ "google": map[string]any{
+ "compute_engine": map[string]any{"project_id": "proj-1"},
+ },
+ }
+ if !srv.isWorkloadClaims(gceClaims) {
+ t.Error("expected google.compute_engine claim on https://accounts.google.com to be classified as workload")
+ }
+}
+
+func TestRefreshWithPlatformJWT(t *testing.T) {
+ issuer, mintToken := startCustomMockOIDC(t)
+ srv, store, baseURL := setupTestServer(t, issuer, func(o *Options) {
+ o.WorkloadIssuer = issuer
+ o.WorkloadSessionTTL = 2 * time.Hour
+ })
+ defer func() {
+ _ = srv.Close()
+ _ = store.Close()
+ }()
+
+ ctx := context.Background()
+ roles := []*api.PolicyRole{
+ {Name: api.RoleNode, AllowedTargets: []string{"*"}},
+ {Name: "payments-reader", AllowedServices: []string{"mcp://Payments"}},
+ }
+ bindings := []*api.PolicyBinding{
+ {Role: api.RoleNode, Members: []string{"user:system:serviceaccount:payments:*"}},
+ {Role: "payments-reader", Members: []string{"group:payments-team"}},
+ }
+ if err := store.SaveMeshPolicy(ctx, roles, bindings); err != nil {
+ t.Fatalf("SaveMeshPolicy: %v", err)
+ }
+
+ priv, pub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pubBytes, err := crypto.MarshalPublicKey(pub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pID, err := peer.IDFromPublicKey(pub)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ initialJWT := mintToken(map[string]any{
+ "sub": "system:serviceaccount:payments:worker-1",
+ })
+ ts := time.Now().UnixMilli()
+ sig, err := priv.Sign(api.RegisterChallenge(pID.String(), ts))
+ if err != nil {
+ t.Fatal(err)
+ }
+ regBytes, err := proto.Marshal(&api.EnrollRequest{
+ PeerId: pID.String(),
+ Jwt: initialJWT,
+ PublicKey: pubBytes,
+ RequestedRole: api.RoleNode,
+ ChallengeUnixMs: ts,
+ ChallengeSignature: sig,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ client := &http.Client{Timeout: 5 * time.Second}
+ resp, err := client.Post(baseURL+"/register", "application/x-protobuf", bytes.NewReader(regBytes))
+ if err != nil {
+ t.Fatal(err)
+ }
+ regBody, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("POST /register: got %d %s", resp.StatusCode, regBody)
+ }
+ var enrollResp api.EnrollResponse
+ if err := proto.Unmarshal(regBody, &enrollResp); err != nil {
+ t.Fatal(err)
+ }
+ currentBiscuit := enrollResp.BiscuitToken
+
+ sendRefresh := func(jwtStr string) (int, []byte) {
+ t.Helper()
+ rts := time.Now().UnixMilli()
+ rsig, err := priv.Sign(api.RefreshChallenge(pID.String(), rts))
+ if err != nil {
+ t.Fatal(err)
+ }
+ reqData, err := proto.Marshal(&api.TokenRefreshRequest{
+ ChallengeUnixMs: rts,
+ ChallengeSignature: rsig,
+ Jwt: jwtStr,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ req, err := http.NewRequest(http.MethodPost, baseURL+"/refresh", bytes.NewReader(reqData))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/x-protobuf")
+ req.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(currentBiscuit))
+ r, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := io.ReadAll(r.Body)
+ _ = r.Body.Close()
+ return r.StatusCode, b
+ }
+
+ // 1. Mismatched subject in refresh JWT is rejected with 403 Forbidden.
+ otherSubJWT := mintToken(map[string]any{
+ "sub": "system:serviceaccount:payments:worker-2",
+ })
+ if code, body := sendRefresh(otherSubJWT); code != http.StatusForbidden {
+ t.Fatalf("refresh with mismatched sub: got %d %s, want 403", code, body)
+ }
+
+ // 2. Garbage JWT is rejected with 401 Unauthorized.
+ if code, body := sendRefresh("not-a-valid-jwt"); code != http.StatusUnauthorized {
+ t.Fatalf("refresh with invalid jwt: got %d %s, want 401", code, body)
+ }
+
+ // 3. Force the stored session to appear expired: refresh without JWT fails (401),
+ // refresh with a fresh valid JWT for the same iss|sub succeeds (200) and updates
+ // ClaimsJSON and ExpiresAt in place.
+ rec, err := store.GetNode(ctx, pID.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec.ExpiresAt = time.Now().Add(-time.Minute)
+ if err := store.EnrollNode(ctx, rec); err != nil {
+ t.Fatal(err)
+ }
+ if code, _ := sendRefresh(""); code != http.StatusUnauthorized {
+ t.Fatalf("expired session refresh without jwt: got %d, want 401", code)
+ }
+
+ freshJWT := mintToken(map[string]any{
+ "sub": "system:serviceaccount:payments:worker-1",
+ "groups": []string{"payments-team"},
+ })
+ code, body := sendRefresh(freshJWT)
+ if code != http.StatusOK {
+ t.Fatalf("refresh with fresh valid jwt: got %d %s, want 200", code, body)
+ }
+ var refreshResp api.TokenRefreshResponse
+ if err := proto.Unmarshal(body, &refreshResp); err != nil {
+ t.Fatal(err)
+ }
+ currentBiscuit = refreshResp.BiscuitToken
+
+ updatedRec, err := store.GetNode(ctx, pID.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if time.Until(updatedRec.ExpiresAt) < time.Hour {
+ t.Errorf("expected session ExpiresAt to be renewed to ~2h, got remaining %v", time.Until(updatedRec.ExpiresAt))
+ }
+ if !strings.Contains(updatedRec.ClaimsJSON, "payments-team") {
+ t.Errorf("expected updated ClaimsJSON to include new group claim, got %s", updatedRec.ClaimsJSON)
+ }
+}
diff --git a/internal/controlplane/sts.go b/internal/controlplane/sts.go
index fb97374b..a712a7f8 100644
--- a/internal/controlplane/sts.go
+++ b/internal/controlplane/sts.go
@@ -1002,10 +1002,15 @@ func (s *Server) HandleOAuthAuthorize(w http.ResponseWriter, r *http.Request) {
// Verify the user's OIDC JWT upfront before rendering consent or issuing a code.
verifyCtx, cancel := context.WithTimeout(r.Context(), JWTVerificationTimeout)
defer cancel()
- if _, _, err := identity.VerifyJWT(verifyCtx, subjectJWT, s.config.AllowedAudiences, s.getProviders()); err != nil {
+ claims, _, err := identity.VerifyJWT(verifyCtx, subjectJWT, s.config.AllowedAudiences, s.getProviders())
+ if err != nil {
http.Error(w, "Invalid OIDC token: "+err.Error(), http.StatusUnauthorized)
return
}
+ if s.isWorkloadClaims(claims) {
+ http.Error(w, errWorkloadIdentity.Error(), http.StatusForbidden)
+ return
+ }
actorPeerStr := strings.TrimSpace(r.Form.Get("actor_peer_id"))
var actorPeerID peer.ID
diff --git a/internal/node/node.go b/internal/node/node.go
index f595f48c..d87e11cd 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -29,7 +29,6 @@ import (
"io"
"net"
"net/http"
- "os"
"strconv"
"strings"
"sync"
@@ -200,6 +199,7 @@ type SamNode struct {
// only the last biscuit it issued, so two refreshes in flight would
// invalidate each other.
refreshMu sync.Mutex
+ tokenSource TokenSource
BiscuitTimeout time.Duration
cachedIdentity atomic.Value
logger *golog.ZapEventLogger
@@ -209,6 +209,20 @@ type SamNode struct {
metricsRegistry *prometheus.Registry
}
+// SetTokenSource configures the live platform/OIDC token source presented as
+// TokenRefreshRequest.jwt during RefreshEnrollment.
+func (n *SamNode) SetTokenSource(ts TokenSource) {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ n.tokenSource = ts
+}
+
+func (n *SamNode) getTokenSource() TokenSource {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ return n.tokenSource
+}
+
// UpdateRelays updates the current relays used by AutoRelay.
func (n *SamNode) UpdateRelays(addrs []multiaddr.Multiaddr) {
n.mu.Lock()
@@ -377,6 +391,7 @@ func NewSamNode(cfg Options) (*SamNode, error) {
authSuccess: make(chan struct{}),
reprovideTrigger: make(chan struct{}, 1),
controlPlaneSyncTrigger: make(chan struct{}, 1),
+ tokenSource: cfg.TokenSource,
BiscuitTimeout: cfg.BiscuitTimeout,
logger: golog.Logger("sam-node"),
}
@@ -1104,6 +1119,27 @@ func (n *SamNode) performRouterAuthHandshake(s network.Stream, biscuitBytes []by
}
func (n *SamNode) StartRenewalLoop(ctx context.Context, issuerURL, clientID, clientSecret, jwtPath string) {
+ src, continuous, err := ResolveTokenSource(ctx, TokenSourceConfig{
+ Node: n,
+ IssuerURL: issuerURL,
+ ClientID: clientID,
+ ClientSecret: clientSecret,
+ JWTPath: jwtPath,
+ })
+ if err != nil {
+ logger.Warnf("Failed to resolve token source: %v", err)
+ src = NewRefreshTokenSource(n, clientSecret)
+ }
+ if continuous && n.getTokenSource() == nil {
+ n.SetTokenSource(src)
+ }
+ n.StartRenewalLoopWithSource(ctx, src)
+}
+
+func (n *SamNode) StartRenewalLoopWithSource(ctx context.Context, src TokenSource) {
+ if src == nil {
+ src = n.getTokenSource()
+ }
go func() {
for {
var renewAfter = DefaultRenewalFallback // Default fallback
@@ -1145,26 +1181,10 @@ func (n *SamNode) StartRenewalLoop(ctx context.Context, issuerURL, clientID, cli
var newJWT string
var fetchErr error
-
- if issuerURL != "" {
- tokenURL, err := n.DiscoverTokenURL(ctx, issuerURL)
- if err != nil {
- fetchErr = fmt.Errorf("failed to discover OIDC endpoints for renewal: %w", err)
- } else {
- newJWT, fetchErr = n.FetchJWT(ctx, tokenURL, clientID, clientSecret)
- if fetchErr != nil {
- fetchErr = fmt.Errorf("failed to fetch JWT for renewal: %w", fetchErr)
- }
- }
- } else if jwtPath != "" {
- data, err := os.ReadFile(jwtPath)
- if err != nil {
- fetchErr = fmt.Errorf("failed to read JWT file for renewal: %w", err)
- } else {
- newJWT = strings.TrimSpace(string(data))
- }
+ if src == nil {
+ fetchErr = errors.New("no token source configured for renewal")
} else {
- newJWT, fetchErr = n.renewWithRefreshToken(ctx, clientSecret)
+ newJWT, fetchErr = src.FetchToken(ctx)
}
if fetchErr == nil {
@@ -1239,10 +1259,19 @@ func (n *SamNode) RefreshEnrollment(ctx context.Context) error {
// record when the biscuit's signing key has been retired and the biscuit
// itself can no longer be verified (autonomous recovery, opt-in
// server-side); it is cross-checked against the biscuit otherwise.
+ var freshJWT string
+ if ts := n.getTokenSource(); ts != nil {
+ if tok, fetchErr := ts.FetchToken(ctx); fetchErr != nil {
+ logger.Warnw("Failed to fetch fresh platform JWT for refresh attestation; attempting session-backed refresh", "error", fetchErr)
+ } else {
+ freshJWT = tok
+ }
+ }
req := &api.TokenRefreshRequest{
ChallengeSignature: sig,
ChallengeUnixMs: timestamp,
PeerId: peerID.String(),
+ Jwt: freshJWT,
}
reqData, err := proto.Marshal(req)
if err != nil {
diff --git a/internal/node/options.go b/internal/node/options.go
index d67eeb52..2f97fad9 100644
--- a/internal/node/options.go
+++ b/internal/node/options.go
@@ -101,6 +101,9 @@ type Options struct {
// report is sent, so services configured at startup have registered by
// then. Zero uses the default.
CatalogReportInitialDelay time.Duration
+ // TokenSource is the optional live platform/OIDC token provider presented
+ // as TokenRefreshRequest.jwt during RefreshEnrollment.
+ TokenSource TokenSource
}
// Default applies default values to Options if they are not specified.
diff --git a/internal/node/tokensource.go b/internal/node/tokensource.go
new file mode 100644
index 00000000..574a843c
--- /dev/null
+++ b/internal/node/tokensource.go
@@ -0,0 +1,235 @@
+// 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 (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/google/sam/api"
+ cpclient "github.com/google/sam/internal/controlplane/client"
+)
+
+const (
+ defaultGCEMetadataIdentityEndpoint = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity"
+ maxMetadataIdentityBytes = 64 * 1024
+)
+
+// TokenSource fetches a fresh platform or OIDC JWT for enrollment, continuous
+// attestation at POST /refresh, or fallback re-enrollment.
+type TokenSource = cpclient.TokenSource
+
+// FileTokenSource reads a JWT from a file path (e.g. a Kubernetes projected
+// ServiceAccount token volume or a SPIRE spiffe-helper JWT-SVID file).
+type FileTokenSource = cpclient.FileTokenSource
+
+// NewFileTokenSource creates a TokenSource that reads path on every FetchToken call.
+var NewFileTokenSource = cpclient.NewFileTokenSource
+
+// ClientCredentialsTokenSource fetches a JWT via OAuth2 client_credentials
+// against an OIDC issuer.
+type ClientCredentialsTokenSource struct {
+ node *SamNode
+ issuerURL string
+ clientID string
+ clientSecret string
+}
+
+// NewClientCredentialsTokenSource creates a TokenSource that exchanges client
+// credentials at issuerURL's token endpoint.
+func NewClientCredentialsTokenSource(n *SamNode, issuerURL, clientID, clientSecret string) *ClientCredentialsTokenSource {
+ if n == nil {
+ n = &SamNode{}
+ }
+ return &ClientCredentialsTokenSource{
+ node: n,
+ issuerURL: issuerURL,
+ clientID: clientID,
+ clientSecret: clientSecret,
+ }
+}
+
+// FetchToken discovers the OIDC token endpoint and fetches a fresh JWT.
+func (s *ClientCredentialsTokenSource) FetchToken(ctx context.Context) (string, error) {
+ tokenURL, err := s.node.DiscoverTokenURL(ctx, s.issuerURL)
+ if err != nil {
+ return "", fmt.Errorf("failed to discover OIDC endpoints: %w", err)
+ }
+ tok, err := s.node.FetchJWT(ctx, tokenURL, s.clientID, s.clientSecret)
+ if err != nil {
+ return "", fmt.Errorf("failed to fetch JWT: %w", err)
+ }
+ return tok, nil
+}
+
+// RefreshTokenSource exchanges a stored OIDC refresh token for a fresh JWT.
+type RefreshTokenSource struct {
+ node *SamNode
+ clientSecret string
+}
+
+// NewRefreshTokenSource creates a TokenSource backed by the node's persisted
+// OIDC refresh token.
+func NewRefreshTokenSource(n *SamNode, clientSecret string) *RefreshTokenSource {
+ return &RefreshTokenSource{
+ node: n,
+ clientSecret: clientSecret,
+ }
+}
+
+// FetchToken exchanges the stored refresh token for a new ID/access token.
+func (s *RefreshTokenSource) FetchToken(ctx context.Context) (string, error) {
+ if s.node == nil {
+ return "", errors.New("node is required for refresh token source")
+ }
+ return s.node.renewWithRefreshToken(ctx, s.clientSecret)
+}
+
+// GCPMetadataTokenSource fetches a Google-signed OIDC ID token from the GCE or
+// Cloud Run instance metadata server.
+type GCPMetadataTokenSource struct {
+ audience string
+ endpoint string
+ httpClient *http.Client
+}
+
+// NewGCPMetadataTokenSource creates a TokenSource targeting the GCE/Cloud Run
+// service account identity metadata endpoint with format=full.
+func NewGCPMetadataTokenSource(audience, endpoint string, httpClient *http.Client) *GCPMetadataTokenSource {
+ if strings.TrimSpace(audience) == "" {
+ audience = api.DefaultAudience
+ }
+ if strings.TrimSpace(endpoint) == "" {
+ endpoint = defaultGCEMetadataIdentityEndpoint
+ }
+ if httpClient == nil {
+ httpClient = &http.Client{Timeout: 5 * time.Second}
+ }
+ return &GCPMetadataTokenSource{
+ audience: strings.TrimSpace(audience),
+ endpoint: strings.TrimSpace(endpoint),
+ httpClient: httpClient,
+ }
+}
+
+// FetchToken requests an OIDC identity token from the GCP metadata server.
+func (s *GCPMetadataTokenSource) FetchToken(ctx context.Context) (string, error) {
+ u, err := url.Parse(s.endpoint)
+ if err != nil {
+ return "", fmt.Errorf("invalid GCP metadata endpoint %q: %w", s.endpoint, err)
+ }
+ q := u.Query()
+ q.Set("audience", s.audience)
+ q.Set("format", "full")
+ u.RawQuery = q.Encode()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Metadata-Flavor", "Google")
+ resp, err := s.httpClient.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("GCP metadata identity request failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxMetadataIdentityBytes))
+ if err != nil {
+ return "", err
+ }
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("GCP metadata identity returned %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+ tok := strings.TrimSpace(string(body))
+ if tok == "" {
+ return "", errors.New("GCP metadata identity returned an empty token")
+ }
+ return tok, nil
+}
+
+// ProbeGCPMetadata reports whether the GCE/Cloud Run metadata server is
+// reachable and answers with Metadata-Flavor: Google.
+func ProbeGCPMetadata(ctx context.Context, endpoint string, httpClient *http.Client) bool {
+ if strings.TrimSpace(endpoint) == "" {
+ endpoint = defaultGCEMetadataIdentityEndpoint
+ }
+ if httpClient == nil {
+ httpClient = &http.Client{Timeout: 1500 * time.Millisecond}
+ }
+ probeCtx, cancel := context.WithTimeout(ctx, 1500*time.Millisecond)
+ defer cancel()
+
+ u, err := url.Parse(endpoint)
+ if err != nil {
+ return false
+ }
+ probeURL := fmt.Sprintf("%s://%s/computeMetadata/v1/instance/service-accounts/default/email", u.Scheme, u.Host)
+ req, err := http.NewRequestWithContext(probeCtx, http.MethodGet, probeURL, nil)
+ if err != nil {
+ return false
+ }
+ req.Header.Set("Metadata-Flavor", "Google")
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return false
+ }
+ defer func() { _ = resp.Body.Close() }()
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1024))
+ return resp.StatusCode == http.StatusOK && strings.EqualFold(resp.Header.Get("Metadata-Flavor"), "Google")
+}
+
+// TokenSourceConfig configures how sam-node resolves its platform/OIDC JWT source.
+type TokenSourceConfig struct {
+ Node *SamNode
+ IssuerURL string
+ ClientID string
+ ClientSecret string
+ JWTPath string
+ CloudProvider string
+ Audience string
+ MetadataEndpoint string
+ HTTPClient *http.Client
+}
+
+// ResolveTokenSource selects the TokenSource for enrollment and renewal based
+// on the node's configuration. The returned continuousRefresh boolean is true
+// when the source is a non-interactive workload credential (--jwt-path,
+// --oidc-issuer, or GCP metadata) that should also be presented on every
+// POST /refresh call via TokenRefreshRequest.jwt.
+func ResolveTokenSource(ctx context.Context, cfg TokenSourceConfig) (TokenSource, bool, error) {
+ provider := strings.ToLower(strings.TrimSpace(cfg.CloudProvider))
+ if provider != "" && provider != "gcp" && provider != "auto" {
+ return nil, false, fmt.Errorf("unsupported --cloud-provider %q (supported values: gcp, auto)", cfg.CloudProvider)
+ }
+ if strings.TrimSpace(cfg.JWTPath) != "" {
+ return NewFileTokenSource(cfg.JWTPath), true, nil
+ }
+ if strings.TrimSpace(cfg.IssuerURL) != "" {
+ return NewClientCredentialsTokenSource(cfg.Node, cfg.IssuerURL, cfg.ClientID, cfg.ClientSecret), true, nil
+ }
+ if provider == "gcp" {
+ return NewGCPMetadataTokenSource(cfg.Audience, cfg.MetadataEndpoint, cfg.HTTPClient), true, nil
+ }
+ if provider == "auto" && ProbeGCPMetadata(ctx, cfg.MetadataEndpoint, cfg.HTTPClient) {
+ return NewGCPMetadataTokenSource(cfg.Audience, cfg.MetadataEndpoint, cfg.HTTPClient), true, nil
+ }
+ return NewRefreshTokenSource(cfg.Node, cfg.ClientSecret), false, nil
+}
diff --git a/internal/node/tokensource_test.go b/internal/node/tokensource_test.go
new file mode 100644
index 00000000..336d8586
--- /dev/null
+++ b/internal/node/tokensource_test.go
@@ -0,0 +1,247 @@
+// 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 (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/google/sam/api"
+ "github.com/google/sam/internal/identity"
+ "github.com/libp2p/go-libp2p/core/crypto"
+ "github.com/libp2p/go-libp2p/core/peer"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+func TestFileTokenSource(t *testing.T) {
+ ctx := context.Background()
+ dir := t.TempDir()
+ p := filepath.Join(dir, "jwt.token")
+
+ if err := os.WriteFile(p, []byte(" test-jwt-token \n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ src := NewFileTokenSource(p)
+ got, err := src.FetchToken(ctx)
+ if err != nil {
+ t.Fatalf("FetchToken: %v", err)
+ }
+ if got != "test-jwt-token" {
+ t.Errorf("got %q, want %q", got, "test-jwt-token")
+ }
+
+ if err := os.WriteFile(p, []byte(" \n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := src.FetchToken(ctx); err == nil {
+ t.Error("expected error for empty token file")
+ }
+
+ missing := NewFileTokenSource(filepath.Join(dir, "missing"))
+ if _, err := missing.FetchToken(ctx); err == nil {
+ t.Error("expected error for missing token file")
+ }
+}
+
+func TestGCPMetadataTokenSourceAndProbe(t *testing.T) {
+ ctx := context.Background()
+ mux := http.NewServeMux()
+ mux.HandleFunc("/computeMetadata/v1/instance/service-accounts/default/identity", func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Metadata-Flavor") != "Google" {
+ http.Error(w, "missing Metadata-Flavor", http.StatusForbidden)
+ return
+ }
+ if r.URL.Query().Get("audience") != "https://cp.example.com" {
+ http.Error(w, "wrong audience: "+r.URL.Query().Get("audience"), http.StatusBadRequest)
+ return
+ }
+ if r.URL.Query().Get("format") != "full" {
+ http.Error(w, "wrong format: "+r.URL.Query().Get("format"), http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("Metadata-Flavor", "Google")
+ _, _ = w.Write([]byte("gcp-metadata-id-token\n"))
+ })
+ mux.HandleFunc("/computeMetadata/v1/instance/service-accounts/default/email", func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Metadata-Flavor") != "Google" {
+ http.Error(w, "missing Metadata-Flavor", http.StatusForbidden)
+ return
+ }
+ w.Header().Set("Metadata-Flavor", "Google")
+ _, _ = w.Write([]byte("[email protected]"))
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ endpoint := srv.URL + "/computeMetadata/v1/instance/service-accounts/default/identity"
+ src := NewGCPMetadataTokenSource("https://cp.example.com", endpoint, srv.Client())
+ tok, err := src.FetchToken(ctx)
+ if err != nil {
+ t.Fatalf("FetchToken: %v", err)
+ }
+ if tok != "gcp-metadata-id-token" {
+ t.Errorf("got %q, want %q", tok, "gcp-metadata-id-token")
+ }
+
+ if !ProbeGCPMetadata(ctx, endpoint, srv.Client()) {
+ t.Error("ProbeGCPMetadata returned false for valid mock metadata server")
+ }
+
+ // Verify ResolveTokenSource with --cloud-provider=auto and --cloud-provider=gcp.
+ for _, provider := range []string{"gcp", "auto"} {
+ resolved, continuous, err := ResolveTokenSource(ctx, TokenSourceConfig{
+ CloudProvider: provider,
+ Audience: "https://cp.example.com",
+ MetadataEndpoint: endpoint,
+ HTTPClient: srv.Client(),
+ })
+ if err != nil {
+ t.Fatalf("ResolveTokenSource(%s): %v", provider, err)
+ }
+ if !continuous {
+ t.Errorf("ResolveTokenSource(%s) continuous = false, want true", provider)
+ }
+ got, err := resolved.FetchToken(ctx)
+ if err != nil || got != "gcp-metadata-id-token" {
+ t.Errorf("ResolveTokenSource(%s) FetchToken = (%q, %v)", provider, got, err)
+ }
+ }
+
+ // Unsupported provider must fail closed.
+ if _, _, err := ResolveTokenSource(ctx, TokenSourceConfig{CloudProvider: "azure"}); err == nil {
+ t.Error("expected error for unsupported --cloud-provider=azure")
+ }
+}
+
+type staticOrErrTokenSource struct {
+ token string
+ err error
+}
+
+func (s *staticOrErrTokenSource) FetchToken(_ context.Context) (string, error) {
+ return s.token, s.err
+}
+
+func TestRefreshEnrollmentSendsPlatformJWT(t *testing.T) {
+ SetAllowInsecureControlPlane(true)
+ ctx := context.Background()
+
+ cpPub, cpPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ privNode, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pID, err := peer.IDFromPrivateKey(privNode)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ initialExp := time.Now().Add(time.Hour)
+ initialBiscuit, _, err := identity.MintBiscuitToken(cpPriv, jwt.MapClaims{"sub": "worker-1"}, nil, pID, initialExp, []string{api.RoleNode}, nil, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var receivedJWT string
+ cpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/refresh" {
+ http.NotFound(w, r)
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ var req api.TokenRefreshRequest
+ if err := proto.Unmarshal(body, &req); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ receivedJWT = req.Jwt
+ newExp := time.Now().Add(2 * time.Hour)
+ nextBiscuit, _, err := identity.MintBiscuitToken(cpPriv, jwt.MapClaims{"sub": "worker-1"}, nil, pID, newExp, []string{api.RoleNode}, nil, nil)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ respBytes, _ := proto.Marshal(&api.TokenRefreshResponse{
+ BiscuitToken: nextBiscuit,
+ ExpireTime: timestamppb.New(newExp),
+ })
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ _, _ = w.Write(respBytes)
+ }))
+ defer cpSrv.Close()
+
+ nStore, err := NewStore(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = nStore.Close() }()
+ privBytes, err := crypto.MarshalPrivateKey(privNode)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := nStore.SaveKey(privBytes); err != nil {
+ t.Fatal(err)
+ }
+ if err := nStore.SaveControlPlaneURL(cpSrv.URL); err != nil {
+ t.Fatal(err)
+ }
+ if err := nStore.SaveIdentity(initialBiscuit); err != nil {
+ t.Fatal(err)
+ }
+ if err := nStore.SaveIdentityExpiration(initialExp.Unix()); err != nil {
+ t.Fatal(err)
+ }
+
+ n, err := NewSamNode(Options{
+ PrivKey: privNode,
+ Store: nStore,
+ ControlPlanePubKey: cpPub,
+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
+ TokenSource: &staticOrErrTokenSource{token: "fresh-platform-jwt-1"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if err := n.RefreshEnrollment(ctx); err != nil {
+ t.Fatalf("RefreshEnrollment with live TokenSource: %v", err)
+ }
+ if receivedJWT != "fresh-platform-jwt-1" {
+ t.Errorf("received TokenRefreshRequest.jwt = %q, want %q", receivedJWT, "fresh-platform-jwt-1")
+ }
+
+ // Transient TokenSource failure falls back to session-backed refresh (empty jwt).
+ n.SetTokenSource(&staticOrErrTokenSource{err: errors.New("temporary metadata outage")})
+ if err := n.RefreshEnrollment(ctx); err != nil {
+ t.Fatalf("RefreshEnrollment with failing TokenSource: %v", err)
+ }
+ if receivedJWT != "" {
+ t.Errorf("expected empty jwt on transient TokenSource failure, got %q", receivedJWT)
+ }
+}
diff --git a/internal/router/router.go b/internal/router/router.go
index 029879ec..727caf6e 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -716,12 +716,12 @@ func (r *Router) enrollWithTokens(peerID peer.ID) error {
}
// Fallback to OIDC token
- if r.config.JWTPath != "" {
- tokenData, err := os.ReadFile(r.config.JWTPath)
+ if src := r.tokenSource(); src != nil {
+ tok, err := src.FetchToken(r.ctx)
if err != nil {
return fmt.Errorf("failed to read JWT from path %s: %w", r.config.JWTPath, err)
}
- r.config.OIDCToken = strings.TrimSpace(string(tokenData))
+ r.config.OIDCToken = tok
}
if r.config.OIDCToken != "" {
@@ -735,6 +735,13 @@ func (r *Router) enrollWithTokens(peerID peer.ID) error {
return fmt.Errorf("no enrollment token available")
}
+func (r *Router) tokenSource() cpclient.TokenSource {
+ if strings.TrimSpace(r.config.JWTPath) != "" {
+ return cpclient.NewFileTokenSource(r.config.JWTPath)
+ }
+ return nil
+}
+
func (r *Router) reEnroll() error {
r.enrollMu.Lock()
defer r.enrollMu.Unlock()
@@ -1471,6 +1478,13 @@ func (r *Router) RefreshEnrollment(ctx context.Context) error {
ChallengeUnixMs: timestamp,
PeerId: peerID.String(),
}
+ if src := r.tokenSource(); src != nil {
+ if jwt, err := src.FetchToken(ctx); err == nil && jwt != "" {
+ req.Jwt = jwt
+ } else if err != nil {
+ logger.Warnf("Failed to fetch platform JWT for router refresh re-attestation, continuing with PoP-only refresh: %v", err)
+ }
+ }
reqData, err := proto.Marshal(req)
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
diff --git a/internal/router/router_test.go b/internal/router/router_test.go
index 1a870c0d..cc1755a9 100644
--- a/internal/router/router_test.go
+++ b/internal/router/router_test.go
@@ -1065,3 +1065,61 @@ func TestReconcileBannedPeers(t *testing.T) {
t.Error("a ban recorded at the fetch instant must survive: the answer is not newer than the ban, so it cannot report it unbanned")
}
}
+
+func TestRouterRefreshEnrollmentReattestsJWT(t *testing.T) {
+ issuer, mintToken := startCustomMockOIDC(t)
+ cp, cpStore, cpURL := setupControlPlane(t, issuer)
+ defer func() {
+ _ = cp.Close()
+ _ = cpStore.Close()
+ }()
+
+ tempDir := t.TempDir()
+ jwtPath := filepath.Join(tempDir, "router.jwt")
+ initialJWT := mintToken(map[string]interface{}{
+ "sub": "system:serviceaccount:sam-system:sam-router",
+ "groups": []string{"routers"},
+ })
+ if err := os.WriteFile(jwtPath, []byte(initialJWT+"\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ r, err := NewRouter(context.Background(), Options{
+ ControlPlaneURL: cpURL,
+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
+ KeysSyncInterval: time.Hour,
+ LeaseRenewInterval: time.Hour,
+ JWTPath: jwtPath,
+ KeysDBPath: filepath.Join(tempDir, "router.key"),
+ AllowLoopback: true,
+ BiscuitTimeout: time.Second,
+ })
+ if err != nil {
+ t.Fatalf("NewRouter: %v", err)
+ }
+ if err := r.Start(); err != nil {
+ t.Fatalf("r.Start: %v", err)
+ }
+ defer func() { _ = r.Close() }()
+
+ rotatedJWT := mintToken(map[string]interface{}{
+ "sub": "system:serviceaccount:sam-system:sam-router",
+ "groups": []string{"routers"},
+ "email": "[email protected]",
+ })
+ if err := os.WriteFile(jwtPath, []byte(rotatedJWT), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := r.RefreshEnrollment(context.Background()); err != nil {
+ t.Fatalf("RefreshEnrollment with rotated JWT: %v", err)
+ }
+
+ rec, err := cpStore.GetNode(context.Background(), r.Host.ID().String())
+ if err != nil || rec == nil {
+ t.Fatalf("GetNode: %v", err)
+ }
+ if !strings.Contains(rec.ClaimsJSON, "[email protected]") {
+ t.Errorf("ClaimsJSON = %s, want updated claim from rotated router JWT", rec.ClaimsJSON)
+ }
+}
diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.go
index fed07e47..32c373b0 100644
--- a/internal/standalone/standalone.go
+++ b/internal/standalone/standalone.go
@@ -109,6 +109,7 @@ type Options struct {
PolicyFile string
// OIDCIssuer optionally enables full OIDC enrollment.
OIDCIssuer string
+ WorkloadIssuer string
AllowedAudiences []string
// OIDCClientID is the OAuth client id advertised via /info.
OIDCClientID string
@@ -129,6 +130,9 @@ type ControlPlaneTunables struct {
KeyGracePeriod time.Duration
// BiscuitTTL is the lifespan minted into issued biscuits.
BiscuitTTL time.Duration
+ // WorkloadSessionTTL is how long a workload-issuer enrollment stays
+ // refreshable without presenting a fresh platform JWT on /refresh.
+ WorkloadSessionTTL time.Duration
// ManualEnrollment queues bootstrap enrollments for admin approval
// instead of auto-approving them.
ManualEnrollment bool
@@ -263,12 +267,14 @@ func (s *Server) Start(ctx context.Context) error {
DriverName: s.opts.DBDriver,
DataSourceName: s.opts.DBDSN,
OIDCIssuer: s.opts.OIDCIssuer,
+ WorkloadIssuer: s.opts.WorkloadIssuer,
OIDCClientID: s.opts.OIDCClientID,
AllowedAudiences: s.opts.AllowedAudiences,
LeaseDuration: s.opts.ControlPlane.LeaseDuration,
KeyRotationInterval: s.opts.ControlPlane.KeyRotationInterval,
KeyGracePeriod: s.opts.ControlPlane.KeyGracePeriod,
BiscuitTTL: s.opts.ControlPlane.BiscuitTTL,
+ WorkloadSessionTTL: s.opts.ControlPlane.WorkloadSessionTTL,
BiscuitTimeout: 10 * time.Second,
AdminToken: s.adminToken,
AutoApproveEnrollment: !s.opts.ControlPlane.ManualEnrollment,
diff --git a/sdk/js/README.md b/sdk/js/README.md
index 4cccc11d..0b403926 100644
--- a/sdk/js/README.md
+++ b/sdk/js/README.md
@@ -167,10 +167,12 @@ process.on("SIGTERM", stop);
`enroll` reuses the identity and credential saved in `stateDir` when they
are still valid for that control plane, and needs exactly one of
-`bootstrapTokenPath`, `bootstrapToken` or `jwt` otherwise. Read tokens from
-a file or the environment; do not put them on a command line. `labels` are
-attested at enrollment; `join({ egressRequireLabels })` is the floor every
-peer the session calls must attest, all of it, held for the session.
+`bootstrapTokenPath`, `bootstrapToken`, `jwtPath` or `jwt` (a token string or
+a `() => string | Promise<string>` callback invoked at enrollment and on every
+refresh) otherwise. Read tokens from a file, a callback or the environment; do
+not put them on a command line. `labels` are attested at enrollment;
+`join({ egressRequireLabels })` is the floor every peer the session calls must
+attest, all of it, held for the session.
A plaintext `http://` control plane is accepted only on loopback. Pass
`allowInsecure: true` for a network you trust.
diff --git a/sdk/js/src/controlplane.ts b/sdk/js/src/controlplane.ts
index 1290ee56..8cbf51b7 100644
--- a/sdk/js/src/controlplane.ts
+++ b/sdk/js/src/controlplane.ts
@@ -134,6 +134,8 @@ export interface RefreshParams {
identity: Identity;
/** The biscuit currently held; only the last one issued is redeemable. */
biscuit: Uint8Array;
+ /** Optional fresh platform/OIDC JWT for continuous attestation on refresh. */
+ jwt?: string | undefined;
}
export interface RefreshResult {
@@ -331,6 +333,7 @@ export class ControlPlaneClient {
challengeUnixMs: BigInt(ts),
challengeSignature: identity.sign(refreshChallenge(identity.peerId, ts)),
peerId: identity.peerId,
+ ...(params.jwt ? { jwt: params.jwt } : {}),
});
const body = await this.#request("POST", "/refresh", toBinary(TokenRefreshRequestSchema, req), {
Authorization: `Bearer ${toBase64(params.biscuit)}`,
diff --git a/sdk/js/src/gen/sam_pb.ts b/sdk/js/src/gen/sam_pb.ts
index a7d5727b..be7dea1e 100644
--- a/sdk/js/src/gen/sam_pb.ts
+++ b/sdk/js/src/gen/sam_pb.ts
@@ -26,7 +26,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file sam.proto.
*/
export const file_sam: GenFile = /*@__PURE__*/
- fileDesc("CglzYW0ucHJvdG8SBnNhbS52MSI0CglBdXRoRnJhbWUSDwoHYmlzY3VpdBgBIAEoDBIWCg50YXJnZXRfc2VydmljZRgCIAEoCSI/CgxBdXRoUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCRIPCgdiaXN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SqUAQoQRW5yb2xsbWVudFN0YXR1cxIhCh1FTlJPTExNRU5UX1NUQVRVU19VTlNQRUNJRklFRBAAEh0KGUVOUk9MTE1FTlRfU1RBVFVTX1BFTkRJTkcQARIeChpFTlJPTExNRU5UX1NUQVRVU19BUFBST1ZFRBACEh4KGkVOUk9MTE1FTlRfU1RBVFVTX1JFSkVDVEVEEAMqjAEKC1NlcnZpY2VUeXBlEhwKGFNFUlZJQ0VfVFlQRV9VTlNQRUNJRklFRBAAEhQKEFNFUlZJQ0VfVFlQRV9NQ1AQARIaChZTRVJWSUNFX1RZUEVfSU5GRVJFTkNFEAISFAoQU0VSVklDRV9UWVBFX0EyQRADEhcKE1NFUlZJQ0VfVFlQRV9FR1JFU1MQBCo3CgpFZ3Jlc3NNb2RlEhQKEEVHUkVTU19NT0RFX0hUVFAQABITCg9FR1JFU1NfTU9ERV9UQ1AQASpcChJSZXNwb25zZUluc3BlY3Rpb24SIAocUkVTUE9OU0VfSU5TUEVDVElPTl9CVUZGRVJFRBAAEiQKIFJFU1BPTlNFX0lOU1BFQ1RJT05fUkVRVUVTVF9PTkxZEAFCG1oZZ2l0aHViLmNvbS9nb29nbGUvc2FtL2FwaWIGcHJvdG8z", [file_google_protobuf_duration, file_google_protobuf_timestamp]);
/**
* @generated from message sam.v1.AuthFrame
@@ -1479,6 +1479,16 @@ export type TokenRefreshRequest = Message<"sam.v1.TokenRefreshRequest"> & {
* @generated from field: string peer_id = 3;
*/
peerId: string;
+
+ /**
+ * Optional fresh platform JWT for an OIDC-enrolled node. When set, the
+ * control plane verifies the JWT, confirms that iss|sub matches the
+ * stored enrollment's identity, and renews the stored claims and session
+ * expiry in place before minting the refreshed biscuit.
+ *
+ * @generated from field: string jwt = 4;
+ */
+ jwt: string;
};
/**
diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.ts
index 4f6dd807..4ff81249 100644
--- a/sdk/js/src/index.ts
+++ b/sdk/js/src/index.ts
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-export { AgentMesh, CredentialRetiredError, type AgentMeshOptions, type ControlPlaneSync, type EnrollOptions } from "./mesh.ts";
+export { AgentMesh, CredentialRetiredError, type AgentMeshOptions, type ControlPlaneSync, type EnrollOptions, type JwtSource } from "./mesh.ts";
export { Identity, canonicalPeerId, peerIdFromPublicKey, libp2pPublicKey, verifyEd25519 } from "./identity.ts";
export {
ControlPlaneClient,
diff --git a/sdk/js/src/mesh.test.ts b/sdk/js/src/mesh.test.ts
index 52e770fc..b9605c36 100644
--- a/sdk/js/src/mesh.test.ts
+++ b/sdk/js/src/mesh.test.ts
@@ -28,6 +28,7 @@ import {
EnrollResponseSchema,
EnrollmentStatus,
KeysResponseSchema,
+ TokenRefreshRequestSchema,
TokenRefreshResponseSchema,
} from "./gen/sam_pb.ts";
import { Identity } from "./identity.ts";
@@ -41,9 +42,9 @@ function proto(bytes: Uint8Array): Response {
}
/** A control plane that approves everything and hands out numbered biscuits. */
-function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: number; keys: Identity[]; keysOk: boolean } {
+function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: number; lastRefreshJwt: string; keys: Identity[]; keysOk: boolean } {
// keys is what /keys serves and signs with; a test rotates by replacing it.
- const state = { issued: 0, keys: [cpKey], keysOk };
+ const state = { issued: 0, lastRefreshJwt: "", keys: [cpKey], keysOk };
const current = () => (state.keys[state.keys.length - 1] as Identity).publicKeyRaw;
const signedKeys = () => {
const unsigned = create(KeysResponseSchema, { publicKeys: state.keys.map((k) => k.publicKeyRaw), signTime: timestampFromMs(Date.now()) });
@@ -68,9 +69,20 @@ function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: number;
}),
),
);
- case "POST /refresh":
+ case "POST /refresh": {
+ const refreshReq = fromBinary(TokenRefreshRequestSchema, new Uint8Array(await req.arrayBuffer()));
+ state.lastRefreshJwt = refreshReq.jwt;
state.issued++;
- return proto(toBinary(TokenRefreshResponseSchema, create(TokenRefreshResponseSchema, { biscuitToken: text(`biscuit-${state.issued}`), expireTime: timestampFromMs(Date.now() + 7200_000) })));
+ return proto(
+ toBinary(
+ TokenRefreshResponseSchema,
+ create(TokenRefreshResponseSchema, {
+ biscuitToken: text(refreshReq.jwt ? `biscuit-for-${refreshReq.jwt}` : `biscuit-${state.issued}`),
+ expireTime: timestampFromMs(Date.now() + 7200_000),
+ }),
+ ),
+ );
+ }
case "POST /register": {
// The biscuit names the JWT that was presented, so a test can see which.
const jwt = fromBinary(EnrollRequestSchema, new Uint8Array(await req.arrayBuffer())).jwt;
@@ -98,6 +110,9 @@ function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: number;
get issued() {
return state.issued;
},
+ get lastRefreshJwt() {
+ return state.lastRefreshJwt;
+ },
get keys() {
return state.keys;
},
@@ -241,20 +256,53 @@ test("enroll refuses ambiguous credentials", async () => {
assert.equal(cp.issued, 0);
});
-test("enroll reads a workload identity token from jwtPath", async () => {
+test("enroll reads a workload identity token from jwtPath and re-reads on refresh", async () => {
const dir = await mkdtemp(join(tmpdir(), "sam-sdk-"));
try {
const cp = fakeControlPlane();
const jwtPath = join(dir, "token");
- await writeFile(jwtPath, "eyJ.projected.token\n");
+ await writeFile(jwtPath, "eyJ.projected.token.1\n");
const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", jwtPath, fetch: cp.fetch });
- assert.deepEqual(mesh.credential.biscuit, text("biscuit-for-eyJ.projected.token"));
+ assert.deepEqual(mesh.credential.biscuit, text("biscuit-for-eyJ.projected.token.1"));
+
+ await writeFile(jwtPath, "eyJ.projected.token.2\n");
+ await mesh.refresh();
+ assert.equal(cp.lastRefreshJwt, "eyJ.projected.token.2");
+ assert.deepEqual(mesh.credential.biscuit, text("biscuit-for-eyJ.projected.token.2"));
+
await assert.rejects(AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", jwtPath: join(dir, "missing"), fetch: cp.fetch }), /ENOENT/);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
+test("enroll accepts a jwt callback and invokes it on refresh", async () => {
+ const cp = fakeControlPlane();
+ let seq = 0;
+ let shouldFail = false;
+ const mesh = await AgentMesh.enroll({
+ controlPlaneUrl: "http://127.0.0.1:1",
+ jwt: async () => {
+ if (shouldFail) {
+ throw new Error("metadata server temporarily unavailable");
+ }
+ seq++;
+ return ` eyJ.callback.${seq} \n`;
+ },
+ fetch: cp.fetch,
+ });
+ assert.deepEqual(mesh.credential.biscuit, text("biscuit-for-eyJ.callback.1"));
+
+ await mesh.refresh();
+ assert.equal(cp.lastRefreshJwt, "eyJ.callback.2");
+ assert.deepEqual(mesh.credential.biscuit, text("biscuit-for-eyJ.callback.2"));
+
+ // Best-effort fallback when the callback fails during refresh.
+ shouldFail = true;
+ await mesh.refresh();
+ assert.equal(cp.lastRefreshJwt, "");
+});
+
test("authFrame is the AuthFrame protobuf with this member's biscuit", async () => {
const cp = fakeControlPlane();
const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt_secret", fetch: cp.fetch });
diff --git a/sdk/js/src/mesh.ts b/sdk/js/src/mesh.ts
index 0bb9ad26..ae00d709 100644
--- a/sdk/js/src/mesh.ts
+++ b/sdk/js/src/mesh.ts
@@ -93,17 +93,23 @@ export interface AgentMeshOptions {
fetch?: typeof fetch;
}
+/** Callback returning a fresh platform or OIDC JWT for enrollment and refresh. */
+export type JwtSource = () => string | Promise<string>;
+
export interface EnrollOptions extends AgentMeshOptions {
/** A bootstrap token value, when the caller already holds it in memory. */
bootstrapToken?: string | undefined;
/** Path of a file holding the bootstrap token. Preferred over a value on Node; a browser has no files. */
bootstrapTokenPath?: string | undefined;
- /** An OIDC ID token, for meshes that enroll identities interactively. */
- jwt?: string | undefined;
+ /**
+ * An OIDC ID token value, or a callback returning a fresh OIDC / platform
+ * workload identity token at enrollment and on every refresh.
+ */
+ jwt?: string | JwtSource | undefined;
/**
* Path of a file holding an OIDC ID token or a platform's workload identity
* token, such as a Kubernetes projected service account token. Preferred
- * over a value; the file is read at enrollment.
+ * over a value; the file is read at enrollment and on every refresh.
*/
jwtPath?: string | undefined;
/** Bounds the wait for an operator to approve a pending enrollment. */
@@ -136,12 +142,20 @@ export class AgentMesh {
readonly controlPlane: ControlPlaneClient;
#credential: MeshCredential;
readonly #state: StateStore | undefined;
-
- private constructor(identity: Identity, controlPlane: ControlPlaneClient, credential: MeshCredential, state: StateStore | undefined) {
+ readonly #jwtSource: (() => Promise<string>) | undefined;
+
+ private constructor(
+ identity: Identity,
+ controlPlane: ControlPlaneClient,
+ credential: MeshCredential,
+ state: StateStore | undefined,
+ jwtSource?: (() => Promise<string>) | undefined,
+ ) {
this.identity = identity;
this.controlPlane = controlPlane;
this.#credential = withCredentialMethods(credential);
this.#state = state;
+ this.#jwtSource = jwtSource;
}
get peerId(): string {
@@ -181,13 +195,14 @@ export class AgentMesh {
const saved = await loadIdentity(state);
const identity = options.identity ?? saved ?? Identity.generate();
const controlPlane = newClient(options);
+ const jwtSource = resolveJwtSource(options);
const given = [options.bootstrapToken, options.bootstrapTokenPath, options.jwt, options.jwtPath].filter((v) => v !== undefined).length;
if (state !== undefined && saved !== undefined && saved.peerId === identity.peerId) {
const credential = await loadCredential(state);
if (credential !== undefined && sameBaseUrl(credential.controlPlaneUrl, controlPlane.url) && credentialTimeToLiveSeconds(credential) > REUSE_MIN_TTL_SECONDS) {
const resumed = await resumableCredential(controlPlane, credential);
if (resumed !== undefined) {
- const mesh = new AgentMesh(identity, controlPlane, resumed, state);
+ const mesh = new AgentMesh(identity, controlPlane, resumed, state, jwtSource);
if (resumed !== credential) {
await mesh.save();
}
@@ -206,7 +221,7 @@ export class AgentMesh {
let enrollment: Enrollment;
if (options.jwt !== undefined || options.jwtPath !== undefined) {
- const jwt = options.jwtPath !== undefined ? (await readTextFile(options.jwtPath)).trim() : (options.jwt as string);
+ const jwt = jwtSource !== undefined ? await jwtSource() : (options.jwt as string);
enrollment = await controlPlane.register({ identity, jwt, role, ...labelsOf(options) });
} else {
const bootstrapToken = options.bootstrapTokenPath !== undefined ? (await readTextFile(options.bootstrapTokenPath)).trim() : (options.bootstrapToken as string);
@@ -242,6 +257,7 @@ export class AgentMesh {
routerAddresses: enrollment.routerAddresses,
},
state,
+ jwtSource,
);
await mesh.save();
return mesh;
@@ -252,7 +268,13 @@ export class AgentMesh {
* for a process that must never hold an enrollment token. The control
* plane URL comes from the saved credential.
*/
- static async load(options: Omit<AgentMeshOptions, "controlPlaneUrl"> & { stateDir: string }): Promise<AgentMesh> {
+ static async load(
+ options: Omit<AgentMeshOptions, "controlPlaneUrl"> & {
+ stateDir: string;
+ jwt?: JwtSource | undefined;
+ jwtPath?: string | undefined;
+ },
+ ): Promise<AgentMesh> {
const state = openState(options.stateDir);
const identity = options.identity ?? (await loadIdentity(state));
if (!identity) {
@@ -262,7 +284,13 @@ export class AgentMesh {
if (credential === undefined) {
throw new Error(`no credential in ${options.stateDir}; enroll first`);
}
- return new AgentMesh(identity, newClient({ ...options, controlPlaneUrl: credential.controlPlaneUrl }), credential, state);
+ return new AgentMesh(
+ identity,
+ newClient({ ...options, controlPlaneUrl: credential.controlPlaneUrl }),
+ credential,
+ state,
+ resolveJwtSource(options),
+ );
}
/**
@@ -271,7 +299,22 @@ export class AgentMesh {
* means re-enrolling; persisting before returning keeps that rare.
*/
async refresh(): Promise<MeshCredential> {
- const result = await this.controlPlane.refresh({ identity: this.identity, biscuit: this.#credential.biscuit });
+ let jwt: string | undefined;
+ if (this.#jwtSource !== undefined) {
+ try {
+ const token = await this.#jwtSource();
+ if (token !== "") {
+ jwt = token;
+ }
+ } catch {
+ // Best effort: fall back to session-only refresh if the token source is temporarily unavailable.
+ }
+ }
+ const result = await this.controlPlane.refresh({
+ identity: this.identity,
+ biscuit: this.#credential.biscuit,
+ ...(jwt !== undefined ? { jwt } : {}),
+ });
let controlPlaneKeys = this.#credential.controlPlaneKeys;
try {
controlPlaneKeys = await this.controlPlane.keys(controlPlaneKeys);
@@ -415,3 +458,16 @@ function baseUrl(url: URL | string): string {
function sameBaseUrl(a: URL | string, b: URL | string): boolean {
return baseUrl(a) === baseUrl(b);
}
+
+function resolveJwtSource(options: { jwt?: string | JwtSource | undefined; jwtPath?: string | undefined }): (() => Promise<string>) | undefined {
+ if (options.jwtPath !== undefined) {
+ const path = options.jwtPath;
+ return async () => (await readTextFile(path)).trim();
+ }
+ if (typeof options.jwt === "function") {
+ const fn = options.jwt;
+ return async () => (await fn()).trim();
+ }
+ return undefined;
+}
+
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 99b17648..d15fa286 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -175,10 +175,12 @@ trio.run(main)
`enroll` reuses the identity and credential saved in `state_dir` when they
are still valid for that control plane, and needs exactly one of
-`bootstrap_token_path`, `bootstrap_token` or `jwt` otherwise. Read tokens
-from a file or the environment; do not put them on a command line. `labels`
-are attested at enrollment; `join(egress_require_labels=)` is the floor
-every peer the session calls must attest, all of it, held for the session.
+`bootstrap_token_path`, `bootstrap_token`, `jwt_path` or `jwt` (a token string
+or a `Callable[[], str]` invoked at enrollment and on every refresh)
+otherwise. Read tokens from a file, a callback or the environment; do not put
+them on a command line. `labels` are attested at enrollment;
+`join(egress_require_labels=)` is the floor every peer the session calls must
+attest, all of it, held for the session.
A plaintext `http://` control plane is accepted only on loopback. Pass
`allow_insecure=True` for a network you trust.
diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.py
index 4e952a20..2e78b04c 100644
--- a/sdk/python/src/agent_mesh/__init__.py
+++ b/sdk/python/src/agent_mesh/__init__.py
@@ -52,7 +52,7 @@ from .libp2p_http import (
rewrite_agent_card,
)
from .mcp_client import LabelsNotSatisfiedError, ToolCallResult, ToolInfo, open_mcp_session, require_egress_labels, require_labels
-from .mesh import AgentMesh, ControlPlaneSync, CredentialRetiredError
+from .mesh import AgentMesh, ControlPlaneSync, CredentialRetiredError, JwtSource
from .relay import dial_through_relay, reserve_relay
from .session import AdmittedRouter, MeshSession, Peer
from .sync import GOSSIP_EVENTS_TOPIC, BanSet, verify_mesh_event
@@ -103,6 +103,7 @@ __all__ = [
"HTTPResponse",
"Identity",
"InsecureControlPlaneURLError",
+ "JwtSource",
"KeysNotTrustedError",
"LabelsNotSatisfiedError",
"MCP_PROTOCOL",
diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.py b/sdk/python/src/agent_mesh/_proto/sam_pb2.py
index 3d83a3ae..913ace80 100644
--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.py
+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.py
@@ -15,7 +15,7 @@ from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tsam.proto\x12\x06sam.v1\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"4\n\tAuthFrame\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x16\n\x0etarget_service\x18\x02 \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\"\xd6\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.\n\nevent_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\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\"\xf3\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\x19\n\x11\x63hallenge_unix_ms\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\"\xab\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/\n\x0b\x65xpire_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x91\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\x19\n\x11\x63hallenge_unix_ms\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\"\xfd\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/\n\x0b\x65xpire_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"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\"\xb2\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\x31\n\rannounce_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\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\"\xac\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\x19\n\x11\x63hallenge_unix_ms\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\"f\n\x13RouterLeaseResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12/\n\x0b\x65xpire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x9e\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_labels\x18\x05 \x03(\t\x12\x1f\n\x04http\x18\x06 \x03(\x0b\x32\x11.sam.v1.HTTPGrant\"<\n\tHTTPGrant\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x0f\n\x07methods\x18\x02 \x03(\t\x12\r\n\x05paths\x18\x03 \x03(\t\"\x8f\x02\n\x11\x45gressDestination\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ntarget_url\x18\x02 \x01(\t\x12\x12\n\ncredential\x18\x03 \x01(\t\x12\x11\n\tserved_by\x18\x04 \x03(\t\x12(\n\x06\x62roker\x18\x05 \x01(\x0b\x32\x18.sam.v1.CredentialBroker\x12&\n\ninspection\x18\x06 \x01(\x0b\x32\x12.sam.v1.Inspection\x12 \n\x04mode\x18\x07 \x01(\x0e\x32\x12.sam.v1.EgressMode\x12\r\n\x05ports\x18\x08 \x03(\r\x12\x15\n\rpreserve_host\x18\t \x01(\x08\x12\x17\n\x0f\x66orward_context\x18\n \x01(\x08\"3\n\nInspection\x12%\n\ninspectors\x18\x01 \x03(\x0b\x32\x11.sam.v1.Inspector\"c\n\tInspector\x12)\n\x0bmodel_armor\x18\x01 \x01(\x0b\x32\x12.sam.v1.ModelArmorH\x00\x12#\n\x08\x65xt_proc\x18\x02 \x01(\x0b\x32\x0f.sam.v1.ExtProcH\x00\x42\x06\n\x04kind\"\x8b\x01\n\nModelArmor\x12\x10\n\x08template\x18\x01 \x01(\t\x12,\n\x08response\x18\x02 \x01(\x0e\x32\x1a.sam.v1.ResponseInspection\x12\x11\n\tfail_open\x18\x03 \x01(\x08\x12*\n\x07timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\"\x82\x02\n\x07\x45xtProc\x12\x0e\n\x06target\x18\x01 \x01(\t\x12\n\n\x02\x63\x61\x18\x02 \x01(\t\x12\x1a\n\x12\x63lient_certificate\x18\x03 \x01(\t\x12\x36\n\x0fprocessing_mode\x18\x04 \x01(\x0b\x32\x1d.sam.v1.ExtProcProcessingMode\x12\x1b\n\x13\x61llow_mode_override\x18\x05 \x01(\x08\x12\x32\n\x0fmessage_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x1a\n\x12\x66\x61ilure_mode_allow\x18\x07 \x01(\x08\x12\x1a\n\x12max_buffered_bytes\x18\x08 \x01(\r\"\xdb\x04\n\x15\x45xtProcProcessingMode\x12\x45\n\x13request_header_mode\x18\x01 \x01(\x0e\x32(.sam.v1.ExtProcProcessingMode.HeaderMode\x12\x46\n\x14response_header_mode\x18\x02 \x01(\x0e\x32(.sam.v1.ExtProcProcessingMode.HeaderMode\x12\x41\n\x11request_body_mode\x18\x03 \x01(\x0e\x32&.sam.v1.ExtProcProcessingMode.BodyMode\x12\x42\n\x12response_body_mode\x18\x04 \x01(\x0e\x32&.sam.v1.ExtProcProcessingMode.BodyMode\x12\x46\n\x14request_trailer_mode\x18\x05 \x01(\x0e\x32(.sam.v1.ExtProcProcessingMode.HeaderMode\x12G\n\x15response_trailer_mode\x18\x06 \x01(\x0e\x32(.sam.v1.ExtProcProcessingMode.HeaderMode\"9\n\nHeaderMode\x12\x17\n\x13HEADER_MODE_DEFAULT\x10\x00\x12\x08\n\x04SEND\x10\x01\x12\x08\n\x04SKIP\x10\x02\"`\n\x08\x42odyMode\x12\x08\n\x04NONE\x10\x00\x12\x0c\n\x08STREAMED\x10\x01\x12\x0c\n\x08\x42UFFERED\x10\x02\x12\x14\n\x10\x42UFFERED_PARTIAL\x10\x03\x12\x18\n\x14\x46ULL_DUPLEX_STREAMED\x10\x04\"\xcf\x01\n\x10\x43redentialBroker\x12\x17\n\rstatic_secret\x18\x01 \x01(\tH\x00\x12\x31\n\x0foidc_federation\x18\x02 \x01(\x0b\x32\x16.sam.v1.OIDCFederationH\x00\x12\x30\n\x0f\x61ws_assume_role\x18\x03 \x01(\x0b\x32\x15.sam.v1.AWSAssumeRoleH\x00\x12\x35\n\x11platform_identity\x18\x04 \x01(\x0b\x32\x18.sam.v1.PlatformIdentityH\x00\x42\x06\n\x04kind\"_\n\x0eOIDCFederation\x12\x16\n\x0etoken_endpoint\x18\x01 \x01(\t\x12\x10\n\x08\x61udience\x18\x02 \x01(\t\x12\x13\n\x0bimpersonate\x18\x03 \x01(\t\x12\x0e\n\x06scopes\x18\x04 \x03(\t\"9\n\rAWSAssumeRole\x12\x10\n\x08role_arn\x18\x01 \x01(\t\x12\x16\n\x0esession_policy\x18\x02 \x01(\t\"\"\n\x10PlatformIdentity\x12\x0e\n\x06scopes\x18\x01 \x03(\t\".\n\rPolicyBinding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\t\"\x85\x01\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\x12)\n\x06\x65gress\x18\x03 \x03(\x0b\x32\x19.sam.v1.EgressDestination\"\x18\n\x16PolicyConfigGetRequest\"0\n\x17PolicyConfigGetResponse\x12\x15\n\rdatalog_rules\x18\x01 \x03(\t\"<\n\x1aPolicyConfigUpdateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"\x1a\n\x18\x45gressAssignmentsRequest\"F\n\x19\x45gressAssignmentsResponse\x12)\n\x06\x65gress\x18\x01 \x03(\x0b\x32\x19.sam.v1.EgressDestination\"f\n\x0cKeysResponse\x12\x13\n\x0bpublic_keys\x18\x01 \x03(\x0c\x12-\n\tsign_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\nsignatures\x18\x03 \x03(\x0c\"^\n\x13TokenRefreshRequest\x12\x1b\n\x13\x63hallenge_signature\x18\x01 \x01(\x0c\x12\x19\n\x11\x63hallenge_unix_ms\x18\x02 \x01(\x03\x12\x0f\n\x07peer_id\x18\x03 \x01(\t\"u\n\x14TokenRefreshResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12/\n\x0b\x65xpire_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\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\"\xe4\x01\n\x18IdentityEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x37\n\x13\x62iscuit_expire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x19\n\x11\x63ontrol_plane_url\x18\x04 \x01(\t\x12\"\n\x1atrusted_control_plane_keys\x18\x05 \x03(\x0c\x12.\n\ncheck_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\xc0\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/\n\x0b\x65xpire_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x16\n\x0erevocation_ids\x18\x07 \x03(\t\x12.\n\ncheck_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x80\x02\n\x10MemberCredential\x12\x19\n\x11\x63ontrol_plane_url\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12/\n\x0b\x65xpire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0ctrusted_keys\x18\x04 \x03(\x0b\x32\x19.sam.v1.TrustedSigningKey\x12\x19\n\x11issued_under_keys\x18\x05 \x03(\x0c\x12\x18\n\x10router_addresses\x18\x06 \x03(\t\x12)\n\x0coidc_session\x18\x07 \x01(\x0b\x32\x13.sam.v1.OIDCSession\"Y\n\x11TrustedSigningKey\x12\x12\n\npublic_key\x18\x01 \x01(\x0c\x12\x30\n\x0creceive_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"Y\n\x0bOIDCSession\x12\x0e\n\x06issuer\x18\x01 \x01(\t\x12\x11\n\tclient_id\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x15\n\rrefresh_token\x18\x04 \x01(\t\"\x8d\x01\n\x15TaskAuthorizationRule\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x1f\n\x05rules\x18\x03 \x03(\x0b\x32\x10.sam.v1.TaskRule\x12/\n\x0b\x65xpire_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"~\n\x08TaskRule\x12\x13\n\x0b\x64\x65scription\x18\x01 \x01(\t\x12\x18\n\x10\x61llowed_services\x18\x02 \x03(\t\x12(\n\toperation\x18\x03 \x01(\x0b\x32\x15.sam.v1.TaskOperation\x12\x19\n\x11\x61llowed_resources\x18\x04 \x03(\t\"s\n\rTaskOperation\x12\x15\n\rallowed_tools\x18\x01 \x03(\t\x12\x17\n\x0f\x61llowed_methods\x18\x02 \x03(\t\x12\x15\n\rallowed_paths\x18\x03 \x03(\t\x12\x1b\n\x13\x61llowed_permissions\x18\x04 \x03(\t\"\xa5\x01\n\x14TokenExchangeRequest\x12\x15\n\rsubject_token\x18\x01 \x01(\t\x12\x30\n\ttask_rule\x18\x02 \x01(\x0b\x32\x1d.sam.v1.TaskAuthorizationRule\x12\x0c\n\x04seal\x18\x03 \x01(\x08\x12\x19\n\x11\x63hallenge_unix_ms\x18\x04 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x05 \x01(\x0c\"\x7f\n\x15TokenExchangeResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12/\n\x0b\x65xpire_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\r\n\x05roles\x18\x03 \x03(\t\x12\x0f\n\x07subject\x18\x04 \x01(\t\"\x81\x01\n\x0fSTSTokenRequest\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x13\n\x0b\x64\x65stination\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x19\n\x11\x63hallenge_unix_ms\x18\x04 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x05 \x01(\x0c\"\x83\x01\n\x10STSTokenResponse\x12\x0b\n\x03jwt\x18\x01 \x01(\t\x12/\n\x0b\x65xpire_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07subject\x18\x03 \x01(\t\x12\r\n\x05roles\x18\x04 \x03(\t\x12\x11\n\ttask_name\x18\x05 \x01(\t\"F\n\x13RevocationsResponse\x12\x16\n\x0erevocation_ids\x18\x01 \x03(\t\x12\x17\n\x0f\x62\x61nned_peer_ids\x18\x02 \x03(\t*\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*\x8c\x01\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\x12\x17\n\x13SERVICE_TYPE_EGRESS\x10\x04*7\n\nEgressMode\x12\x14\n\x10\x45GRESS_MODE_HTTP\x10\x00\x12\x13\n\x0f\x45GRESS_MODE_TCP\x10\x01*\\\n\x12ResponseInspection\x12 \n\x1cRESPONSE_INSPECTION_BUFFERED\x10\x00\x12$\n RESPONSE_INSPECTION_REQUEST_ONLY\x10\x01\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tsam.proto\x12\x06sam.v1\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"4\n\tAuthFrame\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x16\n\x0etarget_service\x18\x02 \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\"\xd6\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.\n\nevent_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\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\"\xf3\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\x19\n\x11\x63hallenge_unix_ms\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\"\xab\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/\n\x0b\x65xpire_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x91\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\x19\n\x11\x63hallenge_unix_ms\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\"\xfd\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/\n\x0b\x65xpire_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"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\"\xb2\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\x31\n\rannounce_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\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\"\xac\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\x19\n\x11\x63hallenge_unix_ms\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\"f\n\x13RouterLeaseResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12/\n\x0b\x65xpire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x9e\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_labels\x18\x05 \x03(\t\x12\x1f\n\x04http\x18\x06 \x03(\x0b\x32\x11.sam.v1.HTTPGrant\"<\n\tHTTPGrant\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x0f\n\x07methods\x18\x02 \x03(\t\x12\r\n\x05paths\x18\x03 \x03(\t\"\x8f\x02\n\x11\x45gressDestination\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ntarget_url\x18\x02 \x01(\t\x12\x12\n\ncredential\x18\x03 \x01(\t\x12\x11\n\tserved_by\x18\x04 \x03(\t\x12(\n\x06\x62roker\x18\x05 \x01(\x0b\x32\x18.sam.v1.CredentialBroker\x12&\n\ninspection\x18\x06 \x01(\x0b\x32\x12.sam.v1.Inspection\x12 \n\x04mode\x18\x07 \x01(\x0e\x32\x12.sam.v1.EgressMode\x12\r\n\x05ports\x18\x08 \x03(\r\x12\x15\n\rpreserve_host\x18\t \x01(\x08\x12\x17\n\x0f\x66orward_context\x18\n \x01(\x08\"3\n\nInspection\x12%\n\ninspectors\x18\x01 \x03(\x0b\x32\x11.sam.v1.Inspector\"c\n\tInspector\x12)\n\x0bmodel_armor\x18\x01 \x01(\x0b\x32\x12.sam.v1.ModelArmorH\x00\x12#\n\x08\x65xt_proc\x18\x02 \x01(\x0b\x32\x0f.sam.v1.ExtProcH\x00\x42\x06\n\x04kind\"\x8b\x01\n\nModelArmor\x12\x10\n\x08template\x18\x01 \x01(\t\x12,\n\x08response\x18\x02 \x01(\x0e\x32\x1a.sam.v1.ResponseInspection\x12\x11\n\tfail_open\x18\x03 \x01(\x08\x12*\n\x07timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\"\x82\x02\n\x07\x45xtProc\x12\x0e\n\x06target\x18\x01 \x01(\t\x12\n\n\x02\x63\x61\x18\x02 \x01(\t\x12\x1a\n\x12\x63lient_certificate\x18\x03 \x01(\t\x12\x36\n\x0fprocessing_mode\x18\x04 \x01(\x0b\x32\x1d.sam.v1.ExtProcProcessingMode\x12\x1b\n\x13\x61llow_mode_override\x18\x05 \x01(\x08\x12\x32\n\x0fmessage_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x1a\n\x12\x66\x61ilure_mode_allow\x18\x07 \x01(\x08\x12\x1a\n\x12max_buffered_bytes\x18\x08 \x01(\r\"\xdb\x04\n\x15\x45xtProcProcessingMode\x12\x45\n\x13request_header_mode\x18\x01 \x01(\x0e\x32(.sam.v1.ExtProcProcessingMode.HeaderMode\x12\x46\n\x14response_header_mode\x18\x02 \x01(\x0e\x32(.sam.v1.ExtProcProcessingMode.HeaderMode\x12\x41\n\x11request_body_mode\x18\x03 \x01(\x0e\x32&.sam.v1.ExtProcProcessingMode.BodyMode\x12\x42\n\x12response_body_mode\x18\x04 \x01(\x0e\x32&.sam.v1.ExtProcProcessingMode.BodyMode\x12\x46\n\x14request_trailer_mode\x18\x05 \x01(\x0e\x32(.sam.v1.ExtProcProcessingMode.HeaderMode\x12G\n\x15response_trailer_mode\x18\x06 \x01(\x0e\x32(.sam.v1.ExtProcProcessingMode.HeaderMode\"9\n\nHeaderMode\x12\x17\n\x13HEADER_MODE_DEFAULT\x10\x00\x12\x08\n\x04SEND\x10\x01\x12\x08\n\x04SKIP\x10\x02\"`\n\x08\x42odyMode\x12\x08\n\x04NONE\x10\x00\x12\x0c\n\x08STREAMED\x10\x01\x12\x0c\n\x08\x42UFFERED\x10\x02\x12\x14\n\x10\x42UFFERED_PARTIAL\x10\x03\x12\x18\n\x14\x46ULL_DUPLEX_STREAMED\x10\x04\"\xcf\x01\n\x10\x43redentialBroker\x12\x17\n\rstatic_secret\x18\x01 \x01(\tH\x00\x12\x31\n\x0foidc_federation\x18\x02 \x01(\x0b\x32\x16.sam.v1.OIDCFederationH\x00\x12\x30\n\x0f\x61ws_assume_role\x18\x03 \x01(\x0b\x32\x15.sam.v1.AWSAssumeRoleH\x00\x12\x35\n\x11platform_identity\x18\x04 \x01(\x0b\x32\x18.sam.v1.PlatformIdentityH\x00\x42\x06\n\x04kind\"_\n\x0eOIDCFederation\x12\x16\n\x0etoken_endpoint\x18\x01 \x01(\t\x12\x10\n\x08\x61udience\x18\x02 \x01(\t\x12\x13\n\x0bimpersonate\x18\x03 \x01(\t\x12\x0e\n\x06scopes\x18\x04 \x03(\t\"9\n\rAWSAssumeRole\x12\x10\n\x08role_arn\x18\x01 \x01(\t\x12\x16\n\x0esession_policy\x18\x02 \x01(\t\"\"\n\x10PlatformIdentity\x12\x0e\n\x06scopes\x18\x01 \x03(\t\".\n\rPolicyBinding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\t\"\x85\x01\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\x12)\n\x06\x65gress\x18\x03 \x03(\x0b\x32\x19.sam.v1.EgressDestination\"\x18\n\x16PolicyConfigGetRequest\"0\n\x17PolicyConfigGetResponse\x12\x15\n\rdatalog_rules\x18\x01 \x03(\t\"<\n\x1aPolicyConfigUpdateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"\x1a\n\x18\x45gressAssignmentsRequest\"F\n\x19\x45gressAssignmentsResponse\x12)\n\x06\x65gress\x18\x01 \x03(\x0b\x32\x19.sam.v1.EgressDestination\"f\n\x0cKeysResponse\x12\x13\n\x0bpublic_keys\x18\x01 \x03(\x0c\x12-\n\tsign_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\nsignatures\x18\x03 \x03(\x0c\"k\n\x13TokenRefreshRequest\x12\x1b\n\x13\x63hallenge_signature\x18\x01 \x01(\x0c\x12\x19\n\x11\x63hallenge_unix_ms\x18\x02 \x01(\x03\x12\x0f\n\x07peer_id\x18\x03 \x01(\t\x12\x0b\n\x03jwt\x18\x04 \x01(\t\"u\n\x14TokenRefreshResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12/\n\x0b\x65xpire_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\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\"\xe4\x01\n\x18IdentityEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x37\n\x13\x62iscuit_expire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x19\n\x11\x63ontrol_plane_url\x18\x04 \x01(\t\x12\"\n\x1atrusted_control_plane_keys\x18\x05 \x03(\x0c\x12.\n\ncheck_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\xc0\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/\n\x0b\x65xpire_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x16\n\x0erevocation_ids\x18\x07 \x03(\t\x12.\n\ncheck_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x80\x02\n\x10MemberCredential\x12\x19\n\x11\x63ontrol_plane_url\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12/\n\x0b\x65xpire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0ctrusted_keys\x18\x04 \x03(\x0b\x32\x19.sam.v1.TrustedSigningKey\x12\x19\n\x11issued_under_keys\x18\x05 \x03(\x0c\x12\x18\n\x10router_addresses\x18\x06 \x03(\t\x12)\n\x0coidc_session\x18\x07 \x01(\x0b\x32\x13.sam.v1.OIDCSession\"Y\n\x11TrustedSigningKey\x12\x12\n\npublic_key\x18\x01 \x01(\x0c\x12\x30\n\x0creceive_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"Y\n\x0bOIDCSession\x12\x0e\n\x06issuer\x18\x01 \x01(\t\x12\x11\n\tclient_id\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x15\n\rrefresh_token\x18\x04 \x01(\t\"\x8d\x01\n\x15TaskAuthorizationRule\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x1f\n\x05rules\x18\x03 \x03(\x0b\x32\x10.sam.v1.TaskRule\x12/\n\x0b\x65xpire_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"~\n\x08TaskRule\x12\x13\n\x0b\x64\x65scription\x18\x01 \x01(\t\x12\x18\n\x10\x61llowed_services\x18\x02 \x03(\t\x12(\n\toperation\x18\x03 \x01(\x0b\x32\x15.sam.v1.TaskOperation\x12\x19\n\x11\x61llowed_resources\x18\x04 \x03(\t\"s\n\rTaskOperation\x12\x15\n\rallowed_tools\x18\x01 \x03(\t\x12\x17\n\x0f\x61llowed_methods\x18\x02 \x03(\t\x12\x15\n\rallowed_paths\x18\x03 \x03(\t\x12\x1b\n\x13\x61llowed_permissions\x18\x04 \x03(\t\"\xa5\x01\n\x14TokenExchangeRequest\x12\x15\n\rsubject_token\x18\x01 \x01(\t\x12\x30\n\ttask_rule\x18\x02 \x01(\x0b\x32\x1d.sam.v1.TaskAuthorizationRule\x12\x0c\n\x04seal\x18\x03 \x01(\x08\x12\x19\n\x11\x63hallenge_unix_ms\x18\x04 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x05 \x01(\x0c\"\x7f\n\x15TokenExchangeResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12/\n\x0b\x65xpire_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\r\n\x05roles\x18\x03 \x03(\t\x12\x0f\n\x07subject\x18\x04 \x01(\t\"\x81\x01\n\x0fSTSTokenRequest\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x13\n\x0b\x64\x65stination\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x19\n\x11\x63hallenge_unix_ms\x18\x04 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x05 \x01(\x0c\"\x83\x01\n\x10STSTokenResponse\x12\x0b\n\x03jwt\x18\x01 \x01(\t\x12/\n\x0b\x65xpire_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07subject\x18\x03 \x01(\t\x12\r\n\x05roles\x18\x04 \x03(\t\x12\x11\n\ttask_name\x18\x05 \x01(\t\"F\n\x13RevocationsResponse\x12\x16\n\x0erevocation_ids\x18\x01 \x03(\t\x12\x17\n\x0f\x62\x61nned_peer_ids\x18\x02 \x03(\t*\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*\x8c\x01\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\x12\x17\n\x13SERVICE_TYPE_EGRESS\x10\x04*7\n\nEgressMode\x12\x14\n\x10\x45GRESS_MODE_HTTP\x10\x00\x12\x13\n\x0f\x45GRESS_MODE_TCP\x10\x01*\\\n\x12ResponseInspection\x12 \n\x1cRESPONSE_INSPECTION_BUFFERED\x10\x00\x12$\n RESPONSE_INSPECTION_REQUEST_ONLY\x10\x01\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sam_pb2', globals())
@@ -33,14 +33,14 @@ 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=7535
- _ENROLLMENTSTATUS._serialized_end=7683
- _SERVICETYPE._serialized_start=7686
- _SERVICETYPE._serialized_end=7826
- _EGRESSMODE._serialized_start=7828
- _EGRESSMODE._serialized_end=7883
- _RESPONSEINSPECTION._serialized_start=7885
- _RESPONSEINSPECTION._serialized_end=7977
+ _ENROLLMENTSTATUS._serialized_start=7548
+ _ENROLLMENTSTATUS._serialized_end=7696
+ _SERVICETYPE._serialized_start=7699
+ _SERVICETYPE._serialized_end=7839
+ _EGRESSMODE._serialized_start=7841
+ _EGRESSMODE._serialized_end=7896
+ _RESPONSEINSPECTION._serialized_start=7898
+ _RESPONSEINSPECTION._serialized_end=7990
_AUTHFRAME._serialized_start=86
_AUTHFRAME._serialized_end=138
_AUTHRESPONSE._serialized_start=140
@@ -126,41 +126,41 @@ if _descriptor._USE_C_DESCRIPTORS == False:
_KEYSRESPONSE._serialized_start=5042
_KEYSRESPONSE._serialized_end=5144
_TOKENREFRESHREQUEST._serialized_start=5146
- _TOKENREFRESHREQUEST._serialized_end=5240
- _TOKENREFRESHRESPONSE._serialized_start=5242
- _TOKENREFRESHRESPONSE._serialized_end=5359
- _NODECATALOGREPORT._serialized_start=5361
- _NODECATALOGREPORT._serialized_end=5419
- _TOKENREVOKEREQUEST._serialized_start=5421
- _TOKENREVOKEREQUEST._serialized_end=5458
- _TOKENREVOKERESPONSE._serialized_start=5460
- _TOKENREVOKERESPONSE._serialized_end=5513
- _IDENTITYEVIDENCERESPONSE._serialized_start=5516
- _IDENTITYEVIDENCERESPONSE._serialized_end=5744
- _PEEREVIDENCERESPONSE._serialized_start=5747
- _PEEREVIDENCERESPONSE._serialized_end=6067
+ _TOKENREFRESHREQUEST._serialized_end=5253
+ _TOKENREFRESHRESPONSE._serialized_start=5255
+ _TOKENREFRESHRESPONSE._serialized_end=5372
+ _NODECATALOGREPORT._serialized_start=5374
+ _NODECATALOGREPORT._serialized_end=5432
+ _TOKENREVOKEREQUEST._serialized_start=5434
+ _TOKENREVOKEREQUEST._serialized_end=5471
+ _TOKENREVOKERESPONSE._serialized_start=5473
+ _TOKENREVOKERESPONSE._serialized_end=5526
+ _IDENTITYEVIDENCERESPONSE._serialized_start=5529
+ _IDENTITYEVIDENCERESPONSE._serialized_end=5757
+ _PEEREVIDENCERESPONSE._serialized_start=5760
+ _PEEREVIDENCERESPONSE._serialized_end=6080
_PEEREVIDENCERESPONSE_LABELSENTRY._serialized_start=621
_PEEREVIDENCERESPONSE_LABELSENTRY._serialized_end=666
- _MEMBERCREDENTIAL._serialized_start=6070
- _MEMBERCREDENTIAL._serialized_end=6326
- _TRUSTEDSIGNINGKEY._serialized_start=6328
- _TRUSTEDSIGNINGKEY._serialized_end=6417
- _OIDCSESSION._serialized_start=6419
- _OIDCSESSION._serialized_end=6508
- _TASKAUTHORIZATIONRULE._serialized_start=6511
- _TASKAUTHORIZATIONRULE._serialized_end=6652
- _TASKRULE._serialized_start=6654
- _TASKRULE._serialized_end=6780
- _TASKOPERATION._serialized_start=6782
- _TASKOPERATION._serialized_end=6897
- _TOKENEXCHANGEREQUEST._serialized_start=6900
- _TOKENEXCHANGEREQUEST._serialized_end=7065
- _TOKENEXCHANGERESPONSE._serialized_start=7067
- _TOKENEXCHANGERESPONSE._serialized_end=7194
- _STSTOKENREQUEST._serialized_start=7197
- _STSTOKENREQUEST._serialized_end=7326
- _STSTOKENRESPONSE._serialized_start=7329
- _STSTOKENRESPONSE._serialized_end=7460
- _REVOCATIONSRESPONSE._serialized_start=7462
- _REVOCATIONSRESPONSE._serialized_end=7532
+ _MEMBERCREDENTIAL._serialized_start=6083
+ _MEMBERCREDENTIAL._serialized_end=6339
+ _TRUSTEDSIGNINGKEY._serialized_start=6341
+ _TRUSTEDSIGNINGKEY._serialized_end=6430
+ _OIDCSESSION._serialized_start=6432
+ _OIDCSESSION._serialized_end=6521
+ _TASKAUTHORIZATIONRULE._serialized_start=6524
+ _TASKAUTHORIZATIONRULE._serialized_end=6665
+ _TASKRULE._serialized_start=6667
+ _TASKRULE._serialized_end=6793
+ _TASKOPERATION._serialized_start=6795
+ _TASKOPERATION._serialized_end=6910
+ _TOKENEXCHANGEREQUEST._serialized_start=6913
+ _TOKENEXCHANGEREQUEST._serialized_end=7078
+ _TOKENEXCHANGERESPONSE._serialized_start=7080
+ _TOKENEXCHANGERESPONSE._serialized_end=7207
+ _STSTOKENREQUEST._serialized_start=7210
+ _STSTOKENREQUEST._serialized_end=7339
+ _STSTOKENRESPONSE._serialized_start=7342
+ _STSTOKENRESPONSE._serialized_end=7473
+ _REVOCATIONSRESPONSE._serialized_start=7475
+ _REVOCATIONSRESPONSE._serialized_end=7545
# @@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.pyi
index 3ca87b01..613bfc43 100644
--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi
+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi
@@ -652,14 +652,16 @@ class TokenExchangeResponse(_message.Message):
def __init__(self, biscuit_token: _Optional[bytes] = ..., expire_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., roles: _Optional[_Iterable[str]] = ..., subject: _Optional[str] = ...) -> None: ...
class TokenRefreshRequest(_message.Message):
- __slots__ = ["challenge_signature", "challenge_unix_ms", "peer_id"]
+ __slots__ = ["challenge_signature", "challenge_unix_ms", "jwt", "peer_id"]
CHALLENGE_SIGNATURE_FIELD_NUMBER: _ClassVar[int]
CHALLENGE_UNIX_MS_FIELD_NUMBER: _ClassVar[int]
+ JWT_FIELD_NUMBER: _ClassVar[int]
PEER_ID_FIELD_NUMBER: _ClassVar[int]
challenge_signature: bytes
challenge_unix_ms: int
+ jwt: str
peer_id: str
- def __init__(self, challenge_signature: _Optional[bytes] = ..., challenge_unix_ms: _Optional[int] = ..., peer_id: _Optional[str] = ...) -> None: ...
+ def __init__(self, challenge_signature: _Optional[bytes] = ..., challenge_unix_ms: _Optional[int] = ..., peer_id: _Optional[str] = ..., jwt: _Optional[str] = ...) -> None: ...
class TokenRefreshResponse(_message.Message):
__slots__ = ["biscuit_token", "error_message", "expire_time"]
diff --git a/sdk/python/src/agent_mesh/controlplane.py b/sdk/python/src/agent_mesh/controlplane.py
index b90d5b08..01ec5aa8 100644
--- a/sdk/python/src/agent_mesh/controlplane.py
+++ b/sdk/python/src/agent_mesh/controlplane.py
@@ -260,7 +260,7 @@ class ControlPlaneClient:
router_addresses=list(resp.router_addresses),
)
- def refresh(self, identity: Identity, biscuit: bytes) -> RefreshResult:
+ def refresh(self, identity: Identity, biscuit: bytes, *, jwt: Optional[str] = None) -> RefreshResult:
"""POST /refresh: trades the biscuit for a fresh one. The old one is
spent by this call; callers must persist the result before using it."""
ts = _now_ms()
@@ -268,6 +268,7 @@ class ControlPlaneClient:
challenge_unix_ms=ts,
challenge_signature=identity.sign(challenges.refresh_challenge(identity.peer_id, ts)),
peer_id=identity.peer_id,
+ jwt=jwt or "",
)
body = self._request(
"POST",
diff --git a/sdk/python/src/agent_mesh/mesh.py b/sdk/python/src/agent_mesh/mesh.py
index e6b975a1..bc5d6148 100644
--- a/sdk/python/src/agent_mesh/mesh.py
+++ b/sdk/python/src/agent_mesh/mesh.py
@@ -19,7 +19,7 @@ import threading
import time
from dataclasses import dataclass, field, replace
from pathlib import Path
-from typing import Mapping, Optional
+from typing import Callable, Mapping, Optional
from ._proto import sam_pb2 as pb
from .controlplane import ROLE_NODE, ControlPlaneClient, Enrollment, KeysNotTrustedError, Transport
@@ -31,6 +31,8 @@ _CREDENTIAL_FILE = "credential.json"
# A saved credential with less validity left than this is not worth resuming; enroll again instead.
_REUSE_MIN_TTL_SECONDS = 5 * 60
+JwtSource = Callable[[], str]
+
class CredentialRetiredError(Exception):
"""The saved credential was issued under a signing key the control plane
@@ -82,11 +84,19 @@ class AgentMesh:
minted for it, and the client that keeps that credential fresh. join()
puts it on the mesh over libp2p."""
- def __init__(self, identity: Identity, control_plane: ControlPlaneClient, credential: MeshCredential, state_dir: Optional[Path]):
+ def __init__(
+ self,
+ identity: Identity,
+ control_plane: ControlPlaneClient,
+ credential: MeshCredential,
+ state_dir: Optional[Path],
+ jwt_source: Optional[JwtSource] = None,
+ ):
self.identity = identity
self.control_plane = control_plane
self._credential = credential
self._state_dir = state_dir
+ self._jwt_source = jwt_source
# refresh() and sync_control_plane() run in worker threads of the
# session's loops; the control plane redeems only the last biscuit it
# issued, and both write the same state files.
@@ -115,7 +125,7 @@ class AgentMesh:
*,
bootstrap_token: Optional[str] = None,
bootstrap_token_path: Optional[str | os.PathLike[str]] = None,
- jwt: Optional[str] = None,
+ jwt: Optional[str | JwtSource] = None,
jwt_path: Optional[str | os.PathLike[str]] = None,
state_dir: Optional[str | os.PathLike[str]] = None,
identity: Optional[Identity] = None,
@@ -137,21 +147,22 @@ class AgentMesh:
verified or refreshed, so the member enrolls again with the token
given, or raises CredentialRetiredError without one. Otherwise exactly
one of bootstrap_token, bootstrap_token_path, jwt or jwt_path must be
- given; a token is better read from a file than passed as a value, and
- jwt_path also takes a platform's workload identity token, such as a
- Kubernetes projected service account token. Delete the state directory
- to enroll afresh, for instance with other labels."""
+ given; a token is better read from a file or a callback than passed as
+ a value, and jwt_path or a callable jwt also supplies a fresh workload
+ identity token on every refresh. Delete the state directory to enroll
+ afresh, for instance with other labels."""
state = Path(state_dir).expanduser() if state_dir is not None else None
saved = _load_identity(state)
identity = identity or saved or Identity.generate()
control_plane = ControlPlaneClient(control_plane_url, allow_insecure=allow_insecure, transport=transport)
+ jwt_source = _resolve_jwt_source(jwt=jwt, jwt_path=jwt_path)
given = sum(v is not None for v in (bootstrap_token, bootstrap_token_path, jwt, jwt_path))
if state is not None and saved is not None and saved.peer_id == identity.peer_id:
credential = _load_credential(state)
if credential is not None and credential.control_plane_url.rstrip("/") == control_plane.url.rstrip("/") and credential.time_to_live_seconds() > _REUSE_MIN_TTL_SECONDS:
resumed = _resumable_credential(control_plane, credential)
if resumed is not None:
- mesh = cls(identity, control_plane, resumed, state)
+ mesh = cls(identity, control_plane, resumed, state, jwt_source)
if resumed is not credential:
mesh.save()
return mesh
@@ -163,10 +174,8 @@ class AgentMesh:
enrollment: Enrollment
if jwt is not None or jwt_path is not None:
- if jwt_path is not None:
- jwt = Path(jwt_path).expanduser().read_text(encoding="utf-8").strip()
- assert jwt is not None
- enrollment = control_plane.register(identity, jwt, role=role, labels=labels)
+ token = jwt_source() if jwt_source is not None else str(jwt)
+ enrollment = control_plane.register(identity, token, role=role, labels=labels)
else:
if bootstrap_token_path is not None:
bootstrap_token = Path(bootstrap_token_path).expanduser().read_text().strip()
@@ -196,6 +205,7 @@ class AgentMesh:
router_addresses=list(enrollment.router_addresses),
),
state,
+ jwt_source,
)
mesh.save()
return mesh
@@ -206,6 +216,8 @@ class AgentMesh:
state_dir: str | os.PathLike[str],
*,
identity: Optional[Identity] = None,
+ jwt: Optional[JwtSource] = None,
+ jwt_path: Optional[str | os.PathLike[str]] = None,
allow_insecure: bool = False,
transport: Optional[Transport] = None,
) -> "AgentMesh":
@@ -220,14 +232,22 @@ class AgentMesh:
if credential is None:
raise FileNotFoundError(f"no credential in {state}; enroll first")
control_plane = ControlPlaneClient(credential.control_plane_url, allow_insecure=allow_insecure, transport=transport)
- return cls(identity, control_plane, credential, state)
+ return cls(identity, control_plane, credential, state, _resolve_jwt_source(jwt=jwt, jwt_path=jwt_path))
def refresh(self) -> MeshCredential:
"""Trades the current biscuit for a fresh one and persists it. The control
plane redeems only the last biscuit it issued, so a lost refresh result
means re-enrolling; persisting before returning keeps that rare."""
with self._lock:
- result = self.control_plane.refresh(self.identity, self._credential.biscuit)
+ fresh_jwt: Optional[str] = None
+ if self._jwt_source is not None:
+ try:
+ token = self._jwt_source()
+ if token:
+ fresh_jwt = token
+ except Exception: # noqa: BLE001 - fall back to session-only refresh if token source is unavailable
+ pass
+ result = self.control_plane.refresh(self.identity, self._credential.biscuit, jwt=fresh_jwt)
control_plane_keys = self._credential.control_plane_keys
try:
control_plane_keys = self.control_plane.keys(control_plane_keys)
@@ -342,3 +362,18 @@ def _write_atomic(path: Path, data: bytes) -> None:
with os.fdopen(fd, "wb") as f:
f.write(data)
os.replace(tmp, path)
+
+
+def _resolve_jwt_source(
+ *,
+ jwt: Optional[str | JwtSource],
+ jwt_path: Optional[str | os.PathLike[str]],
+) -> Optional[JwtSource]:
+ if jwt_path is not None:
+ path = Path(jwt_path).expanduser()
+ return lambda: path.read_text(encoding="utf-8").strip()
+ if callable(jwt):
+ fn = jwt
+ return lambda: fn().strip()
+ return None
+
diff --git a/sdk/python/tests/test_mesh.py b/sdk/python/tests/test_mesh.py
index 6f3c9e8d..0824125e 100644
--- a/sdk/python/tests/test_mesh.py
+++ b/sdk/python/tests/test_mesh.py
@@ -54,6 +54,7 @@ class FakeControlPlane:
self.strict_refresh = strict_refresh
self.refresh_delay = refresh_delay
self.last_biscuit = b""
+ self.last_refresh_jwt = ""
# What /keys serves and signs with; a test rotates by replacing it.
self.keys = [CP_KEY]
self._lock = threading.Lock()
@@ -90,11 +91,14 @@ class FakeControlPlane:
).SerializeToString()
if (method, path) == ("POST", "/refresh"):
time.sleep(self.refresh_delay)
+ refresh_req = pb.TokenRefreshRequest.FromString(body) if body else pb.TokenRefreshRequest()
with self._lock:
+ self.last_refresh_jwt = refresh_req.jwt
presented = base64.b64decode(headers["Authorization"].removeprefix("Bearer "))
if self.strict_refresh and presented != self.last_biscuit:
return 200, pb.TokenRefreshResponse(error_message="biscuit already redeemed").SerializeToString()
- biscuit = self._issue(f"biscuit-{self.issued + 1}".encode())
+ token_bytes = f"biscuit-for-{refresh_req.jwt}".encode() if refresh_req.jwt else f"biscuit-{self.issued + 1}".encode()
+ biscuit = self._issue(token_bytes)
return 200, pb.TokenRefreshResponse(biscuit_token=biscuit, expire_time=_ts_s(int(time.time()) + 7200)).SerializeToString()
if (method, path) == ("GET", "/keys"):
return (200, self._signed_keys().SerializeToString()) if self.keys_ok else (500, b"boom")
@@ -246,16 +250,46 @@ def test_enroll_refuses_ambiguous_credentials():
assert cp.issued == 0
-def test_enroll_reads_a_workload_identity_token_from_jwt_path(tmp_path):
+def test_enroll_reads_a_workload_identity_token_from_jwt_path_and_refresh(tmp_path):
cp = FakeControlPlane()
token = tmp_path / "token"
- token.write_text("eyJ.projected.token\n")
+ token.write_text("eyJ.projected.token.1\n")
mesh = AgentMesh.enroll("http://127.0.0.1:1", jwt_path=token, transport=cp.transport)
- assert mesh.credential.biscuit == b"biscuit-for-eyJ.projected.token"
+ assert mesh.credential.biscuit == b"biscuit-for-eyJ.projected.token.1"
+
+ token.write_text("eyJ.projected.token.2\n")
+ mesh.refresh()
+ assert cp.last_refresh_jwt == "eyJ.projected.token.2"
+ assert mesh.credential.biscuit == b"biscuit-for-eyJ.projected.token.2"
+
with pytest.raises(FileNotFoundError):
AgentMesh.enroll("http://127.0.0.1:1", jwt_path=tmp_path / "missing", transport=cp.transport)
+def test_enroll_accepts_callable_jwt_and_invokes_on_refresh():
+ cp = FakeControlPlane()
+ seq = 0
+ should_fail = False
+
+ def fetch_jwt() -> str:
+ nonlocal seq
+ if should_fail:
+ raise RuntimeError("metadata server unavailable")
+ seq += 1
+ return f" eyJ.callback.{seq} \n"
+
+ mesh = AgentMesh.enroll("http://127.0.0.1:1", jwt=fetch_jwt, transport=cp.transport)
+ assert mesh.credential.biscuit == b"biscuit-for-eyJ.callback.1"
+
+ mesh.refresh()
+ assert cp.last_refresh_jwt == "eyJ.callback.2"
+ assert mesh.credential.biscuit == b"biscuit-for-eyJ.callback.2"
+
+ should_fail = True
+ mesh.refresh()
+ assert cp.last_refresh_jwt == ""
+
+
def test_load_without_identity_says_enroll_first(tmp_path):
with pytest.raises(FileNotFoundError, match="no identity"):
AgentMesh.load(tmp_path)
diff --git a/site/content/docs/concepts/identity.md b/site/content/docs/concepts/identity.md
index 4e374482..b3012ba9 100644
--- a/site/content/docs/concepts/identity.md
+++ b/site/content/docs/concepts/identity.md
@@ -43,10 +43,16 @@ challenge. This is how a person enrolls a laptop.
**Non-interactive OIDC.** A workload that already has an OIDC token does not
need a login. `sam-node run --jwt-path <file>` enrolls with the token in that
-file. On Kubernetes this is a projected service account token with the
-audience the control plane expects. `--client-id` and `--client-secret-path`
-do the same with an OAuth client-credentials grant. Routers enroll in the
-same way with `sam-router --jwt-path`.
+file (such as a Kubernetes projected service account token or a SPIRE
+JWT-SVID written by `spiffe-helper`). On GCE and Cloud Run,
+`sam-node run --cloud-provider gcp` (or `auto`) fetches an identity token
+directly from the instance metadata server. `--client-id` and
+`--client-secret-path` do the same with an OAuth client-credentials grant.
+Routers enroll in the same way with `sam-router --jwt-path`. The control
+plane marks workload issuers with `--workload-issuer` (`<issuer>` or
+`<issuer>=<email-suffix>`) so workload tokens can enroll, refresh, and
+exchange credentials while being refused at human operator endpoints
+(`/user/*`, `/oauth/authorize`).
**Bootstrap token.** An operator mints a token with the admin API, the
console, or `sam-one token create`, and copies it to the machine. The node
@@ -171,15 +177,19 @@ OIDC token's expiry if sooner). Delegated Session Biscuits default to 1 hour
(bounded by the subject JWT's expiry and any `TaskAuthorizationRule.expire_time`).
Nodes and routers check their Member Biscuit every ten minutes, and when less
than a fifth of the lifetime remains they call `POST /refresh` with the
-current token and a signature over a fresh challenge. The control plane
-verifies both, resolves the identity's roles against the current policy again,
-and mints a new token with the same identity facts and labels.
-
-Refresh is limited by the **session**, which is a record on the control
-plane, not a field in the token. The session of an OIDC enrollment lasts
-`--oidc-session-ttl`, 90 days by default. After that, the node has to log in
-again. A bootstrap enrollment has no session expiry. A ban also acts on the
-session record.
+current token and a signature over a fresh challenge. When the member has a
+live platform token source (`--jwt-path`, `--cloud-provider`, `--client-id`,
+or an SDK `jwtPath` / `jwt` callback), it also sends a fresh platform JWT in
+`TokenRefreshRequest.jwt`: the control plane verifies that `iss|sub` matches
+the enrolled node record, refreshes the stored claims and session in place,
+and re-resolves the identity's roles against the current policy.
+
+Refresh without a fresh platform JWT is bounded by the **session**, which is
+a record on the control plane, not a field in the token. A human OIDC session
+lasts `--oidc-session-ttl` (90 days by default), and a workload OIDC session
+(`--workload-issuer`) lasts `--workload-session-ttl` (48 hours by default). A
+bootstrap enrollment has no session expiry. A ban also acts on the session
+record.
A node that enrolled interactively with `--offline-access` also keeps an OIDC
refresh token. If its credential expires completely, it uses the refresh
diff --git a/site/content/docs/contributing/_index.md b/site/content/docs/contributing/_index.md
index 2a7e23b2..ba603af3 100644
--- a/site/content/docs/contributing/_index.md
+++ b/site/content/docs/contributing/_index.md
@@ -32,6 +32,8 @@ only through `api/sam.proto` (protobuf for anything a mesh component speaks,
protojson of the same messages for the operator API). And no new module may be
added to `go.mod` without discussion. Conformance harnesses with external gRPC
dependencies such as `tests/extproc/` live in their own module for that reason.
+For the security model, token invariants, and scope boundaries of the mesh, see
+[Security Architecture & Posture](security-architecture/).
## Build
diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.md
new file mode 100644
index 00000000..f18c6c67
--- /dev/null
+++ b/site/content/docs/contributing/security-architecture.md
@@ -0,0 +1,590 @@
+---
+title: "Security architecture"
+linkTitle: "Security architecture"
+weight: 2
+aliases:
+ - /docs/development/security-architecture/
+ - /docs/development/sts/
+---
+
+This document describes the security architecture and posture of SAM for
+developers and security reviewers. It covers how SAM acts as an authority,
+Policy Decision Point (PDP), and task-scoped credential layer across
+environments, what problems it solves, what responsibilities remain with the
+surrounding platform, how its cryptographic and policy mechanisms work across
+`sam-control-plane`, `sam-node`, `sam-router`, and the native SDKs, and which
+extensions are deferred on purpose.
+
+---
+
+## 1. Current security posture: a courier network for tasks
+
+![The Agent Mesh as a courier network](/images/agent-mesh-courier.svg)
+
+SAM moves tasks between environments that trust nothing on arrival, the way a
+courier network moves parcels between post offices:
+
+| In the picture | In SAM |
+| :--- | :--- |
+| **Parcel** | One request: an MCP tool call, a chat completion, a BigQuery query, an A2A message. |
+| **Sender** | The agent wherever it runs: a developer laptop, Kubernetes on premises or in a cloud, a SaaS platform, or a sandbox runtime. |
+| **Local post office** | The `sam-node` next to the agent, or the native SDK (`@sam-mesh/sdk`, `sam-mesh`) inside its process. It checks the sender's platform identity (projected service account token, GCE/Cloud Run metadata token, SPIFFE JWT-SVID, OIDC login) and obtains the waybill from the Registry. |
+| **Your gateway** | Istio, `agentgateway`, Envoy AI Gateway, or `kgateway` where a cluster already runs one. It stays in the data path and asks the `sam-node` office over Envoy `ext_proc`, `ext_authz`, or RFC 8693 `/oauth/token`; the office issues the waybill, the gateway carries. |
+| **Waybill** | The SAM Biscuit credential: who the sender (subject) is, through which office (`actor_node`) it travels, what standing roles it holds, and when it expires. |
+| **Mandate** | An offline attenuation block (`tar_block`) appended at a task or sub-agent hop. It can only restrict; a sub-agent's parcel carries one mandate more than its parent's. |
+| **Sealed bag** | The mutually authenticated, encrypted libp2p stream between two offices. Routers relay ciphertext across NAT, clusters, sites, and clouds and cannot open it. |
+| **Registry** | `sam-control-plane`: verifies senders, stamps waybills (`POST /register`, `POST /enroll`, `POST /token/exchange`), distributes Datalog policy (`GET /policies`), issues the permits foreign borders recognize (`POST /sts/token`, `/.well-known/openid-configuration`, `/jwks`), and keeps the receipts. It never touches a parcel. |
+| **Destination office** | The serving or egress `sam-node` for `mcp://`, `inference://`, `a2a://`, or `egress://`: verifies the waybill and every mandate again, runs customs, obtains the permit, and delivers. The operator chooses where it runs, hence from which network or jurisdiction traffic leaves. |
+| **Customs** | Content inspection at the destination office: built-in policy facts, Google Cloud Model Armor, and Envoy `ext_proc` processors. |
+| **Permit** | The destination credential: a federated cloud token exchanged from the Registry's ES256 JWT for this sender and task, or a secret from the office vault. The agent never holds it. |
+| **Receipts** | Structured audit logs at the Registry, at both offices, and at the cloud destination, joined by principal and `sam_task`. |
+
+---
+
+## 2. What problems SAM solves
+
+In traditional cloud and service-mesh architectures, permissions are granted
+ambiently to a workload identity (a Kubernetes Service Account, a cloud service
+account, or a SPIFFE SVID `spiffe://...`). Workload identity authenticates the
+caller, but AI agents need finer boundaries across five dimensions:
+
+1. A single agent service (such as a BigQuery analytics agent, a coding
+ orchestrator, or a customer support assistant) executes many concurrent or
+ sequential sessions with different least-privilege boundaries (for example,
+ read-only access to `dataset_A` in task 1 versus schema updates on
+ `dataset_B` in task 2). Workload identity proves which container is calling,
+ while task authorization bounds what this specific request may do.
+2. If an agent session exercises the full standing privileges of its user or
+ workload identity, a prompt injection during a narrow task can access or
+ mutate unrelated tools, models, or datasets. Narrowing each task credential
+ before the task runs contains confused-deputy and prompt-injection blast
+ radius.
+3. When a parent agent delegates a narrower sub-task to a child agent, it
+ attenuates its credential offline (`Token_2 = Attenuate(Token_1, TaskRule)`)
+ without round-tripping to the identity provider or minting new cloud service
+ accounts on every hop.
+4. An agent running on premises, on a laptop, or inside a sandbox calls cloud
+ APIs (BigQuery, Vertex AI, S3, third-party MCP servers) without any static
+ cloud key or ambient cloud service account inside that environment, and the
+ cloud audit log records the actual user or workload principal rather than a
+ shared node service account.
+5. Agents and tools run across laptops, on-premises clusters, and multiple
+ clouds behind NATs and firewalls. SAM routes and authorizes every call on the
+ service name (`mcp://`, `inference://`, `a2a://`, `egress://`), never on an
+ IP address.
+
+### Two-layer identity and authorization model
+
+SAM separates caller attestation from task authorization:
+
+| Layer | Question answered | Primitive | Role in SAM |
+| :--- | :--- | :--- | :--- |
+| **1. Workload / Subject & Channel Attestation** | *"Which workload or user initiated this request, and through which node is it travelling?"* | **OIDC ID tokens**, **Kubernetes projected SA JWTs**, **GCE/Cloud Run identity tokens**, **SPIFFE JWT-SVIDs**, or **Istio XFCC**. | Verified at `POST /register` (node enrollment) or `POST /token/exchange` (caller delegation) to mint a Biscuit bound to the transport channel (`client_peer_id`, `actor_node`). |
+| **2. Task / Session Authorization (TAR)** | *"What subset of standing permissions may this specific task or sub-agent hop exercise right now?"* | **SAM Task Biscuit** (Block 0 Authority + appended `tar_block` blocks carrying `api.TaskAuthorizationRule`). | Attenuated offline across hops, enforced at every SAM Policy Enforcement Point (PEP), and translated into downscoped upstream cloud credentials by `CloudTokenExchanger` at egress. |
+
+---
+
+## 3. What SAM does not solve
+
+SAM leaves several responsibilities to the surrounding platform.
+
+### 3.1 OS, kernel, and container sandboxing
+
+Confinement of the operating system, filesystem, and guest network namespace
+belongs to the sandbox platform: NVIDIA OpenShell (Landlock, seccomp, network
+namespaces, and its external secret-injecting proxy), Docker Sandbox
+(`docker sbx`), or Kubernetes `agent-sandbox` (`RuntimeClass: gvisor` or `kata`
+paired with a Kubernetes `NetworkPolicy`).
+
+SAM provides the cryptographic task authority that those sandboxes consume:
+control-plane-signed Delegated Session Biscuits (`POST /token/exchange`) and
+sealed offline task attenuations (`tar_block` + `Seal()`).
+
+### 3.2 Replacing an existing cluster gateway
+
+Where a cluster already runs `agentgateway`, Istio, Envoy AI Gateway, or
+`kgateway`, that proxy stays in place. Cluster gateways validate flat JWTs and
+route local traffic, while `sam-node` plugs into them over Envoy `ext_authz`,
+Envoy `ext_proc`, and RFC 8693 `/oauth/token` to add offline multi-hop task
+attenuation, cross-network peer-to-peer routing, and cloud credential
+brokering.
+
+### 3.3 Using SPIFFE X509-SVID keys as libp2p member keys
+
+Every mesh member (`sam-node`, `sam-router`, and native SDK peers) generates and
+persists its own Ed25519 libp2p key pair. The peer ID derived from that key is
+the primary key of the enrollment record, the value of `node()` and
+`client_peer_id()`, the member in `node:<peer_id>` bindings, the holder of
+router leases and discovery announcements, and the suffix of `/p2p/<peer_id>`
+addresses.
+
+SAM never uses an X509-SVID private key from the SPIFFE Workload API as the
+libp2p key:
+
+| Property | SVID key as the libp2p key | SAM design |
+| :--- | :--- | :--- |
+| **Algorithm** | SPIRE issues EC P-256 or RSA keys, not Ed25519. The TypeScript/Python SDKs, mobile FFI, and portable `MemberCredential` state directories are Ed25519-only. | Ed25519 for every member. |
+| **Rotation** | SPIRE rotates X509-SVIDs with a fresh key pair (every 30 minutes by default) and accepts no CSR on the Workload API. Every rotation would change the peer ID, drop active streams, and break `node:<peer_id>` bindings. | The Ed25519 key is stable for the life of the enrollment; the Biscuit is the rotating credential (`POST /refresh`). |
+| **Transport** | The libp2p TLS handshake requires a self-signed certificate carrying the libp2p host-key extension, which an enterprise SVID cannot carry. | Noise or libp2p TLS with the member's Ed25519 key. |
+| **Attestation** | A key copied out of an SVID attests nothing to the control plane without an enrollment step. | Enrollment (`POST /register`) uses a platform OIDC token or SPIFFE JWT-SVID as attestation evidence for the member's Ed25519 key. |
+
+### 3.4 Fine-grained cloud IAM where the cloud provider has no per-task API
+
+Where each layer enforces depends on what the destination cloud API supports:
+
+| Destination class | Border credential | Per-task narrowing enforced today | Residual boundary |
+| :--- | :--- | :--- | :--- |
+| **Google Cloud APIs** (BigQuery, Vertex AI, Cloud Storage) | Control-plane ES256 JWT federated via Workload or Workforce Identity Pool (`oidc_federation`), optional SA impersonation with narrowed `scopes` | Mesh PEP on host, HTTP method, and REST path (BigQuery REST paths carry project, dataset, and table; Vertex paths carry the model); OAuth scopes; CEL attribute conditions on `act.sub`; `principalSet` bindings on `google.groups` (`sam_roles`); Credential Access Boundaries for Cloud Storage. | A body-level reference inside an allowed REST path (for example, a SQL string in BigQuery `jobs.insert` referencing a second table) is bounded by the federated principal's standing IAM ceiling until a public Google per-task token API exists. |
+| **AWS** (`aws_assume_role`) | Control-plane ES256 JWT via `AssumeRoleWithWebIdentity` | Inline AWS session policy compiled from the intersected `TaskAuthorizationRule` chain (`allowed_permissions` $\rightarrow$ `Action`, `allowed_resources` $\rightarrow$ `Resource`) intersected with the role's standing IAM policy. | AWS 1-hour role-chaining limit (sub-agent hops re-assume from the egress node rather than chaining AWS STS credentials) and packed session policy size limit. |
+| **API-key services** (Gemini Developer API, OpenAI, Anthropic, GitHub PATs) | `static_secret` from the egress node's `--secrets-dir` | Mesh PEP on service name, HTTP method, REST path (model name), MCP tool name, and task TTL. | Static API keys cannot be downscoped at the upstream provider; the egress node never exposes the key to the caller. |
+| **External agents (`a2a://`) & third-party MCP servers** | Control-plane JWT if the party federates with the SAM OIDC issuer; otherwise `static_secret` | Mesh PEP plus whatever scope/claim checks the remote authorization server enforces. | Depends on the remote party's authorization server. |
+
+### 3.5 Non-HTTP protocols without TLS SNI
+
+SAM terminates and inspects HTTP/1.1 and HTTP/2 (REST, JSON-RPC MCP, A2A, SSE)
+and supports raw TCP carrying TLS (PostgreSQL, Cloud SQL, AlloyDB, Redis, SSH)
+via named `CONNECT` tunnels (`EGRESS_MODE_TCP`). It does not proxy raw UDP,
+QUIC/HTTP/3, ICMP, or raw IP frames, and it does not inject brokered credentials
+into opaque TCP tunnels. For TCP tunnels, the client authenticates end-to-end
+over the spliced TLS stream while the egress node enforces the `ports`
+allow-list and TLS `ClientHello` SNI match.
+
+---
+
+## 4. How SAM solves it
+
+### 4.1 Platform attestation, binding wildcards, and workload containment
+
+#### Node attestation sources (`TokenSource`)
+
+`sam-node` and `sam-router` consolidate headless enrollment and continuous
+refresh re-attestation behind the
+[`TokenSource`](https://github.com/google/sam/blob/main/internal/controlplane/client/tokensource.go)
+interface (`FetchToken(ctx)`):
+
+| Environment | Token source | How it works |
+| :--- | :--- | :--- |
+| **Kubernetes** | `--jwt-path` (`FileTokenSource`) | Reads a projected service account token (`aud` = control plane audience), rotated by kubelet, at enrollment and on every `POST /refresh`. |
+| **GCE VMs & Cloud Run** | `--cloud-provider=gcp\|auto` (`GCPMetadataTokenSource`) | Queries `http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=<aud>&format=full` with `Metadata-Flavor: Google` at enrollment and on every `POST /refresh`. |
+| **VMs & bare metal with SPIRE** (or multi-cluster SPIFFE) | `--jwt-path` + `spiffe-helper` (`FileTokenSource`) | `spiffe-helper` fetches a JWT-SVID from the SPIFFE Workload API and rotates the file on disk; `sub` is `spiffe://<trust-domain>/<path>`. |
+| **OAuth 2.0 service clients** | `--oidc-issuer` + `--client-id` + `--client-secret-path` (`ClientCredentialsTokenSource`) | Runs an OAuth client-credentials grant at enrollment and on every `POST /refresh`. |
+| **TypeScript & Python SDKs** | `jwtPath` / `jwt_path` or `jwt` callback (`JwtSource`) | Re-reads the file or invokes `jwt: () => string \| Promise<string>` / `Callable[[], str]` at enrollment and on every `refresh()`. |
+
+An interactive human login with `--join --offline-access`
+(`RefreshTokenSource`) also implements `TokenSource`, but `ResolveTokenSource`
+marks it `continuous=false`: the stored OIDC refresh token is not redeemed on
+routine `POST /refresh` calls and is used only when `/refresh` fails and the
+node falls back to re-enrollment.
+
+#### Prefix and suffix wildcards in `PolicyBinding.members`
+
+Claim-backed binding members (`user:`, `email:`, `group:`, `idp_role:`) accept
+either an exact value, a single trailing `*` (`$v.starts_with("<prefix>")`), or
+a single leading `*` (`$v.ends_with("<suffix>")`), evaluated identically in
+control-plane role resolution (`resolveRoles`) and node-side Datalog generation
+(`api.BuildPolicyRules`):
+
+- `user:system:serviceaccount:sam-nodes:*` matches any service account in
+ namespace `sam-nodes`.
+- `user:spiffe://acme.example/ns/prod/*` matches any SPIFFE workload under that
+ path prefix.
+- `email:*@my-project.iam.gserviceaccount.com` matches any Google Cloud service
+ account in `my-project`.
+
+To prevent accidental open bindings and Datalog rule injection:
+
+- Bare `<prefix>:*` (such as `user:*` or `email:*`) is rejected as a disguised
+ `sam:system:authenticated`.
+- Interior wildcards (`a*b`) and wildcards on `node:<peer_id>` are rejected.
+- `ValidateBindingMember` and `ValidateRoleName` reject `"`, `\`, and control
+ characters while permitting spaces, `;`, and UTF-8 (such as
+ `group:Engineering Team`). `BuildPolicyRules` never skips exact members on
+ charset grounds and quotes wildcard string literals with `strconv.Quote`.
+
+#### Workload issuer containment (`--workload-issuer`)
+
+Without separation between human and workload OIDC tokens, any workload token
+from a trusted `--issuer` could call `/user/bootstrap-tokens` and mint
+`sam:role:node` bootstrap tokens.
+
+`--workload-issuer` (a subset of `--issuer`, automatically added to the OIDC
+verifier pool) classifies tokens as workload identities:
+
+- A bare `<issuer>` entry marks every token from that issuer (for example, a
+ Kubernetes cluster issuer or SPIRE OIDC Discovery Provider) as a workload.
+- An `<issuer>=<email-suffix>` entry (such as
+ `https://accounts.google.com=.gserviceaccount.com`) marks tokens from a shared
+ issuer whose `email` ends with that suffix as workloads. GCE VM metadata
+ tokens requested with `format=full` also carry a `google.compute_engine` claim
+ that is classified automatically as a workload; Cloud Run metadata tokens do
+ not carry `google.compute_engine` and therefore require the
+ `https://accounts.google.com=.gserviceaccount.com` suffix form.
+- Workload tokens are accepted at `POST /register`, `POST /refresh`, and
+ `POST /token/exchange`, and refused with `403 Forbidden` at `/user/*` and
+ `/oauth/authorize`.
+
+#### Continuous attestation on `POST /refresh` and `--workload-session-ttl`
+
+When `sam-node`, `sam-router`, or an SDK member has a continuous token source,
+it includes a fresh platform JWT in `TokenRefreshRequest.jwt` on every Biscuit
+refresh:
+
+- `HandleRefresh` verifies the JWT against the OIDC verifier pool, confirms
+ that `oidcIdentityKey` (`iss|sub`) matches the enrolled node record, updates
+ `ClaimsJSON` and the session `ExpiresAt` in place, and re-resolves the node's
+ roles against the current policy.
+- `--workload-session-ttl` defaults to `48h` (compared with `2160h` / 90 days
+ for human `--oidc-session-ttl`), giving the node a bounded window to survive
+ transient metadata or token-file errors before its session expires if no
+ fresh JWT is presented.
+
+---
+
+### 4.2 Safe Biscuit attenuation (`tar_block`) and single-pass verification
+
+In `biscuit-go`, `datalog.WithMaxFacts` and `datalog.WithMaxIterations` bound
+rule evaluation, not `check if` queries: a holder-authored block with 0 rules
+and a multi-variable cross-join check (`check if a($x), b($y), c($z)`) can
+trigger exponential backtracking inside `check.Run()`. Furthermore, if an
+appended block carried both Datalog checks and a serialized protobuf, a
+malicious holder could craft a token where the Datalog check passes at the mesh
+PEP while a broader protobuf is forwarded to `CloudTokenExchanger`.
+
+SAM never evaluates holder-authored Datalog rules or checks.
+
+Every appended block (`block_idx >= 1`) contains `0` Datalog rules, `0` Datalog
+checks, and `1` Datalog fact of the form
+`tar_block("<unpadded-base64url-serialized api.TaskAuthorizationRule>")`.
+
+Before constructing a Datalog authorizer, `UnmarshalInbound` in Go
+(`biscuit-go`), TypeScript (`@biscuit-auth/biscuit-wasm`), and Python
+(`biscuit_auth`) inspects blocks `1..k` and enforces identical bounds:
+
+- `MaxAttenuationBlocks = 8`
+- `MaxTARBytes = 4096` (serialized protobuf bytes per block)
+- `MaxRulesPerTAR = 16`
+- `MaxEntriesPerTARList = 64` (per `allowed_services`, `allowed_tools`,
+ `allowed_methods`, `allowed_paths`, `allowed_permissions`,
+ `allowed_resources`)
+- `MaxTARNameLength = 128` (printable ASCII)
+- Single-line fact syntax matching `^tar_block\("([A-Za-z0-9_-]+)"\);?\s*$`
+
+The verifier decodes the `[]*api.TaskAuthorizationRule` chain in a single pass
+and evaluates it in host code alongside Block 0's Datalog policy. Within a
+single `TaskAuthorizationRule`, a request matches if it satisfies at least one
+`TaskRule` (an empty `rules` list denies everything). Across blocks `1..k`,
+semantics are strict intersection (logical AND): the request must satisfy
+Block 0 Datalog RBAC, arrive before every block's `expire_time`, and match at
+least one `TaskRule` in every appended block.
+
+#### Per-service-type PEP matching semantics
+
+| Service type | `allowed_services` | `operation.allowed_tools` | `operation.allowed_methods` & `allowed_paths` | `operation.allowed_permissions` & `allowed_resources` |
+| :--- | :--- | :--- | :--- | :--- |
+| **`mcp://<name>`** | Enforced on stream handshake & HTTP | Enforced on `tools/call` (`params.name`). At stream open (`initialize`, `tools/list`), tool name is not yet present so `allowed_tools` does not block opening the stream. | Enforced if the rule sets `allowed_methods` or `allowed_paths` (a raw libp2p stream has no HTTP facts, so HTTP constraints deny raw streams). | Ignored by wire PEP (consumed by `CloudTokenExchanger`). |
+| **`inference://<name>`**, **`a2a://<name>`** | Enforced on HTTP request | A rule with non-empty `allowed_tools` requires an MCP tool name and does not match plain HTTP requests. | Enforced against request `Method` and `Path` when non-empty. | Ignored by wire PEP. |
+| **`egress://<name>`** | Enforced on HTTP request & TCP `CONNECT` | Must be empty for an HTTP or TCP rule to match. | Enforced against `Method` and `Path` when non-empty (a TCP `CONNECT` tunnel has `Method: "CONNECT"` and `Path: ""`, so any rule with `allowed_paths` denies a tunnel). | Intersected across blocks `1..k` and translated by `CloudTokenExchanger` at egress. |
+| **`system://<name>`** | Enforced on stream handshake | Enforced when a tool call is made. | Same as `mcp://`. | Ignored by wire PEP. |
+
+---
+
+### 4.3 Subject vs. actor (`actor_node`), stateless exchange, and revocation
+
+When a `sam-node` exchanges a caller's platform token on their behalf, the
+resulting Biscuit separates the node that owns the transport channel
+(`actor_node`) from the subject whose identity is being exercised (`user`,
+`email`, `role`), matching RFC 8693 (`sub` vs. `act`).
+
+A Member Biscuit (`POST /register`, `POST /enroll`, `POST /refresh`) is minted
+for an infrastructure node, router, or native SDK member and carries
+`node("<peer_id>")`, `client_peer_id("<peer_id>")`, `user("<subject>")`,
+`role("<role>")`, and `expiration(<time>)`.
+
+A Delegated Session Biscuit (`POST /token/exchange`, `POST /oauth/token`) is
+minted statelessly on the control plane with zero database writes:
+
+- `client_peer_id("<origin_node_peer_id>")` binds the token to the origin
+ node's libp2p connection (`check if client_peer_id($id), connection_peer_id($id)`),
+ so an exfiltrated token cannot be replayed from another peer.
+- `actor_node("<origin_node_peer_id>")` records the acting node for audit logs,
+ `act.sub` in outbound border JWTs, and `ext_proc` attributes. No policy rule
+ grants permissions on `actor_node`.
+- `user(...)`, `email(...)`, `group(...)`, `idp_role(...)`, and `role(...)` are
+ resolved strictly from the caller's `subject_token`.
+- No `node()` fact is minted, which prevents `node:<peer_id>` policy bindings on
+ the origin node from leaking to the delegated caller.
+
+Before handing a task token to an untrusted leaf process or sandbox, the holder
+calls `Seal()`, discarding the ephemeral next-block key so no further blocks can
+be appended.
+
+Revocation operates at two levels. Root-prefix revocation (`GET /revocations`)
+uses `b.RevocationIds()[0]` to identify the authority block, so revoking a root
+token or banning a peer or user at the control plane invalidates both the root
+Biscuit and every offline-attenuated child derived from it across the mesh.
+Local task revocation (`POST /oauth/revoke`) lets an orchestrator revoke a
+specific child Task Biscuit at the local `sam-node` as soon as a task finishes,
+caching `RevocationIds()[last]` in the node's revocation LRU until the token's
+`expire_time`.
+
+---
+
+### 4.4 Two-token model: the control plane as OIDC issuer
+
+Inside the mesh, credentials are Biscuits; at both external borders,
+credentials are standard JWTs. For the outbound border, `sam-control-plane` acts
+as a standard OIDC issuer:
+
+| Element | Implementation |
+| :--- | :--- |
+| **Signing key** | **ES256** (P-256 ECDSA), rotated with overlap and `kid` (`internal/controlplane/sts.go`). Google Cloud and AWS STS accept RS256 and ES256, not Ed25519; Ed25519 remains the Biscuit authority key. |
+| **Discovery & JWKS** | `GET /.well-known/openid-configuration` and `GET /jwks` on the control plane. For air-gapped or private control planes, the JWKS can be uploaded directly to the cloud workload identity pool. |
+| **Mint endpoint** | `POST /sts/token` (protobuf over HTTP): accepts the caller's Biscuit and `destination` name, verifies the Biscuit and the full `tar_block` chain against `egress://<destination>`, writes a `Border Crossing` audit log, and returns a short-lived ES256 JWT. |
+| **JWT claims** | `iss` = control plane URL; `sub` = caller principal (`email` or `issuer#subject`); `act` = `{"sub": "<egress_node_peer_id>"}`; `aud` = destination audience from `EgressDestination` (one audience per destination); `sam_roles` = authority-block roles (mapped to `google.groups` for `principalSet` bindings); `sam_task` = innermost `TaskAuthorizationRule.name` (audit-only). |
+| **TAR narrows, never selects** | Nothing in a holder-appended `tar_block` can select a broker, role ARN, service account, or audience; every claim that cloud IAM binds on (`sub`, `sam_roles`, `act.sub`, `aud`) comes from Block 0 or the control plane's `EgressDestination` policy. |
+| **Caching** | The egress node caches minted border JWTs and upstream cloud tokens by Biscuit SHA-256 digest, keeping the control plane off the per-request hot path. |
+
+---
+
+### 4.5 Proof of possession across the three surfaces
+
+| Surface | Mechanism | What it binds | Replay defense |
+| :--- | :--- | :--- | :--- |
+| **libp2p data path** (node-to-node, node-to-router) | Channel binding: Block 0 `client_peer_id` must equal the `connection_peer_id` authenticated by the libp2p Noise or TLS handshake. | The transport private key | None needed; the token is unusable on any other connection. |
+| **Control plane mesh protocol** (`/enroll`, `/enroll/status`, `/register`, `/refresh`, `/routers/lease`, `/token/exchange`, `/sts/token`) | Ed25519 signature over `sam:<endpoint>:<peer_id>:<challenge_unix_ms>`, carried in protobuf fields (`challenge_unix_ms`, `challenge_signature`) or `X-Sam-Challenge-Ts` / `X-Sam-Challenge-Sig` on `GET /enroll/status`. | Endpoint name, peer ID, timestamp | 5-minute freshness window (`challengeMaxAge`); `/refresh` additionally redeems only the last Biscuit issued to the peer. |
+| **Control plane read & report endpoints** (`/policies`, `/egress`, `/revocations`, `/nodes/catalog`) | Bearer Member Biscuit of an admitted node (`admittedNode`). | Enrolled node credential | Bounded by Biscuit TTL and ban/revocation list. |
+| **OAuth 2.1 external client surface** (`/oauth/authorize`, `/oauth/token`, `/mcp` over HTTPS) | Authorization Code + PKCE (`S256`) on the code grant. The `client_peer_id` of the minted Biscuit is the calling node's when a node calls, otherwise the `actor_peer_id` form parameter or the control plane's own peer ID (`resolveDefaultActorPeer`). | A claimed peer ID (the Biscuit is a bearer token on the HTTPS `/mcp` hop unless sender-constrained with DPoP; see §5.2) | Single-use authorization codes with PKCE verifier check on the code exchange; none on the resulting bearer Biscuit. |
+
+---
+
+### 4.6 Gateways, egress credential brokers, content inspection, and TCP tunnels
+
+#### Gateway integration (`sam-node`)
+
+`sam-node` exposes three standard gateway interfaces on its HTTP listener
+(`--bind-addr`):
+
+1. Envoy `ext_authz` (`/ext_authz` and
+ `/envoy.service.auth.v3.Authorization/Check`) evaluates standing Datalog
+ policy and `tar_block` rules on incoming Envoy `CheckRequest` calls, accepts
+ verified SPIFFE IDs from `AttributeContext.Source.Principal` or
+ `X-Forwarded-Client-Cert` (XFCC) on trusted proxy listeners, and injects
+ brokered upstream credentials (`Authorization: Bearer ...`,
+ `X-Sam-Principal`, `X-Sam-Task-Id`).
+2. Envoy `ext_proc` (`/envoy.service.ext_proc.v3.ExternalProcessor/Process`)
+ inspects buffered JSON-RPC request bodies so `operation.allowed_tools` on
+ MCP `tools/call` is enforced before injecting the upstream credential.
+3. RFC 8693 Token Exchange (`POST /oauth/token`) and MCP OAuth 2.1 accept
+ `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` with a JWT or
+ Biscuit `subject_token` and optional `TaskAuthorizationRule` (in `options`,
+ `scope`, or `resource`), and serve RFC 9728
+ `/.well-known/oauth-protected-resource` pointing unauthenticated MCP clients
+ to the control plane's OAuth 2.1 Authorization Server.
+
+On `/sam/{peer}/{type}/{svc}/...`, the `Authorization` header is reserved for
+the destination service's own credential and passes through untouched; callers
+pass their SAM Biscuit or JWT in `X-Sam-Authentication`. Transparent JWT
+exchange on `Authorization: Bearer <JWT>` applies only to `/mcp` and `/v1/*`.
+
+#### Content inspection at the egress node (`inspection.inspectors`)
+
+Requests travel as ciphertext through routers and are decrypted at the egress
+node selected by `served_by`. Inspection is configured on `EgressDestination`
+and runs before the credential broker injects the upstream secret, so an
+inspector never sees destination credentials:
+
+1. Built-in policy facts expose `host()`, `port()`, `method()`, `path()`, and
+ the MCP tool name from `tools/call` to Datalog and `TaskAuthorizationRule`
+ evaluation.
+2. Google Cloud Model Armor (`model_armor`) calls `sanitizeUserPrompt` and (in
+ `BUFFERED` mode) `sanitizeModelResponse` over HTTPS for Gemini, OpenAI chat,
+ MCP `tools/call`, and A2A payloads, blocking findings with `403` and
+ `Proxy-Status` and applying Sensitive Data Protection de-identification
+ replacements.
+3. Envoy `ext_proc` callouts (`ext_proc`) stream headers, bodies, and trailers
+ over standard-library HTTP/2 gRPC (using trimmed protos vendored under
+ `third_party/envoy/` with zero extra root `go.mod` dependencies) with
+ `ProcessingRequest.attributes["sam"]` populated (`principal`, `roles`,
+ `actor_node`, `task`, `service`, `destination`). Any mutation to
+ `Authorization`, `Host`, `:authority`, or `X-Sam-*` by the processor is
+ refused.
+4. Operator inspection chains (`preserve_host`, `forward_context`) route
+ through an explicit outbound proxy (such as Secure Web Proxy or
+ `agentgateway`) while preserving the destination `Host` header and optionally
+ forwarding `X-Sam-Principal`, `X-Sam-Roles`, and `X-Sam-Task`.
+
+#### Named TCP tunnels (`EGRESS_MODE_TCP`)
+
+When `mode: EGRESS_MODE_TCP` and a non-empty `ports` allow-list are set on an
+`EgressDestination`, the node accepts `CONNECT <name>:<port>` and
+`sam-node forward egress://<name>:<port> <local-addr>`. Before splicing the TCP
+stream, the egress node peeks at the TLS `ClientHello` and refuses the
+connection if the SNI does not match `<name>` or if Encrypted Client Hello (ECH)
+hides the SNI.
+
+---
+
+### 4.7 Integration blueprints
+
+#### Blueprint 1: NVIDIA OpenShell (zero-credential sandbox)
+
+```mermaid
+flowchart LR
+ subgraph OpenShell["NVIDIA OpenShell Sandbox (Landlock + seccomp + netns)"]
+ Harness["Unmodified Agent Process<br/>(Holds ZERO credentials)"]
+ end
+ subgraph Host["Host / Orchestrator Boundary"]
+ OSProxy["OpenShell Egress Proxy<br/>& Secret Injector"]
+ SamNode["Local sam-node Gateway"]
+ end
+ Mesh(["SAM Mesh & Providers"])
+
+ Harness -- "Plain HTTP to sam-node:8080/mcp & /v1" --> OSProxy
+ OSProxy -- "Injects X-Sam-Authentication:<br/>Bearer <Sealed-Task-Biscuit>" --> SamNode
+ SamNode -- "X-Sam-Biscuit: <Sealed-Task-Biscuit>" --> Mesh
+```
+
+The orchestrator exchanges and attenuates a Task Biscuit via `POST /oauth/token`
+with `seal=true` and registers it in OpenShell's external proxy secret injector.
+The sandboxed process holds zero credentials in its environment or filesystem.
+
+#### Blueprint 2: Docker Sandbox (`docker sbx`) & Kubernetes `agent-sandbox`
+
+When the sandbox container holds a token (`SAM_TASK_TOKEN` or a Kubernetes
+projected service account JWT) to authenticate to a local or cluster
+`sam-node`:
+
+1. The token is sealed (`Seal()`) and narrowed to the single task's
+ `TaskAuthorizationRule`.
+2. Channel binding (`client_peer_id`) ties the token to the origin `sam-node`'s
+ peer ID, so an exfiltrated token cannot be used from another host or node.
+3. A short `expire_time` and explicit revocation (`POST /oauth/revoke` on
+ container exit) bound the lifetime to the task run.
+
+#### Blueprint 3: `agentgateway` / Istio service mesh
+
+Workloads authenticate to `agentgateway` or Istio via mTLS SPIFFE XFCC or a
+Task Biscuit; the gateway calls `sam-node` over `ext_authz`, `ext_proc`, or RFC
+8693 `/oauth/token` for local policy enforcement and routes cross-cluster MCP,
+A2A, and cloud egress calls through `sam-node`.
+
+#### Blueprint 4: End-to-end cloud egress (BigQuery read-only task & sub-agent hop)
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant Origin as Origin sam-node / SDK agent
+ participant Egress as Egress sam-node (egress://bigquery.googleapis.com)
+ participant CP as SAM Control Plane (OIDC issuer)
+ participant STS as Provider STS (sts.googleapis.com / sts.amazonaws.com)
+ participant API as Destination API
+
+ Origin->>Egress: libp2p stream GET /egress/bigquery.googleapis.com/bigquery/v2/...<br/>AuthFrame.biscuit = <Task Biscuit (authority + tar_block 1..k)>
+ Note over Egress: 1. Authorize: CP signature, actor binding,<br/>standing policy for the subject, TAR chain on<br/>service(), host(), port(), method(), path()
+ Egress->>CP: 2. POST /sts/token { biscuit, destination } (cache miss on biscuit digest)
+ Note over CP: Verifies the Biscuit and TAR chain again;<br/>mints ES256 JWT: sub=principal, act=egress node,<br/>aud=destination audience, sam_task, exp=minutes
+ CP-->>Egress: 3. JWT
+ Egress->>STS: 4. RFC 8693 exchange: subject_token=JWT<br/>(Google: pool provider; AWS: AssumeRoleWithWebIdentity + session Policy from TAR)
+ STS-->>Egress: 5. Short-lived destination credential (cached by biscuit digest)
+ Egress->>API: 6. Request with the destination credential; TLS originated here
+ Note over API: 7. Provider IAM evaluates the federated principal's standing grants<br/>(and the session policy on AWS)
+ API-->>Egress: 200 OK
+ Egress-->>Origin: 200 OK
+```
+
+---
+
+## 5. What is left out or deferred on purpose
+
+### 5.1 Nonce and body-hash binding on control-plane HTTP requests
+
+`POST /enroll`, `GET /enroll/status`, `POST /register`, `POST /refresh`,
+`POST /token/exchange`, and `POST /sts/token` verify an Ed25519 signature over
+`sam:<endpoint>:<peer_id>:<challenge_unix_ms>` within a 5-minute clock window
+(`challengeMaxAge`), while `/policies`, `/egress`, `/revocations`, and
+`/nodes/catalog` authenticate the caller via its bearer Member Biscuit.
+
+Because the signed text does not yet carry a server-tracked random nonce or
+request-body SHA-256 hash, TLS (`https://`) is mandatory for every remote
+control plane (`AllowInsecureControlPlane` is restricted to loopback or
+explicitly trusted networks). Extending the proof message with a random nonce,
+an optional server nonce for skewed clocks, and a request-body SHA-256 hash across
+all credentialed control-plane endpoints is a self-contained future hardening
+step.
+
+### 5.2 Optional DPoP (RFC 9449) at the OAuth 2.1 border
+
+Inside the mesh, libp2p channel binding (`client_peer_id == connection_peer_id`)
+provides per-connection proof of possession between nodes. An external MCP
+client, however, reaches a node's `/mcp` ingress over HTTPS with no libp2p
+channel, so the Biscuit minted for it at `/oauth/token` carries a claimed
+`client_peer_id` and is a bearer token on that HTTPS hop.
+
+DPoP (RFC 9449) is the standard mechanism to sender-constrain that external
+OAuth hop: when a client sends a `DPoP` header at `/oauth/token`, the control
+plane verifies the proof (`htm`, `htu`, `iat`, `jti`), mints the key thumbprint
+as `client_key_thumbprint("<jkt>")` in the Biscuit authority block, and returns
+`token_type: DPoP`, and the node's `/mcp` ingress verifies the `DPoP` proof with
+`ath` over the Biscuit and checks
+`client_key_thumbprint($t), connection_key_thumbprint($t)`. Because the MCP
+authorization specification does not require DPoP and off-the-shelf MCP clients
+(Claude Code, Gemini CLI, Cursor, VS Code) only send Authorization Code + PKCE
+today, DPoP is optional (`dpop_bound_access_tokens_required: false`) and a
+Biscuit minted without a `DPoP` proof remains a bearer token at `/mcp`.
+
+### 5.3 No built-in Azure or AWS IMDS node enrollment `TokenSource`
+
+GCE and Cloud Run provide a standard OIDC JWT from the instance metadata server
+(`--cloud-provider=gcp|auto`). AWS EC2 IMDS issues SigV4 credentials and a
+PKCS7 document rather than an OIDC JWT, and Azure IMDS requires a
+tenant-registered Entra Application ID URI (`resource`). On AWS, Azure, and bare
+metal without Kubernetes projected tokens, SPIRE (`aws_iid`, `azure_msi`,
+`tpm_devid`) with `spiffe-helper` writing a JWT-SVID to `--jwt-path` is the
+single portable path.
+
+### 5.4 No X509-SVID mTLS termination on the control plane
+
+Enrolling via X509-SVID mTLS would require the control plane (and any ingress
+load balancer in front of it) to terminate mTLS against the SPIFFE trust
+bundle. JWT-SVIDs over `--jwt-path` work through standard HTTPS load balancers
+and CDNs with zero TLS termination coupling.
+
+### 5.5 Model Armor streaming modes
+
+Model Armor's unary REST API (`sanitizeUserPrompt` and `sanitizeModelResponse`)
+is called using the Go standard library without vendoring `google/api` gRPC
+protos. Destinations that stream responses choose between
+`RESPONSE_INSPECTION_BUFFERED` (inspect the complete response before release)
+and `RESPONSE_INSPECTION_REQUEST_ONLY` (inspect the prompt and stream the
+response directly).
+
+---
+
+## 6. Summary of security invariants
+
+1. `sam-control-plane` is the customer-owned OIDC issuer for cloud egress,
+ using a KMS/HSM-attributable ES256 signing key, short JWT lifetimes, one
+ audience per destination, CEL attribute conditions restricting `act.sub` to
+ enrolled egress nodes, and joined audit logs (`sub` + `sam_task`).
+2. `sam-control-plane` stays off the per-request hot path: nodes cache
+ unattenuated, unsealed Delegated Session Biscuits by
+ `SHA-256(subject_token_type + "|" + subject_token)` and cache minted border
+ JWTs and upstream cloud tokens by Biscuit SHA-256 digest.
+3. Appended Biscuit blocks are treated as untrusted bytes: structural bounds
+ (`MaxAttenuationBlocks = 8`, `0` rules, `0` checks, `1` `tar_block` fact,
+ `MaxTARBytes = 4096`) run before any Datalog authorizer is constructed in Go,
+ TypeScript, and Python.
+4. Egress nodes prevent confused-deputy attacks by stripping caller
+ `Authorization`, `Cookie`, and `X-Sam-*` headers, running content inspectors
+ before credential injection, refusing inspector mutations to `Authorization`,
+ `Host`, `:authority`, or `X-Sam-*`, and never allowing a holder-authored TAR
+ block to select a broker, role, or audience.
+5. Workload issuers configured via `--workload-issuer` can enroll, refresh, and
+ exchange credentials on the mesh surface, and are refused at `/user/*` and
+ `/oauth/authorize` so a compromised workload cannot register as a human user
+ or mint bootstrap tokens.
+6. Binding member values and role names reject control characters, `"`, and `\`
+ while permitting spaces, `;`, and UTF-8; `BuildPolicyRules` never skips exact
+ members on charset grounds and quotes wildcard string literals with
+ `strconv.Quote` before rendering `.starts_with(...)` or `.ends_with(...)`
+ Datalog rules.
diff --git a/site/content/docs/guides/headless-enrollment.md b/site/content/docs/guides/headless-enrollment.md
index 1c5f62b9..82c16c0f 100644
--- a/site/content/docs/guides/headless-enrollment.md
+++ b/site/content/docs/guides/headless-enrollment.md
@@ -13,8 +13,16 @@ what happens when the credential of such a node expires.
## With an OIDC token that the workload already has
If the platform gives the workload a token from an issuer that the control
-plane trusts, no operator step is needed. On Kubernetes this is a projected
-service account token with the right audience:
+plane trusts, no operator step is needed. Mark workload issuers with
+`--workload-issuer` on the control plane so workload tokens can enroll,
+refresh, and exchange credentials (`POST /register`, `POST /refresh`,
+`POST /token/exchange`), while being refused at human operator endpoints
+(`/user/*`, `/oauth/authorize`).
+
+### Kubernetes projected service account tokens
+
+On Kubernetes, mount a projected service account token with the control
+plane's audience:
```yaml
volumes:
@@ -31,11 +39,67 @@ volumes:
sam-node run --control-plane https://mesh.example.com --jwt-path /var/run/secrets/tokens/sam-token
```
-The control plane must list the cluster's issuer in `--issuer` and the
-audience in `--allowed-audiences`. The policy must bind the service account
-(`user:system:serviceaccount:<namespace>:<name>`) to `sam:role:node`.
-Routers enroll the same way with `sam-router --jwt-path`. The
-[Kubernetes guide](../kubernetes/) shows the complete setup.
+List the cluster's issuer in `--issuer` (`controlPlane.oidcIssuer` in the Helm
+chart) and the audience in `--allowed-audiences`; add the cluster issuer to
+`--workload-issuer` (`controlPlane.workloadIssuer`) as well to keep workload
+tokens off `/user/*` and `/oauth/authorize`. Bind either a specific service
+account (`user:system:serviceaccount:<namespace>:<name>`) or a namespace prefix
+(`user:system:serviceaccount:<namespace>:*`) to `sam:role:node`. Routers enroll
+the same way with `sam-router --jwt-path`. The [Kubernetes guide](../kubernetes/)
+shows the complete setup.
+
+### GCE VMs and Cloud Run (`--cloud-provider`)
+
+On Compute Engine and Cloud Run there is no Kubernetes projected volume, so
+`sam-node` can fetch an OIDC identity token directly from the instance
+metadata server (`.../computeMetadata/v1/instance/service-accounts/default/identity?audience=<aud>&format=full`):
+
+```bash
+sam-node run --control-plane https://mesh.example.com --cloud-provider gcp
+```
+
+`--cloud-provider auto` probes the metadata server at startup and uses it
+when reachable. GCE VM metadata tokens requested with `format=full` carry a
+`google.compute_engine` claim that the control plane recognizes automatically,
+whereas Cloud Run metadata tokens do not carry that claim. On the control
+plane, list `https://accounts.google.com` in `--issuer` and pass the
+service-account suffix filter in `--workload-issuer` so service accounts on
+both GCE and Cloud Run are treated as workload tokens while human Google
+accounts remain able to use `/user/*` and `/oauth/authorize`:
+
+```bash
+sam-control-plane \
+ --issuer https://accounts.google.com \
+ --workload-issuer https://accounts.google.com=.gserviceaccount.com \
+ --allowed-audiences sam-mesh-audience
+```
+
+In the mesh policy, bind the service account email or project suffix (for
+example, `email:*@my-project.iam.gserviceaccount.com`) to `sam:role:node`.
+
+### SPIFFE / SPIRE (`spiffe-helper` + `--jwt-path`)
+
+For VMs and bare metal running SPIRE (or multi-cluster meshes sharing a
+SPIFFE trust domain), run [`spiffe-helper`](https://github.com/spiffe/spiffe-helper)
+beside `sam-node` to fetch a JWT-SVID from the SPIFFE Workload API and keep
+the file at `--jwt-path` rotated across the SVID's lifetime:
+
+```hcl
+# spiffe-helper.conf
+agent_address = "/run/spire/sockets/agent.sock"
+cert_dir = "/run/sam"
+jwt_svids = [{ jwt_audience = "sam-mesh-audience", jwt_svid_file_name = "jwt_svid.token" }]
+```
+
+```bash
+sam-node run --control-plane https://mesh.example.com --jwt-path /run/sam/jwt_svid.token
+```
+
+List the SPIRE OIDC Discovery Provider URL in `--issuer` and `--workload-issuer`
+on the control plane, and bind the SPIFFE ID or path prefix
+(`user:spiffe://example.org/ns/prod/*`) to `sam:role:node`.
+
+### OAuth client credentials
A workload with an OAuth client ID and secret can use the client-credentials
grant instead, with `--oidc-issuer`, `--client-id` and
@@ -127,8 +191,18 @@ remove one of those, ban the node.
## When the credential expires
-A node enrolled with a bootstrap token has no login to fall back on. Its
-credential is refreshed automatically while it runs. But if the node is off
+A node or router enrolled with a platform token (`--jwt-path`,
+`--cloud-provider`, or `--client-id`) presents a fresh platform JWT in
+`TokenRefreshRequest.jwt` on every `POST /refresh`. As long as the token's
+`iss|sub` matches the enrolled record, the control plane re-attests the member
+in place, updates its stored claims and extends its session
+(`--workload-session-ttl`, `48h` by default) without re-enrolling. If the
+member was offline longer than the session or key grace period, its renewal
+loop automatically re-enrolls with a fresh platform token under the same peer
+ID.
+
+A node enrolled with a bootstrap token has no login or platform token source
+to fall back on. Its credential is refreshed automatically while it runs. But if the node is off
for longer than the control plane's key grace period (`--key-grace-period`,
one hour by default), it comes back with a credential signed by a retired
key, and `/refresh` refuses it. An SDK member in the same position enrolls
diff --git a/site/content/docs/guides/kubernetes.md b/site/content/docs/guides/kubernetes.md
index 44874fb5..1f8b0a15 100644
--- a/site/content/docs/guides/kubernetes.md
+++ b/site/content/docs/guides/kubernetes.md
@@ -36,11 +36,15 @@ ISSUER=$(kubectl get --raw /.well-known/openid-configuration | jq -r .issuer)
helm upgrade --install sam-mesh ./charts/sam-mesh \
--namespace sam --create-namespace \
--set controlPlane.oidcIssuer="$ISSUER" \
+ --set controlPlane.workloadIssuer="$ISSUER" \
--set controlPlane.insecureSkipTlsVerify=true \
--set bootstrap.nodeMembers='{user:system:serviceaccount:sam-nodes:calc-mcp-sam-node}' \
--set bootstrap.nodeServices='{mcp://calculator,system://sam.catalog}'
```
+`controlPlane.workloadIssuer` marks the cluster issuer as a workload identity
+provider so service account tokens can enroll, refresh, and exchange credentials
+while being refused at `/user/*` and `/oauth/authorize`.
`insecureSkipTlsVerify` is needed when the cluster issuer is served with the
cluster CA, which the control plane does not trust by default. Leave it off
for a public provider. On a managed cluster the issuer is often public (on
diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.md
index fb9dd4c1..df0ccaae 100644
--- a/site/content/docs/guides/native-sdks.md
+++ b/site/content/docs/guides/native-sdks.md
@@ -93,9 +93,14 @@ On a platform that issues workload identity tokens, a program needs no
bootstrap token. A mesh whose control plane trusts the platform's issuer
enrolls the program from that token instead; on Kubernetes that is a
projected service account token, as [Headless enrollment](../headless-enrollment/)
-shows for `sam-node`. Set `SAM_JWT_PATH` to the token file rather than
-`SAM_BOOTSTRAP_TOKEN_PATH`. That is how the public testnets run these same
-programs as canaries beside the `sam-node` ones.
+shows for `sam-node`. Set `SAM_JWT_PATH` (`jwtPath` / `jwt_path`) to the
+token file rather than `SAM_BOOTSTRAP_TOKEN_PATH`, or pass a `jwt` callback
+(`() => string | Promise<string>` in JS, `Callable[[], str]` in Python) that
+fetches a fresh token (for example, from a cloud metadata server). On every
+credential refresh, the SDK re-reads `jwtPath` or invokes the `jwt` callback
+and sends the fresh token in `TokenRefreshRequest.jwt` so the control plane
+re-attests the member in place. That is how the public testnets run these
+same programs as canaries beside the `sam-node` ones.
## 2. Install the SDK
diff --git a/site/content/docs/reference/control-plane.md b/site/content/docs/reference/control-plane.md
index a50812a8..2641c08d 100644
--- a/site/content/docs/reference/control-plane.md
+++ b/site/content/docs/reference/control-plane.md
@@ -19,7 +19,8 @@ sam-control-plane admin unban --peer <id> lift a ban
| Flag | Default | Meaning |
|---|---|---|
-| `--issuer` | required | OIDC issuer URL(s), comma-separated. The first is advertised to enrolling nodes on `/info`. Can also be set with `SAM_OIDC_ISSUER`. |
+| `--issuer` | | OIDC issuer URL(s), comma-separated. At least one of `--issuer` or `--workload-issuer` is required. The first issuer is advertised to enrolling nodes on `/info`. |
+| `--workload-issuer` | | Workload OIDC issuer(s), comma-separated (`<issuer>` or `<issuer>=<email-suffix>`, such as `https://accounts.google.com=.gserviceaccount.com`). Automatically added to `--issuer`. Workload tokens can enroll, refresh, and exchange credentials (`/register`, `/refresh`, `/token/exchange`), and are refused at `/user/*` and `/oauth/authorize`. |
| `--allowed-audiences` | `sam-mesh-audience` | Audiences accepted in OIDC tokens, comma-separated. |
| `--oidc-client-id` | first audience | OAuth client ID advertised on `/info`, for providers where it differs from the audience. |
| `--insecure-skip-tls-verify` | `false` | Skip TLS verification when fetching issuer metadata and keys. For a cluster issuer served with the cluster CA, or a local development issuer. |
@@ -30,7 +31,8 @@ sam-control-plane admin unban --peer <id> lift a ban
| `--admin-token-path` | | File containing the bearer token for `/admin/*` and `POST /policies`. Can also be set with `SAM_ADMIN_TOKEN`. Without a token, the admin API cannot be used. |
| `--auto-approve-enrollment` | `false` | Issue credentials for valid bootstrap-token enrollments immediately instead of queueing them for approval. |
| `--biscuit-ttl` | `24h` | Lifetime of each credential. If the OIDC token expires sooner, the credential expires with it. |
-| `--oidc-session-ttl` | `2160h` (90 days) | How long an OIDC enrollment may keep refreshing before the identity must log in again. |
+| `--oidc-session-ttl` | `2160h` (90 days) | How long a human OIDC enrollment may keep refreshing before the identity must log in again. |
+| `--workload-session-ttl` | `48h` | How long a workload OIDC enrollment (`--workload-issuer`) may refresh without presenting a fresh platform JWT in `TokenRefreshRequest.jwt`. |
| `--key-rotation-interval` | `24h` | How often a new signing key is generated. `0` disables rotation. |
| `--key-grace-period` | `1h` | How long a rotated-out key stays accepted. Credentials signed by a retired key cannot be verified or refreshed. Nodes and routers must pull `/keys` well within this window (`sam-node --control-plane-sync-interval`, `sam-router --keys-sync-interval`). |
| `--lease-duration` | `15m` | How long a router lease lasts without renewal. |
@@ -60,7 +62,7 @@ Responses that carry credentials are sent with `Cache-Control: no-store`.
| `GET /keys` | The current set of signing public keys, signed by every key in the set. A caller accepts the set only if one signature verifies under a key it already trusts. |
| `GET /.well-known/openid-configuration`, `GET /.well-known/oauth-authorization-server` | OIDC Discovery and OAuth 2.1 Authorization Server metadata for outbound STS federation and MCP OAuth 2.1 clients. |
| `GET /jwks` | JSON Web Key Set (`ES256` public keys) for verifying border JWTs minted by `POST /sts/token`. |
-| `GET /oauth/authorize`, `POST /oauth/token` | OAuth 2.1 Authorization Code + PKCE endpoints (honouring RFC 8707 `resource` indicators to scope the issued Task Biscuit). |
+| `GET /oauth/authorize`, `POST /oauth/token` | OAuth 2.1 Authorization Code + PKCE endpoints (honouring RFC 8707 `resource` indicators to scope the issued Task Biscuit). Tokens from `--workload-issuer` are refused at `/oauth/authorize` with `403`. |
### Enrollment, refresh, and STS
@@ -76,7 +78,7 @@ names. Every instant in a response (`expire_time` and the like) is a
| `POST /register` | `EnrollRequest` (OIDC token, public key, requested role, labels) | OIDC enrollment. Returns `EnrollResponse`: the credential, the control plane public key, router addresses and expiry. |
| `POST /enroll` | `BootstrapEnrollRequest` (bootstrap token, public key, requested role, labels) | Bootstrap enrollment. Returns `BootstrapEnrollResponse` with status `APPROVED` and the credential, or with status `PENDING`. For a peer that is already approved, a new credential is minted directly. |
| `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 /refresh` | `TokenRefreshRequest` (optional `jwt`), current credential as `Authorization: Bearer <base64>` | Exchange a credential for a new one. When `jwt` is present and its `iss|sub` matches the enrolled node record, re-attests the node in place, updates stored claims and extends the session. Refuses a replayed (superseded) credential, a banned node, an expired session without a matching `jwt`, and a credential signed by a retired key unless the node has `autonomous_recovery`. |
| `POST /token/exchange` | `TokenExchangeRequest` (`subject_token`, optional `task_rule` and `seal`, challenge signature), node credential as bearer | Stateless JWT-to-Biscuit exchange. Mints a Delegated Session Biscuit bound to the calling node (`actor_node`, `client_peer_id`) with zero database writes. |
| `POST /sts/token` | `STSTokenRequest` (`biscuit`, `destination`, optional `audience`, challenge signature), node credential as bearer | Stateless Biscuit-to-JWT minting. Verifies the Biscuit and `tar_block` chain against `egress://<destination>` and mints a short-lived ES256 border JWT (`sub`, `act.sub`, `aud`, `sam_roles`, `sam_task`). |
| `GET /revocations` | credential as `Authorization: Bearer <base64>` | `RevocationsResponse`: revoked root Biscuit revocation IDs (`revocation_ids`) and banned peer IDs (`banned_peer_ids`). |
@@ -105,8 +107,9 @@ All routes require `Authorization: Bearer <admin-token>` and use JSON.
### User
-For an OIDC user acting on their own nodes, authenticated with an ID token
-from the configured issuer. The console uses these routes.
+For a human OIDC user acting on their own nodes, authenticated with an ID token
+from a configured human issuer (tokens matching `--workload-issuer` are refused
+with `403`). The console uses these routes.
| Route | Purpose |
|---|---|
diff --git a/site/content/docs/reference/policy.md b/site/content/docs/reference/policy.md
index 16fd80b9..582a4af3 100644
--- a/site/content/docs/reference/policy.md
+++ b/site/content/docs/reference/policy.md
@@ -181,13 +181,28 @@ A member is one of:
| Member | Matches |
|---|---|
-| `user:<sub>` | the OIDC subject. For a Kubernetes service account: `user:system:serviceaccount:<namespace>:<name>`. |
+| `user:<sub>` | the OIDC subject. For a Kubernetes service account: `user:system:serviceaccount:<namespace>:<name>`. For a SPIFFE workload: `user:spiffe://<trust-domain>/<path>`. |
| `email:<address>` | a verified email claim |
| `group:<name>` | an entry of the `groups` claim |
| `idp_role:<name>` | an entry of the issuer's `roles` claim |
-| `node:<peer-id>` | one node, by key |
+| `node:<peer-id>` | one node, by key (exact peer ID only; wildcards are not permitted on `node:`) |
| `sam:system:authenticated` | every identity that the identity provider authenticates |
+Each claim-backed member (`user:`, `email:`, `group:`, `idp_role:`) may carry
+a single trailing `*` (prefix match, compiled to `$v.starts_with("<prefix>")`)
+or a single leading `*` (suffix match, compiled to `$v.ends_with("<suffix>")`),
+for example:
+
+- `user:system:serviceaccount:sam-nodes:*`
+- `user:spiffe://acme.example/ns/prod/*`
+- `email:*@my-project.iam.gserviceaccount.com`
+
+Bare `<prefix>:*` (such as `user:*` or `email:*`) and interior wildcards
+(`a*b`) are rejected; use `sam:system:authenticated` when any authenticated
+identity is intended. Role names and binding member values may contain spaces
+and UTF-8 (for example `group:Engineering Team`), and may not contain `"`,
+`\`, or control characters.
+
`role:` is not a member, because a role cannot grant a role. A bootstrap
token enrollment carries no OIDC claims. Such a node receives exactly the
token's role and nothing that a binding on claims would add, so the grants
diff --git a/site/content/docs/reference/sam-node.md b/site/content/docs/reference/sam-node.md
index dd99352b..1131789c 100644
--- a/site/content/docs/reference/sam-node.md
+++ b/site/content/docs/reference/sam-node.md
@@ -72,17 +72,18 @@ refuses until `sam-node reset` has been run.
Starts the node. If the data directory holds a credential, the node uses it.
Otherwise the node enrolls if it has a way to (`--jwt-path`,
-`--bootstrap-token-path`, `--client-id`, or `--join`). If it has none, it
-starts an unauthenticated local MCP server whose only tool explains how to
-enroll.
+`--cloud-provider`, `--bootstrap-token-path`, `--client-id`, or `--join`). If
+it has none, it starts an unauthenticated local MCP server whose only tool
+explains how to enroll.
### Enrollment
| Flag | Default | Meaning |
|---|---|---|
| `--join` | `false` | Run the interactive login on first start if there is no credential. Needs a terminal and `--control-plane` (or a stored control plane). Does nothing once the node is enrolled. |
-| `--jwt-path` | | File containing an OIDC token to enroll with, for example a projected service account token. |
+| `--jwt-path` | | File containing an OIDC token to enroll and refresh with, for example a Kubernetes projected service account token or a `spiffe-helper` JWT-SVID file. |
| `--jwt` | | The token as a value. Logged as a warning. The file form is preferred. |
+| `--cloud-provider` | | Cloud metadata provider for workload identity enrollment and refresh: `gcp` (GCE and Cloud Run metadata identity endpoint) or `auto` (probe GCE/Cloud Run metadata at startup). |
| `--bootstrap-token-path`, `--bootstrap-token` | | As for `join`. |
| `--client-id`, `--client-secret-path` | | OAuth client-credentials grant against `--oidc-issuer`. The secret can also come from `SAM_CLIENT_SECRET`. |
| `--offline-access` | `false` | With `--join`, as for `join`. |
diff --git a/site/content/docs/reference/sam-one.md b/site/content/docs/reference/sam-one.md
index e1233af4..9ce07755 100644
--- a/site/content/docs/reference/sam-one.md
+++ b/site/content/docs/reference/sam-one.md
@@ -41,6 +41,7 @@ downloaded tunnel connector.
| `--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 `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. |
+| `--workload-issuer` | | Workload OIDC issuer(s), comma-separated (`<issuer>` or `<issuer>=<email-suffix>`). Automatically added to `--issuer` and refused at `/user/*` and `/oauth/authorize`. |
| `--oidc-client-id` | first audience | Client ID advertised on `/info`. |
| `--allowed-audiences` | `sam-mesh-audience` | Accepted OIDC audiences. |
| `--enroll-qr` | when stdout is a terminal | Print a device-enrollment QR code at startup. Only for `https` URLs. |
@@ -58,6 +59,7 @@ of zero leaves the default of that component unchanged.
| `--control-plane-key-rotation-interval` | `--key-rotation-interval` |
| `--control-plane-key-grace-period` | `--key-grace-period` |
| `--control-plane-biscuit-ttl` | `--biscuit-ttl` |
+| `--control-plane-workload-session-ttl` | `--workload-session-ttl` |
| `--control-plane-manual-enrollment` | The opposite of `--auto-approve-enrollment`: queue bootstrap enrollments for approval. |
| `--router-keys-sync-interval` | `sam-router --keys-sync-interval` |
| `--router-lease-renew-interval` | `--lease-renew-interval` |
diff --git a/sts.md b/sts.md
deleted file mode 100644
index 49e6b003..00000000
--- a/sts.md
+++ /dev/null
@@ -1,754 +0,0 @@
-# SAM Design Doc: Task-Based Authorization, STS & PDP Architecture
-
-* **Status:** Draft / Proposal (v3 — v2 incorporated the architecture and security review; v3 adds the two-token model with the control plane as OIDC issuer (section 3.5), the egress credential broker and per-destination narrowing (section 5), content inspection and non-HTTP protocols at the egress node (sections 5.6, 5.7), the security considerations (section 7) and the list of facts to verify before implementation starts (section 8)).
-* **Context:** Evolving SAM from a custom sandbox network stack (`sam-box` / `nano-init`) into an **Authority, Policy Decision Point (PDP), and Task-Scoped Credential Layer** that composes with existing agent gateways (`agentgateway`, Istio, Envoy AI Gateway), sandbox runtimes (NVIDIA OpenShell, Docker Sandbox, Kubernetes `agent-sandbox`), and cloud providers (Google Cloud STS, AWS STS, Entra).
-* **Primary CUJ:** an agent that runs on premises or inside a customer environment needs access to external services (BigQuery, Vertex AI and Gemini, object storage, third-party MCP servers) and to external agents, without any cloud credential existing in that environment and with the customer keeping the policy, the signing keys and the audit trail. In-mesh MCP access and ingress to the agent are secondary journeys built from the same primitives. The gateway integrations in section 4 matter where a customer already runs a mesh; on premises without one, the local `sam-node` or the SDK is the entry point and no gateway is required.
-
----
-
-## The Picture: a Courier Network for Tasks
-
-![The Agent Mesh as a courier network](site/static/images/agent-mesh-courier.svg)
-
-SAM is not a network proxy that happens to carry agent traffic. It moves tasks between places that trust nothing on arrival, the way a courier network moves parcels between post offices. The animation ([site/static/images/agent-mesh-courier.svg](site/static/images/agent-mesh-courier.svg), SMIL, dark theme for the landing page, plays in any browser or `<img>` tag) follows six parcels: a developer to `inference://claude` and to `inference://gemini`, Kubernetes on premises to `mcp://bigquery`, a sandbox platform to `mcp://github`, a SaaS platform to `egress://generativelanguage.googleapis.com`, and Kubernetes in a cloud, through the gateway it already runs, to `a2a://partner-agent`. The mapping is exact:
-
-| In the picture | In SAM |
-| :--- | :--- |
-| Parcel | One request: an MCP call, a chat completion, a BigQuery query, an A2A message. |
-| Sender | The agent wherever it runs: a developer laptop, Kubernetes on premises, Kubernetes in a cloud, a SaaS platform, a sandbox platform. |
-| Local post office | The `sam-node` next to the agent, or the SDK inside its process. It checks the sender's platform identity (projected service account token, Workload Identity, SPIFFE JWT-SVID, OIDC login) and obtains the waybill from the Registry. |
-| Your gateway | Istio, agentgateway or kgateway where a cluster already runs one. It stays in the data path and asks the `sam-node` office over `ext_proc` (or `ext_authz`, or RFC 8693 token exchange); the office stamps, the gateway carries. This is the row that separates SAM from the gateways: SAM is not another one. |
-| Waybill | The Task Biscuit: who the sender is, through which office (actor), what this task may do, until when. |
-| Stamp | An attenuation block added at a hop (`tar_block`). It can only restrict; a sub-agent's parcel carries one stamp more than its parent's. |
-| Sealed bag | The encrypted libp2p stream between two offices. Routers relay it across NAT, clusters, sites and clouds and cannot open it. |
-| Registry | The control plane: verifies senders, issues waybills, holds the policy, issues the permits foreign borders recognize (OIDC issuer), keeps the receipts. It never touches a parcel. The rubber stamp thumps once per waybill and once per permit. |
-| Destination office | The egress `sam-node` for one destination (`mcp://`, `inference://`, `egress://`, `a2a://`): verifies the waybill and every stamp again, runs customs, obtains the permit, delivers. The operator chooses where it runs, hence where traffic leaves. |
-| Customs | Content inspection at the destination office: policy facts, Model Armor, and any Envoy `ext_proc` processor the operator brings (section 5.6). |
-| Permit | The destination credential: a federated token minted on the Registry's signature for this sender and task, or a key from the office vault. The agent never holds it. |
-| Receipts | Audit logs at the Registry, at both offices and at the destination, joined by task id. |
-
----
-
-## 1. Executive Summary & Architectural Positioning
-
-In traditional cloud and service-mesh architectures, permissions are granted **ambiently** to a workload identity (a Kubernetes Service Account, a GCP Service Account, a SPIFFE SVID `spiffe://...`, or Google Cloud **Agent Identity**).
-
-**Workload identity is necessary, but insufficient for AI agents:**
-1. **Same Workload, Different Tasks (CUJs 1 & 2):** A single agent workload (e.g., a BigQuery analytics agent, a coding sandbox, or a personal assistant) executes many concurrent or sequential sessions with different least-privilege boundaries (e.g., read-only access to `dataset_A` in task 1 vs. schema mutation on `dataset_B` in task 2). Workload identity proves *which binary/container* is calling, not *what task boundary* applies to this session.
-2. **Prompt Injection & Confused Deputy Risks:** If an agent session exercises the full ambient privileges of its user or workload identity, a prompt injection during a narrow task can exfiltrate or mutate unrelated resources.
-3. **Multi-Hop Ephemeral Sub-Agents (CUJ 3):** When a parent agent delegates a narrower sub-task to a child agent, it needs **offline, progressive credential attenuation** (`Token2 = Attenuate(Token1, TaskRule)`)—which static IdP/OIDC tokens and 1-hop Credential Access Boundaries (CAB) cannot do without minting new identities at the IdP on every hop.
-
-### Core Architectural Shift
-
-SAM explicitly reverses the earlier preview assumption that SAM must build its own userspace TCP/IP sandbox boundary (`nano-init` + `sam-box`). **OS/container confinement belongs to the platform (`agent-sandbox`, OpenShell, `docker sbx`); gateway traffic interception belongs to the proxy (`agentgateway`, Envoy, Istio, or `sam-node`). SAM owns the cross-environment mesh, the Task-Scoped Authority (Biscuit + TAR), and the Policy Decision Point (PDP) / Credential Broker.**
-
-1. **Two Composable Primitives (`sam-node` + SDKs):**
- * **[`sam-node`](file:///usr/local/google/home/aojea/src/sam/cmd/sam-node) is Infrastructure (PDP, STS, & Mesh Gateway):** Deployed by operators as:
- 1. An **External Authorizer (`ext_authz`) & RFC 8693 STS** behind existing gateways (`agentgateway`, Istio, Envoy AI Gateway / Agent Router, kgateway).
- 2. A **Mesh Provider / Egress Broker** in front of MCP servers, inference backends, and cloud APIs (`egress://`).
- 3. A **Standalone Local/Cluster Gateway** (`/mcp`, `/v1/*`, `/sam/*`) when no Envoy/`agentgateway` is present (laptops, Cloud Run, simple K8s clusters).
- * **SDKs ([`sdk/js`](file:///usr/local/google/home/aojea/src/sam/sdk/js), [`sdk/python`](file:///usr/local/google/home/aojea/src/sam/sdk/python)) are Native Mesh Clients:** Embedded directly in greenfield Python, Node.js, or browser agents to join the mesh and attenuate task tokens in-process.
-2. **How SAM Complements `agentgateway` / Istio:**
- * **`agentgateway`** (LF v1.6) validates JWTs, evaluates local CEL per MCP tool, calls Envoy `ext_authz`, and performs RFC 8693 backend token exchange (`subject_token` + `actor_token`). However, `agentgateway` is a single-cluster proxy operating on flat JWTs: it cannot do **offline multi-hop sub-agent attenuation** without an IdP round trip, nor does it provide **cross-organization P2P/relayed routing and discovery**.
- * By exposing a standard **Envoy `ext_authz` gRPC/HTTP server** and a strict **RFC 8693 `/oauth/token` STS endpoint** on `sam-node`, `agentgateway` and Istio can use SAM as their **Task Authority & Cross-Cluster Mesh Backend** with zero custom code.
-3. **Two-Token Model: Biscuit Inside the Mesh, JWT at Both Borders (section 3.5):**
- * **Inbound border:** the caller's platform credential (OIDC JWT, Kubernetes projected token, SPIFFE JWT-SVID, Google Agent Identity token) is exchanged at the control plane for a delegated Biscuit (subject = caller, actor = node).
- * **Outbound border:** the egress node verifies the Biscuit and the TAR chain, obtains a short-lived JWT for the verified principal from the control plane, which is an OIDC issuer, and exchanges that JWT at the destination's security token service (Google Cloud Workload or Workforce Identity Federation, AWS `AssumeRoleWithWebIdentity`). Biscuits never leave the mesh; external parties only ever see standard JWTs.
-4. **The Egress Node Is the Sovereign Exit:** the operator chooses which nodes serve `egress://<name>`, hence from which jurisdiction traffic leaves; no cloud credential exists in the customer environment; the cloud audit log records the SAM principal rather than a shared service account; the only key a cloud trusts is the control plane's, which the customer owns and rotates.
-
----
-
-## 2. Reframing Alternatives: Workload Identity vs. Task Authority
-
-### 2.1 SPIFFE & Workload Identity: Necessary Input, Not the Task Token
-
-An earlier iteration of SAM ([`api/agent.go`](file:///usr/local/google/home/aojea/src/sam/api/agent.go#L38)) used `spiffe://acme.example/prod/reviewer-7` as SAM's own agent identifier format and keyed central RBAC policies on it. That conflated two distinct layers:
-
-| Layer | Question Answered | Right Primitive | Role in SAM |
-| :--- | :--- | :--- | :--- |
-| **1. Workload / Subject Attestation** | *"Which workload or user is initiating or acting in this request?"* | **SPIFFE SVIDs** (`spiffe://...`), **Google Cloud Agent Identity** (GA SPIFFE JWTs), **K8s Projected SA JWTs**, **OIDC ID Tokens**, or **Istio XFCC**. | **Accepted as `subject_token` / `actor_token` inputs** at SAM's token exchange (or extracted from mTLS XFCC headers). |
-| **2. Task / Session Authorization (TAR)** | *"What subset of standing permissions may this specific task or sub-agent hop exercise right now?"* | **SAM Task Biscuit** (Root Authority Block + Appended `TaskAuthorizationRule` Blocks). | **Issued and evaluated by SAM**, progressively attenuated offline across hops, and translated into downscoped upstream cloud credentials at egress. |
-
-* **Why Node Enrollment $\neq$ Caller Identity:** [`sam-node` enrollment](file:///usr/local/google/home/aojea/src/sam/internal/node/enroll.go) attests the **infrastructure node** (`peer_id`). Callers (agents, users, workloads) are **not** nodes: their workload/user credentials are exchanged into **delegated Biscuits** where the caller is the **subject** (`user(...)`) and the `sam-node` is the **actor/channel** (`actor_node(peer_id)`).
-
-### 2.2 Why `sam-box`, `nano-init`, and `X-Sam-Agent` Are Removed
-
-We are completely removing [`cmd/sam-box`](file:///usr/local/google/home/aojea/src/sam/cmd/sam-box), [`cmd/nano-init`](file:///usr/local/google/home/aojea/src/sam/cmd/nano-init), [`internal/sambox`](file:///usr/local/google/home/aojea/src/sam/internal/sambox), [`api/agent.go`](file:///usr/local/google/home/aojea/src/sam/api/agent.go), and the `X-Sam-Agent` header ([`internal/tunnel`](file:///usr/local/google/home/aojea/src/sam/internal/tunnel) has no sandbox dependency; its fate is a separate decision, section 8 item 15):
-
-1. **Confinement is the Sandbox Platform's Job:** `nano-init` required PID 1, `/dev/net/tun`, `CAP_NET_ADMIN`, and a userspace gVisor netstack inside the guest. Real sandbox platforms (**NVIDIA OpenShell**, **Docker Sandbox `sbx`**, **Kubernetes `agent-sandbox`**) already own the kernel/VM boundary and network namespace.
-2. **`X-Sam-Agent` Was Self-Asserted by the Node:** `X-Sam-Agent` was an unverified header beside the node's own Biscuit ([`internal/node/agent.go:L38-45`](file:///usr/local/google/home/aojea/src/sam/internal/node/agent.go#L38-L45)). Replacing it with Control-Plane-signed delegated Biscuits (`POST /token/exchange`) provides cryptographic proof of the caller's subject identity.
-3. **Explicit Update to `AGENTS.md`:** This design intentionally supersedes and replaces three sections in [`AGENTS.md`](file:///usr/local/google/home/aojea/src/sam/AGENTS.md):
- * *Sandbox Dataplane* (`sam-box` / `nano-init` / `tun2connect`) $\rightarrow$ replaced by `sam-node` PDP/`ext_authz` + external sandbox runtimes.
- * *Enforcement over Convention* $\rightarrow$ network confinement is enforced by the platform (OpenShell netns, K8s `NetworkPolicy`, Istio/Envoy, `docker sbx`); SAM enforces cryptographic task authorization at the gateway/provider PDP.
- * *Agent Identity* (`Attach`/`Detach`/`Refresh`/`Status` and `AgentBundle`) $\rightarrow$ replaced by RFC 8693 Token Exchange + Biscuit Task Attenuation.
- * *One schema, two encodings* $\rightarrow$ adds an explicit third wire carve-out for **RFC-mandated OAuth 2.1 / RFC 8693 endpoints** (`/oauth/token`, `/.well-known/*`), which accept RFC `application/x-www-form-urlencoded` and return RFC JSON mapped to/from messages in `api/sam.proto`.
-
-### 2.3 Why the Egress Node Does Not Hold a Cloud Service Account Credential by Default
-
-The obvious design for `egress://bigquery.googleapis.com` is a node that runs with a Google service account (Workload Identity on GKE, or a key file on premises) and calls the API as that account. It is not the default because:
-
-1. **It puts a cloud credential in the customer environment** when the egress node runs on premises, which is the primary CUJ. A key file or a metadata-server identity is exactly the standing credential this design removes.
-2. **It loses attribution:** Cloud Audit Logs record the service account, not the agent or the user who started the task.
-3. **It shares one ceiling** across every caller the node serves; narrowing per task then rests entirely on the SAM PEP.
-
-With the control plane as an OIDC issuer (section 3.5), the egress node obtains a per-principal JWT and exchanges it at the cloud's STS through Workload or Workforce Identity Federation. The customer's IAM grants roles to `principal://.../subject/<sam-principal>` or `principalSet://.../attribute.<key>/<value>`, so the cloud administrator keeps the ceiling and the audit log shows the SAM principal. Service account impersonation remains an adapter option for APIs that do not accept federated principals directly, and a node that runs inside the cloud may still use its platform identity where the operator prefers it (`platform_identity` broker, section 5.1).
-
-Google Credential Access Boundaries are not the task mechanism either: CAB applies to Cloud Storage only (public documentation, checked 2026-10-03), is one hop, and references predefined roles. It stays as one adapter output for `egress://storage.googleapis.com`.
-
----
-
-## 3. Cryptographic & Wire Design (Fixing the 3 Token Correctness Issues)
-
-### 3.1 Issue 3a Fix: Single Source of Truth in Appended Blocks (Zero Holder-Authored Datalog)
-
-A critical subtlety in `biscuit-go` v2.2.0 ([`internal/identity/biscuit.go:L40-49`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go#L40-L49)):
-* `datalog.WithMaxFacts` and `datalog.WithMaxIterations` only bound **rule evaluation**, not **`check if` queries**. A holder-authored block with `0` rules but a multi-variable cross-join check (e.g. `check if label($a), label($b), label($c), label($d)`) still triggers exponential backtracking inside `check.Run()`, and `WithMaxDuration` does not preempt a running check.
-* Furthermore, if a holder writes *both* Datalog `check if` statements and a serialized `TaskAuthorizationRule` protobuf in an appended block, a malicious holder can make them disagree (passing SAM's Datalog check while smuggling a broader protobuf to the Cloud STS adapter).
-
-**Design Invariant: SAM NEVER evaluates holder-authored Datalog (`Rules` or `Checks`).**
-
-1. **What an Appended Block Contains:**
- When a holder (an orchestrator, `sam-node`, or an SDK session) attenuates a Biscuit with a `TaskAuthorizationRule`, the appended block $i \ge 1$ contains:
- * **`0` Datalog `Rules`**
- * **`0` Datalog `Checks`**
- * **Exactly `1` Datalog `Fact`:** `tar_block("<unpadded-base64url-serialized api.TaskAuthorizationRule protobuf>")`
-2. **How `UnmarshalInbound` Validates & Extracts Blocks:**
- In [`internal/identity/biscuit.go`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go), `UnmarshalInbound(rawToken []byte)` inspects the Biscuit envelope (`blocks[1..k]`, with `k <= MaxAttenuationBlocks = 8`) **before** building an authorizer and returns `(*biscuit.Biscuit, []*api.TaskAuthorizationRule, error)` so nothing parses twice:
- * **Go (`biscuit-go` v2.2.0):** Unmarshals the outer `pb.Biscuit` protobuf to check structural counts on each `blocks[i-1]` (`len(FactsV2) == 1`, `len(RulesV2) == 0`, `len(ChecksV2) == 0`) and matches block $i$'s rendered source against the strict single-line regex `^tar_block\("([A-Za-z0-9_-]+)"\);?\s*$`.
- * **TypeScript (`biscuit-wasm` `getBlockSource(i)`) & Python (`biscuit_auth` `block_source(i)`):** Enforce `block_count() - 1 <= MaxAttenuationBlocks` and match each appended block's source string (`i >= 1`) against the identical regex `^tar_block\("([A-Za-z0-9_-]+)"\);?\s*$`, rejecting any block with multiple lines, rules, checks, or non-string terms before building an authorizer.
- * **Bounds enforced by `api.ValidateTaskAuthorizationRule` and both SDKs:**
- * `MaxAttenuationBlocks = 8`
- * `MaxTARBytes = 4096` (serialized protobuf bytes per block, well within the 64 KiB `AuthFrame` reader limit)
- * `MaxRulesPerTAR = 16`
- * `MaxEntriesPerTARList = 64` (per `allowed_services`, `allowed_tools`, `allowed_methods`, `allowed_paths`, `allowed_permissions`, `allowed_resources`)
- * `MaxTARNameLength = 128` (printable ASCII name syntax)
-3. **How the Verifier Enforces the `TaskAuthorizationRule` Chain:**
- Because the **verifier** (not the token holder) decodes the validated `[]*api.TaskAuthorizationRule` slice from the token:
- * The verifier evaluates each `TaskAuthorizationRule` directly in Go/TS/Python against the verified `RequestContext` (`service`, `method`, `path`, `mcp_tool`, `time`).
- * **Result:** Zero attacker-authored Datalog ever runs in the Datalog VM, zero possibility of drift between SAM's PEP decision and the `TaskAuthorizationRule` forwarded to Cloud STS, and single-pass extraction of the `TaskAuthorizationRule` chain.
-
----
-
-### 3.2 Issue 3b Fix: Strictly Positive Allow-List Polarity (Intersection Semantics)
-
-To avoid polarity bugs when chaining multiple attenuation hops ($\text{Authority} \cap \text{TAR}_1 \cap \text{TAR}_2$), SAM's `TaskAuthorizationRule` in [`api/sam.proto`](file:///usr/local/google/home/aojea/src/sam/api/sam.proto) uses **strictly positive allow-lists**:
-
-```protobuf
-// TaskAuthorizationRule narrows a credential's authority for a specific task or
-// sub-agent hop. Across multiple appended blocks (1..k), semantics are strict
-// set intersection (logical AND): a request is permitted only if it is allowed
-// by the standing mesh policy AND is before every block's expire_time AND
-// matches at least one TaskRule in EVERY appended TaskAuthorizationRule block.
-message TaskAuthorizationRule {
- string name = 1;
- string display_name = 2;
- // Positive allow-list of rules for this hop. Empty rules list denies everything.
- repeated TaskRule rules = 3;
- // Optional shorter expiration for this task hop. Effective token expiry is
- // the minimum across the authority block's expiration() fact and every
- // appended block's expire_time.
- google.protobuf.Timestamp expire_time = 4;
-}
-
-message TaskRule {
- string description = 1;
-
- // Allowed mesh services (e.g., "mcp://bigquery", "inference://gemini.*",
- // "egress://bigquery.googleapis.com"). Uses the dot-anchored grammar of
- // api.ValidateServiceFormat ("*", "<type>://*", "<type>://*.<suffix>",
- // "<type>://<prefix>.*", "<type>://<exact>"). Required (non-empty).
- repeated string allowed_services = 2;
-
- // Optional operation-level allow-list. If set, the request must also match
- // the specified MCP tools, HTTP methods/paths, or cloud permissions.
- TaskOperation operation = 3;
-
- // Optional allowed upstream resource names (e.g. CRM resource prefixes
- // "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026").
- // Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.
- repeated string allowed_resources = 4;
-}
-
-message TaskOperation {
- // Allowed MCP tool names (enforced by the PEP on mcp:// tools/call).
- repeated string allowed_tools = 1;
- // Allowed HTTP methods (e.g. ["GET", "POST"]), validated with httpMethodSyntax.
- repeated string allowed_methods = 2;
- // Allowed HTTP path patterns ("/exact" or "/prefix/*"), validated with
- // validateHTTPGrantPath.
- repeated string allowed_paths = 3;
- // Allowed cloud IAM permissions (e.g. "bigquery.googleapis.com/datasets.get").
- // Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.
- repeated string allowed_permissions = 4;
-}
-```
-
-#### Per-Service-Type PEP Matching Semantics
-
-Within a single `TaskAuthorizationRule`, a request matches if it satisfies **at least one** `TaskRule`. Across blocks $1 \dots k$, the request must match **every** `TaskAuthorizationRule` block AND have `now < block.expire_time` whenever `expire_time` is set (fail-closed if `now` is unset or `>= expire_time`):
-
-| Service Type | `allowed_services` | `operation.allowed_tools` | `operation.allowed_methods` & `allowed_paths` | `operation.allowed_permissions` & `allowed_resources` |
-| :--- | :--- | :--- | :--- | :--- |
-| **`mcp://<name>`** | Enforced on stream handshake & HTTP | Enforced on `tools/call` (`params.name`). At stream open (`initialize`, `tools/list`), tool name is not yet present so `allowed_tools` does not block opening the stream. | Enforced only if the rule sets `allowed_methods` / `allowed_paths` (a raw stream has no HTTP facts, so a rule with HTTP constraints denies non-HTTP streams). | Ignored by wire PEP (`CloudTokenExchanger` only). |
-| **`inference://<name>`**, **`a2a://<name>`** | Enforced on HTTP request | If non-empty on a rule, that rule requires an MCP tool name and therefore does not match a plain HTTP request. | Enforced against request `Method` and `Path` when non-empty. | Ignored by wire PEP. |
-| **`egress://<name>`** | Enforced on HTTP request & TCP `CONNECT` | Same as above (must be empty for an HTTP/TCP rule to match). | Enforced against request `Method` and `Path` when non-empty (a TCP `CONNECT` tunnel has `Method: "CONNECT", Path: ""`, so any rule with `allowed_paths` denies a tunnel). | Intersected across blocks $1 \dots k$ and translated by `CloudTokenExchanger` at egress. |
-| **`system://<name>`** | Enforced on stream handshake | Enforced if a tool call is made. | Same as `mcp://`. | Ignored by wire PEP. |
-
-* **How Multi-Hop Narrowing Works (CUJ 3):**
- * **Hop 1 (Orchestrator $\rightarrow$ Analytics Agent):** Appends `TAR_1` with `allowed_paths: ["/bigquery/v2/projects/my-proj/datasets/sales_2026/*"]`, `allowed_resources: ["//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/*"]`, and `allowed_permissions: ["bigquery.googleapis.com/datasets.get", "bigquery.googleapis.com/tables.get", "bigquery.googleapis.com/tables.getData"]`.
- * **Hop 2 (Analytics Agent $\rightarrow$ Sub-Agent):** Appends `TAR_2` with `allowed_paths: ["/bigquery/v2/projects/my-proj/datasets/sales_2026/tables/q1/*"]`, `allowed_resources: ["//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/tables/q1"]`, and `allowed_permissions: ["bigquery.googleapis.com/tables.getData"]`.
- * Both SAM PEPs and the Cloud STS adapter compute the **intersection** ($\text{TAR}_1 \cap \text{TAR}_2$), which cleanly narrows access to `tables.getData` on `tables/q1` only.
-* **Where Inversion Happens:** If a downstream cloud API (such as Google's internal TAR spec) uses a `DENY`-with-`excludedPermissions` wire format, the **Google Cloud STS Adapter** in `EgressService` computes the intersection of the allow-lists across blocks $1 \dots k$ and writes that intersected allow-list into Google's `excludedPermissions` / `excludedResources` fields.
-
----
-
-### 3.3 Issue 3c Fix: Subject vs. Actor (`actor_node`) & Stateless Control-Plane Exchange
-
-When a `sam-node` exchanges a workload's or user's credential on their behalf, the resulting Biscuit must distinguish **who owns the transport channel (the actor node)** from **whose identity is being exercised (the subject)**, matching RFC 8693 (`sub` vs. `act`):
-
-1. **Direct Member Biscuit (minted at `/enroll` or `/register` for a node or native SDK peer):**
- * Authority facts: `node("<peer_id>")`, `client_peer_id("<peer_id>")`, `user("<subject>")`, `role("<role>")`, `expiration(<time>)`.
-2. **Delegated Session Biscuit (minted at stateless `POST /token/exchange` on the Control Plane):**
- * Authority facts:
- * `client_peer_id("<origin_sam_node_peer_id>")` — satisfies transport replay defense (`connection_peer_id == client_peer_id`) so only that `sam-node` can present the token over libp2p.
- * `actor_node("<origin_sam_node_peer_id>")` — names the channel for the audit log, for `act.sub` in the border JWT (section 3.5) and for `attributes["sam"].actor_node` (section 5.6). It grants nothing: no baseline rule and no policy binding reads it.
- * `user("<caller_subject>")`, `email("<caller_email>")`, `group("<caller_group>")`, `role("<caller_role>")` — resolved from the **caller's `subject_token`**, never from the `sam-node`'s own roles!
- * **No `node()` fact.** `node:<peer_id>` is a policy binding member (`api.BindingMemberPrefixes`), rendered as `role($r) <- node("<peer_id>")`. A delegated token that carried `node("<origin_sam_node_peer_id>")` would attach the origin node's roles to the subject.
- * **How verifiers bind each kind:** the Datalog replay check (`check if client_peer_id($id), connection_peer_id($id)`) is the transport binding for both kinds. It reads authority facts only, so a `client_peer_id` in an appended block never satisfies it. [`RequireAuthorityBinding`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go#L118-L131) on `node()` remains the check for an identity token presented in the peer handshake (`VerifyBiscuitAndGetExpiry`, the SDKs' `verifyPeerBiscuit`). For a request token, `SamNode.Authorize` binds on `client_peer_id` in the authority block, because a delegated token has no `node()` fact.
- * **Why `POST /token/exchange` is Separate from `POST /register`:**
- * `/register` is for **node enrollment**: it persists a node record (`SaveNode`, `SaveUser`) in the Control Plane store.
- * `POST /token/exchange` is **100% stateless on the Control Plane**: it authenticates the requesting `sam-node` (via its `Authorization: Bearer <node-biscuit>` + `peer_id` challenge PoP), verifies the presented `subject_token` (OIDC JWT, K8s projected SA JWT, or SPIFFE JWT-SVID), resolves the subject's roles against the in-memory policy cache, and signs a short-lived Delegated Session Biscuit (TTL = `min(subject_jwt.exp, MaxSessionTTL)`). It performs **zero database writes**, scaling to high-frequency token exchanges (e.g., 5-minute JWT-SVIDs or 1-hour K8s SA tokens) with per-node rate limiting.
-
-### 3.4 Token Sealing (`b.Seal()`) & Revocation of Offline Attenuations
-
-1. **Sealing Leaf Tokens (`b.Seal()`):**
- When `sam-node` or an orchestrator hands an attenuated Task Biscuit to an untrusted leaf sandbox (e.g. `docker sbx` or a K8s `Sandbox` pod), it calls `attenuatedBiscuit.Seal()` (`biscuit-go` native `Seal()`), which discards the ephemeral next-block private key and replaces it with a single signature. A sealed token cannot have any further blocks appended by the sandbox.
-2. **Revocation of Offline-Attenuated Tokens:**
- Because offline attenuations never touch the Control Plane, how are they revoked?
- * **Root-Prefix Revocation (`RevocationIds()[0]`):** In Biscuit, `b.RevocationIds()` returns a slice where index `0` is deterministic for the **authority block**, and index $i$ covers block $i$. Therefore, revoking the root session or banning the subject/node at the Control Plane revokes `RevocationIds()[0]`, which instantly invalidates **every offline-attenuated child token derived from it** across the entire mesh.
- * **Local Task Revocation at the Gateway:** When an orchestrator finishes a task before its short TTL expires, it can call `POST /oauth/revoke` (RFC 7009) on the origin `sam-node` with the child token, which caches `RevocationIds()[last]` in the node's local revocation LRU until the token's `expire_time`.
-
-### 3.5 Two-Token Model: The Control Plane as OIDC Issuer
-
-External parties do not understand Biscuits, and SAM must not forward a caller's token to a third party (the MCP specification forbids it, and it would defeat attenuation). The border therefore translates in both directions: platform credential $\rightarrow$ Biscuit at the inbound border (section 3.3), Biscuit $\rightarrow$ short-lived JWT $\rightarrow$ destination credential at the outbound border (section 5). For the outbound half the control plane becomes an OIDC issuer. Today it is an OIDC client only; discovery and JWKS documents exist in test mocks alone.
-
-| Element | Decision |
-| :--- | :--- |
-| Signing key | ES256. Google and AWS federation accept RS256 and ES256 only, not EdDSA; the Ed25519 root key stays for Biscuits. Stored in a KMS or HSM where available; rotated with overlap and `kid`. |
-| Discovery | `/.well-known/openid-configuration` and `/jwks` served by the control plane. For a control plane that is not reachable from the cloud, the operator uploads the JWKS to the provider (Google accepts up to 8 uploaded keys per pool provider). |
-| Mint endpoint | `POST /sts/token` (protobuf, mesh surface): request = Biscuit, destination name; response = JWT, `expire_time`. The control plane verifies the Biscuit and the full `tar_block` chain before minting, exactly as a PEP would, and logs the crossing. |
-| Claims | `iss` = control plane URL; `sub` = the SAM principal (`email`, or `issuer#subject` for workloads); `act` = `{ "sub": "<egress node peer_id>" }`; `aud` = the destination's audience from `EgressDestination` (one per destination, never shared); `sam_roles` = the subject's mesh roles as a JSON array, from the `role()` facts of the authority block, mapped to `google.groups` for `principalSet` bindings; `sam_task` = the innermost `TaskAuthorizationRule.name`, for the audit log; `exp` = minutes. |
-| Holder input | Nothing a holder writes into an appended block reaches the cloud except `sam_task`, which grants nothing. Every claim the cloud binds on (`sub`, `sam_roles`, `act`) comes from the authority block the control plane signed. The JWT carries no task-class claim: cloud IAM bindings are additive, so a class chosen by the holder would select grants rather than narrow them (section 5.5). |
-| Caching | The egress node caches the JWT per Biscuit digest for its lifetime and the destination credential by the same key, so the control plane is off the hot path. |
-| Keys never leave the control plane | Nodes hold nothing a cloud trusts. The control plane is the single issuer and the single audit point for border crossings, which matches the existing rule that the control plane is the authority and the node is the channel. |
-
-Signing an ES256 JWT needs `crypto/ecdsa`, `encoding/json` and `encoding/base64` only; no new dependency.
-
----
-
-## 4. Mesh, Gateway, & MCP Integration Architecture
-
-### 4.1 First-Class `ext_authz` PDP & RFC 8693 STS for Existing Gateways (`agentgateway`, Istio, Envoy)
-
-In environments that already run **agentgateway**, **Istio**, **Agent Router (Envoy AI Gateway)**, or **kgateway**, traffic already flows through those proxies. `sam-node` integrates with them as an **External Authorizer (`ext_authz`)** and **RFC 8693 Token Service**:
-
-```mermaid
-sequenceDiagram
- autonumber
- participant Caller as Agent Workload<br/>(Istio / agentgateway client)
- participant GW as Existing Gateway<br/>(agentgateway / Istio Envoy)
- participant SamPDP as sam-node<br/>(ext_authz PDP + RFC 8693 STS)
- participant Upstream as Upstream MCP / LLM / Cloud API
-
- Caller->>GW: 1. Request (mTLS SPIFFE XFCC or Bearer Token)
- GW->>SamPDP: 2. Envoy ext_authz CheckRequest<br/>(Headers, Method, Path, XFCC / Source.Principal, MCP Tool)
- Note over SamPDP: 3. Authenticate Subject:<br/>• If Task Biscuit: verify authority + TAR blocks<br/>• If XFCC / JWT: exchange/verify against mesh policy<br/>4. Broker Upstream Credential (if egress target):<br/>• Exchange TAR via CloudTokenExchanger
- SamPDP-->>GW: 5. CheckResponse: OK<br/>+ Inject Headers:<br/> Authorization: Bearer <Upstream-Cloud-or-Mesh-Token><br/> X-Sam-Principal: <Verified-Subject><br/> X-Sam-Task-Id: <Task-Name>
- GW->>Upstream: 6. Forward request with injected headers
-```
-
-#### Three Standard Interfaces Exposed by `sam-node`:
-1. **Envoy `ext_authz` Server (`--ext-authz-addr` / socket):**
- * Evaluates standing mesh Datalog policy + any `TaskAuthorizationRule` blocks on the request.
- * Accepts **Channel Identity as Subject**: when `ext_authz` arrives from a trusted local Envoy/Istio proxy, `sam-node` reads the verified SPIFFE ID from `AttributeContext.Source.Principal` or `X-Forwarded-Client-Cert` (XFCC) when no Bearer token is present.
- * Injects the brokered upstream credential (`Authorization: Bearer ...`) or mesh headers (`X-Sam-Biscuit`) back into Envoy's upstream request so `sam-node` does not have to sit in the data path when Envoy/`agentgateway` is already proxying.
- * **`ext_proc` server, the body-aware form of the same role.** With the vendored protos and the standard-library gRPC transport from section 5.6, `sam-node` can also serve `envoy.service.ext_proc.v3.ExternalProcessor` to a gateway. `ext_authz` decides on headers (a buffered body is optional and bounded); `ext_proc` sees the body, so a TAR rule on an MCP tool name, which travels in the JSON-RPC body, is enforced at the gateway, and the brokered credential is injected on the upstream request after the body has passed inspection. One gateway filter then covers authorization, task enforcement and credential brokering. Whether to ship the server side with the first release is section 8, item 20.
-2. **Strict RFC 8693 Token Exchange (`POST /oauth/token`):**
- * Accepts standard `application/x-www-form-urlencoded` requests:
- * `grant_type=urn:ietf:params:oauth:grant-type:token-exchange`
- * `subject_token` & `subject_token_type` (`jwt`, `id_token`, `access_token`, or `urn:sam-mesh:params:oauth:token-type:biscuit`)
- * `actor_token` & `actor_token_type` (optional, for multi-hop delegation)
- * `resource` / `scope` / `options` (serialized `TaskAuthorizationRule` JSON)
- * Returns standard RFC 8693 JSON (`access_token`, `issued_token_type: "urn:sam-mesh:params:oauth:token-type:biscuit"`, `token_type: "Bearer"`, `expires_in`).
- * **Zero-code compatibility with `agentgateway`:** `agentgateway`'s built-in RFC 8693 backend token exchange policy points directly at `http://sam-node:8080/oauth/token`.
-3. **MCP OAuth 2.1 Alignment (2026-07-28 Spec):**
- * Standard MCP clients (Claude Code, Cursor, Gemini CLI) implement **OAuth 2.1 Authorization Code + PKCE** with RFC 9728 Protected Resource Metadata (`/.well-known/oauth-protected-resource`) and RFC 8707 `resource` indicators—they do **not** run RFC 8693 on their own.
- * Therefore:
- * **`sam-node` is the OAuth 2.1 Resource Server:** On `401 Unauthorized`, `sam-node` serves `/.well-known/oauth-protected-resource` naming the **SAM Control Plane** in `authorization_servers`.
- * **`sam-control-plane` is the OAuth 2.1 Authorization Server:** It exposes `/.well-known/oauth-authorization-server`, `/oauth/authorize`, and `/oauth/token` (Authorization Code + PKCE, delegating user login to the configured OIDC provider and honoring RFC 8707 `resource` indicators to scope the initial TAR block), returning a **SAM Task Biscuit** as the `access_token`.
- * **MCP Anti-Passthrough Compliance:** The MCP specification forbids passing client-issued MCP access tokens directly to downstream APIs. SAM complies strictly: the client's SAM Task Biscuit is consumed and stripped at the SAM PEP (`X-Sam-Biscuit` is never sent to upstream backends) and exchanged via `CloudTokenExchanger` when calling external cloud APIs.
-
----
-
-### 4.2 Gateway & Environment Integration Matrix
-
-| Environment / Stack | Who Owns the Data Path | How Caller Identity Arrives | How SAM Enforces & Downscopes |
-| :--- | :--- | :--- | :--- |
-| **1. `agentgateway` / Envoy AI Gateway / kgateway** | `agentgateway` / Envoy | JWT or MCP OAuth token | `agentgateway` calls `sam-node` via **RFC 8693 `/oauth/token`** or **Envoy `ext_authz`**, or routes cross-cluster MCP/A2A traffic through `sam-node` mesh egress. |
-| **2. Istio (Sidecar or Ambient Waypoint)** | Istio Envoy (`ztunnel` / waypoint) | mTLS SPIFFE SVID (`source.principal` / XFCC) + optional Bearer Task Biscuit | Istio `AuthorizationPolicy (action: CUSTOM)` calls `sam-node` **`ext_authz`**, which authorizes the SPIFFE principal + TAR and injects upstream credentials. |
-| **3. Brownfield K8s / Cloud Run / VM (No Mesh Gateway)** | `sam-node` HTTP Facade (`/mcp`, `/v1/*`, `/sam/*`) | Workload sends `Authorization: Bearer <K8s-or-GCP-JWT>` on `/mcp` or `/v1/*` (or `X-Sam-Authentication` on `/sam/*`) | `sam-node` `withAuth` exchanges the JWT via Control Plane `POST /token/exchange` (cached) and forwards the Delegated Biscuit across the SAM mesh. |
-| **4. Greenfield Python / Node.js / Browser App** | Embedded SAM SDK (`sam-mesh` / `@sam-mesh/sdk`) | Enrolled `MemberCredential` or delegated Task Biscuit | App calls `session.attenuate(tar)` offline in memory before each task or sub-agent hop and dials mesh providers directly over libp2p. |
-
-> **Important Note on Mode B (`Authorization: Bearer <JWT>` Transparent Exchange):**
-> As established in [`internal/node/sidecar.go:L80-84`](file:///usr/local/google/home/aojea/src/sam/internal/node/sidecar.go#L80-L84), on `/sam/{peer}/{type}/{svc}/...` the `Authorization` header is reserved exclusively for the destination service's own credential and passes through untouched. Transparent JWT-to-Biscuit exchange on `Authorization` applies **only** to `/mcp` and `/v1/*` (where `allowAuthorizationFallback=true`). Callers of `/sam/...` pass their SAM Biscuit or JWT in `X-Sam-Authentication`.
-
----
-
-## 5. Cloud Provider Egress: Credential Broker & `CloudTokenExchanger`
-
-[`EgressService`](file:///usr/local/google/home/aojea/src/sam/internal/node/egress.go) already strips the caller's `Authorization` and injects a credential read from the node's secrets directory on every request (`EgressService.credential()`). This design turns that single static path into a **credential broker** selected per destination in the control-plane policy, and decouples SAM's `api.TaskAuthorizationRule` from any single cloud's wire format through a pluggable `CloudTokenExchanger`. Google's `urn:ietf:params:oauth:token-type:task_access_token` (`iam.v3.TaskAuthorizationRule`) is an internal specification (`go/session-access-boundary-policy`) and not a public API as of 2026-10-03; nothing in the core schema depends on it.
-
-### 5.1 Broker Configuration in `EgressDestination`
-
-None of these fields is a secret, which keeps the rule that secret material never travels through the API:
-
-```protobuf
-message EgressDestination {
- string name = 1;
- string target_url = 2;
- repeated string served_by = 3;
- CredentialBroker broker = 4;
- // Content inspection the egress node applies (section 5.6). Destination
- // policy: a TAR cannot disable it or choose another inspector.
- Inspection inspection = 5;
- // HTTP (default): the node terminates TLS, brokers the credential and
- // inspects. TCP: a named CONNECT tunnel, L4 policy only (section 5.7).
- EgressMode mode = 6;
- // TCP mode: destination ports a tunnel may open. Empty denies every tunnel.
- repeated uint32 ports = 7;
- // Keep the destination hostname in Host when target_url is an operator
- // inspection chain that forwards to the real host (section 5.6, tier 4).
- bool preserve_host = 8;
- // Forward X-Sam-Principal, X-Sam-Roles and X-Sam-Task to target_url.
- // Only for an operator chain; the node strips them for a real destination.
- bool forward_context = 9;
-}
-
-enum EgressMode {
- EGRESS_MODE_HTTP = 0;
- EGRESS_MODE_TCP = 1;
-}
-
-// Inspection lists the inspectors the egress node runs, in order; the first
-// block wins. Inspectors run before the broker injects the destination
-// credential, so a processor never sees it.
-message Inspection {
- repeated Inspector inspectors = 1;
-}
-
-message Inspector {
- oneof kind {
- ModelArmor model_armor = 1;
- ExtProc ext_proc = 2;
- }
-}
-
-// ModelArmor calls sanitizeUserPrompt / sanitizeModelResponse directly over
-// HTTPS. Model Armor is reached as an egress destination with an
-// oidc_federation broker, so no credential is stored for it.
-message ModelArmor {
- // projects/P/locations/L/templates/T. One template per destination; a
- // destination that needs another template is declared as another
- // EgressDestination.
- string template = 1;
- // BUFFERED: the whole response is inspected before release and may be
- // rewritten. REQUEST_ONLY: prompts are inspected, responses pass.
- ResponseInspection response = 2;
- // Default false: an unreachable Model Armor fails the request.
- bool fail_open = 3;
- google.protobuf.Duration timeout = 4;
-}
-
-enum ResponseInspection {
- RESPONSE_INSPECTION_BUFFERED = 0;
- RESPONSE_INSPECTION_REQUEST_ONLY = 1;
-}
-
-// ExtProc runs an Envoy external processor (envoy.service.ext_proc.v3
-// ExternalProcessor) over one bidirectional gRPC stream per request. Field
-// names follow Envoy's ext_proc filter configuration so a processor's
-// settings carry over unchanged.
-message ExtProc {
- // host:port, or unix:/path for a processor on the same host.
- string target = 1;
- // Names in the node's secrets directory for mTLS to the processor: the CA
- // bundle and the client certificate with its key. Never values.
- string ca = 2;
- string client_certificate = 3;
- ExtProcProcessingMode processing_mode = 4;
- // Let the processor change the mode mid-request (Envoy allow_mode_override).
- bool allow_mode_override = 5;
- // Per-message deadline; 200ms when unset, as in Envoy.
- google.protobuf.Duration message_timeout = 6;
- // Default false: a processor error fails the request (Envoy failure_mode_allow).
- bool failure_mode_allow = 7;
- // Upper bound for BUFFERED and BUFFERED_PARTIAL bodies.
- uint32 max_buffered_bytes = 8;
-}
-
-message ExtProcProcessingMode {
- enum HeaderMode { HEADER_MODE_DEFAULT = 0; SEND = 1; SKIP = 2; }
- enum BodyMode { NONE = 0; STREAMED = 1; BUFFERED = 2; BUFFERED_PARTIAL = 3; FULL_DUPLEX_STREAMED = 4; }
- HeaderMode request_header_mode = 1;
- HeaderMode response_header_mode = 2;
- BodyMode request_body_mode = 3;
- BodyMode response_body_mode = 4;
- HeaderMode request_trailer_mode = 5;
- HeaderMode response_trailer_mode = 6;
-}
-
-message CredentialBroker {
- oneof kind {
- // Name of a file in the node's secrets directory ("TOKEN" or "user:pass").
- string static_secret = 1;
- OIDCFederation oidc_federation = 2;
- AWSAssumeRole aws_assume_role = 3;
- // The node's own platform identity (GKE Workload Identity, instance
- // metadata). Only for nodes that run inside the provider; see section 2.3.
- PlatformIdentity platform_identity = 4;
- }
-}
-
-// OIDCFederation exchanges the control plane's JWT (section 3.5) at a provider STS.
-message OIDCFederation {
- // Google: https://sts.googleapis.com/v1/token. Other providers: their RFC 8693 endpoint.
- string token_endpoint = 1;
- // The audience the provider expects, e.g. the Google workload or workforce
- // pool provider resource name. One per destination.
- string audience = 2;
- // Optional service account to impersonate when the API does not accept the
- // federated principal directly (Google iamcredentials.generateAccessToken).
- string impersonate = 3;
- // OAuth scopes requested for the destination credential; the TAR may narrow
- // them further, never widen them.
- repeated string scopes = 4;
-}
-
-message AWSAssumeRole {
- string role_arn = 1;
- // Session policy template; the adapter intersects it with the TAR.
- string session_policy = 2;
-}
-
-message PlatformIdentity {
- repeated string scopes = 1;
-}
-```
-
-```go
-// CloudTokenExchanger translates a verified SAM principal and its intersected
-// TaskAuthorizationRule chain into a downscoped upstream credential.
-type CloudTokenExchanger interface {
- Exchange(ctx context.Context, principal string, rules []*api.TaskAuthorizationRule) (bearerToken string, expiry time.Time, err error)
-}
-```
-
-### 5.2 Flow at the Egress Node
-
-```mermaid
-sequenceDiagram
- autonumber
- participant Origin as Origin sam-node / SDK agent
- participant Egress as Egress sam-node (egress://bigquery.googleapis.com)
- participant CP as SAM Control Plane (OIDC issuer)
- participant STS as Provider STS (sts.googleapis.com / sts.amazonaws.com)
- participant API as Destination API
-
- Origin->>Egress: libp2p stream GET /egress/bigquery.googleapis.com/bigquery/v2/...<br/>AuthFrame.biscuit = <Task Biscuit (authority + tar_block 1..k)>
- Note over Egress: 1. Authorize: CP signature, actor binding,<br/>standing policy for the subject, TAR chain on<br/>service(), host(), port(), method(), path()
- Egress->>CP: 2. POST /sts/token { biscuit, destination } (cache miss on biscuit digest)
- Note over CP: Verifies the Biscuit and TAR chain again;<br/>mints ES256 JWT: sub=principal, act=egress node,<br/>aud=destination audience, sam_task, exp=minutes
- CP-->>Egress: 3. JWT
- Egress->>STS: 4. RFC 8693 exchange: subject_token=JWT<br/>(Google: pool provider; AWS: AssumeRoleWithWebIdentity + session Policy from TAR)
- STS-->>Egress: 5. Short-lived destination credential (cached by biscuit digest)
- Egress->>API: 6. Request with the destination credential; TLS originated here
- Note over API: 7. Provider IAM evaluates the federated principal's standing grants<br/>(and the session policy on AWS)
- API-->>Egress: 200 OK
- Egress-->>Origin: 200 OK
-```
-
-### 5.3 Adapters
-
-1. **Google Cloud (`oidc_federation` $\rightarrow$ `sts.googleapis.com/v1/token`):**
- * **Public today:** the control-plane JWT is exchanged through a **Workload Identity Pool** (workload principals) or a **Workforce Identity Pool** (human principals) whose OIDC provider is the SAM control plane. Attribute mapping `google.subject = assertion.sub`, `google.groups = assertion.sam_roles`, `attribute.actor = assertion.act.sub`; an attribute condition restricts `act.sub` to enrolled egress nodes. Optional `impersonate` for APIs that need a service account; `scopes` narrowed by the TAR; CAB `accessBoundary` for `storage.googleapis.com`.
- * **When the task token API is public:** the adapter additionally computes $\text{TAR}_1 \cap \dots \cap \text{TAR}_k$ over `allowed_permissions` and `allowed_resources` and emits the provider's wire form (inverting to `excludedPermissions` / `excludedResources` if that is what the API expects).
-2. **AWS (`aws_assume_role` $\rightarrow$ `AssumeRoleWithWebIdentity`):**
- The account trusts the control plane as an IAM OIDC identity provider. The adapter compiles the intersected chain into an inline **session policy** (`Effect: Allow`, `Action` from `allowed_permissions`, `Resource` from `allowed_resources`) intersected with the template; AWS evaluates role policy $\cap$ session policy, which is genuine per-task downscoping today. Role chaining is capped at one hour, so a sub-agent hop re-assumes from the egress node instead of chaining.
-3. **API-key and client-credential destinations (`static_secret`):**
- The existing behaviour: the node injects the stored secret. Gemini Developer API, OpenAI, Anthropic, GitHub tokens, and third-party MCP servers or `a2a://` agents that do not federate with the SAM issuer.
-4. **Generic RFC 8693 / Entra OBO (`oidc_federation` with another `token_endpoint`):**
- Maps `allowed_services` and `allowed_permissions` to OAuth `resource` and `scope`. Entra OBO delegates for user principals only; app-only calls use client credentials.
-
-### 5.4 Per-Destination Narrowing, Honestly Stated
-
-Where each layer enforces differs by destination class. The design must not promise per-task cloud IAM where the provider has no mechanism for it.
-
-| Destination class | Border credential | Per-task narrowing available today | Residual gap |
-| :--- | :--- | :--- | :--- |
-| Google Cloud APIs (BigQuery, Vertex AI, Cloud Storage) | Control-plane JWT federated through a workload or workforce pool; optional impersonation with narrowed `scope` | Mesh PEP on host, method and path (BigQuery REST paths carry project, dataset and table; Vertex paths carry the model), OAuth scopes, CEL attribute conditions, `principalSet` bindings on `google.groups` (the subject's mesh roles), CAB for Cloud Storage | A body-level reference (SQL in `jobs.insert` naming another table) is bounded by the principal's standing IAM, not by the task, until a task token API is public |
-| AWS | Control-plane JWT, `AssumeRoleWithWebIdentity` | Session policy compiled from the TAR: fine-grained, intersection semantics | One-hour role chaining limit; packed session policy size limit |
-| API-key services (Gemini Developer API, OpenAI, Anthropic, GitHub tokens) | Static secret from the node's secrets directory | Mesh PEP only: path (which carries the model), method, TTL | The key cannot be downscoped; a leaked key is the full key |
-| External agents (`a2a://`) and third-party MCP servers | Control-plane JWT if the party federates with the SAM issuer; otherwise a stored client credential | Mesh PEP plus whatever the party's authorization server supports | Depends on the party |
-
-### 5.5 Rules That Hold the Model Together
-
-1. **The TAR narrows; it never selects.** The broker kind, the role ARN, the service account to impersonate and the audience come from `EgressDestination` in the control-plane policy. A holder-appended block can shrink scopes, paths, methods and lifetime; it can never pick a different credential. Effective authority is IAM ceiling $\cap$ egress policy $\cap$ $\text{TAR}_1 \cap \dots \cap \text{TAR}_k$.
-2. **The signing key stays in the control plane.** The egress node holds nothing a cloud trusts. One control-plane round trip per Biscuit digest, cached for the JWT lifetime, is the price.
-3. **TLS terminates at the egress node for HTTP destinations.** The agent speaks plain HTTP to its local node or through the SDK; the egress node originates TLS to the destination. L7 facts (method, path, model, dataset) are available without a CA inside the sandbox, which the previous architecture required for the same visibility. TCP tunnels (section 5.7) are the exception: the node splices them end to end and sees L4 facts and the SNI only.
-4. **Both layers matter.** The mesh PEP blocks unauthorized callers, services, methods and paths before any STS call is made. Provider IAM enforces what the proxy cannot see, including transitive calls (BigQuery reading Cloud Storage during a query).
-5. **No caller token reaches the destination.** `EgressService` strips `Authorization`, `Cookie` and `X-Sam-*` today; the brokered credential is the only one the destination sees. This is also the MCP anti-passthrough requirement.
-
-### 5.6 Content Inspection at the Egress Node
-
-Operators want to inspect what agents send and receive: prompts and completions for injection, jailbreak and sensitive data; tool-call arguments and results; HTTP payloads in general. Google's products for this are Model Armor (a sanitization API for prompts, responses and supported MCP and A2A payloads, also reachable inline through Service Extensions `ext_proc` on Secure Web Proxy, in Preview), Secure Web Proxy (HTTP(S) with TLS inspection) and Cloud NGFW Enterprise (TLS inspection with threat signatures, no payload rewriting). agentgateway ships a Model Armor guard and a webhook guard. The design uses them; it does not reimplement them.
-
-**Where inspection happens.** Requests travel inside encrypted libp2p streams between the origin node and the egress node; routers relay ciphertext and cannot inspect. The egress node is the point where the request is plaintext and where the subject, the task chain and the destination are all known, and it is the node the operator selected through `served_by`. Inspection is therefore destination policy, configured on `EgressDestination`, executed by the egress node and outside the reach of a TAR: a holder-appended block can narrow what a task may do and can never turn inspection off or pick a different inspector. The origin node sees plaintext as well, but it may be a developer laptop; an operator who wants inspection at the origin runs an inspected node as the origin.
-
-**Four tiers, combinable per destination:**
-
-1. **Policy facts (built in).** `host()`, `port()`, `method()`, `path()` and the MCP tool name from `tools/call`. Google API paths carry the model (`.../models/M:generateContent`), the project, the dataset and the table, so a large part of what operators call inspection is a path rule. This tier is the PEP and runs on every request.
-2. **Model Armor, called directly (`inspectors[].model_armor`).** For payload shapes the node understands (Gemini `generateContent`, the OpenAI-compatible chat shape served by the `/v1` facade, MCP `tools/call` arguments and results, A2A messages) the egress node calls `sanitizeUserPrompt` on the request and `sanitizeModelResponse` on the response over HTTPS with the standard library. The template is chosen per destination. A finding blocks the request with `403` and a `Proxy-Status` reason; a Sensitive Data Protection de-identification result replaces the text. Streamed responses are handled in `BUFFERED` mode (inspected whole, then released; higher latency, no incremental display) or `REQUEST_ONLY` mode (prompt inspected, response passed), chosen per destination; Model Armor's bidirectional streaming methods are a follow-up (section 8, item 22). The inspector is unreachable: the request fails unless `fail_open` is set.
-3. **Envoy `ext_proc` processors (`inspectors[].ext_proc`), the standard interface.** The egress node is the client side of `envoy.service.ext_proc.v3.ExternalProcessor`: one bidirectional gRPC stream per request, carrying `request_headers`, `request_body`, `request_trailers`, `response_headers`, `response_body` and `response_trailers` according to the processing mode; the processor answers with header and body mutations, an `immediate_response` that blocks, or a mode override. Any processor written for Envoy, agentgateway or Google Service Extensions callouts runs unchanged against `sam-node`: a customer's own DLP or guardrail service, a vendor product that exposes `ext_proc`, or the Service Extensions callout SDK examples. The node fills `ProcessingRequest.attributes["sam"]` with `principal`, `roles`, `actor_node`, `task`, `service` and `destination`, so the processor applies per-task policy without SAM headers on the wire. Body modes map to Envoy's: `BUFFERED` for whole-body decisions and rewriting (bounded by `max_buffered_bytes`), `STREAMED` for chunked bodies such as SSE where the processor can stop a stream but cannot rewrite what was already forwarded, `FULL_DUPLEX_STREAMED` for processors that rewrite chunks as they pass. A processor runs before the broker injects the destination credential and after `X-Sam-*` and the caller's `Authorization` are stripped, so it sees neither token; its mutations to `Authorization`, `Host`, `:authority` and `X-Sam-*` are refused, which keeps the invariant that an inspector narrows or blocks and never selects a credential or a destination. `failure_mode_allow` defaults to false; `message_timeout` defaults to 200ms; mTLS to the processor uses names from the node's secrets directory.
-4. **Operator inspection chain.** `target_url` points at the operator's inspection proxy with `preserve_host` set: agentgateway with its Model Armor or webhook guard, or Secure Web Proxy in explicit mode. The egress node hands over plaintext HTTP with the brokered credential already injected; the chain inspects and forwards to the real host. With `forward_context`, the node also sends `X-Sam-Principal`, `X-Sam-Roles` and `X-Sam-Task`, so the chain applies per-task policy and the chain's log joins the control plane's. The other form of this tier needs no SAM configuration: the egress node runs in a VPC whose outbound path is Secure Web Proxy next-hop or Cloud NGFW Enterprise with TLS inspection, and the node trusts the inspection CA through `--egress-ca-bundle`. The node is then an ordinary workload to the network inspection product. This tier remains for proxies that are not `ext_proc` servers.
-
-**Dependencies for tier 3: none in the root module.** `ext_proc` is being donated as an independent open-source project, so SAM depends on the protocol and not on Envoy's Go ecosystem. Three decisions keep `go.mod` unchanged:
-
-* **Protos are vendored under `third_party/`, trimmed, not imported.** Google's open-source policy for a `github.com/google` repository places third-party code under `third_party/<project>/` with the upstream `LICENSE` and a `METADATA` file recording name, upstream URL, the pinned version or commit, the license type and every local modification. The repository has no `third_party/` directory today; this is its first entry:
-
- ```
- third_party/envoy/
- LICENSE # Envoy's Apache-2.0, verbatim
- METADATA # upstream github.com/envoyproxy/envoy, commit, local modifications
- README.md # what is vendored, why trimmed, how to refresh
- envoy/service/ext_proc/v3/external_processor.proto
- envoy/extensions/filters/http/ext_proc/v3/processing_mode.proto
- envoy/config/core/v3/base.proto # HeaderValue, HeaderValueOption, HeaderMap, Metadata only
- envoy/type/v3/http_status.proto
- ```
-
- The local modifications, listed in `METADATA`, are: the `validate`, `udpa`, `xds` and deprecation annotation imports and their options removed, `base.proto` reduced to the four messages `ext_proc` references, and `go_package` set to `github.com/google/sam/third_party/envoy/...`. Annotations are options; removing them changes neither field numbers nor the wire format. The proto package names stay `envoy.service.ext_proc.v3` and `envoy.config.core.v3`, because the method path `/envoy.service.ext_proc.v3.ExternalProcessor/Process` and the `Any` type URLs derive from them. `hack/gen-proto.sh` generates the Go code next to the `.proto` files with the `protoc-gen-go` the repository already pins, and `hack/verify-generated.sh` covers them like `api/sam.pb.go`; `protoc-gen-go-grpc` is not needed, since the service is one method path and SAM does not link grpc-go. The generated code needs `google.golang.org/protobuf` only, already a dependency, and the linter and license checks (`hack/lint.sh`, the license-header check) exclude `third_party/`. One constraint: protobuf-go refuses two registrations of the same full name, so if `go-control-plane` ever enters the dependency graph, the vendored copy is replaced by that module. When the donated project publishes under its own package, it is vendored the same way under `third_party/<project>/` and SAM offers both method paths, since a processor answers on exactly one.
-* **gRPC over the standard library.** One bidirectional method needs the gRPC wire protocol, not grpc-go: a `POST` to the method path with `content-type: application/grpc+proto`, `te: trailers` and `grpc-timeout` from the context deadline; a request body streamed through an `io.Pipe` and a response body read as a stream, each a sequence of length-prefixed messages (one flag byte, a four-byte big-endian length, the serialized message); `grpc-status` and `grpc-message` read from the trailers, or from the headers for a trailers-only response. Go's `net/http` HTTP/2 client streams the request body while reading the response and applies HTTP/2 flow control. `Transport.Protocols.SetUnencryptedHTTP2(true)` (Go 1.24 and later; the module is on 1.26) covers processors on `unix:` sockets and plaintext in-cluster addresses; TLS with ALPN `h2` covers the rest. The server side in section 4.1 uses the same pieces (`Server.Protocols.SetUnencryptedHTTP2(true)`, frames flushed with `ResponseController.Flush`, status in HTTP trailers). About three hundred lines, with the risks named and tested: trailers-only responses, deadline propagation, cancellation when either side closes, processors behind gRPC-aware load balancers.
-* **Conformance harness in its own module.** `tests/extproc/` carries its own `go.mod` with grpc-go, `go-control-plane` and a Google Service Extensions callout example, following the pattern `cmd/nano-init` used to keep guest-only dependencies out of the root module, and runs a reference processor against `sam-node` in the integration suite. Being a separate module that imports `go-control-plane`, it also exercises the registration constraint above: the harness and `sam-node` are separate processes, never one binary. The harness depends on modules, not on copied code, so nothing in it belongs under `third_party/`.
-
-Every verdict is logged at the egress node with `sam_task`, destination, tier and finding category. A BigQuery SQL statement is not a prompt; tier 2 does not apply to it, and the statement's reach is bounded by the principal's IAM (section 5.4).
-
-### 5.7 Non-HTTP Protocols
-
-The primary CUJ is HTTP: Google REST APIs, Gemini and OpenAI-compatible inference, MCP Streamable HTTP, A2A. The egress node handles everything else as a named tunnel or not at all.
-
-| Protocol | Handling at the egress node | Brokered credential | Inspection |
-| :--- | :--- | :--- | :--- |
-| HTTP/1.1 and HTTP/2 REST, JSON-RPC (MCP), A2A, SSE | Terminated and proxied | Yes | Tiers 1 to 4 |
-| gRPC | Tunnel mode until HTTP/2 framing and trailers over the mesh stream are verified (section 8, item 18). Google client libraries can select the REST transport instead. | In tunnel mode, no | In tunnel mode, L4 |
-| Raw TCP carrying TLS: Postgres and Cloud SQL, AlloyDB, Redis, Kafka, SSH and git over SSH, mTLS or certificate-pinned destinations | Named `CONNECT` tunnel, L4 policy | No | L4 facts and SNI at the node; Cloud NGFW Enterprise TLS inspection in the exit VPC (TLS 1.0 to 1.3 over TCP, not HTTP/2 or QUIC) when the agent trusts its CA |
-| UDP, QUIC and HTTP/3, ICMP, raw IP | Not supported | | |
-
-**Named `CONNECT` tunnels.** `EgressDestination.mode = EGRESS_MODE_TCP` with a `ports` allow-list. Two entry points on the local node: the facade accepts `CONNECT name:port` for clients that honour `HTTPS_PROXY` or an SSH `ProxyCommand`, and `sam-node forward egress://pg.internal.example:5432 127.0.0.1:15432` opens a local listener bound to one destination for clients that do not speak `CONNECT` (the Cloud SQL Auth Proxy pattern). The mesh stream carries `method("CONNECT")`, an empty `path()`, `host()` and `port()`; [`RequestContext`](file:///usr/local/google/home/aojea/src/sam/internal/node/middleware.go#L42-L45) already models a tunnel this way and `egress_test.go` already checks that a narrowed grant denies one. Before splicing, the egress node reads the TLS ClientHello and refuses the tunnel when the SNI does not name the destination or when Encrypted Client Hello hides it: the name on the wire must be the name in policy. The node cannot inject a credential into an opaque stream, so a tunnel destination is authenticated with what the agent holds, and the "no cloud credential in the customer environment" property applies to HTTP destinations only. Bytes in each direction, duration and the verdict are audited.
-
-**Dropped with `sam-box`:** `connect-udp` and the virtual DNS. DNS belongs to the platform. HTTP/3 is unnecessary at the egress because the node originates HTTP/1.1 or HTTP/2 toward destinations. MASQUE (RFC 9298 `CONNECT-UDP`, RFC 9484 `CONNECT-IP`) has no standard-library implementation and is deferred until a QUIC-only destination exists.
-
----
-
-## 6. Integration Blueprints
-
-### Blueprint 1: NVIDIA OpenShell (True Zero-Credential Sandbox)
-
-**Context:** NVIDIA OpenShell isolates untrusted agents using Landlock, seccomp, and network namespaces, routing outbound HTTP through an external OpenShell proxy that injects secrets outside the sandbox boundary.
-
-```mermaid
-flowchart LR
- subgraph OpenShell["NVIDIA OpenShell Sandbox (Landlock + seccomp + netns)"]
- Harness["Unmodified Agent Process<br/>(Holds ZERO credentials)"]
- end
- subgraph Host["Host / Orchestrator Boundary"]
- OSProxy["OpenShell Egress Proxy<br/>& Secret Injector"]
- SamNode["Local sam-node Gateway"]
- end
- Mesh(["SAM Mesh & Providers"])
-
- Harness -- "Plain HTTP to sam-node:8080/mcp & /v1" --> OSProxy
- OSProxy -- "Injects X-Sam-Authentication:<br/>Bearer <Sealed-Task-Biscuit>" --> SamNode
- SamNode -- "X-Sam-Biscuit: <Sealed-Task-Biscuit>" --> Mesh
-```
-
-1. **Pre-Task Negotiation:** The orchestrator calls `POST /oauth/token` on `sam-node` with a `TaskAuthorizationRule` and seals the resulting Biscuit (`Seal()`).
-2. **Secret Injection:** The sealed Task Biscuit is registered in OpenShell's proxy secret injector for `sam-node:8080`. The sandboxed process holds **zero credentials** in its environment or filesystem.
-
----
-
-### Blueprint 2: Docker Sandbox (`docker sbx`) & Kubernetes `agent-sandbox` (GKE)
-
-**Context:** In `docker sbx` (local microVM) and Kubernetes `agent-sandbox` (`RuntimeClass: gvisor` or `kata`) without an external secret-injecting proxy, the sandbox container *does* hold a credential (`SAM_TASK_TOKEN` or a K8s projected ServiceAccount JWT) to authenticate to `sam-node`.
-
-**Threat Model & Mitigations When the Sandbox Holds a Token:**
-1. **Sealed Leaf Token (`b.Seal()`):** The orchestrator hands the sandbox a **sealed, task-attenuated Biscuit** (`OPENAI_API_KEY=$SAM_TASK_TOKEN`). The sandbox cannot append blocks or widen permissions.
-2. **Channel Binding (`client_peer_id`):** Because the Biscuit's authority block binds `client_peer_id` to the local/cluster `sam-node`'s `peer_id` (section 3.3), if a prompt-injected agent exfiltrates `$SAM_TASK_TOKEN` to an external attacker, **the attacker cannot use it from another machine or another mesh node**.
-3. **Short Task TTL & Explicit Revocation:** The token is scoped to the single task's services/tools with a short `expire_time` (e.g., 15 minutes) and is revoked at the local `sam-node` (`POST /oauth/revoke`) as soon as the sandbox container exits.
-4. **No `/dev/net/tun` or `nano-init`:** `Sandbox` pods on GKE run cleanly under `RuntimeClass: gvisor` with a standard K8s `NetworkPolicy` allowing egress only to the cluster `sam-node` (or `agentgateway`) Service.
-
----
-
-### Blueprint 3: `agentgateway` / Istio Service Mesh Integration
-
-**Context:** An enterprise Kubernetes cluster already runs **Istio Ambient** (or sidecars) and **agentgateway** for MCP and LLM routing.
-
-1. **Local Cluster Policy + SAM Task Authority:**
- * `agentgateway` is configured with `sam-node`'s `ext_authz` gRPC service (or RFC 8693 backend token exchange at `http://sam-node:8080/oauth/token`).
- * Workloads in the cluster authenticate via Istio mTLS (SPIFFE XFCC) or present a SAM Task Biscuit.
-2. **Multi-Hop Sub-Agent Delegation Across Clusters:**
- * When an orchestrator agent in Cluster A spawns a sub-agent or calls a remote MCP tool in Cluster B, it attenuates its SAM Task Biscuit offline (`tar_block` narrowing `allowed_services` and `allowed_tools` / `allowed_permissions`) and sends the request through `agentgateway` $\rightarrow$ `sam-node`.
- * The remote `sam-node` in Cluster B verifies the Control Plane signature, the standing policy, and every appended `TaskAuthorizationRule` block before forwarding to the MCP server or exchanging via `CloudTokenExchanger`.
-
----
-
-### Blueprint 4: End-to-End Cloud Egress (BigQuery Read-Only Task & Sub-Agent Hop)
-
-**Setup, once per cloud project (no Google credential in the customer environment):**
-* The cloud administrator creates a workload identity pool (workload principals) and, for human principals, a workforce identity pool, each with an OIDC provider whose issuer is the SAM control plane, or whose JWKS is uploaded when the control plane is not reachable from the internet. Attribute mapping: `google.subject = assertion.sub`, `google.groups = assertion.sam_roles`, `attribute.actor = assertion.act.sub`. Attribute condition: `assertion.act.sub` is one of the enrolled egress node peer IDs.
-* IAM grants the ceiling: `roles/bigquery.dataViewer` on `projects/my-proj/datasets/sales_2026` to `principal://iam.googleapis.com/.../subject/[email protected]`, or to `principalSet://.../group/analyst` for every subject the mesh policy binds to the `analyst` role.
-* The mesh policy declares the destination:
- ```yaml
- egress:
- - name: bigquery.googleapis.com
- served_by: ["egress-eu"]
- broker:
- oidc_federation:
- token_endpoint: https://sts.googleapis.com/v1/token
- audience: //iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/sam/providers/sam-cp
- scopes: ["https://www.googleapis.com/auth/bigquery.readonly"]
- ```
-
-1. **Hop 1 (Orchestrator $\rightarrow$ Analytics Agent):**
- Orchestrator attenuates its Biscuit with `TAR_1`:
- ```json
- {
- "name": "tasks/session-bq-read-sales",
- "rules": [
- {
- "allowed_services": ["egress://bigquery.googleapis.com"],
- "operation": {
- "allowed_methods": ["GET", "POST"],
- "allowed_paths": ["/bigquery/v2/projects/my-proj/datasets/sales_2026/*"],
- "allowed_permissions": [
- "bigquery.googleapis.com/datasets.get",
- "bigquery.googleapis.com/tables.get",
- "bigquery.googleapis.com/tables.getData",
- "bigquery.googleapis.com/jobs.create"
- ]
- },
- "allowed_resources": [
- "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/*"
- ]
- },
- {
- "allowed_services": ["mcp://bigquery"],
- "operation": {
- "allowed_tools": ["list_tables", "query_sales"]
- }
- }
- ]
- }
- ```
-2. **Hop 2 (Analytics Agent $\rightarrow$ Ephemeral Sub-Agent, CUJ 3):**
- The analytics agent spawns a sub-agent to summarize only table `q1`, appending `TAR_2` offline:
- ```json
- {
- "name": "tasks/subagent-q1-only",
- "rules": [{
- "allowed_services": ["egress://bigquery.googleapis.com"],
- "operation": {
- "allowed_methods": ["GET"],
- "allowed_paths": ["/bigquery/v2/projects/my-proj/datasets/sales_2026/tables/q1/*"],
- "allowed_permissions": ["bigquery.googleapis.com/tables.getData"]
- },
- "allowed_resources": [
- "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/tables/q1"
- ]
- }]
- }
- ```
-3. **Egress Enforcement, Issuer Mint & Cloud STS Exchange:**
- * The egress `sam-node` (`egress-eu`, serving `egress://bigquery.googleapis.com`) verifies the Biscuit signature chain, the `client_peer_id` binding to the connection peer, the standing policy for `[email protected]`, and confirms the HTTP request (`GET /bigquery/v2/projects/my-proj/datasets/sales_2026/tables/q1/data`) satisfies **both** `TAR_1` and `TAR_2` (`allowed_services`, `allowed_methods`, and `allowed_paths`).
- * On a cache miss for this Biscuit digest it calls `POST /sts/token` on the control plane and receives an ES256 JWT (`[email protected]`, `act.sub=<egress-eu peer id>`, `aud=<pool provider>`, `sam_roles=["analyst"]`, `sam_task=tasks/subagent-q1-only`, `exp` in minutes).
- * `CloudTokenExchanger` exchanges the JWT at `sts.googleapis.com/v1/token` with `scope` narrowed to `bigquery.readonly`, caches the federated access token by Biscuit digest, and injects it as `Authorization: Bearer ...`. When the task token API is public it also forwards $\text{TAR}_1 \cap \text{TAR}_2$ (`allowed_permissions: ["bigquery.googleapis.com/tables.getData"]`, `allowed_resources: [".../tables/q1"]`) in the provider's form; on AWS the same intersection becomes an `Effect: Allow` session policy.
- * BigQuery's audit log records `principal://.../subject/[email protected]` as a member of group `analyst`; the control plane's log records the same principal and `sam_task`, so the two logs join.
-
----
-
-## 7. Security Considerations
-
-1. **The control plane becomes an identity provider the customer's cloud trusts.** That is the right place for it (the customer owns it), and it raises the bar: KMS- or HSM-backed ES256 key; JWT lifetime of minutes; one audience per destination; a CEL attribute condition on the cloud side that accepts only JWTs whose `act.sub` is an enrolled SAM egress node; detailed audit logging on the pool provider. A compromised issuer key exposes the IAM ceiling of every federated principal, the same as any IdP compromise; rotation with overlap and replacing the uploaded JWKS are the recovery path.
-2. **The control plane is on the egress path.** Caching per Biscuit digest for the JWT lifetime keeps it off the hot path, but it now needs HA and rate limits sized for egress and token exchange, not only enrollment. Kubernetes projected tokens rotate hourly and SPIRE JWT-SVIDs default to five minutes, so `POST /token/exchange` runs at the caller rotation rate.
-3. **A task Biscuit is a bearer token at the local hop.** In blueprint 2 the sandbox holds it. Mitigations: lifetime of minutes to an hour; `client_peer_id` binds it to one origin node, so an exfiltrated token is useless to anyone who cannot reach that node's local socket or facade; `Seal()` for leaf tokens; the destination verifies the binding against the libp2p connection peer.
-4. **Appended blocks are attacker-controlled bytes.** Structural validation (block count, one fact per block, no rules, no checks, payload size) runs before any authorizer is built; the TAR evaluator is trusted code with its own tests; limits are the same in all three verifiers.
-5. **Confused deputy at the egress node.** The node must never forward a caller-supplied `Authorization` to a destination (it strips it today) and must never let a TAR select a broker, a role or an audience. Both are unit-tested invariants.
-6. **Revocation and audit.** Revocation works on the authority block's revocation ID (section 3.4). Every border crossing is logged at the control plane (`/token/exchange`, `/sts/token`) with subject, actor, destination and `sam_task`; the cloud audit log carries the same principal, so the two logs join.
-7. **Per-task narrowing on Google Cloud is coarse today.** Paths, model names, scopes and attribute conditions; AWS session policies are the only fine-grained case. CUJ 1 and CUJ 2 must not be described as cloud-enforced per-task IAM on Google Cloud until the task token API is public.
-8. **Cross-organization reach of workforce principals.** Workforce pool principals cannot access resources outside their organization unless they may impersonate a service account; `impersonate` in the broker therefore widens reach and must be granted deliberately.
-9. **Mesh role names are visible to the cloud.** `sam_roles` carries them as group names, and the cloud audit log records them. Role names are therefore not secrets, and a cloud administrator who binds a role to `principalSet://.../group/<role>` grants to every subject the mesh policy binds to that role, now and later.
-
----
-
-## 8. Things to Verify Before Implementation Starts
-
-A one-week spike settles the items marked **spike**; the others are checks against documentation, measurements, or review decisions.
-
-| # | Question | How |
-| :--- | :--- | :--- |
-| 1 | Google Workload and Workforce Identity Federation accept a control-plane-issued ES256 JWT (`aud` = pool provider, `exp - iat` ≤ 24h), including the uploaded-JWKS path for a control plane that is not reachable from the internet. | **spike** |
-| 2 | BigQuery and Vertex AI accept the federated principal directly or need service account impersonation (the "federated identity supported services" page, then a call against each API). | **spike** + docs |
-| 3 | Cloud Audit Logs show the SAM principal (`google.subject`) and the `google.groups` membership for a BigQuery call made through the egress node. | **spike** |
-| 4 | Workforce vs. workload pool: a human principal (`email`) federates through a workforce pool, a workload principal through a workload pool. Confirm one issuer can serve both, what `sub` each expects, and that `google.groups` accepts the mesh role name syntax (`sam:role:node` carries colons) in both pool kinds. | docs |
-| 5 | AWS `AssumeRoleWithWebIdentity` with a session policy compiled from a realistic TAR stays under the packed policy size limit; behaviour at the one-hour chaining limit. | test |
-| 6 | Control-plane throughput and latency for `/token/exchange` and `/sts/token` with caching; cache hit rate with 5-minute JWT-SVIDs and 1-hour projected tokens. | `sam-bench` |
-| 7 | biscuit-go v2.2.0: reading the facts of block $i$ through the `pb` package vs. parsing `Code()`; `Seal()` on a token with appended blocks; whether `check if` queries are bounded by `WithMaxDuration` (section 3.1 assumes they are not) and whether the worker goroutine outlives a timeout. **Resolved (Phase 2):** structural counts come from `pb.Biscuit.Blocks[i-1]` (`FactsV2`/`RulesV2`/`ChecksV2`) and the fact string from `b.Code()` matched against `^tar_block\("([A-Za-z0-9_-]+)"\);?\s*$`; `Seal()` works on tokens with appended blocks. | **resolved** |
-| 8 | biscuit-wasm and biscuit-python expose block inspection and equivalent limits; conformance vectors in `sdk/testdata` pass in all three verifiers. **Note:** `biscuit-wasm` 0.6 exposes `getBlockSource(i)` and `sealToken()`; `biscuit-python` 0.4 exposes `block_count`, `block_source`, `append` and `revocation_ids` (sufficient to verify sealed tokens in Phase 2; Phase 4's Python `.seal()` will upgrade `biscuit-python`). | **resolved (Phase 2)** |
-| 9 | Off-the-shelf MCP clients (Claude Code, Gemini CLI, Cursor, VS Code) complete authorization code + PKCE against the control plane as authorization server, with client ID metadata documents and without dynamic client registration. | **spike** |
-| 10 | agentgateway's token-exchange backend authentication works against `sam-node`'s `/oauth/token` with a Biscuit as the issued token (opaque to the gateway); ext_authz response header size limits for an injected cloud credential. | test |
-| 11 | Publication status of the Google task token API; until public, the adapter interface is the only coupling. | track |
-| 12 | Path shapes for model-level PEP: Vertex AI (`/v1/projects/P/locations/L/publishers/google/models/M:generateContent`) and Gemini Developer API (`/v1beta/models/M:generateContent`), including streaming variants. | docs |
-| 13 | Google APIs that reject federated identities under VPC Service Controls, and the egress rule needed for `sts.googleapis.com` when the pool is organization-level. | docs |
-| 14 | Which sections of `AGENTS.md`, `site/content/docs/preview/agent-architecture.md` and `sandboxed-agents.md` change, and whether `AgentBundle` / `AgentAttach*` messages are removed or repurposed as "attach = mint task token". **Resolved:** `AgentBundle`/`AgentAttach*` removed in Phase 1; docs rewritten in Phase 5. | **resolved** |
-| 15 | Whether `internal/tunnel` (Cloudflare and Codespaces mesh reachability) is removed with the sandbox code or kept; it has no sandbox dependency. **Resolved:** kept. | **resolved** |
-| 16 | Istio: the `ext_authz` `CheckRequest` carries `source.principal` from ambient waypoints as it does from sidecars; XFCC is trusted only on the proxy path. | test |
-| 17 | Model Armor: `sanitizeUserPrompt` / `sanitizeModelResponse` accept a federated principal; per-call latency and quota at the egress node's request rate; which payload shapes (Gemini, OpenAI-compatible, MCP `tools/call`, A2A) the public API sanitizes and which it passes. | **spike** |
-| 18 | gRPC over the mesh: whether the libp2p HTTP stream can carry HTTP/2 framing and trailers end to end so `httputil.ReverseProxy` forwards gRPC; otherwise tunnel mode plus REST-transport guidance for Google client libraries. | **spike** |
-| 19 | Operator chain: Secure Web Proxy explicit mode and agentgateway as `target_url` with `preserve_host`; Cloud NGFW Enterprise TLS inspection with the egress node trusting the inspection CA, and agents trusting it for tunnel mode. | test |
-| 20 | `ext_proc` with no new root-module dependency: the trimmed protos under `third_party/envoy/` (with `LICENSE` and `METADATA` as Google's third-party policy requires) generate with the pinned `protoc-gen-go` and produce bytes identical to `go-control-plane`'s for a captured `ProcessingRequest` and `ProcessingResponse`; the standard-library gRPC client interoperates with a grpc-go reference processor and a Service Extensions callout example (trailers-only responses, `grpc-timeout`, cancellation from either side, `unix:` and h2c through `Protocols.SetUnencryptedHTTP2`, TLS with ALPN `h2`, a processor behind a gRPC-aware load balancer); `immediate_response` after response headers were sent resets the stream as in Envoy; the conformance module under `tests/extproc/` runs in the integration suite within its time budget. Track the package name the donated project publishes. **Decision:** ship both the `ext_proc` egress client (section 5.6) and the `ext_proc` gateway server (section 4.1) using the shared stdlib gRPC stream and vendored protos. | **spike** + **decided** |
-| 21 | Tunnel SNI check: behaviour for destinations that send no SNI (IP literals, some database drivers) and for Encrypted Client Hello; the `ports` allow-list is enforced before any dial. | test |
-| 22 | Model Armor streaming: whether `StreamSanitizeUserPrompt` / `StreamSanitizeModelResponse` are worth vendoring the Model Armor protos (they import `google/api` annotations that would need the same trimming) on top of the standard-library gRPC transport, or whether `BUFFERED` and `REQUEST_ONLY` over the REST API suffice; whether Model Armor itself is reachable as an `ext_proc` processor outside Google's managed Service Extensions. | decision + docs |
-
----
-
-## 9. Implementation Roadmap (Iterating from Known-Good States)
-
-1. **Phase 1 — Wipe Out `sam-box`, `nano-init`, and Legacy `agent:` Machinery:**
- * Remove `cmd/sam-box`, `cmd/nano-init`, `internal/sambox`, `Dockerfile.sam-box`, `Dockerfile.nano-init`, `api/agent.go`, `internal/node/agent.go`, `X-Sam-Agent` (`HeaderSamAgent`), `AuthFrame.agent`, `allowed_agents`, and dead `AgentBundle`/`AgentAttach*`/`AgentDetach*`/`AgentRefresh*`/`AgentStatus*` messages from [`api/sam.proto`](file:///usr/local/google/home/aojea/src/sam/api/sam.proto), SDKs, Makefile, and tests. Keep `api/names.go`: `NormalizeMeshHost` is used by `internal/node/egress.go`; drop only the sandbox-side helpers. `internal/tunnel` (Cloudflare and Codespaces tunnels for mesh reachability) has no sandbox dependency and is a separate decision (section 8, item 15).
- * Update [`AGENTS.md`](file:///usr/local/google/home/aojea/src/sam/AGENTS.md) to reflect the retired sandbox dataplane and the RFC 8693 / OAuth 2.1 surface carve-out.
- * Validate the clean baseline with `make`, `make lint`, `make test`, and `make sdk-test`.
-2. **Phase 2 — Protobuf & Safe `tar_block` Biscuit Attenuation (`api/`, `internal/identity/`, `sdk/`):**
- * Add `TaskAuthorizationRule`, `TaskRule` and `TaskOperation` to [`api/sam.proto`](file:///usr/local/google/home/aojea/src/sam/api/sam.proto). The exchange and mint messages (`TokenExchangeRequest`/`Response`, `STSTokenRequest`/`Response`) and the `actor_node` fact land in Phase 3 with the handlers that give them their shape.
- * Implement `AttenuateBiscuit`, `SealBiscuit`, and `ExtractTaskRules` in `internal/identity/biscuit.go`.
- * Update [`UnmarshalInbound`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go#L78-L87) (and JS/Python SDK verifiers, backed by conformance vectors in `sdk/testdata/`) to accept appended blocks containing **0 rules, 0 checks, and 1 `tar_block(<base64-proto>)` fact**, evaluating the decoded `TaskAuthorizationRule` chain in the verifier.
-3. **Phase 3 — Stateless Control-Plane Exchange & `sam-node` Origin STS / `ext_authz` (`internal/controlplane/`, `internal/node/`):**
- * Add stateless `POST /token/exchange` (`actor_node` + `subject_token` verification) and OAuth 2.1 AS endpoints to `sam-control-plane`, with their messages in `api/sam.proto` (instants as `*_time`, the proof-of-possession value as `challenge_unix_ms`). `SamNode.Authorize` binds a request token on `client_peer_id` in the authority block (section 3.3), with a conformance vector for a delegated token that carries no `node()` fact.
- * Make the control plane an OIDC issuer (section 3.5): ES256 key with a KMS/HSM option and overlap rotation, `/.well-known/openid-configuration`, `/jwks`, stateless `POST /sts/token` (Biscuit $\rightarrow$ JWT), `GET /revocations`, rate limits from `internal/ratelimit`, an audit log line for every crossing. Section 8 items 1–4 run against a test project before this phase is considered done.
- * Add RFC 8693 `POST /oauth/token`, `POST /oauth/revoke`, `/.well-known/oauth-protected-resource`, and Envoy `ext_authz` check support to `sam-node`.
- * Update `withAuth` (scoping transparent JWT exchange on `Authorization` strictly to `/mcp` and `/v1/*`) and `createEgressProxy` / `mcp.go` to forward caller Task Biscuits.
-4. **Phase 4 — `CloudTokenExchanger` on Egress (`internal/node/egress.go`) & SDK `.attenuate()`:**
- * Add `CredentialBroker` to `EgressDestination` (section 5.1) and implement the `CloudTokenExchanger` interface and adapters (`static_secret` = existing behaviour, Google federation, AWS session policy, generic RFC 8693) in [`internal/node/egress.go`](file:///usr/local/google/home/aojea/src/sam/internal/node/egress.go), with the "TAR narrows, never selects" invariant unit-tested.
- * Add `Inspection` (Model Armor direct with `BUFFERED` and `REQUEST_ONLY`; the Envoy `ext_proc` client with Envoy-named processing modes, `attributes["sam"]` context, refused mutations on `Authorization`, `Host` and `X-Sam-*`, and a conformance test against a Service Extensions callout example), `preserve_host` and `forward_context` for operator chains, and `EGRESS_MODE_TCP` named tunnels with the `ports` allow-list, the SNI check and `sam-node forward` (sections 5.6, 5.7). The `ext_proc` work adds nothing to the root `go.mod`: trimmed protos vendored under `third_party/envoy/` with `LICENSE` and `METADATA`, generated code verified by `hack/verify-generated.sh`, the gRPC wire protocol over `net/http`, and a conformance module with its own `go.mod` under `tests/extproc/`.
- * Measure control-plane mint throughput and cache hit rate with `sam-bench` (section 8, item 6) before publishing sizing guidance.
- * Add `.attenuate(task_rule)` and `.seal()` to `MeshSession` / `MemberCredential` in both TypeScript and Python SDKs.
-5. **Phase 5 — Documentation Overhaul (`README.md`, `site/content/docs/`):**
- * Rewrite [`site/content/docs/preview/agent-architecture.md`](file:///usr/local/google/home/aojea/src/sam/site/content/docs/preview/agent-architecture.md), [`site/content/docs/preview/sandboxed-agents.md`](file:///usr/local/google/home/aojea/src/sam/site/content/docs/preview/sandboxed-agents.md), [`site/content/docs/concepts/identity.md`](file:///usr/local/google/home/aojea/src/sam/site/content/docs/concepts/identity.md), [`site/content/docs/concepts/authorization.md`](file:///usr/local/google/home/aojea/src/sam/site/content/docs/concepts/authorization.md), [`site/content/docs/reference/policy.md`](file:///usr/local/google/home/aojea/src/sam/site/content/docs/reference/policy.md), and [`site/content/docs/reference/node-api.md`](file:///usr/local/google/home/aojea/src/sam/site/content/docs/reference/node-api.md).