|
| 1 | +import logging # noqa: I001 |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +from a2a.client.auth.credentials import CredentialService |
| 5 | +from a2a.client.middleware import ClientCallContext, ClientCallInterceptor |
| 6 | +from a2a.types import ( |
| 7 | + AgentCard, |
| 8 | + APIKeySecurityScheme, |
| 9 | + HTTPAuthSecurityScheme, |
| 10 | + In, |
| 11 | + OAuth2SecurityScheme, |
| 12 | + OpenIdConnectSecurityScheme, |
| 13 | +) |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class AuthInterceptor(ClientCallInterceptor): |
| 19 | + """An interceptor that automatically adds authentication details to requests. |
| 20 | +
|
| 21 | + Based on the agent's security schemes. |
| 22 | + """ |
| 23 | + |
| 24 | + def __init__(self, credential_service: CredentialService): |
| 25 | + self._credential_service = credential_service |
| 26 | + |
| 27 | + async def intercept( |
| 28 | + self, |
| 29 | + method_name: str, |
| 30 | + request_payload: dict[str, Any], |
| 31 | + http_kwargs: dict[str, Any], |
| 32 | + agent_card: AgentCard | None, |
| 33 | + context: ClientCallContext | None, |
| 34 | + ) -> tuple[dict[str, Any], dict[str, Any]]: |
| 35 | + """Applies authentication headers to the request if credentials are available.""" |
| 36 | + if ( |
| 37 | + agent_card is None |
| 38 | + or agent_card.security is None |
| 39 | + or agent_card.securitySchemes is None |
| 40 | + ): |
| 41 | + return request_payload, http_kwargs |
| 42 | + |
| 43 | + for requirement in agent_card.security: |
| 44 | + for scheme_name in requirement: |
| 45 | + credential = await self._credential_service.get_credentials( |
| 46 | + scheme_name, context |
| 47 | + ) |
| 48 | + if credential and scheme_name in agent_card.securitySchemes: |
| 49 | + scheme_def_union = agent_card.securitySchemes.get( |
| 50 | + scheme_name |
| 51 | + ) |
| 52 | + if not scheme_def_union: |
| 53 | + continue |
| 54 | + scheme_def = scheme_def_union.root |
| 55 | + |
| 56 | + headers = http_kwargs.get('headers', {}) |
| 57 | + |
| 58 | + match scheme_def: |
| 59 | + # Case 1a: HTTP Bearer scheme with an if guard |
| 60 | + case HTTPAuthSecurityScheme() if ( |
| 61 | + scheme_def.scheme.lower() == 'bearer' |
| 62 | + ): |
| 63 | + headers['Authorization'] = f'Bearer {credential}' |
| 64 | + logger.debug( |
| 65 | + f"Added Bearer token for scheme '{scheme_name}' (type: {scheme_def.type})." |
| 66 | + ) |
| 67 | + http_kwargs['headers'] = headers |
| 68 | + return request_payload, http_kwargs |
| 69 | + |
| 70 | + # Case 1b: OAuth2 and OIDC schemes, which are implicitly Bearer |
| 71 | + case ( |
| 72 | + OAuth2SecurityScheme() |
| 73 | + | OpenIdConnectSecurityScheme() |
| 74 | + ): |
| 75 | + headers['Authorization'] = f'Bearer {credential}' |
| 76 | + logger.debug( |
| 77 | + f"Added Bearer token for scheme '{scheme_name}' (type: {scheme_def.type})." |
| 78 | + ) |
| 79 | + http_kwargs['headers'] = headers |
| 80 | + return request_payload, http_kwargs |
| 81 | + |
| 82 | + # Case 2: API Key in Header |
| 83 | + case APIKeySecurityScheme(in_=In.header): |
| 84 | + headers[scheme_def.name] = credential |
| 85 | + logger.debug( |
| 86 | + f"Added API Key Header for scheme '{scheme_name}'." |
| 87 | + ) |
| 88 | + http_kwargs['headers'] = headers |
| 89 | + return request_payload, http_kwargs |
| 90 | + |
| 91 | + # Note: Other cases like API keys in query/cookie are not handled and will be skipped. |
| 92 | + |
| 93 | + return request_payload, http_kwargs |
0 commit comments