ci / verify (pull_request) Successful in 50s
get_fernet() let Fernet() raise a raw ValueError when ENCRYPTION_KEY was malformed (e.g. the 'change_me_fernet_key' placeholder shipped in .env.example), crashing the WebDAV sync loop with a cryptic 'Fernet key must be 32 url-safe base64-encoded bytes.' message. Guard the Fernet() construction so an invalid key raises EncryptionError with actionable guidance pointing at Fernet.generate_key(). Also blank the invalid placeholder in .env.example so it cannot be copied verbatim into production. Paperclip-Issue: BIT-33939
52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
"""Fernet key validation tests."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
from cryptography.fernet import Fernet
|
|
|
|
from forwarder.crypto import EncryptionError, decrypt_password, get_fernet
|
|
|
|
|
|
def _settings_with_key(key: str):
|
|
settings = MagicMock()
|
|
settings.encryption_key = key
|
|
return settings
|
|
|
|
|
|
def test_get_fernet_raises_encryption_error_when_missing():
|
|
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key(" ")):
|
|
with pytest.raises(EncryptionError, match="not configured"):
|
|
get_fernet()
|
|
|
|
|
|
def test_get_fernet_raises_encryption_error_for_invalid_key():
|
|
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key("change_me_fernet_key")):
|
|
with pytest.raises(EncryptionError, match="valid Fernet key"):
|
|
get_fernet()
|
|
|
|
|
|
def test_get_fernet_does_not_leak_value_error_for_invalid_key():
|
|
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key("change_me_fernet_key")):
|
|
try:
|
|
get_fernet()
|
|
except ValueError as exc:
|
|
pytest.fail(f"raw ValueError leaked instead of EncryptionError: {exc}")
|
|
except EncryptionError:
|
|
pass
|
|
|
|
|
|
def test_get_fernet_accepts_generated_key():
|
|
valid = Fernet.generate_key().decode()
|
|
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key(valid)):
|
|
f = get_fernet()
|
|
assert isinstance(f, Fernet)
|
|
|
|
|
|
def test_decrypt_password_raises_encryption_error_for_invalid_key():
|
|
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key("not-a-fernet-key")):
|
|
with pytest.raises(EncryptionError, match="valid Fernet key"):
|
|
decrypt_password("some-token")
|