import os import shutil import unittest from pathlib import Path from tempfile import TemporaryDirectory from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from wallpaper_changer.argument_parser import parse_args from wallpaper_changer.config import Config from wallpaper_changer.encryption_manager import EncryptionManager, FileInfo from wallpaper_changer.image_repository import ImageRepository class EncryptionManagerTests(unittest.TestCase): def parse_args(self, *arguments: str): return parse_args(list(arguments)) def test_encrypt_decrypt_round_trip(self) -> None: """Verify encrypted bytes decrypt to the original content and hash.""" with TemporaryDirectory() as temporary_directory: image_root = Path(temporary_directory) assets = Path(__file__).resolve().parents[1] / "assets" args = self.parse_args("--conf-dir", str(image_root), "--folder", str(image_root / "corrupt"), "--private-key", str(assets / "test_private_key.pem")) config = Config.load(args) shutil.copytree(assets / "corrupt", config.img_dir) image_repository = ImageRepository(config.img_dir) images_enc = image_repository.scan(config.private_key) hash_enc = {image["hash"] for image in images_enc} image_repository.decode_all(config.private_key) images_dec = image_repository.scan(config.private_key, calc_hash=True) hash_dec = {image["hash"] for image in images_dec} image_repository.check_encryption(config.private_key) images_reenc = image_repository.scan(config.private_key) hash_reenc = {image["hash"] for image in images_reenc} self.assertEqual(hash_enc, hash_dec) self.assertEqual(hash_enc, hash_reenc) def test_decrypt_rejects_wrong_passphrase(self) -> None: """Verify decryption fails when given a different passphrase.""" with TemporaryDirectory() as temporary_directory, \ self.assertRaisesRegex(ValueError, "Invalid padding bytes"): assets = Path(__file__).resolve().parents[1] / "assets" shutil.copytree(assets / "corrupt", Path(temporary_directory) / "corrupt") image_root = Path(temporary_directory) / "corrupt" # Generate 4096-bit RSA private key private_key = rsa.generate_private_key( public_exponent=65537, key_size=4096 ) private_key_file = image_root / "private_key.pem" # Save to PEM file with open(private_key_file, "wb") as f: f.write( private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() ) ) ImageRepository(image_root).decode_all(private_key_file) def test_decrypt_rejects_invalid_or_truncated_ciphertext(self) -> None: """Verify malformed headers and incomplete ciphertext are rejected.""" malformed_ciphertexts = ( b"invalid header", b"Salted__12345678", b"Salted__12345678" + b"x" * 15, b"Salted__12345678" + b"x" * 17, ) manager = EncryptionManager() with TemporaryDirectory() as temporary_directory: encrypted_file = Path(temporary_directory) / "malformed.enc" for ciphertext in malformed_ciphertexts: with self.subTest(ciphertext_length=len(ciphertext)): encrypted_file.write_bytes(ciphertext) with self.assertRaisesRegex( ValueError, "Invalid or truncated encrypted file" ): manager.decrypt( encrypted_file, None, "pass:test passphrase" ) def test_passphrase_formats(self) -> None: """Verify byte, literal, and passphrase-file inputs are read correctly.""" with TemporaryDirectory() as temporary_directory: temporary_path = Path(temporary_directory) passphrase_file = temporary_path / "passphrase.txt" passphrase_file.write_bytes(b"test passphrase\r\nignored line") encrypted_file = temporary_path / "encrypted.bin" plaintext = b"passphrase format test" manager = EncryptionManager() manager.encrypt_data(plaintext, encrypted_file, b"test passphrase") for passphrase in ( b"test passphrase", "test passphrase", "pass:test passphrase", passphrase_file, f"file:{passphrase_file}", ): with self.subTest(passphrase=type(passphrase).__name__): decrypted, _ = manager.decrypt(encrypted_file, None, passphrase) self.assertEqual(decrypted, plaintext) def test_naming_table_round_trip_and_malformed_lines(self) -> None: """Verify naming-table entries round-trip and malformed lines are handled.""" with TemporaryDirectory() as temporary_directory: naming_table_path = Path(temporary_directory) / "naming_table.enc" passphrase = "pass:test passphrase" manager = EncryptionManager() naming_table = [ FileInfo("image one.jpg", "00001.jpg_enc", "hash-one"), FileInfo("image-two.jpg", "00002.jpg_enc", "hash-two"), ] manager.store_naming_table(naming_table, naming_table_path, passphrase) self.assertEqual( manager.load_naming_table(naming_table_path, passphrase), naming_table, ) manager.encrypt_data( b"\nmalformed line\nimage.jpg;00003.jpg_enc;hash-three\n", naming_table_path, passphrase, ) self.assertEqual( manager.load_naming_table(naming_table_path, passphrase), [FileInfo("image.jpg", "00003.jpg_enc", "hash-three")], ) def test_load_naming_table_missing_file(self) -> None: """Verify a missing naming table loads as an empty list.""" with TemporaryDirectory() as temporary_directory, \ self.assertRaisesRegex(FileNotFoundError, "No naming table found"): image_root = Path(temporary_directory) assets = Path(__file__).resolve().parents[1] / "assets" args = self.parse_args("--conf-dir", str(image_root), "--folder", str(image_root / "corrupt"), "--private-key", str(assets / "test_private_key.pem")) config = Config.load(args) shutil.copytree(assets / "corrupt", config.img_dir) os.remove(config.img_dir / "naming_table.enc") image_repository = ImageRepository(config.img_dir) image_repository.decode_all(config.private_key) def test_naming_table_file_operations_remove_source_after_success(self) -> None: """Verify file conversion removes its source only after a successful operation.""" with TemporaryDirectory() as temporary_directory: directory = Path(temporary_directory) source_path = directory / "naming_table.dec" encrypted_path = directory / "naming_table.enc" decrypted_path = directory / "decrypted.dec" passphrase = "pass:test passphrase" manager = EncryptionManager() source_content = b"image.jpg;00001.jpg_enc;hash\n" source_path.write_bytes(source_content) manager.encrypt_naming_table_file( source_path, encrypted_path, passphrase ) self.assertFalse(source_path.exists()) self.assertTrue(encrypted_path.exists()) manager.decrypt_naming_table_file( encrypted_path, decrypted_path, passphrase ) self.assertFalse(encrypted_path.exists()) self.assertEqual(decrypted_path.read_bytes(), source_content) invalid_source = directory / "invalid.enc" invalid_destination = directory / "invalid.dec" invalid_source.write_bytes(b"invalid ciphertext") with self.assertRaisesRegex(ValueError, "Invalid or truncated"): manager.decrypt_naming_table_file( invalid_source, invalid_destination, passphrase ) self.assertTrue(invalid_source.exists()) self.assertFalse(invalid_destination.exists()) def test_naming_table_file_operations_reject_same_source_and_destination(self) -> None: """Verify naming-table file conversion rejects identical paths.""" with TemporaryDirectory() as temporary_directory: source_path = Path(temporary_directory) / "naming_table" source_content = b"naming-table content" source_path.write_bytes(source_content) manager = EncryptionManager() with self.assertRaisesRegex(ValueError, "must be different"): manager.encrypt_naming_table_file( source_path, source_path, "pass:test passphrase" ) with self.assertRaisesRegex(ValueError, "must be different"): manager.decrypt_naming_table_file( source_path, source_path, "pass:test passphrase" ) self.assertEqual(source_path.read_bytes(), source_content)