Skip to main content

ic_build/artifacts/
digest.rs

1use ic_host_artifacts::artifact::{Sha256Digest, visit_reader};
2use sha2::{Digest, Sha256};
3use std::{
4    borrow::Cow,
5    collections::BTreeSet,
6    ffi::{OsStr, OsString},
7    fs::{self, File},
8    io,
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    pub(super) const fn from_bytes(bytes: [u8; 32]) -> Self {
48        Self(bytes)
49    }
50    /// Borrow the raw SHA-256 bytes.
51    #[must_use]
52    pub const fn as_bytes(&self) -> &[u8; 32] {
53        &self.0
54    }
55
56    /// Render the digest as lowercase hexadecimal.
57    #[must_use]
58    pub fn to_hex(self) -> String {
59        self.to_string()
60    }
61}
62
63impl std::fmt::Display for InputDigest {
64    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        Sha256Digest::from_bytes(self.0).fmt(formatter)
66    }
67}
68
69pub(super) struct InputHasher {
70    state: Sha256,
71    read_buffer: Vec<u8>,
72}
73
74impl InputHasher {
75    pub(super) fn new(domain: &str) -> Self {
76        let mut hasher = Self {
77            state: Sha256::new(),
78            read_buffer: Vec::new(),
79        };
80        hasher.field("domain", domain.as_bytes());
81        hasher
82    }
83
84    pub(super) fn field(&mut self, label: &str, value: &[u8]) {
85        self.field_header(
86            label,
87            u64::try_from(value.len()).expect("input value length must fit in u64"),
88        );
89        self.state.update(value);
90    }
91
92    fn field_header(&mut self, label: &str, value_len: u64) {
93        self.state.update(
94            u64::try_from(label.len())
95                .expect("input label length must fit in u64")
96                .to_le_bytes(),
97        );
98        self.state.update(label.as_bytes());
99        self.state.update(value_len.to_le_bytes());
100    }
101
102    fn file_field(&mut self, label: &str, path: &Path) -> io::Result<u64> {
103        let mut file = File::open(path)?;
104        let expected_len = file.metadata()?.len();
105        self.field_header(label, expected_len);
106
107        let mut actual_len = 0_u64;
108        // Small sources need only their declared length; large artifacts use bounded reads.
109        // Even empty files need a nonempty read buffer to detect growth.
110        let buffer_len = usize::try_from(expected_len.clamp(1, 64 * 1024))
111            .expect("bounded artifact buffer length must fit in usize");
112        // A tree hashes many files with one hasher. Retain its bounded scratch
113        // space, reading only this file's window and hashing only returned bytes.
114        if self.read_buffer.len() < buffer_len {
115            // Geometric growth near the read limit would retain almost twice
116            // the scratch space required by any file in this hashing pass.
117            self.read_buffer
118                .reserve_exact(buffer_len - self.read_buffer.len());
119            self.read_buffer.resize(buffer_len, 0);
120        }
121        let changed_size = |actual_len| {
122            io::Error::new(
123                io::ErrorKind::InvalidData,
124                format!(
125                    "file changed size while hashing: expected {expected_len} bytes, read {actual_len}"
126                ),
127            )
128        };
129        visit_reader::<io::Error>(
130            &mut file,
131            &mut self.read_buffer[..buffer_len],
132            u64::MAX,
133            |chunk| {
134                actual_len = actual_len.saturating_add(
135                    u64::try_from(chunk.len()).expect("artifact read length must fit in u64"),
136                );
137                if actual_len > expected_len {
138                    return Err(changed_size(actual_len));
139                }
140                self.state.update(chunk);
141                Ok(())
142            },
143        )?;
144        if actual_len != expected_len {
145            return Err(changed_size(actual_len));
146        }
147        Ok(actual_len)
148    }
149
150    pub(super) fn finish(self) -> InputDigest {
151        InputDigest(self.state.finalize().into())
152    }
153}
154
155pub(super) fn digest_bytes(domain: &str, value: &[u8]) -> InputDigest {
156    let mut hasher = InputHasher::new(domain);
157    hasher.field("content", value);
158    hasher.finish()
159}
160
161#[derive(Clone, Copy, Debug, Eq, PartialEq)]
162pub(super) struct FileDigest {
163    pub(super) bytes: u64,
164    pub(super) digest: InputDigest,
165}
166
167pub(super) fn digest_file(domain: &str, path: &Path) -> io::Result<FileDigest> {
168    let mut hasher = InputHasher::new(domain);
169    let bytes = hasher.file_field("content", path)?;
170    Ok(FileDigest {
171        bytes,
172        digest: hasher.finish(),
173    })
174}
175
176/// Read a UTF-8 stamp without allocating or reading an oversized sidecar in full.
177/// An oversized stamp is stale; other read and decoding errors reach the caller.
178pub(super) fn read_stamp_with_limit(path: &Path, maximum_len: usize) -> io::Result<Option<String>> {
179    read_file_with_limit(path, maximum_len)?
180        .map(|contents| {
181            String::from_utf8(contents)
182                .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
183        })
184        .transpose()
185}
186
187/// Read at most the format's maximum length plus one byte to detect oversized files.
188pub(super) fn read_file_with_limit(path: &Path, maximum_len: usize) -> io::Result<Option<Vec<u8>>> {
189    use ic_host_artifacts::artifact::ArtifactError;
190    use ic_host_fs::read::read_file;
191
192    // The shared library owns bounded reading and allocation. Cache policy owns
193    // the meaning of overflow: an oversized stamp or manifest is a cache miss.
194    match read_file(path, maximum_len) {
195        Ok(contents) => Ok(Some(contents)),
196        Err(ArtifactError::LimitExceeded { .. }) => Ok(None),
197        Err(ArtifactError::NotRegularFile) => Err(io::Error::new(
198            io::ErrorKind::InvalidData,
199            ArtifactError::NotRegularFile,
200        )),
201        Err(error) => Err(error.into()),
202    }
203}
204
205/// Only reuse an independent, caller-owned writable destination. The caller
206/// coordinates other writers and supplies a digest from a verified cache entry.
207fn destination_matches_digest(domain: &str, destination: &Path, expected: &FileDigest) -> bool {
208    destination_is_reusable(destination, expected.bytes)
209        && digest_file(domain, destination).is_ok_and(|actual| actual == *expected)
210}
211
212/// Cold publication always copies; only previously verified outputs may preserve
213/// matching caller-owned destinations and their metadata.
214pub(super) fn materialize_verified_output(
215    domain: &str,
216    source: &Path,
217    destination: &Path,
218    verified: Option<&FileDigest>,
219) -> io::Result<()> {
220    if verified.is_some_and(|info| destination_matches_digest(domain, destination, info)) {
221        return Ok(());
222    }
223    copy_file_atomic(source, destination).map(|_| ())
224}
225
226pub(super) fn destination_matches_bytes(destination: &Path, expected: &[u8]) -> bool {
227    destination_is_reusable(
228        destination,
229        u64::try_from(expected.len()).expect("artifact byte length must fit in u64"),
230    ) && read_file_with_limit(destination, expected.len())
231        .is_ok_and(|actual| actual.as_deref() == Some(expected))
232}
233
234fn destination_is_reusable(destination: &Path, expected_bytes: u64) -> bool {
235    #[cfg(unix)]
236    {
237        let Ok(metadata) = fs::symlink_metadata(destination) else {
238            return false;
239        };
240        let effective_uid = rustix::process::geteuid().as_raw();
241        // Detach links and normalize foreign-owned, restricted or executable
242        // files, even when their bytes match a retained artifact.
243        if !metadata.file_type().is_file()
244            || metadata.nlink() != 1
245            || metadata.uid() != effective_uid
246            || metadata.mode() & 0o600 != 0o600
247            || metadata.mode() & 0o7111 != 0
248            || metadata.len() != expected_bytes
249        {
250            return false;
251        }
252        true
253    }
254    #[cfg(not(unix))]
255    {
256        // Preserve replacement where a portable single-link check is unavailable.
257        let _ = (destination, expected_bytes);
258        false
259    }
260}
261
262// A cache root may not have been created yet. Other failures must not silently
263// remove a declared exclusion and change which inputs contribute to identity.
264fn resolve_excluded_roots(paths: &[PathBuf]) -> io::Result<Vec<PathBuf>> {
265    paths
266        .iter()
267        .filter_map(|path| match path.canonicalize() {
268            Ok(path) => Some(Ok(path)),
269            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
270            Err(error) => Some(Err(io::Error::new(
271                error.kind(),
272                format!(
273                    "failed to resolve excluded root {}: {error}",
274                    path.display()
275                ),
276            ))),
277        })
278        .collect()
279}
280
281pub(super) fn digest_labeled_paths<L: AsRef<Path>, P: AsRef<Path>>(
282    domain: &str,
283    paths: impl IntoIterator<Item = (L, P)>,
284    excluded_roots: &[PathBuf],
285) -> io::Result<InputDigest> {
286    let mut paths = paths.into_iter().collect::<Vec<_>>();
287    paths.sort_by(|(left, _), (right, _)| {
288        os_bytes(left.as_ref().as_os_str()).cmp(&os_bytes(right.as_ref().as_os_str()))
289    });
290
291    let excluded_roots = resolve_excluded_roots(excluded_roots)?;
292    let mut visited_directories = BTreeSet::new();
293    let mut hasher = InputHasher::new(domain);
294    for (label, path) in paths {
295        hash_path(
296            &mut hasher,
297            label.as_ref(),
298            path.as_ref(),
299            &excluded_roots,
300            &mut visited_directories,
301            true,
302            None,
303        )?;
304    }
305    Ok(hasher.finish())
306}
307
308#[derive(Default)]
309pub(super) struct LabeledPathDigestCache {
310    entries: Vec<LabeledPathDigestCacheEntry>,
311}
312
313struct LabeledPathDigestCacheEntry {
314    domain: String,
315    label: PathBuf,
316    path: PathBuf,
317    canonical_root: PathBuf,
318    excluded_roots: Vec<PathBuf>,
319    traversed_external_path: bool,
320    digest: InputDigest,
321}
322
323struct HashPathTrace {
324    canonical_root: PathBuf,
325    traversed_external_path: bool,
326}
327
328pub(super) fn digest_labeled_paths_composable<'a>(
329    domain: &str,
330    paths: impl IntoIterator<Item = (&'a Path, &'a Path)>,
331    excluded_roots: &[PathBuf],
332    cache: &mut LabeledPathDigestCache,
333) -> io::Result<InputDigest> {
334    let mut paths = paths.into_iter().collect::<Vec<_>>();
335    paths.sort_by(|(left, _), (right, _)| {
336        os_bytes(left.as_os_str()).cmp(&os_bytes(right.as_os_str()))
337    });
338    let excluded_roots = resolve_excluded_roots(excluded_roots)?;
339    let mut hasher = InputHasher::new(&format!("{domain}/composable-v1"));
340    for (label, path) in paths {
341        let digest = cache.digest_root(domain, label, path, &excluded_roots)?;
342        hasher.field("input-label", &os_bytes(label.as_os_str()));
343        hasher.field("input-digest", digest.as_bytes());
344    }
345    Ok(hasher.finish())
346}
347
348impl LabeledPathDigestCache {
349    fn digest_root(
350        &mut self,
351        domain: &str,
352        label: &Path,
353        path: &Path,
354        excluded_roots: &[PathBuf],
355    ) -> io::Result<InputDigest> {
356        let canonical_root = path.canonicalize()?;
357        if let Some(entry) = self.entries.iter().find(|entry| {
358            entry.domain == domain
359                && entry.label == label
360                && entry.path == path
361                && entry.excluded_roots.iter().eq(effective_root_exclusions(
362                    &entry.canonical_root,
363                    excluded_roots,
364                    entry.traversed_external_path,
365                ))
366        }) {
367            return Ok(entry.digest);
368        }
369        let mut hasher = InputHasher::new(&format!("{domain}/root-v1"));
370        let mut trace = HashPathTrace {
371            canonical_root: canonical_root.clone(),
372            traversed_external_path: false,
373        };
374        hash_path(
375            &mut hasher,
376            label,
377            path,
378            excluded_roots,
379            &mut BTreeSet::new(),
380            true,
381            Some(&mut trace),
382        )?;
383        let digest = hasher.finish();
384        self.entries.push(LabeledPathDigestCacheEntry {
385            domain: domain.to_owned(),
386            label: label.to_owned(),
387            path: path.to_owned(),
388            canonical_root,
389            excluded_roots: effective_root_exclusions(
390                &trace.canonical_root,
391                excluded_roots,
392                trace.traversed_external_path,
393            )
394            .cloned()
395            .collect(),
396            traversed_external_path: trace.traversed_external_path,
397            digest,
398        });
399        Ok(digest)
400    }
401}
402
403fn effective_root_exclusions<'a>(
404    canonical_root: &'a Path,
405    excluded_roots: &'a [PathBuf],
406    traversed_external_path: bool,
407) -> impl Iterator<Item = &'a PathBuf> {
408    excluded_roots.iter().filter(move |excluded| {
409        traversed_external_path
410            || excluded.starts_with(canonical_root)
411            || canonical_root.starts_with(excluded)
412    })
413}
414
415fn hash_path(
416    hasher: &mut InputHasher,
417    label: &Path,
418    path: &Path,
419    excluded_roots: &[PathBuf],
420    visited_directories: &mut BTreeSet<PathBuf>,
421    declared_root: bool,
422    trace: Option<&mut HashPathTrace>,
423) -> io::Result<()> {
424    let mut traversal = InputTreeWalk {
425        excluded_roots,
426        excluded_names: &[],
427        visited_directories,
428        trace,
429        reject_links: false,
430    };
431    traversal.visit(label, path, declared_root, &mut |entry| {
432        match entry {
433            InputTreeEntry::File { label, path } => {
434                hasher.field("file-path", &os_bytes(label.as_os_str()));
435                hasher.file_field("file-content", path)?;
436            }
437            InputTreeEntry::Directory {
438                label, repeated, ..
439            } => {
440                hasher.field("directory", &os_bytes(label.as_os_str()));
441                if repeated {
442                    hasher.field("directory-already-visited", &os_bytes(label.as_os_str()));
443                }
444            }
445            InputTreeEntry::Missing { path } => {
446                return Err(io::Error::new(
447                    io::ErrorKind::NotFound,
448                    path.display().to_string(),
449                ));
450            }
451        }
452        Ok(())
453    })
454}
455
456/// One filesystem observation emitted by the shared input traversal.
457pub(super) enum InputTreeEntry<'a> {
458    File {
459        label: &'a Path,
460        path: &'a Path,
461    },
462    Directory {
463        label: &'a Path,
464        path: &'a Path,
465        repeated: bool,
466    },
467    Missing {
468        path: &'a Path,
469    },
470}
471
472/// Path context shared by fingerprint and standalone-evidence failures.
473#[derive(Debug)]
474pub(super) struct InputPathError {
475    pub(super) path: PathBuf,
476    pub(super) source: io::Error,
477}
478
479impl std::fmt::Display for InputPathError {
480    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
481        write!(formatter, "{}: {}", self.path.display(), self.source)
482    }
483}
484
485impl std::error::Error for InputPathError {
486    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
487        Some(&self.source)
488    }
489}
490
491/// One traversal owner; cache fingerprints retain their original follow-link policy.
492pub(super) struct InputTreeWalk<'a> {
493    excluded_roots: &'a [PathBuf],
494    excluded_names: &'a [OsString],
495    visited_directories: &'a mut BTreeSet<PathBuf>,
496    trace: Option<&'a mut HashPathTrace>,
497    reject_links: bool,
498}
499
500impl<'a> InputTreeWalk<'a> {
501    pub(super) const fn evidence(
502        excluded_roots: &'a [PathBuf],
503        excluded_names: &'a [OsString],
504        visited_directories: &'a mut BTreeSet<PathBuf>,
505    ) -> Self {
506        Self {
507            excluded_roots,
508            excluded_names,
509            visited_directories,
510            trace: None,
511            reject_links: true,
512        }
513    }
514
515    pub(super) fn visit(
516        &mut self,
517        label: &Path,
518        path: &Path,
519        declared_root: bool,
520        visitor: &mut impl FnMut(InputTreeEntry<'_>) -> io::Result<()>,
521    ) -> io::Result<()> {
522        let context = |source: io::Error| {
523            io::Error::new(
524                source.kind(),
525                InputPathError {
526                    path: path.to_owned(),
527                    source,
528                },
529            )
530        };
531        // Standalone evidence records absence and refuses links. Existing cache
532        // hashing still canonicalizes first and follows links exactly as before.
533        let inspected = if self.reject_links {
534            match fs::symlink_metadata(path) {
535                Ok(metadata) if metadata.file_type().is_symlink() => {
536                    return Err(context(io::Error::new(
537                        io::ErrorKind::InvalidInput,
538                        "input is a symbolic link",
539                    )));
540                }
541                Ok(metadata) => Some(metadata),
542                Err(error) if error.kind() == io::ErrorKind::NotFound => {
543                    let resolved =
544                        super::cache_fs::canonicalize_allow_missing(path).map_err(context)?;
545                    if self
546                        .excluded_roots
547                        .iter()
548                        .any(|root| resolved.starts_with(root))
549                    {
550                        if declared_root {
551                            return Err(context(io::Error::new(
552                                io::ErrorKind::InvalidInput,
553                                "declared missing input is inside an excluded root",
554                            )));
555                        }
556                        return Ok(());
557                    }
558                    return visitor(InputTreeEntry::Missing { path }).map_err(context);
559                }
560                Err(error) => return Err(context(error)),
561            }
562        } else {
563            None
564        };
565        let canonical = path.canonicalize().map_err(context)?;
566        if let Some(trace) = &mut self.trace
567            && !canonical.starts_with(&trace.canonical_root)
568        {
569            trace.traversed_external_path = true;
570        }
571        if self
572            .excluded_roots
573            .iter()
574            .any(|root| canonical.starts_with(root))
575        {
576            if declared_root {
577                return Err(context(io::Error::new(
578                    io::ErrorKind::InvalidInput,
579                    "declared input is inside an excluded root",
580                )));
581            }
582            return Ok(());
583        }
584        let metadata = match inspected {
585            Some(metadata) => metadata,
586            None => fs::metadata(path).map_err(context)?,
587        };
588        if metadata.is_file() {
589            return visitor(InputTreeEntry::File { label, path }).map_err(context);
590        }
591        if !metadata.is_dir() {
592            return Err(context(io::Error::new(
593                io::ErrorKind::InvalidInput,
594                "input is not a regular file or directory",
595            )));
596        }
597        // Cache fingerprints preserve cycle/alias markers. Standalone evidence
598        // refuses child links, so each declared spelling can be fully scanned;
599        // an alias must not be recorded as an empty, complete directory.
600        let repeated = !self.visited_directories.insert(canonical) && !self.reject_links;
601        visitor(InputTreeEntry::Directory {
602            label,
603            path,
604            repeated,
605        })
606        .map_err(context)?;
607        if repeated {
608            return Ok(());
609        }
610        let mut entries = fs::read_dir(path)
611            .map_err(context)?
612            .map(|entry| entry.map(|entry| entry.file_name()))
613            .collect::<Result<Vec<_>, _>>()
614            .map_err(context)?;
615        #[cfg(unix)]
616        entries.sort_unstable_by(|left, right| os_bytes(left).cmp(&os_bytes(right)));
617        #[cfg(not(unix))]
618        entries.sort_by_cached_key(|name| os_bytes(name).into_owned());
619        for name in entries {
620            if self.excluded_names.contains(&name) {
621                continue;
622            }
623            self.visit(&label.join(&name), &path.join(&name), false, visitor)?;
624        }
625        Ok(())
626    }
627}
628
629pub(super) fn copy_file_atomic(source: &Path, destination: &Path) -> io::Result<u64> {
630    let result = (|| {
631        let mut source_file = File::open(source)?;
632        ic_host_fs::durable::copy_from(
633            &mut source_file,
634            destination,
635            ic_host_fs::durable::WriteOptions {
636                mode: ic_host_fs::durable::PublicationMode::Replace,
637                permissions: 0o666,
638            },
639            None,
640        )
641        .map_err(io::Error::other)
642    })();
643    result.map_err(|source_error| {
644        io::Error::new(
645            source_error.kind(),
646            AtomicCopyErrorContext {
647                source_path: source.to_owned(),
648                destination_path: destination.to_owned(),
649                source: source_error,
650            },
651        )
652    })
653}
654
655#[cfg(unix)]
656pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
657    Cow::Borrowed(value.as_bytes())
658}
659
660#[cfg(windows)]
661pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
662    Cow::Owned(value.encode_wide().flat_map(u16::to_le_bytes).collect())
663}
664
665#[cfg(not(any(unix, windows)))]
666pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
667    Cow::Owned(value.to_string_lossy().as_bytes().to_vec())
668}
669
670#[cfg(test)]
671mod tests {
672    use super::{
673        LabeledPathDigestCache, copy_file_atomic, digest_bytes, digest_file,
674        digest_labeled_paths_composable,
675    };
676    use crate::fs_fixture::unique_temp_directory;
677    use std::{fs, path::PathBuf};
678
679    #[cfg(unix)]
680    use super::{InputHasher, digest_labeled_paths};
681    #[cfg(unix)]
682    use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _};
683    #[cfg(windows)]
684    use std::{ffi::OsString, os::windows::ffi::OsStringExt as _};
685
686    #[test]
687    #[cfg(unix)]
688    fn exclusion_resolution_errors_stop_both_fingerprint_paths() {
689        use std::os::unix::fs::symlink;
690        let root = unique_temp_directory("invalid-digest-exclusions");
691        let input = root.join("input");
692        fs::write(&input, b"source").unwrap();
693        let cycle = root.join("cycle");
694        symlink("cycle", &cycle).unwrap();
695        let paths = [(std::path::Path::new("input"), input.as_path())];
696        assert!(
697            digest_labeled_paths("exclusions-v1", paths, std::slice::from_ref(&cycle)).is_err()
698        );
699        let mut cache = LabeledPathDigestCache::default();
700        let expected =
701            digest_labeled_paths_composable("exclusions-v1", paths, &[], &mut cache).unwrap();
702        assert!(
703            digest_labeled_paths_composable("exclusions-v1", paths, &[cycle], &mut cache).is_err()
704        );
705        // A not-yet-created cache root remains an accepted exclusion, including
706        // on a reused source-lease digest. A failed resolution cannot reuse it.
707        assert_eq!(
708            digest_labeled_paths_composable(
709                "exclusions-v1",
710                paths,
711                &[root.join("missing")],
712                &mut cache,
713            )
714            .unwrap(),
715            expected
716        );
717        assert_eq!(
718            digest_labeled_paths("exclusions-v1", paths, &[]).unwrap(),
719            digest_labeled_paths("exclusions-v1", paths, &[root.join("missing")]).unwrap()
720        );
721        fs::remove_dir_all(root).unwrap();
722    }
723
724    #[test]
725    fn digest_text_preserves_lowercase_hex_and_leading_zeroes() {
726        let digest = super::InputDigest(std::array::from_fn(|index| {
727            u8::try_from(index).expect("digest byte index must fit")
728        }));
729        let expected = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
730        assert_eq!(digest.to_hex(), expected);
731        assert_eq!(digest.to_string(), expected);
732        assert_eq!(super::InputDigest([0xff; 32]).to_string(), "ff".repeat(32));
733    }
734
735    #[test]
736    #[cfg(unix)]
737    fn labeled_path_digests_preserve_native_names_and_sorted_order() {
738        let names: &[&[u8]] = &[
739            b"\xce\xbb",
740            #[cfg(target_os = "linux")]
741            b"\xff",
742        ];
743        for &name in names {
744            let root = unique_temp_directory("native-path-digest");
745            let tree = root.join("tree");
746            fs::create_dir_all(tree.join("nested")).unwrap();
747            fs::write(tree.join(OsStr::from_bytes(name)), b"native").unwrap();
748            fs::write(tree.join("nested/z"), b"last").unwrap();
749            fs::write(tree.join("a"), b"first").unwrap();
750            fs::write(root.join("top"), b"top").unwrap();
751            let mut paths = [
752                (PathBuf::from("tree"), tree),
753                (PathBuf::from("aaa"), root.join("top")),
754            ];
755
756            let tree_fields = |hasher: &mut InputHasher| {
757                hasher.field("directory", b"tree");
758                hasher.field("file-path", b"tree/a");
759                hasher.field("file-content", b"first");
760                hasher.field("directory", b"tree/nested");
761                hasher.field("file-path", b"tree/nested/z");
762                hasher.field("file-content", b"last");
763                hasher.field("file-path", &[b"tree/".as_slice(), name].concat());
764                hasher.field("file-content", b"native");
765            };
766            let mut expected = InputHasher::new("native-path-test-v1");
767            expected.field("file-path", b"aaa");
768            expected.field("file-content", b"top");
769            tree_fields(&mut expected);
770            let expected = expected.finish();
771
772            let mut top = InputHasher::new("native-path-test-v1/root-v1");
773            top.field("file-path", b"aaa");
774            top.field("file-content", b"top");
775            let mut tree = InputHasher::new("native-path-test-v1/root-v1");
776            tree_fields(&mut tree);
777            let mut composable = InputHasher::new("native-path-test-v1/composable-v1");
778            composable.field("input-label", b"aaa");
779            composable.field("input-digest", top.finish().as_bytes());
780            composable.field("input-label", b"tree");
781            composable.field("input-digest", tree.finish().as_bytes());
782            let composable = composable.finish();
783
784            for _ in 0..2 {
785                assert_eq!(
786                    digest_labeled_paths(
787                        "native-path-test-v1",
788                        paths.iter().map(|(label, path)| (label, path)),
789                        &[],
790                    )
791                    .unwrap(),
792                    expected,
793                );
794                assert_eq!(
795                    digest_labeled_paths_composable(
796                        "native-path-test-v1",
797                        paths
798                            .iter()
799                            .map(|(label, path)| (label.as_path(), path.as_path())),
800                        &[],
801                        &mut LabeledPathDigestCache::default(),
802                    )
803                    .unwrap(),
804                    composable,
805                );
806                paths.reverse();
807            }
808            fs::remove_dir_all(root).unwrap();
809        }
810    }
811
812    #[test]
813    #[cfg(unix)]
814    fn native_bytes_preserve_non_utf8_without_a_filesystem_roundtrip() {
815        assert_eq!(
816            super::os_bytes(OsStr::from_bytes(b"name\xff")).as_ref(),
817            b"name\xff"
818        );
819    }
820
821    #[test]
822    #[cfg(windows)]
823    fn native_names_preserve_utf16_little_endian_encoding() {
824        let value = OsString::from_wide(&[0x0061, 0xd800, 0x0100]);
825        assert_eq!(super::os_bytes(&value).as_ref(), &[0x61, 0, 0, 0xd8, 0, 1]);
826    }
827
828    #[test]
829    fn streamed_fields_preserve_bytes_across_different_file_sizes() {
830        let root = unique_temp_directory("streamed-field-sizes");
831        let source = root.join("source");
832        let contents = (0..192 * 1024 + 37)
833            .map(|index| u8::try_from(index % 251).unwrap())
834            .collect::<Vec<_>>();
835        let mut streamed = super::InputHasher::new("streamed-fields-v1");
836        let mut expected = super::InputHasher::new("streamed-fields-v1");
837        for length in [1, 64 * 1024 - 1, contents.len(), 0, 7, 1024, 64 * 1024 + 1] {
838            let bytes = &contents[..length];
839            fs::write(&source, bytes).unwrap();
840            assert_eq!(streamed.file_field("part", &source).unwrap(), length as u64);
841            expected.field("part", bytes);
842        }
843        assert_eq!(streamed.finish(), expected.finish());
844        fs::remove_dir_all(root).unwrap();
845    }
846
847    #[test]
848    fn streaming_digest_and_atomic_copy_preserve_exact_bytes() {
849        let root = unique_temp_directory("streaming-digest");
850        let source = root.join("source");
851        let destination = root.join("destination");
852        let mut contents = vec![0_u8; 192 * 1024 + 37];
853        for (index, byte) in contents.iter_mut().enumerate() {
854            *byte = u8::try_from(index % 251).expect("test byte must fit");
855        }
856        for length in [
857            0,
858            1,
859            1024,
860            16 * 1024,
861            64 * 1024 - 1,
862            64 * 1024,
863            64 * 1024 + 1,
864            contents.len(),
865        ] {
866            let data = &contents[..length];
867            fs::write(&source, data).expect("write source");
868            let streamed = digest_file("streaming-test-v1", &source).expect("digest file");
869            assert_eq!(
870                streamed.bytes,
871                u64::try_from(length).expect("fixture length must fit in u64")
872            );
873            assert_eq!(streamed.digest, digest_bytes("streaming-test-v1", data));
874        }
875
876        ic_host_fs::durable::write_bytes(
877            &destination,
878            ic_host_fs::durable::WriteOptions {
879                mode: ic_host_fs::durable::PublicationMode::Replace,
880                permissions: 0o666,
881            },
882            b"old",
883        )
884        .expect("write original destination");
885        assert_eq!(
886            copy_file_atomic(&source, &destination).expect("copy source atomically"),
887            u64::try_from(contents.len()).expect("fixture length must fit in u64")
888        );
889        assert_eq!(
890            fs::read(&destination).expect("read copied destination"),
891            contents
892        );
893
894        let missing = root.join("missing");
895        let error = copy_file_atomic(&missing, &destination).expect_err("missing source must fail");
896        let message = error.to_string();
897        assert!(message.contains(&missing.display().to_string()));
898        assert!(message.contains(&destination.display().to_string()));
899        fs::remove_dir_all(root).expect("remove streaming-digest test directory");
900    }
901
902    #[test]
903    #[cfg(unix)]
904    fn atomic_copy_retains_publication_phase_and_original_output_on_failure() {
905        use ic_host_fs::durable::NamedWriteError;
906
907        let root = unique_temp_directory("atomic-copy-publication-errors");
908        let destination = root.join("destination");
909        fs::write(&destination, b"retained").unwrap();
910        // Opening a directory succeeds on Unix, but copying its bytes fails
911        // inside the producer after staging has started.
912        let error = copy_file_atomic(&root, &destination).unwrap_err();
913        let context = error
914            .get_ref()
915            .unwrap()
916            .downcast_ref::<super::AtomicCopyErrorContext>()
917            .unwrap();
918        let publication = context
919            .source
920            .get_ref()
921            .unwrap()
922            .downcast_ref::<NamedWriteError<std::io::Error>>()
923            .unwrap();
924        assert!(matches!(
925            publication,
926            NamedWriteError::Producer {
927                cleanup_error: None,
928                ..
929            }
930        ));
931        assert_eq!(fs::read(&destination).unwrap(), b"retained");
932        assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
933        fs::remove_dir_all(root).unwrap();
934    }
935
936    #[test]
937    #[cfg(unix)]
938    fn atomic_copy_rejects_invalid_destinations_without_publication() {
939        use ic_host_fs::durable::NamedWriteError;
940
941        let root = unique_temp_directory("atomic-copy-directory-suffix");
942        let source = root.join("source");
943        let destination = root.join("destination");
944        fs::write(&source, b"replacement").unwrap();
945        fs::write(&destination, b"retained").unwrap();
946        for (name, suffix) in [
947            ("destination", "/"),
948            ("destination", "/."),
949            ("missing/child", "/"),
950            ("missing/child", "/."),
951            ("missing/invalid\0name", ""),
952            ("invalid\0parent/child", ""),
953        ] {
954            let mut raw = root.join(name).into_os_string();
955            raw.push(suffix);
956            let target = PathBuf::from(raw);
957            let error = copy_file_atomic(&source, &target).unwrap_err();
958            let context = error
959                .get_ref()
960                .unwrap()
961                .downcast_ref::<super::AtomicCopyErrorContext>()
962                .unwrap();
963            assert_eq!(context.source_path, source);
964            assert_eq!(context.destination_path, target);
965            let publication = context
966                .source
967                .get_ref()
968                .unwrap()
969                .downcast_ref::<NamedWriteError<std::io::Error>>()
970                .unwrap();
971            assert!(matches!(
972                publication,
973                NamedWriteError::BeforePublication { source, cleanup_error: None }
974                    if source.kind() == std::io::ErrorKind::InvalidInput
975            ));
976            assert_eq!(fs::read(&destination).unwrap(), b"retained");
977            assert_eq!(fs::read_dir(&root).unwrap().count(), 2);
978        }
979        fs::remove_dir_all(root).unwrap();
980    }
981
982    #[test]
983    #[cfg(unix)]
984    fn atomic_publication_supports_long_destination_names() {
985        let root = unique_temp_directory("atomic-long-destination");
986        let destination = root.join("a".repeat(255));
987        // Establish that the destination itself is valid on this filesystem.
988        fs::write(&destination, b"original output").unwrap();
989        let source = root.join("source");
990        fs::write(&source, b"copied output").unwrap();
991        assert_eq!(copy_file_atomic(&source, &destination).unwrap(), 13);
992        assert_eq!(fs::read(&destination).unwrap(), b"copied output");
993        assert_eq!(fs::read_dir(&root).unwrap().count(), 2);
994        fs::remove_dir_all(root).unwrap();
995    }
996
997    #[test]
998    fn composable_digest_reuses_roots_across_irrelevant_exclusion_changes() {
999        let root = unique_temp_directory("composable-digest-cache");
1000        let input = root.join("input");
1001        fs::create_dir_all(&input).expect("create composable input");
1002        fs::create_dir_all(root.join("generated-a")).expect("create first generated root");
1003        fs::create_dir_all(root.join("generated-b")).expect("create second generated root");
1004        fs::write(input.join("source"), b"source").expect("write composable input");
1005        let paths = [(PathBuf::from("shared"), input)];
1006        let mut cache = LabeledPathDigestCache::default();
1007
1008        let first = digest_labeled_paths_composable(
1009            "composable-test-v1",
1010            paths
1011                .iter()
1012                .map(|(label, path)| (label.as_path(), path.as_path())),
1013            &[root.join("generated-a")],
1014            &mut cache,
1015        )
1016        .expect("hash first composable input");
1017        let second = digest_labeled_paths_composable(
1018            "composable-test-v1",
1019            paths
1020                .iter()
1021                .map(|(label, path)| (label.as_path(), path.as_path())),
1022            &[root.join("generated-b")],
1023            &mut cache,
1024        )
1025        .expect("reuse composable input root");
1026
1027        assert_eq!(first, second);
1028        assert_eq!(cache.entries.len(), 1);
1029        fs::remove_dir_all(root).expect("remove composable digest fixture");
1030    }
1031
1032    #[test]
1033    fn composable_digest_rehashes_changed_descendant_exclusions_and_rejects_ancestors() {
1034        let root = unique_temp_directory("composable-relevant-exclusions");
1035        let input = root.join("input");
1036        let generated = input.join("generated");
1037        fs::create_dir_all(&generated).unwrap();
1038        fs::write(input.join("source"), b"source").unwrap();
1039        fs::write(generated.join("artifact"), b"generated").unwrap();
1040        let paths = [(PathBuf::from("input"), input.clone())];
1041        let digest = |exclusions: &[PathBuf], cache: &mut LabeledPathDigestCache| {
1042            digest_labeled_paths_composable(
1043                "exclusions-test-v1",
1044                paths
1045                    .iter()
1046                    .map(|(label, path)| (label.as_path(), path.as_path())),
1047                exclusions,
1048                cache,
1049            )
1050        };
1051        let mut cache = LabeledPathDigestCache::default();
1052        let excluded = digest(std::slice::from_ref(&generated), &mut cache).unwrap();
1053        let included = digest(&[], &mut cache).unwrap();
1054        assert_ne!(included, excluded);
1055        assert_eq!(
1056            included,
1057            digest(&[], &mut LabeledPathDigestCache::default()).unwrap(),
1058        );
1059        for ancestor in [&input, &root] {
1060            assert_eq!(
1061                digest(std::slice::from_ref(ancestor), &mut cache)
1062                    .unwrap_err()
1063                    .kind(),
1064                std::io::ErrorKind::InvalidInput,
1065            );
1066        }
1067        assert_eq!(
1068            digest(std::slice::from_ref(&generated), &mut cache).unwrap(),
1069            excluded,
1070        );
1071        fs::remove_dir_all(root).unwrap();
1072    }
1073
1074    #[test]
1075    #[cfg(unix)]
1076    fn composable_digest_tracks_exclusions_beyond_an_external_symlink() {
1077        let root = unique_temp_directory("composable-external-exclusions");
1078        let input = root.join("input");
1079        let external = root.join("external");
1080        fs::create_dir_all(&input).unwrap();
1081        fs::create_dir_all(external.join("first")).unwrap();
1082        fs::create_dir_all(external.join("second")).unwrap();
1083        fs::write(input.join("source"), b"source").unwrap();
1084        fs::write(external.join("first/file"), b"first").unwrap();
1085        fs::write(external.join("second/file"), b"second").unwrap();
1086        std::os::unix::fs::symlink(&external, input.join("linked")).unwrap();
1087        let paths = [(PathBuf::from("input"), input)];
1088        let digest = |exclusion: &PathBuf, cache: &mut LabeledPathDigestCache| {
1089            digest_labeled_paths_composable(
1090                "external-exclusions-test-v1",
1091                paths
1092                    .iter()
1093                    .map(|(label, path)| (label.as_path(), path.as_path())),
1094                std::slice::from_ref(exclusion),
1095                cache,
1096            )
1097        };
1098        let mut cache = LabeledPathDigestCache::default();
1099        let first = digest(&external.join("first"), &mut cache).unwrap();
1100        let second = digest(&external.join("second"), &mut cache).unwrap();
1101        assert_ne!(first, second);
1102        assert_eq!(
1103            second,
1104            digest(
1105                &external.join("second"),
1106                &mut LabeledPathDigestCache::default(),
1107            )
1108            .unwrap(),
1109        );
1110        assert_eq!(digest(&external.join("first"), &mut cache).unwrap(), first);
1111        fs::remove_dir_all(root).unwrap();
1112    }
1113}