Skip to content

Commit

Permalink
Avoid TOCTOU errors in cache initialization (#10884)
Browse files Browse the repository at this point in the history
## Summary

I believe this should close
#10880? The `.gitignore`
creation seems ok, since it truncates, but using `cachedir::is_tagged`
followed by `cachedir::add_tag` is not safe, as `cachedir::add_tag`
_fails_ if the file already exists.

This also matches the structure of the code in `uv`.

Closes #10880.
  • Loading branch information
charliermarsh committed Apr 11, 2024
1 parent 4e8a846 commit 0cc154c
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions crates/ruff/src/cache.rs
Expand Up @@ -375,15 +375,17 @@ pub(crate) fn init(path: &Path) -> Result<()> {
fs::create_dir_all(path.join(VERSION))?;

// Add the CACHEDIR.TAG.
if !cachedir::is_tagged(path)? {
cachedir::add_tag(path)?;
}
cachedir::ensure_tag(path)?;

// Add the .gitignore.
let gitignore_path = path.join(".gitignore");
if !gitignore_path.exists() {
let mut file = fs::File::create(gitignore_path)?;
file.write_all(b"# Automatically created by ruff.\n*\n")?;
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path.join(".gitignore"))
{
Ok(mut file) => file.write_all(b"# Automatically created by ruff.\n*\n")?,
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
Err(err) => return Err(err.into()),
}

Ok(())
Expand Down

0 comments on commit 0cc154c

Please sign in to comment.