Files
Server-scripts/wallpaper_changer/python/tests/unit/test_encryption_manager.py
T

221 lines
10 KiB
Python
Raw Normal View History

2026-11-15 20:07:46 +01:00
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)
2026-11-20 09:35:08 +01:00
assets = Path(__file__).resolve().parents[3] / "test" / "assets"
2026-11-15 20:07:46 +01:00
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"):
2026-11-20 09:35:08 +01:00
assets = Path(__file__).resolve().parents[3] / "test" / "assets"
2026-11-15 20:07:46 +01:00
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."""
2026-11-16 19:43:45 +01:00
malformed_ciphertexts = (
b"invalid header",
b"Salted__12345678",
b"Salted__12345678" + b"x" * 15,
b"Salted__12345678" + b"x" * 17,
)
manager = EncryptionManager()
2026-11-15 20:07:46 +01:00
2026-11-16 19:43:45 +01:00
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"
)
2026-11-15 20:07:46 +01:00
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_pem_private_key_uses_complete_file_contents(self) -> None:
"""Verify PEM keys are not reduced to their generic header line."""
with TemporaryDirectory() as temporary_directory:
private_key_file = Path(temporary_directory) / "private_key.pem"
pem_contents = (
b"-----BEGIN RSA PRIVATE KEY-----\n"
b"private-key-bytes\n"
b"-----END RSA PRIVATE KEY-----\n"
)
private_key_file.write_bytes(pem_contents)
self.assertEqual(
EncryptionManager._read_passphrase(private_key_file),
pem_contents,
)
2026-11-15 20:07:46 +01:00
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)
2026-11-20 09:35:08 +01:00
assets = Path(__file__).resolve().parents[3] / "test" / "assets"
2026-11-15 20:07:46 +01:00
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)