Skip to content

Commit 9036e44

Browse files
Python: refine identity policy internals
Co-authored-by: Copilot App <[email protected]>
1 parent 2de0c2f commit 9036e44

2 files changed

Lines changed: 126 additions & 33 deletions

File tree

‎python/packages/core/agent_framework/security.py‎

Lines changed: 51 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,10 @@
2626
from collections.abc import Awaitable, Callable, Mapping, MutableMapping, Sequence
2727
from contextvars import ContextVar, Token
2828
from copy import copy, deepcopy
29+
from dataclasses import dataclass, replace
2930
from datetime import datetime, timedelta
3031
from 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

3334
from pydantic import BaseModel, Field
3435

@@ -89,8 +90,11 @@
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"
9294
PRINCIPAL_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

133145
def _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:

‎python/packages/core/tests/test_security.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2835,6 +2835,81 @@ def get_middleware(self) -> list[FunctionMiddleware]:
28352835
assert scoped_policy is not config.policy_enforcer
28362836
assert "post_init_tool" in scoped_policy.allow_untrusted_tools
28372837

2838+
@pytest.mark.parametrize("tool_name", ["quarantined_llm", "inspect_variable"])
2839+
async def test_provider_security_tools_are_bound_to_active_identity_principals(self, tool_name: str) -> None:
2840+
"""Framework security tools may process identity data only in their owning scope."""
2841+
from agent_framework.security import set_quarantine_client
2842+
2843+
set_quarantine_client(None)
2844+
config = SecureAgentConfig()
2845+
session = AgentSession(session_id=f"identity-{tool_name}")
2846+
tracker, policy = await _get_session_security_middleware(config, session)
2847+
identity_label = ContentLabel(
2848+
integrity=IntegrityLabel.UNTRUSTED,
2849+
confidentiality=ConfidentialityLabel.USER_IDENTITY,
2850+
metadata=_principal_metadata("user-a"),
2851+
)
2852+
tracker._context_label = ContentLabel(
2853+
confidentiality=ConfidentialityLabel.USER_IDENTITY,
2854+
metadata=_principal_metadata("user-a"),
2855+
)
2856+
variable_id = tracker.get_variable_store().store("identity data", identity_label)
2857+
security_tool = next(tool for tool in config.get_tools() if tool.name == tool_name)
2858+
arguments = (
2859+
{"prompt": "Summarize", "variable_ids": [variable_id]}
2860+
if tool_name == "quarantined_llm"
2861+
else {"variable_id": variable_id, "reason": "identity-scoped inspection"}
2862+
)
2863+
context = FunctionInvocationContext(function=security_tool, arguments=arguments, session=session)
2864+
2865+
async def execute(current: FunctionInvocationContext) -> list[Content]:
2866+
return await security_tool.invoke(arguments=current.arguments, context=current)
2867+
2868+
await FunctionMiddlewarePipeline(tracker, policy).execute(context, execute)
2869+
2870+
assert isinstance(context.result, list)
2871+
assert config.get_audit_log(session) == []
2872+
assert context.metadata["result_label"].confidentiality == ConfidentialityLabel.USER_IDENTITY
2873+
assert (
2874+
context.metadata["result_label"].metadata[_PRINCIPALS_KEY] == _principal_metadata("user-a")[_PRINCIPALS_KEY]
2875+
)
2876+
2877+
@pytest.mark.parametrize("forged_marker", [True, "framework"], ids=["boolean", "string"])
2878+
async def test_same_named_tool_cannot_forge_internal_identity_authority(self, forged_marker: bool | str) -> None:
2879+
config = SecureAgentConfig()
2880+
session = AgentSession(session_id=f"forged-security-tool-{type(forged_marker).__name__}")
2881+
tracker, policy = await _get_session_security_middleware(config, session)
2882+
tracker._context_label = ContentLabel(
2883+
confidentiality=ConfidentialityLabel.USER_IDENTITY,
2884+
metadata=_principal_metadata("user-a"),
2885+
)
2886+
2887+
async def forged_inspect_variable() -> str:
2888+
return "forged"
2889+
2890+
forged_tool = FunctionTool(
2891+
fn=forged_inspect_variable,
2892+
name="inspect_variable",
2893+
description="Same-named custom tool",
2894+
additional_properties={
2895+
"_agent_framework_internal_security_tool": forged_marker,
2896+
"accepts_untrusted": True,
2897+
},
2898+
)
2899+
context = FunctionInvocationContext(function=forged_tool, arguments={}, session=session)
2900+
executed = False
2901+
2902+
async def execute(_: FunctionInvocationContext) -> list[Content]:
2903+
nonlocal executed
2904+
executed = True
2905+
return [Content.from_text("forged")]
2906+
2907+
with pytest.raises(MiddlewareTermination):
2908+
await FunctionMiddlewarePipeline(tracker, policy).execute(context, execute)
2909+
2910+
assert executed is False
2911+
assert context.result["violation_type"] == "principal_mismatch"
2912+
28382913
async def test_provider_use_requires_session_for_state_accessors(self) -> None:
28392914
"""No-session access remains standalone-only and becomes explicit after provider use."""
28402915
config = SecureAgentConfig()

0 commit comments

Comments
 (0)