Repository navigation
Expand file tree
/
Copy pathtest.py
More file actions
executable file
·1105 lines (963 loc) · 54.4 KB
/
Copy pathtest.py
File metadata and controls
executable file
·1105 lines (963 loc) · 54.4 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
#!/usr/bin/env python
import base64
import datetime
import hashlib
import os
import sys
import time
import unittest
import warnings
from typing import ClassVar
from unittest.mock import patch
from urllib.parse import parse_qsl, urlencode, urlparse
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
import pyotp
class OTPConfigurationTest(unittest.TestCase):
def test_provisioning_uri_accepts_only_first_positional_argument(self):
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
for otp_type in (pyotp.TOTP, pyotp.HOTP):
with self.subTest(otp_type=otp_type):
otp = otp_type(secret)
uri = otp.provisioning_uri("Name", issuer_name="Issuer")
self.assertEqual(urlparse(uri).path, "/Issuer:Name")
with self.assertRaises(TypeError):
otp.provisioning_uri("Name", 0 if otp_type is pyotp.HOTP else "Issuer")
def test_decoded_seed_length(self):
for otp_type in (pyotp.OTP, pyotp.HOTP, pyotp.TOTP, pyotp.contrib.Steam):
for length in (0, 1, 9, 10, 14, 15, 16, 20):
raw = bytes(range(length))
encoded = base64.b32encode(raw).decode("ascii")
for seed in (encoded, encoded.rstrip("="), encoded.lower()):
with self.subTest(otp_type=otp_type, length=length, seed=seed):
if length < 10:
with self.assertRaisesRegex(ValueError, "at least 80 bits after decoding"):
otp_type(seed)
continue
with warnings.catch_warnings(record=True) as captured:
warnings.simplefilter("always")
otp = otp_type(seed)
expected_count = 1 if length < 16 else 0
self.assertEqual(len(captured), expected_count)
if length < 16:
self.assertIs(captured[0].category, pyotp.InsecureSecretWarning)
self.assertIn("128 bits", str(captured[0].message))
self.assertNotIn(seed, str(captured[0].message))
self.assertEqual(otp.byte_secret(), raw)
self.assertEqual(len(otp.generate_otp(0)), 5 if otp_type is pyotp.contrib.Steam else 6)
self.assertEqual(len(captured), expected_count)
def test_short_seed_warning_points_to_caller(self):
self.assertTrue(issubclass(pyotp.InsecureSecretWarning, UserWarning))
for otp_type in (pyotp.HOTP, pyotp.TOTP):
with self.subTest(otp_type=otp_type):
with self.assertWarns(pyotp.InsecureSecretWarning) as captured:
caller_line = sys._getframe().f_lineno + 1
otp_type("wrn3pqx5uqxqvnqr")
self.assertEqual(captured.filename, __file__)
self.assertEqual(captured.lineno, caller_line)
def test_subclass_minimum_seed_length(self):
for otp_type in (pyotp.OTP, pyotp.HOTP, pyotp.TOTP, pyotp.contrib.Steam):
for minimum_bits in (72, 113, 128, 160):
class CustomOTP(otp_type):
min_secret_length_bits: ClassVar[int] = minimum_bits
minimum_bytes = (minimum_bits + 7) // 8
for length in (minimum_bytes - 1, minimum_bytes, minimum_bytes + 1):
raw = bytes(range(length))
encoded = base64.b32encode(raw).decode("ascii")
for seed in (encoded, encoded.rstrip("="), encoded.lower()):
with self.subTest(otp_type=otp_type, minimum_bits=minimum_bits, length=length, seed=seed):
if length < minimum_bytes:
with self.assertRaisesRegex(ValueError, f"at least {minimum_bits} bits after decoding"):
CustomOTP(seed)
else:
if length < 16:
with self.assertWarns(pyotp.InsecureSecretWarning):
otp = CustomOTP(seed)
else:
otp = CustomOTP(seed)
self.assertEqual(otp.byte_secret(), raw)
self.assertEqual(len(otp.generate_otp(0)), 5 if otp_type is pyotp.contrib.Steam else 6)
self.assertEqual(otp_type.min_secret_length_bits, 80)
def test_subclass_minimum_seed_length_after_secret_change(self):
for otp_type in (pyotp.OTP, pyotp.HOTP, pyotp.TOTP, pyotp.contrib.Steam):
class CustomOTP(otp_type):
min_secret_length_bits: ClassVar[int] = 128
with self.subTest(otp_type=otp_type):
otp = CustomOTP(base64.b32encode(bytes(range(16))).decode("ascii"))
otp.secret = base64.b32encode(bytes(range(15))).decode("ascii")
with self.assertRaisesRegex(ValueError, "at least 128 bits after decoding"):
otp.generate_otp(0)
with self.assertWarns(pyotp.InsecureSecretWarning):
self.assertEqual(len(otp_type(otp.secret).byte_secret()), 15)
def test_decodes_reassigned_secret_on_use(self):
otp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
with warnings.catch_warnings():
warnings.simplefilter("error", pyotp.InsecureSecretWarning)
otp.secret = "wrn3pqx5uqxqvnqr"
self.assertTrue(otp.verify("102705", for_time=1297553958))
otp.secret = "SOME_SECRET"
with self.assertRaises(ValueError):
otp.at(0)
def test_lower_minimum_seed_length_preserves_base32_validation(self):
class CustomOTP(pyotp.OTP):
min_secret_length_bits: ClassVar[int] = 8
for secret in ("SOME_SECRET", "abc", "!" * 32):
with self.subTest(secret=secret):
with self.assertRaises(ValueError):
CustomOTP(secret)
def test_invalid_base32_is_rejected_at_construction(self):
for otp_type in (pyotp.OTP, pyotp.HOTP, pyotp.TOTP, pyotp.contrib.Steam):
for secret in ("SOME_SECRET", "abc", "!" * 32):
with self.subTest(otp_type=otp_type, secret=secret):
with self.assertRaises(ValueError):
otp_type(secret)
def test_modified_short_secrets_are_rejected_by_verification(self):
valid_secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
for length in (1, 9):
secret = base64.b32encode(bytes(range(length))).decode("ascii")
with self.subTest(length=length):
hotp = pyotp.HOTP(valid_secret)
hotp.secret = secret
with self.assertRaisesRegex(ValueError, "at least 80 bits after decoding"):
hotp.verify("123456", counter=0)
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
otp = otp_type(valid_secret)
otp.secret = secret
with self.assertRaisesRegex(ValueError, "at least 80 bits after decoding"):
otp.verify("123456", for_time=0)
with self.assertRaisesRegex(ValueError, "at least 80 bits after decoding"):
otp.verify_and_get_timecode("123456", for_time=0)
def test_digit_range(self):
for otp_type in (pyotp.OTP, pyotp.HOTP, pyotp.TOTP):
for digits in (-1, 0, 1, 5, 11):
with self.subTest(otp_type=otp_type, digits=digits):
with self.assertRaisesRegex(ValueError, "digits must be between 6 and 10"):
otp_type("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", digits=digits)
for digits in range(6, 11):
with self.subTest(otp_type=otp_type, digits=digits):
otp = otp_type("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", digits=digits)
self.assertEqual(len(otp.generate_otp(0)), digits)
def test_interval_must_be_positive(self):
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
for interval in (0, -1, -30):
with self.subTest(otp_type=otp_type, interval=interval):
with self.assertRaisesRegex(ValueError, "interval must be positive"):
otp_type("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", interval=interval)
for interval in (1, 30, 60):
with self.subTest(interval=interval):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", interval=interval)
self.assertEqual(totp.at(interval), "287082")
class TOTPIntervalLimitTest(unittest.TestCase):
def test_interval_bounds(self):
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
for interval in (0, -1, 121, 300, float("inf"), float("nan")):
with self.subTest(otp_type=otp_type, interval=interval):
with self.assertRaisesRegex(ValueError, "interval must be positive and at most 120 seconds"):
otp_type(secret, interval=interval)
for interval in (1, 30, 120):
with self.subTest(otp_type=otp_type, interval=interval):
otp_type(secret, interval=interval)
def test_maximum_interval_changes_counter(self):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", interval=120)
self.assertEqual(totp.timecode(119), 0)
self.assertEqual(totp.timecode(120), 1)
self.assertEqual(totp.at(119), "755224")
self.assertEqual(totp.at(120), "287082")
def test_uri_period_limit(self):
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
for encoder in (None, "steam"):
for period in (120, 121):
query = {"secret": secret, "period": period}
if encoder is not None:
query["encoder"] = encoder
uri = "otpauth://totp/Example?" + urlencode(query)
with self.subTest(encoder=encoder, period=period):
if period > 120:
with self.assertRaisesRegex(ValueError, "at most 120 seconds"):
pyotp.parse_uri(uri)
else:
otp = pyotp.parse_uri(uri)
if encoder is None:
self.assertEqual(otp.interval, 120)
self.assertEqual(pyotp.parse_uri(otp.provisioning_uri()).interval, 120)
class HOTPExampleValuesFromTheRFC(unittest.TestCase):
def test_match_rfc(self):
# 12345678901234567890 in Bas32
# GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
hotp = pyotp.HOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
self.assertEqual(hotp.at(0), "755224")
self.assertEqual(hotp.at(1), "287082")
self.assertEqual(hotp.at(2), "359152")
self.assertEqual(hotp.at(3), "969429")
self.assertEqual(hotp.at(4), "338314")
self.assertEqual(hotp.at(5), "254676")
self.assertEqual(hotp.at(6), "287922")
self.assertEqual(hotp.at(7), "162583")
self.assertEqual(hotp.at(8), "399871")
self.assertEqual(hotp.at(9), "520489")
def test_invalid_input(self):
hotp = pyotp.HOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
with self.assertRaises(ValueError):
hotp.at(-1)
def test_verify_otp_reuse(self):
hotp = pyotp.HOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
self.assertTrue(hotp.verify("520489", counter=9))
self.assertTrue(hotp.verify("520489", counter=9))
self.assertFalse(hotp.verify("520489", counter=10))
self.assertFalse(hotp.verify("520489", counter=10))
def test_verify_counter_is_keyword_only(self):
hotp = pyotp.HOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
with self.assertRaises(TypeError):
hotp.verify("520489", 9)
def test_provisioning_uri(self):
hotp = pyotp.HOTP("wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", name="mark@percival")
url = urlparse(hotp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "hotp")
self.assertEqual(url.path, "/mark%40percival")
self.assertEqual(dict(parse_qsl(url.query)), {"secret": "wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", "counter": "0"})
self.assertEqual(hotp.provisioning_uri(), pyotp.parse_uri(hotp.provisioning_uri()).provisioning_uri())
hotp = pyotp.HOTP("wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", name="mark@percival", initial_count=12)
url = urlparse(hotp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "hotp")
self.assertEqual(url.path, "/mark%40percival")
self.assertEqual(dict(parse_qsl(url.query)), {"secret": "wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", "counter": "12"})
self.assertEqual(hotp.provisioning_uri(), pyotp.parse_uri(hotp.provisioning_uri()).provisioning_uri())
hotp = pyotp.HOTP("wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", name="mark@percival", issuer="FooCorp!")
url = urlparse(hotp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "hotp")
self.assertEqual(url.path, "/FooCorp%21:mark%40percival")
self.assertEqual(
dict(parse_qsl(url.query)),
{"secret": "wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", "counter": "0", "issuer": "FooCorp!"},
)
self.assertEqual(hotp.provisioning_uri(), pyotp.parse_uri(hotp.provisioning_uri()).provisioning_uri())
key = "c7uxuqhgflpw7oruedmglbrk7u6242vb"
hotp = pyotp.HOTP(key, digits=8, digest=hashlib.sha256, name="baco@peperina", issuer="FooCorp")
url = urlparse(hotp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "hotp")
self.assertEqual(url.path, "/FooCorp:baco%40peperina")
self.assertEqual(
dict(parse_qsl(url.query)),
{
"secret": "c7uxuqhgflpw7oruedmglbrk7u6242vb",
"counter": "0",
"issuer": "FooCorp",
"digits": "8",
"algorithm": "SHA256",
},
)
self.assertEqual(hotp.provisioning_uri(), pyotp.parse_uri(hotp.provisioning_uri()).provisioning_uri())
hotp = pyotp.HOTP(key, digits=8, name="baco@peperina", issuer="Foo Corp", initial_count=10)
url = urlparse(hotp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "hotp")
self.assertEqual(url.path, "/Foo%20Corp:baco%40peperina")
self.assertEqual(
dict(parse_qsl(url.query)),
{"secret": "c7uxuqhgflpw7oruedmglbrk7u6242vb", "counter": "10", "issuer": "Foo Corp", "digits": "8"},
)
self.assertEqual(hotp.provisioning_uri(), pyotp.parse_uri(hotp.provisioning_uri()).provisioning_uri())
# initial_count=0 must be respected even though 0 is falsy
hotp = pyotp.HOTP("wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", name="mark@percival", initial_count=7)
url = urlparse(hotp.provisioning_uri(initial_count=0))
self.assertEqual(dict(parse_qsl(url.query))["counter"], "0")
code = pyotp.totp.TOTP("S46SQCPPTCNPROMHWYBDCTBZXV")
self.assertEqual(code.provisioning_uri(), "otpauth://totp/Secret?secret=S46SQCPPTCNPROMHWYBDCTBZXV")
code.verify("123456")
self.assertEqual(code.provisioning_uri(), "otpauth://totp/Secret?secret=S46SQCPPTCNPROMHWYBDCTBZXV")
def test_other_secret(self):
hotp = pyotp.HOTP("N3OVNIBRERIO5OHGVCMDGS4V4RJ3AUZOUN34J6FRM4P6JIFCG3ZA")
self.assertEqual(hotp.at(0), "737863")
self.assertEqual(hotp.at(1), "390601")
self.assertEqual(hotp.at(2), "363354")
self.assertEqual(hotp.at(3), "936780")
self.assertEqual(hotp.at(4), "654019")
class TOTPExampleValuesFromTheRFC(unittest.TestCase):
RFC_VALUES: ClassVar[dict] = {
(hashlib.sha1, b"12345678901234567890"): (
(59, "94287082"),
(1111111109, "07081804"),
(1111111111, "14050471"),
(1234567890, "89005924"),
(2000000000, "69279037"),
(20000000000, "65353130"),
),
(hashlib.sha256, b"12345678901234567890123456789012"): (
(59, 46119246),
(1111111109, "68084774"),
(1111111111, "67062674"),
(1234567890, "91819424"),
(2000000000, "90698825"),
(20000000000, "77737706"),
),
(hashlib.sha512, b"1234567890123456789012345678901234567890123456789012345678901234"): (
(59, 90693936),
(1111111109, "25091201"),
(1111111111, "99943326"),
(1234567890, "93441116"),
(2000000000, "38618901"),
(20000000000, "47863826"),
),
}
def test_match_rfc(self):
for digest, secret in self.RFC_VALUES:
totp = pyotp.TOTP(base64.b32encode(secret), digits=8, digest=digest)
for utime, code in self.RFC_VALUES[(digest, secret)]:
if utime > sys.maxsize:
warnings.warn(
"32-bit platforms use native functions to handle timestamps, so they fail this test"
+ " (and will fail after 19 January 2038)"
)
continue
value = totp.at(utime)
msg = "%s != %s (%s, time=%d)"
msg %= (value, code, digest().name, utime)
self.assertEqual(value, str(code), msg)
def test_match_rfc_digit_length(self):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
self.assertEqual(totp.at(1111111111), "050471")
self.assertEqual(totp.at(1234567890), "005924")
self.assertEqual(totp.at(2000000000), "279037")
def test_legacy_google_authenticator_secret(self):
with self.assertWarns(pyotp.InsecureSecretWarning):
totp = pyotp.TOTP("wrn3pqx5uqxqvnqr")
self.assertTrue(totp.verify("102705", for_time=1297553958))
def test_validate_totp(self):
totp = pyotp.TOTP("wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr")
with patch("pyotp.totp.time.time", return_value=1297553958):
self.assertTrue(totp.verify("415823"))
self.assertTrue(totp.verify("415823"))
with patch("pyotp.totp.time.time", return_value=1297553958 + 30):
self.assertFalse(totp.verify("415823"))
def test_input_before_epoch(self):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
for timestamp in (-30, -29.5, -1, -0.1):
with self.subTest(timestamp=timestamp):
with self.assertRaises(ValueError):
totp.at(timestamp)
def test_validate_totp_with_digit_length(self):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
with patch("pyotp.totp.time.time", return_value=1111111111):
self.assertTrue(totp.verify("050471"))
with patch("pyotp.totp.time.time", return_value=1297553958 + 30):
self.assertFalse(totp.verify("050471"))
def test_provisioning_uri(self):
totp = pyotp.TOTP("wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", name="mark@percival")
url = urlparse(totp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "totp")
self.assertEqual(url.path, "/mark%40percival")
self.assertEqual(dict(parse_qsl(url.query)), {"secret": "wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr"})
self.assertEqual(totp.provisioning_uri(), pyotp.parse_uri(totp.provisioning_uri()).provisioning_uri())
totp = pyotp.TOTP("wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", name="mark@percival", issuer="FooCorp!")
url = urlparse(totp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "totp")
self.assertEqual(url.path, "/FooCorp%21:mark%40percival")
self.assertEqual(
dict(parse_qsl(url.query)), {"secret": "wrn3pqx5uqxqvnqrwrn3pqx5uqxqvnqr", "issuer": "FooCorp!"}
)
self.assertEqual(totp.provisioning_uri(), pyotp.parse_uri(totp.provisioning_uri()).provisioning_uri())
key = "c7uxuqhgflpw7oruedmglbrk7u6242vb"
totp = pyotp.TOTP(key, digits=8, interval=60, digest=hashlib.sha256, name="baco@peperina", issuer="FooCorp")
url = urlparse(totp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "totp")
self.assertEqual(url.path, "/FooCorp:baco%40peperina")
self.assertEqual(
dict(parse_qsl(url.query)),
{
"secret": "c7uxuqhgflpw7oruedmglbrk7u6242vb",
"issuer": "FooCorp",
"digits": "8",
"period": "60",
"algorithm": "SHA256",
},
)
self.assertEqual(totp.provisioning_uri(), pyotp.parse_uri(totp.provisioning_uri()).provisioning_uri())
totp = pyotp.TOTP(key, digits=8, interval=60, name="baco@peperina", issuer="FooCorp")
url = urlparse(totp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "totp")
self.assertEqual(url.path, "/FooCorp:baco%40peperina")
self.assertEqual(
dict(parse_qsl(url.query)),
{"secret": "c7uxuqhgflpw7oruedmglbrk7u6242vb", "issuer": "FooCorp", "digits": "8", "period": "60"},
)
self.assertEqual(totp.provisioning_uri(), pyotp.parse_uri(totp.provisioning_uri()).provisioning_uri())
totp = pyotp.TOTP(key, digits=8, name="baco@peperina", issuer="FooCorp")
url = urlparse(totp.provisioning_uri())
self.assertEqual(url.scheme, "otpauth")
self.assertEqual(url.netloc, "totp")
self.assertEqual(url.path, "/FooCorp:baco%40peperina")
self.assertEqual(
dict(parse_qsl(url.query)),
{"secret": "c7uxuqhgflpw7oruedmglbrk7u6242vb", "issuer": "FooCorp", "digits": "8"},
)
self.assertEqual(totp.provisioning_uri(), pyotp.parse_uri(totp.provisioning_uri()).provisioning_uri())
def test_provisioning_uri_parameter_types(self):
for otp_type in (pyotp.TOTP, pyotp.HOTP):
with self.subTest(otp_type=otp_type):
otp = otp_type("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
with self.assertRaises(TypeError):
otp.provisioning_uri(image=123)
with self.assertRaises(ValueError):
otp.provisioning_uri(image="not-a-url")
def test_random_key_generation(self):
self.assertEqual(len(pyotp.random_base32()), 32)
self.assertEqual(len(pyotp.random_base32(length=34)), 34)
self.assertEqual(len(pyotp.random_hex()), 40)
self.assertEqual(len(pyotp.random_hex(length=42)), 42)
with self.assertRaises(ValueError):
pyotp.random_base32(length=31)
with self.assertRaises(ValueError):
pyotp.random_hex(length=39)
@unittest.skipUnless(hasattr(time, "tzset"), "Local timezone tests require time.tzset()")
class TOTPTimezones(unittest.TestCase):
def setUp(self):
self.original_tz = os.environ.get("TZ")
self.addCleanup(self.restore_timezone)
def restore_timezone(self):
if self.original_tz is None:
os.environ.pop("TZ", None)
else:
os.environ["TZ"] = self.original_tz
time.tzset()
def test_repeated_local_times(self):
# POSIX rules keep these tests independent of the installed timezone database.
transitions = (
("GMT0BST,M3.5.0/1,M10.5.0/2", "2026-10-25T00:30:00+00:00", "2026-10-25T01:30:00+00:00"),
("EST5EDT,M3.2.0/2,M11.1.0/2", "2026-11-01T05:30:00+00:00", "2026-11-01T06:30:00+00:00"),
("LHST-10:30LHDT-11,M10.1.0/2,M4.1.0/2", "2026-04-04T14:45:00+00:00", "2026-04-04T15:15:00+00:00"),
)
for timezone, first, second in transitions:
os.environ["TZ"] = timezone
time.tzset()
timestamps = [int(datetime.datetime.fromisoformat(value).timestamp()) for value in (first, second)]
local_times = [datetime.datetime.fromtimestamp(ts, datetime.timezone.utc).astimezone() for ts in timestamps]
self.assertEqual(local_times[0].replace(tzinfo=None), local_times[1].replace(tzinfo=None))
self.assertNotEqual(local_times[0].utcoffset(), local_times[1].utcoffset())
for fold, timestamp in enumerate(timestamps):
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
for interval in (30, 60) if otp_type is pyotp.TOTP else (30,):
totp = otp_type("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", interval=interval)
for delta in (-1, 0, 1):
with self.subTest(
timezone=timezone, fold=fold, otp=otp_type, interval=interval, delta=delta
):
ts = timestamp + delta
counter = ts // interval
expected = totp.generate_otp(counter)
aware = datetime.datetime.fromtimestamp(ts, datetime.timezone.utc).astimezone()
naive = aware.replace(tzinfo=None, fold=fold)
for for_time in (ts, ts + 0.5, naive, aware):
self.assertEqual(totp.timecode(for_time), counter)
self.assertEqual(totp.at(for_time), expected)
self.assertTrue(totp.verify(expected, for_time=for_time))
self.assertEqual(totp.verify_and_get_timecode(expected, for_time=for_time), counter)
for offset in (-1, 1):
adjacent = totp.generate_otp(counter + offset)
self.assertEqual(totp.at(for_time, counter_offset=offset), adjacent)
self.assertTrue(totp.verify(adjacent, for_time=for_time, valid_window=1))
self.assertEqual(
totp.verify_and_get_timecode(adjacent, for_time=for_time, valid_window=1),
counter + offset,
)
other = totp.generate_otp((timestamps[1 - fold] + delta) // interval)
self.assertFalse(totp.verify(other, for_time=naive, valid_window=1))
with self.assertRaises(pyotp.OTPVerificationError):
totp.verify_and_get_timecode(other, for_time=naive, valid_window=1)
with patch("pyotp.totp.time.time", return_value=ts):
self.assertEqual(totp.now(), expected)
self.assertTrue(totp.verify(expected))
self.assertEqual(totp.verify_and_get_timecode(expected), counter)
def test_naive_fractional_seconds(self):
os.environ["TZ"] = "UTC0"
time.tzset()
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
for for_time, counter in TOTPTimecode.FRACTIONAL_SECONDS:
with self.subTest(for_time=for_time):
self.assertEqual(totp.timecode(for_time.replace(tzinfo=None)), counter)
def test_naive_time_range(self):
os.environ["TZ"] = "UTC0"
time.tzset()
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc).replace(tzinfo=None)
self.assertEqual(totp.timecode(epoch), 0)
self.assertEqual(totp.timecode(datetime.datetime.max), 8446743359)
for for_time in (datetime.datetime.min, epoch - datetime.timedelta(microseconds=1)):
with self.subTest(for_time=for_time):
with self.assertRaisesRegex(ValueError, "for_time must be"):
totp.timecode(for_time)
with self.assertRaises(ValueError):
totp.at(for_time)
with self.assertRaises(ValueError):
totp.verify("invalid", for_time=for_time)
with self.assertRaises(ValueError):
totp.verify_and_get_timecode("invalid", for_time=for_time)
class TOTPTimecode(unittest.TestCase):
FRACTIONAL_SECONDS = (
(datetime.datetime(1970, 1, 1, 0, 0, 29, 999999, tzinfo=datetime.timezone.utc), 0),
(datetime.datetime(1970, 1, 1, 0, 0, 30, tzinfo=datetime.timezone.utc), 1),
(datetime.datetime(2600, 1, 1, 0, 0, 29, 999999, tzinfo=datetime.timezone.utc), 662696640),
)
def test_aware_fractional_seconds(self):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
for for_time, counter in self.FRACTIONAL_SECONDS:
for timezone in (datetime.timezone.utc, datetime.timezone(datetime.timedelta(hours=5, minutes=30))):
aware = for_time.astimezone(timezone)
with self.subTest(for_time=aware):
self.assertEqual(totp.timecode(aware), counter)
def test_numeric_timestamps(self):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
cases = (
(0, 0),
(29.999999, 0),
(30.0, 1),
(59.999999, 1),
(60, 2),
(253402300799, 8446743359),
(253402300799.5, 8446743359),
)
for timestamp, counter in cases:
with self.subTest(timestamp=timestamp):
self.assertEqual(totp.timecode(timestamp), counter)
code = totp.generate_otp(counter)
self.assertEqual(totp.at(timestamp), code)
self.assertTrue(totp.verify(code, for_time=timestamp))
matched = totp.verify_and_get_timecode(code, for_time=timestamp)
self.assertIs(type(matched), int)
self.assertEqual(matched, counter)
def test_timestamps_outside_datetime_range(self):
for timestamp in (-30.5, -29.5, -1, -0.1, 253402300800, 253402300800.0, 10**12):
self.assert_time_out_of_range(timestamp)
def test_nonfinite_timestamps(self):
for timestamp in (float("nan"), float("inf"), float("-inf")):
self.assert_time_out_of_range(timestamp)
def test_current_time_outside_range(self):
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
totp = otp_type("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
for timestamp in (-0.1, 253402300800):
with self.subTest(otp_type=otp_type, timestamp=timestamp):
with patch("pyotp.totp.time.time", return_value=timestamp):
with self.assertRaisesRegex(ValueError, "for_time must be"):
totp.now()
with self.assertRaises(ValueError):
totp.verify("invalid")
with self.assertRaises(ValueError):
totp.verify_and_get_timecode("invalid")
def test_datetimes_outside_range(self):
cases = (
datetime.datetime.min,
datetime.datetime.min.replace(tzinfo=datetime.timezone.utc),
datetime.datetime(1969, 12, 31, 23, 59, 59, 999999, tzinfo=datetime.timezone.utc),
datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone(datetime.timedelta(hours=1))),
datetime.datetime.max.replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-1))),
)
for for_time in cases:
self.assert_time_out_of_range(for_time)
def test_datetime_range_boundaries(self):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
cases = (
(datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc), 0),
(datetime.datetime(1969, 12, 31, 23, tzinfo=datetime.timezone(datetime.timedelta(hours=-1))), 0),
(datetime.datetime.max.replace(tzinfo=datetime.timezone.utc), 8446743359),
)
for for_time, counter in cases:
with self.subTest(for_time=for_time):
code = totp.generate_otp(counter)
self.assertEqual(totp.timecode(for_time), counter)
self.assertEqual(totp.at(for_time), code)
self.assertTrue(totp.verify(code, for_time=for_time))
self.assertEqual(totp.verify_and_get_timecode(code, for_time=for_time), counter)
def assert_time_out_of_range(self, for_time):
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
totp = otp_type("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
calls = (
(totp.timecode, (for_time,), {}),
(totp.at, (for_time,), {}),
(totp.verify, ("invalid",), {"for_time": for_time}),
(totp.verify_and_get_timecode, ("invalid",), {"for_time": for_time}),
)
for method, args, kwargs in calls:
with self.subTest(otp_type=otp_type, method=method.__name__, for_time=for_time):
with self.assertRaisesRegex(ValueError, "for_time must be"):
method(*args, **kwargs)
def test_verification_normalizes_time_once(self):
totp = pyotp.TOTP("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
timestamp = 200.5
counter = 6
code = totp.generate_otp(counter + 2)
for verify in (totp.verify, totp.verify_and_get_timecode):
for candidate in (code, "invalid"):
with self.subTest(method=verify.__name__, candidate=candidate):
with patch.object(totp, "timecode", wraps=totp.timecode) as normalize:
if candidate == "invalid" and verify == totp.verify_and_get_timecode:
with self.assertRaises(pyotp.OTPVerificationError):
verify(candidate, for_time=timestamp, valid_window=2)
else:
result = verify(candidate, for_time=timestamp, valid_window=2)
if candidate == code:
self.assertTrue(result)
else:
self.assertIs(result, False)
normalize.assert_called_once_with(timestamp)
class SteamTOTP(unittest.TestCase):
def test_legacy_example_secret(self):
with self.assertWarns(pyotp.InsecureSecretWarning):
steam = pyotp.contrib.Steam("BASE32SECRET3232")
for timestamp, code in (
(0, "2TC8B"),
(30, "YKKK4"),
(60, "M4HQB"),
(90, "DTVB3"),
(1662883100, "N3G63"),
(946681223, "7VP3X"),
):
with self.subTest(timestamp=timestamp, code=code):
self.assertEqual(steam.at(timestamp), code)
def test_match_examples(self):
steam = pyotp.contrib.Steam("BASE32SECRET32323232323232")
self.assertEqual(steam.at(0), "WYMY2")
self.assertEqual(steam.at(30), "HG48B")
self.assertEqual(steam.at(60), "WTM99")
self.assertEqual(steam.at(90), "BKYDG")
steam = pyotp.contrib.Steam("FMXNK4QEGKVPULRTADY6JIDK5VHUBGZW")
self.assertEqual(steam.at(0), "C5V56")
self.assertEqual(steam.at(30), "QJY8Y")
self.assertEqual(steam.at(60), "R3WQY")
self.assertEqual(steam.at(90), "JG3T3")
def test_verify(self):
steam = pyotp.contrib.Steam("BASE32SECRET32323232323232")
with patch("pyotp.totp.time.time", return_value=1662883100):
self.assertTrue(steam.verify("FW33J"))
with patch("pyotp.totp.time.time", return_value=1662883100 + 30):
self.assertFalse(steam.verify("FW33J"))
with patch("pyotp.totp.time.time", return_value=946681223):
self.assertTrue(steam.verify("BDJKQ"))
with patch("pyotp.totp.time.time", return_value=946681223 + 30):
self.assertFalse(steam.verify("BDJKQ"))
steam = pyotp.contrib.Steam("FMXNK4QEGKVPULRTADY6JIDK5VHUBGZW")
with patch("pyotp.totp.time.time", return_value=1662884261):
self.assertTrue(steam.verify("V6WKJ"))
with patch("pyotp.totp.time.time", return_value=1662884261 + 30):
self.assertFalse(steam.verify("V6WKJ"))
with patch("pyotp.totp.time.time", return_value=946681223):
self.assertTrue(steam.verify("4MK54"))
with patch("pyotp.totp.time.time", return_value=946681223 + 30):
self.assertFalse(steam.verify("4MK54"))
class CompareDigestTest(unittest.TestCase):
method = staticmethod(pyotp.utils.compare_digest)
def test_comparisons(self):
self.assertTrue(self.method("", ""))
self.assertTrue(self.method("a", "a"))
self.assertTrue(self.method("a" * 1000, "a" * 1000))
self.assertFalse(self.method("", "a"))
self.assertFalse(self.method("a", ""))
self.assertFalse(self.method("a" * 999 + "b", "a" * 1000))
class StringComparisonTest(CompareDigestTest):
method = staticmethod(pyotp.utils.strings_equal)
def test_fullwidth_input(self):
self.assertTrue(self.method("xs12345", "xs12345"))
def test_unicode_equal(self):
self.assertTrue(self.method("ěšč45", "ěšč45"))
def test_input_length_limit(self):
self.assertTrue(self.method("a" * 1024, "a" * 1024))
self.assertFalse(self.method("a" * 1024, "b" * 1024))
def test_oversized_input_is_not_normalized(self):
inputs = ("a" * 1025, "\u0301\u0323" * 512 + "\u0301", "\u0301\u0323" * 32768)
for value in inputs:
for s1, s2 in ((value, "a"), ("a", value), (value, value)):
with self.subTest(lengths=(len(s1), len(s2))):
with patch("pyotp.utils.unicodedata.normalize") as normalize:
self.assertFalse(self.method(s1, s2))
normalize.assert_not_called()
class OTPInputSizeTest(unittest.TestCase):
def test_oversized_otp_is_not_normalized(self):
oversized = "\u0301\u0323" * 32768
hotp = pyotp.HOTP("ABCDEFGHABCDEFGHABCDEFGH")
with patch("pyotp.utils.unicodedata.normalize") as normalize:
self.assertFalse(hotp.verify(oversized, counter=6))
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
totp = otp_type("ABCDEFGHABCDEFGHABCDEFGH")
for valid_window in (0, 1):
with self.subTest(otp_type=otp_type, valid_window=valid_window):
self.assertFalse(totp.verify(oversized, for_time=200, valid_window=valid_window))
with self.assertRaises(pyotp.OTPVerificationError):
totp.verify_and_get_timecode(oversized, for_time=200, valid_window=valid_window)
normalize.assert_not_called()
def test_fullwidth_otp(self):
fullwidth = str.maketrans(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",
)
for digits in (6, 8, 10):
with self.subTest(digits=digits):
hotp = pyotp.HOTP("ABCDEFGHABCDEFGHABCDEFGH", digits=digits)
self.assertTrue(hotp.verify(hotp.at(6).translate(fullwidth), counter=6))
totp = pyotp.TOTP("ABCDEFGHABCDEFGHABCDEFGH", digits=digits)
code = totp.at(200).translate(fullwidth)
self.assertTrue(totp.verify(code, for_time=200))
self.assertEqual(totp.verify_and_get_timecode(code, for_time=200), 6)
steam = pyotp.contrib.Steam("ABCDEFGHABCDEFGHABCDEFGH")
code = steam.at(200).translate(fullwidth)
self.assertTrue(steam.verify(code, for_time=200))
self.assertEqual(steam.verify_and_get_timecode(code, for_time=200), 6)
class CounterOffsetTest(unittest.TestCase):
def test_counter_offset(self):
totp = pyotp.TOTP("ABCDEFGHABCDEFGHABCDEFGH")
self.assertEqual(totp.at(200), "823229")
self.assertEqual(totp.at(200, counter_offset=1), "797869")
class ValidWindowTest(unittest.TestCase):
def test_valid_window(self):
totp = pyotp.TOTP("ABCDEFGHABCDEFGHABCDEFGH")
self.assertTrue(totp.verify("549250", for_time=200, valid_window=1))
self.assertTrue(totp.verify("823229", for_time=200, valid_window=1))
self.assertTrue(totp.verify("797869", for_time=200, valid_window=1))
self.assertFalse(totp.verify("449527", for_time=200, valid_window=1))
class GetTimeCodeTest(unittest.TestCase):
def test_timecode(self):
totp = pyotp.TOTP("ABCDEFGHABCDEFGHABCDEFGH")
self.assertEqual(totp.verify_and_get_timecode("549250", for_time=200, valid_window=1), 5)
self.assertEqual(totp.verify_and_get_timecode("823229", for_time=200, valid_window=1), 6)
self.assertEqual(totp.verify_and_get_timecode("797869", for_time=200, valid_window=1), 7)
with self.assertRaises(pyotp.OTPVerificationError):
totp.verify_and_get_timecode("449527", for_time=200, valid_window=1)
def test_invalid_otp(self):
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
totp = otp_type("ABCDEFGHABCDEFGHABCDEFGH")
for valid_window in (0, 1):
for code in ("", "invalid"):
with self.subTest(otp_type=otp_type, valid_window=valid_window, code=code):
with self.assertRaises(pyotp.OTPVerificationError) as error:
totp.verify_and_get_timecode(code, for_time=200, valid_window=valid_window)
self.assertIsInstance(error.exception, pyotp.PyOTPError)
self.assertFalse(totp.verify(code, for_time=200, valid_window=valid_window))
def test_current_time(self):
for otp_type in (pyotp.TOTP, pyotp.contrib.Steam):
totp = otp_type("ABCDEFGHABCDEFGHABCDEFGH")
with self.subTest(otp_type=otp_type):
with patch("pyotp.totp.time.time", return_value=0):
matched = totp.verify_and_get_timecode(totp.at(0))
self.assertIs(type(matched), int)
self.assertEqual(matched, 0)
with self.assertRaises(pyotp.OTPVerificationError):
totp.verify_and_get_timecode("invalid")
def test_negative_window(self):
totp = pyotp.TOTP("ABCDEFGHABCDEFGHABCDEFGH")
with self.assertRaisesRegex(ValueError, "valid_window cannot be negative"):
totp.verify_and_get_timecode("823229", for_time=200, valid_window=-1)
class DigestFunctionTest(unittest.TestCase):
def test_md5(self):
with self.assertRaises(ValueError) as cm:
pyotp.OTP(s="secret", digest=hashlib.md5)
self.assertEqual(
"selected digest function must generate digest size greater than or equals to 18 bytes", str(cm.exception)
)
def test_shake128(self):
with self.assertRaises(ValueError) as cm:
pyotp.OTP(s="secret", digest=hashlib.shake_128)
self.assertEqual(
"selected digest function must generate digest size greater than or equals to 18 bytes", str(cm.exception)
)
class ParseUriTest(unittest.TestCase):
def test_warns_each_time_a_short_secret_is_loaded(self):
for kind, suffix in (("hotp", "&counter=0"), ("totp", ""), ("totp", "&encoder=steam")):
uri = f"otpauth://{kind}/Example?secret=GEZDGNBVGY3TQOJQ{suffix}"
with self.subTest(uri=uri):
with warnings.catch_warnings(record=True) as captured:
warnings.simplefilter("always", pyotp.InsecureSecretWarning)
for _ in range(2):
pyotp.parse_uri(uri)
self.assertEqual([item.category for item in captured], [pyotp.InsecureSecretWarning] * 2)
def test_invalid_secrets_are_rejected(self):
for otp_type, encoder in (("hotp", None), ("totp", None), ("totp", "steam")):
for secret in ("MZXW6YTBOI", "SOME_SECRET"):
query = {"secret": secret}
if encoder is not None:
query["encoder"] = encoder
with self.subTest(otp_type=otp_type, encoder=encoder, secret=secret):
with self.assertRaises(ValueError):
pyotp.parse_uri(f"otpauth://{otp_type}/Example?" + urlencode(query))
def test_hotp_factory_can_override_minimum_secret_length(self):
class LegacyHOTP(pyotp.HOTP):
min_secret_length_bits: ClassVar[int] = 72
uri = "otpauth://hotp/Issuer:Name?secret=GEZDGNBVGY3TQOI&issuer=Issuer&counter=7"
with self.assertRaisesRegex(ValueError, "at least 80 bits after decoding"):
pyotp.parse_uri(uri)
with self.assertWarns(pyotp.InsecureSecretWarning):
otp = pyotp.parse_uri(uri, hotp_factory=LegacyHOTP)
self.assertIs(type(otp), LegacyHOTP)
self.assertEqual(otp.byte_secret(), b"123456789")
self.assertEqual((otp.issuer, otp.name, otp.initial_count), ("Issuer", "Name", 7))
def test_totp_factory_can_override_minimum_secret_length(self):
class LegacyTOTP(pyotp.TOTP):
min_secret_length_bits: ClassVar[int] = 72
uri = "otpauth://totp/Issuer:Name?secret=GEZDGNBVGY3TQOI&digits=8&period=60"
with self.assertRaisesRegex(ValueError, "at least 80 bits after decoding"):
pyotp.parse_uri(uri)
with self.assertWarns(pyotp.InsecureSecretWarning):
otp = pyotp.parse_uri(uri, totp_factory=LegacyTOTP)
self.assertIs(type(otp), LegacyTOTP)
self.assertEqual(otp.byte_secret(), b"123456789")
self.assertEqual((otp.issuer, otp.name, otp.digits, otp.interval), ("Issuer", "Name", 8, 60))
def test_factories_are_keyword_only(self):
uri = "otpauth://totp/Example?secret=GEZDGNBVGY3TQOJQGEZDGNBV"
with self.assertRaises(TypeError):
pyotp.parse_uri(uri, pyotp.HOTP, pyotp.TOTP)
def test_duplicate_security_parameters(self):
seed = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
parameters = {
"secret": seed,
"issuer": "Example",
"algorithm": "SHA1",
"encoder": "steam",
"digits": "6",
"period": "30",
"counter": "0",
}
for key, value in parameters.items():
kind = "hotp" if key == "counter" else "totp"
for first, second in ((value, value), (value, "different"), (value, ""), ("", value)):
query = [(key, first), (key, second)]
if key != "secret":
query.append(("secret", seed))
with self.subTest(key=key, first=first, second=second):
with self.assertRaisesRegex(ValueError, f"Duplicate {key} parameter"):
pyotp.parse_uri(f"otpauth://{kind}/?{urlencode(query)}")
def test_encoded_duplicate_parameter(self):
with self.assertRaisesRegex(ValueError, "Duplicate secret parameter"):
pyotp.parse_uri(
"otpauth://totp/?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&%73ecret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
)
def test_duplicate_unknown_parameters(self):
otp = pyotp.parse_uri("otpauth://totp/?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&unknown=one&unknown=two")
self.assertEqual(otp.at(0), "755224")
def test_invalid_period(self):
for encoder in ("", "steam"):
for period in (0, -1):
query = urlencode({"secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "encoder": encoder, "period": period})
with self.subTest(encoder=encoder, period=period):
with self.assertRaisesRegex(ValueError, "interval must be positive"):
pyotp.parse_uri(f"otpauth://totp/?{query}")
def test_invalids(self):
with self.assertRaises(ValueError) as cm:
pyotp.parse_uri("http://hello.com")
self.assertEqual("Not an otpauth URI", str(cm.exception))
with self.assertRaises(ValueError) as cm:
pyotp.parse_uri("otpauth://totp")
self.assertEqual("No secret found in URI", str(cm.exception))
with self.assertRaises(ValueError) as cm:
pyotp.parse_uri("otpauth://derp?secret=foo")
self.assertEqual("Not a supported OTP type", str(cm.exception))
with self.assertRaises(ValueError) as cm:
pyotp.parse_uri("otpauth://totp?digits=-1")
self.assertEqual("Digits may only be 6, 7, or 8", str(cm.exception))
with self.assertRaises(ValueError) as cm:
pyotp.parse_uri("otpauth://totp/SomeIssuer:?issuer=AnotherIssuer")
self.assertEqual("If issuer is specified in both label and parameters, it should be equal.", str(cm.exception))
with self.assertRaises(ValueError) as cm:
pyotp.parse_uri("otpauth://totp?algorithm=aes")
self.assertEqual("Invalid value for algorithm, must be SHA1, SHA256 or SHA512", str(cm.exception))
def test_parse_steam(self):
otp = pyotp.parse_uri("otpauth://totp/Steam:?secret=JBSWY3DPEHPK3PXPJBSWY3DP&encoder=steam")
self.assertEqual(type(otp), pyotp.contrib.Steam)
otp = pyotp.parse_uri("otpauth://totp/Steam:?secret=JBSWY3DPEHPK3PXPJBSWY3DP")
self.assertNotEqual(type(otp), pyotp.contrib.Steam)
@unittest.skipIf(sys.version_info < (3, 6), "Skipping test that requires deterministic dict key enumeration")
def test_algorithms(self):
otp = pyotp.parse_uri("otpauth://totp?algorithm=SHA1&secret=GEZDGNBVGY3TQOJQGEZDGNBV")
self.assertEqual(hashlib.sha1, otp.digest)