Answer#
A temporary file with a predictable name in a shared folder (/tmp/myapp.tmp) is an old attack: another local user creates that name first, as a link to a file they want you to overwrite. The tempfile crate avoids it by creating the file with a random name and failing if the name already exists.
The same crate solves a second problem: crashes during writes. Write the new content to a temporary file in the same directory as the target (a rename across volumes is not atomic), then persist it over the target.
[dependencies]
tempfile = "3"use std::fs::OpenOptions;
use std::io::Write;
use tempfile::NamedTempFile;
fn main() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let target = dir.path().join("settings.json");
// Write the whole file under a random name, then move it into place in one step.
let mut tmp = NamedTempFile::new_in(dir.path())?;
tmp.write_all(b"{\"v\":1}")?;
tmp.persist(&target).map_err(|e| e.error)?;
println!("settings.json holds {} bytes", std::fs::metadata(&target)?.len());
// create_new fails if the path already exists, so an existing file or link is never reused.
let again = OpenOptions::new().write(true).create_new(true).open(&target);
println!("second create_new: {:?}", again.map(|_| ()).map_err(|e| e.kind()));
Ok(())
}settings.json holds 7 bytes
second create_new: Err(AlreadyExists)create_new(true) is the standard-library way to say "create this file, and fail if anything is already there", which also refuses to follow a link that was put in place beforehand.
How to do it#
- Use
NamedTempFile::new_in(dir)for files that are renamed into place, andtempfile::tempfile()for scratch data with no name. - Write, flush, and only then
persist. - Keep the directory private to the service account.
- Use
create_newwhenever "this file must not exist yet" is part of the logic.
Common mistakes#
- Building a name from the process ID or the time.
- Using
fs::writedirectly on a configuration file and losing it when the power fails halfway. - Persisting into a different file system than the temporary file lives on.
Related questions#
Is persist atomic on Windows?#
The crate documents the behaviour of each platform; read its notes for the version you use before relying on atomic replacement.
What is the difference between tempfile() and NamedTempFile?#
tempfile() returns an unnamed file that disappears when closed. NamedTempFile has a path, which you need if you want to rename it into place.
Sources#
tempfiledocumentation: https://docs.rs/tempfile/3.27.0/tempfile/- Standard library,
OpenOptions::create_new: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.create_new