-
Notifications
You must be signed in to change notification settings - Fork 1
MPT-16525 support pluggable authentication backends #41
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 all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| .venv |
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 was deleted.
Oops, something went wrong.
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,11 @@ | ||
| from mrok.controller.auth.backends import OIDCJWTAuthenticationBackend # noqa: F401 | ||
| from mrok.controller.auth.base import AuthIdentity, BaseHTTPAuthBackend | ||
| from mrok.controller.auth.manager import HTTPAuthManager | ||
| from mrok.controller.auth.registry import register_authentication_backend | ||
|
|
||
| __all__ = [ | ||
| "AuthIdentity", | ||
| "BaseHTTPAuthBackend", | ||
| "HTTPAuthManager", | ||
| "register_authentication_backend", | ||
| ] |
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,60 @@ | ||
| import logging | ||
|
|
||
| import httpx | ||
| import jwt | ||
| from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer | ||
| from fastapi.security.http import HTTPBase | ||
|
|
||
| from mrok.controller.auth.base import UNAUTHORIZED_EXCEPTION, AuthIdentity, BaseHTTPAuthBackend | ||
| from mrok.controller.auth.registry import register_authentication_backend | ||
|
|
||
| logger = logging.getLogger("mrok.controller") | ||
|
|
||
|
|
||
| @register_authentication_backend("oidc") | ||
| class OIDCJWTAuthenticationBackend(BaseHTTPAuthBackend): | ||
| def init_scheme(self) -> HTTPBase: | ||
| return HTTPBearer(auto_error=False) | ||
|
|
||
| async def authenticate(self, credentials: HTTPAuthorizationCredentials) -> AuthIdentity | None: | ||
| async with httpx.AsyncClient() as client: | ||
| try: | ||
| config_resp = await client.get(self.config.openid_config_url) | ||
| config_resp.raise_for_status() | ||
| config = config_resp.json() | ||
| issuer = config["issuer"] | ||
| jwks_uri = config["jwks_uri"] | ||
|
|
||
| jwks_resp = await client.get(jwks_uri) | ||
| jwks_resp.raise_for_status() | ||
| jwks = jwks_resp.json() | ||
|
|
||
| header = jwt.get_unverified_header(credentials.credentials) | ||
| kid = header["kid"] | ||
|
|
||
| key_data = next((k for k in jwks["keys"] if k["kid"] == kid), None) | ||
| except Exception: | ||
| logger.exception("Error fetching openid-config/jwks") | ||
| raise UNAUTHORIZED_EXCEPTION | ||
| if key_data is None: | ||
| logger.error("Key ID not found in JWKS") | ||
| raise UNAUTHORIZED_EXCEPTION | ||
|
|
||
| try: | ||
| payload = jwt.decode( | ||
| credentials.credentials, | ||
| jwt.PyJWK(key_data), | ||
| algorithms=[header["alg"]], | ||
| issuer=issuer, | ||
| audience=self.config.audience, | ||
| ) | ||
| return AuthIdentity( | ||
| subject=payload["sub"], | ||
| metadata=payload, | ||
| ) | ||
| except jwt.InvalidKeyError as e: | ||
| logger.error(f"Invalid jwt token: {e} ({credentials.credentials})") | ||
| raise UNAUTHORIZED_EXCEPTION | ||
| except jwt.InvalidTokenError as e: | ||
| logger.error(f"Invalid jwt token: {e} ({credentials.credentials})") | ||
| raise UNAUTHORIZED_EXCEPTION | ||
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,38 @@ | ||
| from abc import ABC, abstractmethod | ||
| from typing import Any | ||
|
|
||
| from dynaconf.utils.boxing import DynaBox | ||
| from fastapi import HTTPException, Request, status | ||
| from fastapi.security import HTTPAuthorizationCredentials | ||
| from fastapi.security.http import HTTPBase | ||
| from pydantic import BaseModel | ||
|
|
||
| UNAUTHORIZED_EXCEPTION = HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized." | ||
| ) | ||
|
|
||
|
|
||
| class AuthIdentity(BaseModel): | ||
| subject: str | ||
| scopes: list[str] = [] | ||
| metadata: dict[str, Any] = {} | ||
|
|
||
|
|
||
| class BaseHTTPAuthBackend(ABC): | ||
| def __init__(self, config: DynaBox): | ||
| self.config = config | ||
| self.scheme = self.init_scheme() | ||
|
|
||
| @abstractmethod | ||
| def init_scheme(self) -> HTTPBase: | ||
| raise NotImplementedError() | ||
|
|
||
| @abstractmethod | ||
| async def authenticate(self, credentials: HTTPAuthorizationCredentials) -> AuthIdentity | None: | ||
| raise NotImplementedError() | ||
|
|
||
| async def __call__(self, request: Request) -> AuthIdentity | None: | ||
| credentials = await self.scheme(request) | ||
| if not credentials: | ||
| return None | ||
| return await self.authenticate(credentials) |
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,31 @@ | ||
| from dynaconf.utils.boxing import DynaBox | ||
| from fastapi import Request | ||
|
|
||
| from mrok.controller.auth.base import UNAUTHORIZED_EXCEPTION, AuthIdentity, BaseHTTPAuthBackend | ||
| from mrok.controller.auth.registry import get_authentication_backend | ||
|
|
||
|
|
||
| class HTTPAuthManager: | ||
| def __init__(self, auth_settings: DynaBox): | ||
| self.auth_settings = auth_settings | ||
| self.active_backends: list[BaseHTTPAuthBackend] = [] | ||
| self._setup_backends() | ||
|
|
||
| def _setup_backends(self): | ||
| enabled_keys = self.auth_settings.get("backends", []) | ||
|
|
||
| for key in enabled_keys: | ||
| backend_cls = get_authentication_backend(key) | ||
| if not backend_cls: | ||
| raise ValueError(f"Backend '{key}' is not registered.") | ||
|
|
||
| specific_config = self.auth_settings.get(key, {}) | ||
| self.active_backends.append(backend_cls(specific_config)) | ||
|
|
||
| async def __call__(self, request: Request) -> AuthIdentity: | ||
| for backend in self.active_backends: | ||
| identity = await backend(request) | ||
| if identity: | ||
| return identity | ||
|
|
||
| raise UNAUTHORIZED_EXCEPTION |
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,17 @@ | ||
| from mrok.controller.auth.base import BaseHTTPAuthBackend | ||
|
|
||
| BACKEND_REGISTRY: dict[str, type[BaseHTTPAuthBackend]] = {} | ||
|
|
||
|
|
||
| def register_authentication_backend(name: str): | ||
| """Decorator to register a backend class with a unique key.""" | ||
|
|
||
| def decorator(cls: type[BaseHTTPAuthBackend]): | ||
| BACKEND_REGISTRY[name] = cls | ||
| return cls | ||
|
|
||
| return decorator | ||
|
|
||
|
|
||
| def get_authentication_backend(name: str) -> type[BaseHTTPAuthBackend] | None: | ||
| return BACKEND_REGISTRY.get(name) |
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
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.