Skip to main content

jubarte_edit/
publication.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Stage complete bytes before replacing outputs. A set has one commit per
6//! file; errors name any files already committed. No rollback or delete-old
7//! fallback is attempted. Native host filesystems only.
8
9use std::io;
10use std::path::{Path, PathBuf};
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13enum Phase {
14    Write,
15    Flush,
16    Sync,
17    Validate,
18    Commit,
19    SyncParent,
20}
21
22trait Backend {
23    type Staged;
24    fn stage(&mut self, path: &Path) -> io::Result<Self::Staged>;
25    /// Whether `a` and `b` were staged in one directory, as the filesystem
26    /// resolved each parent (symlinks, `..`, the output root), not as spelled.
27    fn same_parent(&mut self, a: &Self::Staged, b: &Self::Staged) -> io::Result<bool>;
28    /// Record `staged`'s name among the names claimed in `holder`'s directory
29    /// (one parent); `true` when the volume already holds an equivalent name.
30    fn claim_name(&mut self, holder: &Self::Staged, staged: &Self::Staged) -> io::Result<bool>;
31    fn step(&mut self, staged: &mut Self::Staged, phase: Phase, bytes: &[u8]) -> io::Result<()>;
32    fn cleanup(&mut self, staged: &mut Self::Staged) -> io::Result<()>;
33}
34
35/// A successful publication, including any staging cleanup warnings.
36#[derive(Debug, Default)]
37pub struct PublishReport {
38    /// Cleanup failures do not undo installed output.
39    pub warnings: Vec<String>,
40}
41
42/// A publication failure, including output that has already become visible.
43#[derive(Debug)]
44pub struct PublishError {
45    /// Files committed before the error. An empty list means nothing published.
46    pub committed: Vec<PathBuf>,
47    /// True when a committed file's parent could not acknowledge durability.
48    pub durability_uncertain: bool,
49    /// The operation's I/O error.
50    pub source: io::Error,
51    /// Staging cleanup failures, separate from the original publication error.
52    pub warnings: Vec<String>,
53}
54
55impl std::fmt::Display for PublishError {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        write!(
58            f,
59            "{}; committed outputs: {:?}{}",
60            self.source,
61            self.committed,
62            if self.durability_uncertain {
63                "; durability uncertain"
64            } else {
65                ""
66            }
67        )
68    }
69}
70impl std::error::Error for PublishError {
71    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
72        Some(&self.source)
73    }
74}
75
76fn finish(
77    result: Result<(), PublishError>,
78    warnings: Vec<String>,
79) -> Result<PublishReport, PublishError> {
80    match result {
81        Ok(()) => Ok(PublishReport { warnings }),
82        Err(mut error) => {
83            error.warnings = warnings;
84            Err(error)
85        }
86    }
87}
88
89fn transaction<B: Backend>(
90    backend: &mut B,
91    files: &[(PathBuf, &[u8])],
92) -> Result<PublishReport, PublishError> {
93    let mut staged: Vec<(PathBuf, B::Staged)> = Vec::with_capacity(files.len());
94    let mut committed = Vec::new();
95    let failure = |source: io::Error, path: &Path, committed: &[PathBuf], durability_uncertain| {
96        PublishError {
97            source: io::Error::new(
98                source.kind(),
99                format!("writing {}: {source}", path.display()),
100            ),
101            committed: committed.to_vec(),
102            durability_uncertain,
103            warnings: vec![],
104        }
105    };
106    let result = (|| {
107        // One staged file per distinct parent directory holds the names
108        // claimed there: a destination is the parent the filesystem resolved
109        // plus a name the volume treats as equal (case, normalization).
110        let mut holders: Vec<usize> = Vec::new();
111        for (path, bytes) in files {
112            let held = backend
113                .stage(path)
114                .map_err(|e| failure(e, path, &committed, false))?;
115            // Retain every staged file, including the one whose next step fails,
116            // until the explicit cleanup below has reported its outcome.
117            staged.push((path.clone(), held));
118            let index = staged.len() - 1;
119            let mut holder = None;
120            for &candidate in &holders {
121                if backend
122                    .same_parent(&staged[candidate].1, &staged[index].1)
123                    .map_err(|e| failure(e, path, &committed, false))?
124                {
125                    holder = Some(candidate);
126                    break;
127                }
128            }
129            let holder = holder.unwrap_or_else(|| {
130                holders.push(index);
131                index
132            });
133            if backend
134                .claim_name(&staged[holder].1, &staged[index].1)
135                .map_err(|e| failure(e, path, &committed, false))?
136            {
137                return Err(failure(
138                    io::Error::new(io::ErrorKind::InvalidInput, "duplicate output path"),
139                    path,
140                    &committed,
141                    false,
142                ));
143            }
144            let (_, held) = staged.last_mut().expect("just staged");
145            for phase in [Phase::Write, Phase::Flush, Phase::Sync, Phase::Validate] {
146                backend
147                    .step(held, phase, bytes)
148                    .map_err(|e| failure(e, path, &committed, false))?;
149            }
150        }
151        for (path, held) in &mut staged {
152            backend
153                .step(held, Phase::Commit, &[])
154                .map_err(|e| failure(e, path, &committed, false))?;
155            committed.push(path.clone());
156            backend
157                .step(held, Phase::SyncParent, &[])
158                .map_err(|e| failure(e, path, &committed, true))?;
159        }
160        Ok(())
161    })();
162    let warnings = staged
163        .iter_mut()
164        .filter_map(|(path, held)| {
165            backend
166                .cleanup(held)
167                .err()
168                .map(|error| format!("cleaning staging for {}: {error}", path.display()))
169        })
170        .collect();
171    finish(result, warnings)
172}
173
174/// A caller-granted directory held open across all operations. Relative path
175/// resolution cannot follow a symlink outside this capability, even if a
176/// pathname checked earlier is concurrently replaced.
177pub struct OutputRoot {
178    dir: cap_std::fs::Dir,
179}
180
181impl OutputRoot {
182    /// Grant access to an existing trusted directory once, before serving callers.
183    pub fn open(root: &Path) -> io::Result<Self> {
184        Ok(Self {
185            dir: cap_std::fs::Dir::open_ambient_dir(root, cap_std::ambient_authority())?,
186        })
187    }
188
189    /// Read a confined file without reopening the root by pathname.
190    pub fn read(&self, relative: &Path) -> io::Result<Vec<u8>> {
191        // Input names are literal local names. The directory capability itself
192        // confines resolution; export portability rules apply only to writes.
193        self.dir.read(relative)
194    }
195
196    /// Stage and verify every file before committing any. Replacement is atomic
197    /// per file, not across the set. Existing outputs survive all staging errors.
198    ///
199    /// # Errors
200    /// Rejects nonportable paths, escaping symlinks, output symlinks and conflicts.
201    /// A commit or durability error reports the files already committed.
202    /// Cleanup failures are returned as warnings on either outcome.
203    pub fn publish(
204        &self,
205        files: &[(PathBuf, &[u8])],
206        overwrite: bool,
207    ) -> Result<PublishReport, PublishError> {
208        // Validate all names before even creating output directories.
209        for (path, _) in files {
210            validate_relative(path).map_err(|source| PublishError {
211                committed: vec![],
212                durability_uncertain: false,
213                warnings: vec![],
214                source,
215            })?;
216        }
217        transaction(
218            &mut FsBackend {
219                root: Some(&self.dir),
220                overwrite,
221                #[cfg(test)]
222                fail: None,
223                #[cfg(test)]
224                fail_cleanup: false,
225            },
226            files,
227        )
228    }
229}
230
231/// Publish explicitly authorized local paths. Each file's parent is opened
232/// once and held through staging, replacement and directory sync. Unlike
233/// [`OutputRoot`], this API grants ambient local access (the CLI policy).
234/// Replacing a symlink replaces the link itself, never its referent.
235///
236/// # Errors
237/// See [`PublishError`]; no fallback removes an old destination.
238/// Cleanup failures are returned as warnings, including after successful installation.
239pub fn publish_paths(
240    files: &[(PathBuf, &[u8])],
241    overwrite: bool,
242) -> Result<PublishReport, PublishError> {
243    transaction(
244        &mut FsBackend {
245            root: None,
246            overwrite,
247            #[cfg(test)]
248            fail: None,
249            #[cfg(test)]
250            fail_cleanup: false,
251        },
252        files,
253    )
254}
255
256fn validate_relative(path: &Path) -> io::Result<()> {
257    let bad = || {
258        io::Error::new(
259            io::ErrorKind::InvalidInput,
260            format!("unsafe export path: {}", path.display()),
261        )
262    };
263    let text = path.to_str().ok_or_else(bad)?;
264    if text.is_empty() {
265        return Err(bad());
266    }
267    for part in text.split('/') {
268        if part.is_empty()
269            || part == "."
270            || part == ".."
271            || part.len() > 255
272            || part.ends_with(['.', ' '])
273            || part.chars().any(|c| {
274                c.is_control()
275                    || matches!(
276                        c,
277                        '\\' | ':' | '%' | '<' | '>' | '"' | '|' | '?' | '*'
278                            | '\u{061c}' | '\u{200e}' | '\u{200f}'
279                            | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
280                            | '\u{feff}'
281                    )
282            })
283        {
284            return Err(bad());
285        }
286        let stem = part.split('.').next().unwrap_or("").to_ascii_uppercase();
287        if matches!(
288            stem.as_str(),
289            "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
290        ) || ["COM", "LPT"].iter().any(|prefix| {
291            stem.strip_prefix(prefix).is_some_and(|n| {
292                matches!(
293                    n,
294                    "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
295                )
296            })
297        }) {
298            return Err(bad());
299        }
300    }
301    Ok(())
302}
303
304struct FsBackend<'a> {
305    root: Option<&'a cap_std::fs::Dir>,
306    overwrite: bool,
307    #[cfg(test)]
308    fail: Option<Phase>,
309    #[cfg(test)]
310    fail_cleanup: bool,
311}
312/// Verified bytes held in private staging beside an authorized local output.
313/// Dropping an uncommitted file removes its staging directory best effort.
314pub struct StagedFile {
315    path: PathBuf,
316    parent: cap_std::fs::Dir,
317    scratch: Option<cap_std::fs::Dir>,
318    scratch_name: Option<String>,
319    file: Option<cap_std::fs::File>,
320    target: std::ffi::OsString,
321    overwrite: bool,
322    #[cfg(test)]
323    fail_cleanup: bool,
324}
325impl StagedFile {
326    /// Write, flush, sync and verify bytes without changing the destination.
327    pub fn prepare(path: &Path, bytes: &[u8], overwrite: bool) -> io::Result<Self> {
328        let mut backend = FsBackend {
329            root: None,
330            overwrite,
331            #[cfg(test)]
332            fail: None,
333            #[cfg(test)]
334            fail_cleanup: false,
335        };
336        let mut staged = backend.stage(path)?;
337        for phase in [Phase::Write, Phase::Flush, Phase::Sync, Phase::Validate] {
338            backend.step(&mut staged, phase, bytes)?;
339        }
340        Ok(staged)
341    }
342
343    /// Install the verified bytes, then acknowledge parent-directory durability.
344    /// A durability error names the output that has already committed.
345    pub fn commit(mut self) -> Result<PublishReport, PublishError> {
346        let mut backend = FsBackend {
347            root: None,
348            overwrite: self.overwrite,
349            #[cfg(test)]
350            fail: None,
351            #[cfg(test)]
352            fail_cleanup: false,
353        };
354        let result = (|| {
355            backend
356                .step(&mut self, Phase::Commit, &[])
357                .map_err(|source| PublishError {
358                    committed: vec![],
359                    durability_uncertain: false,
360                    source,
361                    warnings: vec![],
362                })?;
363            backend
364                .step(&mut self, Phase::SyncParent, &[])
365                .map_err(|source| PublishError {
366                    committed: vec![self.path.clone()],
367                    durability_uncertain: true,
368                    source,
369                    warnings: vec![],
370                })
371        })();
372        let warnings = self
373            .cleanup()
374            .err()
375            .map(|error| format!("cleaning staging for {}: {error}", self.path.display()))
376            .into_iter()
377            .collect();
378        finish(result, warnings)
379    }
380
381    /// Remove staging after closing all of its handles. Safe to call again.
382    /// A swapped symlink is refused; its referent must never be traversed.
383    fn cleanup(&mut self) -> io::Result<()> {
384        drop(self.file.take());
385        // cap-std directory handles deny FILE_SHARE_DELETE on Windows. Even
386        // a clone passed to remove_open_dir_all leaves the original blocking it.
387        drop(self.scratch.take());
388        let Some(name) = self.scratch_name.as_ref() else {
389            return Ok(());
390        };
391        #[cfg(test)]
392        if self.fail_cleanup {
393            return Err(io::Error::other("injected cleanup"));
394        }
395        match self.parent.symlink_metadata(name) {
396            Ok(metadata) if metadata.is_symlink() => {
397                return Err(io::Error::new(
398                    io::ErrorKind::PermissionDenied,
399                    "refusing staging cleanup through a symlink",
400                ));
401            }
402            Err(error) if error.kind() == io::ErrorKind::NotFound => {
403                self.scratch_name = None;
404                return Ok(());
405            }
406            Err(error) => return Err(error),
407            Ok(_) => (),
408        }
409        self.parent.remove_dir_all(name)?;
410        self.scratch_name = None;
411        Ok(())
412    }
413}
414
415/// Windows directory handles are read-only, but `FlushFileBuffers` needs
416/// `GENERIC_WRITE`. NTFS journals metadata; directory sync is a no-op there.
417/// Reopening the parent for writing by path would break root confinement (D35).
418fn sync_directory_for_platform(
419    windows: bool,
420    sync: impl FnOnce() -> io::Result<()>,
421) -> io::Result<()> {
422    if windows { Ok(()) } else { sync() }
423}
424
425/// cap-std opens directories `O_PATH` on Linux, and `fsync` on an `O_PATH`
426/// descriptor is EBADF (#1351). Opening `.` through the handle gives a
427/// readable descriptor without walking a path, so confinement holds (D35).
428fn sync_directory_handle(dir: &cap_std::fs::Dir) -> io::Result<()> {
429    sync_directory_for_platform(cfg!(windows), || {
430        dir.open_with(".", cap_std::fs::OpenOptions::new().read(true))?
431            .into_std()
432            .sync_all()
433    })
434}
435
436/// Acknowledge directory durability using a held directory handle (no-op on Windows).
437pub fn sync_directory(path: &Path) -> io::Result<()> {
438    let dir = cap_std::fs::Dir::open_ambient_dir(path, cap_std::ambient_authority())?;
439    sync_directory_handle(&dir)
440}
441
442impl Drop for StagedFile {
443    fn drop(&mut self) {
444        let _ = self.cleanup();
445    }
446}
447
448/// Attributes that belong to the destination and must move onto the staged
449/// inode. A kernel security label stays behind: the kernel applies it, and
450/// refusing the replacement because that label cannot be reset would fail
451/// an ordinary publish.
452#[cfg(unix)]
453fn copy_replaced_xattrs(from: &cap_std::fs::File, to: &cap_std::fs::File) -> io::Result<()> {
454    use std::os::unix::io::{AsRawFd, RawFd};
455    use xattr::FileExt;
456
457    struct Handle<'a>(&'a cap_std::fs::File);
458
459    impl AsRawFd for Handle<'_> {
460        fn as_raw_fd(&self) -> RawFd {
461            self.0.as_raw_fd()
462        }
463    }
464
465    impl xattr::FileExt for Handle<'_> {}
466
467    let from = Handle(from);
468    let to = Handle(to);
469    let names = match from.list_xattr() {
470        Ok(names) => names,
471        Err(error) if error.kind() == io::ErrorKind::Unsupported => return Ok(()),
472        Err(error) => return Err(error),
473    };
474    for name in names {
475        if !replaced_xattr(&name) {
476            continue;
477        }
478        if let Some(value) = from.get_xattr(&name)? {
479            to.set_xattr(&name, &value)?;
480        }
481    }
482    Ok(())
483}
484
485#[cfg(all(unix, target_os = "linux"))]
486fn replaced_xattr(name: &std::ffi::OsStr) -> bool {
487    let bytes = name.as_encoded_bytes();
488    bytes.starts_with(b"user.") || bytes.starts_with(b"system.posix_acl_")
489}
490
491#[cfg(all(unix, not(target_os = "linux")))]
492fn replaced_xattr(name: &std::ffi::OsStr) -> bool {
493    let bytes = name.as_encoded_bytes();
494    !bytes.starts_with(b"system.") && !macos_kernel_label(bytes)
495}
496
497/// A label the macOS kernel owns: userspace gets EPERM writing
498/// `com.apple.rootless` or a `com.apple.system.` name, and the kernel sets
499/// `com.apple.provenance` and `com.apple.macl` on the new inode itself.
500#[cfg(all(unix, not(target_os = "linux")))]
501fn macos_kernel_label(name: &[u8]) -> bool {
502    name.starts_with(b"com.apple.system.")
503        || matches!(
504            name,
505            b"com.apple.rootless" | b"com.apple.provenance" | b"com.apple.macl"
506        )
507}
508
509impl Backend for FsBackend<'_> {
510    type Staged = StagedFile;
511    fn stage(&mut self, path: &Path) -> io::Result<StagedFile> {
512        use cap_std::fs::{Dir, DirBuilder, OpenOptions};
513        let parent = path
514            .parent()
515            .filter(|p| !p.as_os_str().is_empty())
516            .unwrap_or(Path::new("."));
517        let target = path
518            .file_name()
519            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "output has no filename"))?
520            .to_os_string();
521        let parent = if let Some(root) = self.root {
522            let mut dir = root.try_clone()?;
523            for component in parent.components() {
524                if let std::path::Component::Normal(name) = component {
525                    match dir.create_dir(name) {
526                        Ok(()) => sync_directory_handle(&dir)?,
527                        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => (),
528                        Err(e) => return Err(e),
529                    }
530                    dir = dir.open_dir(name)?;
531                }
532            }
533            dir
534        } else {
535            Dir::open_ambient_dir(parent, cap_std::ambient_authority())?
536        };
537        let mut permissions = None;
538        match parent.symlink_metadata(&target) {
539            Ok(metadata) => {
540                if !self.overwrite {
541                    return Err(io::Error::new(
542                        io::ErrorKind::AlreadyExists,
543                        format!(
544                            "{} exists; pass overwrite=true or --force to replace it",
545                            path.display()
546                        ),
547                    ));
548                }
549                if metadata.is_dir() || (self.root.is_some() && metadata.is_symlink()) {
550                    return Err(io::Error::new(
551                        io::ErrorKind::PermissionDenied,
552                        format!("output is a directory or symlink: {}", path.display()),
553                    ));
554                }
555                if metadata.is_file() {
556                    permissions = Some(metadata.permissions());
557                }
558            }
559            Err(e) if e.kind() == io::ErrorKind::NotFound => (),
560            Err(e) => return Err(e),
561        }
562        // Open the destination before `parent` and `target` move into the
563        // staged file. The attributes are read from this handle.
564        #[cfg(unix)]
565        let source = if permissions.is_some() {
566            Some(parent.open(&target)?)
567        } else {
568            None
569        };
570        let builder = DirBuilder::new();
571        #[cfg(unix)]
572        let builder = {
573            use cap_std::fs::DirBuilderExt;
574            let mut builder = builder;
575            builder.mode(0o700);
576            builder
577        };
578        let name = format!(".jubarte-{}.partial", staging_suffix());
579        // Exclusive mkdir: a collision is an error, never an existing staging area.
580        parent.create_dir_with(&name, &builder)?;
581        let scratch = parent.open_dir(&name).inspect_err(|_| {
582            let _ = parent.remove_dir(&name);
583        })?;
584        let mut staged = StagedFile {
585            path: path.to_path_buf(),
586            parent,
587            scratch: Some(scratch),
588            scratch_name: Some(name),
589            file: None,
590            target,
591            overwrite: self.overwrite,
592            #[cfg(test)]
593            fail_cleanup: self.fail_cleanup,
594        };
595        staged.file = Some(
596            staged
597                .scratch
598                .as_ref()
599                .expect("open staging directory")
600                .open_with(
601                    "bytes",
602                    OpenOptions::new().read(true).write(true).create_new(true),
603                )?,
604        );
605        if let Some(permissions) = permissions {
606            let file = staged.file.as_ref().expect("open staging file");
607            file.set_permissions(permissions)?;
608            // Mode bits are on the staged inode. Attributes are not, and the
609            // later rename drops whatever still sits on the old inode.
610            #[cfg(unix)]
611            if let Some(source) = source.as_ref() {
612                copy_replaced_xattrs(source, file)?;
613            }
614        }
615        Ok(staged)
616    }
617    fn cleanup(&mut self, staged: &mut StagedFile) -> io::Result<()> {
618        staged.cleanup()
619    }
620    fn same_parent(&mut self, a: &StagedFile, b: &StagedFile) -> io::Result<bool> {
621        // `a`'s staging directory has a unique name; `b`'s parent handle sees
622        // it exactly when both handles are one directory.
623        let Some(name) = a.scratch_name.as_deref() else {
624            return Ok(false);
625        };
626        match b.parent.symlink_metadata(name) {
627            Ok(_) => Ok(true),
628            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
629            Err(error) => Err(error),
630        }
631    }
632    fn claim_name(&mut self, holder: &StagedFile, staged: &StagedFile) -> io::Result<bool> {
633        // The names live in a private directory inside `holder`'s staging, on
634        // the destination's volume, so the volume itself decides equality.
635        // The handle is closed before return: staging cleanup removes it.
636        const NAMES: &str = "names";
637        let scratch = holder.scratch.as_ref().expect("open staging directory");
638        match scratch.create_dir(NAMES) {
639            Ok(()) => (),
640            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => (),
641            Err(error) => return Err(error),
642        }
643        let names = scratch.open_dir(NAMES)?;
644        match names.symlink_metadata(&staged.target) {
645            Ok(_) => return Ok(true),
646            Err(error) if error.kind() == io::ErrorKind::NotFound => (),
647            Err(error) => return Err(error),
648        }
649        names.open_with(
650            &staged.target,
651            cap_std::fs::OpenOptions::new().write(true).create_new(true),
652        )?;
653        Ok(false)
654    }
655    fn step(&mut self, staged: &mut StagedFile, phase: Phase, bytes: &[u8]) -> io::Result<()> {
656        use std::io::{Read, Seek, SeekFrom, Write};
657        #[cfg(test)]
658        if self.fail == Some(phase) {
659            if phase == Phase::Commit {
660                staged
661                    .scratch
662                    .as_ref()
663                    .expect("open staging directory")
664                    .remove_file("bytes")?;
665            } else {
666                return Err(io::Error::other(format!("injected {phase:?}")));
667            }
668        }
669        let file = staged.file.as_mut().expect("open staging file");
670        match phase {
671            Phase::Write => file.write_all(bytes),
672            Phase::Flush => file.flush(),
673            Phase::Sync => file.sync_all(),
674            Phase::Validate => {
675                file.seek(SeekFrom::Start(0))?;
676                if file.metadata()?.len() != bytes.len() as u64 {
677                    return Err(io::Error::new(
678                        io::ErrorKind::InvalidData,
679                        "staged output length mismatch",
680                    ));
681                }
682                let mut buffer = [0; 8192];
683                for chunk in bytes.chunks(buffer.len()) {
684                    file.read_exact(&mut buffer[..chunk.len()])?;
685                    if buffer[..chunk.len()] != *chunk {
686                        return Err(io::Error::new(
687                            io::ErrorKind::InvalidData,
688                            "staged output bytes mismatch",
689                        ));
690                    }
691                }
692                Ok(())
693            }
694            Phase::Commit if staged.overwrite => staged
695                .scratch
696                .as_ref()
697                .expect("open staging directory")
698                .rename("bytes", &staged.parent, &staged.target),
699            // hard_link is an atomic no-clobber installation, including when a
700            // hostile writer creates the target after the initial check.
701            Phase::Commit => staged
702                .scratch
703                .as_ref()
704                .expect("open staging directory")
705                .hard_link("bytes", &staged.parent, &staged.target),
706            Phase::SyncParent => sync_directory_handle(&staged.parent),
707        }
708    }
709}
710
711/// A staging-directory suffix: 32 lowercase hex characters hashed from the
712/// process id, a process-wide counter and the clock, through two freshly
713/// seeded hashers, so two staging areas never share a name without a uuid
714/// dependency (the exclusive `create_dir_with` below still makes a
715/// collision an error, never an existing staging area).
716fn staging_suffix() -> String {
717    use std::hash::BuildHasher;
718    use std::sync::atomic::{AtomicU64, Ordering};
719    use std::time::{SystemTime, UNIX_EPOCH};
720
721    static COUNTER: AtomicU64 = AtomicU64::new(0);
722    let nanos = SystemTime::now()
723        .duration_since(UNIX_EPOCH)
724        .map_or(0, |d| d.as_nanos() as u64);
725    let pid = u64::from(std::process::id());
726    let count = COUNTER.fetch_add(1, Ordering::Relaxed);
727    let one = std::hash::RandomState::new().hash_one((pid, count, nanos));
728    let two = std::hash::RandomState::new().hash_one((nanos, count, pid));
729    format!("{one:016x}{two:016x}")
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735    use std::collections::BTreeMap;
736
737    #[test]
738    fn staging_suffixes_are_unique_and_hex() {
739        let suffixes: Vec<String> = (0..10_000).map(|_| staging_suffix()).collect();
740        let distinct: std::collections::HashSet<&String> = suffixes.iter().collect();
741        assert_eq!(distinct.len(), suffixes.len(), "every suffix is distinct");
742        for suffix in &suffixes {
743            assert_eq!(suffix.len(), 32, "{suffix}: 32 characters");
744            assert!(
745                suffix
746                    .bytes()
747                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
748                "{suffix}: lowercase hex only"
749            );
750        }
751    }
752
753    // Filesystem integration probes: exercise actual handle lifetime and hard links.
754    #[test]
755    fn cleanup_failure_is_reported_after_install_and_alongside_publish_failure() {
756        for phase in [
757            None,
758            Some(Phase::Write),
759            Some(Phase::Commit),
760            Some(Phase::SyncParent),
761        ] {
762            let temp = tempfile::tempdir().unwrap();
763            let root = OutputRoot::open(temp.path()).unwrap();
764            let mut backend = FsBackend {
765                root: Some(&root.dir),
766                overwrite: false,
767                fail: phase,
768                fail_cleanup: true,
769            };
770            let result = transaction(&mut backend, &[("output".into(), b"Alice")]);
771            let installed = phase.is_none() || phase == Some(Phase::SyncParent);
772            assert_eq!(temp.path().join("output").exists(), installed);
773            if installed {
774                assert_eq!(root.read(Path::new("output")).unwrap(), b"Alice");
775            }
776            let warnings = match result {
777                Ok(report) => {
778                    assert!(phase.is_none());
779                    report.warnings
780                }
781                Err(error) => {
782                    assert!(phase.is_some());
783                    assert_eq!(
784                        error.committed,
785                        if installed {
786                            vec![PathBuf::from("output")]
787                        } else {
788                            vec![]
789                        }
790                    );
791                    assert_eq!(error.durability_uncertain, phase == Some(Phase::SyncParent));
792                    if phase == Some(Phase::Commit) {
793                        assert_eq!(error.source.kind(), io::ErrorKind::NotFound);
794                    } else {
795                        assert!(
796                            error
797                                .source
798                                .to_string()
799                                .contains(&format!("injected {:?}", phase.unwrap()))
800                        );
801                    }
802                    error.warnings
803                }
804            };
805            assert_eq!(warnings.len(), 1);
806            assert!(
807                warnings[0].contains("injected cleanup"),
808                "cleanup failure was swallowed: {warnings:?}"
809            );
810        }
811    }
812
813    #[test]
814    fn prepared_commit_reports_cleanup_failure_after_install() {
815        let temp = tempfile::tempdir().unwrap();
816        let path = temp.path().join("output");
817        let mut staged = StagedFile::prepare(&path, b"Bob", false).unwrap();
818        staged.fail_cleanup = true;
819        let result = staged.commit();
820        assert_eq!(std::fs::read(path).unwrap(), b"Bob");
821        let report = result.unwrap();
822        assert_eq!(report.warnings.len(), 1);
823        assert!(report.warnings[0].contains("injected cleanup"));
824    }
825
826    #[test]
827    fn every_publish_path_removes_partial_directories() {
828        let temp = tempfile::tempdir().unwrap();
829        let output = temp.path().join("output");
830        // Fresh replacement, forced replacement, then no-overwrite hard-link commit.
831        for overwrite in [true, true, false] {
832            if !overwrite {
833                std::fs::remove_file(&output).unwrap();
834            }
835            let report = publish_paths(&[(output.clone(), b"Carol Diaz")], overwrite).unwrap();
836            assert!(report.warnings.is_empty(), "{report:?}");
837            assert_no_partials(temp.path());
838            assert_eq!(std::fs::read(&output).unwrap(), b"Carol Diaz");
839        }
840        for phase in [
841            Phase::Write,
842            Phase::Flush,
843            Phase::Sync,
844            Phase::Validate,
845            Phase::Commit,
846            Phase::SyncParent,
847        ] {
848            let mut backend = FsBackend {
849                root: None,
850                overwrite: true,
851                fail: Some(phase),
852                fail_cleanup: false,
853            };
854            let error = transaction(
855                &mut backend,
856                &[
857                    (output.clone(), b"Alice"),
858                    (temp.path().join("second"), b"Bob"),
859                ],
860            )
861            .unwrap_err();
862            assert!(error.warnings.is_empty(), "{error:?}");
863            assert_no_partials(temp.path());
864        }
865    }
866
867    fn assert_no_partials(parent: &Path) {
868        let partials: Vec<_> = std::fs::read_dir(parent)
869            .unwrap()
870            .map(|entry| entry.unwrap().file_name())
871            .filter(|name| {
872                let name = name.to_string_lossy();
873                name.starts_with(".jubarte-") && name.ends_with(".partial")
874            })
875            .collect();
876        assert!(partials.is_empty(), "staging leftovers: {partials:?}");
877    }
878
879    #[cfg(unix)]
880    #[test]
881    fn cleanup_refuses_a_swapped_scratch_symlink() {
882        let temp = tempfile::tempdir().unwrap();
883        let outside = tempfile::tempdir().unwrap();
884        std::fs::write(outside.path().join("keep"), b"Carol Diaz").unwrap();
885        let path = temp.path().join("output");
886        let staged = StagedFile::prepare(&path, b"Alice", false).unwrap();
887        let name = std::fs::read_dir(temp.path())
888            .unwrap()
889            .next()
890            .unwrap()
891            .unwrap()
892            .file_name();
893        std::fs::rename(temp.path().join(&name), temp.path().join("held")).unwrap();
894        std::os::unix::fs::symlink(outside.path(), temp.path().join(&name)).unwrap();
895        let result = staged.commit();
896        assert_eq!(
897            std::fs::read(outside.path().join("keep")).unwrap(),
898            b"Carol Diaz"
899        );
900        assert!(
901            temp.path()
902                .join(&name)
903                .symlink_metadata()
904                .unwrap()
905                .is_symlink()
906        );
907        let report = format!("{result:?}");
908        assert!(
909            report.contains("symlink"),
910            "swapped symlink was not reported: {report}"
911        );
912    }
913
914    /// A forced replacement keeps a user attribute that lived on the old inode.
915    #[cfg(unix)]
916    #[test]
917    fn a_forced_replacement_keeps_the_destination_user_xattr() {
918        let temp = tempfile::tempdir().unwrap();
919        let output = temp.path().join("output");
920        std::fs::write(&output, b"old").unwrap();
921        // The crate the copy itself uses, so Linux and macOS both run it.
922        match xattr::set(&output, "user.jubarte", b"kept") {
923            Ok(()) => {}
924            // A file system with no user attributes has nothing to keep.
925            Err(error) if error.kind() == std::io::ErrorKind::Unsupported => return,
926            Err(error) => panic!("could not set the user attribute: {error}"),
927        }
928        let report = publish_paths(&[(output.clone(), b"new")], true).unwrap();
929        assert!(report.warnings.is_empty(), "{report:?}");
930        assert_eq!(std::fs::read(&output).unwrap(), b"new");
931        assert_eq!(
932            xattr::get(&output, "user.jubarte").unwrap().as_deref(),
933            Some(b"kept".as_slice()),
934            "overwrite dropped the destination extended attribute"
935        );
936    }
937
938    /// macOS labels the kernel owns stay behind: userspace cannot write
939    /// `com.apple.rootless` or `com.apple.system.*` (EPERM), and the kernel
940    /// sets `com.apple.provenance` and `com.apple.macl` itself. Copying them
941    /// would fail an ordinary forced publish. Other names still move.
942    #[cfg(target_os = "macos")]
943    #[test]
944    fn macos_kernel_labels_are_left_for_the_kernel() {
945        use std::ffi::OsStr;
946        for name in [
947            "com.apple.rootless",
948            "com.apple.system.Security",
949            "com.apple.provenance",
950            "com.apple.macl",
951        ] {
952            assert!(!replaced_xattr(OsStr::new(name)), "{name} must stay behind");
953        }
954        for name in ["user.jubarte", "com.apple.quarantine", "com.example.tag"] {
955            assert!(replaced_xattr(OsStr::new(name)), "{name} must move");
956        }
957    }
958
959    #[test]
960    fn windows_directory_sync_is_a_noop() {
961        let mut called = false;
962        let result = sync_directory_for_platform(true, || {
963            called = true;
964            Err(io::Error::new(
965                io::ErrorKind::PermissionDenied,
966                "read-only directory",
967            ))
968        });
969        assert!(
970            result.is_ok(),
971            "Windows directory sync must succeed: {result:?}"
972        );
973        assert!(!called, "Windows must not attempt the directory sync");
974    }
975
976    #[test]
977    fn unix_directory_sync_calls_the_operation_and_preserves_its_result() {
978        for kind in [None, Some(io::ErrorKind::PermissionDenied)] {
979            let mut called = false;
980            let result = sync_directory_for_platform(false, || {
981                called = true;
982                match kind {
983                    None => Ok(()),
984                    Some(kind) => Err(io::Error::new(kind, "read-only directory")),
985                }
986            });
987            assert!(called, "Unix must attempt the directory sync");
988            assert_eq!(result.as_ref().err().map(io::Error::kind), kind);
989            if let Err(error) = result {
990                assert_eq!(error.to_string(), "read-only directory");
991            }
992        }
993    }
994
995    /// cap-std opens directories `O_PATH` on Linux, and `fsync` on an
996    /// `O_PATH` descriptor is EBADF (#1351): every publication failed after
997    /// its commit there, with "durability uncertain".
998    #[test]
999    fn a_cap_std_directory_handle_can_be_synced() {
1000        let temp = tempfile::tempdir().unwrap();
1001        std::fs::create_dir(temp.path().join("sub")).unwrap();
1002        let dir =
1003            cap_std::fs::Dir::open_ambient_dir(temp.path(), cap_std::ambient_authority()).unwrap();
1004        sync_directory_handle(&dir).expect("an ambient directory handle syncs");
1005        sync_directory_handle(&dir.open_dir("sub").unwrap())
1006            .expect("a directory opened through a handle syncs");
1007        sync_directory(temp.path()).expect("sync_directory syncs");
1008    }
1009
1010    /// Deterministic filesystem fake: all state and injected failures stay in memory.
1011    struct Memory {
1012        visible: BTreeMap<PathBuf, Vec<u8>>,
1013        fail: Option<(usize, Phase)>,
1014        count: usize,
1015        order: Vec<(usize, Phase)>,
1016        fail_stage: Option<usize>,
1017        claimed: std::collections::BTreeSet<PathBuf>,
1018    }
1019    impl Memory {
1020        fn new(fail: Option<(usize, Phase)>) -> Self {
1021            Self {
1022                visible: [
1023                    (PathBuf::from("a"), b"old a".to_vec()),
1024                    (PathBuf::from("b"), b"old b".to_vec()),
1025                ]
1026                .into(),
1027                fail,
1028                count: 0,
1029                order: vec![],
1030                fail_stage: None,
1031                claimed: std::collections::BTreeSet::new(),
1032            }
1033        }
1034    }
1035    impl Backend for Memory {
1036        type Staged = (usize, PathBuf, Vec<u8>);
1037        fn stage(&mut self, path: &Path) -> io::Result<Self::Staged> {
1038            let id = self.count;
1039            self.count += 1;
1040            if self.fail_stage == Some(id) {
1041                return Err(io::Error::other("injected staging creation failure"));
1042            }
1043            Ok((id, path.into(), vec![]))
1044        }
1045        fn cleanup(&mut self, _staged: &mut Self::Staged) -> io::Result<()> {
1046            Ok(())
1047        }
1048        fn same_parent(&mut self, a: &Self::Staged, b: &Self::Staged) -> io::Result<bool> {
1049            Ok(a.1.parent() == b.1.parent())
1050        }
1051        fn claim_name(
1052            &mut self,
1053            _holder: &Self::Staged,
1054            staged: &Self::Staged,
1055        ) -> io::Result<bool> {
1056            Ok(!self.claimed.insert(staged.1.clone()))
1057        }
1058        fn step(
1059            &mut self,
1060            staged: &mut Self::Staged,
1061            phase: Phase,
1062            bytes: &[u8],
1063        ) -> io::Result<()> {
1064            let (id, path, held) = staged;
1065            self.order.push((*id, phase));
1066            if self.fail == Some((*id, phase)) {
1067                return Err(io::Error::other(format!("injected {phase:?}")));
1068            }
1069            match phase {
1070                Phase::Write => *held = bytes.to_vec(),
1071                Phase::Commit => {
1072                    self.visible.insert(path.clone(), held.clone());
1073                }
1074                _ => (),
1075            }
1076            Ok(())
1077        }
1078    }
1079    fn files() -> [(PathBuf, &'static [u8]); 2] {
1080        [("a".into(), b"new a"), ("b".into(), b"new b")]
1081    }
1082
1083    fn fs_failure(phase: Phase) {
1084        let temp = tempfile::tempdir().unwrap();
1085        std::fs::write(temp.path().join("output"), b"old output").unwrap();
1086        let root = OutputRoot::open(temp.path()).unwrap();
1087        let mut backend = FsBackend {
1088            root: Some(&root.dir),
1089            overwrite: true,
1090            fail: Some(phase),
1091            fail_cleanup: false,
1092        };
1093        let error = transaction(&mut backend, &[("output".into(), b"new output")])
1094            .expect_err("configured filesystem fault must fail publication");
1095        let installed = phase == Phase::SyncParent;
1096        assert_eq!(
1097            root.read(Path::new("output")).unwrap(),
1098            if installed {
1099                b"new output"
1100            } else {
1101                b"old output"
1102            }
1103        );
1104        assert_eq!(
1105            error.committed,
1106            if installed {
1107                vec![PathBuf::from("output")]
1108            } else {
1109                vec![]
1110            }
1111        );
1112        assert_eq!(error.durability_uncertain, installed);
1113        if installed {
1114            assert!(
1115                error.to_string().contains("durability uncertain"),
1116                "{error}"
1117            );
1118            assert!(
1119                error.source.to_string().contains("injected SyncParent"),
1120                "{error}"
1121            );
1122        } else {
1123            assert_eq!(error.source.kind(), io::ErrorKind::NotFound);
1124        }
1125        let remaining: Vec<_> = std::fs::read_dir(temp.path())
1126            .unwrap()
1127            .map(|entry| entry.unwrap().file_name())
1128            .collect();
1129        assert_eq!(remaining, [std::ffi::OsString::from("output")]);
1130    }
1131
1132    #[test]
1133    fn audit_d13_fs_rename_failure_preserves_prior_output_and_cleans_staging() {
1134        fs_failure(Phase::Commit);
1135    }
1136
1137    #[test]
1138    fn audit_d13_fs_parent_sync_failure_reports_installed_output_and_cleans_staging() {
1139        fs_failure(Phase::SyncParent);
1140    }
1141
1142    #[test]
1143    fn audit_d13_all_precommit_failures_preserve_every_prior_output() {
1144        for phase in [Phase::Write, Phase::Flush, Phase::Sync, Phase::Validate] {
1145            for index in 0..2 {
1146                let mut fs = Memory::new(Some((index, phase)));
1147                let error = transaction(&mut fs, &files()).unwrap_err();
1148                assert!(error.source.to_string().contains("injected"), "{error}");
1149                assert!(error.committed.is_empty());
1150                assert!(!error.durability_uncertain);
1151                assert_eq!(fs.visible, Memory::new(None).visible);
1152            }
1153        }
1154    }
1155    #[test]
1156    fn audit_d13_rename_failure_never_deletes_old_and_reports_prior_commits() {
1157        for index in 0..2 {
1158            let mut fs = Memory::new(Some((index, Phase::Commit)));
1159            let error = transaction(&mut fs, &files()).unwrap_err();
1160            assert!(error.source.to_string().contains("injected"), "{error}");
1161            assert_eq!(error.committed.len(), index);
1162            assert_eq!(fs.visible[Path::new("b")], b"old b");
1163            assert_eq!(
1164                fs.visible[Path::new("a")],
1165                if index == 0 { b"old a" } else { b"new a" }
1166            );
1167        }
1168    }
1169    #[test]
1170    fn audit_d13_postcommit_sync_failure_reports_visible_output_and_uncertain_durability() {
1171        let mut fs = Memory::new(Some((0, Phase::SyncParent)));
1172        let error = transaction(&mut fs, &files()).unwrap_err();
1173        assert_eq!(error.committed, [PathBuf::from("a")]);
1174        assert!(error.durability_uncertain);
1175        assert_eq!(fs.visible[Path::new("a")], b"new a");
1176        assert_eq!(fs.visible[Path::new("b")], b"old b");
1177    }
1178    #[test]
1179    fn audit_d13_validates_the_entire_set_before_the_first_commit() {
1180        let mut fs = Memory::new(None);
1181        transaction(&mut fs, &files()).unwrap();
1182        assert_eq!(fs.visible[Path::new("b")], b"new b");
1183        let first_commit = fs
1184            .order
1185            .iter()
1186            .position(|(_, p)| *p == Phase::Commit)
1187            .unwrap();
1188        let last_validate = fs
1189            .order
1190            .iter()
1191            .rposition(|(_, p)| *p == Phase::Validate)
1192            .unwrap();
1193        assert!(last_validate < first_commit);
1194    }
1195    #[test]
1196    fn audit_d35_portable_names_cannot_smuggle_extra_path_authority() {
1197        for path in [
1198            "",
1199            "PRN",
1200            "AUX",
1201            "CONIN$",
1202            "CONOUT$",
1203            "COM¹.txt",
1204            "LPT².docx",
1205            "a<b",
1206            "a>b",
1207            "a\"b",
1208            "a|b",
1209            "a?b",
1210            "a*b",
1211            "../escape",
1212            "/absolute",
1213            "ok/../../escape",
1214            "C:\\escape",
1215            "a\\b",
1216            "NUL.txt",
1217            "con",
1218            "COM1.docx",
1219            "LPT9",
1220            "file:stream",
1221            "trailing.",
1222            "trailing ",
1223            "a/../b",
1224            "a//b",
1225            "./a",
1226            "a/%2e%2e/b",
1227            "a/%2Ftmp",
1228            "a/line\n",
1229            "a\u{061c}b",
1230            "a\u{200e}b",
1231            "a\u{200f}b",
1232            "a\u{202a}b",
1233            "a\u{202b}b",
1234            "a\u{202c}b",
1235            "a\u{202d}b",
1236            "a\u{202e}b",
1237            "a\u{2066}b",
1238            "a\u{2067}b",
1239            "a\u{2068}b",
1240            "a\u{2069}b",
1241            "a\u{feff}b",
1242        ] {
1243            assert!(
1244                validate_relative(Path::new(path)).is_err(),
1245                "accepted {path:?}"
1246            );
1247        }
1248        assert!(validate_relative(Path::new(&"x".repeat(256))).is_err());
1249        for path in [
1250            "page-01.png",
1251            "media/0123456789abcdef.png",
1252            "new folder/redline.docx",
1253            "نام\u{200c}نامه.docx",
1254            "नाम\u{200d}पत्र.docx",
1255        ] {
1256            assert!(validate_relative(Path::new(path)).is_ok(), "refused {path}");
1257        }
1258    }
1259    #[test]
1260    fn staging_creation_failure_and_duplicate_names_never_commit() {
1261        let mut fs = Memory::new(None);
1262        fs.fail_stage = Some(1);
1263        let error = transaction(&mut fs, &files()).unwrap_err();
1264        assert!(error.committed.is_empty());
1265        assert_eq!(fs.visible, Memory::new(None).visible);
1266        let mut fs = Memory::new(None);
1267        let error = transaction(
1268            &mut fs,
1269            &[("a".into(), b"first".as_slice()), ("a".into(), b"second")],
1270        )
1271        .unwrap_err();
1272        assert_eq!(error.source.kind(), io::ErrorKind::InvalidInput);
1273        assert!(error.committed.is_empty());
1274        assert_eq!(fs.visible, Memory::new(None).visible);
1275        assert!(transaction(&mut fs, &[]).is_ok());
1276    }
1277
1278    /// A refused set publishes nothing and leaves no staging behind.
1279    fn refused(dir: &Path, files: &[(PathBuf, &[u8])], overwrite: bool) {
1280        let error = publish_paths(files, overwrite).unwrap_err();
1281        assert!(
1282            error.source.to_string().contains("duplicate output path"),
1283            "{error}"
1284        );
1285        assert!(error.committed.is_empty(), "{error}");
1286        assert_no_partials(dir);
1287    }
1288
1289    /// Whether `dir`'s volume treats `a` and `b` as one name.
1290    fn one_name(dir: &Path, a: &str, b: &str) -> bool {
1291        let probe = tempfile::tempdir_in(dir).unwrap();
1292        std::fs::write(probe.path().join(a), b"").unwrap();
1293        probe.path().join(b).exists()
1294    }
1295
1296    #[test]
1297    fn a_parent_step_spelling_of_one_destination_publishes_nothing() {
1298        let temp = tempfile::tempdir().unwrap();
1299        std::fs::create_dir(temp.path().join("x")).unwrap();
1300        let (a, stepped) = (temp.path().join("a"), temp.path().join("x/../a"));
1301        assert_ne!(a, stepped);
1302        refused(temp.path(), &[(a.clone(), b"1"), (stepped, b"2")], false);
1303        assert!(!a.exists(), "a refused set must not publish");
1304    }
1305
1306    #[cfg(unix)]
1307    #[test]
1308    fn a_parent_reached_through_a_directory_symlink_is_one_destination() {
1309        let temp = tempfile::tempdir().unwrap();
1310        std::fs::create_dir(temp.path().join("real")).unwrap();
1311        std::os::unix::fs::symlink("real", temp.path().join("alias")).unwrap();
1312        refused(
1313            temp.path(),
1314            &[
1315                (temp.path().join("real/x"), b"1"),
1316                (temp.path().join("alias/x"), b"2"),
1317            ],
1318            true,
1319        );
1320        assert!(!temp.path().join("real/x").exists());
1321    }
1322
1323    /// The kernel resolves `jump` before `..`: `left/jump/../out` is
1324    /// `elsewhere/out`, not `left/out`.
1325    #[cfg(unix)]
1326    #[test]
1327    fn a_parent_step_through_a_symlink_follows_the_filesystem() {
1328        let temp = tempfile::tempdir().unwrap();
1329        std::fs::create_dir_all(temp.path().join("elsewhere/sub")).unwrap();
1330        std::fs::create_dir(temp.path().join("left")).unwrap();
1331        std::os::unix::fs::symlink(
1332            temp.path().join("elsewhere/sub"),
1333            temp.path().join("left/jump"),
1334        )
1335        .unwrap();
1336        refused(
1337            temp.path(),
1338            &[
1339                (temp.path().join("left/jump/../out"), b"1"),
1340                (temp.path().join("elsewhere/out"), b"2"),
1341            ],
1342            true,
1343        );
1344        // `left/out` is a different file: it publishes beside `elsewhere/out`.
1345        publish_paths(
1346            &[
1347                (temp.path().join("left/jump/../out"), b"1"),
1348                (temp.path().join("left/out"), b"2"),
1349            ],
1350            true,
1351        )
1352        .unwrap();
1353        assert_eq!(
1354            std::fs::read(temp.path().join("elsewhere/out")).unwrap(),
1355            b"1"
1356        );
1357        assert_eq!(std::fs::read(temp.path().join("left/out")).unwrap(), b"2");
1358    }
1359
1360    /// Installing replaces a symlink's entry, never its referent: the link
1361    /// and its target are two destinations.
1362    #[cfg(unix)]
1363    #[test]
1364    fn a_symlink_and_its_referent_are_two_destinations() {
1365        let temp = tempfile::tempdir().unwrap();
1366        let (link, target) = (temp.path().join("link"), temp.path().join("target"));
1367        std::fs::write(&target, b"old").unwrap();
1368        std::os::unix::fs::symlink("target", &link).unwrap();
1369        publish_paths(
1370            &[(link.clone(), b"by link"), (target.clone(), b"by target")],
1371            true,
1372        )
1373        .unwrap();
1374        assert!(!std::fs::symlink_metadata(&link).unwrap().is_symlink());
1375        assert_eq!(std::fs::read(&link).unwrap(), b"by link");
1376        assert_eq!(std::fs::read(&target).unwrap(), b"by target");
1377    }
1378
1379    /// Names one only by case are one destination exactly when the volume
1380    /// says so; a case-sensitive volume keeps both.
1381    #[test]
1382    fn case_follows_the_volume() {
1383        let temp = tempfile::tempdir().unwrap();
1384        let files = [
1385            (temp.path().join("Report.txt"), &b"1"[..]),
1386            (temp.path().join("report.txt"), &b"2"[..]),
1387        ];
1388        if one_name(temp.path(), "Report.txt", "report.txt") {
1389            refused(temp.path(), &files, false);
1390        } else {
1391            publish_paths(&files, false).unwrap();
1392        }
1393    }
1394
1395    /// Composed and decomposed `é` are one name on a normalization-
1396    /// insensitive volume (APFS) and two elsewhere.
1397    #[test]
1398    fn unicode_normalization_follows_the_volume() {
1399        let temp = tempfile::tempdir().unwrap();
1400        let (composed, decomposed) = ("caf\u{e9}", "cafe\u{301}");
1401        let files = [
1402            (temp.path().join(composed), &b"1"[..]),
1403            (temp.path().join(decomposed), &b"2"[..]),
1404        ];
1405        if one_name(temp.path(), composed, decomposed) {
1406            refused(temp.path(), &files, false);
1407        } else {
1408            publish_paths(&files, false).unwrap();
1409        }
1410    }
1411
1412    /// Distinct non-UTF-8 names stay distinct (APFS refuses them outright).
1413    #[cfg(target_os = "linux")]
1414    #[test]
1415    fn distinct_non_utf8_names_are_two_destinations() {
1416        use std::os::unix::ffi::OsStrExt;
1417        let temp = tempfile::tempdir().unwrap();
1418        let name = |byte: u8| temp.path().join(std::ffi::OsStr::from_bytes(&[b'x', byte]));
1419        publish_paths(&[(name(0xff), b"1"), (name(0xfe), b"2")], false).unwrap();
1420        assert_eq!(std::fs::read(name(0xff)).unwrap(), b"1");
1421        assert_eq!(std::fs::read(name(0xfe)).unwrap(), b"2");
1422    }
1423
1424    /// An output root resolves its names from the root, whatever the
1425    /// process's working directory is.
1426    #[cfg(unix)]
1427    #[test]
1428    fn an_output_root_resolves_aliases_from_the_root() {
1429        let temp = tempfile::tempdir().unwrap();
1430        std::fs::create_dir(temp.path().join("real")).unwrap();
1431        std::os::unix::fs::symlink("real", temp.path().join("alias")).unwrap();
1432        let root = OutputRoot::open(temp.path()).unwrap();
1433        let error = root
1434            .publish(
1435                &[
1436                    (PathBuf::from("real/x"), b"1"),
1437                    (PathBuf::from("alias/x"), b"2"),
1438                ],
1439                true,
1440            )
1441            .unwrap_err();
1442        assert!(
1443            error.source.to_string().contains("duplicate output path"),
1444            "{error}"
1445        );
1446        assert!(error.committed.is_empty(), "{error}");
1447        assert!(!temp.path().join("real/x").exists());
1448        assert_no_partials(temp.path());
1449    }
1450}