diff --git a/django_email_learning/models.py b/django_email_learning/models.py index c470c14..024fdb9 100644 --- a/django_email_learning/models.py +++ b/django_email_learning/models.py @@ -5,6 +5,7 @@ from django.conf import settings from django.db import models from django.core.validators import MaxValueValidator +from django.core.exceptions import ImproperlyConfigured from cryptography.fernet import Fernet from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import hashes @@ -79,7 +80,13 @@ def _fernet(self) -> Fernet: kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=FIXED_SALT, iterations=100000 ) - key = base64.urlsafe_b64encode(kdf.derive(settings.SECRET_KEY.encode())) + try: + secret = settings.DJANGO_EMAIL_LEARNING["ENCRYPTION_SECRET_KEY"] + except (AttributeError, KeyError): + raise ImproperlyConfigured( + "DJANGO_EMAIL_LEARNING['ENCRYPTION_SECRET_KEY'] must be set in settings.py" + ) + key = base64.urlsafe_b64encode(kdf.derive(secret.encode())) return Fernet(key) def _encrypt_password(self, password: str) -> str: diff --git a/django_service/settings.py b/django_service/settings.py index 15c644d..817f8a4 100644 --- a/django_service/settings.py +++ b/django_service/settings.py @@ -98,6 +98,10 @@ } } +DJANGO_EMAIL_LEARNING = { + "ENCRYPTION_SECRET_KEY": "your-very-secure-and-random-key", +} + LOGGING = { "version": 1, "disable_existing_loggers": False, diff --git a/tests/test_models/test_imap_connection.py b/tests/test_models/test_imap_connection.py index e17ea78..42250f8 100644 --- a/tests/test_models/test_imap_connection.py +++ b/tests/test_models/test_imap_connection.py @@ -1,4 +1,5 @@ from django_email_learning.models import ImapConnection +from django.core.exceptions import ImproperlyConfigured import pytest @@ -39,3 +40,29 @@ def test_imap_invalid_server_validation(invalid_server, imap_connection): def test_imap_valid_server_validation(valid_server, imap_connection): imap_connection.server = valid_server imap_connection.full_clean() # Should not raise + + +def test_raise_improperly_configured_if_django_email_learning_config_missing( + settings, db +): + delattr(settings, "DJANGO_EMAIL_LEARNING") + with pytest.raises(ImproperlyConfigured): + ImapConnection.objects.create( + server="imap.example.com", + port=993, + email="user@example.com", + password="my_secret_password", + organization_id=1, + ) + + +def test_raise_improperly_configured_if_encryption_key_missing(settings, db): + settings.DJANGO_EMAIL_LEARNING = {} + with pytest.raises(ImproperlyConfigured): + ImapConnection.objects.create( + server="imap.example.com", + port=993, + email="user@example.com", + password="my_secret_password", + organization_id=1, + )