-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapi_client.py
More file actions
1243 lines (1047 loc) · 49.2 KB
/
api_client.py
File metadata and controls
1243 lines (1047 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import time
from collections import defaultdict
from collections.abc import Mapping, Sequence
from typing import Any, Optional, Union
import httpx
from authlib.jose import JsonWebKey, JsonWebToken
from .cache import InMemoryCache
from .config import ApiClientOptions
from .errors import (
ApiError,
BaseAuthError,
ConfigurationError,
DomainsResolverError,
GetAccessTokenForConnectionError,
GetTokenByExchangeProfileError,
InvalidAuthSchemeError,
InvalidDpopProofError,
MissingAuthorizationError,
MissingRequiredArgumentError,
VerifyAccessTokenError,
)
from .utils import (
aclose_default_httpx_client,
calculate_jwk_thumbprint,
fetch_jwks,
fetch_oidc_metadata,
get_unverified_header,
get_unverified_payload,
normalize_domain,
normalize_url_for_htu,
sha256_base64url,
)
# Token Exchange constants
TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" # noqa: S105
MAX_ARRAY_VALUES_PER_KEY = 20 # DoS protection for extra parameter arrays
# OAuth parameter denylist - parameters that cannot be overridden via extras
RESERVED_PARAMS = frozenset([
"grant_type", "client_id", "client_secret", "client_assertion",
"client_assertion_type", "subject_token", "subject_token_type",
"requested_token_type", "actor_token", "actor_token_type",
"subject_issuer", "audience", "aud", "resource", "resources",
"resource_indicator", "scope", "connection", "login_hint",
"organization", "assertion",
])
class ApiClient:
"""
The main class for discovering OIDC metadata (issuer, jwks_uri) and verifying
Auth0-issued JWT access tokens in an async environment.
"""
def __init__(self, options: ApiClientOptions):
# Validate audience is always required
if not options.audience:
raise MissingRequiredArgumentError("audience")
# Validate domains parameter if provided
if options.domains is not None:
if isinstance(options.domains, list):
# Static list validation
if len(options.domains) == 0:
raise ConfigurationError("domains list cannot be empty")
if not all(isinstance(d, str) and d.strip() for d in options.domains):
raise ConfigurationError(
"domains list must contain only non-empty strings"
)
# Normalize and store domains
self._allowed_domains = [normalize_domain(d) for d in options.domains]
elif callable(options.domains):
# Dynamic resolver - store the function
self._allowed_domains = options.domains
else:
raise ConfigurationError(
"domains must be either a list of domain strings or a callable resolver function"
)
else:
# Single domain mode
self._allowed_domains = None
# Validate domain/domains configuration
if not options.domain and not options.domains:
raise ConfigurationError(
"Must provide either 'domain' or 'domains' parameter. "
"Use 'domain' for single-domain mode, 'domains' for multi-domain support."
)
# Validate that domain is set when client_id is configured
if options.client_id and not options.domain:
raise ConfigurationError(
"The 'domain' parameter is required when 'client_id' is configured."
)
self.options = options
# Validate cache configuration
if not isinstance(options.cache_ttl_seconds, (int, float)) or options.cache_ttl_seconds < 0:
raise ConfigurationError("cache_ttl_seconds must be a non-negative number")
if not isinstance(options.cache_max_entries, int) or options.cache_max_entries < 2:
raise ConfigurationError("cache_max_entries must be an integer greater than 1")
if options.cache_adapter:
self._discovery_cache = options.cache_adapter
self._jwks_cache = options.cache_adapter
else:
self._discovery_cache = InMemoryCache(max_entries=options.cache_max_entries)
self._jwks_cache = InMemoryCache(max_entries=options.cache_max_entries)
self._cache_ttl = options.cache_ttl_seconds
# Per-cache-key single-flight locks for OIDC discovery and JWKS
# refetches. Without these, every concurrent request that misses the
# cache at the moment of TTL expiry fires its own outbound HTTP call
# — a thundering herd that Auth0 rate-limits and we time out on.
# The lock guarantees only ONE coroutine per cache key refetches;
# the rest await the result and read from the now-warm cache.
self._discovery_locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
self._jwks_locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
self._jwt = JsonWebToken(["RS256"])
self._dpop_algorithms = ["ES256"]
self._dpop_jwt = JsonWebToken(self._dpop_algorithms)
async def aclose(self) -> None:
"""Release the shared default httpx client. Idempotent; no-op when a `custom_fetch` is in use."""
await aclose_default_httpx_client()
def is_dpop_required(self) -> bool:
"""Check if DPoP authentication is required."""
return getattr(self.options, "dpop_required", False)
async def _resolve_allowed_domains(
self,
unverified_iss: str,
request_url: Optional[str] = None,
request_headers: Optional[dict] = None
) -> Optional[list[str]]:
"""
Resolve and validate allowed domains for the given issuer.
Handles three modes:
1. Static list: Returns normalized list, validates issuer against it
2. Dynamic resolver: Invokes resolver function, validates issuer against result
3. Single domain: Returns None (backward compatibility, uses domain)
Args:
unverified_iss: The issuer claim from the token (not yet verified)
request_url: Optional request URL for dynamic resolvers
request_headers: Optional request headers for dynamic resolvers
Returns:
List of normalized allowed domain strings
Raises:
DomainsResolverError: If resolver invocation fails
VerifyAccessTokenError: If issuer is not in allowed domains
"""
# Single domain mode
if self._allowed_domains is None:
return None
# Static list mode
if isinstance(self._allowed_domains, list):
allowed_domains = self._allowed_domains
# Dynamic resolver mode
elif callable(self._allowed_domains):
# Build resolver context
context = {
'request_url': request_url,
'request_headers': request_headers,
'unverified_iss': unverified_iss
}
# Invoke resolver (supports both sync and async resolvers)
try:
result = self._allowed_domains(context)
if asyncio.iscoroutine(result) or asyncio.isfuture(result):
result = await result
except Exception as e:
raise DomainsResolverError(
f"Domains resolver function failed: {str(e)}"
) from e
# Validate resolver result
if not isinstance(result, list):
raise DomainsResolverError(
"Domains resolver must return a list"
)
if len(result) == 0:
raise DomainsResolverError(
"Domains resolver returned an empty list"
)
if not all(isinstance(d, str) and d.strip() for d in result):
raise DomainsResolverError(
"Domains resolver must return a list of non-empty strings"
)
# Normalize domains from resolver
try:
allowed_domains = [normalize_domain(d) for d in result]
except ValueError as e:
raise DomainsResolverError(
f"Domains resolver returned invalid domain: {str(e)}"
) from e
else:
# Should never happen due to __init__ validation
raise ConfigurationError("Invalid _allowed_domains type")
# Validate issuer is in allowed domains
if unverified_iss not in allowed_domains:
raise VerifyAccessTokenError(
"Token issuer is not in the list of allowed domains"
)
return allowed_domains
async def verify_request(
self,
headers: dict[str, str],
http_method: Optional[str] = None,
http_url: Optional[str] = None
) -> dict[str, Any]:
"""
Dispatch based on Authorization scheme:
• If scheme is 'DPoP', verifies both access token and DPoP proof
• If scheme is 'Bearer', verifies only the access token
Note:
Authorization header parsing uses split(None, 1) to correctly handle
tabs and multiple spaces per HTTP specs. Malformed headers with multiple
spaces now raise VerifyAccessTokenError during JWT parsing (previously
raised InvalidAuthSchemeError).
Args:
headers: HTTP headers dict containing (header keys should be lowercase):
- "authorization": The Authorization header value (required)
- "dpop": The DPoP proof header value (required for DPoP)
http_method: The HTTP method (required for DPoP)
http_url: The HTTP URL (required for DPoP, also used for MCD resolver context)
Returns:
The decoded access token claims
Raises:
MissingRequiredArgumentError: If required args are missing
InvalidAuthSchemeError: If an unsupported scheme is provided
InvalidDpopProofError: If DPoP verification fails
VerifyAccessTokenError: If access token verification fails
"""
# Normalize header keys to lowercase for robust access
headers = {k.lower(): v for k, v in headers.items()}
authorization_header = headers.get("authorization", "")
dpop_proof = headers.get("dpop")
if not authorization_header:
if self.is_dpop_required():
raise self._prepare_error(
InvalidAuthSchemeError("")
)
else:
raise self._prepare_error(MissingAuthorizationError())
# Split authorization header on first whitespace
parts = authorization_header.split(None, 1)
if len(parts) != 2:
raise self._prepare_error(MissingAuthorizationError())
scheme, token = parts
scheme = scheme.lower()
if self.is_dpop_required() and scheme != "dpop":
raise self._prepare_error(
InvalidAuthSchemeError(""),
auth_scheme=scheme
)
if not token.strip():
raise self._prepare_error(MissingAuthorizationError())
if scheme == "dpop":
if not self.options.dpop_enabled:
raise self._prepare_error(MissingAuthorizationError())
if not dpop_proof:
if self.is_dpop_required():
raise self._prepare_error(
InvalidAuthSchemeError(""),
auth_scheme=scheme
)
else:
raise self._prepare_error(
InvalidAuthSchemeError(""),
auth_scheme=scheme
)
if "," in dpop_proof:
raise self._prepare_error(
InvalidDpopProofError("Multiple DPoP proofs are not allowed"),
auth_scheme=scheme
)
try:
dpop_header = get_unverified_header(dpop_proof)
except Exception:
raise self._prepare_error(InvalidDpopProofError("Failed to verify DPoP proof"), auth_scheme=scheme)
if not http_method or not http_url:
missing_params = []
if not http_method:
missing_params.append("http_method")
if not http_url:
missing_params.append("http_url")
raise self._prepare_error(
MissingRequiredArgumentError(f"DPoP authentication requires {' and '.join(missing_params)}"),
auth_scheme=scheme
)
try:
access_token_claims = await self.verify_access_token(
token,
request_url=http_url,
request_headers=headers
)
except VerifyAccessTokenError as e:
raise self._prepare_error(e, auth_scheme=scheme)
cnf_claim = access_token_claims.get("cnf")
if not cnf_claim:
raise self._prepare_error(
VerifyAccessTokenError("JWT Access Token has no jkt confirmation claim"),
auth_scheme=scheme
)
if not isinstance(cnf_claim, dict):
raise self._prepare_error(
VerifyAccessTokenError("JWT Access Token has invalid confirmation claim format"),
auth_scheme=scheme
)
try:
await self.verify_dpop_proof(
access_token=token,
proof=dpop_proof,
http_method=http_method,
http_url=http_url
)
except InvalidDpopProofError as e:
raise self._prepare_error(e, auth_scheme=scheme)
# DPoP binding verification
jwk_dict = dpop_header["jwk"]
actual_jkt = calculate_jwk_thumbprint(jwk_dict)
expected_jkt = cnf_claim.get("jkt")
if not expected_jkt:
raise self._prepare_error(
VerifyAccessTokenError("Access token 'cnf' claim missing 'jkt'"),
auth_scheme=scheme
)
if expected_jkt != actual_jkt:
raise self._prepare_error(
VerifyAccessTokenError("JWT Access Token confirmation mismatch"),
auth_scheme=scheme
)
return access_token_claims
if scheme == "bearer":
try:
claims = await self.verify_access_token(
token,
request_url=http_url,
request_headers=headers
)
if claims.get("cnf") and isinstance(claims["cnf"], dict) and claims["cnf"].get("jkt"):
if self.options.dpop_enabled:
raise self._prepare_error(
VerifyAccessTokenError(
"DPoP-bound token requires the DPoP authentication scheme, not Bearer"
),
auth_scheme=scheme
)
if dpop_proof:
if self.options.dpop_enabled:
raise self._prepare_error(
InvalidAuthSchemeError(
"DPoP proof requires DPoP authentication scheme, not Bearer"
),
auth_scheme=scheme
)
return claims
except VerifyAccessTokenError as e:
raise self._prepare_error(e, auth_scheme=scheme)
raise self._prepare_error(MissingAuthorizationError())
async def verify_access_token(
self,
access_token: str,
request_url: Optional[str] = None,
request_headers: Optional[dict] = None,
required_claims: Optional[list[str]] = None
) -> dict[str, Any]:
"""
Asynchronously verifies the provided JWT access token.
- Fetches OIDC metadata and JWKS if not already cached.
- Decodes and validates signature (RS256) with the correct key.
- Checks standard claims: 'iss', 'aud', 'exp', 'iat'
- Checks extra required claims if 'required_claims' is provided.
Args:
access_token: The JWT access token to verify
request_url: Optional request URL for dynamic domain resolvers
request_headers: Optional request headers dict for dynamic domain resolvers
required_claims: Optional list of additional claim names that must be present
Returns:
The decoded token claims if valid.
Raises:
MissingRequiredArgumentError: If no token is provided.
VerifyAccessTokenError: If verification fails (signature, claims mismatch, etc.).
DomainsResolverError: If domains resolver function fails.
"""
if not access_token:
raise MissingRequiredArgumentError("access_token")
required_claims = required_claims or []
# Extract header and payload without signature verification
try:
header = get_unverified_header(access_token)
except Exception as e:
raise VerifyAccessTokenError(f"Failed to parse token header: {str(e)}") from e
# Reject symmetric algorithms
alg = header.get('alg', '')
if alg.startswith('HS'):
raise VerifyAccessTokenError(
f"Symmetric algorithm '{alg}' is not supported. "
"Only asymmetric algorithms (e.g., RS256) are allowed."
)
# Extract and validate issuer claim (before network calls)
try:
unverified_payload = get_unverified_payload(access_token)
except Exception as e:
raise VerifyAccessTokenError(f"Failed to parse token payload: {str(e)}") from e
unverified_iss = unverified_payload.get('iss')
if not unverified_iss:
raise VerifyAccessTokenError("Token missing 'iss' claim")
# Normalize issuer for validation
try:
normalized_iss = normalize_domain(unverified_iss)
except ValueError as e:
raise VerifyAccessTokenError(f"Invalid token issuer format: {str(e)}") from e
# Validate issuer against allowed domains (MCD)
if self._allowed_domains is not None:
await self._resolve_allowed_domains(
normalized_iss,
request_url=request_url,
request_headers=request_headers
)
# Fetch OIDC discovery metadata
try:
if self._allowed_domains is not None:
metadata = await self._discover(issuer=normalized_iss)
else:
metadata = await self._discover()
except VerifyAccessTokenError:
raise
except Exception as e:
raise VerifyAccessTokenError(
f"Failed to fetch OIDC discovery metadata: {str(e)}"
) from e
# First issuer validation: Prevent issuer confusion attacks
discovery_issuer = metadata.get("issuer")
if not discovery_issuer:
raise VerifyAccessTokenError("Discovery metadata missing 'issuer' field")
# Normalize discovery issuer for comparison
try:
normalized_discovery_issuer = normalize_domain(discovery_issuer)
except ValueError as e:
raise VerifyAccessTokenError(f"Invalid discovery issuer format: {str(e)}") from e
if normalized_iss != normalized_discovery_issuer:
raise VerifyAccessTokenError(
"Token issuer does not match the discovery issuer"
)
# Extract JWKS URI from discovery metadata
jwks_uri = metadata.get("jwks_uri")
if not jwks_uri:
raise VerifyAccessTokenError("Discovery metadata missing 'jwks_uri' field")
# Fetch JWKS from discovery's jwks_uri
try:
jwks_data = await self._fetch_jwks(jwks_uri)
except VerifyAccessTokenError:
raise
except Exception as e:
raise VerifyAccessTokenError(
f"Failed to fetch JWKS: {str(e)}"
) from e
# Extract kid for JWKS lookup
kid = header.get("kid")
if not kid:
raise VerifyAccessTokenError("Token header missing 'kid' claim")
# Find matching key
matching_key_dict = None
for key_dict in jwks_data["keys"]:
if key_dict.get("kid") == kid:
matching_key_dict = key_dict
break
if not matching_key_dict:
raise VerifyAccessTokenError("No matching key found in JWKS")
# Import public key and verify signature
public_key = JsonWebKey.import_key(matching_key_dict)
if isinstance(access_token, str) and access_token.startswith("b'"):
access_token = access_token[2:-1]
try:
claims = self._jwt.decode(access_token, public_key)
except Exception as e:
raise VerifyAccessTokenError(f"Signature verification failed: {str(e)}") from e
# Second issuer validation: Ensure verified token wasn't tampered
if claims.get("iss") != discovery_issuer:
raise VerifyAccessTokenError(
"Verified Token issuer does not match the discovery issuer"
)
expected_aud = self.options.audience
actual_aud = claims.get("aud")
if isinstance(actual_aud, list):
if expected_aud not in actual_aud:
raise VerifyAccessTokenError("Audience mismatch (not in token's aud array)")
else:
if actual_aud != expected_aud:
raise VerifyAccessTokenError("Audience mismatch (single aud)")
now = int(time.time())
if "exp" not in claims or now >= claims["exp"]:
raise VerifyAccessTokenError("Token is expired")
if "iat" not in claims:
raise VerifyAccessTokenError("Missing 'iat' claim in token")
# Additional required_claims
for rc in required_claims:
if rc not in claims:
raise VerifyAccessTokenError(f"Missing required claim: {rc}")
return claims
async def verify_dpop_proof(
self,
access_token: str,
proof: str,
http_method: str,
http_url: str
) -> dict[str, Any]:
"""
1. Single well-formed compact JWS
2. typ="dpop+jwt", alg∈allowed, alg≠none
3. jwk header present & public only
4. Signature verifies with jwk
5. Validates all required claims
Raises InvalidDpopProofError on any failure.
"""
if not proof:
raise MissingRequiredArgumentError("dpop_proof")
if not access_token:
raise MissingRequiredArgumentError("access_token")
if not http_method or not http_url:
raise MissingRequiredArgumentError("http_method/http_url")
header = get_unverified_header(proof)
if header.get("typ") != "dpop+jwt":
raise InvalidDpopProofError("Unexpected JWT 'typ' header parameter value")
alg = header.get("alg")
if alg not in self._dpop_algorithms:
raise InvalidDpopProofError("Unsupported algorithm in DPoP proof")
jwk_dict = header.get("jwk")
if not jwk_dict or not isinstance(jwk_dict, dict):
raise InvalidDpopProofError("Missing or invalid jwk in header")
if "d" in jwk_dict:
raise InvalidDpopProofError("Private key material found in jwk header")
if jwk_dict.get("kty") != "EC":
raise InvalidDpopProofError("Only EC keys are supported for DPoP")
if jwk_dict.get("crv") != "P-256":
raise InvalidDpopProofError("Only P-256 curve is supported")
public_key = JsonWebKey.import_key(jwk_dict)
try:
claims = self._dpop_jwt.decode(proof, public_key)
except Exception as e:
raise InvalidDpopProofError(f"JWT signature verification failed: {e}")
# Checks all required claims are present
self._validate_claims_presence(claims, ["iat", "ath", "htm", "htu", "jti"])
jti = claims["jti"]
if not isinstance(jti, str):
raise InvalidDpopProofError("jti claim must be a string")
if not jti.strip():
raise InvalidDpopProofError("jti claim must not be empty")
now = int(time.time())
iat = claims["iat"]
offset = getattr(self.options, "dpop_iat_offset", 300) # default 5 minutes
leeway = getattr(self.options, "dpop_iat_leeway", 30) # default 30 seconds
if not isinstance(iat, (int, float)):
raise InvalidDpopProofError("Invalid iat claim (must be integer or float)")
if iat < now - offset:
raise InvalidDpopProofError("DPoP Proof iat is too old")
elif iat > now + leeway:
raise InvalidDpopProofError("DPoP Proof iat is from the future")
if claims["htm"].lower() != http_method.lower():
raise InvalidDpopProofError("DPoP Proof htm mismatch")
try:
normalized_htu = normalize_url_for_htu(claims["htu"])
normalized_http_url = normalize_url_for_htu(http_url)
if normalized_htu != normalized_http_url:
raise InvalidDpopProofError("DPoP Proof htu mismatch")
except ValueError:
raise InvalidDpopProofError("DPoP Proof htu mismatch")
if claims["ath"] != sha256_base64url(access_token):
raise InvalidDpopProofError("DPoP Proof ath mismatch")
return claims
async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict[str, Any]:
"""
Retrieves a token for a connection.
Args:
options: Options for retrieving an access token for a connection.
Must include 'connection' and 'access_token' keys.
May optionally include 'login_hint'.
Raises:
GetAccessTokenForConnectionError: If there was an issue requesting the access token.
ApiError: If the token exchange endpoint returns an error.
Returns:
Dictionary containing the token response with access_token, expires_in, and scope.
"""
# Constants
SUBJECT_TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token" # noqa S105
REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN = "http://auth0.com/oauth/token-type/federated-connection-access-token" # noqa S105
GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN = "urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token" # noqa S105
connection = options.get("connection")
access_token = options.get("access_token")
if not connection:
raise MissingRequiredArgumentError("connection")
if not access_token:
raise MissingRequiredArgumentError("access_token")
client_id = self.options.client_id
client_secret = self.options.client_secret
if not client_id or not client_secret:
raise GetAccessTokenForConnectionError("You must configure the SDK with a client_id and client_secret to use get_access_token_for_connection.")
metadata = await self._discover()
token_endpoint = metadata.get("token_endpoint")
if not token_endpoint:
raise GetAccessTokenForConnectionError(
"Token endpoint missing in OIDC metadata. "
"Verify your domain configuration and that the OIDC discovery endpoint "
f"(https://{self.options.domain}/.well-known/openid-configuration) is accessible"
)
# Prepare parameters
params = {
"connection": connection,
"requested_token_type": REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN,
"grant_type": GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN,
"client_id": client_id,
"subject_token": access_token,
"subject_token_type": SUBJECT_TYPE_ACCESS_TOKEN,
}
# Add login_hint if provided
if "login_hint" in options and options["login_hint"]:
params["login_hint"] = options["login_hint"]
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(self.options.timeout)) as client:
response = await client.post(
token_endpoint,
data=params,
auth=(client_id, client_secret)
)
if response.status_code != 200:
# Lenient check for JSON error responses (handles application/json, text/json, etc.)
content_type = response.headers.get("content-type", "").lower()
error_data = response.json() if "json" in content_type else {}
raise ApiError(
error_data.get("error", "connection_token_error"),
error_data.get(
"error_description", f"Failed to get token for connection: {response.status_code}"),
response.status_code
)
try:
token_endpoint_response = response.json()
except ValueError:
raise ApiError("invalid_json", "Token endpoint returned invalid JSON.")
access_token = token_endpoint_response.get("access_token")
if not isinstance(access_token, str) or not access_token:
raise ApiError("invalid_response", "Missing or invalid access_token in response.", 502)
expires_in_raw = token_endpoint_response.get("expires_in", 3600)
try:
expires_in = int(expires_in_raw)
except (TypeError, ValueError):
raise ApiError("invalid_response", "expires_in is not an integer.", 502)
return {
"access_token": access_token,
"expires_at": int(time.time()) + expires_in,
"scope": token_endpoint_response.get("scope", "")
}
except httpx.TimeoutException as exc:
raise ApiError(
"timeout_error",
f"Request to token endpoint timed out: {str(exc)}",
504,
exc
)
except httpx.HTTPError as exc:
raise ApiError(
"network_error",
f"Network error occurred: {str(exc)}",
502,
exc
)
async def get_token_by_exchange_profile(
self,
subject_token: str,
subject_token_type: str,
audience: Optional[str] = None,
scope: Optional[str] = None,
requested_token_type: Optional[str] = None,
extra: Optional[Mapping[str, Union[str, Sequence[str]]]] = None
) -> dict[str, Any]:
"""
Exchange a subject token for an Auth0 token using RFC 8693.
The matching Token Exchange Profile is selected by subject_token_type.
This method requires a confidential client (client_id and client_secret must be configured).
Args:
subject_token: The token to be exchanged
subject_token_type: URI identifying the token type (must match a Token Exchange Profile)
audience: Optional target API identifier for the exchanged tokens
scope: Optional space-separated OAuth 2.0 scopes to request
requested_token_type: Optional type of token to issue (defaults to access token)
extra: Optional additional parameters sent as form fields to Auth0.
All values are converted to strings before sending.
Arrays are limited to 20 values per key for DoS protection.
Cannot override reserved OAuth parameters (case-insensitive check).
Returns:
Dictionary containing:
- access_token (str): The Auth0 access token
- expires_in (int): Token lifetime in seconds
- expires_at (int): Unix timestamp when token expires
- id_token (str, optional): OpenID Connect ID token
- refresh_token (str, optional): Refresh token
- scope (str, optional): Granted scopes
- token_type (str, optional): Token type (typically "Bearer")
- issued_token_type (str, optional): RFC 8693 issued token type identifier
Raises:
MissingRequiredArgumentError: If required parameters are missing
GetTokenByExchangeProfileError: If client credentials not configured, validation fails,
or reserved parameters are supplied in extra
ApiError: If the token endpoint returns an error
Example:
async def example():
result = await api_client.get_token_by_exchange_profile(
subject_token=token,
subject_token_type="urn:example:subject-token",
audience="https://api.backend.com"
)
References:
- Custom Token Exchange: https://auth0.com/docs/authenticate/custom-token-exchange
- RFC 8693: https://datatracker.ietf.org/doc/html/rfc8693
- Related SDK: https://github.com/auth0/auth0-auth-js
"""
# Validate required parameters
if not subject_token:
raise MissingRequiredArgumentError("subject_token")
if not subject_token_type:
raise MissingRequiredArgumentError("subject_token_type")
# Validate subject token format (fail fast to ensure token integrity)
tok = subject_token
if not isinstance(tok, str) or not tok.strip():
raise GetTokenByExchangeProfileError("subject_token cannot be blank or whitespace")
if tok != tok.strip():
raise GetTokenByExchangeProfileError(
"subject_token must not include leading or trailing whitespace"
)
if tok.lower().startswith("bearer "):
raise GetTokenByExchangeProfileError(
"subject_token must not include the 'Bearer ' prefix (case-insensitive check)"
)
# Require client credentials
client_id = self.options.client_id
client_secret = self.options.client_secret
if not client_id or not client_secret:
raise GetTokenByExchangeProfileError(
"Client credentials are required to use get_token_by_exchange_profile. "
"Configure client_id and client_secret in ApiClientOptions to use this feature"
)
# Discover token endpoint
metadata = await self._discover()
token_endpoint = metadata.get("token_endpoint")
if not token_endpoint:
raise GetTokenByExchangeProfileError(
"Token endpoint missing in OIDC metadata. "
"Verify your domain configuration and that the OIDC discovery endpoint "
f"(https://{self.options.domain}/.well-known/openid-configuration) is accessible"
)
# Build request parameters (client_id sent via HTTP Basic auth only)
params = {
"grant_type": TOKEN_EXCHANGE_GRANT_TYPE,
"subject_token": subject_token,
"subject_token_type": subject_token_type,
}
# Add optional parameters
if audience:
params["audience"] = audience
if scope:
params["scope"] = scope
if requested_token_type:
params["requested_token_type"] = requested_token_type
# Append extra parameters with validation
if extra:
self._apply_extra(params, extra)
# Make token exchange request
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(self.options.timeout)) as client:
response = await client.post(
token_endpoint,
data=params,
auth=(client_id, client_secret)
)
if response.status_code != 200:
error_data = {}
try:
# Lenient check for JSON error responses (handles application/json, text/json, etc.)
content_type = response.headers.get("content-type", "").lower()
if "json" in content_type:
error_data = response.json()
except ValueError:
pass # Ignore JSON parse errors, use generic error message below
raise ApiError(
error_data.get("error", "token_exchange_error"),
error_data.get(
"error_description",
f"Failed to exchange token of type '{subject_token_type}'"
+ (f" for audience '{audience}'" if audience else "")
),
response.status_code
)
try:
token_response = response.json()
except ValueError:
raise ApiError("invalid_json", "Token endpoint returned invalid JSON.", 502)
# Validate required fields
access_token = token_response.get("access_token")
if not isinstance(access_token, str) or not access_token:
raise ApiError(
"invalid_response",
"Missing or invalid access_token in response.",
502
)
# Lenient policy: coerce numeric strings like "3600" to int
# Reject non-numeric values (e.g., "not-a-number", None, objects)
# Reject negative values (prevent accidental "already expired" tokens)
expires_in_raw = token_response.get("expires_in", 3600)
try:
expires_in = int(expires_in_raw)
except (TypeError, ValueError):
raise ApiError("invalid_response", "expires_in is not an integer.", 502)
if expires_in < 0:
raise ApiError("invalid_response", "expires_in cannot be negative.", 502)
# Build response with required fields
result = {
"access_token": access_token,
"expires_in": expires_in,
"expires_at": int(time.time()) + expires_in,
}
# Add optional fields if present (preserves falsy values like empty scope)
optional_fields = ["scope", "id_token", "refresh_token", "token_type", "issued_token_type"]
for field in optional_fields:
if field in token_response:
result[field] = token_response[field]
return result
except httpx.TimeoutException as exc:
raise ApiError(
"timeout_error",
f"Request to token endpoint timed out: {str(exc)}",
504,
exc
)
except httpx.HTTPError as exc:
raise ApiError(
"network_error",
f"Network error occurred: {str(exc)}",
502,
exc
)
# ===== Private Methods =====
def _apply_extra(
self,
params: dict[str, Any],
extra: Mapping[str, Union[str, Sequence[str]]]
) -> None:
"""
Apply extra parameters to the params dict with validation.
Args:
params: The parameters dict to append to
extra: Additional parameters to append (accepts str or sequences like list/tuple)
Raises:
GetTokenByExchangeProfileError: If reserved parameter, unsupported type, or array size limit exceeded
"""
# Pre-compute lowercase reserved params for case-insensitive matching
reserved_lower = {p.lower() for p in RESERVED_PARAMS}
for k, v in extra.items():