Skip to content

Agent Mesh

feat(sts): implement Phase 3 STS endpoints, OAuth 2.1, ext_authz, and revocations

Antonio Ojea90603282cf0e
diff --git a/api/datalog.go b/api/datalog.go
index 69c70cd5..e53f1791 100644
--- a/api/datalog.go
+++ b/api/datalog.go
@@ -79,6 +79,12 @@ const (
// Example Datalog: check if client_peer_id($id), connection_peer_id($id)
FactClientPeerID = "client_peer_id"
+ // FactActorNode names the origin sam-node PeerID that exchanged a delegated
+ // subject credential at POST /token/exchange, for audit logs, for act.sub in
+ // border JWTs, and for ext_proc attributes["sam"].actor_node. It grants
+ // nothing: no baseline rule and no policy binding reads it.
+ FactActorNode = "actor_node"
+
// FactGroup defines the group claim extracted from the OIDC token.
// Contains: biscuit.String(groupName)
// Example Datalog: allow if group("data-science")
diff --git a/api/network.go b/api/network.go
index 2dea72f7..97ce98a8 100644
--- a/api/network.go
+++ b/api/network.go
@@ -119,6 +119,44 @@ func RouterLeaseChallenge(peerID string, ts int64) []byte {
return []byte("sam:routers-lease:" + peerID + ":" + strconv.FormatInt(ts, 10))
}
+// TokenExchangeChallenge is the payload an enrolled sam-node signs with its
+// identity key at POST /token/exchange to prove possession of the channel key
+// that will carry the minted Delegated Session Biscuit.
+func TokenExchangeChallenge(peerID string, ts int64) []byte {
+ return []byte("sam:token-exchange:" + peerID + ":" + strconv.FormatInt(ts, 10))
+}
+
+// STSTokenChallenge is the payload an enrolled egress sam-node signs with its
+// identity key at POST /sts/token when asking the control plane to mint an
+// ES256 border JWT for an outbound destination.
+func STSTokenChallenge(peerID string, ts int64) []byte {
+ return []byte("sam:sts-token:" + peerID + ":" + strconv.FormatInt(ts, 10))
+}
+
+// ============================================================================
+// OAuth 2.1 & RFC 8693 Token Exchange Constants
+// ============================================================================
+
+const (
+ // GrantTypeTokenExchange is the RFC 8693 OAuth 2.0 Token Exchange grant type URI.
+ GrantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
+
+ // GrantTypeAuthorizationCode is the standard OAuth 2.1 authorization_code grant type.
+ GrantTypeAuthorizationCode = "authorization_code"
+
+ // TokenTypeBiscuit is the token type URI identifying a SAM Biscuit token in RFC 8693 exchanges.
+ TokenTypeBiscuit = "urn:sam-mesh:params:oauth:token-type:biscuit"
+
+ // TokenTypeJWT is the RFC 8693 JWT token type URI.
+ TokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt"
+
+ // TokenTypeIDToken is the RFC 8693 OIDC ID token type URI.
+ TokenTypeIDToken = "urn:ietf:params:oauth:token-type:id_token"
+
+ // TokenTypeAccessToken is the RFC 8693 OAuth access token type URI.
+ TokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token"
+)
+
// ============================================================================
// SAM Custom HTTP Headers
// ============================================================================
@@ -180,6 +218,15 @@ const (
// scorer. Label declarations are routing hints until attested via the
// node's Biscuit (see api/labels.go).
HeaderSamRequiredLabels = "X-Sam-Required-Labels"
+
+ // HeaderSamPrincipal, HeaderSamRoles, HeaderSamTask, and HeaderSamTaskID carry
+ // verified caller attribution injected by ext_authz or forwarded to an
+ // operator inspection chain when forward_context is enabled.
+ HeaderSamPrincipal = "X-Sam-Principal"
+ HeaderSamRoles = "X-Sam-Roles"
+ HeaderSamTask = "X-Sam-Task"
+ HeaderSamTaskID = "X-Sam-Task-Id"
+ HeaderSamTargetService = "X-Sam-Target-Service"
)
// ============================================================================
diff --git a/api/sam.pb.go b/api/sam.pb.go
index 56ed699d..2c086791 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -2943,6 +2943,385 @@ func (x *TaskOperation) GetAllowedPermissions() []string {
return nil
}
+// TokenExchangeRequest is the body of POST /token/exchange on the control
+// plane: an enrolled sam-node (authenticated via its own Biscuit in
+// Authorization: Bearer and proof of possession below) exchanges a caller's
+// platform JWT (OIDC ID token, K8s projected SA JWT, or SPIFFE JWT-SVID) into
+// a short-lived Delegated Session Biscuit bound to the calling node's
+// transport channel (client_peer_id + actor_node, without node()).
+type TokenExchangeRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The subject's platform JWT to verify against the control plane's OIDC
+ // providers and allowed audiences.
+ SubjectToken string `protobuf:"bytes,1,opt,name=subject_token,json=subjectToken,proto3" json:"subject_token,omitempty"`
+ // Optional initial task narrowing to append as block 1 on the minted
+ // Biscuit.
+ TaskRule *TaskAuthorizationRule `protobuf:"bytes,2,opt,name=task_rule,json=taskRule,proto3" json:"task_rule,omitempty"`
+ // If true, the minted Biscuit is sealed (b.Seal()) before returning so
+ // downstream holders cannot append further blocks.
+ Seal bool `protobuf:"varint,3,opt,name=seal,proto3" json:"seal,omitempty"`
+ // Proof of possession of the calling node's enrolled key:
+ // challenge_unix_ms is the caller's clock in unix milliseconds and
+ // challenge_signature signs the UTF-8 bytes of
+ // "sam:token-exchange:<peer_id>:<challenge_unix_ms>".
+ ChallengeUnixMs int64 `protobuf:"varint,4,opt,name=challenge_unix_ms,json=challengeUnixMs,proto3" json:"challenge_unix_ms,omitempty"`
+ ChallengeSignature []byte `protobuf:"bytes,5,opt,name=challenge_signature,json=challengeSignature,proto3" json:"challenge_signature,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *TokenExchangeRequest) Reset() {
+ *x = TokenExchangeRequest{}
+ mi := &file_api_sam_proto_msgTypes[39]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *TokenExchangeRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TokenExchangeRequest) ProtoMessage() {}
+
+func (x *TokenExchangeRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[39]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use TokenExchangeRequest.ProtoReflect.Descriptor instead.
+func (*TokenExchangeRequest) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{39}
+}
+
+func (x *TokenExchangeRequest) GetSubjectToken() string {
+ if x != nil {
+ return x.SubjectToken
+ }
+ return ""
+}
+
+func (x *TokenExchangeRequest) GetTaskRule() *TaskAuthorizationRule {
+ if x != nil {
+ return x.TaskRule
+ }
+ return nil
+}
+
+func (x *TokenExchangeRequest) GetSeal() bool {
+ if x != nil {
+ return x.Seal
+ }
+ return false
+}
+
+func (x *TokenExchangeRequest) GetChallengeUnixMs() int64 {
+ if x != nil {
+ return x.ChallengeUnixMs
+ }
+ return 0
+}
+
+func (x *TokenExchangeRequest) GetChallengeSignature() []byte {
+ if x != nil {
+ return x.ChallengeSignature
+ }
+ return nil
+}
+
+type TokenExchangeResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ BiscuitToken []byte `protobuf:"bytes,1,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"`
+ ExpireTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"`
+ Roles []string `protobuf:"bytes,3,rep,name=roles,proto3" json:"roles,omitempty"`
+ Subject string `protobuf:"bytes,4,opt,name=subject,proto3" json:"subject,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *TokenExchangeResponse) Reset() {
+ *x = TokenExchangeResponse{}
+ mi := &file_api_sam_proto_msgTypes[40]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *TokenExchangeResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TokenExchangeResponse) ProtoMessage() {}
+
+func (x *TokenExchangeResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[40]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use TokenExchangeResponse.ProtoReflect.Descriptor instead.
+func (*TokenExchangeResponse) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{40}
+}
+
+func (x *TokenExchangeResponse) GetBiscuitToken() []byte {
+ if x != nil {
+ return x.BiscuitToken
+ }
+ return nil
+}
+
+func (x *TokenExchangeResponse) GetExpireTime() *timestamppb.Timestamp {
+ if x != nil {
+ return x.ExpireTime
+ }
+ return nil
+}
+
+func (x *TokenExchangeResponse) GetRoles() []string {
+ if x != nil {
+ return x.Roles
+ }
+ return nil
+}
+
+func (x *TokenExchangeResponse) GetSubject() string {
+ if x != nil {
+ return x.Subject
+ }
+ return ""
+}
+
+// STSTokenRequest is the body of POST /sts/token on the control plane: an
+// enrolled egress sam-node asks the control plane (acting as OIDC issuer) to
+// verify a caller's Biscuit and TaskAuthorizationRule chain for an egress
+// destination and mint a short-lived ES256 border JWT for cloud STS federation.
+type STSTokenRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The caller's Biscuit token (authority block + any tar_block chain).
+ Biscuit []byte `protobuf:"bytes,1,opt,name=biscuit,proto3" json:"biscuit,omitempty"`
+ // The egress destination hostname (e.g. "bigquery.googleapis.com").
+ Destination string `protobuf:"bytes,2,opt,name=destination,proto3" json:"destination,omitempty"`
+ // Optional explicit audience for the border JWT when not derived from the
+ // destination's broker configuration.
+ Audience string `protobuf:"bytes,3,opt,name=audience,proto3" json:"audience,omitempty"`
+ // Proof of possession of the calling egress node's enrolled key:
+ // challenge_unix_ms is the caller's clock in unix milliseconds and
+ // challenge_signature signs the UTF-8 bytes of
+ // "sam:sts-token:<peer_id>:<challenge_unix_ms>".
+ ChallengeUnixMs int64 `protobuf:"varint,4,opt,name=challenge_unix_ms,json=challengeUnixMs,proto3" json:"challenge_unix_ms,omitempty"`
+ ChallengeSignature []byte `protobuf:"bytes,5,opt,name=challenge_signature,json=challengeSignature,proto3" json:"challenge_signature,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *STSTokenRequest) Reset() {
+ *x = STSTokenRequest{}
+ mi := &file_api_sam_proto_msgTypes[41]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *STSTokenRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*STSTokenRequest) ProtoMessage() {}
+
+func (x *STSTokenRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[41]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use STSTokenRequest.ProtoReflect.Descriptor instead.
+func (*STSTokenRequest) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{41}
+}
+
+func (x *STSTokenRequest) GetBiscuit() []byte {
+ if x != nil {
+ return x.Biscuit
+ }
+ return nil
+}
+
+func (x *STSTokenRequest) GetDestination() string {
+ if x != nil {
+ return x.Destination
+ }
+ return ""
+}
+
+func (x *STSTokenRequest) GetAudience() string {
+ if x != nil {
+ return x.Audience
+ }
+ return ""
+}
+
+func (x *STSTokenRequest) GetChallengeUnixMs() int64 {
+ if x != nil {
+ return x.ChallengeUnixMs
+ }
+ return 0
+}
+
+func (x *STSTokenRequest) GetChallengeSignature() []byte {
+ if x != nil {
+ return x.ChallengeSignature
+ }
+ return nil
+}
+
+type STSTokenResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Jwt string `protobuf:"bytes,1,opt,name=jwt,proto3" json:"jwt,omitempty"`
+ ExpireTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"`
+ Subject string `protobuf:"bytes,3,opt,name=subject,proto3" json:"subject,omitempty"`
+ Roles []string `protobuf:"bytes,4,rep,name=roles,proto3" json:"roles,omitempty"`
+ TaskName string `protobuf:"bytes,5,opt,name=task_name,json=taskName,proto3" json:"task_name,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *STSTokenResponse) Reset() {
+ *x = STSTokenResponse{}
+ mi := &file_api_sam_proto_msgTypes[42]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *STSTokenResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*STSTokenResponse) ProtoMessage() {}
+
+func (x *STSTokenResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[42]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use STSTokenResponse.ProtoReflect.Descriptor instead.
+func (*STSTokenResponse) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{42}
+}
+
+func (x *STSTokenResponse) GetJwt() string {
+ if x != nil {
+ return x.Jwt
+ }
+ return ""
+}
+
+func (x *STSTokenResponse) GetExpireTime() *timestamppb.Timestamp {
+ if x != nil {
+ return x.ExpireTime
+ }
+ return nil
+}
+
+func (x *STSTokenResponse) GetSubject() string {
+ if x != nil {
+ return x.Subject
+ }
+ return ""
+}
+
+func (x *STSTokenResponse) GetRoles() []string {
+ if x != nil {
+ return x.Roles
+ }
+ return nil
+}
+
+func (x *STSTokenResponse) GetTaskName() string {
+ if x != nil {
+ return x.TaskName
+ }
+ return ""
+}
+
+// RevocationsResponse answers GET /revocations on the control plane: the set of
+// revoked Biscuit authority revocation IDs (hex-encoded RevocationIds()[0]) and
+// banned peer IDs.
+type RevocationsResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ RevocationIds []string `protobuf:"bytes,1,rep,name=revocation_ids,json=revocationIds,proto3" json:"revocation_ids,omitempty"`
+ BannedPeerIds []string `protobuf:"bytes,2,rep,name=banned_peer_ids,json=bannedPeerIds,proto3" json:"banned_peer_ids,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RevocationsResponse) Reset() {
+ *x = RevocationsResponse{}
+ mi := &file_api_sam_proto_msgTypes[43]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RevocationsResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RevocationsResponse) ProtoMessage() {}
+
+func (x *RevocationsResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[43]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RevocationsResponse.ProtoReflect.Descriptor instead.
+func (*RevocationsResponse) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{43}
+}
+
+func (x *RevocationsResponse) GetRevocationIds() []string {
+ if x != nil {
+ return x.RevocationIds
+ }
+ return nil
+}
+
+func (x *RevocationsResponse) GetBannedPeerIds() []string {
+ if x != nil {
+ return x.BannedPeerIds
+ }
+ return nil
+}
+
var File_api_sam_proto protoreflect.FileDescriptor
const file_api_sam_proto_rawDesc = "" +
@@ -3174,7 +3553,35 @@ const file_api_sam_proto_rawDesc = "" +
"\rallowed_tools\x18\x01 \x03(\tR\fallowedTools\x12'\n" +
"\x0fallowed_methods\x18\x02 \x03(\tR\x0eallowedMethods\x12#\n" +
"\rallowed_paths\x18\x03 \x03(\tR\fallowedPaths\x12/\n" +
- "\x13allowed_permissions\x18\x04 \x03(\tR\x12allowedPermissions*\x94\x01\n" +
+ "\x13allowed_permissions\x18\x04 \x03(\tR\x12allowedPermissions\"\xe8\x01\n" +
+ "\x14TokenExchangeRequest\x12#\n" +
+ "\rsubject_token\x18\x01 \x01(\tR\fsubjectToken\x12:\n" +
+ "\ttask_rule\x18\x02 \x01(\v2\x1d.sam.v1.TaskAuthorizationRuleR\btaskRule\x12\x12\n" +
+ "\x04seal\x18\x03 \x01(\bR\x04seal\x12*\n" +
+ "\x11challenge_unix_ms\x18\x04 \x01(\x03R\x0fchallengeUnixMs\x12/\n" +
+ "\x13challenge_signature\x18\x05 \x01(\fR\x12challengeSignature\"\xa9\x01\n" +
+ "\x15TokenExchangeResponse\x12#\n" +
+ "\rbiscuit_token\x18\x01 \x01(\fR\fbiscuitToken\x12;\n" +
+ "\vexpire_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\n" +
+ "expireTime\x12\x14\n" +
+ "\x05roles\x18\x03 \x03(\tR\x05roles\x12\x18\n" +
+ "\asubject\x18\x04 \x01(\tR\asubject\"\xc6\x01\n" +
+ "\x0fSTSTokenRequest\x12\x18\n" +
+ "\abiscuit\x18\x01 \x01(\fR\abiscuit\x12 \n" +
+ "\vdestination\x18\x02 \x01(\tR\vdestination\x12\x1a\n" +
+ "\baudience\x18\x03 \x01(\tR\baudience\x12*\n" +
+ "\x11challenge_unix_ms\x18\x04 \x01(\x03R\x0fchallengeUnixMs\x12/\n" +
+ "\x13challenge_signature\x18\x05 \x01(\fR\x12challengeSignature\"\xae\x01\n" +
+ "\x10STSTokenResponse\x12\x10\n" +
+ "\x03jwt\x18\x01 \x01(\tR\x03jwt\x12;\n" +
+ "\vexpire_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\n" +
+ "expireTime\x12\x18\n" +
+ "\asubject\x18\x03 \x01(\tR\asubject\x12\x14\n" +
+ "\x05roles\x18\x04 \x03(\tR\x05roles\x12\x1b\n" +
+ "\ttask_name\x18\x05 \x01(\tR\btaskName\"d\n" +
+ "\x13RevocationsResponse\x12%\n" +
+ "\x0erevocation_ids\x18\x01 \x03(\tR\rrevocationIds\x12&\n" +
+ "\x0fbanned_peer_ids\x18\x02 \x03(\tR\rbannedPeerIds*\x94\x01\n" +
"\x10EnrollmentStatus\x12!\n" +
"\x1dENROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n" +
"\x19ENROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n" +
@@ -3200,7 +3607,7 @@ func file_api_sam_proto_rawDescGZIP() []byte {
}
var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 3)
-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 44)
+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 49)
var file_api_sam_proto_goTypes = []any{
(EnrollmentStatus)(0), // 0: sam.v1.EnrollmentStatus
(ServiceType)(0), // 1: sam.v1.ServiceType
@@ -3244,54 +3651,62 @@ var file_api_sam_proto_goTypes = []any{
(*TaskAuthorizationRule)(nil), // 39: sam.v1.TaskAuthorizationRule
(*TaskRule)(nil), // 40: sam.v1.TaskRule
(*TaskOperation)(nil), // 41: sam.v1.TaskOperation
- nil, // 42: sam.v1.EnrollRequest.LabelsEntry
- nil, // 43: sam.v1.BootstrapEnrollRequest.LabelsEntry
- nil, // 44: sam.v1.CommandBackend.EnvEntry
- nil, // 45: sam.v1.ServiceAnnounce.LabelsEntry
- nil, // 46: sam.v1.PeerEvidenceResponse.LabelsEntry
- (*timestamppb.Timestamp)(nil), // 47: google.protobuf.Timestamp
+ (*TokenExchangeRequest)(nil), // 42: sam.v1.TokenExchangeRequest
+ (*TokenExchangeResponse)(nil), // 43: sam.v1.TokenExchangeResponse
+ (*STSTokenRequest)(nil), // 44: sam.v1.STSTokenRequest
+ (*STSTokenResponse)(nil), // 45: sam.v1.STSTokenResponse
+ (*RevocationsResponse)(nil), // 46: sam.v1.RevocationsResponse
+ nil, // 47: sam.v1.EnrollRequest.LabelsEntry
+ nil, // 48: sam.v1.BootstrapEnrollRequest.LabelsEntry
+ nil, // 49: sam.v1.CommandBackend.EnvEntry
+ nil, // 50: sam.v1.ServiceAnnounce.LabelsEntry
+ nil, // 51: sam.v1.PeerEvidenceResponse.LabelsEntry
+ (*timestamppb.Timestamp)(nil), // 52: google.protobuf.Timestamp
}
var file_api_sam_proto_depIdxs = []int32{
2, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type
- 47, // 1: sam.v1.MeshEvent.event_time:type_name -> google.protobuf.Timestamp
- 42, // 2: sam.v1.EnrollRequest.labels:type_name -> sam.v1.EnrollRequest.LabelsEntry
- 47, // 3: sam.v1.EnrollResponse.expire_time:type_name -> google.protobuf.Timestamp
- 43, // 4: sam.v1.BootstrapEnrollRequest.labels:type_name -> sam.v1.BootstrapEnrollRequest.LabelsEntry
+ 52, // 1: sam.v1.MeshEvent.event_time:type_name -> google.protobuf.Timestamp
+ 47, // 2: sam.v1.EnrollRequest.labels:type_name -> sam.v1.EnrollRequest.LabelsEntry
+ 52, // 3: sam.v1.EnrollResponse.expire_time:type_name -> google.protobuf.Timestamp
+ 48, // 4: sam.v1.BootstrapEnrollRequest.labels:type_name -> sam.v1.BootstrapEnrollRequest.LabelsEntry
0, // 5: sam.v1.BootstrapEnrollResponse.status:type_name -> sam.v1.EnrollmentStatus
- 47, // 6: sam.v1.BootstrapEnrollResponse.expire_time:type_name -> google.protobuf.Timestamp
+ 52, // 6: sam.v1.BootstrapEnrollResponse.expire_time:type_name -> google.protobuf.Timestamp
1, // 7: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType
- 44, // 8: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry
+ 49, // 8: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry
10, // 9: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo
11, // 10: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend
1, // 11: sam.v1.ServiceAnnounce.type:type_name -> sam.v1.ServiceType
- 45, // 12: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry
- 47, // 13: sam.v1.ServiceAnnounce.announce_time:type_name -> google.protobuf.Timestamp
- 47, // 14: sam.v1.RouterLeaseResponse.expire_time:type_name -> google.protobuf.Timestamp
+ 50, // 12: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry
+ 52, // 13: sam.v1.ServiceAnnounce.announce_time:type_name -> google.protobuf.Timestamp
+ 52, // 14: sam.v1.RouterLeaseResponse.expire_time:type_name -> google.protobuf.Timestamp
19, // 15: sam.v1.PolicyRole.http:type_name -> sam.v1.HTTPGrant
18, // 16: sam.v1.PolicyConfig.roles:type_name -> sam.v1.PolicyRole
21, // 17: sam.v1.PolicyConfig.bindings:type_name -> sam.v1.PolicyBinding
20, // 18: sam.v1.PolicyConfig.egress:type_name -> sam.v1.EgressDestination
20, // 19: sam.v1.EgressAssignmentsResponse.egress:type_name -> sam.v1.EgressDestination
- 47, // 20: sam.v1.KeysResponse.sign_time:type_name -> google.protobuf.Timestamp
- 47, // 21: sam.v1.TokenRefreshResponse.expire_time:type_name -> google.protobuf.Timestamp
+ 52, // 20: sam.v1.KeysResponse.sign_time:type_name -> google.protobuf.Timestamp
+ 52, // 21: sam.v1.TokenRefreshResponse.expire_time:type_name -> google.protobuf.Timestamp
10, // 22: sam.v1.NodeCatalogReport.services:type_name -> sam.v1.ServiceInfo
- 47, // 23: sam.v1.IdentityEvidenceResponse.biscuit_expire_time:type_name -> google.protobuf.Timestamp
- 47, // 24: sam.v1.IdentityEvidenceResponse.check_time:type_name -> google.protobuf.Timestamp
- 46, // 25: sam.v1.PeerEvidenceResponse.labels:type_name -> sam.v1.PeerEvidenceResponse.LabelsEntry
- 47, // 26: sam.v1.PeerEvidenceResponse.expire_time:type_name -> google.protobuf.Timestamp
- 47, // 27: sam.v1.PeerEvidenceResponse.check_time:type_name -> google.protobuf.Timestamp
- 47, // 28: sam.v1.MemberCredential.expire_time:type_name -> google.protobuf.Timestamp
+ 52, // 23: sam.v1.IdentityEvidenceResponse.biscuit_expire_time:type_name -> google.protobuf.Timestamp
+ 52, // 24: sam.v1.IdentityEvidenceResponse.check_time:type_name -> google.protobuf.Timestamp
+ 51, // 25: sam.v1.PeerEvidenceResponse.labels:type_name -> sam.v1.PeerEvidenceResponse.LabelsEntry
+ 52, // 26: sam.v1.PeerEvidenceResponse.expire_time:type_name -> google.protobuf.Timestamp
+ 52, // 27: sam.v1.PeerEvidenceResponse.check_time:type_name -> google.protobuf.Timestamp
+ 52, // 28: sam.v1.MemberCredential.expire_time:type_name -> google.protobuf.Timestamp
37, // 29: sam.v1.MemberCredential.trusted_keys:type_name -> sam.v1.TrustedSigningKey
38, // 30: sam.v1.MemberCredential.oidc_session:type_name -> sam.v1.OIDCSession
- 47, // 31: sam.v1.TrustedSigningKey.receive_time:type_name -> google.protobuf.Timestamp
+ 52, // 31: sam.v1.TrustedSigningKey.receive_time:type_name -> google.protobuf.Timestamp
40, // 32: sam.v1.TaskAuthorizationRule.rules:type_name -> sam.v1.TaskRule
- 47, // 33: sam.v1.TaskAuthorizationRule.expire_time:type_name -> google.protobuf.Timestamp
+ 52, // 33: sam.v1.TaskAuthorizationRule.expire_time:type_name -> google.protobuf.Timestamp
41, // 34: sam.v1.TaskRule.operation:type_name -> sam.v1.TaskOperation
- 35, // [35:35] is the sub-list for method output_type
- 35, // [35:35] is the sub-list for method input_type
- 35, // [35:35] is the sub-list for extension type_name
- 35, // [35:35] is the sub-list for extension extendee
- 0, // [0:35] is the sub-list for field type_name
+ 39, // 35: sam.v1.TokenExchangeRequest.task_rule:type_name -> sam.v1.TaskAuthorizationRule
+ 52, // 36: sam.v1.TokenExchangeResponse.expire_time:type_name -> google.protobuf.Timestamp
+ 52, // 37: sam.v1.STSTokenResponse.expire_time:type_name -> google.protobuf.Timestamp
+ 38, // [38:38] is the sub-list for method output_type
+ 38, // [38:38] is the sub-list for method input_type
+ 38, // [38:38] is the sub-list for extension type_name
+ 38, // [38:38] is the sub-list for extension extendee
+ 0, // [0:38] is the sub-list for field type_name
}
func init() { file_api_sam_proto_init() }
@@ -3309,7 +3724,7 @@ func file_api_sam_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),
NumEnums: 3,
- NumMessages: 44,
+ NumMessages: 49,
NumExtensions: 0,
NumServices: 0,
},
diff --git a/api/sam.proto b/api/sam.proto
index c289ec5b..2faf7170 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -492,3 +492,75 @@ message TaskOperation {
// Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.
repeated string allowed_permissions = 4;
}
+
+// ============================================================================
+// Stateless Token Exchange & Border STS (Two-Token Model)
+// ============================================================================
+
+// TokenExchangeRequest is the body of POST /token/exchange on the control
+// plane: an enrolled sam-node (authenticated via its own Biscuit in
+// Authorization: Bearer and proof of possession below) exchanges a caller's
+// platform JWT (OIDC ID token, K8s projected SA JWT, or SPIFFE JWT-SVID) into
+// a short-lived Delegated Session Biscuit bound to the calling node's
+// transport channel (client_peer_id + actor_node, without node()).
+message TokenExchangeRequest {
+ // The subject's platform JWT to verify against the control plane's OIDC
+ // providers and allowed audiences.
+ string subject_token = 1;
+ // Optional initial task narrowing to append as block 1 on the minted
+ // Biscuit.
+ TaskAuthorizationRule task_rule = 2;
+ // If true, the minted Biscuit is sealed (b.Seal()) before returning so
+ // downstream holders cannot append further blocks.
+ bool seal = 3;
+ // Proof of possession of the calling node's enrolled key:
+ // challenge_unix_ms is the caller's clock in unix milliseconds and
+ // challenge_signature signs the UTF-8 bytes of
+ // "sam:token-exchange:<peer_id>:<challenge_unix_ms>".
+ int64 challenge_unix_ms = 4;
+ bytes challenge_signature = 5;
+}
+
+message TokenExchangeResponse {
+ bytes biscuit_token = 1;
+ google.protobuf.Timestamp expire_time = 2;
+ repeated string roles = 3;
+ string subject = 4;
+}
+
+// STSTokenRequest is the body of POST /sts/token on the control plane: an
+// enrolled egress sam-node asks the control plane (acting as OIDC issuer) to
+// verify a caller's Biscuit and TaskAuthorizationRule chain for an egress
+// destination and mint a short-lived ES256 border JWT for cloud STS federation.
+message STSTokenRequest {
+ // The caller's Biscuit token (authority block + any tar_block chain).
+ bytes biscuit = 1;
+ // The egress destination hostname (e.g. "bigquery.googleapis.com").
+ string destination = 2;
+ // Optional explicit audience for the border JWT when not derived from the
+ // destination's broker configuration.
+ string audience = 3;
+ // Proof of possession of the calling egress node's enrolled key:
+ // challenge_unix_ms is the caller's clock in unix milliseconds and
+ // challenge_signature signs the UTF-8 bytes of
+ // "sam:sts-token:<peer_id>:<challenge_unix_ms>".
+ int64 challenge_unix_ms = 4;
+ bytes challenge_signature = 5;
+}
+
+message STSTokenResponse {
+ string jwt = 1;
+ google.protobuf.Timestamp expire_time = 2;
+ string subject = 3;
+ repeated string roles = 4;
+ string task_name = 5;
+}
+
+// RevocationsResponse answers GET /revocations on the control plane: the set of
+// revoked Biscuit authority revocation IDs (hex-encoded RevocationIds()[0]) and
+// banned peer IDs.
+message RevocationsResponse {
+ repeated string revocation_ids = 1;
+ repeated string banned_peer_ids = 2;
+}
+
diff --git a/api/tar.go b/api/tar.go
index 170b73ee..53eab2a1 100644
--- a/api/tar.go
+++ b/api/tar.go
@@ -23,7 +23,9 @@ import (
"time"
"github.com/biscuit-auth/biscuit-go/v2"
+ "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
)
// Structural bounds for holder-appended TaskAuthorizationRule (tar_block)
@@ -447,6 +449,50 @@ func EvaluateTaskRules(blocks []*TaskAuthorizationRule, req TaskRequestContext,
return nil
}
+// EvaluateTaskRulesForDestination verifies that every appended
+// TaskAuthorizationRule block in blocks is unexpired at now and contains at
+// least one TaskRule whose allowed_services matches (serviceType, serviceName).
+// Used by control-plane destination-level checks (e.g. POST /sts/token) where
+// per-request HTTP method and path constraints have already been enforced by
+// the egress node PEP.
+func EvaluateTaskRulesForDestination(blocks []*TaskAuthorizationRule, serviceType, serviceName string, now time.Time) error {
+ for i, block := range blocks {
+ if block == nil {
+ return fmt.Errorf("tar_block[%d] is nil", i+1)
+ }
+ if exp := block.GetExpireTime(); exp != nil {
+ if !exp.IsValid() {
+ return fmt.Errorf("tar_block[%d] has invalid expire_time", i+1)
+ }
+ if now.After(exp.AsTime()) {
+ return fmt.Errorf("tar_block[%d] (%q) expired at %s", i+1, block.GetName(), exp.AsTime().UTC().Format(time.RFC3339))
+ }
+ }
+ matched := false
+ for _, r := range block.GetRules() {
+ if r == nil {
+ continue
+ }
+ if op := r.GetOperation(); op != nil && len(op.GetAllowedTools()) > 0 && serviceType != "mcp" {
+ continue
+ }
+ for _, pattern := range r.GetAllowedServices() {
+ if MatchServicePattern(pattern, serviceType, serviceName) {
+ matched = true
+ break
+ }
+ }
+ if matched {
+ break
+ }
+ }
+ if !matched {
+ return fmt.Errorf("tar_block[%d] (%q) denied request to %s://%s", i+1, block.GetName(), serviceType, serviceName)
+ }
+ }
+ return nil
+}
+
// EffectiveTARExpiration returns the earliest expiration time across the
// authority block's expiration and every appended TaskAuthorizationRule's
// expire_time.
@@ -463,3 +509,101 @@ func EffectiveTARExpiration(authorityExp time.Time, blocks []*TaskAuthorizationR
}
return effective
}
+
+// BuildTARFromOAuthParams constructs and validates a TaskAuthorizationRule from
+// OAuth 2.1 / RFC 8693 / RFC 8707 request parameters:
+// - optionsParam: optional base64url-serialized TaskAuthorizationRule protobuf
+// (or JSON object when starting with '{').
+// - resources: optional RFC 8707 resource indicators (e.g. "mcp://weather").
+// - scope: optional space-delimited scope tokens ("mcp://...", "tool:<name>",
+// "method:<HTTP_METHOD>", "path:<prefix>", "perm:<permission>").
+//
+// Returns (nil, nil) if none of optionsParam, resources, or scope narrow the token.
+func BuildTARFromOAuthParams(defaultName, optionsParam string, resources []string, scope string, expireTime *timestamppb.Timestamp) (*TaskAuthorizationRule, error) {
+ optionsParam = strings.TrimSpace(optionsParam)
+ var tar *TaskAuthorizationRule
+ if optionsParam != "" {
+ if strings.HasPrefix(optionsParam, "{") {
+ var parsed TaskAuthorizationRule
+ if err := (protojson.UnmarshalOptions{DiscardUnknown: false}).Unmarshal([]byte(optionsParam), &parsed); err != nil {
+ return nil, fmt.Errorf("invalid options JSON: %w", err)
+ }
+ tar = &parsed
+ } else {
+ decoded, err := DecodeTARBlockPayload(optionsParam)
+ if err != nil {
+ return nil, fmt.Errorf("invalid options tar_block: %w", err)
+ }
+ tar = decoded
+ }
+ }
+
+ var services []string
+ for _, r := range resources {
+ r = strings.TrimSpace(r)
+ if r != "" {
+ services = append(services, r)
+ }
+ }
+ var tools, methods, paths, perms []string
+ for _, tok := range strings.Fields(scope) {
+ switch {
+ case strings.HasPrefix(tok, "tool:"):
+ tools = append(tools, strings.TrimPrefix(tok, "tool:"))
+ case strings.HasPrefix(tok, "method:"):
+ methods = append(methods, strings.TrimPrefix(tok, "method:"))
+ case strings.HasPrefix(tok, "path:"):
+ paths = append(paths, strings.TrimPrefix(tok, "path:"))
+ case strings.HasPrefix(tok, "perm:"):
+ perms = append(perms, strings.TrimPrefix(tok, "perm:"))
+ case strings.HasPrefix(tok, "permission:"):
+ perms = append(perms, strings.TrimPrefix(tok, "permission:"))
+ case strings.Contains(tok, "://") || tok == "*":
+ services = append(services, tok)
+ }
+ }
+
+ if tar == nil {
+ if len(services) == 0 && len(tools) == 0 && len(methods) == 0 && len(paths) == 0 && len(perms) == 0 {
+ return nil, nil
+ }
+ if len(services) == 0 {
+ return nil, fmt.Errorf("resource or service scope is required when specifying operation scopes")
+ }
+ name := strings.TrimSpace(defaultName)
+ if name == "" {
+ name = "oauth-task"
+ }
+ rule := &TaskRule{
+ AllowedServices: services,
+ }
+ if len(tools) > 0 || len(methods) > 0 || len(paths) > 0 || len(perms) > 0 {
+ rule.Operation = &TaskOperation{
+ AllowedTools: tools,
+ AllowedMethods: methods,
+ AllowedPaths: paths,
+ AllowedPermissions: perms,
+ }
+ }
+ tar = &TaskAuthorizationRule{
+ Name: name,
+ ExpireTime: expireTime,
+ Rules: []*TaskRule{rule},
+ }
+ } else {
+ if tar.Name == "" && defaultName != "" {
+ tar.Name = defaultName
+ }
+ if tar.ExpireTime == nil && expireTime != nil {
+ tar.ExpireTime = expireTime
+ }
+ }
+
+ if err := ValidateTaskAuthorizationRule(tar); err != nil {
+ return nil, err
+ }
+ if len(tar.GetRules()) == 0 {
+ return nil, fmt.Errorf("task authorization rule must contain at least one rule")
+ }
+ return tar, nil
+}
diff --git a/hack/gen-sdk-datalog/main.go b/hack/gen-sdk-datalog/main.go
index ba729a38..ededab5d 100644
--- a/hack/gen-sdk-datalog/main.go
+++ b/hack/gen-sdk-datalog/main.go
@@ -48,6 +48,9 @@ import (
type artifact struct {
Comment string `json:"_comment"`
api.DatalogSources
+ FactNode string `json:"fact_node"`
+ FactClientPeer string `json:"fact_client_peer_id"`
+ FactActorNode string `json:"fact_actor_node"`
FactService string `json:"fact_service"`
FactConnectionPeer string `json:"fact_connection_peer_id"`
FactMethod string `json:"fact_method"`
@@ -558,6 +561,69 @@ func buildConformanceSuite() tarConformanceSuite {
MCPTool: "get_weather",
Allow: false,
},
+ {
+ Name: "delegated_token_no_node_fact_allowed",
+ BiscuitB64: b64(func() []byte {
+ policyRoles := []*api.PolicyRole{
+ {
+ Name: "analyst",
+ AllowedServices: []string{"*"},
+ AllowedTargets: []string{"*"},
+ },
+ }
+ tok, err := identity.MintDelegatedBiscuitTokenWithRand(
+ newDeterministicReader("delegated-caller"),
+ cpPriv,
+ map[string]any{"sub": "alice", "email": "[email protected]"},
+ callerPeer,
+ authExp,
+ []string{"analyst"},
+ policyRoles,
+ hop1,
+ true,
+ )
+ if err != nil {
+ panic(err)
+ }
+ return tok
+ }()),
+ TargetService: "mcp://weather",
+ Protocol: string(api.MCPProtocolID),
+ MCPTool: "get_weather",
+ Allow: true,
+ ExpectedEffectiveExpiration: hop1Exp.Format(time.RFC3339),
+ },
+ {
+ Name: "delegated_token_wrong_actor_rejected",
+ BiscuitB64: b64(func() []byte {
+ policyRoles := []*api.PolicyRole{
+ {
+ Name: "analyst",
+ AllowedServices: []string{"*"},
+ AllowedTargets: []string{"*"},
+ },
+ }
+ tok, err := identity.MintDelegatedBiscuitTokenWithRand(
+ newDeterministicReader("delegated-wrong-actor"),
+ cpPriv,
+ map[string]any{"sub": "alice", "email": "[email protected]"},
+ providerPeer,
+ authExp,
+ []string{"analyst"},
+ policyRoles,
+ hop1,
+ false,
+ )
+ if err != nil {
+ panic(err)
+ }
+ return tok
+ }()),
+ TargetService: "mcp://weather",
+ Protocol: string(api.MCPProtocolID),
+ MCPTool: "get_weather",
+ Allow: false,
+ },
},
}
}
@@ -570,6 +636,9 @@ func main() {
a := artifact{
Comment: "Generated by hack/gen-sdk-datalog from api/datalog.go; do not edit.",
DatalogSources: api.BaselineSources,
+ FactNode: api.FactNode,
+ FactClientPeer: api.FactClientPeerID,
+ FactActorNode: api.FactActorNode,
FactService: api.FactService,
FactConnectionPeer: api.FactConnectionPeerID,
FactMethod: api.FactMethod,
diff --git a/internal/controlplane/client/client.go b/internal/controlplane/client/client.go
index b9fc97e2..75a343b7 100644
--- a/internal/controlplane/client/client.go
+++ b/internal/controlplane/client/client.go
@@ -19,6 +19,7 @@
package client
import (
+ "bytes"
"context"
"crypto/ed25519"
"encoding/base64"
@@ -155,6 +156,38 @@ func (c *Client) FetchEgress(ctx context.Context, biscuit []byte) (*api.EgressAs
return &egress, nil
}
+// FetchRevocations is GET /revocations, authenticated with the caller's biscuit:
+// the revoked Biscuit IDs and banned peer IDs currently tracked by the control plane.
+func (c *Client) FetchRevocations(ctx context.Context, biscuit []byte) (*api.RevocationsResponse, error) {
+ var revocations api.RevocationsResponse
+ if err := c.get(ctx, "/revocations", biscuit, &revocations); err != nil {
+ return nil, err
+ }
+ return &revocations, nil
+}
+
+// ExchangeToken is POST /token/exchange, authenticated with the calling node's
+// biscuit: verifies an external OIDC/K8s/SPIFFE JWT and mints a short-lived
+// Delegated Session Biscuit bound to the calling node.
+func (c *Client) ExchangeToken(ctx context.Context, biscuit []byte, req *api.TokenExchangeRequest) (*api.TokenExchangeResponse, error) {
+ var resp api.TokenExchangeResponse
+ if err := c.post(ctx, "/token/exchange", biscuit, req, &resp); err != nil {
+ return nil, err
+ }
+ return &resp, nil
+}
+
+// MintSTSToken is POST /sts/token, authenticated with the egress node's
+// biscuit: verifies a caller Biscuit for an egress destination and mints a
+// short-lived ES256 JWT for cloud STS federation.
+func (c *Client) MintSTSToken(ctx context.Context, biscuit []byte, req *api.STSTokenRequest) (*api.STSTokenResponse, error) {
+ var resp api.STSTokenResponse
+ if err := c.post(ctx, "/sts/token", biscuit, req, &resp); err != nil {
+ return nil, err
+ }
+ return &resp, nil
+}
+
func (c *Client) get(ctx context.Context, path string, biscuit []byte, msg proto.Message) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
if err != nil {
@@ -184,3 +217,38 @@ func (c *Client) get(ctx context.Context, path string, biscuit []byte, msg proto
}
return nil
}
+
+func (c *Client) post(ctx context.Context, path string, biscuit []byte, reqMsg, respMsg proto.Message) error {
+ payload, err := proto.Marshal(reqMsg)
+ if err != nil {
+ return fmt.Errorf("failed to marshal %s request: %w", path, err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(payload))
+ if err != nil {
+ return fmt.Errorf("failed to create HTTP request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/x-protobuf")
+ if len(biscuit) > 0 {
+ req.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(biscuit))
+ }
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return fmt.Errorf("HTTP request failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ body, err := ReadBody(resp.Body)
+ if err != nil {
+ return fmt.Errorf("%s: %w", path, err)
+ }
+ if resp.StatusCode == http.StatusNotFound {
+ return fmt.Errorf("%w: %s", ErrNotFound, path)
+ }
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("control plane returned status %s: %s", resp.Status, strings.TrimSpace(string(body)))
+ }
+ if err := proto.Unmarshal(body, respMsg); err != nil {
+ return fmt.Errorf("failed to decode %s response: %w", path, err)
+ }
+ return nil
+}
diff --git a/internal/controlplane/config.go b/internal/controlplane/config.go
index 20ad86bf..96805760 100644
--- a/internal/controlplane/config.go
+++ b/internal/controlplane/config.go
@@ -43,6 +43,19 @@ type Options struct {
NodeRetention time.Duration
AdminToken string // Optional: administrative bearer token for protecting policy and enrollment queue REST APIs
AutoApproveEnrollment bool // If true, valid bootstrap token enrollment requests are immediately approved without administrative manual gate
+ // STSIssuerURL is the public issuer URL advertised in
+ // /.well-known/openid-configuration and minted as the "iss" claim in
+ // outbound /sts/token JWTs. If empty, derived from the incoming HTTP request.
+ STSIssuerURL string
+ // DelegatedBiscuitTTL bounds the lifespan of Delegated Session Biscuits
+ // minted by POST /token/exchange and OAuth 2.1 flows (defaults to 1h).
+ DelegatedBiscuitTTL time.Duration
+ // STSTokenTTL is the default lifespan of short-lived ES256 border JWTs
+ // minted by POST /sts/token (defaults to 5m, capped at 15m).
+ STSTokenTTL time.Duration
+ // OIDCSigner signs outbound border JWTs and serves /jwks. If nil, a
+ // LocalES256Signer is initialized automatically.
+ OIDCSigner OIDCSigner
}
// Default sets default values for control plane options.
@@ -69,6 +82,12 @@ func (o *Options) Default() {
if o.OIDCSessionTTL <= 0 {
o.OIDCSessionTTL = api.OIDCSessionTTL
}
+ if o.DelegatedBiscuitTTL <= 0 {
+ o.DelegatedBiscuitTTL = 1 * time.Hour
+ }
+ if o.STSTokenTTL <= 0 {
+ o.STSTokenTTL = 5 * time.Minute
+ }
}
// Validate ensures options are valid.
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index a5ddd86b..0a9897f4 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -41,6 +41,7 @@ import (
jwt "github.com/golang-jwt/jwt/v5"
"github.com/google/sam/api"
"github.com/google/sam/internal/identity"
+ "github.com/google/sam/internal/ratelimit"
"github.com/google/sam/internal/storage"
golog "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/crypto"
@@ -97,6 +98,14 @@ type Server struct {
httpServer *http.Server
listener net.Listener
limiter *rate.Limiter
+ stsLimiter *ratelimit.PeerRateLimiter
+ oidcSigner OIDCSigner
+
+ revokedBiscuitsMu sync.RWMutex
+ revokedBiscuits map[string]time.Time
+
+ oauthCodesMu sync.Mutex
+ oauthCodes map[string]*oauthAuthCode
meshMu sync.RWMutex
mesh MeshAdapter
@@ -128,6 +137,19 @@ func NewServer(config Options, store storage.Store) (*Server, error) {
return nil, err
}
+ signer := config.OIDCSigner
+ if signer == nil {
+ var err error
+ signer, err = NewLocalES256Signer()
+ if err != nil {
+ return nil, fmt.Errorf("failed to initialize OIDC signer: %w", err)
+ }
+ }
+ stsLimiter, err := ratelimit.NewPeerRateLimiter(1000)
+ if err != nil {
+ return nil, fmt.Errorf("failed to initialize STS rate limiter: %w", err)
+ }
+
ctx, cancel := context.WithCancel(context.Background())
reg := prometheus.NewRegistry()
@@ -138,6 +160,10 @@ func NewServer(config Options, store storage.Store) (*Server, error) {
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,
@@ -256,6 +282,14 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {
handle("/enroll", meshSurface(noStore(s.HandleEnroll)))
handle("/enroll/status", meshSurface(noStore(s.HandleEnrollStatus)))
handle("/refresh", meshSurface(noStore(s.HandleRefresh)))
+ handle("/token/exchange", meshSurface(noStore(s.HandleTokenExchange)))
+ handle("/sts/token", meshSurface(noStore(s.HandleSTSToken)))
+ handle("/revocations", meshSurface(noStore(s.HandleRevocations)))
+ handle("/.well-known/openid-configuration", meshSurface(s.HandleOpenIDConfiguration))
+ handle("/.well-known/oauth-authorization-server", meshSurface(s.HandleOAuthAuthorizationServer))
+ handle("/jwks", meshSurface(s.HandleJWKS))
+ handle("/oauth/authorize", noStore(s.HandleOAuthAuthorize))
+ handle("/oauth/token", meshSurface(noStore(s.HandleOAuthToken)))
handle("/nodes/catalog", s.HandleNodeCatalog)
handle("/admin/bootstrap-tokens", noStore(s.HandleAdminBootstrapTokens))
handle("/admin/bootstrap-tokens/", noStore(s.HandleAdminBootstrapTokenAction))
diff --git a/internal/controlplane/sts.go b/internal/controlplane/sts.go
new file mode 100644
index 00000000..6f645d11
--- /dev/null
+++ b/internal/controlplane/sts.go
@@ -0,0 +1,1313 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package controlplane
+
+import (
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "html/template"
+ "io"
+ "net/http"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/biscuit-auth/biscuit-go/v2/parser"
+ jwt "github.com/golang-jwt/jwt/v5"
+ "github.com/google/sam/api"
+ "github.com/google/sam/internal/identity"
+ "github.com/google/sam/internal/storage"
+ "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"
+)
+
+const (
+ // maxSTSTokenTTL is the maximum lifetime of an outbound border JWT minted by POST /sts/token.
+ maxSTSTokenTTL = 15 * time.Minute
+ // oauthAuthCodeTTL is the lifetime of a single-use OAuth 2.1 authorization code.
+ oauthAuthCodeTTL = 5 * time.Minute
+)
+
+// JSONWebKey represents a single public key in an RFC 7517 JSON Web Key Set.
+type JSONWebKey struct {
+ Kty string `json:"kty"`
+ Crv string `json:"crv"`
+ Use string `json:"use"`
+ Alg string `json:"alg"`
+ Kid string `json:"kid"`
+ X string `json:"x"`
+ Y string `json:"y"`
+}
+
+// JSONWebKeySet represents an RFC 7517 JSON Web Key Set served at GET /jwks.
+type JSONWebKeySet struct {
+ Keys []JSONWebKey `json:"keys"`
+}
+
+// OIDCSigner signs outbound ES256 border JWTs at POST /sts/token and publishes
+// the corresponding public keys at GET /jwks.
+type OIDCSigner interface {
+ SignJWT(ctx context.Context, claims jwt.MapClaims) (string, error)
+ JWKS(ctx context.Context) (*JSONWebKeySet, error)
+}
+
+type es256KeyEntry struct {
+ kid string
+ priv *ecdsa.PrivateKey
+ jwk JSONWebKey
+ expiresAt time.Time // zero for the currently active signing key
+}
+
+// LocalES256Signer is the default in-memory OIDCSigner using P-256 (ES256) keys
+// with overlap grace-period support during key rotation.
+type LocalES256Signer struct {
+ mu sync.RWMutex
+ current es256KeyEntry
+ retired []es256KeyEntry
+}
+
+// NewLocalES256Signer creates a LocalES256Signer with a freshly generated P-256 key.
+func NewLocalES256Signer() (*LocalES256Signer, error) {
+ entry, err := generateES256KeyEntry()
+ if err != nil {
+ return nil, err
+ }
+ return &LocalES256Signer{current: entry}, nil
+}
+
+func generateES256KeyEntry() (es256KeyEntry, error) {
+ priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ return es256KeyEntry{}, fmt.Errorf("generate P-256 key: %w", err)
+ }
+ uncompressed, err := priv.PublicKey.Bytes()
+ if err != nil || len(uncompressed) != 65 {
+ return es256KeyEntry{}, fmt.Errorf("encode P-256 public key: %w", err)
+ }
+ xBytes := uncompressed[1:33]
+ yBytes := uncompressed[33:65]
+ sum := sha256.Sum256(uncompressed)
+ kid := hex.EncodeToString(sum[:8])
+ return es256KeyEntry{
+ kid: kid,
+ priv: priv,
+ jwk: JSONWebKey{
+ Kty: "EC",
+ Crv: "P-256",
+ Use: "sig",
+ Alg: "ES256",
+ Kid: kid,
+ X: base64.RawURLEncoding.EncodeToString(xBytes),
+ Y: base64.RawURLEncoding.EncodeToString(yBytes),
+ },
+ }, nil
+}
+
+// Rotate generates a new active ES256 signing key and retains the previous key
+// in JWKS for gracePeriod so in-flight border JWTs remain verifiable.
+func (s *LocalES256Signer) Rotate(gracePeriod time.Duration) (string, error) {
+ next, err := generateES256KeyEntry()
+ if err != nil {
+ return "", err
+ }
+ now := time.Now()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ prev := s.current
+ prev.expiresAt = now.Add(gracePeriod)
+ var kept []es256KeyEntry
+ for _, r := range s.retired {
+ if now.Before(r.expiresAt) {
+ kept = append(kept, r)
+ }
+ }
+ if gracePeriod > 0 {
+ kept = append(kept, prev)
+ }
+ s.retired = kept
+ s.current = next
+ return next.kid, nil
+}
+
+// SignJWT signs claims with the active ES256 key and sets the "kid" header.
+func (s *LocalES256Signer) SignJWT(_ context.Context, claims jwt.MapClaims) (string, error) {
+ s.mu.RLock()
+ active := s.current
+ s.mu.RUnlock()
+
+ tok := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
+ tok.Header["kid"] = active.kid
+ return tok.SignedString(active.priv)
+}
+
+// JWKS returns the active public key plus any retired keys still within their overlap grace window.
+func (s *LocalES256Signer) JWKS(_ context.Context) (*JSONWebKeySet, error) {
+ now := time.Now()
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ keys := []JSONWebKey{s.current.jwk}
+ for _, r := range s.retired {
+ if now.Before(r.expiresAt) {
+ keys = append(keys, r.jwk)
+ }
+ }
+ return &JSONWebKeySet{Keys: keys}, nil
+}
+
+// RotateOIDCKey rotates the control plane's ES256 OIDC signing key when backed by LocalES256Signer.
+func (s *Server) RotateOIDCKey(gracePeriod time.Duration) (string, error) {
+ local, ok := s.oidcSigner.(*LocalES256Signer)
+ if !ok {
+ return "", errors.New("configured OIDCSigner does not support local key rotation")
+ }
+ return local.Rotate(gracePeriod)
+}
+
+// oidcIssuerURL returns the canonical OIDC issuer URL for this control plane.
+func (s *Server) oidcIssuerURL(r *http.Request) string {
+ if iss := strings.TrimRight(strings.TrimSpace(s.config.STSIssuerURL), "/"); iss != "" {
+ return iss
+ }
+ scheme := "http"
+ if r != nil {
+ if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
+ scheme = "https"
+ }
+ if r.Host != "" {
+ return scheme + "://" + r.Host
+ }
+ }
+ if s.listener != nil {
+ return scheme + "://" + s.listener.Addr().String()
+ }
+ return scheme + "://" + s.config.ListenAddr
+}
+
+// HandleOpenIDConfiguration serves GET `/.well-known/openid-configuration`.
+func (s *Server) HandleOpenIDConfiguration(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ issuer := s.oidcIssuerURL(r)
+ doc := map[string]any{
+ "issuer": issuer,
+ "jwks_uri": issuer + "/jwks",
+ "authorization_endpoint": issuer + "/oauth/authorize",
+ "token_endpoint": issuer + "/oauth/token",
+ "response_types_supported": []string{"code"},
+ "subject_types_supported": []string{"public"},
+ "id_token_signing_alg_values_supported": []string{"ES256"},
+ "grant_types_supported": []string{
+ api.GrantTypeAuthorizationCode,
+ api.GrantTypeTokenExchange,
+ },
+ "code_challenge_methods_supported": []string{"S256"},
+ "claims_supported": []string{
+ "iss", "sub", "aud", "exp", "iat", "jti", "act", "sam_roles", "sam_task",
+ },
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(doc)
+}
+
+// HandleOAuthAuthorizationServer serves GET `/.well-known/oauth-authorization-server` (RFC 8414).
+func (s *Server) HandleOAuthAuthorizationServer(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ issuer := s.oidcIssuerURL(r)
+ doc := map[string]any{
+ "issuer": issuer,
+ "authorization_endpoint": issuer + "/oauth/authorize",
+ "token_endpoint": issuer + "/oauth/token",
+ "jwks_uri": issuer + "/jwks",
+ "response_types_supported": []string{"code"},
+ "grant_types_supported": []string{api.GrantTypeAuthorizationCode, api.GrantTypeTokenExchange},
+ "code_challenge_methods_supported": []string{"S256"},
+ "token_endpoint_auth_methods_supported": []string{
+ "none",
+ "client_secret_post",
+ "private_key_jwt",
+ },
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(doc)
+}
+
+// HandleJWKS serves GET `/jwks`.
+func (s *Server) HandleJWKS(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ jwks, err := s.oidcSigner.JWKS(r.Context())
+ if err != nil {
+ logger.Errorf("Failed to build JWKS: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(jwks)
+}
+
+func (s *Server) allowNodeSTSRequest(peerID string) bool {
+ if s.stsLimiter == nil {
+ return true
+ }
+ return s.stsLimiter.Allow(peerID)
+}
+
+// RevokeBiscuitID records a root Biscuit revocation ID (base64url-encoded) as
+// revoked until expiry.
+func (s *Server) RevokeBiscuitID(revocationID string, expiry time.Time) {
+ if revocationID == "" {
+ return
+ }
+ if expiry.IsZero() {
+ expiry = time.Now().Add(s.config.BiscuitTTL)
+ }
+ s.revokedBiscuitsMu.Lock()
+ s.revokedBiscuits[revocationID] = expiry
+ s.revokedBiscuitsMu.Unlock()
+}
+
+// RevokeBiscuitToken extracts the root (block 0) RevocationId of rawToken and
+// records it in the control plane's revocation set.
+func (s *Server) RevokeBiscuitToken(rawToken []byte, expiry time.Time) (string, error) {
+ b, err := biscuit.Unmarshal(rawToken)
+ if err != nil {
+ return "", err
+ }
+ ids := b.RevocationIds()
+ if len(ids) == 0 {
+ return "", errors.New("biscuit has no revocation IDs")
+ }
+ revID := base64.RawURLEncoding.EncodeToString(ids[0])
+ s.RevokeBiscuitID(revID, expiry)
+ return revID, nil
+}
+
+func (s *Server) listRevokedBiscuitIDs(ctx context.Context) ([]string, error) {
+ now := time.Now()
+ set := make(map[string]bool)
+
+ s.revokedBiscuitsMu.Lock()
+ for id, exp := range s.revokedBiscuits {
+ if now.Before(exp) {
+ set[id] = true
+ } else {
+ delete(s.revokedBiscuits, id)
+ }
+ }
+ s.revokedBiscuitsMu.Unlock()
+
+ nodes, err := s.store.ListNodes(ctx)
+ if err != nil {
+ return nil, err
+ }
+ for _, n := range nodes {
+ if !n.Banned || len(n.Biscuit) == 0 {
+ continue
+ }
+ if b, uErr := biscuit.Unmarshal(n.Biscuit); uErr == nil {
+ if ids := b.RevocationIds(); len(ids) > 0 {
+ set[base64.RawURLEncoding.EncodeToString(ids[0])] = true
+ }
+ }
+ }
+
+ out := make([]string, 0, len(set))
+ for id := range set {
+ out = append(out, id)
+ }
+ sort.Strings(out)
+ return out, nil
+}
+
+func (s *Server) isBiscuitRevoked(ctx context.Context, revocationIDs [][]byte) bool {
+ if len(revocationIDs) == 0 {
+ return false
+ }
+ revokedList, err := s.listRevokedBiscuitIDs(ctx)
+ if err != nil || len(revokedList) == 0 {
+ return false
+ }
+ revokedSet := make(map[string]bool, len(revokedList))
+ for _, id := range revokedList {
+ revokedSet[id] = true
+ }
+ for _, rawID := range revocationIDs {
+ if revokedSet[base64.RawURLEncoding.EncodeToString(rawID)] {
+ return true
+ }
+ }
+ return false
+}
+
+// HandleRevocations serves GET `/revocations` (mesh protocol, binary protobuf).
+func (s *Server) HandleRevocations(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if !s.isAdmittedNodeRequest(r) {
+ http.Error(w, "Unauthorized: node credential required", http.StatusUnauthorized)
+ return
+ }
+ ctx := r.Context()
+ bannedPeers, err := s.store.ListBannedPeerIDs(ctx)
+ if err != nil {
+ logger.Errorf("Failed to retrieve banned peers for /revocations: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ revocationIDs, err := s.listRevokedBiscuitIDs(ctx)
+ if err != nil {
+ logger.Errorf("Failed to retrieve revoked biscuit IDs for /revocations: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ resp := &api.RevocationsResponse{
+ RevocationIds: revocationIDs,
+ BannedPeerIds: bannedPeers,
+ }
+ respData, err := proto.Marshal(resp)
+ if err != nil {
+ http.Error(w, "Failed to serialize response", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(respData)
+}
+
+// HandleTokenExchange serves stateless HTTP POST `/token/exchange` (mesh protocol).
+// It verifies the calling sam-node's Biscuit + PoP challenge, verifies the
+// inbound subject JWT, resolves subject roles from mesh policy, and mints a
+// short-lived Delegated Session Biscuit with zero database writes.
+func (s *Server) HandleTokenExchange(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ nodeRecord := s.admittedNode(r)
+ if nodeRecord == nil {
+ http.Error(w, "Unauthorized: node credential required", http.StatusUnauthorized)
+ return
+ }
+ if !s.allowNodeSTSRequest(nodeRecord.PeerID) {
+ http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
+ return
+ }
+
+ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, "Failed to read body", http.StatusBadRequest)
+ return
+ }
+ defer func() { _ = r.Body.Close() }()
+
+ var req api.TokenExchangeRequest
+ if err := proto.Unmarshal(body, &req); err != nil {
+ http.Error(w, "Invalid request format", http.StatusBadRequest)
+ return
+ }
+ if strings.TrimSpace(req.SubjectToken) == "" {
+ http.Error(w, "subject_token is required", http.StatusBadRequest)
+ return
+ }
+
+ nodePubKey, err := crypto.UnmarshalPublicKey(nodeRecord.PublicKey)
+ if err != nil {
+ logger.Errorf("Corrupted public key stored for node %s: %v", nodeRecord.PeerID, err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ challengePayload := api.TokenExchangeChallenge(nodeRecord.PeerID, req.ChallengeUnixMs)
+ if err := verifyFreshChallenge(nodePubKey, challengePayload, req.ChallengeUnixMs, req.ChallengeSignature); err != nil {
+ logger.Warnw("Token exchange challenge verification failed", "peer_id", nodeRecord.PeerID, "error", err)
+ http.Error(w, "Invalid token exchange challenge: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+
+ actorPeerID, err := peer.Decode(nodeRecord.PeerID)
+ if err != nil {
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ biscuitData, biscuitExpiry, subjectID, resolvedRoles, status, err := s.mintDelegatedBiscuitFromJWT(
+ r.Context(),
+ req.SubjectToken,
+ actorPeerID,
+ req.TaskRule,
+ req.Seal,
+ 0,
+ )
+ if err != nil {
+ logger.Infow("Border Crossing",
+ "direction", "inbound",
+ "endpoint", "/token/exchange",
+ "decision", "deny",
+ "actor_node", nodeRecord.PeerID,
+ "reason", err.Error(),
+ )
+ http.Error(w, err.Error(), status)
+ return
+ }
+
+ logger.Infow("Border Crossing",
+ "direction", "inbound",
+ "endpoint", "/token/exchange",
+ "decision", "allow",
+ "actor_node", nodeRecord.PeerID,
+ "subject", subjectID,
+ "roles", resolvedRoles,
+ "expire_time", biscuitExpiry.UTC().Format(time.RFC3339),
+ )
+
+ resp := &api.TokenExchangeResponse{
+ BiscuitToken: biscuitData,
+ ExpireTime: timestamppb.New(biscuitExpiry),
+ Roles: resolvedRoles,
+ Subject: subjectID,
+ }
+ respData, err := proto.Marshal(resp)
+ if err != nil {
+ http.Error(w, "Failed to serialize response", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(respData)
+}
+
+func (s *Server) mintDelegatedBiscuitFromJWT(
+ ctx context.Context,
+ subjectJWT string,
+ actorPeerID peer.ID,
+ taskRule *api.TaskAuthorizationRule,
+ seal bool,
+ requestedTTLSeconds int64,
+) ([]byte, time.Time, string, []string, int, error) {
+ verifyCtx, cancel := context.WithTimeout(ctx, JWTVerificationTimeout)
+ defer cancel()
+
+ claims, token, err := identity.VerifyJWT(verifyCtx, subjectJWT, s.config.AllowedAudiences, s.getProviders())
+ if err != nil {
+ return nil, time.Time{}, "", nil, http.StatusUnauthorized, fmt.Errorf("JWT validation failed: %w", err)
+ }
+ if verifiedEmail(claims) == "" {
+ delete(claims, "email")
+ }
+
+ subjectKey := oidcIdentityKey(claims)
+ if subjectKey != "" {
+ banned, err := s.store.IsIdentityBanned(ctx, subjectKey)
+ if err != nil {
+ logger.Errorf("Failed to check identity ban for %s: %v", subjectKey, err)
+ return nil, time.Time{}, "", nil, http.StatusInternalServerError, errors.New("internal server error")
+ }
+ if banned {
+ return nil, time.Time{}, "", nil, http.StatusForbidden, errors.New("identity is banned")
+ }
+ }
+
+ subjectPrincipal := verifiedEmail(claims)
+ if subjectPrincipal == "" {
+ if sub, _ := claims["sub"].(string); sub != "" {
+ subjectPrincipal = sub
+ } else {
+ subjectPrincipal = subjectKey
+ }
+ }
+
+ privKey, _, err := s.store.GetCurrentKey(ctx)
+ if err != nil {
+ logger.Errorf("Failed to retrieve current signing key: %v", err)
+ return nil, time.Time{}, "", nil, http.StatusInternalServerError, errors.New("internal server error")
+ }
+
+ policyRoles, bindings, err := s.store.GetMeshPolicy(ctx)
+ if err != nil && err != storage.ErrNotFound {
+ logger.Errorf("Failed to load mesh policy for token exchange: %v", err)
+ return nil, time.Time{}, "", nil, http.StatusInternalServerError, errors.New("internal server error")
+ }
+
+ // Pass empty peerID so node:<peer> bindings on the origin node never leak to the delegated subject.
+ rawRoles := resolveRoles("", claims, bindings)
+ var resolvedRoles []string
+ for _, r := range rawRoles {
+ if r == api.RoleRouter {
+ continue
+ }
+ resolvedRoles = append(resolvedRoles, r)
+ }
+ sort.Strings(resolvedRoles)
+
+ now := time.Now()
+ ttl := s.config.DelegatedBiscuitTTL
+ if ttl <= 0 || ttl > s.config.BiscuitTTL {
+ ttl = s.config.BiscuitTTL
+ }
+ if requestedTTLSeconds > 0 {
+ reqDur := time.Duration(requestedTTLSeconds) * time.Second
+ if reqDur < ttl {
+ ttl = reqDur
+ }
+ }
+ biscuitExpiry := now.Add(ttl)
+ if !token.Expiry.IsZero() && token.Expiry.Before(biscuitExpiry) {
+ biscuitExpiry = token.Expiry
+ }
+
+ biscuitData, err := identity.MintDelegatedBiscuitToken(privKey, claims, actorPeerID, biscuitExpiry, resolvedRoles, policyRoles, taskRule, seal)
+ if err != nil {
+ logger.Errorw("Delegated Biscuit minting failed", "actor_node", actorPeerID.String(), "error", err)
+ return nil, time.Time{}, "", nil, http.StatusBadRequest, fmt.Errorf("failed to mint delegated biscuit: %w", err)
+ }
+ if taskRule != nil {
+ biscuitExpiry = api.EffectiveTARExpiration(biscuitExpiry, []*api.TaskAuthorizationRule{taskRule})
+ }
+ return biscuitData, biscuitExpiry, subjectPrincipal, resolvedRoles, http.StatusOK, nil
+}
+
+// HandleSTSToken serves stateless HTTP POST `/sts/token` (mesh protocol).
+// It authenticates the calling egress sam-node via Biscuit + PoP challenge,
+// verifies the caller's Biscuit + appended tar_block chain against standing
+// mesh policy and egress://<destination>, and mints a short-lived ES256 JWT.
+func (s *Server) HandleSTSToken(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ nodeRecord := s.admittedNode(r)
+ if nodeRecord == nil {
+ http.Error(w, "Unauthorized: node credential required", http.StatusUnauthorized)
+ return
+ }
+ if !s.allowNodeSTSRequest(nodeRecord.PeerID) {
+ http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
+ return
+ }
+
+ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, "Failed to read body", http.StatusBadRequest)
+ return
+ }
+ defer func() { _ = r.Body.Close() }()
+
+ var req api.STSTokenRequest
+ if err := proto.Unmarshal(body, &req); err != nil {
+ http.Error(w, "Invalid request format", http.StatusBadRequest)
+ return
+ }
+ if len(req.Biscuit) == 0 {
+ http.Error(w, "biscuit is required", http.StatusBadRequest)
+ return
+ }
+ if strings.TrimSpace(req.Destination) == "" {
+ http.Error(w, "destination is required", http.StatusBadRequest)
+ return
+ }
+ audience := strings.TrimSpace(req.Audience)
+ if audience == "" {
+ audience = "https://" + strings.TrimSpace(req.Destination)
+ }
+
+ nodePubKey, err := crypto.UnmarshalPublicKey(nodeRecord.PublicKey)
+ if err != nil {
+ logger.Errorf("Corrupted public key stored for node %s: %v", nodeRecord.PeerID, err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ challengePayload := api.STSTokenChallenge(nodeRecord.PeerID, req.ChallengeUnixMs)
+ if err := verifyFreshChallenge(nodePubKey, challengePayload, req.ChallengeUnixMs, req.ChallengeSignature); err != nil {
+ logger.Warnw("STS token challenge verification failed", "peer_id", nodeRecord.PeerID, "error", err)
+ http.Error(w, "Invalid STS token challenge: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+
+ claims, status, err := s.authorizeBiscuitForEgress(r.Context(), req.Biscuit, req.Destination)
+ if err != nil {
+ logger.Infow("Border Crossing",
+ "direction", "outbound",
+ "endpoint", "/sts/token",
+ "decision", "deny",
+ "actor_node", nodeRecord.PeerID,
+ "audience", audience,
+ "destination", req.Destination,
+ "reason", err.Error(),
+ )
+ http.Error(w, err.Error(), status)
+ return
+ }
+
+ now := time.Now()
+ ttl := s.config.STSTokenTTL
+ if ttl <= 0 {
+ ttl = 5 * time.Minute
+ }
+ if ttl > maxSTSTokenTTL {
+ ttl = maxSTSTokenTTL
+ }
+ jwtExpiry := now.Add(ttl)
+ if !claims.Expiration.IsZero() && claims.Expiration.Before(jwtExpiry) {
+ jwtExpiry = claims.Expiration
+ }
+ if !now.Before(jwtExpiry) {
+ http.Error(w, "Biscuit token is expired", http.StatusForbidden)
+ return
+ }
+
+ jti := cryptoRandUUID()
+ subject := claims.Principal()
+ taskName := claims.InnermostTaskName()
+ jwtClaims := jwt.MapClaims{
+ "iss": s.oidcIssuerURL(r),
+ "sub": subject,
+ "aud": audience,
+ "act": map[string]any{"sub": nodeRecord.PeerID},
+ "sam_roles": claims.Roles,
+ "iat": now.Unix(),
+ "exp": jwtExpiry.Unix(),
+ "jti": jti,
+ }
+ if taskName != "" {
+ jwtClaims["sam_task"] = taskName
+ }
+
+ signedJWT, err := s.oidcSigner.SignJWT(r.Context(), jwtClaims)
+ if err != nil {
+ logger.Errorf("Failed to sign outbound STS JWT: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ logger.Infow("Border Crossing",
+ "direction", "outbound",
+ "endpoint", "/sts/token",
+ "decision", "allow",
+ "actor_node", nodeRecord.PeerID,
+ "subject", subject,
+ "audience", audience,
+ "destination", req.Destination,
+ "task", taskName,
+ "jti", jti,
+ "expire_time", jwtExpiry.UTC().Format(time.RFC3339),
+ )
+
+ resp := &api.STSTokenResponse{
+ Jwt: signedJWT,
+ ExpireTime: timestamppb.New(jwtExpiry),
+ Subject: subject,
+ Roles: claims.Roles,
+ TaskName: taskName,
+ }
+ respData, err := proto.Marshal(resp)
+ if err != nil {
+ http.Error(w, "Failed to serialize response", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(respData)
+}
+
+func (s *Server) authorizeBiscuitForEgress(ctx context.Context, rawBiscuit []byte, destination string) (*identity.VerifiedBiscuitClaims, int, error) {
+ trustedKeys, err := s.store.GetAllValidPublicKeys(ctx)
+ if err != nil {
+ return nil, http.StatusInternalServerError, fmt.Errorf("failed to load signing keys: %w", err)
+ }
+ claims, err := identity.InspectVerifiedBiscuit(rawBiscuit, trustedKeys, s.config.BiscuitTimeout)
+ if err != nil {
+ return nil, http.StatusForbidden, fmt.Errorf("invalid caller biscuit: %w", err)
+ }
+ if s.isBiscuitRevoked(ctx, claims.RevocationIDs) {
+ return nil, http.StatusForbidden, errors.New("caller biscuit is revoked")
+ }
+ if claims.ClientPeerID == "" {
+ return nil, http.StatusForbidden, errors.New("caller biscuit lacks client_peer_id")
+ }
+ clientPeer, err := peer.Decode(claims.ClientPeerID)
+ if err != nil {
+ return nil, http.StatusForbidden, fmt.Errorf("invalid client_peer_id in biscuit: %w", err)
+ }
+ if err := identity.RequireAuthorityRequestBinding(claims.Biscuit, clientPeer); err != nil {
+ return nil, http.StatusForbidden, err
+ }
+
+ for _, peerID := range []string{claims.NodePeerID, claims.ActorNodePeerID, claims.ClientPeerID} {
+ if peerID == "" {
+ continue
+ }
+ banned, err := s.store.IsNodeBanned(ctx, peerID)
+ if err != nil {
+ return nil, http.StatusInternalServerError, fmt.Errorf("failed to check node ban: %w", err)
+ }
+ if banned {
+ return nil, http.StatusForbidden, fmt.Errorf("peer %s is banned", peerID)
+ }
+ }
+
+ authorizer, err := claims.Biscuit.Authorizer(claims.VerifyingKey, identity.AuthorizerOptions(s.config.BiscuitTimeout)...)
+ if err != nil {
+ return nil, http.StatusForbidden, err
+ }
+ authorizer.AddFact(biscuit.Fact{
+ Predicate: biscuit.Predicate{
+ Name: api.FactService,
+ IDs: []biscuit.Term{biscuit.String("egress"), biscuit.String(destination)},
+ },
+ })
+ authorizer.AddFact(biscuit.Fact{
+ Predicate: biscuit.Predicate{
+ Name: api.FactConnectionPeerID,
+ IDs: []biscuit.Term{biscuit.String(claims.ClientPeerID)},
+ },
+ })
+ authorizer.AddCheck(api.BaselineReplayCheck)
+ authorizer.AddFact(api.MarkerFact(api.FactTargetUnrestricted))
+ authorizer.AddCheck(api.BaselineTargetCheck)
+ identity.EnforceExpiration(authorizer)
+
+ for _, p := range api.BaselinePolicies {
+ authorizer.AddPolicy(p)
+ }
+ for _, r := range api.BaselineRules {
+ authorizer.AddRule(r)
+ }
+ for _, r := range api.BaselineHTTPRules {
+ authorizer.AddRule(r)
+ }
+ // Destination-level STS minting checks whether the role grants egress://<destination>
+ // at all (plain or HTTP-narrowed); per-request method/path restrictions are
+ // enforced by the egress sam-node PEP on the wire HTTP request.
+ if r, rErr := parser.FromStringRule(fmt.Sprintf(`%s($t, $k) <- %s($t, $k)`, api.FactHTTPMethodOK, api.FactService)); rErr == nil {
+ authorizer.AddRule(r)
+ }
+ if r, rErr := parser.FromStringRule(fmt.Sprintf(`%s($t, $k) <- %s($t, $k)`, api.FactHTTPPathOK, api.FactService)); rErr == nil {
+ authorizer.AddRule(r)
+ }
+ if r, rErr := parser.FromStringRule(fmt.Sprintf(`%s($t, "*") <- %s($t, $n)`, api.FactHTTPMethodOK, api.FactService)); rErr == nil {
+ authorizer.AddRule(r)
+ }
+ if r, rErr := parser.FromStringRule(fmt.Sprintf(`%s($t, "*") <- %s($t, $n)`, api.FactHTTPPathOK, api.FactService)); rErr == nil {
+ authorizer.AddRule(r)
+ }
+ if r, rErr := parser.FromStringRule(fmt.Sprintf(`%s("*", "*") <- %s($t, $n)`, api.FactHTTPMethodOK, api.FactService)); rErr == nil {
+ authorizer.AddRule(r)
+ }
+ if r, rErr := parser.FromStringRule(fmt.Sprintf(`%s("*", "*") <- %s($t, $n)`, api.FactHTTPPathOK, api.FactService)); rErr == nil {
+ authorizer.AddRule(r)
+ }
+
+ roles, bindings, err := s.store.GetMeshPolicy(ctx)
+ if err != nil && err != storage.ErrNotFound {
+ return nil, http.StatusInternalServerError, fmt.Errorf("failed to load mesh policy: %w", err)
+ }
+ egressDests, err := s.store.GetEgressDestinations(ctx)
+ if err != nil && err != storage.ErrNotFound {
+ return nil, http.StatusInternalServerError, fmt.Errorf("failed to load egress destinations: %w", err)
+ }
+ policyRules, _ := api.BuildPolicyRules(roles, bindings)
+ policyRules = append(policyRules, api.BuildEgressServingRules(egressDests)...)
+ for _, pr := range policyRules {
+ authorizer.AddRule(pr.Rule)
+ }
+
+ if err := authorizer.Authorize(); err != nil {
+ return nil, http.StatusForbidden, fmt.Errorf("standing policy denied egress://%s: %w", destination, err)
+ }
+
+ if err := api.EvaluateTaskRulesForDestination(claims.TaskRules, "egress", destination, time.Now()); err != nil {
+ return nil, http.StatusForbidden, err
+ }
+
+ // Collect any roles derived via Datalog policy bindings so sam_roles is complete.
+ if facts, qErr := authorizer.Query(biscuit.Rule{
+ Head: biscuit.Predicate{Name: "get_roles", IDs: []biscuit.Term{biscuit.Variable("r")}},
+ Body: []biscuit.Predicate{{Name: api.FactRole, IDs: []biscuit.Term{biscuit.Variable("r")}}},
+ }); qErr == nil {
+ roleSet := make(map[string]bool, len(claims.Roles))
+ for _, r := range claims.Roles {
+ roleSet[r] = true
+ }
+ for _, f := range facts {
+ if len(f.IDs) == 1 {
+ if str, ok := f.IDs[0].(biscuit.String); ok {
+ roleSet[string(str)] = true
+ }
+ }
+ }
+ merged := make([]string, 0, len(roleSet))
+ for r := range roleSet {
+ merged = append(merged, r)
+ }
+ sort.Strings(merged)
+ claims.Roles = merged
+ }
+
+ return claims, http.StatusOK, nil
+}
+
+// oauthAuthCode represents a single-use OAuth 2.1 PKCE authorization code.
+type oauthAuthCode struct {
+ Code string
+ ClientID string
+ RedirectURI string
+ CodeChallenge string
+ SubjectJWT string
+ ActorPeerID peer.ID
+ TAR *api.TaskAuthorizationRule
+ ExpiresAt time.Time
+}
+
+var oauthConsentPageTmpl = template.Must(template.New("consent").Parse(`<!DOCTYPE html>
+<html>
+<head><meta charset="utf-8"><title>Authorize Agent Task</title></head>
+<body>
+ <h2>Authorize Agent Task</h2>
+ <p>Client: <strong>{{.ClientID}}</strong></p>
+ {{if .TaskName}}<p>Task: <strong>{{.TaskName}}</strong></p>{{end}}
+ {{if .Services}}<p>Allowed Services: <code>{{.Services}}</code></p>{{end}}
+ <form method="POST" action="/oauth/authorize">
+ <input type="hidden" name="response_type" value="code">
+ <input type="hidden" name="client_id" value="{{.ClientID}}">
+ <input type="hidden" name="redirect_uri" value="{{.RedirectURI}}">
+ <input type="hidden" name="state" value="{{.State}}">
+ <input type="hidden" name="code_challenge" value="{{.CodeChallenge}}">
+ <input type="hidden" name="code_challenge_method" value="{{.CodeChallengeMethod}}">
+ <input type="hidden" name="scope" value="{{.Scope}}">
+ {{range .Resources}}<input type="hidden" name="resource" value="{{.}}">{{end}}
+ <input type="hidden" name="options" value="{{.Options}}">
+ <input type="hidden" name="actor_peer_id" value="{{.ActorPeerID}}">
+ <input type="hidden" name="id_token" value="{{.IDToken}}">
+ <input type="hidden" name="approve" value="true">
+ <button type="submit">Approve</button>
+ </form>
+</body>
+</html>`))
+
+// HandleOAuthAuthorize serves GET and POST `/oauth/authorize` (OAuth 2.1 Authorization Code + PKCE S256).
+func (s *Server) HandleOAuthAuthorize(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet && r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "Invalid form parameters", http.StatusBadRequest)
+ return
+ }
+
+ responseType := r.Form.Get("response_type")
+ if responseType != "" && responseType != "code" {
+ http.Error(w, "Unsupported response_type (must be code)", http.StatusBadRequest)
+ return
+ }
+ clientID := strings.TrimSpace(r.Form.Get("client_id"))
+ if clientID == "" {
+ http.Error(w, "client_id is required", http.StatusBadRequest)
+ return
+ }
+ redirectURI := strings.TrimSpace(r.Form.Get("redirect_uri"))
+ state := r.Form.Get("state")
+ codeChallenge := strings.TrimSpace(r.Form.Get("code_challenge"))
+ codeChallengeMethod := strings.TrimSpace(r.Form.Get("code_challenge_method"))
+ if codeChallenge == "" || (codeChallengeMethod != "" && codeChallengeMethod != "S256") {
+ http.Error(w, "PKCE code_challenge with code_challenge_method=S256 is required", http.StatusBadRequest)
+ return
+ }
+
+ subjectJWT := strings.TrimSpace(r.Form.Get("id_token"))
+ if subjectJWT == "" {
+ subjectJWT = strings.TrimSpace(r.Form.Get("id_token_hint"))
+ }
+ if subjectJWT == "" {
+ if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "Bearer ") {
+ subjectJWT = strings.TrimSpace(strings.TrimPrefix(auth, "Bearer "))
+ }
+ }
+ if subjectJWT == "" {
+ http.Error(w, "Bearer OIDC token or id_token parameter required", http.StatusUnauthorized)
+ return
+ }
+
+ // 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 {
+ http.Error(w, "Invalid OIDC token: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+
+ actorPeerStr := strings.TrimSpace(r.Form.Get("actor_peer_id"))
+ var actorPeerID peer.ID
+ if actorPeerStr != "" {
+ pID, err := peer.Decode(actorPeerStr)
+ if err != nil {
+ http.Error(w, "Invalid actor_peer_id", http.StatusBadRequest)
+ return
+ }
+ actorPeerID = pID
+ }
+
+ resources := r.Form["resource"]
+ scope := r.Form.Get("scope")
+ optionsParam := r.Form.Get("options")
+ if optionsParam == "" {
+ optionsParam = r.Form.Get("tar")
+ }
+ tarRule, err := api.BuildTARFromOAuthParams("consent-"+clientID, optionsParam, resources, scope, nil)
+ if err != nil {
+ http.Error(w, "Invalid task scope/options: "+err.Error(), http.StatusBadRequest)
+ return
+ }
+
+ if r.Method == http.MethodGet && r.Form.Get("approve") != "true" && strings.Contains(r.Header.Get("Accept"), "text/html") {
+ var svcList []string
+ var taskName string
+ if tarRule != nil {
+ taskName = tarRule.GetName()
+ for _, rule := range tarRule.GetRules() {
+ svcList = append(svcList, rule.GetAllowedServices()...)
+ }
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.WriteHeader(http.StatusOK)
+ _ = oauthConsentPageTmpl.Execute(w, map[string]any{
+ "ClientID": clientID,
+ "RedirectURI": redirectURI,
+ "State": state,
+ "CodeChallenge": codeChallenge,
+ "CodeChallengeMethod": "S256",
+ "Scope": scope,
+ "Resources": resources,
+ "Options": optionsParam,
+ "ActorPeerID": actorPeerStr,
+ "IDToken": subjectJWT,
+ "TaskName": taskName,
+ "Services": strings.Join(svcList, ", "),
+ })
+ return
+ }
+
+ rawCode := make([]byte, 24)
+ if _, err := rand.Read(rawCode); err != nil {
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ code := base64.RawURLEncoding.EncodeToString(rawCode)
+
+ now := time.Now()
+ s.oauthCodesMu.Lock()
+ for k, v := range s.oauthCodes {
+ if now.After(v.ExpiresAt) {
+ delete(s.oauthCodes, k)
+ }
+ }
+ s.oauthCodes[code] = &oauthAuthCode{
+ Code: code,
+ ClientID: clientID,
+ RedirectURI: redirectURI,
+ CodeChallenge: codeChallenge,
+ SubjectJWT: subjectJWT,
+ ActorPeerID: actorPeerID,
+ TAR: tarRule,
+ ExpiresAt: now.Add(oauthAuthCodeTTL),
+ }
+ s.oauthCodesMu.Unlock()
+
+ if redirectURI != "" {
+ u, err := url.Parse(redirectURI)
+ if err != nil {
+ http.Error(w, "Invalid redirect_uri", http.StatusBadRequest)
+ return
+ }
+ q := u.Query()
+ q.Set("code", code)
+ if state != "" {
+ q.Set("state", state)
+ }
+ u.RawQuery = q.Encode()
+ http.Redirect(w, r, u.String(), http.StatusFound)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": code,
+ "state": state,
+ })
+}
+
+// HandleOAuthToken serves POST `/oauth/token` supporting OAuth 2.1
+// `authorization_code` (with PKCE S256) and RFC 8693 `token-exchange`.
+func (s *Server) HandleOAuthToken(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
+ if err := r.ParseForm(); err != nil {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_request", "Failed to parse form body")
+ return
+ }
+
+ grantType := r.Form.Get("grant_type")
+ switch grantType {
+ case api.GrantTypeAuthorizationCode:
+ s.handleOAuthAuthCodeGrant(w, r)
+ case api.GrantTypeTokenExchange:
+ s.handleOAuthTokenExchangeGrant(w, r)
+ default:
+ writeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type", "Unsupported grant_type")
+ }
+}
+
+func decodeBase64Biscuit(encoded string) ([]byte, error) {
+ encoded = strings.TrimSpace(encoded)
+ if b, err := base64.StdEncoding.DecodeString(encoded); err == nil {
+ return b, nil
+ }
+ return base64.RawURLEncoding.DecodeString(encoded)
+}
+
+func (s *Server) resolveDefaultActorPeer(ctx context.Context, r *http.Request) (peer.ID, error) {
+ if nodeRecord := s.admittedNode(r); nodeRecord != nil {
+ return peer.Decode(nodeRecord.PeerID)
+ }
+ if actorToken := strings.TrimSpace(r.Form.Get("actor_token")); actorToken != "" {
+ rawActor, err := decodeBase64Biscuit(actorToken)
+ if err != nil {
+ return "", fmt.Errorf("invalid actor_token: %w", err)
+ }
+ trustedKeys, err := s.store.GetAllValidPublicKeys(ctx)
+ if err != nil {
+ return "", err
+ }
+ return identity.VerifyAndExtractPeerID(trustedKeys, rawActor, s.config.BiscuitTimeout)
+ }
+ if peerStr := strings.TrimSpace(r.Form.Get("actor_peer_id")); peerStr != "" {
+ return peer.Decode(peerStr)
+ }
+ _, pub, err := s.store.GetCurrentKey(ctx)
+ if err != nil {
+ return "", err
+ }
+ ck, err := crypto.UnmarshalEd25519PublicKey(pub)
+ if err != nil {
+ return "", err
+ }
+ return peer.IDFromPublicKey(ck)
+}
+
+func (s *Server) handleOAuthAuthCodeGrant(w http.ResponseWriter, r *http.Request) {
+ code := strings.TrimSpace(r.Form.Get("code"))
+ codeVerifier := strings.TrimSpace(r.Form.Get("code_verifier"))
+ clientID := strings.TrimSpace(r.Form.Get("client_id"))
+ redirectURI := strings.TrimSpace(r.Form.Get("redirect_uri"))
+ if code == "" || codeVerifier == "" {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_request", "code and code_verifier are required")
+ return
+ }
+
+ s.oauthCodesMu.Lock()
+ entry, ok := s.oauthCodes[code]
+ if ok {
+ delete(s.oauthCodes, code)
+ }
+ s.oauthCodesMu.Unlock()
+
+ if !ok || time.Now().After(entry.ExpiresAt) {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "Authorization code is invalid or expired")
+ return
+ }
+ if clientID != "" && entry.ClientID != "" && clientID != entry.ClientID {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "client_id mismatch")
+ return
+ }
+ if entry.RedirectURI != "" && redirectURI != entry.RedirectURI {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "redirect_uri mismatch")
+ return
+ }
+
+ verifierHash := sha256.Sum256([]byte(codeVerifier))
+ computedChallenge := base64.RawURLEncoding.EncodeToString(verifierHash[:])
+ if subtle.ConstantTimeCompare([]byte(computedChallenge), []byte(entry.CodeChallenge)) != 1 {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "PKCE code_verifier verification failed")
+ return
+ }
+
+ actorPeerID := entry.ActorPeerID
+ if actorPeerID == "" {
+ var err error
+ actorPeerID, err = s.resolveDefaultActorPeer(r.Context(), r)
+ if err != nil {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_request", "Could not resolve actor node peer_id: "+err.Error())
+ return
+ }
+ }
+
+ seal := r.Form.Get("seal") == "true"
+ biscuitData, biscuitExpiry, _, _, status, err := s.mintDelegatedBiscuitFromJWT(r.Context(), entry.SubjectJWT, actorPeerID, entry.TAR, seal, 0)
+ if err != nil {
+ writeOAuthError(w, status, "invalid_grant", err.Error())
+ return
+ }
+
+ expiresIn := int64(time.Until(biscuitExpiry).Seconds())
+ if expiresIn < 0 {
+ expiresIn = 0
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "access_token": base64.StdEncoding.EncodeToString(biscuitData),
+ "issued_token_type": api.TokenTypeBiscuit,
+ "token_type": "Bearer",
+ "expires_in": expiresIn,
+ })
+}
+
+func (s *Server) handleOAuthTokenExchangeGrant(w http.ResponseWriter, r *http.Request) {
+ subjectToken := strings.TrimSpace(r.Form.Get("subject_token"))
+ subjectTokenType := strings.TrimSpace(r.Form.Get("subject_token_type"))
+ if subjectToken == "" {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_request", "subject_token is required")
+ return
+ }
+
+ var reqTTL int64
+ if ttlStr := strings.TrimSpace(r.Form.Get("expires_in")); ttlStr != "" {
+ if parsed, err := strconv.ParseInt(ttlStr, 10, 64); err == nil && parsed > 0 {
+ reqTTL = parsed
+ }
+ }
+
+ var tarExpire *timestamppb.Timestamp
+ if reqTTL > 0 {
+ tarExpire = timestamppb.New(time.Now().Add(time.Duration(reqTTL) * time.Second))
+ }
+ tarRule, err := api.BuildTARFromOAuthParams(
+ r.Form.Get("task_name"),
+ r.Form.Get("options"),
+ r.Form["resource"],
+ r.Form.Get("scope"),
+ tarExpire,
+ )
+ if err != nil {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_request", err.Error())
+ return
+ }
+ seal := r.Form.Get("seal") == "true"
+
+ var biscuitData []byte
+ var biscuitExpiry time.Time
+
+ if subjectTokenType == api.TokenTypeBiscuit {
+ rawBiscuit, err := decodeBase64Biscuit(subjectToken)
+ if err != nil {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_request", "Invalid biscuit subject_token")
+ return
+ }
+ trustedKeys, err := s.store.GetAllValidPublicKeys(r.Context())
+ if err != nil {
+ writeOAuthError(w, http.StatusInternalServerError, "server_error", "Failed to load signing keys")
+ return
+ }
+ claims, err := identity.InspectVerifiedBiscuit(rawBiscuit, trustedKeys, s.config.BiscuitTimeout)
+ if err != nil {
+ writeOAuthError(w, http.StatusUnauthorized, "invalid_grant", "Invalid subject biscuit: "+err.Error())
+ return
+ }
+ biscuitData = rawBiscuit
+ biscuitExpiry = claims.Expiration
+ if tarRule != nil {
+ biscuitData, err = identity.AttenuateBiscuit(biscuitData, tarRule)
+ if err != nil {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_request", "Failed to attenuate biscuit: "+err.Error())
+ return
+ }
+ biscuitExpiry = api.EffectiveTARExpiration(biscuitExpiry, []*api.TaskAuthorizationRule{tarRule})
+ }
+ if seal {
+ biscuitData, err = identity.SealBiscuit(biscuitData)
+ if err != nil {
+ writeOAuthError(w, http.StatusInternalServerError, "server_error", "Failed to seal biscuit")
+ return
+ }
+ }
+ } else {
+ actorPeerID, err := s.resolveDefaultActorPeer(r.Context(), r)
+ if err != nil {
+ writeOAuthError(w, http.StatusBadRequest, "invalid_request", "Could not resolve actor peer_id: "+err.Error())
+ return
+ }
+ var status int
+ biscuitData, biscuitExpiry, _, _, status, err = s.mintDelegatedBiscuitFromJWT(r.Context(), subjectToken, actorPeerID, tarRule, seal, reqTTL)
+ if err != nil {
+ writeOAuthError(w, status, "invalid_grant", err.Error())
+ return
+ }
+ }
+
+ expiresIn := int64(time.Until(biscuitExpiry).Seconds())
+ if expiresIn < 0 {
+ expiresIn = 0
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "access_token": base64.StdEncoding.EncodeToString(biscuitData),
+ "issued_token_type": api.TokenTypeBiscuit,
+ "token_type": "Bearer",
+ "expires_in": expiresIn,
+ })
+}
+
+func writeOAuthError(w http.ResponseWriter, status int, errCode, description string) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(map[string]string{
+ "error": errCode,
+ "error_description": description,
+ })
+}
diff --git a/internal/controlplane/sts_test.go b/internal/controlplane/sts_test.go
new file mode 100644
index 00000000..858c2147
--- /dev/null
+++ b/internal/controlplane/sts_test.go
@@ -0,0 +1,667 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package controlplane
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/url"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ jwt "github.com/golang-jwt/jwt/v5"
+ "github.com/google/sam/api"
+ "github.com/google/sam/internal/identity"
+ "github.com/google/sam/internal/node"
+ "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 enrollTestNodeForSTS(t *testing.T, baseURL string, mintOIDC func(map[string]interface{}) string) (crypto.PrivKey, peer.ID, []byte, ed25519.PublicKey) {
+ t.Helper()
+ priv, pub, err := crypto.GenerateEd25519Key(rand.Reader)
+ if err != nil {
+ t.Fatalf("generate key: %v", err)
+ }
+ peerID, err := peer.IDFromPublicKey(pub)
+ if err != nil {
+ t.Fatalf("peer id: %v", err)
+ }
+ pubBytes, err := crypto.MarshalPublicKey(pub)
+ if err != nil {
+ t.Fatalf("marshal pub: %v", err)
+ }
+ ts := time.Now().UnixMilli()
+ sig, err := priv.Sign(api.RegisterChallenge(peerID.String(), ts))
+ if err != nil {
+ t.Fatalf("sign challenge: %v", err)
+ }
+ enrollReq := &api.EnrollRequest{
+ Jwt: mintOIDC(map[string]interface{}{"sub": "node-operator", "email": "[email protected]", "email_verified": true}),
+ PeerId: peerID.String(),
+ PublicKey: pubBytes,
+ RequestedRole: api.RoleNode,
+ ChallengeUnixMs: ts,
+ ChallengeSignature: sig,
+ }
+ reqBytes, _ := proto.Marshal(enrollReq)
+ resp, err := http.Post(baseURL+"/register", "application/x-protobuf", bytes.NewReader(reqBytes))
+ if err != nil {
+ t.Fatalf("register request failed: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("register returned %d: %s", resp.StatusCode, string(body))
+ }
+ var enrollResp api.EnrollResponse
+ if err := proto.Unmarshal(body, &enrollResp); err != nil {
+ t.Fatalf("unmarshal EnrollResponse: %v", err)
+ }
+ return priv, peerID, enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.ControlPlanePublicKey)
+}
+
+func TestTokenExchangeStatelessAndRoleIsolation(t *testing.T) {
+ issuer, mintOIDC := startCustomMockOIDC(t)
+ srv, store, baseURL := setupTestServer(t, issuer)
+ defer func() { _ = srv.Close() }()
+
+ // Seed initial policy allowing open node enrollment so we can enroll nodeA.
+ ctx := context.Background()
+ initialRoles := []*api.PolicyRole{
+ {Name: api.RoleNode, AllowedServices: []string{"mcp://weather"}, AllowedTargets: []string{"*"}},
+ }
+ initialBindings := []*api.PolicyBinding{
+ {Role: api.RoleNode, Members: []string{api.SystemAuthenticated}},
+ }
+ if err := store.SavePolicyDocument(ctx, initialRoles, initialBindings, nil); err != nil {
+ t.Fatalf("SavePolicyDocument: %v", err)
+ }
+
+ nodePriv, nodePeerID, nodeBiscuit, cpPubKey := enrollTestNodeForSTS(t, baseURL, mintOIDC)
+
+ // Now update policy so that:
+ // - node:<nodePeerID> is bound to "node-admin-role" (granting mcp://internal-admin)
+ // - user:alice-sub is bound to "analyst" (granting mcp://weather and egress://bigquery.googleapis.com)
+ roles := []*api.PolicyRole{
+ {Name: api.RoleNode, AllowedServices: []string{"mcp://weather"}, AllowedTargets: []string{"*"}},
+ {Name: "node-admin-role", AllowedServices: []string{"mcp://internal-admin"}, AllowedTargets: []string{"*"}},
+ {Name: "analyst", AllowedServices: []string{"mcp://weather", "egress://bigquery.googleapis.com"}, AllowedTargets: []string{"*"}},
+ }
+ bindings := []*api.PolicyBinding{
+ {Role: api.RoleNode, Members: []string{api.SystemAuthenticated}},
+ {Role: "node-admin-role", Members: []string{"node:" + nodePeerID.String()}},
+ {Role: "analyst", Members: []string{"user:alice-sub"}},
+ }
+ if err := store.SavePolicyDocument(ctx, roles, bindings, nil); err != nil {
+ t.Fatalf("SavePolicyDocument: %v", err)
+ }
+
+ nodesBefore, err := store.ListNodes(ctx)
+ if err != nil {
+ t.Fatalf("ListNodes: %v", err)
+ }
+
+ aliceJWT := mintOIDC(map[string]interface{}{
+ "sub": "alice-sub",
+ "email": "[email protected]",
+ "email_verified": true,
+ })
+
+ ts := time.Now().UnixMilli()
+ sig, err := nodePriv.Sign(api.TokenExchangeChallenge(nodePeerID.String(), ts))
+ if err != nil {
+ t.Fatalf("sign challenge: %v", err)
+ }
+ exReq := &api.TokenExchangeRequest{
+ SubjectToken: aliceJWT,
+ TaskRule: &api.TaskAuthorizationRule{
+ Name: "weather-check",
+ Rules: []*api.TaskRule{
+ {
+ AllowedServices: []string{"mcp://weather"},
+ Operation: &api.TaskOperation{AllowedTools: []string{"get_forecast"}},
+ },
+ },
+ },
+ ChallengeUnixMs: ts,
+ ChallengeSignature: sig,
+ }
+ exBytes, _ := proto.Marshal(exReq)
+ httpReq, _ := http.NewRequest(http.MethodPost, baseURL+"/token/exchange", bytes.NewReader(exBytes))
+ httpReq.Header.Set("Content-Type", "application/x-protobuf")
+ httpReq.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(nodeBiscuit))
+
+ resp, err := http.DefaultClient.Do(httpReq)
+ if err != nil {
+ t.Fatalf("POST /token/exchange failed: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ respBody, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("POST /token/exchange returned %d: %s", resp.StatusCode, string(respBody))
+ }
+
+ var exResp api.TokenExchangeResponse
+ if err := proto.Unmarshal(respBody, &exResp); err != nil {
+ t.Fatalf("unmarshal TokenExchangeResponse: %v", err)
+ }
+ if exResp.Subject != "[email protected]" {
+ t.Fatalf("Subject = %q, want [email protected]", exResp.Subject)
+ }
+ if slices.Contains(exResp.Roles, "node-admin-role") {
+ t.Fatalf("delegated token leaked node:<peer> role: %v", exResp.Roles)
+ }
+ if !slices.Contains(exResp.Roles, "analyst") {
+ t.Fatalf("expected analyst role in %v", exResp.Roles)
+ }
+
+ // Verify zero DB writes occurred during /token/exchange.
+ nodesAfter, err := store.ListNodes(ctx)
+ if err != nil {
+ t.Fatalf("ListNodes after exchange: %v", err)
+ }
+ if len(nodesAfter) != len(nodesBefore) {
+ t.Fatalf("nodes count changed from %d to %d; /token/exchange must be stateless", len(nodesBefore), len(nodesAfter))
+ }
+
+ // Delegated Biscuit must NOT pass peer handshake verification (no node() fact).
+ if _, err := identity.VerifyBiscuit(exResp.BiscuitToken, nodePeerID, []ed25519.PublicKey{cpPubKey}, time.Second); err == nil {
+ t.Fatal("expected VerifyBiscuit (peer handshake) to reject delegated token lacking node() fact")
+ }
+
+ // Verify SamNode.Authorize accepts the delegated token for mcp://weather get_forecast,
+ // denies mcp://weather drop_table (TAR), and denies mcp://internal-admin (standing policy).
+ compiledRules, _ := api.BuildPolicyRules(roles, bindings)
+ parsedRules, err := api.ParseDatalogRules(api.PolicyRuleTexts(compiledRules))
+ if err != nil {
+ t.Fatalf("ParseDatalogRules: %v", err)
+ }
+ nStore, err := node.NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ defer func() { _ = nStore.Close() }()
+ verifierNode, err := node.NewSamNode(node.Options{
+ PrivKey: nodePriv,
+ Store: nStore,
+ ControlPlanePubKey: cpPubKey,
+ BiscuitTimeout: time.Second,
+ })
+ if err != nil {
+ t.Fatalf("NewSamNode: %v", err)
+ }
+ verifierNode.MeshPolicyRules = parsedRules
+ verifierNode.SetIdentityCache(nodeBiscuit)
+
+ if err := verifierNode.Authorize(exResp.BiscuitToken, node.RequestContext{
+ PeerID: nodePeerID,
+ Protocol: string(api.MCPProtocolID),
+ Target: "mcp://weather",
+ MCPTool: "get_forecast",
+ }, cpPubKey); err != nil {
+ t.Fatalf("expected Authorize to allow get_forecast on mcp://weather, got: %v", err)
+ }
+
+ if err := verifierNode.Authorize(exResp.BiscuitToken, node.RequestContext{
+ PeerID: nodePeerID,
+ Protocol: string(api.MCPProtocolID),
+ Target: "mcp://weather",
+ MCPTool: "drop_table",
+ }, cpPubKey); err == nil {
+ t.Fatal("expected Authorize to deny drop_table on mcp://weather")
+ }
+
+ if err := verifierNode.Authorize(exResp.BiscuitToken, node.RequestContext{
+ PeerID: nodePeerID,
+ Protocol: string(api.MCPProtocolID),
+ Target: "mcp://internal-admin",
+ MCPTool: "get_forecast",
+ }, cpPubKey); err == nil {
+ t.Fatal("expected Authorize to deny mcp://internal-admin")
+ }
+}
+
+func jwkToECDSAPublicKey(t *testing.T, jwk JSONWebKey) *ecdsa.PublicKey {
+ t.Helper()
+ xBytes, err := base64.RawURLEncoding.DecodeString(jwk.X)
+ if err != nil {
+ t.Fatalf("decode jwk.X: %v", err)
+ }
+ yBytes, err := base64.RawURLEncoding.DecodeString(jwk.Y)
+ if err != nil {
+ t.Fatalf("decode jwk.Y: %v", err)
+ }
+ uncompressed := make([]byte, 0, 1+len(xBytes)+len(yBytes))
+ uncompressed = append(uncompressed, 0x04)
+ uncompressed = append(uncompressed, xBytes...)
+ uncompressed = append(uncompressed, yBytes...)
+ pub, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), uncompressed)
+ if err != nil {
+ t.Fatalf("ParseUncompressedPublicKey: %v", err)
+ }
+ return pub
+}
+
+func TestOIDCIssuerJWKSAndSTSToken(t *testing.T) {
+ issuer, mintOIDC := startCustomMockOIDC(t)
+ srv, store, baseURL := setupTestServer(t, issuer, func(o *Options) {
+ o.STSIssuerURL = "https://cp.sam-mesh.example"
+ })
+ defer func() { _ = srv.Close() }()
+
+ ctx := context.Background()
+ roles := []*api.PolicyRole{
+ {Name: api.RoleNode, AllowedServices: []string{"mcp://weather"}, AllowedTargets: []string{"*"}},
+ {Name: "analyst", AllowedServices: []string{"egress://bigquery.googleapis.com", "mcp://weather"}, AllowedTargets: []string{"*"}},
+ }
+ bindings := []*api.PolicyBinding{
+ {Role: api.RoleNode, Members: []string{api.SystemAuthenticated}},
+ {Role: "analyst", Members: []string{"user:alice-sub"}},
+ }
+ if err := store.SavePolicyDocument(ctx, roles, bindings, nil); err != nil {
+ t.Fatalf("SavePolicyDocument: %v", err)
+ }
+
+ nodePriv, nodePeerID, nodeBiscuit, _ := enrollTestNodeForSTS(t, baseURL, mintOIDC)
+
+ // 1. Check /.well-known/openid-configuration
+ discResp, err := http.Get(baseURL + "/.well-known/openid-configuration")
+ if err != nil {
+ t.Fatalf("GET openid-configuration: %v", err)
+ }
+ defer func() { _ = discResp.Body.Close() }()
+ var discDoc map[string]any
+ if err := json.NewDecoder(discResp.Body).Decode(&discDoc); err != nil {
+ t.Fatalf("decode discovery doc: %v", err)
+ }
+ if discDoc["issuer"] != "https://cp.sam-mesh.example" {
+ t.Fatalf("issuer = %v, want https://cp.sam-mesh.example", discDoc["issuer"])
+ }
+ if discDoc["jwks_uri"] != "https://cp.sam-mesh.example/jwks" {
+ t.Fatalf("jwks_uri = %v", discDoc["jwks_uri"])
+ }
+
+ // 2. Mint a delegated Biscuit for Alice with a TAR allowing egress://bigquery.googleapis.com
+ aliceJWT := mintOIDC(map[string]interface{}{
+ "sub": "alice-sub",
+ "email": "[email protected]",
+ "email_verified": true,
+ })
+ ts := time.Now().UnixMilli()
+ sig, _ := nodePriv.Sign(api.TokenExchangeChallenge(nodePeerID.String(), ts))
+ exReq := &api.TokenExchangeRequest{
+ SubjectToken: aliceJWT,
+ TaskRule: &api.TaskAuthorizationRule{
+ Name: "bq-export",
+ Rules: []*api.TaskRule{
+ {
+ AllowedServices: []string{"egress://bigquery.googleapis.com"},
+ Operation: &api.TaskOperation{AllowedMethods: []string{"POST"}, AllowedPaths: []string{"/bigquery/v2/*"}},
+ },
+ },
+ },
+ ChallengeUnixMs: ts,
+ ChallengeSignature: sig,
+ }
+ exBytes, _ := proto.Marshal(exReq)
+ httpExReq, _ := http.NewRequest(http.MethodPost, baseURL+"/token/exchange", bytes.NewReader(exBytes))
+ httpExReq.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(nodeBiscuit))
+ exHTTPResp, err := http.DefaultClient.Do(httpExReq)
+ if err != nil || exHTTPResp.StatusCode != http.StatusOK {
+ t.Fatalf("token exchange failed: %v", err)
+ }
+ exBody, _ := io.ReadAll(exHTTPResp.Body)
+ _ = exHTTPResp.Body.Close()
+ var exResp api.TokenExchangeResponse
+ _ = proto.Unmarshal(exBody, &exResp)
+
+ // 3. Call POST /sts/token for bigquery.googleapis.com
+ stsTs := time.Now().UnixMilli()
+ stsSig, _ := nodePriv.Sign(api.STSTokenChallenge(nodePeerID.String(), stsTs))
+ stsReq := &api.STSTokenRequest{
+ Biscuit: exResp.BiscuitToken,
+ Destination: "bigquery.googleapis.com",
+ Audience: "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/sam/providers/cp",
+ ChallengeUnixMs: stsTs,
+ ChallengeSignature: stsSig,
+ }
+ stsReqBytes, _ := proto.Marshal(stsReq)
+ httpSTSReq, _ := http.NewRequest(http.MethodPost, baseURL+"/sts/token", bytes.NewReader(stsReqBytes))
+ httpSTSReq.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(nodeBiscuit))
+ stsHTTPResp, err := http.DefaultClient.Do(httpSTSReq)
+ if err != nil {
+ t.Fatalf("POST /sts/token failed: %v", err)
+ }
+ defer func() { _ = stsHTTPResp.Body.Close() }()
+ stsBody, _ := io.ReadAll(stsHTTPResp.Body)
+ if stsHTTPResp.StatusCode != http.StatusOK {
+ t.Fatalf("POST /sts/token returned %d: %s", stsHTTPResp.StatusCode, string(stsBody))
+ }
+ var stsResp api.STSTokenResponse
+ if err := proto.Unmarshal(stsBody, &stsResp); err != nil {
+ t.Fatalf("unmarshal STSTokenResponse: %v", err)
+ }
+ if stsResp.Subject != "[email protected]" || stsResp.TaskName != "bq-export" {
+ t.Fatalf("unexpected STSTokenResponse metadata: subject=%q task=%q", stsResp.Subject, stsResp.TaskName)
+ }
+
+ // 4. Rotate OIDC key with overlap and verify both old and new keys appear in /jwks
+ if _, err := srv.RotateOIDCKey(time.Minute); err != nil {
+ t.Fatalf("RotateOIDCKey: %v", err)
+ }
+ jwksResp, err := http.Get(baseURL + "/jwks")
+ if err != nil {
+ t.Fatalf("GET /jwks: %v", err)
+ }
+ defer func() { _ = jwksResp.Body.Close() }()
+ var jwks JSONWebKeySet
+ if err := json.NewDecoder(jwksResp.Body).Decode(&jwks); err != nil {
+ t.Fatalf("decode JWKS: %v", err)
+ }
+ if len(jwks.Keys) != 2 {
+ t.Fatalf("expected 2 keys in JWKS after overlap rotation, got %d", len(jwks.Keys))
+ }
+
+ // Verify the JWT minted before rotation against the JWKS!
+ parsedJWT, err := jwt.Parse(stsResp.Jwt, func(tok *jwt.Token) (any, error) {
+ kid, _ := tok.Header["kid"].(string)
+ for _, k := range jwks.Keys {
+ if k.Kid == kid {
+ return jwkToECDSAPublicKey(t, k), nil
+ }
+ }
+ return nil, jwt.ErrTokenUnverifiable
+ })
+ if err != nil || !parsedJWT.Valid {
+ t.Fatalf("failed to verify STS JWT against /jwks: %v", err)
+ }
+ claims := parsedJWT.Claims.(jwt.MapClaims)
+ if claims["sub"] != "[email protected]" {
+ t.Fatalf("jwt sub = %v, want [email protected]", claims["sub"])
+ }
+ if claims["sam_task"] != "bq-export" {
+ t.Fatalf("jwt sam_task = %v, want bq-export", claims["sam_task"])
+ }
+ actMap, _ := claims["act"].(map[string]any)
+ if actMap["sub"] != nodePeerID.String() {
+ t.Fatalf("jwt act.sub = %v, want %s", actMap["sub"], nodePeerID.String())
+ }
+
+ // 5. Verify /sts/token denies destination not allowed by TAR (e.g. api.github.com)
+ badSTSReq := &api.STSTokenRequest{
+ Biscuit: exResp.BiscuitToken,
+ Destination: "api.github.com",
+ Audience: "https://api.github.com",
+ ChallengeUnixMs: stsTs,
+ ChallengeSignature: stsSig,
+ }
+ badBytes, _ := proto.Marshal(badSTSReq)
+ httpBadReq, _ := http.NewRequest(http.MethodPost, baseURL+"/sts/token", bytes.NewReader(badBytes))
+ httpBadReq.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(nodeBiscuit))
+ badResp, err := http.DefaultClient.Do(httpBadReq)
+ if err != nil {
+ t.Fatalf("POST /sts/token failed: %v", err)
+ }
+ _ = badResp.Body.Close()
+ if badResp.StatusCode != http.StatusForbidden {
+ t.Fatalf("expected 403 for unauthorized destination, got %d", badResp.StatusCode)
+ }
+
+ // 6. Revoke the Biscuit and verify /sts/token denies it and /revocations lists it
+ revID, err := srv.RevokeBiscuitToken(exResp.BiscuitToken, time.Now().Add(time.Hour))
+ if err != nil {
+ t.Fatalf("RevokeBiscuitToken: %v", err)
+ }
+ httpRevokedSTS, _ := http.NewRequest(http.MethodPost, baseURL+"/sts/token", bytes.NewReader(stsReqBytes))
+ httpRevokedSTS.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(nodeBiscuit))
+ revSTSResp, err := http.DefaultClient.Do(httpRevokedSTS)
+ if err != nil {
+ t.Fatalf("POST /sts/token failed: %v", err)
+ }
+ _ = revSTSResp.Body.Close()
+ if revSTSResp.StatusCode != http.StatusForbidden {
+ t.Fatalf("expected 403 for revoked Biscuit at /sts/token, got %d", revSTSResp.StatusCode)
+ }
+
+ httpRevList, _ := http.NewRequest(http.MethodGet, baseURL+"/revocations", nil)
+ httpRevList.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(nodeBiscuit))
+ revListResp, err := http.DefaultClient.Do(httpRevList)
+ if err != nil {
+ t.Fatalf("GET /revocations failed: %v", err)
+ }
+ defer func() { _ = revListResp.Body.Close() }()
+ revListBody, _ := io.ReadAll(revListResp.Body)
+ var revocations api.RevocationsResponse
+ if err := proto.Unmarshal(revListBody, &revocations); err != nil {
+ t.Fatalf("unmarshal RevocationsResponse: %v", err)
+ }
+ if !slices.Contains(revocations.RevocationIds, revID) {
+ t.Fatalf("expected revocation ID %q in %v", revID, revocations.RevocationIds)
+ }
+}
+
+func TestOAuth21AuthorizationCodePKCEAndTokenExchange(t *testing.T) {
+ issuer, mintOIDC := startCustomMockOIDC(t)
+ srv, store, baseURL := setupTestServer(t, issuer)
+ defer func() { _ = srv.Close() }()
+
+ ctx := context.Background()
+ roles := []*api.PolicyRole{
+ {Name: api.RoleNode, AllowedServices: []string{"mcp://weather"}, AllowedTargets: []string{"*"}},
+ {Name: "analyst", AllowedServices: []string{"mcp://weather", "inference://gemini.pro"}, AllowedTargets: []string{"*"}},
+ }
+ bindings := []*api.PolicyBinding{
+ {Role: api.RoleNode, Members: []string{api.SystemAuthenticated}},
+ {Role: "analyst", Members: []string{"user:alice-sub"}},
+ }
+ if err := store.SavePolicyDocument(ctx, roles, bindings, nil); err != nil {
+ t.Fatalf("SavePolicyDocument: %v", err)
+ }
+
+ nodePriv, nodePeerID, nodeBiscuit, cpPubKey := enrollTestNodeForSTS(t, baseURL, mintOIDC)
+ aliceJWT := mintOIDC(map[string]interface{}{
+ "sub": "alice-sub",
+ "email": "[email protected]",
+ "email_verified": true,
+ })
+
+ // 1. Perform OAuth 2.1 Authorization Code + PKCE S256
+ codeVerifier := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
+ verifierHash := sha256.Sum256([]byte(codeVerifier))
+ codeChallenge := base64.RawURLEncoding.EncodeToString(verifierHash[:])
+
+ authForm := url.Values{
+ "response_type": {"code"},
+ "client_id": {"planner-ui"},
+ "code_challenge": {codeChallenge},
+ "code_challenge_method": {"S256"},
+ "resource": {"mcp://weather"},
+ "scope": {"tool:get_forecast"},
+ "actor_peer_id": {nodePeerID.String()},
+ "state": {"xyz-123"},
+ "approve": {"true"},
+ }
+ authReq, _ := http.NewRequest(http.MethodPost, baseURL+"/oauth/authorize", strings.NewReader(authForm.Encode()))
+ authReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ authReq.Header.Set("Authorization", "Bearer "+aliceJWT)
+
+ authResp, err := http.DefaultClient.Do(authReq)
+ if err != nil {
+ t.Fatalf("POST /oauth/authorize: %v", err)
+ }
+ defer func() { _ = authResp.Body.Close() }()
+ if authResp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(authResp.Body)
+ t.Fatalf("POST /oauth/authorize returned %d: %s", authResp.StatusCode, string(body))
+ }
+ var codePayload map[string]string
+ if err := json.NewDecoder(authResp.Body).Decode(&codePayload); err != nil {
+ t.Fatalf("decode code payload: %v", err)
+ }
+ authCode := codePayload["code"]
+ if authCode == "" || codePayload["state"] != "xyz-123" {
+ t.Fatalf("unexpected authorize response: %v", codePayload)
+ }
+
+ // Wrong PKCE verifier must fail (and consume the single-use code, so issue a second one after).
+ badTokForm := url.Values{
+ "grant_type": {api.GrantTypeAuthorizationCode},
+ "code": {authCode},
+ "client_id": {"planner-ui"},
+ "code_verifier": {"wrong-verifier"},
+ }
+ badTokResp, err := http.PostForm(baseURL+"/oauth/token", badTokForm)
+ if err != nil {
+ t.Fatalf("POST /oauth/token: %v", err)
+ }
+ _ = badTokResp.Body.Close()
+ if badTokResp.StatusCode != http.StatusBadRequest {
+ t.Fatalf("expected 400 on bad PKCE verifier, got %d", badTokResp.StatusCode)
+ }
+
+ // Issue a fresh code and redeem with the valid PKCE code_verifier.
+ authReq2, _ := http.NewRequest(http.MethodPost, baseURL+"/oauth/authorize", strings.NewReader(authForm.Encode()))
+ authReq2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ authReq2.Header.Set("Authorization", "Bearer "+aliceJWT)
+ authResp2, _ := http.DefaultClient.Do(authReq2)
+ _ = json.NewDecoder(authResp2.Body).Decode(&codePayload)
+ _ = authResp2.Body.Close()
+
+ tokForm := url.Values{
+ "grant_type": {api.GrantTypeAuthorizationCode},
+ "code": {codePayload["code"]},
+ "client_id": {"planner-ui"},
+ "code_verifier": {codeVerifier},
+ }
+ tokResp, err := http.PostForm(baseURL+"/oauth/token", tokForm)
+ if err != nil {
+ t.Fatalf("POST /oauth/token: %v", err)
+ }
+ defer func() { _ = tokResp.Body.Close() }()
+ if tokResp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(tokResp.Body)
+ t.Fatalf("POST /oauth/token returned %d: %s", tokResp.StatusCode, string(body))
+ }
+ var tokJSON map[string]any
+ if err := json.NewDecoder(tokResp.Body).Decode(&tokJSON); err != nil {
+ t.Fatalf("decode token response: %v", err)
+ }
+ if tokJSON["issued_token_type"] != api.TokenTypeBiscuit {
+ t.Fatalf("issued_token_type = %v, want %s", tokJSON["issued_token_type"], api.TokenTypeBiscuit)
+ }
+ biscuitB64, _ := tokJSON["access_token"].(string)
+ biscuitBytes, err := base64.StdEncoding.DecodeString(biscuitB64)
+ if err != nil {
+ t.Fatalf("decode access_token biscuit: %v", err)
+ }
+
+ // Verify the returned Biscuit has 1 appended tar_block narrowing to mcp://weather get_forecast.
+ _, taskRules, err := identity.UnmarshalInbound(biscuitBytes)
+ if err != nil {
+ t.Fatalf("UnmarshalInbound: %v", err)
+ }
+ if len(taskRules) != 1 {
+ t.Fatalf("expected 1 tar_block on OAuth biscuit, got %d", len(taskRules))
+ }
+
+ // 2. Test RFC 8693 Token Exchange on /oauth/token to further attenuate and seal the Biscuit.
+ subTAR := &api.TaskAuthorizationRule{
+ Name: "sealed-subtask",
+ ExpireTime: timestamppb.New(time.Now().Add(5 * time.Minute)),
+ Rules: []*api.TaskRule{
+ {
+ AllowedServices: []string{"mcp://weather"},
+ Operation: &api.TaskOperation{AllowedTools: []string{"get_forecast"}},
+ },
+ },
+ }
+ subTARB64, err := api.EncodeTARBlockPayload(subTAR)
+ if err != nil {
+ t.Fatalf("EncodeTARBlockPayload: %v", err)
+ }
+ exForm := url.Values{
+ "grant_type": {api.GrantTypeTokenExchange},
+ "subject_token": {biscuitB64},
+ "subject_token_type": {api.TokenTypeBiscuit},
+ "options": {subTARB64},
+ "seal": {"true"},
+ }
+ exTokResp, err := http.PostForm(baseURL+"/oauth/token", exForm)
+ if err != nil {
+ t.Fatalf("POST /oauth/token (exchange): %v", err)
+ }
+ defer func() { _ = exTokResp.Body.Close() }()
+ if exTokResp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(exTokResp.Body)
+ t.Fatalf("POST /oauth/token (exchange) returned %d: %s", exTokResp.StatusCode, string(body))
+ }
+ var exTokJSON map[string]any
+ _ = json.NewDecoder(exTokResp.Body).Decode(&exTokJSON)
+ sealedBytes, _ := base64.StdEncoding.DecodeString(exTokJSON["access_token"].(string))
+
+ // Sealed Biscuit must have 2 tar_blocks and reject further attenuation!
+ _, rules2, err := identity.UnmarshalInbound(sealedBytes)
+ if err != nil {
+ t.Fatalf("UnmarshalInbound sealed: %v", err)
+ }
+ if len(rules2) != 2 {
+ t.Fatalf("expected 2 tar_blocks, got %d", len(rules2))
+ }
+ if _, err := identity.AttenuateBiscuit(sealedBytes, subTAR); err == nil {
+ t.Fatal("expected AttenuateBiscuit on a sealed token to fail")
+ }
+
+ // And verify the 2-block sealed Biscuit authorizes mcp://weather get_forecast on SamNode.
+ compiledRules, _ := api.BuildPolicyRules(roles, bindings)
+ parsedRules, _ := api.ParseDatalogRules(api.PolicyRuleTexts(compiledRules))
+ nStore, err := node.NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ defer func() { _ = nStore.Close() }()
+ verifierNode, err := node.NewSamNode(node.Options{
+ PrivKey: nodePriv,
+ Store: nStore,
+ ControlPlanePubKey: cpPubKey,
+ BiscuitTimeout: time.Second,
+ })
+ if err != nil {
+ t.Fatalf("NewSamNode: %v", err)
+ }
+ verifierNode.MeshPolicyRules = parsedRules
+ verifierNode.SetIdentityCache(nodeBiscuit)
+ if err := verifierNode.Authorize(sealedBytes, node.RequestContext{
+ PeerID: nodePeerID,
+ Protocol: string(api.MCPProtocolID),
+ Target: "mcp://weather",
+ MCPTool: "get_forecast",
+ }, cpPubKey); err != nil {
+ t.Fatalf("expected sealed 2-hop OAuth Biscuit to authorize get_forecast, got: %v", err)
+ }
+}
diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.go
index eb7960b8..f6210b62 100644
--- a/internal/identity/biscuit.go
+++ b/internal/identity/biscuit.go
@@ -236,16 +236,39 @@ const authorityBlockID = 0
// TestAttenuationBlockFactsAreInvisibleToTheAuthorizer), so this lookup is the
// only place the distinction has to be made by hand.
func RequireAuthorityBinding(b *biscuit.Biscuit, expectedPeer peer.ID) error {
+ return requireAuthorityFact(b, api.FactNode, expectedPeer.String())
+}
+
+// RequireAuthorityRequestBinding checks that a request token is bound to
+// expectedPeer in the authority block: either as a direct member token
+// carrying node(expectedPeer), or as a delegated session token (minted at
+// POST /token/exchange) carrying both actor_node(expectedPeer) and
+// client_peer_id(expectedPeer) in the authority block without node().
+func RequireAuthorityRequestBinding(b *biscuit.Biscuit, expectedPeer peer.ID) error {
+ if err := RequireAuthorityBinding(b, expectedPeer); err == nil {
+ return nil
+ }
+ peerStr := expectedPeer.String()
+ if err := requireAuthorityFact(b, api.FactActorNode, peerStr); err != nil {
+ return fmt.Errorf("token is not bound to peer %s (neither %s nor %s in authority block): %w", expectedPeer, api.FactNode, api.FactActorNode, err)
+ }
+ if err := requireAuthorityFact(b, api.FactClientPeerID, peerStr); err != nil {
+ return fmt.Errorf("delegated token is not bound to client peer %s: %w", expectedPeer, err)
+ }
+ return nil
+}
+
+func requireAuthorityFact(b *biscuit.Biscuit, factName, value string) error {
boundFact := biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactNode,
- IDs: []biscuit.Term{biscuit.String(expectedPeer.String())},
+ Name: factName,
+ IDs: []biscuit.Term{biscuit.String(value)},
}}
blockID, err := b.GetBlockID(boundFact)
if err != nil {
- return fmt.Errorf("token is not bound to peer %s: %w", expectedPeer, err)
+ return fmt.Errorf("token is not bound to peer %s via %s: %w", value, factName, err)
}
if blockID != authorityBlockID {
- return fmt.Errorf("token is not bound to peer %s: %s fact comes from appended block %d, not the authority block", expectedPeer, api.FactNode, blockID)
+ return fmt.Errorf("token is not bound to peer %s: %s fact comes from appended block %d, not the authority block", value, factName, blockID)
}
return nil
}
@@ -287,15 +310,58 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
return nil, nil, fmt.Errorf("claims cannot be nil")
}
- biscuitBytes, err := mintBiscuit(signingKey, remotePeer, roles, biscuitExpiry, claims, policyRoles, labels)
+ biscuitBytes, err := mintBiscuitWithBinding(signingKey, remotePeer, false, roles, biscuitExpiry, claims, policyRoles, labels)
if err != nil {
return nil, nil, err
}
return biscuitBytes, roles, nil
}
+// MintDelegatedBiscuitToken generates a stateless Delegated Session Biscuit for
+// a subject whose credential was exchanged by actorPeer at POST /token/exchange.
+// The authority block carries client_peer_id(actorPeer) and
+// actor_node(actorPeer), and deliberately omits node(actorPeer) so policy
+// bindings targeting node:<actorPeer> never attach the node's roles to the
+// delegated subject.
+func MintDelegatedBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, actorPeer peer.ID, biscuitExpiry time.Time, roles []string, policyRoles []*api.PolicyRole, taskRule *api.TaskAuthorizationRule, seal bool) ([]byte, error) {
+ return MintDelegatedBiscuitTokenWithRand(rand.Reader, signingKey, claims, actorPeer, biscuitExpiry, roles, policyRoles, taskRule, seal)
+}
+
+// MintDelegatedBiscuitTokenWithRand is MintDelegatedBiscuitToken with an
+// explicit random source (used by deterministic conformance vector generators).
+func MintDelegatedBiscuitTokenWithRand(rng io.Reader, signingKey ed25519.PrivateKey, claims jwt.MapClaims, actorPeer peer.ID, biscuitExpiry time.Time, roles []string, policyRoles []*api.PolicyRole, taskRule *api.TaskAuthorizationRule, seal bool) ([]byte, error) {
+ if claims == nil {
+ return nil, fmt.Errorf("claims cannot be nil")
+ }
+ biscuitBytes, err := mintBiscuitWithBindingAndRand(rng, signingKey, actorPeer, true, roles, biscuitExpiry, claims, policyRoles, nil)
+ if err != nil {
+ return nil, err
+ }
+ if taskRule != nil {
+ biscuitBytes, err = AttenuateBiscuitWithRand(rng, biscuitBytes, taskRule)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if seal {
+ biscuitBytes, err = SealBiscuitWithRand(rng, biscuitBytes)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return biscuitBytes, nil
+}
+
func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []string, expiration time.Time, claims jwt.MapClaims, policyRoles []*api.PolicyRole, labels map[string]string) ([]byte, error) {
- builder := biscuit.NewBuilder(signingKey)
+ return mintBiscuitWithBinding(signingKey, remotePeer, false, roles, expiration, claims, policyRoles, labels)
+}
+
+func mintBiscuitWithBinding(signingKey ed25519.PrivateKey, remotePeer peer.ID, delegated bool, roles []string, expiration time.Time, claims jwt.MapClaims, policyRoles []*api.PolicyRole, labels map[string]string) ([]byte, error) {
+ return mintBiscuitWithBindingAndRand(rand.Reader, signingKey, remotePeer, delegated, roles, expiration, claims, policyRoles, labels)
+}
+
+func mintBiscuitWithBindingAndRand(rng io.Reader, signingKey ed25519.PrivateKey, remotePeer peer.ID, delegated bool, roles []string, expiration time.Time, claims jwt.MapClaims, policyRoles []*api.PolicyRole, labels map[string]string) ([]byte, error) {
+ builder := biscuit.NewBuilder(signingKey, biscuit.WithRandom(rng))
addedFacts := make(map[string]bool)
addFact := func(fact biscuit.Fact) error {
factStr := fact.String()
@@ -316,11 +382,20 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []stri
return nil, fmt.Errorf("failed to add expiration fact: %w", err)
}
- if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: api.FactNode,
- IDs: []biscuit.Term{biscuit.String(remotePeer.String())},
- }}); err != nil {
- return nil, fmt.Errorf("failed to add node fact: %w", err)
+ if delegated {
+ if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactActorNode,
+ IDs: []biscuit.Term{biscuit.String(remotePeer.String())},
+ }}); err != nil {
+ return nil, fmt.Errorf("failed to add actor_node fact: %w", err)
+ }
+ } else {
+ if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactNode,
+ IDs: []biscuit.Term{biscuit.String(remotePeer.String())},
+ }}); err != nil {
+ return nil, fmt.Errorf("failed to add node fact: %w", err)
+ }
}
if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{
@@ -722,3 +797,132 @@ func RequireRole(b *biscuit.Biscuit, key ed25519.PublicKey, expectedRole string,
}
return nil
}
+
+// VerifiedBiscuitClaims holds the authority facts, effective expiration,
+// revocation IDs, and TaskAuthorizationRule chain extracted from a verified
+// Biscuit token.
+type VerifiedBiscuitClaims struct {
+ Biscuit *biscuit.Biscuit
+ VerifyingKey ed25519.PublicKey
+ User string
+ Email string
+ Roles []string
+ NodePeerID string
+ ActorNodePeerID string
+ ClientPeerID string
+ Expiration time.Time
+ RevocationIDs [][]byte
+ TaskRules []*api.TaskAuthorizationRule
+}
+
+// Principal returns the primary subject identifier for audit logs and border
+// JWTs: Email when present, otherwise User, otherwise "node:<NodePeerID>" or
+// "peer:<ClientPeerID>".
+func (c *VerifiedBiscuitClaims) Principal() string {
+ if c.Email != "" {
+ return c.Email
+ }
+ if c.User != "" {
+ return c.User
+ }
+ if c.NodePeerID != "" {
+ return "node:" + c.NodePeerID
+ }
+ if c.ClientPeerID != "" {
+ return "peer:" + c.ClientPeerID
+ }
+ return ""
+}
+
+// InnermostTaskName returns the name of the last appended TaskAuthorizationRule
+// block, or "" if the token carries no appended blocks.
+func (c *VerifiedBiscuitClaims) InnermostTaskName() string {
+ if len(c.TaskRules) == 0 {
+ return ""
+ }
+ return c.TaskRules[len(c.TaskRules)-1].GetName()
+}
+
+// InspectVerifiedBiscuit parses a Biscuit, validates its appended tar_block
+// chain, verifies its signature and expiration against trustedPublicKeys, and
+// extracts its authority claims and effective expiration.
+func InspectVerifiedBiscuit(biscuitData []byte, trustedPublicKeys []ed25519.PublicKey, timeout time.Duration) (*VerifiedBiscuitClaims, error) {
+ b, rules, err := UnmarshalInbound(biscuitData)
+ if err != nil {
+ return nil, err
+ }
+
+ authOpts := AuthorizerOptions(timeout)
+ var authorizer biscuit.Authorizer
+ var verifyingKey ed25519.PublicKey
+ var lastErr error
+ for _, pubKey := range trustedPublicKeys {
+ candidate, err := b.Authorizer(pubKey, authOpts...)
+ if err != nil {
+ lastErr = err
+ continue
+ }
+ EnforceExpiration(candidate)
+ candidate.AddPolicy(api.AllowIfTruePolicy)
+ if err := candidate.Authorize(); err == nil {
+ authorizer = candidate
+ verifyingKey = pubKey
+ break
+ } else {
+ lastErr = err
+ }
+ }
+ if authorizer == nil {
+ return nil, fmt.Errorf("signature or expiration verification failed: %v", lastErr)
+ }
+
+ expiry, err := expirationOf(authorizer)
+ if err != nil {
+ return nil, err
+ }
+ expiry = api.EffectiveTARExpiration(expiry, rules)
+ if !time.Now().Before(expiry) {
+ return nil, fmt.Errorf("token tar_block expired at %s", expiry.UTC().Format(time.RFC3339))
+ }
+
+ queryStrings := func(factName string) []string {
+ facts, err := authorizer.Query(biscuit.Rule{
+ Head: biscuit.Predicate{Name: "q", IDs: []biscuit.Term{biscuit.Variable("v")}},
+ Body: []biscuit.Predicate{{Name: factName, IDs: []biscuit.Term{biscuit.Variable("v")}}},
+ })
+ if err != nil {
+ return nil
+ }
+ var out []string
+ for _, f := range facts {
+ if len(f.IDs) == 1 {
+ if s, ok := f.IDs[0].(biscuit.String); ok {
+ out = append(out, string(s))
+ }
+ }
+ }
+ sort.Strings(out)
+ return out
+ }
+ firstString := func(factName string) string {
+ vals := queryStrings(factName)
+ if len(vals) == 0 {
+ return ""
+ }
+ return vals[0]
+ }
+
+ return &VerifiedBiscuitClaims{
+ Biscuit: b,
+ VerifyingKey: verifyingKey,
+ User: firstString(api.FactUser),
+ Email: firstString(api.FactEmail),
+ Roles: queryStrings(api.FactRole),
+ NodePeerID: firstString(api.FactNode),
+ ActorNodePeerID: firstString(api.FactActorNode),
+ ClientPeerID: firstString(api.FactClientPeerID),
+ Expiration: expiry,
+ RevocationIDs: b.RevocationIds(),
+ TaskRules: rules,
+ }, nil
+}
diff --git a/internal/node/controlplane_sync.go b/internal/node/controlplane_sync.go
index 3d279450..10daa5bf 100644
--- a/internal/node/controlplane_sync.go
+++ b/internal/node/controlplane_sync.go
@@ -22,6 +22,7 @@ import (
"math/rand"
"time"
+ cpclient "github.com/google/sam/internal/controlplane/client"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
)
@@ -64,9 +65,35 @@ func (n *SamNode) SyncControlPlane(ctx context.Context) error {
if err := n.syncEgressAssignments(ctx, controlPlaneURL); err != nil {
errs = append(errs, fmt.Errorf("egress: %w", err))
}
+ if err := n.syncRevocations(ctx, controlPlaneURL); err != nil {
+ errs = append(errs, fmt.Errorf("revocations: %w", err))
+ }
return errors.Join(errs...)
}
+func (n *SamNode) syncRevocations(ctx context.Context, controlPlaneURL string) error {
+ token := n.GetIdentity()
+ if len(token) == 0 {
+ return nil
+ }
+ fetchedAt := time.Now()
+ resp, err := controlPlaneClient(controlPlaneURL).FetchRevocations(ctx, token)
+ if errors.Is(err, cpclient.ErrNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ expiry := fetchedAt.Add(24 * time.Hour)
+ for _, revID := range resp.GetRevocationIds() {
+ n.RevokeBiscuitID(revID, expiry)
+ }
+ if len(resp.GetBannedPeerIds()) > 0 {
+ n.reconcileBannedPeers(resp.GetBannedPeerIds(), fetchedAt)
+ }
+ return nil
+}
+
// syncTrustedKeys replaces the trust set with the control plane's current
// /keys answer and persists it. Enrollment hands out only the newest key, so
// this is how a node learns the key still in its rotation grace period (which
diff --git a/internal/node/egress.go b/internal/node/egress.go
index 9046af5a..e9f1637e 100644
--- a/internal/node/egress.go
+++ b/internal/node/egress.go
@@ -313,7 +313,7 @@ func handleLocalEgress(node *SamNode, w http.ResponseWriter, r *http.Request) {
refuse(w, http.StatusNotFound, fmt.Sprintf("no egress destination %q is assigned to this node", host), proxyStatusDestinationNotFound)
return
}
- identity := node.GetIdentity()
+ identity := node.GetRequestIdentity(r.Context())
if len(identity) == 0 {
http.Error(w, "node has no credential yet", http.StatusServiceUnavailable)
return
diff --git a/internal/node/ext_authz.go b/internal/node/ext_authz.go
new file mode 100644
index 00000000..2fb8eddc
--- /dev/null
+++ b/internal/node/ext_authz.go
@@ -0,0 +1,580 @@
+// 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"
+ "encoding/base64"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/peer"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/encoding/protowire"
+)
+
+const (
+ // HeaderSamMCPTool lets an external proxy (or ext_proc filter) pass the
+ // extracted MCP tool name during an ext_authz check.
+ HeaderSamMCPTool = "X-Sam-Mcp-Tool"
+)
+
+type extAuthzCheckInput struct {
+ Method string
+ Path string
+ Host string
+ Headers map[string]string
+}
+
+type extAuthzCheckResult struct {
+ Allowed bool
+ HTTPStatus int
+ Message string
+ ResponseHeaders map[string]string
+}
+
+// handleExtAuthzHTTP implements Envoy's HTTP ext_authz check service on
+// /ext_authz and /ext_authz/*.
+func handleExtAuthzHTTP(node *SamNode, w http.ResponseWriter, r *http.Request) {
+ headers := make(map[string]string, len(r.Header))
+ for k, vals := range r.Header {
+ if len(vals) > 0 {
+ headers[strings.ToLower(k)] = vals[0]
+ }
+ }
+ checkPath := strings.TrimPrefix(r.URL.Path, "/ext_authz")
+ if origPath := headers["x-envoy-original-path"]; origPath != "" {
+ checkPath = origPath
+ } else if origPath := headers["x-original-path"]; origPath != "" {
+ checkPath = origPath
+ }
+ if checkPath == "" {
+ checkPath = "/"
+ }
+ method := r.Method
+ if origMethod := headers["x-original-method"]; origMethod != "" {
+ method = origMethod
+ }
+
+ res := evaluateExtAuthz(r.Context(), node, extAuthzCheckInput{
+ Method: method,
+ Path: checkPath,
+ Host: r.Host,
+ Headers: headers,
+ })
+ if !res.Allowed {
+ http.Error(w, res.Message, res.HTTPStatus)
+ return
+ }
+ for k, v := range res.ResponseHeaders {
+ w.Header().Set(k, v)
+ }
+ w.WriteHeader(http.StatusOK)
+}
+
+// handleExtAuthzGRPC implements Envoy's gRPC ext_authz service
+// (/envoy.service.auth.v3.Authorization/Check and v2) over HTTP/2 using
+// standard protobuf wire encoding without external gRPC dependencies.
+func handleExtAuthzGRPC(node *SamNode, w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ defer func() { _ = r.Body.Close() }()
+ frame, err := readGRPCFrame(io.LimitReader(r.Body, maxRequestBodyBytes))
+ if err != nil {
+ writeGRPCError(w, 3, fmt.Sprintf("invalid gRPC frame: %v", err)) // INVALID_ARGUMENT = 3
+ return
+ }
+ in, err := unmarshalEnvoyCheckRequest(frame)
+ if err != nil {
+ writeGRPCError(w, 3, fmt.Sprintf("invalid CheckRequest: %v", err))
+ return
+ }
+ res := evaluateExtAuthz(r.Context(), node, in)
+ respPayload := marshalEnvoyCheckResponse(res)
+
+ w.Header().Set("Content-Type", "application/grpc")
+ w.Header().Set("Trailer", "Grpc-Status, Grpc-Message")
+ w.WriteHeader(http.StatusOK)
+ _ = writeGRPCFrame(w, respPayload)
+ w.Header().Set("Grpc-Status", "0")
+ w.Header().Set("Grpc-Message", "")
+}
+
+func evaluateExtAuthz(ctx context.Context, node *SamNode, in extAuthzCheckInput) extAuthzCheckResult {
+ if node == nil {
+ return extAuthzCheckResult{
+ Allowed: false,
+ HTTPStatus: http.StatusServiceUnavailable,
+ Message: "Service Unavailable: Node Not Initialized",
+ }
+ }
+
+ rawBiscuit, status, err := extractAndVerifyExtAuthzBiscuit(ctx, node, in.Headers)
+ if err != nil {
+ return extAuthzCheckResult{
+ Allowed: false,
+ HTTPStatus: status,
+ Message: err.Error(),
+ }
+ }
+
+ claims, err := node.VerifyLocalBiscuit(rawBiscuit)
+ if err != nil {
+ return extAuthzCheckResult{
+ Allowed: false,
+ HTTPStatus: http.StatusForbidden,
+ Message: fmt.Sprintf("Forbidden: %v", err),
+ }
+ }
+
+ target, reqPath := resolveExtAuthzTarget(in)
+ if target != "" {
+ var callerPeer peer.ID
+ var isLocal bool
+ if peerHdr := in.Headers[strings.ToLower(api.HeaderPeerID)]; peerHdr != "" {
+ if pid, pErr := peer.Decode(peerHdr); pErr == nil {
+ callerPeer = pid
+ }
+ }
+ if callerPeer == "" && claims.ActorNodePeerID != "" {
+ if pid, pErr := peer.Decode(claims.ActorNodePeerID); pErr == nil {
+ callerPeer = pid
+ }
+ }
+ if callerPeer == "" && claims.NodePeerID != "" {
+ if pid, pErr := peer.Decode(claims.NodePeerID); pErr == nil {
+ callerPeer = pid
+ }
+ }
+ if callerPeer == "" {
+ if pid, pErr := node.localPeerID(); pErr == nil {
+ callerPeer = pid
+ }
+ isLocal = true
+ }
+ if localPID, pErr := node.localPeerID(); pErr == nil && callerPeer == localPID {
+ isLocal = true
+ }
+
+ method := in.Method
+ if method == "" {
+ method = http.MethodGet
+ }
+ if reqPath == "" {
+ reqPath = "/"
+ }
+ reqCtx := RequestContext{
+ PeerID: callerPeer,
+ Protocol: "ext_authz",
+ Target: target,
+ MCPTool: in.Headers[strings.ToLower(HeaderSamMCPTool)],
+ HTTP: &HTTPRequestFacts{Method: method, Path: reqPath},
+ Local: isLocal,
+ }
+ if after, ok := strings.CutPrefix(target, api.EgressServicePrefix); ok {
+ reqCtx.Egress = &EgressFacts{Host: after, Port: 443}
+ if node.services != nil {
+ if svc, ok := node.services.GetTyped(api.ServiceType_SERVICE_TYPE_EGRESS, after); ok {
+ if ef := egressFactsFor(svc); ef != nil {
+ reqCtx.Egress = ef
+ }
+ }
+ }
+ }
+ if err := node.VerifyBiscuitToken(rawBiscuit, reqCtx); err != nil {
+ return extAuthzCheckResult{
+ Allowed: false,
+ HTTPStatus: http.StatusForbidden,
+ Message: fmt.Sprintf("Forbidden: %v", err),
+ }
+ }
+ }
+
+ respHeaders := map[string]string{
+ api.HeaderSamBiscuit: base64.StdEncoding.EncodeToString(rawBiscuit),
+ api.HeaderSamPrincipal: claims.Principal(),
+ api.HeaderSamRoles: strings.Join(claims.Roles, ","),
+ }
+ if len(claims.TaskRules) > 0 {
+ lastRule := claims.TaskRules[len(claims.TaskRules)-1]
+ if taskJSON, mErr := (protojson.MarshalOptions{UseProtoNames: true}).Marshal(lastRule); mErr == nil {
+ respHeaders[api.HeaderSamTask] = string(taskJSON)
+ }
+ }
+
+ return extAuthzCheckResult{
+ Allowed: true,
+ HTTPStatus: http.StatusOK,
+ ResponseHeaders: respHeaders,
+ }
+}
+
+func extractAndVerifyExtAuthzBiscuit(ctx context.Context, node *SamNode, headers map[string]string) ([]byte, int, error) {
+ if rawB64 := strings.TrimSpace(headers[strings.ToLower(api.HeaderSamBiscuit)]); rawB64 != "" {
+ raw, err := decodeBiscuitToken(rawB64)
+ if err != nil {
+ return nil, http.StatusForbidden, fmt.Errorf("invalid %s header: %w", api.HeaderSamBiscuit, err)
+ }
+ return raw, http.StatusOK, nil
+ }
+
+ var bearer string
+ for _, h := range []string{strings.ToLower(api.HeaderSamAuthentication), "authorization"} {
+ val := strings.TrimSpace(headers[h])
+ if val == "" {
+ continue
+ }
+ parts := strings.SplitN(val, " ", 2)
+ if len(parts) == 2 && strings.EqualFold(parts[0], "bearer") {
+ bearer = strings.TrimSpace(parts[1])
+ break
+ }
+ }
+ if bearer == "" {
+ return nil, http.StatusUnauthorized, errors.New("unauthorized: missing Bearer token or X-Sam-Biscuit header")
+ }
+
+ if raw, err := decodeBiscuitToken(bearer); err == nil {
+ return raw, http.StatusOK, nil
+ }
+ if isLikelyJWT(bearer) {
+ resp, err := node.ExchangeSubjectJWT(ctx, bearer, api.TokenTypeJWT, nil, false)
+ if err != nil {
+ return nil, http.StatusForbidden, fmt.Errorf("JWT token exchange failed: %w", err)
+ }
+ return resp.GetBiscuitToken(), http.StatusOK, nil
+ }
+ return nil, http.StatusForbidden, errors.New("forbidden: unrecognizable credential")
+}
+
+func resolveExtAuthzTarget(in extAuthzCheckInput) (target, reqPath string) {
+ path := in.Path
+ if idx := strings.IndexByte(path, '?'); idx >= 0 {
+ path = path[:idx]
+ }
+ if explicit := strings.TrimSpace(in.Headers[strings.ToLower(api.HeaderSamTargetService)]); explicit != "" {
+ return explicit, path
+ }
+ if strings.HasPrefix(path, "/sam/") {
+ if route, ok := parseEgressRoute(path); ok {
+ up := "/" + route.upstreamPath
+ return route.serviceType + "://" + route.serviceName, up
+ }
+ }
+ if after, ok := strings.CutPrefix(path, "/egress/"); ok {
+ host, rest, _ := strings.Cut(after, "/")
+ host = api.NormalizeMeshHost(host)
+ if host != "" {
+ return api.EgressServicePrefix + host, "/" + rest
+ }
+ }
+ trimmed := strings.TrimPrefix(path, "/")
+ parts := strings.SplitN(trimmed, "/", 3)
+ if len(parts) >= 2 {
+ scheme := strings.ToLower(parts[0])
+ switch scheme {
+ case api.ServiceTypeStringMCP, api.ServiceTypeStringInference, api.ServiceTypeStringA2A, api.ServiceTypeStringEgress, "http":
+ rest := "/"
+ if len(parts) == 3 {
+ rest = "/" + parts[2]
+ }
+ return scheme + "://" + parts[1], rest
+ }
+ }
+ return "", path
+}
+
+func readGRPCFrame(r io.Reader) ([]byte, error) {
+ var hdr [5]byte
+ if _, err := io.ReadFull(r, hdr[:]); err != nil {
+ return nil, err
+ }
+ if hdr[0] != 0 {
+ return nil, errors.New("compressed gRPC frames are not supported")
+ }
+ length := binary.BigEndian.Uint32(hdr[1:5])
+ if length > maxRequestBodyBytes {
+ return nil, fmt.Errorf("gRPC message length %d exceeds limit", length)
+ }
+ buf := make([]byte, length)
+ if _, err := io.ReadFull(r, buf); err != nil {
+ return nil, err
+ }
+ return buf, nil
+}
+
+func writeGRPCFrame(w io.Writer, payload []byte) error {
+ var hdr [5]byte
+ hdr[0] = 0
+ binary.BigEndian.PutUint32(hdr[1:5], uint32(len(payload)))
+ if _, err := w.Write(hdr[:]); err != nil {
+ return err
+ }
+ _, err := w.Write(payload)
+ return err
+}
+
+func writeGRPCError(w http.ResponseWriter, code int, msg string) {
+ w.Header().Set("Content-Type", "application/grpc")
+ w.Header().Set("Grpc-Status", fmt.Sprintf("%d", code))
+ w.Header().Set("Grpc-Message", msg)
+ w.WriteHeader(http.StatusOK)
+}
+
+// unmarshalEnvoyCheckRequest decodes envoy.service.auth.v3.CheckRequest:
+//
+// message CheckRequest {
+// AttributeContext attributes = 1;
+// }
+// message AttributeContext {
+// Request request = 4;
+// message Request {
+// HttpRequest http = 2;
+// }
+// message HttpRequest {
+// string method = 2;
+// map<string, string> headers = 3;
+// string path = 4;
+// string host = 5;
+// }
+// }
+func unmarshalEnvoyCheckRequest(b []byte) (extAuthzCheckInput, error) {
+ out := extAuthzCheckInput{Headers: make(map[string]string)}
+ for len(b) > 0 {
+ num, typ, n := protowire.ConsumeTag(b)
+ if n < 0 {
+ return out, protowire.ParseError(n)
+ }
+ b = b[n:]
+ if num == 1 && typ == protowire.BytesType {
+ attrBytes, m := protowire.ConsumeBytes(b)
+ if m < 0 {
+ return out, protowire.ParseError(m)
+ }
+ b = b[m:]
+ if err := parseAttributeContext(attrBytes, &out); err != nil {
+ return out, err
+ }
+ continue
+ }
+ m := protowire.ConsumeFieldValue(num, typ, b)
+ if m < 0 {
+ return out, protowire.ParseError(m)
+ }
+ b = b[m:]
+ }
+ return out, nil
+}
+
+func parseAttributeContext(b []byte, out *extAuthzCheckInput) error {
+ for len(b) > 0 {
+ num, typ, n := protowire.ConsumeTag(b)
+ if n < 0 {
+ return protowire.ParseError(n)
+ }
+ b = b[n:]
+ if num == 4 && typ == protowire.BytesType {
+ reqBytes, m := protowire.ConsumeBytes(b)
+ if m < 0 {
+ return protowire.ParseError(m)
+ }
+ b = b[m:]
+ if err := parseAttributeRequest(reqBytes, out); err != nil {
+ return err
+ }
+ continue
+ }
+ m := protowire.ConsumeFieldValue(num, typ, b)
+ if m < 0 {
+ return protowire.ParseError(m)
+ }
+ b = b[m:]
+ }
+ return nil
+}
+
+func parseAttributeRequest(b []byte, out *extAuthzCheckInput) error {
+ for len(b) > 0 {
+ num, typ, n := protowire.ConsumeTag(b)
+ if n < 0 {
+ return protowire.ParseError(n)
+ }
+ b = b[n:]
+ if num == 2 && typ == protowire.BytesType {
+ httpBytes, m := protowire.ConsumeBytes(b)
+ if m < 0 {
+ return protowire.ParseError(m)
+ }
+ b = b[m:]
+ if err := parseAttributeHTTPRequest(httpBytes, out); err != nil {
+ return err
+ }
+ continue
+ }
+ m := protowire.ConsumeFieldValue(num, typ, b)
+ if m < 0 {
+ return protowire.ParseError(m)
+ }
+ b = b[m:]
+ }
+ return nil
+}
+
+func parseAttributeHTTPRequest(b []byte, out *extAuthzCheckInput) error {
+ for len(b) > 0 {
+ num, typ, n := protowire.ConsumeTag(b)
+ if n < 0 {
+ return protowire.ParseError(n)
+ }
+ b = b[n:]
+ if typ == protowire.BytesType {
+ valBytes, m := protowire.ConsumeBytes(b)
+ if m < 0 {
+ return protowire.ParseError(m)
+ }
+ b = b[m:]
+ switch num {
+ case 2:
+ out.Method = string(valBytes)
+ case 3:
+ k, v, err := parseStringMapEntry(valBytes)
+ if err != nil {
+ return err
+ }
+ out.Headers[strings.ToLower(k)] = v
+ case 4:
+ out.Path = string(valBytes)
+ case 5:
+ out.Host = string(valBytes)
+ }
+ continue
+ }
+ m := protowire.ConsumeFieldValue(num, typ, b)
+ if m < 0 {
+ return protowire.ParseError(m)
+ }
+ b = b[m:]
+ }
+ return nil
+}
+
+func parseStringMapEntry(b []byte) (string, string, error) {
+ var k, v string
+ for len(b) > 0 {
+ num, typ, n := protowire.ConsumeTag(b)
+ if n < 0 {
+ return "", "", protowire.ParseError(n)
+ }
+ b = b[n:]
+ if typ == protowire.BytesType && (num == 1 || num == 2) {
+ val, m := protowire.ConsumeBytes(b)
+ if m < 0 {
+ return "", "", protowire.ParseError(m)
+ }
+ b = b[m:]
+ if num == 1 {
+ k = string(val)
+ } else {
+ v = string(val)
+ }
+ continue
+ }
+ m := protowire.ConsumeFieldValue(num, typ, b)
+ if m < 0 {
+ return "", "", protowire.ParseError(m)
+ }
+ b = b[m:]
+ }
+ return k, v, nil
+}
+
+// marshalEnvoyCheckResponse encodes envoy.service.auth.v3.CheckResponse:
+//
+// message CheckResponse {
+// google.rpc.Status status = 1;
+// oneof http_response {
+// DeniedHttpResponse denied_response = 2;
+// OkHttpResponse ok_response = 3;
+// }
+// }
+func marshalEnvoyCheckResponse(res extAuthzCheckResult) []byte {
+ var out []byte
+ if res.Allowed {
+ // status = {code: 0}
+ var statusBytes []byte
+ statusBytes = protowire.AppendTag(statusBytes, 1, protowire.VarintType)
+ statusBytes = protowire.AppendVarint(statusBytes, 0)
+ out = protowire.AppendTag(out, 1, protowire.BytesType)
+ out = protowire.AppendBytes(out, statusBytes)
+
+ // ok_response (field 3): repeated HeaderValueOption headers = 2
+ var okBytes []byte
+ for k, v := range res.ResponseHeaders {
+ var hvBytes []byte
+ hvBytes = protowire.AppendTag(hvBytes, 1, protowire.BytesType)
+ hvBytes = protowire.AppendString(hvBytes, k)
+ hvBytes = protowire.AppendTag(hvBytes, 2, protowire.BytesType)
+ hvBytes = protowire.AppendString(hvBytes, v)
+
+ var hvoBytes []byte
+ hvoBytes = protowire.AppendTag(hvoBytes, 1, protowire.BytesType)
+ hvoBytes = protowire.AppendBytes(hvoBytes, hvBytes)
+
+ okBytes = protowire.AppendTag(okBytes, 2, protowire.BytesType)
+ okBytes = protowire.AppendBytes(okBytes, hvoBytes)
+ }
+ out = protowire.AppendTag(out, 3, protowire.BytesType)
+ out = protowire.AppendBytes(out, okBytes)
+ return out
+ }
+
+ // Denied: google.rpc.Code PERMISSION_DENIED (7) or UNAUTHENTICATED (16)
+ rpcCode := uint64(7)
+ if res.HTTPStatus == http.StatusUnauthorized {
+ rpcCode = 16
+ }
+ var statusBytes []byte
+ statusBytes = protowire.AppendTag(statusBytes, 1, protowire.VarintType)
+ statusBytes = protowire.AppendVarint(statusBytes, rpcCode)
+ if res.Message != "" {
+ statusBytes = protowire.AppendTag(statusBytes, 2, protowire.BytesType)
+ statusBytes = protowire.AppendString(statusBytes, res.Message)
+ }
+ out = protowire.AppendTag(out, 1, protowire.BytesType)
+ out = protowire.AppendBytes(out, statusBytes)
+
+ // denied_response (field 2): HttpStatus status = 1 {code = res.HTTPStatus}, string body = 3
+ var httpStatusBytes []byte
+ httpStatusBytes = protowire.AppendTag(httpStatusBytes, 1, protowire.VarintType)
+ httpStatusBytes = protowire.AppendVarint(httpStatusBytes, uint64(res.HTTPStatus))
+
+ var deniedBytes []byte
+ deniedBytes = protowire.AppendTag(deniedBytes, 1, protowire.BytesType)
+ deniedBytes = protowire.AppendBytes(deniedBytes, httpStatusBytes)
+ if res.Message != "" {
+ deniedBytes = protowire.AppendTag(deniedBytes, 3, protowire.BytesType)
+ deniedBytes = protowire.AppendString(deniedBytes, res.Message)
+ }
+ out = protowire.AppendTag(out, 2, protowire.BytesType)
+ out = protowire.AppendBytes(out, deniedBytes)
+ return out
+}
diff --git a/internal/node/mcp.go b/internal/node/mcp.go
index ba52d177..72e57bfb 100644
--- a/internal/node/mcp.go
+++ b/internal/node/mcp.go
@@ -279,11 +279,19 @@ func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, tar
}
}
- // Load this node's biscuit
- biscuitBytes, err := n.Store.LoadIdentity()
- if err != nil {
+ // Load caller's task biscuit from ctx when present, falling back to this node's biscuit
+ biscuitBytes := n.GetRequestIdentity(ctx)
+ if len(biscuitBytes) == 0 && n.Store != nil {
+ var loadErr error
+ biscuitBytes, loadErr = n.Store.LoadIdentity()
+ if loadErr != nil {
+ cleanup()
+ return nil, nil, fmt.Errorf("failed to load identity biscuit: %w", loadErr)
+ }
+ }
+ if len(biscuitBytes) == 0 {
cleanup()
- return nil, nil, fmt.Errorf("failed to load identity biscuit: %w", err)
+ return nil, nil, fmt.Errorf("failed to load identity biscuit: empty credential")
}
// Marshal AuthFrame
diff --git a/internal/node/middleware.go b/internal/node/middleware.go
index 450824a1..1bb91d26 100644
--- a/internal/node/middleware.go
+++ b/internal/node/middleware.go
@@ -256,13 +256,17 @@ func (n *SamNode) authorizeWithRules(rawToken []byte, req RequestContext, pubKey
if err != nil {
return nil, fmt.Errorf("invalid biscuit: %w", err)
}
+ if n.IsBiscuitRevoked(b) {
+ logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", "biscuit is revoked")...)
+ return nil, fmt.Errorf("biscuit is revoked")
+ }
authorizer, err := b.Authorizer(pubKey, identity.AuthorizerOptions(n.BiscuitTimeout)...)
if err != nil {
return nil, err
}
- if err := identity.RequireAuthorityBinding(b, req.PeerID); err != nil {
+ if err := identity.RequireAuthorityRequestBinding(b, req.PeerID); err != nil {
return nil, err
}
@@ -387,7 +391,7 @@ func (n *SamNode) authorizeWithRules(rawToken []byte, req RequestContext, pubKey
}
}
- var userStr, emailStr, roleStr string
+ var userStr, emailStr, roleStr, actorNodeStr string
if facts, _ := authorizer.Query(biscuit.Rule{
Head: biscuit.Predicate{Name: "get_user", IDs: []biscuit.Term{biscuit.Variable("u")}},
@@ -416,12 +420,24 @@ func (n *SamNode) authorizeWithRules(rawToken []byte, req RequestContext, pubKey
}
}
+ if facts, _ := authorizer.Query(biscuit.Rule{
+ Head: biscuit.Predicate{Name: "get_actor_node", IDs: []biscuit.Term{biscuit.Variable("a")}},
+ Body: []biscuit.Predicate{{Name: api.FactActorNode, IDs: []biscuit.Term{biscuit.Variable("a")}}},
+ }); len(facts) > 0 && len(facts[0].IDs) > 0 {
+ if s, ok := facts[0].IDs[0].(biscuit.String); ok {
+ actorNodeStr = string(s)
+ }
+ }
+
auditFields := append(req.auditFields(),
"decision", "allow",
"user", userStr,
"email", emailStr,
"role", roleStr,
)
+ if actorNodeStr != "" {
+ auditFields = append(auditFields, "actor_node", actorNodeStr)
+ }
if len(taskRules) > 0 {
auditFields = append(auditFields, "task", taskRules[len(taskRules)-1].GetName())
}
diff --git a/internal/node/middleware_test.go b/internal/node/middleware_test.go
index a622a3c9..54ed5fcb 100644
--- a/internal/node/middleware_test.go
+++ b/internal/node/middleware_test.go
@@ -1218,16 +1218,16 @@ func TestTARConformanceVectors(t *testing.T) {
t.Fatal(err)
}
if vec.ExpectedEffectiveExpiration != "" {
- exp, verifyErr := identity.VerifyBiscuitAndGetExpiry(tokenBytes, callerPeer, []ed25519.PublicKey{rootPub}, 500*time.Millisecond)
+ claims, verifyErr := identity.InspectVerifiedBiscuit(tokenBytes, []ed25519.PublicKey{rootPub}, 500*time.Millisecond)
if verifyErr != nil {
- t.Fatalf("VerifyBiscuitAndGetExpiry failed: %v", verifyErr)
+ t.Fatalf("InspectVerifiedBiscuit failed: %v", verifyErr)
}
wantExp, err := time.Parse(time.RFC3339, vec.ExpectedEffectiveExpiration)
if err != nil {
t.Fatal(err)
}
- if !exp.Equal(wantExp) {
- t.Fatalf("effective expiration = %v, want %v", exp, wantExp)
+ if !claims.Expiration.Equal(wantExp) {
+ t.Fatalf("effective expiration = %v, want %v", claims.Expiration, wantExp)
}
}
diff --git a/internal/node/node.go b/internal/node/node.go
index daaaf6a5..31178a15 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -23,6 +23,7 @@ import (
"context"
"crypto/ed25519"
"encoding/base64"
+ "encoding/hex"
"errors"
"fmt"
"io"
@@ -154,24 +155,27 @@ func (n *SamNode) isAdmitted(p peer.ID) bool {
}
type SamNode struct {
- config Options
- Host host.Host
- DHT *dht.IpfsDHT
- PubSub *pubsub.PubSub
- Discovery *samdiscovery.Discovery
- Store *Store
- RouterPeerID peer.ID
- authenticatedRouters map[peer.ID]bool
- peerLastEventTime map[string]int64
- mu sync.Mutex
- nodeConfig *NodeConfigComplete
- revokedPeers *lru.Cache[string, int64]
- peerLabelGate *lru.Cache[string, time.Time]
- authPeers sync.Map
- trustedKeys []TrustedKey
- keysMu sync.RWMutex
- MeshPolicyRules []biscuit.Rule
- MeshPolicyMu sync.RWMutex
+ config Options
+ Host host.Host
+ DHT *dht.IpfsDHT
+ PubSub *pubsub.PubSub
+ Discovery *samdiscovery.Discovery
+ Store *Store
+ RouterPeerID peer.ID
+ authenticatedRouters map[peer.ID]bool
+ peerLastEventTime map[string]int64
+ mu sync.Mutex
+ nodeConfig *NodeConfigComplete
+ revokedPeers *lru.Cache[string, int64]
+ revokedTokens *lru.Cache[string, time.Time]
+ delegatedBiscuitCache *lru.Cache[string, *api.TokenExchangeResponse]
+ stsTokenCache *lru.Cache[string, *api.STSTokenResponse]
+ peerLabelGate *lru.Cache[string, time.Time]
+ authPeers sync.Map
+ trustedKeys []TrustedKey
+ keysMu sync.RWMutex
+ MeshPolicyRules []biscuit.Rule
+ MeshPolicyMu sync.RWMutex
// pendingEgress holds assignments that arrived before Start created the
// service registry (SyncControlPlane runs first); Start applies them.
pendingEgress []*api.EgressDestination
@@ -249,6 +253,64 @@ func (n *SamNode) SetIdentityCache(b []byte) {
}
}
+// RevokeBiscuitID records a Biscuit revocation ID (base64url- or hex-encoded) as revoked until expiry.
+func (n *SamNode) RevokeBiscuitID(revocationID string, expiry time.Time) {
+ if revocationID == "" {
+ return
+ }
+ if n.revokedTokens == nil {
+ n.mu.Lock()
+ if n.revokedTokens == nil {
+ n.revokedTokens, _ = lru.New[string, time.Time](RevocationCacheSize)
+ }
+ n.mu.Unlock()
+ }
+ if expiry.IsZero() {
+ expiry = time.Now().Add(api.BiscuitTokenTTL)
+ }
+ if n.revokedTokens != nil {
+ n.revokedTokens.Add(revocationID, expiry)
+ if raw, err := hex.DecodeString(revocationID); err == nil && len(raw) > 0 {
+ n.revokedTokens.Add(base64.RawURLEncoding.EncodeToString(raw), expiry)
+ }
+ }
+}
+
+// RevokeBiscuitToken revokes the outermost block of a Biscuit token locally.
+// Revoking the final block's RevocationId invalidates that task token and any
+// further attenuated descendants without revoking the parent token.
+func (n *SamNode) RevokeBiscuitToken(rawToken []byte, expiry time.Time) (string, error) {
+ b, _, err := identity.UnmarshalInbound(rawToken)
+ if err != nil {
+ return "", err
+ }
+ ids := b.RevocationIds()
+ if len(ids) == 0 {
+ return "", fmt.Errorf("biscuit has no revocation IDs")
+ }
+ revID := base64.RawURLEncoding.EncodeToString(ids[len(ids)-1])
+ n.RevokeBiscuitID(revID, expiry)
+ return revID, nil
+}
+
+// IsBiscuitRevoked checks whether any block of b has been revoked.
+func (n *SamNode) IsBiscuitRevoked(b *biscuit.Biscuit) bool {
+ if n == nil || n.revokedTokens == nil || b == nil {
+ return false
+ }
+ now := time.Now()
+ for _, id := range b.RevocationIds() {
+ key := base64.RawURLEncoding.EncodeToString(id)
+ if exp, ok := n.revokedTokens.Get(key); ok {
+ if now.Before(exp) {
+ return true
+ }
+ n.revokedTokens.Remove(key)
+ }
+ }
+ return false
+}
+
func stripP2pFromDnsaddr(addr multiaddr.Multiaddr) multiaddr.Multiaddr {
_, err := addr.ValueForProtocol(multiaddr.P_DNSADDR)
if err != nil {
@@ -331,6 +393,10 @@ func NewSamNode(cfg Options) (*SamNode, error) {
if err != nil {
return nil, fmt.Errorf("failed to create revocation cache: %w", err)
}
+ node.revokedTokens, err = lru.New[string, time.Time](RevocationCacheSize)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create token revocation cache: %w", err)
+ }
node.peerLabelGate, err = lru.New[string, time.Time](labelGateCacheSize)
if err != nil {
return nil, fmt.Errorf("failed to create label gate cache: %w", err)
diff --git a/internal/node/openai_facade.go b/internal/node/openai_facade.go
index 4ebcd37d..d6ff9875 100644
--- a/internal/node/openai_facade.go
+++ b/internal/node/openai_facade.go
@@ -91,6 +91,7 @@ type openAIFacade struct {
// control-plane-attested labels before any request data is sent
// (see labels_gate.go).
verifyPeerLabels func(ctx context.Context, peerID string, required map[string]string) error
+ authorizeLocal func(ctx context.Context, serviceName, method, path string) error
ttl time.Duration
mu sync.Mutex
@@ -160,6 +161,20 @@ func newOpenAIFacade(node *SamNode, egress http.Handler) *openAIFacade {
}
return node.VerifyPeerLabels(ctx, pid, required)
},
+ authorizeLocal: func(ctx context.Context, serviceName, method, path string) error {
+ callerBiscuit := CallerBiscuitFromContext(ctx)
+ if len(callerBiscuit) == 0 {
+ return nil
+ }
+ pid, _ := node.localPeerID()
+ return node.VerifyBiscuitToken(callerBiscuit, RequestContext{
+ PeerID: pid,
+ Protocol: "local-api",
+ Target: api.InferenceServicePrefix + serviceName,
+ HTTP: &HTTPRequestFacts{Method: method, Path: path},
+ Local: true,
+ })
+ },
}
}
@@ -170,7 +185,7 @@ func fetchRemoteModels(ctx context.Context, node *SamNode, client *http.Client,
if err != nil {
return nil, fmt.Errorf("invalid peer ID %q: %w", peerID, err)
}
- identity := node.GetIdentity()
+ identity := node.GetRequestIdentity(ctx)
if identity == nil {
return nil, fmt.Errorf("missing node identity")
}
@@ -452,6 +467,12 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)
}
func (f *openAIFacade) serveLocal(w http.ResponseWriter, r *http.Request, serviceName string) {
+ if f.authorizeLocal != nil {
+ if err := f.authorizeLocal(r.Context(), serviceName, r.Method, r.URL.Path); err != nil {
+ writeOpenAIError(w, http.StatusForbidden, "permission_denied", fmt.Sprintf("authorization failed: %v", err))
+ return
+ }
+ }
for _, svc := range f.localServices() {
if svc.Info().GetName() != serviceName || svc.Handler() == nil {
continue
diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go
index 0c7972fa..a43ab2ea 100644
--- a/internal/node/sidecar.go
+++ b/internal/node/sidecar.go
@@ -47,6 +47,28 @@ func StartSidecarServer(node *SamNode, addr, socketPath, token, certFile, keyFil
// Public endpoints
mux.HandleFunc("/healthz", handleHealthz)
mux.HandleFunc("/readyz", handleReadyz)
+ mux.HandleFunc("/.well-known/oauth-protected-resource", func(w http.ResponseWriter, r *http.Request) {
+ handleOAuthProtectedResource(node, w, r)
+ })
+ mux.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) {
+ handleNodeOAuthToken(node, token, w, r)
+ })
+ mux.HandleFunc("/oauth/revoke", func(w http.ResponseWriter, r *http.Request) {
+ handleNodeOAuthRevoke(node, token, w, r)
+ })
+ mux.HandleFunc("/ext_authz", func(w http.ResponseWriter, r *http.Request) {
+ handleExtAuthzHTTP(node, w, r)
+ })
+ mux.HandleFunc("/ext_authz/", func(w http.ResponseWriter, r *http.Request) {
+ handleExtAuthzHTTP(node, w, r)
+ })
+ mux.HandleFunc("/envoy.service.auth.v3.Authorization/Check", func(w http.ResponseWriter, r *http.Request) {
+ handleExtAuthzGRPC(node, w, r)
+ })
+ mux.HandleFunc("/envoy.service.auth.v2.Authorization/Check", func(w http.ResponseWriter, r *http.Request) {
+ handleExtAuthzGRPC(node, w, r)
+ })
+
// Gated like the rest: the labels carry peer IDs and per-peer request counts,
// and this mux is reachable by any local process over TCP. Socket callers are
// unaffected, which is how every scrape in this repo reads it.
@@ -58,7 +80,7 @@ func StartSidecarServer(node *SamNode, addr, socketPath, token, certFile, keyFil
// startup; there is deliberately no runtime registration surface, so no
// credential held by an agent can point the mesh at a new backend or
// withdraw a sibling service.
- mux.Handle("/sam/service/discover", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mux.Handle("/sam/service/discover", withCallerOrTokenAuth(node, token, true, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handleDiscoverService(node, w, r)
}))))
@@ -81,30 +103,30 @@ func StartSidecarServer(node *SamNode, addr, socketPath, token, certFile, keyFil
// handler forwards Authorization to the destination service, so it must never
// also accept it as the local gate credential (would leak the sidecar token off-node).
egress := createEgressProxy(node)
- mux.Handle("/sam/", withAuth(token, false, withMeshConnection(node, egress)))
+ mux.Handle("/sam/", withCallerOrTokenAuth(node, token, false, withMeshConnection(node, egress)))
// OpenAI-compatible facade: point any OpenAI SDK at the sidecar.
// allowAuthorizationFallback=true lets SDKs send the sidecar token as their
- // api_key; withAuth strips whichever header carried it, so an Authorization
- // header that survives the gate is the backend's own credential and is
- // forwarded like on the egress path.
+ // api_key; withCallerOrTokenAuth strips whichever header carried it, so an
+ // Authorization header that survives the gate is the backend's own credential
+ // and is forwarded like on the egress path.
facade := newOpenAIFacade(node, egress)
- mux.Handle("/v1/models", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(facade.handleModels))))
- mux.Handle("/v1/chat/completions", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(facade.handleCompletions))))
- mux.Handle("/v1/completions", withAuth(token, true, withMeshConnection(node, http.HandlerFunc(facade.handleCompletions))))
+ mux.Handle("/v1/models", withCallerOrTokenAuth(node, token, true, withMeshConnection(node, http.HandlerFunc(facade.handleModels))))
+ mux.Handle("/v1/chat/completions", withCallerOrTokenAuth(node, token, true, withMeshConnection(node, http.HandlerFunc(facade.handleCompletions))))
+ mux.Handle("/v1/completions", withCallerOrTokenAuth(node, token, true, withMeshConnection(node, http.HandlerFunc(facade.handleCompletions))))
// Egress destinations this node serves, for local clients. Same gate as
// the facade: an SDK sends the sidecar token as its api_key. Whatever
// Authorization survives the gate is dropped by the egress handler, which
// presents the node's own credential to the destination. Not behind
// withMeshConnection: the destination is outside the mesh.
- mux.Handle("/egress/", withAuth(token, true, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mux.Handle("/egress/", withCallerOrTokenAuth(node, token, true, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handleLocalEgress(node, w, r)
})))
// Mount MCP handler
mcpHandler := NewMCPHandler(node)
- mux.Handle("/", withAuth(token, true, withMeshConnection(node, mcpHandler)))
+ mux.Handle("/", withCallerOrTokenAuth(node, token, true, withMeshConnection(node, mcpHandler)))
server := &http.Server{
Handler: observeRequests(mux),
@@ -737,7 +759,7 @@ func createEgressProxy(node *SamNode) http.Handler {
http.Error(w, "Service Unavailable: Node Not Initialized", http.StatusServiceUnavailable)
return
}
- biscuitBytes := node.GetIdentity()
+ biscuitBytes := node.GetRequestIdentity(r.Context())
if biscuitBytes == nil {
logger.Errorf("[Proxy] Failed to load node identity for egress request, rejecting.")
http.Error(w, "Service Unavailable: Missing Node Identity", http.StatusServiceUnavailable)
diff --git a/internal/node/sts.go b/internal/node/sts.go
new file mode 100644
index 00000000..6873b44f
--- /dev/null
+++ b/internal/node/sts.go
@@ -0,0 +1,730 @@
+// 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/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/google/sam/api"
+ "github.com/google/sam/internal/identity"
+ lru "github.com/hashicorp/golang-lru/v2"
+ "github.com/libp2p/go-libp2p/core/peer"
+)
+
+type callerBiscuitContextKey struct{}
+
+// WithCallerBiscuit attaches a verified caller Biscuit (such as a narrowed
+// Task Biscuit or an exchanged Delegated Session Biscuit) to ctx so outbound
+// mesh and egress handlers use it instead of the node's standing identity.
+func WithCallerBiscuit(ctx context.Context, biscuitBytes []byte) context.Context {
+ if len(biscuitBytes) == 0 {
+ return ctx
+ }
+ cp := append([]byte(nil), biscuitBytes...)
+ return context.WithValue(ctx, callerBiscuitContextKey{}, cp)
+}
+
+// CallerBiscuitFromContext returns the caller Biscuit attached to ctx, or nil.
+func CallerBiscuitFromContext(ctx context.Context) []byte {
+ if ctx == nil {
+ return nil
+ }
+ b, _ := ctx.Value(callerBiscuitContextKey{}).([]byte)
+ return b
+}
+
+// GetRequestIdentity returns the caller Biscuit from ctx when present,
+// falling back to the node's own enrolled Biscuit identity.
+func (n *SamNode) GetRequestIdentity(ctx context.Context) []byte {
+ if b := CallerBiscuitFromContext(ctx); len(b) > 0 {
+ return b
+ }
+ return n.GetIdentity()
+}
+
+// trustedPublicKeys returns the Control Plane Ed25519 public keys currently
+// trusted by this node, falling back to the stored mesh config key if needed.
+func (n *SamNode) trustedPublicKeys() []ed25519.PublicKey {
+ n.keysMu.RLock()
+ keys := publicKeysOf(n.trustedKeys)
+ n.keysMu.RUnlock()
+ if len(keys) == 0 && n.Store != nil {
+ if pubKeyBytes, _, err := n.Store.LoadMeshConfig(); err == nil && len(pubKeyBytes) == ed25519.PublicKeySize {
+ keys = append(keys, ed25519.PublicKey(pubKeyBytes))
+ }
+ }
+ return keys
+}
+
+// VerifyLocalBiscuit verifies a raw Biscuit against the node's revocation
+// cache and trusted Control Plane keys, returning its extracted claims and
+// TaskAuthorizationRule chain.
+func (n *SamNode) VerifyLocalBiscuit(rawToken []byte) (*identity.VerifiedBiscuitClaims, error) {
+ if len(rawToken) == 0 {
+ return nil, errors.New("empty biscuit token")
+ }
+ b, _, err := identity.UnmarshalInbound(rawToken)
+ if err != nil {
+ return nil, fmt.Errorf("invalid biscuit: %w", err)
+ }
+ if n.IsBiscuitRevoked(b) {
+ return nil, errors.New("biscuit is revoked")
+ }
+ keys := n.trustedPublicKeys()
+ if len(keys) == 0 {
+ return nil, errors.New("no trusted control plane keys available")
+ }
+ return identity.InspectVerifiedBiscuit(rawToken, keys, n.BiscuitTimeout)
+}
+
+func (n *SamNode) localPeerID() (peer.ID, error) {
+ if n.Host != nil && n.Host.ID() != "" {
+ return n.Host.ID(), nil
+ }
+ if n.config.PrivKey != nil {
+ return peer.IDFromPrivateKey(n.config.PrivKey)
+ }
+ return "", errors.New("node has no peer ID")
+}
+
+func (n *SamNode) controlPlaneURL() (string, error) {
+ if n.Store != nil {
+ if u, err := n.Store.LoadControlPlaneURL(); err == nil && u != "" {
+ return u, nil
+ }
+ }
+ return "", errors.New("control plane URL not configured in node store")
+}
+
+// ExchangeSubjectJWT calls POST /token/exchange on the Control Plane to verify
+// an external JWT (OIDC, K8s SA, SPIFFE JWT-SVID) and mint a short-lived
+// Delegated Session Biscuit bound to this node. Unattenuated, unsealed
+// exchanges are cached in memory by SHA-256 of the subject JWT.
+func (n *SamNode) ExchangeSubjectJWT(ctx context.Context, subjectToken, subjectTokenType string, taskRule *api.TaskAuthorizationRule, seal bool) (*api.TokenExchangeResponse, error) {
+ if subjectToken == "" {
+ return nil, errors.New("subject_token is required")
+ }
+ cacheable := taskRule == nil && !seal
+ sum := sha256.Sum256([]byte(subjectTokenType + "|" + subjectToken))
+ cacheKey := hex.EncodeToString(sum[:])
+
+ if cacheable {
+ n.mu.Lock()
+ if n.delegatedBiscuitCache == nil {
+ n.delegatedBiscuitCache, _ = lru.New[string, *api.TokenExchangeResponse](1024)
+ }
+ cache := n.delegatedBiscuitCache
+ n.mu.Unlock()
+ if cache != nil {
+ if cached, ok := cache.Get(cacheKey); ok && cached != nil {
+ if cached.GetExpireTime().IsValid() && cached.GetExpireTime().AsTime().After(time.Now().Add(10*time.Second)) {
+ if b, _, err := identity.UnmarshalInbound(cached.GetBiscuitToken()); err == nil && !n.IsBiscuitRevoked(b) {
+ return cached, nil
+ }
+ }
+ cache.Remove(cacheKey)
+ }
+ }
+ }
+
+ cpURL, err := n.controlPlaneURL()
+ if err != nil {
+ return nil, err
+ }
+ nodeBiscuit := n.GetIdentity()
+ if len(nodeBiscuit) == 0 {
+ return nil, errors.New("node has no enrolled biscuit identity")
+ }
+ if n.config.PrivKey == nil {
+ return nil, errors.New("node has no private key")
+ }
+ pid, err := n.localPeerID()
+ if err != nil {
+ return nil, err
+ }
+ challengeMs := time.Now().UnixMilli()
+ challenge := api.TokenExchangeChallenge(pid.String(), challengeMs)
+ sig, err := n.config.PrivKey.Sign([]byte(challenge))
+ if err != nil {
+ return nil, fmt.Errorf("failed to sign token exchange challenge: %w", err)
+ }
+ req := &api.TokenExchangeRequest{
+ SubjectToken: subjectToken,
+ TaskRule: taskRule,
+ Seal: seal,
+ ChallengeUnixMs: challengeMs,
+ ChallengeSignature: sig,
+ }
+ resp, err := controlPlaneClient(cpURL).ExchangeToken(ctx, nodeBiscuit, req)
+ if err != nil {
+ return nil, err
+ }
+ if cacheable && n.delegatedBiscuitCache != nil {
+ n.delegatedBiscuitCache.Add(cacheKey, resp)
+ }
+ return resp, nil
+}
+
+// MintBorderJWT calls POST /sts/token on the Control Plane to verify a caller
+// Biscuit for an egress destination and mint a short-lived ES256 JWT for cloud
+// STS federation. Minted JWTs are cached in memory until 10s before expiry.
+func (n *SamNode) MintBorderJWT(ctx context.Context, callerBiscuit []byte, destination, audience string) (*api.STSTokenResponse, error) {
+ if len(callerBiscuit) == 0 {
+ callerBiscuit = n.GetIdentity()
+ }
+ if len(callerBiscuit) == 0 {
+ return nil, errors.New("missing biscuit for STS token minting")
+ }
+ destination = api.NormalizeMeshHost(destination)
+ if destination == "" {
+ return nil, errors.New("destination is required")
+ }
+ h := sha256.New()
+ h.Write(callerBiscuit)
+ h.Write([]byte("|" + destination + "|" + audience))
+ cacheKey := hex.EncodeToString(h.Sum(nil))
+
+ n.mu.Lock()
+ if n.stsTokenCache == nil {
+ n.stsTokenCache, _ = lru.New[string, *api.STSTokenResponse](1024)
+ }
+ cache := n.stsTokenCache
+ n.mu.Unlock()
+ if cache != nil {
+ if cached, ok := cache.Get(cacheKey); ok && cached != nil {
+ if cached.GetExpireTime().IsValid() && cached.GetExpireTime().AsTime().After(time.Now().Add(10*time.Second)) {
+ return cached, nil
+ }
+ cache.Remove(cacheKey)
+ }
+ }
+
+ cpURL, err := n.controlPlaneURL()
+ if err != nil {
+ return nil, err
+ }
+ nodeBiscuit := n.GetIdentity()
+ if len(nodeBiscuit) == 0 {
+ return nil, errors.New("node has no enrolled biscuit identity")
+ }
+ if n.config.PrivKey == nil {
+ return nil, errors.New("node has no private key")
+ }
+ pid, err := n.localPeerID()
+ if err != nil {
+ return nil, err
+ }
+ challengeMs := time.Now().UnixMilli()
+ challenge := api.STSTokenChallenge(pid.String(), challengeMs)
+ sig, err := n.config.PrivKey.Sign([]byte(challenge))
+ if err != nil {
+ return nil, fmt.Errorf("failed to sign STS token challenge: %w", err)
+ }
+ req := &api.STSTokenRequest{
+ Biscuit: callerBiscuit,
+ Destination: destination,
+ Audience: audience,
+ ChallengeUnixMs: challengeMs,
+ ChallengeSignature: sig,
+ }
+ resp, err := controlPlaneClient(cpURL).MintSTSToken(ctx, nodeBiscuit, req)
+ if err != nil {
+ return nil, err
+ }
+ if cache != nil {
+ cache.Add(cacheKey, resp)
+ }
+ return resp, nil
+}
+
+// decodeBiscuitToken decodes a base64 or base64url Biscuit string and checks
+// that it unmarshals as a syntactically valid Biscuit with valid tar_blocks.
+func decodeBiscuitToken(s string) ([]byte, error) {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return nil, errors.New("empty token")
+ }
+ for _, enc := range []*base64.Encoding{
+ base64.StdEncoding,
+ base64.URLEncoding,
+ base64.RawURLEncoding,
+ base64.RawStdEncoding,
+ } {
+ raw, err := enc.DecodeString(s)
+ if err != nil || len(raw) == 0 {
+ continue
+ }
+ if _, _, err := identity.UnmarshalInbound(raw); err == nil {
+ return raw, nil
+ }
+ }
+ return nil, errors.New("not a valid SAM biscuit token")
+}
+
+// isLikelyJWT reports whether s has the 3-part base64url structure of a compact
+// JWS/JWT with a JSON header containing an "alg" field.
+func isLikelyJWT(s string) bool {
+ parts := strings.Split(strings.TrimSpace(s), ".")
+ if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" {
+ return false
+ }
+ hdrBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
+ if err != nil {
+ return false
+ }
+ var hdr map[string]any
+ if err := json.Unmarshal(hdrBytes, &hdr); err != nil {
+ return false
+ }
+ _, ok := hdr["alg"].(string)
+ return ok
+}
+
+// resolveCallerCredential inspects a bearer credential presented to sam-node.
+// It returns:
+// - (biscuitBytes, true, nil) when the credential is a valid Biscuit or an
+// external JWT successfully exchanged into a Delegated Session Biscuit;
+// - (nil, true, err) when the credential is recognizable as a Biscuit or JWT
+// but failed verification/exchange (so the caller must fail closed);
+// - (nil, false, nil) when the credential is neither a Biscuit nor a JWT.
+func (n *SamNode) resolveCallerCredential(ctx context.Context, bearer string) ([]byte, bool, error) {
+ if n == nil || bearer == "" {
+ return nil, false, nil
+ }
+ if rawBiscuit, err := decodeBiscuitToken(bearer); err == nil {
+ if _, verifyErr := n.VerifyLocalBiscuit(rawBiscuit); verifyErr != nil {
+ return nil, true, verifyErr
+ }
+ return rawBiscuit, true, nil
+ }
+ // Check if it's a syntactically valid Biscuit whose tar_blocks failed validation.
+ for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.URLEncoding, base64.RawURLEncoding, base64.RawStdEncoding} {
+ if raw, err := enc.DecodeString(bearer); err == nil && len(raw) > 0 {
+ if _, _, uErr := identity.UnmarshalInbound(raw); uErr != nil && errors.Is(uErr, identity.ErrAppendedBlocks) {
+ return nil, true, uErr
+ }
+ }
+ }
+ if isLikelyJWT(bearer) {
+ resp, err := n.ExchangeSubjectJWT(ctx, bearer, api.TokenTypeJWT, nil, false)
+ if err != nil {
+ return nil, true, err
+ }
+ return resp.GetBiscuitToken(), true, nil
+ }
+ return nil, false, nil
+}
+
+// withCallerOrTokenAuth gates a sidecar handler behind either:
+// 1. the Unix domain socket / mTLS,
+// 2. the static sidecar API token (SAM_API_TOKEN),
+// 3. a verified SAM Biscuit (including attenuated Task Biscuits), or
+// 4. an external Workload/User JWT exchanged via the Control Plane STS.
+//
+// Whenever a caller Biscuit or JWT is presented, the verified Biscuit is
+// attached to r.Context() via WithCallerBiscuit so outbound mesh/egress calls
+// execute under the caller's narrowed authority.
+func withCallerOrTokenAuth(node *SamNode, token string, allowAuthorizationFallback bool, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ logger.Debugf("[SidecarAuth] Incoming request: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
+
+ // Extract optional X-Sam-Authentication or Authorization bearer value.
+ headerName := api.HeaderSamAuthentication
+ authHeader := r.Header.Get(headerName)
+ if authHeader == "" && allowAuthorizationFallback {
+ headerName = "Authorization"
+ authHeader = r.Header.Get(headerName)
+ }
+
+ var bearer string
+ var hasBearer bool
+ if authHeader != "" {
+ parts := strings.SplitN(authHeader, " ", 2)
+ if len(parts) == 2 && strings.EqualFold(parts[0], "bearer") {
+ bearer = strings.TrimSpace(parts[1])
+ hasBearer = true
+ }
+ }
+
+ // Local Unix socket or mTLS (token == ""): transport already authenticates
+ // the local process, but if the caller also supplied a Task Biscuit or JWT,
+ // bind it to the request context (and fail closed if that Biscuit/JWT is invalid/revoked).
+ if fromLocalSocket(r) || token == "" {
+ if hasBearer && (token == "" || !constantTimeEqual(bearer, token)) {
+ biscuitBytes, isMeshCred, err := node.resolveCallerCredential(r.Context(), bearer)
+ if isMeshCred {
+ if err != nil {
+ http.Error(w, fmt.Sprintf("Forbidden: %v", err), http.StatusForbidden)
+ return
+ }
+ r = r.WithContext(WithCallerBiscuit(r.Context(), biscuitBytes))
+ r.Header.Del(headerName)
+ } else if headerName == api.HeaderSamAuthentication {
+ http.Error(w, "Forbidden", http.StatusForbidden)
+ return
+ }
+ }
+ r.Header.Del(api.HeaderSamAuthentication)
+ stripSidecarTokenFromAuthorization(r, token)
+ next.ServeHTTP(w, r)
+ return
+ }
+
+ if authHeader == "" {
+ accepted := fmt.Sprintf("%q", api.HeaderSamAuthentication)
+ if allowAuthorizationFallback {
+ accepted += ` or "Authorization"`
+ }
+ logger.Warnf("[SidecarAuth] Request %s %s rejected: missing %s header", r.Method, r.URL.Path, accepted)
+ http.Error(w, fmt.Sprintf("Unauthorized: missing %s header, e.g. %q: \"Bearer <api-token>\"", accepted, api.HeaderSamAuthentication), http.StatusUnauthorized)
+ return
+ }
+ if !hasBearer {
+ http.Error(w, fmt.Sprintf("Invalid %q header format, expected \"Bearer <api-token>\"", headerName), http.StatusUnauthorized)
+ return
+ }
+
+ if constantTimeEqual(bearer, token) {
+ r.Header.Del(headerName)
+ stripSidecarTokenFromAuthorization(r, token)
+ next.ServeHTTP(w, r)
+ return
+ }
+
+ biscuitBytes, isMeshCred, err := node.resolveCallerCredential(r.Context(), bearer)
+ if !isMeshCred || err != nil {
+ http.Error(w, "Forbidden", http.StatusForbidden)
+ return
+ }
+ r = r.WithContext(WithCallerBiscuit(r.Context(), biscuitBytes))
+ r.Header.Del(headerName)
+ stripSidecarTokenFromAuthorization(r, token)
+ next.ServeHTTP(w, r)
+ })
+}
+
+// handleNodeOAuthToken implements RFC 8693 Token Exchange & Attenuation
+// (POST /oauth/token) on sam-node.
+func handleNodeOAuthToken(node *SamNode, sidecarToken string, w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ writeNodeOAuthError(w, http.StatusMethodNotAllowed, "invalid_request", "Method not allowed")
+ return
+ }
+ if node == nil {
+ writeNodeOAuthError(w, http.StatusServiceUnavailable, "temporarily_unavailable", "Node not initialized")
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
+ if err := r.ParseForm(); err != nil {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_request", "Failed to parse form body")
+ return
+ }
+
+ grantType := r.FormValue("grant_type")
+ if grantType != api.GrantTypeTokenExchange {
+ writeNodeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type", "Only urn:ietf:params:oauth:grant-type:token-exchange is supported on sam-node")
+ return
+ }
+
+ subjectToken := strings.TrimSpace(r.FormValue("subject_token"))
+ subjectTokenType := strings.TrimSpace(r.FormValue("subject_token_type"))
+ requestedTokenType := strings.TrimSpace(r.FormValue("requested_token_type"))
+ resources := r.Form["resource"]
+ scope := strings.TrimSpace(r.FormValue("scope"))
+ options := strings.TrimSpace(r.FormValue("options"))
+ sealParam := strings.TrimSpace(r.FormValue("seal"))
+ audience := strings.TrimSpace(r.FormValue("audience"))
+ seal := sealParam == "true" || sealParam == "1"
+
+ tar, err := api.BuildTARFromOAuthParams("oauth-task", options, resources, scope, nil)
+ if err != nil {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_request", err.Error())
+ return
+ }
+
+ var baseBiscuit []byte
+ var expiresAt time.Time
+
+ if subjectToken != "" && subjectToken != "self" {
+ if rawBiscuit, bErr := decodeBiscuitToken(subjectToken); bErr == nil {
+ claims, vErr := node.VerifyLocalBiscuit(rawBiscuit)
+ if vErr != nil {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_grant", vErr.Error())
+ return
+ }
+ baseBiscuit = rawBiscuit
+ expiresAt = claims.Expiration
+ } else if subjectTokenType == api.TokenTypeBiscuit {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_grant", "subject_token is not a valid Biscuit")
+ return
+ } else {
+ // External JWT: exchange at the Control Plane.
+ if requestedTokenType != api.TokenTypeJWT {
+ resp, exErr := node.ExchangeSubjectJWT(r.Context(), subjectToken, subjectTokenType, tar, seal)
+ if exErr != nil {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_grant", exErr.Error())
+ return
+ }
+ expIn := int64(300)
+ if resp.GetExpireTime().IsValid() {
+ expIn = int64(time.Until(resp.GetExpireTime().AsTime()).Seconds())
+ if expIn <= 0 {
+ expIn = 1
+ }
+ }
+ writeNodeOAuthTokenResponse(w, base64.StdEncoding.EncodeToString(resp.GetBiscuitToken()), api.TokenTypeBiscuit, expIn, scope)
+ return
+ }
+ resp, exErr := node.ExchangeSubjectJWT(r.Context(), subjectToken, subjectTokenType, tar, false)
+ if exErr != nil {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_grant", exErr.Error())
+ return
+ }
+ baseBiscuit = resp.GetBiscuitToken()
+ if resp.GetExpireTime().IsValid() {
+ expiresAt = resp.GetExpireTime().AsTime()
+ }
+ }
+ } else {
+ // No subject_token (or "self"): authenticate caller via sidecar gate and
+ // use the caller's Biscuit if provided, or the node's own Biscuit.
+ callerBiscuit, ok := authenticateSidecarCaller(node, sidecarToken, r)
+ if !ok {
+ writeNodeOAuthError(w, http.StatusUnauthorized, "invalid_client", "Sidecar authentication or subject_token required")
+ return
+ }
+ if len(callerBiscuit) > 0 {
+ baseBiscuit = callerBiscuit
+ } else {
+ baseBiscuit = node.GetIdentity()
+ }
+ if len(baseBiscuit) == 0 {
+ writeNodeOAuthError(w, http.StatusServiceUnavailable, "temporarily_unavailable", "Node has no identity biscuit")
+ return
+ }
+ if claims, vErr := node.VerifyLocalBiscuit(baseBiscuit); vErr == nil {
+ expiresAt = claims.Expiration
+ }
+ }
+
+ if tar != nil {
+ if tar.GetExpireTime().IsValid() && (expiresAt.IsZero() || tar.GetExpireTime().AsTime().Before(expiresAt)) {
+ expiresAt = tar.GetExpireTime().AsTime()
+ }
+ baseBiscuit, err = identity.AttenuateBiscuit(baseBiscuit, tar)
+ if err != nil {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_request", fmt.Sprintf("Failed to attenuate biscuit: %v", err))
+ return
+ }
+ }
+ if seal {
+ baseBiscuit, err = identity.SealBiscuit(baseBiscuit)
+ if err != nil {
+ writeNodeOAuthError(w, http.StatusInternalServerError, "server_error", fmt.Sprintf("Failed to seal biscuit: %v", err))
+ return
+ }
+ }
+
+ // If the caller explicitly requested an outbound border JWT for an egress resource:
+ if requestedTokenType == api.TokenTypeJWT {
+ dest := ""
+ for _, res := range resources {
+ if after, ok := strings.CutPrefix(res, api.EgressServicePrefix); ok {
+ dest = after
+ break
+ }
+ }
+ if dest == "" {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_target", "requested_token_type=jwt requires an egress://<destination> resource")
+ return
+ }
+ stsResp, stsErr := node.MintBorderJWT(r.Context(), baseBiscuit, dest, audience)
+ if stsErr != nil {
+ writeNodeOAuthError(w, http.StatusForbidden, "access_denied", stsErr.Error())
+ return
+ }
+ expIn := int64(300)
+ if stsResp.GetExpireTime().IsValid() {
+ expIn = int64(time.Until(stsResp.GetExpireTime().AsTime()).Seconds())
+ if expIn <= 0 {
+ expIn = 1
+ }
+ }
+ writeNodeOAuthTokenResponse(w, stsResp.GetJwt(), api.TokenTypeJWT, expIn, scope)
+ return
+ }
+
+ expIn := int64(300)
+ if !expiresAt.IsZero() {
+ expIn = int64(time.Until(expiresAt).Seconds())
+ if expIn <= 0 {
+ expIn = 1
+ }
+ }
+ writeNodeOAuthTokenResponse(w, base64.StdEncoding.EncodeToString(baseBiscuit), api.TokenTypeBiscuit, expIn, scope)
+}
+
+func authenticateSidecarCaller(node *SamNode, sidecarToken string, r *http.Request) ([]byte, bool) {
+ for _, hdr := range []string{api.HeaderSamAuthentication, "Authorization"} {
+ val := r.Header.Get(hdr)
+ if val == "" {
+ continue
+ }
+ parts := strings.SplitN(val, " ", 2)
+ if len(parts) != 2 || !strings.EqualFold(parts[0], "bearer") {
+ continue
+ }
+ bearer := strings.TrimSpace(parts[1])
+ if sidecarToken != "" && constantTimeEqual(bearer, sidecarToken) {
+ return nil, true
+ }
+ if biscuitBytes, isMeshCred, err := node.resolveCallerCredential(r.Context(), bearer); isMeshCred && err == nil {
+ return biscuitBytes, true
+ }
+ }
+ if fromLocalSocket(r) || sidecarToken == "" {
+ return nil, true
+ }
+ return nil, false
+}
+
+// handleNodeOAuthRevoke implements RFC 7009 Token Revocation (POST /oauth/revoke)
+// on sam-node, adding the Biscuit's root Block 0 revocation ID to the local
+// revocation cache so any call carrying it (or any child attenuated from it)
+// is immediately rejected.
+func handleNodeOAuthRevoke(node *SamNode, sidecarToken string, w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ writeNodeOAuthError(w, http.StatusMethodNotAllowed, "invalid_request", "Method not allowed")
+ return
+ }
+ if node == nil {
+ writeNodeOAuthError(w, http.StatusServiceUnavailable, "temporarily_unavailable", "Node not initialized")
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
+ if err := r.ParseForm(); err != nil {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_request", "Failed to parse form body")
+ return
+ }
+ tokenStr := strings.TrimSpace(r.FormValue("token"))
+ if tokenStr == "" {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_request", "token parameter is required")
+ return
+ }
+
+ rawBiscuit, err := decodeBiscuitToken(tokenStr)
+ if err != nil {
+ // Per RFC 7009 Section 2.2, invalid tokens still return 200 OK if the
+ // client is authenticated, or 400 if unrecognizable and unauthenticated.
+ if _, ok := authenticateSidecarCaller(node, sidecarToken, r); ok {
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_request", "invalid biscuit token")
+ return
+ }
+
+ // Verify signature against trusted Control Plane keys before accepting an
+ // unauthenticated revocation so arbitrary bytes cannot pollute the cache.
+ expiry := time.Now().Add(24 * time.Hour)
+ if claims, vErr := node.VerifyLocalBiscuit(rawBiscuit); vErr == nil {
+ if !claims.Expiration.IsZero() {
+ expiry = claims.Expiration
+ }
+ } else if _, ok := authenticateSidecarCaller(node, sidecarToken, r); !ok {
+ // Allow revoking an already-revoked token idempotently if its signature is valid.
+ b, _, uErr := identity.UnmarshalInbound(rawBiscuit)
+ if uErr != nil || !node.IsBiscuitRevoked(b) {
+ writeNodeOAuthError(w, http.StatusUnauthorized, "invalid_token", vErr.Error())
+ return
+ }
+ }
+
+ if _, err := node.RevokeBiscuitToken(rawBiscuit, expiry); err != nil {
+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_request", err.Error())
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+}
+
+// handleOAuthProtectedResource serves RFC 9728 OAuth 2.0 Protected Resource Metadata
+// (GET /.well-known/oauth-protected-resource).
+func handleOAuthProtectedResource(node *SamNode, w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ scheme := "http"
+ if r.TLS != nil {
+ scheme = "https"
+ }
+ host := r.Host
+ if host == "" && node != nil && node.BoundHTTPAddr != "" {
+ host = node.BoundHTTPAddr
+ }
+ if host == "" {
+ host = "localhost"
+ }
+ var authServers []string
+ if node != nil {
+ if cpURL, err := node.controlPlaneURL(); err == nil && cpURL != "" {
+ authServers = append(authServers, cpURL)
+ }
+ }
+ meta := map[string]any{
+ "resource": fmt.Sprintf("%s://%s/mcp", scheme, host),
+ "authorization_servers": authServers,
+ "bearer_methods_supported": []string{"header"},
+ "scopes_supported": []string{"mcp", "inference", "egress", "a2a"},
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(meta)
+}
+
+func writeNodeOAuthTokenResponse(w http.ResponseWriter, accessToken, issuedTokenType string, expiresIn int64, scope string) {
+ resp := map[string]any{
+ "access_token": accessToken,
+ "issued_token_type": issuedTokenType,
+ "token_type": "Bearer",
+ "expires_in": expiresIn,
+ }
+ if scope != "" {
+ resp["scope"] = scope
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Pragma", "no-cache")
+ _ = json.NewEncoder(w).Encode(resp)
+}
+
+func writeNodeOAuthError(w http.ResponseWriter, status int, code, description string) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(map[string]string{
+ "error": code,
+ "error_description": description,
+ })
+}
diff --git a/internal/node/sts_test.go b/internal/node/sts_test.go
new file mode 100644
index 00000000..c88896ab
--- /dev/null
+++ b/internal/node/sts_test.go
@@ -0,0 +1,527 @@
+// 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 (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/biscuit-auth/biscuit-go/v2"
+ "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/encoding/protowire"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+type stsNodeHarness struct {
+ node *SamNode
+ cpPub ed25519.PublicKey
+ cpPriv ed25519.PrivateKey
+ peerID peer.ID
+ nodeBiscuit []byte
+ policyRoles []*api.PolicyRole
+}
+
+func newSTSNodeHarness(t *testing.T) *stsNodeHarness {
+ t.Helper()
+ cpPub, cpPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("GenerateKey: %v", err)
+ }
+ privKey, _, err := crypto.GenerateEd25519Key(rand.Reader)
+ if err != nil {
+ t.Fatalf("GenerateEd25519Key: %v", err)
+ }
+ pid, err := peer.IDFromPrivateKey(privKey)
+ if err != nil {
+ t.Fatalf("IDFromPrivateKey: %v", err)
+ }
+ store, err := NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ if err := store.SaveMeshConfig(cpPub, nil); err != nil {
+ t.Fatalf("SaveMeshConfig: %v", err)
+ }
+
+ policyRoles := []*api.PolicyRole{
+ {
+ Name: "developer",
+ AllowedServices: []string{"mcp://github", "inference://gemini-pro", "egress://api.github.com"},
+ AllowedTargets: []string{"*"},
+ },
+ }
+
+ nodeBiscuit, _, err := identity.MintBiscuitToken(
+ cpPriv,
+ jwt.MapClaims{"sub": "alice", "email": "[email protected]"},
+ nil,
+ pid,
+ time.Now().Add(time.Hour),
+ []string{api.RoleNode, "developer"},
+ policyRoles,
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("MintBiscuitToken: %v", err)
+ }
+ if err := store.SaveIdentity(nodeBiscuit); err != nil {
+ t.Fatalf("SaveIdentity: %v", err)
+ }
+
+ n, err := NewSamNode(Options{
+ PrivKey: privKey,
+ Store: store,
+ })
+ if err != nil {
+ t.Fatalf("NewSamNode: %v", err)
+ }
+ n.trustedKeys = []TrustedKey{{Key: cpPub, ReceivedAt: time.Now()}}
+ n.SetIdentityCache(nodeBiscuit)
+ n.MeshPolicyRules = []biscuit.Rule{}
+
+ return &stsNodeHarness{
+ node: n,
+ cpPub: cpPub,
+ cpPriv: cpPriv,
+ peerID: pid,
+ nodeBiscuit: nodeBiscuit,
+ policyRoles: policyRoles,
+ }
+}
+
+func TestNodeOAuthTokenAttenuationAndSeal(t *testing.T) {
+ h := newSTSNodeHarness(t)
+ sidecarToken := "secret-sidecar-token"
+
+ // 1. Exchange subject_token Biscuit with RFC 8707 resource + scope narrowing.
+ form := url.Values{}
+ form.Set("grant_type", api.GrantTypeTokenExchange)
+ form.Set("subject_token", base64.StdEncoding.EncodeToString(h.nodeBiscuit))
+ form.Set("subject_token_type", api.TokenTypeBiscuit)
+ form.Add("resource", "mcp://github")
+ form.Set("scope", "tool:get_pr")
+
+ req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ rec := httptest.NewRecorder()
+ handleNodeOAuthToken(h.node, sidecarToken, rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200 OK, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("json.Unmarshal: %v", err)
+ }
+ if resp["issued_token_type"] != api.TokenTypeBiscuit {
+ t.Fatalf("unexpected issued_token_type: %v", resp["issued_token_type"])
+ }
+ attenuatedB64, _ := resp["access_token"].(string)
+ attenuatedBytes, err := base64.StdEncoding.DecodeString(attenuatedB64)
+ if err != nil {
+ t.Fatalf("DecodeString: %v", err)
+ }
+
+ // Verify narrowed Biscuit allows mcp://github get_pr, denies merge_pr and mcp://billing.
+ allowCtx := RequestContext{
+ PeerID: h.peerID,
+ Protocol: string(api.MCPProtocolID),
+ Target: "mcp://github",
+ MCPTool: "get_pr",
+ Local: true,
+ }
+ if err := h.node.VerifyBiscuitToken(attenuatedBytes, allowCtx); err != nil {
+ t.Fatalf("expected get_pr to be allowed: %v", err)
+ }
+ denyToolCtx := allowCtx
+ denyToolCtx.MCPTool = "merge_pr"
+ if err := h.node.VerifyBiscuitToken(attenuatedBytes, denyToolCtx); err == nil {
+ t.Fatalf("expected merge_pr to be denied by tar_block")
+ }
+
+ // 2. Attenuate node's own identity via sidecar token (subject_token omitted) and seal=true.
+ tar := &api.TaskAuthorizationRule{
+ Name: "sealed-task",
+ Rules: []*api.TaskRule{
+ {
+ AllowedServices: []string{"inference://gemini-pro"},
+ },
+ },
+ }
+ tarB64, err := api.EncodeTARBlockPayload(tar)
+ if err != nil {
+ t.Fatalf("EncodeTARBlockPayload: %v", err)
+ }
+
+ form2 := url.Values{}
+ form2.Set("grant_type", api.GrantTypeTokenExchange)
+ form2.Set("options", tarB64)
+ form2.Set("seal", "true")
+
+ req2 := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(form2.Encode()))
+ req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req2.Header.Set("Authorization", "Bearer "+sidecarToken)
+ rec2 := httptest.NewRecorder()
+ handleNodeOAuthToken(h.node, sidecarToken, rec2, req2)
+ if rec2.Code != http.StatusOK {
+ t.Fatalf("expected 200 OK for sealed self-attenuation, got %d: %s", rec2.Code, rec2.Body.String())
+ }
+ var resp2 map[string]any
+ _ = json.Unmarshal(rec2.Body.Bytes(), &resp2)
+ sealedBytes, _ := base64.StdEncoding.DecodeString(resp2["access_token"].(string))
+
+ // Attempting to further attenuate a sealed Biscuit must fail.
+ if _, err := identity.AttenuateBiscuit(sealedBytes, tar); err == nil {
+ t.Fatalf("expected further attenuation of sealed biscuit to fail")
+ }
+}
+
+func TestNodeOAuthRevokeAndSyncRevocations(t *testing.T) {
+ h := newSTSNodeHarness(t)
+ sidecarToken := "secret-sidecar-token"
+
+ // Mint a separate task biscuit and attenuate a child from it.
+ parentBiscuit, _, err := identity.MintBiscuitToken(
+ h.cpPriv,
+ jwt.MapClaims{"sub": "bob", "email": "[email protected]"},
+ nil,
+ h.peerID,
+ time.Now().Add(time.Hour),
+ []string{api.RoleNode, "developer"},
+ h.policyRoles,
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("MintBiscuitToken: %v", err)
+ }
+ childBiscuit, err := identity.AttenuateBiscuit(parentBiscuit, &api.TaskAuthorizationRule{
+ Name: "child-task",
+ Rules: []*api.TaskRule{
+ {AllowedServices: []string{"mcp://github"}},
+ },
+ })
+ if err != nil {
+ t.Fatalf("AttenuateBiscuit: %v", err)
+ }
+ grandchildBiscuit, err := identity.AttenuateBiscuit(childBiscuit, &api.TaskAuthorizationRule{
+ Name: "grandchild-task",
+ Rules: []*api.TaskRule{
+ {
+ AllowedServices: []string{"mcp://github"},
+ Operation: &api.TaskOperation{AllowedTools: []string{"get_pr"}},
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("AttenuateBiscuit grandchild: %v", err)
+ }
+
+ // Revoke childBiscuit on POST /oauth/revoke: invalidates childBiscuit and
+ // grandchildBiscuit while keeping parentBiscuit valid.
+ form := url.Values{}
+ form.Set("token", base64.StdEncoding.EncodeToString(childBiscuit))
+ req := httptest.NewRequest(http.MethodPost, "/oauth/revoke", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ rec := httptest.NewRecorder()
+ handleNodeOAuthRevoke(h.node, sidecarToken, rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200 OK from /oauth/revoke, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ if _, err := h.node.VerifyLocalBiscuit(childBiscuit); err == nil {
+ t.Fatalf("expected revoked child biscuit to fail VerifyLocalBiscuit")
+ }
+ if _, err := h.node.VerifyLocalBiscuit(grandchildBiscuit); err == nil {
+ t.Fatalf("expected grandchild biscuit to also be revoked via child's RevocationId")
+ }
+ if _, err := h.node.VerifyLocalBiscuit(parentBiscuit); err != nil {
+ t.Fatalf("expected parent biscuit to remain valid when only child task is revoked: %v", err)
+ }
+
+ // Revoking parentBiscuit invalidates parentBiscuit too.
+ formParent := url.Values{}
+ formParent.Set("token", base64.StdEncoding.EncodeToString(parentBiscuit))
+ reqParent := httptest.NewRequest(http.MethodPost, "/oauth/revoke", strings.NewReader(formParent.Encode()))
+ reqParent.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ recParent := httptest.NewRecorder()
+ handleNodeOAuthRevoke(h.node, sidecarToken, recParent, reqParent)
+ if recParent.Code != http.StatusOK {
+ t.Fatalf("expected 200 OK from /oauth/revoke for parent, got %d", recParent.Code)
+ }
+ if _, err := h.node.VerifyLocalBiscuit(parentBiscuit); err == nil {
+ t.Fatalf("expected revoked parent biscuit to fail VerifyLocalBiscuit")
+ }
+
+ // Test syncRevocations pulling from Control Plane /revocations.
+ thirdBiscuit, _, err := identity.MintBiscuitToken(
+ h.cpPriv,
+ jwt.MapClaims{"sub": "carol", "email": "[email protected]"},
+ nil,
+ h.peerID,
+ time.Now().Add(time.Hour),
+ []string{api.RoleNode, "developer"},
+ h.policyRoles,
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("MintBiscuitToken: %v", err)
+ }
+ parsedThird, _, err := identity.UnmarshalInbound(thirdBiscuit)
+ if err != nil {
+ t.Fatalf("UnmarshalInbound: %v", err)
+ }
+ revIDHex := hex.EncodeToString(parsedThird.RevocationIds()[0])
+
+ cpServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/revocations" {
+ http.NotFound(w, r)
+ return
+ }
+ payload, _ := proto.Marshal(&api.RevocationsResponse{
+ RevocationIds: []string{revIDHex},
+ })
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ _, _ = w.Write(payload)
+ }))
+ defer cpServer.Close()
+
+ // Point controlPlaneClient at cpServer by temporarily swapping http.DefaultTransport.
+ origTransport := http.DefaultTransport
+ http.DefaultTransport = cpServer.Client().Transport
+ t.Cleanup(func() { http.DefaultTransport = origTransport })
+
+ if err := h.node.syncRevocations(context.Background(), cpServer.URL); err != nil {
+ t.Fatalf("syncRevocations: %v", err)
+ }
+ if _, err := h.node.VerifyLocalBiscuit(thirdBiscuit); err == nil {
+ t.Fatalf("expected thirdBiscuit to be rejected after syncRevocations")
+ }
+}
+
+func TestWithCallerOrTokenAuthAndJWTExchange(t *testing.T) {
+ h := newSTSNodeHarness(t)
+ sidecarToken := "secret-sidecar-token"
+
+ delegatedBiscuit, err := identity.MintDelegatedBiscuitToken(
+ h.cpPriv,
+ jwt.MapClaims{"sub": "k8s-sa-payments", "email": "[email protected]"},
+ h.peerID,
+ time.Now().Add(5*time.Minute),
+ []string{"developer"},
+ h.policyRoles,
+ nil,
+ false,
+ )
+ if err != nil {
+ t.Fatalf("MintDelegatedBiscuitToken: %v", err)
+ }
+
+ var exchangeCalls atomic.Int32
+ cpServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/token/exchange" {
+ exchangeCalls.Add(1)
+ payload, _ := proto.Marshal(&api.TokenExchangeResponse{
+ BiscuitToken: delegatedBiscuit,
+ ExpireTime: timestamppb.New(time.Now().Add(5 * time.Minute)),
+ Roles: []string{"developer"},
+ Subject: "k8s-sa-payments",
+ })
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ _, _ = w.Write(payload)
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ defer cpServer.Close()
+
+ origTransport := http.DefaultTransport
+ http.DefaultTransport = cpServer.Client().Transport
+ t.Cleanup(func() { http.DefaultTransport = origTransport })
+ if err := h.node.Store.SaveControlPlaneURL(cpServer.URL); err != nil {
+ t.Fatalf("SaveControlPlaneURL: %v", err)
+ }
+
+ var capturedIdentity []byte
+ handler := withCallerOrTokenAuth(h.node, sidecarToken, true, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ capturedIdentity = h.node.GetRequestIdentity(r.Context())
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ // 1. Static sidecar token uses node's standing identity.
+ req1 := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
+ req1.Header.Set("Authorization", "Bearer "+sidecarToken)
+ rec1 := httptest.NewRecorder()
+ handler.ServeHTTP(rec1, req1)
+ if rec1.Code != http.StatusOK || !bytes.Equal(capturedIdentity, h.nodeBiscuit) {
+ t.Fatalf("expected 200 OK with nodeBiscuit, got %d", rec1.Code)
+ }
+
+ // 2. Narrowed Task Biscuit in Authorization header overrides request identity.
+ narrowed, err := identity.AttenuateBiscuit(h.nodeBiscuit, &api.TaskAuthorizationRule{
+ Name: "narrow-task",
+ Rules: []*api.TaskRule{{AllowedServices: []string{"mcp://github"}}},
+ })
+ if err != nil {
+ t.Fatalf("AttenuateBiscuit: %v", err)
+ }
+ req2 := httptest.NewRequest(http.MethodPost, "/mcp", nil)
+ req2.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(narrowed))
+ rec2 := httptest.NewRecorder()
+ handler.ServeHTTP(rec2, req2)
+ if rec2.Code != http.StatusOK || !bytes.Equal(capturedIdentity, narrowed) {
+ t.Fatalf("expected 200 OK with narrowed task biscuit, got %d", rec2.Code)
+ }
+
+ // 3. External JWT in Authorization header triggers transparent /token/exchange and caches result.
+ fakeJWTHeader := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`))
+ fakeJWTPayload := base64.RawURLEncoding.EncodeToString([]byte(`{"sub":"k8s-sa-payments"}`))
+ fakeJWTSig := base64.RawURLEncoding.EncodeToString([]byte("sig"))
+ fakeJWT := fakeJWTHeader + "." + fakeJWTPayload + "." + fakeJWTSig
+
+ for i := range 2 {
+ reqJWT := httptest.NewRequest(http.MethodPost, "/mcp", nil)
+ reqJWT.Header.Set("Authorization", "Bearer "+fakeJWT)
+ recJWT := httptest.NewRecorder()
+ handler.ServeHTTP(recJWT, reqJWT)
+ if recJWT.Code != http.StatusOK || !bytes.Equal(capturedIdentity, delegatedBiscuit) {
+ t.Fatalf("attempt %d: expected 200 OK with delegatedBiscuit, got %d", i+1, recJWT.Code)
+ }
+ }
+ if got := exchangeCalls.Load(); got != 1 {
+ t.Fatalf("expected second JWT call to hit LRU cache (1 control plane call), got %d", got)
+ }
+}
+
+func TestExtAuthzHTTPAndGRPC(t *testing.T) {
+ h := newSTSNodeHarness(t)
+
+ narrowed, err := identity.AttenuateBiscuit(h.nodeBiscuit, &api.TaskAuthorizationRule{
+ Name: "pr-review-task",
+ Rules: []*api.TaskRule{
+ {
+ AllowedServices: []string{"mcp://github"},
+ Operation: &api.TaskOperation{
+ AllowedTools: []string{"get_pr"},
+ },
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("AttenuateBiscuit: %v", err)
+ }
+ narrowedB64 := base64.StdEncoding.EncodeToString(narrowed)
+
+ // 1. HTTP ext_authz allow: mcp://github + tool get_pr
+ reqAllow := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", nil)
+ reqAllow.Header.Set("Authorization", "Bearer "+narrowedB64)
+ reqAllow.Header.Set(HeaderSamMCPTool, "get_pr")
+ recAllow := httptest.NewRecorder()
+ handleExtAuthzHTTP(h.node, recAllow, reqAllow)
+ if recAllow.Code != http.StatusOK {
+ t.Fatalf("expected HTTP ext_authz 200 OK, got %d: %s", recAllow.Code, recAllow.Body.String())
+ }
+ if recAllow.Header().Get(api.HeaderSamPrincipal) != "[email protected]" {
+ t.Fatalf("unexpected X-Sam-Principal: %q", recAllow.Header().Get(api.HeaderSamPrincipal))
+ }
+ if !strings.Contains(recAllow.Header().Get(api.HeaderSamTask), "pr-review-task") {
+ t.Fatalf("expected X-Sam-Task to contain pr-review-task, got %q", recAllow.Header().Get(api.HeaderSamTask))
+ }
+
+ // 2. HTTP ext_authz deny: mcp://github + tool merge_pr
+ reqDeny := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", nil)
+ reqDeny.Header.Set("Authorization", "Bearer "+narrowedB64)
+ reqDeny.Header.Set(HeaderSamMCPTool, "merge_pr")
+ recDeny := httptest.NewRecorder()
+ handleExtAuthzHTTP(h.node, recDeny, reqDeny)
+ if recDeny.Code != http.StatusForbidden {
+ t.Fatalf("expected HTTP ext_authz 403 Forbidden for merge_pr, got %d", recDeny.Code)
+ }
+
+ // 3. gRPC ext_authz Check (/envoy.service.auth.v3.Authorization/Check)
+ grpcReqPayload := buildEnvoyCheckRequestPayload("POST", "/mcp/github", map[string]string{
+ "authorization": "Bearer " + narrowedB64,
+ strings.ToLower(HeaderSamMCPTool): "get_pr",
+ })
+ var grpcBody bytes.Buffer
+ _ = writeGRPCFrame(&grpcBody, grpcReqPayload)
+
+ grpcReq := httptest.NewRequest(http.MethodPost, "/envoy.service.auth.v3.Authorization/Check", &grpcBody)
+ grpcReq.Header.Set("Content-Type", "application/grpc")
+ grpcRec := httptest.NewRecorder()
+ handleExtAuthzGRPC(h.node, grpcRec, grpcReq)
+ if grpcRec.Code != http.StatusOK {
+ t.Fatalf("expected gRPC HTTP 200, got %d", grpcRec.Code)
+ }
+ respFrame, err := readGRPCFrame(grpcRec.Body)
+ if err != nil {
+ t.Fatalf("readGRPCFrame: %v", err)
+ }
+ // First field is status {code: 0}; field 3 is ok_response.
+ num, typ, n := protowire.ConsumeTag(respFrame)
+ if n < 0 || num != 1 || typ != protowire.BytesType {
+ t.Fatalf("unexpected CheckResponse tag: num=%d typ=%d", num, typ)
+ }
+ statusBytes, m := protowire.ConsumeBytes(respFrame[n:])
+ if m < 0 || len(statusBytes) < 2 || statusBytes[1] != 0 {
+ t.Fatalf("expected gRPC CheckResponse status.code == 0 (OK), got %x", statusBytes)
+ }
+}
+
+func buildEnvoyCheckRequestPayload(method, path string, headers map[string]string) []byte {
+ var httpBytes []byte
+ httpBytes = protowire.AppendTag(httpBytes, 2, protowire.BytesType)
+ httpBytes = protowire.AppendString(httpBytes, method)
+ for k, v := range headers {
+ var entry []byte
+ entry = protowire.AppendTag(entry, 1, protowire.BytesType)
+ entry = protowire.AppendString(entry, k)
+ entry = protowire.AppendTag(entry, 2, protowire.BytesType)
+ entry = protowire.AppendString(entry, v)
+ httpBytes = protowire.AppendTag(httpBytes, 3, protowire.BytesType)
+ httpBytes = protowire.AppendBytes(httpBytes, entry)
+ }
+ httpBytes = protowire.AppendTag(httpBytes, 4, protowire.BytesType)
+ httpBytes = protowire.AppendString(httpBytes, path)
+
+ var reqBytes []byte
+ reqBytes = protowire.AppendTag(reqBytes, 2, protowire.BytesType)
+ reqBytes = protowire.AppendBytes(reqBytes, httpBytes)
+
+ var attrBytes []byte
+ attrBytes = protowire.AppendTag(attrBytes, 4, protowire.BytesType)
+ attrBytes = protowire.AppendBytes(attrBytes, reqBytes)
+
+ var checkReq []byte
+ checkReq = protowire.AppendTag(checkReq, 1, protowire.BytesType)
+ checkReq = protowire.AppendBytes(checkReq, attrBytes)
+ return checkReq
+}
diff --git a/sdk/js/src/authorizer.ts b/sdk/js/src/authorizer.ts
index 434fd55b..5c3b97a7 100644
--- a/sdk/js/src/authorizer.ts
+++ b/sdk/js/src/authorizer.ts
@@ -92,10 +92,10 @@ export async function authorizeCaller(req: AuthorizeRequest, options: ProviderAu
}
// Signature under a trusted key, authority block + tar_block chain, expiry and binding
- // to the connection peer: RequireAuthorityBinding and EnforceExpiration.
+ // to the connection peer: RequireAuthorityRequestBinding and EnforceExpiration.
let caller: VerifiedBiscuit;
try {
- caller = await verifyPeerBiscuit(req.biscuit, req.peerId, keys, now);
+ caller = await verifyPeerBiscuit(req.biscuit, req.peerId, keys, now, { allowDelegated: true });
} catch (err) {
throw new AuthorizationError(req.peerId, describe(err));
}
diff --git a/sdk/js/src/biscuit.ts b/sdk/js/src/biscuit.ts
index 18d3cd0e..afc4441f 100644
--- a/sdk/js/src/biscuit.ts
+++ b/sdk/js/src/biscuit.ts
@@ -71,8 +71,10 @@ export class BiscuitVerificationError extends Error {
/** What a verified peer biscuit says about its holder. */
export interface VerifiedBiscuit {
- /** The peer the token is bound to (its node() fact). */
+ /** The peer the token is bound to (its node() or actor_node()/client_peer_id() fact). */
peerId: string;
+ /** The origin node channel when the token is a delegated session biscuit (actor_node()). */
+ actorNode?: string;
/** When the token lapses; the minimum of authority expiration() and any tar_block expire_time. */
expiration: Date;
/** The trusted key that verified the signature. */
@@ -144,12 +146,18 @@ function extractTARChain(token: ReturnType<BiscuitWasm["Biscuit"]["fromBytes"]>)
* Verifies a biscuit received from expectedPeerId over an authenticated
* connection. Every trusted key is tried, so a token minted under a
* retiring key still verifies during rotation.
+ *
+ * By default (peer handshakes on /sam/auth/1.0.0), the authority block must
+ * carry node(expectedPeerId). When allowDelegated is true (request tokens in
+ * authorizeCaller), the authority block may alternatively carry both
+ * actor_node(expectedPeerId) and client_peer_id(expectedPeerId) without node().
*/
export async function verifyPeerBiscuit(
biscuitBytes: Uint8Array,
expectedPeerId: string,
trustedKeys: Uint8Array[],
now: Date = new Date(),
+ options?: { allowDelegated?: boolean },
): Promise<VerifiedBiscuit> {
const wasm = await loadBiscuit();
const { token, verifyingKey } = parseWithTrustedKeys(wasm, biscuitBytes, trustedKeys);
@@ -170,7 +178,14 @@ export async function verifyPeerBiscuit(
const strings = (facts: QueriedFact[]) => facts.map((f) => f.terms()[0]).filter((t): t is string => typeof t === "string");
const bound = strings(query("p($p) <- node($p)"));
- if (!bound.includes(expectedPeerId)) {
+ const actorNodes = strings(query("a($a) <- actor_node($a)"));
+ const clientPeers = strings(query("c($c) <- client_peer_id($c)"));
+ const isBoundNode = bound.includes(expectedPeerId);
+ const isBoundDelegated =
+ options?.allowDelegated === true &&
+ actorNodes.includes(expectedPeerId) &&
+ clientPeers.includes(expectedPeerId);
+ if (!isBoundNode && !isBoundDelegated) {
throw new BiscuitVerificationError(`biscuit is not bound to peer ${expectedPeerId}`);
}
@@ -198,6 +213,7 @@ export async function verifyPeerBiscuit(
return {
peerId: expectedPeerId,
+ ...(actorNodes[0] !== undefined ? { actorNode: actorNodes[0] } : {}),
expiration,
verifyingKey,
roles: strings(query("r($r) <- role($r)")),
diff --git a/sdk/js/src/gen/datalog.ts b/sdk/js/src/gen/datalog.ts
index 2a8ee060..c54c1ec7 100644
--- a/sdk/js/src/gen/datalog.ts
+++ b/sdk/js/src/gen/datalog.ts
@@ -42,6 +42,9 @@ export const BASELINE_DATALOG = {
"target_check": "check if allow_network_target($fact, $val) or target_unrestricted(true)",
"time_check": "check if time($time), expiration($exp), $time <= $exp",
"allow_if_true": "allow if true",
+ "fact_node": "node",
+ "fact_client_peer_id": "client_peer_id",
+ "fact_actor_node": "actor_node",
"fact_service": "service",
"fact_connection_peer_id": "connection_peer_id",
"fact_method": "method",
diff --git a/sdk/js/src/gen/sam_pb.ts b/sdk/js/src/gen/sam_pb.ts
index 8bbe0a00..355bc558 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/CgxBdXRoUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCRIPCgdiaXNjdWl0GAMgASgMItYBCglNZXNoRXZlbnQSJAoEdHlwZRgBIAEoDjIWLnNhbS52MS5NZXNoRXZlbnQuVHlwZRIPCgdwZWVyX2lkGAIgASgJEi4KCmV2ZW50X3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEhYKDm5ld19wdWJsaWNfa2V5GAQgASgMEhEKCXNpZ25hdHVyZRgFIAEoDCI3CgRUeXBlEgoKBkJBTk5FRBAAEhAKDEtFWV9ST1RBVElPThABEhEKDVBPTElDWV9VUERBVEUQAiLzAQoNRW5yb2xsUmVxdWVzdBILCgNqd3QYASABKAkSDwoHcGVlcl9pZBgCIAEoCRISCgpwdWJsaWNfa2V5GAMgASgMEhYKDnJlcXVlc3RlZF9yb2xlGAQgASgJEjEKBmxhYmVscxgFIAMoCzIhLnNhbS52MS5FbnJvbGxSZXF1ZXN0LkxhYmVsc0VudHJ5EhkKEWNoYWxsZW5nZV91bml4X21zGAYgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYByABKAwaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASKrAQoORW5yb2xsUmVzcG9uc2USFQoNYmlzY3VpdF90b2tlbhgBIAEoDBIVCg1lcnJvcl9tZXNzYWdlGAIgASgJEiAKGGNvbnRyb2xfcGxhbmVfcHVibGljX2tleRgDIAEoDBIYChByb3V0ZXJfYWRkcmVzc2VzGAQgAygJEi8KC2V4cGlyZV90aW1lGAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCKRAgoWQm9vdHN0cmFwRW5yb2xsUmVxdWVzdBIXCg9ib290c3RyYXBfdG9rZW4YASABKAkSDwoHcGVlcl9pZBgCIAEoCRISCgpwdWJsaWNfa2V5GAMgASgMEhYKDnJlcXVlc3RlZF9yb2xlGAQgASgJEjoKBmxhYmVscxgFIAMoCzIqLnNhbS52MS5Cb290c3RyYXBFbnJvbGxSZXF1ZXN0LkxhYmVsc0VudHJ5EhkKEWNoYWxsZW5nZV91bml4X21zGAYgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYByABKAwaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASL9AQoXQm9vdHN0cmFwRW5yb2xsUmVzcG9uc2USKAoGc3RhdHVzGAEgASgOMhguc2FtLnYxLkVucm9sbG1lbnRTdGF0dXMSFQoNYmlzY3VpdF90b2tlbhgCIAEoDBIdChVwb2xsX2ludGVydmFsX3NlY29uZHMYAyABKAUSFQoNZXJyb3JfbWVzc2FnZRgEIAEoCRIgChhjb250cm9sX3BsYW5lX3B1YmxpY19rZXkYBSABKAwSGAoQcm91dGVyX2FkZHJlc3NlcxgGIAMoCRIvCgtleHBpcmVfdGltZRgHIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAiUwoLU2VydmljZUluZm8SIQoEdHlwZRgBIAEoDjITLnNhbS52MS5TZXJ2aWNlVHlwZRIMCgRuYW1lGAIgASgJEhMKC2Rlc2NyaXB0aW9uGAMgASgJInsKDkNvbW1hbmRCYWNrZW5kEg8KB2NvbW1hbmQYASADKAkSLAoDZW52GAIgAygLMh8uc2FtLnYxLkNvbW1hbmRCYWNrZW5kLkVudkVudHJ5GioKCEVudkVudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAEiigEKFlJlZ2lzdGVyU2VydmljZVJlcXVlc3QSJAoHc2VydmljZRgBIAEoCzITLnNhbS52MS5TZXJ2aWNlSW5mbxIUCgp0YXJnZXRfdXJsGAIgASgJSAASKQoHY29tbWFuZBgDIAEoCzIWLnNhbS52MS5Db21tYW5kQmFja2VuZEgAQgkKB2JhY2tlbmQiaQoSRGlzY292ZXJlZFByb3ZpZGVyEg8KB3BlZXJfaWQYASABKAkSFwoPbG9jYWxfcHJveHlfdXJsGAIgASgJEhAKCHNydl9uYW1lGAMgASgJEhcKD3Nydl9kZXNjcmlwdGlvbhgEIAEoCSKyAgoPU2VydmljZUFubm91bmNlEg8KB3BlZXJfaWQYASABKAkSIQoEdHlwZRgCIAEoDjITLnNhbS52MS5TZXJ2aWNlVHlwZRIUCgxzZXJ2aWNlX25hbWUYAyABKAkSDAoEa2V5cxgEIAMoCRIzCgZsYWJlbHMYBSADKAsyIy5zYW0udjEuU2VydmljZUFubm91bmNlLkxhYmVsc0VudHJ5EhcKD2FjdGl2ZV9yZXF1ZXN0cxgGIAEoDRIXCg9sYXRlbmN5X2V3bWFfbXMYByABKAESMQoNYW5ub3VuY2VfdGltZRgIIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASKHAQoYQ29udHJvbFBsYW5lSW5mb1Jlc3BvbnNlEhMKC29pZGNfaXNzdWVyGAEgASgJEhEKCWNsaWVudF9pZBgCIAEoCRIQCghhdWRpZW5jZRgDIAEoCRIYChByb3V0ZXJfYWRkcmVzc2VzGAQgAygJEhcKD2Jhbm5lZF9wZWVyX2lkcxgFIAMoCSKsAQoSUm91dGVyTGVhc2VSZXF1ZXN0Eg8KB3BlZXJfaWQYASABKAkSEQoJYWRkcmVzc2VzGAIgAygJEg8KB2Jpc2N1aXQYAyABKAwSFwoPY29ubmVjdGVkX3BlZXJzGAQgAygJEhAKCGRodF9zaXplGAUgASgFEhkKEWNoYWxsZW5nZV91bml4X21zGAYgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYByABKAwiZgoTUm91dGVyTGVhc2VSZXNwb25zZRIPCgdzdWNjZXNzGAEgASgIEg0KBWVycm9yGAIgASgJEi8KC2V4cGlyZV90aW1lGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCKeAQoKUG9saWN5Um9sZRIMCgRuYW1lGAEgASgJEhcKD2FsbG93ZWRfdGFyZ2V0cxgCIAMoCRIYChBhbGxvd2VkX3NlcnZpY2VzGAMgAygJEhYKDmN1c3RvbV9kYXRhbG9nGAQgAygJEhYKDmFsbG93ZWRfbGFiZWxzGAUgAygJEh8KBGh0dHAYBiADKAsyES5zYW0udjEuSFRUUEdyYW50IjwKCUhUVFBHcmFudBIPCgdzZXJ2aWNlGAEgASgJEg8KB21ldGhvZHMYAiADKAkSDQoFcGF0aHMYAyADKAkiXAoRRWdyZXNzRGVzdGluYXRpb24SDAoEbmFtZRgBIAEoCRISCgp0YXJnZXRfdXJsGAIgASgJEhIKCmNyZWRlbnRpYWwYAyABKAkSEQoJc2VydmVkX2J5GAQgAygJIi4KDVBvbGljeUJpbmRpbmcSDAoEcm9sZRgBIAEoCRIPCgdtZW1iZXJzGAIgAygJIoUBCgxQb2xpY3lDb25maWcSIQoFcm9sZXMYASADKAsyEi5zYW0udjEuUG9saWN5Um9sZRInCghiaW5kaW5ncxgCIAMoCzIVLnNhbS52MS5Qb2xpY3lCaW5kaW5nEikKBmVncmVzcxgDIAMoCzIZLnNhbS52MS5FZ3Jlc3NEZXN0aW5hdGlvbiIYChZQb2xpY3lDb25maWdHZXRSZXF1ZXN0IjAKF1BvbGljeUNvbmZpZ0dldFJlc3BvbnNlEhUKDWRhdGFsb2dfcnVsZXMYASADKAkiPAoaUG9saWN5Q29uZmlnVXBkYXRlUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCSIaChhFZ3Jlc3NBc3NpZ25tZW50c1JlcXVlc3QiRgoZRWdyZXNzQXNzaWdubWVudHNSZXNwb25zZRIpCgZlZ3Jlc3MYASADKAsyGS5zYW0udjEuRWdyZXNzRGVzdGluYXRpb24iZgoMS2V5c1Jlc3BvbnNlEhMKC3B1YmxpY19rZXlzGAEgAygMEi0KCXNpZ25fdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASEgoKc2lnbmF0dXJlcxgDIAMoDCJeChNUb2tlblJlZnJlc2hSZXF1ZXN0EhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYASABKAwSGQoRY2hhbGxlbmdlX3VuaXhfbXMYAiABKAMSDwoHcGVlcl9pZBgDIAEoCSJ1ChRUb2tlblJlZnJlc2hSZXNwb25zZRIVCg1iaXNjdWl0X3Rva2VuGAEgASgMEi8KC2V4cGlyZV90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIVCg1lcnJvcl9tZXNzYWdlGAMgASgJIjoKEU5vZGVDYXRhbG9nUmVwb3J0EiUKCHNlcnZpY2VzGAEgAygLMhMuc2FtLnYxLlNlcnZpY2VJbmZvIiUKElRva2VuUmV2b2tlUmVxdWVzdBIPCgdwZWVyX2lkGAEgASgJIjUKE1Rva2VuUmV2b2tlUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCSLkAQoYSWRlbnRpdHlFdmlkZW5jZVJlc3BvbnNlEg8KB3BlZXJfaWQYASABKAkSDwoHYmlzY3VpdBgCIAEoDBI3ChNiaXNjdWl0X2V4cGlyZV90aW1lGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIZChFjb250cm9sX3BsYW5lX3VybBgEIAEoCRIiChp0cnVzdGVkX2NvbnRyb2xfcGxhbmVfa2V5cxgFIAMoDBIuCgpjaGVja190aW1lGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCLAAgoUUGVlckV2aWRlbmNlUmVzcG9uc2USDwoHcGVlcl9pZBgBIAEoCRIPCgdiaXNjdWl0GAIgASgMEhUKDXZlcmlmeWluZ19rZXkYAyABKAwSDQoFcm9sZXMYBCADKAkSOAoGbGFiZWxzGAUgAygLMiguc2FtLnYxLlBlZXJFdmlkZW5jZVJlc3BvbnNlLkxhYmVsc0VudHJ5Ei8KC2V4cGlyZV90aW1lGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIWCg5yZXZvY2F0aW9uX2lkcxgHIAMoCRIuCgpjaGVja190aW1lGAggASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBotCgtMYWJlbHNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBIoACChBNZW1iZXJDcmVkZW50aWFsEhkKEWNvbnRyb2xfcGxhbmVfdXJsGAEgASgJEg8KB2Jpc2N1aXQYAiABKAwSLwoLZXhwaXJlX3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEi8KDHRydXN0ZWRfa2V5cxgEIAMoCzIZLnNhbS52MS5UcnVzdGVkU2lnbmluZ0tleRIZChFpc3N1ZWRfdW5kZXJfa2V5cxgFIAMoDBIYChByb3V0ZXJfYWRkcmVzc2VzGAYgAygJEikKDG9pZGNfc2Vzc2lvbhgHIAEoCzITLnNhbS52MS5PSURDU2Vzc2lvbiJZChFUcnVzdGVkU2lnbmluZ0tleRISCgpwdWJsaWNfa2V5GAEgASgMEjAKDHJlY2VpdmVfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAiWQoLT0lEQ1Nlc3Npb24SDgoGaXNzdWVyGAEgASgJEhEKCWNsaWVudF9pZBgCIAEoCRIQCghhdWRpZW5jZRgDIAEoCRIVCg1yZWZyZXNoX3Rva2VuGAQgASgJIo0BChVUYXNrQXV0aG9yaXphdGlvblJ1bGUSDAoEbmFtZRgBIAEoCRIUCgxkaXNwbGF5X25hbWUYAiABKAkSHwoFcnVsZXMYAyADKAsyEC5zYW0udjEuVGFza1J1bGUSLwoLZXhwaXJlX3RpbWUYBCABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wIn4KCFRhc2tSdWxlEhMKC2Rlc2NyaXB0aW9uGAEgASgJEhgKEGFsbG93ZWRfc2VydmljZXMYAiADKAkSKAoJb3BlcmF0aW9uGAMgASgLMhUuc2FtLnYxLlRhc2tPcGVyYXRpb24SGQoRYWxsb3dlZF9yZXNvdXJjZXMYBCADKAkicwoNVGFza09wZXJhdGlvbhIVCg1hbGxvd2VkX3Rvb2xzGAEgAygJEhcKD2FsbG93ZWRfbWV0aG9kcxgCIAMoCRIVCg1hbGxvd2VkX3BhdGhzGAMgAygJEhsKE2FsbG93ZWRfcGVybWlzc2lvbnMYBCADKAkqlAEKEEVucm9sbG1lbnRTdGF0dXMSIQodRU5ST0xMTUVOVF9TVEFUVVNfVU5TUEVDSUZJRUQQABIdChlFTlJPTExNRU5UX1NUQVRVU19QRU5ESU5HEAESHgoaRU5ST0xMTUVOVF9TVEFUVVNfQVBQUk9WRUQQAhIeChpFTlJPTExNRU5UX1NUQVRVU19SRUpFQ1RFRBADKowBCgtTZXJ2aWNlVHlwZRIcChhTRVJWSUNFX1RZUEVfVU5TUEVDSUZJRUQQABIUChBTRVJWSUNFX1RZUEVfTUNQEAESGgoWU0VSVklDRV9UWVBFX0lORkVSRU5DRRACEhQKEFNFUlZJQ0VfVFlQRV9BMkEQAxIXChNTRVJWSUNFX1RZUEVfRUdSRVNTEARCG1oZZ2l0aHViLmNvbS9nb29nbGUvc2FtL2FwaWIGcHJvdG8z", [file_google_protobuf_timestamp]);
+ fileDesc("CglzYW0ucHJvdG8SBnNhbS52MSI0CglBdXRoRnJhbWUSDwoHYmlzY3VpdBgBIAEoDBIWCg50YXJnZXRfc2VydmljZRgCIAEoCSI/CgxBdXRoUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCRIPCgdiaXNjdWl0GAMgASgMItYBCglNZXNoRXZlbnQSJAoEdHlwZRgBIAEoDjIWLnNhbS52MS5NZXNoRXZlbnQuVHlwZRIPCgdwZWVyX2lkGAIgASgJEi4KCmV2ZW50X3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEhYKDm5ld19wdWJsaWNfa2V5GAQgASgMEhEKCXNpZ25hdHVyZRgFIAEoDCI3CgRUeXBlEgoKBkJBTk5FRBAAEhAKDEtFWV9ST1RBVElPThABEhEKDVBPTElDWV9VUERBVEUQAiLzAQoNRW5yb2xsUmVxdWVzdBILCgNqd3QYASABKAkSDwoHcGVlcl9pZBgCIAEoCRISCgpwdWJsaWNfa2V5GAMgASgMEhYKDnJlcXVlc3RlZF9yb2xlGAQgASgJEjEKBmxhYmVscxgFIAMoCzIhLnNhbS52MS5FbnJvbGxSZXF1ZXN0LkxhYmVsc0VudHJ5EhkKEWNoYWxsZW5nZV91bml4X21zGAYgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYByABKAwaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASKrAQoORW5yb2xsUmVzcG9uc2USFQoNYmlzY3VpdF90b2tlbhgBIAEoDBIVCg1lcnJvcl9tZXNzYWdlGAIgASgJEiAKGGNvbnRyb2xfcGxhbmVfcHVibGljX2tleRgDIAEoDBIYChByb3V0ZXJfYWRkcmVzc2VzGAQgAygJEi8KC2V4cGlyZV90aW1lGAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCKRAgoWQm9vdHN0cmFwRW5yb2xsUmVxdWVzdBIXCg9ib290c3RyYXBfdG9rZW4YASABKAkSDwoHcGVlcl9pZBgCIAEoCRISCgpwdWJsaWNfa2V5GAMgASgMEhYKDnJlcXVlc3RlZF9yb2xlGAQgASgJEjoKBmxhYmVscxgFIAMoCzIqLnNhbS52MS5Cb290c3RyYXBFbnJvbGxSZXF1ZXN0LkxhYmVsc0VudHJ5EhkKEWNoYWxsZW5nZV91bml4X21zGAYgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYByABKAwaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASL9AQoXQm9vdHN0cmFwRW5yb2xsUmVzcG9uc2USKAoGc3RhdHVzGAEgASgOMhguc2FtLnYxLkVucm9sbG1lbnRTdGF0dXMSFQoNYmlzY3VpdF90b2tlbhgCIAEoDBIdChVwb2xsX2ludGVydmFsX3NlY29uZHMYAyABKAUSFQoNZXJyb3JfbWVzc2FnZRgEIAEoCRIgChhjb250cm9sX3BsYW5lX3B1YmxpY19rZXkYBSABKAwSGAoQcm91dGVyX2FkZHJlc3NlcxgGIAMoCRIvCgtleHBpcmVfdGltZRgHIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAiUwoLU2VydmljZUluZm8SIQoEdHlwZRgBIAEoDjITLnNhbS52MS5TZXJ2aWNlVHlwZRIMCgRuYW1lGAIgASgJEhMKC2Rlc2NyaXB0aW9uGAMgASgJInsKDkNvbW1hbmRCYWNrZW5kEg8KB2NvbW1hbmQYASADKAkSLAoDZW52GAIgAygLMh8uc2FtLnYxLkNvbW1hbmRCYWNrZW5kLkVudkVudHJ5GioKCEVudkVudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAEiigEKFlJlZ2lzdGVyU2VydmljZVJlcXVlc3QSJAoHc2VydmljZRgBIAEoCzITLnNhbS52MS5TZXJ2aWNlSW5mbxIUCgp0YXJnZXRfdXJsGAIgASgJSAASKQoHY29tbWFuZBgDIAEoCzIWLnNhbS52MS5Db21tYW5kQmFja2VuZEgAQgkKB2JhY2tlbmQiaQoSRGlzY292ZXJlZFByb3ZpZGVyEg8KB3BlZXJfaWQYASABKAkSFwoPbG9jYWxfcHJveHlfdXJsGAIgASgJEhAKCHNydl9uYW1lGAMgASgJEhcKD3Nydl9kZXNjcmlwdGlvbhgEIAEoCSKyAgoPU2VydmljZUFubm91bmNlEg8KB3BlZXJfaWQYASABKAkSIQoEdHlwZRgCIAEoDjITLnNhbS52MS5TZXJ2aWNlVHlwZRIUCgxzZXJ2aWNlX25hbWUYAyABKAkSDAoEa2V5cxgEIAMoCRIzCgZsYWJlbHMYBSADKAsyIy5zYW0udjEuU2VydmljZUFubm91bmNlLkxhYmVsc0VudHJ5EhcKD2FjdGl2ZV9yZXF1ZXN0cxgGIAEoDRIXCg9sYXRlbmN5X2V3bWFfbXMYByABKAESMQoNYW5ub3VuY2VfdGltZRgIIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASKHAQoYQ29udHJvbFBsYW5lSW5mb1Jlc3BvbnNlEhMKC29pZGNfaXNzdWVyGAEgASgJEhEKCWNsaWVudF9pZBgCIAEoCRIQCghhdWRpZW5jZRgDIAEoCRIYChByb3V0ZXJfYWRkcmVzc2VzGAQgAygJEhcKD2Jhbm5lZF9wZWVyX2lkcxgFIAMoCSKsAQoSUm91dGVyTGVhc2VSZXF1ZXN0Eg8KB3BlZXJfaWQYASABKAkSEQoJYWRkcmVzc2VzGAIgAygJEg8KB2Jpc2N1aXQYAyABKAwSFwoPY29ubmVjdGVkX3BlZXJzGAQgAygJEhAKCGRodF9zaXplGAUgASgFEhkKEWNoYWxsZW5nZV91bml4X21zGAYgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYByABKAwiZgoTUm91dGVyTGVhc2VSZXNwb25zZRIPCgdzdWNjZXNzGAEgASgIEg0KBWVycm9yGAIgASgJEi8KC2V4cGlyZV90aW1lGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCKeAQoKUG9saWN5Um9sZRIMCgRuYW1lGAEgASgJEhcKD2FsbG93ZWRfdGFyZ2V0cxgCIAMoCRIYChBhbGxvd2VkX3NlcnZpY2VzGAMgAygJEhYKDmN1c3RvbV9kYXRhbG9nGAQgAygJEhYKDmFsbG93ZWRfbGFiZWxzGAUgAygJEh8KBGh0dHAYBiADKAsyES5zYW0udjEuSFRUUEdyYW50IjwKCUhUVFBHcmFudBIPCgdzZXJ2aWNlGAEgASgJEg8KB21ldGhvZHMYAiADKAkSDQoFcGF0aHMYAyADKAkiXAoRRWdyZXNzRGVzdGluYXRpb24SDAoEbmFtZRgBIAEoCRISCgp0YXJnZXRfdXJsGAIgASgJEhIKCmNyZWRlbnRpYWwYAyABKAkSEQoJc2VydmVkX2J5GAQgAygJIi4KDVBvbGljeUJpbmRpbmcSDAoEcm9sZRgBIAEoCRIPCgdtZW1iZXJzGAIgAygJIoUBCgxQb2xpY3lDb25maWcSIQoFcm9sZXMYASADKAsyEi5zYW0udjEuUG9saWN5Um9sZRInCghiaW5kaW5ncxgCIAMoCzIVLnNhbS52MS5Qb2xpY3lCaW5kaW5nEikKBmVncmVzcxgDIAMoCzIZLnNhbS52MS5FZ3Jlc3NEZXN0aW5hdGlvbiIYChZQb2xpY3lDb25maWdHZXRSZXF1ZXN0IjAKF1BvbGljeUNvbmZpZ0dldFJlc3BvbnNlEhUKDWRhdGFsb2dfcnVsZXMYASADKAkiPAoaUG9saWN5Q29uZmlnVXBkYXRlUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCSIaChhFZ3Jlc3NBc3NpZ25tZW50c1JlcXVlc3QiRgoZRWdyZXNzQXNzaWdubWVudHNSZXNwb25zZRIpCgZlZ3Jlc3MYASADKAsyGS5zYW0udjEuRWdyZXNzRGVzdGluYXRpb24iZgoMS2V5c1Jlc3BvbnNlEhMKC3B1YmxpY19rZXlzGAEgAygMEi0KCXNpZ25fdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASEgoKc2lnbmF0dXJlcxgDIAMoDCJeChNUb2tlblJlZnJlc2hSZXF1ZXN0EhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYASABKAwSGQoRY2hhbGxlbmdlX3VuaXhfbXMYAiABKAMSDwoHcGVlcl9pZBgDIAEoCSJ1ChRUb2tlblJlZnJlc2hSZXNwb25zZRIVCg1iaXNjdWl0X3Rva2VuGAEgASgMEi8KC2V4cGlyZV90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIVCg1lcnJvcl9tZXNzYWdlGAMgASgJIjoKEU5vZGVDYXRhbG9nUmVwb3J0EiUKCHNlcnZpY2VzGAEgAygLMhMuc2FtLnYxLlNlcnZpY2VJbmZvIiUKElRva2VuUmV2b2tlUmVxdWVzdBIPCgdwZWVyX2lkGAEgASgJIjUKE1Rva2VuUmV2b2tlUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCSLkAQoYSWRlbnRpdHlFdmlkZW5jZVJlc3BvbnNlEg8KB3BlZXJfaWQYASABKAkSDwoHYmlzY3VpdBgCIAEoDBI3ChNiaXNjdWl0X2V4cGlyZV90aW1lGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIZChFjb250cm9sX3BsYW5lX3VybBgEIAEoCRIiChp0cnVzdGVkX2NvbnRyb2xfcGxhbmVfa2V5cxgFIAMoDBIuCgpjaGVja190aW1lGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCLAAgoUUGVlckV2aWRlbmNlUmVzcG9uc2USDwoHcGVlcl9pZBgBIAEoCRIPCgdiaXNjdWl0GAIgASgMEhUKDXZlcmlmeWluZ19rZXkYAyABKAwSDQoFcm9sZXMYBCADKAkSOAoGbGFiZWxzGAUgAygLMiguc2FtLnYxLlBlZXJFdmlkZW5jZVJlc3BvbnNlLkxhYmVsc0VudHJ5Ei8KC2V4cGlyZV90aW1lGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIWCg5yZXZvY2F0aW9uX2lkcxgHIAMoCRIuCgpjaGVja190aW1lGAggASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBotCgtMYWJlbHNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBIoACChBNZW1iZXJDcmVkZW50aWFsEhkKEWNvbnRyb2xfcGxhbmVfdXJsGAEgASgJEg8KB2Jpc2N1aXQYAiABKAwSLwoLZXhwaXJlX3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEi8KDHRydXN0ZWRfa2V5cxgEIAMoCzIZLnNhbS52MS5UcnVzdGVkU2lnbmluZ0tleRIZChFpc3N1ZWRfdW5kZXJfa2V5cxgFIAMoDBIYChByb3V0ZXJfYWRkcmVzc2VzGAYgAygJEikKDG9pZGNfc2Vzc2lvbhgHIAEoCzITLnNhbS52MS5PSURDU2Vzc2lvbiJZChFUcnVzdGVkU2lnbmluZ0tleRISCgpwdWJsaWNfa2V5GAEgASgMEjAKDHJlY2VpdmVfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAiWQoLT0lEQ1Nlc3Npb24SDgoGaXNzdWVyGAEgASgJEhEKCWNsaWVudF9pZBgCIAEoCRIQCghhdWRpZW5jZRgDIAEoCRIVCg1yZWZyZXNoX3Rva2VuGAQgASgJIo0BChVUYXNrQXV0aG9yaXphdGlvblJ1bGUSDAoEbmFtZRgBIAEoCRIUCgxkaXNwbGF5X25hbWUYAiABKAkSHwoFcnVsZXMYAyADKAsyEC5zYW0udjEuVGFza1J1bGUSLwoLZXhwaXJlX3RpbWUYBCABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wIn4KCFRhc2tSdWxlEhMKC2Rlc2NyaXB0aW9uGAEgASgJEhgKEGFsbG93ZWRfc2VydmljZXMYAiADKAkSKAoJb3BlcmF0aW9uGAMgASgLMhUuc2FtLnYxLlRhc2tPcGVyYXRpb24SGQoRYWxsb3dlZF9yZXNvdXJjZXMYBCADKAkicwoNVGFza09wZXJhdGlvbhIVCg1hbGxvd2VkX3Rvb2xzGAEgAygJEhcKD2FsbG93ZWRfbWV0aG9kcxgCIAMoCRIVCg1hbGxvd2VkX3BhdGhzGAMgAygJEhsKE2FsbG93ZWRfcGVybWlzc2lvbnMYBCADKAkipQEKFFRva2VuRXhjaGFuZ2VSZXF1ZXN0EhUKDXN1YmplY3RfdG9rZW4YASABKAkSMAoJdGFza19ydWxlGAIgASgLMh0uc2FtLnYxLlRhc2tBdXRob3JpemF0aW9uUnVsZRIMCgRzZWFsGAMgASgIEhkKEWNoYWxsZW5nZV91bml4X21zGAQgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYBSABKAwifwoVVG9rZW5FeGNoYW5nZVJlc3BvbnNlEhUKDWJpc2N1aXRfdG9rZW4YASABKAwSLwoLZXhwaXJlX3RpbWUYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEg0KBXJvbGVzGAMgAygJEg8KB3N1YmplY3QYBCABKAkigQEKD1NUU1Rva2VuUmVxdWVzdBIPCgdiaXNjdWl0GAEgASgMEhMKC2Rlc3RpbmF0aW9uGAIgASgJEhAKCGF1ZGllbmNlGAMgASgJEhkKEWNoYWxsZW5nZV91bml4X21zGAQgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYBSABKAwigwEKEFNUU1Rva2VuUmVzcG9uc2USCwoDand0GAEgASgJEi8KC2V4cGlyZV90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIPCgdzdWJqZWN0GAMgASgJEg0KBXJvbGVzGAQgAygJEhEKCXRhc2tfbmFtZRgFIAEoCSJGChNSZXZvY2F0aW9uc1Jlc3BvbnNlEhYKDnJldm9jYXRpb25faWRzGAEgAygJEhcKD2Jhbm5lZF9wZWVyX2lkcxgCIAMoCSqUAQoQRW5yb2xsbWVudFN0YXR1cxIhCh1FTlJPTExNRU5UX1NUQVRVU19VTlNQRUNJRklFRBAAEh0KGUVOUk9MTE1FTlRfU1RBVFVTX1BFTkRJTkcQARIeChpFTlJPTExNRU5UX1NUQVRVU19BUFBST1ZFRBACEh4KGkVOUk9MTE1FTlRfU1RBVFVTX1JFSkVDVEVEEAMqjAEKC1NlcnZpY2VUeXBlEhwKGFNFUlZJQ0VfVFlQRV9VTlNQRUNJRklFRBAAEhQKEFNFUlZJQ0VfVFlQRV9NQ1AQARIaChZTRVJWSUNFX1RZUEVfSU5GRVJFTkNFEAISFAoQU0VSVklDRV9UWVBFX0EyQRADEhcKE1NFUlZJQ0VfVFlQRV9FR1JFU1MQBEIbWhlnaXRodWIuY29tL2dvb2dsZS9zYW0vYXBpYgZwcm90bzM", [file_google_protobuf_timestamp]);
/**
* @generated from message sam.v1.AuthFrame
@@ -1483,6 +1483,213 @@ export type TaskOperation = Message<"sam.v1.TaskOperation"> & {
export const TaskOperationSchema: GenMessage<TaskOperation> = /*@__PURE__*/
messageDesc(file_sam, 38);
+/**
+ * TokenExchangeRequest is the body of POST /token/exchange on the control
+ * plane: an enrolled sam-node (authenticated via its own Biscuit in
+ * Authorization: Bearer and proof of possession below) exchanges a caller's
+ * platform JWT (OIDC ID token, K8s projected SA JWT, or SPIFFE JWT-SVID) into
+ * a short-lived Delegated Session Biscuit bound to the calling node's
+ * transport channel (client_peer_id + actor_node, without node()).
+ *
+ * @generated from message sam.v1.TokenExchangeRequest
+ */
+export type TokenExchangeRequest = Message<"sam.v1.TokenExchangeRequest"> & {
+ /**
+ * The subject's platform JWT to verify against the control plane's OIDC
+ * providers and allowed audiences.
+ *
+ * @generated from field: string subject_token = 1;
+ */
+ subjectToken: string;
+
+ /**
+ * Optional initial task narrowing to append as block 1 on the minted
+ * Biscuit.
+ *
+ * @generated from field: sam.v1.TaskAuthorizationRule task_rule = 2;
+ */
+ taskRule?: TaskAuthorizationRule | undefined;
+
+ /**
+ * If true, the minted Biscuit is sealed (b.Seal()) before returning so
+ * downstream holders cannot append further blocks.
+ *
+ * @generated from field: bool seal = 3;
+ */
+ seal: boolean;
+
+ /**
+ * Proof of possession of the calling node's enrolled key:
+ * challenge_unix_ms is the caller's clock in unix milliseconds and
+ * challenge_signature signs the UTF-8 bytes of
+ * "sam:token-exchange:<peer_id>:<challenge_unix_ms>".
+ *
+ * @generated from field: int64 challenge_unix_ms = 4;
+ */
+ challengeUnixMs: bigint;
+
+ /**
+ * @generated from field: bytes challenge_signature = 5;
+ */
+ challengeSignature: Uint8Array;
+};
+
+/**
+ * Describes the message sam.v1.TokenExchangeRequest.
+ * Use `create(TokenExchangeRequestSchema)` to create a new message.
+ */
+export const TokenExchangeRequestSchema: GenMessage<TokenExchangeRequest> = /*@__PURE__*/
+ messageDesc(file_sam, 39);
+
+/**
+ * @generated from message sam.v1.TokenExchangeResponse
+ */
+export type TokenExchangeResponse = Message<"sam.v1.TokenExchangeResponse"> & {
+ /**
+ * @generated from field: bytes biscuit_token = 1;
+ */
+ biscuitToken: Uint8Array;
+
+ /**
+ * @generated from field: google.protobuf.Timestamp expire_time = 2;
+ */
+ expireTime?: Timestamp | undefined;
+
+ /**
+ * @generated from field: repeated string roles = 3;
+ */
+ roles: string[];
+
+ /**
+ * @generated from field: string subject = 4;
+ */
+ subject: string;
+};
+
+/**
+ * Describes the message sam.v1.TokenExchangeResponse.
+ * Use `create(TokenExchangeResponseSchema)` to create a new message.
+ */
+export const TokenExchangeResponseSchema: GenMessage<TokenExchangeResponse> = /*@__PURE__*/
+ messageDesc(file_sam, 40);
+
+/**
+ * STSTokenRequest is the body of POST /sts/token on the control plane: an
+ * enrolled egress sam-node asks the control plane (acting as OIDC issuer) to
+ * verify a caller's Biscuit and TaskAuthorizationRule chain for an egress
+ * destination and mint a short-lived ES256 border JWT for cloud STS federation.
+ *
+ * @generated from message sam.v1.STSTokenRequest
+ */
+export type STSTokenRequest = Message<"sam.v1.STSTokenRequest"> & {
+ /**
+ * The caller's Biscuit token (authority block + any tar_block chain).
+ *
+ * @generated from field: bytes biscuit = 1;
+ */
+ biscuit: Uint8Array;
+
+ /**
+ * The egress destination hostname (e.g. "bigquery.googleapis.com").
+ *
+ * @generated from field: string destination = 2;
+ */
+ destination: string;
+
+ /**
+ * Optional explicit audience for the border JWT when not derived from the
+ * destination's broker configuration.
+ *
+ * @generated from field: string audience = 3;
+ */
+ audience: string;
+
+ /**
+ * Proof of possession of the calling egress node's enrolled key:
+ * challenge_unix_ms is the caller's clock in unix milliseconds and
+ * challenge_signature signs the UTF-8 bytes of
+ * "sam:sts-token:<peer_id>:<challenge_unix_ms>".
+ *
+ * @generated from field: int64 challenge_unix_ms = 4;
+ */
+ challengeUnixMs: bigint;
+
+ /**
+ * @generated from field: bytes challenge_signature = 5;
+ */
+ challengeSignature: Uint8Array;
+};
+
+/**
+ * Describes the message sam.v1.STSTokenRequest.
+ * Use `create(STSTokenRequestSchema)` to create a new message.
+ */
+export const STSTokenRequestSchema: GenMessage<STSTokenRequest> = /*@__PURE__*/
+ messageDesc(file_sam, 41);
+
+/**
+ * @generated from message sam.v1.STSTokenResponse
+ */
+export type STSTokenResponse = Message<"sam.v1.STSTokenResponse"> & {
+ /**
+ * @generated from field: string jwt = 1;
+ */
+ jwt: string;
+
+ /**
+ * @generated from field: google.protobuf.Timestamp expire_time = 2;
+ */
+ expireTime?: Timestamp | undefined;
+
+ /**
+ * @generated from field: string subject = 3;
+ */
+ subject: string;
+
+ /**
+ * @generated from field: repeated string roles = 4;
+ */
+ roles: string[];
+
+ /**
+ * @generated from field: string task_name = 5;
+ */
+ taskName: string;
+};
+
+/**
+ * Describes the message sam.v1.STSTokenResponse.
+ * Use `create(STSTokenResponseSchema)` to create a new message.
+ */
+export const STSTokenResponseSchema: GenMessage<STSTokenResponse> = /*@__PURE__*/
+ messageDesc(file_sam, 42);
+
+/**
+ * RevocationsResponse answers GET /revocations on the control plane: the set of
+ * revoked Biscuit authority revocation IDs (hex-encoded RevocationIds()[0]) and
+ * banned peer IDs.
+ *
+ * @generated from message sam.v1.RevocationsResponse
+ */
+export type RevocationsResponse = Message<"sam.v1.RevocationsResponse"> & {
+ /**
+ * @generated from field: repeated string revocation_ids = 1;
+ */
+ revocationIds: string[];
+
+ /**
+ * @generated from field: repeated string banned_peer_ids = 2;
+ */
+ bannedPeerIds: string[];
+};
+
+/**
+ * Describes the message sam.v1.RevocationsResponse.
+ * Use `create(RevocationsResponseSchema)` to create a new message.
+ */
+export const RevocationsResponseSchema: GenMessage<RevocationsResponse> = /*@__PURE__*/
+ messageDesc(file_sam, 43);
+
/**
* @generated from enum sam.v1.EnrollmentStatus
*/
diff --git a/sdk/python/src/agent_mesh/_gen/datalog.json b/sdk/python/src/agent_mesh/_gen/datalog.json
index b3e52993..3096b910 100644
--- a/sdk/python/src/agent_mesh/_gen/datalog.json
+++ b/sdk/python/src/agent_mesh/_gen/datalog.json
@@ -39,6 +39,9 @@
"target_check": "check if allow_network_target($fact, $val) or target_unrestricted(true)",
"time_check": "check if time($time), expiration($exp), $time <= $exp",
"allow_if_true": "allow if true",
+ "fact_node": "node",
+ "fact_client_peer_id": "client_peer_id",
+ "fact_actor_node": "actor_node",
"fact_service": "service",
"fact_connection_peer_id": "connection_peer_id",
"fact_method": "method",
diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.py b/sdk/python/src/agent_mesh/_proto/sam_pb2.py
index 5425f287..2a0a313f 100644
--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.py
+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.py
@@ -14,7 +14,7 @@ _sym_db = _symbol_database.Default()
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\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\"\\\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\".\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*\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\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tsam.proto\x12\x06sam.v1\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\"\\\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\".\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\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sam_pb2', globals())
@@ -32,10 +32,10 @@ if _descriptor._USE_C_DESCRIPTORS == False:
_SERVICEANNOUNCE_LABELSENTRY._serialized_options = b'8\001'
_PEEREVIDENCERESPONSE_LABELSENTRY._options = None
_PEEREVIDENCERESPONSE_LABELSENTRY._serialized_options = b'8\001'
- _ENROLLMENTSTATUS._serialized_start=5123
- _ENROLLMENTSTATUS._serialized_end=5271
- _SERVICETYPE._serialized_start=5274
- _SERVICETYPE._serialized_end=5414
+ _ENROLLMENTSTATUS._serialized_start=5758
+ _ENROLLMENTSTATUS._serialized_end=5906
+ _SERVICETYPE._serialized_start=5909
+ _SERVICETYPE._serialized_end=6049
_AUTHFRAME._serialized_start=54
_AUTHFRAME._serialized_end=106
_AUTHRESPONSE._serialized_start=108
@@ -126,4 +126,14 @@ if _descriptor._USE_C_DESCRIPTORS == False:
_TASKRULE._serialized_end=5003
_TASKOPERATION._serialized_start=5005
_TASKOPERATION._serialized_end=5120
+ _TOKENEXCHANGEREQUEST._serialized_start=5123
+ _TOKENEXCHANGEREQUEST._serialized_end=5288
+ _TOKENEXCHANGERESPONSE._serialized_start=5290
+ _TOKENEXCHANGERESPONSE._serialized_end=5417
+ _STSTOKENREQUEST._serialized_start=5420
+ _STSTOKENREQUEST._serialized_end=5549
+ _STSTOKENRESPONSE._serialized_start=5552
+ _STSTOKENRESPONSE._serialized_end=5683
+ _REVOCATIONSRESPONSE._serialized_start=5685
+ _REVOCATIONSRESPONSE._serialized_end=5755
# @@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 980a3c9e..37bed627 100644
--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi
+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi
@@ -359,6 +359,14 @@ class RegisterServiceRequest(_message.Message):
target_url: str
def __init__(self, service: _Optional[_Union[ServiceInfo, _Mapping]] = ..., target_url: _Optional[str] = ..., command: _Optional[_Union[CommandBackend, _Mapping]] = ...) -> None: ...
+class RevocationsResponse(_message.Message):
+ __slots__ = ["banned_peer_ids", "revocation_ids"]
+ BANNED_PEER_IDS_FIELD_NUMBER: _ClassVar[int]
+ REVOCATION_IDS_FIELD_NUMBER: _ClassVar[int]
+ banned_peer_ids: _containers.RepeatedScalarFieldContainer[str]
+ revocation_ids: _containers.RepeatedScalarFieldContainer[str]
+ def __init__(self, revocation_ids: _Optional[_Iterable[str]] = ..., banned_peer_ids: _Optional[_Iterable[str]] = ...) -> None: ...
+
class RouterLeaseRequest(_message.Message):
__slots__ = ["addresses", "biscuit", "challenge_signature", "challenge_unix_ms", "connected_peers", "dht_size", "peer_id"]
ADDRESSES_FIELD_NUMBER: _ClassVar[int]
@@ -387,6 +395,34 @@ class RouterLeaseResponse(_message.Message):
success: bool
def __init__(self, success: bool = ..., error: _Optional[str] = ..., expire_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...) -> None: ...
+class STSTokenRequest(_message.Message):
+ __slots__ = ["audience", "biscuit", "challenge_signature", "challenge_unix_ms", "destination"]
+ AUDIENCE_FIELD_NUMBER: _ClassVar[int]
+ BISCUIT_FIELD_NUMBER: _ClassVar[int]
+ CHALLENGE_SIGNATURE_FIELD_NUMBER: _ClassVar[int]
+ CHALLENGE_UNIX_MS_FIELD_NUMBER: _ClassVar[int]
+ DESTINATION_FIELD_NUMBER: _ClassVar[int]
+ audience: str
+ biscuit: bytes
+ challenge_signature: bytes
+ challenge_unix_ms: int
+ destination: str
+ def __init__(self, biscuit: _Optional[bytes] = ..., destination: _Optional[str] = ..., audience: _Optional[str] = ..., challenge_unix_ms: _Optional[int] = ..., challenge_signature: _Optional[bytes] = ...) -> None: ...
+
+class STSTokenResponse(_message.Message):
+ __slots__ = ["expire_time", "jwt", "roles", "subject", "task_name"]
+ EXPIRE_TIME_FIELD_NUMBER: _ClassVar[int]
+ JWT_FIELD_NUMBER: _ClassVar[int]
+ ROLES_FIELD_NUMBER: _ClassVar[int]
+ SUBJECT_FIELD_NUMBER: _ClassVar[int]
+ TASK_NAME_FIELD_NUMBER: _ClassVar[int]
+ expire_time: _timestamp_pb2.Timestamp
+ jwt: str
+ roles: _containers.RepeatedScalarFieldContainer[str]
+ subject: str
+ task_name: str
+ def __init__(self, jwt: _Optional[str] = ..., expire_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., subject: _Optional[str] = ..., roles: _Optional[_Iterable[str]] = ..., task_name: _Optional[str] = ...) -> None: ...
+
class ServiceAnnounce(_message.Message):
__slots__ = ["active_requests", "announce_time", "keys", "labels", "latency_ewma_ms", "peer_id", "service_name", "type"]
class LabelsEntry(_message.Message):
@@ -460,6 +496,32 @@ class TaskRule(_message.Message):
operation: TaskOperation
def __init__(self, description: _Optional[str] = ..., allowed_services: _Optional[_Iterable[str]] = ..., operation: _Optional[_Union[TaskOperation, _Mapping]] = ..., allowed_resources: _Optional[_Iterable[str]] = ...) -> None: ...
+class TokenExchangeRequest(_message.Message):
+ __slots__ = ["challenge_signature", "challenge_unix_ms", "seal", "subject_token", "task_rule"]
+ CHALLENGE_SIGNATURE_FIELD_NUMBER: _ClassVar[int]
+ CHALLENGE_UNIX_MS_FIELD_NUMBER: _ClassVar[int]
+ SEAL_FIELD_NUMBER: _ClassVar[int]
+ SUBJECT_TOKEN_FIELD_NUMBER: _ClassVar[int]
+ TASK_RULE_FIELD_NUMBER: _ClassVar[int]
+ challenge_signature: bytes
+ challenge_unix_ms: int
+ seal: bool
+ subject_token: str
+ task_rule: TaskAuthorizationRule
+ def __init__(self, subject_token: _Optional[str] = ..., task_rule: _Optional[_Union[TaskAuthorizationRule, _Mapping]] = ..., seal: bool = ..., challenge_unix_ms: _Optional[int] = ..., challenge_signature: _Optional[bytes] = ...) -> None: ...
+
+class TokenExchangeResponse(_message.Message):
+ __slots__ = ["biscuit_token", "expire_time", "roles", "subject"]
+ BISCUIT_TOKEN_FIELD_NUMBER: _ClassVar[int]
+ EXPIRE_TIME_FIELD_NUMBER: _ClassVar[int]
+ ROLES_FIELD_NUMBER: _ClassVar[int]
+ SUBJECT_FIELD_NUMBER: _ClassVar[int]
+ biscuit_token: bytes
+ expire_time: _timestamp_pb2.Timestamp
+ roles: _containers.RepeatedScalarFieldContainer[str]
+ subject: str
+ 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"]
CHALLENGE_SIGNATURE_FIELD_NUMBER: _ClassVar[int]
diff --git a/sdk/python/src/agent_mesh/authorizer.py b/sdk/python/src/agent_mesh/authorizer.py
index 8d8f902f..0884b98b 100644
--- a/sdk/python/src/agent_mesh/authorizer.py
+++ b/sdk/python/src/agent_mesh/authorizer.py
@@ -89,9 +89,9 @@ def authorize_caller(req: AuthorizeRequest, options: ProviderAuthorizerOptions)
raise AuthorizationError(req.peer_id, "no trusted control plane key")
# Signature under a trusted key, authority block + tar_block chain, expiry and binding
- # to the connection peer: RequireAuthorityBinding and EnforceExpiration.
+ # to the connection peer: RequireAuthorityRequestBinding and EnforceExpiration.
try:
- caller = verify_peer_biscuit(req.biscuit, req.peer_id, keys, now)
+ caller = verify_peer_biscuit(req.biscuit, req.peer_id, keys, now, allow_delegated=True)
except BiscuitVerificationError as err:
raise AuthorizationError(req.peer_id, str(err)) from err
token = _token(req.biscuit, caller.verifying_key)
diff --git a/sdk/python/src/agent_mesh/biscuit.py b/sdk/python/src/agent_mesh/biscuit.py
index 32fbc43d..6a5ddfb1 100644
--- a/sdk/python/src/agent_mesh/biscuit.py
+++ b/sdk/python/src/agent_mesh/biscuit.py
@@ -45,7 +45,7 @@ class BiscuitVerificationError(Exception):
class VerifiedBiscuit:
"""What a verified peer biscuit says about its holder."""
- # The peer the token is bound to (its node() fact).
+ # The peer the token is bound to (its node() or actor_node()/client_peer_id() fact).
peer_id: str
# When the token lapses; the minimum of authority expiration() and any tar_block expire_time.
expiration: datetime
@@ -54,6 +54,7 @@ class VerifiedBiscuit:
roles: list[str] = field(default_factory=list)
labels: dict[str, str] = field(default_factory=dict)
task_rules: list[sam_pb2.TaskAuthorizationRule] = field(default_factory=list)
+ actor_node: Optional[str] = None
def _limits() -> ba.AuthorizerLimits:
@@ -101,6 +102,8 @@ def verify_peer_biscuit(
expected_peer_id: str,
trusted_keys: Sequence[bytes],
now: Optional[datetime] = None,
+ *,
+ allow_delegated: bool = False,
) -> VerifiedBiscuit:
"""Verifies a biscuit received from expected_peer_id over an authenticated
connection. Every trusted key is tried, so a token minted under a retiring
@@ -123,7 +126,12 @@ def verify_peer_biscuit(
def strings(rule: str) -> list[str]:
return [f.terms[0] for f in authorizer.query(ba.Rule(rule)) if isinstance(f.terms[0], str)]
- if expected_peer_id not in strings("p($p) <- node($p)"):
+ bound_nodes = strings("p($p) <- node($p)")
+ actor_nodes = strings("a($a) <- actor_node($a)")
+ client_peers = strings("c($c) <- client_peer_id($c)")
+ is_bound_node = expected_peer_id in bound_nodes
+ is_bound_delegated = allow_delegated and expected_peer_id in actor_nodes and expected_peer_id in client_peers
+ if not is_bound_node and not is_bound_delegated:
raise BiscuitVerificationError(f"biscuit is not bound to peer {expected_peer_id}")
expirations = [f.terms[0] for f in authorizer.query(ba.Rule("e($e) <- expiration($e)")) if isinstance(f.terms[0], datetime)]
@@ -146,6 +154,7 @@ def verify_peer_biscuit(
roles=strings("r($r) <- role($r)"),
labels=labels,
task_rules=task_rules,
+ actor_node=actor_nodes[0] if actor_nodes else None,
)
diff --git a/sdk/testdata/tar_conformance.json b/sdk/testdata/tar_conformance.json
index ae80b568..8d3bbd3a 100644
--- a/sdk/testdata/tar_conformance.json
+++ b/sdk/testdata/tar_conformance.json
@@ -195,6 +195,23 @@
"protocol": "/sam/mcp/1.0.0",
"mcp_tool": "get_weather",
"allow": false
+ },
+ {
+ "name": "delegated_token_no_node_fact_allowed",
+ "biscuit_b64": "EoMDCpgCCgpleHBpcmF0aW9uCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCgphY3Rvcl9ub2RlCg5jbGllbnRfcGVlcl9pZAoRYWxpY2VAZXhhbXBsZS5jb20KBWFsaWNlCgdhbmFseXN0ChlncmFudGVkX3NlcnZpY2VfYWxsX3R5cGVzChhncmFudGVkX3RhcmdldF9hbGxfZmFjdHMSABgDIg0KCwiACBIGIIDXjNIHIgoKCAiCCBIDGIEIIgoKCAiDCBIDGIEIIgkKBwgOEgMYhAgiCQoHCAoSAxiFCCIJCgcIBhIDGIYIIgkKBwiHCBICMAEiCQoHCIgIEgIwARIkCAASILbMbqLs7S/MNUxxdSQyxdy0fmV7eikjJdOF/vP9vqUMGkDV9r4B5SgKQepmB0ZNKUBFf1eupQV6j2ZUbJZhpIyyc8sGMhkrQzrKjhaAeAuCzdw58rK4Ra+2T1zuGmdS4FsFGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sSABgDIgoKCAiKCBIDGIkIEiQIABIgyMkwaG0ipvNYQtUAoVjQ7+Koof6kFICCkMpW5lyivbkaQKqCWX8oRaOd4Y/X8opSrQ+Orjf8PJjg1RlnKK2jroBTjvtjOznHpXXBu20ttRfwZ0YMgRC8Ty6mF5KgoQ+Y/wciQhJA7LYlGFIS30VUUEWoCbNE2cy0zNEd30szIwI5NnokpSuRoXeAMLrX/Py4746cAq+fh/C4f9MfDUcuhenx0abzCw==",
+ "target_service": "mcp://weather",
+ "protocol": "/sam/mcp/1.0.0",
+ "mcp_tool": "get_weather",
+ "allow": true,
+ "expected_effective_expiration": "2034-06-01T00:00:00Z"
+ },
+ {
+ "name": "delegated_token_wrong_actor_rejected",
+ "biscuit_b64": "EoMDCpgCCgpleHBpcmF0aW9uCjQxMkQzS29vV01YcWNaWENWazc4bkhjczRiTGpYZENaRFZwOUVQYVpDcWtMeVFMTXRQak1YCgphY3Rvcl9ub2RlCg5jbGllbnRfcGVlcl9pZAoRYWxpY2VAZXhhbXBsZS5jb20KBWFsaWNlCgdhbmFseXN0ChlncmFudGVkX3NlcnZpY2VfYWxsX3R5cGVzChhncmFudGVkX3RhcmdldF9hbGxfZmFjdHMSABgDIg0KCwiACBIGIIDXjNIHIgoKCAiCCBIDGIEIIgoKCAiDCBIDGIEIIgkKBwgOEgMYhAgiCQoHCAoSAxiFCCIJCgcIBhIDGIYIIgkKBwiHCBICMAEiCQoHCIgIEgIwARIkCAASIBTNtY8uXx8MUP0HL3J4snDARlENL8afG3SFGzj8mjvyGkD3ravwly4/hhdC6NoJTD71etVKI268K+DH71ADto2b/BN4nvClJmhlnXMUx1NtrokUKWFttg5xqB73ZJ5mH6EFGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sSABgDIgoKCAiKCBIDGIkIEiQIABIgjWfu1jbf2FAZ5u7DzJCw++MS8TEJR3kTqMWwR8T8SZcaQHYLptOauiTs8YlbrLtGlI9QlOizbN6osUoPYQG8XtKB5IUkStCssvW/43CzYFSc6PJBTOK9sEY3EAnJR+fyhAUiIgogrTiAvUeC8RC237jw942MXsf/Uk6sW4xDtEuKBr7porw=",
+ "target_service": "mcp://weather",
+ "protocol": "/sam/mcp/1.0.0",
+ "mcp_tool": "get_weather",
+ "allow": false
}
]
}
diff --git a/tests/e2e/standalone.bats b/tests/e2e/standalone.bats
index dc3c7a27..eca74cfd 100644
--- a/tests/e2e/standalone.bats
+++ b/tests/e2e/standalone.bats
@@ -172,6 +172,48 @@ EOF
[[ "$status" -eq 0 ]]
[[ "$output" == *"hello from the mesh"* ]]
+ # STS CUJ: Mint a task-scoped Biscuit on node B narrowed to inference://laptop-llm
+ # via RFC 8693 POST /oauth/token and forward it across B -> router -> A.
+ task_biscuit="$(curl -sf --unix-socket "$sock_b" "http://localhost/oauth/token" \
+ -d 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
+ -d 'resource=inference://laptop-llm' |
+ python3 -c 'import json, sys; print(json.load(sys.stdin)["access_token"])')"
+ [[ -n "$task_biscuit" ]]
+
+ run curl -sf --unix-socket "$sock_b" "http://localhost/v1/chat/completions" \
+ -H "Authorization: Bearer $task_biscuit" \
+ -H 'Content-Type: application/json' \
+ -d '{"model":"e2e-model","messages":[{"role":"user","content":"hi with task biscuit"}]}'
+ [[ "$status" -eq 0 ]]
+ [[ "$output" == *"hello from the mesh"* ]]
+
+ # A Task Biscuit narrowed to a different resource (mcp://other) is rejected by node A's verifier.
+ wrong_biscuit="$(curl -sf --unix-socket "$sock_b" "http://localhost/oauth/token" \
+ -d 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
+ -d 'resource=mcp://other' |
+ python3 -c 'import json, sys; print(json.load(sys.stdin)["access_token"])')"
+ [[ -n "$wrong_biscuit" ]]
+
+ http_code="$(curl -s -o /dev/null -w '%{http_code}' --unix-socket "$sock_b" \
+ "http://localhost/v1/chat/completions" \
+ -H "Authorization: Bearer $wrong_biscuit" \
+ -H 'Content-Type: application/json' \
+ -d '{"model":"e2e-model","messages":[{"role":"user","content":"should fail"}]}')"
+ [[ "$http_code" -ne 200 ]]
+
+ # Revoking the task Biscuit via RFC 7009 POST /oauth/revoke immediately blocks
+ # reuse of that task Biscuit without revoking node B's standing identity.
+ run curl -sf --unix-socket "$sock_b" "http://localhost/oauth/revoke" \
+ --data-urlencode "token=$task_biscuit"
+ [[ "$status" -eq 0 ]]
+
+ revoked_code="$(curl -s -o /dev/null -w '%{http_code}' --unix-socket "$sock_b" \
+ "http://localhost/v1/chat/completions" \
+ -H "Authorization: Bearer $task_biscuit" \
+ -H 'Content-Type: application/json' \
+ -d '{"model":"e2e-model","messages":[{"role":"user","content":"revoked task"}]}')"
+ [[ "$revoked_code" -eq 403 ]]
+
# The plain HTTP server never shows up as an MCP provider: node A had
# registered every configured service before its API came up, so its
# absence here is a verdict, not a race.
diff --git a/tests/integration/sts_cuj_test.go b/tests/integration/sts_cuj_test.go
new file mode 100644
index 00000000..8a7d153d
--- /dev/null
+++ b/tests/integration/sts_cuj_test.go
@@ -0,0 +1,338 @@
+// 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 integration_test
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+)
+
+// TestSTSTaskScopedSecurityCUJ validates the Phase 3 Security Token Service (STS),
+// Task-Scoped Biscuit Attenuation, OAuth 2.1 / PKCE, Envoy ext_authz, RFC 7009
+// Revocation, and Outbound Border JWT Minting journeys end-to-end across real
+// sam-control-plane, sam-router, and sam-node processes.
+func TestSTSTaskScopedSecurityCUJ(t *testing.T) {
+ nodeBin := buildBinary(t, "./cmd/sam-node")
+ tmpDir := t.TempDir()
+ oidcURL, mintToken := startCustomMockOIDC(t)
+
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer upstream.Close()
+
+ policyFile := filepath.Join(tmpDir, "policies.yaml")
+ policyYAML := fmt.Sprintf(`roles:
+ - name: pep
+ allowed_services: ["egress://api.github.com"]
+ allowed_targets: ["*"]
+ - name: developer
+ allowed_services: ["egress://api.github.com"]
+ allowed_targets: ["*"]
+ http:
+ - service: "egress://api.github.com"
+ methods: ["GET", "POST"]
+ paths: ["/repos/acme/*"]
+ - name: contractor
+ allowed_services: ["egress://api.github.com"]
+ allowed_targets: ["*"]
+ http:
+ - service: "egress://api.github.com"
+ methods: ["GET"]
+ paths: ["/repos/acme/public/*"]
+bindings:
+ - role: pep
+ members: ["user:pep-user"]
+ - role: developer
+ members: ["user:dev-user"]
+ - role: contractor
+ members: ["user:contractor-user"]
+ - role: sam:role:node
+ members: ["user:pep-user", "user:dev-user"]
+egress:
+ - name: api.github.com
+ target_url: %q
+ credential: github-token
+ served_by: ["pep"]
+`, upstream.URL)
+ if err := os.WriteFile(policyFile, []byte(policyYAML), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ cpPort, cleanupCP := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, policyFile)
+ defer cleanupCP()
+ controlPlane := fmt.Sprintf("http://127.0.0.1:%d", cpPort)
+
+ secrets := filepath.Join(tmpDir, "secrets")
+ if err := os.MkdirAll(secrets, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(secrets, "github-token"), []byte("ghp_upstream_secret\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ pepToken := "test-token"
+ pep := launchNode(t, nodeBin, os.Environ(), filepath.Join(tmpDir, "pep"), "run",
+ "--control-plane", controlPlane,
+ "--data-dir", filepath.Join(tmpDir, "pep"),
+ "--api-token-path", tokenPath(t, pepToken),
+ "--jwt", mintToken(map[string]any{"sub": "pep-user", "roles": []string{api.RoleNode}}),
+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
+ "--listen", "/ip4/127.0.0.1/tcp/0",
+ "--allow-loopback",
+ "--discovery-interval", "100ms",
+ "--control-plane-sync-interval", "1s",
+ "--secrets-dir", secrets,
+ )
+ pepAPI := pep.waitForAPI(t)
+
+ callerToken := "test-token"
+ caller := launchNode(t, nodeBin, os.Environ(), filepath.Join(tmpDir, "caller"), "run",
+ "--control-plane", controlPlane,
+ "--data-dir", filepath.Join(tmpDir, "caller"),
+ "--api-token-path", tokenPath(t, callerToken),
+ "--jwt", mintToken(map[string]any{"sub": "dev-user", "roles": []string{api.RoleNode}}),
+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
+ "--listen", "/ip4/127.0.0.1/tcp/0",
+ "--allow-loopback",
+ "--discovery-interval", "100ms",
+ "--control-plane-sync-interval", "1s",
+ )
+ callerAPI := caller.waitForAPI(t)
+ connectPeer(t, callerAPI, pep.p2pAddr)
+ waitForDHTPeers(t, pepAPI)
+ pepPeer := extractPeerID(pep.p2pAddr)
+ waitForDiscoverableService(t, callerAPI, callerToken, "egress", "api.github.com")
+
+ client := &http.Client{
+ Timeout: 10 * time.Second,
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+ }
+
+ t.Run("OIDC discovery, JWKS, and OAuth 2.1 PKCE on control plane and protected resource metadata on node", func(t *testing.T) {
+ for _, endpoint := range []string{
+ controlPlane + "/.well-known/openid-configuration",
+ controlPlane + "/.well-known/oauth-authorization-server",
+ controlPlane + "/jwks",
+ "http://" + callerAPI + "/.well-known/oauth-protected-resource",
+ } {
+ resp, err := client.Get(endpoint)
+ if err != nil {
+ t.Fatalf("GET %s: %v", endpoint, err)
+ }
+ _ = resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET %s: status %d, want 200", endpoint, resp.StatusCode)
+ }
+ }
+
+ // OAuth 2.1 Authorization Code + PKCE S256 flow
+ verifier := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
+ sum := sha256.Sum256([]byte(verifier))
+ challenge := base64.RawURLEncoding.EncodeToString(sum[:])
+ userJWT := mintToken(map[string]any{"sub": "dev-user", "email": "[email protected]"})
+
+ authURL, _ := url.Parse(controlPlane + "/oauth/authorize")
+ q := authURL.Query()
+ q.Set("response_type", "code")
+ q.Set("client_id", "mcp-desktop-client")
+ q.Set("redirect_uri", "http://127.0.0.1:54321/callback")
+ q.Set("code_challenge", challenge)
+ q.Set("code_challenge_method", "S256")
+ q.Set("resource", "egress://api.github.com")
+ q.Set("scope", "method:GET path:/repos/acme/public/*")
+ q.Set("id_token_hint", userJWT)
+ q.Set("state", "xyz-state")
+ authURL.RawQuery = q.Encode()
+
+ authResp, err := client.Get(authURL.String())
+ if err != nil {
+ t.Fatalf("GET /oauth/authorize: %v", err)
+ }
+ _ = authResp.Body.Close()
+ if authResp.StatusCode != http.StatusFound {
+ t.Fatalf("/oauth/authorize status = %d, want 302", authResp.StatusCode)
+ }
+ loc, err := url.Parse(authResp.Header.Get("Location"))
+ if err != nil {
+ t.Fatalf("parse redirect Location: %v", err)
+ }
+ code := loc.Query().Get("code")
+ if code == "" {
+ t.Fatalf("missing code in redirect Location %q", loc.String())
+ }
+
+ tokenForm := url.Values{}
+ tokenForm.Set("grant_type", api.GrantTypeAuthorizationCode)
+ tokenForm.Set("code", code)
+ tokenForm.Set("redirect_uri", "http://127.0.0.1:54321/callback")
+ tokenForm.Set("client_id", "mcp-desktop-client")
+ tokenForm.Set("code_verifier", verifier)
+ tokenResp, err := client.PostForm(controlPlane+"/oauth/token", tokenForm)
+ if err != nil {
+ t.Fatalf("POST /oauth/token: %v", err)
+ }
+ defer func() { _ = tokenResp.Body.Close() }()
+ if tokenResp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(tokenResp.Body)
+ t.Fatalf("POST /oauth/token status = %d: %s", tokenResp.StatusCode, string(body))
+ }
+ })
+
+ t.Run("Inbound external JWT exchange and role isolation via ext_authz", func(t *testing.T) {
+ contractorJWT := mintToken(map[string]any{"sub": "contractor-user", "email": "[email protected]"})
+
+ // contractor is allowed GET /repos/acme/public/*
+ reqAllow, _ := http.NewRequest(http.MethodGet, "http://"+callerAPI+"/ext_authz/egress/api.github.com/repos/acme/public/readme", nil)
+ reqAllow.Header.Set("Authorization", "Bearer "+contractorJWT)
+ respAllow, err := client.Do(reqAllow)
+ if err != nil {
+ t.Fatalf("ext_authz allow request: %v", err)
+ }
+ _ = respAllow.Body.Close()
+ if respAllow.StatusCode != http.StatusOK {
+ t.Fatalf("ext_authz allow status = %d, want 200", respAllow.StatusCode)
+ }
+ if got := respAllow.Header.Get(api.HeaderSamRoles); got != "contractor" {
+ t.Fatalf("ext_authz X-Sam-Roles = %q, want \"contractor\" (no node role leakage)", got)
+ }
+
+ // contractor is denied GET /repos/acme/private/secret (even though caller node has developer role!)
+ reqDeny, _ := http.NewRequest(http.MethodGet, "http://"+callerAPI+"/ext_authz/egress/api.github.com/repos/acme/private/secret", nil)
+ reqDeny.Header.Set("Authorization", "Bearer "+contractorJWT)
+ respDeny, err := client.Do(reqDeny)
+ if err != nil {
+ t.Fatalf("ext_authz deny request: %v", err)
+ }
+ _ = respDeny.Body.Close()
+ if respDeny.StatusCode != http.StatusForbidden {
+ t.Fatalf("ext_authz deny status = %d, want 403", respDeny.StatusCode)
+ }
+ })
+
+ t.Run("Task biscuit attenuation, mesh enforcement, outbound STS JWT minting, and task revocation", func(t *testing.T) {
+ // 1. Exchange caller node's standing Biscuit into a narrowed Task Biscuit
+ // only allowing GET /repos/acme/public/* on egress://api.github.com.
+ form := url.Values{}
+ form.Set("grant_type", api.GrantTypeTokenExchange)
+ form.Add("resource", "egress://api.github.com")
+ form.Set("scope", "method:GET path:/repos/acme/public/*")
+
+ reqEx, _ := http.NewRequest(http.MethodPost, "http://"+callerAPI+"/oauth/token", strings.NewReader(form.Encode()))
+ reqEx.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ reqEx.Header.Set("Authorization", "Bearer "+callerToken)
+ respEx, err := client.Do(reqEx)
+ if err != nil {
+ t.Fatalf("POST /oauth/token on caller node: %v", err)
+ }
+ var tokData map[string]any
+ _ = json.NewDecoder(respEx.Body).Decode(&tokData)
+ _ = respEx.Body.Close()
+ if respEx.StatusCode != http.StatusOK {
+ t.Fatalf("POST /oauth/token status = %d, want 200", respEx.StatusCode)
+ }
+ taskBiscuit, _ := tokData["access_token"].(string)
+ if taskBiscuit == "" {
+ t.Fatal("empty access_token from /oauth/token")
+ }
+
+ baseMeshURL := fmt.Sprintf("http://%s/sam/%s/egress/api.github.com", callerAPI, pepPeer)
+ doWithCred := func(method, path, cred string) int {
+ req, _ := http.NewRequest(method, baseMeshURL+path, nil)
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+cred)
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("%s %s: %v", method, path, err)
+ }
+ _ = resp.Body.Close()
+ return resp.StatusCode
+ }
+
+ // 2. Allowed by both developer role and tar_block: GET /repos/acme/public/readme
+ if got := doWithCred(http.MethodGet, "/repos/acme/public/readme", taskBiscuit); got != http.StatusNoContent {
+ t.Fatalf("GET /repos/acme/public/readme with taskBiscuit: %d, want 204", got)
+ }
+
+ // 3. Denied by tar_block method constraint (developer role allows POST, but tar_block only allows GET):
+ if got := doWithCred(http.MethodPost, "/repos/acme/public/readme", taskBiscuit); got != http.StatusForbidden {
+ t.Fatalf("POST /repos/acme/public/readme with taskBiscuit: %d, want 403", got)
+ }
+
+ // 4. Denied by tar_block path constraint (developer role allows /repos/acme/*, but tar_block only allows /repos/acme/public/*):
+ if got := doWithCred(http.MethodGet, "/repos/acme/private/secret", taskBiscuit); got != http.StatusForbidden {
+ t.Fatalf("GET /repos/acme/private/secret with taskBiscuit: %d, want 403", got)
+ }
+
+ // 5. Outbound Border STS JWT Minting at the PEP node for egress://api.github.com:
+ stsForm := url.Values{}
+ stsForm.Set("grant_type", api.GrantTypeTokenExchange)
+ stsForm.Set("subject_token", taskBiscuit)
+ stsForm.Set("subject_token_type", api.TokenTypeBiscuit)
+ stsForm.Set("requested_token_type", api.TokenTypeJWT)
+ stsForm.Add("resource", "egress://api.github.com")
+ stsForm.Set("audience", "https://sts.googleapis.com")
+ stsResp, err := client.PostForm("http://"+pepAPI+"/oauth/token", stsForm)
+ if err != nil {
+ t.Fatalf("POST /oauth/token (border JWT): %v", err)
+ }
+ var stsData map[string]any
+ _ = json.NewDecoder(stsResp.Body).Decode(&stsData)
+ _ = stsResp.Body.Close()
+ if stsResp.StatusCode != http.StatusOK {
+ t.Fatalf("border JWT status = %d, want 200: %v", stsResp.StatusCode, stsData)
+ }
+ borderJWT, _ := stsData["access_token"].(string)
+ if strings.Count(borderJWT, ".") != 2 {
+ t.Fatalf("expected compact JWT with 2 dots, got %q", borderJWT)
+ }
+
+ // 6. Revoke taskBiscuit on the PEP node (and caller node) via RFC 7009 POST /oauth/revoke:
+ revForm := url.Values{}
+ revForm.Set("token", taskBiscuit)
+ for _, addr := range []string{pepAPI, callerAPI} {
+ revResp, err := client.PostForm("http://"+addr+"/oauth/revoke", revForm)
+ if err != nil {
+ t.Fatalf("POST /oauth/revoke on %s: %v", addr, err)
+ }
+ _ = revResp.Body.Close()
+ if revResp.StatusCode != http.StatusOK {
+ t.Fatalf("POST /oauth/revoke status = %d, want 200", revResp.StatusCode)
+ }
+ }
+
+ // Revoked taskBiscuit is now rejected immediately, while caller's parent node identity still works!
+ if got := doWithCred(http.MethodGet, "/repos/acme/public/readme", taskBiscuit); got != http.StatusForbidden {
+ t.Fatalf("revoked taskBiscuit status = %d, want 403", got)
+ }
+ if got := doWithCred(http.MethodGet, "/repos/acme/private/secret", callerToken); got != http.StatusNoContent {
+ t.Fatalf("parent node identity status = %d, want 204", got)
+ }
+ })
+}