Repository navigation
Expand file tree
/
Copy pathtest_api_client.py
More file actions
7285 lines (6066 loc) · 255 KB
/
Copy pathtest_api_client.py
File metadata and controls
7285 lines (6066 loc) · 255 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 base64
import json
import logging
import time
import httpx
import pytest
# Import shared helpers and constants from conftest
from conftest import (
DISCOVERY_URL,
JWKS_URL,
TOKEN_ENDPOINT,
InMemoryIndexedTokenStore,
InMemoryTokenStore,
assert_api_error,
assert_form_post,
assert_no_requests,
last_form,
token_success,
)
from freezegun import freeze_time
from pytest_httpx import HTTPXMock
from auth0_api_python import (
AuthServerUnavailableError,
MissingOrganizationError,
OrganizationNotAllowedError,
get_current_actor,
get_delegation_chain,
)
from auth0_api_python import __all__ as package_exports
from auth0_api_python._internal.cache_keys import (
index_cache_key,
m2m_cache_key,
obo_cache_key,
session_fingerprint,
token_vault_cache_key,
)
from auth0_api_python.api_client import MAX_ARRAY_VALUES_PER_KEY, ApiClient
from auth0_api_python.config import ApiClientOptions
from auth0_api_python.errors import (
ApiError,
ConfigurationError,
DomainsResolverError,
GetAccessTokenForConnectionError,
GetClientCredentialsTokenError,
GetTokenByExchangeProfileError,
InvalidAuthSchemeError,
InvalidDpopProofError,
MissingAuthorizationError,
MissingRequiredArgumentError,
VerifyAccessTokenError,
)
from auth0_api_python.token_store import VerifiedToken
from auth0_api_python.token_utils import (
PRIVATE_EC_JWK,
PRIVATE_JWK,
generate_dpop_proof,
generate_token,
generate_token_with_cnf,
sha256_base64url,
)
# Create public RSA JWK by selecting only public key components
PUBLIC_RSA_JWK = {k: PRIVATE_JWK[k] for k in ["kty", "n", "e", "alg", "use", "kid"] if k in PRIVATE_JWK}
# ===== Tests =====
@pytest.mark.asyncio
async def test_init_missing_args():
"""
Test that providing no audience or domain raises an error.
"""
# Empty domain now raises ConfigurationError (not MissingRequiredArgumentError)
with pytest.raises(ConfigurationError):
_ = ApiClient(ApiClientOptions(domain="", audience="some_audience"))
# Empty audience still raises MissingRequiredArgumentError
with pytest.raises(MissingRequiredArgumentError):
_ = ApiClient(ApiClientOptions(domain="example.us.auth0.com", audience=""))
@pytest.mark.asyncio
async def test_verify_access_token_successfully(httpx_mock: HTTPXMock):
"""
Test that a valid RS256 token with correct issuer, audience, iat, and exp
is verified successfully by ApiClient.
"""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience", # sets 'aud'
issuer=None, # uses default "https://auth0.local/"
iat=True,
exp=True
)
api_client = ApiClient(
ApiClientOptions(domain="auth0.local", audience="my-audience")
)
# 5) Verify the token
claims = await api_client.verify_access_token(access_token=access_token)
assert claims["sub"] == "user_123"
@pytest.mark.asyncio
async def test_verify_access_token_preserves_act_claim(httpx_mock: HTTPXMock):
"""
Test that verified access token claims expose the act claim for OBO delegation.
"""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer=None,
iat=True,
exp=True,
claims={
"act": {
"sub": "mcp_server_client_id",
"act": {
"sub": "spa_client_id",
},
},
},
)
api_client = ApiClient(
ApiClientOptions(domain="auth0.local", audience="my-audience")
)
claims = await api_client.verify_access_token(access_token=access_token)
assert claims["sub"] == "user_123"
assert claims["act"]["sub"] == "mcp_server_client_id"
assert get_current_actor(claims) == "mcp_server_client_id"
assert get_delegation_chain(claims) == [
"mcp_server_client_id",
"spa_client_id",
]
@pytest.mark.asyncio
async def test_verify_access_token_fail_no_iss():
"""
Test that a token missing 'iss' claim fails verification during pre-validation.
No HTTP mocks needed since pre-validation rejects before network calls.
"""
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer=False, # skip 'iss'
iat=True,
exp=True
)
api_client = ApiClient(
ApiClientOptions(domain="auth0.local", audience="my-audience")
)
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token=access_token)
assert "missing 'iss' claim" in str(err.value).lower()
@pytest.mark.asyncio
async def test_verify_access_token_fail_invalid_iss(httpx_mock: HTTPXMock):
"""
Test that a token with an invalid issuer fails verification.
In single-domain mode, discovery is fetched from configured domain.
First issuer validation fails before JWKS fetch.
"""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer="https://invalid-issuer.local", # mismatch
iat=True,
exp=True
)
api_client = ApiClient(
ApiClientOptions(domain="auth0.local", audience="my-audience")
)
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token=access_token)
# Should fail at first issuer validation
assert "does not match" in str(err.value).lower()
@pytest.mark.asyncio
async def test_verify_access_token_fail_no_aud(httpx_mock: HTTPXMock):
"""
Test that a token missing 'aud' claim fails verification.
"""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience=None, # no 'aud' claim
issuer=None,
iat=True,
exp=True
)
api_client = ApiClient(
ApiClientOptions(domain="auth0.local", audience="my-audience")
)
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token=access_token)
assert "aud" in str(err.value).lower() or "audience" in str(err.value).lower()
@pytest.mark.asyncio
async def test_verify_access_token_fail_invalid_aud(httpx_mock: HTTPXMock):
"""
Test that a token with an invalid audience fails verification.
"""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="wrong-aud", # mismatch from the config
issuer=None,
iat=True,
exp=True
)
api_client = ApiClient(
ApiClientOptions(domain="auth0.local", audience="my-audience")
)
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token=access_token)
error_str = str(err.value).lower()
assert "audience mismatch" in error_str or "invalid aud" in error_str
@pytest.mark.asyncio
async def test_verify_access_token_fail_no_iat(httpx_mock: HTTPXMock):
"""
Test that a token missing 'iat' claim fails verification.
"""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer=None,
iat=False, # skip iat
exp=True
)
api_client = ApiClient(
ApiClientOptions(domain="auth0.local", audience="my-audience")
)
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token=access_token)
assert "iat" in str(err.value).lower() or "missing" in str(err.value).lower()
@pytest.mark.asyncio
async def test_verify_access_token_fail_no_exp(httpx_mock: HTTPXMock):
"""
Test that a token missing 'exp' claim fails verification.
"""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer=None,
iat=True,
exp=False # skip exp
)
api_client = ApiClient(
ApiClientOptions(domain="auth0.local", audience="my-audience")
)
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token=access_token)
error_str = str(err.value).lower()
assert "exp" in error_str or "missing" in error_str
async def _verify_with_nbf(httpx_mock: HTTPXMock, nbf):
httpx_mock.add_response(method="GET", url=DISCOVERY_URL, json={"issuer": "https://auth0.local/", "jwks_uri": JWKS_URL})
httpx_mock.add_response(method="GET", url=JWKS_URL, json={"keys": [PUBLIC_RSA_JWK]})
claims = {} if nbf is None else {"nbf": nbf}
access_token = await generate_token(
domain="auth0.local", user_id="user_123", audience="my-audience", claims=claims
)
api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience"))
return await api_client.verify_access_token(access_token=access_token)
@pytest.mark.asyncio
async def test_verify_access_token_fail_nbf_in_future(httpx_mock: HTTPXMock):
"""A token whose 'nbf' is still in the future is rejected."""
with pytest.raises(VerifyAccessTokenError) as err:
await _verify_with_nbf(httpx_mock, int(time.time()) + 3600)
assert "not yet valid" in str(err.value)
@pytest.mark.asyncio
async def test_verify_access_token_succeeds_with_past_nbf(httpx_mock: HTTPXMock):
"""A token whose 'nbf' has passed is accepted."""
claims = await _verify_with_nbf(httpx_mock, int(time.time()) - 60)
assert claims["sub"] == "user_123"
@pytest.mark.asyncio
async def test_verify_access_token_succeeds_without_nbf(httpx_mock: HTTPXMock):
"""'nbf' is optional, so a token without it is accepted."""
claims = await _verify_with_nbf(httpx_mock, None)
assert "nbf" not in claims
@pytest.mark.asyncio
@freeze_time("2025-01-01T00:00:00Z")
async def test_verify_access_token_succeeds_when_nbf_equals_now(httpx_mock: HTTPXMock):
"""A token whose 'nbf' is exactly the current time is accepted."""
claims = await _verify_with_nbf(httpx_mock, int(time.time()))
assert claims["sub"] == "user_123"
@pytest.mark.asyncio
@freeze_time("2025-01-01T00:00:00Z")
async def test_verify_access_token_fail_fractional_nbf_in_future(httpx_mock: HTTPXMock):
"""A fractional 'nbf' half a second ahead is a valid number and is rejected as not yet valid."""
with pytest.raises(VerifyAccessTokenError) as err:
await _verify_with_nbf(httpx_mock, time.time() + 0.5)
assert "not yet valid" in str(err.value)
@pytest.mark.asyncio
@pytest.mark.parametrize("bad_nbf", ["soon", True, [1]])
async def test_verify_access_token_fail_non_numeric_nbf(httpx_mock: HTTPXMock, bad_nbf):
"""A non-numeric 'nbf' is rejected as an invalid token."""
with pytest.raises(VerifyAccessTokenError) as err:
await _verify_with_nbf(httpx_mock, bad_nbf)
assert "nbf" in str(err.value)
@pytest.mark.asyncio
async def test_verify_access_token_fail_no_audience_config():
"""
Test that if the ApiClient doesn't get an audience in ApiClientOptions,
it raises a MissingRequiredArgumentError or similar.
"""
with pytest.raises(MissingRequiredArgumentError) as err:
_ = ApiClient(
ApiClientOptions(domain="auth0.local", audience="")
)
error_str = str(err.value).lower()
assert "audience" in error_str and ("required" in error_str or "not provided" in error_str)
@pytest.mark.asyncio
async def test_verify_access_token_fail_malformed_token():
"""Test that a malformed token fails verification."""
api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience"))
with pytest.raises(VerifyAccessTokenError) as e:
await api_client.verify_access_token("header.payload")
assert "failed to parse token" in str(e.value).lower()
with pytest.raises(VerifyAccessTokenError) as e:
await api_client.verify_access_token("header.pay!load.signature")
assert "failed to parse token" in str(e.value).lower()
FETCH_FAILURES = [
("connect_error", True),
("http_500", True),
("http_429", True),
("http_404", False),
]
def _add_fetch_failure(httpx_mock: HTTPXMock, url: str, failure: str):
if failure == "connect_error":
httpx_mock.add_exception(httpx.ConnectError("boom"), method="GET", url=url)
else:
httpx_mock.add_response(method="GET", url=url, status_code=int(failure.split("_")[1]))
@pytest.mark.asyncio
@pytest.mark.parametrize("failure,unavailable", FETCH_FAILURES)
async def test_verify_access_token_discovery_fetch_failure_status(httpx_mock: HTTPXMock, failure, unavailable):
"""Outage-type discovery failures raise the 503 error, other failures stay a 401 invalid token."""
_add_fetch_failure(httpx_mock, DISCOVERY_URL, failure)
access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience")
api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience"))
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token)
assert isinstance(err.value, AuthServerUnavailableError) is unavailable
assert err.value.get_status_code() == (503 if unavailable else 401)
assert err.value.get_error_code() == ("auth_server_unavailable" if unavailable else "invalid_token")
@pytest.mark.asyncio
@pytest.mark.parametrize("failure,unavailable", FETCH_FAILURES)
async def test_verify_access_token_jwks_fetch_failure_status(httpx_mock: HTTPXMock, failure, unavailable):
"""Outage-type JWKS failures raise the 503 error, other failures stay a 401 invalid token."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={"issuer": "https://auth0.local/", "jwks_uri": JWKS_URL},
)
_add_fetch_failure(httpx_mock, JWKS_URL, failure)
access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience")
api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience"))
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token)
assert isinstance(err.value, AuthServerUnavailableError) is unavailable
assert err.value.get_status_code() == (503 if unavailable else 401)
assert err.value.get_error_code() == ("auth_server_unavailable" if unavailable else "invalid_token")
@pytest.mark.asyncio
async def test_verify_access_token_custom_fetch_failure_is_unavailable():
"""A custom_fetch that raises is reported as an unavailable auth server."""
async def failing_fetch(url, **kwargs):
raise ConnectionError("boom")
access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience")
api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience", custom_fetch=failing_fetch))
with pytest.raises(AuthServerUnavailableError) as err:
await api_client.verify_access_token(access_token)
assert err.value.get_status_code() == 503
@pytest.mark.asyncio
async def test_verify_access_token_custom_fetch_non_network_error_stays_invalid_token():
"""A custom_fetch that raises something other than a connection error or timeout is a 401, not an outage."""
async def broken_fetch(url, **kwargs):
raise ValueError("boom")
access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience")
api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience", custom_fetch=broken_fetch))
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(access_token)
assert not isinstance(err.value, AuthServerUnavailableError)
assert err.value.get_status_code() == 401
@pytest.mark.asyncio
async def test_verify_access_token_bad_signature_stays_invalid_token(httpx_mock: HTTPXMock):
"""A reachable tenant with a token it did not sign still fails as a 401 invalid token."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={"issuer": "https://auth0.local/", "jwks_uri": JWKS_URL},
)
httpx_mock.add_response(method="GET", url=JWKS_URL, json={"keys": [PUBLIC_RSA_JWK]})
access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience")
header, payload, signature = access_token.split(".")
tampered = f"{header}.{payload}.{signature[:-4]}AAAA"
api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience"))
with pytest.raises(VerifyAccessTokenError) as err:
await api_client.verify_access_token(tampered)
assert not isinstance(err.value, AuthServerUnavailableError)
assert err.value.get_status_code() == 401
assert err.value.get_error_code() == "invalid_token"
# ===== Organization Policy: verify_access_token Enforcement =====
@pytest.mark.asyncio
async def test_organization_policy_missing_org_id_when_required(httpx_mock: HTTPXMock):
"""Test that a token with no org_id claim is rejected when organization_policy is 'required'."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer=None,
iat=True,
exp=True,
)
api_client = ApiClient(ApiClientOptions(
domain="auth0.local",
audience="my-audience",
organization_policy="required",
))
with pytest.raises(MissingOrganizationError) as err:
await api_client.verify_access_token(access_token=access_token)
assert err.value.get_error_code() == "invalid_token"
assert err.value.get_status_code() == 401
@pytest.mark.asyncio
async def test_organization_policy_disallowed_org(httpx_mock: HTTPXMock):
"""Test that a token whose org_id is not in the allowlist is rejected."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer=None,
iat=True,
exp=True,
claims={"org_id": "org_untrusted"},
)
api_client = ApiClient(ApiClientOptions(
domain="auth0.local",
audience="my-audience",
organization_policy="required",
organization_id=["org_abc123", "org_def456"],
))
with pytest.raises(OrganizationNotAllowedError) as err:
await api_client.verify_access_token(access_token=access_token)
assert err.value.get_error_code() == "invalid_token"
assert err.value.get_status_code() == 401
assert "org_untrusted" not in str(err.value)
@pytest.mark.asyncio
async def test_organization_policy_allowed_org_succeeds(httpx_mock: HTTPXMock):
"""Test that a token with an allowlisted org_id verifies successfully."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer=None,
iat=True,
exp=True,
claims={"org_id": "org_abc123"},
)
api_client = ApiClient(ApiClientOptions(
domain="auth0.local",
audience="my-audience",
organization_policy="required",
organization_id=["org_abc123", "org_def456"],
))
claims = await api_client.verify_access_token(access_token=access_token)
assert claims["sub"] == "user_123"
assert claims["org_id"] == "org_abc123"
@pytest.mark.asyncio
async def test_organization_policy_default_allow_does_not_require_org_id(httpx_mock: HTTPXMock):
"""Test that the default 'allow' policy accepts a token with no org_id claim (no behavior change)."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={
"issuer": "https://auth0.local/",
"jwks_uri": JWKS_URL
}
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={
"keys": [
{
"kty": "RSA",
"kid": "TEST_KEY",
"n": "whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw",
"e": "AQAB",
"alg": "RS256",
"use": "sig"
}
]
}
)
access_token = await generate_token(
domain="auth0.local",
user_id="user_123",
audience="my-audience",
issuer=None,
iat=True,
exp=True,
)
api_client = ApiClient(ApiClientOptions(
domain="auth0.local",
audience="my-audience",
))
claims = await api_client.verify_access_token(access_token=access_token)
assert claims["sub"] == "user_123"
@pytest.mark.asyncio
async def test_organization_policy_single_string_allowlist(httpx_mock: HTTPXMock):
"""Test that a single string organization_id accepts a matching org_id and rejects others."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={"jwks_uri": JWKS_URL, "issuer": "https://auth0.local/"},
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={"keys": [PUBLIC_RSA_JWK]},
)
api_client = ApiClient(ApiClientOptions(
domain="auth0.local",
audience="my-audience",
organization_policy="required",
organization_id="org_abc123",
))
allowed = await generate_token(
domain="auth0.local", user_id="user_123", audience="my-audience", claims={"org_id": "org_abc123"},
)
claims = await api_client.verify_access_token(access_token=allowed)
assert claims["org_id"] == "org_abc123"
other = await generate_token(
domain="auth0.local", user_id="user_123", audience="my-audience", claims={"org_id": "org_other"},
)
with pytest.raises(OrganizationNotAllowedError):
await api_client.verify_access_token(access_token=other)
@pytest.mark.asyncio
async def test_organization_policy_required_without_allowlist_accepts_any_org(httpx_mock: HTTPXMock):
"""Test that 'required' with no allowlist accepts any token that carries an org_id."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={"jwks_uri": JWKS_URL, "issuer": "https://auth0.local/"},
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={"keys": [PUBLIC_RSA_JWK]},
)
token = await generate_token(
domain="auth0.local", user_id="user_123", audience="my-audience", claims={"org_id": "org_any"},
)
api_client = ApiClient(ApiClientOptions(
domain="auth0.local", audience="my-audience", organization_policy="required",
))
claims = await api_client.verify_access_token(access_token=token)
assert claims["org_id"] == "org_any"
@pytest.mark.asyncio
async def test_organization_policy_allow_accepts_token_with_org_id(httpx_mock: HTTPXMock):
"""Test that the default 'allow' policy accepts a token that carries an org_id."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={"jwks_uri": JWKS_URL, "issuer": "https://auth0.local/"},
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={"keys": [PUBLIC_RSA_JWK]},
)
token = await generate_token(
domain="auth0.local", user_id="user_123", audience="my-audience", claims={"org_id": "org_any"},
)
api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience"))
claims = await api_client.verify_access_token(access_token=token)
assert claims["org_id"] == "org_any"
@pytest.mark.asyncio
@pytest.mark.parametrize("org_id", [123, ["org_abc123"], "", None])
async def test_organization_policy_rejects_non_string_org_id(httpx_mock: HTTPXMock, org_id):
"""Test that an org_id claim that is not a non-empty string is treated as missing."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={"jwks_uri": JWKS_URL, "issuer": "https://auth0.local/"},
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={"keys": [PUBLIC_RSA_JWK]},
)
token = await generate_token(
domain="auth0.local", user_id="user_123", audience="my-audience", claims={"org_id": org_id},
)
api_client = ApiClient(ApiClientOptions(
domain="auth0.local",
audience="my-audience",
organization_policy="required",
organization_id=["org_abc123"],
))
with pytest.raises(MissingOrganizationError):
await api_client.verify_access_token(access_token=token)
@pytest.mark.asyncio
async def test_organization_policy_logs_rejected_org_id(httpx_mock: HTTPXMock, caplog):
"""Test that the rejected org_id is logged since it is kept out of the error message."""
httpx_mock.add_response(
method="GET",
url=DISCOVERY_URL,
json={"jwks_uri": JWKS_URL, "issuer": "https://auth0.local/"},
)
httpx_mock.add_response(
method="GET",
url=JWKS_URL,
json={"keys": [PUBLIC_RSA_JWK]},
)
token = await generate_token(
domain="auth0.local", user_id="user_123", audience="my-audience", claims={"org_id": "org_untrusted"},
)
api_client = ApiClient(ApiClientOptions(
domain="auth0.local",