Skip to content
Closed
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
51 changes: 49 additions & 2 deletions src/google/adk/a2a/executor/a2a_agent_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import inspect
import logging
import os
from typing import Awaitable
from typing import Callable

Expand Down Expand Up @@ -44,6 +45,44 @@
from .utils import _require_request_context
from .utils import _require_user_id
from .utils import execute_after_agent_interceptors

#: Env var that puts exception text back into the failure message sent to the peer.
#: Off by default, and meant for local debugging only: enabling it on a
#: network-reachable deployment restores the disclosure the opaque id exists to
#: prevent.
_DEBUG_ERRORS_ENV_VAR = 'ADK_DEBUG_ERRORS'

#: Length of the correlation id, matching ``newErrorId()`` in adk-java.
_ERROR_ID_LENGTH = 12

#: Fixed summary the peer receives. It deliberately carries no throwable text.
_FAILURE_SUMMARY = 'Agent execution failed.'


def _new_error_id() -> str:
"""Returns a short opaque id correlating a peer-visible failure with the log."""
return platform_uuid.new_uuid().replace('-', '')[:_ERROR_ID_LENGTH]


def _debug_errors_enabled() -> bool:
"""Whether exception text should be echoed to the peer. Local debugging only."""
value = os.environ.get(_DEBUG_ERRORS_ENV_VAR, '')
return value.strip().lower() in ('1', 'true', 'yes', 'on')


def failure_text(error: Exception, error_id: str) -> str:
"""Builds the failure text handed back to the remote peer.

The peer is not trusted with the throwable: exception text routinely names
absolute filesystem paths, module locations, configuration values and echoed
request payloads, none of which the caller needs and all of which are useful
reconnaissance. Set ``ADK_DEBUG_ERRORS=1`` to restore the old behaviour while
debugging locally.
"""
text = f'{_FAILURE_SUMMARY} (error_id: {error_id})'
if _debug_errors_enabled():
text = f'{text} {error}'
return text
from .utils import execute_after_event_interceptors
from .utils import execute_before_agent_interceptors

Expand Down Expand Up @@ -153,7 +192,15 @@ async def execute(
try:
await self._handle_request(context, event_queue)
except Exception as e:
logger.error('Error handling A2A request: %s', e, exc_info=True)
# Logged in full here, under a short opaque id. The peer receives only that
# id, never the throwable text - see failure_text().
error_id = _new_error_id()
logger.error(
'Error handling A2A request [error_id=%s]: %s',
error_id,
e,
exc_info=True,
)
# Publish failure event
try:
await event_queue.enqueue_event(
Expand All @@ -165,7 +212,7 @@ async def execute(
message=Message(
message_id=platform_uuid.new_uuid(),
role=_compat.ROLE_AGENT,
parts=[_compat.make_text_part(str(e))],
parts=[_compat.make_text_part(failure_text(e, error_id))],
),
),
final=True,
Expand Down
54 changes: 54 additions & 0 deletions tests/unittests/a2a/executor/test_a2a_agent_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
# limitations under the License.

import asyncio
import os
import re
from unittest.mock import AsyncMock
from unittest.mock import Mock
from unittest.mock import patch
Expand Down Expand Up @@ -90,6 +92,15 @@ def _final_events(call_args_list):
return [e for e in events if getattr(e, "final", False)]


def _part_text(part) -> str:
"""Reads the text out of a Part on both A2A v1 (flat) and 0.3.x (union)."""
direct = getattr(part, 'text', None)
if direct:
return direct
root = getattr(part, 'root', None)
return getattr(root, 'text', '') or ''


class TestA2aAgentExecutor:
"""Test suite for A2aAgentExecutor class."""

Expand Down Expand Up @@ -289,6 +300,49 @@ def test_check_new_version_extension_activation_is_version_aware(self):
_NEW_A2A_ADK_INTEGRATION_EXTENSION
)

@pytest.mark.asyncio
async def test_failure_event_does_not_leak_exception_text(self):
"""The remote peer must not receive the throwable's message."""
secret = (
'Runner error: /home/victim/.config/adk/credentials.json (No such file)'
)
self.executor._handle_request = AsyncMock(side_effect=RuntimeError(secret))

await self.executor.execute(self.mock_context, self.mock_event_queue)

events = [c.args[0] for c in self.mock_event_queue.enqueue_event.call_args_list]
statuses = [
e.status
for e in events
if getattr(e, 'status', None) is not None
]
assert statuses, 'a failed status event should reach the peer'
parts = statuses[-1].message.parts
text = ''.join(_part_text(p) for p in parts)

assert re.fullmatch(
r'Agent execution failed\. \(error_id: [0-9a-f]{12}\)', text
), text
assert secret not in text
assert '/home/victim' not in text

@pytest.mark.asyncio
async def test_failure_event_leaks_when_debug_errors_enabled(self):
"""ADK_DEBUG_ERRORS restores exception text, for local debugging only."""
secret = 'boom at /home/victim/secret'
self.executor._handle_request = AsyncMock(side_effect=RuntimeError(secret))

with patch.dict(os.environ, {'ADK_DEBUG_ERRORS': '1'}):
await self.executor.execute(self.mock_context, self.mock_event_queue)

events = [c.args[0] for c in self.mock_event_queue.enqueue_event.call_args_list]
statuses = [
e.status for e in events if getattr(e, 'status', None) is not None
]
parts = statuses[-1].message.parts
text = ''.join(_part_text(p) for p in parts)
assert secret in text

@pytest.mark.asyncio
async def test_execute_no_message_error(self):
"""Test execution fails when no message is provided."""
Expand Down
Loading