summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--docs/lib/passlib.ext.django.rst16
-rw-r--r--passlib/context.py4
-rw-r--r--passlib/ext/django/models.py277
-rw-r--r--passlib/ext/django/utils.py859
-rw-r--r--passlib/ifc.py10
-rw-r--r--passlib/tests/test_ext_django.py224
-rw-r--r--passlib/tests/test_ext_django_source.py249
-rw-r--r--passlib/tests/utils.py7
-rw-r--r--passlib/utils/handlers.py13
9 files changed, 1086 insertions, 573 deletions
diff --git a/docs/lib/passlib.ext.django.rst b/docs/lib/passlib.ext.django.rst
index 8fd4e83..51097cc 100644
--- a/docs/lib/passlib.ext.django.rst
+++ b/docs/lib/passlib.ext.django.rst
@@ -12,6 +12,15 @@
As of Passlib 1.7, this module requires Django 1.8 or newer.
+.. rst-class:: float-center without-title
+
+.. warning::
+
+ This extension is a high maintenance, with an uncertain number of users.
+ The current plan is to split this out as a separate package concurrent
+ with Passlib 1.8, and then judge whether it should continue to be maintained
+ in it's own right. See :issue:`81`.
+
This module contains a `Django <http://www.djangoproject.com>`_ plugin which
overrides all of Django's password hashing functions, replacing them
with wrappers around a Passlib :ref:`CryptContext <context-reference>` object
@@ -126,6 +135,13 @@ Module Contents
It can be imported and examined to inspect the current configuration,
changes made to it will immediately alter how Django hashes passwords.
+ (Do not replace the reference with another CryptContext, it will break things;
+ just update the context in-place).
+
+.. function:: context_changed
+
+ If the context is modified after loading, call this function to clear internal caches.
+
.. module:: passlib.ext.django.utils
.. autofunction:: get_preset_config
diff --git a/passlib/context.py b/passlib/context.py
index 0bf03e4..7d7c7c9 100644
--- a/passlib/context.py
+++ b/passlib/context.py
@@ -1021,6 +1021,10 @@ class _CryptConfig(object):
# if whole alg is deprecated, patch it's needs_update() method.
# XXX: could do this check at context level, and remove need for patch.
+ # at least should give a way to test if deprecated hash's
+ # data is itself outdated w/in hash's config,
+ # that's needed in a few places (e.g. passlib.ext.django)
+ subcls._Context__orig_needs_update = subcls.needs_update
if deprecated:
subcls.needs_update = _always_needs_update
diff --git a/passlib/ext/django/models.py b/passlib/ext/django/models.py
index 1337ce2..e766c2d 100644
--- a/passlib/ext/django/models.py
+++ b/passlib/ext/django/models.py
@@ -3,17 +3,10 @@
# imports
#=============================================================================
# core
-import logging; log = logging.getLogger(__name__)
-from warnings import warn
# site
-from django import VERSION
-from django.conf import settings
# pkg
from passlib.context import CryptContext
-from passlib.exc import ExpectedTypeError
-from passlib.ext.django.utils import _PatchManager, hasher_to_passlib_name, \
- get_passlib_hasher, get_preset_config, MIN_DJANGO_VERSION
-from passlib.utils.compat import unicode
+from passlib.ext.django.utils import DjangoContextAdapter
# local
__all__ = ["password_context"]
@@ -21,274 +14,22 @@ __all__ = ["password_context"]
# global attrs
#=============================================================================
+#: adapter instance used to drive most of this
+adapter = DjangoContextAdapter()
+
# the context object which this patches contrib.auth to use for password hashing.
# configuration controlled by ``settings.PASSLIB_CONFIG``.
-password_context = CryptContext()
-
-# function mapping User objects -> passlib user category.
-# may be overridden via ``settings.PASSLIB_GET_CATEGORY``.
-def _get_category(user):
- """default get_category() implementation"""
- if user.is_superuser:
- return "superuser"
- elif user.is_staff:
- return "staff"
- else:
- return None
+password_context = adapter.context
-# object used to track state of patches applied to django.
-_manager = _PatchManager(log=logging.getLogger(__name__ + "._manager"))
-
-# patch status
-_patched = False
-
-#=============================================================================
-# applying & removing the patches
-#=============================================================================
-def _apply_patch():
- """monkeypatch django's password handling to use ``passlib_context``,
- assumes the caller will configure the object.
- """
- #
- # setup environment & patch-paths
- #
- if VERSION < MIN_DJANGO_VERSION:
- raise RuntimeError("passlib.ext.django requires django >= %s" % (MIN_DJANGO_VERSION,))
-
- log.debug("preparing to monkeypatch 'django.contrib.auth' ...")
- global _patched
- assert not _patched, "monkeypatching already applied"
-
- HASHERS_PATH = "django.contrib.auth.hashers"
- MODELS_PATH = "django.contrib.auth.models"
- USER_PATH = MODELS_PATH + ":User"
- FORMS_PATH = "django.contrib.auth.forms"
-
- #
- # import some helpers from hashers module
- #
- from django.contrib.auth.hashers import is_password_usable
- from django.utils import lru_cache
- from passlib.utils.compat import lmap
-
- #
- # patch ``User.set_password() & ``User.check_password()`` to use
- # context & get_category (would just leave these as wrappers for hashers
- # module, but then we couldn't pass User object into get_category very easily)
- #
- @_manager.monkeypatch(USER_PATH)
- def set_password(user, password):
- """passlib replacement for User.set_password()"""
- if password is None:
- user.set_unusable_password()
- else:
- # NOTE: pulls _get_category from module globals
- cat = _get_category(user)
- user.password = password_context.hash(password, category=cat)
-
- @_manager.monkeypatch(USER_PATH)
- def check_password(user, password):
- """passlib replacement for User.check_password()"""
- hash = user.password
- if password is None or not is_password_usable(hash):
- return False
- # NOTE: pulls _get_category from module globals
- cat = _get_category(user)
- ok, new_hash = password_context.verify_and_update(password, hash,
- category=cat)
- if ok and new_hash is not None:
- # migrate to new hash if needed.
- user.password = new_hash
- user.save()
- return ok
-
- #
- # override check_password() with our own implementation
- #
- @_manager.monkeypatch(HASHERS_PATH)
- @_manager.monkeypatch(MODELS_PATH)
- def check_password(password, encoded, setter=None, preferred="default"):
- """passlib replacement for check_password()"""
- # XXX: this currently ignores "preferred" keyword, since its purpose
- # was for hash migration, and that's handled by the context.
- if password is None or not is_password_usable(encoded):
- return False
- ok = password_context.verify(password, encoded)
- if ok and setter:
- # django's check_password() won't call setter() on a legacy alg if it's explicitly
- # chosen via 'preferred' kwd (unless alg itself says hash needs updating, of course).
- # as a hack to replicate this behavior, the following makes a temp copy of the
- # active context, to ensure the preferred scheme isn't deprecated.
- test_context = password_context
- if preferred != "default":
- scheme = hasher_to_passlib_name(preferred)
- if password_context._is_deprecated_scheme(scheme):
- test_context = password_context.copy(default=scheme)
- if test_context.needs_update(encoded):
- setter(password)
- return ok
-
- #
- # patch the other functions defined in the ``hashers`` module, as well
- # as any other known locations where they're imported within ``contrib.auth``
- #
- @_manager.monkeypatch(HASHERS_PATH, wrap=True)
- @_manager.monkeypatch(MODELS_PATH, wrap=True)
- def make_password(__wrapped__, password, salt=None, hasher="default"):
- """passlib replacement for make_password()"""
- if password is None:
- return __wrapped__(None)
- if hasher == "default":
- scheme = None
- else:
- scheme = hasher_to_passlib_name(hasher)
- kwds = dict(scheme=scheme)
- handler = password_context.handler(scheme)
- if "salt" in handler.setting_kwds:
- if hasher.startswith("unsalted_"):
- # Django 1.4.6+ uses a separate 'unsalted_sha1' hasher for "sha1$$digest",
- # but passlib just reuses it's "sha1" handler ("sha1$salt$digest"). To make
- # this work, have to explicitly tell the sha1 handler to use an empty salt.
- kwds['salt'] = ''
- elif salt:
- # Django make_password() autogenerates a salt if salt is bool False (None / ''),
- # so we only pass the keyword on if there's actually a fixed salt.
- kwds['salt'] = salt
- return password_context.hash(password, **kwds)
-
- @_manager.monkeypatch(HASHERS_PATH)
- @lru_cache.lru_cache()
- def get_hashers():
- """passlib replacement for get_hashers()"""
- return lmap(get_passlib_hasher, password_context.schemes(resolve=True))
-
- # NOTE: leaving get_hashers_by_algorithm() unpatched, since it just
- # proxies get_hashers(). but we do want to wipe it's cache...
- from django.contrib.auth.hashers import reset_hashers
- reset_hashers(setting="PASSWORD_HASHERS")
-
- @_manager.monkeypatch(HASHERS_PATH)
- @_manager.monkeypatch(FORMS_PATH)
- def get_hasher(algorithm="default"):
- """passlib replacement for get_hasher()"""
- if algorithm == "default":
- scheme = None
- else:
- scheme = hasher_to_passlib_name(algorithm)
- # NOTE: resolving scheme -> handler instead of
- # passing scheme into get_passlib_hasher(),
- # in case context contains custom handler
- # shadowing name of a builtin handler.
- handler = password_context.handler(scheme)
- return get_passlib_hasher(handler, algorithm=algorithm)
-
- # identify_hasher() was added in django 1.5,
- # patching it anyways for 1.4, so passlib's version is always available.
- @_manager.monkeypatch(HASHERS_PATH)
- @_manager.monkeypatch(FORMS_PATH)
- def identify_hasher(encoded):
- """passlib helper to identify hasher from encoded password"""
- handler = password_context.identify(encoded, resolve=True,
- required=True)
- algorithm = None
- if handler.name == "django_salted_sha1" and encoded.startswith("sha1$$"):
- # django 1.4.6+ uses a separate hasher for "sha1$$digest" hashes,
- # but passlib just reuses the "sha1$salt$digest" handler.
- # we want to resolve to correct django hasher.
- algorithm = "unsalted_sha1"
- return get_passlib_hasher(handler, algorithm=algorithm)
-
- _patched = True
- log.debug("... finished monkeypatching django")
-
-def _remove_patch():
- """undo the django monkeypatching done by this module.
- offered as a last resort if it's ever needed.
-
- .. warning::
- This may cause problems if any other Django modules have imported
- their own copies of the patched functions, though the patched
- code has been designed to throw an error as soon as possible in
- this case.
- """
- global _patched
- if _patched:
- log.debug("removing django monkeypatching...")
- _manager.unpatch_all(unpatch_conflicts=True)
- password_context.load({})
- _patched = False
- log.debug("...finished removing django monkeypatching")
- return True
- if _manager: # pragma: no cover -- sanity check
- log.warning("reverting partial monkeypatching of django...")
- _manager.unpatch_all()
- password_context.load({})
- log.debug("...finished removing django monkeypatching")
- return True
- log.debug("django not monkeypatched")
- return False
+#: hook callers should use if context is changed
+context_changed = adapter.reset_hashers
#=============================================================================
# main code
#=============================================================================
-def _load():
- global _get_category
-
- # TODO: would like to add support for inheriting config from a preset
- # (or from existing hasher state) and letting PASSLIB_CONFIG
- # be an update, not a replacement.
-
- # TODO: wrap and import any custom hashers as passlib handlers,
- # so they could be used in the passlib config.
-
- # load config from settings
- _UNSET = object()
- config = getattr(settings, "PASSLIB_CONFIG", _UNSET)
- if config is _UNSET:
- # XXX: should probably deprecate this alias
- config = getattr(settings, "PASSLIB_CONTEXT", _UNSET)
- if config is _UNSET:
- config = "passlib-default"
- if config is None:
- warn("setting PASSLIB_CONFIG=None is deprecated, "
- "and support will be removed in Passlib 1.8, "
- "use PASSLIB_CONFIG='disabled' instead.",
- DeprecationWarning)
- config = "disabled"
- elif not isinstance(config, (unicode, bytes, dict)):
- raise ExpectedTypeError(config, "str or dict", "PASSLIB_CONFIG")
-
- # load custom category func (if any)
- get_category = getattr(settings, "PASSLIB_GET_CATEGORY", None)
- if get_category and not callable(get_category):
- raise ExpectedTypeError(get_category, "callable", "PASSLIB_GET_CATEGORY")
-
- # check if we've been disabled
- if config == "disabled":
- if _patched: # pragma: no cover -- sanity check
- log.error("didn't expect monkeypatching would be applied!")
- _remove_patch()
- return
-
- # resolve any preset aliases
- if isinstance(config, str) and '\n' not in config:
- config = get_preset_config(config)
-
- # setup context
- _apply_patch()
- password_context.load(config)
- if get_category:
- # NOTE: _get_category is module global which is read by
- # monkeypatched functions constructed by _apply_patch()
- _get_category = get_category
- log.debug("passlib.ext.django loaded")
-# wrap load function so we can undo any patching if something goes wrong
-try:
- _load()
-except:
- _remove_patch()
- raise
+# load config & install monkeypatch
+adapter.load_model()
#=============================================================================
# eof
diff --git a/passlib/ext/django/utils.py b/passlib/ext/django/utils.py
index 5107a52..52d41d7 100644
--- a/passlib/ext/django/utils.py
+++ b/passlib/ext/django/utils.py
@@ -3,9 +3,10 @@
# imports
#=============================================================================
# core
-from functools import update_wrapper
+from functools import update_wrapper, wraps
import logging; log = logging.getLogger(__name__)
-from weakref import WeakKeyDictionary
+import sys
+import weakref
from warnings import warn
# site
try:
@@ -15,17 +16,17 @@ except ImportError:
log.debug("django installation not found")
DJANGO_VERSION = ()
# pkg
+from passlib import exc, registry
from passlib.context import CryptContext
from passlib.exc import PasslibRuntimeWarning
-from passlib.registry import get_crypt_handler, list_crypt_handlers
from passlib.utils import memoized_property
-from passlib.utils.compat import get_method_function, iteritems, OrderedDict, native_string_types
+from passlib.utils.compat import get_method_function, iteritems, OrderedDict
# local
__all__ = [
"DJANGO_VERSION",
"MIN_DJANGO_VERSION",
"get_preset_config",
- "get_passlib_hasher",
+ "get_django_hasher",
]
#: minimum version supported by passlib.ext.django
@@ -107,45 +108,717 @@ superuser__django_pbkdf2_sha256__default_rounds = 15000
"""
#=============================================================================
-# translating passlib names <-> hasher names
+# helpers
#=============================================================================
-# prefix used to shoehorn passlib's handler names into django hasher namespace;
-# allows get_hasher() to be meaningfully called even if passlib handler
-# is the one being used.
-PASSLIB_HASHER_PREFIX = "passlib_"
-
-# prefix all the django-specific hash formats are stored under w/in passlib;
-# all of these hashes should expose their hasher name via ``.django_name``.
-DJANGO_PASSLIB_PREFIX = "django_"
-
-# non-django-specific hashes which also expose ``.django_name``.
-_other_django_hashes = ["hex_md5"]
-
-def passlib_to_hasher_name(passlib_name):
- """convert passlib handler name -> hasher name"""
- handler = get_crypt_handler(passlib_name)
- if hasattr(handler, "django_name"):
- return handler.django_name
- return PASSLIB_HASHER_PREFIX + passlib_name
-
-def hasher_to_passlib_name(hasher_name):
- """convert hasher name -> passlib handler name"""
- if hasher_name.startswith(PASSLIB_HASHER_PREFIX):
- return hasher_name[len(PASSLIB_HASHER_PREFIX):]
- if hasher_name == "unsalted_sha1":
- # django 1.4.6+ uses a separate hasher for "sha1$$digest" hashes,
- # but passlib just reuses the "sha1$salt$digest" handler.
- hasher_name = "sha1"
- for name in list_crypt_handlers():
- if name.startswith(DJANGO_PASSLIB_PREFIX) or name in _other_django_hashes:
- handler = get_crypt_handler(name)
- if getattr(handler, "django_name", None) == hasher_name:
- return name
- # XXX: this should only happen for custom hashers that have been registered.
- # _HasherHandler (below) is work in progress that would fix this.
- raise ValueError("can't translate hasher name to passlib name: %r" %
- hasher_name)
+#: prefix used to shoehorn passlib's handler names into django hasher namespace
+PASSLIB_WRAPPER_PREFIX = "passlib_"
+
+#: prefix used by all the django-specific hash formats in passlib;
+#: all of these hashes should have a ``.django_name`` attribute.
+DJANGO_COMPAT_PREFIX = "django_"
+
+#: set of hashes w/o "django_" prefix, but which also expose ``.django_name``.
+_other_django_hashes = set(["hex_md5"])
+
+def _wrap_method(method):
+ """wrap method object in bare function"""
+ @wraps(method)
+ def wrapper(*args, **kwds):
+ return method(*args, **kwds)
+ return wrapper
+
+#=============================================================================
+# translator
+#=============================================================================
+class DjangoTranslator(object):
+ """
+ Object which helps translate passlib hasher objects / names
+ to and from django hasher objects / names.
+
+ These methods are wrapped in a class so that results can be cached,
+ but with the ability to have independant caches, since django hasher
+ names may / may not correspond to the same instance (or even class).
+ """
+ #=============================================================================
+ # instance attrs
+ #=============================================================================
+
+ #: CryptContext instance
+ #: (if any -- generally only set by DjangoContextAdapter subclass)
+ context = None
+
+ #: internal cache of passlib hasher -> django hasher instance.
+ #: key stores weakref to passlib hasher.
+ _django_hasher_cache = None
+
+ #: special case -- unsalted_sha1
+ _django_unsalted_sha1 = None
+
+ #: internal cache of django name -> passlib hasher
+ #: value stores weakrefs to passlib hasher.
+ _passlib_hasher_cache = None
+
+ #=============================================================================
+ # init
+ #=============================================================================
+
+ def __init__(self, context=None, **kwds):
+ super(DjangoTranslator, self).__init__(**kwds)
+ if context is not None:
+ self.context = context
+
+ self._django_hasher_cache = weakref.WeakKeyDictionary()
+ self._passlib_hasher_cache = weakref.WeakValueDictionary()
+
+ def reset_hashers(self):
+ self._django_hasher_cache.clear()
+ self._passlib_hasher_cache.clear()
+ self._django_unsalted_sha1 = None
+
+ def _get_passlib_hasher(self, passlib_name):
+ """
+ resolve passlib hasher by name, using context if available.
+ """
+ context = self.context
+ if context is None:
+ return registry.get_crypt_handler(passlib_name)
+ else:
+ return context.handler(passlib_name)
+
+ #=============================================================================
+ # resolve passlib hasher -> django hasher
+ #=============================================================================
+
+ def passlib_to_django_name(self, passlib_name):
+ """
+ Convert passlib hasher / name to Django hasher name.
+ """
+ return self.passlib_to_django(passlib_name).algorithm
+
+ # XXX: add option (in class, or call signature) to always return a wrapper,
+ # rather than native builtin -- would let HashersTest check that
+ # our own wrapper + implementations are matching up with their tests.
+ def passlib_to_django(self, passlib_hasher, cached=True):
+ """
+ Convert passlib hasher / name to Django hasher.
+
+ :param passlib_hasher:
+ passlib hasher / name
+
+ :returns:
+ django hasher instance
+ """
+ # resolve names to hasher
+ if not hasattr(passlib_hasher, "name"):
+ passlib_hasher = self._get_passlib_hasher(passlib_hasher)
+
+ # check cache
+ if cached:
+ cache = self._django_hasher_cache
+ try:
+ return cache[passlib_hasher]
+ except KeyError:
+ pass
+ result = cache[passlib_hasher] = \
+ self.passlib_to_django(passlib_hasher, cached=False)
+ return result
+
+ # find native equivalent, and return wrapper if there isn't one
+ django_name = getattr(passlib_hasher, "django_name", None)
+ if django_name:
+ return self._create_django_hasher(django_name)
+ else:
+ return _PasslibHasherWrapper(passlib_hasher)
+
+ _builtin_django_hashers = dict(
+ md5="MD5PasswordHasher",
+ )
+
+ def _create_django_hasher(self, django_name):
+ """
+ helper to create new django hasher by name.
+ wraps underlying django methods.
+ """
+ # if we haven't patched django, can use it directly
+ module = sys.modules.get("passlib.ext.django.models")
+ if module is None or not module.adapter.patched:
+ from django.contrib.auth.hashers import get_hasher
+ return get_hasher(django_name)
+
+ # We've patched django's get_hashers(), so calling django's get_hasher()
+ # or get_hashers_by_algorithm() would only land us back here.
+ # As non-ideal workaround, have to use original get_hashers(),
+ get_hashers = module.adapter._manager.getorig("django.contrib.auth.hashers:get_hashers").__wrapped__
+ for hasher in get_hashers():
+ if hasher.algorithm == django_name:
+ return hasher
+
+ # hardcode a few for cases where get_hashers() look won't work.
+ path = self._builtin_django_hashers.get(django_name)
+ if path:
+ if "." not in path:
+ path = "django.contrib.auth.hashers." + path
+ from django.utils.module_loading import import_string
+ return import_string(path)()
+
+ raise ValueError("unknown hasher: %r" % django_name)
+
+ #=============================================================================
+ # reverse django -> passlib
+ #=============================================================================
+
+ def django_to_passlib_name(self, django_name):
+ """
+ Convert Django hasher / name to Passlib hasher name.
+ """
+ return self.django_to_passlib(django_name).name
+
+ def django_to_passlib(self, django_name, cached=True):
+ """
+ Convert Django hasher / name to Passlib hasher / name.
+ If present, CryptContext will be checked instead of main registry.
+
+ :param django_name:
+ Django hasher class or algorithm name.
+ "default" allowed if context provided.
+
+ :raises ValueError:
+ if can't resolve hasher.
+
+ :returns:
+ passlib hasher or name
+ """
+ # check for django hasher
+ if hasattr(django_name, "algorithm"):
+
+ # check for passlib adapter
+ if isinstance(django_name, _PasslibHasherWrapper):
+ return django_name.passlib_handler
+
+ # resolve django hasher -> name
+ django_name = django_name.algorithm
+
+ # check cache
+ if cached:
+ cache = self._passlib_hasher_cache
+ try:
+ return cache[django_name]
+ except KeyError:
+ pass
+ result = cache[django_name] = \
+ self.django_to_passlib(django_name, cached=False)
+ return result
+
+ # check if it's an obviously-wrapped name
+ if django_name.startswith(PASSLIB_WRAPPER_PREFIX):
+ passlib_name = django_name[len(PASSLIB_WRAPPER_PREFIX):]
+ return self._get_passlib_hasher(passlib_name)
+
+ # resolve default
+ if django_name == "default":
+ context = self.context
+ if context is None:
+ raise TypeError("can't determine default scheme w/ context")
+ return context.handler()
+
+ # special case: Django uses a separate hasher for "sha1$$digest"
+ # hashes (unsalted_sha1) and "sha1$salt$digest" (sha1);
+ # but passlib uses "django_salted_sha1" for both of these.
+ if django_name == "unsalted_sha1":
+ django_name = "sha1"
+
+ # resolve name
+ # XXX: bother caching these lists / mapping?
+ # not needed in long-term due to cache above.
+ context = self.context
+ if context is None:
+ # check registry
+ # TODO: should make iteration via registry easier
+ candidates = (
+ registry.get_crypt_handler(passlib_name)
+ for passlib_name in registry.list_crypt_handlers()
+ if passlib_name.startswith(DJANGO_COMPAT_PREFIX) or
+ passlib_name in _other_django_hashes
+ )
+ else:
+ # check context
+ candidates = context.schemes(resolve=True)
+ for handler in candidates:
+ if getattr(handler, "django_name", None) == django_name:
+ return handler
+
+ # give up
+ # NOTE: this should only happen for custom django hashers that we don't
+ # know the equivalents for. _HasherHandler (below) is work in
+ # progress that would allow us to at least return a wrapper.
+ raise ValueError("can't translate django name to passlib name: %r" %
+ (django_name,))
+
+ #=============================================================================
+ # django hasher lookup
+ #=============================================================================
+
+ def resolve_django_hasher(self, django_name, cached=True):
+ """
+ Take in a django algorithm name, return django hasher.
+ """
+ # check for django hasher
+ if hasattr(django_name, "algorithm"):
+ return django_name
+
+ # resolve to passlib hasher
+ passlib_hasher = self.django_to_passlib(django_name, cached=cached)
+
+ # special case: Django uses a separate hasher for "sha1$$digest"
+ # hashes (unsalted_sha1) and "sha1$salt$digest" (sha1);
+ # but passlib uses "django_salted_sha1" for both of these.
+ # XXX: this isn't ideal way to handle this. would like to do something
+ # like pass "django_variant=django_name" into passlib_to_django(),
+ # and have it cache separate hasher there.
+ # but that creates a LOT of complication in it's cache structure,
+ # for what is just one special case.
+ if django_name == "unsalted_sha1" and passlib_hasher.name == "django_salted_sha1":
+ if not cached:
+ return self._create_django_hasher(django_name)
+ result = self._django_unsalted_sha1
+ if result is None:
+ result = self._django_unsalted_sha1 = self._create_django_hasher(django_name)
+ return result
+
+ # lookup corresponding django hasher
+ return self.passlib_to_django(passlib_hasher, cached=cached)
+
+ #=============================================================================
+ # eoc
+ #=============================================================================
+
+#=============================================================================
+# adapter
+#=============================================================================
+class DjangoContextAdapter(DjangoTranslator):
+ """
+ Object which tries to adapt a Passlib CryptContext object,
+ using a Django-hasher compatible API.
+
+ When installed in django, :mod:`!passlib.ext.django` will create
+ an instance of this class, and then monkeypatch the appropriate
+ methods into :mod:`!django.contrib.auth` and other appropriate places.
+ """
+ #=============================================================================
+ # instance attrs
+ #=============================================================================
+
+ #: CryptContext instance we're wrapping
+ context = None
+
+ #: ref to original make_password(),
+ #: needed to generate usuable passwords that match django
+ _orig_make_password = None
+
+ #: ref to django helper of this name -- not monkeypatched
+ is_password_usable = None
+
+ #: PatchManager instance used to track installation
+ _manager = None
+
+ #: whether config=disabled flag was set
+ enabled = True
+
+ #: patch status
+ patched = False
+
+ #=============================================================================
+ # init
+ #=============================================================================
+ def __init__(self, context=None, get_user_category=None, **kwds):
+
+ # init log
+ self.log = logging.getLogger(__name__ + ".DjangoContextAdapter")
+
+ # init parent, filling in default context object
+ if context is None:
+ context = CryptContext()
+ super(DjangoContextAdapter, self).__init__(context=context, **kwds)
+
+ # setup user category
+ if get_user_category:
+ assert callable(get_user_category)
+ self.get_user_category = get_user_category
+
+ # install lru cache wrappers
+ from django.utils.lru_cache import lru_cache
+ self.get_hashers = lru_cache()(self.get_hashers)
+
+ # get copy of original make_password
+ from django.contrib.auth.hashers import make_password
+ if make_password.__module__.startswith("passlib."):
+ make_password = _PatchManager.peek_unpatched_func(make_password)
+ self._orig_make_password = make_password
+
+ # get other django helpers
+ from django.contrib.auth.hashers import is_password_usable
+ self.is_password_usable = is_password_usable
+
+ # init manager
+ mlog = logging.getLogger(__name__ + ".DjangoContextAdapter._manager")
+ self._manager = _PatchManager(log=mlog)
+
+ def reset_hashers(self):
+ """
+ Wrapper to manually reset django's hasher lookup cache
+ """
+ # resets cache for .get_hashers() & .get_hashers_by_algorithm()
+ from django.contrib.auth.hashers import reset_hashers
+ reset_hashers(setting="PASSWORD_HASHERS")
+
+ # reset internal caches
+ super(DjangoContextAdapter, self).reset_hashers()
+
+ #=============================================================================
+ # django hashers helpers -- hasher lookup
+ #=============================================================================
+
+ # lru_cache()'ed by init
+ def get_hashers(self):
+ """
+ Passlib replacement for get_hashers() --
+ Return list of available django hasher classes
+ """
+ passlib_to_django = self.passlib_to_django
+ return [passlib_to_django(hasher)
+ for hasher in self.context.schemes(resolve=True)]
+
+ def get_hasher(self, algorithm="default"):
+ """
+ Passlib replacement for get_hasher() --
+ Return django hasher by name
+ """
+ return self.resolve_django_hasher(algorithm)
+
+ def identify_hasher(self, encoded):
+ """
+ Passlib replacement for identify_hasher() --
+ Identify django hasher based on hash.
+ """
+ handler = self.context.identify(encoded, resolve=True, required=True)
+ if handler.name == "django_salted_sha1" and encoded.startswith("sha1$$"):
+ # Django uses a separate hasher for "sha1$$digest" hashes, but
+ # passlib identifies it as belonging to "sha1$salt$digest" handler.
+ # We want to resolve to correct django hasher.
+ return self.get_hasher("unsalted_sha1")
+ return self.passlib_to_django(handler)
+
+ #=============================================================================
+ # django.contrib.auth.hashers helpers -- password helpers
+ #=============================================================================
+
+ def make_password(self, password, salt=None, hasher="default"):
+ """
+ Passlib replacement for make_password()
+ """
+ if password is None:
+ return self._orig_make_password(None)
+ # NOTE: relying on hasher coming from context, and thus having
+ # context-specific config baked into it.
+ passlib_hasher = self.django_to_passlib(hasher)
+ if "salt" not in passlib_hasher.setting_kwds:
+ # ignore salt param even if preset
+ pass
+ elif hasher.startswith("unsalted_"):
+ # Django uses a separate 'unsalted_sha1' hasher for "sha1$$digest",
+ # but passlib just reuses it's "sha1" handler ("sha1$salt$digest"). To make
+ # this work, have to explicitly tell the sha1 handler to use an empty salt.
+ passlib_hasher = passlib_hasher.using(salt="")
+ elif salt:
+ # Django make_password() autogenerates a salt if salt is bool False (None / ''),
+ # so we only pass the keyword on if there's actually a fixed salt.
+ passlib_hasher = passlib_hasher.using(salt=salt)
+ return passlib_hasher.hash(password)
+
+ def check_password(self, password, encoded, setter=None, preferred="default"):
+ """
+ Passlib replacement for check_password()
+ """
+ # XXX: this currently ignores "preferred" keyword, since its purpose
+ # was for hash migration, and that's handled by the context.
+ if password is None or not self.is_password_usable(encoded):
+ return False
+
+ # verify password
+ context = self.context
+ correct = context.verify(password, encoded)
+ if not (correct and setter):
+ return correct
+
+ # check if we need to rehash
+ if preferred == "default":
+ if not context.needs_update(encoded, secret=password):
+ return correct
+ else:
+ # Django's check_password() won't call setter() on a
+ # 'preferred' alg, even if it's otherwise deprecated. To try and
+ # replicate this behavior if preferred is set, we look up the
+ # passlib hasher, and call it's original needs_update() method.
+ # TODO: * To make this less hackneyed, need to straighten things out
+ # on CryptContext end so we don't have to work around
+ # it's annoying monkeypatching.
+ # * Should also solve redundancy that verify() call
+ # above is already identifying hash.
+ hasher = self.django_to_passlib(preferred)
+ if (hasher.identify(encoded) and
+ not hasher._Context__orig_needs_update(encoded, secret=password)):
+ # alg is 'preferred' and hash itself doesn't need updating,
+ # so nothing to do.
+ return correct
+ # else: either hash isn't preferred, or it needs updating.
+
+ # call setter to rehash
+ setter(password)
+ return correct
+
+ #=============================================================================
+ # django users helpers
+ #=============================================================================
+
+ def user_check_password(self, user, password):
+ """
+ Passlib replacement for User.check_password()
+ """
+ if password is None:
+ return False
+ hash = user.password
+ if not self.is_password_usable(hash):
+ return False
+ cat = self.get_user_category(user)
+ ok, new_hash = self.context.verify_and_update(password, hash,
+ category=cat)
+ if ok and new_hash is not None:
+ # migrate to new hash if needed.
+ user.password = new_hash
+ user.save()
+ return ok
+
+ def user_set_password(self, user, password):
+ """
+ Passlib replacement for User.set_password()
+ """
+ if password is None:
+ user.set_unusable_password()
+ else:
+ cat = self.get_user_category(user)
+ user.password = self.context.hash(password, category=cat)
+
+ def get_user_category(self, user):
+ """
+ Helper for hashing passwords per-user --
+ figure out the CryptContext category for specified Django user object.
+ .. note::
+ This may be overridden via PASSLIB_GET_CATEGORY django setting
+ """
+ if user.is_superuser:
+ return "superuser"
+ elif user.is_staff:
+ return "staff"
+ else:
+ return None
+
+ #=============================================================================
+ # patch control
+ #=============================================================================
+
+ HASHERS_PATH = "django.contrib.auth.hashers"
+ MODELS_PATH = "django.contrib.auth.models"
+ USER_CLASS_PATH = MODELS_PATH + ":User"
+ FORMS_PATH = "django.contrib.auth.forms"
+
+ #: list of locations to patch
+ patch_locations = [
+ #
+ # User object
+ # NOTE: could leave defaults alone, but want to have user available
+ # so that we can support get_user_category()
+ #
+ (USER_CLASS_PATH + ".check_password", "user_check_password", dict(method=True)),
+ (USER_CLASS_PATH + ".set_password", "user_set_password", dict(method=True)),
+
+ #
+ # Hashers module
+ #
+ (HASHERS_PATH + ":", "check_password"),
+ (HASHERS_PATH + ":", "make_password"),
+ (HASHERS_PATH + ":", "get_hashers"),
+ (HASHERS_PATH + ":", "get_hasher"),
+ (HASHERS_PATH + ":", "identify_hasher"),
+
+ #
+ # Patch known imports from hashers module
+ #
+ (MODELS_PATH + ":", "check_password"),
+ (MODELS_PATH + ":", "make_password"),
+ (FORMS_PATH + ":", "get_hasher"),
+ (FORMS_PATH + ":", "identify_hasher"),
+
+ ]
+
+ def install_patch(self):
+ """
+ Install monkeypatch to replace django hasher framework.
+ """
+ # don't reapply
+ log = self.log
+ if self.patched:
+ log.warning("monkeypatching already applied, refusing to reapply")
+ return False
+
+ # version check
+ if DJANGO_VERSION < MIN_DJANGO_VERSION:
+ raise RuntimeError("passlib.ext.django requires django >= %s" %
+ (MIN_DJANGO_VERSION,))
+
+ # log start
+ log.debug("preparing to monkeypatch django ...")
+
+ # run through patch locations
+ manager = self._manager
+ for record in self.patch_locations:
+ if len(record) == 2:
+ record += ({},)
+ target, source, opts = record
+ if target.endswith((":", ",")):
+ target += source
+ value = getattr(self, source)
+ if opts.get("method"):
+ # have to wrap our method in a function,
+ # since we're installing it in a class *as* a method
+ # XXX: make this a flag for .patch()?
+ value = _wrap_method(value)
+ manager.patch(target, value)
+
+ # reset django's caches (e.g. get_hash_by_algorithm)
+ self.reset_hashers()
+
+ # done!
+ self.patched = True
+ log.debug("... finished monkeypatching django")
+ return True
+
+ def remove_patch(self):
+ """
+ Remove monkeypatch from django hasher framework.
+ As precaution in case there are lingering refs to context,
+ context object will be wiped.
+
+ .. warning::
+ This may cause problems if any other Django modules have imported
+ their own copies of the patched functions, though the patched
+ code has been designed to throw an error as soon as possible in
+ this case.
+ """
+ log = self.log
+ manager = self._manager
+
+ if self.patched:
+ log.debug("removing django monkeypatching...")
+ manager.unpatch_all(unpatch_conflicts=True)
+ self.context.load({})
+ self.patched = False
+ self.reset_hashers()
+ log.debug("...finished removing django monkeypatching")
+ return True
+
+ if manager.isactive(): # pragma: no cover -- sanity check
+ log.warning("reverting partial monkeypatching of django...")
+ manager.unpatch_all()
+ self.context.load({})
+ self.reset_hashers()
+ log.debug("...finished removing django monkeypatching")
+ return True
+
+ log.debug("django not monkeypatched")
+ return False
+
+ #=============================================================================
+ # loading config
+ #=============================================================================
+
+ def load_model(self):
+ """
+ Load configuration from django, and install patch.
+ """
+ self._load_settings()
+ if self.enabled:
+ try:
+ self.install_patch()
+ except:
+ # try to undo what we can
+ self.remove_patch()
+ raise
+ else:
+ if self.patched: # pragma: no cover -- sanity check
+ log.error("didn't expect monkeypatching would be applied!")
+ self.remove_patch()
+ log.debug("passlib.ext.django loaded")
+
+ def _load_settings(self):
+ """
+ Update settings from django
+ """
+ from django.conf import settings
+
+ # TODO: would like to add support for inheriting config from a preset
+ # (or from existing hasher state) and letting PASSLIB_CONFIG
+ # be an update, not a replacement.
+
+ # TODO: wrap and import any custom hashers as passlib handlers,
+ # so they could be used in the passlib config.
+
+ # load config from settings
+ _UNSET = object()
+ config = getattr(settings, "PASSLIB_CONFIG", _UNSET)
+ if config is _UNSET:
+ # XXX: should probably deprecate this alias
+ config = getattr(settings, "PASSLIB_CONTEXT", _UNSET)
+ if config is _UNSET:
+ config = "passlib-default"
+ if config is None:
+ warn("setting PASSLIB_CONFIG=None is deprecated, "
+ "and support will be removed in Passlib 1.8, "
+ "use PASSLIB_CONFIG='disabled' instead.",
+ DeprecationWarning)
+ config = "disabled"
+ elif not isinstance(config, (unicode, bytes, dict)):
+ raise exc.ExpectedTypeError(config, "str or dict", "PASSLIB_CONFIG")
+
+ # load custom category func (if any)
+ get_category = getattr(settings, "PASSLIB_GET_CATEGORY", None)
+ if get_category and not callable(get_category):
+ raise exc.ExpectedTypeError(get_category, "callable", "PASSLIB_GET_CATEGORY")
+
+ # check if we've been disabled
+ if config == "disabled":
+ self.enabled = False
+ return
+ else:
+ self.__dict__.pop("enabled", None)
+
+ # resolve any preset aliases
+ if isinstance(config, str) and '\n' not in config:
+ config = get_preset_config(config)
+
+ # setup category func
+ if get_category:
+ self.get_user_category = get_category
+ else:
+ self.__dict__.pop("get_category", None)
+
+ # setup context
+ self.context.load(config)
+ self.reset_hashers()
+
+ #=============================================================================
+ # eof
+ #=============================================================================
#=============================================================================
# wrapping passlib handlers as django hashers
@@ -169,6 +842,7 @@ class ProxyProperty(object):
def __delete__(self, obj):
delattr(obj, self.attr)
+
class _PasslibHasherWrapper(object):
"""
adapter which which wraps a :cls:`passlib.ifc.PasswordHash` class,
@@ -177,7 +851,6 @@ class _PasslibHasherWrapper(object):
:param passlib_handler:
passlib hash handler (e.g. :cls:`passlib.hash.sha256_crypt`.
"""
-
#=====================================================================
# instance attrs
#=====================================================================
@@ -195,9 +868,14 @@ class _PasslibHasherWrapper(object):
#=====================================================================
def __init__(self, passlib_handler):
# init handler
- assert not hasattr(passlib_handler, "django_name"), \
- "bug in get_passlib_hasher() -- handlers that reflect an official django hasher " \
- "should be used directly"
+ if getattr(passlib_handler, "django_name", None):
+ raise ValueError("handlers that reflect an official django "
+ "hasher shouldn't be wrapped: %r" %
+ (passlib_handler.name,))
+ if passlib_handler.is_disabled:
+ # XXX: could this be implemented?
+ raise ValueError("can't wrap disabled-hash handlers: %r" %
+ (passlib_handler.name))
self.passlib_handler = passlib_handler
# init rounds support
@@ -240,7 +918,7 @@ class _PasslibHasherWrapper(object):
@memoized_property
def algorithm(self):
- return PASSLIB_HASHER_PREFIX + self.passlib_handler.name
+ return PASSLIB_WRAPPER_PREFIX + self.passlib_handler.name
#=====================================================================
# hasher api
@@ -267,7 +945,10 @@ class _PasslibHasherWrapper(object):
kwds['rounds'] = self.rounds
elif rounds is not None or iterations is not None:
warn("%s.hash(): 'rounds' and 'iterations' are ignored" % self.__name__)
- return self.passlib_handler.hash(password, **kwds)
+ handler = self.passlib_handler
+ if kwds:
+ handler = handler.using(**kwds)
+ return handler.hash(password)
def safe_summary(self, encoded):
from django.contrib.auth.hashers import mask_hash
@@ -285,7 +966,6 @@ class _PasslibHasherWrapper(object):
items.append((_(key), value))
return OrderedDict(items)
- # added in django 1.6
def must_update(self, encoded):
# TODO: would like access CryptContext, would need caller to pass it to get_passlib_hasher().
# for now (as of passlib 1.6.6), replicating django policy that this returns True
@@ -302,68 +982,6 @@ class _PasslibHasherWrapper(object):
# eoc
#=====================================================================
-#: legacy alias for < 1.6.6
-_HasherWrapper = _PasslibHasherWrapper
-
-# cache of hasher wrappers generated by get_passlib_hasher()
-_hasher_cache = WeakKeyDictionary()
-
-def get_passlib_hasher(handler, algorithm=None, native_only=False):
- """create *Hasher*-compatible wrapper for specified passlib hash.
-
- This takes in the name of a passlib hash (or the handler object itself),
- and returns a wrapper instance which should be compatible with
- Django's Hashers framework.
-
- If the named hash corresponds to one of Django's builtin hashers,
- an instance of the real hasher class will be returned.
-
- Note that the format of the handler won't be altered,
- so will probably not be compatible with Django's algorithm format,
- so the monkeypatch provided by this plugin must have been applied.
- """
- if isinstance(handler, native_string_types):
- handler = get_crypt_handler(handler)
- if hasattr(handler, "django_name"):
- # return native hasher instance
- # XXX: should add this to _hasher_cache[]
- # TODO: should have this honor .using() configuration
- name = handler.django_name
- if name == "sha1" and algorithm == "unsalted_sha1":
- # django 1.4.6+ uses a separate hasher for "sha1$$digest" hashes,
- # but passlib just reuses the "sha1$salt$digest" handler.
- # we want to resolve to correct django hasher.
- name = algorithm
- return _get_hasher(name)
- if native_only:
- # caller doesn't want any wrapped hashers.
- return None
- if handler.name == "django_disabled":
- raise ValueError("can't wrap unusable-password handler")
- try:
- return _hasher_cache[handler]
- except KeyError:
- hasher = _hasher_cache[handler] = _PasslibHasherWrapper(handler)
- return hasher
-
-def _get_hasher(algorithm):
- """wrapper to call django.contrib.auth.hashers:get_hasher()"""
- import sys
- module = sys.modules.get("passlib.ext.django.models")
- if module is None:
- # we haven't patched django, so just import directly
- from django.contrib.auth.hashers import get_hasher
- return get_hasher(algorithm)
- else:
- # We've patched django's get_hashers(), so calling django's get_hasher()
- # or get_hashers_by_algorithm() would only land us back here via patched get_hashers().
- # As non-ideal workaround, have to use original get_hashers()...
- get_hashers = module._manager.getorig("django.contrib.auth.hashers:get_hashers")
- for hasher in get_hashers():
- if hasher.algorithm == algorithm:
- return hasher
- raise ValueError("unknown hasher: %r" % algorithm)
-
#=============================================================================
# adapting django hashers -> passlib handlers
#=============================================================================
@@ -467,8 +1085,12 @@ class _PatchManager(object):
self.log = log or logging.getLogger(__name__ + "._PatchManager")
self._state = {}
+ def isactive(self):
+ return bool(self._state)
+
# bool value tests if any patches are currently applied.
- __bool__ = __nonzero__ = lambda self: bool(self._state)
+ # NOTE: this behavior is deprecated in favor of .isactive
+ __bool__ = __nonzero__ = isactive
def _import_path(self, path):
"""retrieve obj and final attribute name from resource path"""
@@ -548,9 +1170,16 @@ class _PatchManager(object):
return wrapped_by(wrapped, *args, **kwds)
update_wrapper(wrapper, value)
value = wrapper
+ if callable(value):
+ # needed by DjangoContextAdapter init
+ get_method_function(value)._patched_original_value = orig
self._set_path(path, value)
self._state[path] = (orig, value)
+ @classmethod
+ def peek_unpatched_func(cls, value):
+ return value._patched_original_value
+
##def patch_many(self, **kwds):
## "override specified resources with new values"
## for path, value in iteritems(kwds):
@@ -564,6 +1193,12 @@ class _PatchManager(object):
path = parent + sep + (name or func.__name__)
self.patch(path, func, wrap=wrap)
return func
+ if callable(name):
+ # called in non-decorator mode
+ func = name
+ name = None
+ builder(func)
+ return None
return builder
#===================================================================
diff --git a/passlib/ifc.py b/passlib/ifc.py
index 72c9df4..4d57daa 100644
--- a/passlib/ifc.py
+++ b/passlib/ifc.py
@@ -243,6 +243,16 @@ class PasswordHash(object):
# but are documented here so there's a list of them *somewhere*.
#---------------------------------------------------------------
+ # extra metdata
+ #---------------------------------------------------------------
+
+ #: optionally present if hasher corresponds to format built into Django.
+ #: this attribute (if not None) should be the Django 'algorithm' name.
+ #: also indicates to passlib.ext.django that (when installed in django),
+ #: django's native hasher should be used in preference to this one.
+ ## django_name
+
+ #---------------------------------------------------------------
# checksum information - defined for many hashes
#---------------------------------------------------------------
## checksum_chars
diff --git a/passlib/tests/test_ext_django.py b/passlib/tests/test_ext_django.py
index b51a59e..9115860 100644
--- a/passlib/tests/test_ext_django.py
+++ b/passlib/tests/test_ext_django.py
@@ -2,28 +2,32 @@
#=============================================================================
# imports
#=============================================================================
-# NOTE: double __future__ is workaround for py2.5.0 bug,
-# per https://bitbucket.org/ecollins/passlib/issues/58#comment-20589295
-from __future__ import with_statement
-from __future__ import absolute_import
# core
+from __future__ import absolute_import, division, print_function
import logging; log = logging.getLogger(__name__)
import sys
# site
# pkg
from passlib import apps as _apps, exc, registry
from passlib.apps import django10_context, django14_context, django16_context
-from passlib.utils.compat import iteritems, unicode, get_method_function, u, PY3, suppress_cause
+from passlib.context import CryptContext
+from passlib.ext.django.utils import (
+ DJANGO_VERSION, MIN_DJANGO_VERSION, DjangoTranslator,
+)
+from passlib.utils.compat import iteritems, get_method_function, u
from passlib.utils import memoized_property
# tests
-from passlib.tests.utils import TestCase, skipUnless, TEST_MODE, handler_derived_from
+from passlib.tests.utils import TestCase, TEST_MODE, handler_derived_from
from passlib.tests.test_handlers import get_handler_case, conditionally_available_hashes
# local
-
+__all__ = [
+ "DjangoBehaviorTest",
+ "ExtensionBehaviorTest",
+ "_ExtensionSupport",
+]
#=============================================================================
# configure django settings for testcases
#=============================================================================
-from passlib.ext.django.utils import DJANGO_VERSION, MIN_DJANGO_VERSION
# whether we have supported django version
has_min_django = DJANGO_VERSION >= MIN_DJANGO_VERSION
@@ -113,7 +117,7 @@ def create_mock_setter():
#=============================================================================
# build config dict that matches stock django
-# TODO: move these to passlib.apps
+# XXX: move these to passlib.apps?
if DJANGO_VERSION >= (1, 10):
stock_config = _apps.django110_context.to_dict()
stock_rounds = 30000
@@ -134,7 +138,7 @@ stock_config.update(
from passlib.hash import django_pbkdf2_sha256
sample_hashes = dict(
django_pbkdf2_sha256=("not a password", django_pbkdf2_sha256.hash("not a password",
- rounds=stock_config.get("django_pbkdf2_sha256__default_rounds")))
+ rounds=stock_config.get("django_pbkdf2_sha256__default_rounds")))
)
#=============================================================================
@@ -185,7 +189,7 @@ class _ExtensionSupport(object):
"""test that django is in unpatched state"""
# make sure we aren't currently patched
mod = sys.modules.get("passlib.ext.django.models")
- self.assertFalse(mod and mod._patched, "patch should not be enabled")
+ self.assertFalse(mod and mod.adapter.patched, "patch should not be enabled")
# make sure no objects have been replaced, by checking __module__
for obj, attr, source, patched in self._iter_patch_candidates():
@@ -202,12 +206,12 @@ class _ExtensionSupport(object):
"""helper to ensure django HAS been patched, and is using specified config"""
# make sure we're currently patched
mod = sys.modules.get("passlib.ext.django.models")
- self.assertTrue(mod and mod._patched, "patch should have been enabled")
+ self.assertTrue(mod and mod.adapter.patched, "patch should have been enabled")
# make sure only the expected objects have been patched
for obj, attr, source, patched in self._iter_patch_candidates():
if patched:
- self.assertTrue(source == "passlib.ext.django.models",
+ self.assertTrue(source == "passlib.ext.django.utils",
"obj=%r attr=%r should have been patched: %r" %
(obj, attr, source))
else:
@@ -242,7 +246,7 @@ class _ExtensionSupport(object):
# remove patches and unload module
mod = sys.modules.get("passlib.ext.django.models")
if mod:
- mod._remove_patch()
+ mod.adapter.remove_patch()
del sys.modules["passlib.ext.django.models"]
# wipe config from django settings
update_settings(**dict((key, UNSET) for key in self._config_keys))
@@ -342,7 +346,6 @@ class DjangoBehaviorTest(_ExtensionTest):
PASS1 = "toomanysecrets"
WRONG1 = "letmein"
- from passlib.ext.django.utils import hasher_to_passlib_name, passlib_to_hasher_name
from django.contrib.auth.hashers import (check_password, make_password,
is_password_usable, identify_hasher)
@@ -357,7 +360,7 @@ class DjangoBehaviorTest(_ExtensionTest):
# should have patched both places
from django.contrib.auth.models import check_password as check_password2
- self.assertIs(check_password2, check_password)
+ self.assertEqual(check_password2, check_password)
#=======================================================
# default algorithm
@@ -505,8 +508,9 @@ class DjangoBehaviorTest(_ExtensionTest):
try:
secret, hash = sample_hashes[scheme]
except KeyError:
+ get_sample_hash = testcase("setUp").get_sample_hash
while True:
- secret, hash = testcase('setUp').get_sample_hash()
+ secret, hash = get_sample_hash()
if secret: # don't select blank passwords
break
other = 'dontletmein'
@@ -546,7 +550,8 @@ class DjangoBehaviorTest(_ExtensionTest):
#-------------------------------------------------------
# make_password() correctly selects algorithm
#-------------------------------------------------------
- hash2 = make_password(secret, hasher=passlib_to_hasher_name(scheme))
+ alg = DjangoTranslator().passlib_to_django_name(scheme)
+ hash2 = make_password(secret, hasher=alg)
self.assertTrue(handler.verify(secret, hash2))
#-------------------------------------------------------
@@ -570,7 +575,7 @@ class DjangoBehaviorTest(_ExtensionTest):
# identify_hasher() recognizes known hash
#-------------------------------------------------------
self.assertTrue(is_password_usable(hash))
- name = hasher_to_passlib_name(identify_hasher(hash).algorithm)
+ name = DjangoTranslator().django_to_passlib_name(identify_hasher(hash).algorithm)
self.assertEqual(name, scheme)
class ExtensionBehaviorTest(DjangoBehaviorTest):
@@ -631,7 +636,7 @@ class DjangoExtensionTest(_ExtensionTest):
# setup helpers
import django.contrib.auth.models as models
- from passlib.ext.django.models import _manager
+ from passlib.ext.django.models import adapter
def dummy():
pass
@@ -639,34 +644,35 @@ class DjangoExtensionTest(_ExtensionTest):
orig = models.User.set_password
models.User.set_password = dummy
with self.assertWarningList("another library has patched.*User\.set_password"):
- _manager.check_all()
+ adapter._manager.check_all()
models.User.set_password = orig
# mess with models.check_password, make sure it's detected
orig = models.check_password
models.check_password = dummy
with self.assertWarningList("another library has patched.*models:check_password"):
- _manager.check_all()
+ adapter._manager.check_all()
models.check_password = orig
def test_02_handler_wrapper(self):
"""test Hasher-compatible handler wrappers"""
- from passlib.ext.django.utils import get_passlib_hasher
from django.contrib.auth import hashers
+ passlib_to_django = DjangoTranslator().passlib_to_django
+
# should return native django hasher if available
if DJANGO_VERSION > (1,10):
- self.assertRaises(ValueError, get_passlib_hasher, "hex_md5")
+ self.assertRaises(ValueError, passlib_to_django, "hex_md5")
else:
- hasher = get_passlib_hasher("hex_md5")
+ hasher = passlib_to_django("hex_md5")
self.assertIsInstance(hasher, hashers.UnsaltedMD5PasswordHasher)
- hasher = get_passlib_hasher("django_bcrypt")
+ hasher = passlib_to_django("django_bcrypt")
self.assertIsInstance(hasher, hashers.BCryptPasswordHasher)
# otherwise should return wrapper
from passlib.hash import sha256_crypt
- hasher = get_passlib_hasher("sha256_crypt")
+ hasher = passlib_to_django("sha256_crypt")
self.assertEqual(hasher.algorithm, "passlib_sha256_crypt")
# and wrapper should return correct hash
@@ -793,169 +799,5 @@ class DjangoExtensionTest(_ExtensionTest):
#===================================================================
#=============================================================================
-# helpers for HashersTest below
-#=============================================================================
-
-from passlib.context import CryptContext
-class ContextWithHook(CryptContext):
- """subclass which invokes update_hook(self) before major actions"""
-
- @staticmethod
- def update_hook(self):
- pass
-
- def hash(self, *args, **kwds):
- self.update_hook(self)
- return super(ContextWithHook, self).hash(*args, **kwds)
-
- def verify(self, *args, **kwds):
- self.update_hook(self)
- return super(ContextWithHook, self).verify(*args, **kwds)
-
- def needs_update(self, *args, **kwds):
- self.update_hook(self)
- return super(ContextWithHook, self).needs_update(*args, **kwds)
-
- def verify_and_update(self, *args, **kwds):
- self.update_hook(self)
- return super(ContextWithHook, self).verify_and_update(*args, **kwds)
-
-#=============================================================================
-# HashersTest --
-# hack up the some of the real django tests to run w/ extension loaded,
-# to ensure we mimic their behavior.
-# however, the django tests were moved out of the package, and into a source-only location
-# as of django 1.7. so we disable tests from that point on unless test-runner specifies
-#=============================================================================
-
-#
-# try to load django's tests/auth_tests/test_hasher.py module,
-# or note why we failed.
-#
-
-test_hashers_mod = None
-hashers_skip_msg = None
-
-if TEST_MODE(max="quick"):
- hashers_skip_msg = "requires >= 'default' test mode"
-
-elif has_min_django:
- import os
- import sys
- source_path = os.environ.get("PASSLIB_TESTS_DJANGO_SOURCE_PATH")
-
- if source_path:
- if not os.path.exists(source_path):
- raise EnvironmentError("django source path not found: %r" % source_path)
- if not all(os.path.exists(os.path.join(source_path, name))
- for name in ["django", "tests"]):
- raise EnvironmentError("invalid django source path: %r" % source_path)
- log.info("using django tests from source path: %r", source_path)
- tests_path = os.path.join(source_path, "tests")
- sys.path.insert(0, tests_path)
- try:
- from auth_tests import test_hashers as test_hashers_mod
- except ImportError as err:
- raise suppress_cause(
- EnvironmentError("error trying to import django tests "
- "from source path (%r): %r" %
- (source_path, err)))
- finally:
- sys.path.remove(tests_path)
-
- else:
- hashers_skip_msg = "requires PASSLIB_TESTS_DJANGO_SOURCE_PATH to be set"
-
- if TEST_MODE("full"):
- # print warning so user knows what's happening
- sys.stderr.write("\nWARNING: $PASSLIB_TESTS_DJANGO_SOURCE_PATH is not set; "
- "can't run Django's own unittests against passlib.ext.django\n")
-
-elif DJANGO_VERSION:
- hashers_skip_msg = "django version too old"
-
-else:
- hashers_skip_msg = "django not installed"
-
-#
-# if found module, create wrapper to run django's own tests w/ passlib monkeypatched in.
-#
-if test_hashers_mod:
- from passlib.utils.compat import get_unbound_method_function
-
- class HashersTest(test_hashers_mod.TestUtilsHashPass, _ExtensionSupport):
- """run django's hasher unittests against passlib's extension
- and workalike implementations"""
-
- # port patchAttr() helper method from passlib.tests.utils.TestCase
- patchAttr = get_unbound_method_function(TestCase.patchAttr)
-
- def setUp(self):
- #
- # install passlib.ext.django monkeypatches
- # NOTE: omitted orig setup, want to install our extension,
- # and load hashers through it instead.
- #
- self.load_extension(PASSLIB_CONTEXT=stock_config, check=False)
- from passlib.ext.django.models import password_context
- from passlib.ext.django.utils import get_passlib_hasher
-
- #
- # update test module to use our versions of some hasher funcs
- #
- from django.contrib.auth import hashers
- for attr in ["make_password",
- "check_password",
- "identify_hasher",
- "get_hasher"]:
- self.patchAttr(test_hashers_mod, attr, getattr(hashers, attr))
-
- #
- # django tests expect empty django_des_crypt salt field
- #
- from passlib.hash import django_des_crypt
- self.patchAttr(django_des_crypt, "use_duplicate_salt", False)
-
- #
- # hack: need password_context to keep up to date with hasher.iterations
- #
- def update_hook(context):
- """called to sync hasher.rounds to crypt context before any operations"""
- for handler in context.schemes(resolve=True):
- if 'rounds' not in handler.setting_kwds:
- continue
- hasher = get_passlib_hasher(handler, native_only=True)
- if not hasher:
- continue
- rounds = getattr(hasher, "rounds", None) or \
- getattr(hasher, "iterations", None)
- if rounds is None:
- continue
- prefix = handler.name + "__"
- context.update({prefix + "default_rounds": rounds,
- prefix + "min_rounds": rounds,
- prefix + "max_rounds": rounds})
-
- self.password_context = password_context
- self.patchAttr(password_context, "__class__", ContextWithHook)
- self.patchAttr(password_context, "update_hook", update_hook)
-
- # NOTE: omitting this test, since tries to reinitialize the hashers on top of our patch.
- test_pbkdf2_upgrade_new_hasher = lambda self: self.skipTest("omitted by passlib")
-
- def tearDown(self):
- self.unload_extension()
- super(HashersTest, self).tearDown()
-
-else:
- # otherwise leave a stub so test log tells why test was skipped.
-
- class HashersTest(TestCase):
-
- def test_external_django_hasher_tests(self):
- """external django hasher tests"""
- raise self.skipTest(hashers_skip_msg)
-
-#=============================================================================
# eof
#=============================================================================
diff --git a/passlib/tests/test_ext_django_source.py b/passlib/tests/test_ext_django_source.py
new file mode 100644
index 0000000..4a4b397
--- /dev/null
+++ b/passlib/tests/test_ext_django_source.py
@@ -0,0 +1,249 @@
+"""
+test passlib.ext.django against django source tests
+"""
+#=============================================================================
+# imports
+#=============================================================================
+from __future__ import absolute_import, division, print_function
+# core
+import logging; log = logging.getLogger(__name__)
+# site
+# pkg
+from passlib.utils.compat import suppress_cause
+from passlib.ext.django.utils import DJANGO_VERSION, DjangoTranslator, _PasslibHasherWrapper
+# tests
+from passlib.tests.utils import TestCase, TEST_MODE
+from .test_ext_django import (
+ has_min_django, stock_config, settings, _ExtensionSupport,
+)
+# local
+__all__ = [
+ "HashersTest",
+]
+#=============================================================================
+# HashersTest --
+# hack up the some of the real django tests to run w/ extension loaded,
+# to ensure we mimic their behavior.
+# however, the django tests were moved out of the package, and into a source-only location
+# as of django 1.7. so we disable tests from that point on unless test-runner specifies
+#=============================================================================
+
+#: ref to django unittest root module (if found)
+test_hashers_mod = None
+
+#: message about why test module isn't present (if not found)
+hashers_skip_msg = None
+
+#----------------------------------------------------------------------
+# try to load django's tests/auth_tests/test_hasher.py module,
+# or note why we failed.
+#----------------------------------------------------------------------
+if TEST_MODE(max="quick"):
+ hashers_skip_msg = "requires >= 'default' test mode"
+
+elif has_min_django:
+ import os
+ import sys
+ source_path = os.environ.get("PASSLIB_TESTS_DJANGO_SOURCE_PATH")
+
+ if source_path:
+ if not os.path.exists(source_path):
+ raise EnvironmentError("django source path not found: %r" % source_path)
+ if not all(os.path.exists(os.path.join(source_path, name))
+ for name in ["django", "tests"]):
+ raise EnvironmentError("invalid django source path: %r" % source_path)
+ log.info("using django tests from source path: %r", source_path)
+ tests_path = os.path.join(source_path, "tests")
+ sys.path.insert(0, tests_path)
+ try:
+ from auth_tests import test_hashers as test_hashers_mod
+ except ImportError as err:
+ raise suppress_cause(
+ EnvironmentError("error trying to import django tests "
+ "from source path (%r): %r" %
+ (source_path, err)))
+ finally:
+ sys.path.remove(tests_path)
+
+ else:
+ hashers_skip_msg = "requires PASSLIB_TESTS_DJANGO_SOURCE_PATH to be set"
+
+ if TEST_MODE("full"):
+ # print warning so user knows what's happening
+ sys.stderr.write("\nWARNING: $PASSLIB_TESTS_DJANGO_SOURCE_PATH is not set; "
+ "can't run Django's own unittests against passlib.ext.django\n")
+
+elif DJANGO_VERSION:
+ hashers_skip_msg = "django version too old"
+
+else:
+ hashers_skip_msg = "django not installed"
+
+#----------------------------------------------------------------------
+# if found module, create wrapper to run django's own tests,
+# but with passlib monkeypatched in.
+#----------------------------------------------------------------------
+if test_hashers_mod:
+ from django.core.signals import setting_changed
+ from django.dispatch import receiver
+ from django.utils.module_loading import import_string
+ from passlib.utils.compat import get_unbound_method_function
+
+ class HashersTest(test_hashers_mod.TestUtilsHashPass, _ExtensionSupport):
+ """
+ Run django's hasher unittests against passlib's extension
+ and workalike implementations
+ """
+
+ #==================================================================
+ # helpers
+ #==================================================================
+
+ # port patchAttr() helper method from passlib.tests.utils.TestCase
+ patchAttr = get_unbound_method_function(TestCase.patchAttr)
+
+ #==================================================================
+ # custom setup
+ #==================================================================
+ def setUp(self):
+ #---------------------------------------------------------
+ # install passlib.ext.django adapter, and get context
+ #---------------------------------------------------------
+ self.load_extension(PASSLIB_CONTEXT=stock_config, check=False)
+ from passlib.ext.django.models import adapter
+ context = adapter.context
+
+ #---------------------------------------------------------
+ # patch tests module to use our versions of patched funcs
+ # (which should be installed in hashers module)
+ #---------------------------------------------------------
+ from django.contrib.auth import hashers
+ for attr in ["make_password",
+ "check_password",
+ "identify_hasher",
+ "is_password_usable",
+ "get_hasher"]:
+ self.patchAttr(test_hashers_mod, attr, getattr(hashers, attr))
+
+ #---------------------------------------------------------
+ # django tests expect empty django_des_crypt salt field
+ #---------------------------------------------------------
+ from passlib.hash import django_des_crypt
+ self.patchAttr(django_des_crypt, "use_duplicate_salt", False)
+
+ #---------------------------------------------------------
+ # install receiver to update scheme list if test changes settings
+ #---------------------------------------------------------
+ django_to_passlib_name = DjangoTranslator().django_to_passlib_name
+
+ @receiver(setting_changed, weak=False)
+ def update_schemes(**kwds):
+ if kwds and kwds['setting'] != 'PASSWORD_HASHERS':
+ return
+ assert context is adapter.context
+ schemes = [
+ django_to_passlib_name(import_string(hash_path)())
+ for hash_path in settings.PASSWORD_HASHERS
+ ]
+ # workaround for a few tests that only specify hex_md5,
+ # but test for django_salted_md5 format.
+ if "hex_md5" in schemes and "django_salted_md5" not in schemes:
+ schemes.append("django_salted_md5")
+ schemes.append("django_disabled")
+ context.update(schemes=schemes, deprecated="auto")
+ adapter.reset_hashers()
+
+ self.addCleanup(setting_changed.disconnect, update_schemes)
+
+ update_schemes()
+
+ #---------------------------------------------------------
+ # need password_context to keep up to date with django_hasher.iterations,
+ # which is frequently patched by django tests.
+ #
+ # HACK: to fix this, inserting wrapper around a bunch of context
+ # methods so that any time adapter calls them,
+ # attrs are resynced first.
+ #---------------------------------------------------------
+
+ def update_rounds():
+ """
+ sync django hasher config -> passlib hashers
+ """
+ for handler in context.schemes(resolve=True):
+ if 'rounds' not in handler.setting_kwds:
+ continue
+ hasher = adapter.passlib_to_django(handler)
+ if isinstance(hasher, _PasslibHasherWrapper):
+ continue
+ rounds = getattr(hasher, "rounds", None) or \
+ getattr(hasher, "iterations", None)
+ if rounds is None:
+ continue
+ # XXX: this doesn't modify the context, which would
+ # cause other weirdness (since it would replace handler factories completely,
+ # instead of just updating their state)
+ handler.min_desired_rounds = handler.max_desired_rounds = handler.default_rounds = rounds
+
+ _in_update = [False]
+
+ def update_wrapper(wrapped, *args, **kwds):
+ """
+ wrapper around arbitrary func, that first triggers sync
+ """
+ if not _in_update[0]:
+ _in_update[0] = True
+ try:
+ update_rounds()
+ finally:
+ _in_update[0] = False
+ return wrapped(*args, **kwds)
+
+ # sync before any context call
+ for attr in ["schemes", "handler", "default_scheme", "hash",
+ "verify", "needs_update", "verify_and_update"]:
+ self.patchAttr(context, attr, update_wrapper, wrap=True)
+
+ # sync whenever adapter tries to resolve passlib hasher
+ self.patchAttr(adapter, "django_to_passlib", update_wrapper, wrap=True)
+
+ def tearDown(self):
+ # NOTE: could rely on addCleanup() instead, but need py26 compat
+ self.unload_extension()
+ super(HashersTest, self).tearDown()
+
+ #==================================================================
+ # skip a few methods that can't be replicated properly
+ # *want to minimize these as much as possible*
+ #==================================================================
+
+ _OMIT = lambda self: self.skipTest("omitted by passlib")
+
+ # XXX: this test registers two classes w/ same algorithm id,
+ # something we don't support -- how does django sanely handle
+ # that anyways? get_hashers_by_algorithm() should throw KeyError, right?
+ test_pbkdf2_upgrade_new_hasher = _OMIT
+
+ # TODO: need to support wrapping django's harden-runtime feature w/ our own.
+ # still won't be able to pass their tests, because what they test for
+ # isn't how CryptContext.harden_verify works.
+ test_check_password_calls_harden_runtime = _OMIT
+ test_bcrypt_harden_runtime = _OMIT
+ test_pbkdf2_harden_runtime = _OMIT
+
+ #==================================================================
+ # eoc
+ #==================================================================
+
+else:
+ # otherwise leave a stub so test log tells why test was skipped.
+
+ class HashersTest(TestCase):
+
+ def test_external_django_hasher_tests(self):
+ """external django hasher tests"""
+ raise self.skipTest(hashers_skip_msg)
+
+#=============================================================================
+# eof
+#=============================================================================
diff --git a/passlib/tests/utils.py b/passlib/tests/utils.py
index 8711da9..bd72652 100644
--- a/passlib/tests/utils.py
+++ b/passlib/tests/utils.py
@@ -6,7 +6,7 @@ from __future__ import with_statement
# core
from binascii import unhexlify
import contextlib
-from functools import wraps
+from functools import wraps, partial
import hashlib
import logging; log = logging.getLogger(__name__)
import random
@@ -636,7 +636,7 @@ class TestCase(_TestCase):
queue.append(path)
return path
- def patchAttr(self, obj, attr, value, require_existing=True):
+ def patchAttr(self, obj, attr, value, require_existing=True, wrap=False):
"""monkeypatch object value, restoring original value on cleanup"""
try:
orig = getattr(obj, attr)
@@ -651,6 +651,9 @@ class TestCase(_TestCase):
self.addCleanup(cleanup)
else:
self.addCleanup(setattr, obj, attr, orig)
+ if wrap:
+ value = partial(value, orig)
+ wraps(orig)(value)
setattr(obj, attr, value)
#===================================================================
diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py
index dbda909..d9c2c1e 100644
--- a/passlib/utils/handlers.py
+++ b/passlib/utils/handlers.py
@@ -2577,6 +2577,19 @@ class PrefixWrapper(object):
return getattr(self.wrapped, attr)
raise AttributeError("missing attribute: %r" % (attr,))
+ def __setattr__(self, attr, value):
+ # if proxy attr present on wrapped object,
+ # and we own it, modify *it* instead.
+ # TODO: needs UTs
+ # TODO: any other cases where wrapped is "owned"?
+ # currently just if created via .using()
+ if attr in self._proxy_attrs and self._derived_from:
+ wrapped = self.wrapped
+ if hasattr(wrapped, attr):
+ setattr(wrapped, attr, value)
+ return
+ return object.__setattr__(self, attr, value)
+
def _unwrap_hash(self, hash):
"""given hash belonging to wrapper, return orig version"""
# NOTE: assumes hash has been validated as unicode already