from cryptography.fernet import Fernet from resonance_engine.utils.encrypter import ( FernetEncrypter, PlaintextEncrypter, ) class TestFernetEncrypter: def test_encrypt_prefixes_key_id(self) -> None: key = FernetEncrypter.generate_key() key_id = key.get_secret_value().partition(":")[0] encrypter = FernetEncrypter([key]) assert encrypter.encrypt("hello").startswith(f"{key_id}:") def test_encrypt_decrypt_round_trips(self) -> None: key = FernetEncrypter.generate_key() encrypter = FernetEncrypter([key]) assert encrypter.decrypt(encrypter.encrypt("hello world")) == "hello world" def test_active_key_id_is_first_key(self) -> None: key1 = FernetEncrypter.generate_key() key2 = FernetEncrypter.generate_key() encrypter = FernetEncrypter([key1, key2]) assert encrypter.active_key_id == key1.get_secret_value().partition(":")[0] def test_decrypt_ciphertext_from_old_key_after_rotation(self) -> None: key1 = FernetEncrypter.generate_key() key2 = FernetEncrypter.generate_key() ciphertext = FernetEncrypter([key1]).encrypt("secret") assert FernetEncrypter([key2, key1]).decrypt(ciphertext) == "secret" def test_generate_key_has_valid_format(self) -> None: key = FernetEncrypter.generate_key() key_id, _, fernet_key = key.get_secret_value().partition(":") assert len(key_id) == 8 Fernet(fernet_key.encode()) # raises if invalid def test_generate_key_is_unique_each_call(self) -> None: assert ( FernetEncrypter.generate_key().get_secret_value() != FernetEncrypter.generate_key().get_secret_value() ) class TestPlaintextEncrypter: def test_encrypt_returns_input_unchanged(self) -> None: assert PlaintextEncrypter().encrypt("hello") == "hello" def test_decrypt_returns_input_unchanged(self) -> None: assert PlaintextEncrypter().decrypt("hello") == "hello" def test_encrypt_decrypt_round_trips(self) -> None: enc = PlaintextEncrypter() assert enc.decrypt(enc.encrypt("secret")) == "secret"