Debian Codegraph @

src/globus_sdk/services/auth/client/service_client.py

raw
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, strseq_listify
11 from globus_sdk._missing import MISSING, MissingType
12 from globus_sdk.authorizers import GlobusAuthorizer
13 from globus_sdk.response import GlobusHTTPResponse, IterableResponse
14 from globus_sdk.scopes import AuthScopes, Scope
15 from globus_sdk.transport import RequestsTransport, RetryConfig
16
17 if t.TYPE_CHECKING:
18 from globus_sdk.globus_app import GlobusApp
19
20 from .._common import get_jwk_data, pem_decode_jwk_data
21 from ..data import DependentScopeSpec
22 from ..errors import AuthAPIError
23 from ..response import (
24 GetClientCredentialsResponse,
25 GetClientsResponse,
26 GetConsentsResponse,
27 GetIdentitiesResponse,
28 GetIdentityProvidersResponse,
29 GetPoliciesResponse,
30 GetProjectsResponse,
31 GetScopesResponse,
32 )
33
34 log = logging.getLogger(__name__)
35
36 F = t.TypeVar("F", bound=t.Callable[..., GlobusHTTPResponse])
37
38
39 class AuthClient(client.BaseClient):
40 """
41 A client for using the
42 `Globus Auth API <https://docs.globus.org/api/auth/>`_
43
44 .. sdk-sphinx-copy-params:: BaseClient
45
46 This class provides helper methods for most common resources in the
47 Auth API, and the common low-level interface from
48 :class:`BaseClient <globus_sdk.client.BaseClient>` of ``get``, ``put``,
49 ``post``, and ``delete`` methods, which can be used to access any API
50 resource.
51
52 **Examples**
53
54 Initializing an ``AuthClient`` to authenticate a user making calls to the
55 Globus Auth service with an access token takes the form
56
57 >>> from globus_sdk import AuthClient, AccessTokenAuthorizer
58 >>> ac = AuthClient(authorizer=AccessTokenAuthorizer('<token_string>'))
59
60 Other authorizers, most notably ``RefreshTokenAuthorizer``, are also supported.
61
62 .. automethodlist:: globus_sdk.AuthClient
63 """
64
65 service_name = "auth"
66 error_class = AuthAPIError
67 scopes = AuthScopes
68 default_scope_requirements = [
69 AuthScopes.openid,
70 AuthScopes.profile,
71 AuthScopes.email,
72 ]
73
74 def __init__(
75 self,
76 environment: str | None = None,
77 base_url: str | None = None,
78 app: GlobusApp | None = None,
79 app_scopes: list[Scope] | None = None,
80 authorizer: GlobusAuthorizer | None = None,
81 app_name: str | None = None,
82 transport: RequestsTransport | None = None,
83 retry_config: RetryConfig | None = None,
84 ) -> None:
85 super().__init__(
86 environment=environment,
87 base_url=base_url,
88 app=app,
89 app_scopes=app_scopes,
90 authorizer=authorizer,
91 app_name=app_name,
92 transport=transport,
93 retry_config=retry_config,
94 )
95
96 # FYI: this get_openid_configuration method is duplicated in AuthLoginBaseClient
97 # if this code is modified, please update that copy as well
98 # this will ideally be resolved in a future SDK version by making this the only copy
99 def get_openid_configuration(self) -> GlobusHTTPResponse:
100 """
101 Fetch the OpenID Connect configuration data from the well-known URI for Globus
102 Auth.
103 """
104 log.debug("Fetching OIDC Config")
105 return self.get("/.well-known/openid-configuration")
106
107 @t.overload
108 def get_jwk(
109 self,
110 openid_configuration: GlobusHTTPResponse | dict[str, t.Any] | MissingType,
111 *,
112 as_pem: t.Literal[True],
113 ) -> RSAPublicKey: ...
114
115 @t.overload
116 def get_jwk(
117 self,
118 openid_configuration: GlobusHTTPResponse | dict[str, t.Any] | MissingType,
119 *,
120 as_pem: t.Literal[False],
121 ) -> dict[str, t.Any]: ...
122
123 # FYI: this get_jwk method is duplicated in AuthLoginBaseClient
124 # if this code is modified, please update that copy as well
125 # this will ideally be resolved in a future SDK version by making this the only copy
126 def get_jwk(
127 self,
128 openid_configuration: (
129 GlobusHTTPResponse | dict[str, t.Any] | MissingType
130 ) = MISSING,
131 *,
132 as_pem: bool = False,
133 ) -> RSAPublicKey | dict[str, t.Any]:
134 """
135 Fetch the Globus Auth JWK.
136
137 Returns either a dict or an RSA Public Key object depending on ``as_pem``.
138
139 :param openid_configuration: The OIDC config as a GlobusHTTPResponse or dict.
140 When not provided, it will be fetched automatically.
141 :type openid_configuration: None | GlobusHTTPResponse | dict[str, typing.Any]
142 :param as_pem: Decode the JWK to an RSA PEM key, typically for JWT decoding
143 :type as_pem: bool
144 """
145 if openid_configuration is MISSING:
146 log.debug("No OIDC Config provided, autofetching...")
147 openid_configuration = self.get_openid_configuration()
148 jwk_data = get_jwk_data(
149 fget=self.get, openid_configuration=openid_configuration
150 )
151 return pem_decode_jwk_data(jwk_data=jwk_data) if as_pem else jwk_data
152
153 def userinfo(self) -> GlobusHTTPResponse:
154 """
155 Call the Userinfo endpoint of Globus Auth.
156 Userinfo is specified as part of the OpenID Connect (OIDC) standard,
157 and Globus Auth's Userinfo is OIDC-compliant.
158
159 The exact data returned will depend upon the set of OIDC-related scopes
160 which were used to acquire the token being used for this call. For
161 details, see the **API Info** below.
162
163 .. tab-set::
164
165 .. tab-item:: Example Usage
166
167 .. code-block:: python
168
169 ac = AuthClient(...)
170 info = ac.userinfo()
171 print(
172 'Effective Identity "{info["sub"]}" has '
173 f'Full Name "{info["name"]}" and '
174 f'Email "{info["email"]}"'
175 )
176
177 .. tab-item:: API Info
178
179 ``GET /v2/oauth2/userinfo``
180
181 .. extdoclink:: Get Userinfo
182 :ref: auth/reference/#get_or_post_v2_oauth2_userinfo_resource
183 """
184 log.debug("Looking up OIDC-style Userinfo from Globus Auth")
185 return self.get("/v2/oauth2/userinfo")
186
187 def get_identities(
188 self,
189 *,
190 usernames: t.Iterable[str] | str | MissingType = MISSING,
191 ids: t.Iterable[uuid.UUID | str] | uuid.UUID | str | MissingType = MISSING,
192 provision: bool = False,
193 query_params: dict[str, t.Any] | None = None,
194 ) -> GetIdentitiesResponse:
195 r"""
196 Given ``usernames=<U>`` or (exclusive) ``ids=<I>`` as keyword
197 arguments, looks up identity information for the set of identities
198 provided.
199 ``<U>`` and ``<I>`` in this case are comma-delimited strings listing
200 multiple Identity Usernames or Identity IDs, or iterables of strings,
201 each of which is an Identity Username or Identity ID.
202
203 If Globus Auth's identity auto-provisioning behavior is desired,
204 ``provision=True`` may be specified.
205
206 Available with any authentication/client type.
207
208 :param usernames: A username or list of usernames to lookup. Mutually exclusive
209 with ``ids``
210 :param ids: An identity ID or list of IDs to lookup. Mutually exclusive
211 with ``usernames``
212 :param provision: Create identities if they do not exist, allowing clients to
213 get username-to-identity mappings prior to the identity being used
214 :param query_params: Any additional parameters to be passed through
215 as query params.
216
217 .. tab-set::
218
219 .. tab-item:: Example Usage
220
221 .. code-block:: pycon
222
223 >>> ac = globus_sdk.AuthClient(...)
224 >>> # get by ID
225 >>> r = ac.get_identities(ids="46bd0f56-e24f-11e5-a510-131bef46955c")
226 >>> r.data
227 {
228 'identities': [
229 {
230 'email': None,
231 'id': '46bd0f56-e24f-11e5-a510-131bef46955c',
232 'identity_provider': '7daddf46-70c5-45ee-9f0f-7244fe7c8707',
233 'name': None,
234 'organization': None,
235 'status': 'unused',
236 'username': '[email protected]'
237 }
238 ]
239 }
240 >>> ac.get_identities(
241 ... ids=",".join(
242 ... ("46bd0f56-e24f-11e5-a510-131bef46955c", "168edc3d-c6ba-478c-9cf8-541ff5ebdc1c")
243 ... )
244 ... )
245 >>> # or by usernames
246 >>> ac.get_identities(usernames="[email protected]")
247 >>> ac.get_identities(usernames="[email protected],[email protected]")
248
249 You could also use iterables:
250
251 .. code-block:: python
252
253 ac.get_identities(usernames=["[email protected]", "[email protected]"])
254
255 ac.get_identities(
256 ids=["46bd0f56-e24f-11e5-a510-131bef46955c", "168edc3d-c6ba-478c-9cf8-541ff5ebdc1c"]
257 )
258
259 The result itself is iterable, so you can use it like so:
260
261 .. code-block:: python
262
263 for identity in ac.get_identities(usernames=["[email protected]", "[email protected]"]):
264 print(identity["id"])
265
266 .. tab-item:: API Info
267
268 ``GET /v2/api/identities``
269
270 .. extdoclink:: Get Identities
271 :ref: auth/reference/#v2_api_identities_resources
272 """ # noqa: E501
273
274 log.debug("Looking up Globus Auth Identities")
275
276 query_params = {
277 "usernames": commajoin(usernames),
278 "ids": commajoin(ids),
279 # only specify `provision` if `usernames` is given
280 "provision": (
281 str(provision).lower() if usernames is not MISSING else MISSING
282 ),
283 **(query_params or {}),
284 }
285
286 if (
287 query_params["usernames"] is not MISSING
288 and query_params["ids"] is not MISSING
289 ):
290 log.warning(
291 "get_identities called with both usernames and "
292 "identities set! Expecting an error."
293 )
294
295 log.debug(f"query_params={query_params}")
296
297 return GetIdentitiesResponse(
298 self.get("/v2/api/identities", query_params=query_params)
299 )
300
301 def get_identity_providers(
302 self,
303 *,
304 domains: t.Iterable[str] | str | MissingType = MISSING,
305 ids: t.Iterable[uuid.UUID | str] | uuid.UUID | str | MissingType = MISSING,
306 query_params: dict[str, t.Any] | None = None,
307 ) -> GetIdentityProvidersResponse:
308 r"""
309 Look up information about identity providers by domains or by IDs.
310
311 :param domains: A domain or iterable of domains to lookup. Mutually exclusive
312 with ``ids``.
313 :param ids: An identity provider ID or iterable of IDs to lookup. Mutually exclusive
314 with ``domains``.
315 :param query_params: Any additional parameters to be passed through
316 as query params.
317
318 .. tab-set::
319
320 .. tab-item:: Example Usage
321
322 .. code-block:: pycon
323
324 >>> ac = globus_sdk.AuthClient(...)
325 >>> # get by ID
326 >>> r = ac.get_identity_providers(ids="41143743-f3c8-4d60-bbdb-eeecaba85bd9")
327 >>> r.data
328 {
329 'identity_providers': [
330 {
331 'alternative_names': [],
332 'name': 'Globus ID',
333 'domains': ['globusid.org'],
334 'id': '41143743-f3c8-4d60-bbdb-eeecaba85bd9',
335 'short_name': 'globusid'
336 }
337 ]
338 }
339 >>> ac.get_identities(
340 ... ids=["41143743-f3c8-4d60-bbdb-eeecaba85bd9", "927d7238-f917-4eb2-9ace-c523fa9ba34e"]
341 ... )
342 >>> # or by domain
343 >>> ac.get_identities(domains="globusid.org")
344 >>> ac.get_identities(domains=["globus.org", "globusid.org"])
345
346 The result itself is iterable, so you can use it like so:
347
348 .. code-block:: python
349
350 for idp in ac.get_identity_providers(domains=["globus.org", "globusid.org"]):
351 print(f"name: {idp['name']}")
352 print(f"id: {idp['id']}")
353 print(f"domains: {idp['domains']}")
354 print()
355
356 .. tab-item:: Example Response Data
357
358 .. expandtestfixture:: auth.get_identity_providers
359
360 .. tab-item:: API Info
361
362 ``GET /v2/api/identity_providers``
363
364 .. extdoclink:: Get Identity Providers
365 :ref: auth/reference/#get_identity_providers
366 """ # noqa: E501
367
368 log.debug("Looking up Globus Auth Identity Providers")
369
370 if domains is not MISSING and ids is not MISSING:
371 raise exc.GlobusSDKUsageError(
372 "AuthClient.get_identity_providers does not take both "
373 "'domains' and 'ids'. These are mutually exclusive."
374 )
375 elif domains is MISSING and ids is MISSING:
376 log.warning(
377 "Neither 'domains' nor 'ids' provided to get_identity_providers(). "
378 "This can only succeed if 'query_params' were given."
379 )
380
381 query_params = {
382 "domains": commajoin(domains),
383 "ids": commajoin(ids),
384 **(query_params or {}),
385 }
386
387 log.debug(f"query_params={query_params}")
388 return GetIdentityProvidersResponse(
389 self.get("/v2/api/identity_providers", query_params=query_params)
390 )
391
392 #
393 # Developer APIs
394 #
395
396 def get_project(self, project_id: uuid.UUID | str) -> GlobusHTTPResponse:
397 """
398 Look up a project. Requires the ``manage_projects`` scope.
399
400 :param project_id: The ID of the project to lookup
401
402 .. tab-set::
403
404 .. tab-item:: Example Usage
405
406 .. code-block:: pycon
407
408 >>> ac = globus_sdk.AuthClient(...)
409 >>> r = ac.get_project("927d7238-f917-4eb2-9ace-c523fa9ba34e")
410 >>> r.data
411 {
412 'project': {
413 'admin_ids': ['41143743-f3c8-4d60-bbdb-eeecaba85bd9']
414 'contact_email': '[email protected]',
415 'display_name': 'Globus SDK Demo Project',
416 'admin_group_ids': None,
417 'id': '927d7238-f917-4eb2-9ace-c523fa9ba34e',
418 'project_name': 'Globus SDK Demo Project',
419 'admins': {
420 'identities': ['41143743-f3c8-4d60-bbdb-eeecaba85bd9'],
421 'groups': [],
422 },
423 }
424 }
425
426 .. tab-item:: Example Response Data
427
428 .. expandtestfixture:: auth.get_project
429
430 .. tab-item:: API Info
431
432 ``GET /v2/api/projects/{project_id}``
433
434 .. extdoclink:: Get Projects
435 :ref: auth/reference/#get_projects
436 """
437 return self.get(f"/v2/api/projects/{project_id}")
438
439 def get_projects(self) -> IterableResponse:
440 """
441 Look up projects on which the authenticated user is an admin.
442 Requires the ``manage_projects`` scope.
443
444 .. tab-set::
445
446 .. tab-item:: Example Usage
447
448 .. code-block:: pycon
449
450 >>> ac = globus_sdk.AuthClient(...)
451 >>> r = ac.get_projects()
452 >>> r.data
453 {
454 'projects': [
455 {
456 'admin_ids': ['41143743-f3c8-4d60-bbdb-eeecaba85bd9']
457 'contact_email': '[email protected]',
458 'display_name': 'Globus SDK Demo Project',
459 'admin_group_ids': None,
460 'id': '927d7238-f917-4eb2-9ace-c523fa9ba34e',
461 'project_name': 'Globus SDK Demo Project',
462 'admins': {
463 'identities': ['41143743-f3c8-4d60-bbdb-eeecaba85bd9'],
464 'groups': [],
465 },
466 }
467 ]
468 }
469
470 The result itself is iterable, so you can use it like so:
471
472 .. code-block:: python
473
474 for project in ac.get_projects():
475 print(f"name: {project['display_name']}")
476 print(f"id: {project['id']}")
477 print()
478
479 .. tab-item:: Example Response Data
480
481 .. expandtestfixture:: auth.get_projects
482
483 .. tab-item:: API Info
484
485 ``GET /v2/api/projects``
486
487 .. extdoclink:: Get Projects
488 :ref: auth/reference/#get_projects
489 """ # noqa: E501
490 return GetProjectsResponse(self.get("/v2/api/projects"))
491
492 def create_project(
493 self,
494 display_name: str,
495 contact_email: str,
496 *,
497 admin_ids: (
498 uuid.UUID | str | t.Iterable[uuid.UUID | str] | MissingType
499 ) = MISSING,
500 admin_group_ids: (
501 uuid.UUID | str | t.Iterable[uuid.UUID | str] | MissingType
502 ) = MISSING,
503 ) -> GlobusHTTPResponse:
504 """
505 Create a new project. Requires the ``manage_projects`` scope.
506
507 At least one of ``admin_ids`` or ``admin_group_ids`` must be provided.
508
509 :param display_name: The name of the project
510 :param contact_email: The email address of the project's point of contact
511 :param admin_ids: A list of user IDs to be added as admins of the project
512 :param admin_group_ids: A list of group IDs to be added as admins of the project
513
514 .. tab-set::
515
516 .. tab-item:: Example Usage
517
518 When creating a project, your account is not necessarily included as an
519 admin. The following snippet uses the ``manage_projects`` scope as well
520 as the ``openid`` and ``email`` scopes to get the current user ID and
521 email address and use those data to setup the project.
522
523 .. code-block:: pycon
524
525 >>> ac = globus_sdk.AuthClient(...)
526 >>> userinfo = ac.userinfo()
527 >>> identity_id = userinfo["sub"]
528 >>> email = userinfo["email"]
529 >>> r = ac.create_project(
530 ... "My Project",
531 ... contact_email=email,
532 ... admin_ids=identity_id,
533 ... )
534 >>> project_id = r["project"]["id"]
535
536 .. tab-item:: Example Response Data
537
538 .. expandtestfixture:: auth.create_project
539
540 .. tab-item:: API Info
541
542 ``POST /v2/api/projects``
543
544 .. extdoclink:: Create Project
545 :ref: auth/reference/#create_project
546 """
547 body = {
548 "display_name": display_name,
549 "contact_email": contact_email,
550 "admin_ids": strseq_listify(admin_ids),
551 "admin_group_ids": strseq_listify(admin_group_ids),
552 }
553 return self.post("/v2/api/projects", data={"project": body})
554
555 def update_project(
556 self,
557 project_id: uuid.UUID | str,
558 *,
559 display_name: str | MissingType = MISSING,
560 contact_email: str | MissingType = MISSING,
561 admin_ids: (
562 uuid.UUID | str | t.Iterable[uuid.UUID | str] | MissingType
563 ) = MISSING,
564 admin_group_ids: (
565 uuid.UUID | str | t.Iterable[uuid.UUID | str] | MissingType
566 ) = MISSING,
567 ) -> GlobusHTTPResponse:
568 """
569 Update a project. Requires the ``manage_projects`` scope.
570
571 :param project_id: The ID of the project to update
572 :param display_name: The name of the project
573 :param contact_email: The email address of the project's point of contact
574 :param admin_ids: A list of user IDs to be set as admins of the project
575 :param admin_group_ids: A list of group IDs to be set as admins of the project
576
577 .. tab-set::
578
579 .. tab-item:: Example Usage
580
581 The following snippet uses the ``manage_projects`` scope as well
582 as the ``email`` scope to get the current user email address and set it
583 as a project's contact email:
584
585 .. code-block:: pycon
586
587 >>> ac = globus_sdk.AuthClient(...)
588 >>> project_id = ...
589 >>> userinfo = ac.userinfo()
590 >>> email = userinfo["email"]
591 >>> r = ac.update_project(project_id, contact_email=email)
592
593 .. tab-item:: Example Response Data
594
595 .. expandtestfixture:: auth.update_project
596
597 .. tab-item:: API Info
598
599 ``POST /v2/api/projects``
600
601 .. extdoclink:: Update Project
602 :ref: auth/reference/#update_project
603 """
604 body = {
605 "display_name": display_name,
606 "contact_email": contact_email,
607 "admin_ids": strseq_listify(admin_ids),
608 "admin_group_ids": strseq_listify(admin_group_ids),
609 }
610 return self.put(f"/v2/api/projects/{project_id}", data={"project": body})
611
612 def delete_project(self, project_id: uuid.UUID | str) -> GlobusHTTPResponse:
613 """
614 Delete a project. Requires the ``manage_projects`` scope.
615
616 :param project_id: The ID of the project to delete
617
618 .. tab-set::
619
620 .. tab-item:: Example Usage
621
622 .. code-block:: pycon
623
624 >>> ac = globus_sdk.AuthClient(...)
625 >>> project_id = ...
626 >>> r = ac.delete_project(project_id)
627
628 .. tab-item:: Example Response Data
629
630 .. expandtestfixture:: auth.delete_project
631
632 .. tab-item:: API Info
633
634 ``DELETE /v2/api/projects/{project_id}``
635
636 .. extdoclink:: Delete Project
637 :ref: auth/reference/#delete_project
638 """
639 return self.delete(f"/v2/api/projects/{project_id}")
640
641 def get_policy(self, policy_id: uuid.UUID | str) -> GlobusHTTPResponse:
642 """
643 Look up a policy. Requires the ``manage_projects`` scope.
644
645 :param policy_id: The ID of the policy to lookup
646
647 .. tab-set::
648
649 .. tab-item:: Example Usage
650
651 .. code-block:: pycon
652
653 >>> ac = globus_sdk.AuthClient(...)
654 >>> r = ac.get_policy("f5eaae7e-807f-41be-891a-ec86ff88df8f")
655 >>> r.data
656 {
657 'policy': {
658 'high_assurance': False,
659 'domain_constraints_include': ['globus.org'],
660 'display_name': 'Display Name',
661 'description': 'Description',
662 'id': 'f5eaae7e-807f-41be-891a-ec86ff88df8f',
663 'domain_constraints_exclude': None,
664 'project_id': 'da84e531-1afb-43cb-8c87-135ab580516a',
665 'authentication_assurance_timeout': 35,
666 'required_mfa": False
667 }
668 }
669
670 .. tab-item:: Example Response Data
671
672 .. expandtestfixture:: auth.get_policy
673
674 .. tab-item:: API Info
675
676 ``GET /v2/api/policies/{policy_id}``
677
678 .. extdoclink:: Get Policies
679 :ref: auth/reference/#get_policies
680 """
681 return self.get(f"/v2/api/policies/{policy_id}")
682
683 def get_policies(self) -> IterableResponse:
684 """
685 Look up policies in projects on which the authenticated user is an admin.
686 Requires the ``manage_projects`` scope.
687
688 .. tab-set::
689
690 .. tab-item:: Example Usage
691
692 .. code-block:: pycon
693
694 >>> ac = globus_sdk.AuthClient(...)
695 >>> r = ac.get_policies()
696 >>> r.data
697 {
698 'policies': [
699 {
700 'high_assurance': False,
701 'domain_constraints_include': ['greenlight.org'],
702 'display_name': 'GreenLight domain Only Policy',
703 'description': 'Only allow access from @greenlight.org',
704 'id': '99d2dc75-3acb-48ff-b5e5-2eee0a5121d1',
705 'domain_constraints_exclude': None,
706 'project_id': 'da84e531-1afb-43cb-8c87-135ab580516a',
707 'authentication_assurance_timeout': 35,
708 'required_mfa': False
709 },
710 {
711 'high_assurance': True,
712 'domain_constraints_include': None,
713 'display_name': 'No RedLight domain Policy',
714 'description': 'Disallow access from @redlight.org',
715 'id': '5d93ebf0-b4c6-4928-9929-4ac47fc2786d',
716 'domain_constraints_exclude': ['redlight.org'],
717 'project_id': 'da84e531-1afb-43cb-8c87-135ab580516a',
718 'authentication_assurance_timeout': 35,
719 'required_mfa': True
720 }
721 ]
722 }
723
724 .. tab-item:: Example Response Data
725
726 .. expandtestfixture:: auth.get_policies
727
728 .. tab-item:: API Info
729
730 ``GET /v2/api/policies``
731
732 .. extdoclink:: Get Policies
733 :ref: auth/reference/#get_policies
734 """
735 return GetPoliciesResponse(self.get("/v2/api/policies"))
736
737 def create_policy(
738 self,
739 *,
740 project_id: uuid.UUID | str,
741 display_name: str,
742 description: str,
743 high_assurance: bool | MissingType = MISSING,
744 authentication_assurance_timeout: int | MissingType = MISSING,
745 required_mfa: bool | MissingType = MISSING,
746 domain_constraints_include: t.Iterable[str] | None | MissingType = MISSING,
747 domain_constraints_exclude: t.Iterable[str] | None | MissingType = MISSING,
748 ) -> GlobusHTTPResponse:
749 """
750 Create a new Auth policy. Requires the ``manage_projects`` scope.
751
752 :param project_id: ID of the project for the new policy
753 :param display_name: A user-friendly name for the policy
754 :param description: A user-friendly description to explain the purpose of the
755 policy
756 :param high_assurance: Whether or not this policy is applied to sessions.
757 :param authentication_assurance_timeout: Number of seconds within which someone
758 must have authenticated to satisfy the policy
759 :param required_mfa: If True, then multi-factor authentication is required.
760 This can only be set to True for high-assurance policies. The default
761 is False.
762 :param domain_constraints_include: A list of domains that can satisfy the policy
763 :param domain_constraints_exclude: A list of domains that cannot satisfy the
764 policy
765
766 .. note::
767
768 ``project_id``, ``display_name``, and ``description`` are all required
769 arguments, although they are not declared as required in the function
770 signature. This is due to a backwards compatible behavior with earlier
771 versions of globus-sdk, and will be changed in a future release which
772 removes the compatible behavior.
773
774 .. tab-set::
775
776 .. tab-item:: Example Usage
777
778 .. code-block:: pycon
779
780 >>> ac = globus_sdk.AuthClient(...)
781 >>> r = ac.create_policy(
782 ... project_id="da84e531-1afb-43cb-8c87-135ab580516a",
783 ... high_assurance=True,
784 ... authentication_assurance_timeout=35,
785 ... required_mfa=True,
786 ... display_name="No RedLight domain Policy",
787 ... description="Disallow access from @redlight.org",
788 ... domain_constraints_exclude=["redlight.org"],
789 ... )
790 >>> policy_id = r["policy"]["id"]
791
792 .. tab-item:: Example Response Data
793
794 .. expandtestfixture:: auth.create_policy
795
796 .. tab-item:: API Info
797
798 ``POST /v2/api/policies``
799
800 .. extdoclink:: Create Policy
801 :ref: auth/reference/#create_policy
802 """
803 body: dict[str, t.Any] = {
804 "project_id": project_id,
805 "high_assurance": high_assurance,
806 "authentication_assurance_timeout": authentication_assurance_timeout,
807 "required_mfa": required_mfa,
808 "display_name": display_name,
809 "description": description,
810 "domain_constraints_include": strseq_listify(domain_constraints_include),
811 "domain_constraints_exclude": strseq_listify(domain_constraints_exclude),
812 }
813
814 return self.post("/v2/api/policies", data={"policy": body})
815
816 def update_policy(
817 self,
818 policy_id: uuid.UUID | str,
819 *,
820 project_id: uuid.UUID | str | MissingType = MISSING,
821 authentication_assurance_timeout: int | MissingType = MISSING,
822 required_mfa: bool | MissingType = MISSING,
823 display_name: str | MissingType = MISSING,
824 description: str | MissingType = MISSING,
825 domain_constraints_include: t.Iterable[str] | None | MissingType = MISSING,
826 domain_constraints_exclude: t.Iterable[str] | None | MissingType = MISSING,
827 ) -> GlobusHTTPResponse:
828 """
829 Update a policy. Requires the ``manage_projects`` scope.
830
831 :param policy_id: ID of the policy to update
832 :param project_id: ID of the project for the new policy
833 :param authentication_assurance_timeout: Number of seconds within which someone
834 must have authenticated to satisfy the policy
835 :param required_mfa: If True, then multi-factor authentication is required.
836 This can only be set to True for high-assurance policies. The default
837 is False.
838 :param display_name: A user-friendly name for the policy
839 :param description: A user-friendly description to explain the purpose of the
840 policy
841 :param domain_constraints_include: A list of domains that can satisfy the policy
842 :param domain_constraints_exclude: A list of domains that can not satisfy the
843 policy
844
845 .. tab-set::
846
847 .. tab-item:: Example Usage
848
849 .. code-block:: pycon
850
851 >>> ac = globus_sdk.AuthClient(...)
852 >>> policy_id = ...
853 >>> r = ac.update_policy(scope_id, display_name="Greenlight Policy")
854
855 .. tab-item:: Example Response Data
856
857 .. expandtestfixture:: auth.update_policy
858
859 .. tab-item:: API Info
860
861 ``POST /v2/api/policies/{policy_id}``
862
863 .. extdoclink:: Update Policy
864 :ref: auth/reference/#update_policy
865 """
866 body: dict[str, t.Any] = {
867 "authentication_assurance_timeout": authentication_assurance_timeout,
868 "required_mfa": required_mfa,
869 "display_name": display_name,
870 "description": description,
871 "domain_constraints_include": strseq_listify(domain_constraints_include),
872 "domain_constraints_exclude": strseq_listify(domain_constraints_exclude),
873 "project_id": project_id,
874 }
875 return self.put(f"/v2/api/policies/{policy_id}", data={"policy": body})
876
877 def delete_policy(self, policy_id: uuid.UUID | str) -> GlobusHTTPResponse:
878 """
879 Delete a policy. Requires the ``manage_projects`` scope.
880
881 :param policy_id: The ID of the policy to delete
882
883 .. tab-set::
884
885 .. tab-item:: Example Usage
886
887 .. code-block:: pycon
888
889 >>> ac = globus_sdk.AuthClient(...)
890 >>> policy_id = ...
891 >>> r = ac.delete_policy(policy_id)
892
893 .. tab-item:: Example Response Data
894
895 .. expandtestfixture:: auth.delete_policy
896
897 .. tab-item:: API Info
898
899 ``DELETE /v2/api/policies/{policy_id}``
900
901 .. extdoclink:: Delete Policy
902 :ref: auth/reference/#delete_policy
903 """
904 return self.delete(f"/v2/api/policies/{policy_id}")
905
906 def get_client(
907 self,
908 *,
909 client_id: uuid.UUID | str | MissingType = MISSING,
910 fqdn: str | MissingType = MISSING,
911 ) -> GlobusHTTPResponse:
912 """
913 Look up a client by ``client_id`` or (exclusive) by ``fqdn``.
914 Requires the ``manage_projects`` scope.
915
916 :param client_id: The ID of the client to look up
917 :param fqdn: The fully-qualified domain name of the client to look up
918
919 .. tab-set::
920
921 .. tab-item:: Example Usage
922
923 .. code-block:: pycon
924
925 >>> ac = globus_sdk.AuthClient(...)
926 >>> # by client_id
927 >>> r = ac.get_client(client_id="6336437e-37e8-4559-82a8-674390c1fd2e")
928 >>> r.data
929 {
930 'client': {
931 'required_idp': None,
932 'name': 'Great client of FOO',
933 'redirect_uris': [],
934 'links': {
935 'privacy_policy': None,
936 'terms_and_conditions': None
937 },
938 'scopes': [],
939 'grant_types': [
940 'authorization_code',
941 'client_credentials',
942 'refresh_token'
943 ],
944 'id': '6336437e-37e8-4559-82a8-674390c1fd2e',
945 'prompt_for_named_grant': False,
946 'fqdns': ['globus.org'],
947 'project': 'da84e531-1afb-43cb-8c87-135ab580516a',
948 'client_type': 'client_identity',
949 'visibility': 'private',
950 'parent_client': None,
951 'userinfo_from_effective_identity': True,
952 'preselect_idp': None,
953 'public_client': False
954 }
955 }
956 >>> # by fqdn
957 >>> fqdn = ...
958 >>> r = ac.get_client(fqdn=fqdn)
959
960 .. tab-item:: Example Response Data
961
962 .. expandtestfixture:: auth.get_client
963
964 .. tab-item:: API Info
965
966 ``GET /v2/api/clients/{client_id}``
967 ``GET /v2/api/clients?fqdn={fqdn}``
968
969 .. extdoclink:: Get Clients
970 :ref: auth/reference/#get_clients
971 """ # noqa: E501
972 if client_id is not MISSING and fqdn is not MISSING:
973 raise exc.GlobusSDKUsageError(
974 "AuthClient.get_client does not take both "
975 "'client_id' and 'fqdn'. These are mutually exclusive."
976 )
977
978 if client_id is MISSING and fqdn is MISSING:
979 raise exc.GlobusSDKUsageError(
980 "AuthClient.get_client requires either 'client_id' or 'fqdn'."
981 )
982
983 if client_id is not MISSING:
984 return self.get(f"/v2/api/clients/{client_id}")
985 return self.get("/v2/api/clients", query_params={"fqdn": fqdn})
986
987 def get_clients(self) -> IterableResponse:
988 """
989 Look up clients in projects on which the authenticated user is an admin.
990 Requires the ``manage_projects`` scope.
991
992 .. tab-set::
993
994 .. tab-item:: Example Usage
995
996 .. code-block:: pycon
997
998 >>> ac = globus_sdk.AuthClient(...)
999 >>> r = ac.get_clients()
1000 >>> r.data
1001 {
1002 'clients': [
1003 {
1004 'required_idp': None,
1005 'name': 'Great client of FOO',
1006 'redirect_uris': [],
1007 'links': {'privacy_policy': None, 'terms_and_conditions': None},
1008 'scopes': [],
1009 'grant_types': ['authorization_code', 'client_credentials', 'refresh_token'],
1010 'id': 'b6001d11-8765-49d3-a503-ba323fc74eee',
1011 'prompt_for_named_grant': False,
1012 'fqdns': ['foo.net'],
1013 'project': 'da84e531-1afb-43cb-8c87-135ab580516a',
1014 'client_type': 'client_identity',
1015 'visibility': 'private',
1016 'parent_client': None,
1017 'userinfo_from_effective_identity': True,
1018 'preselect_idp': None,
1019 'public_client': False,
1020 },
1021 {
1022 'required_idp': None,
1023 'name': 'Lessor client of BAR',
1024 'redirect_uris': [],
1025 'links': {'privacy_policy': None, 'terms_and_conditions': None},
1026 'scopes': [],
1027 'grant_types': ['authorization_code', 'client_credentials', 'refresh_token'],
1028 'id': 'b87f7415-ddf9-4868-8e55-d10c065f733d',
1029 'prompt_for_named_grant': False,
1030 'fqdns': ['bar.org'],
1031 'project': 'da84e531-1afb-43cb-8c87-135ab580516a',
1032 'client_type': 'client_identity',
1033 'visibility': 'private',
1034 'parent_client': None,
1035 'userinfo_from_effective_identity': True,
1036 'preselect_idp': None,
1037 'public_client': False,
1038 }
1039 ]
1040 }
1041
1042 .. tab-item:: Example Response Data
1043
1044 .. expandtestfixture:: auth.get_clients
1045
1046 .. tab-item:: API Info
1047
1048 ``GET /v2/api/clients``
1049
1050 .. extdoclink:: Get Clients
1051 :ref: auth/reference/#get_clients
1052 """ # noqa: E501
1053 return GetClientsResponse(self.get("/v2/api/clients"))
1054
1055 def create_client(
1056 self,
1057 name: str,
1058 project: uuid.UUID | str,
1059 *,
1060 public_client: bool | MissingType = MISSING,
1061 client_type: (
1062 MissingType
1063 | t.Literal[
1064 "client_identity",
1065 "confidential_client",
1066 "globus_connect_server",
1067 "public_installed_client",
1068 "hybrid_confidential_client_resource_server",
1069 "resource_server",
1070 ]
1071 ) = MISSING,
1072 visibility: MissingType | t.Literal["public", "private"] = MISSING,
1073 redirect_uris: t.Iterable[str] | MissingType = MISSING,
1074 terms_and_conditions: str | MissingType = MISSING,
1075 privacy_policy: str | MissingType = MISSING,
1076 required_idp: uuid.UUID | str | MissingType = MISSING,
1077 preselect_idp: uuid.UUID | str | MissingType = MISSING,
1078 additional_fields: dict[str, t.Any] | MissingType = MISSING,
1079 ) -> GlobusHTTPResponse:
1080 """
1081 Create a new client. Requires the ``manage_projects`` scope.
1082
1083 :param name: The display name shown to users on consents. May not contain
1084 linebreaks.
1085 :param project: ID representing the project this client belongs to.
1086
1087 :param public_client: This is used to infer which OAuth grant_types the client
1088 will be able to use. Should be false if the client is capable of keeping
1089 secret credentials (such as clients running on a server) and true if it is
1090 not (such as native apps). After creation this value is immutable. This
1091 option is mutually exclusive with ``client_type``, exactly one must be
1092 given.
1093 :param client_type: Defines the type of client that will be created. This
1094 option is mutually exclusive with ``public_client``, exactly one must
1095 be given.
1096
1097 .. dropdown:: Values for ``client_type``
1098
1099 .. list-table::
1100
1101 * - ``"confidential_client"``
1102 - Applications that are OAuth confidential clients, and can
1103 manage a client secret and requests for user consent.
1104 * - ``"public_installed_client"``
1105 - Applications that are OAuth public clients or native
1106 applications that are distributed to users, and thus cannot
1107 manage a client secret.
1108 * - ``"client_identity"``
1109 - Applications that authenticate and act as the application
1110 itself. These applications are used for automation and as
1111 service or community accounts, and do NOT act on behalf of
1112 other users. Also known as a "Service Account".
1113 * - ``"resource_server"``
1114 - An API (OAuth resource server) that uses Globus Auth tokens for
1115 authentication. Users accessing the service login via Globus and
1116 consent for the client to use your API.
1117 * - ``"globus_connect_server"``
1118 - Create a client that will service as a Globus Connect Server
1119 endpoint.
1120 * - ``"hybrid_confidential_client_resource_server"``
1121 - A client which can use any behavior with Globus Auth - an
1122 application (confidential or public client), service account,
1123 or API.
1124
1125 :param visibility: If set to "public", any authenticated entity can view it.
1126 When set to "private", only entities in the same project as the client can
1127 view it.
1128 :param redirect_uris: list of URIs that may be used in OAuth authorization
1129 flows.
1130 :param terms_and_conditions: URL of client's terms and conditions.
1131 :param privacy_policy: URL of client's privacy policy.
1132 :param required_idp: In order to use this client a user must have an identity
1133 from this IdP in their identity set.
1134 :param preselect_idp: This preselects the given IdP on the Globus Auth login
1135 page if the user is not already authenticated.
1136 :param additional_fields: Any additional parameters to be passed through.
1137
1138 .. tab-set::
1139
1140 .. tab-item:: Example Usage
1141
1142 .. code-block:: pycon
1143
1144 >>> ac = globus_sdk.AuthClient(...)
1145 >>> project = ...
1146 >>> r = ac.create_client(
1147 ... "My client",
1148 ... True,
1149 ... project,
1150 ... True,
1151 ... )
1152 >>> client_id = r["client"]["id"]
1153
1154 .. tab-item:: Example Response Data
1155
1156 .. expandtestfixture:: auth.create_client
1157
1158 .. tab-item:: API Info
1159
1160 ``POST /v2/api/clients``
1161
1162 .. extdoclink:: Create Client
1163 :ref: auth/reference/#create_client
1164 """
1165 # Must specify exactly one of public_client or client_type
1166 if public_client is not MISSING and client_type is not MISSING:
1167 raise exc.GlobusSDKUsageError(
1168 "AuthClient.create_client does not take both "
1169 "'public_client' and 'client_type'. These are mutually exclusive."
1170 )
1171 if public_client is MISSING and client_type is MISSING:
1172 raise exc.GlobusSDKUsageError(
1173 "AuthClient.create_client requires either 'public_client' or "
1174 "'client_type'."
1175 )
1176
1177 body: dict[str, t.Any] = {
1178 "name": name,
1179 "project": project,
1180 "visibility": visibility,
1181 "redirect_uris": redirect_uris,
1182 "required_idp": required_idp,
1183 "preselect_idp": preselect_idp,
1184 "public_client": public_client,
1185 "client_type": client_type,
1186 }
1187 # terms_and_conditions and privacy_policy must both be set or unset
1188 if bool(terms_and_conditions) ^ bool(privacy_policy):
1189 raise exc.GlobusSDKUsageError(
1190 "terms_and_conditions and privacy_policy must both be set or unset"
1191 )
1192 links: dict[str, str | MissingType] = {
1193 "terms_and_conditions": terms_and_conditions,
1194 "privacy_policy": privacy_policy,
1195 }
1196 if terms_and_conditions or privacy_policy:
1197 body["links"] = links
1198
1199 if additional_fields is not MISSING:
1200 body.update(additional_fields)
1201
1202 return self.post("/v2/api/clients", data={"client": body})
1203
1204 def update_client(
1205 self,
1206 client_id: uuid.UUID | str,
1207 *,
1208 name: str | MissingType = MISSING,
1209 visibility: MissingType | t.Literal["public", "private"] = MISSING,
1210 redirect_uris: t.Iterable[str] | MissingType = MISSING,
1211 terms_and_conditions: str | None | MissingType = MISSING,
1212 privacy_policy: str | None | MissingType = MISSING,
1213 required_idp: uuid.UUID | str | None | MissingType = MISSING,
1214 preselect_idp: uuid.UUID | str | None | MissingType = MISSING,
1215 additional_fields: dict[str, t.Any] | MissingType = MISSING,
1216 ) -> GlobusHTTPResponse:
1217 """
1218 Update a client. Requires the ``manage_projects`` scope.
1219
1220 :param client_id: ID of the client to update
1221 :param name: The display name shown to users on consents. May not contain
1222 linebreaks.
1223 :param visibility: If set to "public", any authenticated entity can view it.
1224 When set to "private", only entities in the same project as the client can
1225 view it.
1226 :param redirect_uris: list of URIs that may be used in OAuth authorization
1227 flows.
1228 :param terms_and_conditions: URL of client's terms and conditions.
1229 :param privacy_policy: URL of client's privacy policy.
1230 :param required_idp: In order to use this client a user must have an identity
1231 from this IdP in their identity set.
1232 :param preselect_idp: This preselects the given IdP on the Globus Auth login
1233 page if the user is not already authenticated.
1234 :param additional_fields: Any additional parameters to be passed through.
1235
1236
1237 .. tab-set::
1238
1239 .. tab-item:: Example Usage
1240
1241 .. code-block:: pycon
1242
1243 >>> ac = globus_sdk.AuthClient(...)
1244 >>> client_id = ...
1245 >>> r = ac.update_client(client_id, name="Foo Utility")
1246
1247 .. tab-item:: Example Response Data
1248
1249 .. expandtestfixture:: auth.update_client
1250
1251 .. tab-item:: API Info
1252
1253 ``POST /v2/api/clients/{client_id}``
1254
1255 .. extdoclink:: Update Client
1256 :ref: auth/reference/#update_client
1257 """
1258 body: dict[str, t.Any] = {
1259 "name": name,
1260 "visibility": visibility,
1261 "redirect_uris": redirect_uris,
1262 "required_idp": required_idp,
1263 "preselect_idp": preselect_idp,
1264 }
1265
1266 # terms_and_conditions and privacy_policy must both be set or unset, and if one
1267 # is set to `None` they both must be set to `None`
1268 # note the subtle differences between this logic for "update" and the matching
1269 # logic for "create"
1270 # "create" does not need to handle `None` as a distinct and meaningful value
1271 if type(terms_and_conditions) is not type(privacy_policy):
1272 raise exc.GlobusSDKUsageError(
1273 "terms_and_conditions and privacy_policy must both be set or unset"
1274 )
1275 links: dict[str, str | None | MissingType] = {
1276 "terms_and_conditions": terms_and_conditions,
1277 "privacy_policy": privacy_policy,
1278 }
1279 if terms_and_conditions is not MISSING or privacy_policy is not MISSING:
1280 body["links"] = links
1281
1282 if additional_fields is not MISSING:
1283 body.update(additional_fields)
1284
1285 return self.put(f"/v2/api/clients/{client_id}", data={"client": body})
1286
1287 def delete_client(self, client_id: uuid.UUID | str) -> GlobusHTTPResponse:
1288 """
1289 Delete a client. Requires the ``manage_projects`` scope.
1290
1291 :param client_id: The ID of the client to delete
1292
1293 .. tab-set::
1294
1295 .. tab-item:: Example Usage
1296
1297 .. code-block:: pycon
1298
1299 >>> ac = globus_sdk.AuthClient(...)
1300 >>> client_id = ...
1301 >>> r = ac.delete_policy(client_id)
1302
1303 .. tab-item:: Example Response Data
1304
1305 .. expandtestfixture:: auth.delete_client
1306
1307 .. tab-item:: API Info
1308
1309 ``DELETE /v2/api/clients/{client_id}``
1310
1311 .. extdoclink:: Delete Client
1312 :ref: auth/reference/#delete_client
1313 """
1314 return self.delete(f"/v2/api/clients/{client_id}")
1315
1316 def get_client_credentials(self, client_id: uuid.UUID | str) -> IterableResponse:
1317 """
1318 Look up client credentials by ``client_id``. Requires the
1319 ``manage_projects`` scope.
1320
1321 :param client_id: The ID of the client that owns the credentials
1322
1323 .. tab-set::
1324
1325 .. tab-item:: Example Usage
1326
1327 .. code-block:: pycon
1328
1329 >>> ac = globus_sdk.AuthClient(...)
1330 >>> r = ac.get_credentials("6336437e-37e8-4559-82a8-674390c1fd2e")
1331 >>> r.data
1332 {
1333 'credentials': [
1334 'name': 'foo',
1335 'id': 'cf88318e-b2dd-43fd-8ea5-2086fc69ffac',
1336 'created': '2023-10-21T22:46:15.845937+00:00',
1337 'client': '6336437e-37e8-4559-82a8-674390c1fd2e',
1338 'secret': None,
1339 ]
1340 }
1341
1342 .. tab-item:: Example Response Data
1343
1344 .. expandtestfixture:: auth.get_client_credentials
1345
1346 .. tab-item:: API Info
1347
1348 ``GET /v2/api/clients/{client_id}/credentials``
1349
1350 .. extdoclink:: Get Client Credentials
1351 :ref: auth/reference/#get_client_credentials
1352 """ # noqa: E501
1353 return GetClientCredentialsResponse(
1354 self.get(f"/v2/api/clients/{client_id}/credentials")
1355 )
1356
1357 def create_client_credential(
1358 self,
1359 client_id: uuid.UUID | str,
1360 name: str,
1361 ) -> GlobusHTTPResponse:
1362 """
1363 Create a new client credential. Requires the ``manage_projects`` scope.
1364
1365 :param client_id: ID for the client
1366 :param name: The display name of the new credential.
1367
1368 .. tab-set::
1369
1370 .. tab-item:: Example Usage
1371
1372 .. code-block:: pycon
1373
1374 >>> ac = globus_sdk.AuthClient(...)
1375 >>> client_id = ...
1376 >>> name = ...
1377 >>> r = ac.create_client_credential(
1378 ... "25afc56d-02af-4175-8c90-9941ebb623dd",
1379 ... "New Credentials",
1380 ... )
1381 >>> r.data
1382 {
1383 'name': 'New Credentials',
1384 'id': '3a53cb4d-edd6-4ae3-900e-25b38b5fce02',
1385 'created': '2023-10-21T22:46:15.845937+00:00',
1386 'client': '25afc56d-02af-4175-8c90-9941ebb623dd',
1387 'secret': 'abc123',
1388 }
1389
1390 .. tab-item:: Example Response Data
1391
1392 .. expandtestfixture:: auth.create_client_credential
1393
1394 .. tab-item:: API Info
1395
1396 ``POST /v2/api/clients/{client_id}/credentials``
1397
1398 .. extdoclink:: Create Client Credentials
1399 :ref: auth/reference/#create_client_credential
1400 """
1401 return self.post(
1402 f"/v2/api/clients/{client_id}/credentials",
1403 data={"credential": {"name": name}},
1404 )
1405
1406 def delete_client_credential(
1407 self,
1408 client_id: uuid.UUID | str,
1409 credential_id: uuid.UUID | str,
1410 ) -> GlobusHTTPResponse:
1411 """
1412 Delete a credential. Requires the ``manage_projects`` scope.
1413
1414 :param client_id: The ID of the client that owns the credential to delete
1415 :param credential_id: The ID of the credential to delete
1416
1417 .. tab-set::
1418
1419 .. tab-item:: Example Usage
1420
1421 .. code-block:: pycon
1422
1423 >>> ac = globus_sdk.AuthClient(...)
1424 >>> client_id = ...
1425 >>> credential_id = ...
1426 >>> r = ac.delete_policy(client_id, credential_id)
1427
1428 .. tab-item:: Example Response Data
1429
1430 .. expandtestfixture:: auth.delete_client_credential
1431
1432 .. tab-item:: API Info
1433
1434 ``DELETE /v2/api/clients/{client_id}/credentials/{credential_id}``
1435
1436 .. extdoclink:: Delete Credential
1437 :ref: auth/reference/#delete_client_credentials
1438 """
1439 return self.delete(f"/v2/api/clients/{client_id}/credentials/{credential_id}")
1440
1441 def get_scope(self, scope_id: uuid.UUID | str) -> GlobusHTTPResponse:
1442 """
1443 Look up a scope by ``scope_id``. Requires the ``manage_projects`` scope.
1444
1445 :param scope_id: The ID of the scope to look up
1446
1447 .. tab-set::
1448
1449 .. tab-item:: Example Usage
1450
1451 .. code-block:: pycon
1452
1453 >>> ac = globus_sdk.AuthClient(...)
1454 >>> r = ac.get_scope(scope_id="6336437e-37e8-4559-82a8-674390c1fd2e")
1455 >>> r.data
1456 {
1457 'scope': {
1458 'scope_string': 'https://auth.globus.org/scopes/3f33d83f-ec0a-4190-887d-0622e7c4ee9a/manager',
1459 'allows_refresh_token': False,
1460 'id': '87cf7b34-e1e1-4805-a8d5-51ab59fe6000',
1461 'advertised': False,
1462 'required_domains': [],
1463 'name': 'Client manage scope',
1464 'description': 'Manage configuration of this client',
1465 'client': '3f33d83f-ec0a-4190-887d-0622e7c4ee9a',
1466 'dependent_scopes': [],
1467 }
1468 }
1469
1470 .. tab-item:: Example Response Data
1471
1472 .. expandtestfixture:: auth.get_scope
1473
1474 .. tab-item:: API Info
1475
1476 ``GET /v2/api/scopes/{scope_id}``
1477
1478 .. extdoclink:: Get Scopes
1479 :ref: auth/reference/#get_scopes
1480 """ # noqa: E501
1481 return self.get(f"/v2/api/scopes/{scope_id}")
1482
1483 def get_scopes(
1484 self,
1485 *,
1486 scope_strings: t.Iterable[str] | str | MissingType = MISSING,
1487 ids: t.Iterable[uuid.UUID | str] | uuid.UUID | str | MissingType = MISSING,
1488 query_params: dict[str, t.Any] | MissingType = MISSING,
1489 ) -> IterableResponse:
1490 """
1491 Look up scopes in projects on which the authenticated user is an admin.
1492 The scopes response can be filted by ``scope_strings`` or (exclusive)
1493 ``ids``. Requires the ``manage_projects`` scope.
1494
1495 :param scope_strings: The scope_strings of the scopes to look up
1496 :param ids: The ID of the scopes to look up
1497 :param query_params: Any additional parameters to be passed through
1498 as query params.
1499
1500 .. tab-set::
1501
1502 .. tab-item:: Example Usage
1503
1504 .. code-block:: pycon
1505
1506 >>> ac = globus_sdk.AuthClient(...)
1507 >>> # get all scopes
1508 >>> r = ac.get_scopes()
1509 >>> r.data
1510 {
1511 'scopes': [
1512 {
1513 'scope_string': 'https://auth.globus.org/scopes/3f33d83f-ec0a-4190-887d-0622e7c4ee9a/manage',
1514 'allows_refresh_token': False,
1515 'id': '70147193-f88a-4da9-9d6e-677c15e790e5',
1516 'advertised': False,
1517 'required_domains': [],
1518 'name': 'Client manage scope',
1519 'description': 'Manage configuration of this client',
1520 'client': '3f33d83f-ec0a-4190-887d-0622e7c4ee9a',
1521 'dependent_scopes': [],
1522 },
1523 {
1524 'scope_string': 'https://auth.globus.org/scopes/dfc9a6d3-3373-4a6d-b0a1-b7026d1559d6/view',
1525 'allows_refresh_token': False,
1526 'id': '3793042a-203c-4e86-8dfe-17d407d0bb5f',
1527 'advertised': False,
1528 'required_domains': [],
1529 'name': 'Client view scope',
1530 'description': 'View configuration of this client',
1531 'client': 'dfc9a6d3-3373-4a6d-b0a1-b7026d1559d6',
1532 'dependent_scopes': [],
1533 }
1534 ]
1535 }
1536
1537 >>> # by all scope ids
1538 >>> scope_ids = ...
1539 >>> r = ac.get_scopes(ids=scopes_ides)
1540
1541 >>> # by all scope strings
1542 >>> scope_strings = ...
1543 >>> r = ac.get_scopes(scope_strings=scope_strings)
1544
1545 .. tab-item:: Example Response Data
1546
1547 .. expandtestfixture:: auth.get_scopes
1548
1549 .. tab-item:: API Info
1550
1551 ``GET /v2/api/scopes``
1552 ``GET /v2/api/scopes?ids=...``
1553 ``GET /v2/api/scopes?scope_strings=...``
1554
1555 .. extdoclink:: Get Scopes
1556 :ref: auth/reference/#get_scopes
1557 """ # noqa: E501
1558 if scope_strings is not MISSING and ids is not MISSING:
1559 raise exc.GlobusSDKUsageError(
1560 "AuthClient.get_scopes does not take both "
1561 "'scopes_strings' and 'ids'. These are mutually exclusive."
1562 )
1563
1564 if query_params is MISSING:
1565 query_params = {}
1566
1567 if scope_strings is not MISSING:
1568 query_params["scope_strings"] = commajoin(scope_strings)
1569 if ids is not MISSING:
1570 query_params["ids"] = commajoin(ids)
1571
1572 return GetScopesResponse(self.get("/v2/api/scopes", query_params=query_params))
1573
1574 def create_scope(
1575 self,
1576 client_id: uuid.UUID | str,
1577 name: str,
1578 description: str,
1579 scope_suffix: str,
1580 *,
1581 required_domains: t.Iterable[str] | MissingType = MISSING,
1582 dependent_scopes: t.Iterable[DependentScopeSpec] | MissingType = MISSING,
1583 advertised: bool | MissingType = MISSING,
1584 allows_refresh_token: bool | MissingType = MISSING,
1585 ) -> GlobusHTTPResponse:
1586 """
1587 Create a new scope. Requires the ``manage_projects`` scope.
1588
1589 :param client_id: ID of the client for the new scope
1590 :param name: A display name used to display consents to users,
1591 along with description
1592 :param description: A description used to display consents to users, along with
1593 name
1594 :param scope_suffix: String consisting of lowercase letters, number, and
1595 underscores. This will be the final part of the scope_string
1596 :param required_domains: Domains the user must have linked identities in in
1597 order to make use of the scope
1598 :param dependent_scopes: Scopes included in the consent for this new scope
1599 :param advertised: If True, scope is visible to anyone regardless of client
1600 visibility, otherwise, scope visibility is based on client visibility.
1601 :param allows_refresh_token: Whether or not the scope allows refresh tokens
1602 to be issued.
1603
1604 .. tab-set::
1605
1606 .. tab-item:: Example Usage
1607
1608 .. code-block:: pycon
1609
1610 >>> ac = globus_sdk.AuthClient(...)
1611 >>> client_id = ...
1612 >>> r = ac.create_scope(
1613 ... client_id,
1614 ... "Client Management",
1615 ... "Manage client configuration",
1616 ... "manage",
1617 ... )
1618 >>> scope_id = r["scope"]["id"]
1619
1620 .. tab-item:: Example Response Data
1621
1622 .. expandtestfixture:: auth.create_scope
1623
1624 .. tab-item:: API Info
1625
1626 ``POST /v2/api/clients/{client_id}/scopes``
1627
1628 .. extdoclink:: Create Scope
1629 :ref: auth/reference/#create_scope
1630 """
1631 body: dict[str, t.Any] = {
1632 "name": name,
1633 "description": description,
1634 "scope_suffix": scope_suffix,
1635 "advertised": advertised,
1636 "allows_refresh_token": allows_refresh_token,
1637 "required_domains": required_domains,
1638 "dependent_scopes": dependent_scopes,
1639 }
1640
1641 return self.post(f"/v2/api/clients/{client_id}/scopes", data={"scope": body})
1642
1643 def update_scope(
1644 self,
1645 scope_id: uuid.UUID | str,
1646 *,
1647 name: str | MissingType = MISSING,
1648 description: str | MissingType = MISSING,
1649 scope_suffix: str | MissingType = MISSING,
1650 required_domains: t.Iterable[str] | MissingType = MISSING,
1651 dependent_scopes: t.Iterable[DependentScopeSpec] | MissingType = MISSING,
1652 advertised: bool | MissingType = MISSING,
1653 allows_refresh_token: bool | MissingType = MISSING,
1654 ) -> GlobusHTTPResponse:
1655 """
1656 Update a scope. Requires the ``manage_projects`` scope.
1657
1658 :param scope_id: ID of the scope to update
1659 :param name: A display name used to display consents to users,
1660 along with description
1661 :param description: A description used to display consents to users, along with
1662 name
1663 :param scope_suffix: String consisting of lowercase letters, number, and
1664 underscores. This will be the final part of the scope_string
1665 :param required_domains: Domains the user must have linked identities in in
1666 order to make use of the scope
1667 :param dependent_scopes: Scopes included in the consent for this new scope
1668 :param advertised: If True, scope is visible to anyone regardless of client
1669 visibility, otherwise, scope visibility is based on client visibility.
1670 :param allows_refresh_token: Whether or not the scope allows refresh tokens
1671 to be issued.
1672
1673 .. tab-set::
1674
1675 .. tab-item:: Example Usage
1676
1677 .. code-block:: pycon
1678
1679 >>> ac = globus_sdk.AuthClient(...)
1680 >>> scope_id = ...
1681 >>> r = ac.update_scope(scope_id, scope_suffix="manage")
1682
1683 .. tab-item:: Example Response Data
1684
1685 .. expandtestfixture:: auth.update_scope
1686
1687 .. tab-item:: API Info
1688
1689 ``POST /v2/api/scopes/{scope_id}``
1690
1691 .. extdoclink:: Update Scope
1692 :ref: auth/reference/#update_scope
1693 """
1694 body: dict[str, t.Any] = {
1695 "name": name,
1696 "description": description,
1697 "scope_suffix": scope_suffix,
1698 "advertised": advertised,
1699 "allows_refresh_token": allows_refresh_token,
1700 "required_domains": required_domains,
1701 "dependent_scopes": dependent_scopes,
1702 }
1703
1704 return self.put(f"/v2/api/scopes/{scope_id}", data={"scope": body})
1705
1706 def delete_scope(self, scope_id: uuid.UUID | str) -> GlobusHTTPResponse:
1707 """
1708 Delete a scope. Requires the ``manage_projects`` scope.
1709
1710 :param scope_id: The ID of the scope to delete
1711
1712 .. tab-set::
1713
1714 .. tab-item:: Example Usage
1715
1716 .. code-block:: pycon
1717
1718 >>> ac = globus_sdk.AuthClient(...)
1719 >>> scope_id = ...
1720 >>> r = ac.delete_scope(scope_id)
1721
1722 .. tab-item:: Example Response Data
1723
1724 .. expandtestfixture:: auth.delete_scope
1725
1726 .. tab-item:: API Info
1727
1728 ``DELETE /v2/api/scopes/{scope_id}``
1729
1730 .. extdoclink:: Delete Scopes
1731 :ref: auth/reference/#delete_scope
1732 """
1733 return self.delete(f"/v2/api/scopes/{scope_id}")
1734
1735 def get_consents(
1736 self,
1737 identity_id: uuid.UUID | str,
1738 *,
1739 # pylint: disable=redefined-builtin
1740 all: bool = False,
1741 ) -> GetConsentsResponse:
1742 """
1743 Look up consents for a user.
1744
1745 If requesting "all" consents, the view_consents scope is required.
1746
1747 :param identity_id: The ID of the identity to look up consents for
1748 :param all: If true, return all consents, including those that have
1749 been issued to other clients. If false, return only consents rooted at this
1750 client id for the requested identity. Most clients should pass False.
1751
1752 .. tab-set::
1753
1754 .. tab-item:: Example Usage
1755
1756 .. code-block:: pycon
1757
1758 >>> ac = globus_sdk.AuthClient(...)
1759 >>> identity_id = ...
1760 >>> forest = ac.get_consents(identity_id).to_forest()
1761
1762 .. tab-item:: Example Response Data
1763
1764 .. expandtestfixture:: auth.get_consents
1765
1766 .. tab-item:: API Info
1767
1768 ``GET /v2/api/identities/{identity_id}/consents``
1769 """
1770 return GetConsentsResponse(
1771 self.get(
1772 f"/v2/api/identities/{identity_id}/consents", query_params={"all": all}
1773 )
1774 )