forked from MeltanoLabs/tap-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_authenticator.py
More file actions
1260 lines (1107 loc) · 48.5 KB
/
test_authenticator.py
File metadata and controls
1260 lines (1107 loc) · 48.5 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 logging
import re
from datetime import datetime, timedelta, timezone
from unittest.mock import MagicMock, patch
import pytest
import requests
import requests.exceptions
from singer_sdk.streams import RESTStream
from tap_github.authenticator import (
AppTokenManager,
GitHubTokenAuthenticator,
PersonalTokenManager,
TokenManager,
)
def _now():
return datetime.now(tz=timezone.utc)
class TestTokenManager:
def test_default_rate_limits(self):
token_manager = TokenManager("mytoken", rate_limit_buffer=700)
assert token_manager.rate_limit == 5000
assert token_manager.rate_limit_remaining == 5000
assert token_manager.rate_limit_reset is None
assert token_manager.rate_limit_used == 0
assert token_manager.rate_limit_buffer == 700
token_manager_2 = TokenManager("mytoken")
assert token_manager_2.rate_limit_buffer == 1000
def test_update_rate_limit(self):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "4999",
"X-RateLimit-Reset": "1372700873",
"X-RateLimit-Used": "1",
}
token_manager = TokenManager("mytoken")
token_manager.update_rate_limit(mock_response_headers)
assert token_manager.rate_limit == 5000
assert token_manager.rate_limit_remaining == 4999
assert token_manager.rate_limit_reset == datetime(
2013,
7,
1,
17,
47,
53,
tzinfo=timezone.utc,
)
assert token_manager.rate_limit_used == 1
def test_is_valid_token_successful(self):
with patch("requests.get") as mock_get:
mock_response = mock_get.return_value
mock_response.raise_for_status.return_value = None
token_manager = TokenManager("validtoken")
assert token_manager.is_valid_token()
mock_get.assert_called_once_with(
url="https://api.github.com/rate_limit",
headers={"Authorization": "token validtoken"},
)
def test_is_valid_token_failure(self, caplog: pytest.LogCaptureFixture):
with patch("requests.get") as mock_get:
# Setup for a failed request
mock_response = mock_get.return_value
mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError()
mock_response.status_code = 401
mock_response.content = b"Unauthorized Access"
mock_response.reason = "Unauthorized"
token_manager = TokenManager("invalidtoken")
with caplog.at_level(logging.WARNING):
assert not token_manager.is_valid_token()
assert "401" in caplog.text
def test_has_calls_remaining_succeeds_if_token_never_used(self):
token_manager = TokenManager("mytoken")
assert token_manager.has_calls_remaining()
def test_has_calls_remaining_succeeds_if_lots_remaining(self):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "4999",
"X-RateLimit-Reset": "1372700873",
"X-RateLimit-Used": "1",
}
token_manager = TokenManager("mytoken")
token_manager.update_rate_limit(mock_response_headers)
assert token_manager.has_calls_remaining()
def test_has_calls_remaining_succeeds_if_reset_time_reached(self):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "1",
"X-RateLimit-Reset": "1372700873",
"X-RateLimit-Used": "4999",
}
token_manager = TokenManager("mytoken", rate_limit_buffer=1000)
token_manager.update_rate_limit(mock_response_headers)
assert token_manager.has_calls_remaining()
def test_has_calls_remaining_fails_if_few_calls_remaining_and_reset_time_not_reached( # noqa: E501
self,
):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "1",
"X-RateLimit-Reset": str(int((_now() + timedelta(days=100)).timestamp())),
"X-RateLimit-Used": "4999",
}
token_manager = TokenManager("mytoken", rate_limit_buffer=1000)
token_manager.update_rate_limit(mock_response_headers)
assert not token_manager.has_calls_remaining()
class TestAppTokenManager:
def test_initialization_with_3_part_env_key(self):
with patch.object(AppTokenManager, "claim_token", return_value=None):
token_manager = AppTokenManager("12345;;key\\ncontent;;67890")
assert token_manager.github_app_id == "12345"
assert token_manager.github_private_key == "key\ncontent"
assert token_manager.github_installation_id == "67890"
def test_initialization_with_2_part_env_key(self):
with patch.object(AppTokenManager, "claim_token", return_value=None):
token_manager = AppTokenManager("12345;;key\\ncontent")
assert token_manager.github_app_id == "12345"
assert token_manager.github_private_key == "key\ncontent"
assert token_manager.github_installation_id is None
def test_initialization_with_malformed_env_key(self):
expected_error_expression = re.escape(
"GITHUB_APP_PRIVATE_KEY could not be parsed. The expected format is "
'":app_id:;;-----BEGIN RSA PRIVATE KEY-----\\n_YOUR_P_KEY_\\n-----END RSA PRIVATE KEY-----"' # noqa: E501
)
with pytest.raises(ValueError, match=expected_error_expression):
AppTokenManager("12345key\\ncontent")
def test_generate_token_with_invalid_credentials(self):
with (
patch.object(AppTokenManager, "is_valid_token", return_value=False),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("some_token", MagicMock()),
),
):
token_manager = AppTokenManager("12345;;key\\ncontent;;67890")
assert token_manager.token is None
assert token_manager.token_expires_at is None
def test_successful_token_generation(self):
token_time = MagicMock()
with (
patch.object(AppTokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("valid_token", token_time),
),
):
token_manager = AppTokenManager("12345;;key\\ncontent;;67890")
token_manager.claim_token()
assert token_manager.token == "valid_token"
assert token_manager.token_expires_at == token_time
def test_has_calls_remaining_regenerates_a_token_if_close_to_expiry(
self,
caplog: pytest.LogCaptureFixture,
):
unexpired_time = _now() + timedelta(days=1)
expired_time = _now() - timedelta(days=1)
with (
patch.object(AppTokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("valid_token", unexpired_time),
),
):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "4999",
"X-RateLimit-Reset": "1372700873",
"X-RateLimit-Used": "1",
}
token_manager = AppTokenManager("12345;;key\\ncontent;;67890")
token_manager.token_expires_at = expired_time
token_manager.update_rate_limit(mock_response_headers)
with caplog.at_level(logging.INFO):
assert token_manager.has_calls_remaining()
# calling has_calls_remaining() will trigger the token generation function to be called again, # noqa: E501
# so token_expires_at should have been reset back to the mocked unexpired_time # noqa: E501
assert token_manager.token_expires_at == unexpired_time
assert "GitHub app token refresh succeeded." in caplog.text
def test_has_calls_remaining_logs_warning_if_token_regeneration_fails(
self, caplog: pytest.LogCaptureFixture
):
unexpired_time = _now() + timedelta(days=1)
expired_time = _now() - timedelta(days=1)
with (
patch.object(
AppTokenManager, "is_valid_token", return_value=True
) as mock_is_valid,
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("valid_token", unexpired_time),
),
):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "4999",
"X-RateLimit-Reset": "1372700873",
"X-RateLimit-Used": "1",
}
token_manager = AppTokenManager("12345;;key\\ncontent;;67890")
token_manager.token_expires_at = expired_time
token_manager.update_rate_limit(mock_response_headers)
mock_is_valid.return_value = False
with caplog.at_level(logging.WARNING):
assert not token_manager.has_calls_remaining()
assert "GitHub app token refresh failed." in caplog.text
def test_has_calls_remaining_succeeds_if_token_new_and_never_used(self):
unexpired_time = _now() + timedelta(days=1)
with (
patch.object(AppTokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("valid_token", unexpired_time),
),
):
token_manager = AppTokenManager("12345;;key\\ncontent;;67890")
assert token_manager.has_calls_remaining()
def test_has_calls_remaining_succeeds_if_time_and_requests_left(self):
unexpired_time = _now() + timedelta(days=1)
with (
patch.object(AppTokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("valid_token", unexpired_time),
),
):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "4999",
"X-RateLimit-Reset": "1372700873",
"X-RateLimit-Used": "1",
}
token_manager = AppTokenManager("12345;;key\\ncontent;;67890")
token_manager.update_rate_limit(mock_response_headers)
assert token_manager.has_calls_remaining()
def test_has_calls_remaining_succeeds_if_time_left_and_reset_time_reached(self):
unexpired_time = _now() + timedelta(days=1)
with (
patch.object(AppTokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("valid_token", unexpired_time),
),
):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "1",
"X-RateLimit-Reset": "1372700873",
"X-RateLimit-Used": "4999",
}
token_manager = AppTokenManager(
"12345;;key\\ncontent;;67890", rate_limit_buffer=1000
)
token_manager.update_rate_limit(mock_response_headers)
assert token_manager.has_calls_remaining()
def test_has_calls_remaining_fails_if_time_left_and_few_calls_remaining_and_reset_time_not_reached( # noqa: E501
self,
):
unexpired_time = _now() + timedelta(days=1)
with (
patch.object(AppTokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("valid_token", unexpired_time),
),
):
mock_response_headers = {
"X-RateLimit-Limit": "5000",
"X-RateLimit-Remaining": "1",
"X-RateLimit-Reset": str(
int((_now() + timedelta(days=100)).timestamp())
),
"X-RateLimit-Used": "4999",
}
token_manager = AppTokenManager(
"12345;;key\\ncontent;;67890", rate_limit_buffer=1000
)
token_manager.update_rate_limit(mock_response_headers)
assert not token_manager.has_calls_remaining()
@pytest.fixture
def mock_stream():
stream = MagicMock(spec=RESTStream)
stream.tap_name = "tap_github"
stream.config = {"rate_limit_buffer": 5}
return stream
class TestGitHubTokenAuthenticator:
@staticmethod
def _count_total_tokens(token_managers):
"""Count total tokens across all organizations."""
return sum(len(tokens) for tokens in token_managers.values())
@staticmethod
def _flatten_token_managers(token_managers):
"""Flatten token_managers dict to a list of all TokenManager objects."""
return [tm for tokens in token_managers.values() for tm in tokens]
def test_prepare_tokens_returns_empty_if_none_found(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={"GITHUB_TLJKJFDS": "gt1"},
),
patch.object(PersonalTokenManager, "is_valid_token", return_value=True),
):
auth = GitHubTokenAuthenticator.from_stream(stream=mock_stream)
token_managers = auth.prepare_tokens()
assert len(token_managers) == 0
def test_config_auth_token_only(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={"OTHER_TOKEN": "blah", "NOT_THE_RIGHT_TOKEN": "meh"},
),
patch.object(PersonalTokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update({"auth_token": "gt5"})
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 1
assert token_managers[None][0].token == "gt5"
def test_config_additional_auth_tokens_only(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={"OTHER_TOKEN": "blah", "NOT_THE_RIGHT_TOKEN": "meh"},
),
patch.object(PersonalTokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update({"additional_auth_tokens": ["gt7", "gt8", "gt9"]})
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 3
all_tokens = self._flatten_token_managers(token_managers)
assert sorted({tm.token for tm in all_tokens}) == ["gt7", "gt8", "gt9"]
def test_env_personal_tokens_only(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={
"GITHUB_TOKEN1": "gt1",
"GITHUB_TOKENxyz": "gt2",
"OTHER_TOKEN": "blah",
},
),
patch.object(PersonalTokenManager, "is_valid_token", return_value=True),
):
auth = GitHubTokenAuthenticator.from_stream(stream=mock_stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 2
all_tokens = self._flatten_token_managers(token_managers)
assert sorted({tm.token for tm in all_tokens}) == ["gt1", "gt2"]
def test_config_app_keys(self, mock_stream):
def generate_token_mock(app_id, private_key, installation_id):
return (f"installationtokenfor{app_id}", MagicMock())
with (
patch.object(TokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
side_effect=generate_token_mock,
),
):
stream = mock_stream
stream.config.update(
{
"auth_token": "gt5",
"additional_auth_tokens": ["gt7", "gt8", "gt9"],
"auth_app_keys": [
"123;;gak1;;13",
"456;;gak1;;46",
"789;;gak1;;79",
],
}
)
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 7
all_tokens = self._flatten_token_managers(token_managers)
app_token_managers = {
tm for tm in all_tokens if isinstance(tm, AppTokenManager)
}
assert len(app_token_managers) == 3
app_tokens = {tm.token for tm in app_token_managers}
assert app_tokens == {
"installationtokenfor123",
"installationtokenfor456",
"installationtokenfor789",
}
def test_env_app_key_only(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={
"GITHUB_APP_PRIVATE_KEY": "123;;key",
"OTHER_TOKEN": "blah",
},
),
patch.object(AppTokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("installationtoken12345", MagicMock()),
),
):
auth = GitHubTokenAuthenticator.from_stream(stream=mock_stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 1
assert token_managers[None][0].token == "installationtoken12345"
def test_all_token_types(self, mock_stream):
# Expectations:
# - the presence of additional_auth_tokens causes personal tokens in the environment to be ignored. # noqa: E501
# - the other types all coexist
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={
"GITHUB_TOKEN1": "gt1",
"GITHUB_TOKENxyz": "gt2",
"GITHUB_APP_PRIVATE_KEY": "123;;key;;install_id",
"OTHER_TOKEN": "blah",
},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("installationtoken12345", MagicMock()),
),
):
stream = mock_stream
stream.config.update(
{
"auth_token": "gt5",
"additional_auth_tokens": ["gt7", "gt8", "gt9"],
}
)
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 5
all_tokens = self._flatten_token_managers(token_managers)
assert sorted({tm.token for tm in all_tokens}) == [
"gt5",
"gt7",
"gt8",
"gt9",
"installationtoken12345",
]
def test_all_token_types_except_additional_auth_tokens(self, mock_stream):
# Expectations:
# - in the absence of additional_auth_tokens, all the other types can coexist
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={
"GITHUB_TOKEN1": "gt1",
"GITHUB_TOKENxyz": "gt2",
"GITHUB_APP_PRIVATE_KEY": "123;;key;;install_id",
"OTHER_TOKEN": "blah",
},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("installationtoken12345", MagicMock()),
),
):
stream = mock_stream
stream.config.update(
{
"auth_token": "gt5",
}
)
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 4
all_tokens = self._flatten_token_managers(token_managers)
assert sorted({tm.token for tm in all_tokens}) == [
"gt1",
"gt2",
"gt5",
"installationtoken12345",
]
def test_auth_token_and_additional_auth_tokens_deduped(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={
"GITHUB_TOKEN1": "gt1",
"GITHUB_TOKENxyz": "gt2",
"OTHER_TOKEN": "blah",
},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("installationtoken12345", MagicMock()),
),
):
stream = mock_stream
stream.config.update(
{
"auth_token": "gt1",
"additional_auth_tokens": ["gt1", "gt1", "gt8", "gt8", "gt9"],
}
)
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 3
all_tokens = self._flatten_token_managers(token_managers)
assert sorted({tm.token for tm in all_tokens}) == ["gt1", "gt8", "gt9"]
def test_auth_token_and_env_tokens_deduped(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={
"GITHUB_TOKEN1": "gt1",
"GITHUB_TOKENa": "gt2",
"GITHUB_TOKENxyz": "gt2",
"OTHER_TOKEN": "blah",
},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("installationtoken12345", MagicMock()),
),
):
stream = mock_stream
stream.config.update({"auth_token": "gt1"})
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
assert self._count_total_tokens(token_managers) == 2
all_tokens = self._flatten_token_managers(token_managers)
assert sorted({tm.token for tm in all_tokens}) == ["gt1", "gt2"]
def test_handle_error_if_app_key_invalid(
self,
mock_stream,
caplog: pytest.LogCaptureFixture,
):
# Confirm expected behaviour if an error is raised while setting up the app token manager: # noqa: E501
# - don"t crash
# - print the error as a warning
# - continue with any other obtained tokens
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={"GITHUB_APP_PRIVATE_KEY": "123garbagekey"},
),
patch("tap_github.authenticator.AppTokenManager") as mock_app_manager,
):
mock_app_manager.side_effect = ValueError("Invalid key format")
auth = GitHubTokenAuthenticator.from_stream(stream=mock_stream)
auth.prepare_tokens()
msg = "An error was thrown while preparing an app token: Invalid key format"
with caplog.at_level(logging.WARNING):
assert msg in caplog.text
def test_exclude_generated_app_token_if_invalid(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={"GITHUB_APP_PRIVATE_KEY": "123;;key"},
),
patch.object(AppTokenManager, "is_valid_token", return_value=False),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("installationtoken12345", MagicMock()),
),
):
auth = GitHubTokenAuthenticator.from_stream(stream=mock_stream)
token_managers = auth.prepare_tokens()
assert len(token_managers) == 0
def test_prepare_tokens_returns_empty_if_all_tokens_invalid(self, mock_stream):
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={
"GITHUB_TOKEN1": "gt1",
"GITHUB_APP_PRIVATE_KEY": "123;;key",
},
),
patch.object(PersonalTokenManager, "is_valid_token", return_value=False),
patch.object(AppTokenManager, "is_valid_token", return_value=False),
patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("installationtoken12345", MagicMock()),
),
):
stream = mock_stream
stream.config.update(
{
"auth_token": "gt5",
"additional_auth_tokens": ["gt7", "gt8", "gt9"],
}
)
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
assert len(token_managers) == 0
def test_get_next_auth_token_rotates_within_org(self, mock_stream):
"""Test that token rotation works correctly with org-specific token pools."""
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update(
{
"org_auth_app_keys": {
"acme-corp": ["app1;;key1", "app2;;key2"],
}
}
)
def mock_generate_token(app_id, private_key, installation_id):
return (f"token_for_{app_id}", MagicMock())
with patch(
"tap_github.authenticator.generate_app_access_token",
side_effect=mock_generate_token,
):
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
# Get the two tokens for acme-corp org
org_tokens = auth.token_managers["acme-corp"]
assert len(org_tokens) == 2
# Set current org and active token
auth.current_organization = "acme-corp"
auth.active_token = org_tokens[0]
# Mock first token as exhausted, second as available
with (
patch.object(
org_tokens[0], "has_calls_remaining", return_value=False
),
patch.object(
org_tokens[1], "has_calls_remaining", return_value=True
),
):
initial_token = auth.active_token
# Should rotate to second token
auth.get_next_auth_token()
assert auth.active_token != initial_token
assert auth.active_token == org_tokens[1]
assert auth.current_organization == "acme-corp"
def test_get_next_auth_token_keeps_org_specific_tokens_isolated(self, mock_stream):
"""Test org-specific token rotation does not fall back to agnostic tokens."""
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update(
{
"additional_auth_tokens": ["personal_token"],
"org_auth_app_keys": {
"acme-corp": ["app1;;key1"],
},
}
)
with patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("org_app_token", MagicMock()),
):
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
org_token = auth.token_managers["acme-corp"][0]
agnostic_token = auth.token_managers[None][0]
auth.current_organization = "acme-corp"
auth.active_token = org_token
with (
patch.object(org_token, "has_calls_remaining", return_value=False),
patch.object(
agnostic_token, "has_calls_remaining", return_value=True
),
pytest.raises(
RuntimeError,
match="All GitHub tokens have hit their rate limit",
),
):
auth.get_next_auth_token()
assert auth.active_token == org_token
assert auth.current_organization == "acme-corp"
def test_get_next_auth_token_raises_when_all_exhausted(self, mock_stream):
"""Test that get_next_auth_token raises when all tokens are exhausted."""
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update(
{
"org_auth_app_keys": {
"acme-corp": ["app1;;key1", "app2;;key2"],
}
}
)
with patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("org_token", MagicMock()),
):
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
org_tokens = auth.token_managers["acme-corp"]
auth.current_organization = "acme-corp"
auth.active_token = org_tokens[0]
# Mock all tokens as exhausted
with (
patch.object(
org_tokens[0], "has_calls_remaining", return_value=False
),
patch.object(
org_tokens[1], "has_calls_remaining", return_value=False
),
pytest.raises(
RuntimeError,
match="All GitHub tokens have hit their rate limit",
),
):
auth.get_next_auth_token()
def test_auth_app_keys_array_format_stores_under_none_key(self, mock_stream):
"""Test that array format for auth_app_keys stores tokens under None key."""
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update(
{
"auth_app_keys": ["app1;;key1", "app2;;key2"],
}
)
with patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("array_format_token", MagicMock()),
):
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
# Tokens should be stored under None key (org-agnostic)
assert None in token_managers
assert len(token_managers[None]) == 2
assert self._count_total_tokens(token_managers) == 2
# Should not have any org-specific keys
org_keys = [k for k in token_managers if k is not None]
assert len(org_keys) == 0
def test_auth_app_keys_object_format_stores_by_org(self, mock_stream):
"""Test that org_auth_app_keys stores tokens by organization."""
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update(
{
"org_auth_app_keys": {
"org1": ["app1;;key1"],
"org2": ["app2;;key2", "app3;;key3"],
}
}
)
with patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("org_token", MagicMock()),
):
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
# Tokens should be stored under org-specific keys
assert "org1" in token_managers
assert "org2" in token_managers
assert len(token_managers["org1"]) == 1
assert len(token_managers["org2"]) == 2
assert self._count_total_tokens(token_managers) == 3
# Should not have any tokens under None key
assert None not in token_managers or len(token_managers[None]) == 0
def test_auth_app_keys_mixed_with_personal_tokens(self, mock_stream):
"""Test that org-specific app keys and personal tokens coexist correctly."""
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update(
{
"auth_token": "personal_token",
"org_auth_app_keys": {
"org1": ["app1;;key1"],
},
}
)
with patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("org_token", MagicMock()),
):
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
token_managers = auth.prepare_tokens()
# Should have both org-specific and org-agnostic tokens
assert "org1" in token_managers
assert None in token_managers
assert len(token_managers["org1"]) == 1
assert len(token_managers[None]) == 1
assert self._count_total_tokens(token_managers) == 2
# Verify personal token is under None key
personal_tokens = [
tm
for tm in token_managers[None]
if isinstance(tm, PersonalTokenManager)
]
assert len(personal_tokens) == 1
assert personal_tokens[0].token == "personal_token"
def test_set_organization_switches_to_org_specific_token(self, mock_stream):
"""Test that set_organization switches to org-specific token."""
with (
patch.object(
GitHubTokenAuthenticator,
"get_env",
return_value={},
),
patch.object(TokenManager, "is_valid_token", return_value=True),
):
stream = mock_stream
stream.config.update(
{
"org_auth_app_keys": {
"org1": ["app1;;key1"],
"org2": ["app2;;key2"],
}
}
)
with patch(
"tap_github.authenticator.generate_app_access_token",
return_value=("org_token", MagicMock()),
):
auth = GitHubTokenAuthenticator.from_stream(stream=stream)
# Initially should be on org1 (alphabetically first)
assert auth.current_organization is None # Not set yet
org1_token = auth.token_managers["org1"][0]
org2_token = auth.token_managers["org2"][0]
# Mock has_calls_remaining to return True for all tokens
with (
patch.object(org1_token, "has_calls_remaining", return_value=True),
patch.object(org2_token, "has_calls_remaining", return_value=True),
):
# Switch to org1
auth.set_organization("org1")
assert auth.current_organization == "org1"
assert auth.active_token == org1_token
# Switch to org2
auth.set_organization("org2")
assert auth.current_organization == "org2"
assert auth.active_token == org2_token
# Switch back to org1
auth.set_organization("org1")
assert auth.current_organization == "org1"
assert auth.active_token == org1_token
def test_set_organization_falls_back_to_org_agnostic(self, mock_stream):