pycrossauth 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. crossauth_backend/__init__.py +59 -0
  2. crossauth_backend/auth.py +132 -0
  3. crossauth_backend/common/__init__.py +2 -0
  4. crossauth_backend/common/error.py +498 -0
  5. crossauth_backend/common/interfaces.py +287 -0
  6. crossauth_backend/common/jwt.py +41 -0
  7. crossauth_backend/common/logger.py +202 -0
  8. crossauth_backend/cookieauth.py +575 -0
  9. crossauth_backend/crypto.py +457 -0
  10. crossauth_backend/oauth/__init__.py +2 -0
  11. crossauth_backend/oauth/client.py +1063 -0
  12. crossauth_backend/oauth/clientmanager.py +157 -0
  13. crossauth_backend/oauth/resserver.py +34 -0
  14. crossauth_backend/oauth/tokenconsumer.py +412 -0
  15. crossauth_backend/oauth/wellknown.py +108 -0
  16. crossauth_backend/session.py +450 -0
  17. crossauth_backend/storage.py +626 -0
  18. crossauth_backend/storageimpl/__init__.py +2 -0
  19. crossauth_backend/storageimpl/inmemorystorage.py +132 -0
  20. crossauth_backend/storageimpl/sqlalchemystorage.py +294 -0
  21. crossauth_backend/utils.py +150 -0
  22. crossauth_fastapi/__init__.py +23 -0
  23. crossauth_fastapi/fastapioauthclient.py +2185 -0
  24. crossauth_fastapi/fastapiresserver.py +300 -0
  25. crossauth_fastapi/fastapiserver.py +437 -0
  26. crossauth_fastapi/fastapiserverbase.py +62 -0
  27. crossauth_fastapi/fastapisession.py +654 -0
  28. crossauth_fastapi/fastapisessionadapter.py +94 -0
  29. pycrossauth-0.0.2.dist-info/LICENSE +203 -0
  30. pycrossauth-0.0.2.dist-info/METADATA +257 -0
  31. pycrossauth-0.0.2.dist-info/NOTICE +5 -0
  32. pycrossauth-0.0.2.dist-info/RECORD +34 -0
  33. pycrossauth-0.0.2.dist-info/WHEEL +5 -0
  34. pycrossauth-0.0.2.dist-info/top_level.txt +2 -0
@@ -0,0 +1,1063 @@
1
+ # Copyright (c) 2024 Matthew Baker. All rights reserved. Licenced under the Apache Licence 2.0. See LICENSE file
2
+ from crossauth_backend.common.error import CrossauthError, ErrorCode
3
+ from crossauth_backend.utils import set_parameter, ParamType, MapGetter
4
+ from crossauth_backend.common.logger import CrossauthLogger, j
5
+ from crossauth_backend.oauth.wellknown import OpenIdConfiguration, TokenBodyType
6
+ from crossauth_backend.oauth.tokenconsumer import OAuthTokenConsumer, OAuthTokenConsumerOptions
7
+ from crossauth_backend.crypto import Crypto
8
+
9
+ from typing import Dict, List, Optional, TypedDict, Any, Literal, Mapping, cast
10
+ import json
11
+ import urllib.parse
12
+ from abc import abstractmethod
13
+ import requests
14
+ from urllib.parse import urlparse
15
+ from jwt import (
16
+ JWT
17
+ )
18
+ import aiohttp
19
+
20
+ class OAuthFlows:
21
+ """
22
+ Crossauth allows you to define which flows are valid for a given client.
23
+ """
24
+
25
+ All = "all"
26
+ """ All flows are allowed """
27
+
28
+ AuthorizationCode = "authorizationCode"
29
+ """ OAuth authorization code flow (without PKCE) """
30
+
31
+ AuthorizationCodeWithPKCE = "authorizationCodeWithPKCE"
32
+ """ OAuth authorization code flow with PKCE """
33
+
34
+ ClientCredentials = "clientCredentials"
35
+ """ Auth client credentials flow """
36
+
37
+ RefreshToken = "refresh_token"
38
+ """ OAuth refresh token flow """
39
+
40
+ DeviceCode = "device_code"
41
+ """ OAuth device code flow """
42
+
43
+ Password = "password"
44
+ """ OAuth password flow """
45
+
46
+ PasswordMfa = "passwordMfa"
47
+ """ The Auth0 password MFA extension to the password flow """
48
+
49
+ OidcAuthorizationCode = "oidcAuthorizationCode"
50
+ """ The OpenID Connect authorization code flow, with or without PKCE """
51
+
52
+ flow_name = {
53
+ AuthorizationCode: "Authorization Code",
54
+ AuthorizationCodeWithPKCE: "Authorization Code with PKCE",
55
+ ClientCredentials: "Client Credentials",
56
+ RefreshToken: "Refresh Token",
57
+ DeviceCode: "Device Code",
58
+ Password: "Password",
59
+ PasswordMfa: "Password MFA",
60
+ OidcAuthorizationCode: "OIDC Authorization Code",
61
+ }
62
+ """ A user friendly name for the given flow ID """
63
+
64
+ @staticmethod
65
+ def flow_names(flows: List[str]) -> Dict[str, str]:
66
+ """
67
+ Returns a user-friendly name for the given flow strs.
68
+
69
+ The value returned is the one in `flow_name`.
70
+ :param List[str] flows: the flows to return the names of
71
+
72
+ :return: a dictionary of strs
73
+ """
74
+
75
+ return {flow: OAuthFlows.flow_name[flow] for flow in flows if flow in OAuthFlows.flow_name}
76
+
77
+ @staticmethod
78
+ def is_valid_flow(flow: str) -> bool:
79
+ """
80
+ Returns true if the given str is a valid flow name.
81
+ :param str flow: the flow to check
82
+
83
+ :return: true or false.
84
+ """
85
+
86
+ return flow in OAuthFlows.all_flows()
87
+
88
+ @staticmethod
89
+ def are_valid_flows(flows: List[str]) -> bool:
90
+ """
91
+ Returns true only if all given strs are valid flows
92
+ :param List[str] flows: the flows to check
93
+
94
+ :return: true or false.
95
+ """
96
+
97
+ return all(OAuthFlows.is_valid_flow(flow) for flow in flows)
98
+
99
+ @staticmethod
100
+ def all_flows() -> List[str]:
101
+ """ Returns a lsit of all possible OAuth flows """
102
+
103
+ return [
104
+ OAuthFlows.AuthorizationCode,
105
+ OAuthFlows.AuthorizationCodeWithPKCE,
106
+ OAuthFlows.ClientCredentials,
107
+ OAuthFlows.RefreshToken,
108
+ OAuthFlows.DeviceCode,
109
+ OAuthFlows.Password,
110
+ OAuthFlows.PasswordMfa,
111
+ OAuthFlows.OidcAuthorizationCode,
112
+ ]
113
+
114
+ @staticmethod
115
+ def grant_type(oauthFlow: str) -> Optional[List[str]]:
116
+ """
117
+ Returns the OAuth grant types that are valid for a given flow, or
118
+ `None` if it is not a valid flow.
119
+ :param str oauthFlow: the flow to get the grant type for.
120
+
121
+ :return: a list of grant type strs or None
122
+ """
123
+
124
+ match oauthFlow:
125
+ case OAuthFlows.AuthorizationCode:
126
+ return ["authorization_code"]
127
+ case OAuthFlows.AuthorizationCodeWithPKCE:
128
+ return ["authorization_code"]
129
+ case OAuthFlows.OidcAuthorizationCode:
130
+ return ["authorization_code"]
131
+ case OAuthFlows.ClientCredentials:
132
+ return ["client_credentials"]
133
+ case OAuthFlows.RefreshToken:
134
+ return ["refresh_token"]
135
+ case OAuthFlows.Password:
136
+ return ["password"]
137
+ case OAuthFlows.PasswordMfa:
138
+ return ["http://auth0.com/oauth/grant-type/mfa-otp", "http://auth0.com/oauth/grant-type/mfa-oob"]
139
+ case OAuthFlows.DeviceCode:
140
+ return ["urn:ietf:params:oauth:grant-type:device_code"]
141
+ case _:
142
+ raise CrossauthError(ErrorCode.BadRequest, "Invalid OAuth flow " + oauthFlow)
143
+
144
+ class OAuthTokenResponse(TypedDict, total=False):
145
+ """
146
+ These are the fields that can be returned in the JSON from an OAuth call.
147
+ """
148
+
149
+ access_token : str
150
+ refresh_token : str
151
+ id_token : str
152
+ token_type : str
153
+ expires_in : int
154
+ error : str
155
+ error_description : str
156
+ scope : str
157
+ mfa_token : str
158
+ oob_channel : str
159
+ oob_code : str
160
+ challenge_type : str
161
+ binding_method : str
162
+ name : str
163
+
164
+ class OAuthMfaAuthenticator(TypedDict, total=False):
165
+ authenticator_type: str
166
+ id : str
167
+ active: bool
168
+ oob_channel : str
169
+ name: str
170
+ error: str
171
+ error_description: str
172
+
173
+ class OAuthMfaAuthenticatorsResponse(TypedDict, total=False):
174
+ authenticators: List[OAuthMfaAuthenticator]
175
+ error : str
176
+ error_description: str
177
+
178
+ class OAuthMfaAuthenticatorsOrTokenResponse(OAuthMfaAuthenticatorsResponse, OAuthTokenResponse, total=False):
179
+ pass
180
+
181
+ class OAuthMfaChallengeResponse(TypedDict, total=False):
182
+ challenge_type: str
183
+ oob_code: str
184
+ binding_method: str
185
+ error : str
186
+ error_description: str
187
+
188
+ class OAuthDeviceAuthorizationResponse(TypedDict, total=False):
189
+ """
190
+ These are the fields that can be returned in the device_authorization
191
+ device code flow endpoint.
192
+ """
193
+
194
+ device_code : str
195
+ user_code : str
196
+ verification_uri : str
197
+ verification_uri_complete : str
198
+ expires_in : str
199
+ interval : str
200
+ error : str
201
+ error_description : str
202
+
203
+ class OAuthDeviceResponse(TypedDict, total=False):
204
+ """
205
+ These are the fields that can be returned in the device
206
+ device code flow endpoint.
207
+ """
208
+
209
+ client_id : str
210
+ scope_authorization_needed : bool
211
+ scope : str
212
+ error : str
213
+ error_description : str
214
+
215
+ class OAuthClientOptions(OAuthTokenConsumerOptions, total=False):
216
+ """ Options for :class: OAuthClientBase """
217
+
218
+ state_length : int
219
+ """ Length of random state variable for passing to `authorize` endpoint
220
+ (before bsae64-url-encoding)
221
+ """
222
+
223
+ verifier_length : int
224
+ """ Length of random code verifier to generate
225
+ (before bsae64-url-encoding)
226
+ """
227
+
228
+ client_id : str
229
+ """
230
+ Client ID for this client
231
+ """
232
+
233
+ client_secret : str
234
+ """
235
+ Client secret for this client (can be undefined for no secret)
236
+ """
237
+
238
+ redirect_uri : str
239
+ """
240
+ Redirect URI to send in `authorize` requests
241
+ """
242
+
243
+ code_challenge_method : Literal["plain", "S256"]
244
+ """
245
+ Type of code challenge for PKCE
246
+ """
247
+
248
+ device_authorization_url : str
249
+ """
250
+ URL to call for the device_authorization endpoint, relative to
251
+ the `auth_server_base_url`.
252
+
253
+ Default `device_authorization`
254
+ """
255
+
256
+ class OAuthClient:
257
+ """
258
+ Base class for OAuth clients.
259
+
260
+ Flows supported are Authorization Code Flow with and without PKCE,
261
+ Client Credentials, Refresh Token, Password and Password MFA. The
262
+ latter is defined at
263
+ [auth0.com](https://auth0.com/docs/secure/multi-factor-authentication/multi-factor-authentication-factors).
264
+
265
+ It also supports the OpenID Connect Authorization Code Flow, with and
266
+ without PKCE.
267
+ """
268
+
269
+ def __init__(self, auth_server_base_url : str, options : OAuthClientOptions):
270
+ """
271
+ Constructor.
272
+
273
+ Args:
274
+ :param str auth_server_base_url: bsae URL for the authorization server
275
+ expected to issue access tokens. If the `iss` field in a JWT
276
+ does not match this, it is rejected.
277
+ :param crossauth_backend.OAuthClientOptions options: see :class: OAuthClientOptions
278
+
279
+ """
280
+
281
+ self._verifier_length = 32
282
+ self._state_length = 32
283
+ self._client_id : str = ""
284
+ self._client_secret : str|None = None
285
+ self._redirect_uri : str|None = None
286
+ self._code_challenge_method : Literal["plain", "S256"] = "S256"
287
+ self._auth_server_credentials : Literal["include", "omit", "same-origin" ] | None = None
288
+ self._auth_server_mode : Literal["no-cors", "cors", "same-origin" ] | None = None
289
+ self._auth_server_headers : Dict[str, str] = {}
290
+ self._code_challenge : str|None = None
291
+ self._code_verifier : str|None = None
292
+ self._state = ""
293
+ self._authz_code = ""
294
+ self._oidc_config : OpenIdConfiguration | None = None
295
+ self._device_authorization_url : str = "device_authorization"
296
+
297
+ self.auth_server_base_url = auth_server_base_url
298
+ set_parameter("client_id", ParamType.String, self, options, "OAUTH_CLIENT_ID", required=True, protected=True)
299
+ set_parameter("client_secret", ParamType.String, self, options, "OAUTH_CLIENT_SECRET", protected=True)
300
+ set_parameter("redirect_uri", ParamType.String, self, options, "OAUTH_REDIRECT_URI", protected=True)
301
+
302
+ self._token_consumer = OAuthTokenConsumer(self._client_id, {"auth_server_base_url": auth_server_base_url, **options})
303
+ set_parameter("state_length", ParamType.String, self, options, "OAUTH_STATE_LENGTH", protected=True)
304
+ set_parameter("verifier_length", ParamType.String, self, options, "OAUTH_VERIFIER_LENGTH", protected=True)
305
+ set_parameter("client_secret", ParamType.String, self, options, "OAUTH_CLIENT_SECRET", protected=True)
306
+ set_parameter("code_challenge_method", ParamType.String, self, options, "OAUTH_CODE_CHALLENGE_METHOD", protected=True)
307
+ set_parameter("device_authorization_url", ParamType.String, self, options, "OAUTH_DEVICE_AUTHORIZATION_URL", protected=True)
308
+ set_parameter("auth_server_credentials", ParamType.String, self, options, "OAUTH_AUTH_SERVER_CREDENTIALS", protected=True)
309
+ set_parameter("auth_server_mode", ParamType.String, self, options, "OAUTH_AUTH_SERVER_MODE", protected=True)
310
+ set_parameter("auth_server_headers", ParamType.Json, self, options, "OAUTH_AUTH_SERVER_HEADERS", protected=True)
311
+ if (self._device_authorization_url[0:1] == "/"): self._device_authorization_url = self._device_authorization_url[1:]
312
+
313
+ async def load_config(self, oidc_config : OpenIdConfiguration|None=None):
314
+ """
315
+ Loads OpenID Connect configuration so that the client can determine
316
+ the URLs it can call and the features the authorization server provides.
317
+
318
+ :param oidc_config if defined, loadsa the config from this object.
319
+ Otherwise, performs a fetch by appending
320
+ `/.well-known/openid-configuration` to the
321
+ `auth_server_base_url`.
322
+ :throws :class: crossauth_backend.CrossauthError} with the following
323
+ :attr: crossauth_backend.ErrorCode.Connection if data from the URL
324
+ could not be fetched or parsed.
325
+ """
326
+
327
+ if oidc_config:
328
+ CrossauthLogger.logger().debug(j({"msg": "Reading OIDC config locally"}))
329
+ self._oidc_config = oidc_config
330
+ return
331
+
332
+ url = f"{self.auth_server_base_url}/.well-known/openid-configuration"
333
+ urlparse(url)
334
+ CrossauthLogger.logger().debug(j({"msg": f"Fetching OIDC config from {url}"}))
335
+ headers = self._auth_server_headers
336
+ options : Dict[str, Any] = {"headers": headers}
337
+ if self._auth_server_mode is not None:
338
+ options["mode"] = self._auth_server_mode
339
+ if self._auth_server_credentials:
340
+ options["credentials"] = self._auth_server_credentials
341
+
342
+ try:
343
+ async with aiohttp.ClientSession() as session:
344
+ response = await session.get(url, **options)
345
+ response.raise_for_status()
346
+ except requests.RequestException as e:
347
+ CrossauthLogger.logger().error(j({"err": str(e)}))
348
+ raise Exception("Couldn't get OIDC configuration from URL")
349
+
350
+ self._oidc_config : OpenIdConfiguration | None= None
351
+ try:
352
+ body : Mapping[str,str] = await response.json()
353
+ self._oidc_config = {**(cast(OpenIdConfiguration, body))}
354
+ except json.JSONDecodeError:
355
+ raise Exception("Unrecognized response from OIDC configuration endpoint")
356
+
357
+ def get_oidc_config(self):
358
+ return self._oidc_config
359
+
360
+ @abstractmethod
361
+ def random_value(self, length : int) -> str:
362
+ """
363
+ Produce a random Base64-url-encoded str, whose length before
364
+ base64-url-encoding is the given length,
365
+ @param length the length of the random array before base64-url-encoding.
366
+ @returns the random value as a Base64-url-encoded srting
367
+ """
368
+
369
+ return Crypto.random_value(length);
370
+
371
+ @abstractmethod
372
+ async def sha256(self, plaintext : str) -> str:
373
+ """
374
+ SHA256 and Base64-url-encodes the given test
375
+ @param plaintext the text to encode
376
+ @returns the SHA256 hash, Base64-url-encode
377
+ """
378
+
379
+ return Crypto.sha256(plaintext)
380
+
381
+ async def start_authorization_code_flow(self, scope : str | None = None, pkce : bool = False):
382
+ """
383
+ Initiates the authorization code flow
384
+
385
+ :param str|None scope:, which can be None
386
+ :param bool pkce: if True, start the flow with PKCE (for public clients). Default False
387
+
388
+ """
389
+
390
+ CrossauthLogger.logger().debug(j({"msg": "Starting authorization code flow"}))
391
+ if self._oidc_config is None:
392
+ await self.load_config()
393
+ if (self._oidc_config is None):
394
+ raise CrossauthError(ErrorCode.Connection, "Couldn't load OIDC Configuration")
395
+ if "code" not in self._oidc_config["response_types_supported"] or not "query" in self._oidc_config["response_modes_supported"]:
396
+ return {
397
+ "error": "invalid_request",
398
+ "error_description": "Server does not support authorization code flow"
399
+ }
400
+ if not self._oidc_config.get("authorization_endpoint"):
401
+ return {
402
+ "error": "server_error",
403
+ "error_description": "Cannot get authorize endpoint"
404
+ }
405
+ self.state = self.random_value(self._state_length)
406
+ if not self._client_id:
407
+ return {
408
+ "error": "invalid_request",
409
+ "error_description": "Cannot make authorization code flow without client id"
410
+ }
411
+ if not self._redirect_uri:
412
+ return {
413
+ "error": "invalid_request",
414
+ "error_description": "Cannot make authorization code flow without Redirect Uri"
415
+ }
416
+
417
+ base = self._oidc_config["authorization_endpoint"]
418
+ url = f"{base}?response_type=code&client_id={urllib.parse.quote(self._client_id)}&state={urllib.parse.quote(self.state)}&redirect_uri={urllib.parse.quote(self._redirect_uri)}"
419
+
420
+ if scope:
421
+ url += f"&scope={urllib.parse.quote(scope)}"
422
+
423
+ if pkce:
424
+ self._code_verifier = self.random_value(self._verifier_length)
425
+ self._code_challenge = await self.sha256(self._code_verifier) if self._code_challenge_method == "S256" else self._code_verifier
426
+ url += f"&code_challenge={self._code_challenge}"
427
+
428
+ return {"url": url}
429
+
430
+ async def redirect_endpoint(self, code : str|None = None, state : str|None = None, error : str|None =None, error_description : str|None=None) -> OAuthTokenResponse:
431
+ """
432
+ For calling in a Redirect Uri endpoint
433
+
434
+ :param str|None code: the authorization code
435
+ :param str|None the state, if one is used by the authorization server
436
+ :param str|None any error: error message returned by the authorization server. It is passed through in the returned value
437
+ :param str|None any error_description: error description returned by the authorization server. It is passed through in the returned value
438
+
439
+ :return: an OAuth token endpoint response
440
+ """
441
+
442
+ if not self._oidc_config:
443
+ await self.load_config()
444
+ if (not self._oidc_config):
445
+ return {"error": "server_error", "error_description": "Couldn't load OIDC configuration"}
446
+ if error is not None or not code:
447
+ if error is None:
448
+ error = "server_error"
449
+ if error_description is None:
450
+ error_description = "Unknown error"
451
+ return {"error": error, "error_description": error_description}
452
+ if self._state and state != self._state:
453
+ return {"error": "access_denied", "error_description": "State is not valid"}
454
+ self.authzCode = code
455
+
456
+ if "authorization_code" not in self._oidc_config["grant_types_supported"]:
457
+ return {
458
+ "error": "invalid_request",
459
+ "error_description": "Server does not support authorization code grant"
460
+ }
461
+ if not self._oidc_config.get("token_endpoint"):
462
+ return {
463
+ "error": "server_error",
464
+ "error_description": "Cannot get token endpoint"
465
+ }
466
+ url = self._oidc_config["token_endpoint"]
467
+
468
+ grant_type = "authorization_code"
469
+ client_secret = self._client_secret
470
+ params : Dict[str, Any]= {
471
+ "grant_type": grant_type,
472
+ "client_id": self._client_id,
473
+ "code": self.authzCode,
474
+ }
475
+ if client_secret:
476
+ params["client_secret"] = client_secret
477
+ params["code_verifier"] = self._code_verifier
478
+ try:
479
+ ret = cast(OAuthTokenResponse, await self._post(url, params, self._auth_server_headers))
480
+ if ("id_token" in ret):
481
+ if (await self.validate_id_token(ret["id_token"]) is None):
482
+ raise CrossauthError(ErrorCode.InvalidToken, "Invalid ID token")
483
+ return ret
484
+ except Exception as e:
485
+ CrossauthLogger.logger().error(j({"cerr": e}))
486
+ CrossauthLogger.logger().debug(j({"err": e}))
487
+ return {
488
+ "error": "server_error",
489
+ "error_description": "Unable to get access token from server"
490
+ }
491
+
492
+ async def client_credentials_flow(self, scope : str|None = None) -> OAuthTokenResponse:
493
+ """
494
+ Start the client credentials flow
495
+
496
+ :param str|None scope:, which can be None
497
+
498
+ :return: an OAuth token endpoint response
499
+ """
500
+
501
+ CrossauthLogger.logger().debug(j({"msg": "Starting client credentials flow"}))
502
+ if not self._oidc_config:
503
+ await self.load_config()
504
+ if self._oidc_config is None or self._oidc_config["token_endpoint"] == "":
505
+ return {"error": "server_error", "error_description": "Cannot get token endpoint"}
506
+ if "client_credentials" not in self._oidc_config["grant_types_supported"]:
507
+ return {
508
+ "error": "invalid_request",
509
+ "error_description": "Server does not support client credentials grant"
510
+ }
511
+ if self._client_id == "":
512
+ return {
513
+ "error": "invalid_request",
514
+ "error_description": "Cannot make client credentials flow without client id"
515
+ }
516
+
517
+ url = self._oidc_config["token_endpoint"]
518
+
519
+ params : TokenBodyType = {
520
+ "grant_type": "client_credentials",
521
+ "client_id": self._client_id,
522
+ }
523
+ if self._client_secret is not None:
524
+ params["client_secret"] = self._client_secret
525
+
526
+ if scope:
527
+ params["scope"] = scope
528
+ try:
529
+ return cast(OAuthTokenResponse, await self._post(url, params, self._auth_server_headers))
530
+ except Exception as e:
531
+ CrossauthLogger.logger().error(j({"err": str(e)}))
532
+ return {
533
+ "error": "server_error",
534
+ "error_description": "Error connecting to authorization server"
535
+ }
536
+
537
+ async def password_flow(self, username : str, password : str, scope : str|None = None) -> OAuthTokenResponse:
538
+ """
539
+ Start the password flow
540
+
541
+ :param str username:, user's username
542
+ :param str password:, user's plaintext password
543
+ :param str|None scope:, which can be None
544
+
545
+ :return: an OAuth token endpoint response
546
+ """
547
+
548
+ CrossauthLogger.logger().debug(j({"msg": "Starting password flow"}))
549
+ if not self._oidc_config:
550
+ await self.load_config()
551
+ if (self._oidc_config is None):
552
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
553
+ if "password" not in self._oidc_config["grant_types_supported"]:
554
+ return {
555
+ "error": "invalid_request",
556
+ "error_description": "Server does not support password grant"
557
+ }
558
+ if not self._oidc_config.get("token_endpoint"):
559
+ return {
560
+ "error": "server_error",
561
+ "error_description": "Cannot get token endpoint"
562
+ }
563
+
564
+ url = self._oidc_config["token_endpoint"]
565
+
566
+ params : TokenBodyType = {
567
+ "grant_type": "password",
568
+ "client_id": self._client_id,
569
+ "username": username,
570
+ "password": password,
571
+ }
572
+ if (self._client_secret is not None):
573
+ params["client_secret"] = self._client_secret
574
+
575
+ if scope:
576
+ params["scope"] = scope
577
+ try:
578
+ ret = cast(OAuthTokenResponse, await self._post(url, params, self._auth_server_headers))
579
+ if ("id_token" in ret):
580
+ if (await self.validate_id_token(ret["id_token"]) is None):
581
+ raise CrossauthError(ErrorCode.InvalidToken, "Invalid ID token")
582
+ return ret
583
+ except Exception as e:
584
+ CrossauthLogger.logger().error(j({"err": str(e)}))
585
+ return {
586
+ "error": "server_error",
587
+ "error_description": "Error connecting to authorization server"
588
+ }
589
+
590
+ async def mfa_authenticators(self, mfa_token: str) -> OAuthMfaAuthenticatorsResponse :
591
+ """
592
+ Fields that canb be returned by the `mfaAuthenticators` function call
593
+ See Auth0's documentation for the password MFA flow.
594
+
595
+ :param str mfa_token:, The MFA token returned when the flow was initiated
596
+
597
+ :return: See :class:`OAuthMfaAuthenticatorsResponse`
598
+ """
599
+
600
+ CrossauthLogger.logger().debug(j({"msg": "Getting valid MFA authenticators"}))
601
+ if self._oidc_config is None:
602
+ await self.load_config()
603
+ if (self._oidc_config is None):
604
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
605
+
606
+ if "http://auth0.com/oauth/grant-type/mfa-otp" not in self._oidc_config["grant_types_supported"] and \
607
+ "http://auth0.com/oauth/grant-type/mfa-oob" not in self._oidc_config["grant_types_supported"]:
608
+ return {
609
+ "error": "invalid_request",
610
+ "error_description": "Server does not support password_mfa grant"
611
+ }
612
+ if not self._oidc_config.get("issuer"):
613
+ return {"error": "server_error", "error_description": "Cannot get issuer"}
614
+
615
+ url = f"{self._oidc_config['issuer']}/mfa/authenticators" if self._oidc_config['issuer'].endswith("/") else f"{self._oidc_config['issuer']}/mfa/authenticators"
616
+ resp = await self._get(url, {'authorization': f'Bearer {mfa_token}', **self._auth_server_headers})
617
+ if not isinstance(resp, list):
618
+ return {
619
+ "error": "server_error",
620
+ "error_description": "Expected array of authenticators in mfa/authenticators response"
621
+ }
622
+ authenticators : List[OAuthMfaAuthenticator] = []
623
+ for authenticator in resp:
624
+ if not authenticator.get("id") or not authenticator.get("authenticator_type") or not authenticator.get("active"):
625
+ return {
626
+ "error": "server_error",
627
+ "error_description": "Invalid mfa/authenticators response"
628
+ }
629
+ authenticators.append({
630
+ "id": authenticator["id"],
631
+ "authenticator_type": authenticator["authenticator_type"],
632
+ "active": authenticator["active"],
633
+ "name": authenticator.get("name"),
634
+ "oob_channel": authenticator.get("oob_channel"),
635
+ })
636
+ return {"authenticators": authenticators}
637
+
638
+ async def mfa_otp_request(self, mfa_token: str, authenticator_id: str) -> OAuthMfaChallengeResponse:
639
+ """
640
+ This is part of the Auth0 Password MFA flow. Once the client has
641
+ received a list of valid authenticators, if it wishes to initiate
642
+ OTP, call this function
643
+
644
+ Does not throw exceptions.
645
+
646
+ :param str mfa_token: the MFA token that was returned by the authorization
647
+ server in the response from the Password Flow.
648
+ :param str authenticator_id: the authenticator ID, as returned in the response
649
+ from the :func:`mfaAuthenticators` request.
650
+ """
651
+
652
+ CrossauthLogger.logger().debug(j({"msg": "Making MFA OTB request"}))
653
+ if not self._oidc_config:
654
+ await self.load_config()
655
+ if (self._oidc_config is None):
656
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
657
+ if "http://auth0.com/oauth/grant-type/mfa-otp" not in self._oidc_config["grant_types_supported"]:
658
+ return {
659
+ "error": "invalid_request",
660
+ "error_description": "Server does not support password_mfa grant"
661
+ }
662
+ if not self._oidc_config.get("issuer"):
663
+ return {"error": "server_error", "error_description": "Cannot get issuer"}
664
+
665
+ url = f"{self._oidc_config['issuer']}/mfa/challenge" if self._oidc_config['issuer'].endswith("/") else f"{self._oidc_config['issuer']}/mfa/challenge"
666
+ resp = await self._post(url, {
667
+ "client_id": self._client_id,
668
+ "client_secret": self._client_secret,
669
+ "challenge_type": "otp",
670
+ "mfa_token": mfa_token,
671
+ "authenticator_id": authenticator_id,
672
+ }, self._auth_server_headers)
673
+ if resp.get("challenge_type") != "otp":
674
+ return {
675
+ "error": resp.get("error", "server_error"),
676
+ "error_description": resp.get("error_description", "Invalid OTP challenge response")
677
+ }
678
+
679
+ return cast(OAuthMfaChallengeResponse, resp)
680
+
681
+ async def mfa_otp_complete(self, mfa_token: str, otp: str, scope: Optional[str] = None) -> OAuthTokenResponse:
682
+ """
683
+ Completes the Password MFA OTP flow.
684
+
685
+ :param str mfa_token: the MFA token that was returned by the authorization
686
+ server in the response from the Password Flow.
687
+ :param str otp: the OTP entered by the user
688
+
689
+ :return: an object with some of the following fields, depending on
690
+ authorization server configuration and whether there were
691
+ errors:
692
+ - `access_token` an OAuth access token
693
+ - `refresh_token` an OAuth access token
694
+ - `id_token` an OpenID Connect ID token
695
+ - `expires_in` number of seconds when the access token expires
696
+ - `scope` the scopes the user authorized
697
+ - `token_type` the OAuth token type
698
+ - `error` as per Auth0 Password MFA documentation
699
+ - `error_description` friendly error message
700
+ """
701
+
702
+ CrossauthLogger.logger().debug(j({"msg": "Completing MFA OTP request"}))
703
+ if self._oidc_config is None:
704
+ await self.load_config()
705
+ if (self._oidc_config is None):
706
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
707
+ if "http://auth0.com/oauth/grant-type/mfa-otp" not in self._oidc_config["grant_types_supported"]:
708
+ return {
709
+ "error": "invalid_request",
710
+ "error_description": "Server does not support password_mfa grant"
711
+ }
712
+ if not self._oidc_config.get("issuer"):
713
+ return {"error": "server_error", "error_description": "Cannot get issuer"}
714
+
715
+ otpUrl = self._oidc_config["token_endpoint"]
716
+ otpResp = await self._post(otpUrl, {
717
+ "grant_type": "http://auth0.com/oauth/grant-type/mfa-otp",
718
+ "client_id": self._client_id,
719
+ "client_secret": self._client_secret,
720
+ "challenge_type": "otp",
721
+ "mfa_token": mfa_token,
722
+ "otp": otp,
723
+ "scope": scope,
724
+ }, self._auth_server_headers)
725
+ if ("id_token" in otpResp):
726
+ if (await self.validate_id_token(otpResp["id_token"]) is None):
727
+ raise CrossauthError(ErrorCode.InvalidToken, "Invalid ID token")
728
+ return cast(OAuthTokenResponse, {
729
+ "id_token": otpResp.get("id_token"),
730
+ "access_token": otpResp.get("access_token"),
731
+ "refresh_token": otpResp.get("refresh_token"),
732
+ "expires_in": int(otpResp.get("expires_in", 0)),
733
+ "scope": otpResp.get("scope"),
734
+ "token_type": otpResp.get("token_type"),
735
+ "error": otpResp.get("error"),
736
+ "error_description": otpResp.get("error_description"),
737
+ })
738
+
739
+ async def mfa_oob_request(self, mfa_token: str, authenticator_id: str) -> OAuthMfaAuthenticatorsResponse:
740
+ """
741
+ This is part of the Auth0 Password MFA flow. Once the client has
742
+ received a list of valid authenticators, if it wishes to initiate
743
+ OOB (out of band) login, call this function
744
+
745
+ Does not throw exceptions.
746
+
747
+ :param str mfa_token: the MFA token that was returned by the authorization
748
+ server in the response from the Password Flow.
749
+ :param str authenticator_id: the authenticator ID, as returned in the response
750
+ from the :func:`mfa_authenticators` request.
751
+
752
+ :return: an object with one or more of the following defined:
753
+ - `challenge_type` as per the Auth0 MFA documentation
754
+ - `oob_code` as per the Auth0 MFA documentation
755
+ - `binding_method` as per the Auth0 MFA documentation
756
+ - `error` as per Auth0 Password MFA documentation
757
+ - `error_description` friendly error message
758
+ """
759
+
760
+ CrossauthLogger.logger().debug(j({"msg": "Making MFA OOB request"}))
761
+ if self._oidc_config is None:
762
+ await self.load_config()
763
+ if (self._oidc_config is None):
764
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
765
+ if "http://auth0.com/oauth/grant-type/mfa-otp" not in self._oidc_config["grant_types_supported"]:
766
+ return {
767
+ "error": "invalid_request",
768
+ "error_description": "Server does not support password_mfa grant"
769
+ }
770
+ if not self._oidc_config.get("issuer"):
771
+ return {"error": "server_error", "error_description": "Cannot get issuer"}
772
+
773
+ url = f"{self._oidc_config['issuer']}/mfa/challenge" if self._oidc_config['issuer'].endswith("/") else f"{self._oidc_config['issuer']}/mfa/challenge"
774
+ resp = await self._post(url, {
775
+ "client_id": self._client_id,
776
+ "client_secret": self._client_secret,
777
+ "challenge_type": "oob",
778
+ "mfa_token": mfa_token,
779
+ "authenticator_id": authenticator_id,
780
+ }, self._auth_server_headers)
781
+ if resp.get("challenge_type") != "oob" or not resp.get("oob_code") or not resp.get("binding_method"):
782
+ return {
783
+ "error": resp.get("error", "server_error"),
784
+ "error_description": resp.get("error_description", "Invalid OOB challenge response")
785
+ }
786
+
787
+ return cast(OAuthMfaAuthenticatorsResponse, {
788
+ "challenge_type": resp.get("challenge_type"),
789
+ "oob_code": resp.get("oob_code"),
790
+ "binding_method": resp.get("binding_method"),
791
+ "error": resp.get("error"),
792
+ "error_description": resp.get("error_description"),
793
+ })
794
+
795
+ async def mfa_oob_complete(self, mfa_token: str, oobCode: str, bindingCode: str, scope: Optional[str] = None) -> OAuthTokenResponse:
796
+ """
797
+ Completes the Password MFA OTP flow.
798
+
799
+ Does not throw exceptions.
800
+
801
+ :param str mfa_token: the MFA token that was returned by the authorization
802
+ server in the response from the Password Flow.
803
+ :param oob_code: the code entered by the user
804
+
805
+ :return: an :class:`OAuthTokenResponse` object, which may contain
806
+ an error instead of the response fields.
807
+ """
808
+
809
+ CrossauthLogger.logger().debug(j({"msg": "Completing MFA OOB request"}))
810
+ if self._oidc_config is None:
811
+ await self.load_config()
812
+ if (self._oidc_config is None):
813
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
814
+ if "http://auth0.com/oauth/grant-type/mfa-oob" not in self._oidc_config["grant_types_supported"]:
815
+ return {
816
+ "error": "invalid_request",
817
+ "error_description": "Server does not support password_mfa grant"
818
+ }
819
+ if not self._oidc_config.get("issuer"):
820
+ return {"error": "server_error", "error_description": "Cannot get issuer"}
821
+
822
+ url = self._oidc_config["token_endpoint"]
823
+ resp = await self._post(url, {
824
+ "grant_type": "http://auth0.com/oauth/grant-type/mfa-oob",
825
+ "client_id": self._client_id,
826
+ "client_secret": self._client_secret,
827
+ "challenge_type": "otp",
828
+ "mfa_token": mfa_token,
829
+ "oob_code": oobCode,
830
+ "binding_code": bindingCode,
831
+ "scope": scope,
832
+ }, self._auth_server_headers)
833
+ if "error" in resp and "error_description" in resp:
834
+ return {
835
+ "error": MapGetter[str].get(resp, "error", ""),
836
+ "error_description": MapGetter[str].get(resp, "error_description", ""),
837
+ }
838
+ if ("id_token" in resp):
839
+ if (await self.validate_id_token(resp["id_token"]) is None):
840
+ raise CrossauthError(ErrorCode.InvalidToken, "Invalid ID token")
841
+ return cast(OAuthTokenResponse, {
842
+ "id_token": resp.get("id_token"),
843
+ "access_token": resp.get("access_token"),
844
+ "refresh_token": resp.get("refresh_token"),
845
+ "expires_in": int(resp.get("expires_in", 0)),
846
+ "scope": resp.get("scope"),
847
+ "token_type": resp.get("token_type"),
848
+ })
849
+
850
+ async def refresh_token_flow(self, refresh_token: str) -> OAuthTokenResponse:
851
+ """
852
+ Starts the refresh token flow
853
+
854
+ :param str refresh_token: the refresh token to exchange
855
+
856
+ :return: a :class:`OAuthTokenResponse? response
857
+ """
858
+
859
+ CrossauthLogger.logger().debug(j({"msg": "Starting refresh token flow"}))
860
+ if self._oidc_config is None:
861
+ await self.load_config()
862
+ if (self._oidc_config is None):
863
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
864
+ if "refresh_token" not in self._oidc_config["grant_types_supported"]:
865
+ return {
866
+ "error": "invalid_request",
867
+ "error_description": "Server does not support refresh_token grant"
868
+ }
869
+ if not self._oidc_config.get("token_endpoint"):
870
+ return {
871
+ "error": "server_error",
872
+ "error_description": "Cannot get token endpoint"
873
+ }
874
+
875
+ url = self._oidc_config["token_endpoint"]
876
+
877
+ client_secret = self._client_secret
878
+
879
+ params = {
880
+ "grant_type": "refresh_token",
881
+ "refresh_token": refresh_token,
882
+ "client_id": self._client_id,
883
+ }
884
+ if client_secret:
885
+ params["client_secret"] = client_secret
886
+ try:
887
+ ret = cast(OAuthTokenResponse, await self._post(url, params, self._auth_server_headers))
888
+ if ("id_token" in ret):
889
+ if (await self.validate_id_token(ret["id_token"]) is None):
890
+ raise CrossauthError(ErrorCode.InvalidToken, "Invalid ID token")
891
+ return ret
892
+ except Exception as e:
893
+ CrossauthLogger.logger().error(j({"err": str(e)}))
894
+ return {
895
+ "error": "server_error",
896
+ "error_description": "Error connecting to authorization server"
897
+ }
898
+
899
+ async def start_device_code_flow(self, url: str, scope: Optional[str] = None) -> OAuthDeviceAuthorizationResponse:
900
+
901
+ """
902
+ Starts the Device Code Flow on the primary device (the one wanting an access token)
903
+ :param str url: The URl for the device_authorization endpoint, as it is not defined in the OIDC configuration
904
+ :param str|None scope: optional scope to request authorization for
905
+
906
+ :return: See :class:`OAuthDeviceAuthorizationResponse`
907
+ """
908
+
909
+ CrossauthLogger.logger().debug(j({"msg": "Starting device code flow"}))
910
+ if self._oidc_config is None:
911
+ await self.load_config()
912
+ if (self._oidc_config is None):
913
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
914
+ if "urn:ietf:params:oauth:grant-type:device_code" not in self._oidc_config["grant_types_supported"]:
915
+ return {
916
+ "error": "invalid_request",
917
+ "error_description": "Server does not support device code grant"
918
+ }
919
+
920
+ params : TokenBodyType = {
921
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
922
+ "client_id": self._client_id,
923
+ }
924
+ if self._client_secret is not None:
925
+ params["client_secret"] = self._client_secret
926
+
927
+ if scope:
928
+ params["scope"] = scope
929
+ try:
930
+ ret = cast(OAuthDeviceAuthorizationResponse, await self._post(url, params, self._auth_server_headers))
931
+ if ("id_token" in ret):
932
+ if (await self.validate_id_token(ret["id_token"]) is None):
933
+ raise CrossauthError(ErrorCode.InvalidToken, "Invalid ID token")
934
+ return ret
935
+ except Exception as e:
936
+ CrossauthLogger.logger().error(j({"err": str(e)}))
937
+ return {
938
+ "error": "server_error",
939
+ "error_description": "Error connecting to authorization server"
940
+ }
941
+
942
+ async def poll_device_code_flow(self, device_code: str) -> OAuthDeviceResponse:
943
+ """
944
+ Polls the device endpoint to check if the device code flow has been
945
+ authorized by the user.
946
+
947
+ :param str device_code: the device code to poll
948
+
949
+ :return: See :class:`OAuthDeviceResponse`
950
+ """
951
+
952
+ CrossauthLogger.logger().debug(j({"msg": "Starting device code flow"}))
953
+ if self._oidc_config is None:
954
+ await self.load_config()
955
+ if (self._oidc_config is None):
956
+ raise CrossauthError(ErrorCode.Connection, "Couldn't fet OIDC configuration")
957
+ if "urn:ietf:params:oauth:grant-type:device_code" not in self._oidc_config["grant_types_supported"]:
958
+ return {
959
+ "error": "invalid_request",
960
+ "error_description": "Server does not support device code grant"
961
+ }
962
+ if not self._oidc_config.get("token_endpoint"):
963
+ return {
964
+ "error": "server_error",
965
+ "error_description": "Cannot get token endpoint"
966
+ }
967
+
968
+ params : TokenBodyType = {
969
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
970
+ "client_id": self._client_id,
971
+ "device_code": device_code,
972
+ }
973
+ if self._client_secret is not None:
974
+ params["client_secret"] = self._client_secret
975
+
976
+ try:
977
+ resp = await self._post(self._oidc_config["token_endpoint"], params, self._auth_server_headers)
978
+ ret = cast(OAuthDeviceResponse, resp)
979
+ if ("id_token" in ret):
980
+ if (await self.validate_id_token(ret["id_token"]) is None):
981
+ raise CrossauthError(ErrorCode.InvalidToken, "Invalid ID token")
982
+ return ret
983
+ except Exception as e:
984
+ CrossauthLogger.logger().error(j({"err": str(e)}))
985
+ return {
986
+ "error": "server_error",
987
+ "error_description": "Error connecting to authorization server"
988
+ }
989
+
990
+ async def _post(self, url: str, params: Mapping[str, Any], headers: Dict[str, Any] = {}) -> Mapping[str, Any]:
991
+ CrossauthLogger.logger().debug(j({
992
+ "msg": "Fetch POST",
993
+ "url": url,
994
+ "params": list(params.keys())
995
+ }))
996
+ options = {}
997
+ if self._auth_server_credentials:
998
+ options["credentials"] = self._auth_server_credentials
999
+ if self._auth_server_mode:
1000
+ options["mode"] = self._auth_server_mode
1001
+ async with aiohttp.ClientSession() as session:
1002
+ resp = await session.post(url, json=params, headers={
1003
+ 'Accept': 'application/json',
1004
+ 'Content-Type': 'application/json',
1005
+ **headers,
1006
+ })
1007
+ return await resp.json()
1008
+
1009
+ async def _get(self, url: str, headers: Mapping[str, Any] = {}) -> Mapping[str, Any] | List[Any]:
1010
+ CrossauthLogger.logger().debug(j({"msg": "Fetch GET", "url": url}))
1011
+ options = {}
1012
+ if self._auth_server_credentials:
1013
+ options["credentials"] = self._auth_server_credentials
1014
+ if self._auth_server_mode:
1015
+ options["mode"] = self._auth_server_mode
1016
+ async with aiohttp.ClientSession() as session:
1017
+ resp = await session.get(url, headers={
1018
+ 'Accept': 'application/json',
1019
+ 'Content-Type': 'application/json',
1020
+ **headers,
1021
+ })
1022
+ return await resp.json()
1023
+
1024
+ async def validate_id_token(self, token: str) -> Optional[Dict[str, Any]]:
1025
+ """
1026
+ Validates an OpenID ID token, returning None if it is invalid.
1027
+
1028
+ Does not raise exceptions.
1029
+
1030
+ :param token: the token to validate. To be valid, the signature must
1031
+ be valid and the `type` claim in the payload must be set to `id`.
1032
+
1033
+ :returns
1034
+ the parsed payload or None if the token is invalid.
1035
+ """
1036
+
1037
+ try:
1038
+ return await self._token_consumer.token_authorized(token, "id")
1039
+ except Exception:
1040
+ return None
1041
+
1042
+ async def id_token_authorized(self, id_token: str) -> Optional[Dict[str, Any]]:
1043
+ """
1044
+ Validates a token using the token consumer.
1045
+
1046
+ :param id_token (str): the token to validate
1047
+
1048
+ :returns the parsed JSON of the payload, or None if it is not valid.
1049
+ """
1050
+
1051
+ try:
1052
+ return await self._token_consumer.token_authorized(id_token, "id")
1053
+ except Exception as e:
1054
+ CrossauthLogger.logger().warn(j({"err": e}))
1055
+ return None
1056
+
1057
+ def get_token_payload(self, token: str) -> Dict[str, Any]:
1058
+ """
1059
+ Validates a token and, if valid, returns the payload
1060
+ """
1061
+ instance = JWT()
1062
+ return instance.decode(token, None, do_verify=False, do_time_check=False)
1063
+