diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2016-06-29 13:21:29 -0400 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2016-06-29 13:21:29 -0400 |
| commit | bb950fe7a23884aa3b16a1cfd788f9a4550283bb (patch) | |
| tree | 12016f79c11a3227601d7fa9cafd050aa1c5b5cf /passlib | |
| parent | ab319ed8bb0b43ebe68d17118ad065b0b02e05ff (diff) | |
| download | passlib-bb950fe7a23884aa3b16a1cfd788f9a4550283bb.tar.gz | |
CryptContext: adjusted interface to expose configured handlers
rather than base handlers, deprecated some unneeded args.
* .schemes(resolve=True), .default_scheme(resolve=True), .handlers(),
and .identify() -- All these methods now return configured handlers
rather than the base ones, so callers who are inspecting context
get a handler which honors it's configuration.
This required adding a few keywords to these methods,
but leaving them mostly undocumented -- if no one asks for them,
don't have to preserve them when 1.8 updates the context api.
* .hash(), .verify(), .verify_and_update() -- deprecated the 'scheme' keyword:
Nothing but UTs is probably using this, and '.handler().hash()' can be used
as a replacement.
* added context.using() to match hash api, is an alias for context.copy()
Diffstat (limited to 'passlib')
| -rw-r--r-- | passlib/context.py | 116 | ||||
| -rw-r--r-- | passlib/tests/test_context.py | 117 |
2 files changed, 175 insertions, 58 deletions
diff --git a/passlib/context.py b/passlib/context.py index 73592aa..c1c6ce9 100644 --- a/passlib/context.py +++ b/passlib/context.py @@ -362,7 +362,7 @@ class CryptPolicy(object): "create a CryptContext instance and " "use ``context.schemes(resolve=True)``.", DeprecationWarning, stacklevel=2) - return self._context.schemes(resolve=True) + return self._context.schemes(resolve=True, unconfigured=True) def schemes(self, resolve=False): """return list of schemes defined in policy. @@ -381,7 +381,7 @@ class CryptPolicy(object): "create a CryptContext instance and " "use ``context.schemes()``.", DeprecationWarning, stacklevel=2) - return list(self._context.schemes(resolve=resolve)) + return list(self._context.schemes(resolve=resolve, unconfigured=True)) def get_handler(self, name=None, category=None, required=False): """return handler as specified by name, or default handler. @@ -405,7 +405,7 @@ class CryptPolicy(object): # CryptContext.handler() doesn't support required=False, # so wrapping it in try/except try: - return self._context.handler(name, category) + return self._context.handler(name, category, unconfigured=True) except KeyError: if required: raise @@ -1364,6 +1364,12 @@ class CryptContext(object): other.load(kwds, update=True) return other + def using(self, **kwds): + """ + alias for :meth:`copy`, to match PasswordHash.using() + """ + return self.copy(**kwds) + def replace(self, **kwds): """deprecated alias of :meth:`copy`""" warn("CryptContext().replace() has been deprecated in Passlib 1.6, " @@ -1700,7 +1706,7 @@ class CryptContext(object): #=================================================================== # reading configuration #=================================================================== - def schemes(self, resolve=False): + def schemes(self, resolve=False, category=None, unconfigured=False): """return schemes loaded into this CryptContext instance. :type resolve: bool @@ -1717,7 +1723,18 @@ class CryptContext(object): .. seealso:: the :ref:`schemes <context-schemes-option>` option for usage example. """ - return self._config.handlers if resolve else self._config.schemes + # XXX: should resolv return records rather than handlers? + # or deprecate resolve keyword completely? + # offering up a .hashers Mapping in v1.8 would be great. + # NOTE: supporting 'category' and 'unconfigured' kwds as of 1.7 + # just to pass through to .handler(), but not documenting them... + # may not need to put them to use. + schemes = self._config.schemes + if resolve: + return tuple(self.handler(scheme, category, unconfigured=unconfigured) + for scheme in schemes) + else: + return schemes # XXX: need to decide if exposing this would be useful to applications # in any way that isn't already served by to_dict(); @@ -1727,7 +1744,7 @@ class CryptContext(object): """helper used by unittests to check if scheme is deprecated""" return self._get_record(scheme, category)._Context__deprecated - def default_scheme(self, category=None, resolve=False): + def default_scheme(self, category=None, resolve=False, unconfigured=False): """return name of scheme that :meth:`hash` will use by default. :type resolve: bool @@ -1746,10 +1763,19 @@ class CryptContext(object): .. seealso:: the :ref:`default <context-default-option>` option for usage example. .. versionadded:: 1.6 + + .. versionchanged:: 1.7 + + This now returns a hasher configured with any CryptContext-specific + options (custom rounds settings, etc). Previously this returned + the base hasher from :mod:`passlib.hash`. """ - # type check of category - handled by _get_record() - record = self._get_record(None, category) - return record._Context__orig_handler if resolve else record.name + # XXX: deprecate this in favor of .handler() or whatever it's replaced with? + # NOTE: supporting 'unconfigured' kwds as of 1.7 + # just to pass through to .handler(), but not documenting them... + # may not need to put them to use. + hasher = self.handler(None, category, unconfigured=unconfigured) + return hasher if resolve else hasher.name # XXX: need to decide if exposing this would be useful in any way ##def categories(self): @@ -1767,7 +1793,7 @@ class CryptContext(object): ## kwds, percat = self._config.get_options(scheme, category) ## return kwds - def handler(self, scheme=None, category=None): + def handler(self, scheme=None, category=None, unconfigured=False): """helper to resolve name of scheme -> :class:`~passlib.ifc.PasswordHash` object used by scheme. :arg scheme: @@ -1780,6 +1806,14 @@ class CryptContext(object): it will use the default for that category. Otherwise this parameter is ignored. + :param unconfigured: + + By default, this returns a handler object whose .hash() + and .needs_update() methods will honor the configured + provided by CryptContext. See ``unconfigured=True`` + to get the underlying handler from before any context-specific + configuration was applied. + :raises KeyError: If the scheme does not exist OR is not being used within this context. @@ -1790,9 +1824,19 @@ class CryptContext(object): .. versionadded:: 1.6 This was previously available as ``CryptContext().policy.get_handler()`` + + .. versionchanged:: 1.7 + + This now returns a hasher configured with any CryptContext-specific + options (custom rounds settings, etc). Previously this returned + the base hasher from :mod:`passlib.hash`. """ try: - return self._get_record(scheme, category)._Context__orig_handler + hasher = self._get_record(scheme, category) + if unconfigured: + return hasher._Context__orig_handler + else: + return hasher except KeyError: pass if self._config.handlers: @@ -2167,6 +2211,10 @@ class CryptContext(object): If no scheme is specified, it will be identified based on the value of *hash*. + .. deprecated:: 1.7 + + Support for this keyword is deprecated, and will be removed in Passlib 2.0. + :type category: str or None :param category: Optional :ref:`user category <user-categories>`. @@ -2195,6 +2243,13 @@ class CryptContext(object): .. seealso:: the :ref:`context-migration-example` example in the tutorial. """ + if scheme is not None: + # TODO: offer replacement alternative. + # ``context.handler(scheme).needs_update()`` would work, + # but may deprecate .handler() in passlib 1.8. + warn("CryptContext.needs_update(): 'scheme' keyword is deprecated as of " + "Passlib 1.7, and will be removed in Passlib 2.0", + DeprecationWarning) record = self._get_or_identify_record(hash, scheme, category) return record.needs_update(hash, secret=secret) @@ -2239,7 +2294,8 @@ class CryptContext(object): strip_unused(kwds, record) return record.genhash(secret, config, **kwds) - def identify(self, hash, category=None, resolve=False, required=False): + def identify(self, hash, category=None, resolve=False, required=False, + unconfigured=False): """Attempt to identify which algorithm the hash belongs to. Note that this will only consider the algorithms @@ -2276,8 +2332,10 @@ class CryptContext(object): if record is None: return None elif resolve: - # XXX: which one should we return? custom_handler (record), or orig handler? - return record._Context__orig_handler + if unconfigured: + return record._Context__orig_handler + else: + return record else: return record.name @@ -2297,6 +2355,10 @@ class CryptContext(object): If no scheme is specified, the configured default will be used. + .. deprecated:: 1.7 + + Support for this keyword is deprecated, and will be removed in Passlib 2.0. + :type category: str or None :param category: Optional :ref:`user category <user-categories>`. @@ -2320,6 +2382,13 @@ class CryptContext(object): .. seealso:: the :ref:`context-basic-example` example in the tutorial """ # XXX: could insert normalization to preferred unicode encoding here + if scheme is not None: + # TODO: offer replacement alternative. + # ``context.handler(scheme).hash()`` would work, + # but may deprecate .handler() in passlib 1.8. + warn("CryptContext.hash(): 'scheme' keyword is deprecated as of " + "Passlib 1.7, and will be removed in Passlib 2.0" + DeprecationWarning) record = self._get_record(scheme, category) strip_unused = self._strip_unused_context_kwds if strip_unused: @@ -2364,6 +2433,10 @@ class CryptContext(object): for this context (see the :ref:`schemes <context-schemes-option>` option). + .. deprecated:: 1.7 + + Support for this keyword is deprecated, and will be removed in Passlib 2.0. + :type category: str or None :param category: Optional :ref:`user category <user-categories>` string. @@ -2393,6 +2466,13 @@ class CryptContext(object): """ # XXX: could insert normalization to preferred unicode encoding here # XXX: what about supporting a setter() callback ala django 1.4 ? + if scheme is not None: + # TODO: offer replacement alternative. + # ``context.handler(scheme).verify()`` would work, + # but may deprecate .handler() in passlib 1.8. + warn("CryptContext.verify(): 'scheme' keyword is deprecated as of " + "Passlib 1.7, and will be removed in Passlib 2.0", + DeprecationWarning) if hash is None: # convenience feature -- let apps pass in hash=None when user # isn't found / has no hash; mainly to get dummy_verify() benefit. @@ -2438,6 +2518,10 @@ class CryptContext(object): for this context (see the :ref:`schemes <context-schemes-option>` option). + .. deprecated:: 1.7 + + Support for this keyword is deprecated, and will be removed in Passlib 2.0. + :type category: str or None :param category: Optional :ref:`user category <user-categories>`. @@ -2469,6 +2553,10 @@ class CryptContext(object): .. seealso:: the :ref:`context-migration-example` example in the tutorial. """ # XXX: could insert normalization to preferred unicode encoding here. + if scheme is not None: + warn("CryptContext.verify(): 'scheme' keyword is deprecated as of " + "Passlib 1.7, and will be removed in Passlib 2.0", + DeprecationWarning) if hash is None: # convenience feature -- let apps pass in hash=None when user # isn't found / has no hash; mainly to get dummy_verify() benefit. diff --git a/passlib/tests/test_context.py b/passlib/tests/test_context.py index f82ea06..7187d06 100644 --- a/passlib/tests/test_context.py +++ b/passlib/tests/test_context.py @@ -23,7 +23,7 @@ from passlib.utils import tick, to_unicode from passlib.utils.compat import irange, u, unicode, str_to_uascii, PY2, PY26 import passlib.utils.handlers as uh from passlib.tests.utils import (TestCase, set_file, TICK_RESOLUTION, - quicksleep, time_call) + quicksleep, time_call, handler_derived_from) from passlib.registry import (register_crypt_handler_path, _has_crypt_handler as has_crypt_handler, _unload_handler_name as unload_handler_name, @@ -178,6 +178,7 @@ sha512_crypt__min_rounds = 45000 def setUp(self): super(CryptContextTest, self).setUp() warnings.filterwarnings("ignore", "The 'all' scheme is deprecated.*") + warnings.filterwarnings("ignore", ".*'scheme' keyword is deprecated as of Passlib 1.7.*") #=================================================================== # constructors @@ -667,6 +668,10 @@ sha512_crypt__min_rounds = 45000 #=================================================================== # inspection & serialization #=================================================================== + + def assertHandlerDerivedFrom(self, handler, base, msg=None): + self.assertTrue(handler_derived_from(handler, base), msg=msg) + def test_30_schemes(self): """test schemes() method""" # NOTE: also checked under test_21 @@ -679,7 +684,9 @@ sha512_crypt__min_rounds = 45000 # test sample 1 ctx = CryptContext(**self.sample_1_dict) self.assertEqual(ctx.schemes(), tuple(self.sample_1_schemes)) - self.assertEqual(ctx.schemes(resolve=True), tuple(self.sample_1_handlers)) + self.assertEqual(ctx.schemes(resolve=True, unconfigured=True), tuple(self.sample_1_handlers)) + for result, correct in zip(ctx.schemes(resolve=True), self.sample_1_handlers): + self.assertTrue(handler_derived_from(result, correct)) # test sample 2 ctx = CryptContext(**self.sample_2_dict) @@ -696,7 +703,8 @@ sha512_crypt__min_rounds = 45000 # test sample 1 ctx = CryptContext(**self.sample_1_dict) self.assertEqual(ctx.default_scheme(), "md5_crypt") - self.assertEqual(ctx.default_scheme(resolve=True), hash.md5_crypt) + self.assertEqual(ctx.default_scheme(resolve=True, unconfigured=True), hash.md5_crypt) + self.assertHandlerDerivedFrom(ctx.default_scheme(resolve=True), hash.md5_crypt) # test sample 2 ctx = CryptContext(**self.sample_2_dict) @@ -718,24 +726,31 @@ sha512_crypt__min_rounds = 45000 # default for sample 1 ctx = CryptContext(**self.sample_1_dict) - self.assertEqual(ctx.handler(), hash.md5_crypt) + self.assertEqual(ctx.handler(unconfigured=True), hash.md5_crypt) + self.assertHandlerDerivedFrom(ctx.handler(), hash.md5_crypt) # by name - self.assertEqual(ctx.handler("des_crypt"), hash.des_crypt) + self.assertEqual(ctx.handler("des_crypt", unconfigured=True), hash.des_crypt) + self.assertHandlerDerivedFrom(ctx.handler("des_crypt"), hash.des_crypt) # name not in schemes self.assertRaises(KeyError, ctx.handler, "mysql323") # check handler() honors category default ctx = CryptContext("sha256_crypt,md5_crypt", admin__context__default="md5_crypt") - self.assertEqual(ctx.handler(), hash.sha256_crypt) - self.assertEqual(ctx.handler(category="staff"), hash.sha256_crypt) - self.assertEqual(ctx.handler(category="admin"), hash.md5_crypt) + self.assertEqual(ctx.handler(unconfigured=True), hash.sha256_crypt) + self.assertHandlerDerivedFrom(ctx.handler(), hash.sha256_crypt) + + self.assertEqual(ctx.handler(category="staff", unconfigured=True), hash.sha256_crypt) + self.assertHandlerDerivedFrom(ctx.handler(category="staff"), hash.sha256_crypt) + + self.assertEqual(ctx.handler(category="admin", unconfigured=True), hash.md5_crypt) + self.assertHandlerDerivedFrom(ctx.handler(category="staff"), hash.sha256_crypt) # test unicode category strings are accepted under py2 if PY2: - self.assertEqual(ctx.handler(category=u("staff")), hash.sha256_crypt) - self.assertEqual(ctx.handler(category=u("admin")), hash.md5_crypt) + self.assertEqual(ctx.handler(category=u("staff"), unconfigured=True), hash.sha256_crypt) + self.assertEqual(ctx.handler(category=u("admin"), unconfigured=True), hash.md5_crypt) def test_33_options(self): """test internal _get_record_options() method""" @@ -871,7 +886,8 @@ sha512_crypt__min_rounds = 45000 for crypt in handlers: h = cc.hash("test", scheme=crypt.name) self.assertEqual(cc.identify(h), crypt.name) - self.assertEqual(cc.identify(h, resolve=True), crypt) + self.assertEqual(cc.identify(h, resolve=True, unconfigured=True), crypt) + self.assertHandlerDerivedFrom(cc.identify(h, resolve=True), crypt) self.assertTrue(cc.verify('test', h)) self.assertFalse(cc.verify('notest', h)) @@ -973,19 +989,52 @@ sha512_crypt__min_rounds = 45000 # bad category values self.assertRaises(TypeError, cc.genconfig, 'secret', hash, category=1) + def test_43_hash(self,): + """test hash() method""" + # XXX: what more can we test here that isn't deprecated + # or handled under another test (e.g. context kwds?) - def test_43_hash(self, use_16_legacy=False): - """test hash_using() method""" + # respects rounds cc = CryptContext(**self.sample_4_dict) + hash = cc.hash("password") + self.assertTrue(hash.startswith("$5$rounds=3000$")) + self.assertTrue(cc.verify("password", hash)) + self.assertFalse(cc.verify("passwordx", hash)) - def call_hash(ctx, *args, **kwds): - if use_16_legacy: - return ctx.hash(*args, **kwds) - else: - return ctx.hash_using(**kwds).hash(*args) + # make default > max throws error if attempted + # XXX: move this to copy() test? + self.assertRaises(ValueError, cc.copy, + sha256_crypt__default_rounds=4000) + + # rejects non-string secrets + cc = CryptContext(["des_crypt"]) + for secret, kwds in self.nonstring_vectors: + self.assertRaises(TypeError, cc.hash, secret, **kwds) + + # throws error without schemes + self.assertRaises(KeyError, CryptContext().hash, 'secret') + + # bad category values + self.assertRaises(TypeError, cc.hash, 'secret', category=1) + + def test_43_hash_legacy(self, use_16_legacy=False): + """test hash() method -- legacy 'scheme' and settings keywords""" + cc = CryptContext(**self.sample_4_dict) + + # TODO: should migrate these tests elsewhere, or remove them. + # can be replaced with following equivalent: + # + # def wrapper(secret, scheme=None, category=None, **kwds): + # handler = cc.handler(scheme, category) + # if kwds: + # handler = handler.using(**kwds) + # return handler.hash(secret) + # + # need to make sure bits being tested here are tested + # under the tests for the equivalent methods called above, + # and then discard the rest of these under 2.0. # hash specific settings - # TODO: passing settings this way is deprecated, need to add alternative self.assertEqual( cc.hash("password", scheme="phpass", salt='.'*8), '$H$5........De04R5Egz0aq8Tf.1eVhY/', @@ -1000,42 +1049,22 @@ sha512_crypt__min_rounds = 45000 # min rounds with self.assertWarningList([]): self.assertEqual( - cc.hash_using("password", rounds=1999, salt="nacl"), + cc.hash("password", rounds=1999, salt="nacl"), '$5$rounds=1999$nacl$nmfwJIxqj0csloAAvSER0B8LU0ERCAbhmMug4Twl609', ) with self.assertWarningList([]): self.assertEqual( - cc.hash_using("password", rounds=2001, salt="nacl"), + cc.hash("password", rounds=2001, salt="nacl"), '$5$rounds=2001$nacl$8PdeoPL4aXQnJ0woHhqgIw/efyfCKC2WHneOpnvF.31' ) # NOTE: max rounds, etc tested in genconfig() - # make default > max throws error if attempted - self.assertRaises(ValueError, cc.copy, - sha256_crypt__default_rounds=4000) - - #-------------------------------------------------------------- - # border cases - #-------------------------------------------------------------- - - # rejects non-string secrets - cc = CryptContext(["des_crypt"]) - for secret, kwds in self.nonstring_vectors: - self.assertRaises(TypeError, cc.hash, secret, **kwds) - - # throws error without schemes - self.assertRaises(KeyError, CryptContext().hash, 'secret') - # bad scheme values self.assertRaises(KeyError, cc.hash, 'secret', scheme="fake") # XXX: should this be ValueError? self.assertRaises(TypeError, cc.hash, 'secret', scheme=1) - # bad category values - self.assertRaises(TypeError, cc.hash, 'secret', category=1) - - def test_44_identify(self): """test identify() border cases""" handlers = ["md5_crypt", "des_crypt", "bsdi_crypt"] @@ -1100,7 +1129,7 @@ sha512_crypt__min_rounds = 45000 cc = CryptContext(["des_crypt"]) for h, kwds in self.nonstring_vectors: if h is None: - pass + continue self.assertRaises(TypeError, cc.verify, 'secret', h, **kwds) # throws error without schemes @@ -1189,8 +1218,8 @@ sha512_crypt__min_rounds = 45000 cc = CryptContext(**self.sample_4_dict) # create some hashes - h1 = cc.hash("password", scheme="des_crypt") - h2 = cc.hash("password", scheme="sha256_crypt") + h1 = cc.handler("des_crypt").hash("password") + h2 = cc.handler("sha256_crypt").hash("password") # check bad password, deprecated hash ok, new_hash = cc.verify_and_update("wrongpass", h1) |
