| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
import typing as t |
| 5 |
import uuid |
| 6 |
|
| 7 |
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey |
| 8 |
|
| 9 |
from globus_sdk import client, exc |
| 10 |
from globus_sdk._internal.remarshal import commajoin |
| 11 |
from globus_sdk._missing import MISSING, MissingType |
| 12 |
from globus_sdk.authorizers import GlobusAuthorizer, NullAuthorizer |
| 13 |
from globus_sdk.response import GlobusHTTPResponse |
| 14 |
from globus_sdk.scopes import AuthScopes, Scope |
| 15 |
from globus_sdk.transport import RequestsTransport, RetryConfig |
| 16 |
|
| 17 |
from .._common import get_jwk_data, pem_decode_jwk_data |
| 18 |
from ..errors import AuthAPIError |
| 19 |
from ..flow_managers import GlobusOAuthFlowManager |
| 20 |
from ..response import ( |
| 21 |
OAuthAuthorizationCodeResponse, |
| 22 |
OAuthRefreshTokenResponse, |
| 23 |
OAuthTokenResponse, |
| 24 |
) |
| 25 |
|
| 26 |
log = logging.getLogger(__name__) |
| 27 |
|
| 28 |
RT = t.TypeVar("RT", bound=GlobusHTTPResponse) |
| 29 |
|
| 30 |
|
| 31 |
class AuthLoginClient(client.BaseClient): |
| 32 |
""" |
| 33 |
This client class provides the common base for clients providing login |
| 34 |
functionality via |
| 35 |
`Globus Auth <https://docs.globus.org/api/auth/>`_ |
| 36 |
|
| 37 |
:param client_id: The ID of the application provided by registration with |
| 38 |
Globus Auth. |
| 39 |
|
| 40 |
All other initialization parameters are passed through to ``BaseClient``. |
| 41 |
|
| 42 |
.. automethodlist:: globus_sdk.AuthLoginClient |
| 43 |
""" |
| 44 |
|
| 45 |
service_name = "auth" |
| 46 |
error_class = AuthAPIError |
| 47 |
scopes = AuthScopes |
| 48 |
|
| 49 |
def __init__( |
| 50 |
self, |
| 51 |
client_id: uuid.UUID | str | None = None, |
| 52 |
environment: str | None = None, |
| 53 |
base_url: str | None = None, |
| 54 |
authorizer: GlobusAuthorizer | None = None, |
| 55 |
app_name: str | None = None, |
| 56 |
transport: RequestsTransport | None = None, |
| 57 |
retry_config: RetryConfig | None = None, |
| 58 |
) -> None: |
| 59 |
super().__init__( |
| 60 |
environment=environment, |
| 61 |
base_url=base_url, |
| 62 |
authorizer=authorizer, |
| 63 |
app_name=app_name, |
| 64 |
transport=transport, |
| 65 |
retry_config=retry_config, |
| 66 |
) |
| 67 |
self.client_id: str | None = str(client_id) if client_id is not None else None |
| 68 |
# an AuthClient may contain a GlobusOAuth2FlowManager in order to |
| 69 |
# encapsulate the functionality of various different types of flow |
| 70 |
# managers |
| 71 |
self.current_oauth2_flow_manager: GlobusOAuthFlowManager | None = None |
| 72 |
|
| 73 |
log.debug( |
| 74 |
"Finished initializing AuthLoginClient. " |
| 75 |
f"client_id='{client_id}', type(authorizer)={type(authorizer)}" |
| 76 |
) |
| 77 |
|
| 78 |
@property |
| 79 |
def default_scope_requirements(self) -> list[Scope]: |
| 80 |
raise exc.GlobusSDKUsageError( |
| 81 |
"AuthLoginClients do not have default_scope_requirements, " |
| 82 |
"use AuthClient instead." |
| 83 |
) |
| 84 |
|
| 85 |
# FYI: this get_openid_configuration method is duplicated in AuthClient |
| 86 |
# if this code is modified, please update that copy as well |
| 87 |
# |
| 88 |
# we would like to restructure code using this method to be calling the matching |
| 89 |
# AuthClient method |
| 90 |
# for example, a future SDK version may make an AuthLoginClient contain |
| 91 |
# an AuthClient which it uses |
| 92 |
def get_openid_configuration(self) -> GlobusHTTPResponse: |
| 93 |
""" |
| 94 |
Fetch the OpenID Connect configuration data from the well-known URI for Globus |
| 95 |
Auth. |
| 96 |
""" |
| 97 |
log.debug("Fetching OIDC Config") |
| 98 |
return self.get("/.well-known/openid-configuration") |
| 99 |
|
| 100 |
@t.overload |
| 101 |
def get_jwk( |
| 102 |
self, |
| 103 |
openid_configuration: GlobusHTTPResponse | dict[str, t.Any] | MissingType, |
| 104 |
*, |
| 105 |
as_pem: t.Literal[True], |
| 106 |
) -> RSAPublicKey: ... |
| 107 |
|
| 108 |
@t.overload |
| 109 |
def get_jwk( |
| 110 |
self, |
| 111 |
openid_configuration: GlobusHTTPResponse | dict[str, t.Any] | MissingType, |
| 112 |
*, |
| 113 |
as_pem: t.Literal[False], |
| 114 |
) -> dict[str, t.Any]: ... |
| 115 |
|
| 116 |
# FYI: this get_jwk method is duplicated in AuthClient |
| 117 |
# if this code is modified, please update that copy as well |
| 118 |
# |
| 119 |
# we would like to restructure code using this method to be calling the matching |
| 120 |
# AuthClient method |
| 121 |
# for example, a future SDK version may make an AuthLoginClient contain |
| 122 |
# an AuthClient which it uses |
| 123 |
def get_jwk( |
| 124 |
self, |
| 125 |
openid_configuration: ( |
| 126 |
GlobusHTTPResponse | dict[str, t.Any] | MissingType |
| 127 |
) = MISSING, |
| 128 |
*, |
| 129 |
as_pem: bool = False, |
| 130 |
) -> RSAPublicKey | dict[str, t.Any]: |
| 131 |
""" |
| 132 |
Fetch the Globus Auth JWK. |
| 133 |
|
| 134 |
Returns either a dict or an RSA Public Key object depending on ``as_pem``. |
| 135 |
|
| 136 |
:param openid_configuration: The OIDC config as a GlobusHTTPResponse or dict. |
| 137 |
When not provided, it will be fetched automatically. |
| 138 |
:param as_pem: Decode the JWK to an RSA PEM key, typically for JWT decoding |
| 139 |
""" |
| 140 |
if openid_configuration is MISSING: |
| 141 |
log.debug("No OIDC Config provided, autofetching...") |
| 142 |
openid_configuration = self.get_openid_configuration() |
| 143 |
jwk_data = get_jwk_data( |
| 144 |
fget=self.get, openid_configuration=openid_configuration |
| 145 |
) |
| 146 |
return pem_decode_jwk_data(jwk_data=jwk_data) if as_pem else jwk_data |
| 147 |
|
| 148 |
def oauth2_get_authorize_url( |
| 149 |
self, |
| 150 |
*, |
| 151 |
session_required_identities: ( |
| 152 |
uuid.UUID | str | t.Iterable[uuid.UUID | str] | MissingType |
| 153 |
) = MISSING, |
| 154 |
session_required_single_domain: str | t.Iterable[str] | MissingType = MISSING, |
| 155 |
session_required_policies: ( |
| 156 |
uuid.UUID | str | t.Iterable[uuid.UUID | str] | MissingType |
| 157 |
) = MISSING, |
| 158 |
session_required_mfa: bool | MissingType = MISSING, |
| 159 |
session_message: str | MissingType = MISSING, |
| 160 |
prompt: t.Literal["login"] | MissingType = MISSING, |
| 161 |
query_params: dict[str, t.Any] | None = None, |
| 162 |
) -> str: |
| 163 |
""" |
| 164 |
Get the authorization URL to which users should be sent. |
| 165 |
This method may only be called after ``oauth2_start_flow`` |
| 166 |
has been called on this ``AuthClient``. |
| 167 |
|
| 168 |
:param session_required_identities: A list of identities must be |
| 169 |
added to the session. |
| 170 |
:param session_required_single_domain: A list of domain requirements |
| 171 |
which must be satisfied by identities added to the session. |
| 172 |
:param session_required_policies: A list of IDs for policies which must |
| 173 |
be satisfied by the user. |
| 174 |
:param session_required_mfa: Whether MFA is required for the session. |
| 175 |
:param session_message: A message to be displayed to the user by Globus Auth. |
| 176 |
:param prompt: |
| 177 |
Control whether a user is required to log in before the authorization step. |
| 178 |
|
| 179 |
If set to "login", the user must authenticate with an identity provider |
| 180 |
even if they are already logged in. Setting this parameter can help ensure |
| 181 |
that a user's session meets known or unknown session requirement policies |
| 182 |
and avoid additional login flows. |
| 183 |
:param query_params: Additional query parameters to include in the |
| 184 |
authorize URL. Primarily for internal use |
| 185 |
""" |
| 186 |
if not self.current_oauth2_flow_manager: |
| 187 |
log.error("OutOfOrderOperations(get_authorize_url before start_flow)") |
| 188 |
raise exc.GlobusSDKUsageError( |
| 189 |
"Cannot get authorize URL until starting an OAuth2 flow. " |
| 190 |
"Call the oauth2_start_flow() method on this " |
| 191 |
"AuthClient to resolve" |
| 192 |
) |
| 193 |
query_params = { |
| 194 |
"session_required_identities": commajoin(session_required_identities), |
| 195 |
"session_required_single_domain": commajoin(session_required_single_domain), |
| 196 |
"session_required_policies": commajoin(session_required_policies), |
| 197 |
"session_required_mfa": session_required_mfa, |
| 198 |
"session_message": session_message, |
| 199 |
"prompt": prompt, |
| 200 |
**(query_params or {}), |
| 201 |
} |
| 202 |
auth_url = self.current_oauth2_flow_manager.get_authorize_url( |
| 203 |
query_params=query_params |
| 204 |
) |
| 205 |
log.debug(f"Got authorization URL: {auth_url}") |
| 206 |
return auth_url |
| 207 |
|
| 208 |
def oauth2_exchange_code_for_tokens( |
| 209 |
self, auth_code: str |
| 210 |
) -> OAuthAuthorizationCodeResponse: |
| 211 |
""" |
| 212 |
Exchange an authorization code for a token or tokens. |
| 213 |
|
| 214 |
:param auth_code: An auth code typically obtained by sending the user to the |
| 215 |
authorize URL. The code is a very short-lived credential which this method |
| 216 |
is exchanging for tokens. Tokens are the credentials used to authenticate |
| 217 |
against Globus APIs. |
| 218 |
""" |
| 219 |
log.debug( |
| 220 |
"Final Step of 3-legged OAuth2 Flows: " |
| 221 |
"Exchanging authorization code for token(s)" |
| 222 |
) |
| 223 |
if not self.current_oauth2_flow_manager: |
| 224 |
log.error("OutOfOrderOperations(exchange_code before start_flow)") |
| 225 |
raise exc.GlobusSDKUsageError( |
| 226 |
"Cannot exchange auth code until starting an OAuth2 flow. " |
| 227 |
"Call the oauth2_start_flow() method on this " |
| 228 |
"AuthClient to resolve" |
| 229 |
) |
| 230 |
|
| 231 |
return self.current_oauth2_flow_manager.exchange_code_for_tokens(auth_code) |
| 232 |
|
| 233 |
def oauth2_refresh_token( |
| 234 |
self, |
| 235 |
refresh_token: str, |
| 236 |
*, |
| 237 |
body_params: dict[str, t.Any] | None = None, |
| 238 |
) -> OAuthRefreshTokenResponse: |
| 239 |
r""" |
| 240 |
Exchange a refresh token for a |
| 241 |
:class:`OAuthTokenResponse <.OAuthTokenResponse>`, containing |
| 242 |
an access token. |
| 243 |
|
| 244 |
Does a token call of the form |
| 245 |
|
| 246 |
.. code-block:: none |
| 247 |
|
| 248 |
refresh_token=<refresh_token> |
| 249 |
grant_type=refresh_token |
| 250 |
|
| 251 |
plus any additional parameters you may specify. |
| 252 |
|
| 253 |
:param refresh_token: A Globus Refresh Token as a string |
| 254 |
:param body_params: A dict of extra params to encode in the refresh call. |
| 255 |
""" |
| 256 |
log.debug("Executing token refresh; typically requires client credentials") |
| 257 |
form_data = {"refresh_token": refresh_token, "grant_type": "refresh_token"} |
| 258 |
return self.oauth2_token( |
| 259 |
form_data, body_params=body_params, response_class=OAuthRefreshTokenResponse |
| 260 |
) |
| 261 |
|
| 262 |
def oauth2_revoke_token( |
| 263 |
self, |
| 264 |
token: str, |
| 265 |
*, |
| 266 |
body_params: dict[str, t.Any] | None = None, |
| 267 |
) -> GlobusHTTPResponse: |
| 268 |
""" |
| 269 |
Revoke a token. It can be an Access Token or a Refresh token. |
| 270 |
|
| 271 |
This call should be used to revoke tokens issued to your client, |
| 272 |
rendering them inert and not further usable. Typically, this is |
| 273 |
incorporated into "logout" functionality, but it should also be used if |
| 274 |
the client detects that its tokens are in an unsafe location (e.x. |
| 275 |
found in a world-readable logfile). |
| 276 |
|
| 277 |
You can check the "active" status of the token after revocation if you |
| 278 |
want to confirm that it was revoked. |
| 279 |
|
| 280 |
:param token: The token which should be revoked |
| 281 |
:param body_params: Additional parameters to include in the revocation |
| 282 |
body, which can help speed the revocation process. Primarily for |
| 283 |
internal use |
| 284 |
|
| 285 |
**Examples** |
| 286 |
|
| 287 |
>>> from globus_sdk import ConfidentialAppAuthClient |
| 288 |
>>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET) |
| 289 |
>>> ac.oauth2_revoke_token('<token_string>') |
| 290 |
""" |
| 291 |
log.debug("Revoking token") |
| 292 |
body = {"token": token} |
| 293 |
|
| 294 |
# if this client has no way of authenticating itself but |
| 295 |
# it does have a client_id, we'll send that in the request |
| 296 |
no_authentication = self.authorizer is None or isinstance( |
| 297 |
self.authorizer, NullAuthorizer |
| 298 |
) |
| 299 |
if no_authentication and self.client_id: |
| 300 |
log.debug("Revoking token with unauthenticated client") |
| 301 |
body.update({"client_id": self.client_id}) |
| 302 |
body.update(body_params or {}) |
| 303 |
return self.post("/v2/oauth2/token/revoke", data=body, encoding="form") |
| 304 |
|
| 305 |
@t.overload |
| 306 |
def oauth2_token( |
| 307 |
self, |
| 308 |
form_data: dict[str, t.Any], |
| 309 |
) -> OAuthTokenResponse: ... |
| 310 |
|
| 311 |
@t.overload |
| 312 |
def oauth2_token( |
| 313 |
self, |
| 314 |
form_data: dict[str, t.Any], |
| 315 |
*, |
| 316 |
body_params: dict[str, t.Any] | None, |
| 317 |
) -> OAuthTokenResponse: ... |
| 318 |
|
| 319 |
@t.overload |
| 320 |
def oauth2_token( |
| 321 |
self, |
| 322 |
form_data: dict[str, t.Any], |
| 323 |
*, |
| 324 |
response_class: type[RT], |
| 325 |
) -> RT: ... |
| 326 |
|
| 327 |
@t.overload |
| 328 |
def oauth2_token( |
| 329 |
self, |
| 330 |
form_data: dict[str, t.Any], |
| 331 |
*, |
| 332 |
body_params: dict[str, t.Any] | None, |
| 333 |
response_class: type[RT], |
| 334 |
) -> RT: ... |
| 335 |
|
| 336 |
def oauth2_token( |
| 337 |
self, |
| 338 |
form_data: dict[str, t.Any], |
| 339 |
*, |
| 340 |
body_params: dict[str, t.Any] | None = None, |
| 341 |
response_class: type[OAuthTokenResponse] | type[RT] = OAuthTokenResponse, |
| 342 |
) -> OAuthTokenResponse | RT: |
| 343 |
""" |
| 344 |
This is the generic form of calling the OAuth2 Token endpoint. |
| 345 |
It takes ``form_data``, a dict which will be encoded in a form POST |
| 346 |
body on the request. |
| 347 |
|
| 348 |
Generally, users of the SDK should not call this method unless they are |
| 349 |
implementing OAuth2 flows. |
| 350 |
|
| 351 |
:param response_class: This is used by calls to the oauth2_token endpoint which |
| 352 |
need to specialize their responses. For example, |
| 353 |
:meth:`oauth2_get_dependent_tokens \ |
| 354 |
<globus_sdk.ConfidentialAppAuthClient.oauth2_get_dependent_tokens>` |
| 355 |
requires a specialize response class to handle the dramatically different |
| 356 |
format of the Dependent Token Grant response |
| 357 |
:param form_data: The main body of the request |
| 358 |
:param body_params: Any additional parameters to be passed through |
| 359 |
as body parameters. |
| 360 |
:rtype: ``response_class`` if set, defaults to |
| 361 |
:py:attr:`~globus_sdk.OAuthTokenResponse` |
| 362 |
""" |
| 363 |
log.debug("Fetching new token from Globus Auth") |
| 364 |
# use the fact that requests implicitly encodes the `data` parameter as |
| 365 |
# a form POST |
| 366 |
data = {**form_data, **(body_params or {})} |
| 367 |
return response_class( |
| 368 |
self.post( |
| 369 |
"/v2/oauth2/token", |
| 370 |
data=data, |
| 371 |
encoding="form", |
| 372 |
) |
| 373 |
) |