Debian Codegraph @

src/globus_sdk/scopes/consents/_model.py

raw
1 """
2 This module provides convenience data structures to model and interact with
3 Globus Auth consents.
4
5 The resources defined herein are:
6 * ``Consent``
7 * A data object modeling a user's grant for a client to perform some scoped
8 operation on their behalf.
9 * This grant is conditional on the invocation path leading to the client's
10 attempted operation being initiated through a chain of similarly scoped
11 operations (consents) defined in the "dependency_path".
12 * ``ConsentTree``
13 * A tree composed of Consent nodes with edges modeling the dependency
14 relationships between them.
15 * A `meets_scope_requirements` method is defined to check whether a scope
16 requirement, including dependent scope requirements, is satisfied by the
17 tree.
18 * ``ConsentForest``
19 * A collection of all ConsentTrees for a user rooted under a particular client
20 (the client that initiated the request for consents).
21 * A `meets_scope_requirements` method is defined to check whether a scope
22 requirement, including dependent scope requirements, is satisfied by any
23 tree in the forest.
24 """
25
26 from __future__ import annotations
27
28 import textwrap
29 import typing as t
30 import uuid
31 from dataclasses import dataclass
32 from datetime import datetime
33
34 from ..parser import ScopeParser
35 from ..representation import Scope
36 from ._errors import ConsentParseError, ConsentTreeConstructionError
37
38
39 @dataclass
40 class Consent:
41 """
42 Consent Data Object
43
44 This object models:
45 * A grant which a user has provided for a client to perform a particular
46 scoped operation on their behalf.
47 * The consent is conditional on the invocation path leading to the client's
48 attempted operation being initiated through a chain of similarly scoped
49 operations (consents) defined in the "dependency_path".
50 """
51
52 client: uuid.UUID | str
53 scope: uuid.UUID | str
54 scope_name: str
55 id: int
56 effective_identity: uuid.UUID | str
57 # A list representing the path of consent dependencies leading from a "root consent"
58 # to this. The last element of this list will always be this consent's ID.
59 # Downstream dependency relationships may exist but will not be defined here.
60 dependency_path: list[int]
61 created: datetime
62 updated: datetime
63 last_used: datetime
64 status: str
65 allows_refresh: bool
66 auto_approved: bool
67 atomically_revocable: bool
68
69 @classmethod
70 def load(cls, data: t.Mapping[str, t.Any]) -> Consent:
71 """
72 Load a Consent object from a raw data dictionary.
73
74 :param data: A dictionary containing the raw consent data.
75 :raises: ConsentParseError if the data is missing a required key.
76 """
77 try:
78 return cls(
79 id=data["id"],
80 client=data["client"],
81 scope=data["scope"],
82 effective_identity=data["effective_identity"],
83 dependency_path=data["dependency_path"],
84 scope_name=data["scope_name"],
85 created=datetime.fromisoformat(data["created"]),
86 updated=datetime.fromisoformat(data["updated"]),
87 last_used=datetime.fromisoformat(data["last_used"]),
88 status=data["status"],
89 allows_refresh=data["allows_refresh"],
90 auto_approved=data["auto_approved"],
91 atomically_revocable=data["atomically_revocable"],
92 )
93 except KeyError as e:
94 raise ConsentParseError(
95 f"Failed to load Consent object. Missing required key: {e}.",
96 raw_consent=dict(data),
97 ) from e
98
99 def __str__(self) -> str:
100 client_id = str(self.client)
101 return f"Consent [{self.id}]: Client [{client_id}] -> Scope [{self.scope_name}]"
102
103
104 class ConsentForest:
105 """
106 A ConsentForest is a data structure which models relationships between Consents,
107 objects describing explicit access users have granted to particular clients.
108 It exists to expose a simple interface for evaluating whether resource server grant
109 requirements, as defined by a scope object are satisfied.
110
111 Consents should be retrieved from the AuthClient's ``get_consents`` method.
112
113 Example usage:
114
115 >>> auth_client = AuthClient(...)
116 >>> identity_id = ...
117 >>> forest = auth_client.get_consents(identity_id).to_forest()
118 >>>
119 >>> # Check whether the forest meets a scope requirement
120 >>> data_access_scope = GCSCollectionScopes(collection_id).data_access
121 >>> scope = TransferScopes.all.with_dependency(data_access_scope)
122 >>> forest.meets_scope_requirements(scope)
123
124
125 The following diagram demonstrates a Consent Forest in which a user has consented
126 to a client ("CLI") initiating transfers against two collections, both of which
127 require a "data_access" dynamic scope.
128 Contained Scope String:
129 `transfer:all[<collection1>:data_access <collection2>:data_access]`
130
131 .. code-block:: rst
132
133 [Consent A ] [Consent B ]
134 [Client: CLI ] -> [Client: Transfer ]
135 [Scope: transfer:all] [Scope: <collection1>:data_access]
136 |
137 | [Consent C ]
138 |--------------> [Client: Transfer ]
139 [Scope: <collection2>:data_access]
140 """
141
142 def __init__(self, consents: t.Iterable[t.Mapping[str, t.Any] | Consent]) -> None:
143 """
144 :param consents: An iterable of consent data objects. Typically, this will be
145 a ConsentForestResponse retrieved via `auth_client.get_consents(identity)`.
146 This iterable may contain either raw consent data as a dict or pre-loaded
147 Consents.
148 """
149 self.nodes = [
150 consent if isinstance(consent, Consent) else Consent.load(consent)
151 for consent in consents
152 ]
153 # Build an index on consent id for constant time lookups
154 self._node_by_id = {node.id: node for node in self.nodes}
155
156 self.edges = self._compute_edges()
157 self.trees = self._build_trees()
158
159 def __str__(self) -> str:
160 # indent 4 for inner elements, so that we can put their headings at 2 indent
161 trees = textwrap.indent("\n".join(str(t) for t in self.trees), " ")
162 nodes = textwrap.indent("\n".join(str(n) for n in self.nodes), " ")
163 return f"ConsentForest\n nodes\n{nodes}\n trees\n{trees}"
164
165 def _compute_edges(self) -> dict[int, set[int]]:
166 """
167 Compute the edges of the forest mapping parent -> child.
168
169 A consent's parent node id is defined as the penultimate element of the
170 consent's dependency path.
171 A consent with dependency list of length 1 is a root node (has no parent).
172 """
173 edges: dict[int, set[int]] = {node.id: set() for node in self.nodes}
174 for node in self.nodes:
175 if len(node.dependency_path) > 1:
176 parent_id = node.dependency_path[-2]
177 try:
178 edges[parent_id].add(node.id)
179 except KeyError as e:
180 raise ConsentTreeConstructionError(
181 f"Failed to compute forest edges. Missing parent node: {e}.",
182 consents=self.nodes,
183 ) from e
184 return edges
185
186 def _build_trees(self) -> list[ConsentTree]:
187 """
188 Build out the list of trees in the forest.
189
190 A distinct tree is built out for each "root nodes" (nodes with no parents).
191 """
192
193 # A node with dependency path length 1 has no parents, so it is a root.
194 roots = [node for node in self.nodes if len(node.dependency_path) == 1]
195 return [ConsentTree(root.id, self) for root in roots]
196
197 def get_node(self, consent_id: int) -> Consent:
198 return self._node_by_id[consent_id]
199
200 def meets_scope_requirements(
201 self, scopes: Scope | str | t.Sequence[Scope | str]
202 ) -> bool:
203 """
204 Check whether this consent meets one or more scope requirements.
205
206 A consent forest meets a particular scope requirement if any consent tree
207 inside the forest meets the scope requirements.
208
209 :param scopes: A single scope, a list of scopes, or a scope string to check
210 against the forest.
211 :returns: True if all scope requirements are met, False otherwise.
212 """
213 for scope in _normalize_scope_types(scopes):
214 if not any(tree.meets_scope_requirements(scope) for tree in self.trees):
215 return False
216 return True
217
218
219 class ConsentTree:
220 """
221 A tree of Consent nodes with edges modeling the dependency relationships between
222 them.
223
224 :raises: ConsentParseError if the tree cannot be constructed due to missing
225 consent dependencies.
226 """
227
228 def __init__(self, root_id: int, forest: ConsentForest) -> None:
229 self.root = forest.get_node(root_id)
230 self.nodes = [self.root]
231 self._node_by_id = {root_id: self.root}
232 self.edges: dict[int, set[int]] = {}
233
234 self._populate_connected_nodes_and_edges(forest)
235
236 def _populate_connected_nodes_and_edges(self, forest: ConsentForest) -> None:
237 """
238 Populate the nodes and edges of the tree by traversing the forest.
239
240 Nodes/Edges are included in the tree iff they are reachable from the root.
241 """
242 nodes_to_evaluate = {self.root.id}
243 while nodes_to_evaluate:
244 consent_id = nodes_to_evaluate.pop()
245 consent = forest.get_node(consent_id)
246 self.edges[consent.id] = forest.edges[consent.id]
247
248 for child_id in self.edges[consent.id]:
249 if child_id not in self._node_by_id:
250 self.nodes.append(forest.get_node(child_id))
251 self._node_by_id[child_id] = forest.get_node(child_id)
252 nodes_to_evaluate.add(child_id)
253
254 def get_node(self, consent_id: int) -> Consent:
255 return self._node_by_id[consent_id]
256
257 def meets_scope_requirements(self, scope: Scope) -> bool:
258 """
259 Check whether this consent tree meets a particular scope requirement.
260
261 :param scope: A Scope requirement to check against the tree.
262 """
263 return self._meets_scope_requirements_recursive(self.root, scope)
264
265 def _meets_scope_requirements_recursive(self, node: Consent, scope: Scope) -> bool:
266 """
267 Check recursively whether a consent node meets the scope requirements defined
268 by a scope object.
269 """
270 if node.scope_name != scope.scope_string:
271 return False
272
273 for dependent_scope in scope.dependencies:
274 for child_id in self.edges[node.id]:
275 if self._meets_scope_requirements_recursive(
276 self.get_node(child_id), dependent_scope
277 ):
278 # We found a child containing this full dependent scope tree
279 # Move onto the next dependent scope tree
280 break
281 else:
282 # We didn't find any child containing this full dependent scope tree
283 return False
284 # We found at least one child containing each full dependent scope tree
285 return True
286
287 @property
288 def max_depth(self) -> int:
289 return self._max_depth_recursive(self.root, 1)
290
291 def _max_depth_recursive(self, node: Consent, depth: int) -> int:
292 if len(self.edges[node.id]) == 0:
293 return depth
294 return max(
295 self._max_depth_recursive(self.get_node(child_id), depth + 1)
296 for child_id in self.edges[node.id]
297 )
298
299 def __str__(self) -> str:
300 """Returns a textual representation of the tree to stdout (one line per node)"""
301 return self._str_recursive(self.root, 0)
302
303 def _str_recursive(self, node: Consent, tab_depth: int) -> str:
304 _str = f"{' ' * tab_depth} - {node}"
305 for child_id in self.edges[node.id]:
306 _str += "\n" + self._str_recursive(self.get_node(child_id), tab_depth + 2)
307 return _str
308
309
310 def _normalize_scope_types(
311 scopes: Scope | str | t.Sequence[Scope | str],
312 ) -> list[Scope]:
313 """
314 Normalize the input scope types into a list of Scope objects.
315
316 Strings are parsed into 1 or more Scopes using `ScopeParser.parse`.
317
318 :param scopes: Some collection of 0 or more scopes as Scope or scope strings.
319 :returns: A list of Scope objects.
320 """
321
322 if isinstance(scopes, Scope):
323 return [scopes]
324 elif isinstance(scopes, str):
325 return ScopeParser.parse(scopes)
326 else:
327 scope_list = []
328 for scope in scopes:
329 if isinstance(scope, str):
330 scope_list.extend(ScopeParser.parse(scope))
331 else:
332 scope_list.append(scope)
333 return scope_list