-
Notifications
You must be signed in to change notification settings - Fork 326
feat: Add middleware to the client SDK #171
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 13 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
9729217
tests working
dmandar 18088e1
OAuth test
dmandar ce5a6e1
common logic for all bearer based schemes
dmandar b43bf9f
fix tests
dmandar a8fde59
Fix merge.
dmandar 6db2b51
Merge branch 'main' into md-auth
dmandar ee8476e
Spelling/formatting
holtskinner 7d0acff
Update .vscode/launch.json
dmandar 5d462bf
Update src/a2a/client/__init__.py
dmandar bc78375
Remove comments
dmandar 0902102
Formatting
holtskinner 3f15cf4
Add ruff --unsafe-fixes
holtskinner 246a719
Merge branch 'main' into md-auth
holtskinner d94df5a
Fix a typo and update tests with a rename
dmandar 6bc8842
Update src/a2a/client/auth/interceptor.py
dmandar b584826
Update src/a2a/client/auth/interceptor.py
dmandar 10f0ae8
Update src/a2a/client/auth/interceptor.py
dmandar c9fe26c
Use match for interceptor logic
dmandar b503b1c
Fix linter errors.
dmandar 9d31edb
Merge branch 'main' into md-auth
dmandar 2a052d5
more linter fixes
dmandar b4d5e6f
linter
dmandar 7701012
Ignore linter failure for MutableMapping to be available at runtime
dmandar 2e0aba9
Add interceptors docstring to init method
dmandar 8700c28
Fixes for tool comments
dmandar 088d25c
Merge branch 'main' into md-auth
holtskinner 10a7d9f
Formatting
holtskinner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| """Client-side authentication components for the A2A Python SDK.""" | ||
|
|
||
| from a2a.client.auth.credentials import ( | ||
| CredentialService, | ||
| InMemoryContextCredentialStore, | ||
| ) | ||
| from a2a.client.auth.interceptor import AuthInterceptor | ||
|
|
||
|
|
||
| __all__ = [ | ||
| 'AuthInterceptor', | ||
| 'CredentialService', | ||
| 'InMemoryContextCredentialStore', | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| from abc import ABC, abstractmethod | ||
|
|
||
| from a2a.client.middleware import ClientCallContext | ||
|
|
||
|
|
||
| class CredentialService(ABC): | ||
| """An abstract service for retrieving credentials.""" | ||
|
|
||
| @abstractmethod | ||
| async def get_credentials( | ||
| self, | ||
| security_scheme_name: str, | ||
| context: ClientCallContext | None, | ||
| ) -> str | None: | ||
| """ | ||
| Retrieves a credential (e.g., token) for a security scheme. | ||
| """ | ||
|
|
||
|
|
||
| class InMemoryContextCredentialStore(CredentialService): | ||
| """A simple in-memory store for session-keyed credentials. | ||
|
|
||
| This class uses the 'sessionId' from the ClientCallContext state to | ||
| store and retrieve credentials... | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| # {session_id: {scheme_name: credential}} | ||
| self._store: dict[str, dict[str, str]] = {} | ||
|
|
||
| async def get_credentials( | ||
| self, | ||
| security_scheme_name: str, | ||
| context: ClientCallContext | None, | ||
| ) -> str | None: | ||
| if not context or 'sessionId' not in context.state: | ||
| return None | ||
| session_id = context.state['sessionId'] | ||
| return self._store.get(session_id, {}).get(security_scheme_name) | ||
|
|
||
| async def set_credential( | ||
dmandar marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self, session_id: str, security_scheme_name: str, credential: str | ||
| ) -> None: | ||
| """Method to populate the store.""" | ||
| if session_id not in self._store: | ||
| self._store[session_id] = {} | ||
| self._store[session_id][security_scheme_name] = credential | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import logging | ||
|
|
||
| from typing import Any | ||
|
|
||
| from a2a.client.auth.credentials import CredentialService | ||
| from a2a.client.middleware import ClientCallContext, ClientCallInterceptor | ||
| from a2a.types import ( | ||
| APIKeySecurityScheme, | ||
| AgentCard, | ||
| HTTPAuthSecurityScheme, | ||
| In, | ||
| OAuth2SecurityScheme, | ||
| OpenIdConnectSecurityScheme, | ||
| ) | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class AuthInterceptor(ClientCallInterceptor): | ||
| """An interceptor that automatically adds authentication details to requests | ||
| based on the agent's security schemes. | ||
| """ | ||
|
|
||
| def __init__(self, credential_service: CredentialService): | ||
| self._credential_service = credential_service | ||
|
|
||
| async def intercept( | ||
| self, | ||
| method_name: str, | ||
| request_payload: dict[str, Any], | ||
| http_kwargs: dict[str, Any], | ||
| agent_card: AgentCard | None, | ||
| context: ClientCallContext | None, | ||
| ) -> tuple[dict[str, Any], dict[str, Any]]: | ||
| if ( | ||
| not agent_card | ||
| or not agent_card.security | ||
| or not agent_card.securitySchemes | ||
| ): | ||
dmandar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return request_payload, http_kwargs | ||
|
|
||
| for requirement in agent_card.security: | ||
| for scheme_name in requirement: | ||
| credential = await self._credential_service.get_credentials( | ||
| scheme_name, context | ||
| ) | ||
| if credential and scheme_name in agent_card.securitySchemes: | ||
| scheme_def_union = agent_card.securitySchemes[scheme_name] | ||
dmandar marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if not scheme_def_union: | ||
| continue | ||
| scheme_def = scheme_def_union.root | ||
|
|
||
| headers = http_kwargs.get('headers', {}) | ||
|
|
||
| is_bearer_scheme = False | ||
| if ( | ||
| isinstance(scheme_def, HTTPAuthSecurityScheme) | ||
| and scheme_def.scheme.lower() == 'bearer' | ||
| ) or isinstance( | ||
| scheme_def, | ||
| OAuth2SecurityScheme | OpenIdConnectSecurityScheme, | ||
| ): | ||
| is_bearer_scheme = True | ||
|
|
||
| if is_bearer_scheme: | ||
| headers['Authorization'] = f'Bearer {credential}' | ||
| logger.debug( | ||
| f"Added Bearer token for scheme '{scheme_name}' (type: {scheme_def.type})." | ||
| ) | ||
| http_kwargs['headers'] = headers | ||
| return request_payload, http_kwargs | ||
| if isinstance(scheme_def, APIKeySecurityScheme): | ||
| if scheme_def.in_ == In.header: | ||
| headers[scheme_def.name] = credential | ||
| logger.debug( | ||
| f"Added API Key Header for scheme '{scheme_name}'." | ||
| ) | ||
| http_kwargs['headers'] = headers | ||
| return request_payload, http_kwargs | ||
| # Note: API keys in query or cookie are not handled here. | ||
dmandar marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| return request_payload, http_kwargs | ||
dmandar marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| """Authenticated user information.""" | ||
|
|
||
| from abc import ABC, abstractmethod | ||
|
|
||
|
|
||
| class User(ABC): | ||
| """A representation of an authenticated user.""" | ||
|
|
||
| @property | ||
| @abstractmethod | ||
| def is_authenticated(self) -> bool: | ||
| """Returns whether the current user is authenticated.""" | ||
|
|
||
| @property | ||
| @abstractmethod | ||
| def user_name(self) -> str: | ||
| """Returns the user name of the current user.""" | ||
|
|
||
|
|
||
| class UnauthenticatedUser(User): | ||
| """A representation that no user has been authenticated in the request.""" | ||
|
|
||
| @property | ||
| def is_authenticated(self) -> bool: | ||
| return False | ||
|
|
||
| @property | ||
| def user_name(self) -> str: | ||
| return '' |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.