Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 36 additions & 25 deletions python/packages/purview/agent_framework_purview/_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ def _is_valid_guid(value: str | None) -> bool:
return False


def _get_message_user_id(message: Message) -> str | None:
"""Return the message's explicit user id: a valid ``user_id`` property, else a GUID ``author_name``."""
potential_user_id = (message.additional_properties or {}).get("user_id")
if isinstance(potential_user_id, str) and _is_valid_guid(potential_user_id):
return potential_user_id
if _is_valid_guid(message.author_name):
return message.author_name
return None


# RFC 2397: data:[<mediatype>][;base64],<data>, where <mediatype> may be followed by any number of
# ";parameter=value" segments (for example "data:text/plain;charset=utf-8;base64,..."). The optional
# parameters have to be matched explicitly, otherwise a parameterised media type fails to decode and
Expand Down Expand Up @@ -212,12 +222,13 @@ async def process_messages(
messages: The messages to process
activity: The activity type (e.g., UPLOAD_TEXT)
session_id: Optional session/conversation id. Else, a new GUID is generated.
user_id: Optional user_id to use for all messages. If provided, this is the fallback.
user_id: Optional user_id to use for all messages when the credential does not identify a user.
Otherwise, each message is evaluated under its own user id.

Returns:
A tuple of (should_block: bool, resolved_user_id: str | None).
The resolved_user_id can be stored and passed back when processing the response
to ensure the same user context is maintained throughout the request/response cycle.
The resolved_user_id is the user id of the last message. It can be stored and passed back when
processing the response so the response is evaluated under the same user context.
"""
pc_requests, resolved_user_id = await self._map_messages(messages, activity, session_id, user_id)
should_block = False
Expand Down Expand Up @@ -245,10 +256,12 @@ async def _map_messages(
messages: The messages to map
activity: The activity type
session_id: Optional session/conversation id to use for correlation
provided_user_id: Optional user_id to use. If provided, this is the fallback.
provided_user_id: Optional user_id to use for all messages when the credential does not identify a
user. Otherwise, each message uses its own user id, and messages without one inherit the latest
explicit user id in the batch.

Returns:
A tuple of (requests, resolved_user_id)
A tuple of (requests, resolved_user_id), where resolved_user_id is the user id of the last message.
"""
results: list[ProcessContentRequest] = []
token_info = await self._client.get_user_info_from_token(tenant_id=self._settings.get("tenant_id"))
Expand All @@ -257,34 +270,32 @@ async def _map_messages(
if not tenant_id or not _is_valid_guid(tenant_id):
raise ValueError("Tenant id required or must be inferable from credential")

resolved_user_id = (token_info or {}).get("user_id")
resolved_author_name = None
if not resolved_user_id:
resolved_user_id = provided_user_id if provided_user_id and _is_valid_guid(provided_user_id) else None

if not resolved_user_id:
for m in messages:
if m.additional_properties:
potential_user_id = m.additional_properties.get("user_id")
if _is_valid_guid(potential_user_id):
resolved_user_id = potential_user_id
break
if m.author_name and _is_valid_guid(m.author_name) and not resolved_author_name:
resolved_author_name = m.author_name
message_list = list(messages)
override_user_id = (token_info or {}).get("user_id")
if not override_user_id:
override_user_id = provided_user_id if provided_user_id and _is_valid_guid(provided_user_id) else None

if not resolved_user_id and resolved_author_name:
resolved_user_id = resolved_author_name
# Leading messages without an identity (e.g. system or generated messages) use the first explicit identity.
inherited_user_id = override_user_id or next(
(uid for uid in map(_get_message_user_id, message_list) if uid), None
)

# Fail closed: without a resolvable user identity no policy can be evaluated,
# so the content must not be allowed through unevaluated.
if not resolved_user_id or not _is_valid_guid(resolved_user_id):
if not inherited_user_id or not _is_valid_guid(inherited_user_id):
raise ValueError(
"No user id provided or inferred for Purview request. Please provide an Entra user id in each "
"message, pass a user id to the processor, or configure the credential to authenticate to an "
"Entra user."
)

for m in messages:
for m in message_list:
if not override_user_id:
# Messages without an identity (e.g. assistant or tool messages) are attributed to the
# latest explicitly identified user, without overriding later explicit identities.
inherited_user_id = _get_message_user_id(m) or inherited_user_id
resolved_user_id = inherited_user_id

message_id = m.message_id or str(uuid.uuid4())
correlation_id = (session_id or str(uuid.uuid4())) + "@AF"
# This would be c# ticks equivalent and needs to fit inside c# long
Expand Down Expand Up @@ -337,13 +348,13 @@ async def _map_messages(
)
req = ProcessContentRequest(
content_to_process=ctp,
user_id=resolved_user_id, # Use the resolved user_id for all messages
user_id=resolved_user_id,
tenant_id=tenant_id,
correlation_id=correlation_id,
process_inline=None, # Will be set based on execution mode
)
results.append(req)
return results, resolved_user_id
return results, inherited_user_id

async def _process_with_scopes(self, pc_request: ProcessContentRequest) -> ProcessContentResponse:
app_location = pc_request.content_to_process.protected_app_metadata.application_location
Expand Down
78 changes: 65 additions & 13 deletions python/packages/purview/tests/purview/test_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1236,35 +1236,87 @@ async def test_multiple_messages_same_user_id(self, mock_client: AsyncMock, sett
# All requests should have the same user_id
assert all(req.user_id == "55555555-5555-5555-5555-555555555555" for req in requests)

async def test_first_valid_user_id_in_messages_is_used(
self, mock_client: AsyncMock, settings: PurviewSettings
) -> None:
"""Test that the first valid user_id found in messages is used for all."""
async def test_each_message_uses_its_own_user_id(self, mock_client: AsyncMock, settings: PurviewSettings) -> None:
"""Test that messages from different users are evaluated under each user's own id.

Messages without an id inherit the latest explicit id; leading ones use the first explicit id.
"""
processor = ScopedContentProcessor(mock_client, settings)
mock_client.get_user_info_from_token.return_value = {
"tenant_id": "12345678-1234-1234-1234-123456789012",
"client_id": "12345678-1234-1234-1234-123456789012",
}
user_a = "66666666-6666-6666-6666-666666666666"
user_b = "77777777-7777-7777-7777-777777777777"

messages = [
Message(role="user", contents=["First"], author_name="Not a GUID"),
Message(role="system", contents=["System"]),
Message(
role="assistant",
contents=["Response"],
additional_properties={"user_id": "66666666-6666-6666-6666-666666666666"},
role="user", contents=["From A"], author_name="Not a GUID", additional_properties={"user_id": user_a}
),
Message(role="assistant", contents=["Reply to A"]),
Message(role="user", contents=["From A again"], author_name=user_a),
Message(role="user", contents=["From B"], additional_properties={"user_id": user_b}),
Message(role="assistant", contents=["Reply to B"]),
]

requests, user_id = await processor._map_messages(messages, Activity.UPLOAD_TEXT)

assert [req.user_id for req in requests] == [user_a, user_a, user_a, user_a, user_b, user_b]
assert user_id == user_b

async def test_user_id_property_takes_priority_over_author_name(
self, mock_client: AsyncMock, settings: PurviewSettings
) -> None:
"""Test a message's user_id property wins over a GUID author_name on the same message."""
processor = ScopedContentProcessor(mock_client, settings)
mock_client.get_user_info_from_token.return_value = {
"tenant_id": "12345678-1234-1234-1234-123456789012",
"client_id": "12345678-1234-1234-1234-123456789012",
}

messages = [
Message(
role="user",
contents=["Third"],
additional_properties={"user_id": "77777777-7777-7777-7777-777777777777"},
),
contents=["Test"],
author_name="33333333-3333-3333-3333-333333333333",
additional_properties={"user_id": "66666666-6666-6666-6666-666666666666"},
)
]

requests, user_id = await processor._map_messages(messages, Activity.UPLOAD_TEXT)

# First valid user_id (from second message) should be used
assert user_id == "66666666-6666-6666-6666-666666666666"
assert all(req.user_id == "66666666-6666-6666-6666-666666666666" for req in requests)
assert requests[0].user_id == "66666666-6666-6666-6666-666666666666"

@pytest.mark.parametrize("override_source", ["token", "provided"])
async def test_override_user_id_applies_to_all_messages(
self, mock_client: AsyncMock, settings: PurviewSettings, override_source: str
) -> None:
"""Test that a token or provided user id is used for every message, ignoring per-message ids."""
processor = ScopedContentProcessor(mock_client, settings)
override = "11111111-1111-1111-1111-111111111111"
provided_user_id = None
if override_source == "provided":
mock_client.get_user_info_from_token.return_value = {
"tenant_id": "12345678-1234-1234-1234-123456789012",
"client_id": "12345678-1234-1234-1234-123456789012",
}
provided_user_id = override

messages = [
Message(
role="user", contents=["A"], additional_properties={"user_id": "66666666-6666-6666-6666-666666666666"}
),
Message(role="user", contents=["B"], author_name="77777777-7777-7777-7777-777777777777"),
]

requests, user_id = await processor._map_messages(
messages, Activity.UPLOAD_TEXT, provided_user_id=provided_user_id
)

assert user_id == override
assert [req.user_id for req in requests] == [override, override]


class TestScopedContentProcessorCaching:
Expand Down
Loading