forked from notypecheck/passlib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
3435 lines (2872 loc) · 125 KB
/
utils.py
File metadata and controls
3435 lines (2872 loc) · 125 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
"""helpers for passlib unittests"""
from __future__ import annotations
import contextlib
import hashlib
import logging
import math
import os
import random
import re
import sys
import tempfile
import threading
import time
import unittest
import warnings
# core
from binascii import unhexlify
from functools import partial, wraps
from typing import TYPE_CHECKING, Any
from unittest import SkipTest
from warnings import warn
import pytest
import passlib.utils.handlers as uh
from passlib import exc
from passlib.exc import (
InternalBackendError,
MissingBackendError,
PasslibConfigWarning,
PasslibHashWarning,
)
from passlib.utils import (
batch,
getrandstr,
has_rounds_info,
has_salt_info,
is_ascii_safe,
repeat_string,
rounds_cost_values,
tick,
)
from passlib.utils import (
rng as sys_rng,
)
from passlib.utils.decor import classproperty
from tests.utils_ import no_warnings
if TYPE_CHECKING:
from collections.abc import Sequence
from passlib.ifc import PasswordHash
from passlib.utils.handlers import PrefixWrapper
log = logging.getLogger(__name__)
# local
__all__ = [
# util funcs
"TEST_MODE",
"set_file",
"get_file",
# unit testing
"TestCase",
"HandlerCase",
]
def ensure_mtime_changed(path):
"""ensure file's mtime has changed"""
# NOTE: this is hack to deal w/ filesystems whose mtime resolution is >= 1s,
# when a test needs to be sure the mtime changed after writing to the file.
last = os.path.getmtime(path)
while os.path.getmtime(path) == last:
time.sleep(0.1)
os.utime(path, None)
def _get_timer_resolution(timer):
def sample():
start = cur = timer()
while start == cur:
cur = timer()
return cur - start
return min(sample() for _ in range(3))
TICK_RESOLUTION = _get_timer_resolution(tick)
_TEST_MODES = ["quick", "default", "full"]
_test_mode = _TEST_MODES.index(
os.environ.get("PASSLIB_TEST_MODE", "default").strip().lower()
)
def TEST_MODE(min=None, max=None):
"""check if test for specified mode should be enabled.
``"quick"``
run the bare minimum tests to ensure functionality.
variable-cost hashes are tested at their lowest setting.
hash algorithms are only tested against the backend that will
be used on the current host. no fuzz testing is done.
``"default"``
same as ``"quick"``, except: hash algorithms are tested
at default levels, and a brief round of fuzz testing is done
for each hash.
``"full"``
extra regression and internal tests are enabled, hash algorithms are tested
against all available backends, unavailable ones are mocked whre possible,
additional time is devoted to fuzz testing.
"""
if min and _test_mode < _TEST_MODES.index(min):
return False
if max and _test_mode > _TEST_MODES.index(max): # noqa: SIM103
return False
return True
def has_relaxed_setting(handler):
"""check if handler supports 'relaxed' kwd"""
# FIXME: I've been lazy, should probably just add 'relaxed' kwd
# to all handlers that derive from GenericHandler
# ignore wrapper classes for now.. though could introspec.
if hasattr(handler, "orig_prefix"):
return False
return "relaxed" in handler.setting_kwds or issubclass(handler, uh.GenericHandler)
def get_effective_rounds(handler, rounds=None):
"""get effective rounds value from handler"""
handler = unwrap_handler(handler)
return handler(rounds=rounds, use_defaults=True).rounds
def is_default_backend(handler, backend):
"""check if backend is the default for source"""
try:
orig = handler.get_backend()
except MissingBackendError:
return False
try:
handler.set_backend("default")
return handler.get_backend() == backend
finally:
handler.set_backend(orig)
def iter_alt_backends(handler, current=None, fallback=False):
"""
iterate over alternate backends available to handler.
.. warning::
not thread-safe due to has_backend() call
"""
if current is None:
current = handler.get_backend()
backends = handler.backends
idx = backends.index(current) + 1 if fallback else 0
for backend in backends[idx:]:
if backend != current and handler.has_backend(backend):
yield backend
def get_alt_backend(*args, **kwds):
for backend in iter_alt_backends(*args, **kwds):
return backend
return None
def unwrap_handler(handler):
"""return original handler, removing any wrapper objects"""
while hasattr(handler, "wrapped"):
handler = handler.wrapped
return handler
def handler_derived_from(handler, base):
"""
test if <handler> was derived from <base> via <base.using()>.
"""
# XXX: need way to do this more formally via ifc,
# for now just hacking in the cases we encounter in testing.
if handler == base:
return True
if isinstance(handler, uh.PrefixWrapper):
while handler:
if handler == base:
return True
# helper set by PrefixWrapper().using() just for this case...
handler = handler._derived_from
return False
if isinstance(handler, type) and issubclass(handler, uh.MinimalHandler):
return issubclass(handler, base)
raise NotImplementedError(f"don't know how to inspect handler: {handler!r}")
@contextlib.contextmanager
def patch_calc_min_rounds(handler):
"""
internal helper for do_config_encrypt() --
context manager which temporarily replaces handler's _calc_checksum()
with one that uses min_rounds; useful when trying to generate config
with high rounds value, but don't care if output is correct.
"""
if isinstance(handler, type) and issubclass(handler, uh.HasRounds):
# XXX: also require GenericHandler for this branch?
wrapped = handler._calc_checksum
def wrapper(self, *args, **kwds):
rounds = self.rounds
try:
self.rounds = self.min_rounds
return wrapped(self, *args, **kwds)
finally:
self.rounds = rounds
handler._calc_checksum = wrapper
try:
yield
finally:
handler._calc_checksum = wrapped
elif isinstance(handler, uh.PrefixWrapper):
with patch_calc_min_rounds(handler.wrapped):
yield
else:
yield
return
def set_file(path, content):
"""set file to specified bytes"""
if isinstance(content, str):
content = content.encode("utf-8")
with open(path, "wb") as fh:
fh.write(content)
def get_file(path):
"""read file as bytes"""
with open(path, "rb") as fh:
return fh.read()
def tonn(source):
"""convert native string to non-native string"""
if isinstance(source, str):
return source.encode("utf-8")
return source
def hb(source):
"""
helper for represent byte strings in hex.
usage: ``hb("deadbeef23")``
"""
return unhexlify(re.sub(r"\s", "", source))
def limit(value, lower, upper):
if value < lower:
return lower
if value > upper:
return upper
return value
def quicksleep(delay):
"""because time.sleep() doesn't even have 10ms accuracy on some OSes"""
start = tick()
while tick() - start < delay:
pass
def time_call(func, setup=None, maxtime=1, bestof=10):
"""
timeit() wrapper which tries to get as accurate a measurement as possible w/in maxtime seconds.
:returns:
``(avg_seconds_per_call, log10_number_of_repetitions)``
"""
from timeit import Timer
timer = Timer(func, setup=setup or "")
number = 1
end = tick() + maxtime
while True:
delta = min(timer.repeat(bestof, number))
if tick() >= end:
return delta / number, int(math.log10(number))
number *= 10
def run_with_fixed_seeds(count=128, master_seed=0x243F6A8885A308D3):
"""
decorator run test method w/ multiple fixed seeds.
"""
def builder(func):
@wraps(func)
def wrapper(*args, **kwds):
rng = random.Random(master_seed)
for _ in range(count):
kwds["seed"] = rng.getrandbits(32)
func(*args, **kwds)
return wrapper
return builder
class TestCase(unittest.TestCase):
"""passlib-specific test case class
this class adds a number of features to the standard TestCase...
* common prefix for all test descriptions
* resets warnings filter & registry for every test
* tweaks to message formatting
* __msg__ kwd added to assertRaises()
* suite of methods for matching against warnings
"""
# ---------------------------------------------------------------
# make it easy for test cases to add common prefix to shortDescription
# ---------------------------------------------------------------
# string prepended to all tests in TestCase
descriptionPrefix: str | None = None
def shortDescription(self):
"""wrap shortDescription() method to prepend descriptionPrefix"""
desc = super().shortDescription()
prefix = self.descriptionPrefix
if prefix:
desc = f"{prefix}: {desc or str(self)}"
return desc
# ---------------------------------------------------------------
# hack things so nose and ut2 both skip subclasses who have
# "__unittest_skip=True" set, or whose names start with "_"
# ---------------------------------------------------------------
@classproperty
def __unittest_skip__(cls):
# NOTE: this attr is technically a unittest internal detail.
name = cls.__name__
return name.startswith("_") or getattr(cls, f"_{name}__unittest_skip", False)
@classproperty
def __test__(cls):
# make nose just proxy __unittest_skip__
return not cls.__unittest_skip__
# flag to skip *this* class
__unittest_skip = True
# ---------------------------------------------------------------
# reset warning filters & registry before each test
# ---------------------------------------------------------------
# flag to reset all warning filters & ignore state
resetWarningState = True
def setUp(self):
super().setUp()
self.setUpWarnings()
# have uh.debug_only_repr() return real values for duration of test
self.patchAttr(exc, "ENABLE_DEBUG_ONLY_REPR", True)
def setUpWarnings(self):
"""helper to init warning filters before subclass setUp()"""
if self.resetWarningState:
ctx = reset_warnings()
ctx.__enter__()
self.addCleanup(ctx.__exit__)
# ignore security warnings, tests may deliberately cause these
# TODO: may want to filter out a few of this, but not blanket filter...
# warnings.filterwarnings("ignore", category=exc.PasslibSecurityWarning)
# ignore warnings about PasswordHash features deprecated in 1.7
# TODO: should be cleaned in 2.0, when support will be dropped.
# should be kept until then, so we test the legacy paths.
warnings.filterwarnings(
"ignore",
r"the method .*\.(encrypt|genconfig|genhash)\(\) is deprecated",
)
warnings.filterwarnings("ignore", r"the 'vary_rounds' option is deprecated")
# ---------------------------------------------------------------
# tweak message formatting so longMessage mode is only enabled
# if msg ends with ":", and turn on longMessage by default.
# ---------------------------------------------------------------
longMessage = True
def _formatMessage(self, msg, std):
if self.longMessage and msg and msg.rstrip().endswith(":"):
return f"{msg.rstrip()} {std}"
return msg or std
def require_stringprep(self):
"""helper to skip test if stringprep is missing"""
from passlib.utils import stringprep
if not stringprep:
from passlib.utils import _stringprep_missing_reason
raise self.skipTest(
"not available - stringprep module is " + _stringprep_missing_reason
)
def require_TEST_MODE(self, level):
"""skip test for all PASSLIB_TEST_MODE values below <level>"""
if not TEST_MODE(level):
raise self.skipTest(f"requires >= {level!r} test mode")
#: global thread lock for random state
#: XXX: could split into global & per-instance locks if need be
_random_global_lock = threading.Lock()
#: cache of global seed value, initialized on first call to getRandom()
_random_global_seed = None
#: per-instance cache of name -> RNG
_random_cache = None
def getRandom(self, name="default", seed=None):
"""
Return a :class:`random.Random` object for current test method to use.
Within an instance, multiple calls with the same name will return
the same object.
When first created, each RNG will be seeded with value derived from
a global seed, the test class module & name, the current test method name,
and the **name** parameter.
The global seed taken from the $RANDOM_TEST_SEED env var,
the $PYTHONHASHSEED env var, or a randomly generated the
first time this method is called. In all cases, the value
is logged for reproducibility.
:param name:
name to uniquely identify separate RNGs w/in a test
(e.g. for threaded tests).
:param seed:
override global seed when initialzing rng.
:rtype: random.Random
"""
# check cache
cache = self._random_cache
if cache and name in cache:
return cache[name]
with self._random_global_lock:
# check cache again, and initialize it
cache = self._random_cache
if cache and name in cache:
return cache[name]
if not cache:
cache = self._random_cache = {}
# init global seed
global_seed = seed or TestCase._random_global_seed
if global_seed is None:
# NOTE: checking PYTHONHASHSEED, because if that's set,
# the test runner wants something reproducible.
global_seed = TestCase._random_global_seed = int(
os.environ.get("RANDOM_TEST_SEED")
or os.environ.get("PYTHONHASHSEED")
or sys_rng.getrandbits(32)
)
# XXX: would it be better to print() this?
log.info("using RANDOM_TEST_SEED=%d", global_seed)
# create seed
cls = type(self)
source = "\n".join(
[
str(global_seed),
cls.__module__,
cls.__name__,
self._testMethodName,
name,
]
)
digest = hashlib.sha256(source.encode("utf-8")).hexdigest()
seed = int(digest[:16], 16)
# create rng
value = cache[name] = random.Random(seed)
return value
@contextlib.contextmanager
def subTest(self, *args, **kwds):
"""
wrapper for .subTest() which traps SkipTest errors.
(see source for details)
"""
# this function works around issue that as 2020-10-08,
# .subTest() doesn't play nicely w/ .skipTest();
# and also makes it hard to debug which subtest had a failure.
# (see https://bugs.python.org/issue25894 and https://bugs.python.org/issue35327)
# this method traps skipTest exceptions, and adds some logging to help debug
# which subtest caused the issue.
# setup way to log subtest info
# XXX: would like better way to inject messages into test output;
# but this at least gets us something for debugging...
# NOTE: this hack will miss parent params if called from nested .subTest()
def _render_title(_msg=None, **params):
out = f"[{_msg}] " if _msg else ""
if params:
out += "({})".format(
" ".join("{}={!r}".format(*tuple(item)) for item in params.items())
)
return out.strip() or "<subtest>"
test_log = self.getLogger()
title = _render_title(*args, **kwds)
# run the subtest
ctx = super().subTest(*args, **kwds)
with ctx:
test_log.info("running subtest: %s", title)
try:
yield
except SkipTest:
# silence "SkipTest" exceptions, want to keep running next subtest.
test_log.info("subtest skipped: %s", title)
# XXX: should revisit whether latest py3 version of UTs handle this ok,
# meaning it's safe to re-raise this.
return
except Exception as err:
# log unhandled exception occurred
# (assuming traceback will be reported up higher, so not bothering here)
test_log.warning(
"subtest failed: %s: %s: %r", title, type(err).__name__, str(err)
)
raise
# XXX: check for "failed" state in ``self._outcome`` before writing this?
test_log.info("subtest passed: %s", title)
_mktemp_queue = None
def mktemp(self, *args, **kwds):
"""create temp file that's cleaned up at end of test"""
fd, path = tempfile.mkstemp(*args, **kwds)
os.close(fd)
queue = self._mktemp_queue
if queue is None:
queue = self._mktemp_queue = []
def cleaner():
for path in queue:
if os.path.exists(path):
os.remove(path)
del queue[:]
self.addCleanup(cleaner)
queue.append(path)
return path
def patchAttr(self, obj, attr, value, require_existing=True, wrap=False):
"""monkeypatch object value, restoring original value on cleanup"""
try:
orig = getattr(obj, attr)
except AttributeError:
if require_existing:
raise
def cleanup():
with contextlib.suppress(AttributeError):
delattr(obj, attr)
self.addCleanup(cleanup)
else:
self.addCleanup(setattr, obj, attr, orig)
if wrap:
value = partial(value, orig)
wraps(orig)(value)
setattr(obj, attr, value)
def getLogger(self):
"""
return logger named after current test.
"""
cls = type(self)
path = cls.__module__ + "." + cls.__qualname__
name = self._testMethodName
if name:
path = path + "." + name
return logging.getLogger(path)
RESERVED_BACKEND_NAMES = ["any", "default"]
def doesnt_require_backend(func):
"""
decorator for HandlerCase.create_backend_case() --
used to decorate methods that should be run even if backend isn't present
(by default, full test suite is skipped when backend is missing)
NOTE: tests decorated with this should not rely on handler have expected (or any!) backend.
"""
func._doesnt_require_backend = True
return func
class HandlerCase(TestCase):
"""base class for testing password hash handlers (esp passlib.utils.handlers subclasses)
In order to use this to test a handler,
create a subclass will all the appropriate attributes
filled as listed in the example below,
and run the subclass via unittest.
.. todo::
Document all of the options HandlerCase offers.
.. note::
This is subclass of :class:`unittest.TestCase`.
"""
# ---------------------------------------------------------------
# handler setup
# ---------------------------------------------------------------
# handler class to test [required]
handler: type[PasswordHash] | PrefixWrapper | None = None
# if set, run tests against specified backend
backend: str | None = None
# ---------------------------------------------------------------
# test vectors
# ---------------------------------------------------------------
# list of (secret, hash) tuples which are known to be correct
known_correct_hashes: list[Any] = []
# list of (config, secret, hash) tuples are known to be correct
known_correct_configs: list[tuple[str, str, str]] = []
# list of (alt_hash, secret, hash) tuples, where alt_hash is a hash
# using an alternate representation that should be recognized and verify
# correctly, but should be corrected to match hash when passed through
# genhash()
known_alternate_hashes: list[tuple[str, str | tuple[str, ...], str]] = []
# hashes so malformed they aren't even identified properly
known_unidentified_hashes: list[str | bytes] = []
# hashes which are identifiabled but malformed - they should identify()
# as True, but cause an error when passed to genhash/verify.
known_malformed_hashes: list[str | bytes] = []
# list of (handler name, hash) pairs for other algorithm's hashes that
# handler shouldn't identify as belonging to it this list should generally
# be sufficient (if handler name in list, that entry will be skipped)
known_other_hashes = [
("des_crypt", "6f8c114b58f2c"),
("md5_crypt", "$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6o."),
(
"sha512_crypt",
"$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywW"
"vt0RLE8uZ4oPwcelCjmw2kSYu.Ec6ycULevoBK25fs2xXgMNrCzIMVcgEJAstJeonj1",
),
]
# passwords used to test basic hash behavior - generally
# don't need to be overidden.
stock_passwords = ["test", "\u20ac\u00a5$", b"\xe2\x82\xac\xc2\xa5$"]
# ---------------------------------------------------------------
# option flags
# ---------------------------------------------------------------
# whether hash is case insensitive
# True, False, or special value "verify-only" (which indicates
# hash contains case-sensitive portion, but verifies is case-insensitive)
secret_case_insensitive: str | bool = False
# flag if scheme accepts ALL hash strings (e.g. plaintext)
accepts_all_hashes = False
# flag if scheme has "is_disabled" set, and contains 'salted' data
disabled_contains_salt = False
# flag/hack to filter PasslibHashWarning issued by test_72_configs()
filter_config_warnings = False
# forbid certain characters in passwords
@classproperty
def forbidden_characters(cls):
# anything that supports crypt() interface should forbid null chars,
# since crypt() uses null-terminated strings.
if "os_crypt" in getattr(cls.handler, "backends", ()):
return b"\x00"
return None
__unittest_skip = True
@property
def descriptionPrefix(self):
handler = self.handler
name = handler.name
if hasattr(handler, "get_backend"):
name += f" ({handler.get_backend()} backend)"
return name
# ---------------------------------------------------------------
# configuration helpers
# ---------------------------------------------------------------
@classmethod
def iter_known_hashes(cls):
"""iterate through known (secret, hash) pairs"""
for secret, hash in cls.known_correct_hashes:
yield secret, hash
for config, secret, hash in cls.known_correct_configs:
yield secret, hash
for alt, secret, hash in cls.known_alternate_hashes:
yield secret, hash
def get_sample_hash(self):
"""test random sample secret/hash pair"""
known = list(self.iter_known_hashes())
return self.getRandom().choice(known)
# ---------------------------------------------------------------
# test helpers
# ---------------------------------------------------------------
def check_verify(self, secret, hash, msg=None, negate=False):
"""helper to check verify() outcome, honoring is_disabled_handler"""
result = self.do_verify(secret, hash)
assert result is True or result is False, (
f"verify() returned non-boolean value: {result!r}"
)
if self.handler.is_disabled or negate:
if not result:
return
if not msg:
msg = f"verify incorrectly returned True: secret={secret!r}, hash={hash!r}"
raise self.failureException(msg)
if result:
return
if not msg:
msg = f"verify failed: secret={secret!r}, hash={hash!r}"
raise self.failureException(msg)
def check_returned_native_str(self, result, func_name):
assert isinstance(result, str), (
f"{func_name}() failed to return native string: {result!r}"
)
# ---------------------------------------------------------------
# PasswordHash helpers - wraps all calls to PasswordHash api,
# so that subclasses can fill in defaults and account for other specialized behavior
# ---------------------------------------------------------------
def populate_settings(self, kwds):
"""subclassable method to populate default settings"""
# use lower rounds settings for certain test modes
handler = self.handler
if "rounds" in handler.setting_kwds and "rounds" not in kwds:
mn = handler.min_rounds
df = handler.default_rounds
if TEST_MODE(max="quick"):
# use minimum rounds for quick mode
kwds["rounds"] = max(3, mn)
else:
# use default/16 otherwise
factor = 3
if getattr(handler, "rounds_cost", None) == "log2":
df -= factor
else:
df //= 1 << factor
kwds["rounds"] = max(3, mn, df)
def populate_context(self, secret, kwds):
"""subclassable method allowing 'secret' to be encode context kwds"""
return secret
# TODO: rename to do_hash() to match new API
def do_encrypt(
self, secret, use_encrypt=False, handler=None, context=None, **settings
):
"""call handler's hash() method with specified options"""
self.populate_settings(settings)
if context is None:
context = {}
secret = self.populate_context(secret, context)
if use_encrypt:
# use legacy 1.6 api
warnings_context = contextlib.nullcontext()
if settings:
context.update(**settings)
warnings_context = pytest.warns(
match="passing settings to.*is deprecated"
)
with warnings_context:
return (handler or self.handler).encrypt(secret, **context)
else:
# use 1.7 api
return (handler or self.handler).using(**settings).hash(secret, **context)
def do_verify(self, secret, hash, handler=None, **kwds):
"""call handler's verify method"""
secret = self.populate_context(secret, kwds)
return (handler or self.handler).verify(secret, hash, **kwds)
def do_identify(self, hash):
"""call handler's identify method"""
return self.handler.identify(hash)
def do_genconfig(self, **kwds):
"""call handler's genconfig method with specified options"""
self.populate_settings(kwds)
return self.handler.genconfig(**kwds)
def do_genhash(self, secret, config, **kwds):
"""call handler's genhash method with specified options"""
secret = self.populate_context(secret, kwds)
return self.handler.genhash(secret, config, **kwds)
def do_stub_encrypt(self, handler=None, context=None, **settings):
"""
return sample hash for handler, w/o caring if digest is valid
(uses some monkeypatching to minimize digest calculation cost)
"""
handler = (handler or self.handler).using(**settings)
if context is None:
context = {}
secret = self.populate_context("", context)
with patch_calc_min_rounds(handler):
return handler.hash(secret, **context)
# ---------------------------------------------------------------
# automatically generate subclasses for testing specific backends,
# and other backend helpers
# ---------------------------------------------------------------
#: default message used by _get_skip_backend_reason()
_BACKEND_NOT_AVAILABLE = "backend not available"
@classmethod
def _get_skip_backend_reason(cls, backend):
"""
helper for create_backend_case() --
returns reason to skip backend, or None if backend should be tested
"""
handler = cls.handler
if not is_default_backend(handler, backend) and not TEST_MODE("full"):
return "only default backend is being tested"
if handler.has_backend(backend):
return None
return cls._BACKEND_NOT_AVAILABLE
@classmethod
def create_backend_case(cls, backend):
handler = cls.handler
name = handler.name
assert hasattr(handler, "backends"), (
"handler must support uh.HasManyBackends protocol"
)
assert backend in handler.backends, f"unknown backend: {backend!r}"
bases = (cls,)
if backend == "os_crypt":
bases += (OsCryptMixin,)
return type(
f"{name}_{backend}_test",
bases,
dict(
descriptionPrefix=f"{name} ({backend} backend)",
backend=backend,
_skip_backend_reason=cls._get_skip_backend_reason(backend),
__module__=cls.__module__,
),
)
#: flag for setUp() indicating this class is disabled due to backend issue;
#: this is only set for dynamic subclasses generated by create_backend_case()
_skip_backend_reason = None
def _test_requires_backend(self):
"""
check if current test method decorated with doesnt_require_backend() helper
"""
meth = getattr(self, self._testMethodName, None)
return not getattr(meth, "_doesnt_require_backend", False)
def setUp(self):
# check if test is disabled due to missing backend;
# and that it wasn't exempted via @doesnt_require_backend() decorator
test_requires_backend = self._test_requires_backend()
if test_requires_backend and self._skip_backend_reason:
raise self.skipTest(self._skip_backend_reason)
super().setUp()
# if needed, select specific backend for duration of test
# NOTE: skipping this if create_backend_case() signalled we're skipping backend
# (can only get here for @doesnt_require_backend decorated methods)
handler = self.handler
backend = self.backend
if backend:
if not hasattr(handler, "set_backend"):
raise RuntimeError("handler doesn't support multiple backends")
try:
self.addCleanup(handler.set_backend, handler.get_backend())
handler.set_backend(backend)
except uh.exc.MissingBackendError:
if test_requires_backend:
raise
# else test is decorated with @doesnt_require_backend, let it through.
# patch some RNG references so they're reproducible.
from passlib.utils import handlers
self.patchAttr(handlers, "rng", self.getRandom("salt generator"))
def test_01_required_attributes(self):
"""validate required attributes"""
handler = self.handler
def ga(name):
return getattr(handler, name, None)
#
# name should be a str, and valid
#
name = ga("name")
assert name, "name not defined:"
assert isinstance(name, str), "name must be native str"
assert name.lower() == name, "name not lower-case:"
assert re.match("^[a-z0-9_]+$", name), (
f"name must be alphanum + underscore: {name!r}"
)
#
# setting_kwds should be specified
#
settings = ga("setting_kwds")
assert settings is not None, "setting_kwds must be defined:"
assert isinstance(settings, tuple), "setting_kwds must be a tuple:"
#
# context_kwds should be specified
#
context = ga("context_kwds")
assert context is not None, "context_kwds must be defined:"
assert isinstance(context, tuple), "context_kwds must be a tuple:"
# XXX: any more checks needed?
def test_02_config_workflow(self):
"""test basic config-string workflow
this tests that genconfig() returns the expected types,
and that identify() and genhash() handle the result correctly.
"""
#
# genconfig() should return native string.
# NOTE: prior to 1.7 could return None, but that's no longer allowed.
#
config = self.do_genconfig()
self.check_returned_native_str(config, "genconfig")
#
# genhash() should always accept genconfig()'s output,
# whether str OR None.
#
result = self.do_genhash("stub", config)
self.check_returned_native_str(result, "genhash")
#
# verify() should never accept config strings
#
# NOTE: changed as of 1.7 -- previously, .verify() should have
# rejected partial config strings returned by genconfig().
# as of 1.7, that feature is deprecated, and genconfig()
# always returns a hash (usually of the empty string)
# so verify should always accept it's output
self.do_verify("", config) # usually true, but not required by protocol
#