Skip to main content

agent_first_data/
atomic_file.rs

1//! One atomic file installation, shared by every writer in this crate.
2//!
3//! Installing a file so that a crash can never expose a half-written one is a
4//! fixed sequence — private same-directory temporary file, write, permissions,
5//! fsync the file, atomically install it over the target, fsync the directory
6//! entry — and each step has a way to be got subtly wrong. Writing that
7//! sequence a second time somewhere else is how one copy ends up durable and
8//! the other only looks it: a `rename` that is never followed by a parent
9//! directory fsync returns success while the new directory entry may still be
10//! lost to a power cut.
11//!
12//! So the sequence lives here once, and callers bring only what is genuinely
13//! theirs: the pre-write guard (what may be overwritten is a policy question,
14//! and different writers answer it differently) and the error type. Failures
15//! name the step that failed through [`AtomicError`], whose `Display` is the
16//! tail of a caller's own message — `write: ` + `install \`p\`: …`.
17
18use std::fs::{self, File, OpenOptions};
19use std::io::Write as _;
20use std::path::{Path, PathBuf};
21
22/// Atomically replace a regular file, preserving its permissions. On Unix a
23/// new file starts owner-only (`0600`); Windows has no mode bits, so a new file
24/// takes the directory's inherited ACL. Symbolic links and special files are refused; parent
25/// directories must already exist. A directory-sync error reports an uncertain
26/// durable commit through [`AtomicError::commit_uncertain`].
27///
28/// This is the default form of [`AtomicWrite`]; use that for explicit
29/// permission bits or a write that refuses an existing target.
30///
31/// Hard links are not checked. The new file is renamed over the path, so a
32/// target with other hard links is split from them: this path gets the new
33/// bytes and every other link keeps the old file. A caller that needs a
34/// hard-linked target refused writes through
35/// [`DocumentFile`](crate::document::DocumentFile) instead, whose
36/// [`ensure_mutable`](crate::document::DocumentFile::ensure_mutable) guard (run
37/// by `save` and by a replacing `create_atomic`) refuses one on Unix.
38pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), AtomicError> {
39    AtomicWrite::new(bytes).write(path)
40}
41
42pub(crate) fn validate_unix_mode(mode: Option<u32>) -> std::io::Result<()> {
43    if let Some(mode) = mode
44        && mode & !0o777 != 0
45    {
46        return Err(std::io::Error::new(
47            std::io::ErrorKind::InvalidInput,
48            format!("unix mode {mode:o} contains bits outside 0o777"),
49        ));
50    }
51    Ok(())
52}
53
54/// How the finished temporary file becomes the target.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56enum InstallMode {
57    /// `rename` over the target. Replaces whatever is at the path — including a
58    /// symbolic link, which is replaced rather than followed.
59    Replace,
60    /// `hard_link`, which refuses to install over an existing target. The
61    /// caller distinguishes that refusal by [`AtomicError::target_exists`].
62    NewOnly,
63}
64
65/// One atomic file write and its options: [`write_atomic`] is the default form.
66///
67/// ```no_run
68/// # use agent_first_data::AtomicWrite;
69/// # use std::path::Path;
70/// # fn demo() -> Result<(), agent_first_data::AtomicError> {
71/// let secret = AtomicWrite::new(b"token_secret = \"...\"\n");
72/// #[cfg(unix)]
73/// let secret = secret.mode(0o600);
74/// match secret.new_only().write(Path::new("credentials.toml")) {
75///     Err(error) if error.target_exists() => { /* keep the file that is there */ }
76///     other => other?,
77/// }
78/// # Ok(()) }
79/// ```
80///
81/// By default the write replaces a regular file and keeps that file's own
82/// permissions; a new file starts owner-only on Unix. The options:
83///
84/// - [`mode`](Self::mode) sets explicit permission bits on the new file, over
85///   either default. Unix only: Windows has no mode bits, so the method does
86///   not exist there and a caller that needs one writes the `cfg(unix)` itself
87///   rather than have the request silently ignored. A new Windows file takes
88///   the directory's inherited ACL.
89/// - [`new_only`](Self::new_only) refuses an existing target of any kind. The
90///   target is never touched; the refusal is
91///   [`AtomicError::target_exists`].
92///
93/// Every form keeps the full sequence: private same-directory temporary file,
94/// write, permissions, file fsync, atomic install, directory fsync.
95#[derive(Debug, Clone)]
96pub struct AtomicWrite<'a> {
97    bytes: &'a [u8],
98    install_mode: InstallMode,
99    unix_mode: Option<u32>,
100    /// `Some` when the caller has already inspected the target under its own
101    /// policy and hands over the metadata to keep; `None` lets
102    /// [`write`](Self::write) inspect it.
103    caller_guarded: Option<Option<fs::Metadata>>,
104}
105
106impl<'a> AtomicWrite<'a> {
107    /// A write of the complete new contents with the default behavior.
108    pub fn new(bytes: &'a [u8]) -> Self {
109        Self {
110            bytes,
111            install_mode: InstallMode::Replace,
112            unix_mode: None,
113            caller_guarded: None,
114        }
115    }
116
117    /// Give the new file these permission bits (`0o600`), overriding both the
118    /// replaced file's permissions and the owner-only default. Unix only.
119    #[cfg(unix)]
120    #[must_use]
121    pub fn mode(mut self, bits: u32) -> Self {
122        self.unix_mode = Some(bits);
123        self
124    }
125
126    /// Refuse an existing target instead of replacing it. The refusal is
127    /// reported by [`AtomicError::target_exists`], including when the name is
128    /// taken between the check and the install.
129    #[must_use]
130    pub fn new_only(mut self) -> Self {
131        self.install_mode = InstallMode::NewOnly;
132        self
133    }
134
135    /// Write `self` to `path`. Every failure before the install leaves the
136    /// original untouched and removes the temporary file. A failure at the
137    /// final parent directory fsync — the one [`AtomicError::commit_uncertain`]
138    /// reports — means the new file may already be in place without confirmed
139    /// durability.
140    pub fn write(self, path: &Path) -> Result<(), AtomicError> {
141        self.write_with(path, |file, bytes| file.write_all(bytes))
142    }
143
144    /// Crate-internal: set unix bits without the `cfg(unix)` the public
145    /// [`mode`](Self::mode) carries; ignored where the platform has none.
146    pub(crate) fn with_unix_mode(mut self, unix_mode: Option<u32>) -> Self {
147        self.unix_mode = unix_mode;
148        self
149    }
150
151    /// Crate-internal: the caller already guarded the target under its own
152    /// policy (what may be overwritten differs between writers) and supplies
153    /// its metadata for ownership and permission preservation.
154    pub(crate) fn with_target_metadata(mut self, metadata: Option<fs::Metadata>) -> Self {
155        self.caller_guarded = Some(metadata);
156        self
157    }
158
159    fn write_with(
160        mut self,
161        path: &Path,
162        write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
163    ) -> Result<(), AtomicError> {
164        validate_unix_mode(self.unix_mode)
165            .map_err(|error| AtomicError::at(AtomicStep::Guard, path, error))?;
166        if let Some(metadata) = self.caller_guarded.take() {
167            return install_with_writer(path, &self, metadata, write);
168        }
169        // A new-only write never looks at the target: whatever is there, even a
170        // symlink or directory, is "exists" and is refused by the install.
171        let metadata = if self.install_mode == InstallMode::NewOnly {
172            None
173        } else {
174            match fs::symlink_metadata(path) {
175                Ok(metadata) if metadata.file_type().is_file() => Some(metadata),
176                Ok(_) => {
177                    return Err(AtomicError::at(
178                        AtomicStep::Guard,
179                        path,
180                        std::io::Error::new(
181                            std::io::ErrorKind::InvalidInput,
182                            "atomic target must be a regular file, not a symlink, directory, or special file",
183                        ),
184                    ));
185                }
186                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
187                Err(error) => return Err(AtomicError::at(AtomicStep::Guard, path, error)),
188            }
189        };
190        install_with_writer(path, &self, metadata, write)
191    }
192}
193
194/// The step of an atomic installation that failed.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum AtomicStep {
197    /// Inspecting the target without following links.
198    Guard,
199    /// The target has no parent directory to write the temporary file into.
200    NoParent,
201    /// The target's own file name is not valid UTF-8.
202    NonUtf8Name,
203    /// Creating the private temporary file.
204    Temp,
205    /// Every candidate temporary name was taken.
206    TempExhausted,
207    /// Writing the new bytes.
208    Write,
209    /// Re-applying the replaced file's permissions.
210    PreservePermissions,
211    /// Re-applying the replaced file's Unix owner and group: a group the mode
212    /// grants access to must be kept, an owner only where the process may.
213    #[cfg(unix)]
214    PreserveOwnership,
215    /// Applying explicitly requested permission bits. Unix only, because the
216    /// bits themselves are: the step does not exist on a platform that has no
217    /// mode to set, and a variant no code can construct is a step a reader
218    /// would look for and never find.
219    #[cfg(unix)]
220    SetPermissions,
221    /// Flushing the temporary file to storage.
222    Sync,
223    /// Installing the temporary file over the target.
224    Install,
225    /// Recording the new directory entry.
226    SyncParent,
227}
228
229/// A failed atomic installation: which step, which path, and the OS error.
230#[derive(Debug)]
231pub struct AtomicError {
232    /// The step that failed.
233    pub step: AtomicStep,
234    /// The path that step was about — the target, its temporary file, or the
235    /// parent directory, depending on the step.
236    pub path: PathBuf,
237    /// The underlying OS error, absent only where the step had none.
238    pub source: Option<std::io::Error>,
239}
240
241impl AtomicError {
242    fn at(step: AtomicStep, path: &Path, source: std::io::Error) -> Self {
243        Self {
244            step,
245            path: path.to_path_buf(),
246            source: Some(source),
247        }
248    }
249
250    /// Whether this is a [`new_only`](AtomicWrite::new_only) write refusing an
251    /// existing target, which is a caller-visible outcome rather than an I/O
252    /// fault. The target was not touched. Never true for a replacing write.
253    pub fn target_exists(&self) -> bool {
254        self.step == AtomicStep::Install
255            && self
256                .source
257                .as_ref()
258                .is_some_and(|error| error.kind() == std::io::ErrorKind::AlreadyExists)
259    }
260
261    /// Whether the target may already carry the new bytes.
262    ///
263    /// Only the final directory fsync can fail after the installation itself
264    /// succeeded: the file is complete and in place, but its survival across a
265    /// crash is unconfirmed. Every other step fails before the install and
266    /// leaves the original untouched.
267    pub fn commit_uncertain(&self) -> bool {
268        self.step == AtomicStep::SyncParent
269    }
270}
271
272impl std::fmt::Display for AtomicError {
273    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        let path = self.path.display();
275        let phrase = match self.step {
276            AtomicStep::Guard => "inspect",
277            AtomicStep::NoParent => {
278                return write!(formatter, "has no parent directory for `{path}`");
279            }
280            AtomicStep::NonUtf8Name => {
281                return write!(formatter, "path is not valid UTF-8: `{path}`");
282            }
283            AtomicStep::TempExhausted => {
284                return write!(formatter, "could not allocate temporary file in `{path}`");
285            }
286            AtomicStep::Temp => "temporary file in",
287            AtomicStep::Write => "write",
288            #[cfg(unix)]
289            AtomicStep::PreserveOwnership => "preserve owner and group of",
290            AtomicStep::PreservePermissions => "preserve permissions",
291            #[cfg(unix)]
292            AtomicStep::SetPermissions => "set permissions on",
293            AtomicStep::Sync => "fsync",
294            AtomicStep::Install => "install",
295            AtomicStep::SyncParent => "fsync parent directory",
296        };
297        write!(formatter, "{phrase} `{path}`")?;
298        match &self.source {
299            Some(source) => write!(formatter, ": {source}"),
300            None => Ok(()),
301        }
302    }
303}
304
305/// The smallest `NAME_MAX` across the platforms this runs on.
306const MAX_NAME_BYTES: usize = 255;
307
308/// Compose a temporary file name that stays within one path component's limit.
309///
310/// The marker, pid, and attempt add about 35 bytes. A target whose own name is
311/// close to `NAME_MAX` would push the composed name past it, and the failure
312/// would surface at install time — after the caller had already done its work,
313/// on a file it opened successfully. Truncating the stem keeps the write
314/// possible; uniqueness still comes from the pid and attempt, with `create_new`
315/// retrying the rare collision.
316fn temp_file_name(file_name: &str, pid: u32, attempt: u32) -> String {
317    let suffix = format!(".afdata.{pid}.{attempt}.tmp");
318    // One byte for the leading dot that hides the temporary file.
319    let budget = MAX_NAME_BYTES.saturating_sub(suffix.len() + 1);
320    let stem = &file_name[..file_name.floor_char_boundary(budget)];
321    format!(".{stem}{suffix}")
322}
323
324/// Split a target into the directory the temporary file must share with it and
325/// the target's own name. Sharing the directory is what makes the final install
326/// a rename within one filesystem, which is the atomic operation this relies on.
327fn parent_and_name(path: &Path) -> Result<(&Path, String), AtomicError> {
328    let parent = match path.parent() {
329        Some(parent) if parent.as_os_str().is_empty() => Path::new("."),
330        Some(parent) => parent,
331        None => {
332            return Err(AtomicError {
333                step: AtomicStep::NoParent,
334                path: path.to_path_buf(),
335                source: None,
336            });
337        }
338    };
339    let file_name = path
340        .file_name()
341        .and_then(|name| name.to_str())
342        .ok_or_else(|| AtomicError {
343            step: AtomicStep::NonUtf8Name,
344            path: path.to_path_buf(),
345            source: None,
346        })?
347        .to_string();
348    Ok((parent, file_name))
349}
350
351fn allocate_private_temp(parent: &Path, file_name: &str) -> Result<(PathBuf, File), AtomicError> {
352    let pid = std::process::id();
353    for attempt in 0..32_u32 {
354        let candidate = parent.join(temp_file_name(file_name, pid, attempt));
355        let mut options = OpenOptions::new();
356        options.write(true).create_new(true);
357        #[cfg(unix)]
358        {
359            use std::os::unix::fs::OpenOptionsExt as _;
360            // Nothing may read the new contents through the temporary name
361            // before the caller's own permissions are applied below.
362            options.mode(0o600);
363        }
364        match options.open(&candidate) {
365            Ok(file) => return Ok((candidate, file)),
366            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
367            Err(error) => return Err(AtomicError::at(AtomicStep::Temp, parent, error)),
368        }
369    }
370    Err(AtomicError {
371        step: AtomicStep::TempExhausted,
372        path: parent.to_path_buf(),
373        source: None,
374    })
375}
376
377#[cfg(unix)]
378fn sync_parent(parent: &Path) -> Result<(), AtomicError> {
379    File::open(parent)
380        .and_then(|directory| directory.sync_all())
381        .map_err(|error| AtomicError::at(AtomicStep::SyncParent, parent, error))
382}
383
384#[cfg(not(unix))]
385fn sync_parent(_parent: &Path) -> Result<(), AtomicError> {
386    // Rust does not expose a portable directory handle on non-unix targets.
387    // The file itself is still synced before its atomic installation.
388    Ok(())
389}
390
391/// Give the temporary file the replaced file's owner and group, as far as that
392/// keeps access where it was.
393///
394/// The owner is restored when the process may; a writer that is not the owner
395/// cannot give a file away, and becoming its owner widens nothing, because the
396/// owner bits then apply to the one who could already write it. The group is
397/// different: installed under another group, the group bits would hand this
398/// content to that group. So a group that cannot be restored refuses the write,
399/// unless the final `mode` grants the group nothing.
400#[cfg(unix)]
401fn preserve_ownership(file: &File, target: &fs::Metadata, mode: u32) -> std::io::Result<()> {
402    use std::os::unix::fs::{MetadataExt as _, fchown};
403    let current = file.metadata()?;
404    let uid = (current.uid() != target.uid()).then_some(target.uid());
405    let gid = (current.gid() != target.gid()).then_some(target.gid());
406    if uid.is_none() && gid.is_none() {
407        return Ok(());
408    }
409    let denied = |error: &std::io::Error| error.kind() == std::io::ErrorKind::PermissionDenied;
410    let result = match fchown(file, uid, gid) {
411        Err(error) if uid.is_some() && gid.is_some() && denied(&error) => fchown(file, None, gid),
412        Err(error) if uid.is_some() && gid.is_none() && denied(&error) => Ok(()),
413        other => other,
414    };
415    match result {
416        Err(error) if mode & 0o070 == 0 && denied(&error) => Ok(()),
417        other => other,
418    }
419}
420
421fn write_temp(
422    mut temp_file: File,
423    temp_path: &Path,
424    target: &Path,
425    request: &AtomicWrite<'_>,
426    metadata: Option<fs::Metadata>,
427    write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
428) -> Result<(), AtomicError> {
429    write(&mut temp_file, request.bytes)
430        .map_err(|error| AtomicError::at(AtomicStep::Write, target, error))?;
431    if let Some(metadata) = metadata {
432        #[cfg(unix)]
433        {
434            use std::os::unix::fs::PermissionsExt as _;
435            let mode = request
436                .unix_mode
437                .unwrap_or_else(|| metadata.permissions().mode());
438            preserve_ownership(&temp_file, &metadata, mode)
439                .map_err(|error| AtomicError::at(AtomicStep::PreserveOwnership, target, error))?;
440        }
441        if request.unix_mode.is_none() {
442            temp_file
443                .set_permissions(metadata.permissions())
444                .map_err(|error| AtomicError::at(AtomicStep::PreservePermissions, target, error))?;
445        }
446    }
447    #[cfg(unix)]
448    if let Some(unix_mode) = request.unix_mode {
449        use std::os::unix::fs::PermissionsExt as _;
450        temp_file
451            .set_permissions(fs::Permissions::from_mode(unix_mode))
452            .map_err(|error| AtomicError::at(AtomicStep::SetPermissions, target, error))?;
453    }
454    temp_file
455        .sync_all()
456        .map_err(|error| AtomicError::at(AtomicStep::Sync, temp_path, error))
457}
458
459/// Install `request` at `path` atomically, with the caller's own guard already
460/// decided: `metadata` belongs to the replaced file.
461///
462// The writer seam keeps disk-full, short-write, and interrupted-process
463// regressions at the primitive that owns publication, without exposing a
464// callback or partial-file API to callers.
465fn install_with_writer(
466    path: &Path,
467    request: &AtomicWrite<'_>,
468    metadata: Option<fs::Metadata>,
469    write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
470) -> Result<(), AtomicError> {
471    let (parent, file_name) = parent_and_name(path)?;
472    let (temp_path, temp_file) = allocate_private_temp(parent, &file_name)?;
473    let result = (|| -> Result<(), AtomicError> {
474        write_temp(temp_file, &temp_path, path, request, metadata, write)?;
475        match request.install_mode {
476            InstallMode::Replace => {
477                fs::rename(&temp_path, path)
478                    .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
479            }
480            InstallMode::NewOnly => {
481                fs::hard_link(&temp_path, path)
482                    .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
483                // The file is installed from here on. Failing to unlink the
484                // temporary link leaves a stray file, but reporting an error
485                // would tell the caller the commit did not happen — and a retry
486                // would then refuse a target that this call in fact created.
487                let _ = fs::remove_file(&temp_path);
488            }
489        }
490        sync_parent(parent)?;
491        Ok(())
492    })();
493    if let Err(error) = &result {
494        // A parent-directory fsync failure comes after the install, where the
495        // temporary name no longer refers to anything to clean up.
496        if !error.commit_uncertain() {
497            let _ = fs::remove_file(&temp_path);
498        }
499    }
500    result
501}
502
503impl std::error::Error for AtomicError {
504    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
505        self.source.as_ref().map(|error| error as _)
506    }
507}
508
509#[cfg(test)]
510mod tests {
511    #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
512    use super::*;
513
514    #[test]
515    fn temp_name_stays_within_one_path_component() {
516        let long = "x".repeat(400);
517        let name = temp_file_name(&long, 1234, 0);
518        assert!(name.len() <= MAX_NAME_BYTES, "{} bytes", name.len());
519        assert!(name.starts_with('.'));
520        assert!(name.ends_with(".tmp"));
521    }
522
523    #[test]
524    fn temp_name_truncates_on_a_character_boundary() {
525        let long = "é".repeat(300);
526        let name = temp_file_name(&long, 1234, 0);
527        assert!(name.is_char_boundary(name.len()));
528        assert!(name.len() <= MAX_NAME_BYTES);
529    }
530
531    #[test]
532    fn bare_relative_paths_use_the_current_directory() {
533        let (parent, file_name) = parent_and_name(Path::new("config.json")).unwrap();
534
535        assert_eq!(parent, Path::new("."));
536        assert_eq!(file_name, "config.json");
537    }
538
539    #[test]
540    fn replace_installs_new_bytes_and_leaves_no_temporary_file() {
541        let dir = tempfile::tempdir().unwrap();
542        let path = dir.path().join("config.json");
543        fs::write(&path, b"old").unwrap();
544
545        AtomicWrite::new(b"new").write(&path).unwrap();
546
547        assert_eq!(fs::read(&path).unwrap(), b"new");
548        let strays: Vec<_> = fs::read_dir(dir.path())
549            .unwrap()
550            .filter_map(Result::ok)
551            .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp"))
552            .collect();
553        assert!(strays.is_empty(), "temporary files left behind");
554    }
555
556    #[test]
557    fn new_only_refuses_an_existing_target_without_touching_it() {
558        let dir = tempfile::tempdir().unwrap();
559        let path = dir.path().join("config.json");
560        fs::write(&path, b"original").unwrap();
561
562        let error = AtomicWrite::new(b"new")
563            .new_only()
564            .write(&path)
565            .unwrap_err();
566
567        assert!(error.target_exists());
568        assert_eq!(fs::read(&path).unwrap(), b"original");
569    }
570
571    #[cfg(unix)]
572    #[test]
573    fn replace_swaps_a_symlink_rather_than_following_it() {
574        use std::os::unix::fs::symlink;
575
576        let dir = tempfile::tempdir().unwrap();
577        let outside = dir.path().join("outside.txt");
578        fs::write(&outside, b"untouched").unwrap();
579        let link = dir.path().join("link.txt");
580        symlink(&outside, &link).unwrap();
581
582        AtomicWrite::new(b"new")
583            .with_target_metadata(None)
584            .write(&link)
585            .unwrap();
586
587        assert_eq!(fs::read(&outside).unwrap(), b"untouched");
588        assert!(
589            !fs::symlink_metadata(&link)
590                .unwrap()
591                .file_type()
592                .is_symlink()
593        );
594        assert_eq!(fs::read(&link).unwrap(), b"new");
595    }
596
597    #[cfg(unix)]
598    #[test]
599    fn explicit_unix_mode_wins_over_the_private_temporary_mode() {
600        use std::os::unix::fs::PermissionsExt as _;
601
602        let dir = tempfile::tempdir().unwrap();
603        let path = dir.path().join("readable.md");
604
605        AtomicWrite::new(b"body").mode(0o644).write(&path).unwrap();
606
607        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
608        assert_eq!(mode, 0o644);
609    }
610
611    #[test]
612    fn a_missing_parent_directory_fails_before_any_write() {
613        let dir = tempfile::tempdir().unwrap();
614        let path = dir.path().join("absent").join("config.json");
615
616        let error = AtomicWrite::new(b"new").write(&path).unwrap_err();
617
618        assert_eq!(error.step, AtomicStep::Temp);
619        assert!(!error.commit_uncertain());
620        assert!(!path.exists());
621    }
622    #[test]
623    fn failed_writes_preserve_previous_bytes_and_remove_temporary_file() {
624        let dir = tempfile::tempdir().unwrap();
625        let path = dir.path().join("state.json");
626        fs::write(&path, b"old complete value").unwrap();
627        for error in [
628            std::io::Error::from_raw_os_error(28),
629            std::io::Error::from(std::io::ErrorKind::Interrupted),
630            std::io::Error::from(std::io::ErrorKind::WriteZero),
631        ] {
632            let error = AtomicWrite::new(b"new")
633                .write_with(&path, |file, _| {
634                    file.write_all(b"partial")?;
635                    Err(error)
636                })
637                .unwrap_err();
638            assert_eq!(error.step, AtomicStep::Write);
639            assert!(!error.commit_uncertain());
640            assert_eq!(fs::read(&path).unwrap(), b"old complete value");
641            assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
642        }
643    }
644
645    /// Metadata of a file whose owner and group this process cannot take on,
646    /// or `None` on a runner privileged enough to apply them.
647    #[cfg(unix)]
648    fn foreign_ownership(probe: &Path) -> Option<fs::Metadata> {
649        use std::os::unix::fs::MetadataExt as _;
650        let foreign = fs::metadata("/").unwrap();
651        if fs::metadata(probe).unwrap().uid() == foreign.uid()
652            || std::os::unix::fs::chown(probe, None, Some(foreign.gid())).is_ok()
653        {
654            return None;
655        }
656        Some(foreign)
657    }
658
659    #[cfg(unix)]
660    #[test]
661    fn refused_ownership_change_does_not_install_the_temporary_file() {
662        let dir = tempfile::tempdir().unwrap();
663        let path = dir.path().join("state.json");
664        fs::write(&path, b"old complete value").unwrap();
665        let Some(foreign) = foreign_ownership(&path) else {
666            return;
667        };
668        // `/` grants its group access, so a group this process cannot keep
669        // would hand the new contents to a different group.
670        let error = AtomicWrite::new(b"new complete value")
671            .with_target_metadata(Some(foreign))
672            .write(&path)
673            .unwrap_err();
674        assert_eq!(error.step, AtomicStep::PreserveOwnership);
675        assert!(!error.commit_uncertain());
676        assert_eq!(fs::read(&path).unwrap(), b"old complete value");
677        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
678    }
679
680    #[cfg(unix)]
681    #[test]
682    fn unkeepable_ownership_is_accepted_when_the_mode_grants_the_group_nothing() {
683        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
684
685        let dir = tempfile::tempdir().unwrap();
686        let path = dir.path().join("state.json");
687        fs::write(&path, b"old complete value").unwrap();
688        let Some(foreign) = foreign_ownership(&path) else {
689            return;
690        };
691        let before = fs::metadata(&path).unwrap();
692        AtomicWrite::new(b"new complete value")
693            .with_target_metadata(Some(foreign))
694            .mode(0o600)
695            .write(&path)
696            .unwrap();
697        let after = fs::metadata(&path).unwrap();
698        assert_eq!(fs::read(&path).unwrap(), b"new complete value");
699        assert_eq!((after.uid(), after.gid()), (before.uid(), before.gid()));
700        assert_eq!(after.permissions().mode() & 0o777, 0o600);
701    }
702
703    #[test]
704    fn write_all_retries_short_writes_and_interruptions_before_publish() {
705        struct ShortWriter<'a> {
706            file: &'a mut File,
707            interrupted: bool,
708        }
709        impl std::io::Write for ShortWriter<'_> {
710            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
711                if !self.interrupted {
712                    self.interrupted = true;
713                    return Err(std::io::ErrorKind::Interrupted.into());
714                }
715                self.file.write(&bytes[..bytes.len().min(2)])
716            }
717            fn flush(&mut self) -> std::io::Result<()> {
718                self.file.flush()
719            }
720        }
721        let dir = tempfile::tempdir().unwrap();
722        let path = dir.path().join("state.json");
723        let bytes = b"new complete value";
724        AtomicWrite::new(bytes)
725            .write_with(&path, |file, bytes| {
726                ShortWriter {
727                    file,
728                    interrupted: false,
729                }
730                .write_all(bytes)
731            })
732            .unwrap();
733        assert_eq!(fs::read(&path).unwrap(), bytes);
734    }
735
736    #[test]
737    fn interrupted_process_leaves_uncommitted_temporary_file_not_target() {
738        const CHILD_PATH: &str = "AFDATA_TEST_INTERRUPTED_ATOMIC_PATH";
739        if let Some(path) = std::env::var_os(CHILD_PATH) {
740            let _ = AtomicWrite::new(b"new").write_with(Path::new(&path), |file, _| {
741                file.write_all(b"partial")?;
742                file.sync_all()?;
743                std::process::exit(86);
744            });
745            panic!("child did not reach the interrupted write");
746        }
747        let dir = tempfile::tempdir().unwrap();
748        let path = dir.path().join("state.json");
749        write_atomic(&path, b"old complete value").unwrap();
750        let status = std::process::Command::new(std::env::current_exe().unwrap())
751            .args(["--exact", "atomic_file::tests::interrupted_process_leaves_uncommitted_temporary_file_not_target"])
752            .env(CHILD_PATH, &path).status().unwrap();
753        assert_eq!(status.code(), Some(86));
754        assert_eq!(fs::read(&path).unwrap(), b"old complete value");
755        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2);
756        write_atomic(&path, b"new complete value").unwrap();
757        assert_eq!(fs::read(&path).unwrap(), b"new complete value");
758    }
759
760    #[cfg(unix)]
761    #[test]
762    fn public_write_refuses_a_symlink_target() {
763        let dir = tempfile::tempdir().unwrap();
764        let outside = dir.path().join("outside");
765        fs::write(&outside, b"untouched").unwrap();
766        let link = dir.path().join("link");
767        std::os::unix::fs::symlink(&outside, &link).unwrap();
768        let error = AtomicWrite::new(b"x").write(&link).unwrap_err();
769        assert_eq!(error.step, AtomicStep::Guard);
770        assert_eq!(fs::read(&outside).unwrap(), b"untouched");
771    }
772
773    #[cfg(unix)]
774    fn mode_of(path: &Path) -> u32 {
775        use std::os::unix::fs::PermissionsExt as _;
776        fs::metadata(path).unwrap().permissions().mode() & 0o777
777    }
778
779    #[cfg(unix)]
780    #[test]
781    fn mode_applies_to_a_new_file_and_overrides_an_existing_one() {
782        let dir = tempfile::tempdir().unwrap();
783        let fresh = dir.path().join("fresh");
784        AtomicWrite::new(b"x").mode(0o640).write(&fresh).unwrap();
785        assert_eq!(mode_of(&fresh), 0o640);
786
787        let existing = dir.path().join("existing");
788        write_atomic(&existing, b"old").unwrap();
789        AtomicWrite::new(b"new")
790            .mode(0o604)
791            .write(&existing)
792            .unwrap();
793        assert_eq!(mode_of(&existing), 0o604);
794        assert_eq!(fs::read(&existing).unwrap(), b"new");
795    }
796
797    #[cfg(unix)]
798    #[test]
799    fn default_write_keeps_existing_mode_and_starts_new_files_private() {
800        use std::os::unix::fs::PermissionsExt as _;
801        let dir = tempfile::tempdir().unwrap();
802        let existing = dir.path().join("existing");
803        fs::write(&existing, b"old").unwrap();
804        fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap();
805        write_atomic(&existing, b"new").unwrap();
806        assert_eq!(mode_of(&existing), 0o644);
807
808        let fresh = dir.path().join("fresh");
809        write_atomic(&fresh, b"x").unwrap();
810        assert_eq!(mode_of(&fresh), 0o600);
811    }
812
813    #[test]
814    fn new_only_creates_an_absent_target_and_leaves_no_temporary_file() {
815        let dir = tempfile::tempdir().unwrap();
816        let path = dir.path().join("fresh.json");
817        AtomicWrite::new(b"created")
818            .new_only()
819            .write(&path)
820            .unwrap();
821        assert_eq!(fs::read(&path).unwrap(), b"created");
822        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
823    }
824
825    #[test]
826    fn public_new_only_refuses_an_existing_target_byte_identical() {
827        let dir = tempfile::tempdir().unwrap();
828        let path = dir.path().join("keep.json");
829        fs::write(&path, b"original").unwrap();
830        let error = AtomicWrite::new(b"other")
831            .new_only()
832            .write(&path)
833            .unwrap_err();
834        assert!(error.target_exists());
835        assert!(!error.commit_uncertain());
836        assert_eq!(fs::read(&path).unwrap(), b"original");
837        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
838    }
839}