Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
feat(auth): implement Phase 2 TaskAuthorizationRule (tar_block) attenuation and cross-language verification
Antonio Ojea198c1a23e875
diff --git a/AGENTS.md b/AGENTS.mdindex 0b1aec10..73812c78 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -9,7 +9,7 @@ You are an expert software engineering assistant helping to develop, maintain, a* **Instants are `google.protobuf.Timestamp`, named `*_time`** (`expire_time`, `sign_time`, `event_time`), never `int64` seconds or milliseconds. `Timestamp` has fixed units, an explicit unset, renders as RFC 3339 in protojson (an `int64` renders as a quoted decimal string), and has a first-class conversion in Go, JavaScript, Python and Dart. A receiver treats an unset instant as invalid, never as the epoch. The one exception is a proof-of-possession value: it is the number that appears in the signed text (`sam:<endpoint>:<peer_id>:<n>`), so it stays an `int64` named `challenge_unix_ms`, the unit in the name. What a member persists between runs is also a message here (`MemberCredential`), so a state directory written by one implementation loads in another.* **Datalog text is the policy contract:** the control plane renders the mesh policy as Datalog rules (`PolicyConfigGetResponse.datalog_rules`); every member, in any language, adds that text to its authorizer and none derives rules from roles and bindings itself. Datalog must stay in the form every Biscuit implementation parses: a predicate carries at least one term (presence-only facts are `name(true)`, see `api.MarkerFact`).* **Secrets never travel as flag values:** binaries read credentials from a file (`--*-path`) or the environment, never from a command-line argument that would sit in `ps` output and shell history. Banners and logs name the source of an operator-supplied secret instead of echoing it.-* **Task-Scoped Authorization & Safe Biscuit Attenuation (`tar_block`):** SAM acts as the Authority, Policy Decision Point (PDP), and Task-Scoped Credential Layer (`sts.md`). Never add Datalog rules or checks to non-authority Biscuit blocks (`block_idx >= 1`). Appended blocks must contain 0 rules, 0 checks, and at most 1 `tar_block("<base64url-proto>")` fact encoding a serialized `api.TaskAuthorizationRule`. Verifiers enforce the intersection of Block 0 Datalog RBAC and every appended `TaskAuthorizationRule` in Go, TypeScript, and Python.+* **Task-Scoped Authorization & Safe Biscuit Attenuation (`tar_block`):** SAM acts as the Authority, Policy Decision Point (PDP), and Task-Scoped Credential Layer (`sts.md`). Never add Datalog rules or checks to non-authority Biscuit blocks (`block_idx >= 1`). Appended blocks must contain 0 rules, 0 checks, and exactly 1 `tar_block("<base64url-proto>")` fact encoding a serialized `api.TaskAuthorizationRule`. Verifiers enforce the intersection of Block 0 Datalog RBAC and every appended `TaskAuthorizationRule` in Go, TypeScript, and Python.* **Two-Token Model & Complementary Gateway/PEP Integration:** Inside the mesh, credentials are Biscuits; at both borders, credentials are standard JWTs (`sts.md`). Inbound platform credentials (OIDC, K8s SA, SPIFFE JWT-SVID) exchange into delegated Biscuits (`POST /token/exchange`); outbound verified Biscuits mint short-lived ES256 JWTs at the control plane (`POST /sts/token`) that the egress node exchanges at cloud STS endpoints (`CloudTokenExchanger`). `sam-node` integrates with existing gateways (`agentgateway`, Istio, Envoy) via Envoy `ext_authz` / `ext_proc` and RFC 8693 `/oauth/token`, while native SDKs (`sdk/js`, `sdk/python`) attenuate and seal Biscuits in memory.* **Policy on Names:** egress policy, secret injection and routing decisions are made on the destination *name*, never on an IP. Deny by default.* **Zero Trust:** Enforce a Zero Trust architecture. Assume no implicit trust between nodes, control planes, routers, or external actors. All data passing through the API must be authenticated, authorized, and validated.diff --git a/api/datalog.go b/api/datalog.goindex 50fbe054..69c70cd5 100644--- a/api/datalog.go+++ b/api/datalog.go@@ -320,6 +320,14 @@ const (// Contains: biscuit.Date(currentTime)// Example Datalog: check if time($time)FactTime = "time"++ // FactTARBlock is the sole Datalog predicate allowed in a holder-appended+ // Biscuit attenuation block (block index >= 1). Its single string term is+ // the unpadded base64url-encoded protobuf serialization of an+ // api.TaskAuthorizationRule.+ // Contains: biscuit.String(base64urlProto)+ // Example Datalog: tar_block("ChB0YXNrLWJxLXJlYWQtMTIz...")+ FactTARBlock = "tar_block")// MarkerTerm is the single term every marker fact carries, written `true` indiff --git a/api/sam.pb.go b/api/sam.pb.goindex 4f5a5565..56ed699d 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -2715,6 +2715,234 @@ func (x *OIDCSession) GetRefreshToken() string {return ""}+// TaskAuthorizationRule narrows a credential's authority for a specific task or+// sub-agent hop. Across multiple appended blocks (1..k), semantics are strict+// set intersection (logical AND): a request is permitted only if it is allowed+// by the standing mesh policy AND is before every block's expire_time AND+// matches at least one TaskRule in EVERY appended TaskAuthorizationRule block.+type TaskAuthorizationRule struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"`+ // Positive allow-list of rules for this hop. Empty rules list denies everything.+ Rules []*TaskRule `protobuf:"bytes,3,rep,name=rules,proto3" json:"rules,omitempty"`+ // Optional shorter expiration for this task hop. Effective token expiry is+ // the minimum across the authority block's expiration() fact and every+ // appended block's expire_time.+ ExpireTime *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *TaskAuthorizationRule) Reset() {+ *x = TaskAuthorizationRule{}+ mi := &file_api_sam_proto_msgTypes[36]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *TaskAuthorizationRule) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*TaskAuthorizationRule) ProtoMessage() {}++func (x *TaskAuthorizationRule) ProtoReflect() protoreflect.Message {+ mi := &file_api_sam_proto_msgTypes[36]+ 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 TaskAuthorizationRule.ProtoReflect.Descriptor instead.+func (*TaskAuthorizationRule) Descriptor() ([]byte, []int) {+ return file_api_sam_proto_rawDescGZIP(), []int{36}+}++func (x *TaskAuthorizationRule) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *TaskAuthorizationRule) GetDisplayName() string {+ if x != nil {+ return x.DisplayName+ }+ return ""+}++func (x *TaskAuthorizationRule) GetRules() []*TaskRule {+ if x != nil {+ return x.Rules+ }+ return nil+}++func (x *TaskAuthorizationRule) GetExpireTime() *timestamppb.Timestamp {+ if x != nil {+ return x.ExpireTime+ }+ return nil+}++type TaskRule struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"`+ // Allowed mesh services (e.g., "mcp://bigquery", "inference://gemini.*",+ // "egress://bigquery.googleapis.com"). Uses the dot-anchored grammar of+ // api.ValidateServiceFormat ("*", "<type>://*", "<type>://*.<suffix>",+ // "<type>://<prefix>.*", "<type>://<exact>"). Required (non-empty).+ AllowedServices []string `protobuf:"bytes,2,rep,name=allowed_services,json=allowedServices,proto3" json:"allowed_services,omitempty"`+ // Optional operation-level allow-list. If set, the request must also match+ // the specified MCP tools, HTTP methods/paths, or cloud permissions.+ Operation *TaskOperation `protobuf:"bytes,3,opt,name=operation,proto3" json:"operation,omitempty"`+ // Optional allowed upstream resource names (e.g. CRM resource prefixes+ // "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026").+ // Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.+ AllowedResources []string `protobuf:"bytes,4,rep,name=allowed_resources,json=allowedResources,proto3" json:"allowed_resources,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *TaskRule) Reset() {+ *x = TaskRule{}+ mi := &file_api_sam_proto_msgTypes[37]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *TaskRule) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*TaskRule) ProtoMessage() {}++func (x *TaskRule) ProtoReflect() protoreflect.Message {+ mi := &file_api_sam_proto_msgTypes[37]+ 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 TaskRule.ProtoReflect.Descriptor instead.+func (*TaskRule) Descriptor() ([]byte, []int) {+ return file_api_sam_proto_rawDescGZIP(), []int{37}+}++func (x *TaskRule) GetDescription() string {+ if x != nil {+ return x.Description+ }+ return ""+}++func (x *TaskRule) GetAllowedServices() []string {+ if x != nil {+ return x.AllowedServices+ }+ return nil+}++func (x *TaskRule) GetOperation() *TaskOperation {+ if x != nil {+ return x.Operation+ }+ return nil+}++func (x *TaskRule) GetAllowedResources() []string {+ if x != nil {+ return x.AllowedResources+ }+ return nil+}++type TaskOperation struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // Allowed MCP tool names (enforced by the PEP on mcp:// tools/call).+ AllowedTools []string `protobuf:"bytes,1,rep,name=allowed_tools,json=allowedTools,proto3" json:"allowed_tools,omitempty"`+ // Allowed HTTP methods (e.g. ["GET", "POST"]), validated with httpMethodSyntax.+ AllowedMethods []string `protobuf:"bytes,2,rep,name=allowed_methods,json=allowedMethods,proto3" json:"allowed_methods,omitempty"`+ // Allowed HTTP path patterns ("/exact" or "/prefix/*"), validated with+ // validateHTTPGrantPath.+ AllowedPaths []string `protobuf:"bytes,3,rep,name=allowed_paths,json=allowedPaths,proto3" json:"allowed_paths,omitempty"`+ // Allowed cloud IAM permissions (e.g. "bigquery.googleapis.com/datasets.get").+ // Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.+ AllowedPermissions []string `protobuf:"bytes,4,rep,name=allowed_permissions,json=allowedPermissions,proto3" json:"allowed_permissions,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *TaskOperation) Reset() {+ *x = TaskOperation{}+ mi := &file_api_sam_proto_msgTypes[38]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *TaskOperation) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*TaskOperation) ProtoMessage() {}++func (x *TaskOperation) ProtoReflect() protoreflect.Message {+ mi := &file_api_sam_proto_msgTypes[38]+ 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 TaskOperation.ProtoReflect.Descriptor instead.+func (*TaskOperation) Descriptor() ([]byte, []int) {+ return file_api_sam_proto_rawDescGZIP(), []int{38}+}++func (x *TaskOperation) GetAllowedTools() []string {+ if x != nil {+ return x.AllowedTools+ }+ return nil+}++func (x *TaskOperation) GetAllowedMethods() []string {+ if x != nil {+ return x.AllowedMethods+ }+ return nil+}++func (x *TaskOperation) GetAllowedPaths() []string {+ if x != nil {+ return x.AllowedPaths+ }+ return nil+}++func (x *TaskOperation) GetAllowedPermissions() []string {+ if x != nil {+ return x.AllowedPermissions+ }+ return nil+}+var File_api_sam_proto protoreflect.FileDescriptorconst file_api_sam_proto_rawDesc = "" +@@ -2930,7 +3158,23 @@ const file_api_sam_proto_rawDesc = "" +"\x06issuer\x18\x01 \x01(\tR\x06issuer\x12\x1b\n" +"\tclient_id\x18\x02 \x01(\tR\bclientId\x12\x1a\n" +"\baudience\x18\x03 \x01(\tR\baudience\x12#\n" +- "\rrefresh_token\x18\x04 \x01(\tR\frefreshToken*\x94\x01\n" ++ "\rrefresh_token\x18\x04 \x01(\tR\frefreshToken\"\xb3\x01\n" ++ "\x15TaskAuthorizationRule\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12!\n" ++ "\fdisplay_name\x18\x02 \x01(\tR\vdisplayName\x12&\n" ++ "\x05rules\x18\x03 \x03(\v2\x10.sam.v1.TaskRuleR\x05rules\x12;\n" ++ "\vexpire_time\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\n" ++ "expireTime\"\xb9\x01\n" ++ "\bTaskRule\x12 \n" ++ "\vdescription\x18\x01 \x01(\tR\vdescription\x12)\n" ++ "\x10allowed_services\x18\x02 \x03(\tR\x0fallowedServices\x123\n" ++ "\toperation\x18\x03 \x01(\v2\x15.sam.v1.TaskOperationR\toperation\x12+\n" ++ "\x11allowed_resources\x18\x04 \x03(\tR\x10allowedResources\"\xb3\x01\n" ++ "\rTaskOperation\x12#\n" ++ "\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" +"\x10EnrollmentStatus\x12!\n" +"\x1dENROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n" +"\x19ENROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n" +@@ -2956,7 +3200,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, 41)+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 44)var file_api_sam_proto_goTypes = []any{(EnrollmentStatus)(0), // 0: sam.v1.EnrollmentStatus(ServiceType)(0), // 1: sam.v1.ServiceType@@ -2997,51 +3241,57 @@ var file_api_sam_proto_goTypes = []any{(*MemberCredential)(nil), // 36: sam.v1.MemberCredential(*TrustedSigningKey)(nil), // 37: sam.v1.TrustedSigningKey(*OIDCSession)(nil), // 38: sam.v1.OIDCSession- nil, // 39: sam.v1.EnrollRequest.LabelsEntry- nil, // 40: sam.v1.BootstrapEnrollRequest.LabelsEntry- nil, // 41: sam.v1.CommandBackend.EnvEntry- nil, // 42: sam.v1.ServiceAnnounce.LabelsEntry- nil, // 43: sam.v1.PeerEvidenceResponse.LabelsEntry- (*timestamppb.Timestamp)(nil), // 44: google.protobuf.Timestamp+ (*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}var file_api_sam_proto_depIdxs = []int32{2, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type- 44, // 1: sam.v1.MeshEvent.event_time:type_name -> google.protobuf.Timestamp- 39, // 2: sam.v1.EnrollRequest.labels:type_name -> sam.v1.EnrollRequest.LabelsEntry- 44, // 3: sam.v1.EnrollResponse.expire_time:type_name -> google.protobuf.Timestamp- 40, // 4: sam.v1.BootstrapEnrollRequest.labels:type_name -> sam.v1.BootstrapEnrollRequest.LabelsEntry+ 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.LabelsEntry0, // 5: sam.v1.BootstrapEnrollResponse.status:type_name -> sam.v1.EnrollmentStatus- 44, // 6: sam.v1.BootstrapEnrollResponse.expire_time:type_name -> google.protobuf.Timestamp+ 47, // 6: sam.v1.BootstrapEnrollResponse.expire_time:type_name -> google.protobuf.Timestamp1, // 7: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType- 41, // 8: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry+ 44, // 8: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry10, // 9: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo11, // 10: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend1, // 11: sam.v1.ServiceAnnounce.type:type_name -> sam.v1.ServiceType- 42, // 12: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry- 44, // 13: sam.v1.ServiceAnnounce.announce_time:type_name -> google.protobuf.Timestamp- 44, // 14: sam.v1.RouterLeaseResponse.expire_time:type_name -> google.protobuf.Timestamp+ 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.Timestamp19, // 15: sam.v1.PolicyRole.http:type_name -> sam.v1.HTTPGrant18, // 16: sam.v1.PolicyConfig.roles:type_name -> sam.v1.PolicyRole21, // 17: sam.v1.PolicyConfig.bindings:type_name -> sam.v1.PolicyBinding20, // 18: sam.v1.PolicyConfig.egress:type_name -> sam.v1.EgressDestination20, // 19: sam.v1.EgressAssignmentsResponse.egress:type_name -> sam.v1.EgressDestination- 44, // 20: sam.v1.KeysResponse.sign_time:type_name -> google.protobuf.Timestamp- 44, // 21: sam.v1.TokenRefreshResponse.expire_time:type_name -> google.protobuf.Timestamp+ 47, // 20: sam.v1.KeysResponse.sign_time:type_name -> google.protobuf.Timestamp+ 47, // 21: sam.v1.TokenRefreshResponse.expire_time:type_name -> google.protobuf.Timestamp10, // 22: sam.v1.NodeCatalogReport.services:type_name -> sam.v1.ServiceInfo- 44, // 23: sam.v1.IdentityEvidenceResponse.biscuit_expire_time:type_name -> google.protobuf.Timestamp- 44, // 24: sam.v1.IdentityEvidenceResponse.check_time:type_name -> google.protobuf.Timestamp- 43, // 25: sam.v1.PeerEvidenceResponse.labels:type_name -> sam.v1.PeerEvidenceResponse.LabelsEntry- 44, // 26: sam.v1.PeerEvidenceResponse.expire_time:type_name -> google.protobuf.Timestamp- 44, // 27: sam.v1.PeerEvidenceResponse.check_time:type_name -> google.protobuf.Timestamp- 44, // 28: sam.v1.MemberCredential.expire_time:type_name -> google.protobuf.Timestamp+ 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.Timestamp37, // 29: sam.v1.MemberCredential.trusted_keys:type_name -> sam.v1.TrustedSigningKey38, // 30: sam.v1.MemberCredential.oidc_session:type_name -> sam.v1.OIDCSession- 44, // 31: sam.v1.TrustedSigningKey.receive_time:type_name -> google.protobuf.Timestamp- 32, // [32:32] is the sub-list for method output_type- 32, // [32:32] is the sub-list for method input_type- 32, // [32:32] is the sub-list for extension type_name- 32, // [32:32] is the sub-list for extension extendee- 0, // [0:32] is the sub-list for field type_name+ 47, // 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+ 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}func init() { file_api_sam_proto_init() }@@ -3059,7 +3309,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: 41,+ NumMessages: 44,NumExtensions: 0,NumServices: 0,},diff --git a/api/sam.proto b/api/sam.protoindex 0a4dfcaa..c289ec5b 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -441,5 +441,54 @@ message OIDCSession {string refresh_token = 4;}+// ============================================================================+// Task-Scoped Authorization (TAR)+// ============================================================================-+// TaskAuthorizationRule narrows a credential's authority for a specific task or+// sub-agent hop. Across multiple appended blocks (1..k), semantics are strict+// set intersection (logical AND): a request is permitted only if it is allowed+// by the standing mesh policy AND is before every block's expire_time AND+// matches at least one TaskRule in EVERY appended TaskAuthorizationRule block.+message TaskAuthorizationRule {+ string name = 1;+ string display_name = 2;+ // Positive allow-list of rules for this hop. Empty rules list denies everything.+ repeated TaskRule rules = 3;+ // Optional shorter expiration for this task hop. Effective token expiry is+ // the minimum across the authority block's expiration() fact and every+ // appended block's expire_time.+ google.protobuf.Timestamp expire_time = 4;+}++message TaskRule {+ string description = 1;++ // Allowed mesh services (e.g., "mcp://bigquery", "inference://gemini.*",+ // "egress://bigquery.googleapis.com"). Uses the dot-anchored grammar of+ // api.ValidateServiceFormat ("*", "<type>://*", "<type>://*.<suffix>",+ // "<type>://<prefix>.*", "<type>://<exact>"). Required (non-empty).+ repeated string allowed_services = 2;++ // Optional operation-level allow-list. If set, the request must also match+ // the specified MCP tools, HTTP methods/paths, or cloud permissions.+ TaskOperation operation = 3;++ // Optional allowed upstream resource names (e.g. CRM resource prefixes+ // "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026").+ // Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.+ repeated string allowed_resources = 4;+}++message TaskOperation {+ // Allowed MCP tool names (enforced by the PEP on mcp:// tools/call).+ repeated string allowed_tools = 1;+ // Allowed HTTP methods (e.g. ["GET", "POST"]), validated with httpMethodSyntax.+ repeated string allowed_methods = 2;+ // Allowed HTTP path patterns ("/exact" or "/prefix/*"), validated with+ // validateHTTPGrantPath.+ repeated string allowed_paths = 3;+ // Allowed cloud IAM permissions (e.g. "bigquery.googleapis.com/datasets.get").+ // Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.+ repeated string allowed_permissions = 4;+}diff --git a/api/tar.go b/api/tar.gonew file mode 100644index 00000000..170b73ee--- /dev/null+++ b/api/tar.go@@ -0,0 +1,465 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package api++import (+ "encoding/base64"+ "fmt"+ "regexp"+ "slices"+ "strings"+ "time"++ "github.com/biscuit-auth/biscuit-go/v2"+ "google.golang.org/protobuf/proto"+)++// Structural bounds for holder-appended TaskAuthorizationRule (tar_block)+// attenuation blocks. Enforced identically by the Go, TypeScript, and Python+// verifiers before evaluating a request.+const (+ // MaxAttenuationBlocks is the maximum number of appended Biscuit blocks+ // (block index 1..MaxAttenuationBlocks) allowed on an inbound token.+ MaxAttenuationBlocks = 8++ // MaxTARBytes is the maximum serialized protobuf byte size of a single+ // TaskAuthorizationRule before base64url encoding.+ MaxTARBytes = 4096++ // MaxRulesPerTAR is the maximum number of TaskRule entries in one+ // TaskAuthorizationRule.+ MaxRulesPerTAR = 16++ // MaxEntriesPerTARList is the maximum number of strings in any repeated+ // field of TaskRule or TaskOperation.+ MaxEntriesPerTARList = 64++ // MaxTARNameLength is the maximum byte length of task_id, name, service+ // patterns, tool names, HTTP paths, and cloud permissions in a TAR.+ MaxTARNameLength = 128++ // MaxTARDescriptionLength is the maximum byte length of human-readable+ // description fields in TaskAuthorizationRule and TaskRule.+ MaxTARDescriptionLength = 256++ // MaxTARResourceLength is the maximum byte length of an allowed_resources+ // entry (e.g. a cloud resource manager path).+ MaxTARResourceLength = 256++ // TARBlockSourcePattern is the exact regular expression that every+ // appended block's Datalog source text must match across Go, TypeScript,+ // and Python verifiers. It permits only a single tar_block("<base64url>")+ // fact with zero rules and zero checks.+ TARBlockSourcePattern = `^tar_block\("([A-Za-z0-9_-]+)"\);?\s*$`+)++var (+ // TARBlockSourceRegex matches the Datalog source of a valid tar_block.+ TARBlockSourceRegex = regexp.MustCompile(TARBlockSourcePattern)+)++// HTTPMethodSyntaxPattern returns the regular expression string used to+// validate HTTP methods in PolicyRole.http and TaskOperation.allowed_methods.+func HTTPMethodSyntaxPattern() string {+ return httpMethodSyntax.String()+}++// ValidateTARServicePattern validates an entry in TaskRule.allowed_services+// using the same dot-anchored service grammar as PolicyRole.allowed_services+// ("*", "<type>://*", "<type>://*.<suffix>", "<type>://<prefix>.*",+// "<type>://<exact>").+func ValidateTARServicePattern(svc string) error {+ if svc == "" {+ return fmt.Errorf("allowed_services entry cannot be empty")+ }+ if len(svc) > MaxTARNameLength {+ return fmt.Errorf("allowed_services entry %q exceeds max length %d", svc, MaxTARNameLength)+ }+ if err := ValidateServiceFormat(svc); err != nil {+ return err+ }+ if svc == "*" {+ return nil+ }+ _, svcName := ParseServiceTarget(svc)+ if strings.Contains(svcName, "/") {+ return fmt.Errorf("invalid service format %q: path segments are not allowed in allowed_services (use allowed_paths)", svc)+ }+ if svcName != "*" && strings.Count(svcName, "*") > 1 {+ return fmt.Errorf("invalid service format %q: at most one wildcard is allowed", svc)+ }+ return nil+}++// ValidateTaskAuthorizationRule validates the structural limits and field+// grammars of a TaskAuthorizationRule. An empty rules list is valid and+// represents a fail-closed rule set that denies all requests.+func ValidateTaskAuthorizationRule(rule *TaskAuthorizationRule) error {+ if rule == nil {+ return fmt.Errorf("task authorization rule is nil")+ }+ if len(rule.GetName()) > MaxTARNameLength {+ return fmt.Errorf("name exceeds max length %d", MaxTARNameLength)+ }+ if len(rule.GetDisplayName()) > MaxTARDescriptionLength {+ return fmt.Errorf("display_name exceeds max length %d", MaxTARDescriptionLength)+ }+ if exp := rule.GetExpireTime(); exp != nil {+ if !exp.IsValid() {+ return fmt.Errorf("expire_time is invalid")+ }+ if exp.AsTime().Unix() <= 0 {+ return fmt.Errorf("expire_time must be after the Unix epoch")+ }+ }+ if len(rule.GetRules()) > MaxRulesPerTAR {+ return fmt.Errorf("rules count %d exceeds max %d", len(rule.GetRules()), MaxRulesPerTAR)+ }+ for i, r := range rule.GetRules() {+ if err := validateTaskRule(i, r); err != nil {+ return err+ }+ }+ return nil+}++func validateTaskRule(idx int, r *TaskRule) error {+ if r == nil {+ return fmt.Errorf("rule[%d] is nil", idx)+ }+ if len(r.GetDescription()) > MaxTARDescriptionLength {+ return fmt.Errorf("rule[%d]: description exceeds max length %d", idx, MaxTARDescriptionLength)+ }+ services := r.GetAllowedServices()+ if len(services) == 0 {+ return fmt.Errorf("rule[%d]: allowed_services must not be empty", idx)+ }+ if len(services) > MaxEntriesPerTARList {+ return fmt.Errorf("rule[%d]: allowed_services count %d exceeds max %d", idx, len(services), MaxEntriesPerTARList)+ }+ for _, svc := range services {+ if err := ValidateTARServicePattern(svc); err != nil {+ return fmt.Errorf("rule[%d]: %w", idx, err)+ }+ }+ if len(r.GetAllowedResources()) > MaxEntriesPerTARList {+ return fmt.Errorf("rule[%d]: allowed_resources count %d exceeds max %d", idx, len(r.GetAllowedResources()), MaxEntriesPerTARList)+ }+ for _, res := range r.GetAllowedResources() {+ if res == "" || len(res) > MaxTARResourceLength {+ return fmt.Errorf("rule[%d]: invalid allowed_resources entry %q", idx, res)+ }+ }+ op := r.GetOperation()+ if op == nil {+ return nil+ }+ if len(op.GetAllowedTools()) > MaxEntriesPerTARList {+ return fmt.Errorf("rule[%d]: allowed_tools count %d exceeds max %d", idx, len(op.GetAllowedTools()), MaxEntriesPerTARList)+ }+ for _, tool := range op.GetAllowedTools() {+ if tool == "" || len(tool) > MaxTARNameLength || strings.ContainsAny(tool, "/?# \t\r\n") {+ return fmt.Errorf("rule[%d]: invalid tool name %q in allowed_tools", idx, tool)+ }+ }+ if len(op.GetAllowedMethods()) > MaxEntriesPerTARList {+ return fmt.Errorf("rule[%d]: allowed_methods count %d exceeds max %d", idx, len(op.GetAllowedMethods()), MaxEntriesPerTARList)+ }+ for _, m := range op.GetAllowedMethods() {+ if !httpMethodSyntax.MatchString(m) {+ return fmt.Errorf("rule[%d]: method %q must be an uppercase HTTP method such as \"GET\"", idx, m)+ }+ }+ if len(op.GetAllowedPaths()) > MaxEntriesPerTARList {+ return fmt.Errorf("rule[%d]: allowed_paths count %d exceeds max %d", idx, len(op.GetAllowedPaths()), MaxEntriesPerTARList)+ }+ for _, p := range op.GetAllowedPaths() {+ if len(p) > MaxTARNameLength {+ return fmt.Errorf("rule[%d]: path %q exceeds max length %d", idx, p, MaxTARNameLength)+ }+ if err := validateHTTPGrantPath(p); err != nil {+ return fmt.Errorf("rule[%d]: %w", idx, err)+ }+ }+ if len(op.GetAllowedPermissions()) > MaxEntriesPerTARList {+ return fmt.Errorf("rule[%d]: allowed_permissions count %d exceeds max %d", idx, len(op.GetAllowedPermissions()), MaxEntriesPerTARList)+ }+ for _, perm := range op.GetAllowedPermissions() {+ if perm == "" || len(perm) > MaxTARNameLength || strings.ContainsAny(perm, " \t\r\n") {+ return fmt.Errorf("rule[%d]: invalid permission %q in allowed_permissions", idx, perm)+ }+ }+ return nil+}++// EncodeTARBlockPayload validates and serializes a TaskAuthorizationRule into+// its canonical unpadded base64url string representation.+func EncodeTARBlockPayload(rule *TaskAuthorizationRule) (string, error) {+ if err := ValidateTaskAuthorizationRule(rule); err != nil {+ return "", err+ }+ if len(rule.GetRules()) == 0 {+ return "", fmt.Errorf("task authorization rule must contain at least one rule when attenuating")+ }+ raw, err := proto.MarshalOptions{Deterministic: true}.Marshal(rule)+ if err != nil {+ return "", fmt.Errorf("marshal task authorization rule: %w", err)+ }+ if len(raw) == 0 || len(raw) > MaxTARBytes {+ return "", fmt.Errorf("serialized task authorization rule size %d out of range [1, %d]", len(raw), MaxTARBytes)+ }+ return base64.RawURLEncoding.EncodeToString(raw), nil+}++// EncodeTARBlockFact validates a TaskAuthorizationRule and returns the single+// tar_block("<base64url>") Datalog fact to append in a Biscuit block.+func EncodeTARBlockFact(rule *TaskAuthorizationRule) (biscuit.Fact, error) {+ encoded, err := EncodeTARBlockPayload(rule)+ if err != nil {+ return biscuit.Fact{}, err+ }+ return biscuit.Fact{+ Predicate: biscuit.Predicate{+ Name: FactTARBlock,+ IDs: []biscuit.Term{biscuit.String(encoded)},+ },+ }, nil+}++// DecodeTARBlockPayload decodes an unpadded base64url string into a validated+// TaskAuthorizationRule, rejecting oversized payloads and unknown wire fields.+func DecodeTARBlockPayload(b64 string) (*TaskAuthorizationRule, error) {+ if b64 == "" {+ return nil, fmt.Errorf("empty tar_block payload")+ }+ raw, err := base64.RawURLEncoding.DecodeString(b64)+ if err != nil {+ return nil, fmt.Errorf("invalid base64url in tar_block: %w", err)+ }+ if len(raw) == 0 || len(raw) > MaxTARBytes {+ return nil, fmt.Errorf("tar_block protobuf size %d out of range [1, %d]", len(raw), MaxTARBytes)+ }+ var rule TaskAuthorizationRule+ if err := proto.Unmarshal(raw, &rule); err != nil {+ return nil, fmt.Errorf("unmarshal tar_block protobuf: %w", err)+ }+ if len(rule.ProtoReflect().GetUnknown()) > 0 {+ return nil, fmt.Errorf("tar_block protobuf contains unknown fields")+ }+ if err := ValidateTaskAuthorizationRule(&rule); err != nil {+ return nil, fmt.Errorf("invalid tar_block: %w", err)+ }+ return &rule, nil+}++// ParseTARBlockSource validates that a Biscuit block's Datalog source text+// contains solely a single tar_block("<base64url>") fact (with optional+// trailing semicolon and whitespace) and decodes its TaskAuthorizationRule.+func ParseTARBlockSource(blockSource string) (*TaskAuthorizationRule, error) {+ m := TARBlockSourceRegex.FindStringSubmatch(strings.TrimSpace(blockSource))+ if len(m) != 2 {+ return nil, fmt.Errorf("appended block must contain solely a single tar_block(\"<base64url>\") fact")+ }+ return DecodeTARBlockPayload(m[1])+}++// MatchServicePattern reports whether a service pattern from+// TaskRule.allowed_services matches the target (reqType, reqName) using the+// exact same dot-anchored semantics as BuildServiceDatalogFact and+// BaselineSources.Rules:+// - "*" matches every non-empty (reqType, reqName)+// - "<type>://*" matches every non-empty reqName of <type>+// - "<type>://*.<suffix>" matches reqName ending with ".<suffix>"+// - "<type>://<prefix>.*" matches reqName starting with "<prefix>."+// - "<type>://<exact>" matches reqName == "<exact>"+func MatchServicePattern(pattern, reqType, reqName string) bool {+ if reqType == "" || reqName == "" || pattern == "" {+ return false+ }+ if pattern == "*" {+ return true+ }+ pType, pName := ParseServiceTarget(pattern)+ if pType == "" || pType != reqType || pName == "" {+ return false+ }+ if pName == "*" {+ return true+ }+ if strings.HasPrefix(pName, "*.") && !strings.HasSuffix(pName, ".*") {+ return strings.HasSuffix(reqName, pName[1:])+ }+ if strings.HasSuffix(pName, ".*") && !strings.HasPrefix(pName, "*.") {+ return strings.HasPrefix(reqName, pName[:len(pName)-1])+ }+ return reqName == pName+}++// MatchHTTPPath reports whether a path pattern from TaskOperation.allowed_paths+// ("/exact" or "/prefix/*") matches reqPath using the same semantics as+// BuildHTTPGrantFacts and BaselineSources.HTTPRules.+func MatchHTTPPath(pattern, reqPath string) bool {+ if pattern == "" || reqPath == "" {+ return false+ }+ if strings.HasSuffix(pattern, "*") {+ return strings.HasPrefix(reqPath, strings.TrimSuffix(pattern, "*"))+ }+ return reqPath == pattern+}++// TaskRequestContext carries the wire attributes of a request evaluated+// against a chain of TaskAuthorizationRules.+type TaskRequestContext struct {+ ServiceType string+ ServiceName string++ // HasHTTP is true when the verifier handles the request as HTTP with+ // Method and Path taken from the wire. A CONNECT tunnel carries+ // Method == "CONNECT" and Path == "".+ HasHTTP bool+ Method string+ Path string++ // MCPTool is the tool name from params.name on an MCP tools/call request.+ MCPTool string++ // AllowMCPStreamInit permits an MCP session handshake (before tools/call)+ // to satisfy a rule whose only operation restriction is allowed_tools.+ // Every subsequent tools/call on the stream is evaluated with+ // AllowMCPStreamInit false and MCPTool set to params.name.+ AllowMCPStreamInit bool+}++// MatchTaskRule reports whether a single TaskRule permits req.+//+// Fail-closed semantics:+// - allowed_services must have at least one entry matching (ServiceType, ServiceName).+// - If operation.allowed_tools is non-empty, ServiceType must be "mcp" and+// MCPTool must be in allowed_tools (unless AllowMCPStreamInit is true and+// MCPTool is empty during stream setup).+// - If operation.allowed_methods or operation.allowed_paths is non-empty,+// the request must carry HTTP facts (HasHTTP && Method != "" &&+// Method != "CONNECT" && Path != ""), and every non-empty axis must match.+// - operation.allowed_permissions and rule.allowed_resources are opaque to+// the wire PEP and consumed by CloudTokenExchanger at egress.+func MatchTaskRule(rule *TaskRule, req TaskRequestContext) bool {+ if rule == nil {+ return false+ }+ svcMatched := false+ for _, pattern := range rule.GetAllowedServices() {+ if MatchServicePattern(pattern, req.ServiceType, req.ServiceName) {+ svcMatched = true+ break+ }+ }+ if !svcMatched {+ return false+ }++ op := rule.GetOperation()+ if op == nil {+ return true+ }++ if tools := op.GetAllowedTools(); len(tools) > 0 {+ if req.ServiceType != "mcp" {+ return false+ }+ if req.MCPTool == "" {+ if !req.AllowMCPStreamInit {+ return false+ }+ } else if !slices.Contains(tools, req.MCPTool) {+ return false+ }+ }++ methods := op.GetAllowedMethods()+ paths := op.GetAllowedPaths()+ if len(methods) > 0 || len(paths) > 0 {+ if !req.HasHTTP || req.Method == "" || req.Method == "CONNECT" || req.Path == "" {+ return false+ }+ if len(methods) > 0 && !slices.Contains(methods, req.Method) {+ return false+ }+ if len(paths) > 0 {+ pathMatched := false+ for _, p := range paths {+ if MatchHTTPPath(p, req.Path) {+ pathMatched = true+ break+ }+ }+ if !pathMatched {+ return false+ }+ }+ }++ return true+}++// EvaluateTaskRules enforces the intersection of all appended+// TaskAuthorizationRule blocks in a Biscuit token:+// - For each block, if expire_time is set and now > expire_time, the token+// is rejected.+// - For each block, at least one TaskRule in block.rules must match req; if+// block.rules is empty or no rule matches, the request is denied.+func EvaluateTaskRules(blocks []*TaskAuthorizationRule, req TaskRequestContext, 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 MatchTaskRule(r, req) {+ matched = true+ break+ }+ }+ if !matched {+ return fmt.Errorf("tar_block[%d] (%q) denied request to %s://%s", i+1, block.GetName(), req.ServiceType, req.ServiceName)+ }+ }+ return nil+}++// EffectiveTARExpiration returns the earliest expiration time across the+// authority block's expiration and every appended TaskAuthorizationRule's+// expire_time.+func EffectiveTARExpiration(authorityExp time.Time, blocks []*TaskAuthorizationRule) time.Time {+ effective := authorityExp+ for _, block := range blocks {+ if block == nil || block.GetExpireTime() == nil || !block.GetExpireTime().IsValid() {+ continue+ }+ t := block.GetExpireTime().AsTime()+ if effective.IsZero() || t.Before(effective) {+ effective = t+ }+ }+ return effective+}diff --git a/api/tar_test.go b/api/tar_test.gonew file mode 100644index 00000000..177f3fbd--- /dev/null+++ b/api/tar_test.go@@ -0,0 +1,384 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package api++import (+ "encoding/base64"+ "strings"+ "testing"+ "time"++ "google.golang.org/protobuf/encoding/protowire"+ "google.golang.org/protobuf/proto"+ "google.golang.org/protobuf/types/known/timestamppb"+)++func TestValidateTaskAuthorizationRule(t *testing.T) {+ validExp := timestamppb.New(time.Date(2026, 10, 3, 15, 0, 0, 0, time.UTC))++ tests := []struct {+ name string+ rule *TaskAuthorizationRule+ wantErr bool+ }{+ {+ name: "nil rule",+ rule: nil,+ wantErr: true,+ },+ {+ name: "valid minimal rule",+ rule: &TaskAuthorizationRule{+ Name: "bq-read",+ DisplayName: "BigQuery Read Task",+ ExpireTime: validExp,+ Rules: []*TaskRule{+ {+ AllowedServices: []string{"mcp://bigquery", "inference://gemini.*", "egress://*.googleapis.com"},+ Operation: &TaskOperation{+ AllowedTools: []string{"execute_sql"},+ AllowedMethods: []string{"GET", "POST"},+ AllowedPaths: []string{"/v1/projects/*", "/healthz"},+ AllowedPermissions: []string{"bigquery.jobs.create"},+ },+ AllowedResources: []string{"//bigquery.googleapis.com/projects/p1/datasets/d1"},+ },+ },+ },+ wantErr: false,+ },+ {+ name: "empty rules list is structurally valid (fails closed at evaluation)",+ rule: &TaskAuthorizationRule{+ Name: "deny-all",+ },+ wantErr: false,+ },+ {+ name: "name too long",+ rule: &TaskAuthorizationRule{+ Name: strings.Repeat("a", MaxTARNameLength+1),+ },+ wantErr: true,+ },+ {+ name: "too many rules",+ rule: &TaskAuthorizationRule{+ Rules: make([]*TaskRule, MaxRulesPerTAR+1),+ },+ wantErr: true,+ },+ {+ name: "rule with empty allowed_services",+ rule: &TaskAuthorizationRule{+ Rules: []*TaskRule{{}},+ },+ wantErr: true,+ },+ {+ name: "service with path segment rejected",+ rule: &TaskAuthorizationRule{+ Rules: []*TaskRule{{+ AllowedServices: []string{"egress://api.github.com/repos"},+ }},+ },+ wantErr: true,+ },+ {+ name: "service with two wildcards rejected",+ rule: &TaskAuthorizationRule{+ Rules: []*TaskRule{{+ AllowedServices: []string{"mcp://*.example.*"},+ }},+ },+ wantErr: true,+ },+ {+ name: "invalid lowercase HTTP method rejected",+ rule: &TaskAuthorizationRule{+ Rules: []*TaskRule{{+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &TaskOperation{AllowedMethods: []string{"get"}},+ }},+ },+ wantErr: true,+ },+ {+ name: "invalid HTTP path with dot segment rejected",+ rule: &TaskAuthorizationRule{+ Rules: []*TaskRule{{+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &TaskOperation{AllowedPaths: []string{"/repos/../secret"}},+ }},+ },+ wantErr: true,+ },+ {+ name: "invalid HTTP path with middle wildcard rejected",+ rule: &TaskAuthorizationRule{+ Rules: []*TaskRule{{+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &TaskOperation{AllowedPaths: []string{"/repos/*/issues"}},+ }},+ },+ wantErr: true,+ },+ {+ name: "invalid tool name with slash rejected",+ rule: &TaskAuthorizationRule{+ Rules: []*TaskRule{{+ AllowedServices: []string{"mcp://calc"},+ Operation: &TaskOperation{AllowedTools: []string{"mcp://calc/add"}},+ }},+ },+ wantErr: true,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ err := ValidateTaskAuthorizationRule(tc.rule)+ if (err != nil) != tc.wantErr {+ t.Fatalf("ValidateTaskAuthorizationRule() error = %v, wantErr %v", err, tc.wantErr)+ }+ })+ }+}++func TestEncodeAndDecodeTARBlock(t *testing.T) {+ exp := time.Date(2026, 10, 3, 16, 0, 0, 0, time.UTC)+ orig := &TaskAuthorizationRule{+ Name: "weather-lookup",+ DisplayName: "Weather Lookup Task",+ ExpireTime: timestamppb.New(exp),+ Rules: []*TaskRule{+ {+ Description: "Allow get_weather on weather MCP",+ AllowedServices: []string{"mcp://weather"},+ Operation: &TaskOperation{+ AllowedTools: []string{"get_weather"},+ },+ },+ },+ }++ fact, err := EncodeTARBlockFact(orig)+ if err != nil {+ t.Fatalf("EncodeTARBlockFact() unexpected error: %v", err)+ }+ parsed, err := ParseTARBlockSource(fact.String())+ if err != nil {+ t.Fatalf("ParseTARBlockSource(%q) unexpected error: %v", fact.String(), err)+ }+ if !proto.Equal(orig, parsed) {+ t.Fatalf("round-trip mismatch: got %v, want %v", parsed, orig)+ }++ // Empty rules must be rejected when encoding for attenuation.+ if _, err := EncodeTARBlockFact(&TaskAuthorizationRule{Name: "empty"}); err == nil {+ t.Fatal("expected EncodeTARBlockFact to reject empty rules")+ }++ // Unknown protobuf wire field must be rejected when decoding.+ raw, err := proto.Marshal(orig)+ if err != nil {+ t.Fatal(err)+ }+ withUnknown := protowire.AppendTag(raw, 99, protowire.VarintType)+ withUnknown = protowire.AppendVarint(withUnknown, 1)+ b64Unknown := base64.RawURLEncoding.EncodeToString(withUnknown)+ if _, err := DecodeTARBlockPayload(b64Unknown); err == nil {+ t.Fatal("expected DecodeTARBlockPayload to reject unknown protobuf fields")+ }++ // Padded base64 or non-tar_block source must be rejected.+ if _, err := ParseTARBlockSource(`node("attacker")`); err == nil {+ t.Fatal("expected ParseTARBlockSource to reject non-tar_block predicate")+ }+ if _, err := ParseTARBlockSource(`tar_block("abc=");`); err == nil {+ t.Fatal("expected ParseTARBlockSource to reject padded base64")+ }+}++func TestMatchServicePattern(t *testing.T) {+ tests := []struct {+ pattern string+ reqType string+ reqName string+ want bool+ }{+ {"*", "mcp", "calculator", true},+ {"*", "egress", "api.github.com", true},+ {"mcp://*", "mcp", "calculator", true},+ {"mcp://*", "inference", "calculator", false},+ {"mcp://calculator", "mcp", "calculator", true},+ {"mcp://calculator", "mcp", "other", false},+ {"egress://*.googleapis.com", "egress", "bigquery.googleapis.com", true},+ {"egress://*.googleapis.com", "egress", "googleapis.com", false},+ {"egress://*.googleapis.com", "egress", "evilgoogleapis.com", false},+ {"inference://gemini.*", "inference", "gemini.pro", true},+ {"inference://gemini.*", "inference", "gemini", false},+ {"inference://gemini.*", "inference", "gemini2.pro", false},+ }++ for _, tc := range tests {+ got := MatchServicePattern(tc.pattern, tc.reqType, tc.reqName)+ if got != tc.want {+ t.Errorf("MatchServicePattern(%q, %q, %q) = %v, want %v", tc.pattern, tc.reqType, tc.reqName, got, tc.want)+ }+ }+}++func TestEvaluateTaskRulesIntersection(t *testing.T) {+ now := time.Date(2026, 10, 3, 12, 0, 0, 0, time.UTC)+ future := timestamppb.New(now.Add(10 * time.Minute))+ past := timestamppb.New(now.Add(-1 * time.Minute))++ // Hop 1 (Orchestrator): allows mcp://weather (get_weather, get_forecast) and egress://api.github.com (GET, POST /repos/acme/*)+ hop1 := &TaskAuthorizationRule{+ Name: "orchestrator-scope",+ DisplayName: "Orchestrator Task",+ ExpireTime: future,+ Rules: []*TaskRule{+ {+ AllowedServices: []string{"mcp://weather"},+ Operation: &TaskOperation{AllowedTools: []string{"get_weather", "get_forecast"}},+ },+ {+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &TaskOperation{+ AllowedMethods: []string{"GET", "POST"},+ AllowedPaths: []string{"/repos/acme/*"},+ },+ },+ },+ }++ // Hop 2 (Sub-agent): narrows to mcp://weather (get_weather only) and egress://api.github.com (GET /repos/acme/public/*)+ hop2 := &TaskAuthorizationRule{+ Name: "subagent-scope",+ DisplayName: "Subagent Task",+ ExpireTime: future,+ Rules: []*TaskRule{+ {+ AllowedServices: []string{"mcp://weather"},+ Operation: &TaskOperation{AllowedTools: []string{"get_weather"}},+ },+ {+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &TaskOperation{+ AllowedMethods: []string{"GET"},+ AllowedPaths: []string{"/repos/acme/public/*"},+ },+ },+ },+ }++ chain := []*TaskAuthorizationRule{hop1, hop2}++ cases := []struct {+ name string+ req TaskRequestContext+ wantErr bool+ }{+ {+ name: "MCP tool in intersection allowed",+ req: TaskRequestContext{ServiceType: "mcp", ServiceName: "weather", MCPTool: "get_weather"},+ wantErr: false,+ },+ {+ name: "MCP stream handshake allowed before tools/call",+ req: TaskRequestContext{ServiceType: "mcp", ServiceName: "weather", AllowMCPStreamInit: true},+ wantErr: false,+ },+ {+ name: "MCP request without tool name denied when AllowMCPStreamInit is false",+ req: TaskRequestContext{ServiceType: "mcp", ServiceName: "weather"},+ wantErr: true,+ },+ {+ name: "MCP tool dropped in hop 2 denied",+ req: TaskRequestContext{ServiceType: "mcp", ServiceName: "weather", MCPTool: "get_forecast"},+ wantErr: true,+ },+ {+ name: "HTTP GET under narrowed prefix allowed",+ req: TaskRequestContext{ServiceType: "egress", ServiceName: "api.github.com", HasHTTP: true, Method: "GET", Path: "/repos/acme/public/readme"},+ wantErr: false,+ },+ {+ name: "HTTP POST dropped in hop 2 denied",+ req: TaskRequestContext{ServiceType: "egress", ServiceName: "api.github.com", HasHTTP: true, Method: "POST", Path: "/repos/acme/public/readme"},+ wantErr: true,+ },+ {+ name: "HTTP path outside hop 2 prefix denied",+ req: TaskRequestContext{ServiceType: "egress", ServiceName: "api.github.com", HasHTTP: true, Method: "GET", Path: "/repos/acme/private/secret"},+ wantErr: true,+ },+ {+ name: "CONNECT tunnel on HTTP-narrowed rule denied",+ req: TaskRequestContext{ServiceType: "egress", ServiceName: "api.github.com", HasHTTP: true, Method: "CONNECT", Path: ""},+ wantErr: true,+ },+ {+ name: "Non-HTTP request on HTTP-narrowed rule denied",+ req: TaskRequestContext{ServiceType: "egress", ServiceName: "api.github.com", HasHTTP: false},+ wantErr: true,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ err := EvaluateTaskRules(chain, tc.req, now)+ if (err != nil) != tc.wantErr {+ t.Fatalf("EvaluateTaskRules() error = %v, wantErr %v", err, tc.wantErr)+ }+ })+ }++ // Expired TAR block must be rejected even if the rule matches.+ expiredChain := []*TaskAuthorizationRule{+ {+ Name: "expired-hop",+ ExpireTime: past,+ Rules: []*TaskRule{{AllowedServices: []string{"*"}}},+ },+ }+ if err := EvaluateTaskRules(expiredChain, TaskRequestContext{ServiceType: "mcp", ServiceName: "weather", MCPTool: "get_weather"}, now); err == nil {+ t.Fatal("expected expired TAR block to be rejected")+ }++ // Empty rules TAR block must deny all requests.+ emptyRulesChain := []*TaskAuthorizationRule{{Name: "empty-rules"}}+ if err := EvaluateTaskRules(emptyRulesChain, TaskRequestContext{ServiceType: "mcp", ServiceName: "weather"}, now); err == nil {+ t.Fatal("expected TAR block with empty rules to deny request")+ }+}++func TestEffectiveTARExpiration(t *testing.T) {+ base := time.Date(2026, 10, 3, 12, 0, 0, 0, time.UTC)+ authExp := base.Add(1 * time.Hour)+ hop1Exp := base.Add(30 * time.Minute)+ hop2Exp := base.Add(15 * time.Minute)++ blocks := []*TaskAuthorizationRule{+ {ExpireTime: timestamppb.New(hop1Exp)},+ {ExpireTime: timestamppb.New(hop2Exp)},+ }+ if got := EffectiveTARExpiration(authExp, blocks); !got.Equal(hop2Exp) {+ t.Fatalf("EffectiveTARExpiration() = %v, want %v", got, hop2Exp)+ }+}diff --git a/hack/gen-sdk-datalog/main.go b/hack/gen-sdk-datalog/main.goindex dd3ca1fb..ba729a38 100644--- a/hack/gen-sdk-datalog/main.go+++ b/hack/gen-sdk-datalog/main.go@@ -13,56 +13,584 @@// limitations under the License.// Command gen-sdk-datalog writes the baseline Datalog a mesh member evaluates-// when it authorizes a caller, as api/datalog.go defines it, into the JSON-// artifact the native SDKs embed. Go stays the source of truth;-// hack/verify-sdk-generated.sh fails when the artifact is stale.+// when it authorizes a caller, as api/datalog.go and api/tar.go define it,+// into the JSON/TS artifacts the native SDKs embed, and generates the+// deterministic cross-language TAR conformance vectors in+// sdk/testdata/tar_conformance.json. Go stays the source of truth;+// hack/verify-sdk-generated.sh fails when the artifacts are stale.package mainimport ("bytes"+ "crypto/ed25519"+ "crypto/sha256"+ "encoding/base64"+ "encoding/binary""encoding/json""fmt"+ "io""os"+ "path/filepath""strings"+ "time"+ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/biscuit-auth/biscuit-go/v2/parser""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 artifact struct {Comment string `json:"_comment"`api.DatalogSources- FactService string `json:"fact_service"`- FactConnectionPeer string `json:"fact_connection_peer_id"`- FactMethod string `json:"fact_method"`- FactPath string `json:"fact_path"`- FactTime string `json:"fact_time"`- FactRole string `json:"fact_role"`- FactTargetFact string `json:"fact_target_fact"`- MarkerTerm string `json:"marker_term"`- SystemNamespace string `json:"system_namespace"`- BindingPrefixes []string `json:"binding_member_prefixes"`- SystemAuthenticated string `json:"system_authenticated_member"`+ FactService string `json:"fact_service"`+ FactConnectionPeer string `json:"fact_connection_peer_id"`+ FactMethod string `json:"fact_method"`+ FactPath string `json:"fact_path"`+ FactTime string `json:"fact_time"`+ FactRole string `json:"fact_role"`+ FactTargetFact string `json:"fact_target_fact"`+ FactTARBlock string `json:"fact_tar_block"`+ TARBlockSourcePattern string `json:"tar_block_source_pattern"`+ HTTPMethodSyntax string `json:"http_method_syntax"`+ MaxAttenuationBlocks int `json:"max_attenuation_blocks"`+ MaxTARBytes int `json:"max_tar_bytes"`+ MaxRulesPerTAR int `json:"max_rules_per_tar"`+ MaxEntriesPerTARList int `json:"max_entries_per_tar_list"`+ MaxTARNameLength int `json:"max_tar_name_length"`+ MaxTARDescriptionLength int `json:"max_tar_description_length"`+ MaxTARResourceLength int `json:"max_tar_resource_length"`+ MarkerTerm string `json:"marker_term"`+ SystemNamespace string `json:"system_namespace"`+ BindingPrefixes []string `json:"binding_member_prefixes"`+ SystemAuthenticated string `json:"system_authenticated_member"`+}++type tarConformanceSuite struct {+ Comment string `json:"_comment"`+ PublicKeyB64 string `json:"public_key_b64"`+ CallerPeerID string `json:"caller_peer_id"`+ ProviderPeerID string `json:"provider_peer_id"`+ ProviderBiscuitB64 string `json:"provider_biscuit_b64"`+ EvaluationTime string `json:"evaluation_time"`+ PolicyDatalogRules []string `json:"policy_datalog_rules"`+ Vectors []tarConformanceVector `json:"vectors"`+}++type tarConformanceVector struct {+ Name string `json:"name"`+ BiscuitB64 string `json:"biscuit_b64"`+ TargetService string `json:"target_service"`+ Protocol string `json:"protocol"`+ Method *string `json:"method,omitempty"`+ Path string `json:"path,omitempty"`+ MCPTool string `json:"mcp_tool,omitempty"`+ Allow bool `json:"allow"`+ ExpectedEffectiveExpiration string `json:"expected_effective_expiration,omitempty"`+}++// deterministicReader is a reproducible stream of bytes derived from SHA-256+// blocks so Biscuit keypair generation and sealing are 100% deterministic.+type deterministicReader struct {+ seed string+ counter uint64+ buf []byte+}++func newDeterministicReader(seed string) io.Reader {+ return &deterministicReader{seed: seed}+}++func (d *deterministicReader) Read(p []byte) (int, error) {+ written := 0+ for written < len(p) {+ if len(d.buf) == 0 {+ var ctr [8]byte+ binary.LittleEndian.PutUint64(ctr[:], d.counter)+ d.counter+++ h := sha256.New()+ h.Write([]byte(d.seed))+ h.Write(ctr[:])+ d.buf = h.Sum(nil)+ }+ n := copy(p[written:], d.buf)+ d.buf = d.buf[n:]+ written += n+ }+ return written, nil+}++func deterministicPeerID(seed string) peer.ID {+ sum := sha256.Sum256([]byte(seed))+ priv := ed25519.NewKeyFromSeed(sum[:])+ libp2pPriv, err := crypto.UnmarshalEd25519PrivateKey(priv)+ if err != nil {+ panic(err)+ }+ pid, err := peer.IDFromPrivateKey(libp2pPriv)+ if err != nil {+ panic(err)+ }+ return pid+}++func strPtr(s string) *string { return &s }++func buildConformanceSuite() tarConformanceSuite {+ cpSeed := sha256.Sum256([]byte("sam-tar-conformance-cp-root-key-v1"))+ cpPriv := ed25519.NewKeyFromSeed(cpSeed[:])+ cpPub := cpPriv.Public().(ed25519.PublicKey)++ callerPeer := deterministicPeerID("sam-tar-conformance-caller-peer-v1")+ providerPeer := deterministicPeerID("sam-tar-conformance-provider-peer-v1")++ evalTime := time.Date(2026, 10, 3, 12, 0, 0, 0, time.UTC)+ authExp := time.Date(2035, 1, 1, 0, 0, 0, 0, time.UTC)+ hop1Exp := time.Date(2034, 6, 1, 0, 0, 0, 0, time.UTC)+ hop2Exp := time.Date(2034, 3, 1, 0, 0, 0, 0, time.UTC)+ expiredExp := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)++ // Mint provider Biscuit.+ provBuilder := biscuit.NewBuilder(cpPriv, biscuit.WithRandom(newDeterministicReader("provider-root")))+ for _, f := range []biscuit.Fact{+ {Predicate: biscuit.Predicate{Name: api.FactNode, IDs: []biscuit.Term{biscuit.String(providerPeer.String())}}},+ {Predicate: biscuit.Predicate{Name: api.FactClientPeerID, IDs: []biscuit.Term{biscuit.String(providerPeer.String())}}},+ {Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(authExp)}}},+ {Predicate: biscuit.Predicate{Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleNode)}}},+ } {+ if err := provBuilder.AddAuthorityFact(f); err != nil {+ panic(err)+ }+ }+ provToken, err := provBuilder.Build()+ if err != nil {+ panic(err)+ }+ provBytes, err := provToken.Serialize()+ if err != nil {+ panic(err)+ }++ // Mint caller authority Biscuit with wildcard service and target grants.+ callerBuilder := biscuit.NewBuilder(cpPriv, biscuit.WithRandom(newDeterministicReader("caller-root")))+ for _, f := range []biscuit.Fact{+ {Predicate: biscuit.Predicate{Name: api.FactNode, IDs: []biscuit.Term{biscuit.String(callerPeer.String())}}},+ {Predicate: biscuit.Predicate{Name: api.FactClientPeerID, IDs: []biscuit.Term{biscuit.String(callerPeer.String())}}},+ {Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(authExp)}}},+ {Predicate: biscuit.Predicate{Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleNode)}}},+ api.MarkerFact(api.FactGrantedServiceAllTypes),+ api.MarkerFact(api.FactTargetUnrestricted),+ } {+ if err := callerBuilder.AddAuthorityFact(f); err != nil {+ panic(err)+ }+ }+ callerRoot, err := callerBuilder.Build()+ if err != nil {+ panic(err)+ }+ callerRootBytes, err := callerRoot.Serialize()+ if err != nil {+ panic(err)+ }++ hop1 := &api.TaskAuthorizationRule{+ Name: "orchestrator-hop",+ DisplayName: "Orchestrator Task Scope",+ ExpireTime: timestamppb.New(hop1Exp),+ Rules: []*api.TaskRule{+ {+ Description: "Weather MCP tools",+ AllowedServices: []string{"mcp://weather"},+ Operation: &api.TaskOperation{+ AllowedTools: []string{"get_weather", "get_forecast"},+ },+ },+ {+ Description: "GitHub API read/write under /repos/acme/*",+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &api.TaskOperation{+ AllowedMethods: []string{"GET", "POST"},+ AllowedPaths: []string{"/repos/acme/*"},+ },+ },+ {+ Description: "Gemini inference prefix",+ AllowedServices: []string{"inference://gemini.*"},+ },+ },+ }+ att1Bytes, err := identity.AttenuateBiscuitWithRand(newDeterministicReader("hop1"), callerRootBytes, hop1)+ if err != nil {+ panic(err)+ }++ hop2 := &api.TaskAuthorizationRule{+ Name: "subagent-hop",+ DisplayName: "Subagent Narrowed Scope",+ ExpireTime: timestamppb.New(hop2Exp),+ Rules: []*api.TaskRule{+ {+ AllowedServices: []string{"mcp://weather"},+ Operation: &api.TaskOperation{+ AllowedTools: []string{"get_weather"},+ },+ },+ {+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &api.TaskOperation{+ AllowedMethods: []string{"GET"},+ AllowedPaths: []string{"/repos/acme/public/*"},+ },+ },+ },+ }+ att2Bytes, err := identity.AttenuateBiscuitWithRand(newDeterministicReader("hop2"), att1Bytes, hop2)+ if err != nil {+ panic(err)+ }+ sealedAtt2Bytes, err := identity.SealBiscuitWithRand(newDeterministicReader("seal-hop2"), att2Bytes)+ if err != nil {+ panic(err)+ }++ expiredRule := &api.TaskAuthorizationRule{+ Name: "expired-hop",+ ExpireTime: timestamppb.New(expiredExp),+ Rules: []*api.TaskRule{{AllowedServices: []string{"*"}}},+ }+ expiredBytes, err := identity.AttenuateBiscuitWithRand(newDeterministicReader("expired"), callerRootBytes, expiredRule)+ if err != nil {+ panic(err)+ }++ // Empty rules TAR block (valid protobuf, 0 rules -> fail-closed deny).+ emptyTARRaw, err := proto.MarshalOptions{Deterministic: true}.Marshal(&api.TaskAuthorizationRule{Name: "empty-rules"})+ if err != nil {+ panic(err)+ }+ emptyTARFact := biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactTARBlock,+ IDs: []biscuit.Term{biscuit.String(base64.RawURLEncoding.EncodeToString(emptyTARRaw))},+ }}+ bbEmpty := callerRoot.CreateBlock()+ _ = bbEmpty.AddFact(emptyTARFact)+ bEmpty, err := callerRoot.Append(newDeterministicReader("empty-rules"), bbEmpty.Build())+ if err != nil {+ panic(err)+ }+ emptyRulesBytes, _ := bEmpty.Serialize()++ // 9 blocks (> MaxAttenuationBlocks).+ cur9 := callerRootBytes+ for i := 0; i < api.MaxAttenuationBlocks; i++ {+ cur9, err = identity.AttenuateBiscuitWithRand(newDeterministicReader(fmt.Sprintf("b9-%d", i)), cur9, hop1)+ if err != nil {+ panic(err)+ }+ }+ b8, _ := biscuit.Unmarshal(cur9)+ validFact, _ := api.EncodeTARBlockFact(hop1)+ bb9 := b8.CreateBlock()+ _ = bb9.AddFact(validFact)+ b9, _ := b8.Append(newDeterministicReader("b9-9"), bb9.Build())+ nineBlocksBytes, _ := b9.Serialize()++ // Block with rule.+ bbRule := callerRoot.CreateBlock()+ _ = bbRule.AddFact(validFact)+ r, _ := parser.FromStringRule(`x($a) <- tar_block($a)`)+ _ = bbRule.AddRule(r)+ bWithRule, _ := callerRoot.Append(newDeterministicReader("with-rule"), bbRule.Build())+ withRuleBytes, _ := bWithRule.Serialize()++ // Block with check.+ bbCheck := callerRoot.CreateBlock()+ _ = bbCheck.AddFact(validFact)+ chk, _ := parser.FromStringCheck(`check if tar_block($a)`)+ _ = bbCheck.AddCheck(chk)+ bWithCheck, _ := callerRoot.Append(newDeterministicReader("with-check"), bbCheck.Build())+ withCheckBytes, _ := bWithCheck.Serialize()++ // Block with two facts.+ bbTwoFacts := callerRoot.CreateBlock()+ _ = bbTwoFacts.AddFact(validFact)+ _ = bbTwoFacts.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactTARBlock,+ IDs: []biscuit.Term{biscuit.String("extra")},+ }})+ bTwoFacts, _ := callerRoot.Append(newDeterministicReader("two-facts"), bbTwoFacts.Build())+ twoFactsBytes, _ := bTwoFacts.Serialize()++ // Block with wrong predicate name (e.g. node("attacker")).+ bbWrongPred := callerRoot.CreateBlock()+ _ = bbWrongPred.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactNode,+ IDs: []biscuit.Term{biscuit.String(providerPeer.String())},+ }})+ bWrongPred, _ := callerRoot.Append(newDeterministicReader("wrong-pred"), bbWrongPred.Build())+ wrongPredBytes, _ := bWrongPred.Serialize()++ // Block with bytes term instead of string.+ bbBytesTerm := callerRoot.CreateBlock()+ _ = bbBytesTerm.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactTARBlock,+ IDs: []biscuit.Term{biscuit.Bytes([]byte{1, 2, 3})},+ }})+ bBytesTerm, _ := callerRoot.Append(newDeterministicReader("bytes-term"), bbBytesTerm.Build())+ bytesTermBytes, _ := bBytesTerm.Serialize()++ // Block with unknown protobuf wire field in tar_block.+ hop1Raw, _ := proto.MarshalOptions{Deterministic: true}.Marshal(hop1)+ unknownRaw := protowire.AppendTag(hop1Raw, 99, protowire.VarintType)+ unknownRaw = protowire.AppendVarint(unknownRaw, 1)+ bbUnknownProto := callerRoot.CreateBlock()+ _ = bbUnknownProto.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactTARBlock,+ IDs: []biscuit.Term{biscuit.String(base64.RawURLEncoding.EncodeToString(unknownRaw))},+ }})+ bUnknownProto, _ := callerRoot.Append(newDeterministicReader("unknown-proto"), bbUnknownProto.Build())+ unknownProtoBytes, _ := bUnknownProto.Serialize()++ b64 := base64.StdEncoding.EncodeToString++ return tarConformanceSuite{+ Comment: "Generated by hack/gen-sdk-datalog; do not edit.",+ PublicKeyB64: b64(cpPub),+ CallerPeerID: callerPeer.String(),+ ProviderPeerID: providerPeer.String(),+ ProviderBiscuitB64: b64(provBytes),+ EvaluationTime: evalTime.Format(time.RFC3339),+ PolicyDatalogRules: []string{},+ Vectors: []tarConformanceVector{+ {+ Name: "authority_only_allowed",+ BiscuitB64: b64(callerRootBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "any_tool",+ Allow: true,+ ExpectedEffectiveExpiration: authExp.Format(time.RFC3339),+ },+ {+ Name: "one_hop_mcp_allowed_tool",+ BiscuitB64: b64(att1Bytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_forecast",+ Allow: true,+ ExpectedEffectiveExpiration: hop1Exp.Format(time.RFC3339),+ },+ {+ Name: "one_hop_mcp_denied_tool",+ BiscuitB64: b64(att1Bytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "drop_table",+ Allow: false,+ },+ {+ Name: "one_hop_mcp_missing_tool_denied_on_http",+ BiscuitB64: b64(att1Bytes),+ TargetService: "mcp://weather",+ Protocol: "/libp2p-http",+ Method: strPtr("POST"),+ Path: "/mcp",+ Allow: false,+ },+ {+ Name: "one_hop_wildcard_prefix_inference_allowed",+ BiscuitB64: b64(att1Bytes),+ TargetService: "inference://gemini.pro",+ Protocol: "/libp2p-http",+ Method: strPtr("POST"),+ Path: "/v1/chat/completions",+ Allow: true,+ ExpectedEffectiveExpiration: hop1Exp.Format(time.RFC3339),+ },+ {+ Name: "one_hop_dot_boundary_inference_denied",+ BiscuitB64: b64(att1Bytes),+ TargetService: "inference://gemini2.pro",+ Protocol: "/libp2p-http",+ Method: strPtr("POST"),+ Path: "/v1/chat/completions",+ Allow: false,+ },+ {+ Name: "two_hop_intersection_mcp_allowed",+ BiscuitB64: b64(att2Bytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: true,+ ExpectedEffectiveExpiration: hop2Exp.Format(time.RFC3339),+ },+ {+ Name: "two_hop_intersection_mcp_dropped_tool_denied",+ BiscuitB64: b64(att2Bytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_forecast",+ Allow: false,+ },+ {+ Name: "two_hop_intersection_http_allowed",+ BiscuitB64: b64(att2Bytes),+ TargetService: "egress://api.github.com",+ Protocol: "/libp2p-http",+ Method: strPtr("GET"),+ Path: "/repos/acme/public/readme",+ Allow: true,+ ExpectedEffectiveExpiration: hop2Exp.Format(time.RFC3339),+ },+ {+ Name: "two_hop_intersection_http_dropped_method_denied",+ BiscuitB64: b64(att2Bytes),+ TargetService: "egress://api.github.com",+ Protocol: "/libp2p-http",+ Method: strPtr("POST"),+ Path: "/repos/acme/public/readme",+ Allow: false,+ },+ {+ Name: "two_hop_intersection_http_dropped_path_denied",+ BiscuitB64: b64(att2Bytes),+ TargetService: "egress://api.github.com",+ Protocol: "/libp2p-http",+ Method: strPtr("GET"),+ Path: "/repos/acme/private/secret",+ Allow: false,+ },+ {+ Name: "two_hop_intersection_connect_tunnel_denied",+ BiscuitB64: b64(att2Bytes),+ TargetService: "egress://api.github.com",+ Protocol: "/libp2p-http",+ Method: strPtr("CONNECT"),+ Path: "",+ Allow: false,+ },+ {+ Name: "sealed_two_hop_allowed",+ BiscuitB64: b64(sealedAtt2Bytes),+ TargetService: "egress://api.github.com",+ Protocol: "/libp2p-http",+ Method: strPtr("GET"),+ Path: "/repos/acme/public/readme",+ Allow: true,+ ExpectedEffectiveExpiration: hop2Exp.Format(time.RFC3339),+ },+ {+ Name: "expired_tar_block_rejected",+ BiscuitB64: b64(expiredBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ {+ Name: "empty_rules_tar_denied",+ BiscuitB64: b64(emptyRulesBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ {+ Name: "nine_blocks_rejected",+ BiscuitB64: b64(nineBlocksBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ {+ Name: "block_with_rule_rejected",+ BiscuitB64: b64(withRuleBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ {+ Name: "block_with_check_rejected",+ BiscuitB64: b64(withCheckBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ {+ Name: "block_with_two_facts_rejected",+ BiscuitB64: b64(twoFactsBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ {+ Name: "block_with_wrong_predicate_rejected",+ BiscuitB64: b64(wrongPredBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ {+ Name: "block_with_bytes_term_rejected",+ BiscuitB64: b64(bytesTermBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ {+ Name: "block_with_unknown_proto_field_rejected",+ BiscuitB64: b64(unknownProtoBytes),+ TargetService: "mcp://weather",+ Protocol: string(api.MCPProtocolID),+ MCPTool: "get_weather",+ Allow: false,+ },+ },+ }}func main() {- if len(os.Args) != 3 {- fmt.Fprintln(os.Stderr, "usage: gen-sdk-datalog <output.json> <output.ts>")+ if len(os.Args) < 3 || len(os.Args) > 4 {+ fmt.Fprintln(os.Stderr, "usage: gen-sdk-datalog <output.json> <output.ts> [conformance.json]")os.Exit(2)}a := artifact{- Comment: "Generated by hack/gen-sdk-datalog from api/datalog.go; do not edit.",- DatalogSources: api.BaselineSources,- FactService: api.FactService,- FactConnectionPeer: api.FactConnectionPeerID,- FactMethod: api.FactMethod,- FactPath: api.FactPath,- FactTime: api.FactTime,- FactRole: api.FactRole,- FactTargetFact: api.FactTargetFact,- MarkerTerm: api.MarkerTerm.String(),- SystemNamespace: api.SystemNamespace,- BindingPrefixes: api.BindingMemberPrefixes(),- SystemAuthenticated: api.SystemAuthenticated,+ Comment: "Generated by hack/gen-sdk-datalog from api/datalog.go; do not edit.",+ DatalogSources: api.BaselineSources,+ FactService: api.FactService,+ FactConnectionPeer: api.FactConnectionPeerID,+ FactMethod: api.FactMethod,+ FactPath: api.FactPath,+ FactTime: api.FactTime,+ FactRole: api.FactRole,+ FactTargetFact: api.FactTargetFact,+ FactTARBlock: api.FactTARBlock,+ TARBlockSourcePattern: api.TARBlockSourcePattern,+ HTTPMethodSyntax: api.HTTPMethodSyntaxPattern(),+ MaxAttenuationBlocks: api.MaxAttenuationBlocks,+ MaxTARBytes: api.MaxTARBytes,+ MaxRulesPerTAR: api.MaxRulesPerTAR,+ MaxEntriesPerTARList: api.MaxEntriesPerTARList,+ MaxTARNameLength: api.MaxTARNameLength,+ MaxTARDescriptionLength: api.MaxTARDescriptionLength,+ MaxTARResourceLength: api.MaxTARResourceLength,+ MarkerTerm: api.MarkerTerm.String(),+ SystemNamespace: api.SystemNamespace,+ BindingPrefixes: api.BindingMemberPrefixes(),+ SystemAuthenticated: api.SystemAuthenticated,}var buf bytes.Bufferenc := json.NewEncoder(&buf)@@ -83,4 +611,24 @@ func main() {fmt.Fprintln(os.Stderr, err)os.Exit(1)}++ if len(os.Args) == 4 {+ suite := buildConformanceSuite()+ var cbuf bytes.Buffer+ cenc := json.NewEncoder(&cbuf)+ cenc.SetEscapeHTML(false)+ cenc.SetIndent("", " ")+ if err := cenc.Encode(suite); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ if err := os.MkdirAll(filepath.Dir(os.Args[3]), 0o755); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ if err := os.WriteFile(os.Args[3], cbuf.Bytes(), 0o644); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ }}diff --git a/hack/gen-sdk-proto.sh b/hack/gen-sdk-proto.shindex f2edf889..97a618a5 100755--- a/hack/gen-sdk-proto.sh+++ b/hack/gen-sdk-proto.sh@@ -56,8 +56,8 @@ protoc -I sdk/python/proto \--pyi_out="${PY_GEN_DIR}" \sdk/python/proto/circuit.proto-echo "Generating baseline Datalog artifact..."-mkdir -p "${PY_DATALOG_DIR}"-go run ./hack/gen-sdk-datalog "${PY_DATALOG_DIR}/datalog.json" "${JS_GEN_DIR}/datalog.ts"+echo "Generating baseline Datalog artifact and TAR conformance vectors..."+mkdir -p "${PY_DATALOG_DIR}" sdk/testdata+go run ./hack/gen-sdk-datalog "${PY_DATALOG_DIR}/datalog.json" "${JS_GEN_DIR}/datalog.ts" "sdk/testdata/tar_conformance.json"echo "SDK protobuf generation complete."diff --git a/hack/verify-sdk-generated.sh b/hack/verify-sdk-generated.shindex d744a5b0..aca7a2fd 100755--- a/hack/verify-sdk-generated.sh+++ b/hack/verify-sdk-generated.sh@@ -26,7 +26,7 @@ set -o pipefailREPO_ROOT=$(git rev-parse --show-toplevel)cd "${REPO_ROOT}"-GENERATED=(sdk/js/src/gen sdk/python/src/agent_mesh/_proto sdk/python/src/agent_mesh/_gen)+GENERATED=(sdk/js/src/gen sdk/python/src/agent_mesh/_proto sdk/python/src/agent_mesh/_gen sdk/testdata)./hack/gen-sdk-proto.shdiff --git a/internal/identity/attenuation_test.go b/internal/identity/attenuation_test.goindex b49efc86..1ac57bb5 100644--- a/internal/identity/attenuation_test.go+++ b/internal/identity/attenuation_test.go@@ -17,10 +17,14 @@ package identityimport ("crypto/ed25519""crypto/rand"+ "errors""testing""time""github.com/biscuit-auth/biscuit-go/v2"+ "github.com/biscuit-auth/biscuit-go/v2/parser"+ "google.golang.org/protobuf/proto"+ "google.golang.org/protobuf/types/known/timestamppb""github.com/google/sam/api")@@ -99,6 +103,188 @@ func TestAttenuationBlockFactsAreInvisibleToTheAuthorizer(t *testing.T) {}}+func TestTARAttenuationAndSealing(t *testing.T) {+ pub, priv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ peerID := newTestPeer(t)+ keys := []ed25519.PublicKey{pub}+ authExp := time.Now().Add(time.Hour).Truncate(time.Second)++ rootToken, err := MintBootstrapBiscuitToken(priv, peerID, api.RoleNode, authExp, nil, nil)+ if err != nil {+ t.Fatal(err)+ }++ hop1Exp := time.Now().Add(20 * time.Minute).Truncate(time.Second)+ hop1 := &api.TaskAuthorizationRule{+ Name: "hop-1",+ DisplayName: "Orchestrator Hop",+ ExpireTime: timestamppb.New(hop1Exp),+ Rules: []*api.TaskRule{{+ AllowedServices: []string{"mcp://weather", "egress://api.github.com"},+ Operation: &api.TaskOperation{AllowedTools: []string{"get_weather", "get_forecast"}},+ }},+ }+ att1, err := AttenuateBiscuit(rootToken, hop1)+ if err != nil {+ t.Fatalf("AttenuateBiscuit hop1: %v", err)+ }++ hop2Exp := time.Now().Add(10 * time.Minute).Truncate(time.Second)+ hop2 := &api.TaskAuthorizationRule{+ Name: "hop-2",+ DisplayName: "Leaf Sandbox Hop",+ ExpireTime: timestamppb.New(hop2Exp),+ Rules: []*api.TaskRule{{+ AllowedServices: []string{"mcp://weather"},+ Operation: &api.TaskOperation{AllowedTools: []string{"get_weather"}},+ }},+ }+ att2, err := AttenuateBiscuit(att1, hop2)+ if err != nil {+ t.Fatalf("AttenuateBiscuit hop2: %v", err)+ }++ sealed, err := SealBiscuit(att2)+ if err != nil {+ t.Fatalf("SealBiscuit: %v", err)+ }++ // Appending after sealing must fail.+ if _, err := AttenuateBiscuit(sealed, hop2); err == nil {+ t.Fatal("expected AttenuateBiscuit on a sealed token to fail")+ }++ // Extracting rules from the sealed token must return [hop1, hop2].+ rules, err := ExtractTaskRules(sealed)+ if err != nil {+ t.Fatalf("ExtractTaskRules on sealed token: %v", err)+ }+ if len(rules) != 2 || !proto.Equal(rules[0], hop1) || !proto.Equal(rules[1], hop2) {+ t.Fatalf("ExtractTaskRules mismatch: got %v", rules)+ }++ // VerifyBiscuitAndGetExpiry must return the effective TAR expiry (hop2Exp).+ gotExp, err := VerifyBiscuitAndGetExpiry(sealed, peerID, keys, time.Second)+ if err != nil {+ t.Fatalf("VerifyBiscuitAndGetExpiry on sealed token: %v", err)+ }+ if !gotExp.Equal(hop2Exp) {+ t.Fatalf("VerifyBiscuitAndGetExpiry = %v, want %v", gotExp, hop2Exp)+ }++ // A token with an expired TAR block must be rejected even when authority expiration is in the future.+ expiredHop := &api.TaskAuthorizationRule{+ Name: "expired-hop",+ ExpireTime: timestamppb.New(time.Now().Add(-1 * time.Minute)),+ Rules: []*api.TaskRule{{AllowedServices: []string{"*"}}},+ }+ attExpired, err := AttenuateBiscuit(rootToken, expiredHop)+ if err != nil {+ t.Fatalf("AttenuateBiscuit expiredHop: %v", err)+ }+ if _, err := VerifyBiscuitAndGetExpiry(attExpired, peerID, keys, time.Second); err == nil {+ t.Fatal("expected VerifyBiscuitAndGetExpiry to reject expired TAR block")+ }+}++func TestUnmarshalInboundRejectsInvalidAppendedBlocks(t *testing.T) {+ _, priv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ peerID := newTestPeer(t)+ rootBytes, err := MintBootstrapBiscuitToken(priv, peerID, api.RoleNode, time.Now().Add(time.Hour), nil, nil)+ if err != nil {+ t.Fatal(err)+ }+ validTAR := &api.TaskAuthorizationRule{+ Name: "valid",+ Rules: []*api.TaskRule{{AllowedServices: []string{"mcp://calc"}}},+ }+ validFact, err := api.EncodeTARBlockFact(validTAR)+ if err != nil {+ t.Fatal(err)+ }++ // 1. Exceeding MaxAttenuationBlocks (9 blocks)+ cur := rootBytes+ for i := 0; i < api.MaxAttenuationBlocks; i++ {+ cur, err = AttenuateBiscuit(cur, validTAR)+ if err != nil {+ t.Fatalf("append block %d: %v", i+1, err)+ }+ }+ if _, err := AttenuateBiscuit(cur, validTAR); !errors.Is(err, ErrAppendedBlocks) {+ t.Fatalf("9th AttenuateBiscuit err = %v, want ErrAppendedBlocks", err)+ }+ // Manually append a 9th block via biscuit-go and verify UnmarshalInbound rejects it.+ b8, err := biscuit.Unmarshal(cur)+ if err != nil {+ t.Fatal(err)+ }+ bb9 := b8.CreateBlock()+ _ = bb9.AddFact(validFact)+ b9, err := b8.Append(rand.Reader, bb9.Build())+ if err != nil {+ t.Fatal(err)+ }+ b9Bytes, _ := b9.Serialize()+ if _, _, err := UnmarshalInbound(b9Bytes); !errors.Is(err, ErrAppendedBlocks) {+ t.Fatalf("UnmarshalInbound on 9-block token: err = %v, want ErrAppendedBlocks", err)+ }++ // 2. Appended block with a rule+ rootB, _ := biscuit.Unmarshal(rootBytes)+ bbRule := rootB.CreateBlock()+ _ = bbRule.AddFact(validFact)+ r, _ := parser.FromStringRule(`x($a) <- tar_block($a)`)+ _ = bbRule.AddRule(r)+ bWithRule, _ := rootB.Append(rand.Reader, bbRule.Build())+ bWithRuleBytes, _ := bWithRule.Serialize()+ if _, _, err := UnmarshalInbound(bWithRuleBytes); !errors.Is(err, ErrAppendedBlocks) {+ t.Fatalf("UnmarshalInbound on block with rule: err = %v, want ErrAppendedBlocks", err)+ }++ // 3. Appended block with a check+ bbCheck := rootB.CreateBlock()+ _ = bbCheck.AddFact(validFact)+ chk, _ := parser.FromStringCheck(`check if tar_block($a)`)+ _ = bbCheck.AddCheck(chk)+ bWithCheck, _ := rootB.Append(rand.Reader, bbCheck.Build())+ bWithCheckBytes, _ := bWithCheck.Serialize()+ if _, _, err := UnmarshalInbound(bWithCheckBytes); !errors.Is(err, ErrAppendedBlocks) {+ t.Fatalf("UnmarshalInbound on block with check: err = %v, want ErrAppendedBlocks", err)+ }++ // 4. Appended block with 2 facts+ bbTwoFacts := rootB.CreateBlock()+ _ = bbTwoFacts.AddFact(validFact)+ _ = bbTwoFacts.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactTARBlock,+ IDs: []biscuit.Term{biscuit.String("extra")},+ }})+ bTwoFacts, _ := rootB.Append(rand.Reader, bbTwoFacts.Build())+ bTwoFactsBytes, _ := bTwoFacts.Serialize()+ if _, _, err := UnmarshalInbound(bTwoFactsBytes); !errors.Is(err, ErrAppendedBlocks) {+ t.Fatalf("UnmarshalInbound on block with 2 facts: err = %v, want ErrAppendedBlocks", err)+ }++ // 5. Appended block with non-string term (bytes)+ bbBytesTerm := rootB.CreateBlock()+ _ = bbBytesTerm.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactTARBlock,+ IDs: []biscuit.Term{biscuit.Bytes([]byte{1, 2, 3})},+ }})+ bBytesTerm, _ := rootB.Append(rand.Reader, bbBytesTerm.Build())+ bBytesTermBytes, _ := bBytesTerm.Serialize()+ if _, _, err := UnmarshalInbound(bBytesTermBytes); !errors.Is(err, ErrAppendedBlocks) {+ t.Fatalf("UnmarshalInbound on block with bytes term: err = %v, want ErrAppendedBlocks", err)+ }+}+func mustAddAuthorityFact(t *testing.T, builder biscuit.Builder, name string, term biscuit.Term) {t.Helper()if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.goindex f560a2d9..eb7960b8 100644--- a/internal/identity/biscuit.go+++ b/internal/identity/biscuit.go@@ -16,8 +16,10 @@ package identityimport ("crypto/ed25519"+ "crypto/rand""errors""fmt"+ "io""sort""strings""time"@@ -25,10 +27,12 @@ import ("github.com/biscuit-auth/biscuit-go/v2""github.com/biscuit-auth/biscuit-go/v2/datalog""github.com/biscuit-auth/biscuit-go/v2/parser"+ "github.com/biscuit-auth/biscuit-go/v2/pb""github.com/coreos/go-oidc/v3/oidc""github.com/golang-jwt/jwt/v5""github.com/google/sam/api""github.com/libp2p/go-libp2p/core/peer"+ "google.golang.org/protobuf/proto")// DefaultAuthorizerTimeout bounds Datalog evaluation when no timeout is configured.@@ -61,29 +65,145 @@ func AuthorizerOptions(timeout time.Duration) []biscuit.AuthorizerOption {)}}-// ErrAppendedBlocks is returned for a token that carries attenuation blocks.-var ErrAppendedBlocks = errors.New("biscuit carries appended blocks; SAM tokens are authority-block only")+// ErrAppendedBlocks is returned for a token that carries an invalid appended+// attenuation block (more than api.MaxAttenuationBlocks blocks, or any block+// that does not consist solely of 0 rules, 0 checks, and 1 valid tar_block fact).+var ErrAppendedBlocks = errors.New("biscuit carries invalid appended blocks; only tar_block attenuation facts are permitted")// UnmarshalInbound parses a token received from a peer or a client and-// refuses one with appended blocks.+// validates any appended attenuation blocks BEFORE building a Datalog+// authorizer.//// Appending needs no root key, so appended blocks are the one place a token-// holder can put Datalog of their own. SAM reads nothing from them: facts-// there are invisible to the authorizer and RequireAuthorityBinding ignores-// them. What they can still do is cost CPU: a block with a self-join rule-// over a few hundred facts pins a core for the whole evaluation budget on-// every verifier that evaluates it, and leaks the worker goroutine (see the-// limits above). The control plane never mints such blocks, so a token that-// has any is not one SAM issued in its current form.-func UnmarshalInbound(biscuitData []byte) (*biscuit.Biscuit, error) {+// holder could otherwise put Datalog of their own (such as a self-join rule or+// check that pins a core for the evaluation budget and leaks a worker+// goroutine). UnmarshalInbound inspects the raw pb.Biscuit envelope and block+// sources first, admitting at most api.MaxAttenuationBlocks blocks and+// requiring every appended block to contain 0 rules, 0 checks, and exactly 1+// tar_block("<base64url-proto>") fact encoding a valid+// api.TaskAuthorizationRule. It returns both the parsed Biscuit and the+// decoded TaskAuthorizationRule chain so callers never parse twice.+func UnmarshalInbound(biscuitData []byte) (*biscuit.Biscuit, []*api.TaskAuthorizationRule, error) {b, err := biscuit.Unmarshal(biscuitData)if err != nil {- return nil, fmt.Errorf("malformed biscuit: %w", err)+ return nil, nil, fmt.Errorf("malformed biscuit: %w", err)}- if n := b.BlockCount(); n > 0 {- return nil, fmt.Errorf("%w (%d)", ErrAppendedBlocks, n)+ n := b.BlockCount()+ if n == 0 {+ return b, nil, nil}- return b, nil+ if n > api.MaxAttenuationBlocks {+ return nil, nil, fmt.Errorf("%w: block count %d exceeds maximum %d", ErrAppendedBlocks, n, api.MaxAttenuationBlocks)+ }++ var container pb.Biscuit+ if err := proto.Unmarshal(biscuitData, &container); err != nil {+ return nil, nil, fmt.Errorf("malformed biscuit envelope: %w", err)+ }+ if len(container.GetBlocks()) != n {+ return nil, nil, fmt.Errorf("%w: block count mismatch (%d != %d)", ErrAppendedBlocks, len(container.GetBlocks()), n)+ }++ for i, sb := range container.GetBlocks() {+ var blk pb.Block+ if err := proto.Unmarshal(sb.GetBlock(), &blk); err != nil {+ return nil, nil, fmt.Errorf("%w: block %d malformed: %w", ErrAppendedBlocks, i+1, err)+ }+ if len(blk.GetRulesV2()) != 0 {+ return nil, nil, fmt.Errorf("%w: block %d contains %d rules (0 allowed)", ErrAppendedBlocks, i+1, len(blk.GetRulesV2()))+ }+ if len(blk.GetChecksV2()) != 0 {+ return nil, nil, fmt.Errorf("%w: block %d contains %d checks (0 allowed)", ErrAppendedBlocks, i+1, len(blk.GetChecksV2()))+ }+ if len(blk.GetFactsV2()) != 1 {+ return nil, nil, fmt.Errorf("%w: block %d contains %d facts (1 tar_block fact required)", ErrAppendedBlocks, i+1, len(blk.GetFactsV2()))+ }+ pred := blk.GetFactsV2()[0].GetPredicate()+ if pred == nil || len(pred.GetTerms()) != 1 {+ return nil, nil, fmt.Errorf("%w: block %d fact must have exactly 1 term", ErrAppendedBlocks, i+1)+ }+ if _, ok := pred.GetTerms()[0].GetContent().(*pb.TermV2_String_); !ok {+ return nil, nil, fmt.Errorf("%w: block %d fact term must be a string", ErrAppendedBlocks, i+1)+ }+ }++ codes := b.Code()+ if len(codes) != n {+ return nil, nil, fmt.Errorf("%w: block code count mismatch (%d != %d)", ErrAppendedBlocks, len(codes), n)+ }+ rules := make([]*api.TaskAuthorizationRule, 0, n)+ for i, rawCode := range codes {+ inner := strings.TrimSpace(rawCode)+ inner = strings.TrimPrefix(inner, "Block {")+ inner = strings.TrimSuffix(inner, "}")+ inner = strings.TrimSpace(inner)+ rule, err := api.ParseTARBlockSource(inner)+ if err != nil {+ return nil, nil, fmt.Errorf("%w: block %d: %w", ErrAppendedBlocks, i+1, err)+ }+ rules = append(rules, rule)+ }++ return b, rules, nil+}++// AttenuateBiscuit appends a validated TaskAuthorizationRule as a single+// tar_block("<base64url>") fact block (with 0 rules and 0 checks) to an+// existing Biscuit token.+func AttenuateBiscuit(biscuitData []byte, rule *api.TaskAuthorizationRule) ([]byte, error) {+ return AttenuateBiscuitWithRand(rand.Reader, biscuitData, rule)+}++// AttenuateBiscuitWithRand is AttenuateBiscuit with an explicit random source+// (used by deterministic conformance vector generators).+func AttenuateBiscuitWithRand(rng io.Reader, biscuitData []byte, rule *api.TaskAuthorizationRule) ([]byte, error) {+ b, existingRules, err := UnmarshalInbound(biscuitData)+ if err != nil {+ return nil, err+ }+ if len(existingRules) >= api.MaxAttenuationBlocks {+ return nil, fmt.Errorf("%w: cannot append block %d (max %d)", ErrAppendedBlocks, len(existingRules)+1, api.MaxAttenuationBlocks)+ }+ fact, err := api.EncodeTARBlockFact(rule)+ if err != nil {+ return nil, err+ }+ blockBuilder := b.CreateBlock()+ if err := blockBuilder.AddFact(fact); err != nil {+ return nil, fmt.Errorf("failed to add tar_block fact: %w", err)+ }+ attenuated, err := b.Append(rng, blockBuilder.Build())+ if err != nil {+ return nil, fmt.Errorf("failed to append tar_block to biscuit: %w", err)+ }+ return attenuated.Serialize()+}++// SealBiscuit cryptographically seals a Biscuit token so no further blocks can+// be appended by a downstream holder.+func SealBiscuit(biscuitData []byte) ([]byte, error) {+ return SealBiscuitWithRand(rand.Reader, biscuitData)+}++// SealBiscuitWithRand is SealBiscuit with an explicit random source (used by+// deterministic conformance vector generators).+func SealBiscuitWithRand(rng io.Reader, biscuitData []byte) ([]byte, error) {+ b, _, err := UnmarshalInbound(biscuitData)+ if err != nil {+ return nil, err+ }+ sealed, err := b.Seal(rng)+ if err != nil {+ return nil, fmt.Errorf("failed to seal biscuit: %w", err)+ }+ return sealed.Serialize()+}++// ExtractTaskRules validates an inbound Biscuit's appended blocks and returns+// its decoded TaskAuthorizationRule chain (nil if authority-only).+func ExtractTaskRules(biscuitData []byte) ([]*api.TaskAuthorizationRule, error) {+ _, rules, err := UnmarshalInbound(biscuitData)+ return rules, err}// EnforceExpiration injects the current time and the expiration check into an@@ -357,7 +477,7 @@ func VerifyBiscuitAndGetExpiry(biscuitData []byte, expectedPeer peer.ID, trusted}func verifyBiscuit(biscuitData []byte, expectedPeer peer.ID, trustedPublicKeys []ed25519.PublicKey, timeout time.Duration) (*biscuit.Biscuit, ed25519.PublicKey, time.Time, error) {- b, err := UnmarshalInbound(biscuitData)+ b, rules, err := UnmarshalInbound(biscuitData)if err != nil {return nil, nil, time.Time{}, err}@@ -400,6 +520,10 @@ func verifyBiscuit(biscuitData []byte, expectedPeer peer.ID, trustedPublicKeys [if err != nil {return nil, nil, time.Time{}, err}+ expiry = api.EffectiveTARExpiration(expiry, rules)+ if !time.Now().Before(expiry) {+ return nil, nil, time.Time{}, fmt.Errorf("token tar_block expired at %s", expiry.UTC().Format(time.RFC3339))+ }return b, verifyingKey, expiry, nil}@@ -484,10 +608,18 @@ func VerifyAndExtractPeerID(trustedPublicKeys []ed25519.PublicKey, biscuitData [}func extractPeerID(trustedPublicKeys []ed25519.PublicKey, biscuitData []byte, timeout time.Duration, enforceExpiry bool) (peer.ID, error) {- b, err := UnmarshalInbound(biscuitData)+ b, rules, err := UnmarshalInbound(biscuitData)if err != nil {return "", err}+ if enforceExpiry {+ now := time.Now()+ for i, rule := range rules {+ if exp := rule.GetExpireTime(); exp != nil && now.After(exp.AsTime()) {+ return "", fmt.Errorf("tar_block[%d] expired at %s", i+1, exp.AsTime().UTC().Format(time.RFC3339))+ }+ }+ }authOpts := AuthorizerOptions(timeout)@@ -559,7 +691,7 @@ func extractPeerID(trustedPublicKeys []ed25519.PublicKey, biscuitData []byte, ti// should trigger a refresh rather than refuse to boot. Do not use it to admit a token// received from a peer.func VerifyBiscuitRole(biscuitData []byte, controlPlanePubKey ed25519.PublicKey, expectedRole string, timeout time.Duration) error {- b, err := UnmarshalInbound(biscuitData)+ b, _, err := UnmarshalInbound(biscuitData)if err != nil {return err}diff --git a/internal/node/gate.go b/internal/node/gate.goindex 84ab2181..b3118158 100644--- a/internal/node/gate.go+++ b/internal/node/gate.go@@ -87,7 +87,7 @@ func (n *SamNode) HandleMCPStream(s network.Stream, reqCtx RequestContext) {if t, err := api.ParseServiceType(targetType); err == nil && t == api.ServiceType_SERVICE_TYPE_MCP {if svc, ok := n.services.GetTyped(t, targetName); ok {if mcpSvc, isMcp := svc.(*MCPService); isMcp {- mcpSvc.HandleStreamPassThrough(s)+ mcpSvc.HandleStreamPassThrough(s, reqCtx)return}}diff --git a/internal/node/gate_test.go b/internal/node/gate_test.goindex 1df88817..70cdb846 100644--- a/internal/node/gate_test.go+++ b/internal/node/gate_test.go@@ -545,3 +545,83 @@ func TestHandleStreamPassThrough_SlowBackendDoesNotHitDrainTimeout(t *testing.T)t.Fatalf("got %v, want text %q", res.Content, "ok")}}++func TestHandleMCPStream_TAREnforcesAllowedTools(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ upstream := httptest.NewServer(mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server {+ srv := mcp.NewServer(&mcp.Implementation{Name: "weather-srv", Version: "0.0.1"}, nil)+ srv.AddTool(&mcp.Tool{Name: "get_weather", Description: "allowed tool", InputSchema: map[string]any{"type": "object"}},+ func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "sunny"}}}, nil+ })+ srv.AddTool(&mcp.Tool{Name: "drop_table", Description: "forbidden tool", InputSchema: map[string]any{"type": "object"}},+ func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "dropped"}}}, nil+ })+ return srv+ }, nil))+ defer upstream.Close()++ nodeA, cleanupA := startBareNode(t, ctx)+ defer cleanupA()+ nodeB, cleanupB := startBareNode(t, ctx)+ defer cleanupB()++ svc := &MCPService{baseService: baseService{+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "weather"},+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL},+ }}+ if err := svc.Init(ctx); err != nil {+ t.Fatalf("MCPService.Init: %v", err)+ }+ nodeA.services.insertService(svc)+ t.Cleanup(func() { _ = svc.Teardown() })++ tar := &api.TaskAuthorizationRule{+ Name: "only-get-weather",+ Rules: []*api.TaskRule{{+ AllowedServices: []string{"mcp://weather"},+ Operation: &api.TaskOperation{AllowedTools: []string{"get_weather"}},+ }},+ }+ nodeA.Host.SetStreamHandler(testMCPProtocol, func(s network.Stream) {+ nodeA.HandleMCPStream(s, RequestContext{+ PeerID: s.Conn().RemotePeer(),+ Target: "mcp://weather",+ TaskRules: []*api.TaskAuthorizationRule{tar},+ })+ })++ if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil {+ t.Fatalf("connect: %v", err)+ }++ s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProtocol)+ if err != nil {+ t.Fatalf("NewStream: %v", err)+ }+ defer func() { _ = s.Close() }()++ client := mcp.NewClient(&mcp.Implementation{Name: "tc", Version: "0.0.1"}, nil)+ session, err := client.Connect(ctx, NewStreamTransport(s), nil)+ if err != nil {+ t.Fatalf("client.Connect: %v", err)+ }+ defer func() { _ = session.Close() }()++ // Allowed tool call succeeds.+ res, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "get_weather", Arguments: map[string]any{}})+ if err != nil {+ t.Fatalf("CallTool(get_weather) unexpected error: %v", err)+ }+ if tc, ok := res.Content[0].(*mcp.TextContent); !ok || tc.Text != "sunny" {+ t.Fatalf("got %v, want text %q", res.Content, "sunny")+ }++ // Forbidden tool call is rejected by the PEP before reaching the upstream MCP server.+ if _, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "drop_table", Arguments: map[string]any{}}); err == nil {+ t.Fatal("expected CallTool(drop_table) to be denied by TAR")+ }+}diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.goindex a7873c10..937a48e0 100644--- a/internal/node/mcp_service.go+++ b/internal/node/mcp_service.go@@ -16,6 +16,7 @@ package nodeimport ("context"+ "encoding/json""errors""fmt""os/exec"@@ -221,7 +222,7 @@ var preflightMethodsUnsupportedByPassThrough = map[string]bool{var passThroughDrainTimeout = 5 * time.Second// HandleStreamPassThrough connects to the backend and proxies JSON-RPC messages.-func (m *MCPService) HandleStreamPassThrough(s network.Stream) {+func (m *MCPService) HandleStreamPassThrough(s network.Stream, reqCtx RequestContext) {defer func() {if err := s.Close(); err != nil {logger.Debugf("[MCPService] Failed to close MCP stream: %v", err)@@ -323,6 +324,16 @@ func (m *MCPService) HandleStreamPassThrough(s network.Stream) {}continue}+ if req, ok := msg.(*jsonrpc.Request); ok && len(reqCtx.TaskRules) > 0 {+ if errResp := m.authorizeMCPRequest(req, reqCtx); errResp != nil {+ if werr := clientConn.Write(ctx, errResp); werr != nil {+ logger.Debugf("[MCPService] %s: failed to write TAR rejection: %v", m.info.Name, werr)+ clientErrc <- werr+ return+ }+ continue+ }+ }if err := backendConn.Write(ctx, msg); err != nil {logger.Debugf("[MCPService] %s: backend write error: %v", m.info.Name, err)clientErrc <- err@@ -346,3 +357,50 @@ func (m *MCPService) HandleStreamPassThrough(s network.Stream) {logger.Debugf("[MCPService] %s: client did not hang up within %v of the backend finishing; closing", m.info.Name, passThroughDrainTimeout)}}++// authorizeMCPRequest evaluates reqCtx.TaskRules against an inbound JSON-RPC+// request on an MCP stream. Returns a JSON-RPC error response when denied, or+// nil when allowed.+func (m *MCPService) authorizeMCPRequest(req *jsonrpc.Request, reqCtx RequestContext) *jsonrpc.Response {+ if !req.IsCall() {+ return nil+ }+ svcName := m.info.GetName()+ switch req.Method {+ case "initialize", "ping", "tools/list":+ if err := api.EvaluateTaskRules(reqCtx.TaskRules, api.TaskRequestContext{+ ServiceType: "mcp",+ ServiceName: svcName,+ AllowMCPStreamInit: true,+ }, time.Now()); err != nil {+ logger.Warnf("[MCPService] %s: TAR denied %s from %s: %v", svcName, req.Method, reqCtx.PeerID, err)+ return &jsonrpc.Response{ID: req.ID, Error: &jsonrpc.Error{Code: jsonrpc.CodeInvalidRequest, Message: fmt.Sprintf("task authorization denied %s: %v", req.Method, err)}}+ }+ return nil+ case "tools/call":+ var params struct {+ Name string `json:"name"`+ }+ if len(req.Params) == 0 || json.Unmarshal(req.Params, ¶ms) != nil || params.Name == "" {+ return &jsonrpc.Response{ID: req.ID, Error: &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "tools/call requires a non-empty tool name"}}+ }+ if err := api.EvaluateTaskRules(reqCtx.TaskRules, api.TaskRequestContext{+ ServiceType: "mcp",+ ServiceName: svcName,+ MCPTool: params.Name,+ }, time.Now()); err != nil {+ logger.Warnf("[MCPService] %s: TAR denied tools/call %q from %s: %v", svcName, params.Name, reqCtx.PeerID, err)+ return &jsonrpc.Response{ID: req.ID, Error: &jsonrpc.Error{Code: jsonrpc.CodeInvalidRequest, Message: fmt.Sprintf("task authorization denied tool %q: %v", params.Name, err)}}+ }+ return nil+ default:+ if err := api.EvaluateTaskRules(reqCtx.TaskRules, api.TaskRequestContext{+ ServiceType: "mcp",+ ServiceName: svcName,+ }, time.Now()); err != nil {+ logger.Warnf("[MCPService] %s: TAR denied %s from %s: %v", svcName, req.Method, reqCtx.PeerID, err)+ return &jsonrpc.Response{ID: req.ID, Error: &jsonrpc.Error{Code: jsonrpc.CodeInvalidRequest, Message: fmt.Sprintf("task authorization denied %s: %v", req.Method, err)}}+ }+ return nil+ }+}diff --git a/internal/node/middleware.go b/internal/node/middleware.goindex ddc66c53..450824a1 100644--- a/internal/node/middleware.go+++ b/internal/node/middleware.go@@ -54,6 +54,14 @@ type RequestContext struct {// node, evaluated on its own credential, and the target check is satisfied// because a node is always allowed to reach itself. Never set from the wire.Local bool++ // MCPTool is set when evaluating a specific MCP tools/call invocation.+ MCPTool string++ // TaskRules holds the verified TaskAuthorizationRule chain extracted from+ // the caller's Biscuit during stream authentication so downstream stream+ // handlers (such as MCP pass-through) can enforce tool-level constraints.+ TaskRules []*api.TaskAuthorizationRule}// HTTPRequestFacts is what an HTTP request contributes to policy.@@ -160,7 +168,7 @@ func (n *SamNode) WithBiscuitAuth(next func(network.Stream, RequestContext)) netwriter := msgio.NewVarintWriter(ts)- err = n.VerifyBiscuitToken(authFrame.Biscuit, reqCtx)+ taskRules, err := n.verifyBiscuitTokenWithRules(authFrame.Biscuit, reqCtx)if err != nil {logger.Warnf("[Auth] AuthZ Denied %s: %v", remotePeer, err)resp := &api.AuthResponse{Success: false, Error: err.Error()}@@ -168,6 +176,7 @@ func (n *SamNode) WithBiscuitAuth(next func(network.Stream, RequestContext)) net_ = writer.WriteMsg(respBytes)return}+ reqCtx.TaskRules = taskRules// Valid. Mutual auth: return our control-plane-minted identity so the// caller can verify this node's attested facts (e.g. region) before@@ -191,13 +200,18 @@ func (n *SamNode) WithBiscuitAuth(next func(network.Stream, RequestContext)) net// VerifyBiscuitToken checks revocation, cache, and evaluates the token against trusted keys and local policies.func (n *SamNode) VerifyBiscuitToken(biscuitBytes []byte, reqCtx RequestContext) error {+ _, err := n.verifyBiscuitTokenWithRules(biscuitBytes, reqCtx)+ return err+}++func (n *SamNode) verifyBiscuitTokenWithRules(biscuitBytes []byte, reqCtx RequestContext) ([]*api.TaskAuthorizationRule, error) {remotePeer := reqCtx.PeerID// Check revocation cacheif n.revokedPeers != nil {if _, isRevoked := n.revokedPeers.Get(remotePeer.String()); isRevoked {logger.Warnf("[Auth] Peer %s is revoked", remotePeer)- return fmt.Errorf("peer is revoked")+ return nil, fmt.Errorf("peer is revoked")}}@@ -206,11 +220,13 @@ func (n *SamNode) VerifyBiscuitToken(biscuitBytes []byte, reqCtx RequestContext)n.keysMu.RUnlock()var authorized bool+ var taskRules []*api.TaskAuthorizationRulevar lastErr errorfor _, pubKey := range keys {logger.Infof("[Auth] Trying key: %x", pubKey.Key)- if err := n.Authorize(biscuitBytes, reqCtx, pubKey.Key); err == nil {+ if rules, err := n.authorizeWithRules(biscuitBytes, reqCtx, pubKey.Key); err == nil {authorized = true+ taskRules = rulesbreak} else {lastErr = err@@ -219,30 +235,35 @@ func (n *SamNode) VerifyBiscuitToken(biscuitBytes []byte, reqCtx RequestContext)if !authorized {if lastErr != nil {- return lastErr+ return nil, lastErr}- return fmt.Errorf("authorization failed")+ return nil, fmt.Errorf("authorization failed")}- return nil+ return taskRules, nil}func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.PublicKey) error {+ _, err := n.authorizeWithRules(rawToken, req, pubKey)+ return err+}++func (n *SamNode) authorizeWithRules(rawToken []byte, req RequestContext, pubKey ed25519.PublicKey) ([]*api.TaskAuthorizationRule, error) {if len(pubKey) != ed25519.PublicKeySize {- return fmt.Errorf("invalid public key size: %d", len(pubKey))+ return nil, fmt.Errorf("invalid public key size: %d", len(pubKey))}- b, err := identity.UnmarshalInbound(rawToken)+ b, taskRules, err := identity.UnmarshalInbound(rawToken)if err != nil {- return fmt.Errorf("invalid biscuit: %w", err)+ return nil, fmt.Errorf("invalid biscuit: %w", err)}authorizer, err := b.Authorizer(pubKey, identity.AuthorizerOptions(n.BiscuitTimeout)...)if err != nil {- return err+ return nil, err}if err := identity.RequireAuthorityBinding(b, req.PeerID); err != nil {- return err+ return nil, err}// Inject the current action context (Standard Vocabulary)@@ -304,7 +325,7 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.// Inject facts from our own identity token to support target matchingif err := n.injectIdentityFacts(authorizer, pubKey); err != nil {- return fmt.Errorf("failed to inject target facts: %w", err)+ return nil, fmt.Errorf("failed to inject target facts: %w", err)}if n.nodeConfig != nil {@@ -345,7 +366,25 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", err.Error())...)logger.Debugf("Authorizer failure: %v, token: %s", err, b.String())logger.Debugf("Authorizer state: %s", authorizer.PrintWorld())- return err+ return nil, err+ }++ if len(taskRules) > 0 {+ taskReq := api.TaskRequestContext{+ ServiceType: opType,+ ServiceName: opName,+ MCPTool: req.MCPTool,+ AllowMCPStreamInit: req.HTTP == nil && req.MCPTool == "" && req.Protocol == string(api.MCPProtocolID),+ }+ if req.HTTP != nil {+ taskReq.HasHTTP = true+ taskReq.Method = req.HTTP.Method+ taskReq.Path = req.HTTP.Path+ }+ if err := api.EvaluateTaskRules(taskRules, taskReq, time.Now()); err != nil {+ logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", err.Error())...)+ return nil, err+ }}var userStr, emailStr, roleStr string@@ -377,14 +416,18 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.}}- logger.Infow("Audit Traceability", append(req.auditFields(),+ auditFields := append(req.auditFields(),"decision", "allow","user", userStr,"email", emailStr,"role", roleStr,- )...)+ )+ if len(taskRules) > 0 {+ auditFields = append(auditFields, "task", taskRules[len(taskRules)-1].GetName())+ }+ logger.Infow("Audit Traceability", auditFields...)- return nil+ return taskRules, nil}// auditFields is what every authorization decision logs about the request:@@ -402,6 +445,9 @@ func (req RequestContext) auditFields() []any {if req.Egress != nil {fields = append(fields, "host", req.Egress.Host, "port", req.Egress.Port)}+ if req.MCPTool != "" {+ fields = append(fields, "mcp_tool", req.MCPTool)+ }return fields}diff --git a/internal/node/middleware_test.go b/internal/node/middleware_test.goindex b6fecee5..a622a3c9 100644--- a/internal/node/middleware_test.go+++ b/internal/node/middleware_test.go@@ -19,6 +19,8 @@ import ("context""crypto/ed25519"cryptorand "crypto/rand"+ "encoding/base64"+ "encoding/json""fmt""io"@@ -1026,3 +1028,228 @@ func TestTrackingStream(t *testing.T) {t.Errorf("Expected bytesRead to be %d, got %d", n, ts.bytesRead.Load())}}++func TestAuthorize_WithTARBlocks(t *testing.T) {+ pub, priv, err := ed25519.GenerateKey(cryptorand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ callerKey, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ t.Fatal(err)+ }+ callerPeer, err := peer.IDFromPrivateKey(callerKey)+ if err != nil {+ t.Fatal(err)+ }++ // Mint an authority Biscuit that grants wildcard services and targets.+ builder := biscuit.NewBuilder(priv)+ for _, f := range []biscuit.Fact{+ {Predicate: biscuit.Predicate{Name: api.FactClientPeerID, IDs: []biscuit.Term{biscuit.String(callerPeer.String())}}},+ {Predicate: biscuit.Predicate{Name: api.FactNode, IDs: []biscuit.Term{biscuit.String(callerPeer.String())}}},+ {Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(time.Now().Add(time.Hour))}}},+ api.MarkerFact(api.FactGrantedServiceAllTypes),+ api.MarkerFact(api.FactTargetUnrestricted),+ } {+ if err := builder.AddAuthorityFact(f); err != nil {+ t.Fatal(err)+ }+ }+ rootBiscuit, err := builder.Build()+ if err != nil {+ t.Fatal(err)+ }+ rootBytes, err := rootBiscuit.Serialize()+ if err != nil {+ t.Fatal(err)+ }++ // Attenuate with Hop 1 (allows mcp://weather and egress://api.github.com GET/POST /repos/acme/*)+ hop1 := &api.TaskAuthorizationRule{+ Name: "hop-1",+ ExpireTime: timestamppb.New(time.Now().Add(10 * time.Minute)),+ Rules: []*api.TaskRule{+ {+ AllowedServices: []string{"mcp://weather"},+ Operation: &api.TaskOperation{AllowedTools: []string{"get_weather", "get_forecast"}},+ },+ {+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &api.TaskOperation{+ AllowedMethods: []string{"GET", "POST"},+ AllowedPaths: []string{"/repos/acme/*"},+ },+ },+ },+ }+ att1, err := identity.AttenuateBiscuit(rootBytes, hop1)+ if err != nil {+ t.Fatal(err)+ }++ // Attenuate with Hop 2 (narrows to GET /repos/acme/public/* and get_weather) and seal.+ hop2 := &api.TaskAuthorizationRule{+ Name: "hop-2",+ ExpireTime: timestamppb.New(time.Now().Add(5 * time.Minute)),+ Rules: []*api.TaskRule{+ {+ AllowedServices: []string{"mcp://weather"},+ Operation: &api.TaskOperation{AllowedTools: []string{"get_weather"}},+ },+ {+ AllowedServices: []string{"egress://api.github.com"},+ Operation: &api.TaskOperation{+ AllowedMethods: []string{"GET"},+ AllowedPaths: []string{"/repos/acme/public/*"},+ },+ },+ },+ }+ att2, err := identity.AttenuateBiscuit(att1, hop2)+ if err != nil {+ t.Fatal(err)+ }+ sealed, err := identity.SealBiscuit(att2)+ if err != nil {+ t.Fatal(err)+ }++ node := &SamNode{+ trustedKeys: []TrustedKey{{Key: pub, ReceivedAt: time.Now()}},+ BiscuitTimeout: 500 * time.Millisecond,+ }++ // 1. Allowed HTTP GET under narrowed prefix+ if err := node.Authorize(sealed, RequestContext{+ PeerID: callerPeer,+ Protocol: "/libp2p-http",+ Target: "egress://api.github.com",+ HTTP: &HTTPRequestFacts{Method: "GET", Path: "/repos/acme/public/readme"},+ }, pub); err != nil {+ t.Errorf("expected allowed HTTP GET to succeed, got: %v", err)+ }++ // 2. Denied HTTP POST (dropped in hop 2)+ if err := node.Authorize(sealed, RequestContext{+ PeerID: callerPeer,+ Protocol: "/libp2p-http",+ Target: "egress://api.github.com",+ HTTP: &HTTPRequestFacts{Method: "POST", Path: "/repos/acme/public/readme"},+ }, pub); err == nil {+ t.Error("expected HTTP POST to be denied by hop 2 TAR")+ }++ // 3. Denied service outside TAR (even though standing RBAC grants *)+ if err := node.Authorize(sealed, RequestContext{+ PeerID: callerPeer,+ Protocol: "/libp2p-http",+ Target: "inference://llama3",+ HTTP: &HTTPRequestFacts{Method: "POST", Path: "/v1/chat/completions"},+ }, pub); err == nil {+ t.Error("expected inference://llama3 to be denied by TAR")+ }++ // 4. Allowed MCP stream handshake on api.MCPProtocolID+ if err := node.Authorize(sealed, RequestContext{+ PeerID: callerPeer,+ Protocol: string(api.MCPProtocolID),+ Target: "mcp://weather",+ }, pub); err != nil {+ t.Errorf("expected MCP stream handshake to mcp://weather to succeed, got: %v", err)+ }+}++func TestTARConformanceVectors(t *testing.T) {+ rawJSON, err := os.ReadFile(filepath.Join("..", "..", "sdk", "testdata", "tar_conformance.json"))+ if err != nil {+ t.Fatalf("failed to read tar_conformance.json: %v", err)+ }+ var suite struct {+ PublicKeyB64 string `json:"public_key_b64"`+ CallerPeerID string `json:"caller_peer_id"`+ ProviderBiscuitB64 string `json:"provider_biscuit_b64"`+ PolicyDatalogRules []string `json:"policy_datalog_rules"`+ Vectors []struct {+ Name string `json:"name"`+ BiscuitB64 string `json:"biscuit_b64"`+ TargetService string `json:"target_service"`+ Protocol string `json:"protocol"`+ Method *string `json:"method,omitempty"`+ Path string `json:"path,omitempty"`+ MCPTool string `json:"mcp_tool,omitempty"`+ Allow bool `json:"allow"`+ ExpectedEffectiveExpiration string `json:"expected_effective_expiration,omitempty"`+ } `json:"vectors"`+ }+ if err := json.Unmarshal(rawJSON, &suite); err != nil {+ t.Fatalf("failed to unmarshal tar_conformance.json: %v", err)+ }++ rootPubBytes, err := base64.StdEncoding.DecodeString(suite.PublicKeyB64)+ if err != nil {+ t.Fatal(err)+ }+ rootPub := ed25519.PublicKey(rootPubBytes)+ callerPeer, err := peer.Decode(suite.CallerPeerID)+ if err != nil {+ t.Fatal(err)+ }+ providerBytes, err := base64.StdEncoding.DecodeString(suite.ProviderBiscuitB64)+ if err != nil {+ t.Fatal(err)+ }+ meshRules, err := api.ParseDatalogRules(suite.PolicyDatalogRules)+ if err != nil {+ t.Fatal(err)+ }++ node := &SamNode{+ trustedKeys: []TrustedKey{{Key: rootPub, ReceivedAt: time.Now()}},+ MeshPolicyRules: meshRules,+ BiscuitTimeout: 500 * time.Millisecond,+ }+ node.SetIdentityCache(providerBytes)++ for _, vec := range suite.Vectors {+ t.Run(vec.Name, func(t *testing.T) {+ tokenBytes, err := base64.StdEncoding.DecodeString(vec.BiscuitB64)+ if err != nil {+ t.Fatal(err)+ }+ if vec.ExpectedEffectiveExpiration != "" {+ exp, verifyErr := identity.VerifyBiscuitAndGetExpiry(tokenBytes, callerPeer, []ed25519.PublicKey{rootPub}, 500*time.Millisecond)+ if verifyErr != nil {+ t.Fatalf("VerifyBiscuitAndGetExpiry 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)+ }+ }++ req := RequestContext{+ PeerID: callerPeer,+ Protocol: vec.Protocol,+ Target: vec.TargetService,+ MCPTool: vec.MCPTool,+ }+ if vec.Method != nil {+ req.HTTP = &HTTPRequestFacts{+ Method: *vec.Method,+ Path: vec.Path,+ }+ }+ authErr := node.Authorize(tokenBytes, req, rootPub)+ if vec.Allow && authErr != nil {+ t.Fatalf("expected allow=true, got error: %v", authErr)+ }+ if !vec.Allow && authErr == nil {+ t.Fatalf("expected allow=false, got nil")+ }+ })+ }+}diff --git a/sdk/js/src/authorizer.test.ts b/sdk/js/src/authorizer.test.tsindex 08e3f05b..87308dac 100644--- a/sdk/js/src/authorizer.test.ts+++ b/sdk/js/src/authorizer.test.ts@@ -16,10 +16,12 @@// mints them and policy rules rendered the way it renders them. The// decisions here are the ones internal/node/middleware_test.go pins.+import { timestampFromDate } from "@bufbuild/protobuf/wkt";import assert from "node:assert/strict";+import { readFileSync } from "node:fs";import { before, test } from "node:test";import { AuthorizationError, authorizeCaller, type AuthorizeRequest } from "./authorizer.ts";-import { loadBiscuit } from "./biscuit.ts";+import { BiscuitVerificationError, attenuateBiscuit, loadBiscuit, sealBiscuit } from "./biscuit.ts";import { BASELINE_DATALOG } from "./gen/datalog.ts";type Wasm = Awaited<ReturnType<typeof loadBiscuit>>;@@ -172,3 +174,113 @@ test("every baseline item parses in biscuit-wasm", () => {wasm.Policy.fromString(p);}});++interface TARConformanceVector {+ name: string;+ biscuit_b64: string;+ target_service: string;+ protocol: string;+ method?: string;+ path?: string;+ mcp_tool?: string;+ allow: boolean;+ expected_effective_expiration?: string;+}++const tarSuite = JSON.parse(readFileSync(new URL("../../testdata/tar_conformance.json", import.meta.url), "utf8")) as {+ public_key_b64: string;+ caller_peer_id: string;+ provider_biscuit_b64: string;+ evaluation_time: string;+ policy_datalog_rules: string[];+ vectors: TARConformanceVector[];+};++for (const vec of tarSuite.vectors) {+ test(`tar conformance: ${vec.name}`, async () => {+ const rootPub = new Uint8Array(Buffer.from(tarSuite.public_key_b64, "base64"));+ const providerBiscuit = new Uint8Array(Buffer.from(tarSuite.provider_biscuit_b64, "base64"));+ const biscuitBytes = new Uint8Array(Buffer.from(vec.biscuit_b64, "base64"));+ const evalNow = new Date(tarSuite.evaluation_time);+ const req: AuthorizeRequest = {+ biscuit: biscuitBytes,+ peerId: tarSuite.caller_peer_id,+ targetService: vec.target_service,+ protocol: vec.protocol,+ ...(vec.method !== undefined ? { method: vec.method, path: vec.path ?? "" } : {}),+ ...(vec.mcp_tool !== undefined ? { mcpTool: vec.mcp_tool } : {}),+ };+ const opts = {+ trustedKeys: () => [rootPub],+ ownBiscuit: () => providerBiscuit,+ policyRules: () => tarSuite.policy_datalog_rules,+ now: () => evalNow,+ };+ if (!vec.allow) {+ await assert.rejects(authorizeCaller(req, opts), AuthorizationError);+ return;+ }+ const verified = await authorizeCaller(req, opts);+ assert.equal(verified.peerId, tarSuite.caller_peer_id);+ if (vec.expected_effective_expiration !== undefined) {+ assert.equal(verified.expiration.getTime(), new Date(vec.expected_effective_expiration).getTime());+ }+ });+}++test("attenuateBiscuit and sealBiscuit narrow authority across hops", async () => {+ const root = nodeToken(CALLER, [`granted_service_all_types(true)`, `target_unrestricted(true)`]);+ const hop1Exp = new Date("2034-05-01T00:00:00Z");+ const hop2Exp = new Date("2034-02-01T00:00:00Z");++ const att1 = await attenuateBiscuit(+ root,+ {+ name: "hop-1",+ expireTime: timestampFromDate(hop1Exp),+ rules: [+ {+ allowedServices: ["mcp://calc"],+ operation: { allowedTools: ["add", "multiply"] },+ },+ ],+ },+ [cpKey],+ );+ const att2 = await attenuateBiscuit(+ att1,+ {+ name: "hop-2",+ expireTime: timestampFromDate(hop2Exp),+ rules: [+ {+ allowedServices: ["mcp://calc"],+ operation: { allowedTools: ["add"] },+ },+ ],+ },+ [cpKey],+ );+ const sealed = await sealBiscuit(att2, [cpKey]);++ const verified = await authorizeCaller({ ...request(sealed, "mcp://calc"), mcpTool: "add" }, options([]));+ assert.equal(verified.expiration.getTime(), hop2Exp.getTime());+ assert.equal(verified.taskRules.length, 2);++ await assert.rejects(+ authorizeCaller({ ...request(sealed, "mcp://calc"), mcpTool: "multiply" }, options([])),+ AuthorizationError,+ );+ await assert.rejects(+ attenuateBiscuit(+ sealed,+ {+ name: "hop-3",+ rules: [{ allowedServices: ["mcp://calc"] }],+ },+ [cpKey],+ ),+ BiscuitVerificationError,+ );+});+diff --git a/sdk/js/src/authorizer.ts b/sdk/js/src/authorizer.tsindex 97489d5a..434fd55b 100644--- a/sdk/js/src/authorizer.ts+++ b/sdk/js/src/authorizer.ts@@ -20,6 +20,7 @@import { AUTHORIZER_LIMITS, BiscuitVerificationError, loadBiscuit, verifyPeerBiscuit, withinLimits, type VerifiedBiscuit } from "./biscuit.ts";import { parseServiceTarget } from "./discovery.ts";import { BASELINE_DATALOG } from "./gen/datalog.ts";+import { evaluateTaskRules } from "./tar.ts";/** What a caller asks for, as sam-node's RequestContext. */export interface AuthorizeRequest {@@ -39,6 +40,8 @@ export interface AuthorizeRequest {*/method?: string;path?: string;+ /** The MCP tool name when evaluating a specific MCP tools/call invocation. */+ mcpTool?: string;}export interface ProviderAuthorizerOptions {@@ -88,7 +91,7 @@ export async function authorizeCaller(req: AuthorizeRequest, options: ProviderAuthrow new AuthorizationError(req.peerId, "no trusted control plane key");}- // Signature under a trusted key, authority block only, expiry and binding+ // Signature under a trusted key, authority block + tar_block chain, expiry and binding// to the connection peer: RequireAuthorityBinding and EnforceExpiration.let caller: VerifiedBiscuit;try {@@ -163,6 +166,27 @@ export async function authorizeCaller(req: AuthorizeRequest, options: ProviderAu} catch (err) {throw new AuthorizationError(req.peerId, describe(err));}++ if (caller.taskRules.length > 0) {+ const mcpTool = req.mcpTool ?? "";+ try {+ evaluateTaskRules(+ caller.taskRules,+ {+ serviceType: svcType,+ serviceName: svcName,+ hasHttp: req.method !== undefined,+ method: req.method ?? "",+ path: req.path ?? "",+ mcpTool,+ allowMCPStreamInit: req.method === undefined && mcpTool === "" && req.protocol === "/sam/mcp/1.0.0",+ },+ now,+ );+ } catch (err) {+ throw new AuthorizationError(req.peerId, describe(err));+ }+ }return caller;}diff --git a/sdk/js/src/biscuit.ts b/sdk/js/src/biscuit.tsindex 629aa904..18d3cd0e 100644--- a/sdk/js/src/biscuit.ts+++ b/sdk/js/src/biscuit.ts@@ -13,10 +13,14 @@// limitations under the License.// Verification of a peer's biscuit, mirroring internal/identity.verifyBiscuit:-// signed by a trusted control plane key, authority block only, unexpired,-// and bound to the peer at the other end of the connection.+// signed by a trusted control plane key, authority block + validated tar_block+// chain, unexpired, and bound to the peer at the other end of the connection.+import type { MessageInitShape } from "@bufbuild/protobuf";+import { BASELINE_DATALOG } from "./gen/datalog.ts";+import { TaskAuthorizationRuleSchema, type TaskAuthorizationRule } from "./gen/sam_pb.ts";import { loadBiscuitWasm, type BiscuitWasm } from "./platform/wasm.ts";+import { effectiveTARExpiration, encodeTARBlockFact, parseTARBlockSource } from "./tar.ts";let loading: Promise<BiscuitWasm> | undefined;@@ -69,12 +73,14 @@ export class BiscuitVerificationError extends Error {export interface VerifiedBiscuit {/** The peer the token is bound to (its node() fact). */peerId: string;- /** When the token lapses; the earliest expiration() fact. */+ /** When the token lapses; the minimum of authority expiration() and any tar_block expire_time. */expiration: Date;/** The trusted key that verified the signature. */verifyingKey: Uint8Array;roles: string[];labels: Record<string, string>;+ /** Verified TaskAuthorizationRule chain from blocks 1..N (empty for unattenuated tokens). */+ taskRules: TaskAuthorizationRule[];}function describe(err: unknown): string {@@ -90,22 +96,14 @@ function describe(err: unknown): string {type QueriedFact = { terms(): unknown[] };-/**- * 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.- */-export async function verifyPeerBiscuit(+function parseWithTrustedKeys(+ wasm: BiscuitWasm,biscuitBytes: Uint8Array,- expectedPeerId: string,trustedKeys: Uint8Array[],- now: Date = new Date(),-): Promise<VerifiedBiscuit> {- const wasm = await loadBiscuit();+): { token: ReturnType<BiscuitWasm["Biscuit"]["fromBytes"]>; verifyingKey: Uint8Array } {if (trustedKeys.length === 0) {throw new BiscuitVerificationError("no trusted control plane key to verify against");}-let token: ReturnType<BiscuitWasm["Biscuit"]["fromBytes"]> | undefined;let verifyingKey: Uint8Array | undefined;let lastErr: unknown;@@ -121,12 +119,41 @@ export async function verifyPeerBiscuit(if (!token || !verifyingKey) {throw new BiscuitVerificationError(`biscuit is not signed by a trusted control plane key: ${describe(lastErr)}`);}+ return { token, verifyingKey };+}- // Appending needs no root key, so appended blocks are the one place a- // holder can put Datalog of their own. SAM tokens are authority-only.- if (token.countBlocks() !== 1) {- throw new BiscuitVerificationError(`biscuit carries appended blocks; SAM tokens are authority-block only (${token.countBlocks() - 1})`);+function extractTARChain(token: ReturnType<BiscuitWasm["Biscuit"]["fromBytes"]>): TaskAuthorizationRule[] {+ const appendedCount = token.countBlocks() - 1;+ if (appendedCount > BASELINE_DATALOG.max_attenuation_blocks) {+ throw new BiscuitVerificationError(+ `biscuit carries ${appendedCount} appended blocks; maximum is ${BASELINE_DATALOG.max_attenuation_blocks}`,+ );+ }+ const taskRules: TaskAuthorizationRule[] = [];+ for (let i = 1; i <= appendedCount; i++) {+ try {+ taskRules.push(parseTARBlockSource(token.getBlockSource(i)));+ } catch (err) {+ throw new BiscuitVerificationError(`biscuit block ${i}: ${describe(err)}`);+ }}+ return taskRules;+}++/**+ * 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.+ */+export async function verifyPeerBiscuit(+ biscuitBytes: Uint8Array,+ expectedPeerId: string,+ trustedKeys: Uint8Array[],+ now: Date = new Date(),+): Promise<VerifiedBiscuit> {+ const wasm = await loadBiscuit();+ const { token, verifyingKey } = parseWithTrustedKeys(wasm, biscuitBytes, trustedKeys);+ const taskRules = extractTARChain(token);const builder = new wasm.AuthorizerBuilder();builder.addFact(wasm.Fact.fromString(`time(${now.toISOString().replace(/\.\d{3}Z$/, "Z")})`));@@ -153,7 +180,13 @@ export async function verifyPeerBiscuit(if (expirations.length === 0) {throw new BiscuitVerificationError("biscuit carries no expiration fact");}- const expiration = new Date(Math.min(...expirations.map((d) => d.getTime())));+ const authorityExpiration = new Date(Math.min(...expirations.map((d) => d.getTime())));+ const expiration = effectiveTARExpiration(authorityExpiration, taskRules);+ if (now.getTime() > expiration.getTime()) {+ throw new BiscuitVerificationError(+ `biscuit is expired at ${now.toISOString()} (effective expiration ${expiration.toISOString()})`,+ );+ }const labels: Record<string, string> = {};for (const f of query("l($k, $v) <- label($k, $v)")) {@@ -163,7 +196,56 @@ export async function verifyPeerBiscuit(}}- return { peerId: expectedPeerId, expiration, verifyingKey, roles: strings(query("r($r) <- role($r)")), labels };+ return {+ peerId: expectedPeerId,+ expiration,+ verifyingKey,+ roles: strings(query("r($r) <- role($r)")),+ labels,+ taskRules,+ };+}++/**+ * Appends a non-authority block carrying a single tar_block("<base64url-proto>")+ * fact to an existing Biscuit token in memory without contacting the control plane.+ */+export async function attenuateBiscuit(+ biscuitBytes: Uint8Array,+ ruleInput: MessageInitShape<typeof TaskAuthorizationRuleSchema>,+ trustedKeys: Uint8Array[],+): Promise<Uint8Array> {+ const wasm = await loadBiscuit();+ const { token } = parseWithTrustedKeys(wasm, biscuitBytes, trustedKeys);+ const appendedCount = token.countBlocks() - 1;+ if (appendedCount >= BASELINE_DATALOG.max_attenuation_blocks) {+ throw new BiscuitVerificationError(+ `biscuit already has ${appendedCount} appended blocks (maximum ${BASELINE_DATALOG.max_attenuation_blocks})`,+ );+ }+ extractTARChain(token);+ const factStr = encodeTARBlockFact(ruleInput);+ const block = wasm.Biscuit.block_builder();+ block.addFact(wasm.Fact.fromString(factStr));+ try {+ return token.appendBlock(block).toBytes();+ } catch (err) {+ throw new BiscuitVerificationError(`failed to append tar_block to biscuit: ${describe(err)}`);+ }+}++/**+ * Seals a Biscuit token so no further blocks can be appended by downstream holders.+ */+export async function sealBiscuit(biscuitBytes: Uint8Array, trustedKeys: Uint8Array[]): Promise<Uint8Array> {+ const wasm = await loadBiscuit();+ const { token } = parseWithTrustedKeys(wasm, biscuitBytes, trustedKeys);+ extractTARChain(token);+ try {+ return token.sealToken().toBytes();+ } catch (err) {+ throw new BiscuitVerificationError(`failed to seal biscuit: ${describe(err)}`);+ }}/** Requires role(<role>) on an already verified token, as identity.RequireRole. */@@ -172,3 +254,4 @@ export function requireRole(verified: VerifiedBiscuit, role: string): void {throw new BiscuitVerificationError(`biscuit lacks expected role ${JSON.stringify(role)}`);}}+diff --git a/sdk/js/src/bytes.ts b/sdk/js/src/bytes.tsindex f33245f2..fb22dad2 100644--- a/sdk/js/src/bytes.ts+++ b/sdk/js/src/bytes.ts@@ -42,6 +42,10 @@ export function toBase64Url(bytes: Uint8Array): string {return toString(bytes, "base64url");}+export function fromBase64Url(text: string): Uint8Array {+ return fromString(text, "base64url");+}+export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {return a.length === b.length && a.every((v, i) => v === b[i]);}diff --git a/sdk/js/src/gen/datalog.ts b/sdk/js/src/gen/datalog.tsindex 89a995d1..2a8ee060 100644--- a/sdk/js/src/gen/datalog.ts+++ b/sdk/js/src/gen/datalog.ts@@ -49,6 +49,16 @@ export const BASELINE_DATALOG = {"fact_time": "time","fact_role": "role","fact_target_fact": "target_fact",+ "fact_tar_block": "tar_block",+ "tar_block_source_pattern": "^tar_block\\(\"([A-Za-z0-9_-]+)\"\\);?\\s*$",+ "http_method_syntax": "^[A-Z][A-Z0-9-]{0,31}$",+ "max_attenuation_blocks": 8,+ "max_tar_bytes": 4096,+ "max_rules_per_tar": 16,+ "max_entries_per_tar_list": 64,+ "max_tar_name_length": 128,+ "max_tar_description_length": 256,+ "max_tar_resource_length": 256,"marker_term": "true","system_namespace": "sam:system","binding_member_prefixes": [diff --git a/sdk/js/src/gen/sam_pb.ts b/sdk/js/src/gen/sam_pb.tsindex 8e2a440c..8bbe0a00 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/CgxBdXRoUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCRIPCgdiaXNjdWl0GAMgASgMItYBCglNZXNoRXZlbnQSJAoEdHlwZRgBIAEoDjIWLnNhbS52MS5NZXNoRXZlbnQuVHlwZRIPCgdwZWVyX2lkGAIgASgJEi4KCmV2ZW50X3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEhYKDm5ld19wdWJsaWNfa2V5GAQgASgMEhEKCXNpZ25hdHVyZRgFIAEoDCI3CgRUeXBlEgoKBkJBTk5FRBAAEhAKDEtFWV9ST1RBVElPThABEhEKDVBPTElDWV9VUERBVEUQAiLzAQoNRW5yb2xsUmVxdWVzdBILCgNqd3QYASABKAkSDwoHcGVlcl9pZBgCIAEoCRISCgpwdWJsaWNfa2V5GAMgASgMEhYKDnJlcXVlc3RlZF9yb2xlGAQgASgJEjEKBmxhYmVscxgFIAMoCzIhLnNhbS52MS5FbnJvbGxSZXF1ZXN0LkxhYmVsc0VudHJ5EhkKEWNoYWxsZW5nZV91bml4X21zGAYgASgDEhsKE2NoYWxsZW5nZV9zaWduYXR1cmUYByABKAw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HEAESHgoaRU5ST0xMTUVOVF9TVEFUVVNfQVBQUk9WRUQQAhIeChpFTlJPTExNRU5UX1NUQVRVU19SRUpFQ1RFRBADKowBCgtTZXJ2aWNlVHlwZRIcChhTRVJWSUNFX1RZUEVfVU5TUEVDSUZJRUQQABIUChBTRVJWSUNFX1RZUEVfTUNQEAESGgoWU0VSVklDRV9UWVBFX0lORkVSRU5DRRACEhQKEFNFUlZJQ0VfVFlQRV9BMkEQAxIXChNTRVJWSUNFX1RZUEVfRUdSRVNTEARCG1oZZ2l0aHViLmNvbS9nb29nbGUvc2FtL2FwaWIGcHJvdG8z", [file_google_protobuf_timestamp]);/*** @generated from message sam.v1.AuthFrame@@ -1353,6 +1353,136 @@ export type OIDCSession = Message<"sam.v1.OIDCSession"> & {export const OIDCSessionSchema: GenMessage<OIDCSession> = /*@__PURE__*/messageDesc(file_sam, 35);+/**+ * TaskAuthorizationRule narrows a credential's authority for a specific task or+ * sub-agent hop. Across multiple appended blocks (1..k), semantics are strict+ * set intersection (logical AND): a request is permitted only if it is allowed+ * by the standing mesh policy AND is before every block's expire_time AND+ * matches at least one TaskRule in EVERY appended TaskAuthorizationRule block.+ *+ * @generated from message sam.v1.TaskAuthorizationRule+ */+export type TaskAuthorizationRule = Message<"sam.v1.TaskAuthorizationRule"> & {+ /**+ * @generated from field: string name = 1;+ */+ name: string;++ /**+ * @generated from field: string display_name = 2;+ */+ displayName: string;++ /**+ * Positive allow-list of rules for this hop. Empty rules list denies everything.+ *+ * @generated from field: repeated sam.v1.TaskRule rules = 3;+ */+ rules: TaskRule[];++ /**+ * Optional shorter expiration for this task hop. Effective token expiry is+ * the minimum across the authority block's expiration() fact and every+ * appended block's expire_time.+ *+ * @generated from field: google.protobuf.Timestamp expire_time = 4;+ */+ expireTime?: Timestamp | undefined;+};++/**+ * Describes the message sam.v1.TaskAuthorizationRule.+ * Use `create(TaskAuthorizationRuleSchema)` to create a new message.+ */+export const TaskAuthorizationRuleSchema: GenMessage<TaskAuthorizationRule> = /*@__PURE__*/+ messageDesc(file_sam, 36);++/**+ * @generated from message sam.v1.TaskRule+ */+export type TaskRule = Message<"sam.v1.TaskRule"> & {+ /**+ * @generated from field: string description = 1;+ */+ description: string;++ /**+ * Allowed mesh services (e.g., "mcp://bigquery", "inference://gemini.*",+ * "egress://bigquery.googleapis.com"). Uses the dot-anchored grammar of+ * api.ValidateServiceFormat ("*", "<type>://*", "<type>://*.<suffix>",+ * "<type>://<prefix>.*", "<type>://<exact>"). Required (non-empty).+ *+ * @generated from field: repeated string allowed_services = 2;+ */+ allowedServices: string[];++ /**+ * Optional operation-level allow-list. If set, the request must also match+ * the specified MCP tools, HTTP methods/paths, or cloud permissions.+ *+ * @generated from field: sam.v1.TaskOperation operation = 3;+ */+ operation?: TaskOperation | undefined;++ /**+ * Optional allowed upstream resource names (e.g. CRM resource prefixes+ * "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026").+ * Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.+ *+ * @generated from field: repeated string allowed_resources = 4;+ */+ allowedResources: string[];+};++/**+ * Describes the message sam.v1.TaskRule.+ * Use `create(TaskRuleSchema)` to create a new message.+ */+export const TaskRuleSchema: GenMessage<TaskRule> = /*@__PURE__*/+ messageDesc(file_sam, 37);++/**+ * @generated from message sam.v1.TaskOperation+ */+export type TaskOperation = Message<"sam.v1.TaskOperation"> & {+ /**+ * Allowed MCP tool names (enforced by the PEP on mcp:// tools/call).+ *+ * @generated from field: repeated string allowed_tools = 1;+ */+ allowedTools: string[];++ /**+ * Allowed HTTP methods (e.g. ["GET", "POST"]), validated with httpMethodSyntax.+ *+ * @generated from field: repeated string allowed_methods = 2;+ */+ allowedMethods: string[];++ /**+ * Allowed HTTP path patterns ("/exact" or "/prefix/*"), validated with+ * validateHTTPGrantPath.+ *+ * @generated from field: repeated string allowed_paths = 3;+ */+ allowedPaths: string[];++ /**+ * Allowed cloud IAM permissions (e.g. "bigquery.googleapis.com/datasets.get").+ * Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.+ *+ * @generated from field: repeated string allowed_permissions = 4;+ */+ allowedPermissions: string[];+};++/**+ * Describes the message sam.v1.TaskOperation.+ * Use `create(TaskOperationSchema)` to create a new message.+ */+export const TaskOperationSchema: GenMessage<TaskOperation> = /*@__PURE__*/+ messageDesc(file_sam, 38);+/*** @generated from enum sam.v1.EnrollmentStatus*/diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.tsindex c0870713..112b4004 100644--- a/sdk/js/src/index.ts+++ b/sdk/js/src/index.ts@@ -40,7 +40,31 @@ export {} from "./credential.ts";export { enrollChallenge, enrollStatusChallenge, refreshChallenge, registerChallenge } from "./challenges.ts";export { MeshSession, type AdmittedRouter, type DiscoveredProvider, type JoinOptions, type Peer, type ToolCallResult } from "./session.ts";-export { BiscuitVerificationError, ROLE_ROUTER, requireRole, verifyPeerBiscuit, type VerifiedBiscuit } from "./biscuit.ts";+export {+ BiscuitVerificationError,+ ROLE_ROUTER,+ attenuateBiscuit,+ requireRole,+ sealBiscuit,+ verifyPeerBiscuit,+ type VerifiedBiscuit,+} from "./biscuit.ts";+export {+ decodeTARBlockPayload,+ effectiveTARExpiration,+ encodeTARBlockFact,+ encodeTARBlockPayload,+ evaluateTaskRules,+ matchHTTPPath,+ matchServicePattern,+ matchTaskRule,+ parseTARBlockSource,+ validateHTTPGrantPath,+ validateServicePattern,+ validateTaskAuthorizationRule,+ validateTaskRule,+ type TaskRequestContext,+} from "./tar.ts";export { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, MCP_PROTOCOL, AuthRejectedError, authenticateWithPeer, authStreamHandler } from "./auth.ts";export { createMeshHost, type MeshHost, type MeshHostOptions } from "./host.ts";export { DHT_PROTOCOL, isServiceType, parseServiceTarget, serviceCID, type ServiceType } from "./discovery.ts";diff --git a/sdk/js/src/mcp.test.ts b/sdk/js/src/mcp.test.tsindex 5d70379f..86f450b2 100644--- a/sdk/js/src/mcp.test.ts+++ b/sdk/js/src/mcp.test.ts@@ -166,12 +166,12 @@ test("required labels are checked on the provider's credential", async () => {const ok = await openMCPSession(conn, frame("mcp://calc"), [cpKey], { requiredLabels: { region: "eu" } });await ok.close();await assert.rejects(openMCPSession(conn, frame("mcp://calc"), [cpKey], { requiredLabels: { region: "us" } }), LabelsNotSatisfiedError);- assert.throws(() => requireLabels({ peerId: "p", expiration: new Date(), verifyingKey: cpKey, roles: [], labels: {} }, { team: "x" }), /team=x/);+ assert.throws(() => requireLabels({ peerId: "p", expiration: new Date(), verifyingKey: cpKey, roles: [], labels: {}, taskRules: [] }, { team: "x" }), /team=x/);});test("a requirement of several labels is met only by every one of them, as sam-node's checkPeerLabels", () => {// The cases of internal/node/labels_gate_test.go, run through the SDK's predicate.- const attesting = (labels: Record<string, string>) => ({ peerId: "p", expiration: new Date(), verifyingKey: cpKey, roles: [], labels });+ const attesting = (labels: Record<string, string>) => ({ peerId: "p", expiration: new Date(), verifyingKey: cpKey, roles: [], labels, taskRules: [] });// exact matchrequireLabels(attesting({ region: "us-east-1" }), { region: "us-east-1" });// every pair of two attested@@ -192,7 +192,7 @@ test("a requirement of several labels is met only by every one of them, as sam-n});test("the egress floor is met only by every one of its pairs, as sam-node's api.LabelCheck", () => {- const attesting = (labels: Record<string, string>) => ({ peerId: "p", expiration: new Date(), verifyingKey: cpKey, roles: [], labels });+ const attesting = (labels: Record<string, string>) => ({ peerId: "p", expiration: new Date(), verifyingKey: cpKey, roles: [], labels, taskRules: [] });requireEgressLabels(attesting({ region: "eu", team: "platform" }), { region: "eu" });requireEgressLabels(attesting({ region: "eu", team: "platform" }), { region: "eu", team: "platform" });// one pair short is a refusal that names the whole floordiff --git a/sdk/js/src/tar.ts b/sdk/js/src/tar.tsnew file mode 100644index 00000000..b3670a64--- /dev/null+++ b/sdk/js/src/tar.ts@@ -0,0 +1,356 @@+// 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.++import { create, fromBinary, toBinary, type MessageInitShape } from "@bufbuild/protobuf";+import { timestampDate } from "@bufbuild/protobuf/wkt";+import { fromBase64Url, toBase64Url } from "./bytes.ts";+import { isServiceType } from "./discovery.ts";+import { BASELINE_DATALOG } from "./gen/datalog.ts";+import { TaskAuthorizationRuleSchema, type TaskAuthorizationRule, type TaskRule } from "./gen/sam_pb.ts";++const TAR_BLOCK_SOURCE_RE = new RegExp(BASELINE_DATALOG.tar_block_source_pattern);+const HTTP_METHOD_RE = new RegExp(BASELINE_DATALOG.http_method_syntax);+const TEXT_ENCODER = new TextEncoder();++function utf8Length(s: string): number {+ return TEXT_ENCODER.encode(s).length;+}++function countChar(s: string, ch: string): number {+ let count = 0;+ for (let i = 0; i < s.length; i++) {+ if (s[i] === ch) {+ count++;+ }+ }+ return count;+}++export function validateServicePattern(s: string): void {+ if (s === "*") {+ return;+ }+ const idx = s.indexOf("://");+ if (idx <= 0) {+ throw new Error(`invalid service format: ${s}`);+ }+ const serviceType = s.slice(0, idx);+ const target = s.slice(idx + 3);+ if (!isServiceType(serviceType) && serviceType !== "http") {+ throw new Error(`invalid service type "${serviceType}" in ${s}`);+ }+ if (target === "" || target.includes("/") || countChar(target, "*") > 1) {+ throw new Error(`invalid service target "${target}" in ${s}`);+ }+ if (target.includes("*") && target !== "*") {+ const validSuffix = target.startsWith("*.") && target.slice(2).length > 0;+ const validPrefix = target.endsWith(".*") && target.slice(0, -2).length > 0;+ if (!validSuffix && !validPrefix) {+ throw new Error(`wildcard in "${s}" must be '*', '*.<suffix>' or '<prefix>.*'`);+ }+ }+}++export function validateHTTPGrantPath(p: string): void {+ if (!p.startsWith("/")) {+ throw new Error(`path ${JSON.stringify(p)} must start with '/'`);+ }+ if (p.includes("?") || p.includes("#")) {+ throw new Error(`path ${JSON.stringify(p)} must not contain '?' or '#'`);+ }+ const stars = countChar(p, "*");+ if (stars > 1 || (stars === 1 && !p.endsWith("*"))) {+ throw new Error(`path ${JSON.stringify(p)}: '*' is only valid once, at the end`);+ }+ for (const seg of p.slice(1).split("/")) {+ if (seg === "." || seg === "..") {+ throw new Error(`path ${JSON.stringify(p)} must not contain '.' or '..' segments`);+ }+ }+}++function validateTARStringList(fieldName: string, values: string[], checkElem: (v: string) => void): void {+ if (values.length > BASELINE_DATALOG.max_entries_per_tar_list) {+ throw new Error(`TaskRule.${fieldName} has ${values.length} entries; maximum is ${BASELINE_DATALOG.max_entries_per_tar_list}`);+ }+ for (const [i, val] of values.entries()) {+ try {+ checkElem(val);+ } catch (err) {+ throw new Error(`TaskRule.${fieldName}[${i}]: ${err instanceof Error ? err.message : String(err)}`);+ }+ }+}++export function validateTaskRule(r: TaskRule): void {+ if (utf8Length(r.description) > BASELINE_DATALOG.max_tar_description_length) {+ throw new Error(`TaskRule.description exceeds ${BASELINE_DATALOG.max_tar_description_length} bytes`);+ }+ validateTARStringList("allowed_services", r.allowedServices, validateServicePattern);+ validateTARStringList("allowed_resources", r.allowedResources, (res) => {+ if (res === "") {+ throw new Error("resource must not be empty");+ }+ if (utf8Length(res) > BASELINE_DATALOG.max_tar_resource_length) {+ throw new Error(`resource exceeds ${BASELINE_DATALOG.max_tar_resource_length} bytes`);+ }+ });+ if (r.operation !== undefined) {+ const op = r.operation;+ validateTARStringList("operation.allowed_tools", op.allowedTools, (tool) => {+ if (tool === "") {+ throw new Error("tool name must not be empty");+ }+ });+ validateTARStringList("operation.allowed_methods", op.allowedMethods, (m) => {+ if (!HTTP_METHOD_RE.test(m)) {+ throw new Error(`invalid HTTP method ${JSON.stringify(m)}`);+ }+ if (m === "CONNECT") {+ throw new Error("CONNECT is not a grantable HTTP method");+ }+ });+ validateTARStringList("operation.allowed_paths", op.allowedPaths, validateHTTPGrantPath);+ validateTARStringList("operation.allowed_permissions", op.allowedPermissions, (perm) => {+ if (perm === "") {+ throw new Error("permission must not be empty");+ }+ });+ }+}++export function validateTaskAuthorizationRule(rule: TaskAuthorizationRule, requireNonEmptyRules: boolean): void {+ if (utf8Length(rule.name) > BASELINE_DATALOG.max_tar_name_length) {+ throw new Error(`TaskAuthorizationRule.name exceeds ${BASELINE_DATALOG.max_tar_name_length} bytes`);+ }+ if (utf8Length(rule.displayName) > BASELINE_DATALOG.max_tar_description_length) {+ throw new Error(`TaskAuthorizationRule.display_name exceeds ${BASELINE_DATALOG.max_tar_description_length} bytes`);+ }+ if (requireNonEmptyRules && rule.rules.length === 0) {+ throw new Error("TaskAuthorizationRule.rules must not be empty");+ }+ if (rule.rules.length > BASELINE_DATALOG.max_rules_per_tar) {+ throw new Error(`TaskAuthorizationRule.rules has ${rule.rules.length} entries; maximum is ${BASELINE_DATALOG.max_rules_per_tar}`);+ }+ for (const [i, r] of rule.rules.entries()) {+ try {+ validateTaskRule(r);+ } catch (err) {+ throw new Error(`TaskAuthorizationRule.rules[${i}]: ${err instanceof Error ? err.message : String(err)}`);+ }+ }+}++function hasUnknownWireFields(rule: TaskAuthorizationRule): boolean {+ const unknownOf = (msg: unknown): boolean => {+ if (typeof msg !== "object" || msg === null) {+ return false;+ }+ const unk = (msg as { $unknown?: unknown[] }).$unknown;+ return Array.isArray(unk) && unk.length > 0;+ };+ if (unknownOf(rule) || unknownOf(rule.expireTime)) {+ return true;+ }+ for (const r of rule.rules) {+ if (unknownOf(r) || unknownOf(r.operation)) {+ return true;+ }+ }+ return false;+}++export function encodeTARBlockPayload(ruleInput: MessageInitShape<typeof TaskAuthorizationRuleSchema>): string {+ const rule = create(TaskAuthorizationRuleSchema, ruleInput);+ validateTaskAuthorizationRule(rule, true);+ const raw = toBinary(TaskAuthorizationRuleSchema, rule);+ if (raw.length > BASELINE_DATALOG.max_tar_bytes) {+ throw new Error(`TaskAuthorizationRule serialized size ${raw.length} exceeds ${BASELINE_DATALOG.max_tar_bytes} bytes`);+ }+ return toBase64Url(raw);+}++export function encodeTARBlockFact(ruleInput: MessageInitShape<typeof TaskAuthorizationRuleSchema>): string {+ const b64 = encodeTARBlockPayload(ruleInput);+ return `${BASELINE_DATALOG.fact_tar_block}(${JSON.stringify(b64)})`;+}++export function decodeTARBlockPayload(b64Payload: string): TaskAuthorizationRule {+ if (b64Payload === "") {+ throw new Error("empty tar_block payload");+ }+ let raw: Uint8Array;+ try {+ raw = fromBase64Url(b64Payload);+ } catch (err) {+ throw new Error(`invalid base64url in tar_block: ${err instanceof Error ? err.message : String(err)}`);+ }+ if (toBase64Url(raw) !== b64Payload) {+ throw new Error("non-canonical base64url in tar_block");+ }+ if (raw.length === 0 || raw.length > BASELINE_DATALOG.max_tar_bytes) {+ throw new Error(`tar_block decoded payload size ${raw.length} out of bounds [1, ${BASELINE_DATALOG.max_tar_bytes}]`);+ }+ let rule: TaskAuthorizationRule;+ try {+ rule = fromBinary(TaskAuthorizationRuleSchema, raw);+ } catch (err) {+ throw new Error(`invalid TaskAuthorizationRule protobuf in tar_block: ${err instanceof Error ? err.message : String(err)}`);+ }+ if (hasUnknownWireFields(rule)) {+ throw new Error("TaskAuthorizationRule in tar_block contains unknown protobuf wire fields");+ }+ validateTaskAuthorizationRule(rule, false);+ return rule;+}++export function parseTARBlockSource(blockSource: string): TaskAuthorizationRule {+ const m = TAR_BLOCK_SOURCE_RE.exec(blockSource.trim());+ if (!m || m[1] === undefined) {+ throw new Error(`non-authority block does not match single tar_block("<base64url>") grammar`);+ }+ return decodeTARBlockPayload(m[1]);+}++export function effectiveTARExpiration(authorityExpiration: Date, rules: TaskAuthorizationRule[]): Date {+ let effective = authorityExpiration;+ for (const r of rules) {+ if (r.expireTime !== undefined) {+ const exp = timestampDate(r.expireTime);+ if (exp.getTime() < effective.getTime()) {+ effective = exp;+ }+ }+ }+ return effective;+}++export interface TaskRequestContext {+ serviceType: string;+ serviceName: string;+ hasHttp: boolean;+ method: string;+ path: string;+ mcpTool: string;+ allowMCPStreamInit: boolean;+ resource?: string;+ permission?: string;+}++export function matchServicePattern(pattern: string, serviceType: string, serviceName: string): boolean {+ if (serviceType === "" || serviceName === "") {+ return false;+ }+ if (pattern === "*") {+ return true;+ }+ const idx = pattern.indexOf("://");+ if (idx <= 0) {+ return false;+ }+ const patType = pattern.slice(0, idx);+ const patTarget = pattern.slice(idx + 3);+ if (patType !== serviceType) {+ return false;+ }+ if (patTarget === "*") {+ return true;+ }+ if (patTarget.startsWith("*.")) {+ return serviceName.endsWith(patTarget.slice(1));+ }+ if (patTarget.endsWith(".*")) {+ return serviceName.startsWith(patTarget.slice(0, -1));+ }+ return serviceName === patTarget;+}++export function matchHTTPPath(pattern: string, reqPath: string): boolean {+ if (reqPath === "") {+ return false;+ }+ if (pattern.endsWith("*")) {+ return reqPath.startsWith(pattern.slice(0, -1));+ }+ return reqPath === pattern;+}++export function matchTaskRule(rule: TaskRule, req: TaskRequestContext): boolean {+ if (rule.allowedServices.length > 0) {+ if (!rule.allowedServices.some((pat) => matchServicePattern(pat, req.serviceType, req.serviceName))) {+ return false;+ }+ }+ if (rule.allowedResources.length > 0) {+ const res = req.resource ?? "";+ if (res === "" || !rule.allowedResources.includes(res)) {+ return false;+ }+ }+ if (rule.operation !== undefined) {+ const op = rule.operation;+ if (op.allowedTools.length > 0) {+ if (req.serviceType !== "mcp") {+ return false;+ }+ if (req.mcpTool === "") {+ if (!req.allowMCPStreamInit) {+ return false;+ }+ } else if (!op.allowedTools.includes(req.mcpTool)) {+ return false;+ }+ }+ if (op.allowedMethods.length > 0) {+ if (!req.hasHttp || req.method === "" || req.method === "CONNECT") {+ return false;+ }+ if (!op.allowedMethods.includes(req.method)) {+ return false;+ }+ }+ if (op.allowedPaths.length > 0) {+ if (!req.hasHttp || req.path === "" || req.method === "CONNECT") {+ return false;+ }+ if (!op.allowedPaths.some((pat) => matchHTTPPath(pat, req.path))) {+ return false;+ }+ }+ if (op.allowedPermissions.length > 0) {+ const perm = req.permission ?? "";+ if (perm === "" || !op.allowedPermissions.includes(perm)) {+ return false;+ }+ }+ }+ return true;+}++export function evaluateTaskRules(chain: TaskAuthorizationRule[], req: TaskRequestContext, now: Date): void {+ for (const [i, tar] of chain.entries()) {+ if (tar.expireTime !== undefined) {+ const exp = timestampDate(tar.expireTime);+ if (now.getTime() > exp.getTime()) {+ throw new Error(`TaskAuthorizationRule block ${i + 1} (${JSON.stringify(tar.name)}) is expired`);+ }+ }+ if (tar.rules.length === 0) {+ throw new Error(`TaskAuthorizationRule block ${i + 1} (${JSON.stringify(tar.name)}) has no rules (fail-closed)`);+ }+ if (!tar.rules.some((rule) => matchTaskRule(rule, req))) {+ throw new Error(`request denied by TaskAuthorizationRule block ${i + 1} (${JSON.stringify(tar.name)})`);+ }+ }+}diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.pyindex e7275b6d..9fca06b6 100644--- a/sdk/python/src/agent_mesh/__init__.py+++ b/sdk/python/src/agent_mesh/__init__.py@@ -16,7 +16,7 @@from .auth import AUTH_PROTOCOL, MCP_PROTOCOL, AuthRejectedError, auth_stream_handler, authenticate_with_peerfrom .authorizer import BASELINE_DATALOG, AuthorizationError, AuthorizeRequest, ProviderAuthorizerOptions, authorize_caller-from .biscuit import ROLE_ROUTER, BiscuitVerificationError, VerifiedBiscuit, require_role, verify_peer_biscuit+from .biscuit import ROLE_ROUTER, BiscuitVerificationError, VerifiedBiscuit, attenuate_biscuit, require_role, verify_peer_biscuitfrom .challenges import enroll_challenge, enroll_status_challenge, refresh_challenge, register_challengefrom .controlplane import (ROLE_NODE,@@ -56,6 +56,22 @@ from .mesh import AgentMesh, ControlPlaneSync, CredentialRetiredErrorfrom .relay import dial_through_relay, reserve_relayfrom .session import AdmittedRouter, MeshSession, Peerfrom .sync import GOSSIP_EVENTS_TOPIC, BanSet, verify_mesh_event+from .tar import (+ TaskRequestContext,+ decode_tar_block_payload,+ effective_tar_expiration,+ encode_tar_block_fact,+ encode_tar_block_payload,+ evaluate_task_rules,+ match_http_path,+ match_service_pattern,+ match_task_rule,+ parse_tar_block_source,+ validate_http_grant_path,+ validate_service_pattern,+ validate_task_authorization_rule,+ validate_task_rule,+)__version__ = "0.1.0"@@ -101,27 +117,38 @@ __all__ = ["ROLE_ROUTER","RefreshResult","StreamedResponse",+ "TaskRequestContext","ToolCallResult","ToolInfo","VerifiedBiscuit",+ "attenuate_biscuit","auth_stream_handler","authenticate_with_peer","authorize_caller","canonical_peer_id","decode_auth_response",+ "decode_tar_block_payload","dial_through_relay",+ "effective_tar_expiration","encode_auth_frame",+ "encode_tar_block_fact",+ "encode_tar_block_payload","enroll_challenge","enroll_status_challenge",+ "evaluate_task_rules","find_providers","http_ingress_handler","http_request_over_stream","libp2p_public_key",+ "match_http_path",+ "match_service_pattern",+ "match_task_rule","mesh_http_target","mesh_url","open_http_request","open_mcp_session","parse_service_target",+ "parse_tar_block_source","peer_id_from_public_key","refresh_challenge","register_challenge",@@ -133,6 +160,10 @@ __all__ = ["rewrite_agent_card","split_mesh_url","validate_control_plane_url",+ "validate_http_grant_path",+ "validate_service_pattern",+ "validate_task_authorization_rule",+ "validate_task_rule","verify_ed25519","verify_keys_response","verify_mesh_event",diff --git a/sdk/python/src/agent_mesh/_gen/datalog.json b/sdk/python/src/agent_mesh/_gen/datalog.jsonindex b8aa9825..b3e52993 100644--- a/sdk/python/src/agent_mesh/_gen/datalog.json+++ b/sdk/python/src/agent_mesh/_gen/datalog.json@@ -46,6 +46,16 @@"fact_time": "time","fact_role": "role","fact_target_fact": "target_fact",+ "fact_tar_block": "tar_block",+ "tar_block_source_pattern": "^tar_block\\(\"([A-Za-z0-9_-]+)\"\\);?\\s*$",+ "http_method_syntax": "^[A-Z][A-Z0-9-]{0,31}$",+ "max_attenuation_blocks": 8,+ "max_tar_bytes": 4096,+ "max_rules_per_tar": 16,+ "max_entries_per_tar_list": 64,+ "max_tar_name_length": 128,+ "max_tar_description_length": 256,+ "max_tar_resource_length": 256,"marker_term": "true","system_namespace": "sam:system","binding_member_prefixes": [diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.py b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyindex 5eb08989..5425f287 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*\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*\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=4734- _ENROLLMENTSTATUS._serialized_end=4882- _SERVICETYPE._serialized_start=4885- _SERVICETYPE._serialized_end=5025+ _ENROLLMENTSTATUS._serialized_start=5123+ _ENROLLMENTSTATUS._serialized_end=5271+ _SERVICETYPE._serialized_start=5274+ _SERVICETYPE._serialized_end=5414_AUTHFRAME._serialized_start=54_AUTHFRAME._serialized_end=106_AUTHRESPONSE._serialized_start=108@@ -120,4 +120,10 @@ if _descriptor._USE_C_DESCRIPTORS == False:_TRUSTEDSIGNINGKEY._serialized_end=4640_OIDCSESSION._serialized_start=4642_OIDCSESSION._serialized_end=4731+ _TASKAUTHORIZATIONRULE._serialized_start=4734+ _TASKAUTHORIZATIONRULE._serialized_end=4875+ _TASKRULE._serialized_start=4877+ _TASKRULE._serialized_end=5003+ _TASKOPERATION._serialized_start=5005+ _TASKOPERATION._serialized_end=5120# @@protoc_insertion_point(module_scope)diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyiindex 9b63fce6..980a3c9e 100644--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi@@ -424,6 +424,42 @@ class ServiceInfo(_message.Message):type: ServiceTypedef __init__(self, type: _Optional[_Union[ServiceType, str]] = ..., name: _Optional[str] = ..., description: _Optional[str] = ...) -> None: ...+class TaskAuthorizationRule(_message.Message):+ __slots__ = ["display_name", "expire_time", "name", "rules"]+ DISPLAY_NAME_FIELD_NUMBER: _ClassVar[int]+ EXPIRE_TIME_FIELD_NUMBER: _ClassVar[int]+ NAME_FIELD_NUMBER: _ClassVar[int]+ RULES_FIELD_NUMBER: _ClassVar[int]+ display_name: str+ expire_time: _timestamp_pb2.Timestamp+ name: str+ rules: _containers.RepeatedCompositeFieldContainer[TaskRule]+ def __init__(self, name: _Optional[str] = ..., display_name: _Optional[str] = ..., rules: _Optional[_Iterable[_Union[TaskRule, _Mapping]]] = ..., expire_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...) -> None: ...++class TaskOperation(_message.Message):+ __slots__ = ["allowed_methods", "allowed_paths", "allowed_permissions", "allowed_tools"]+ ALLOWED_METHODS_FIELD_NUMBER: _ClassVar[int]+ ALLOWED_PATHS_FIELD_NUMBER: _ClassVar[int]+ ALLOWED_PERMISSIONS_FIELD_NUMBER: _ClassVar[int]+ ALLOWED_TOOLS_FIELD_NUMBER: _ClassVar[int]+ allowed_methods: _containers.RepeatedScalarFieldContainer[str]+ allowed_paths: _containers.RepeatedScalarFieldContainer[str]+ allowed_permissions: _containers.RepeatedScalarFieldContainer[str]+ allowed_tools: _containers.RepeatedScalarFieldContainer[str]+ def __init__(self, allowed_tools: _Optional[_Iterable[str]] = ..., allowed_methods: _Optional[_Iterable[str]] = ..., allowed_paths: _Optional[_Iterable[str]] = ..., allowed_permissions: _Optional[_Iterable[str]] = ...) -> None: ...++class TaskRule(_message.Message):+ __slots__ = ["allowed_resources", "allowed_services", "description", "operation"]+ ALLOWED_RESOURCES_FIELD_NUMBER: _ClassVar[int]+ ALLOWED_SERVICES_FIELD_NUMBER: _ClassVar[int]+ DESCRIPTION_FIELD_NUMBER: _ClassVar[int]+ OPERATION_FIELD_NUMBER: _ClassVar[int]+ allowed_resources: _containers.RepeatedScalarFieldContainer[str]+ allowed_services: _containers.RepeatedScalarFieldContainer[str]+ description: str+ 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 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.pyindex e5209349..8d8f902f 100644--- a/sdk/python/src/agent_mesh/authorizer.py+++ b/sdk/python/src/agent_mesh/authorizer.py@@ -29,6 +29,7 @@ import biscuit_auth as bafrom .biscuit import BiscuitVerificationError, VerifiedBiscuit, _limits, verify_peer_biscuitfrom .discovery import parse_service_target+from .tar import TaskRequestContext, evaluate_task_rulesBASELINE_DATALOG: dict = json.loads(resources.files("agent_mesh._gen").joinpath("datalog.json").read_text())@@ -58,6 +59,8 @@ class AuthorizeRequest:# PolicyRole.http.method: Optional[str] = Nonepath: str = ""+ # The MCP tool name when evaluating a specific MCP tools/call invocation.+ mcp_tool: str = ""@dataclass(frozen=True)@@ -85,7 +88,7 @@ def authorize_caller(req: AuthorizeRequest, options: ProviderAuthorizerOptions)if not keys:raise AuthorizationError(req.peer_id, "no trusted control plane key")- # Signature under a trusted key, authority block only, expiry and binding+ # Signature under a trusted key, authority block + tar_block chain, expiry and binding# to the connection peer: RequireAuthorityBinding and EnforceExpiration.try:caller = verify_peer_biscuit(req.biscuit, req.peer_id, keys, now)@@ -136,6 +139,24 @@ def authorize_caller(req: AuthorizeRequest, options: ProviderAuthorizerOptions)b.build(token).authorize()except Exception as err: # noqa: BLE001 - biscuit-python raises several types for a denialraise AuthorizationError(req.peer_id, str(err)) from err++ if caller.task_rules:+ try:+ evaluate_task_rules(+ caller.task_rules,+ TaskRequestContext(+ service_type=svc_type,+ service_name=svc_name,+ has_http=req.method is not None,+ method=req.method or "",+ path=req.path,+ mcp_tool=req.mcp_tool,+ allow_mcp_stream_init=req.method is None and not req.mcp_tool and req.protocol == "/sam/mcp/1.0.0",+ ),+ now,+ )+ except Exception as err: # noqa: BLE001+ raise AuthorizationError(req.peer_id, str(err)) from errreturn callerdiff --git a/sdk/python/src/agent_mesh/biscuit.py b/sdk/python/src/agent_mesh/biscuit.pyindex 62258058..32fbc43d 100644--- a/sdk/python/src/agent_mesh/biscuit.py+++ b/sdk/python/src/agent_mesh/biscuit.py@@ -13,8 +13,8 @@# limitations under the License."""Verification of a peer's biscuit, mirroring internal/identity.verifyBiscuit:-signed by a trusted control plane key, authority block only, unexpired, and-bound to the peer at the other end of the connection."""+signed by a trusted control plane key, authority block + validated tar_block+chain, unexpired, and bound to the peer at the other end of the connection."""from __future__ import annotations@@ -24,6 +24,9 @@ from typing import Optional, Sequenceimport biscuit_auth as ba+from ._proto import sam_pb2+from .tar import _DATALOG, effective_tar_expiration, encode_tar_block_fact, parse_tar_block_source+ROLE_ROUTER = "sam:role:router"# Datalog evaluation budget, as in internal/identity.AuthorizerOptions.@@ -44,12 +47,13 @@ class VerifiedBiscuit:# The peer the token is bound to (its node() fact).peer_id: str- # When the token lapses; the earliest expiration() fact.+ # When the token lapses; the minimum of authority expiration() and any tar_block expire_time.expiration: datetime# The trusted key that verified the signature.verifying_key: bytesroles: list[str] = field(default_factory=list)labels: dict[str, str] = field(default_factory=dict)+ task_rules: list[sam_pb2.TaskAuthorizationRule] = field(default_factory=list)def _limits() -> ba.AuthorizerLimits:@@ -60,19 +64,9 @@ def _limits() -> ba.AuthorizerLimits:return limits-def verify_peer_biscuit(- biscuit: bytes,- expected_peer_id: str,- trusted_keys: Sequence[bytes],- now: Optional[datetime] = None,-) -> 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- key still verifies during rotation."""+def _parse_with_trusted_keys(biscuit: bytes, trusted_keys: Sequence[bytes]) -> tuple[ba.Biscuit, bytes]:if not trusted_keys:raise BiscuitVerificationError("no trusted control plane key to verify against")- now = now or datetime.now(timezone.utc)-token = Noneverifying_key = b""last_err: Exception | None = None@@ -85,13 +79,35 @@ def verify_peer_biscuit(last_err = errif token is None:raise BiscuitVerificationError(f"biscuit is not signed by a trusted control plane key: {last_err}")+ return token, verifying_key+++def _extract_tar_chain(token: ba.Biscuit) -> list[sam_pb2.TaskAuthorizationRule]:+ appended_count = token.block_count() - 1+ max_blocks = _DATALOG["max_attenuation_blocks"]+ if appended_count > max_blocks:+ raise BiscuitVerificationError(f"biscuit carries {appended_count} appended blocks; maximum is {max_blocks}")+ task_rules: list[sam_pb2.TaskAuthorizationRule] = []+ for i in range(1, appended_count + 1):+ try:+ task_rules.append(parse_tar_block_source(token.block_source(i)))+ except Exception as err: # noqa: BLE001+ raise BiscuitVerificationError(f"biscuit block {i}: {err}") from err+ return task_rules- # Appending needs no root key, so appended blocks are the one place a- # holder can put Datalog of their own. SAM tokens are authority-only.- if token.block_count() != 1:- raise BiscuitVerificationError(- f"biscuit carries appended blocks; SAM tokens are authority-block only ({token.block_count() - 1})"- )++def verify_peer_biscuit(+ biscuit: bytes,+ expected_peer_id: str,+ trusted_keys: Sequence[bytes],+ now: Optional[datetime] = None,+) -> 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+ key still verifies during rotation."""+ now = now or datetime.now(timezone.utc)+ token, verifying_key = _parse_with_trusted_keys(biscuit, trusted_keys)+ task_rules = _extract_tar_chain(token)builder = ba.AuthorizerBuilder()builder.set_limits(_limits())@@ -113,6 +129,9 @@ def verify_peer_biscuit(expirations = [f.terms[0] for f in authorizer.query(ba.Rule("e($e) <- expiration($e)")) if isinstance(f.terms[0], datetime)]if not expirations:raise BiscuitVerificationError("biscuit carries no expiration fact")+ expiration = effective_tar_expiration(min(expirations), task_rules)+ if now > expiration:+ raise BiscuitVerificationError(f"biscuit is expired at {now.isoformat()} (effective expiration {expiration.isoformat()})")labels = {f.terms[0]: f.terms[1]@@ -122,14 +141,38 @@ def verify_peer_biscuit(return VerifiedBiscuit(peer_id=expected_peer_id,- expiration=min(expirations),+ expiration=expiration,verifying_key=verifying_key,roles=strings("r($r) <- role($r)"),labels=labels,+ task_rules=task_rules,)+def attenuate_biscuit(+ biscuit: bytes,+ rule: sam_pb2.TaskAuthorizationRule,+ trusted_keys: Sequence[bytes],+) -> bytes:+ """Appends a non-authority block carrying a single tar_block("<base64url-proto>")+ fact to an existing Biscuit token in memory without contacting the control plane."""+ token, _ = _parse_with_trusted_keys(biscuit, trusted_keys)+ appended_count = token.block_count() - 1+ max_blocks = _DATALOG["max_attenuation_blocks"]+ if appended_count >= max_blocks:+ raise BiscuitVerificationError(f"biscuit already has {appended_count} appended blocks (maximum {max_blocks})")+ _extract_tar_chain(token)+ fact_str = encode_tar_block_fact(rule)+ bb = ba.BlockBuilder()+ bb.add_fact(ba.Fact(fact_str))+ try:+ return token.append(bb).to_bytes()+ except Exception as err: # noqa: BLE001+ raise BiscuitVerificationError(f"failed to append tar_block to biscuit: {err}") from err++def require_role(verified: VerifiedBiscuit, role: str) -> None:"""Requires role(<role>) on an already verified token, as identity.RequireRole."""if role not in verified.roles:raise BiscuitVerificationError(f"biscuit lacks expected role {role!r}")+diff --git a/sdk/python/src/agent_mesh/tar.py b/sdk/python/src/agent_mesh/tar.pynew file mode 100644index 00000000..0671d3da--- /dev/null+++ b/sdk/python/src/agent_mesh/tar.py@@ -0,0 +1,294 @@+# 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.++"""Task-Scoped Authorization Rule (TAR) validation, tar_block encoding/decoding,+and multi-hop intersection evaluation, mirroring api/tar.go."""++from __future__ import annotations++import base64+import json+import re+from dataclasses import dataclass+from datetime import datetime, timezone+from importlib import resources+from typing import Callable, Sequence++from ._proto import sam_pb2++_DATALOG: dict = json.loads(resources.files("agent_mesh._gen").joinpath("datalog.json").read_text())++_TAR_BLOCK_SOURCE_RE = re.compile(_DATALOG["tar_block_source_pattern"])+_HTTP_METHOD_RE = re.compile(_DATALOG["http_method_syntax"])+_VALID_SERVICE_TYPES = frozenset({"mcp", "a2a", "inference", "http", "egress"})+++def _b64url_encode(raw: bytes) -> str:+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")+++def _b64url_decode(b64_payload: str) -> bytes:+ if not b64_payload or "=" in b64_payload:+ raise ValueError("invalid unpadded base64url in tar_block")+ padded = b64_payload + "=" * ((4 - len(b64_payload) % 4) % 4)+ raw = base64.urlsafe_b64decode(padded.encode("ascii"))+ if _b64url_encode(raw) != b64_payload:+ raise ValueError("non-canonical base64url in tar_block")+ return raw+++def validate_service_pattern(s: str) -> None:+ if s == "*":+ return+ scheme, sep, target = s.partition("://")+ if not sep or not scheme:+ raise ValueError(f"invalid service format: {s}")+ if scheme not in _VALID_SERVICE_TYPES:+ raise ValueError(f'invalid service type "{scheme}" in {s}')+ if not target or "/" in target or target.count("*") > 1:+ raise ValueError(f'invalid service target "{target}" in {s}')+ if "*" in target and target != "*":+ valid_suffix = target.startswith("*.") and len(target[2:]) > 0+ valid_prefix = target.endswith(".*") and len(target[:-2]) > 0+ if not valid_suffix and not valid_prefix:+ raise ValueError(f"wildcard in {s!r} must be '*', '*.<suffix>' or '<prefix>.*'")+++def validate_http_grant_path(p: str) -> None:+ if not p.startswith("/"):+ raise ValueError(f"path {p!r} must start with '/'")+ if "?" in p or "#" in p:+ raise ValueError(f"path {p!r} must not contain '?' or '#'")+ stars = p.count("*")+ if stars > 1 or (stars == 1 and not p.endswith("*")):+ raise ValueError(f"path {p!r}: '*' is only valid once, at the end")+ for seg in p[1:].split("/"):+ if seg in (".", ".."):+ raise ValueError(f"path {p!r} must not contain '.' or '..' segments")+++def _validate_tar_string_list(field_name: str, values: Sequence[str], check_elem: Callable[[str], None]) -> None:+ max_entries = _DATALOG["max_entries_per_tar_list"]+ if len(values) > max_entries:+ raise ValueError(f"TaskRule.{field_name} has {len(values)} entries; maximum is {max_entries}")+ for i, val in enumerate(values):+ try:+ check_elem(val)+ except Exception as err: # noqa: BLE001+ raise ValueError(f"TaskRule.{field_name}[{i}]: {err}") from err+++def validate_task_rule(r: sam_pb2.TaskRule) -> None:+ max_desc = _DATALOG["max_tar_description_length"]+ if len(r.description.encode("utf-8")) > max_desc:+ raise ValueError(f"TaskRule.description exceeds {max_desc} bytes")+ _validate_tar_string_list("allowed_services", r.allowed_services, validate_service_pattern)++ max_res = _DATALOG["max_tar_resource_length"]++ def _check_resource(res: str) -> None:+ if not res:+ raise ValueError("resource must not be empty")+ if len(res.encode("utf-8")) > max_res:+ raise ValueError(f"resource exceeds {max_res} bytes")++ _validate_tar_string_list("allowed_resources", r.allowed_resources, _check_resource)++ if r.HasField("operation"):+ op = r.operation++ def _check_non_empty(label: str) -> Callable[[str], None]:+ def _fn(v: str) -> None:+ if not v:+ raise ValueError(f"{label} must not be empty")++ return _fn++ def _check_method(m: str) -> None:+ if not _HTTP_METHOD_RE.match(m):+ raise ValueError(f"invalid HTTP method {m!r}")+ if m == "CONNECT":+ raise ValueError("CONNECT is not a grantable HTTP method")++ _validate_tar_string_list("operation.allowed_tools", op.allowed_tools, _check_non_empty("tool name"))+ _validate_tar_string_list("operation.allowed_methods", op.allowed_methods, _check_method)+ _validate_tar_string_list("operation.allowed_paths", op.allowed_paths, validate_http_grant_path)+ _validate_tar_string_list("operation.allowed_permissions", op.allowed_permissions, _check_non_empty("permission"))+++def validate_task_authorization_rule(rule: sam_pb2.TaskAuthorizationRule, require_non_empty_rules: bool = True) -> None:+ max_name = _DATALOG["max_tar_name_length"]+ if len(rule.name.encode("utf-8")) > max_name:+ raise ValueError(f"TaskAuthorizationRule.name exceeds {max_name} bytes")+ max_desc = _DATALOG["max_tar_description_length"]+ if len(rule.display_name.encode("utf-8")) > max_desc:+ raise ValueError(f"TaskAuthorizationRule.display_name exceeds {max_desc} bytes")+ if require_non_empty_rules and len(rule.rules) == 0:+ raise ValueError("TaskAuthorizationRule.rules must not be empty")+ max_rules = _DATALOG["max_rules_per_tar"]+ if len(rule.rules) > max_rules:+ raise ValueError(f"TaskAuthorizationRule.rules has {len(rule.rules)} entries; maximum is {max_rules}")+ for i, r in enumerate(rule.rules):+ try:+ validate_task_rule(r)+ except Exception as err: # noqa: BLE001+ raise ValueError(f"TaskAuthorizationRule.rules[{i}]: {err}") from err+ if rule.HasField("expire_time"):+ seconds = rule.expire_time.seconds+ nanos = rule.expire_time.nanos+ if nanos < 0 or nanos >= 1_000_000_000:+ raise ValueError("TaskAuthorizationRule.expire_time has invalid nanos")+ _ = seconds+++def encode_tar_block_payload(rule: sam_pb2.TaskAuthorizationRule) -> str:+ validate_task_authorization_rule(rule, require_non_empty_rules=True)+ raw = rule.SerializeToString(deterministic=True)+ max_bytes = _DATALOG["max_tar_bytes"]+ if len(raw) > max_bytes:+ raise ValueError(f"TaskAuthorizationRule serialized size {len(raw)} exceeds {max_bytes} bytes")+ return _b64url_encode(raw)+++def encode_tar_block_fact(rule: sam_pb2.TaskAuthorizationRule) -> str:+ b64 = encode_tar_block_payload(rule)+ return f'{_DATALOG["fact_tar_block"]}("{b64}")'+++def decode_tar_block_payload(b64_payload: str) -> sam_pb2.TaskAuthorizationRule:+ raw = _b64url_decode(b64_payload)+ max_bytes = _DATALOG["max_tar_bytes"]+ if len(raw) == 0 or len(raw) > max_bytes:+ raise ValueError(f"tar_block decoded payload size {len(raw)} out of bounds [1, {max_bytes}]")+ rule = sam_pb2.TaskAuthorizationRule()+ try:+ rule.ParseFromString(raw)+ except Exception as err: # noqa: BLE001+ raise ValueError(f"invalid TaskAuthorizationRule protobuf in tar_block: {err}") from err+ before = rule.SerializeToString(deterministic=True)+ rule.DiscardUnknownFields()+ after = rule.SerializeToString(deterministic=True)+ if before != after:+ raise ValueError("TaskAuthorizationRule in tar_block contains unknown protobuf wire fields")+ validate_task_authorization_rule(rule, require_non_empty_rules=False)+ return rule+++def parse_tar_block_source(block_source: str) -> sam_pb2.TaskAuthorizationRule:+ m = _TAR_BLOCK_SOURCE_RE.match(block_source.strip())+ if not m:+ raise ValueError('non-authority block does not match single tar_block("<base64url>") grammar')+ return decode_tar_block_payload(m.group(1))+++def _tar_expire_datetime(rule: sam_pb2.TaskAuthorizationRule) -> datetime | None:+ if not rule.HasField("expire_time"):+ return None+ ts = rule.expire_time+ return datetime.fromtimestamp(ts.seconds + ts.nanos / 1e9, tz=timezone.utc)+++def effective_tar_expiration(authority_expiration: datetime, rules: Sequence[sam_pb2.TaskAuthorizationRule]) -> datetime:+ effective = authority_expiration+ for r in rules:+ exp = _tar_expire_datetime(r)+ if exp is not None and exp < effective:+ effective = exp+ return effective+++@dataclass(frozen=True)+class TaskRequestContext:+ service_type: str+ service_name: str+ has_http: bool = False+ method: str = ""+ path: str = ""+ mcp_tool: str = ""+ allow_mcp_stream_init: bool = False+ resource: str = ""+ permission: str = ""+++def match_service_pattern(pattern: str, service_type: str, service_name: str) -> bool:+ if not service_type or not service_name:+ return False+ if pattern == "*":+ return True+ pat_type, sep, pat_target = pattern.partition("://")+ if not sep or pat_type != service_type:+ return False+ if pat_target == "*":+ return True+ if pat_target.startswith("*."):+ return service_name.endswith(pat_target[1:])+ if pat_target.endswith(".*"):+ return service_name.startswith(pat_target[:-1])+ return service_name == pat_target+++def match_http_path(pattern: str, req_path: str) -> bool:+ if not req_path:+ return False+ if pattern.endswith("*"):+ return req_path.startswith(pattern[:-1])+ return req_path == pattern+++def match_task_rule(rule: sam_pb2.TaskRule, req: TaskRequestContext) -> bool:+ if rule.allowed_services:+ if not any(match_service_pattern(pat, req.service_type, req.service_name) for pat in rule.allowed_services):+ return False+ if rule.allowed_resources:+ if not req.resource or req.resource not in rule.allowed_resources:+ return False+ if rule.HasField("operation"):+ op = rule.operation+ if op.allowed_tools:+ if req.service_type != "mcp":+ return False+ if not req.mcp_tool:+ if not req.allow_mcp_stream_init:+ return False+ elif req.mcp_tool not in op.allowed_tools:+ return False+ if op.allowed_methods:+ if not req.has_http or not req.method or req.method == "CONNECT":+ return False+ if req.method not in op.allowed_methods:+ return False+ if op.allowed_paths:+ if not req.has_http or not req.path or req.method == "CONNECT":+ return False+ if not any(match_http_path(pat, req.path) for pat in op.allowed_paths):+ return False+ if op.allowed_permissions:+ if not req.permission or req.permission not in op.allowed_permissions:+ return False+ return True+++def evaluate_task_rules(+ chain: Sequence[sam_pb2.TaskAuthorizationRule],+ req: TaskRequestContext,+ now: datetime,+) -> None:+ for i, tar in enumerate(chain):+ exp = _tar_expire_datetime(tar)+ if exp is not None and now > exp:+ raise ValueError(f"TaskAuthorizationRule block {i + 1} ({tar.name!r}) is expired")+ if len(tar.rules) == 0:+ raise ValueError(f"TaskAuthorizationRule block {i + 1} ({tar.name!r}) has no rules (fail-closed)")+ if not any(match_task_rule(r, req) for r in tar.rules):+ raise ValueError(f"request denied by TaskAuthorizationRule block {i + 1} ({tar.name!r})")diff --git a/sdk/python/tests/test_authorizer.py b/sdk/python/tests/test_authorizer.pyindex 02ccaa1a..911667a8 100644--- a/sdk/python/tests/test_authorizer.py+++ b/sdk/python/tests/test_authorizer.py@@ -16,10 +16,18 @@mints them and policy rules rendered the way it renders them. The decisionshere are the ones internal/node/middleware_test.go pins."""+import base64+import json+from datetime import datetime, timezone+from pathlib import Path+import biscuit_auth as baimport pytest+from google.protobuf.timestamp_pb2 import Timestamp+from agent_mesh._proto import sam_pb2from agent_mesh.authorizer import BASELINE_DATALOG, AuthorizationError, AuthorizeRequest, ProviderAuthorizerOptions, authorize_caller+from agent_mesh.biscuit import attenuate_biscuitfrom .test_session import CP, CP_KEY@@ -159,3 +167,92 @@ def test_every_baseline_item_parses_in_biscuit_python():ba.Rule(r)for p in BASELINE_DATALOG["policies"] + [BASELINE_DATALOG["allow_if_true"]]:ba.Policy(p)+++_TAR_SUITE = json.loads((Path(__file__).resolve().parents[2] / "testdata" / "tar_conformance.json").read_text())++[email protected]("vec", _TAR_SUITE["vectors"], ids=lambda v: v["name"])+def test_tar_conformance_vector(vec: dict):+ root_pub = base64.b64decode(_TAR_SUITE["public_key_b64"])+ provider_biscuit = base64.b64decode(_TAR_SUITE["provider_biscuit_b64"])+ biscuit_bytes = base64.b64decode(vec["biscuit_b64"])+ eval_now = datetime.fromisoformat(_TAR_SUITE["evaluation_time"])+ req = AuthorizeRequest(+ biscuit=biscuit_bytes,+ peer_id=_TAR_SUITE["caller_peer_id"],+ target_service=vec["target_service"],+ protocol=vec["protocol"],+ method=vec.get("method"),+ path=vec.get("path", ""),+ mcp_tool=vec.get("mcp_tool", ""),+ )+ opts = ProviderAuthorizerOptions(+ trusted_keys=lambda: [root_pub],+ own_biscuit=lambda: provider_biscuit,+ policy_rules=lambda: _TAR_SUITE["policy_datalog_rules"],+ now=lambda: eval_now,+ )+ if not vec["allow"]:+ with pytest.raises(AuthorizationError):+ authorize_caller(req, opts)+ return+ verified = authorize_caller(req, opts)+ assert verified.peer_id == _TAR_SUITE["caller_peer_id"]+ if "expected_effective_expiration" in vec:+ want_exp = datetime.fromisoformat(vec["expected_effective_expiration"])+ assert verified.expiration == want_exp+++def test_attenuate_biscuit_narrows_authority_across_hops():+ root = node_token(CALLER, ["granted_service_all_types(true)", "target_unrestricted(true)"])+ hop1_exp = datetime(2034, 5, 1, 0, 0, 0, tzinfo=timezone.utc)+ hop2_exp = datetime(2034, 2, 1, 0, 0, 0, tzinfo=timezone.utc)++ ts1 = Timestamp()+ ts1.FromDatetime(hop1_exp)+ att1 = attenuate_biscuit(+ root,+ sam_pb2.TaskAuthorizationRule(+ name="hop-1",+ expire_time=ts1,+ rules=[+ sam_pb2.TaskRule(+ allowed_services=["mcp://calc"],+ operation=sam_pb2.TaskOperation(allowed_tools=["add", "multiply"]),+ )+ ],+ ),+ [CP_KEY],+ )++ ts2 = Timestamp()+ ts2.FromDatetime(hop2_exp)+ att2 = attenuate_biscuit(+ att1,+ sam_pb2.TaskAuthorizationRule(+ name="hop-2",+ expire_time=ts2,+ rules=[+ sam_pb2.TaskRule(+ allowed_services=["mcp://calc"],+ operation=sam_pb2.TaskOperation(allowed_tools=["add"]),+ )+ ],+ ),+ [CP_KEY],+ )++ verified = authorize_caller(+ AuthorizeRequest(biscuit=att2, peer_id=CALLER, target_service="mcp://calc", protocol="/sam/mcp/1.0.0", mcp_tool="add"),+ options([]),+ )+ assert verified.expiration == hop2_exp+ assert len(verified.task_rules) == 2++ with pytest.raises(AuthorizationError):+ authorize_caller(+ AuthorizeRequest(biscuit=att2, peer_id=CALLER, target_service="mcp://calc", protocol="/sam/mcp/1.0.0", mcp_tool="multiply"),+ options([]),+ )+diff --git a/sdk/testdata/tar_conformance.json b/sdk/testdata/tar_conformance.jsonnew file mode 100644index 00000000..ae80b568--- /dev/null+++ b/sdk/testdata/tar_conformance.json@@ -0,0 +1,200 @@+{+ "_comment": "Generated by hack/gen-sdk-datalog; do not edit.",+ "public_key_b64": "+eAauv9zlp6c0Zk/mGWThohZehix71wGRsVqKsGc97E=",+ "caller_peer_id": "12D3KooWAGBDFVmdHUoxDqPNPNMA8AaTQdXAGgQJ3LaLqqFwUqDC",+ "provider_peer_id": "12D3KooWMXqcZXCVk78nHcs4bLjXdCZDVp9EPaZCqkLyQLMtPjMX",+ "provider_biscuit_b64": "EoECCpYBCjQxMkQzS29vV01YcWNaWENWazc4bkhjczRiTGpYZENaRFZwOUVQYVpDcWtMeVFMTXRQak1YCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZRIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIEiQIABIgnzBD/dsbd2zRhEv++fkUG3SuunbHUcMsxyW1LajgVocaQOaZMx1eN07C6s9Igc6uOWSFHGz3HmjcQCdzlQ/bXfYoidlsnFg9Oy7ZpXFckW3+Z87Ks5E/5ych7kMHIr801gciIgogT4ZZrQazskCPPJ7HCXcHDCrsVk9I9XiFNyivxtdp9YU=",+ "evaluation_time": "2026-10-03T12:00:00Z",+ "policy_datalog_rules": [],+ "vectors": [+ {+ "name": "authority_only_allowed",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOIiIKIEj38hi6JB7hkU8hCIZ4awBKinX5aeKUfG22B6PR0SzZ",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "any_tool",+ "allow": true,+ "expected_effective_expiration": "2035-01-01T00:00:00Z"+ },+ {+ "name": "one_hop_mcp_allowed_tool",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRnd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yQ1/Jxs=",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_forecast",+ "allow": true,+ "expected_effective_expiration": "2034-06-01T00:00:00Z"+ },+ {+ "name": "one_hop_mcp_denied_tool",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sSABgDIgoKCAiHCBIDGIYIEiQIABIgFBc1jobRtYB5XNStsWgEsyKbhad6OaquCym8zrFEyTMaQEHPbtNArr3lhWPJhEyljmz3KIvH1bD3JP/eVfWp02C1oPPX3FuEGW8pv1tUNcddWbW6JdjWei2Nzh2g4lp+sgoiIgog2/agHbA4MIhTf3W+O1uQmndoA/HwjHosP1r4yQ1/Jxs=",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "drop_table",+ "allow": false+ },+ {+ "name": "one_hop_mcp_missing_tool_denied_on_http",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sSABgDIgoKCAiHCBIDGIYIEiQIABIgFBc1jobRtYB5XNStsWgEsyKbhad6OaquCym8zrFEyTMaQEHPbtNArr3lhWPJhEyljmz3KIvH1bD3JP/eVfWp02C1oPPX3FuEGW8pv1tUNcddWbW6JdjWei2Nzh2g4lp+sgoiIgog2/agHbA4MIhTf3W+O1uQmndoA/HwjHosP1r4yQ1/Jxs=",+ "target_service": "mcp://weather",+ "protocol": "/libp2p-http",+ "method": "POST",+ "path": "/mcp",+ "allow": false+ },+ {+ "name": "one_hop_wildcard_prefix_inference_allowed",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sSABgDIgoKCAiHCBIDGIYIEiQIABIgFBc1jobRtYB5XNStsWgEsyKbhad6OaquCym8zrFEyTMaQEHPbtNArr3lhWPJhEyljmz3KIvH1bD3JP/eVfWp02C1oPPX3FuEGW8pv1tUNcddWbW6JdjWei2Nzh2g4lp+sgoiIgog2/agHbA4MIhTf3W+O1uQmndoA/HwjHosP1r4yQ1/Jxs=",+ "target_service": "inference://gemini.pro",+ "protocol": "/libp2p-http",+ "method": "POST",+ "path": "/v1/chat/completions",+ "allow": true,+ "expected_effective_expiration": "2034-06-01T00:00:00Z"+ },+ {+ "name": "one_hop_dot_boundary_inference_denied",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sSABgDIgoKCAiHCBIDGIYIEiQIABIgFBc1jobRtYB5XNStsWgEsyKbhad6OaquCym8zrFEyTMaQEHPbtNArr3lhWPJhEyljmz3KIvH1bD3JP/eVfWp02C1oPPX3FuEGW8pv1tUNcddWbW6JdjWei2Nzh2g4lp+sgoiIgog2/agHbA4MIhTf3W+O1uQmndoA/HwjHosP1r4yQ1/Jxs=",+ "target_service": "inference://gemini2.pro",+ "protocol": "/libp2p-http",+ "method": "POST",+ "path": "/v1/chat/completions",+ "allow": false+ },+ {+ "name": "two_hop_intersection_mcp_allowed",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZX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ZDJWa0lGTmpiM0JsR2g0U0RXMWpjRG92TDNkbFlYUm9aWElhRFFvTFoyVjBYM2RsWVhSb1pYSWFOaElYWldkeVpYTnpPaTh2WVhCcExtZHBkR2gxWWk1amIyMGFHeElEUjBWVUdoUXZjbVZ3YjNNdllXTnRaUzl3ZFdKc2FXTXZLaUlHQ0lDQnY4VUgSABgDIgoKCAiHCBIDGIgIEiQIABIgC9huaQvn5fQqTdRtAuFhgvdLFJMiDjbWMwcSTA5tzowaQFXu1kwk4Ybuf4QFs2WpzN/q9wCsfgu3FjDkZjQY4Z2LdUrYfAMv8f+JBzAkFdhl701TXdLvvCgWXHop0otjyQQiIgog9HgzOE/a2iSFBsDFAMkI1PzGIbngi9Y0kdhh6jY6X8E=",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": true,+ "expected_effective_expiration": "2034-03-01T00:00:00Z"+ },+ {+ "name": "two_hop_intersection_mcp_dropped_tool_denied",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YX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obRtYB5XNStsWgEsyKbhad6OaquCym8zrFEyTMaQEHPbtNArr3lhWPJhEyljmz3KIvH1bD3JP/eVfWp02C1oPPX3FuEGW8pv1tUNcddWbW6JdjWei2Nzh2g4lp+sgoasgIKxwEKtAFDZ3h6ZFdKaFoyVnVkQzFvYjNBU0YxTjFZbUZuWlc1MElFNWhjbkp2ZDJWa0lGTmpiM0JsR2g0U0RXMWpjRG92TDNkbFlYUm9aWElhRFFvTFoyVjBYM2RsWVhSb1pYSWFOaElYWldkeVpYTnpPaTh2WVhCcExtZHBkR2gxWWk1amIyMGFHeElEUjBWVUdoUXZjbVZ3YjNNdllXTnRaUzl3ZFdKc2FXTXZLaUlHQ0lDQnY4VUgSABgDIgoKCAiHCBIDGIgIEiQIABIgC9huaQvn5fQqTdRtAuFhgvdLFJMiDjbWMwcSTA5tzowaQFXu1kwk4Ybuf4QFs2WpzN/q9wCsfgu3FjDkZjQY4Z2LdUrYfAMv8f+JBzAkFdhl701TXdLvvCgWXHop0otjyQQiIgog9HgzOE/a2iSFBsDFAMkI1PzGIbngi9Y0kdhh6jY6X8E=",+ "target_service": "egress://api.github.com",+ "protocol": "/libp2p-http",+ "method": "GET",+ "path": "/repos/acme/public/readme",+ "allow": true,+ "expected_effective_expiration": "2034-03-01T00:00:00Z"+ },+ {+ "name": "two_hop_intersection_http_dropped_method_denied",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xtt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n5fQqTdRtAuFhgvdLFJMiDjbWMwcSTA5tzowaQFXu1kwk4Ybuf4QFs2WpzN/q9wCsfgu3FjDkZjQY4Z2LdUrYfAMv8f+JBzAkFdhl701TXdLvvCgWXHop0otjyQQiIgog9HgzOE/a2iSFBsDFAMkI1PzGIbngi9Y0kdhh6jY6X8E=",+ "target_service": "egress://api.github.com",+ "protocol": "/libp2p-http",+ "method": "POST",+ "path": "/repos/acme/public/readme",+ "allow": false+ },+ {+ "name": "two_hop_intersection_http_dropped_path_denied",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sSABgDIgoKCAiHCBIDGIYIEiQIABIgFBc1jobRtYB5XNStsWgEsyKbhad6OaquCym8zrFEyTMaQEHPbtNArr3lhWPJhEyljmz3KIvH1bD3JP/eVfWp02C1oPPX3FuEGW8pv1tUNcddWbW6JdjWei2Nzh2g4lp+sgoasgIKxwEKtAFDZ3h6ZFdKaFoyVnVkQzFvYjNBU0YxTjFZbUZuWlc1MElFNWhjbkp2ZDJWa0lGTmpiM0JsR2g0U0RXMWpjRG92TDNkbFlYUm9aWElhRFFvTFoyVjBYM2RsWVhSb1pYSWFOaElYWldkeVpYTnpPaTh2WVhCcExtZHBkR2gxWWk1amIyMGFHeElEUjBWVUdoUXZjbVZ3YjNNdllXTnRaUzl3ZFdKc2FXTXZLaUlHQ0lDQnY4VUgSABgDIgoKCAiHCBIDGIgIEiQIABIgC9huaQvn5fQqTdRtAuFhgvdLFJMiDjbWMwcSTA5tzowaQFXu1kwk4Ybuf4QFs2WpzN/q9wCsfgu3FjDkZjQY4Z2LdUrYfAMv8f+JBzAkFdhl701TXdLvvCgWXHop0otjyQQiIgog9HgzOE/a2iSFBsDFAMkI1PzGIbngi9Y0kdhh6jY6X8E=",+ "target_service": "egress://api.github.com",+ "protocol": "/libp2p-http",+ "method": "GET",+ "path": "/repos/acme/private/secret",+ "allow": false+ },+ {+ "name": "two_hop_intersection_connect_tunnel_denied",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9z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FFvTFoyVjBYM2RsWVhSb1pYSWFOaElYWldkeVpYTnpPaTh2WVhCcExtZHBkR2gxWWk1amIyMGFHeElEUjBWVUdoUXZjbVZ3YjNNdllXTnRaUzl3ZFdKc2FXTXZLaUlHQ0lDQnY4VUgSABgDIgoKCAiHCBIDGIgIEiQIABIgC9huaQvn5fQqTdRtAuFhgvdLFJMiDjbWMwcSTA5tzowaQFXu1kwk4Ybuf4QFs2WpzN/q9wCsfgu3FjDkZjQY4Z2LdUrYfAMv8f+JBzAkFdhl701TXdLvvCgWXHop0otjyQQiIgog9HgzOE/a2iSFBsDFAMkI1PzGIbngi9Y0kdhh6jY6X8E=",+ "target_service": "egress://api.github.com",+ "protocol": "/libp2p-http",+ "method": "CONNECT",+ "allow": false+ },+ {+ "name": "sealed_two_hop_allowed",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGugDCv0CCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sSABgDIgoKCAiHCBIDGIYIEiQIABIgFBc1jobRtYB5XNStsWgEsyKbhad6OaquCym8zrFEyTMaQEHPbtNArr3lhWPJhEyljmz3KIvH1bD3JP/eVfWp02C1oPPX3FuEGW8pv1tUNcddWbW6JdjWei2Nzh2g4lp+sgoasgIKxwEKtAFDZ3h6ZFdKaFoyVnVkQzFvYjNBU0YxTjFZbUZuWlc1MElFNWhjbkp2ZDJWa0lGTmpiM0JsR2g0U0RXMWpjRG92TDNkbFlYUm9aWElhRFFvTFoyVjBYM2RsWVhSb1pYSWFOaElYWldkeVpYTnpPaTh2WVhCcExtZHBkR2gxWWk1amIyMGFHeElEUjBWVUdoUXZjbVZ3YjNNdllXTnRaUzl3ZFdKc2FXTXZLaUlHQ0lDQnY4VUgSABgDIgoKCAiHCBIDGIgIEiQIABIgC9huaQvn5fQqTdRtAuFhgvdLFJMiDjbWMwcSTA5tzowaQFXu1kwk4Ybuf4QFs2WpzN/q9wCsfgu3FjDkZjQY4Z2LdUrYfAMv8f+JBzAkFdhl701TXdLvvCgWXHop0otjyQQiQhJADVU4qMUtOePV3e/7xsCryWLns80fKrOfnnN2xI4ZrbfvIIQpuSB4an6iHIv0TPllhPr/JY8v8jwFkGZ9U9ijDQ==",+ "target_service": "egress://api.github.com",+ "protocol": "/libp2p-http",+ "method": "GET",+ "path": "/repos/acme/public/readme",+ "allow": true,+ "expected_effective_expiration": "2034-03-01T00:00:00Z"+ },+ {+ "name": "expired_tar_block_rejected",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGqoBCkAKI0NndGxlSEJwY21Wa0xXaHZjQm9ERWdFcUlnWUlnTUt2OEFVCgl0YXJfYmxvY2sSABgDIgoKCAiHCBIDGIYIEiQIABIgOaoM7ypePfuMGt+yb5zYF/BV2Lwh7TaYT9LBH/YxPegaQGHjY5YHlgBhfiJghMH8PBEs4nxMS2iHeBTjp1lLwpg1vY7m+pP1UXkqkf3yA3uyYStlfDFVypXNPBgKC6w+UQQiIgogCeVSntPE1W4j7/rf/jCbvsj/2NbhpVViUH4RJRxW1mE=",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ },+ {+ "name": "empty_rules_tar_denied",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGpkBCi8KEkNndGxiWEIwZVMxeWRXeGxjdwoJdGFyX2Jsb2NrEgAYAyIKCggIhwgSAxiGCBIkCAASIFtswsSKGAMAeRpTmEoEnl9N9XhRYZBtQMaHy9MJPJawGkCyGYs8HdkcuzUDo5PNsaohS06Wn7FScuCcGmhhh8tamWBlF3n+qZl/5ZzP+hvInEnxpKBMAOYj7F/nFCjeZ4gJIiIKIEe+HjK9l4ayfk80jWHX/AIWeRTRIkkdVNchqHylPn9S",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ },+ {+ "name": "nine_blocks_rejected",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGug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nqP3EFE5nanv+uN1SBO9PK2lDIUK1NHg3M1UR9BQcqvzy0zaLLk0oE+ED3ChVInBEgDpGPq6e+9JonHSg4aegoQEgAYAyIKCggIhwgSAxiGCBIkCAASIKwS5qYli5Kxx+zoPlxQZCFig3d8NcXQ18mrsbPmyiWkGkDxGewK9zfd8hgCxRCa9/9jTst3pd80E/wUyXWCH/LgpKA62XVhLVdMQJnbNlUsj7l2vJvES4M3/elZnMjnOIMEGnoKEBIAGAMiCgoICIcIEgMYhggSJAgAEiCfLdPbFPR20rnRIr9wqdkFaLJIWXdqO6AYIWVTctR6shpA2Q49gdX2E2j96LsSVknYmrORfktyYbUdPbZ9AQttYlIdBHxEDJovujNwkBeiB5vyAp+dfyRYxzuvhaZCPjIcARp6ChASABgDIgoKCAiHCBIDGIYIEiQIABIgz4FiQuyHhvecLnuI1EFkl8iYaCGSJLJ8IIhSA6GVL2YaQOmeZsv1hvEHUq3qPGqWVlSAjtcpQOWBpvNbNWsmsrbfxymw3qYo46TKkke1yA1iM0B2beUIjBneNm9NJyMvDAcaegoQEgAYAyIKCggIhwgSAxiGCBIkCAASIDAoavQNsEAJUELz+X2hlj9Uj4k52fhViY6qPu8FpKoiGkC9e7FIbT+RsGHPoT1ZMjEa9IRSQrSMnCq9aBCKf2mS7V47q1rZ5motNn/DHfztPVwrKGpxi2Ktr3bZh9l5NccOGnoKEBIAGAMiCgoICIcIEgMYhggSJAgAEiA4RWPMIdEZN9ukT/k305IWQRPVYr+jLlTZoe3ciwQUfhpAknd5cmWlzPNxTj2hd/H+iAblQbDOOmRBbh9Fxz8nO7oWrA46euTW5ChVmUboRjh6S/r+a9fLalOq6ltZHjpTAiIiCiB+LS1g1O2lkVrNen5+S0RI4PbcZV5huMkt8UCLxFHQ+g==",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ },+ {+ "name": "block_with_rule_rejected",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0F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VFVXA1AXyFoNEU27G70EQm4bNclvq+30si3+3suwbh1eJ4RMPIiIKIIKi/OxYobnu81f7Uhve/JD3hiHUns5H8QI9LiNia5zv",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ },+ {+ "name": "block_with_check_rejected",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGv0DCpIDCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sKAWESABgDIgoKCAiHCBIDGIYIMhAKDgoCCBsSCAiHCBIDCIgIEiQIABIg9XoxJ0saQo9i31q5+aGyIYYAdDRywM2h8dRxaxWd808aQKf/fpee0TGfcVZ3+NLegjyVXDKORaLAWGvMleYLTWN7cYLGbLx9vpIoQoH/o+mhm/UGfXojV6KRHOceVx+pDQwiIgogXAat6Lc138OGbpF6ZPHHcojayWQP39htNbKWmxX/IMw=",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ },+ {+ "name": "block_with_two_facts_rejected",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGvsDCpADCt8CQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFjCgl0YXJfYmxvY2sKBWV4dHJhEgAYAyIKCggIhwgSAxiGCCIKCggIhwgSAxiICBIkCAASIGkG9L8C2lzdLa9YGzEO9NvMm0s7J4w/CXxPfgMImXe7GkAvMoCmzbxQRiIQtzCbM+hOmSQXeohZNXROFaaVtSp8xUgrMkGpwm6D/j2up/A73d9TVi4dmZULYALPDYRe7/kJIiIKIBLkCqz71dOXTx87VnfzTAh7sZcf94R+IPpHbNFgqe0Q",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ },+ {+ "name": "block_with_wrong_predicate_rejected",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGq8BCkUKNDEyRDNLb29XTVhxY1pYQ1ZrNzhuSGNzNGJMalhkQ1pEVnA5RVBhWkNxa0x5UUxNdFBqTVgSABgDIgkKBwgYEgMYhggSJAgAEiAIBv4hd5wqc8Te2T8+OXZ60ncjJl2TJSCf8AiHGQjN4hpA7d4cSMVtoyiyN2aVvYNJXe5JozQQ17mJ0XHSo4OMCBmvYSZTF2A2xqMzTU9FgeeW1ixgGAoPsusX8blhKCrUCCIiCiDi6hUpfaMCP4KDhNGRK7lFW2k/kIp+9dNAzUZfUadT1w==",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ },+ {+ "name": "block_with_bytes_term_rejected",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGocBCh0KCXRhcl9ibG9jaxIAGAMiDAoKCIYIEgUqAwECAxIkCAASIFG/IkeDKa/9YbLp2eSpb6r5uKCEPLflDogARQD1/a5yGkBqPkF9hrJssgqI3rNrPLsYini6eDkJyjvtm8kUVagFubWYPAeWlsqV6P0mqBK7KWAlthKcXQVdNmZ3MoWBqjsMIiIKIMyXDAvWKmvpQZIjVs5PQAhbAjwLspo6iFk2RSOCKd8p",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ },+ {+ "name": "block_with_unknown_proto_field_rejected",+ "biscuit_b64": "EscCCtwBCjQxMkQzS29vV0FHQkRGVm1kSFVveERxUE5QTk1BOEFhVFFkWEFHZ1FKM0xhTHFxRndVcURDCg5jbGllbnRfcGVlcl9pZAoKZXhwaXJhdGlvbgoNc2FtOnJvbGU6bm9kZQoZZ3JhbnRlZF9zZXJ2aWNlX2FsbF90eXBlcwoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiCQoHCBgSAxiACCIKCggIgQgSAxiACCINCgsIgggSBiCA14zSByIJCgcIBhIDGIMIIgkKBwiECBICMAEiCQoHCIUIEgIwARIkCAASIFRfjc79B/D8bBSsa9C/O1xttSQ5Fnh5HGLhUqDqcgklGkAwQBYoM3AlkokHpgqObXJHjNZZWhQf2Cfa04Hz6K1g3+R2Pfw7Fa4OW0Njmf4g1rETmh2mnAzQ80Qp9Zvz7UgOGuwDCoEDCuMCQ2hCdmNtTm9aWE4wY21GMGIzSXRhRzl3RWhkUGNtTm9aWE4wY21GMGIzSWdWR0Z6YXlCVFkyOXdaUm9fQ2hGWFpXRjBhR1Z5SUUxRFVDQjBiMjlzY3hJTmJXTndPaTh2ZDJWaGRHaGxjaG9iQ2d0blpYUmZkMlZoZEdobGNnb01aMlYwWDJadmNtVmpZWE4wR21BS0tVZHBkRWgxWWlCQlVFa2djbVZoWkM5M2NtbDBaU0IxYm1SbGNpQXZjbVZ3YjNNdllXTnRaUzhxRWhkbFozSmxjM002THk5aGNHa3VaMmwwYUhWaUxtTnZiUm9hRWdOSFJWUVNCRkJQVTFRYURTOXlaWEJ2Y3k5aFkyMWxMeW9hTHdvWFIyVnRhVzVwSUdsdVptVnlaVzVqWlNCd2NtVm1hWGdTRkdsdVptVnlaVzVqWlRvdkwyZGxiV2x1YVM0cUlnWUlnSldreVFlWUJnRQoJdGFyX2Jsb2NrEgAYAyIKCggIhwgSAxiGCBIkCAASIEEhFO8qaYnms0l7oQ815aD2QZjlZhq5Vg2qtz0JES4AGkCVoBNehA9jX+gz7355NbsxpzN0CkewH/g4Ay4CVkdbfJ7XKTq2TLex27q1vTD1HKIpEy2MFzGUwjNXmT1cFhoJIiIKIGy2xVzSts8ocY7Jq5raLjTh0XhjORHYAAW3buv96o1f",+ "target_service": "mcp://weather",+ "protocol": "/sam/mcp/1.0.0",+ "mcp_tool": "get_weather",+ "allow": false+ }+ ]+}diff --git a/sts.md b/sts.mdindex 8f81b46f..49e6b003 100644--- a/sts.md+++ b/sts.md@@ -6,6 +6,29 @@---+## The Picture: a Courier Network for Tasks++++SAM is not a network proxy that happens to carry agent traffic. It moves tasks between places that trust nothing on arrival, the way a courier network moves parcels between post offices. The animation ([site/static/images/agent-mesh-courier.svg](site/static/images/agent-mesh-courier.svg), SMIL, dark theme for the landing page, plays in any browser or `<img>` tag) follows six parcels: a developer to `inference://claude` and to `inference://gemini`, Kubernetes on premises to `mcp://bigquery`, a sandbox platform to `mcp://github`, a SaaS platform to `egress://generativelanguage.googleapis.com`, and Kubernetes in a cloud, through the gateway it already runs, to `a2a://partner-agent`. The mapping is exact:++| In the picture | In SAM |+| :--- | :--- |+| Parcel | One request: an MCP call, a chat completion, a BigQuery query, an A2A message. |+| Sender | The agent wherever it runs: a developer laptop, Kubernetes on premises, Kubernetes in a cloud, a SaaS platform, a sandbox platform. |+| Local post office | The `sam-node` next to the agent, or the SDK inside its process. It checks the sender's platform identity (projected service account token, Workload Identity, SPIFFE JWT-SVID, OIDC login) and obtains the waybill from the Registry. |+| Your gateway | Istio, agentgateway or kgateway where a cluster already runs one. It stays in the data path and asks the `sam-node` office over `ext_proc` (or `ext_authz`, or RFC 8693 token exchange); the office stamps, the gateway carries. This is the row that separates SAM from the gateways: SAM is not another one. |+| Waybill | The Task Biscuit: who the sender is, through which office (actor), what this task may do, until when. |+| Stamp | An attenuation block added at a hop (`tar_block`). It can only restrict; a sub-agent's parcel carries one stamp more than its parent's. |+| Sealed bag | The encrypted libp2p stream between two offices. Routers relay it across NAT, clusters, sites and clouds and cannot open it. |+| Registry | The control plane: verifies senders, issues waybills, holds the policy, issues the permits foreign borders recognize (OIDC issuer), keeps the receipts. It never touches a parcel. The rubber stamp thumps once per waybill and once per permit. |+| Destination office | The egress `sam-node` for one destination (`mcp://`, `inference://`, `egress://`, `a2a://`): verifies the waybill and every stamp again, runs customs, obtains the permit, delivers. The operator chooses where it runs, hence where traffic leaves. |+| Customs | Content inspection at the destination office: policy facts, Model Armor, and any Envoy `ext_proc` processor the operator brings (section 5.6). |+| Permit | The destination credential: a federated token minted on the Registry's signature for this sender and task, or a key from the office vault. The agent never holds it. |+| Receipts | Audit logs at the Registry, at both offices and at the destination, joined by task id. |++---+## 1. Executive Summary & Architectural PositioningIn traditional cloud and service-mesh architectures, permissions are granted **ambiently** to a workload identity (a Kubernetes Service Account, a GCP Service Account, a SPIFFE SVID `spiffe://...`, or Google Cloud **Agent Identity**).@@ -88,15 +111,21 @@ A critical subtlety in `biscuit-go` v2.2.0 ([`internal/identity/biscuit.go:L40-4When a holder (an orchestrator, `sam-node`, or an SDK session) attenuates a Biscuit with a `TaskAuthorizationRule`, the appended block $i \ge 1$ contains:* **`0` Datalog `Rules`*** **`0` Datalog `Checks`**- * **Exactly `1` Datalog `Fact`:** `tar_block("<base64url-serialized api.TaskAuthorizationRule protobuf>")`+ * **Exactly `1` Datalog `Fact`:** `tar_block("<unpadded-base64url-serialized api.TaskAuthorizationRule protobuf>")`2. **How `UnmarshalInbound` Validates & Extracts Blocks:**- In [`internal/identity/biscuit.go`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go), `UnmarshalInbound(rawToken []byte)` inspects the Biscuit protobuf envelope (`blocks[1..k]`, with `k <= MaxAttenuationBlocks = 8`) **before** building an authorizer:- * If any appended block $i \ge 1$ has `len(rules) != 0`, `len(checks) != 0`, or `len(facts) != 1` (or the single fact is not `tar_block(<string>)`), the token is **rejected immediately** (`ErrInvalidAttenuationBlock`) before `b.Authorizer()` is ever called.- * `UnmarshalInbound` decodes each `tar_block` into an `*api.TaskAuthorizationRule` and validates it with `api.ValidateTaskAuthorizationRule(tar)`.+ In [`internal/identity/biscuit.go`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go), `UnmarshalInbound(rawToken []byte)` inspects the Biscuit envelope (`blocks[1..k]`, with `k <= MaxAttenuationBlocks = 8`) **before** building an authorizer and returns `(*biscuit.Biscuit, []*api.TaskAuthorizationRule, error)` so nothing parses twice:+ * **Go (`biscuit-go` v2.2.0):** Unmarshals the outer `pb.Biscuit` protobuf to check structural counts on each `blocks[i-1]` (`len(FactsV2) == 1`, `len(RulesV2) == 0`, `len(ChecksV2) == 0`) and matches block $i$'s rendered source against the strict single-line regex `^tar_block\("([A-Za-z0-9_-]+)"\);?\s*$`.+ * **TypeScript (`biscuit-wasm` `getBlockSource(i)`) & Python (`biscuit_auth` `block_source(i)`):** Enforce `block_count() - 1 <= MaxAttenuationBlocks` and match each appended block's source string (`i >= 1`) against the identical regex `^tar_block\("([A-Za-z0-9_-]+)"\);?\s*$`, rejecting any block with multiple lines, rules, checks, or non-string terms before building an authorizer.+ * **Bounds enforced by `api.ValidateTaskAuthorizationRule` and both SDKs:**+ * `MaxAttenuationBlocks = 8`+ * `MaxTARBytes = 4096` (serialized protobuf bytes per block, well within the 64 KiB `AuthFrame` reader limit)+ * `MaxRulesPerTAR = 16`+ * `MaxEntriesPerTARList = 64` (per `allowed_services`, `allowed_tools`, `allowed_methods`, `allowed_paths`, `allowed_permissions`, `allowed_resources`)+ * `MaxTARNameLength = 128` (printable ASCII name syntax)3. **How the Verifier Enforces the `TaskAuthorizationRule` Chain:**Because the **verifier** (not the token holder) decodes the validated `[]*api.TaskAuthorizationRule` slice from the token:- * The verifier evaluates each `TaskAuthorizationRule` directly in Go/TS/Python against the verified `RequestContext` (`service`, `method`, `path`, `host`, `port`, `mcp_tool`, `time`)—or compiles it with its own trusted code.- * **Result:** Zero attacker-authored Datalog ever runs in the Datalog VM, zero possibility of drift between SAM's PEP decision and the `TaskAuthorizationRule` forwarded to Cloud STS, and trivial $O(1)$ extraction of the `TaskAuthorizationRule` chain!+ * The verifier evaluates each `TaskAuthorizationRule` directly in Go/TS/Python against the verified `RequestContext` (`service`, `method`, `path`, `mcp_tool`, `time`).+ * **Result:** Zero attacker-authored Datalog ever runs in the Datalog VM, zero possibility of drift between SAM's PEP decision and the `TaskAuthorizationRule` forwarded to Cloud STS, and single-pass extraction of the `TaskAuthorizationRule` chain.---@@ -108,23 +137,26 @@ To avoid polarity bugs when chaining multiple attenuation hops ($\text{Authority// TaskAuthorizationRule narrows a credential's authority for a specific task or// sub-agent hop. Across multiple appended blocks (1..k), semantics are strict// set intersection (logical AND): a request is permitted only if it is allowed-// by the standing mesh policy AND matches at least one TaskRule in EVERY-// appended TaskAuthorizationRule block.+// by the standing mesh policy AND is before every block's expire_time AND+// matches at least one TaskRule in EVERY appended TaskAuthorizationRule block.message TaskAuthorizationRule {string name = 1;string display_name = 2;// Positive allow-list of rules for this hop. Empty rules list denies everything.repeated TaskRule rules = 3;- // Optional shorter expiration for this task hop.+ // Optional shorter expiration for this task hop. Effective token expiry is+ // the minimum across the authority block's expiration() fact and every+ // appended block's expire_time.google.protobuf.Timestamp expire_time = 4;}message TaskRule {string description = 1;- // Allowed mesh services (e.g., "mcp://bigquery", "inference://gemini-*",- // "egress://bigquery.googleapis.com"). Supports "*" and prefix/suffix- // wildcards matching SAM's service pattern grammar. Required (non-empty).+ // Allowed mesh services (e.g., "mcp://bigquery", "inference://gemini.*",+ // "egress://bigquery.googleapis.com"). Uses the dot-anchored grammar of+ // api.ValidateServiceFormat ("*", "<type>://*", "<type>://*.<suffix>",+ // "<type>://<prefix>.*", "<type>://<exact>"). Required (non-empty).repeated string allowed_services = 2;// Optional operation-level allow-list. If set, the request must also match@@ -133,23 +165,38 @@ message TaskRule {// Optional allowed upstream resource names (e.g. CRM resource prefixes// "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026").+ // Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.repeated string allowed_resources = 4;}message TaskOperation {- // Allowed MCP tool names (for mcp:// services) or cloud IAM permissions- // (e.g. "bigquery.googleapis.com/datasets.get", "bigquery.googleapis.com/tables.*").- repeated string allowed_actions = 1;- // Allowed HTTP methods (e.g. ["GET", "POST"]).+ // Allowed MCP tool names (enforced by the PEP on mcp:// tools/call).+ repeated string allowed_tools = 1;+ // Allowed HTTP methods (e.g. ["GET", "POST"]), validated with httpMethodSyntax.repeated string allowed_methods = 2;- // Allowed HTTP path patterns (e.g. ["/bigquery/v2/projects/my-proj/*"]).+ // Allowed HTTP path patterns ("/exact" or "/prefix/*"), validated with+ // validateHTTPGrantPath.repeated string allowed_paths = 3;+ // Allowed cloud IAM permissions (e.g. "bigquery.googleapis.com/datasets.get").+ // Opaque to the wire PEP; consumed by CloudTokenExchanger at egress.+ repeated string allowed_permissions = 4;}```+#### Per-Service-Type PEP Matching Semantics++Within a single `TaskAuthorizationRule`, a request matches if it satisfies **at least one** `TaskRule`. Across blocks $1 \dots k$, the request must match **every** `TaskAuthorizationRule` block AND have `now < block.expire_time` whenever `expire_time` is set (fail-closed if `now` is unset or `>= expire_time`):++| Service Type | `allowed_services` | `operation.allowed_tools` | `operation.allowed_methods` & `allowed_paths` | `operation.allowed_permissions` & `allowed_resources` |+| :--- | :--- | :--- | :--- | :--- |+| **`mcp://<name>`** | Enforced on stream handshake & HTTP | Enforced on `tools/call` (`params.name`). At stream open (`initialize`, `tools/list`), tool name is not yet present so `allowed_tools` does not block opening the stream. | Enforced only if the rule sets `allowed_methods` / `allowed_paths` (a raw stream has no HTTP facts, so a rule with HTTP constraints denies non-HTTP streams). | Ignored by wire PEP (`CloudTokenExchanger` only). |+| **`inference://<name>`**, **`a2a://<name>`** | Enforced on HTTP request | If non-empty on a rule, that rule requires an MCP tool name and therefore does not match a plain HTTP request. | Enforced against request `Method` and `Path` when non-empty. | Ignored by wire PEP. |+| **`egress://<name>`** | Enforced on HTTP request & TCP `CONNECT` | Same as above (must be empty for an HTTP/TCP rule to match). | Enforced against request `Method` and `Path` when non-empty (a TCP `CONNECT` tunnel has `Method: "CONNECT", Path: ""`, so any rule with `allowed_paths` denies a tunnel). | Intersected across blocks $1 \dots k$ and translated by `CloudTokenExchanger` at egress. |+| **`system://<name>`** | Enforced on stream handshake | Enforced if a tool call is made. | Same as `mcp://`. | Ignored by wire PEP. |+* **How Multi-Hop Narrowing Works (CUJ 3):**- * **Hop 1 (Orchestrator $\rightarrow$ Analytics Agent):** Appends `TAR_1` with `allowed_resources: ["//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/*"]` and `allowed_actions: ["bigquery.googleapis.com/datasets.get", "bigquery.googleapis.com/tables.get", "bigquery.googleapis.com/tables.getData"]`.- * **Hop 2 (Analytics Agent $\rightarrow$ Sub-Agent):** Appends `TAR_2` with `allowed_resources: ["//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/tables/q1"]` and `allowed_actions: ["bigquery.googleapis.com/tables.getData"]`.+ * **Hop 1 (Orchestrator $\rightarrow$ Analytics Agent):** Appends `TAR_1` with `allowed_paths: ["/bigquery/v2/projects/my-proj/datasets/sales_2026/*"]`, `allowed_resources: ["//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/*"]`, and `allowed_permissions: ["bigquery.googleapis.com/datasets.get", "bigquery.googleapis.com/tables.get", "bigquery.googleapis.com/tables.getData"]`.+ * **Hop 2 (Analytics Agent $\rightarrow$ Sub-Agent):** Appends `TAR_2` with `allowed_paths: ["/bigquery/v2/projects/my-proj/datasets/sales_2026/tables/q1/*"]`, `allowed_resources: ["//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/tables/q1"]`, and `allowed_permissions: ["bigquery.googleapis.com/tables.getData"]`.* Both SAM PEPs and the Cloud STS adapter compute the **intersection** ($\text{TAR}_1 \cap \text{TAR}_2$), which cleanly narrows access to `tables.getData` on `tables/q1` only.* **Where Inversion Happens:** If a downstream cloud API (such as Google's internal TAR spec) uses a `DENY`-with-`excludedPermissions` wire format, the **Google Cloud STS Adapter** in `EgressService` computes the intersection of the allow-lists across blocks $1 \dots k$ and writes that intersected allow-list into Google's `excludedPermissions` / `excludedResources` fields.@@ -163,8 +210,11 @@ When a `sam-node` exchanges a workload's or user's credential on their behalf, t* Authority facts: `node("<peer_id>")`, `client_peer_id("<peer_id>")`, `user("<subject>")`, `role("<role>")`, `expiration(<time>)`.2. **Delegated Session Biscuit (minted at stateless `POST /token/exchange` on the Control Plane):*** Authority facts:- * `actor_node("<origin_sam_node_peer_id>")` and `client_peer_id("<origin_sam_node_peer_id>")` — satisfies transport replay defense (`connection_peer_id == client_peer_id`) so only that `sam-node` can present the token over libp2p.+ * `client_peer_id("<origin_sam_node_peer_id>")` — satisfies transport replay defense (`connection_peer_id == client_peer_id`) so only that `sam-node` can present the token over libp2p.+ * `actor_node("<origin_sam_node_peer_id>")` — names the channel for the audit log, for `act.sub` in the border JWT (section 3.5) and for `attributes["sam"].actor_node` (section 5.6). It grants nothing: no baseline rule and no policy binding reads it.* `user("<caller_subject>")`, `email("<caller_email>")`, `group("<caller_group>")`, `role("<caller_role>")` — resolved from the **caller's `subject_token`**, never from the `sam-node`'s own roles!+ * **No `node()` fact.** `node:<peer_id>` is a policy binding member (`api.BindingMemberPrefixes`), rendered as `role($r) <- node("<peer_id>")`. A delegated token that carried `node("<origin_sam_node_peer_id>")` would attach the origin node's roles to the subject.+ * **How verifiers bind each kind:** the Datalog replay check (`check if client_peer_id($id), connection_peer_id($id)`) is the transport binding for both kinds. It reads authority facts only, so a `client_peer_id` in an appended block never satisfies it. [`RequireAuthorityBinding`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go#L118-L131) on `node()` remains the check for an identity token presented in the peer handshake (`VerifyBiscuitAndGetExpiry`, the SDKs' `verifyPeerBiscuit`). For a request token, `SamNode.Authorize` binds on `client_peer_id` in the authority block, because a delegated token has no `node()` fact.* **Why `POST /token/exchange` is Separate from `POST /register`:*** `/register` is for **node enrollment**: it persists a node record (`SaveNode`, `SaveUser`) in the Control Plane store.* `POST /token/exchange` is **100% stateless on the Control Plane**: it authenticates the requesting `sam-node` (via its `Authorization: Bearer <node-biscuit>` + `peer_id` challenge PoP), verifies the presented `subject_token` (OIDC JWT, K8s projected SA JWT, or SPIFFE JWT-SVID), resolves the subject's roles against the in-memory policy cache, and signs a short-lived Delegated Session Biscuit (TTL = `min(subject_jwt.exp, MaxSessionTTL)`). It performs **zero database writes**, scaling to high-frequency token exchanges (e.g., 5-minute JWT-SVIDs or 1-hour K8s SA tokens) with per-node rate limiting.@@ -187,7 +237,8 @@ External parties do not understand Biscuits, and SAM must not forward a caller's| Signing key | ES256. Google and AWS federation accept RS256 and ES256 only, not EdDSA; the Ed25519 root key stays for Biscuits. Stored in a KMS or HSM where available; rotated with overlap and `kid`. || Discovery | `/.well-known/openid-configuration` and `/jwks` served by the control plane. For a control plane that is not reachable from the cloud, the operator uploads the JWKS to the provider (Google accepts up to 8 uploaded keys per pool provider). || Mint endpoint | `POST /sts/token` (protobuf, mesh surface): request = Biscuit, destination name; response = JWT, `expire_time`. The control plane verifies the Biscuit and the full `tar_block` chain before minting, exactly as a PEP would, and logs the crossing. |-| Claims | `iss` = control plane URL; `sub` = the SAM principal (`email`, or `issuer#subject` for workloads); `act` = `{ "sub": "<egress node peer_id>" }`; `aud` = the destination's audience from `EgressDestination` (one per destination, never shared); `sam_task` = the innermost `TaskAuthorizationRule.name`; `sam_task_class` = an operator-mapped label usable in cloud IAM `principalSet` bindings and attribute conditions; `exp` = minutes. |+| Claims | `iss` = control plane URL; `sub` = the SAM principal (`email`, or `issuer#subject` for workloads); `act` = `{ "sub": "<egress node peer_id>" }`; `aud` = the destination's audience from `EgressDestination` (one per destination, never shared); `sam_roles` = the subject's mesh roles as a JSON array, from the `role()` facts of the authority block, mapped to `google.groups` for `principalSet` bindings; `sam_task` = the innermost `TaskAuthorizationRule.name`, for the audit log; `exp` = minutes. |+| Holder input | Nothing a holder writes into an appended block reaches the cloud except `sam_task`, which grants nothing. Every claim the cloud binds on (`sub`, `sam_roles`, `act`) comes from the authority block the control plane signed. The JWT carries no task-class claim: cloud IAM bindings are additive, so a class chosen by the holder would select grants rather than narrow them (section 5.5). || Caching | The egress node caches the JWT per Biscuit digest for its lifetime and the destination credential by the same key, so the control plane is off the hot path. || Keys never leave the control plane | Nodes hold nothing a cloud trusts. The control plane is the single issuer and the single audit point for border crossings, which matches the existing rule that the control plane is the authority and the node is the channel. |@@ -278,7 +329,7 @@ message EgressDestination {// Keep the destination hostname in Host when target_url is an operator// inspection chain that forwards to the real host (section 5.6, tier 4).bool preserve_host = 8;- // Forward X-Sam-Principal, X-Sam-Task and X-Sam-Task-Class to target_url.+ // Forward X-Sam-Principal, X-Sam-Roles and X-Sam-Task to target_url.// Only for an operator chain; the node strips them for a real destination.bool forward_context = 9;}@@ -306,16 +357,16 @@ message Inspector {// HTTPS. Model Armor is reached as an egress destination with an// oidc_federation broker, so no credential is stored for it.message ModelArmor {- // projects/P/locations/L/templates/T+ // projects/P/locations/L/templates/T. One template per destination; a+ // destination that needs another template is declared as another+ // EgressDestination.string template = 1;- // Template override keyed by the JWT's sam_task_class (section 3.5).- map<string, string> template_by_task_class = 2;// BUFFERED: the whole response is inspected before release and may be// rewritten. REQUEST_ONLY: prompts are inspected, responses pass.- ResponseInspection response = 3;+ ResponseInspection response = 2;// Default false: an unreachable Model Armor fails the request.- bool fail_open = 4;- google.protobuf.Duration timeout = 5;+ bool fail_open = 3;+ google.protobuf.Duration timeout = 4;}enum ResponseInspection {@@ -429,14 +480,14 @@ sequenceDiagram### 5.3 Adapters1. **Google Cloud (`oidc_federation` $\rightarrow$ `sts.googleapis.com/v1/token`):**- * **Public today:** the control-plane JWT is exchanged through a **Workload Identity Pool** (workload principals) or a **Workforce Identity Pool** (human principals) whose OIDC provider is the SAM control plane. Attribute mapping `google.subject = assertion.sub`, `attribute.task_class = assertion.sam_task_class`, `attribute.actor = assertion.act.sub`; an attribute condition restricts `act.sub` to enrolled egress nodes. Optional `impersonate` for APIs that need a service account; `scopes` narrowed by the TAR; CAB `accessBoundary` for `storage.googleapis.com`.- * **When the task token API is public:** the adapter additionally computes $\text{TAR}_1 \cap \dots \cap \text{TAR}_k$ over `allowed_actions` and `allowed_resources` and emits the provider's wire form (inverting to `excludedPermissions` / `excludedResources` if that is what the API expects).+ * **Public today:** the control-plane JWT is exchanged through a **Workload Identity Pool** (workload principals) or a **Workforce Identity Pool** (human principals) whose OIDC provider is the SAM control plane. Attribute mapping `google.subject = assertion.sub`, `google.groups = assertion.sam_roles`, `attribute.actor = assertion.act.sub`; an attribute condition restricts `act.sub` to enrolled egress nodes. Optional `impersonate` for APIs that need a service account; `scopes` narrowed by the TAR; CAB `accessBoundary` for `storage.googleapis.com`.+ * **When the task token API is public:** the adapter additionally computes $\text{TAR}_1 \cap \dots \cap \text{TAR}_k$ over `allowed_permissions` and `allowed_resources` and emits the provider's wire form (inverting to `excludedPermissions` / `excludedResources` if that is what the API expects).2. **AWS (`aws_assume_role` $\rightarrow$ `AssumeRoleWithWebIdentity`):**- The account trusts the control plane as an IAM OIDC identity provider. The adapter compiles the intersected chain into an inline **session policy** (`Effect: Allow`, `Action` from `allowed_actions`, `Resource` from `allowed_resources`) intersected with the template; AWS evaluates role policy $\cap$ session policy, which is genuine per-task downscoping today. Role chaining is capped at one hour, so a sub-agent hop re-assumes from the egress node instead of chaining.+ The account trusts the control plane as an IAM OIDC identity provider. The adapter compiles the intersected chain into an inline **session policy** (`Effect: Allow`, `Action` from `allowed_permissions`, `Resource` from `allowed_resources`) intersected with the template; AWS evaluates role policy $\cap$ session policy, which is genuine per-task downscoping today. Role chaining is capped at one hour, so a sub-agent hop re-assumes from the egress node instead of chaining.3. **API-key and client-credential destinations (`static_secret`):**The existing behaviour: the node injects the stored secret. Gemini Developer API, OpenAI, Anthropic, GitHub tokens, and third-party MCP servers or `a2a://` agents that do not federate with the SAM issuer.4. **Generic RFC 8693 / Entra OBO (`oidc_federation` with another `token_endpoint`):**- Maps `allowed_services` and `allowed_actions` to OAuth `resource` and `scope`. Entra OBO delegates for user principals only; app-only calls use client credentials.+ Maps `allowed_services` and `allowed_permissions` to OAuth `resource` and `scope`. Entra OBO delegates for user principals only; app-only calls use client credentials.### 5.4 Per-Destination Narrowing, Honestly Stated@@ -444,7 +495,7 @@ Where each layer enforces differs by destination class. The design must not prom| Destination class | Border credential | Per-task narrowing available today | Residual gap || :--- | :--- | :--- | :--- |-| Google Cloud APIs (BigQuery, Vertex AI, Cloud Storage) | Control-plane JWT federated through a workload or workforce pool; optional impersonation with narrowed `scope` | Mesh PEP on host, method and path (BigQuery REST paths carry project, dataset and table; Vertex paths carry the model), OAuth scopes, CEL attribute conditions, `principalSet` bindings on `sam_task_class`, CAB for Cloud Storage | A body-level reference (SQL in `jobs.insert` naming another table) is bounded by the principal's standing IAM, not by the task, until a task token API is public |+| Google Cloud APIs (BigQuery, Vertex AI, Cloud Storage) | Control-plane JWT federated through a workload or workforce pool; optional impersonation with narrowed `scope` | Mesh PEP on host, method and path (BigQuery REST paths carry project, dataset and table; Vertex paths carry the model), OAuth scopes, CEL attribute conditions, `principalSet` bindings on `google.groups` (the subject's mesh roles), CAB for Cloud Storage | A body-level reference (SQL in `jobs.insert` naming another table) is bounded by the principal's standing IAM, not by the task, until a task token API is public || AWS | Control-plane JWT, `AssumeRoleWithWebIdentity` | Session policy compiled from the TAR: fine-grained, intersection semantics | One-hour role chaining limit; packed session policy size limit || API-key services (Gemini Developer API, OpenAI, Anthropic, GitHub tokens) | Static secret from the node's secrets directory | Mesh PEP only: path (which carries the model), method, TTL | The key cannot be downscoped; a leaked key is the full key || External agents (`a2a://`) and third-party MCP servers | Control-plane JWT if the party federates with the SAM issuer; otherwise a stored client credential | Mesh PEP plus whatever the party's authorization server supports | Depends on the party |@@ -466,9 +517,9 @@ Operators want to inspect what agents send and receive: prompts and completions**Four tiers, combinable per destination:**1. **Policy facts (built in).** `host()`, `port()`, `method()`, `path()` and the MCP tool name from `tools/call`. Google API paths carry the model (`.../models/M:generateContent`), the project, the dataset and the table, so a large part of what operators call inspection is a path rule. This tier is the PEP and runs on every request.-2. **Model Armor, called directly (`inspectors[].model_armor`).** For payload shapes the node understands (Gemini `generateContent`, the OpenAI-compatible chat shape served by the `/v1` facade, MCP `tools/call` arguments and results, A2A messages) the egress node calls `sanitizeUserPrompt` on the request and `sanitizeModelResponse` on the response over HTTPS with the standard library. The template is chosen per destination with an override per `sam_task_class`, so a code-review task class and a customer-data task class run different templates. A finding blocks the request with `403` and a `Proxy-Status` reason; a Sensitive Data Protection de-identification result replaces the text. Streamed responses are handled in `BUFFERED` mode (inspected whole, then released; higher latency, no incremental display) or `REQUEST_ONLY` mode (prompt inspected, response passed), chosen per destination; Model Armor's bidirectional streaming methods are a follow-up (section 8, item 22). The inspector is unreachable: the request fails unless `fail_open` is set.-3. **Envoy `ext_proc` processors (`inspectors[].ext_proc`), the standard interface.** The egress node is the client side of `envoy.service.ext_proc.v3.ExternalProcessor`: one bidirectional gRPC stream per request, carrying `request_headers`, `request_body`, `request_trailers`, `response_headers`, `response_body` and `response_trailers` according to the processing mode; the processor answers with header and body mutations, an `immediate_response` that blocks, or a mode override. Any processor written for Envoy, agentgateway or Google Service Extensions callouts runs unchanged against `sam-node`: a customer's own DLP or guardrail service, a vendor product that exposes `ext_proc`, or the Service Extensions callout SDK examples. The node fills `ProcessingRequest.attributes["sam"]` with `principal`, `actor_node`, `task`, `task_class`, `service` and `destination`, so the processor applies per-task policy without SAM headers on the wire. Body modes map to Envoy's: `BUFFERED` for whole-body decisions and rewriting (bounded by `max_buffered_bytes`), `STREAMED` for chunked bodies such as SSE where the processor can stop a stream but cannot rewrite what was already forwarded, `FULL_DUPLEX_STREAMED` for processors that rewrite chunks as they pass. A processor runs before the broker injects the destination credential and after `X-Sam-*` and the caller's `Authorization` are stripped, so it sees neither token; its mutations to `Authorization`, `Host`, `:authority` and `X-Sam-*` are refused, which keeps the invariant that an inspector narrows or blocks and never selects a credential or a destination. `failure_mode_allow` defaults to false; `message_timeout` defaults to 200ms; mTLS to the processor uses names from the node's secrets directory.-4. **Operator inspection chain.** `target_url` points at the operator's inspection proxy with `preserve_host` set: agentgateway with its Model Armor or webhook guard, or Secure Web Proxy in explicit mode. The egress node hands over plaintext HTTP with the brokered credential already injected; the chain inspects and forwards to the real host. With `forward_context`, the node also sends `X-Sam-Principal`, `X-Sam-Task` and `X-Sam-Task-Class`, so the chain applies per-task policy and the chain's log joins the control plane's. The other form of this tier needs no SAM configuration: the egress node runs in a VPC whose outbound path is Secure Web Proxy next-hop or Cloud NGFW Enterprise with TLS inspection, and the node trusts the inspection CA through `--egress-ca-bundle`. The node is then an ordinary workload to the network inspection product. This tier remains for proxies that are not `ext_proc` servers.+2. **Model Armor, called directly (`inspectors[].model_armor`).** For payload shapes the node understands (Gemini `generateContent`, the OpenAI-compatible chat shape served by the `/v1` facade, MCP `tools/call` arguments and results, A2A messages) the egress node calls `sanitizeUserPrompt` on the request and `sanitizeModelResponse` on the response over HTTPS with the standard library. The template is chosen per destination. A finding blocks the request with `403` and a `Proxy-Status` reason; a Sensitive Data Protection de-identification result replaces the text. Streamed responses are handled in `BUFFERED` mode (inspected whole, then released; higher latency, no incremental display) or `REQUEST_ONLY` mode (prompt inspected, response passed), chosen per destination; Model Armor's bidirectional streaming methods are a follow-up (section 8, item 22). The inspector is unreachable: the request fails unless `fail_open` is set.+3. **Envoy `ext_proc` processors (`inspectors[].ext_proc`), the standard interface.** The egress node is the client side of `envoy.service.ext_proc.v3.ExternalProcessor`: one bidirectional gRPC stream per request, carrying `request_headers`, `request_body`, `request_trailers`, `response_headers`, `response_body` and `response_trailers` according to the processing mode; the processor answers with header and body mutations, an `immediate_response` that blocks, or a mode override. Any processor written for Envoy, agentgateway or Google Service Extensions callouts runs unchanged against `sam-node`: a customer's own DLP or guardrail service, a vendor product that exposes `ext_proc`, or the Service Extensions callout SDK examples. The node fills `ProcessingRequest.attributes["sam"]` with `principal`, `roles`, `actor_node`, `task`, `service` and `destination`, so the processor applies per-task policy without SAM headers on the wire. Body modes map to Envoy's: `BUFFERED` for whole-body decisions and rewriting (bounded by `max_buffered_bytes`), `STREAMED` for chunked bodies such as SSE where the processor can stop a stream but cannot rewrite what was already forwarded, `FULL_DUPLEX_STREAMED` for processors that rewrite chunks as they pass. A processor runs before the broker injects the destination credential and after `X-Sam-*` and the caller's `Authorization` are stripped, so it sees neither token; its mutations to `Authorization`, `Host`, `:authority` and `X-Sam-*` are refused, which keeps the invariant that an inspector narrows or blocks and never selects a credential or a destination. `failure_mode_allow` defaults to false; `message_timeout` defaults to 200ms; mTLS to the processor uses names from the node's secrets directory.+4. **Operator inspection chain.** `target_url` points at the operator's inspection proxy with `preserve_host` set: agentgateway with its Model Armor or webhook guard, or Secure Web Proxy in explicit mode. The egress node hands over plaintext HTTP with the brokered credential already injected; the chain inspects and forwards to the real host. With `forward_context`, the node also sends `X-Sam-Principal`, `X-Sam-Roles` and `X-Sam-Task`, so the chain applies per-task policy and the chain's log joins the control plane's. The other form of this tier needs no SAM configuration: the egress node runs in a VPC whose outbound path is Secure Web Proxy next-hop or Cloud NGFW Enterprise with TLS inspection, and the node trusts the inspection CA through `--egress-ca-bundle`. The node is then an ordinary workload to the network inspection product. This tier remains for proxies that are not `ext_proc` servers.**Dependencies for tier 3: none in the root module.** `ext_proc` is being donated as an independent open-source project, so SAM depends on the protocol and not on Envoy's Go ecosystem. Three decisions keep `go.mod` unchanged:@@ -541,7 +592,7 @@ flowchart LR**Threat Model & Mitigations When the Sandbox Holds a Token:**1. **Sealed Leaf Token (`b.Seal()`):** The orchestrator hands the sandbox a **sealed, task-attenuated Biscuit** (`OPENAI_API_KEY=$SAM_TASK_TOKEN`). The sandbox cannot append blocks or widen permissions.-2. **Channel Binding (`actor_node(peer_id)`):** Because the Biscuit's authority block binds `client_peer_id` to the local/cluster `sam-node`'s `peer_id` ([`RequireAuthorityBinding`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go#L118-L131)), if a prompt-injected agent exfiltrates `$SAM_TASK_TOKEN` to an external attacker, **the attacker cannot use it from another machine or another mesh node**.+2. **Channel Binding (`client_peer_id`):** Because the Biscuit's authority block binds `client_peer_id` to the local/cluster `sam-node`'s `peer_id` (section 3.3), if a prompt-injected agent exfiltrates `$SAM_TASK_TOKEN` to an external attacker, **the attacker cannot use it from another machine or another mesh node**.3. **Short Task TTL & Explicit Revocation:** The token is scoped to the single task's services/tools with a short `expire_time` (e.g., 15 minutes) and is revoked at the local `sam-node` (`POST /oauth/revoke`) as soon as the sandbox container exits.4. **No `/dev/net/tun` or `nano-init`:** `Sandbox` pods on GKE run cleanly under `RuntimeClass: gvisor` with a standard K8s `NetworkPolicy` allowing egress only to the cluster `sam-node` (or `agentgateway`) Service.@@ -555,7 +606,7 @@ flowchart LR* `agentgateway` is configured with `sam-node`'s `ext_authz` gRPC service (or RFC 8693 backend token exchange at `http://sam-node:8080/oauth/token`).* Workloads in the cluster authenticate via Istio mTLS (SPIFFE XFCC) or present a SAM Task Biscuit.2. **Multi-Hop Sub-Agent Delegation Across Clusters:**- * When an orchestrator agent in Cluster A spawns a sub-agent or calls a remote MCP tool in Cluster B, it attenuates its SAM Task Biscuit offline (`tar_block` narrowing `allowed_services` and `allowed_actions`) and sends the request through `agentgateway` $\rightarrow$ `sam-node`.+ * When an orchestrator agent in Cluster A spawns a sub-agent or calls a remote MCP tool in Cluster B, it attenuates its SAM Task Biscuit offline (`tar_block` narrowing `allowed_services` and `allowed_tools` / `allowed_permissions`) and sends the request through `agentgateway` $\rightarrow$ `sam-node`.* The remote `sam-node` in Cluster B verifies the Control Plane signature, the standing policy, and every appended `TaskAuthorizationRule` block before forwarding to the MCP server or exchanging via `CloudTokenExchanger`.---@@ -563,8 +614,8 @@ flowchart LR### Blueprint 4: End-to-End Cloud Egress (BigQuery Read-Only Task & Sub-Agent Hop)**Setup, once per cloud project (no Google credential in the customer environment):**-* The cloud administrator creates a workload identity pool (workload principals) and, for human principals, a workforce identity pool, each with an OIDC provider whose issuer is the SAM control plane, or whose JWKS is uploaded when the control plane is not reachable from the internet. Attribute mapping: `google.subject = assertion.sub`, `attribute.task_class = assertion.sam_task_class`, `attribute.actor = assertion.act.sub`. Attribute condition: `assertion.act.sub` is one of the enrolled egress node peer IDs.-* IAM grants the ceiling: `roles/bigquery.dataViewer` on `projects/my-proj/datasets/sales_2026` to `principal://iam.googleapis.com/.../subject/[email protected]`, or to `principalSet://.../attribute.task_class/bq-read`.+* The cloud administrator creates a workload identity pool (workload principals) and, for human principals, a workforce identity pool, each with an OIDC provider whose issuer is the SAM control plane, or whose JWKS is uploaded when the control plane is not reachable from the internet. Attribute mapping: `google.subject = assertion.sub`, `google.groups = assertion.sam_roles`, `attribute.actor = assertion.act.sub`. Attribute condition: `assertion.act.sub` is one of the enrolled egress node peer IDs.+* IAM grants the ceiling: `roles/bigquery.dataViewer` on `projects/my-proj/datasets/sales_2026` to `principal://iam.googleapis.com/.../subject/[email protected]`, or to `principalSet://.../group/analyst` for every subject the mesh policy binds to the `analyst` role.* The mesh policy declares the destination:```yamlegress:@@ -582,21 +633,30 @@ flowchart LR```json{"name": "tasks/session-bq-read-sales",- "rules": [{- "allowed_services": ["egress://bigquery.googleapis.com", "mcp://bigquery"],- "operation": {- "allowed_actions": [- "bigquery.googleapis.com/datasets.get",- "bigquery.googleapis.com/tables.get",- "bigquery.googleapis.com/tables.getData",- "bigquery.googleapis.com/jobs.create"- ],- "allowed_methods": ["GET", "POST"]+ "rules": [+ {+ "allowed_services": ["egress://bigquery.googleapis.com"],+ "operation": {+ "allowed_methods": ["GET", "POST"],+ "allowed_paths": ["/bigquery/v2/projects/my-proj/datasets/sales_2026/*"],+ "allowed_permissions": [+ "bigquery.googleapis.com/datasets.get",+ "bigquery.googleapis.com/tables.get",+ "bigquery.googleapis.com/tables.getData",+ "bigquery.googleapis.com/jobs.create"+ ]+ },+ "allowed_resources": [+ "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/*"+ ]},- "allowed_resources": [- "//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/*"- ]- }]+ {+ "allowed_services": ["mcp://bigquery"],+ "operation": {+ "allowed_tools": ["list_tables", "query_sales"]+ }+ }+ ]}```2. **Hop 2 (Analytics Agent $\rightarrow$ Ephemeral Sub-Agent, CUJ 3):**@@ -607,8 +667,9 @@ flowchart LR"rules": [{"allowed_services": ["egress://bigquery.googleapis.com"],"operation": {- "allowed_actions": ["bigquery.googleapis.com/tables.getData"],- "allowed_methods": ["GET"]+ "allowed_methods": ["GET"],+ "allowed_paths": ["/bigquery/v2/projects/my-proj/datasets/sales_2026/tables/q1/*"],+ "allowed_permissions": ["bigquery.googleapis.com/tables.getData"]},"allowed_resources": ["//bigquery.googleapis.com/projects/my-proj/datasets/sales_2026/tables/q1"@@ -617,10 +678,10 @@ flowchart LR}```3. **Egress Enforcement, Issuer Mint & Cloud STS Exchange:**- * The egress `sam-node` (`egress-eu`, serving `egress://bigquery.googleapis.com`) verifies the Biscuit signature chain, the `actor_node` binding to the connection peer, the standing policy for `[email protected]`, and confirms the HTTP request (`GET /bigquery/v2/projects/my-proj/datasets/sales_2026/tables/q1/data`) satisfies **both** `TAR_1` and `TAR_2`.- * On a cache miss for this Biscuit digest it calls `POST /sts/token` on the control plane and receives an ES256 JWT (`[email protected]`, `act.sub=<egress-eu peer id>`, `aud=<pool provider>`, `sam_task=tasks/subagent-q1-only`, `sam_task_class=bq-read`, `exp` in minutes).- * `CloudTokenExchanger` exchanges the JWT at `sts.googleapis.com/v1/token` with `scope` narrowed to `bigquery.readonly`, caches the federated access token by Biscuit digest, and injects it as `Authorization: Bearer ...`. When the task token API is public it also forwards $\text{TAR}_1 \cap \text{TAR}_2$ (`allowed_actions: ["bigquery.googleapis.com/tables.getData"]`, `allowed_resources: [".../tables/q1"]`) in the provider's form; on AWS the same intersection becomes an `Effect: Allow` session policy.- * BigQuery's audit log records `principal://.../subject/[email protected]` with `attribute.task_class=bq-read`; the control plane's log records the same `sam_task`, so the two logs join.+ * The egress `sam-node` (`egress-eu`, serving `egress://bigquery.googleapis.com`) verifies the Biscuit signature chain, the `client_peer_id` binding to the connection peer, the standing policy for `[email protected]`, and confirms the HTTP request (`GET /bigquery/v2/projects/my-proj/datasets/sales_2026/tables/q1/data`) satisfies **both** `TAR_1` and `TAR_2` (`allowed_services`, `allowed_methods`, and `allowed_paths`).+ * On a cache miss for this Biscuit digest it calls `POST /sts/token` on the control plane and receives an ES256 JWT (`[email protected]`, `act.sub=<egress-eu peer id>`, `aud=<pool provider>`, `sam_roles=["analyst"]`, `sam_task=tasks/subagent-q1-only`, `exp` in minutes).+ * `CloudTokenExchanger` exchanges the JWT at `sts.googleapis.com/v1/token` with `scope` narrowed to `bigquery.readonly`, caches the federated access token by Biscuit digest, and injects it as `Authorization: Bearer ...`. When the task token API is public it also forwards $\text{TAR}_1 \cap \text{TAR}_2$ (`allowed_permissions: ["bigquery.googleapis.com/tables.getData"]`, `allowed_resources: [".../tables/q1"]`) in the provider's form; on AWS the same intersection becomes an `Effect: Allow` session policy.+ * BigQuery's audit log records `principal://.../subject/[email protected]` as a member of group `analyst`; the control plane's log records the same principal and `sam_task`, so the two logs join.---@@ -628,12 +689,13 @@ flowchart LR1. **The control plane becomes an identity provider the customer's cloud trusts.** That is the right place for it (the customer owns it), and it raises the bar: KMS- or HSM-backed ES256 key; JWT lifetime of minutes; one audience per destination; a CEL attribute condition on the cloud side that accepts only JWTs whose `act.sub` is an enrolled SAM egress node; detailed audit logging on the pool provider. A compromised issuer key exposes the IAM ceiling of every federated principal, the same as any IdP compromise; rotation with overlap and replacing the uploaded JWKS are the recovery path.2. **The control plane is on the egress path.** Caching per Biscuit digest for the JWT lifetime keeps it off the hot path, but it now needs HA and rate limits sized for egress and token exchange, not only enrollment. Kubernetes projected tokens rotate hourly and SPIRE JWT-SVIDs default to five minutes, so `POST /token/exchange` runs at the caller rotation rate.-3. **A task Biscuit is a bearer token at the local hop.** In blueprint 2 the sandbox holds it. Mitigations: lifetime of minutes to an hour; `actor_node` binds it to one origin node, so an exfiltrated token is useless to anyone who cannot reach that node's local socket or facade; `Seal()` for leaf tokens; the destination verifies the binding against the libp2p connection peer.+3. **A task Biscuit is a bearer token at the local hop.** In blueprint 2 the sandbox holds it. Mitigations: lifetime of minutes to an hour; `client_peer_id` binds it to one origin node, so an exfiltrated token is useless to anyone who cannot reach that node's local socket or facade; `Seal()` for leaf tokens; the destination verifies the binding against the libp2p connection peer.4. **Appended blocks are attacker-controlled bytes.** Structural validation (block count, one fact per block, no rules, no checks, payload size) runs before any authorizer is built; the TAR evaluator is trusted code with its own tests; limits are the same in all three verifiers.5. **Confused deputy at the egress node.** The node must never forward a caller-supplied `Authorization` to a destination (it strips it today) and must never let a TAR select a broker, a role or an audience. Both are unit-tested invariants.6. **Revocation and audit.** Revocation works on the authority block's revocation ID (section 3.4). Every border crossing is logged at the control plane (`/token/exchange`, `/sts/token`) with subject, actor, destination and `sam_task`; the cloud audit log carries the same principal, so the two logs join.7. **Per-task narrowing on Google Cloud is coarse today.** Paths, model names, scopes and attribute conditions; AWS session policies are the only fine-grained case. CUJ 1 and CUJ 2 must not be described as cloud-enforced per-task IAM on Google Cloud until the task token API is public.8. **Cross-organization reach of workforce principals.** Workforce pool principals cannot access resources outside their organization unless they may impersonate a service account; `impersonate` in the broker therefore widens reach and must be granted deliberately.+9. **Mesh role names are visible to the cloud.** `sam_roles` carries them as group names, and the cloud audit log records them. Role names are therefore not secrets, and a cloud administrator who binds a role to `principalSet://.../group/<role>` grants to every subject the mesh policy binds to that role, now and later.---@@ -645,24 +707,24 @@ A one-week spike settles the items marked **spike**; the others are checks again| :--- | :--- | :--- || 1 | Google Workload and Workforce Identity Federation accept a control-plane-issued ES256 JWT (`aud` = pool provider, `exp - iat` ≤ 24h), including the uploaded-JWKS path for a control plane that is not reachable from the internet. | **spike** || 2 | BigQuery and Vertex AI accept the federated principal directly or need service account impersonation (the "federated identity supported services" page, then a call against each API). | **spike** + docs |-| 3 | Cloud Audit Logs show the SAM principal (`google.subject`) and `attribute.task_class` for a BigQuery call made through the egress node. | **spike** |-| 4 | Workforce vs. workload pool: a human principal (`email`) federates through a workforce pool, a workload principal through a workload pool. Confirm one issuer can serve both and what `sub` each expects. | docs |+| 3 | Cloud Audit Logs show the SAM principal (`google.subject`) and the `google.groups` membership for a BigQuery call made through the egress node. | **spike** |+| 4 | Workforce vs. workload pool: a human principal (`email`) federates through a workforce pool, a workload principal through a workload pool. Confirm one issuer can serve both, what `sub` each expects, and that `google.groups` accepts the mesh role name syntax (`sam:role:node` carries colons) in both pool kinds. | docs || 5 | AWS `AssumeRoleWithWebIdentity` with a session policy compiled from a realistic TAR stays under the packed policy size limit; behaviour at the one-hour chaining limit. | test || 6 | Control-plane throughput and latency for `/token/exchange` and `/sts/token` with caching; cache hit rate with 5-minute JWT-SVIDs and 1-hour projected tokens. | `sam-bench` |-| 7 | biscuit-go v2.2.0: reading the facts of block $i$ through the `pb` package vs. parsing `Code()`; `Seal()` on a token with appended blocks; whether `check if` queries are bounded by `WithMaxDuration` (section 3.1 assumes they are not) and whether the worker goroutine outlives a timeout. | **spike** |-| 8 | biscuit-wasm and biscuit-python expose block inspection and equivalent limits; conformance vectors in `sdk/testdata` pass in all three verifiers. | test |+| 7 | biscuit-go v2.2.0: reading the facts of block $i$ through the `pb` package vs. parsing `Code()`; `Seal()` on a token with appended blocks; whether `check if` queries are bounded by `WithMaxDuration` (section 3.1 assumes they are not) and whether the worker goroutine outlives a timeout. **Resolved (Phase 2):** structural counts come from `pb.Biscuit.Blocks[i-1]` (`FactsV2`/`RulesV2`/`ChecksV2`) and the fact string from `b.Code()` matched against `^tar_block\("([A-Za-z0-9_-]+)"\);?\s*$`; `Seal()` works on tokens with appended blocks. | **resolved** |+| 8 | biscuit-wasm and biscuit-python expose block inspection and equivalent limits; conformance vectors in `sdk/testdata` pass in all three verifiers. **Note:** `biscuit-wasm` 0.6 exposes `getBlockSource(i)` and `sealToken()`; `biscuit-python` 0.4 exposes `block_count`, `block_source`, `append` and `revocation_ids` (sufficient to verify sealed tokens in Phase 2; Phase 4's Python `.seal()` will upgrade `biscuit-python`). | **resolved (Phase 2)** || 9 | Off-the-shelf MCP clients (Claude Code, Gemini CLI, Cursor, VS Code) complete authorization code + PKCE against the control plane as authorization server, with client ID metadata documents and without dynamic client registration. | **spike** || 10 | agentgateway's token-exchange backend authentication works against `sam-node`'s `/oauth/token` with a Biscuit as the issued token (opaque to the gateway); ext_authz response header size limits for an injected cloud credential. | test || 11 | Publication status of the Google task token API; until public, the adapter interface is the only coupling. | track || 12 | Path shapes for model-level PEP: Vertex AI (`/v1/projects/P/locations/L/publishers/google/models/M:generateContent`) and Gemini Developer API (`/v1beta/models/M:generateContent`), including streaming variants. | docs || 13 | Google APIs that reject federated identities under VPC Service Controls, and the egress rule needed for `sts.googleapis.com` when the pool is organization-level. | docs |-| 14 | Which sections of `AGENTS.md`, `site/content/docs/preview/agent-architecture.md` and `sandboxed-agents.md` change, and whether `AgentBundle` / `AgentAttach*` messages are removed or repurposed as "attach = mint task token". | review |-| 15 | Whether `internal/tunnel` (Cloudflare and Codespaces mesh reachability) is removed with the sandbox code or kept; it has no sandbox dependency. | review |+| 14 | Which sections of `AGENTS.md`, `site/content/docs/preview/agent-architecture.md` and `sandboxed-agents.md` change, and whether `AgentBundle` / `AgentAttach*` messages are removed or repurposed as "attach = mint task token". **Resolved:** `AgentBundle`/`AgentAttach*` removed in Phase 1; docs rewritten in Phase 5. | **resolved** |+| 15 | Whether `internal/tunnel` (Cloudflare and Codespaces mesh reachability) is removed with the sandbox code or kept; it has no sandbox dependency. **Resolved:** kept. | **resolved** || 16 | Istio: the `ext_authz` `CheckRequest` carries `source.principal` from ambient waypoints as it does from sidecars; XFCC is trusted only on the proxy path. | test |-| 17 | Model Armor: `sanitizeUserPrompt` / `sanitizeModelResponse` accept a federated principal; per-call latency and quota at the egress node's request rate; template selection per `sam_task_class`; which payload shapes (Gemini, OpenAI-compatible, MCP `tools/call`, A2A) the public API sanitizes and which it passes. | **spike** |+| 17 | Model Armor: `sanitizeUserPrompt` / `sanitizeModelResponse` accept a federated principal; per-call latency and quota at the egress node's request rate; which payload shapes (Gemini, OpenAI-compatible, MCP `tools/call`, A2A) the public API sanitizes and which it passes. | **spike** || 18 | gRPC over the mesh: whether the libp2p HTTP stream can carry HTTP/2 framing and trailers end to end so `httputil.ReverseProxy` forwards gRPC; otherwise tunnel mode plus REST-transport guidance for Google client libraries. | **spike** || 19 | Operator chain: Secure Web Proxy explicit mode and agentgateway as `target_url` with `preserve_host`; Cloud NGFW Enterprise TLS inspection with the egress node trusting the inspection CA, and agents trusting it for tunnel mode. | test |-| 20 | `ext_proc` with no new root-module dependency: the trimmed protos under `third_party/envoy/` (with `LICENSE` and `METADATA` as Google's third-party policy requires) generate with the pinned `protoc-gen-go` and produce bytes identical to `go-control-plane`'s for a captured `ProcessingRequest` and `ProcessingResponse`; the standard-library gRPC client interoperates with a grpc-go reference processor and a Service Extensions callout example (trailers-only responses, `grpc-timeout`, cancellation from either side, `unix:` and h2c through `Protocols.SetUnencryptedHTTP2`, TLS with ALPN `h2`, a processor behind a gRPC-aware load balancer); `immediate_response` after response headers were sent resets the stream as in Envoy; the conformance module under `tests/extproc/` runs in the integration suite within its time budget. Track the package name the donated project publishes. Decide whether the `ext_proc` *server* (section 4.1) ships with the first release. | **spike** + decision |+| 20 | `ext_proc` with no new root-module dependency: the trimmed protos under `third_party/envoy/` (with `LICENSE` and `METADATA` as Google's third-party policy requires) generate with the pinned `protoc-gen-go` and produce bytes identical to `go-control-plane`'s for a captured `ProcessingRequest` and `ProcessingResponse`; the standard-library gRPC client interoperates with a grpc-go reference processor and a Service Extensions callout example (trailers-only responses, `grpc-timeout`, cancellation from either side, `unix:` and h2c through `Protocols.SetUnencryptedHTTP2`, TLS with ALPN `h2`, a processor behind a gRPC-aware load balancer); `immediate_response` after response headers were sent resets the stream as in Envoy; the conformance module under `tests/extproc/` runs in the integration suite within its time budget. Track the package name the donated project publishes. **Decision:** ship both the `ext_proc` egress client (section 5.6) and the `ext_proc` gateway server (section 4.1) using the shared stdlib gRPC stream and vendored protos. | **spike** + **decided** || 21 | Tunnel SNI check: behaviour for destinations that send no SNI (IP literals, some database drivers) and for Encrypted Client Hello; the `ports` allow-list is enforced before any dial. | test || 22 | Model Armor streaming: whether `StreamSanitizeUserPrompt` / `StreamSanitizeModelResponse` are worth vendoring the Model Armor protos (they import `google/api` annotations that would need the same trimming) on top of the standard-library gRPC transport, or whether `BUFFERED` and `REQUEST_ONLY` over the REST API suffice; whether Model Armor itself is reachable as an `ext_proc` processor outside Google's managed Service Extensions. | decision + docs |@@ -675,11 +737,11 @@ A one-week spike settles the items marked **spike**; the others are checks again* Update [`AGENTS.md`](file:///usr/local/google/home/aojea/src/sam/AGENTS.md) to reflect the retired sandbox dataplane and the RFC 8693 / OAuth 2.1 surface carve-out.* Validate the clean baseline with `make`, `make lint`, `make test`, and `make sdk-test`.2. **Phase 2 — Protobuf & Safe `tar_block` Biscuit Attenuation (`api/`, `internal/identity/`, `sdk/`):**- * Add `TaskAuthorizationRule`, `TaskRule`, `TaskOperation`, and token exchange messages to [`api/sam.proto`](file:///usr/local/google/home/aojea/src/sam/api/sam.proto).+ * Add `TaskAuthorizationRule`, `TaskRule` and `TaskOperation` to [`api/sam.proto`](file:///usr/local/google/home/aojea/src/sam/api/sam.proto). The exchange and mint messages (`TokenExchangeRequest`/`Response`, `STSTokenRequest`/`Response`) and the `actor_node` fact land in Phase 3 with the handlers that give them their shape.* Implement `AttenuateBiscuit`, `SealBiscuit`, and `ExtractTaskRules` in `internal/identity/biscuit.go`.* Update [`UnmarshalInbound`](file:///usr/local/google/home/aojea/src/sam/internal/identity/biscuit.go#L78-L87) (and JS/Python SDK verifiers, backed by conformance vectors in `sdk/testdata/`) to accept appended blocks containing **0 rules, 0 checks, and 1 `tar_block(<base64-proto>)` fact**, evaluating the decoded `TaskAuthorizationRule` chain in the verifier.3. **Phase 3 — Stateless Control-Plane Exchange & `sam-node` Origin STS / `ext_authz` (`internal/controlplane/`, `internal/node/`):**- * Add stateless `POST /token/exchange` (`actor_node` + `subject_token` verification) and OAuth 2.1 AS endpoints to `sam-control-plane`.+ * Add stateless `POST /token/exchange` (`actor_node` + `subject_token` verification) and OAuth 2.1 AS endpoints to `sam-control-plane`, with their messages in `api/sam.proto` (instants as `*_time`, the proof-of-possession value as `challenge_unix_ms`). `SamNode.Authorize` binds a request token on `client_peer_id` in the authority block (section 3.3), with a conformance vector for a delegated token that carries no `node()` fact.* Make the control plane an OIDC issuer (section 3.5): ES256 key with a KMS/HSM option and overlap rotation, `/.well-known/openid-configuration`, `/jwks`, stateless `POST /sts/token` (Biscuit $\rightarrow$ JWT), `GET /revocations`, rate limits from `internal/ratelimit`, an audit log line for every crossing. Section 8 items 1–4 run against a test project before this phase is considered done.* Add RFC 8693 `POST /oauth/token`, `POST /oauth/revoke`, `/.well-known/oauth-protected-resource`, and Envoy `ext_authz` check support to `sam-node`.* Update `withAuth` (scoping transparent JWT exchange on `Authorization` strictly to `/mcp` and `/v1/*`) and `createEgressProxy` / `mcp.go` to forward caller Task Biscuits.