Merge pull request 'fix(crypto): catch ValueError on malformed Fernet key, raise EncryptionError (BIT-33940)' (#12) from fix/BIT-33940-fernet-key-validation into main
ci / verify (push) Successful in 32s

This commit was merged in pull request #12.
This commit is contained in:
spark committed 2026-12-04 10:32:08 +00:00
commit 948b6ba2c6
2 files changed
+52

No files matched your search

+5
View File
@@ -13,7 +13,12 @@ def get_fernet() -> Fernet:
key = get_settings().encryption_key.strip()
if not key:
raise EncryptionError("ENCRYPTION_KEY is not configured")
try:
return Fernet(key.encode() if isinstance(key, str) else key)
except ValueError as exc:
raise EncryptionError(
"ENCRYPTION_KEY must be 32 url-safe base64-encoded bytes"
) from exc
def encrypt_password(plain: str) -> str:
+47
View File
@@ -0,0 +1,47 @@
"""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"