Skip to main content

codewhale_runtime/
delivery_files.rs

1//! Updater-facing I/O over the existing Fleet file fence. No installation store.
2//!
3//! Retained handles identify ownership; a digest alone cannot identify a file.
4//! Moves never replace another entry. Unix cannot atomically compare a directory
5//! entry and rename it, so callers must recover/preserve the moved entry when
6//! post-move identity validation refuses it. Windows moves the opened object.
7use std::collections::{BTreeMap, BTreeSet};
8use std::fs::File;
9use std::io::{self, Read, Seek};
10use std::path::{Path, PathBuf};
11use std::time::SystemTime;
12
13use sha2::{Digest, Sha256};
14
15use codewhale_util::files::{WorkspaceFile, same_file};
16
17#[derive(Debug, PartialEq, Eq)]
18struct Version {
19    length: u64,
20    modified: SystemTime,
21    #[cfg(unix)]
22    changed: (i64, i64),
23    #[cfg(unix)]
24    nlink: u64,
25}
26
27fn version_with_max_links(file: &File, max_links: u64) -> io::Result<Version> {
28    let metadata = file.metadata()?;
29    if !metadata.is_file() {
30        return Err(invalid("delivery file is not regular"));
31    }
32    #[cfg(unix)]
33    let nlink = {
34        use std::os::unix::fs::MetadataExt;
35        let nlink = metadata.nlink();
36        if nlink == 0 || nlink > max_links {
37            return Err(invalid("delivery file has multiple links"));
38        }
39        nlink
40    };
41    #[cfg(windows)]
42    {
43        let _ = max_links;
44        let identity = codewhale_util::path_identity::windows_file_identity(file)?;
45        if identity.links != 1 || identity.attributes & 0x0000_0400 != 0 {
46            return Err(invalid("delivery file is linked or a reparse point"));
47        }
48    }
49    #[cfg(all(not(unix), not(windows)))]
50    return Err(io::ErrorKind::Unsupported.into());
51    Ok(Version {
52        length: metadata.len(),
53        modified: metadata.modified()?,
54        #[cfg(unix)]
55        changed: {
56            use std::os::unix::fs::MetadataExt;
57            (metadata.ctime(), metadata.ctime_nsec())
58        },
59        #[cfg(unix)]
60        nlink,
61    })
62}
63
64fn invalid(message: &'static str) -> io::Error {
65    io::Error::new(io::ErrorKind::InvalidData, message)
66}
67
68// A regular file may still grow on Unix after its version was captured. Read
69// at most the captured length plus one byte; do not wait for a racing writer's EOF.
70fn hash_exact_length(reader: &mut impl Read, length: u64) -> io::Result<String> {
71    let limit = length
72        .checked_add(1)
73        .ok_or_else(|| invalid("delivery file length cannot be bounded"))?;
74    let mut bounded = reader.take(limit);
75    let mut hash = Sha256::new();
76    let mut buffer = [0; 64 * 1024];
77    let mut total = 0;
78    loop {
79        let count = bounded.read(&mut buffer)?;
80        if count == 0 {
81            break;
82        }
83        total += count as u64;
84        if total > length {
85            return Err(invalid("delivery file grew while reading"));
86        }
87        hash.update(&buffer[..count]);
88    }
89    if total != length {
90        return Err(invalid("delivery file shortened while reading"));
91    }
92    Ok(crate::hashing::hex_bytes(hash.finalize()))
93}
94
95fn stable_hash(file: &mut File, maximum: Option<u64>) -> io::Result<(String, Version)> {
96    stable_hash_with_max_links(file, maximum, 1)
97}
98
99fn stable_hash_with_max_links(
100    file: &mut File,
101    maximum: Option<u64>,
102    max_links: u64,
103) -> io::Result<(String, Version)> {
104    let before = version_with_max_links(file, max_links)?;
105    if maximum.is_some_and(|maximum| before.length > maximum) {
106        return Err(invalid("delivery file exceeds captured size limit"));
107    }
108    file.rewind()?;
109    let digest = hash_exact_length(file, before.length)?;
110    let after = version_with_max_links(file, max_links)?;
111    if before != after {
112        return Err(invalid("delivery file changed while reading"));
113    }
114    Ok((digest, after))
115}
116
117/// Blocking I/O facade used by the synchronous CLI updater. Async callers
118/// must run these methods on their existing blocking worker.
119/// One opened regular, unlinked file and its pinned parent. Drop closes handles;
120/// it never deletes a pathname another process could have replaced.
121#[derive(Debug)]
122pub struct GuardedFile {
123    location: WorkspaceFile,
124    directory: PathBuf,
125    name: String,
126    file: File,
127    digest: String,
128    version: Version,
129}
130
131impl GuardedFile {
132    pub fn open(directory: &Path, name: &str) -> io::Result<Option<Self>> {
133        Self::open_with_limit(directory, name, None)
134    }
135
136    pub fn open_bounded(directory: &Path, name: &str, maximum: usize) -> io::Result<Option<Self>> {
137        Self::open_with_limit(directory, name, Some(maximum))
138    }
139
140    /// Open a closed set of command siblings, rejecting any hard link outside the opened group.
141    pub fn open_command_siblings(
142        directory: &Path,
143        names: &[&str],
144    ) -> io::Result<BTreeMap<String, Self>> {
145        let mut unique_names = BTreeSet::new();
146        for &name in names {
147            if Path::new(name).components().count() != 1 {
148                return Err(invalid("delivery filename must be one basename"));
149            }
150            unique_names.insert(name);
151        }
152        #[cfg(unix)]
153        let max_links = unique_names.len().max(1) as u64;
154        #[cfg(not(unix))]
155        let max_links = 1;
156        let mut opened = BTreeMap::new();
157        for name in unique_names {
158            if let Some(handle) =
159                Self::open_with_limit_and_max_links(directory, name, None, max_links)?
160            {
161                opened.insert(name.to_string(), handle);
162            }
163        }
164        #[cfg(unix)]
165        {
166            for handle in opened.values() {
167                let mut group_len = 0_u64;
168                for candidate in opened.values() {
169                    if same_file(&handle.file, &candidate.file)? {
170                        group_len += 1;
171                    }
172                }
173                if handle.version.nlink != group_len {
174                    return Err(invalid("delivery file has an unowned hard link"));
175                }
176            }
177            for handle in opened.values_mut() {
178                handle.verify()?;
179            }
180        }
181        Ok(opened)
182    }
183
184    fn open_with_limit(
185        directory: &Path,
186        name: &str,
187        maximum: Option<usize>,
188    ) -> io::Result<Option<Self>> {
189        Self::open_with_limit_and_max_links(directory, name, maximum, 1)
190    }
191
192    fn open_with_limit_and_max_links(
193        directory: &Path,
194        name: &str,
195        maximum: Option<usize>,
196        max_links: u64,
197    ) -> io::Result<Option<Self>> {
198        if Path::new(name).components().count() != 1 {
199            return Err(invalid("delivery filename must be one basename"));
200        }
201        #[cfg(windows)]
202        let directory = if directory.is_absolute() {
203            directory.to_path_buf()
204        } else {
205            std::env::current_dir()?.join(directory)
206        };
207        #[cfg(not(windows))]
208        let directory = directory.canonicalize()?;
209        let location = WorkspaceFile::open_delivery(&directory, Path::new(name))?;
210        let mut file = match location.open_retained_with_max_links(max_links) {
211            Ok(file) => file,
212            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
213            Err(error) => return Err(error),
214        };
215        let initial = version_with_max_links(&file, max_links)?;
216        if maximum.is_some_and(|maximum| initial.length > maximum as u64) {
217            return Err(invalid("delivery receipt exceeds size limit"));
218        }
219        let (digest, version) = stable_hash_with_max_links(
220            &mut file,
221            maximum.map(|maximum| maximum as u64),
222            max_links,
223        )?;
224        let result = Self {
225            location,
226            directory,
227            name: name.into(),
228            file,
229            digest,
230            version,
231        };
232        if !result.matches_path()? {
233            return Err(invalid("delivery pathname changed while opening"));
234        }
235        Ok(Some(result))
236    }
237
238    pub fn stage(directory: &Path, bytes: &[u8], executable: bool) -> io::Result<Self> {
239        let name = Self::recovery_name();
240        #[cfg(windows)]
241        let directory = if directory.is_absolute() {
242            directory.to_path_buf()
243        } else {
244            std::env::current_dir()?.join(directory)
245        };
246        #[cfg(not(windows))]
247        let directory = directory.canonicalize()?;
248        let location = WorkspaceFile::open_delivery(&directory, Path::new(&name))?;
249        let mut file = location.publish_retained(bytes, executable)?;
250        let (digest, version) = stable_hash(&mut file, Some(bytes.len() as u64))?;
251        let result = Self {
252            location,
253            directory,
254            name,
255            file,
256            digest,
257            version,
258        };
259        if !result.matches_path()? {
260            return Err(invalid("delivery stage changed while opening"));
261        }
262        Ok(result)
263    }
264
265    fn expected_max_links(&self) -> u64 {
266        #[cfg(unix)]
267        {
268            self.version.nlink
269        }
270        #[cfg(not(unix))]
271        {
272            1
273        }
274    }
275
276    /// Return whether two guarded handles refer to the same underlying file object.
277    pub fn same_inode(&self, other: &Self) -> io::Result<bool> {
278        same_file(&self.file, &other.file)
279    }
280
281    #[cfg(unix)]
282    pub fn verify_owned(&mut self) -> io::Result<()> {
283        let max_links = self.expected_max_links();
284        self.location
285            .verify_delivery_owner_with_max_links(&self.file, max_links)?;
286        self.verify()?;
287        self.location
288            .verify_delivery_owner_with_max_links(&self.file, max_links)
289    }
290
291    #[cfg(unix)]
292    pub fn remove_checked(&mut self, unlinked: &mut bool) -> io::Result<()> {
293        self.remove_sibling_checked(0, false, unlinked)
294    }
295
296    /// Remove a guarded sibling command while enforcing exact pre- and post-unlink link counts.
297    #[cfg(unix)]
298    pub fn remove_sibling_checked(
299        &mut self,
300        expected_remaining_links: u64,
301        prior_sibling_unlinked: bool,
302        unlinked: &mut bool,
303    ) -> io::Result<()> {
304        use std::os::unix::fs::MetadataExt;
305        *unlinked = false;
306        if prior_sibling_unlinked {
307            let expected_current_links = expected_remaining_links
308                .checked_add(1)
309                .ok_or_else(|| invalid("invalid expected link count"))?;
310            if !self.matches_path_with_max_links(expected_current_links)? {
311                return Err(invalid("delivery pathname identity changed"));
312            }
313            self.location
314                .verify_delivery_owner_with_max_links(&self.file, expected_current_links)?;
315            let metadata = self.file.metadata()?;
316            if !metadata.is_file()
317                || metadata.len() != self.version.length
318                || metadata.modified()? != self.version.modified
319                || metadata.nlink() != expected_current_links
320            {
321                return Err(invalid("delivery file changed since capture"));
322            }
323            self.file.rewind()?;
324            let digest = hash_exact_length(&mut self.file, self.version.length)?;
325            if digest != self.digest {
326                return Err(invalid("delivery file changed since capture"));
327            }
328            let reanchored = version_with_max_links(&self.file, expected_current_links)?;
329            if reanchored.length != self.version.length
330                || reanchored.modified != self.version.modified
331                || reanchored.nlink != expected_current_links
332            {
333                return Err(invalid("delivery file changed since capture"));
334            }
335            self.version = reanchored;
336        } else if self.version.nlink != expected_remaining_links.saturating_add(1) {
337            return Err(invalid("delivery file link count changed since capture"));
338        }
339        self.verify_owned()?;
340        let expected_links_before_unlink = self.version.nlink;
341        let directory = tempfile::Builder::new()
342            .prefix(".codewhale-uninstall-")
343            .permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700))
344            .tempdir_in(&self.directory)?
345            .keep();
346        let destination = WorkspaceFile::open_delivery(&directory, Path::new(&self.name))?;
347        self.location.move_opened_to_directory_with_max_links(
348            &self.file,
349            &destination,
350            expected_links_before_unlink,
351        )?;
352        let previous_location = std::mem::replace(&mut self.location, destination);
353        self.directory = directory.clone();
354        let removed = (|| {
355            previous_location.sync_parent()?;
356            self.location.sync_parent()?;
357            if !self.matches_path()? {
358                return Err(invalid("retired uninstall entry has a different identity"));
359            }
360            let (digest, version) = stable_hash_with_max_links(
361                &mut self.file,
362                Some(self.version.length),
363                expected_links_before_unlink,
364            )?;
365            if digest != self.digest
366                || version.length != self.version.length
367                || version.modified != self.version.modified
368                || version.nlink != expected_links_before_unlink
369            {
370                return Err(invalid("delivery file changed during uninstall retirement"));
371            }
372            self.version = version;
373            self.verify_owned()?;
374            self.location
375                .unlink_opened_with_max_links(&self.file, expected_links_before_unlink)?;
376            *unlinked = true;
377            if self.file.metadata()?.nlink() != expected_remaining_links {
378                return Err(invalid("delivery file retained another link after unlink"));
379            }
380            self.location.sync_parent()
381        })();
382        removed.map_err(|error| {
383            let detail = if *unlinked {
384                format!("file entry was unlinked, but its final identity or durability check failed: {error}; recovery directory {}", directory.display())
385            } else {
386                format!("{error}; inspect retained recovery location {}", directory.join(&self.name).display())
387            };
388            io::Error::new(error.kind(), detail)
389        })?;
390        if let Err(error) = std::fs::remove_dir(&directory) {
391            eprintln!(
392                "Removed owned file; empty recovery directory retained at {}: {error}",
393                directory.display()
394            );
395        }
396        Ok(())
397    }
398
399    #[cfg(windows)]
400    pub fn verify_owned(&mut self) -> io::Result<()> {
401        self.verify()
402    }
403
404    #[cfg(windows)]
405    pub fn remove_checked(&mut self, unlinked: &mut bool) -> io::Result<()> {
406        self.remove_sibling_checked(0, false, unlinked)
407    }
408
409    /// Windows binaries stay single-link; reject hard-linked sibling removal parameters.
410    #[cfg(windows)]
411    pub fn remove_sibling_checked(
412        &mut self,
413        expected_remaining_links: u64,
414        prior_sibling_unlinked: bool,
415        unlinked: &mut bool,
416    ) -> io::Result<()> {
417        if expected_remaining_links != 0 || prior_sibling_unlinked {
418            return Err(invalid(
419                "hard-linked sibling removal is unsupported on Windows",
420            ));
421        }
422        *unlinked = false;
423        self.verify()?;
424        self.move_to_vacant(&Self::recovery_name())?;
425        *unlinked = true;
426        codewhale_config::private_directory::mark_windows_file_handle_for_deletion(&self.file)
427            .map_err(|error| {
428                io::Error::other(format!(
429                    "{error:#}; retired entry retained at {}",
430                    self.directory.join(&self.name).display()
431                ))
432            })
433    }
434
435    pub fn recovery_name() -> String {
436        format!(".codewhale-host-recovery-{}", uuid::Uuid::new_v4())
437    }
438
439    pub fn name(&self) -> &str {
440        &self.name
441    }
442    pub fn sha256(&self) -> &str {
443        &self.digest
444    }
445
446    fn matches_path(&self) -> io::Result<bool> {
447        self.matches_path_with_max_links(self.expected_max_links())
448    }
449
450    fn matches_path_with_max_links(&self, max_links: u64) -> io::Result<bool> {
451        if !same_file(
452            &self.file,
453            &self.location.identity_probe_with_max_links(max_links)?,
454        )? {
455            return Ok(false);
456        }
457        // An anchored Unix fd survives a renamed parent. Rewalk the original
458        // captured absolute root without canonicalizing new links, so a new
459        // directory at that pathname cannot inherit the installation receipt.
460        let current = WorkspaceFile::open_delivery(&self.directory, Path::new(&self.name))?;
461        same_file(
462            &self.file,
463            &current.identity_probe_with_max_links(max_links)?,
464        )
465    }
466
467    pub fn verify(&mut self) -> io::Result<()> {
468        if !self.matches_path()? {
469            return Err(invalid("delivery pathname identity changed"));
470        }
471        let max_links = self.expected_max_links();
472        let (digest, version) =
473            stable_hash_with_max_links(&mut self.file, Some(self.version.length), max_links)?;
474        if digest != self.digest || version != self.version {
475            return Err(invalid("delivery file changed since capture"));
476        }
477        if !self.matches_path()? {
478            return Err(invalid("delivery pathname changed while verifying"));
479        }
480        Ok(())
481    }
482
483    /// Reads and validates the same handle used for its digest, without reopening.
484    pub fn read_bounded(&mut self, maximum: usize) -> io::Result<Vec<u8>> {
485        if self.version.length > maximum as u64 {
486            return Err(invalid("delivery receipt exceeds size limit"));
487        }
488        self.verify()?;
489        self.file.rewind()?;
490        let mut bytes = Vec::new();
491        (&mut self.file)
492            .take(self.version.length.saturating_add(1))
493            .read_to_end(&mut bytes)?;
494        if bytes.len() > maximum || crate::hashing::sha256_hex(&bytes) != self.digest {
495            return Err(invalid("delivery receipt changed while reading"));
496        }
497        self.verify()?;
498        Ok(bytes)
499    }
500
501    /// Moves to a vacant sibling. On a post-move refusal `name()` still names
502    /// the recovery entry; callers must retain/report it and recover without
503    /// replacing any concurrent destination.
504    pub fn move_to_vacant(&mut self, name: &str) -> io::Result<()> {
505        self.verify()?;
506        let destination = self.location.sibling(name)?;
507        self.location
508            .move_opened_to_sibling(&self.file, &destination)?;
509        self.location = destination;
510        self.name = name.into();
511        // Journal the completed move before any fallible durability/validation.
512        self.location.sync_parent()?;
513        if !self.matches_path()? {
514            return Err(invalid("retired delivery entry has a different identity"));
515        }
516        let (digest, version) = stable_hash(&mut self.file, Some(self.version.length))?;
517        if digest != self.digest
518            || version.length != self.version.length
519            || version.modified != self.version.modified
520        {
521            return Err(invalid("delivery file changed during retirement"));
522        }
523        // A successful rename may update ctime; it does not change file bytes.
524        self.version = version;
525        self.verify()
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532
533    #[test]
534    fn hash_budget_refuses_a_growing_reader_without_waiting_for_eof() {
535        struct AppendingReader {
536            read_bytes: u64,
537        }
538        impl Read for AppendingReader {
539            fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
540                bytes.fill(b'x');
541                self.read_bytes += bytes.len() as u64;
542                Ok(bytes.len())
543            }
544        }
545        for length in [0, 5, 64 * 1024] {
546            let mut reader = AppendingReader { read_bytes: 0 };
547            assert!(hash_exact_length(&mut reader, length).is_err());
548            assert_eq!(reader.read_bytes, length + 1);
549        }
550        let mut shortened = &b"short"[..];
551        assert!(hash_exact_length(&mut shortened, 6).is_err());
552        let mut exact = &b"owned"[..];
553        assert_eq!(
554            hash_exact_length(&mut exact, 5).unwrap(),
555            crate::hashing::sha256_hex(b"owned")
556        );
557    }
558
559    #[cfg(unix)]
560    #[test]
561    fn grown_receipt_is_refused_by_captured_and_requested_limits() {
562        let root = tempfile::tempdir().unwrap();
563        let path = root.path().join("receipt");
564        std::fs::write(&path, b"owned").unwrap();
565        let mut captured = GuardedFile::open_bounded(root.path(), "receipt", 5)
566            .unwrap()
567            .unwrap();
568        std::fs::write(&path, vec![b'x'; 64 * 1024 + 1]).unwrap();
569        assert!(captured.verify().is_err());
570        assert!(captured.read_bounded(64 * 1024).is_err());
571        assert!(GuardedFile::open_bounded(root.path(), "receipt", 64 * 1024).is_err());
572        let mut opened = File::open(&path).unwrap();
573        assert!(stable_hash(&mut opened, Some(64 * 1024)).is_err());
574        assert_eq!(std::fs::metadata(&path).unwrap().len(), 64 * 1024 + 1);
575    }
576
577    #[test]
578    fn bounded_receipt_and_no_clobber_move_keep_canonical_ownership() {
579        let root = tempfile::tempdir().unwrap();
580        std::fs::write(root.path().join("receipt"), b"owned").unwrap();
581        assert!(GuardedFile::open_bounded(root.path(), "receipt", 4).is_err());
582        let mut file = GuardedFile::open_bounded(root.path(), "receipt", 5)
583            .unwrap()
584            .unwrap();
585        assert_eq!(file.read_bounded(5).unwrap(), b"owned");
586        std::fs::write(root.path().join("taken"), b"foreign").unwrap();
587        assert!(file.move_to_vacant("taken").is_err());
588        assert_eq!(file.name(), "receipt");
589        assert_eq!(
590            std::fs::read(root.path().join("taken")).unwrap(),
591            b"foreign"
592        );
593        file.move_to_vacant("retired").unwrap();
594        assert_eq!(file.read_bounded(5).unwrap(), b"owned");
595        assert!(!root.path().join("receipt").exists());
596    }
597
598    #[cfg(unix)]
599    #[test]
600    fn nofollow_reader_refuses_symlinks_and_multiple_links() {
601        use std::os::unix::fs::symlink;
602        let root = tempfile::tempdir().unwrap();
603        let outside = tempfile::tempdir().unwrap();
604        let source = outside.path().join("untouched");
605        std::fs::write(&source, b"foreign").unwrap();
606        symlink(&source, root.path().join("linked")).unwrap();
607        std::fs::hard_link(&source, root.path().join("hardlinked")).unwrap();
608        for name in ["linked", "hardlinked"] {
609            assert!(GuardedFile::open(root.path(), name).is_err());
610            assert!(GuardedFile::open_bounded(root.path(), name, 64 * 1024).is_err());
611        }
612        assert_eq!(std::fs::read(source).unwrap(), b"foreign");
613    }
614
615    #[cfg(unix)]
616    #[test]
617    fn captured_receipt_cannot_be_reopened_through_a_swapped_symlink() {
618        use std::os::unix::fs::symlink;
619        let root = tempfile::tempdir().unwrap();
620        let outside = tempfile::tempdir().unwrap();
621        std::fs::write(root.path().join("receipt"), b"owned").unwrap();
622        std::fs::write(outside.path().join("foreign"), b"owned").unwrap();
623        let mut file = GuardedFile::open_bounded(root.path(), "receipt", 64 * 1024)
624            .unwrap()
625            .unwrap();
626        std::fs::rename(root.path().join("receipt"), root.path().join("original")).unwrap();
627        symlink(outside.path().join("foreign"), root.path().join("receipt")).unwrap();
628        assert!(file.read_bounded(64 * 1024).is_err());
629        assert_eq!(
630            std::fs::read(root.path().join("original")).unwrap(),
631            b"owned"
632        );
633        assert_eq!(
634            std::fs::read(outside.path().join("foreign")).unwrap(),
635            b"owned"
636        );
637    }
638
639    #[cfg(unix)]
640    #[test]
641    fn replaced_parent_cannot_inherit_a_retained_payload_receipt() {
642        let root = tempfile::tempdir().unwrap();
643        let prefix = root.path().join("prefix");
644        std::fs::create_dir(&prefix).unwrap();
645        std::fs::write(prefix.join("host"), b"old").unwrap();
646        let mut file = GuardedFile::open(&prefix, "host").unwrap().unwrap();
647        std::fs::rename(&prefix, root.path().join("original-prefix")).unwrap();
648        std::fs::create_dir(&prefix).unwrap();
649        std::fs::write(prefix.join("host"), b"old").unwrap();
650        assert!(file.verify().is_err());
651        assert!(file.move_to_vacant("backup").is_err());
652        assert_eq!(std::fs::read(prefix.join("host")).unwrap(), b"old");
653        assert_eq!(
654            std::fs::read(root.path().join("original-prefix/host")).unwrap(),
655            b"old"
656        );
657    }
658
659    #[cfg(windows)]
660    #[test]
661    fn retained_windows_reader_denies_writer_and_parent_replacement() {
662        let root = tempfile::tempdir().unwrap();
663        let prefix = root.path().join("prefix");
664        std::fs::create_dir(&prefix).unwrap();
665        std::fs::write(prefix.join("host"), b"old").unwrap();
666        let mut file = GuardedFile::open(&prefix, "host").unwrap().unwrap();
667        assert!(std::fs::write(prefix.join("host"), b"changed").is_err());
668        assert!(std::fs::rename(&prefix, root.path().join("swapped")).is_err());
669        file.move_to_vacant("backup").unwrap();
670        assert_eq!(file.read_bounded(3).unwrap(), b"old");
671    }
672
673    #[cfg(unix)]
674    #[test]
675    fn command_siblings_allow_owned_pair_and_reject_external_hard_links() {
676        use std::os::unix::fs::PermissionsExt;
677
678        let root = tempfile::tempdir().unwrap();
679        std::fs::set_permissions(root.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
680        let outside = tempfile::tempdir().unwrap();
681        let primary = root.path().join("codewhale");
682        let alias = root.path().join("codew");
683        std::fs::write(&primary, b"release-bytes").unwrap();
684        std::fs::set_permissions(&primary, std::fs::Permissions::from_mode(0o755)).unwrap();
685        std::fs::hard_link(&primary, &alias).unwrap();
686
687        assert!(GuardedFile::open(root.path(), "codewhale").is_err());
688        assert!(GuardedFile::open_bounded(root.path(), "codewhale", 64).is_err());
689        assert!(GuardedFile::open_command_siblings(root.path(), &["codewhale"]).is_err());
690
691        let mut siblings =
692            GuardedFile::open_command_siblings(root.path(), &["codewhale", "codew"]).unwrap();
693        assert_eq!(siblings.len(), 2);
694        assert!(
695            siblings["codewhale"]
696                .same_inode(&siblings["codew"])
697                .unwrap()
698        );
699
700        let third = outside.path().join("external");
701        std::fs::hard_link(&primary, &third).unwrap();
702        assert!(GuardedFile::open_command_siblings(root.path(), &["codewhale", "codew"]).is_err());
703        assert!(siblings.get_mut("codew").unwrap().verify().is_err());
704        let mut unlinked = false;
705        assert!(
706            siblings
707                .get_mut("codew")
708                .unwrap()
709                .remove_sibling_checked(1, false, &mut unlinked)
710                .is_err()
711        );
712        assert!(!unlinked);
713        assert!(primary.exists());
714        assert!(alias.exists());
715
716        std::fs::remove_file(&third).unwrap();
717        let mut siblings =
718            GuardedFile::open_command_siblings(root.path(), &["codewhale", "codew"]).unwrap();
719        let mut unlinked_alias = false;
720        siblings
721            .get_mut("codew")
722            .unwrap()
723            .remove_sibling_checked(1, false, &mut unlinked_alias)
724            .unwrap();
725        assert!(unlinked_alias);
726        assert!(!alias.exists());
727        assert!(primary.exists());
728
729        let mut unlinked_primary = false;
730        siblings
731            .get_mut("codewhale")
732            .unwrap()
733            .remove_sibling_checked(0, true, &mut unlinked_primary)
734            .unwrap();
735        assert!(unlinked_primary);
736        assert!(!primary.exists());
737    }
738
739    #[cfg(unix)]
740    #[test]
741    fn reanchored_sibling_refuses_newly_added_hard_link_before_final_unlink() {
742        use std::os::unix::fs::PermissionsExt;
743
744        let root = tempfile::tempdir().unwrap();
745        std::fs::set_permissions(root.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
746        let outside = tempfile::tempdir().unwrap();
747        let primary = root.path().join("codewhale");
748        let alias = root.path().join("codew");
749        std::fs::write(&primary, b"release-bytes").unwrap();
750        std::fs::set_permissions(&primary, std::fs::Permissions::from_mode(0o755)).unwrap();
751        std::fs::hard_link(&primary, &alias).unwrap();
752
753        let mut siblings =
754            GuardedFile::open_command_siblings(root.path(), &["codewhale", "codew"]).unwrap();
755        let mut unlinked_alias = false;
756        siblings
757            .get_mut("codew")
758            .unwrap()
759            .remove_sibling_checked(1, false, &mut unlinked_alias)
760            .unwrap();
761        assert!(unlinked_alias);
762
763        let third = outside.path().join("raced-link");
764        std::fs::hard_link(&primary, &third).unwrap();
765        let mut unlinked_primary = false;
766        assert!(
767            siblings
768                .get_mut("codewhale")
769                .unwrap()
770                .remove_sibling_checked(0, true, &mut unlinked_primary)
771                .is_err()
772        );
773        assert!(!unlinked_primary);
774        assert!(primary.exists());
775    }
776}