forked from mtusi2026/mtusi2026lab7
fix(pki): isolate concurrent atomic operator file writes
This commit is contained in:
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user