Debian Codegraph @

src/globus_sdk/token_storage/validating_token_storage/validators.py

raw
1 from __future__ import annotations
2
3 import abc
4 import time
5 import typing as t
6
7 import globus_sdk
8 from globus_sdk.scopes.consents import ConsentForest
9
10 from ..token_data import TokenStorageData
11 from .context import TokenValidationContext
12 from .errors import (
13 ExpiredTokenError,
14 IdentityMismatchError,
15 MissingIdentityError,
16 MissingTokenError,
17 UnmetScopeRequirementsError,
18 )
19
20
21 class TokenDataValidator(abc.ABC):
22 """
23 The abstract base class for custom token validation logic.
24
25 Implementations should raise a :class:`TokenValidationError` if a validation error
26 is encountered.
27 """
28
29 @abc.abstractmethod
30 def before_store(
31 self,
32 token_data_by_resource_server: t.Mapping[str, TokenStorageData],
33 context: TokenValidationContext,
34 ) -> None:
35 """
36 Validate token data against this validator's constraints before it is
37 written to token storage.
38
39 :param token_data_by_resource_server: The data to validate.
40 :param context: The validation context object, containing state of the system at
41 the time of validation.
42
43 :raises TokenValidationError: On failure.
44 """
45
46 @abc.abstractmethod
47 def after_retrieve(
48 self,
49 token_data_by_resource_server: t.Mapping[str, TokenStorageData],
50 context: TokenValidationContext,
51 ) -> None:
52 """
53 Validate token data against this validator's constraints after it is
54 retrieved from token storage.
55
56 :param token_data_by_resource_server: The data to validate.
57 :param context: The validation context object, containing state of the system at
58 the time of validation.
59
60 :raises TokenValidationError: On failure.
61 """
62
63
64 class _OnlyBeforeValidator(TokenDataValidator, abc.ABC):
65 def after_retrieve(
66 self,
67 token_data_by_resource_server: t.Mapping[str, TokenStorageData],
68 context: TokenValidationContext,
69 ) -> None:
70 return None
71
72
73 class _OnlyAfterValidator(TokenDataValidator, abc.ABC):
74 def before_store(
75 self,
76 token_data_by_resource_server: t.Mapping[str, TokenStorageData],
77 context: TokenValidationContext,
78 ) -> None:
79 return None
80
81
82 class HasRefreshTokensValidator(_OnlyAfterValidator):
83 """
84 A validator to validate that token data contains refresh tokens.
85
86 * This validator only runs `after_retrieve`.
87
88 :raises MissingTokenError: If any token data does not contain a refresh token.
89 """
90
91 def after_retrieve(
92 self,
93 token_data_by_resource_server: t.Mapping[str, TokenStorageData],
94 context: TokenValidationContext, # pylint: disable=unused-argument
95 ) -> None:
96 for token_data in token_data_by_resource_server.values():
97 if token_data.refresh_token is None:
98 msg = f"No refresh_token for {token_data.resource_server}"
99 raise MissingTokenError(msg, resource_server=token_data.resource_server)
100
101
102 class NotExpiredValidator(_OnlyAfterValidator):
103 """
104 A validator to validate that token data has not expired.
105
106 * This validator only runs `after_retrieve`.
107
108 :raises ExpiredTokenError: If any token data shows has expired.
109 """
110
111 def after_retrieve(
112 self,
113 token_data_by_resource_server: t.Mapping[str, TokenStorageData],
114 context: TokenValidationContext, # pylint: disable=unused-argument
115 ) -> None:
116 for token_data in token_data_by_resource_server.values():
117 if token_data.expires_at_seconds < time.time():
118 raise ExpiredTokenError(token_data.expires_at_seconds)
119
120
121 class UnchangingIdentityIDValidator(_OnlyBeforeValidator):
122 """
123 A validator to validate that user identity does not change across token grants.
124
125 * This validator only runs `before_store`.
126
127 :raises IdentityMismatchError: If identity info changes across token storage
128 operations.
129 :raises MissingIdentityError: If the token data did not have any identity
130 information.
131 """
132
133 def before_store(
134 self,
135 token_data_by_resource_server: t.Mapping[ # pylint: disable=unused-argument
136 str, TokenStorageData
137 ],
138 context: TokenValidationContext,
139 ) -> None:
140 if context.token_data_identity_id is None:
141 raise MissingIdentityError(
142 "Token grant response doesn't contain an id_token. This normally "
143 "occurs if the auth flow didn't include 'openid' alongside other "
144 "scopes."
145 )
146
147 # no prior ID means we cannot validate the content further
148 if context.prior_identity_id is None:
149 return
150
151 if context.token_data_identity_id != context.prior_identity_id:
152 raise IdentityMismatchError(
153 "Detected a change in identity associated with the token data.",
154 stored_id=context.prior_identity_id,
155 new_id=context.token_data_identity_id,
156 )
157
158
159 class ScopeRequirementsValidator(TokenDataValidator):
160 """
161 A validator to validate that token data meets scope requirements.
162
163 A scope requirement, i.e., "transfer:all[collection:data_access]", can be broken
164 into two parts: the **root scope**, "transfer:all", and one or more
165 **dependent scopes**, "collection:data_access".
166
167 * On `before_store`, this validator only evaluates **root** scope requirements.
168 * On `after_retrieve`, this validator evaluates both **root** and **dependent**
169 scope requirements.
170
171 .. note::
172
173 Dependent scopes are only evaluated if an identity ID is extractable from
174 token grants. If no identity ID is available, dependent scope evaluation
175 is silently skipped.
176
177 :param scope_requirements: A mapping of resource servers to required scopes.
178 :param consent_client: An AuthClient to fetch consents with. This auth client must
179 have (or have access to) any valid Globus Auth scoped token.
180
181 :raises UnmetScopeRequirementsError: If any scope requirements are not met.
182 """
183
184 def __init__(
185 self,
186 scope_requirements: t.Mapping[str, t.Sequence[globus_sdk.Scope]],
187 consent_client: globus_sdk.AuthClient,
188 ) -> None:
189 self.scope_requirements = scope_requirements
190 self.consent_client: globus_sdk.AuthClient = consent_client
191 self._cached_consent_forest: ConsentForest | None = None
192
193 def before_store(
194 self,
195 token_data_by_resource_server: t.Mapping[str, TokenStorageData],
196 context: TokenValidationContext,
197 ) -> None:
198 identity_id = context.token_data_identity_id or context.prior_identity_id
199 for resource_server, token_data in token_data_by_resource_server.items():
200 self._validate_token_data_meets_scope_requirements(
201 resource_server=resource_server,
202 token_data=token_data,
203 identity_id=identity_id,
204 eval_dependent=False,
205 )
206
207 def after_retrieve(
208 self,
209 token_data_by_resource_server: t.Mapping[str, TokenStorageData],
210 context: TokenValidationContext,
211 ) -> None:
212 identity_id = context.token_data_identity_id or context.prior_identity_id
213 for token_data in token_data_by_resource_server.values():
214 self._validate_token_data_meets_scope_requirements(
215 resource_server=token_data.resource_server,
216 token_data=token_data,
217 identity_id=identity_id,
218 )
219
220 def _validate_token_data_meets_scope_requirements(
221 self,
222 *,
223 resource_server: str,
224 token_data: TokenStorageData,
225 identity_id: str | None,
226 eval_dependent: bool = True,
227 ) -> None:
228 """
229 Evaluate whether the scope requirements for a given resource server are met.
230
231 :param resource_server: A resource server to access scope requirements.
232 :param token_data: A token data object to validate.
233 :param identity_id: The identity ID of the user, from the surrounding context.
234 :param eval_dependent: Whether to evaluate dependent scope requirements.
235
236 :raises UnmetScopeRequirements: If token/consent data does not meet the
237 attached root or dependent scope requirements for the resource server.
238 """
239 required_scopes = self.scope_requirements.get(resource_server)
240 # Short circuit - No scope requirements are, by definition, met.
241 if required_scopes is None:
242 return
243
244 # 1. Does the token meet root scope requirements?
245 root_scopes = token_data.scope.split()
246 if not all(scope.scope_string in root_scopes for scope in required_scopes):
247 raise UnmetScopeRequirementsError(
248 "Unmet scope requirements",
249 scope_requirements={
250 k: list(v) for k, v in self.scope_requirements.items()
251 },
252 )
253
254 # Short circuit - No dependent scopes; don't validate them.
255 if not eval_dependent or not any(
256 scope.dependencies for scope in required_scopes
257 ):
258 return
259
260 # 2. Does the consent forest meet all dependent scope requirements?
261 # 2a. Try with the cached consent forest first.
262 forest = self._cached_consent_forest
263 if forest is not None and forest.meets_scope_requirements(required_scopes):
264 return
265
266 # Identity id is required to fetch consents.
267 # if we cannot fetch consents, we cannot do any further validation
268 if identity_id is None:
269 return
270
271 # 2b. Poll for fresh consents and try again.
272 forest = self._poll_and_cache_consents(identity_id)
273 if not forest.meets_scope_requirements(required_scopes):
274 raise UnmetScopeRequirementsError(
275 "Unmet dependent scope requirements",
276 scope_requirements={
277 k: list(v) for k, v in self.scope_requirements.items()
278 },
279 )
280
281 def _poll_and_cache_consents(self, identity_id: str) -> ConsentForest:
282 forest = self.consent_client.get_consents(identity_id).to_forest()
283 self._cached_consent_forest = forest
284 return forest