Add atomic write utility and tests

This commit is contained in:
thePR0M3TH3AN
2025-08-03 08:57:04 -04:00
parent 2294656f36
commit 032caed3d0
8 changed files with 123 additions and 24 deletions

View File

@@ -37,6 +37,7 @@ from .entry_types import EntryType
from .totp import TotpManager
from utils.fingerprint import generate_fingerprint
from utils.checksum import canonical_json_dumps
from utils.atomic_write import atomic_write
from utils.key_validation import (
validate_totp_secret,
validate_ssh_key_pair,
@@ -1312,8 +1313,7 @@ class EntryManager:
# The checksum file path already includes the fingerprint directory
checksum_path = self.checksum_file
with open(checksum_path, "w") as f:
f.write(checksum)
atomic_write(checksum_path, lambda f: f.write(checksum))
logger.debug(f"Checksum updated and written to '{checksum_path}'.")
print(colored(f"[+] Checksum updated successfully.", "green"))

View File

@@ -66,6 +66,7 @@ from utils.terminal_utils import (
clear_header_with_notification,
)
from utils.fingerprint import generate_fingerprint
from utils.atomic_write import atomic_write
from constants import MIN_HEALTHY_RELAYS
from .migrations import LATEST_VERSION
@@ -4377,8 +4378,11 @@ class PasswordManager:
else:
# Fallback to legacy file method if config_manager unavailable
hashed_password_file = self.fingerprint_dir / "hashed_password.enc"
with open(hashed_password_file, "wb") as f:
f.write(hashed.encode())
atomic_write(
hashed_password_file,
lambda f: f.write(hashed.encode()),
mode="wb",
)
os.chmod(hashed_password_file, 0o600)
logging.info("User password hashed and stored successfully.")
except AttributeError:
@@ -4389,8 +4393,11 @@ class PasswordManager:
self.config_manager.set_password_hash(hashed)
else:
hashed_password_file = self.fingerprint_dir / "hashed_password.enc"
with open(hashed_password_file, "wb") as f:
f.write(hashed.encode())
atomic_write(
hashed_password_file,
lambda f: f.write(hashed.encode()),
mode="wb",
)
os.chmod(hashed_password_file, 0o600)
logging.info(
"User password hashed and stored successfully (using alternative method)."