|
| 1 | +import functools |
| 2 | +import logging |
| 3 | +import uuid |
| 4 | +from collections.abc import Callable |
| 5 | +from datetime import datetime, timedelta, timezone |
| 6 | +from typing import Any, TypedDict |
| 7 | + |
| 8 | +import jwt |
| 9 | +import requests |
| 10 | + |
| 11 | +from gateway_api.apim_app_auth.http import RequestMethod, SessionManager |
| 12 | + |
| 13 | +_logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +class ApimAuthenticationException(Exception): |
| 17 | + pass |
| 18 | + |
| 19 | + |
| 20 | +class ApimAuthenticator: |
| 21 | + class __AccessToken(TypedDict): |
| 22 | + value: str |
| 23 | + expiry: datetime |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + private_key: str, |
| 28 | + key_id: str, |
| 29 | + api_key: str, |
| 30 | + token_validity_threshold: timedelta, |
| 31 | + token_endpoint: str, |
| 32 | + session_manager: SessionManager, |
| 33 | + ): |
| 34 | + self._private_key = private_key |
| 35 | + self._key_id = key_id |
| 36 | + self._api_key = api_key |
| 37 | + self._token_validity_threshold = token_validity_threshold |
| 38 | + self._token_endpoint = token_endpoint |
| 39 | + self._session_manager = session_manager |
| 40 | + |
| 41 | + self._access_token: ApimAuthenticator.__AccessToken | None = None |
| 42 | + |
| 43 | + def auth[**P, S](self, func: RequestMethod[P, S]) -> Callable[P, S]: |
| 44 | + """ |
| 45 | + Decorate a given function with APIM authentication. This authentication will be |
| 46 | + provided via a `requests.Session` object. |
| 47 | + """ |
| 48 | + |
| 49 | + @functools.wraps(func) |
| 50 | + def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 51 | + @self._session_manager.with_session |
| 52 | + def with_session( |
| 53 | + session: requests.Session, access_token: ApimAuthenticator.__AccessToken |
| 54 | + ) -> S: |
| 55 | + session.headers.update( |
| 56 | + {"Authorization": f"Bearer {access_token['value']}"} |
| 57 | + ) |
| 58 | + return func(session, *args, **kwargs) |
| 59 | + |
| 60 | + # If there isn't an access token yet, or the token will expire within the |
| 61 | + # token validity threshold, reauthenticate. |
| 62 | + if ( |
| 63 | + self._access_token is None |
| 64 | + or self._access_token["expiry"] - datetime.now(tz=timezone.utc) |
| 65 | + < self._token_validity_threshold |
| 66 | + ): |
| 67 | + _logger.debug("Authenticating with APIM...") |
| 68 | + self._access_token = self._authenticate() |
| 69 | + |
| 70 | + return with_session(self._access_token) |
| 71 | + |
| 72 | + return wrapper |
| 73 | + |
| 74 | + def _create_client_assertion(self) -> str: |
| 75 | + _logger.debug("Creating client assertion JWT for APIM authentication") |
| 76 | + claims = { |
| 77 | + "sub": self._api_key, |
| 78 | + "iss": self._api_key, |
| 79 | + "jti": str(uuid.uuid4()), |
| 80 | + "aud": self._token_endpoint, |
| 81 | + "exp": int( |
| 82 | + (datetime.now(tz=timezone.utc) + timedelta(seconds=30)).timestamp() |
| 83 | + ), |
| 84 | + } |
| 85 | + _logger.debug( |
| 86 | + "Created client claims. jti: %s, exp: %s, aud: %s", |
| 87 | + claims["jti"], |
| 88 | + claims["exp"], |
| 89 | + claims["aud"], |
| 90 | + ) |
| 91 | + |
| 92 | + client_assertion = jwt.encode( |
| 93 | + claims, |
| 94 | + self._private_key, |
| 95 | + algorithm="RS512", |
| 96 | + headers={"kid": self._key_id}, |
| 97 | + ) |
| 98 | + |
| 99 | + _logger.debug("Created client assertion. kid: %s", self._key_id) |
| 100 | + |
| 101 | + return client_assertion |
| 102 | + |
| 103 | + def _authenticate(self) -> __AccessToken: |
| 104 | + @self._session_manager.with_session |
| 105 | + def with_session(session: requests.Session) -> ApimAuthenticator.__AccessToken: |
| 106 | + client_assertion = self._create_client_assertion() |
| 107 | + |
| 108 | + _logger.debug("Sending token request with created session.") |
| 109 | + |
| 110 | + response = session.post( |
| 111 | + self._token_endpoint, |
| 112 | + data={ |
| 113 | + "grant_type": "client_credentials", |
| 114 | + "client_assertion_type": "urn:ietf:params:oauth" |
| 115 | + ":client-assertion-type:jwt-bearer", |
| 116 | + "client_assertion": client_assertion, |
| 117 | + }, |
| 118 | + ) |
| 119 | + |
| 120 | + _logger.debug( |
| 121 | + "Response received from APIM token endpoint. Status code: %s", |
| 122 | + response.status_code, |
| 123 | + ) |
| 124 | + |
| 125 | + if response.status_code != 200: |
| 126 | + raise ApimAuthenticationException( |
| 127 | + f"Failed to authenticate with APIM. " |
| 128 | + f"Status code: {response.status_code}" |
| 129 | + f", Response: {response.text}" |
| 130 | + ) |
| 131 | + |
| 132 | + response_data = response.json() |
| 133 | + _logger.debug( |
| 134 | + "APIM authentication successful. Expiry: %s", |
| 135 | + response_data["expires_in"], |
| 136 | + ) |
| 137 | + |
| 138 | + return { |
| 139 | + "value": response_data["access_token"], |
| 140 | + "expiry": datetime.now(tz=timezone.utc) |
| 141 | + + timedelta(seconds=int(response_data["expires_in"])), |
| 142 | + } |
| 143 | + |
| 144 | + _logger.debug( |
| 145 | + "Sending authentication request to APIM: %s", self._token_endpoint |
| 146 | + ) |
| 147 | + return with_session() |
0 commit comments