-
Notifications
You must be signed in to change notification settings - Fork 531
POC: experimental Oauth support #4140
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
Open
timbl-ont
wants to merge
13
commits into
openwallet-foundation:main
Choose a base branch
from
timbl-ont:POC-oauth-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 9 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
7334ebc
experimental support for oauth. Coded with Claud AI
timbl-ont db071ee
fix mermaid chart
timbl-ont 239ee82
fix mermaid chart alt path
timbl-ont d5c1e1d
small wording change
timbl-ont 51e0468
added example require_scope
timbl-ont 462809e
fixed tests and updated context and metadata approach
timbl-ont 4e178a8
Merge branch 'main' into POC-oauth-support
swcurran c4ec629
Merge branch 'main' into POC-oauth-support
swcurran 12c3c39
fix linting errors
timbl-ont 5175a86
fix for demo script to use base64 URL decoding
timbl-ont 60f2843
Address PR review and security audit for OAuth Resource Server
timbl-ont bacd860
Address SonarCloud maintainability findings
timbl-ont 5082094
Merge branch 'main' into POC-oauth-support
swcurran 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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| """Helpers for reading request-scoped auth context safely. | ||
|
|
||
| These helpers support both: | ||
|
|
||
| 1) Preferred request metadata (``AdminRequestContext.metadata``), and | ||
| 2) Request-scoped settings fallback for compatibility. | ||
| """ | ||
|
|
||
| from collections.abc import Mapping | ||
| from typing import Any, Optional | ||
|
|
||
| AUTH_SCOPES_SETTING = "auth.scopes" | ||
| AUTH_SUBJECT_SETTING = "auth.subject" | ||
| AUTH_WALLET_ID_SETTING = "auth.wallet_id" | ||
|
|
||
|
|
||
| def _get_context_settings(context: Any) -> Mapping[str, Any]: | ||
| settings = getattr(context, "settings", None) | ||
| if isinstance(settings, Mapping): | ||
| return settings | ||
| return {} | ||
|
|
||
|
|
||
| def get_auth_metadata(context: Any) -> dict: | ||
| """Return auth metadata when available, else an empty dict.""" | ||
| metadata = getattr(context, "metadata", None) | ||
| if isinstance(metadata, dict): | ||
| return metadata | ||
| return {} | ||
|
|
||
|
|
||
| def has_auth_scopes(context: Any) -> bool: | ||
| """Whether auth scopes are present on the request context.""" | ||
| metadata = get_auth_metadata(context) | ||
| if "scopes" in metadata: | ||
| return True | ||
| settings = _get_context_settings(context) | ||
| return AUTH_SCOPES_SETTING in settings | ||
|
|
||
|
|
||
| def get_auth_scopes(context: Any) -> set[str]: | ||
| """Return normalized auth scopes from metadata or request settings.""" | ||
| metadata = get_auth_metadata(context) | ||
| raw_scopes = metadata.get("scopes") | ||
| if raw_scopes is None: | ||
| raw_scopes = _get_context_settings(context).get(AUTH_SCOPES_SETTING, ()) | ||
|
|
||
| if isinstance(raw_scopes, str): | ||
| return set(raw_scopes.split()) | ||
| if isinstance(raw_scopes, (set, list, tuple, frozenset)): | ||
| return {scope for scope in raw_scopes if isinstance(scope, str)} | ||
| return set() | ||
|
|
||
|
|
||
| def get_auth_subject(context: Any) -> Optional[str]: | ||
| """Return token subject claim from metadata or request settings.""" | ||
| metadata = get_auth_metadata(context) | ||
| subject = metadata.get("sub") | ||
| if subject is None: | ||
| subject = _get_context_settings(context).get(AUTH_SUBJECT_SETTING) | ||
| return subject if isinstance(subject, str) else None | ||
|
|
||
|
|
||
| def get_auth_wallet_id(context: Any) -> Optional[str]: | ||
| """Return request wallet id from metadata or request settings.""" | ||
| metadata = get_auth_metadata(context) | ||
| wallet_id = metadata.get("wallet_id") | ||
| if wallet_id is None: | ||
| wallet_id = _get_context_settings(context).get(AUTH_WALLET_ID_SETTING) | ||
| return wallet_id if isinstance(wallet_id, str) else None | ||
|
|
||
|
|
||
| def has_auth_wallet_id(context: Any) -> bool: | ||
| """Whether request context carries a wallet_id claim.""" | ||
| return bool(get_auth_wallet_id(context)) |
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,129 @@ | ||
| """OAuth2 token validator for ACA-Py acting as a Resource Server.""" | ||
|
|
||
| import logging | ||
| from typing import Optional | ||
|
|
||
| import aiohttp | ||
| import jwt | ||
| from aiohttp import web | ||
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
| _SUPPORTED_ALGORITHMS = [ | ||
| "RS256", | ||
| "RS384", | ||
| "RS512", | ||
| "ES256", | ||
| "ES384", | ||
| "ES512", | ||
| "PS256", | ||
| "PS384", | ||
| "PS512", | ||
| ] | ||
|
|
||
|
|
||
| class OAuthTokenValidator: | ||
| """Validate OAuth2 bearer tokens from an external Authorization Server. | ||
|
|
||
| Supports JWT access tokens validated locally via JWKS, with opaque token | ||
| fallback via RFC 7662 token introspection. | ||
| """ | ||
|
|
||
| def __init__(self, settings): | ||
| """Initialize the validator from application settings.""" | ||
| self.jwks_uri: Optional[str] = settings.get("oauth.jwks_uri") | ||
| self.issuer: Optional[str] = settings.get("oauth.issuer") | ||
| self.audience: Optional[str] = settings.get("oauth.audience") | ||
| self.introspection_endpoint: Optional[str] = settings.get( | ||
| "oauth.introspection_endpoint" | ||
| ) | ||
| self.introspection_client_id: Optional[str] = settings.get( | ||
| "oauth.introspection_client_id" | ||
| ) | ||
| self.introspection_client_secret: Optional[str] = settings.get( | ||
| "oauth.introspection_client_secret" | ||
| ) | ||
|
|
||
| # PyJWKClient handles JWKS fetching and caching internally. | ||
| self._jwks_client = ( | ||
| jwt.PyJWKClient(self.jwks_uri, cache_keys=True) if self.jwks_uri else None | ||
| ) | ||
|
|
||
| async def validate(self, token: str) -> dict: | ||
| """Validate an access token and return its claims. | ||
|
|
||
| Tries JWT validation via JWKS first; falls back to introspection if the | ||
| token is opaque or if JWKS is not configured. | ||
|
|
||
| Raises: | ||
| web.HTTPUnauthorized: If the token is invalid or inactive. | ||
|
|
||
| Returns: | ||
| dict: Validated token claims. | ||
|
|
||
| """ | ||
| if self._jwks_client: | ||
| try: | ||
| return self._validate_jwt(token) | ||
| except jwt.exceptions.PyJWKClientError as exc: | ||
| # JWKS infrastructure error — only fall through if introspection is | ||
| # configured as a fallback, otherwise the token cannot be validated. | ||
| if not self.introspection_endpoint: | ||
| raise web.HTTPUnauthorized(reason="Token validation failed") from exc | ||
| LOGGER.debug("JWKS lookup failed, falling back to introspection: %s", exc) | ||
| except jwt.DecodeError: | ||
| # Token is not a JWT — only meaningful if introspection is available. | ||
| if not self.introspection_endpoint: | ||
| raise web.HTTPUnauthorized(reason="Invalid token") | ||
| LOGGER.debug("JWT decode failed, falling back to introspection") | ||
| except jwt.InvalidTokenError as exc: | ||
| raise web.HTTPUnauthorized(reason=str(exc)) from exc | ||
|
|
||
| if self.introspection_endpoint: | ||
| return await self._introspect(token) | ||
|
|
||
| raise web.HTTPUnauthorized( | ||
| reason="No token validation method available — configure oauth.jwks_uri or " | ||
| "oauth.introspection_endpoint" | ||
| ) | ||
|
|
||
| def _validate_jwt(self, token: str) -> dict: | ||
| """Validate a JWT access token using the configured JWKS endpoint.""" | ||
| signing_key = self._jwks_client.get_signing_key_from_jwt(token) | ||
|
|
||
| decode_kwargs = dict( | ||
|
Check warning on line 94 in acapy_agent/admin/oauth_validator.py
|
||
| algorithms=_SUPPORTED_ALGORITHMS, | ||
| options={"require": ["exp", "iss", "sub"]}, | ||
| ) | ||
| if self.issuer: | ||
| decode_kwargs["issuer"] = self.issuer | ||
| if self.audience: | ||
| decode_kwargs["audience"] = self.audience | ||
|
|
||
| return jwt.decode(token, signing_key.key, **decode_kwargs) | ||
|
|
||
| async def _introspect(self, token: str) -> dict: | ||
| """Validate an opaque token via RFC 7662 introspection.""" | ||
| auth = None | ||
| if self.introspection_client_id: | ||
| auth = aiohttp.BasicAuth( | ||
| self.introspection_client_id, | ||
| self.introspection_client_secret or "", | ||
| ) | ||
|
|
||
| async with aiohttp.ClientSession() as session: | ||
| resp = await session.post( | ||
| self.introspection_endpoint, | ||
| data={"token": token, "token_type_hint": "access_token"}, | ||
| auth=auth, | ||
| ) | ||
| if resp.status != 200: | ||
| raise web.HTTPUnauthorized( | ||
| reason=f"Token introspection returned HTTP {resp.status}" | ||
| ) | ||
| body = await resp.json() | ||
|
|
||
| if not body.get("active"): | ||
| raise web.HTTPUnauthorized(reason="Token is not active") | ||
|
|
||
| return body | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Configurable timeout added