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
249// A cache root may not have been created yet. Other failures must not silently
250// remove a declared exclusion and change which inputs contribute to identity.
251fn resolve_excluded_roots(paths: &[PathBuf]) -> io::Result<Vec<PathBuf>> {
252    paths
253        .iter()
254        .filter_map(|path| match path.canonicalize() {
255            Ok(path) => Some(Ok(path)),
256            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
257            Err(error) => Some(Err(io::Error::new(
258                error.kind(),
259                format!(
260                    "failed to resolve excluded root {}: {error}",
261                    path.display()
262                ),
263            ))),
264        })
265        .collect()
266}
267
268pub(super) fn digest_labeled_paths<L: AsRef<Path>, P: AsRef<Path>>(
269    domain: &str,
270    paths: impl IntoIterator<Item = (L, P)>,
271    excluded_roots: &[PathBuf],
272) -> io::Result<InputDigest> {
273    let mut paths = paths.into_iter().collect::<Vec<_>>();
274    paths.sort_by(|(left, _), (right, _)| {
275        os_bytes(left.as_ref().as_os_str()).cmp(&os_bytes(right.as_ref().as_os_str()))
276    });
277
278    let excluded_roots = resolve_excluded_roots(excluded_roots)?;
279    let mut visited_directories = BTreeSet::new();
280    let mut hasher = InputHasher::new(domain);
281    for (label, path) in paths {
282        hash_path(
283            &mut hasher,
284            label.as_ref(),
285            path.as_ref(),
286            &excluded_roots,
287            &mut visited_directories,
288            true,
289            None,
290        )?;
291    }
292    Ok(hasher.finish())
293}
294
295#[derive(Default)]
296pub(super) struct LabeledPathDigestCache {
297    entries: Vec<LabeledPathDigestCacheEntry>,
298}
299
300struct LabeledPathDigestCacheEntry {
301    domain: String,
302    label: PathBuf,
303    path: PathBuf,
304    canonical_root: PathBuf,
305    excluded_roots: Vec<PathBuf>,
306    traversed_external_path: bool,
307    digest: InputDigest,
308}
309
310struct HashPathTrace {
311    canonical_root: PathBuf,
312    traversed_external_path: bool,
313}
314
315pub(super) fn digest_labeled_paths_composable<'a>(
316    domain: &str,
317    paths: impl IntoIterator<Item = (&'a Path, &'a Path)>,
318    excluded_roots: &[PathBuf],
319    cache: &mut LabeledPathDigestCache,
320) -> io::Result<InputDigest> {
321    let mut paths = paths.into_iter().collect::<Vec<_>>();
322    paths.sort_by(|(left, _), (right, _)| {
323        os_bytes(left.as_os_str()).cmp(&os_bytes(right.as_os_str()))
324    });
325    let excluded_roots = resolve_excluded_roots(excluded_roots)?;
326    let mut hasher = InputHasher::new(&format!("{domain}/composable-v1"));
327    for (label, path) in paths {
328        let digest = cache.digest_root(domain, label, path, &excluded_roots)?;
329        hasher.field("input-label", &os_bytes(label.as_os_str()));
330        hasher.field("input-digest", digest.as_bytes());
331    }
332    Ok(hasher.finish())
333}
334
335impl LabeledPathDigestCache {
336    fn digest_root(
337        &mut self,
338        domain: &str,
339        label: &Path,
340        path: &Path,
341        excluded_roots: &[PathBuf],
342    ) -> io::Result<InputDigest> {
343        let canonical_root = path.canonicalize()?;
344        if let Some(entry) = self.entries.iter().find(|entry| {
345            entry.domain == domain
346                && entry.label == label
347                && entry.path == path
348                && entry.excluded_roots.iter().eq(effective_root_exclusions(
349                    &entry.canonical_root,
350                    excluded_roots,
351                    entry.traversed_external_path,
352                ))
353        }) {
354            return Ok(entry.digest);
355        }
356        let mut hasher = InputHasher::new(&format!("{domain}/root-v1"));
357        let mut trace = HashPathTrace {
358            canonical_root: canonical_root.clone(),
359            traversed_external_path: false,
360        };
361        hash_path(
362            &mut hasher,
363            label,
364            path,
365            excluded_roots,
366            &mut BTreeSet::new(),
367            true,
368            Some(&mut trace),
369        )?;
370        let digest = hasher.finish();
371        self.entries.push(LabeledPathDigestCacheEntry {
372            domain: domain.to_owned(),
373            label: label.to_owned(),
374            path: path.to_owned(),
375            canonical_root,
376            excluded_roots: effective_root_exclusions(
377                &trace.canonical_root,
378                excluded_roots,
379                trace.traversed_external_path,
380            )
381            .cloned()
382            .collect(),
383            traversed_external_path: trace.traversed_external_path,
384            digest,
385        });
386        Ok(digest)
387    }
388}
389
390fn effective_root_exclusions<'a>(
391    canonical_root: &'a Path,
392    excluded_roots: &'a [PathBuf],
393    traversed_external_path: bool,
394) -> impl Iterator<Item = &'a PathBuf> {
395    excluded_roots.iter().filter(move |excluded| {
396        traversed_external_path
397            || excluded.starts_with(canonical_root)
398            || canonical_root.starts_with(excluded)
399    })
400}
401
402fn hash_path(
403    hasher: &mut InputHasher,
404    label: &Path,
405    path: &Path,
406    excluded_roots: &[PathBuf],
407    visited_directories: &mut BTreeSet<PathBuf>,
408    declared_root: bool,
409    mut trace: Option<&mut HashPathTrace>,
410) -> io::Result<()> {
411    let context =
412        |error: io::Error| io::Error::new(error.kind(), format!("{}: {error}", path.display()));
413    let canonical = path.canonicalize().map_err(context)?;
414    if let Some(trace) = &mut trace
415        && !canonical.starts_with(&trace.canonical_root)
416    {
417        trace.traversed_external_path = true;
418    }
419    if excluded_roots
420        .iter()
421        .any(|excluded| canonical.starts_with(excluded))
422    {
423        if declared_root {
424            return Err(io::Error::new(
425                io::ErrorKind::InvalidInput,
426                format!(
427                    "declared input is located inside an excluded cache root: {}",
428                    path.display()
429                ),
430            ));
431        }
432        return Ok(());
433    }
434
435    let metadata = fs::metadata(path).map_err(context)?;
436    let label_bytes = os_bytes(label.as_os_str());
437    if metadata.is_file() {
438        hasher.field("file-path", &label_bytes);
439        hasher.file_field("file-content", path).map_err(context)?;
440        return Ok(());
441    }
442    if !metadata.is_dir() {
443        return Err(io::Error::new(
444            io::ErrorKind::InvalidInput,
445            format!(
446                "watched input is not a regular file or directory: {}",
447                path.display()
448            ),
449        ));
450    }
451
452    hasher.field("directory", &label_bytes);
453    if !visited_directories.insert(canonical) {
454        hasher.field("directory-already-visited", &label_bytes);
455        return Ok(());
456    }
457
458    let mut entries = fs::read_dir(path)
459        .map_err(context)?
460        .map(|entry| entry.map(|entry| entry.file_name()))
461        .collect::<Result<Vec<_>, _>>()
462        .map_err(context)?;
463    // Unix names already own their native byte ordering. Compare borrowed
464    // bytes rather than allocating a second name and cached key per entry.
465    #[cfg(unix)]
466    entries.sort_unstable_by(|left, right| os_bytes(left).cmp(&os_bytes(right)));
467    // Other hosts may need an allocated native encoding; compute it once.
468    #[cfg(not(unix))]
469    entries.sort_by_cached_key(|name| os_bytes(name).into_owned());
470    for name in entries {
471        hash_path(
472            hasher,
473            &label.join(&name),
474            &path.join(&name),
475            excluded_roots,
476            visited_directories,
477            false,
478            trace.as_deref_mut(),
479        )?;
480    }
481    Ok(())
482}
483
484pub(super) fn copy_file_atomic(source: &Path, destination: &Path) -> io::Result<u64> {
485    let result = (|| {
486        let mut source_file = File::open(source)?;
487        ic_host_fs::durable::write_with(destination, |destination_file| {
488            io::copy(&mut source_file, destination_file)
489        })
490    })();
491    result.map_err(|source_error| {
492        io::Error::new(
493            source_error.kind(),
494            AtomicCopyErrorContext {
495                source_path: source.to_owned(),
496                destination_path: destination.to_owned(),
497                source: source_error,
498            },
499        )
500    })
501}
502
503#[cfg(unix)]
504pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
505    Cow::Borrowed(value.as_bytes())
506}
507
508#[cfg(windows)]
509pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
510    Cow::Owned(value.encode_wide().flat_map(u16::to_le_bytes).collect())
511}
512
513#[cfg(not(any(unix, windows)))]
514pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
515    Cow::Owned(value.to_string_lossy().as_bytes().to_vec())
516}
517
518#[cfg(test)]
519mod tests {
520    use super::{
521        LabeledPathDigestCache, copy_file_atomic, digest_bytes, digest_file,
522        digest_labeled_paths_composable,
523    };
524    use crate::artifacts::test_support::unique_temp_directory;
525    use std::{fs, path::PathBuf};
526
527    #[cfg(unix)]
528    use super::{InputHasher, digest_labeled_paths};
529    #[cfg(unix)]
530    use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _};
531    #[cfg(windows)]
532    use std::{ffi::OsString, os::windows::ffi::OsStringExt as _};
533
534    #[test]
535    #[cfg(unix)]
536    fn exclusion_resolution_errors_stop_both_fingerprint_paths() {
537        use std::os::unix::fs::symlink;
538        let root = unique_temp_directory("invalid-digest-exclusions");
539        let input = root.join("input");
540        fs::write(&input, b"source").unwrap();
541        let cycle = root.join("cycle");
542        symlink("cycle", &cycle).unwrap();
543        let paths = [(std::path::Path::new("input"), input.as_path())];
544        assert!(
545            digest_labeled_paths("exclusions-v1", paths, std::slice::from_ref(&cycle)).is_err()
546        );
547        let mut cache = LabeledPathDigestCache::default();
548        let expected =
549            digest_labeled_paths_composable("exclusions-v1", paths, &[], &mut cache).unwrap();
550        assert!(
551            digest_labeled_paths_composable("exclusions-v1", paths, &[cycle], &mut cache).is_err()
552        );
553        // A not-yet-created cache root remains an accepted exclusion, including
554        // on a reused source-lease digest. A failed resolution cannot reuse it.
555        assert_eq!(
556            digest_labeled_paths_composable(
557                "exclusions-v1",
558                paths,
559                &[root.join("missing")],
560                &mut cache,
561            )
562            .unwrap(),
563            expected
564        );
565        assert_eq!(
566            digest_labeled_paths("exclusions-v1", paths, &[]).unwrap(),
567            digest_labeled_paths("exclusions-v1", paths, &[root.join("missing")]).unwrap()
568        );
569        fs::remove_dir_all(root).unwrap();
570    }
571
572    #[test]
573    fn digest_text_preserves_lowercase_hex_and_leading_zeroes() {
574        let digest = super::InputDigest(std::array::from_fn(|index| {
575            u8::try_from(index).expect("digest byte index must fit")
576        }));
577        let expected = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
578        assert_eq!(digest.to_hex(), expected);
579        assert_eq!(digest.to_string(), expected);
580        assert_eq!(super::InputDigest([0xff; 32]).to_string(), "ff".repeat(32));
581    }
582
583    #[test]
584    #[cfg(unix)]
585    fn labeled_path_digests_preserve_native_names_and_sorted_order() {
586        let names: &[&[u8]] = &[
587            b"\xce\xbb",
588            #[cfg(target_os = "linux")]
589            b"\xff",
590        ];
591        for &name in names {
592            let root = unique_temp_directory("native-path-digest");
593            let tree = root.join("tree");
594            fs::create_dir_all(tree.join("nested")).unwrap();
595            fs::write(tree.join(OsStr::from_bytes(name)), b"native").unwrap();
596            fs::write(tree.join("nested/z"), b"last").unwrap();
597            fs::write(tree.join("a"), b"first").unwrap();
598            fs::write(root.join("top"), b"top").unwrap();
599            let mut paths = [
600                (PathBuf::from("tree"), tree),
601                (PathBuf::from("aaa"), root.join("top")),
602            ];
603
604            let tree_fields = |hasher: &mut InputHasher| {
605                hasher.field("directory", b"tree");
606                hasher.field("file-path", b"tree/a");
607                hasher.field("file-content", b"first");
608                hasher.field("directory", b"tree/nested");
609                hasher.field("file-path", b"tree/nested/z");
610                hasher.field("file-content", b"last");
611                hasher.field("file-path", &[b"tree/".as_slice(), name].concat());
612                hasher.field("file-content", b"native");
613            };
614            let mut expected = InputHasher::new("native-path-test-v1");
615            expected.field("file-path", b"aaa");
616            expected.field("file-content", b"top");
617            tree_fields(&mut expected);
618            let expected = expected.finish();
619
620            let mut top = InputHasher::new("native-path-test-v1/root-v1");
621            top.field("file-path", b"aaa");
622            top.field("file-content", b"top");
623            let mut tree = InputHasher::new("native-path-test-v1/root-v1");
624            tree_fields(&mut tree);
625            let mut composable = InputHasher::new("native-path-test-v1/composable-v1");
626            composable.field("input-label", b"aaa");
627            composable.field("input-digest", top.finish().as_bytes());
628            composable.field("input-label", b"tree");
629            composable.field("input-digest", tree.finish().as_bytes());
630            let composable = composable.finish();
631
632            for _ in 0..2 {
633                assert_eq!(
634                    digest_labeled_paths(
635                        "native-path-test-v1",
636                        paths.iter().map(|(label, path)| (label, path)),
637                        &[],
638                    )
639                    .unwrap(),
640                    expected,
641                );
642                assert_eq!(
643                    digest_labeled_paths_composable(
644                        "native-path-test-v1",
645                        paths
646                            .iter()
647                            .map(|(label, path)| (label.as_path(), path.as_path())),
648                        &[],
649                        &mut LabeledPathDigestCache::default(),
650                    )
651                    .unwrap(),
652                    composable,
653                );
654                paths.reverse();
655            }
656            fs::remove_dir_all(root).unwrap();
657        }
658    }
659
660    #[test]
661    #[cfg(unix)]
662    fn native_bytes_preserve_non_utf8_without_a_filesystem_roundtrip() {
663        assert_eq!(
664            super::os_bytes(OsStr::from_bytes(b"name\xff")).as_ref(),
665            b"name\xff"
666        );
667    }
668
669    #[test]
670    #[cfg(windows)]
671    fn native_names_preserve_utf16_little_endian_encoding() {
672        let value = OsString::from_wide(&[0x0061, 0xd800, 0x0100]);
673        assert_eq!(super::os_bytes(&value).as_ref(), &[0x61, 0, 0, 0xd8, 0, 1]);
674    }
675
676    #[test]
677    fn streamed_fields_preserve_bytes_across_different_file_sizes() {
678        let root = unique_temp_directory("streamed-field-sizes");
679        let source = root.join("source");
680        let contents = (0..192 * 1024 + 37)
681            .map(|index| u8::try_from(index % 251).unwrap())
682            .collect::<Vec<_>>();
683        let mut streamed = super::InputHasher::new("streamed-fields-v1");
684        let mut expected = super::InputHasher::new("streamed-fields-v1");
685        for length in [1, 64 * 1024 - 1, contents.len(), 0, 7, 1024, 64 * 1024 + 1] {
686            let bytes = &contents[..length];
687            fs::write(&source, bytes).unwrap();
688            assert_eq!(streamed.file_field("part", &source).unwrap(), length as u64);
689            expected.field("part", bytes);
690        }
691        assert_eq!(streamed.finish(), expected.finish());
692        fs::remove_dir_all(root).unwrap();
693    }
694
695    #[test]
696    fn streaming_digest_and_atomic_copy_preserve_exact_bytes() {
697        let root = unique_temp_directory("streaming-digest");
698        let source = root.join("source");
699        let destination = root.join("destination");
700        let mut contents = vec![0_u8; 192 * 1024 + 37];
701        for (index, byte) in contents.iter_mut().enumerate() {
702            *byte = u8::try_from(index % 251).expect("test byte must fit");
703        }
704        for length in [
705            0,
706            1,
707            1024,
708            16 * 1024,
709            64 * 1024 - 1,
710            64 * 1024,
711            64 * 1024 + 1,
712            contents.len(),
713        ] {
714            let data = &contents[..length];
715            fs::write(&source, data).expect("write source");
716            let streamed = digest_file("streaming-test-v1", &source).expect("digest file");
717            assert_eq!(
718                streamed.bytes,
719                u64::try_from(length).expect("fixture length must fit in u64")
720            );
721            assert_eq!(streamed.digest, digest_bytes("streaming-test-v1", data));
722        }
723
724        ic_host_fs::durable::write_bytes(&destination, b"old").expect("write original destination");
725        assert_eq!(
726            copy_file_atomic(&source, &destination).expect("copy source atomically"),
727            u64::try_from(contents.len()).expect("fixture length must fit in u64")
728        );
729        assert_eq!(
730            fs::read(&destination).expect("read copied destination"),
731            contents
732        );
733
734        let missing = root.join("missing");
735        let error = copy_file_atomic(&missing, &destination).expect_err("missing source must fail");
736        let message = error.to_string();
737        assert!(message.contains(&missing.display().to_string()));
738        assert!(message.contains(&destination.display().to_string()));
739        fs::remove_dir_all(root).expect("remove streaming-digest test directory");
740    }
741
742    #[test]
743    #[cfg(unix)]
744    fn atomic_publication_supports_long_destination_names() {
745        let root = unique_temp_directory("atomic-long-destination");
746        let destination = root.join("a".repeat(255));
747        // Establish that the destination itself is valid on this filesystem.
748        fs::write(&destination, b"original output").unwrap();
749        let source = root.join("source");
750        fs::write(&source, b"copied output").unwrap();
751        assert_eq!(copy_file_atomic(&source, &destination).unwrap(), 13);
752        assert_eq!(fs::read(&destination).unwrap(), b"copied output");
753        assert_eq!(fs::read_dir(&root).unwrap().count(), 2);
754        fs::remove_dir_all(root).unwrap();
755    }
756
757    #[test]
758    fn composable_digest_reuses_roots_across_irrelevant_exclusion_changes() {
759        let root = unique_temp_directory("composable-digest-cache");
760        let input = root.join("input");
761        fs::create_dir_all(&input).expect("create composable input");
762        fs::create_dir_all(root.join("generated-a")).expect("create first generated root");
763        fs::create_dir_all(root.join("generated-b")).expect("create second generated root");
764        fs::write(input.join("source"), b"source").expect("write composable input");
765        let paths = [(PathBuf::from("shared"), input)];
766        let mut cache = LabeledPathDigestCache::default();
767
768        let first = digest_labeled_paths_composable(
769            "composable-test-v1",
770            paths
771                .iter()
772                .map(|(label, path)| (label.as_path(), path.as_path())),
773            &[root.join("generated-a")],
774            &mut cache,
775        )
776        .expect("hash first composable input");
777        let second = digest_labeled_paths_composable(
778            "composable-test-v1",
779            paths
780                .iter()
781                .map(|(label, path)| (label.as_path(), path.as_path())),
782            &[root.join("generated-b")],
783            &mut cache,
784        )
785        .expect("reuse composable input root");
786
787        assert_eq!(first, second);
788        assert_eq!(cache.entries.len(), 1);
789        fs::remove_dir_all(root).expect("remove composable digest fixture");
790    }
791
792    #[test]
793    fn composable_digest_rehashes_changed_descendant_exclusions_and_rejects_ancestors() {
794        let root = unique_temp_directory("composable-relevant-exclusions");
795        let input = root.join("input");
796        let generated = input.join("generated");
797        fs::create_dir_all(&generated).unwrap();
798        fs::write(input.join("source"), b"source").unwrap();
799        fs::write(generated.join("artifact"), b"generated").unwrap();
800        let paths = [(PathBuf::from("input"), input.clone())];
801        let digest = |exclusions: &[PathBuf], cache: &mut LabeledPathDigestCache| {
802            digest_labeled_paths_composable(
803                "exclusions-test-v1",
804                paths
805                    .iter()
806                    .map(|(label, path)| (label.as_path(), path.as_path())),
807                exclusions,
808                cache,
809            )
810        };
811        let mut cache = LabeledPathDigestCache::default();
812        let excluded = digest(std::slice::from_ref(&generated), &mut cache).unwrap();
813        let included = digest(&[], &mut cache).unwrap();
814        assert_ne!(included, excluded);
815        assert_eq!(
816            included,
817            digest(&[], &mut LabeledPathDigestCache::default()).unwrap(),
818        );
819        for ancestor in [&input, &root] {
820            assert_eq!(
821                digest(std::slice::from_ref(ancestor), &mut cache)
822                    .unwrap_err()
823                    .kind(),
824                std::io::ErrorKind::InvalidInput,
825            );
826        }
827        assert_eq!(
828            digest(std::slice::from_ref(&generated), &mut cache).unwrap(),
829            excluded,
830        );
831        fs::remove_dir_all(root).unwrap();
832    }
833
834    #[test]
835    #[cfg(unix)]
836    fn composable_digest_tracks_exclusions_beyond_an_external_symlink() {
837        let root = unique_temp_directory("composable-external-exclusions");
838        let input = root.join("input");
839        let external = root.join("external");
840        fs::create_dir_all(&input).unwrap();
841        fs::create_dir_all(external.join("first")).unwrap();
842        fs::create_dir_all(external.join("second")).unwrap();
843        fs::write(input.join("source"), b"source").unwrap();
844        fs::write(external.join("first/file"), b"first").unwrap();
845        fs::write(external.join("second/file"), b"second").unwrap();
846        std::os::unix::fs::symlink(&external, input.join("linked")).unwrap();
847        let paths = [(PathBuf::from("input"), input)];
848        let digest = |exclusion: &PathBuf, cache: &mut LabeledPathDigestCache| {
849            digest_labeled_paths_composable(
850                "external-exclusions-test-v1",
851                paths
852                    .iter()
853                    .map(|(label, path)| (label.as_path(), path.as_path())),
854                std::slice::from_ref(exclusion),
855                cache,
856            )
857        };
858        let mut cache = LabeledPathDigestCache::default();
859        let first = digest(&external.join("first"), &mut cache).unwrap();
860        let second = digest(&external.join("second"), &mut cache).unwrap();
861        assert_ne!(first, second);
862        assert_eq!(
863            second,
864            digest(
865                &external.join("second"),
866                &mut LabeledPathDigestCache::default(),
867            )
868            .unwrap(),
869        );
870        assert_eq!(digest(&external.join("first"), &mut cache).unwrap(), first);
871        fs::remove_dir_all(root).unwrap();
872    }
873}