| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
import typing as t |
| 5 |
import uuid |
| 6 |
|
| 7 |
from globus_sdk import exc |
| 8 |
from globus_sdk._internal.remarshal import strseq_iter, strseq_listify |
| 9 |
from globus_sdk._missing import MISSING, MissingType |
| 10 |
from globus_sdk.authorizers import BasicAuthorizer |
| 11 |
from globus_sdk.response import GlobusHTTPResponse |
| 12 |
from globus_sdk.scopes import Scope, ScopeParser |
| 13 |
from globus_sdk.transport import RequestsTransport, RetryConfig |
| 14 |
|
| 15 |
from ..flow_managers import GlobusAuthorizationCodeFlowManager |
| 16 |
from ..response import OAuthClientCredentialsResponse, OAuthDependentTokenResponse |
| 17 |
from .base_login_client import AuthLoginClient |
| 18 |
|
| 19 |
log = logging.getLogger(__name__) |
| 20 |
|
| 21 |
|
| 22 |
class ConfidentialAppAuthClient(AuthLoginClient): |
| 23 |
""" |
| 24 |
This is a specialized type of ``AuthLoginClient`` used to represent an App with |
| 25 |
a Client ID and Client Secret wishing to communicate with Globus Auth. |
| 26 |
It must be given a Client ID and a Client Secret, and furthermore, these |
| 27 |
will be used to establish a :class:`BasicAuthorizer <globus_sdk.BasicAuthorizer>` |
| 28 |
for authorization purposes. |
| 29 |
Additionally, the Client ID is stored for use in various calls. |
| 30 |
|
| 31 |
Confidential Applications are those which have their own credentials for |
| 32 |
authenticating against Globus Auth. |
| 33 |
|
| 34 |
:param client_id: The ID of the application provided by registration with |
| 35 |
Globus Auth. |
| 36 |
:param client_secret: The secret string to use for authentication. Secrets can be |
| 37 |
generated via the Globus developers interface. |
| 38 |
|
| 39 |
All other initialization parameters are passed through to ``BaseClient``. |
| 40 |
|
| 41 |
.. automethodlist:: globus_sdk.ConfidentialAppAuthClient |
| 42 |
""" |
| 43 |
|
| 44 |
def __init__( |
| 45 |
self, |
| 46 |
client_id: uuid.UUID | str, |
| 47 |
client_secret: str, |
| 48 |
environment: str | None = None, |
| 49 |
base_url: str | None = None, |
| 50 |
app_name: str | None = None, |
| 51 |
transport: RequestsTransport | None = None, |
| 52 |
retry_config: RetryConfig | None = None, |
| 53 |
) -> None: |
| 54 |
super().__init__( |
| 55 |
client_id=client_id, |
| 56 |
authorizer=BasicAuthorizer(str(client_id), client_secret), |
| 57 |
environment=environment, |
| 58 |
base_url=base_url, |
| 59 |
app_name=app_name, |
| 60 |
transport=transport, |
| 61 |
retry_config=retry_config, |
| 62 |
) |
| 63 |
|
| 64 |
def oauth2_client_credentials_tokens( |
| 65 |
self, requested_scopes: str | Scope | t.Iterable[str | Scope] |
| 66 |
) -> OAuthClientCredentialsResponse: |
| 67 |
r""" |
| 68 |
Perform an OAuth2 Client Credentials Grant to get access tokens which |
| 69 |
directly represent your client and allow it to act on its own |
| 70 |
(independent of any user authorization). |
| 71 |
This method does not use a ``GlobusOAuthFlowManager`` because it is not |
| 72 |
at all necessary to do so. |
| 73 |
|
| 74 |
:param requested_scopes: The scopes on the token(s) being requested. |
| 75 |
|
| 76 |
For example, with a Client ID of "CID1001" and a Client Secret of |
| 77 |
"RAND2002", you could use this grant type like so: |
| 78 |
|
| 79 |
.. code-block:: pycon |
| 80 |
|
| 81 |
>>> client = ConfidentialAppAuthClient("CID1001", "RAND2002") |
| 82 |
>>> tokens = client.oauth2_client_credentials_tokens( |
| 83 |
... "urn:globus:auth:scope:transfer.api.globus.org:all" |
| 84 |
... ) |
| 85 |
>>> transfer_token_info = tokens.by_resource_server["transfer.api.globus.org"] |
| 86 |
>>> transfer_token = transfer_token_info["access_token"] |
| 87 |
""" # noqa: E501 |
| 88 |
requested_scopes_string = ScopeParser.serialize(requested_scopes) |
| 89 |
log.debug( |
| 90 |
"Fetching token(s) using client credentials, " |
| 91 |
f"scope={requested_scopes_string}" |
| 92 |
) |
| 93 |
return self.oauth2_token( |
| 94 |
{"grant_type": "client_credentials", "scope": requested_scopes_string}, |
| 95 |
response_class=OAuthClientCredentialsResponse, |
| 96 |
) |
| 97 |
|
| 98 |
def oauth2_start_flow( |
| 99 |
self, |
| 100 |
redirect_uri: str, |
| 101 |
requested_scopes: str | Scope | t.Iterable[str | Scope], |
| 102 |
*, |
| 103 |
state: str = "_default", |
| 104 |
refresh_tokens: bool = False, |
| 105 |
) -> GlobusAuthorizationCodeFlowManager: |
| 106 |
""" |
| 107 |
Starts or resumes an Authorization Code OAuth2 flow. |
| 108 |
|
| 109 |
Under the hood, this is done by instantiating a |
| 110 |
:class:`GlobusAuthorizationCodeFlowManager |
| 111 |
<.GlobusAuthorizationCodeFlowManager>` |
| 112 |
|
| 113 |
:param redirect_uri: The page that users should be directed to after |
| 114 |
authenticating at the authorize URL. |
| 115 |
:param requested_scopes: The scopes on the token(s) being requested. |
| 116 |
:param state: This string allows an application to pass information back to |
| 117 |
itself in the course of the OAuth flow. Because the user will navigate away |
| 118 |
from the application to complete the flow, this parameter lets the app pass |
| 119 |
an arbitrary string from the starting page to the ``redirect_uri`` |
| 120 |
:param refresh_tokens: When True, request refresh tokens in addition to access |
| 121 |
tokens. [Default: ``False``] |
| 122 |
|
| 123 |
.. tab-set:: |
| 124 |
|
| 125 |
.. tab-item:: Example Usage |
| 126 |
|
| 127 |
You can see an example of this flow :ref:`in the usage examples |
| 128 |
<examples_three_legged_oauth_login>`. |
| 129 |
|
| 130 |
.. tab-item:: API Info |
| 131 |
|
| 132 |
The Authorization Code Grant flow is described |
| 133 |
`in the Globus Auth Specification |
| 134 |
<https://docs.globus.org/api/auth/developer-guide/#obtaining-authorization>`_. |
| 135 |
""" |
| 136 |
log.debug("Starting OAuth2 Authorization Code Grant Flow") |
| 137 |
self.current_oauth2_flow_manager = GlobusAuthorizationCodeFlowManager( |
| 138 |
self, |
| 139 |
redirect_uri, |
| 140 |
requested_scopes=requested_scopes, |
| 141 |
state=state, |
| 142 |
refresh_tokens=refresh_tokens, |
| 143 |
) |
| 144 |
return self.current_oauth2_flow_manager |
| 145 |
|
| 146 |
def oauth2_get_dependent_tokens( |
| 147 |
self, |
| 148 |
token: str, |
| 149 |
*, |
| 150 |
refresh_tokens: bool = False, |
| 151 |
scope: str | t.Iterable[str] | MissingType = MISSING, |
| 152 |
additional_params: dict[str, t.Any] | None = None, |
| 153 |
) -> OAuthDependentTokenResponse: |
| 154 |
""" |
| 155 |
Fetch Dependent Tokens from Globus Auth. |
| 156 |
|
| 157 |
This exchanges a token given to this client for a new set of tokens |
| 158 |
which give it access to resource servers on which it depends. |
| 159 |
This grant type is intended for use by Resource Servers playing out the |
| 160 |
following scenario: |
| 161 |
|
| 162 |
1. User has tokens for Service A, but Service A requires access to |
| 163 |
Service B on behalf of the user |
| 164 |
2. Service B should not see tokens scoped for Service A |
| 165 |
3. Service A therefore requests tokens scoped only for Service B, |
| 166 |
based on tokens which were originally scoped for Service A... |
| 167 |
|
| 168 |
In order to do this exchange, the tokens for Service A must have scopes |
| 169 |
which depend on scopes for Service B (the services' scopes must encode |
| 170 |
their relationship). As long as that is the case, Service A can use |
| 171 |
this Grant to get those "Dependent" or "Downstream" tokens for Service B. |
| 172 |
|
| 173 |
:param token: An access token as a string |
| 174 |
:param refresh_tokens: When True, request dependent refresh tokens in addition |
| 175 |
to access tokens. [Default: ``False``] |
| 176 |
:param scope: The scope or scopes of the dependent tokens which are being |
| 177 |
requested. Applications are recommended to provide this string to ensure |
| 178 |
that they are receiving the tokens they expect. If omitted, all available |
| 179 |
dependent tokens will be returned. |
| 180 |
:param additional_params: Additional parameters to include in the request body |
| 181 |
|
| 182 |
.. tab-set:: |
| 183 |
|
| 184 |
.. tab-item:: Example Usage |
| 185 |
|
| 186 |
Given a token, getting a dependent token for Globus Groups might |
| 187 |
look like the following: |
| 188 |
|
| 189 |
.. code-block:: python |
| 190 |
|
| 191 |
ac = globus_sdk.ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET) |
| 192 |
dependent_token_data = ac.oauth2_get_dependent_tokens( |
| 193 |
"<token_string>", |
| 194 |
scope="urn:globus:auth:scope:groups.api.globus.org:view_my_groups_and_memberships", |
| 195 |
) |
| 196 |
|
| 197 |
group_token_data = dependent_token_data.by_resource_server["groups.api.globus.org"] |
| 198 |
group_token = group_token_data["access_token"] |
| 199 |
|
| 200 |
.. tab-item:: Example Response Data |
| 201 |
|
| 202 |
.. expandtestfixture:: auth.oauth2_get_dependent_tokens |
| 203 |
:case: groups |
| 204 |
|
| 205 |
.. tab-item:: API Info |
| 206 |
|
| 207 |
``POST /v2/oauth2/token`` |
| 208 |
|
| 209 |
.. extdoclink:: Dependent Token Grant |
| 210 |
:ref: auth/reference/##dependent_token_grant_post_v2oauth2token |
| 211 |
""" # noqa: E501 |
| 212 |
log.debug( |
| 213 |
"Getting dependent tokens from access token" |
| 214 |
f"additional_params={additional_params}" |
| 215 |
) |
| 216 |
form_data = { |
| 217 |
"grant_type": "urn:globus:auth:grant_type:dependent_token", |
| 218 |
"token": token, |
| 219 |
# the internal parameter is 'access_type', but using the name |
| 220 |
# 'refresh_tokens' is consistent with the rest of the SDK and better |
| 221 |
# communicates expectations back to the user than the OAuth2 spec wording |
| 222 |
"access_type": "offline" if refresh_tokens else MISSING, |
| 223 |
"scope": (" ".join(strseq_iter(scope)) if scope is not MISSING else scope), |
| 224 |
**(additional_params or {}), |
| 225 |
} |
| 226 |
return self.oauth2_token(form_data, response_class=OAuthDependentTokenResponse) |
| 227 |
|
| 228 |
def oauth2_token_introspect( |
| 229 |
self, |
| 230 |
token: str, |
| 231 |
*, |
| 232 |
include: str | MissingType = MISSING, |
| 233 |
query_params: dict[str, t.Any] | None = None, |
| 234 |
) -> GlobusHTTPResponse: |
| 235 |
""" |
| 236 |
Get information about a Globus Auth token. |
| 237 |
|
| 238 |
:param token: An Access Token as a raw string, being evaluated |
| 239 |
:param include: A value for the ``include`` parameter in the request body. |
| 240 |
Default is to omit the parameter. |
| 241 |
:param query_params: Any additional parameters to be passed through |
| 242 |
as query params. |
| 243 |
|
| 244 |
.. tab-set:: |
| 245 |
|
| 246 |
.. tab-item:: Example Usage |
| 247 |
|
| 248 |
.. code-block:: python |
| 249 |
|
| 250 |
ac = globus_sdk.ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET) |
| 251 |
ac.oauth2_token_introspect("<token_string>") |
| 252 |
|
| 253 |
Get information about a Globus Auth token including the full identity |
| 254 |
set of the user to whom it belongs |
| 255 |
|
| 256 |
.. code-block:: python |
| 257 |
|
| 258 |
ac = globus_sdk.ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET) |
| 259 |
data = ac.oauth2_token_introspect("<token_string>", include="identity_set") |
| 260 |
for identity in data["identity_set"]: |
| 261 |
print('token authenticates for "{}"'.format(identity)) |
| 262 |
|
| 263 |
.. tab-item:: API Info |
| 264 |
|
| 265 |
``POST /v2/oauth2/token/introspect`` |
| 266 |
|
| 267 |
.. extdoclink:: Token Introspection |
| 268 |
:ref: auth/reference/#token_introspection_post_v2_oauth2_token_introspect |
| 269 |
""" # noqa: E501 |
| 270 |
log.debug("Checking token validity (introspect)") |
| 271 |
body = { |
| 272 |
"token": token, |
| 273 |
"include": include, |
| 274 |
} |
| 275 |
return self.post( |
| 276 |
"/v2/oauth2/token/introspect", |
| 277 |
data=body, |
| 278 |
encoding="form", |
| 279 |
query_params=query_params, |
| 280 |
) |
| 281 |
|
| 282 |
def create_child_client( |
| 283 |
self, |
| 284 |
name: str, |
| 285 |
*, |
| 286 |
public_client: bool | MissingType = MISSING, |
| 287 |
client_type: ( |
| 288 |
t.Literal[ |
| 289 |
"client_identity", |
| 290 |
"confidential_client", |
| 291 |
"globus_connect_server", |
| 292 |
"public_installed_client", |
| 293 |
"hybrid_confidential_client_resource_server", |
| 294 |
"resource_server", |
| 295 |
] |
| 296 |
| MissingType |
| 297 |
) = MISSING, |
| 298 |
visibility: t.Literal["public", "private"] | MissingType = MISSING, |
| 299 |
redirect_uris: t.Iterable[str] | MissingType = MISSING, |
| 300 |
terms_and_conditions: str | MissingType = MISSING, |
| 301 |
privacy_policy: str | MissingType = MISSING, |
| 302 |
required_idp: uuid.UUID | str | MissingType = MISSING, |
| 303 |
preselect_idp: uuid.UUID | str | MissingType = MISSING, |
| 304 |
additional_fields: dict[str, t.Any] | None = None, |
| 305 |
) -> GlobusHTTPResponse: |
| 306 |
""" |
| 307 |
Create a new client. Requires the ``manage_projects`` scope. |
| 308 |
|
| 309 |
:param name: The display name shown to users on consents. May not contain |
| 310 |
linebreaks. |
| 311 |
:param public_client: This is used to infer which OAuth grant_types the client |
| 312 |
will be able to use. Should be false if the client is capable of keeping |
| 313 |
secret credentials (such as clients running on a server) and true if it is |
| 314 |
not (such as native apps). After creation this value is immutable. This |
| 315 |
option is mutually exclusive with ``client_type``, exactly one must be |
| 316 |
given. |
| 317 |
:param client_type: Defines the type of client that will be created. This |
| 318 |
option is mutually exclusive with ``public_client``, exactly one must |
| 319 |
be given. |
| 320 |
|
| 321 |
.. dropdown:: Values for ``client_type`` |
| 322 |
|
| 323 |
.. list-table:: |
| 324 |
|
| 325 |
* - ``"confidential_client"`` |
| 326 |
- Applications that are OAuth confidential clients, and can |
| 327 |
manage a client secret and requests for user consent. |
| 328 |
* - ``"public_installed_client"`` |
| 329 |
- Applications that are OAuth public clients or native |
| 330 |
applications that are distributed to users, and thus cannot |
| 331 |
manage a client secret. |
| 332 |
* - ``"client_identity"`` |
| 333 |
- Applications that authenticate and act as the application |
| 334 |
itself. These applications are used for automation and as |
| 335 |
service or community accounts, and do NOT act on behalf of |
| 336 |
other users. Also known as a "Service Account". |
| 337 |
* - ``"resource_server"`` |
| 338 |
- An API (OAuth resource server) that uses Globus Auth tokens for |
| 339 |
authentication. Users accessing the service login via Globus and |
| 340 |
consent for the client to use your API. |
| 341 |
* - ``"globus_connect_server"`` |
| 342 |
- Create a client that will service as a Globus Connect Server |
| 343 |
endpoint. |
| 344 |
* - ``"hybrid_confidential_client_resource_server"`` |
| 345 |
- A client which can use any behavior with Globus Auth - an |
| 346 |
application (confidential or public client), service account, |
| 347 |
or API. |
| 348 |
|
| 349 |
:param visibility: If set to "public", any authenticated entity can view it. |
| 350 |
When set to "private", only entities in the same project as the client can |
| 351 |
view it. |
| 352 |
:param redirect_uris: list of URIs that may be used in OAuth authorization |
| 353 |
flows. |
| 354 |
:param terms_and_conditions: URL of client's terms and conditions. |
| 355 |
:param privacy_policy: URL of client's privacy policy. |
| 356 |
:param required_idp: In order to use this client a user must have an identity |
| 357 |
from this IdP in their identity set. |
| 358 |
:param preselect_idp: This preselects the given IdP on the Globus Auth login |
| 359 |
page if the user is not already authenticated. |
| 360 |
:param additional_fields: Any additional parameters to be passed through. |
| 361 |
|
| 362 |
.. tab-set:: |
| 363 |
|
| 364 |
.. tab-item:: Example Usage |
| 365 |
|
| 366 |
.. code-block:: pycon |
| 367 |
|
| 368 |
>>> ac = globus_sdk.AuthClient(...) |
| 369 |
>>> project_id = ... |
| 370 |
>>> r = ac.create_child_client( |
| 371 |
... "My client", |
| 372 |
... True, |
| 373 |
... True, |
| 374 |
... ) |
| 375 |
>>> client_id = r["client"]["id"] |
| 376 |
|
| 377 |
.. tab-item:: Example Response Data |
| 378 |
|
| 379 |
.. expandtestfixture:: auth.create_child_client |
| 380 |
|
| 381 |
.. tab-item:: API Info |
| 382 |
|
| 383 |
``POST /v2/api/clients`` |
| 384 |
|
| 385 |
.. extdoclink:: Create Client |
| 386 |
:ref: auth/reference/#create_client |
| 387 |
""" |
| 388 |
# Must specify exactly one of public_client or client_type |
| 389 |
if public_client is not MISSING and client_type is not MISSING: |
| 390 |
raise exc.GlobusSDKUsageError( |
| 391 |
"AuthClient.create_client does not take both " |
| 392 |
"'public_client' and 'client_type'. These are mutually exclusive." |
| 393 |
) |
| 394 |
if public_client is MISSING and client_type is MISSING: |
| 395 |
raise exc.GlobusSDKUsageError( |
| 396 |
"AuthClient.create_client requires either 'public_client' or " |
| 397 |
"'client_type'." |
| 398 |
) |
| 399 |
# terms_and_conditions and privacy_policy must both be set or unset |
| 400 |
if bool(terms_and_conditions) ^ bool(privacy_policy): |
| 401 |
raise exc.GlobusSDKUsageError( |
| 402 |
"terms_and_conditions and privacy_policy must both be set or unset" |
| 403 |
) |
| 404 |
links: dict[str, str | MissingType] | MissingType = MISSING |
| 405 |
if terms_and_conditions and privacy_policy: |
| 406 |
links = { |
| 407 |
"terms_and_conditions": terms_and_conditions, |
| 408 |
"privacy_policy": privacy_policy, |
| 409 |
} |
| 410 |
|
| 411 |
body: dict[str, t.Any] = { |
| 412 |
"name": name, |
| 413 |
"visibility": visibility, |
| 414 |
"required_idp": required_idp, |
| 415 |
"preselect_idp": preselect_idp, |
| 416 |
"public_client": public_client, |
| 417 |
"client_type": client_type, |
| 418 |
"redirect_uris": strseq_listify(redirect_uris), |
| 419 |
"links": links, |
| 420 |
**(additional_fields or {}), |
| 421 |
} |
| 422 |
|
| 423 |
return self.post("/v2/api/clients", data={"client": body}) |