Skip to main content

ic_testkit/artifacts/
digest.rs

1use sha2::{Digest, Sha256};
2use std::{
3    borrow::Cow,
4    collections::BTreeSet,
5    ffi::OsStr,
6    fmt::Write as _,
7    fs::{self, File},
8    io::{self, Read as _},
9    path::{Path, PathBuf},
10};
11
12#[cfg(unix)]
13use std::os::unix::{ffi::OsStrExt as _, fs::MetadataExt as _};
14#[cfg(windows)]
15use std::os::windows::ffi::OsStrExt as _;
16
17#[derive(Debug)]
18struct AtomicCopyErrorContext {
19    source_path: PathBuf,
20    destination_path: PathBuf,
21    source: io::Error,
22}
23
24impl std::fmt::Display for AtomicCopyErrorContext {
25    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        write!(
27            formatter,
28            "failed to atomically copy {} to {}: {}",
29            self.source_path.display(),
30            self.destination_path.display(),
31            self.source
32        )
33    }
34}
35
36impl std::error::Error for AtomicCopyErrorContext {
37    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
38        Some(&self.source)
39    }
40}
41
42/// SHA-256 digest of one deterministic artifact-input set.
43#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44pub struct InputDigest([u8; 32]);
45
46impl InputDigest {
47    /// Borrow the raw SHA-256 bytes.
48    #[must_use]
49    pub const fn as_bytes(&self) -> &[u8; 32] {
50        &self.0
51    }
52
53    /// Render the digest as lowercase hexadecimal.
54    #[must_use]
55    pub fn to_hex(self) -> String {
56        let mut hex = String::with_capacity(64);
57        write!(hex, "{self}").expect("writing to a String cannot fail");
58        hex
59    }
60}
61
62impl std::fmt::Display for InputDigest {
63    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        for byte in self.0 {
65            write!(formatter, "{byte:02x}")?;
66        }
67        Ok(())
68    }
69}
70
71pub(super) struct InputHasher {
72    state: Sha256,
73    read_buffer: Vec<u8>,
74}
75
76impl InputHasher {
77    pub(super) fn new(domain: &str) -> Self {
78        let mut hasher = Self {
79            state: Sha256::new(),
80            read_buffer: Vec::new(),
81        };
82        hasher.field("domain", domain.as_bytes());
83        hasher
84    }
85
86    pub(super) fn field(&mut self, label: &str, value: &[u8]) {
87        self.field_header(
88            label,
89            u64::try_from(value.len()).expect("input value length must fit in u64"),
90        );
91        self.state.update(value);
92    }
93
94    fn field_header(&mut self, label: &str, value_len: u64) {
95        self.state.update(
96            u64::try_from(label.len())
97                .expect("input label length must fit in u64")
98                .to_le_bytes(),
99        );
100        self.state.update(label.as_bytes());
101        self.state.update(value_len.to_le_bytes());
102    }
103
104    fn file_field(&mut self, label: &str, path: &Path) -> io::Result<u64> {
105        let mut file = File::open(path)?;
106        let expected_len = file.metadata()?.len();
107        self.field_header(label, expected_len);
108
109        let mut actual_len = 0_u64;
110        // Small sources need only their declared length; large artifacts use bounded reads.
111        // Even empty files need a nonempty read buffer to detect growth.
112        let buffer_len = usize::try_from(expected_len.clamp(1, 64 * 1024))
113            .expect("bounded artifact buffer length must fit in usize");
114        // A tree hashes many files with one hasher. Retain its bounded scratch
115        // space, reading only this file's window and hashing only returned bytes.
116        if self.read_buffer.len() < buffer_len {
117            // Geometric growth near the read limit would retain almost twice
118            // the scratch space required by any file in this hashing pass.
119            self.read_buffer
120                .reserve_exact(buffer_len - self.read_buffer.len());
121            self.read_buffer.resize(buffer_len, 0);
122        }
123        loop {
124            let read = file.read(&mut self.read_buffer[..buffer_len])?;
125            if read == 0 {
126                break;
127            }
128            actual_len = actual_len
129                .saturating_add(u64::try_from(read).expect("artifact read length must fit in u64"));
130            if actual_len > expected_len {
131                break;
132            }
133            self.state.update(&self.read_buffer[..read]);
134        }
135        if actual_len != expected_len {
136            return Err(io::Error::new(
137                io::ErrorKind::InvalidData,
138                format!(
139                    "file changed size while hashing: expected {expected_len} bytes, read {actual_len}"
140                ),
141            ));
142        }
143        Ok(actual_len)
144    }
145
146    pub(super) fn finish(self) -> InputDigest {
147        InputDigest(self.state.finalize().into())
148    }
149}
150
151pub(super) fn digest_bytes(domain: &str, value: &[u8]) -> InputDigest {
152    let mut hasher = InputHasher::new(domain);
153    hasher.field("content", value);
154    hasher.finish()
155}
156
157#[derive(Clone, Copy, Debug, Eq, PartialEq)]
158pub(super) struct FileDigest {
159    pub(super) bytes: u64,
160    pub(super) digest: InputDigest,
161}
162
163pub(super) fn digest_file(domain: &str, path: &Path) -> io::Result<FileDigest> {
164    let mut hasher = InputHasher::new(domain);
165    let bytes = hasher.file_field("content", path)?;
166    Ok(FileDigest {
167        bytes,
168        digest: hasher.finish(),
169    })
170}
171
172/// Read a UTF-8 stamp without allocating or reading an oversized sidecar in full.
173/// An oversized stamp is stale; other read and decoding errors reach the caller.
174pub(super) fn read_stamp_with_limit(path: &Path, maximum_len: usize) -> io::Result<Option<String>> {
175    read_file_with_limit(path, maximum_len)?
176        .map(|contents| {
177            String::from_utf8(contents)
178                .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
179        })
180        .transpose()
181}
182
183/// Read at most the format's maximum length plus one byte to detect oversized files.
184pub(super) fn read_file_with_limit(path: &Path, maximum_len: usize) -> io::Result<Option<Vec<u8>>> {
185    use ic_host_artifacts::artifact::ArtifactError;
186    use ic_host_fs::read::read_file;
187
188    // The shared library owns bounded reading and allocation. Cache policy owns
189    // the meaning of overflow: an oversized stamp or manifest is a cache miss.
190    match read_file(path, maximum_len) {
191        Ok(contents) => Ok(Some(contents)),
192        Err(ArtifactError::LimitExceeded { .. }) => Ok(None),
193        Err(ArtifactError::NotRegularFile) => Err(io::Error::new(
194            io::ErrorKind::InvalidData,
195            ArtifactError::NotRegularFile,
196        )),
197        Err(error) => Err(error.into()),
198    }
199}
200
201/// Only reuse an independent, caller-owned writable destination. The caller
202/// coordinates other writers and supplies a digest from a verified cache entry.
203pub(super) fn destination_matches_digest(
204    domain: &str,
205    destination: &Path,
206    expected: &FileDigest,
207) -> bool {
208    destination_is_reusable(destination, expected.bytes)
209        && digest_file(domain, destination).is_ok_and(|actual| actual == *expected)
210}
211
212pub(super) fn destination_matches_bytes(destination: &Path, expected: &[u8]) -> bool {
213    destination_is_reusable(
214        destination,
215        u64::try_from(expected.len()).expect("artifact byte length must fit in u64"),
216    ) && read_file_with_limit(destination, expected.len())
217        .is_ok_and(|actual| actual.as_deref() == Some(expected))
218}
219
220fn destination_is_reusable(destination: &Path, expected_bytes: u64) -> bool {
221    #[cfg(unix)]
222    {
223        let Ok(metadata) = fs::symlink_metadata(destination) else {
224            return false;
225        };
226        // SAFETY: geteuid takes no pointers and has no failure case.
227        let effective_uid = unsafe { libc::geteuid() };
228        // Detach links and normalize foreign-owned, restricted or executable
229        // files, even when their bytes match a retained artifact.
230        if !metadata.file_type().is_file()
231            || metadata.nlink() != 1
232            || metadata.uid() != effective_uid
233            || metadata.mode() & 0o600 != 0o600
234            || metadata.mode() & 0o7111 != 0
235            || metadata.len() != expected_bytes
236        {
237            return false;
238        }
239        true
240    }
241    #[cfg(not(unix))]
242    {
243        // Preserve replacement where a portable single-link check is unavailable.
244        let _ = (destination, expected_bytes);
245        false
246    }
247}
248
249pub(super) fn digest_labeled_paths<L: AsRef<Path>, P: AsRef<Path>>(
250    domain: &str,
251    paths: impl IntoIterator<Item = (L, P)>,
252    excluded_roots: &[PathBuf],
253) -> io::Result<InputDigest> {
254    let mut paths = paths.into_iter().collect::<Vec<_>>();
255    paths.sort_by(|(left, _), (right, _)| {
256        os_bytes(left.as_ref().as_os_str()).cmp(&os_bytes(right.as_ref().as_os_str()))
257    });
258
259    let excluded_roots = excluded_roots
260        .iter()
261        .filter_map(|path| path.canonicalize().ok())
262        .collect::<Vec<_>>();
263    let mut visited_directories = BTreeSet::new();
264    let mut hasher = InputHasher::new(domain);
265    for (label, path) in paths {
266        hash_path(
267            &mut hasher,
268            label.as_ref(),
269            path.as_ref(),
270            &excluded_roots,
271            &mut visited_directories,
272            true,
273            None,
274        )?;
275    }
276    Ok(hasher.finish())
277}
278
279#[derive(Default)]
280pub(super) struct LabeledPathDigestCache {
281    entries: Vec<LabeledPathDigestCacheEntry>,
282}
283
284struct LabeledPathDigestCacheEntry {
285    domain: String,
286    label: PathBuf,
287    path: PathBuf,
288    canonical_root: PathBuf,
289    excluded_roots: Vec<PathBuf>,
290    traversed_external_path: bool,
291    digest: InputDigest,
292}
293
294struct HashPathTrace {
295    canonical_root: PathBuf,
296    traversed_external_path: bool,
297}
298
299pub(super) fn digest_labeled_paths_composable<'a>(
300    domain: &str,
301    paths: impl IntoIterator<Item = (&'a Path, &'a Path)>,
302    excluded_roots: &[PathBuf],
303    cache: &mut LabeledPathDigestCache,
304) -> io::Result<InputDigest> {
305    let mut paths = paths.into_iter().collect::<Vec<_>>();
306    paths.sort_by(|(left, _), (right, _)| {
307        os_bytes(left.as_os_str()).cmp(&os_bytes(right.as_os_str()))
308    });
309    let excluded_roots = excluded_roots
310        .iter()
311        .filter_map(|path| path.canonicalize().ok())
312        .collect::<Vec<_>>();
313    let mut hasher = InputHasher::new(&format!("{domain}/composable-v1"));
314    for (label, path) in paths {
315        let digest = cache.digest_root(domain, label, path, &excluded_roots)?;
316        hasher.field("input-label", &os_bytes(label.as_os_str()));
317        hasher.field("input-digest", digest.as_bytes());
318    }
319    Ok(hasher.finish())
320}
321
322impl LabeledPathDigestCache {
323    fn digest_root(
324        &mut self,
325        domain: &str,
326        label: &Path,
327        path: &Path,
328        excluded_roots: &[PathBuf],
329    ) -> io::Result<InputDigest> {
330        let canonical_root = path.canonicalize()?;
331        if let Some(entry) = self.entries.iter().find(|entry| {
332            entry.domain == domain
333                && entry.label == label
334                && entry.path == path
335                && entry.excluded_roots.iter().eq(effective_root_exclusions(
336                    &entry.canonical_root,
337                    excluded_roots,
338                    entry.traversed_external_path,
339                ))
340        }) {
341            return Ok(entry.digest);
342        }
343        let mut hasher = InputHasher::new(&format!("{domain}/root-v1"));
344        let mut trace = HashPathTrace {
345            canonical_root: canonical_root.clone(),
346            traversed_external_path: false,
347        };
348        hash_path(
349            &mut hasher,
350            label,
351            path,
352            excluded_roots,
353            &mut BTreeSet::new(),
354            true,
355            Some(&mut trace),
356        )?;
357        let digest = hasher.finish();
358        self.entries.push(LabeledPathDigestCacheEntry {
359            domain: domain.to_owned(),
360            label: label.to_owned(),
361            path: path.to_owned(),
362            canonical_root,
363            excluded_roots: effective_root_exclusions(
364                &trace.canonical_root,
365                excluded_roots,
366                trace.traversed_external_path,
367            )
368            .cloned()
369            .collect(),
370            traversed_external_path: trace.traversed_external_path,
371            digest,
372        });
373        Ok(digest)
374    }
375}
376
377fn effective_root_exclusions<'a>(
378    canonical_root: &'a Path,
379    excluded_roots: &'a [PathBuf],
380    traversed_external_path: bool,
381) -> impl Iterator<Item = &'a PathBuf> {
382    excluded_roots.iter().filter(move |excluded| {
383        traversed_external_path
384            || excluded.starts_with(canonical_root)
385            || canonical_root.starts_with(excluded)
386    })
387}
388
389fn hash_path(
390    hasher: &mut InputHasher,
391    label: &Path,
392    path: &Path,
393    excluded_roots: &[PathBuf],
394    visited_directories: &mut BTreeSet<PathBuf>,
395    declared_root: bool,
396    mut trace: Option<&mut HashPathTrace>,
397) -> io::Result<()> {
398    let context =
399        |error: io::Error| io::Error::new(error.kind(), format!("{}: {error}", path.display()));
400    let canonical = path.canonicalize().map_err(context)?;
401    if let Some(trace) = &mut trace
402        && !canonical.starts_with(&trace.canonical_root)
403    {
404        trace.traversed_external_path = true;
405    }
406    if excluded_roots
407        .iter()
408        .any(|excluded| canonical.starts_with(excluded))
409    {
410        if declared_root {
411            return Err(io::Error::new(
412                io::ErrorKind::InvalidInput,
413                format!(
414                    "declared input is located inside an excluded cache root: {}",
415                    path.display()
416                ),
417            ));
418        }
419        return Ok(());
420    }
421
422    let metadata = fs::metadata(path).map_err(context)?;
423    let label_bytes = os_bytes(label.as_os_str());
424    if metadata.is_file() {
425        hasher.field("file-path", &label_bytes);
426        hasher.file_field("file-content", path).map_err(context)?;
427        return Ok(());
428    }
429    if !metadata.is_dir() {
430        return Err(io::Error::new(
431            io::ErrorKind::InvalidInput,
432            format!(
433                "watched input is not a regular file or directory: {}",
434                path.display()
435            ),
436        ));
437    }
438
439    hasher.field("directory", &label_bytes);
440    if !visited_directories.insert(canonical) {
441        hasher.field("directory-already-visited", &label_bytes);
442        return Ok(());
443    }
444
445    let mut entries = fs::read_dir(path)
446        .map_err(context)?
447        .map(|entry| entry.map(|entry| entry.file_name()))
448        .collect::<Result<Vec<_>, _>>()
449        .map_err(context)?;
450    // Unix names already own their native byte ordering. Compare borrowed
451    // bytes rather than allocating a second name and cached key per entry.
452    #[cfg(unix)]
453    entries.sort_unstable_by(|left, right| os_bytes(left).cmp(&os_bytes(right)));
454    // Other hosts may need an allocated native encoding; compute it once.
455    #[cfg(not(unix))]
456    entries.sort_by_cached_key(|name| os_bytes(name).into_owned());
457    for name in entries {
458        hash_path(
459            hasher,
460            &label.join(&name),
461            &path.join(&name),
462            excluded_roots,
463            visited_directories,
464            false,
465            trace.as_deref_mut(),
466        )?;
467    }
468    Ok(())
469}
470
471pub(super) fn copy_file_atomic(source: &Path, destination: &Path) -> io::Result<u64> {
472    let result = (|| {
473        let mut source_file = File::open(source)?;
474        ic_host_fs::durable::write_with(destination, |destination_file| {
475            io::copy(&mut source_file, destination_file)
476        })
477    })();
478    result.map_err(|source_error| {
479        io::Error::new(
480            source_error.kind(),
481            AtomicCopyErrorContext {
482                source_path: source.to_owned(),
483                destination_path: destination.to_owned(),
484                source: source_error,
485            },
486        )
487    })
488}
489
490#[cfg(unix)]
491pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
492    Cow::Borrowed(value.as_bytes())
493}
494
495#[cfg(windows)]
496pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
497    Cow::Owned(value.encode_wide().flat_map(u16::to_le_bytes).collect())
498}
499
500#[cfg(not(any(unix, windows)))]
501pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
502    Cow::Owned(value.to_string_lossy().as_bytes().to_vec())
503}
504
505#[cfg(test)]
506mod tests {
507    use super::{
508        LabeledPathDigestCache, copy_file_atomic, digest_bytes, digest_file,
509        digest_labeled_paths_composable,
510    };
511    use crate::artifacts::test_support::unique_temp_directory;
512    use std::{fs, path::PathBuf};
513
514    #[cfg(unix)]
515    use super::{InputHasher, digest_labeled_paths};
516    #[cfg(unix)]
517    use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _};
518    #[cfg(windows)]
519    use std::{ffi::OsString, os::windows::ffi::OsStringExt as _};
520
521    #[test]
522    fn digest_text_preserves_lowercase_hex_and_leading_zeroes() {
523        let digest = super::InputDigest(std::array::from_fn(|index| {
524            u8::try_from(index).expect("digest byte index must fit")
525        }));
526        let expected = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
527        assert_eq!(digest.to_hex(), expected);
528        assert_eq!(digest.to_string(), expected);
529        assert_eq!(super::InputDigest([0xff; 32]).to_string(), "ff".repeat(32));
530    }
531
532    #[test]
533    #[cfg(unix)]
534    fn labeled_path_digests_preserve_native_names_and_sorted_order() {
535        let names: &[&[u8]] = &[
536            b"\xce\xbb",
537            #[cfg(target_os = "linux")]
538            b"\xff",
539        ];
540        for &name in names {
541            let root = unique_temp_directory("native-path-digest");
542            let tree = root.join("tree");
543            fs::create_dir_all(tree.join("nested")).unwrap();
544            fs::write(tree.join(OsStr::from_bytes(name)), b"native").unwrap();
545            fs::write(tree.join("nested/z"), b"last").unwrap();
546            fs::write(tree.join("a"), b"first").unwrap();
547            fs::write(root.join("top"), b"top").unwrap();
548            let mut paths = [
549                (PathBuf::from("tree"), tree),
550                (PathBuf::from("aaa"), root.join("top")),
551            ];
552
553            let tree_fields = |hasher: &mut InputHasher| {
554                hasher.field("directory", b"tree");
555                hasher.field("file-path", b"tree/a");
556                hasher.field("file-content", b"first");
557                hasher.field("directory", b"tree/nested");
558                hasher.field("file-path", b"tree/nested/z");
559                hasher.field("file-content", b"last");
560                hasher.field("file-path", &[b"tree/".as_slice(), name].concat());
561                hasher.field("file-content", b"native");
562            };
563            let mut expected = InputHasher::new("native-path-test-v1");
564            expected.field("file-path", b"aaa");
565            expected.field("file-content", b"top");
566            tree_fields(&mut expected);
567            let expected = expected.finish();
568
569            let mut top = InputHasher::new("native-path-test-v1/root-v1");
570            top.field("file-path", b"aaa");
571            top.field("file-content", b"top");
572            let mut tree = InputHasher::new("native-path-test-v1/root-v1");
573            tree_fields(&mut tree);
574            let mut composable = InputHasher::new("native-path-test-v1/composable-v1");
575            composable.field("input-label", b"aaa");
576            composable.field("input-digest", top.finish().as_bytes());
577            composable.field("input-label", b"tree");
578            composable.field("input-digest", tree.finish().as_bytes());
579            let composable = composable.finish();
580
581            for _ in 0..2 {
582                assert_eq!(
583                    digest_labeled_paths(
584                        "native-path-test-v1",
585                        paths.iter().map(|(label, path)| (label, path)),
586                        &[],
587                    )
588                    .unwrap(),
589                    expected,
590                );
591                assert_eq!(
592                    digest_labeled_paths_composable(
593                        "native-path-test-v1",
594                        paths
595                            .iter()
596                            .map(|(label, path)| (label.as_path(), path.as_path())),
597                        &[],
598                        &mut LabeledPathDigestCache::default(),
599                    )
600                    .unwrap(),
601                    composable,
602                );
603                paths.reverse();
604            }
605            fs::remove_dir_all(root).unwrap();
606        }
607    }
608
609    #[test]
610    #[cfg(unix)]
611    fn native_bytes_preserve_non_utf8_without_a_filesystem_roundtrip() {
612        assert_eq!(
613            super::os_bytes(OsStr::from_bytes(b"name\xff")).as_ref(),
614            b"name\xff"
615        );
616    }
617
618    #[test]
619    #[cfg(windows)]
620    fn native_names_preserve_utf16_little_endian_encoding() {
621        let value = OsString::from_wide(&[0x0061, 0xd800, 0x0100]);
622        assert_eq!(super::os_bytes(&value).as_ref(), &[0x61, 0, 0, 0xd8, 0, 1]);
623    }
624
625    #[test]
626    fn streamed_fields_preserve_bytes_across_different_file_sizes() {
627        let root = unique_temp_directory("streamed-field-sizes");
628        let source = root.join("source");
629        let contents = (0..192 * 1024 + 37)
630            .map(|index| u8::try_from(index % 251).unwrap())
631            .collect::<Vec<_>>();
632        let mut streamed = super::InputHasher::new("streamed-fields-v1");
633        let mut expected = super::InputHasher::new("streamed-fields-v1");
634        for length in [1, 64 * 1024 - 1, contents.len(), 0, 7, 1024, 64 * 1024 + 1] {
635            let bytes = &contents[..length];
636            fs::write(&source, bytes).unwrap();
637            assert_eq!(streamed.file_field("part", &source).unwrap(), length as u64);
638            expected.field("part", bytes);
639        }
640        assert_eq!(streamed.finish(), expected.finish());
641        fs::remove_dir_all(root).unwrap();
642    }
643
644    #[test]
645    fn streaming_digest_and_atomic_copy_preserve_exact_bytes() {
646        let root = unique_temp_directory("streaming-digest");
647        let source = root.join("source");
648        let destination = root.join("destination");
649        let mut contents = vec![0_u8; 192 * 1024 + 37];
650        for (index, byte) in contents.iter_mut().enumerate() {
651            *byte = u8::try_from(index % 251).expect("test byte must fit");
652        }
653        for length in [
654            0,
655            1,
656            1024,
657            16 * 1024,
658            64 * 1024 - 1,
659            64 * 1024,
660            64 * 1024 + 1,
661            contents.len(),
662        ] {
663            let data = &contents[..length];
664            fs::write(&source, data).expect("write source");
665            let streamed = digest_file("streaming-test-v1", &source).expect("digest file");
666            assert_eq!(
667                streamed.bytes,
668                u64::try_from(length).expect("fixture length must fit in u64")
669            );
670            assert_eq!(streamed.digest, digest_bytes("streaming-test-v1", data));
671        }
672
673        ic_host_fs::durable::write_bytes(&destination, b"old").expect("write original destination");
674        assert_eq!(
675            copy_file_atomic(&source, &destination).expect("copy source atomically"),
676            u64::try_from(contents.len()).expect("fixture length must fit in u64")
677        );
678        assert_eq!(
679            fs::read(&destination).expect("read copied destination"),
680            contents
681        );
682
683        let missing = root.join("missing");
684        let error = copy_file_atomic(&missing, &destination).expect_err("missing source must fail");
685        let message = error.to_string();
686        assert!(message.contains(&missing.display().to_string()));
687        assert!(message.contains(&destination.display().to_string()));
688        fs::remove_dir_all(root).expect("remove streaming-digest test directory");
689    }
690
691    #[test]
692    #[cfg(unix)]
693    fn atomic_publication_supports_long_destination_names() {
694        let root = unique_temp_directory("atomic-long-destination");
695        let destination = root.join("a".repeat(255));
696        // Establish that the destination itself is valid on this filesystem.
697        fs::write(&destination, b"original output").unwrap();
698        let source = root.join("source");
699        fs::write(&source, b"copied output").unwrap();
700        assert_eq!(copy_file_atomic(&source, &destination).unwrap(), 13);
701        assert_eq!(fs::read(&destination).unwrap(), b"copied output");
702        assert_eq!(fs::read_dir(&root).unwrap().count(), 2);
703        fs::remove_dir_all(root).unwrap();
704    }
705
706    #[test]
707    fn composable_digest_reuses_roots_across_irrelevant_exclusion_changes() {
708        let root = unique_temp_directory("composable-digest-cache");
709        let input = root.join("input");
710        fs::create_dir_all(&input).expect("create composable input");
711        fs::create_dir_all(root.join("generated-a")).expect("create first generated root");
712        fs::create_dir_all(root.join("generated-b")).expect("create second generated root");
713        fs::write(input.join("source"), b"source").expect("write composable input");
714        let paths = [(PathBuf::from("shared"), input)];
715        let mut cache = LabeledPathDigestCache::default();
716
717        let first = digest_labeled_paths_composable(
718            "composable-test-v1",
719            paths
720                .iter()
721                .map(|(label, path)| (label.as_path(), path.as_path())),
722            &[root.join("generated-a")],
723            &mut cache,
724        )
725        .expect("hash first composable input");
726        let second = digest_labeled_paths_composable(
727            "composable-test-v1",
728            paths
729                .iter()
730                .map(|(label, path)| (label.as_path(), path.as_path())),
731            &[root.join("generated-b")],
732            &mut cache,
733        )
734        .expect("reuse composable input root");
735
736        assert_eq!(first, second);
737        assert_eq!(cache.entries.len(), 1);
738        fs::remove_dir_all(root).expect("remove composable digest fixture");
739    }
740
741    #[test]
742    fn composable_digest_rehashes_changed_descendant_exclusions_and_rejects_ancestors() {
743        let root = unique_temp_directory("composable-relevant-exclusions");
744        let input = root.join("input");
745        let generated = input.join("generated");
746        fs::create_dir_all(&generated).unwrap();
747        fs::write(input.join("source"), b"source").unwrap();
748        fs::write(generated.join("artifact"), b"generated").unwrap();
749        let paths = [(PathBuf::from("input"), input.clone())];
750        let digest = |exclusions: &[PathBuf], cache: &mut LabeledPathDigestCache| {
751            digest_labeled_paths_composable(
752                "exclusions-test-v1",
753                paths
754                    .iter()
755                    .map(|(label, path)| (label.as_path(), path.as_path())),
756                exclusions,
757                cache,
758            )
759        };
760        let mut cache = LabeledPathDigestCache::default();
761        let excluded = digest(std::slice::from_ref(&generated), &mut cache).unwrap();
762        let included = digest(&[], &mut cache).unwrap();
763        assert_ne!(included, excluded);
764        assert_eq!(
765            included,
766            digest(&[], &mut LabeledPathDigestCache::default()).unwrap(),
767        );
768        for ancestor in [&input, &root] {
769            assert_eq!(
770                digest(std::slice::from_ref(ancestor), &mut cache)
771                    .unwrap_err()
772                    .kind(),
773                std::io::ErrorKind::InvalidInput,
774            );
775        }
776        assert_eq!(
777            digest(std::slice::from_ref(&generated), &mut cache).unwrap(),
778            excluded,
779        );
780        fs::remove_dir_all(root).unwrap();
781    }
782
783    #[test]
784    #[cfg(unix)]
785    fn composable_digest_tracks_exclusions_beyond_an_external_symlink() {
786        let root = unique_temp_directory("composable-external-exclusions");
787        let input = root.join("input");
788        let external = root.join("external");
789        fs::create_dir_all(&input).unwrap();
790        fs::create_dir_all(external.join("first")).unwrap();
791        fs::create_dir_all(external.join("second")).unwrap();
792        fs::write(input.join("source"), b"source").unwrap();
793        fs::write(external.join("first/file"), b"first").unwrap();
794        fs::write(external.join("second/file"), b"second").unwrap();
795        std::os::unix::fs::symlink(&external, input.join("linked")).unwrap();
796        let paths = [(PathBuf::from("input"), input)];
797        let digest = |exclusion: &PathBuf, cache: &mut LabeledPathDigestCache| {
798            digest_labeled_paths_composable(
799                "external-exclusions-test-v1",
800                paths
801                    .iter()
802                    .map(|(label, path)| (label.as_path(), path.as_path())),
803                std::slice::from_ref(exclusion),
804                cache,
805            )
806        };
807        let mut cache = LabeledPathDigestCache::default();
808        let first = digest(&external.join("first"), &mut cache).unwrap();
809        let second = digest(&external.join("second"), &mut cache).unwrap();
810        assert_ne!(first, second);
811        assert_eq!(
812            second,
813            digest(
814                &external.join("second"),
815                &mut LabeledPathDigestCache::default(),
816            )
817            .unwrap(),
818        );
819        assert_eq!(digest(&external.join("first"), &mut cache).unwrap(), first);
820        fs::remove_dir_all(root).unwrap();
821    }
822}