2626from collections .abc import Awaitable , Callable , Mapping , MutableMapping , Sequence
2727from contextvars import ContextVar , Token
2828from copy import copy , deepcopy
29+ from dataclasses import dataclass , replace
2930from datetime import datetime , timedelta
3031from enum import Enum
31- from typing import TYPE_CHECKING , Annotated , Any , NamedTuple , NoReturn , cast
32+ from typing import TYPE_CHECKING , Annotated , Any , NoReturn , cast
3233
3334from pydantic import BaseModel , Field
3435
8990_INTERNAL_RESULT_MARKER = object ()
9091_MAX_VARIABLE_REFERENCE_DEPTH = 16
9192_MAX_VARIABLE_REFERENCE_COUNT = 100
93+ _LEGACY_AUTHORITATIVE_CONFIDENTIALITY = "_security_label_authoritative_confidentiality"
9294PRINCIPAL_METADATA_KEY = "agent_framework.security.principals"
9395
96+ _INTERNAL_SECURITY_TOOL = "_agent_framework_internal_security_tool"
97+ _INTERNAL_SECURITY_TOOL_MARKER = object ()
9498# Tools that consume variable IDs literally (as opaque references) and therefore
9599# must NOT have ``var_xxx`` arguments expanded to stored content before execution.
96100# ``inspect_variable`` looks the ID up itself; ``quarantined_llm`` resolves the
@@ -105,12 +109,20 @@ def _get_additional_properties(obj: Any) -> dict[str, Any]:
105109 return cast (dict [str , Any ], props ) if isinstance (props , dict ) else {}
106110
107111
108- def _canonical_principals (value : Any , * , source : str ) -> tuple [tuple [str , str ], ...]:
112+ @dataclass (frozen = True , order = True , slots = True )
113+ class _Principal :
114+ """Canonical tenant/user identity used internally for comparisons."""
115+
116+ tenant_id : str
117+ user_id : str
118+
119+
120+ def _canonical_principals (value : Any , * , source : str ) -> tuple [_Principal , ...]:
109121 """Validate and canonicalize a principal-set declaration."""
110122 if not isinstance (value , Sequence ) or isinstance (value , (str , bytes , bytearray )) or not value :
111123 raise ValueError (f"{ source } principals must be a non-empty sequence" )
112124
113- principals : set [tuple [ str , str ] ] = set ()
125+ principals : set [_Principal ] = set ()
114126 for item in cast (Sequence [Any ], value ):
115127 if not isinstance (item , Mapping ):
116128 raise ValueError (f"{ source } principals must contain mappings" )
@@ -121,13 +133,13 @@ def _canonical_principals(value: Any, *, source: str) -> tuple[tuple[str, str],
121133 user_id = principal .get ("user_id" )
122134 if type (tenant_id ) is not str or not tenant_id .strip () or type (user_id ) is not str or not user_id .strip ():
123135 raise ValueError (f"{ source } principal identifiers must be non-empty strings" )
124- principals .add ((tenant_id , user_id ))
136+ principals .add (_Principal (tenant_id = tenant_id , user_id = user_id ))
125137 return tuple (sorted (principals ))
126138
127139
128- def _principal_list (principals : Sequence [tuple [ str , str ] ]) -> list [dict [str , str ]]:
140+ def _principal_list (principals : Sequence [_Principal ]) -> list [dict [str , str ]]:
129141 """Return the serialized canonical representation of a principal set."""
130- return [{"tenant_id" : tenant_id , "user_id" : user_id } for tenant_id , user_id in principals ]
142+ return [{"tenant_id" : principal . tenant_id , "user_id" : principal . user_id } for principal in principals ]
131143
132144
133145def _principal_binding_key (value : Any , * , source : str ) -> str :
@@ -349,7 +361,7 @@ def combine_labels(*labels: ContentLabel) -> ContentLabel:
349361 })
350362
351363 if confidentiality == ConfidentialityLabel .USER_IDENTITY :
352- principal_sets : list [tuple [tuple [ str , str ] , ...]] = []
364+ principal_sets : list [tuple [_Principal , ...]] = []
353365 principals_valid = True
354366 for label in labels :
355367 if label .confidentiality != ConfidentialityLabel .USER_IDENTITY :
@@ -2020,7 +2032,7 @@ def _extract_content_label(
20202032 """
20212033 additional_props = _get_additional_properties (item )
20222034 authoritative_marker = additional_props .pop (_AUTHORITATIVE_SECURITY_LABEL , None )
2023- additional_props .pop ("_security_label_authoritative_confidentiality" , None )
2035+ additional_props .pop (_LEGACY_AUTHORITATIVE_CONFIDENTIALITY , None )
20242036 inspect_error_marker = additional_props .pop (_INSPECT_VARIABLE_ERROR , None )
20252037 authoritative_label = authoritative_marker is _INTERNAL_RESULT_MARKER
20262038 inspect_error = function_name == "inspect_variable" and inspect_error_marker is _INTERNAL_RESULT_MARKER
@@ -2225,7 +2237,8 @@ def get_current_middleware() -> LabelTrackingFunctionMiddleware | None:
22252237 return _current_middleware .get ()
22262238
22272239
2228- class _PendingPolicyApproval (NamedTuple ):
2240+ @dataclass (frozen = True , slots = True )
2241+ class _PendingPolicyApproval :
22292242 """Immutable binding record for a pending policy-violation approval.
22302243
22312244 Captures every dimension a granted approval is bound to so a reused ``call_id`` cannot
@@ -2265,16 +2278,16 @@ def to_state(self) -> dict[str, Any]:
22652278 "created_at" : self .created_at ,
22662279 }
22672280
2268- def binding_key (self ) -> tuple [ str , str , str , str , str , str , tuple [ str , ...]] :
2269- """Return every authorization dimension except lifecycle metadata ."""
2281+ def matches_binding (self , other : _PendingPolicyApproval ) -> bool :
2282+ """Return whether another record represents the same reviewed authorization ."""
22702283 return (
2271- self .body_signature ,
2272- self .resolved_signature ,
2273- self .label_key ,
2274- self .effective_label_key ,
2275- self .destination_principal_key ,
2276- self .session_key ,
2277- self .disclosed_violations ,
2284+ self .body_signature == other . body_signature
2285+ and self .resolved_signature == other . resolved_signature
2286+ and self .label_key == other . label_key
2287+ and self .effective_label_key == other . effective_label_key
2288+ and self .destination_principal_key == other . destination_principal_key
2289+ and self .session_key == other . session_key
2290+ and self .disclosed_violations == other . disclosed_violations
22782291 )
22792292
22802293 @classmethod
@@ -2535,7 +2548,7 @@ def _label_key(label_data: Any) -> str:
25352548 )
25362549 principal_key = _principal_binding_key (principal_value , source = "approval label" )
25372550 return f"{ label_dict .get ('integrity' , '' )} /{ confidentiality } /{ principal_key } "
2538- return "// "
2551+ return "/"
25392552
25402553 def _destination_principal_key (self , context : FunctionInvocationContext ) -> str :
25412554 function_props = _get_additional_properties (context .function )
@@ -2611,7 +2624,7 @@ def _matches_pending_approval(
26112624 and approval_response .approved is True
26122625 ):
26132626 return False
2614- return current_binding .binding_key () == pending . binding_key ( ) and self ._response_matches_pending (
2627+ return current_binding .matches_binding ( pending ) and self ._response_matches_pending (
26152628 approval_response , approval_id , call_id , pending .body_signature , pending .request_id
26162629 )
26172630
@@ -2685,7 +2698,7 @@ def _request_policy_violation_approval(
26852698 )
26862699 request_id = f"{ approval_id } :replacement:{ uuid .uuid4 ().hex } " if is_replacement else approval_id
26872700 if approval_id :
2688- self ._store_pending_approval (approval_id , binding . _replace ( request_id = request_id ))
2701+ self ._store_pending_approval (approval_id , replace ( binding , request_id = request_id ))
26892702 additional_properties : dict [str , Any ] = {
26902703 _APPROVAL_REQUEST_ID_KEY : request_id ,
26912704 "_replacement_approval_request" : is_replacement ,
@@ -2964,25 +2977,28 @@ def _check_confidentiality_policy_detailed(
29642977 }
29652978
29662979 if label .confidentiality == ConfidentialityLabel .USER_IDENTITY :
2967- if max_allowed_conf != ConfidentialityLabel .USER_IDENTITY .value :
2968- return {
2969- "passed" : False ,
2970- "failure_type" : "principal_mismatch" ,
2971- "reason" : "USER_IDENTITY destination does not declare an authorized principal set" ,
2972- }
29732980 try :
29742981 source_principals = set (
29752982 _canonical_principals (
29762983 label .metadata .get (PRINCIPAL_METADATA_KEY ),
29772984 source = "source label" ,
29782985 )
29792986 )
2980- destination_principals = set (
2981- _canonical_principals (
2982- function_props .get (PRINCIPAL_METADATA_KEY ),
2983- source = f"tool { context .function .name } " ,
2987+ if function_props .get (_INTERNAL_SECURITY_TOOL ) is _INTERNAL_SECURITY_TOOL_MARKER :
2988+ destination_principals = source_principals
2989+ else :
2990+ if max_allowed_conf != ConfidentialityLabel .USER_IDENTITY .value :
2991+ return {
2992+ "passed" : False ,
2993+ "failure_type" : "principal_mismatch" ,
2994+ "reason" : "USER_IDENTITY destination does not declare an authorized principal set" ,
2995+ }
2996+ destination_principals = set (
2997+ _canonical_principals (
2998+ function_props .get (PRINCIPAL_METADATA_KEY ),
2999+ source = f"tool { context .function .name } " ,
3000+ )
29843001 )
2985- )
29863002 except ValueError :
29873003 return {
29883004 "passed" : False ,
@@ -3502,6 +3518,7 @@ def _quarantined_llm_result_parser(result: Any) -> list[Content]:
35023518 "confidentiality" : "private" ,
35033519 "accepts_untrusted" : True ,
35043520 "source_integrity" : "untrusted" ,
3521+ _INTERNAL_SECURITY_TOOL : _INTERNAL_SECURITY_TOOL_MARKER ,
35053522 # source_integrity is declared as UNTRUSTED because this tool
35063523 # processes external/untrusted data. The middleware uses this
35073524 # (Tier 2) to label the output UNTRUSTED and auto-hide it via
@@ -3791,6 +3808,7 @@ def _inspect_variable_result_parser(result: Any) -> list[Content]:
37913808 result_parser = _inspect_variable_result_parser ,
37923809 additional_properties = {
37933810 "confidentiality" : _INSPECT_VARIABLE_CONFIDENTIALITY .value ,
3811+ _INTERNAL_SECURITY_TOOL : _INTERNAL_SECURITY_TOOL_MARKER ,
37943812 # No source_integrity declared: output inherits the label of the
37953813 # inspected content via Tier 3. The variable store is just a
37963814 # container — the data inside it is untrusted external content.
@@ -4221,7 +4239,7 @@ def _stamp_mcp_content_labels(
42214239 continue
42224240 props = item .additional_properties or {}
42234241 props .pop (_AUTHORITATIVE_SECURITY_LABEL , None )
4224- props .pop ("_security_label_authoritative_confidentiality" , None )
4242+ props .pop (_LEGACY_AUTHORITATIVE_CONFIDENTIALITY , None )
42254243 server_meta = props .pop (_MCP_RESULT_META_KEY , None )
42264244 dynamic = _label_from_mcp_meta (server_meta ) if server_meta else None
42274245 if dynamic is None :
0 commit comments