Files
forwarder/tests/test_crypto.py
T
Xika 969dbe08ce
ci / verify (pull_request) Successful in 49s
fix(crypto): catch ValueError on malformed Fernet key, raise EncryptionError (BIT-33940)
get_fernet() only checked for an empty ENCRYPTION_KEY. A non-empty but
malformed key (not 32 url-safe base64 bytes) let Fernet() raise a raw
ValueError that crashed sync_account. Wrap the constructor and re-raise
as EncryptionError with a clear message.

Paperclip-BIT-33940
2026-12-04 10:18:29 +00:00

48 lines
1.6 KiB
Python

"""Crypto / Fernet key tests."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from cryptography.fernet import Fernet
from forwarder.crypto import EncryptionError, decrypt_password, encrypt_password, get_fernet
def _make_settings(key: str):
fake = type("FakeSettings", (), {"encryption_key": key})()
return fake
def test_get_fernet_with_valid_key():
key = Fernet.generate_key().decode()
with patch("forwarder.crypto.get_settings", return_value=_make_settings(key)):
f = get_fernet()
assert isinstance(f, Fernet)
def test_get_fernet_empty_key_raises_encryption_error():
with patch("forwarder.crypto.get_settings", return_value=_make_settings("")):
with pytest.raises(EncryptionError, match="not configured"):
get_fernet()
def test_get_fernet_invalid_key_raises_encryption_error():
with patch("forwarder.crypto.get_settings", return_value=_make_settings("not-a-valid-fernet-key")):
with pytest.raises(EncryptionError, match="32 url-safe base64"):
get_fernet()
def test_decrypt_password_with_invalid_key_raises_encryption_error():
with patch("forwarder.crypto.get_settings", return_value=_make_settings("bad-key")):
with pytest.raises(EncryptionError, match="32 url-safe base64"):
decrypt_password("some-token")
def test_encrypt_then_decrypt_roundtrip():
key = Fernet.generate_key().decode()
with patch("forwarder.crypto.get_settings", return_value=_make_settings(key)):
token = encrypt_password("secret123")
assert decrypt_password(token) == "secret123"