diff --git a/src/seedpass/core/encryption.py b/src/seedpass/core/encryption.py index eddfd2b..251addd 100644 --- a/src/seedpass/core/encryption.py +++ b/src/seedpass/core/encryption.py @@ -427,7 +427,22 @@ class EncryptionManager: fh.seek(0) encrypted_bytes = fh.read() checksum = hashlib.sha256(encrypted_bytes).hexdigest() - checksum_file = file_path.parent / f"{file_path.stem}_checksum.txt" + + # Build checksum path by stripping both `.json` and `.enc` + checksum_base = file_path.with_suffix("").with_suffix("") + checksum_file = checksum_base.parent / f"{checksum_base.name}_checksum.txt" + + # Remove legacy checksum file if present + legacy_checksum = file_path.parent / f"{file_path.stem}_checksum.txt" + if legacy_checksum != checksum_file and legacy_checksum.exists(): + try: + legacy_checksum.unlink() + except Exception: + logger.warning( + f"Could not remove legacy checksum file '{legacy_checksum}'", + exc_info=True, + ) + with exclusive_lock(checksum_file) as fh: fh.seek(0) fh.truncate() diff --git a/src/tests/test_encryption_checksum.py b/src/tests/test_encryption_checksum.py index c95f82d..82b2dc4 100644 --- a/src/tests/test_encryption_checksum.py +++ b/src/tests/test_encryption_checksum.py @@ -1,5 +1,6 @@ import re import sys +import hashlib from pathlib import Path from tempfile import TemporaryDirectory @@ -23,7 +24,7 @@ def test_encryption_checksum_workflow(): manager.update_checksum() enc_file = tmp_path / "seedpass_entries_db.json.enc" - chk_file = tmp_path / "seedpass_entries_db.json_checksum.txt" + chk_file = tmp_path / "seedpass_entries_db_checksum.txt" checksum = chk_file.read_text().strip() assert re.fullmatch(r"[0-9a-f]{64}", checksum) @@ -33,3 +34,24 @@ def test_encryption_checksum_workflow(): manager.update_checksum() assert verify_and_update_checksum(str(enc_file), str(chk_file)) + + +def test_update_checksum_removes_legacy(tmp_path): + key = base64.urlsafe_b64encode(os.urandom(32)) + manager = EncryptionManager(key, tmp_path) + + manager.save_json_data({"value": 1}) + + legacy = tmp_path / "seedpass_entries_db.json_checksum.txt" + legacy.write_text("legacy") + + manager.update_checksum() + + enc_file = tmp_path / "seedpass_entries_db.json.enc" + new_chk = tmp_path / "seedpass_entries_db_checksum.txt" + + assert new_chk.exists() + assert not legacy.exists() + + expected = hashlib.sha256(enc_file.read_bytes()).hexdigest() + assert new_chk.read_text() == expected