Skip to content

Commit 13956ad

Browse files
authored
Fix per message user mapping in purview (#10193)
1 parent f87ec53 commit 13956ad

2 files changed

Lines changed: 101 additions & 38 deletions

File tree

‎python/packages/purview/agent_framework_purview/_processor.py‎

Lines changed: 36 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,16 @@ def _is_valid_guid(value: str | None) -> bool:
5858
return False
5959

6060

61+
def _get_message_user_id(message: Message) -> str | None:
62+
"""Return the message's explicit user id: a valid ``user_id`` property, else a GUID ``author_name``."""
63+
potential_user_id = (message.additional_properties or {}).get("user_id")
64+
if isinstance(potential_user_id, str) and _is_valid_guid(potential_user_id):
65+
return potential_user_id
66+
if _is_valid_guid(message.author_name):
67+
return message.author_name
68+
return None
69+
70+
6171
# RFC 2397: data:[<mediatype>][;base64],<data>, where <mediatype> may be followed by any number of
6272
# ";parameter=value" segments (for example "data:text/plain;charset=utf-8;base64,..."). The optional
6373
# parameters have to be matched explicitly, otherwise a parameterised media type fails to decode and
@@ -212,12 +222,13 @@ async def process_messages(
212222
messages: The messages to process
213223
activity: The activity type (e.g., UPLOAD_TEXT)
214224
session_id: Optional session/conversation id. Else, a new GUID is generated.
215-
user_id: Optional user_id to use for all messages. If provided, this is the fallback.
225+
user_id: Optional user_id to use for all messages when the credential does not identify a user.
226+
Otherwise, each message is evaluated under its own user id.
216227
217228
Returns:
218229
A tuple of (should_block: bool, resolved_user_id: str | None).
219-
The resolved_user_id can be stored and passed back when processing the response
220-
to ensure the same user context is maintained throughout the request/response cycle.
230+
The resolved_user_id is the user id of the last message. It can be stored and passed back when
231+
processing the response so the response is evaluated under the same user context.
221232
"""
222233
pc_requests, resolved_user_id = await self._map_messages(messages, activity, session_id, user_id)
223234
should_block = False
@@ -245,10 +256,12 @@ async def _map_messages(
245256
messages: The messages to map
246257
activity: The activity type
247258
session_id: Optional session/conversation id to use for correlation
248-
provided_user_id: Optional user_id to use. If provided, this is the fallback.
259+
provided_user_id: Optional user_id to use for all messages when the credential does not identify a
260+
user. Otherwise, each message uses its own user id, and messages without one inherit the latest
261+
explicit user id in the batch.
249262
250263
Returns:
251-
A tuple of (requests, resolved_user_id)
264+
A tuple of (requests, resolved_user_id), where resolved_user_id is the user id of the last message.
252265
"""
253266
results: list[ProcessContentRequest] = []
254267
token_info = await self._client.get_user_info_from_token(tenant_id=self._settings.get("tenant_id"))
@@ -257,34 +270,32 @@ async def _map_messages(
257270
if not tenant_id or not _is_valid_guid(tenant_id):
258271
raise ValueError("Tenant id required or must be inferable from credential")
259272

260-
resolved_user_id = (token_info or {}).get("user_id")
261-
resolved_author_name = None
262-
if not resolved_user_id:
263-
resolved_user_id = provided_user_id if provided_user_id and _is_valid_guid(provided_user_id) else None
264-
265-
if not resolved_user_id:
266-
for m in messages:
267-
if m.additional_properties:
268-
potential_user_id = m.additional_properties.get("user_id")
269-
if _is_valid_guid(potential_user_id):
270-
resolved_user_id = potential_user_id
271-
break
272-
if m.author_name and _is_valid_guid(m.author_name) and not resolved_author_name:
273-
resolved_author_name = m.author_name
273+
message_list = list(messages)
274+
override_user_id = (token_info or {}).get("user_id")
275+
if not override_user_id:
276+
override_user_id = provided_user_id if provided_user_id and _is_valid_guid(provided_user_id) else None
274277

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

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

287-
for m in messages:
292+
for m in message_list:
293+
if not override_user_id:
294+
# Messages without an identity (e.g. assistant or tool messages) are attributed to the
295+
# latest explicitly identified user, without overriding later explicit identities.
296+
inherited_user_id = _get_message_user_id(m) or inherited_user_id
297+
resolved_user_id = inherited_user_id
298+
288299
message_id = m.message_id or str(uuid.uuid4())
289300
correlation_id = (session_id or str(uuid.uuid4())) + "@AF"
290301
# This would be c# ticks equivalent and needs to fit inside c# long
@@ -337,13 +348,13 @@ async def _map_messages(
337348
)
338349
req = ProcessContentRequest(
339350
content_to_process=ctp,
340-
user_id=resolved_user_id, # Use the resolved user_id for all messages
351+
user_id=resolved_user_id,
341352
tenant_id=tenant_id,
342353
correlation_id=correlation_id,
343354
process_inline=None, # Will be set based on execution mode
344355
)
345356
results.append(req)
346-
return results, resolved_user_id
357+
return results, inherited_user_id
347358

348359
async def _process_with_scopes(self, pc_request: ProcessContentRequest) -> ProcessContentResponse:
349360
app_location = pc_request.content_to_process.protected_app_metadata.application_location

‎python/packages/purview/tests/purview/test_processor.py‎

Lines changed: 65 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1236,35 +1236,87 @@ async def test_multiple_messages_same_user_id(self, mock_client: AsyncMock, sett
12361236
# All requests should have the same user_id
12371237
assert all(req.user_id == "55555555-5555-5555-5555-555555555555" for req in requests)
12381238

1239-
async def test_first_valid_user_id_in_messages_is_used(
1240-
self, mock_client: AsyncMock, settings: PurviewSettings
1241-
) -> None:
1242-
"""Test that the first valid user_id found in messages is used for all."""
1239+
async def test_each_message_uses_its_own_user_id(self, mock_client: AsyncMock, settings: PurviewSettings) -> None:
1240+
"""Test that messages from different users are evaluated under each user's own id.
1241+
1242+
Messages without an id inherit the latest explicit id; leading ones use the first explicit id.
1243+
"""
12431244
processor = ScopedContentProcessor(mock_client, settings)
12441245
mock_client.get_user_info_from_token.return_value = {
12451246
"tenant_id": "12345678-1234-1234-1234-123456789012",
12461247
"client_id": "12345678-1234-1234-1234-123456789012",
12471248
}
1249+
user_a = "66666666-6666-6666-6666-666666666666"
1250+
user_b = "77777777-7777-7777-7777-777777777777"
12481251

12491252
messages = [
1250-
Message(role="user", contents=["First"], author_name="Not a GUID"),
1253+
Message(role="system", contents=["System"]),
12511254
Message(
1252-
role="assistant",
1253-
contents=["Response"],
1254-
additional_properties={"user_id": "66666666-6666-6666-6666-666666666666"},
1255+
role="user", contents=["From A"], author_name="Not a GUID", additional_properties={"user_id": user_a}
12551256
),
1257+
Message(role="assistant", contents=["Reply to A"]),
1258+
Message(role="user", contents=["From A again"], author_name=user_a),
1259+
Message(role="user", contents=["From B"], additional_properties={"user_id": user_b}),
1260+
Message(role="assistant", contents=["Reply to B"]),
1261+
]
1262+
1263+
requests, user_id = await processor._map_messages(messages, Activity.UPLOAD_TEXT)
1264+
1265+
assert [req.user_id for req in requests] == [user_a, user_a, user_a, user_a, user_b, user_b]
1266+
assert user_id == user_b
1267+
1268+
async def test_user_id_property_takes_priority_over_author_name(
1269+
self, mock_client: AsyncMock, settings: PurviewSettings
1270+
) -> None:
1271+
"""Test a message's user_id property wins over a GUID author_name on the same message."""
1272+
processor = ScopedContentProcessor(mock_client, settings)
1273+
mock_client.get_user_info_from_token.return_value = {
1274+
"tenant_id": "12345678-1234-1234-1234-123456789012",
1275+
"client_id": "12345678-1234-1234-1234-123456789012",
1276+
}
1277+
1278+
messages = [
12561279
Message(
12571280
role="user",
1258-
contents=["Third"],
1259-
additional_properties={"user_id": "77777777-7777-7777-7777-777777777777"},
1260-
),
1281+
contents=["Test"],
1282+
author_name="33333333-3333-3333-3333-333333333333",
1283+
additional_properties={"user_id": "66666666-6666-6666-6666-666666666666"},
1284+
)
12611285
]
12621286

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

1265-
# First valid user_id (from second message) should be used
12661289
assert user_id == "66666666-6666-6666-6666-666666666666"
1267-
assert all(req.user_id == "66666666-6666-6666-6666-666666666666" for req in requests)
1290+
assert requests[0].user_id == "66666666-6666-6666-6666-666666666666"
1291+
1292+
@pytest.mark.parametrize("override_source", ["token", "provided"])
1293+
async def test_override_user_id_applies_to_all_messages(
1294+
self, mock_client: AsyncMock, settings: PurviewSettings, override_source: str
1295+
) -> None:
1296+
"""Test that a token or provided user id is used for every message, ignoring per-message ids."""
1297+
processor = ScopedContentProcessor(mock_client, settings)
1298+
override = "11111111-1111-1111-1111-111111111111"
1299+
provided_user_id = None
1300+
if override_source == "provided":
1301+
mock_client.get_user_info_from_token.return_value = {
1302+
"tenant_id": "12345678-1234-1234-1234-123456789012",
1303+
"client_id": "12345678-1234-1234-1234-123456789012",
1304+
}
1305+
provided_user_id = override
1306+
1307+
messages = [
1308+
Message(
1309+
role="user", contents=["A"], additional_properties={"user_id": "66666666-6666-6666-6666-666666666666"}
1310+
),
1311+
Message(role="user", contents=["B"], author_name="77777777-7777-7777-7777-777777777777"),
1312+
]
1313+
1314+
requests, user_id = await processor._map_messages(
1315+
messages, Activity.UPLOAD_TEXT, provided_user_id=provided_user_id
1316+
)
1317+
1318+
assert user_id == override
1319+
assert [req.user_id for req in requests] == [override, override]
12681320

12691321

12701322
class TestScopedContentProcessorCaching:

0 commit comments

Comments
 (0)