fix(pki): isolate concurrent atomic operator file writes

This commit is contained in:
2026-11-22 18:39:23 +03:00
parent 10b280a787
commit 37d40e4789
6 changed files with 422 additions and 8 deletions
+4 -5
View File
@@ -64,18 +64,17 @@ ROLES = {
def write_private(path, content, *, mode=0o600):
path.parent.mkdir(parents=True, exist_ok=True)
raw = content.encode() if isinstance(content, str) else content
temporary = path.with_name(path.name + ".new")
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
temporary = path.with_name(path.name + "." + secrets.token_hex(8) + ".new")
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
try:
os.fchmod(fd, mode)
with os.fdopen(fd, "wb") as stream:
stream.write(raw)
stream.flush()
os.fsync(stream.fileno())
except BaseException:
temporary.replace(path)
finally:
temporary.unlink(missing_ok=True)
raise
temporary.replace(path)
def key_bytes(key):