diff --git a/src/google/adk/a2a/agent/_remote_a2a_agent.py b/src/google/adk/a2a/agent/_remote_a2a_agent.py index 397402df855..4c9851baed4 100644 --- a/src/google/adk/a2a/agent/_remote_a2a_agent.py +++ b/src/google/adk/a2a/agent/_remote_a2a_agent.py @@ -25,6 +25,7 @@ from typing import Literal from typing import Optional from typing import Union +from urllib.parse import quote from urllib.parse import urlparse from a2a.client import Client as A2AClient @@ -579,6 +580,23 @@ def _remote_identity(agent_card: Union[AgentCard, str]) -> str: return _compat.agent_card_url(agent_card) or agent_card.name or "" +def _namespaced_session_context_id(session: Any) -> Optional[str]: + """Derives a remote context ID that namespaces the session by app/user. + + ``session.id`` alone is not globally unique: two distinct local users (or + two apps) can reuse the same session ID, and forwarding the raw ID would + let their conversations collide on a remote A2A server that keys state off + the context ID. + """ + session_id = getattr(session, "id", None) + if not session_id: + return None + app_name = getattr(session, "app_name", "") or "" + user_id = getattr(session, "user_id", "") or "" + # Percent-encoding keeps "/" unambiguous, so the parts can be split back out. + return "/".join(quote(p, safe="") for p in (app_name, user_id, session_id)) + + def _names_its_own_credential_key( auth_scheme: AuthScheme, auth_credential: Optional[AuthCredential] ) -> bool: @@ -1655,8 +1673,8 @@ async def _run_async_impl( branch=ctx.branch, ) return - session_id = ( - getattr(ctx.session, "id", None) + namespaced_session_id = ( + _namespaced_session_context_id(ctx.session) if self._config.forward_session_id_as_context_id and ctx and getattr(ctx, "session", None) @@ -1666,7 +1684,7 @@ async def _run_async_impl( message_id=platform_uuid.new_uuid(), parts=message_parts, role=_compat.ROLE_USER, - context_id=context_id or session_id, + context_id=context_id or namespaced_session_id, ) logger.debug(build_a2a_request_log(a2a_request)) diff --git a/src/google/adk/a2a/agent/config.py b/src/google/adk/a2a/agent/config.py index e7388190f47..d33d23deced 100644 --- a/src/google/adk/a2a/agent/config.py +++ b/src/google/adk/a2a/agent/config.py @@ -139,7 +139,13 @@ class A2aRemoteAgentConfig(BaseModel): """Interceptors that inject headers into the remote agent card fetch.""" forward_session_id_as_context_id: bool = False - """Whether to forward the local session ID as context_id when no context_id is present.""" + """Whether to derive context_id from the local session when no context_id is present. + + The derived value is ``app_name/user_id/session_id`` (each part + percent-encoded), so it stays correlatable across agents and distinct local + users or apps never collapse onto the same remote context, even if they + happen to share a session ID. + """ def __deepcopy__( self, memo: dict[int, Any] | None = None diff --git a/tests/unittests/a2a/agent/test_remote_a2a_agent.py b/tests/unittests/a2a/agent/test_remote_a2a_agent.py index 5a7d5358b5b..149ffaf5852 100644 --- a/tests/unittests/a2a/agent/test_remote_a2a_agent.py +++ b/tests/unittests/a2a/agent/test_remote_a2a_agent.py @@ -3967,6 +3967,8 @@ def setup_method(self): # Mock session and context self.mock_session = Mock(spec=Session) self.mock_session.id = "session-123" + self.mock_session.app_name = "test-app" + self.mock_session.user_id = "user-a" self.mock_session.events = [] self.mock_session.state = {} @@ -4258,19 +4260,51 @@ async def test_run_async_impl_does_not_forward_session_id_by_default(self): @pytest.mark.asyncio async def test_run_async_impl_uses_session_id_when_opted_in(self): - """Test that session ID is used as context_id when opted in. + """Test that a namespaced session ID is used as context_id when opted in. When forward_session_id_as_context_id is True and _construct_message_parts_from_session returns None for context_id, - the agent should use ctx.session.id to maintain session identity across - local and remote agents. + the agent should derive context_id from the session's app name, user ID, + and session ID (not the raw session ID) to maintain session identity + across local and remote agents without collapsing distinct local users + that share a session ID. """ + expected_context_id = remote_a2a_agent._namespaced_session_context_id( + self.mock_session + ) await self._run_context_id_test( mock_context_id=None, - expected_context_id=self.mock_session.id, + expected_context_id=expected_context_id, forward_session_id=True, ) + @pytest.mark.asyncio + async def test_run_async_impl_namespaces_context_id_by_user(self): + """Two distinct users sharing a session ID must not collide remotely. + + Regression test for the vulnerability where forwarding the raw session + ID as context_id let two different local users with the same session ID + be mapped to the same remote A2A context. + """ + self.mock_session.user_id = "user-a" + expected_context_id = remote_a2a_agent._namespaced_session_context_id( + self.mock_session + ) + await self._run_context_id_test( + mock_context_id=None, + expected_context_id=expected_context_id, + forward_session_id=True, + ) + context_id_for_user_a = expected_context_id + + self.mock_session.user_id = "user-b" + context_id_for_user_b = remote_a2a_agent._namespaced_session_context_id( + self.mock_session + ) + + assert context_id_for_user_a == "test-app/user-a/session-123" + assert context_id_for_user_b == "test-app/user-b/session-123" + @pytest.mark.asyncio async def test_run_async_impl_preserves_existing_context_id(self): """Test that existing context_id is preserved when available.