├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── __init__.py ├── rotatesecretkey ├── __init__.py ├── apps.py ├── middleware.py ├── migrations │ └── __init__.py └── sessions │ ├── __init__.py │ ├── base.py │ ├── cache.py │ ├── cache_db.py │ ├── db.py │ ├── file.py │ └── signed_cookies.py ├── setup.py ├── tests ├── __init__.py ├── settings.py ├── test_middleware.py └── urls.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | 3 | # Created by https://www.gitignore.io/api/macos,linux,django,python,pycharm 4 | 5 | ### Django ### 6 | *.log 7 | *.pot 8 | *.pyc 9 | __pycache__/ 10 | local_settings.py 11 | db.sqlite3 12 | media 13 | 14 | ### Linux ### 15 | *~ 16 | 17 | # temporary files which can be created if a process still has a handle open of a deleted file 18 | .fuse_hidden* 19 | 20 | # KDE directory preferences 21 | .directory 22 | 23 | # Linux trash folder which might appear on any partition or disk 24 | .Trash-* 25 | 26 | # .nfs files are created when an open file is removed but is still being accessed 27 | .nfs* 28 | 29 | ### macOS ### 30 | *.DS_Store 31 | .AppleDouble 32 | .LSOverride 33 | 34 | # Icon must end with two \r 35 | Icon 36 | 37 | # Thumbnails 38 | ._* 39 | 40 | # Files that might appear in the root of a volume 41 | .DocumentRevisions-V100 42 | .fseventsd 43 | .Spotlight-V100 44 | .TemporaryItems 45 | .Trashes 46 | .VolumeIcon.icns 47 | .com.apple.timemachine.donotpresent 48 | 49 | # Directories potentially created on remote AFP share 50 | .AppleDB 51 | .AppleDesktop 52 | Network Trash Folder 53 | Temporary Items 54 | .apdisk 55 | 56 | ### PyCharm ### 57 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 58 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 59 | 60 | # User-specific stuff: 61 | .idea/**/workspace.xml 62 | .idea/**/tasks.xml 63 | .idea/dictionaries 64 | 65 | # Sensitive or high-churn files: 66 | .idea/**/dataSources/ 67 | .idea/**/dataSources.ids 68 | .idea/**/dataSources.xml 69 | .idea/**/dataSources.local.xml 70 | .idea/**/sqlDataSources.xml 71 | .idea/**/dynamic.xml 72 | .idea/**/uiDesigner.xml 73 | 74 | # Gradle: 75 | .idea/**/gradle.xml 76 | .idea/**/libraries 77 | 78 | # CMake 79 | cmake-build-debug/ 80 | 81 | # Mongo Explorer plugin: 82 | .idea/**/mongoSettings.xml 83 | 84 | ## File-based project format: 85 | *.iws 86 | 87 | ## Plugin-specific files: 88 | 89 | # IntelliJ 90 | /out/ 91 | 92 | # mpeltonen/sbt-idea plugin 93 | .idea_modules/ 94 | 95 | # JIRA plugin 96 | atlassian-ide-plugin.xml 97 | 98 | # Cursive Clojure plugin 99 | .idea/replstate.xml 100 | 101 | # Crashlytics plugin (for Android Studio and IntelliJ) 102 | com_crashlytics_export_strings.xml 103 | crashlytics.properties 104 | crashlytics-build.properties 105 | fabric.properties 106 | 107 | ### PyCharm Patch ### 108 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 109 | 110 | # *.iml 111 | # modules.xml 112 | # .idea/misc.xml 113 | # *.ipr 114 | 115 | # Sonarlint plugin 116 | .idea/sonarlint 117 | 118 | ### Python ### 119 | # Byte-compiled / optimized / DLL files 120 | *.py[cod] 121 | *$py.class 122 | 123 | # C extensions 124 | *.so 125 | 126 | # Distribution / packaging 127 | .Python 128 | env/ 129 | build/ 130 | develop-eggs/ 131 | dist/ 132 | downloads/ 133 | eggs/ 134 | .eggs/ 135 | lib/ 136 | lib64/ 137 | parts/ 138 | sdist/ 139 | var/ 140 | wheels/ 141 | *.egg-info/ 142 | .installed.cfg 143 | *.egg 144 | 145 | # PyInstaller 146 | # Usually these files are written by a python script from a template 147 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 148 | *.manifest 149 | *.spec 150 | 151 | # Installer logs 152 | pip-log.txt 153 | pip-delete-this-directory.txt 154 | 155 | # Unit test / coverage reports 156 | htmlcov/ 157 | .tox/ 158 | .coverage 159 | .coverage.* 160 | .cache 161 | nosetests.xml 162 | coverage.xml 163 | *,cover 164 | .hypothesis/ 165 | 166 | # Translations 167 | *.mo 168 | 169 | # Django stuff: 170 | 171 | # Flask stuff: 172 | instance/ 173 | .webassets-cache 174 | 175 | # Scrapy stuff: 176 | .scrapy 177 | 178 | # Sphinx documentation 179 | docs/_build/ 180 | 181 | # PyBuilder 182 | target/ 183 | 184 | # Jupyter Notebook 185 | .ipynb_checkpoints 186 | 187 | # pyenv 188 | .python-version 189 | 190 | # celery beat schedule file 191 | celerybeat-schedule 192 | 193 | # SageMath parsed files 194 | *.sage.py 195 | 196 | # dotenv 197 | .env 198 | 199 | # virtualenv 200 | .venv 201 | venv/ 202 | ENV/ 203 | 204 | # Spyder project settings 205 | .spyderproject 206 | .spyproject 207 | 208 | # Rope project settings 209 | .ropeproject 210 | 211 | # mkdocs documentation 212 | /site 213 | 214 | # End of https://www.gitignore.io/api/macos,linux,django,python,pycharm 215 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Eralp Bayraktar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt *.ini *.cfg *.rst 2 | recursive-include rotatesecretkey *.ico *.png *.css *.gif *.jpg *.txt *.js *.html *.xml -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ================================ 2 | Django Rotate Secret Key 3 | ================================ 4 | 5 | Helps rotating your secret keys safely without losing user sessions, which means without logging users out. 6 | 7 | Compatible with Django versions 2.2, 3.1 and 3.2. 8 | 9 | I haven't found any library to allow us to do this on our production website, so I started the library. 10 | 11 | Medium Post 12 | ============ 13 | https://medium.com/@bayraktar.eralp/changing-rotating-django-secret-key-without-logging-users-out-804a29d3ea65?sk=6fe95fa587574e5875b630617f3ecc91 14 | 15 | Problem 16 | ============ 17 | Once you change the ``SECRET_KEY`` on production, all the old sessions and cookies are invalidated, 18 | users are logged out and data in sessions are lost. 19 | 20 | This is good if your ``SECRET_KEY`` is compromised! 21 | But not good if you just want to rotate in a regular schedule for security purposes. 22 | 23 | This library allows you to continue supporting old sessions signed with your old secret key, 24 | while rewriting them with the new secret key if the user comes to the website. 25 | 26 | So optimal schedule would be 27 | 28 | - you decide to rotate your secret key 29 | - Install ``django-rotate-secret-key`` and configure 30 | - Support both keys for a limited time (x months) 31 | - Roll back ``django-rotate-secret-key`` and keep your secret key the same (removing the old one) 32 | 33 | If a user comes back to the website after x months, his session will be invalidated. 34 | But for all the regular users this should be seamless transition. 35 | 36 | Compatibility 37 | ============= 38 | 39 | If you are using JWT tokens created by ``django-rest-framework-jwt``, currently package is not compatible. 40 | 41 | Getting It 42 | ============ 43 | :: 44 | 45 | $ pip install django-rotate-secret-key 46 | 47 | Installing It 48 | ============== 49 | 50 | This is safe to do even before you decide to rotate your keys, 51 | it basically has no effect before you change the settings.:: 52 | 53 | INSTALLED_APPS = ( 54 | ... 55 | 'rotatesecretkey', 56 | ... 57 | ) 58 | 59 | Settings 60 | ============ 61 | 62 | Replace AuthenticationMiddleware with RotateAuthenticationMiddleware:: 63 | 64 | MIDDLEWARE = [ 65 | ... 66 | # 'django.contrib.auth.middleware.AuthenticationMiddleware', 67 | 'rotatesecretkey.middleware.RotateAuthenticationMiddleware', 68 | ... 69 | ] 70 | 71 | Replace SESSION_ENGINE:: 72 | 73 | SESSION_ENGINE = 'rotatesecretkey.sessions' 74 | 75 | Add the old secret key into OLD_SECRET_KEY, and create a new ``SECRET_KEY``.:: 76 | 77 | SECRET_KEY = 'NEWRANDOMKEY' 78 | OLD_SECRET_KEY = 'your_previous_secret_key_that_you_want_to_support' 79 | 80 | Once these changes go live your website will decode old sessions with 81 | the OLD_SECRET_KEY and resign them with the new ``SECRET_KEY``. 82 | 83 | After some time (like 1 or 2 months) you should roll these changes back and just keep the ``SECRET_KEY``.:: 84 | 85 | SECRET_KEY = 'NEWRANDOMKEY' 86 | 87 | You don't want to support ``OLD_SECRET_KEY`` forever but long enough to give your visitors a 88 | chance to visit the website and rewrite their sessions with the new key. 89 | 90 | Things to keep in mind 91 | ====================== 92 | 93 | This library allows keeping Sessions intact and allowing seamless transition for your visitors, if you are using 94 | Django's signing features manually for other purposes (like signing your backups etc.) a generic library cannot take it 95 | into account. 96 | 97 | What SECRET_KEY doesn't break 98 | ============================= 99 | 100 | Even if you don't use this library SECRET_KEY is not used to encrypt user password or OAUTH tokens. So you shouldn't 101 | worry about them during your key rotation. 102 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EralpB/django-rotate-secret-key/0e8dac667a421dddacc019bf5328b5ea67ae08db/__init__.py -------------------------------------------------------------------------------- /rotatesecretkey/__init__.py: -------------------------------------------------------------------------------- 1 | default_app_config = 'rotatesecretkey.apps.RotatesecretkeyConfig' 2 | -------------------------------------------------------------------------------- /rotatesecretkey/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class RotatesecretkeyConfig(AppConfig): 5 | name = 'rotatesecretkey' 6 | -------------------------------------------------------------------------------- /rotatesecretkey/middleware.py: -------------------------------------------------------------------------------- 1 | import django 2 | from django.utils.deprecation import MiddlewareMixin 3 | from django.contrib.auth import settings 4 | from django.utils.functional import SimpleLazyObject 5 | from django.contrib.auth import ( 6 | _get_user_session_key, 7 | BACKEND_SESSION_KEY, 8 | load_backend, 9 | HASH_SESSION_KEY, 10 | ) 11 | from django.utils.crypto import constant_time_compare, salted_hmac 12 | 13 | 14 | def get_user(request): 15 | """ 16 | Return the user model instance associated with the given request session. 17 | If no user is retrieved, return an instance of `AnonymousUser`. 18 | """ 19 | from django.contrib.auth.models import AnonymousUser 20 | user = None 21 | try: 22 | user_id = _get_user_session_key(request) 23 | backend_path = request.session[BACKEND_SESSION_KEY] 24 | except KeyError: 25 | pass 26 | else: 27 | if backend_path in settings.AUTHENTICATION_BACKENDS: 28 | backend = load_backend(backend_path) 29 | user = backend.get_user(user_id) 30 | # Verify the session 31 | if hasattr(user, 'get_session_auth_hash'): 32 | session_hash = request.session.get(HASH_SESSION_KEY) 33 | session_hash_verified = ( 34 | session_hash and 35 | constant_time_compare( 36 | session_hash, 37 | user.get_session_auth_hash() 38 | ) 39 | ) 40 | if not session_hash_verified: 41 | session_hash_verified = ( 42 | session_hash and 43 | hasattr(user, '_legacy_get_session_auth_hash') and 44 | constant_time_compare( 45 | session_hash, 46 | user._legacy_get_session_auth_hash(), 47 | ) 48 | ) 49 | if not session_hash_verified and hasattr(settings, 'OLD_SECRET_KEY'): # noqa 50 | key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" # noqa 51 | compare_kwargs = {} 52 | if django.VERSION >= (3, 1): 53 | compare_kwargs['algorithm'] = ( 54 | settings.DEFAULT_HASHING_ALGORITHM 55 | if django.VERSION < (4, 0) 56 | else "sha256" 57 | ) 58 | session_hash_verified = session_hash and constant_time_compare( # noqa 59 | session_hash, 60 | salted_hmac( 61 | key_salt, 62 | user.password, 63 | secret=settings.OLD_SECRET_KEY, 64 | **compare_kwargs 65 | ).hexdigest() 66 | ) 67 | 68 | request.session.cycle_key() 69 | request.session[HASH_SESSION_KEY] = user.get_session_auth_hash() # noqa 70 | 71 | if not session_hash_verified: 72 | request.session.flush() 73 | user = None 74 | 75 | return user or AnonymousUser() 76 | 77 | 78 | def cached_get_user(request): 79 | if not hasattr(request, '_cached_user'): 80 | request._cached_user = get_user(request) 81 | return request._cached_user 82 | 83 | 84 | class RotateAuthenticationMiddleware(MiddlewareMixin): 85 | def process_request(self, request): 86 | assert hasattr(request, 'session'), ( 87 | "The Django authentication middleware requires session middleware " 88 | "to be installed. Edit your MIDDLEWARE%s setting to insert " 89 | "'django.contrib.sessions.middleware.SessionMiddleware' before " 90 | "'rotatesecretkey.middleware.RotateAuthenticationMiddleware'." 91 | ) % ("_CLASSES" if settings.MIDDLEWARE is None else "") 92 | request.user = SimpleLazyObject(lambda: cached_get_user(request)) 93 | -------------------------------------------------------------------------------- /rotatesecretkey/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EralpB/django-rotate-secret-key/0e8dac667a421dddacc019bf5328b5ea67ae08db/rotatesecretkey/migrations/__init__.py -------------------------------------------------------------------------------- /rotatesecretkey/sessions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EralpB/django-rotate-secret-key/0e8dac667a421dddacc019bf5328b5ea67ae08db/rotatesecretkey/sessions/__init__.py -------------------------------------------------------------------------------- /rotatesecretkey/sessions/base.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import django 4 | from django.contrib.sessions.backends.base import SessionBase 5 | from django.conf import settings 6 | from django.core import signing 7 | from django.utils.crypto import salted_hmac 8 | 9 | 10 | class RotateSecretKeyMixIn(SessionBase): 11 | def __init__(self, *args, **kwargs): 12 | self.try_old_key = False 13 | super().__init__(*args, **kwargs) 14 | 15 | def _hash(self, value): 16 | key_salt = "django.contrib.sessions" + self.__class__.__name__ 17 | secret = ( 18 | getattr(settings, 'OLD_SECRET_KEY', None) 19 | if self.try_old_key 20 | else None 21 | ) 22 | # clear the try_old_key bit for future tries 23 | self.try_old_key = False 24 | return salted_hmac(key_salt, value, secret=secret).hexdigest() 25 | 26 | def inner_decode(self, session_data): 27 | if django.VERSION < (3, 0): 28 | # Django 2.2 path. 29 | return super().decode(session_data) 30 | # Supply the old secret key if needed 31 | key = ( 32 | getattr(settings, 'OLD_SECRET_KEY', None) 33 | if self.try_old_key 34 | else None 35 | ) 36 | try: 37 | return signing.loads( 38 | session_data, 39 | key=key, 40 | salt=self.key_salt, 41 | serializer=self.serializer, 42 | ) 43 | # RemovedInDjango40Warning: when the deprecation ends, handle here 44 | # exceptions similar to what _legacy_decode() does now. 45 | except signing.BadSignature: 46 | try: 47 | # Return an empty session if data is not in the pre-Django 3.1 48 | # format. 49 | return self._legacy_decode(session_data) 50 | except Exception: 51 | logger = logging.getLogger( 52 | 'django.security.SuspiciousSession') 53 | logger.warning('Session data corrupted') 54 | return {} 55 | except Exception: 56 | return self._legacy_decode(session_data) 57 | 58 | def decode(self, session_data): 59 | decoded_session = self.inner_decode(session_data) 60 | # new key failed at decoding try once more with old key 61 | if decoded_session == {}: 62 | self.try_old_key = True 63 | decoded_session = self.inner_decode(session_data) 64 | return decoded_session 65 | -------------------------------------------------------------------------------- /rotatesecretkey/sessions/cache.py: -------------------------------------------------------------------------------- 1 | from django.contrib.sessions.backends.cache import ( 2 | SessionStore as BaseSessionStore 3 | ) 4 | from rotatesecretkey.sessions.base import RotateSecretKeyMixIn 5 | 6 | 7 | class SessionStore(RotateSecretKeyMixIn, BaseSessionStore): 8 | pass 9 | -------------------------------------------------------------------------------- /rotatesecretkey/sessions/cache_db.py: -------------------------------------------------------------------------------- 1 | from django.contrib.sessions.backends.cached_db import ( 2 | SessionStore as BaseSessionStore 3 | ) 4 | from rotatesecretkey.sessions.base import RotateSecretKeyMixIn 5 | 6 | 7 | class SessionStore(RotateSecretKeyMixIn, BaseSessionStore): 8 | pass 9 | -------------------------------------------------------------------------------- /rotatesecretkey/sessions/db.py: -------------------------------------------------------------------------------- 1 | from django.contrib.sessions.backends.db import ( 2 | SessionStore as BaseSessionStore 3 | ) 4 | from rotatesecretkey.sessions.base import RotateSecretKeyMixIn 5 | 6 | 7 | class SessionStore(RotateSecretKeyMixIn, BaseSessionStore): 8 | pass 9 | -------------------------------------------------------------------------------- /rotatesecretkey/sessions/file.py: -------------------------------------------------------------------------------- 1 | from django.contrib.sessions.backends.file import ( 2 | SessionStore as BaseSessionStore 3 | ) 4 | from rotatesecretkey.sessions.base import RotateSecretKeyMixIn 5 | 6 | 7 | class SessionStore(RotateSecretKeyMixIn, BaseSessionStore): 8 | pass 9 | -------------------------------------------------------------------------------- /rotatesecretkey/sessions/signed_cookies.py: -------------------------------------------------------------------------------- 1 | import django 2 | from django.conf import settings 3 | from django.contrib.sessions.backends.signed_cookies import ( 4 | SessionStore as BaseSessionStore 5 | ) 6 | from django.core import signing 7 | from rotatesecretkey.sessions.base import RotateSecretKeyMixIn 8 | 9 | 10 | class SessionStore(RotateSecretKeyMixIn, BaseSessionStore): 11 | def load(self): 12 | """ 13 | Load the data from the key itself instead of fetching from some 14 | external data store. Opposite of _get_session_key(), raise 15 | BadSignature if signature fails. 16 | """ 17 | serializer = self.serializer 18 | if django.VERSION > (2, 2): 19 | max_age = settings.SESSION_COOKIE_AGE 20 | else: 21 | max_age = self.get_session_cookie_age() 22 | 23 | def load(key): 24 | return signing.loads( 25 | self.session_key, 26 | key=key, 27 | serializer=serializer, 28 | # This doesn't handle non-default expiry dates, see #19201 29 | max_age=max_age, 30 | salt='django.contrib.sessions.backends.signed_cookies', 31 | ) 32 | try: 33 | return load(key=None) 34 | except Exception: 35 | old_key = getattr(settings, 'OLD_SECRET_KEY', None) 36 | if old_key: 37 | try: 38 | return load(key=old_key) 39 | except Exception: 40 | self.create() 41 | else: 42 | # BadSignature, ValueError, or unpickling exceptions. If any 43 | # of these happen, reset the session. 44 | self.create() 45 | return {} 46 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup, find_packages 3 | 4 | here = os.path.abspath(os.path.dirname(__file__)) 5 | README = open(os.path.join(here, 'README.rst')).read() 6 | 7 | setup( 8 | name='django-rotate-secret-key', 9 | version='0.3', 10 | packages=find_packages(exclude=['tests']), 11 | description='Rotate your Django secret', 12 | long_description=README, 13 | author='Eralp Bayraktar', 14 | author_email='imeralpb@gmail.com', 15 | url='https://github.com/EralpB/django-rotate-secret-key/', 16 | license='MIT', 17 | install_requires=[ 18 | 'Django>=2.2', 19 | ] 20 | ) -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EralpB/django-rotate-secret-key/0e8dac667a421dddacc019bf5328b5ea67ae08db/tests/__init__.py -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | DEBUG = True 2 | 3 | INSTALLED_APPS = ( 4 | 'django.contrib.auth', 5 | 'django.contrib.admin', 6 | 'django.contrib.contenttypes', 7 | 'django.contrib.sessions', 8 | 'django.contrib.messages', 9 | 'rotatesecretkey', 10 | ) 11 | 12 | DATABASES = { 13 | 'default': { 14 | 'ENGINE': 'django.db.backends.sqlite3', 15 | 'NAME': ':memory:', 16 | } 17 | } 18 | 19 | SECRET_KEY = "secret_key_for_testing" 20 | 21 | ROOT_URLCONF = 'tests.urls' 22 | 23 | MIDDLEWARE = [ 24 | 'django.contrib.sessions.middleware.SessionMiddleware', 25 | 'rotatesecretkey.middleware.RotateAuthenticationMiddleware', 26 | 'django.contrib.messages.middleware.MessageMiddleware', 27 | ] 28 | 29 | 30 | TEMPLATES = [ 31 | { 32 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 33 | 'DIRS': [], 34 | 'APP_DIRS': True, # to use admin/login.html 35 | 'OPTIONS': { 36 | 'context_processors': [ 37 | 'django.template.context_processors.debug', 38 | 'django.template.context_processors.request', 39 | 'django.contrib.auth.context_processors.auth', 40 | 'django.contrib.messages.context_processors.messages', 41 | ], 42 | }, 43 | }, 44 | ] 45 | 46 | SESSION_ENGINE = 'rotatesecretkey.sessions.db' 47 | 48 | SILENCED_SYSTEM_CHECKS = ['admin.E408'] 49 | -------------------------------------------------------------------------------- /tests/test_middleware.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase, override_settings 2 | from django.contrib.auth import get_user_model 3 | from django.conf import settings 4 | 5 | 6 | class RotateAuthenticationMiddlewareTestsDB(TestCase): 7 | 8 | def setUp(self): 9 | User = get_user_model() 10 | self.password = '124#12@!' 11 | self.u = User.objects.create_user( 12 | username='asdas', 13 | password=self.password, 14 | ) 15 | 16 | def test_login_required(self): 17 | response = self.client.get('/profile') 18 | # it redirects us to login page 19 | self.assertEqual(response.status_code, 302) 20 | 21 | self.client.post( 22 | '/login', 23 | {'username': self.u.username, 'password': self.password}, 24 | ) 25 | 26 | response = self.client.get('/profile') 27 | self.assertEqual(response.status_code, 200) 28 | # now we are logged in 29 | 30 | def test_session_breaks(self): 31 | self.client.post( 32 | '/login', 33 | {'username': self.u.username, 'password': self.password}, 34 | ) 35 | 36 | with self.settings(SECRET_KEY='newsecretkey'): 37 | response = self.client.get('/profile') 38 | # BROKEN! because secret_key has changed 39 | self.assertNotEqual(response.status_code, 200) 40 | 41 | def test_support_old_key(self): 42 | self.client.post( 43 | '/login', 44 | {'username': self.u.username, 'password': self.password}, 45 | ) 46 | old_key = settings.SECRET_KEY 47 | 48 | with self.settings(SECRET_KEY='newsecretkey', OLD_SECRET_KEY=old_key): 49 | response = self.client.get('/profile') 50 | # Still logged in, thanks to OLD_SECRET_KEY support, even 51 | # after secret key change 52 | self.assertEqual(response.status_code, 200) 53 | self.assertContains(response, self.u.username) 54 | 55 | # Remove support for old key, STILL logged in, and to this 56 | # own account 57 | with self.settings(OLD_SECRET_KEY=None): 58 | response = self.client.get('/profile') 59 | self.assertEqual(response.status_code, 200) 60 | self.assertContains(response, self.u.username) 61 | 62 | 63 | @override_settings(SESSION_ENGINE='rotatesecretkey.sessions.cache') 64 | class RotateAuthenticationMiddlewareTestsCache( 65 | RotateAuthenticationMiddlewareTestsDB 66 | ): 67 | pass 68 | 69 | 70 | @override_settings(SESSION_ENGINE='rotatesecretkey.sessions.cache_db') 71 | class RotateAuthenticationMiddlewareTestsCacheDB( 72 | RotateAuthenticationMiddlewareTestsDB 73 | ): 74 | pass 75 | 76 | 77 | @override_settings(SESSION_ENGINE='rotatesecretkey.sessions.file') 78 | class RotateAuthenticationMiddlewareTestsFile( 79 | RotateAuthenticationMiddlewareTestsDB 80 | ): 81 | pass 82 | 83 | 84 | @override_settings(SESSION_ENGINE='rotatesecretkey.sessions.signed_cookies') 85 | class RotateAuthenticationMiddlewareTestsSignedCookies( 86 | RotateAuthenticationMiddlewareTestsDB 87 | ): 88 | pass 89 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.decorators import login_required 2 | from django.http import HttpResponse 3 | from django.urls import path 4 | from django.contrib.auth import views as auth_views 5 | 6 | from django.contrib import admin 7 | 8 | urlpatterns = [ 9 | path('', lambda request: HttpResponse("Hello World", content_type="text/plain")), 10 | path('login', auth_views.LoginView.as_view(template_name='admin/login.html')), 11 | path('admin/', admin.site.urls), 12 | 13 | path('profile', login_required(lambda request: HttpResponse(request.user.username, content_type="text/plain"))), 14 | ] -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | py{36,37}-dj{22,31,32} 4 | py{38,39}-dj{22,31,32,40} 5 | py310-dj{32,40} 6 | flake8 7 | 8 | [testenv] 9 | deps = 10 | dj22: Django==2.2.* 11 | dj31: Django==3.1.* 12 | dj32: Django>=3.2,<4.0 13 | dj40: Django>=4.0,<4.1 14 | commands = 15 | pip install -e . 16 | django-admin test --settings=tests.settings 17 | --------------------------------------------------------------------------------