-
Notifications
You must be signed in to change notification settings - Fork 7
/
api_tokens_test.py
1554 lines (1401 loc) · 50.4 KB
/
api_tokens_test.py
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
"""Tests for the ``/auth/api/v1/users/*/tokens`` and related routes."""
from __future__ import annotations
import time
from datetime import UTC, datetime, timedelta
from pathlib import Path
from unittest.mock import ANY
import pytest
from httpx import AsyncClient
from safir.datetime import current_datetime, format_datetime_for_logging
from safir.testing.slack import MockSlackWebhook
from gafaelfawr.config import Config
from gafaelfawr.constants import COOKIE_NAME, UID_BOT_MIN
from gafaelfawr.factory import Factory
from gafaelfawr.models.state import State
from gafaelfawr.models.token import Token, TokenUserInfo
from gafaelfawr.models.userinfo import Group
from ..support.config import reconfigure
from ..support.constants import TEST_HOSTNAME
from ..support.cookies import clear_session_cookie, set_session_cookie
from ..support.firestore import MockFirestore
from ..support.ldap import MockLDAP
from ..support.logging import parse_log
from ..support.tokens import create_session_token
@pytest.mark.asyncio
async def test_create_delete_modify(
client: AsyncClient, factory: Factory, caplog: pytest.LogCaptureFixture
) -> None:
user_info = TokenUserInfo(
username="example",
name="Example Person",
email="example@example.com",
uid=45613,
groups=[Group(name="foo", id=12313)],
)
token_service = factory.create_token_service()
async with factory.session.begin():
session_token = await token_service.create_session_token(
user_info,
scopes=["read:all", "exec:admin", "user:token"],
ip_address="127.0.0.1",
)
csrf = await set_session_cookie(client, session_token)
caplog.clear()
expires = current_datetime() + timedelta(days=100)
r = await client.post(
"/auth/api/v1/users/example/tokens",
headers={"X-CSRF-Token": csrf},
json={
"token_name": "some token",
"scopes": ["read:all"],
"expires": int(expires.timestamp()),
},
)
assert r.status_code == 201
assert r.json() == {"token": ANY}
user_token = Token.from_str(r.json()["token"])
token_url = r.headers["Location"]
assert token_url == f"/auth/api/v1/users/example/tokens/{user_token.key}"
# Check the logging.
assert parse_log(caplog) == [
{
"event": "Created new user token",
"httpRequest": {
"requestMethod": "POST",
"requestUrl": (
f"https://{TEST_HOSTNAME}/auth/api/v1/users/example/tokens"
),
"remoteIp": "127.0.0.1",
},
"scopes": ["exec:admin", "read:all", "user:token"],
"severity": "info",
"token": session_token.key,
"token_key": user_token.key,
"token_expires": format_datetime_for_logging(expires),
"token_name": "some token",
"token_scopes": ["read:all"],
"token_source": "cookie",
"token_userinfo": {
"email": "example@example.com",
"name": "Example Person",
"uid": 45613,
"groups": [{"id": 12313, "name": "foo"}],
},
"user": "example",
}
]
r = await client.get(token_url)
assert r.status_code == 200
info = r.json()
assert info == {
"token": user_token.key,
"username": "example",
"token_name": "some token",
"token_type": "user",
"scopes": ["read:all"],
"created": ANY,
"expires": int(expires.timestamp()),
}
# Check that this is the same information as is returned by the token-info
# route. This is a bit tricky to do since the cookie will take precedence
# over the Authorization header, but we can't just delete the cookie since
# we'll lose the CSRF token. Save the cookie and delete it, and then
# later restore it.
cookie = client.cookies.pop(COOKIE_NAME)
r = await client.get(
"/auth/api/v1/token-info",
headers={"Authorization": f"bearer {user_token}"},
)
assert r.status_code == 200
assert r.json() == info
client.cookies.set(COOKIE_NAME, cookie, domain=TEST_HOSTNAME)
# Listing all tokens for this user should return the user token and a
# session token.
r = await client.get("/auth/api/v1/users/example/tokens")
assert r.status_code == 200
data = r.json()
# Adjust for sorting, which will be by creation date and then token.
assert len(data) == 2
if data[0] == info:
session_info = data[1]
else:
assert data[1] == info
session_info = data[0]
assert session_info == {
"token": session_token.key,
"username": "example",
"token_type": "session",
"scopes": ["exec:admin", "read:all", "user:token"],
"created": ANY,
"expires": ANY,
}
# Modifying a user token fails with permission denied.
new_expires = current_datetime() + timedelta(days=200)
r = await client.patch(
token_url,
headers={"X-CSRF-Token": csrf},
json={
"token_name": "happy token",
"scopes": ["exec:admin"],
"expires": int(new_expires.timestamp()),
},
)
assert r.status_code == 403
assert r.json()["detail"][0]["type"] == "permission_denied"
# Get a token admin token, which will be allowed to modify the token.
async with factory.session.begin():
admin_token = await token_service.create_session_token(
user_info, scopes=["admin:token"], ip_address="127.0.0.1"
)
csrf = await set_session_cookie(client, admin_token)
# Change the name, scope, and expiration of the token.
caplog.clear()
new_expires = current_datetime() + timedelta(days=200)
r = await client.patch(
token_url,
headers={"X-CSRF-Token": csrf},
json={
"token_name": "happy token",
"scopes": ["exec:admin"],
"expires": int(new_expires.timestamp()),
},
)
assert r.status_code == 200
assert r.json() == {
"token": user_token.key,
"username": "example",
"token_name": "happy token",
"token_type": "user",
"scopes": ["exec:admin"],
"created": ANY,
"expires": int(new_expires.timestamp()),
}
# Check the logging. Regression test for a bug where new expirations
# would be logged as raw datetime objects instead of formatted dates.
assert parse_log(caplog) == [
{
"event": "Modified token",
"httpRequest": {
"requestMethod": "PATCH",
"requestUrl": f"https://{TEST_HOSTNAME}{token_url}",
"remoteIp": "127.0.0.1",
},
"scopes": ["admin:token"],
"severity": "info",
"token": admin_token.key,
"token_key": user_token.key,
"token_expires": format_datetime_for_logging(new_expires),
"token_name": "happy token",
"token_scopes": ["exec:admin"],
"token_source": "cookie",
"user": "example",
}
]
# Go back to the previous authentication and delete the token.
csrf = await set_session_cookie(client, session_token)
caplog.clear()
r = await client.delete(token_url, headers={"X-CSRF-Token": csrf})
assert r.status_code == 204
r = await client.get(token_url)
assert r.status_code == 404
# Check the logging.
assert parse_log(caplog) == [
{
"event": "Deleted token",
"httpRequest": {
"requestMethod": "DELETE",
"requestUrl": f"https://{TEST_HOSTNAME}{token_url}",
"remoteIp": "127.0.0.1",
},
"scopes": ["exec:admin", "read:all", "user:token"],
"severity": "info",
"token": session_token.key,
"token_key": user_token.key,
"token_source": "cookie",
"token_username": "example",
"user": "example",
}
]
# Deleting again should return 404.
r = await client.delete(token_url, headers={"X-CSRF-Token": csrf})
assert r.status_code == 404
# This user should now have just the two session tokens we created.
r = await client.get("/auth/api/v1/users/example/tokens")
assert r.status_code == 200
assert len(r.json()) == 2
# We should be able to see the change history for the token.
r = await client.get(token_url + "/change-history")
assert r.status_code == 200
assert r.json() == [
{
"token": user_token.key,
"username": "example",
"token_type": "user",
"token_name": "happy token",
"scopes": ["exec:admin"],
"expires": int(new_expires.timestamp()),
"actor": "example",
"action": "revoke",
"ip_address": "127.0.0.1",
"event_time": ANY,
},
{
"token": user_token.key,
"username": "example",
"token_type": "user",
"token_name": "happy token",
"scopes": ["exec:admin"],
"expires": int(new_expires.timestamp()),
"actor": "example",
"action": "edit",
"old_token_name": "some token",
"old_scopes": ["read:all"],
"old_expires": int(expires.timestamp()),
"ip_address": "127.0.0.1",
"event_time": ANY,
},
{
"token": user_token.key,
"username": "example",
"token_type": "user",
"token_name": "some token",
"scopes": ["read:all"],
"expires": int(expires.timestamp()),
"actor": "example",
"action": "create",
"ip_address": "127.0.0.1",
"event_time": ANY,
},
]
@pytest.mark.asyncio
async def test_token_info(
client: AsyncClient, config: Config, factory: Factory
) -> None:
user_info = TokenUserInfo(
username="example",
name="Example Person",
email="example@example.com",
uid=45613,
gid=12345,
groups=[Group(name="foo", id=12313)],
)
token_service = factory.create_token_service()
async with factory.session.begin():
session_token = await token_service.create_session_token(
user_info,
scopes=["exec:admin", "user:token"],
ip_address="127.0.0.1",
)
r = await client.get(
"/auth/api/v1/token-info",
headers={"Authorization": f"bearer {session_token}"},
)
assert r.status_code == 200
data = r.json()
assert data == {
"token": session_token.key,
"username": "example",
"token_type": "session",
"scopes": ["exec:admin", "user:token"],
"created": ANY,
"expires": ANY,
}
now = current_datetime()
created = datetime.fromtimestamp(data["created"], tz=UTC)
assert now - timedelta(seconds=5) <= created <= now
expires = created + config.token_lifetime
assert datetime.fromtimestamp(data["expires"], tz=UTC) == expires
r = await client.get(
"/auth/api/v1/user-info",
headers={"Authorization": f"bearer {session_token}"},
)
assert r.status_code == 200
session_user_info = r.json()
assert session_user_info == {
"username": "example",
"name": "Example Person",
"email": "example@example.com",
"uid": 45613,
"gid": 12345,
"groups": [{"name": "foo", "id": 12313}],
}
# Check the same with a user token, which has some additional associated
# data.
expires = now + timedelta(days=100)
data = await token_service.get_data(session_token)
async with factory.session.begin():
user_token = await token_service.create_user_token(
data,
data.username,
token_name="some-token",
scopes=["exec:admin"],
expires=expires,
ip_address="127.0.0.1",
)
r = await client.get(
"/auth/api/v1/token-info",
headers={"Authorization": f"bearer {user_token}"},
)
assert r.status_code == 200
data = r.json()
assert data == {
"token": user_token.key,
"username": "example",
"token_type": "user",
"token_name": "some-token",
"scopes": ["exec:admin"],
"created": ANY,
"expires": int(expires.timestamp()),
}
r = await client.get(
"/auth/api/v1/user-info",
headers={"Authorization": f"bearer {user_token}"},
)
assert r.status_code == 200
assert r.json() == session_user_info
# Test getting a list of tokens for a user.
state = State(token=session_token)
client.cookies.set(COOKIE_NAME, state.to_cookie(), domain=TEST_HOSTNAME)
r = await client.get("/auth/api/v1/users/example/tokens")
@pytest.mark.asyncio
async def test_auth_required(
client: AsyncClient, factory: Factory, mock_slack: MockSlackWebhook
) -> None:
token_data = await create_session_token(factory)
token = token_data.token
csrf = await set_session_cookie(client, token)
# Replace the cookie with one containing the CSRF token but not the
# authentication token.
clear_session_cookie(client)
client.cookies[COOKIE_NAME] = State(csrf=csrf).to_cookie()
r = await client.post(
"/auth/api/v1/tokens",
headers={"X-CSRF-Token": csrf},
json={"username": "bot-foo", "token_type": "service"},
)
assert r.status_code == 401
r = await client.get("/auth/api/v1/users/example/tokens")
assert r.status_code == 401
r = await client.post(
"/auth/api/v1/users/example/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token"},
)
assert r.status_code == 401
r = await client.get(f"/auth/api/v1/users/example/tokens/{token.key}")
assert r.status_code == 401
r = await client.get(
f"/auth/api/v1/users/example/tokens/{token.key}/change-history"
)
assert r.status_code == 401
r = await client.delete(
f"/auth/api/v1/users/example/tokens/{token.key}",
headers={"X-CSRF-Token": csrf},
)
assert r.status_code == 401
r = await client.patch(
f"/auth/api/v1/users/example/tokens/{token.key}",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token"},
)
assert r.status_code == 401
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_csrf_required(
client: AsyncClient, factory: Factory, mock_slack: MockSlackWebhook
) -> None:
token_data = await create_session_token(factory, scopes=["admin:token"])
csrf = await set_session_cookie(client, token_data.token)
token_service = factory.create_token_service()
async with factory.session.begin():
user_token = await token_service.create_user_token(
token_data,
token_data.username,
token_name="foo",
scopes=[],
ip_address="127.0.0.1",
)
r = await client.post(
"/auth/api/v1/tokens",
json={"username": "bot-foo", "token_type": "service"},
)
assert r.status_code == 403
r = await client.post(
"/auth/api/v1/tokens",
headers={"X-CSRF-Token": f"XXX{csrf}"},
json={"username": "bot-foo", "token_type": "service"},
)
assert r.status_code == 403
r = await client.post(
"/auth/api/v1/users/example/tokens", json={"token_name": "some token"}
)
assert r.status_code == 403
r = await client.post(
"/auth/api/v1/users/example/tokens",
headers={"X-CSRF-Token": f"XXX{csrf}"},
json={"token_name": "some token"},
)
assert r.status_code == 403
r = await client.delete(
f"/auth/api/v1/users/example/tokens/{user_token.key}"
)
assert r.status_code == 403
r = await client.delete(
f"/auth/api/v1/users/example/tokens/{user_token.key}",
headers={"X-CSRF-Token": f"XXX{csrf}"},
)
assert r.status_code == 403
r = await client.patch(
f"/auth/api/v1/users/example/tokens/{user_token.key}",
json={"token_name": "some token"},
)
assert r.status_code == 403
r = await client.patch(
f"/auth/api/v1/users/example/tokens/{user_token.key}",
headers={"X-CSRF-Token": f"XXX{csrf}"},
json={"token_name": "some token"},
)
assert r.status_code == 403
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_no_bootstrap(
client: AsyncClient,
config: Config,
factory: Factory,
mock_slack: MockSlackWebhook,
) -> None:
token_data = await create_session_token(factory)
token = token_data.token
bootstrap_token = str(config.bootstrap_token)
r = await client.get(
"/auth/api/v1/users/example/tokens",
headers={"Authorization": f"bearer {bootstrap_token}"},
)
assert r.status_code == 401
r = await client.post(
"/auth/api/v1/users/example/tokens",
headers={"Authorization": f"bearer {bootstrap_token}"},
json={"token_name": "some token"},
)
assert r.status_code == 401
r = await client.get(
f"/auth/api/v1/users/example/tokens/{token.key}",
headers={"Authorization": f"bearer {bootstrap_token}"},
)
assert r.status_code == 401
r = await client.delete(
f"/auth/api/v1/users/example/tokens/{token.key}",
headers={"Authorization": f"bearer {bootstrap_token}"},
)
assert r.status_code == 401
r = await client.patch(
f"/auth/api/v1/users/example/tokens/{token.key}",
headers={"Authorization": f"bearer {bootstrap_token}"},
json={"token_name": "some token"},
)
assert r.status_code == 401
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_no_scope(
client: AsyncClient, factory: Factory, mock_slack: MockSlackWebhook
) -> None:
token_data = await create_session_token(factory)
token_service = factory.create_token_service()
async with factory.session.begin():
token = await token_service.create_user_token(
token_data,
token_data.username,
token_name="user",
scopes=[],
ip_address="127.0.0.1",
)
r = await client.get(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"Authorization": f"bearer {token}"},
)
assert r.status_code == 403
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"Authorization": f"bearer {token}"},
json={"token_name": "some token"},
)
assert r.status_code == 403
r = await client.get(
f"/auth/api/v1/users/{token_data.username}/tokens/{token.key}",
headers={"Authorization": f"bearer {token}"},
)
assert r.status_code == 403
r = await client.delete(
f"/auth/api/v1/users/{token_data.username}/tokens/{token.key}",
headers={"Authorization": f"bearer {token}"},
)
assert r.status_code == 403
r = await client.patch(
f"/auth/api/v1/users/{token_data.username}/tokens/{token.key}",
headers={"Authorization": f"bearer {token}"},
json={"token_name": "some token"},
)
assert r.status_code == 403
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_modify_nonuser(
client: AsyncClient, factory: Factory, mock_slack: MockSlackWebhook
) -> None:
token_data = await create_session_token(factory)
token = token_data.token
csrf = await set_session_cookie(client, token)
r = await client.patch(
f"/auth/api/v1/users/{token_data.username}/tokens/{token.key}",
headers={"X-CSRF-Token": csrf},
json={"token_name": "happy token"},
)
assert r.status_code == 403
assert r.json()["detail"][0]["type"] == "permission_denied"
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_wrong_user(
client: AsyncClient, factory: Factory, mock_slack: MockSlackWebhook
) -> None:
token_data = await create_session_token(factory)
csrf = await set_session_cookie(client, token_data.token)
token_service = factory.create_token_service()
user_info = TokenUserInfo(
username="other-person", name="Some Other Person", uid=137123
)
async with factory.session.begin():
other_session_token = await token_service.create_session_token(
user_info, scopes=["user:token"], ip_address="127.0.0.1"
)
other_session_data = await token_service.get_data(other_session_token)
assert other_session_data
async with factory.session.begin():
other_token = await token_service.create_user_token(
other_session_data,
"other-person",
token_name="foo",
scopes=[],
ip_address="127.0.0.1",
)
# Get a token list.
r = await client.get("/auth/api/v1/users/other-person/tokens")
assert r.status_code == 403
assert r.json()["detail"][0]["type"] == "permission_denied"
# Create a new user token.
r = await client.post(
"/auth/api/v1/users/other-person/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "happy token"},
)
assert r.status_code == 403
assert r.json()["detail"][0]["type"] == "permission_denied"
# Get an individual token.
r = await client.get(
f"/auth/api/v1/users/other-person/tokens/{other_token.key}"
)
assert r.status_code == 403
assert r.json()["detail"][0]["type"] == "permission_denied"
# Get the history of an individual token.
r = await client.get(
f"/auth/api/v1/users/other-person/tokens/{other_token.key}"
"/change-history"
)
assert r.status_code == 403
assert r.json()["detail"][0]["type"] == "permission_denied"
# Ensure you can't see someone else's token under your username either.
r = await client.get(
f"/auth/api/v1/users/{token_data.username}/tokens/{other_token.key}"
)
assert r.status_code == 404
# Or their history.
r = await client.get(
f"/auth/api/v1/users/{token_data.username}/tokens/{other_token.key}"
"/change-history"
)
assert r.status_code == 404
# Delete a token.
r = await client.delete(
f"/auth/api/v1/users/other-person/tokens/{other_token.key}",
headers={"X-CSRF-Token": csrf},
)
assert r.status_code == 403
assert r.json()["detail"][0]["type"] == "permission_denied"
r = await client.delete(
f"/auth/api/v1/users/{token_data.username}/tokens/{other_token.key}",
headers={"X-CSRF-Token": csrf},
)
assert r.status_code == 404
# Modify a token.
r = await client.patch(
f"/auth/api/v1/users/other-person/tokens/{other_token.key}",
json={"token_name": "happy token"},
headers={"X-CSRF-Token": csrf},
)
assert r.status_code == 403
assert r.json()["detail"][0]["type"] == "permission_denied"
r = await client.patch(
f"/auth/api/v1/users/{token_data.username}/tokens/{other_token.key}",
json={"token_name": "happy token"},
headers={"X-CSRF-Token": csrf},
)
assert r.status_code == 404
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_no_expires(client: AsyncClient, factory: Factory) -> None:
"""Test creating a user token that doesn't expire."""
token_data = await create_session_token(
factory, scopes=["admin:token", "user:token"]
)
csrf = await set_session_cookie(client, token_data.token)
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token"},
)
assert r.status_code == 201
token_url = r.headers["Location"]
r = await client.get(token_url)
assert "expires" not in r.json()
# Create a user token with an expiration and then adjust it to not expire.
now = current_datetime()
expires = now + timedelta(days=2)
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={
"token_name": "another token",
"expires": int(expires.timestamp()),
},
)
assert r.status_code == 201
user_token = Token.from_str(r.json()["token"])
token_service = factory.create_token_service()
user_token_data = await token_service.get_data(user_token)
assert user_token_data
assert user_token_data.expires == expires
token_url = r.headers["Location"]
r = await client.get(token_url)
assert r.json()["expires"] == int(expires.timestamp())
r = await client.patch(
token_url, headers={"X-CSRF-Token": csrf}, json={"expires": None}
)
assert r.status_code == 200
assert "expires" not in r.json()
# Check that the expiration was also changed in Redis.
user_token_data = await token_service.get_data(user_token)
assert user_token_data
assert user_token_data.expires is None
@pytest.mark.asyncio
async def test_duplicate_token_name(
client: AsyncClient, factory: Factory, mock_slack: MockSlackWebhook
) -> None:
"""Test duplicate token names."""
token_data = await create_session_token(
factory, scopes=["admin:token", "user:token"]
)
csrf = await set_session_cookie(client, token_data.token)
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token"},
)
assert r.status_code == 201
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token"},
)
assert r.status_code == 422
assert r.json()["detail"][0]["type"] == "duplicate_token_name"
# Create a token with a different name and then try to modify the name to
# conflict.
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "another token"},
)
assert r.status_code == 201
token_url = r.headers["Location"]
r = await client.patch(
token_url,
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token"},
)
assert r.status_code == 422
assert r.json()["detail"][0]["type"] == "duplicate_token_name"
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_bad_expires(
client: AsyncClient, factory: Factory, mock_slack: MockSlackWebhook
) -> None:
"""Test creating or modifying a token with bogus expirations."""
token_data = await create_session_token(
factory, scopes=["user:token", "admin:token"]
)
csrf = await set_session_cookie(client, token_data.token)
now = int(time.time())
bad_expires = [-now, -1, 0, now, now + (5 * 60) - 1]
for bad_expire in bad_expires:
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token", "expires": bad_expire},
)
assert r.status_code == 422
data = r.json()
assert data["detail"][0]["loc"] == ["body", "expires"]
assert data["detail"][0]["type"] == "invalid_expires"
# Create a valid token.
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token"},
)
assert r.status_code == 201
token_url = r.headers["Location"]
# Now try modifying the expiration time to the same bogus values.
for bad_expire in bad_expires:
r = await client.patch(
token_url,
headers={"X-CSRF-Token": csrf},
json={"expires": bad_expire},
)
assert r.status_code == 422
data = r.json()
assert data["detail"][0]["loc"] == ["body", "expires"]
assert data["detail"][0]["type"] == "invalid_expires"
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_bad_scopes(
client: AsyncClient,
config: Config,
factory: Factory,
mock_slack: MockSlackWebhook,
) -> None:
"""Test creating or modifying a token with bogus scopes."""
known_scopes = list(config.known_scopes.keys())
assert len(known_scopes) > 4
token_data = await create_session_token(
factory, scopes=known_scopes[:3] + ["other:scope", "user:token"]
)
csrf = await set_session_cookie(client, token_data.token)
# Check that we reject both an unknown scope and a scope that's present on
# the session but isn't valid in the configuration.
for bad_scope in ("some:random-thing", "other:scope"):
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token", "scopes": [bad_scope]},
)
assert r.status_code == 422
data = r.json()
assert data["detail"][0]["loc"] == ["body", "scopes"]
assert data["detail"][0]["type"] == "invalid_scopes"
# Create a valid token with all of the scopes as the session.
r = await client.post(
f"/auth/api/v1/users/{token_data.username}/tokens",
headers={"X-CSRF-Token": csrf},
json={"token_name": "some token", "scopes": known_scopes[:3]},
)
assert r.status_code == 201
token_url = r.headers["Location"]
# Now try modifying it with the invalid scope.
for bad_scope in ("some:random-thing", "other:scope"):
r = await client.patch(
token_url,
headers={"X-CSRF-Token": csrf},
json={"scopes": [known_scopes[1], bad_scope]},
)
assert r.status_code == 422
data = r.json()
assert data["detail"][0]["loc"] == ["body", "scopes"]
assert data["detail"][0]["type"] == "invalid_scopes"
# None of these errors should have resulted in Slack alerts.
assert mock_slack.messages == []
@pytest.mark.asyncio
async def test_create_admin(
client: AsyncClient,
config: Config,
factory: Factory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test creating a token through the admin interface."""
token_data = await create_session_token(factory, scopes=["exec:admin"])
csrf = await set_session_cookie(client, token_data.token)
r = await client.post(
"/auth/api/v1/tokens",
headers={"X-CSRF-Token": csrf},
json={"username": "bot-a-service", "token_type": "service"},
)
assert r.status_code == 403
token_data = await create_session_token(factory, scopes=["admin:token"])
csrf = await set_session_cookie(client, token_data.token)
# Intentionally pass in a datetime with microseconds. They should be
# stripped off so that the expiration is rounded to seconds, which we will
# check when examining the log message.
now = current_datetime(microseconds=True)
expires = now + timedelta(days=2)
caplog.clear()
r = await client.post(
"/auth/api/v1/tokens",
headers={"X-CSRF-Token": csrf},
json={
"username": "bot-a-service",
"token_type": "service",
"scopes": ["admin:token"],
"expires": expires.isoformat(),
"name": "A Service",
"uid": 1234,
"gid": 4567,
"email": "service@example.com",
"groups": [{"name": "some-group", "id": 12381}],
},
)
assert r.status_code == 201
assert r.json() == {"token": ANY}
service_token = Token.from_str(r.json()["token"])
token_url = f"/auth/api/v1/users/bot-a-service/tokens/{service_token.key}"
assert r.headers["Location"] == token_url
# Check the logging.
expected_expires = expires.replace(microsecond=0)
assert parse_log(caplog) == [
{
"event": "Created new service token",
"httpRequest": {
"requestMethod": "POST",
"requestUrl": f"https://{TEST_HOSTNAME}/auth/api/v1/tokens",
"remoteIp": "127.0.0.1",
},
"scopes": ["admin:token"],
"severity": "info",
"token": token_data.token.key,
"token_key": service_token.key,
"token_expires": format_datetime_for_logging(expected_expires),
"token_scopes": ["admin:token"],
"token_source": "cookie",
"token_userinfo": {
"name": "A Service",
"email": "service@example.com",
"uid": 1234,
"gid": 4567,