test_ext_django.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. """test passlib.ext.django"""
  2. #=============================================================================
  3. # imports
  4. #=============================================================================
  5. # core
  6. from __future__ import absolute_import, division, print_function
  7. import logging; log = logging.getLogger(__name__)
  8. import sys
  9. import re
  10. # site
  11. # pkg
  12. from passlib import apps as _apps, exc, registry
  13. from passlib.apps import django10_context, django14_context, django16_context
  14. from passlib.context import CryptContext
  15. from passlib.ext.django.utils import (
  16. DJANGO_VERSION, MIN_DJANGO_VERSION, DjangoTranslator, quirks,
  17. )
  18. from passlib.utils.compat import iteritems, get_method_function, u
  19. from passlib.utils.decor import memoized_property
  20. # tests
  21. from passlib.tests.utils import TestCase, TEST_MODE, handler_derived_from
  22. from passlib.tests.test_handlers import get_handler_case
  23. # local
  24. __all__ = [
  25. "DjangoBehaviorTest",
  26. "ExtensionBehaviorTest",
  27. "DjangoExtensionTest",
  28. "_ExtensionSupport",
  29. "_ExtensionTest",
  30. ]
  31. #=============================================================================
  32. # configure django settings for testcases
  33. #=============================================================================
  34. # whether we have supported django version
  35. has_min_django = DJANGO_VERSION >= MIN_DJANGO_VERSION
  36. # import and configure empty django settings
  37. # NOTE: we don't want to set up entirety of django, so not using django.setup() directly.
  38. # instead, manually configuring the settings, and setting it up w/ no apps installed.
  39. # in future, may need to alter this so we call django.setup() after setting
  40. # DJANGO_SETTINGS_MODULE to a custom settings module w/ a dummy django app.
  41. if has_min_django:
  42. #
  43. # initialize django settings manually
  44. #
  45. from django.conf import settings, LazySettings
  46. if not isinstance(settings, LazySettings):
  47. # this probably means django globals have been configured already,
  48. # which we don't want, since test cases reset and manipulate settings.
  49. raise RuntimeError("expected django.conf.settings to be LazySettings: %r" % (settings,))
  50. # else configure a blank settings instance for the unittests
  51. if not settings.configured:
  52. settings.configure()
  53. #
  54. # init django apps w/ NO installed apps.
  55. # NOTE: required for django >= 1.9
  56. #
  57. from django.apps import apps
  58. apps.populate(["django.contrib.contenttypes", "django.contrib.auth"])
  59. # log a warning if tested w/ newer version.
  60. # NOTE: this is mainly here as place to mark what version it was run against before release.
  61. if DJANGO_VERSION >= (3, 2):
  62. log.info("this release hasn't been tested against Django %r", DJANGO_VERSION)
  63. #=============================================================================
  64. # support funcs
  65. #=============================================================================
  66. # flag for update_settings() to remove specified key entirely
  67. UNSET = object()
  68. def update_settings(**kwds):
  69. """helper to update django settings from kwds"""
  70. for k,v in iteritems(kwds):
  71. if v is UNSET:
  72. if hasattr(settings, k):
  73. delattr(settings, k)
  74. else:
  75. setattr(settings, k, v)
  76. if has_min_django:
  77. from django.contrib.auth.models import User
  78. class FakeUser(User):
  79. """mock user object for use in testing"""
  80. # NOTE: this mainly just overrides .save() to test commit behavior.
  81. # NOTE: .Meta.app_label required for django >= 1.9
  82. class Meta:
  83. app_label = __name__
  84. @memoized_property
  85. def saved_passwords(self):
  86. return []
  87. def pop_saved_passwords(self):
  88. try:
  89. return self.saved_passwords[:]
  90. finally:
  91. del self.saved_passwords[:]
  92. def save(self, update_fields=None):
  93. # NOTE: ignoring update_fields for test purposes
  94. self.saved_passwords.append(self.password)
  95. def create_mock_setter():
  96. state = []
  97. def setter(password):
  98. state.append(password)
  99. def popstate():
  100. try:
  101. return state[:]
  102. finally:
  103. del state[:]
  104. setter.popstate = popstate
  105. return setter
  106. def check_django_hasher_has_backend(name):
  107. """
  108. check whether django hasher is available;
  109. or if it should be skipped because django lacks third-party library.
  110. """
  111. assert name
  112. from django.contrib.auth.hashers import make_password
  113. try:
  114. make_password("", hasher=name)
  115. return True
  116. except ValueError as err:
  117. if re.match("Couldn't load '.*?' algorithm .* No module named .*", str(err)):
  118. return False
  119. raise
  120. #=============================================================================
  121. # work up stock django config
  122. #=============================================================================
  123. def _modify_django_config(kwds, sha_rounds=None):
  124. """
  125. helper to build django CryptContext config matching expected setup for stock django deploy.
  126. :param kwds:
  127. :param sha_rounds:
  128. :return:
  129. """
  130. # make sure we have dict
  131. if hasattr(kwds, "to_dict"):
  132. # type: CryptContext
  133. kwds = kwds.to_dict()
  134. # update defaults
  135. kwds.update(
  136. # TODO: push this to passlib.apps django contexts
  137. deprecated="auto",
  138. )
  139. # fill in default rounds for current django version, so our sample hashes come back
  140. # unchanged, instead of being upgraded in-place by check_password().
  141. if sha_rounds is None and has_min_django:
  142. from django.contrib.auth.hashers import PBKDF2PasswordHasher
  143. sha_rounds = PBKDF2PasswordHasher.iterations
  144. # modify rounds
  145. if sha_rounds:
  146. kwds.update(
  147. django_pbkdf2_sha1__default_rounds=sha_rounds,
  148. django_pbkdf2_sha256__default_rounds=sha_rounds,
  149. )
  150. return kwds
  151. #----------------------------------------------------
  152. # build config dict that matches stock django
  153. #----------------------------------------------------
  154. # XXX: replace this with code that interrogates default django config directly?
  155. # could then separate out "validation of djangoXX_context objects"
  156. # and "validation that individual hashers match django".
  157. # or maybe add a "get_django_context(django_version)" helper to passlib.apps?
  158. if DJANGO_VERSION >= (2, 1):
  159. stock_config = _modify_django_config(_apps.django21_context)
  160. elif DJANGO_VERSION >= (1, 10):
  161. stock_config = _modify_django_config(_apps.django110_context)
  162. else:
  163. # assert DJANGO_VERSION >= (1, 8)
  164. stock_config = _modify_django_config(_apps.django16_context)
  165. #----------------------------------------------------
  166. # override sample hashes used in test cases
  167. #----------------------------------------------------
  168. from passlib.hash import django_pbkdf2_sha256
  169. sample_hashes = dict(
  170. django_pbkdf2_sha256=("not a password", django_pbkdf2_sha256
  171. .using(rounds=stock_config.get("django_pbkdf2_sha256__default_rounds"))
  172. .hash("not a password"))
  173. )
  174. #=============================================================================
  175. # test utils
  176. #=============================================================================
  177. class _ExtensionSupport(object):
  178. """
  179. test support funcs for loading/unloading extension.
  180. this class is mixed in to various TestCase subclasses.
  181. """
  182. #===================================================================
  183. # support funcs
  184. #===================================================================
  185. @classmethod
  186. def _iter_patch_candidates(cls):
  187. """helper to scan for monkeypatches.
  188. returns tuple containing:
  189. * object (module or class)
  190. * attribute of object
  191. * value of attribute
  192. * whether it should or should not be patched
  193. """
  194. # XXX: this and assert_unpatched() could probably be refactored to use
  195. # the PatchManager class to do the heavy lifting.
  196. from django.contrib.auth import models, hashers
  197. user_attrs = ["check_password", "set_password"]
  198. model_attrs = ["check_password", "make_password"]
  199. hasher_attrs = ["check_password", "make_password", "get_hasher", "identify_hasher",
  200. "get_hashers"]
  201. objs = [(models, model_attrs),
  202. (models.User, user_attrs),
  203. (hashers, hasher_attrs),
  204. ]
  205. for obj, patched in objs:
  206. for attr in dir(obj):
  207. if attr.startswith("_"):
  208. continue
  209. value = obj.__dict__.get(attr, UNSET) # can't use getattr() due to GAE
  210. if value is UNSET and attr not in patched:
  211. continue
  212. value = get_method_function(value)
  213. source = getattr(value, "__module__", None)
  214. if source:
  215. yield obj, attr, source, (attr in patched)
  216. #===================================================================
  217. # verify current patch state
  218. #===================================================================
  219. def assert_unpatched(self):
  220. """
  221. test that django is in unpatched state
  222. """
  223. # make sure we aren't currently patched
  224. mod = sys.modules.get("passlib.ext.django.models")
  225. self.assertFalse(mod and mod.adapter.patched, "patch should not be enabled")
  226. # make sure no objects have been replaced, by checking __module__
  227. for obj, attr, source, patched in self._iter_patch_candidates():
  228. if patched:
  229. self.assertTrue(source.startswith("django.contrib.auth."),
  230. "obj=%r attr=%r was not reverted: %r" %
  231. (obj, attr, source))
  232. else:
  233. self.assertFalse(source.startswith("passlib."),
  234. "obj=%r attr=%r should not have been patched: %r" %
  235. (obj, attr, source))
  236. def assert_patched(self, context=None):
  237. """
  238. helper to ensure django HAS been patched, and is using specified config
  239. """
  240. # make sure we're currently patched
  241. mod = sys.modules.get("passlib.ext.django.models")
  242. self.assertTrue(mod and mod.adapter.patched, "patch should have been enabled")
  243. # make sure only the expected objects have been patched
  244. for obj, attr, source, patched in self._iter_patch_candidates():
  245. if patched:
  246. self.assertTrue(source == "passlib.ext.django.utils",
  247. "obj=%r attr=%r should have been patched: %r" %
  248. (obj, attr, source))
  249. else:
  250. self.assertFalse(source.startswith("passlib."),
  251. "obj=%r attr=%r should not have been patched: %r" %
  252. (obj, attr, source))
  253. # check context matches
  254. if context is not None:
  255. context = CryptContext._norm_source(context)
  256. self.assertEqual(mod.password_context.to_dict(resolve=True),
  257. context.to_dict(resolve=True))
  258. #===================================================================
  259. # load / unload the extension (and verify it worked)
  260. #===================================================================
  261. _config_keys = ["PASSLIB_CONFIG", "PASSLIB_CONTEXT", "PASSLIB_GET_CATEGORY"]
  262. def load_extension(self, check=True, **kwds):
  263. """
  264. helper to load extension with specified config & patch django
  265. """
  266. self.unload_extension()
  267. if check:
  268. config = kwds.get("PASSLIB_CONFIG") or kwds.get("PASSLIB_CONTEXT")
  269. for key in self._config_keys:
  270. kwds.setdefault(key, UNSET)
  271. update_settings(**kwds)
  272. import passlib.ext.django.models
  273. if check:
  274. self.assert_patched(context=config)
  275. def unload_extension(self):
  276. """
  277. helper to remove patches and unload extension
  278. """
  279. # remove patches and unload module
  280. mod = sys.modules.get("passlib.ext.django.models")
  281. if mod:
  282. mod.adapter.remove_patch()
  283. del sys.modules["passlib.ext.django.models"]
  284. # wipe config from django settings
  285. update_settings(**dict((key, UNSET) for key in self._config_keys))
  286. # check everything's gone
  287. self.assert_unpatched()
  288. #===================================================================
  289. # eoc
  290. #===================================================================
  291. # XXX: rename to ExtensionFixture?
  292. # NOTE: would roll this into _ExtensionSupport class;
  293. # but we have to mix that one into django's TestCase classes as well;
  294. # and our TestCase class (and this setUp() method) would foul things up.
  295. class _ExtensionTest(TestCase, _ExtensionSupport):
  296. """
  297. TestCase mixin which makes sure extension is unloaded before test;
  298. and make sure it's unloaded after test as well.
  299. """
  300. #=============================================================================
  301. # setup
  302. #=============================================================================
  303. def setUp(self):
  304. super(_ExtensionTest, self).setUp()
  305. self.require_TEST_MODE("default")
  306. if not DJANGO_VERSION:
  307. raise self.skipTest("Django not installed")
  308. elif not has_min_django:
  309. raise self.skipTest("Django version too old")
  310. # reset to baseline, and verify it worked
  311. self.unload_extension()
  312. # and do the same when the test exits
  313. self.addCleanup(self.unload_extension)
  314. #=============================================================================
  315. # eoc
  316. #=============================================================================
  317. #=============================================================================
  318. # extension tests
  319. #=============================================================================
  320. #: static passwords used by DjangoBehaviorTest methods
  321. PASS1 = "toomanysecrets"
  322. WRONG1 = "letmein"
  323. class DjangoBehaviorTest(_ExtensionTest):
  324. """
  325. tests model to verify it matches django's behavior.
  326. running this class verifies the tests correctly assert what Django itself does.
  327. running the ExtensionBehaviorTest subclass below verifies "passlib.ext.django"
  328. matches what the tests assert.
  329. """
  330. #=============================================================================
  331. # class attrs
  332. #=============================================================================
  333. descriptionPrefix = "verify django behavior"
  334. #: tracks whether tests should assume "passlib.ext.django" monkeypatch is applied.
  335. #: (set to True by ExtensionBehaviorTest subclass)
  336. patched = False
  337. #: dict containing CryptContext() config which should match current django deploy.
  338. #: used by tests to verify expected behavior.
  339. config = stock_config
  340. # NOTE: if this test fails, it means we're not accounting for
  341. # some part of django's hashing logic, or that this is
  342. # running against an untested version of django with a new
  343. # hashing policy.
  344. #=============================================================================
  345. # test helpers
  346. #=============================================================================
  347. @memoized_property
  348. def context(self):
  349. """
  350. per-test CryptContext() created from .config.
  351. """
  352. return CryptContext._norm_source(self.config)
  353. def assert_unusable_password(self, user):
  354. """
  355. check that user object is set to 'unusable password' constant
  356. """
  357. self.assertTrue(user.password.startswith("!"))
  358. self.assertFalse(user.has_usable_password())
  359. self.assertEqual(user.pop_saved_passwords(), [])
  360. def assert_valid_password(self, user, hash=UNSET, saved=None):
  361. """
  362. check that user object has a usable password hash.
  363. :param hash: optionally check it has this exact hash
  364. :param saved: check that mock commit history for user.password matches this list
  365. """
  366. if hash is UNSET:
  367. self.assertNotEqual(user.password, "!")
  368. self.assertNotEqual(user.password, None)
  369. else:
  370. self.assertEqual(user.password, hash)
  371. self.assertTrue(user.has_usable_password(),
  372. "hash should be usable: %r" % (user.password,))
  373. self.assertEqual(user.pop_saved_passwords(),
  374. [] if saved is None else [saved])
  375. #=============================================================================
  376. # test hashing interface
  377. #-----------------------------------------------------------------------------
  378. # these functions are run against both the actual django code,
  379. # to verify the assumptions of the unittests are correct;
  380. # and run against the passlib extension, to verify it matches those assumptions.
  381. #
  382. # these tests check the following django methods:
  383. # User.set_password()
  384. # User.check_password()
  385. # make_password() -- 1.4 only
  386. # check_password()
  387. # identify_hasher()
  388. # User.has_usable_password()
  389. # User.set_unusable_password()
  390. #
  391. # XXX: this take a while to run. what could be trimmed?
  392. #
  393. # TODO: add get_hasher() checks where appropriate in tests below.
  394. #=============================================================================
  395. def test_extension_config(self):
  396. """
  397. test extension config is loaded correctly
  398. """
  399. if not self.patched:
  400. raise self.skipTest("extension not loaded")
  401. ctx = self.context
  402. # contexts should match
  403. from django.contrib.auth.hashers import check_password
  404. from passlib.ext.django.models import password_context
  405. self.assertEqual(password_context.to_dict(resolve=True), ctx.to_dict(resolve=True))
  406. # should have patched both places
  407. from django.contrib.auth.models import check_password as check_password2
  408. self.assertEqual(check_password2, check_password)
  409. def test_default_algorithm(self):
  410. """
  411. test django's default algorithm
  412. """
  413. ctx = self.context
  414. # NOTE: import has to be done w/in method, in case monkeypatching is applied by setUp()
  415. from django.contrib.auth.hashers import make_password
  416. # User.set_password() should use default alg
  417. user = FakeUser()
  418. user.set_password(PASS1)
  419. self.assertTrue(ctx.handler().verify(PASS1, user.password))
  420. self.assert_valid_password(user)
  421. # User.check_password() - n/a
  422. # make_password() should use default alg
  423. hash = make_password(PASS1)
  424. self.assertTrue(ctx.handler().verify(PASS1, hash))
  425. # check_password() - n/a
  426. def test_empty_password(self):
  427. """
  428. test how methods handle empty string as password
  429. """
  430. ctx = self.context
  431. # NOTE: import has to be done w/in method, in case monkeypatching is applied by setUp()
  432. from django.contrib.auth.hashers import (
  433. check_password,
  434. make_password,
  435. is_password_usable,
  436. identify_hasher,
  437. )
  438. # User.set_password() should use default alg
  439. user = FakeUser()
  440. user.set_password('')
  441. hash = user.password
  442. self.assertTrue(ctx.handler().verify('', hash))
  443. self.assert_valid_password(user, hash)
  444. # User.check_password() should return True
  445. self.assertTrue(user.check_password(""))
  446. self.assert_valid_password(user, hash)
  447. # XXX: test make_password() ?
  448. # TODO: is_password_usable()
  449. # identify_hasher() -- na
  450. # check_password() should return True
  451. self.assertTrue(check_password("", hash))
  452. def test_unusable_flag(self):
  453. """
  454. test how methods handle 'unusable flag' in hash
  455. """
  456. # NOTE: import has to be done w/in method, in case monkeypatching is applied by setUp()
  457. from django.contrib.auth.hashers import (
  458. check_password,
  459. make_password,
  460. is_password_usable,
  461. identify_hasher,
  462. )
  463. # sanity check via user.set_unusable_password()
  464. user = FakeUser()
  465. user.set_unusable_password()
  466. self.assert_unusable_password(user)
  467. # ensure User.set_password() sets unusable flag
  468. user = FakeUser()
  469. user.set_password(None)
  470. self.assert_unusable_password(user)
  471. # User.check_password() should always fail
  472. self.assertFalse(user.check_password(None))
  473. self.assertFalse(user.check_password('None'))
  474. self.assertFalse(user.check_password(''))
  475. self.assertFalse(user.check_password(PASS1))
  476. self.assertFalse(user.check_password(WRONG1))
  477. self.assert_unusable_password(user)
  478. # make_password() should also set flag
  479. self.assertTrue(make_password(None).startswith("!"))
  480. # check_password() should return False (didn't handle disabled under 1.3)
  481. self.assertFalse(check_password(PASS1, '!'))
  482. # identify_hasher() and is_password_usable() should reject it
  483. self.assertFalse(is_password_usable(user.password))
  484. self.assertRaises(ValueError, identify_hasher, user.password)
  485. def test_none_hash_value(self):
  486. """
  487. test how methods handle None as hash value
  488. """
  489. patched = self.patched
  490. # NOTE: import has to be done w/in method, in case monkeypatching is applied by setUp()
  491. from django.contrib.auth.hashers import (
  492. check_password,
  493. make_password,
  494. is_password_usable,
  495. identify_hasher,
  496. )
  497. # User.set_password() - n/a
  498. # User.check_password() - returns False
  499. user = FakeUser()
  500. user.password = None
  501. if quirks.none_causes_check_password_error and not patched:
  502. # django 2.1+
  503. self.assertRaises(TypeError, user.check_password, PASS1)
  504. else:
  505. self.assertFalse(user.check_password(PASS1))
  506. self.assertEqual(user.has_usable_password(),
  507. quirks.empty_is_usable_password)
  508. # TODO: is_password_usable()
  509. # make_password() - n/a
  510. # check_password() - error
  511. if quirks.none_causes_check_password_error and not patched:
  512. self.assertRaises(TypeError, check_password, PASS1, None)
  513. else:
  514. self.assertFalse(check_password(PASS1, None))
  515. # identify_hasher() - error
  516. self.assertRaises(TypeError, identify_hasher, None)
  517. def test_empty_hash_value(self):
  518. """
  519. test how methods handle empty string as hash value
  520. """
  521. # NOTE: import has to be done w/in method, in case monkeypatching is applied by setUp()
  522. from django.contrib.auth.hashers import (
  523. check_password,
  524. make_password,
  525. is_password_usable,
  526. identify_hasher,
  527. )
  528. # User.set_password() - n/a
  529. # User.check_password()
  530. # As of django 1.5, blank hash returns False (django issue 18453)
  531. user = FakeUser()
  532. user.password = ""
  533. self.assertFalse(user.check_password(PASS1))
  534. # verify hash wasn't changed/upgraded during check_password() call
  535. self.assertEqual(user.password, "")
  536. self.assertEqual(user.pop_saved_passwords(), [])
  537. # User.has_usable_password()
  538. self.assertEqual(user.has_usable_password(), quirks.empty_is_usable_password)
  539. # TODO: is_password_usable()
  540. # make_password() - n/a
  541. # check_password()
  542. self.assertFalse(check_password(PASS1, ""))
  543. # identify_hasher() - throws error
  544. self.assertRaises(ValueError, identify_hasher, "")
  545. def test_invalid_hash_values(self):
  546. """
  547. test how methods handle invalid hash values.
  548. """
  549. for hash in [
  550. "$789$foo", # empty identifier
  551. ]:
  552. with self.subTest(hash=hash):
  553. self._do_test_invalid_hash_value(hash)
  554. def _do_test_invalid_hash_value(self, hash):
  555. # NOTE: import has to be done w/in method, in case monkeypatching is applied by setUp()
  556. from django.contrib.auth.hashers import (
  557. check_password,
  558. make_password,
  559. is_password_usable,
  560. identify_hasher,
  561. )
  562. # User.set_password() - n/a
  563. # User.check_password()
  564. # As of django 1.5, invalid hash returns False (side effect of django issue 18453)
  565. user = FakeUser()
  566. user.password = hash
  567. self.assertFalse(user.check_password(PASS1))
  568. # verify hash wasn't changed/upgraded during check_password() call
  569. self.assertEqual(user.password, hash)
  570. self.assertEqual(user.pop_saved_passwords(), [])
  571. # User.has_usable_password()
  572. self.assertEqual(user.has_usable_password(), quirks.invalid_is_usable_password)
  573. # TODO: is_password_usable()
  574. # make_password() - n/a
  575. # check_password()
  576. self.assertFalse(check_password(PASS1, hash))
  577. # identify_hasher() - throws error
  578. self.assertRaises(ValueError, identify_hasher, hash)
  579. def test_available_schemes(self):
  580. """
  581. run a bunch of subtests for each hasher available in the default django setup
  582. (as determined by reading self.context)
  583. """
  584. for scheme in self.context.schemes():
  585. with self.subTest(scheme=scheme):
  586. self._do_test_available_scheme(scheme)
  587. def _do_test_available_scheme(self, scheme):
  588. """
  589. helper to test how specific hasher behaves.
  590. :param scheme: *passlib* name of hasher (e.g. "django_pbkdf2_sha256")
  591. """
  592. log = self.getLogger()
  593. ctx = self.context
  594. patched = self.patched
  595. setter = create_mock_setter()
  596. # NOTE: import has to be done w/in method, in case monkeypatching is applied by setUp()
  597. from django.contrib.auth.hashers import (
  598. check_password,
  599. make_password,
  600. is_password_usable,
  601. identify_hasher,
  602. )
  603. #-------------------------------------------------------
  604. # setup constants & imports, pick a sample secret/hash combo
  605. #-------------------------------------------------------
  606. handler = ctx.handler(scheme)
  607. log.debug("testing scheme: %r => %r", scheme, handler)
  608. deprecated = ctx.handler(scheme).deprecated
  609. assert not deprecated or scheme != ctx.default_scheme()
  610. try:
  611. testcase = get_handler_case(scheme)
  612. except exc.MissingBackendError:
  613. raise self.skipTest("backend not available")
  614. assert handler_derived_from(handler, testcase.handler)
  615. if handler.is_disabled:
  616. raise self.skipTest("skip disabled hasher")
  617. # verify that django has a backend available
  618. # (since our hasher may use different set of backends,
  619. # get_handler_case() above may work, but django will have nothing)
  620. if not patched and not check_django_hasher_has_backend(handler.django_name):
  621. assert scheme in ["django_bcrypt", "django_bcrypt_sha256", "django_argon2"], \
  622. "%r scheme should always have active backend" % scheme
  623. log.warning("skipping scheme %r due to missing django dependency", scheme)
  624. raise self.skipTest("skip due to missing dependency")
  625. # find a sample (secret, hash) pair to test with
  626. try:
  627. secret, hash = sample_hashes[scheme]
  628. except KeyError:
  629. get_sample_hash = testcase("setUp").get_sample_hash
  630. while True:
  631. secret, hash = get_sample_hash()
  632. if secret: # don't select blank passwords
  633. break
  634. other = 'dontletmein'
  635. #-------------------------------------------------------
  636. # User.set_password() - not tested here
  637. #-------------------------------------------------------
  638. #-------------------------------------------------------
  639. # User.check_password()+migration against known hash
  640. #-------------------------------------------------------
  641. user = FakeUser()
  642. user.password = hash
  643. # check against invalid password
  644. self.assertFalse(user.check_password(None))
  645. ##self.assertFalse(user.check_password(''))
  646. self.assertFalse(user.check_password(other))
  647. self.assert_valid_password(user, hash)
  648. # check against valid password
  649. self.assertTrue(user.check_password(secret))
  650. # check if it upgraded the hash
  651. # NOTE: needs_update kept separate in case we need to test rounds.
  652. needs_update = deprecated
  653. if needs_update:
  654. self.assertNotEqual(user.password, hash)
  655. self.assertFalse(handler.identify(user.password))
  656. self.assertTrue(ctx.handler().verify(secret, user.password))
  657. self.assert_valid_password(user, saved=user.password)
  658. else:
  659. self.assert_valid_password(user, hash)
  660. # don't need to check rest for most deployments
  661. if TEST_MODE(max="default"):
  662. return
  663. #-------------------------------------------------------
  664. # make_password() correctly selects algorithm
  665. #-------------------------------------------------------
  666. alg = DjangoTranslator().passlib_to_django_name(scheme)
  667. hash2 = make_password(secret, hasher=alg)
  668. self.assertTrue(handler.verify(secret, hash2))
  669. #-------------------------------------------------------
  670. # check_password()+setter against known hash
  671. #-------------------------------------------------------
  672. # should call setter only if it needs_update
  673. self.assertTrue(check_password(secret, hash, setter=setter))
  674. self.assertEqual(setter.popstate(), [secret] if needs_update else [])
  675. # should not call setter
  676. self.assertFalse(check_password(other, hash, setter=setter))
  677. self.assertEqual(setter.popstate(), [])
  678. ### check preferred kwd is ignored (feature we don't currently support fully)
  679. ##self.assertTrue(check_password(secret, hash, setter=setter, preferred='fooey'))
  680. ##self.assertEqual(setter.popstate(), [secret])
  681. # TODO: get_hasher()
  682. #-------------------------------------------------------
  683. # identify_hasher() recognizes known hash
  684. #-------------------------------------------------------
  685. self.assertTrue(is_password_usable(hash))
  686. name = DjangoTranslator().django_to_passlib_name(identify_hasher(hash).algorithm)
  687. self.assertEqual(name, scheme)
  688. #===================================================================
  689. # eoc
  690. #===================================================================
  691. #===================================================================
  692. # extension fidelity tests
  693. #===================================================================
  694. class ExtensionBehaviorTest(DjangoBehaviorTest):
  695. """
  696. test that "passlib.ext.django" conforms to behavioral assertions in DjangoBehaviorTest
  697. """
  698. descriptionPrefix = "verify extension behavior"
  699. config = dict(
  700. schemes="sha256_crypt,md5_crypt,des_crypt",
  701. deprecated="des_crypt",
  702. )
  703. def setUp(self):
  704. super(ExtensionBehaviorTest, self).setUp()
  705. # always load extension before each test
  706. self.load_extension(PASSLIB_CONFIG=self.config)
  707. self.patched = True
  708. #===================================================================
  709. # extension internal tests
  710. #===================================================================
  711. class DjangoExtensionTest(_ExtensionTest):
  712. """
  713. test the ``passlib.ext.django`` plugin
  714. """
  715. #===================================================================
  716. # class attrs
  717. #===================================================================
  718. descriptionPrefix = "passlib.ext.django plugin"
  719. #===================================================================
  720. # monkeypatch testing
  721. #===================================================================
  722. def test_00_patch_control(self):
  723. """test set_django_password_context patch/unpatch"""
  724. # check config="disabled"
  725. self.load_extension(PASSLIB_CONFIG="disabled", check=False)
  726. self.assert_unpatched()
  727. # check legacy config=None
  728. with self.assertWarningList("PASSLIB_CONFIG=None is deprecated"):
  729. self.load_extension(PASSLIB_CONFIG=None, check=False)
  730. self.assert_unpatched()
  731. # try stock django 1.0 context
  732. self.load_extension(PASSLIB_CONFIG="django-1.0", check=False)
  733. self.assert_patched(context=django10_context)
  734. # try to remove patch
  735. self.unload_extension()
  736. # patch to use stock django 1.4 context
  737. self.load_extension(PASSLIB_CONFIG="django-1.4", check=False)
  738. self.assert_patched(context=django14_context)
  739. # try to remove patch again
  740. self.unload_extension()
  741. def test_01_overwrite_detection(self):
  742. """test detection of foreign monkeypatching"""
  743. # NOTE: this sets things up, and spot checks two methods,
  744. # this should be enough to verify patch manager is working.
  745. # TODO: test unpatch behavior honors flag.
  746. # configure plugin to use sample context
  747. config = "[passlib]\nschemes=des_crypt\n"
  748. self.load_extension(PASSLIB_CONFIG=config)
  749. # setup helpers
  750. import django.contrib.auth.models as models
  751. from passlib.ext.django.models import adapter
  752. def dummy():
  753. pass
  754. # mess with User.set_password, make sure it's detected
  755. orig = models.User.set_password
  756. models.User.set_password = dummy
  757. with self.assertWarningList("another library has patched.*User\.set_password"):
  758. adapter._manager.check_all()
  759. models.User.set_password = orig
  760. # mess with models.check_password, make sure it's detected
  761. orig = models.check_password
  762. models.check_password = dummy
  763. with self.assertWarningList("another library has patched.*models:check_password"):
  764. adapter._manager.check_all()
  765. models.check_password = orig
  766. def test_02_handler_wrapper(self):
  767. """test Hasher-compatible handler wrappers"""
  768. from django.contrib.auth import hashers
  769. passlib_to_django = DjangoTranslator().passlib_to_django
  770. # should return native django hasher if available
  771. if DJANGO_VERSION > (1, 10):
  772. self.assertRaises(ValueError, passlib_to_django, "hex_md5")
  773. else:
  774. hasher = passlib_to_django("hex_md5")
  775. self.assertIsInstance(hasher, hashers.UnsaltedMD5PasswordHasher)
  776. # should return native django hasher
  777. # NOTE: present but not enabled by default in django as of 2.1
  778. # (see _builtin_django_hashers)
  779. hasher = passlib_to_django("django_bcrypt")
  780. self.assertIsInstance(hasher, hashers.BCryptPasswordHasher)
  781. # otherwise should return wrapper
  782. from passlib.hash import sha256_crypt
  783. hasher = passlib_to_django("sha256_crypt")
  784. self.assertEqual(hasher.algorithm, "passlib_sha256_crypt")
  785. # and wrapper should return correct hash
  786. encoded = hasher.encode("stub")
  787. self.assertTrue(sha256_crypt.verify("stub", encoded))
  788. self.assertTrue(hasher.verify("stub", encoded))
  789. self.assertFalse(hasher.verify("xxxx", encoded))
  790. # test wrapper accepts options
  791. encoded = hasher.encode("stub", "abcd"*4, rounds=1234)
  792. self.assertEqual(encoded, "$5$rounds=1234$abcdabcdabcdabcd$"
  793. "v2RWkZQzctPdejyRqmmTDQpZN6wTh7.RUy9zF2LftT6")
  794. self.assertEqual(hasher.safe_summary(encoded),
  795. {'algorithm': 'sha256_crypt',
  796. 'salt': u('abcdab**********'),
  797. 'rounds': 1234,
  798. 'hash': u('v2RWkZ*************************************'),
  799. })
  800. # made up name should throw error
  801. # XXX: should this throw ValueError instead, to match django?
  802. self.assertRaises(KeyError, passlib_to_django, "does_not_exist")
  803. #===================================================================
  804. # PASSLIB_CONFIG settings
  805. #===================================================================
  806. def test_11_config_disabled(self):
  807. """test PASSLIB_CONFIG='disabled'"""
  808. # test config=None (deprecated)
  809. with self.assertWarningList("PASSLIB_CONFIG=None is deprecated"):
  810. self.load_extension(PASSLIB_CONFIG=None, check=False)
  811. self.assert_unpatched()
  812. # test disabled config
  813. self.load_extension(PASSLIB_CONFIG="disabled", check=False)
  814. self.assert_unpatched()
  815. def test_12_config_presets(self):
  816. """test PASSLIB_CONFIG='<preset>'"""
  817. # test django presets
  818. self.load_extension(PASSLIB_CONTEXT="django-default", check=False)
  819. ctx = django16_context
  820. self.assert_patched(ctx)
  821. self.load_extension(PASSLIB_CONFIG="django-1.0", check=False)
  822. self.assert_patched(django10_context)
  823. self.load_extension(PASSLIB_CONFIG="django-1.4", check=False)
  824. self.assert_patched(django14_context)
  825. def test_13_config_defaults(self):
  826. """test PASSLIB_CONFIG default behavior"""
  827. # check implicit default
  828. from passlib.ext.django.utils import PASSLIB_DEFAULT
  829. default = CryptContext.from_string(PASSLIB_DEFAULT)
  830. self.load_extension()
  831. self.assert_patched(PASSLIB_DEFAULT)
  832. # check default preset
  833. self.load_extension(PASSLIB_CONTEXT="passlib-default", check=False)
  834. self.assert_patched(PASSLIB_DEFAULT)
  835. # check explicit string
  836. self.load_extension(PASSLIB_CONTEXT=PASSLIB_DEFAULT, check=False)
  837. self.assert_patched(PASSLIB_DEFAULT)
  838. def test_14_config_invalid(self):
  839. """test PASSLIB_CONFIG type checks"""
  840. update_settings(PASSLIB_CONTEXT=123, PASSLIB_CONFIG=UNSET)
  841. self.assertRaises(TypeError, __import__, 'passlib.ext.django.models')
  842. self.unload_extension()
  843. update_settings(PASSLIB_CONFIG="missing-preset", PASSLIB_CONTEXT=UNSET)
  844. self.assertRaises(ValueError, __import__, 'passlib.ext.django.models')
  845. #===================================================================
  846. # PASSLIB_GET_CATEGORY setting
  847. #===================================================================
  848. def test_21_category_setting(self):
  849. """test PASSLIB_GET_CATEGORY parameter"""
  850. # define config where rounds can be used to detect category
  851. config = dict(
  852. schemes = ["sha256_crypt"],
  853. sha256_crypt__default_rounds = 1000,
  854. staff__sha256_crypt__default_rounds = 2000,
  855. superuser__sha256_crypt__default_rounds = 3000,
  856. )
  857. from passlib.hash import sha256_crypt
  858. def run(**kwds):
  859. """helper to take in user opts, return rounds used in password"""
  860. user = FakeUser(**kwds)
  861. user.set_password("stub")
  862. return sha256_crypt.from_string(user.password).rounds
  863. # test default get_category
  864. self.load_extension(PASSLIB_CONFIG=config)
  865. self.assertEqual(run(), 1000)
  866. self.assertEqual(run(is_staff=True), 2000)
  867. self.assertEqual(run(is_superuser=True), 3000)
  868. # test patch uses explicit get_category function
  869. def get_category(user):
  870. return user.first_name or None
  871. self.load_extension(PASSLIB_CONTEXT=config,
  872. PASSLIB_GET_CATEGORY=get_category)
  873. self.assertEqual(run(), 1000)
  874. self.assertEqual(run(first_name='other'), 1000)
  875. self.assertEqual(run(first_name='staff'), 2000)
  876. self.assertEqual(run(first_name='superuser'), 3000)
  877. # test patch can disable get_category entirely
  878. def get_category(user):
  879. return None
  880. self.load_extension(PASSLIB_CONTEXT=config,
  881. PASSLIB_GET_CATEGORY=get_category)
  882. self.assertEqual(run(), 1000)
  883. self.assertEqual(run(first_name='other'), 1000)
  884. self.assertEqual(run(first_name='staff', is_staff=True), 1000)
  885. self.assertEqual(run(first_name='superuser', is_superuser=True), 1000)
  886. # test bad value
  887. self.assertRaises(TypeError, self.load_extension, PASSLIB_CONTEXT=config,
  888. PASSLIB_GET_CATEGORY='x')
  889. #===================================================================
  890. # eoc
  891. #===================================================================
  892. #=============================================================================
  893. # eof
  894. #=============================================================================