Skip to content

fix: don't leak or mask errors when rewrite cleanup fails on Windows - #686

Open
MohammedAlkindi wants to merge 1 commit into
theskumar:mainfrom
MohammedAlkindi:fix/rewrite-temp-file-cleanup
Open

fix: don't leak or mask errors when rewrite cleanup fails on Windows#686
MohammedAlkindi wants to merge 1 commit into
theskumar:mainfrom
MohammedAlkindi:fix/rewrite-temp-file-cleanup

Conversation

@MohammedAlkindi

Copy link
Copy Markdown

When set_key or unset_key fails after rewrite() has restored the original file mode, the temporary file has already been chmoded to that mode. On Windows a mode without the owner-write bit sets the read-only attribute, so the os.unlink in the cleanup path fails too. The .tmp_* file is left next to the user's .env, and the cleanup error replaces the real one in the traceback.

A read-only .env is the easiest way in:

import os, stat
from dotenv import set_key

open(".env", "w").write("A=1\n")
os.chmod(".env", stat.S_IREAD)
set_key(".env", "B", "2")

Before, on Windows, that raises from pathlib's os.unlink and the message names only a temp file the caller has never heard of, with .tmp_* left behind. After, it raises from os.replace with both paths in the message and nothing is left behind.

This keeps the existing behaviour that set_key on a read-only file raises PermissionError (test_set_key_permission_error covers it). That test was passing for the wrong reason on Windows: it caught the cleanup's error, not the one from os.replace. I have not tried to make the write succeed by clearing the read-only attribute, which seems like a separate call and against the intent of the mode-preservation work in 790c5c0.

Two tests: one asserts no temp file survives the failure, one mocks os.replace and Path.unlink to assert a cleanup failure cannot stand in for the original error. The second is platform-independent; the first bites on Windows, where CI covers 3.10 and 3.14.

Found while looking into #554. That report cites the old shutil.move call, which 790c5c0 already replaced with os.replace, and I could not reproduce its symptom on a native Windows host. This is a different bug in the same function.

When set_key or unset_key fails after rewrite() has restored the original
file mode, the temporary file has already been chmod'ed to that mode. On
Windows a mode without the owner-write bit sets the read-only attribute,
so the os.unlink in the cleanup path fails too. The temporary file is left
next to the .env file and the cleanup error replaces the real one in the
traceback.

Reset the mode and retry before giving up, and never let a cleanup failure
propagate in place of the error that caused the rewrite to be abandoned.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant