Debian Codegraph @

src/globus_sdk/services/auth/identity_map.py

raw
1 from __future__ import annotations
2
3 import typing as t
4 import uuid
5
6 from .client import AuthClient
7
8
9 def is_username(val: str) -> bool:
10 # If the value parses as a UUID, then it's an ID, not a username.
11 # If it does not parse as such, then it must be a username.
12 try:
13 uuid.UUID(val)
14 return False
15 except ValueError:
16 return True
17
18
19 def split_ids_and_usernames(
20 identity_ids: t.Iterable[str],
21 ) -> tuple[set[str], set[str]]:
22 ids = set()
23 usernames = set()
24
25 for val in identity_ids:
26 if is_username(val):
27 usernames.add(val)
28 else:
29 ids.add(val)
30
31 return ids, usernames
32
33
34 class IdentityMap:
35 r"""
36 There's a common pattern of having a large batch of Globus Auth Identities which you
37 want to inspect. For example, you may have a list of identity IDs fetched from
38 Access Control Lists on Globus Endpoints. In order to display these identities to an
39 end user, you may want to resolve them to usernames.
40
41 However, naively looking up the identities one-by-one is very inefficient. It's best
42 to do batched lookups with multiple identities at once. In these cases, an
43 ``IdentityMap`` can be used to do those batched lookups for you.
44
45 An ``IdentityMap`` is a mapping-like type which converts Identity IDs and Identity
46 Names to Identity records (dictionaries) using the Globus Auth API.
47
48 .. note::
49
50 ``IdentityMap`` objects are not full Mappings in the same sense as python dicts
51 and similar objects. By design, they only implement a small part of the Mapping
52 protocol.
53
54 The basic usage pattern is
55
56 - create an ``IdentityMap`` with an AuthClient which will be used to call out to
57 Globus Auth
58
59 - seed the ``IdentityMap`` with IDs and Usernames via :py:meth:`~IdentityMap.add` (you
60 can also do this during initialization)
61
62 - retrieve identity IDs or Usernames from the map
63
64 Because the map can be populated with a collection of identity IDs and Usernames
65 prior to lookups being performed, it can improve the efficiency of these operations
66 up to 100x over individual lookups.
67
68 If you attempt to retrieve an identity which has not been previously added to the
69 map, it will be immediately added. But adding many identities beforehand will
70 improve performance.
71
72 The ``IdentityMap`` will cache its results so that repeated lookups of the same Identity
73 will not repeat work. It will also map identities both by ID and by Username,
74 regardless of how they're initially looked up.
75
76 .. warning::
77
78 If an Identity is not found in Globus Auth, it will trigger a KeyError when
79 looked up. Your code must be ready to handle KeyErrors when doing a lookup.
80
81 Correct usage looks something like so::
82
83 ac = globus_sdk.AuthClient(...)
84 idmap = globus_sdk.IdentityMap(
85 ac, ["[email protected]", "[email protected]"]
86 )
87 idmap.add("[email protected]")
88 # adding by ID is also valid
89 idmap.add("c699d42e-d274-11e5-bf75-1fc5bf53bb24")
90 # map ID to username
91 assert (
92 idmap["c699d42e-d274-11e5-bf75-1fc5bf53bb24"]["username"]
93 == "[email protected]"
94 )
95 # map username to ID
96 assert (
97 idmap["[email protected]"]["id"]
98 == "c699d42e-d274-11e5-bf75-1fc5bf53bb24"
99 )
100
101 And simple handling of errors::
102
103 try:
104 record = idmap["[email protected]"]
105 except KeyError:
106 username = "NO_SUCH_IDENTITY"
107 else:
108 username = record["username"]
109
110 or you may achieve this by using the :py:meth:`~.IdentityMap.get` method::
111
112 # internally handles the KeyError and returns the default value
113 record = idmap.get("[email protected]", None)
114 username = record["username"] if record is not None else "NO_SUCH_IDENTITY"
115
116 :param auth_client: The client object which will be used for lookups against Globus Auth
117 :param identity_ids: A list or other iterable of usernames or identity IDs (potentially
118 mixed together) which will be used to seed the ``IdentityMap`` 's tracking of
119 unresolved Identities.
120 :param id_batch_size: A non-default batch size to use when communicating with Globus
121 Auth. Leaving this set to the default is strongly recommended.
122 :param cache: A dict or other mapping object which will be used to cache results.
123 The default is that results are cached once per IdentityMap object. If you want
124 multiple IdentityMaps to share data, explicitly pass the same ``cache`` to both.
125
126 .. automethodlist:: globus_sdk.IdentityMap
127 :include_methods: __getitem__,__delitem__
128 """ # noqa
129
130 _default_id_batch_size = 100
131
132 def __init__(
133 self,
134 auth_client: AuthClient,
135 identity_ids: t.Iterable[str] | None = None,
136 *,
137 id_batch_size: int | None = None,
138 cache: None | t.MutableMapping[str, dict[str, t.Any]] = None,
139 ) -> None:
140 self.auth_client = auth_client
141 self.id_batch_size = id_batch_size or self._default_id_batch_size
142
143 # uniquify, copy, and split into IDs vs usernames
144 self.unresolved_ids, self.unresolved_usernames = split_ids_and_usernames(
145 [] if identity_ids is None else identity_ids
146 )
147
148 # a cache may be passed in via the constructor in order to make multiple
149 # IdentityMap objects share a cache
150 self._cache = cache if cache is not None else {}
151
152 def _create_batch(self, key: str) -> set[str]:
153 """
154 Create a batch to do a lookup.
155
156 For whichever set of unresolved names is appropriate, build the batch to
157 lookup up to *at most* the batch size. Also, remove the unresolved names from
158 tracking so that they will not be looked up again.
159 """
160 key_is_username = is_username(key)
161 set_to_use = (
162 self.unresolved_usernames if key_is_username else self.unresolved_ids
163 )
164
165 # start the batch with the key being looked up, and if it is in the unresolved
166 # list remove it
167 batch = {key}
168 if key in set_to_use:
169 set_to_use.remove(key)
170
171 # until we've exhausted the set or filled the batch, keep trying to add
172 while set_to_use and len(batch) < self.id_batch_size:
173 value = set_to_use.pop()
174
175 # value may already have been looked up if the cache is shared, skip those
176 if value in self._cache:
177 continue
178
179 batch.add(value)
180
181 return batch
182
183 def _fetch_batch_including(self, key: str) -> None:
184 """
185 Batch resolve identifiers (usernames or IDs), being sure to include the desired,
186 named key. The key also determines which kind of batch will be built --
187 usernames or IDs.
188
189 Store the results in the internal cache.
190 """
191 batch = self._create_batch(key)
192
193 if is_username(key):
194 response = self.auth_client.get_identities(usernames=batch)
195 else:
196 response = self.auth_client.get_identities(ids=batch)
197
198 for x in response["identities"]:
199 self._cache[x["id"]] = x
200 self._cache[x["username"]] = x
201
202 def add(self, identity_id: str) -> bool:
203 """
204 Add a username or ID to the ``IdentityMap`` for batch lookups later.
205
206 Returns True if the ID was added for lookup.
207 Returns False if it was rejected as a duplicate of an already known name.
208
209 :param identity_id: A string Identity ID or Identity Name (a.k.a. "username") to
210 add
211 """
212 if identity_id in self._cache:
213 return False
214 if is_username(identity_id):
215 if identity_id in self.unresolved_usernames:
216 return False
217 else:
218 self.unresolved_usernames.add(identity_id)
219 return True
220 if identity_id in self.unresolved_ids:
221 return False
222 self.unresolved_ids.add(identity_id)
223 return True
224
225 def get(self, key: str, default: t.Any | None = None) -> t.Any:
226 """
227 A dict-like get() method which accepts a default value.
228
229 :param key: The username or ID to look up
230 :param default: The default value to return if the key is not found
231 """
232 try:
233 return self[key]
234 except KeyError:
235 return default
236
237 def __getitem__(self, key: str) -> t.Any:
238 """
239 ``IdentityMap`` supports dict-like lookups with ``map[key]``
240 """
241 if key not in self._cache:
242 self._fetch_batch_including(key)
243 return self._cache[key]
244
245 def __delitem__(self, key: str) -> None:
246 """
247 ``IdentityMap`` supports ``del map[key]``. Note that this only removes lookup
248 values from the cache and will not impact the set of unresolved/pending IDs.
249 """
250 del self._cache[key]