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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44pub struct InputDigest([u8; 32]);
45
46impl InputDigest {
47 #[must_use]
49 pub const fn as_bytes(&self) -> &[u8; 32] {
50 &self.0
51 }
52
53 #[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 let buffer_len = usize::try_from(expected_len.clamp(1, 64 * 1024))
113 .expect("bounded artifact buffer length must fit in usize");
114 if self.read_buffer.len() < buffer_len {
117 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
172pub(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
183pub(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 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
201pub(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 let effective_uid = unsafe { libc::geteuid() };
228 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 let _ = (destination, expected_bytes);
245 false
246 }
247}
248
249fn 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 #[cfg(unix)]
466 entries.sort_unstable_by(|left, right| os_bytes(left).cmp(&os_bytes(right)));
467 #[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(
488 destination,
489 ic_host_fs::durable::WriteOptions {
490 mode: ic_host_fs::durable::PublicationMode::Replace,
491 permissions: 0o666,
492 },
493 |destination_file| io::copy(&mut source_file, destination_file),
494 )
495 .map_err(io::Error::other)
496 })();
497 result.map_err(|source_error| {
498 io::Error::new(
499 source_error.kind(),
500 AtomicCopyErrorContext {
501 source_path: source.to_owned(),
502 destination_path: destination.to_owned(),
503 source: source_error,
504 },
505 )
506 })
507}
508
509#[cfg(unix)]
510pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
511 Cow::Borrowed(value.as_bytes())
512}
513
514#[cfg(windows)]
515pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
516 Cow::Owned(value.encode_wide().flat_map(u16::to_le_bytes).collect())
517}
518
519#[cfg(not(any(unix, windows)))]
520pub(super) fn os_bytes(value: &OsStr) -> Cow<'_, [u8]> {
521 Cow::Owned(value.to_string_lossy().as_bytes().to_vec())
522}
523
524#[cfg(test)]
525mod tests {
526 use super::{
527 LabeledPathDigestCache, copy_file_atomic, digest_bytes, digest_file,
528 digest_labeled_paths_composable,
529 };
530 use crate::artifacts::test_support::unique_temp_directory;
531 use std::{fs, path::PathBuf};
532
533 #[cfg(unix)]
534 use super::{InputHasher, digest_labeled_paths};
535 #[cfg(unix)]
536 use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _};
537 #[cfg(windows)]
538 use std::{ffi::OsString, os::windows::ffi::OsStringExt as _};
539
540 #[test]
541 #[cfg(unix)]
542 fn exclusion_resolution_errors_stop_both_fingerprint_paths() {
543 use std::os::unix::fs::symlink;
544 let root = unique_temp_directory("invalid-digest-exclusions");
545 let input = root.join("input");
546 fs::write(&input, b"source").unwrap();
547 let cycle = root.join("cycle");
548 symlink("cycle", &cycle).unwrap();
549 let paths = [(std::path::Path::new("input"), input.as_path())];
550 assert!(
551 digest_labeled_paths("exclusions-v1", paths, std::slice::from_ref(&cycle)).is_err()
552 );
553 let mut cache = LabeledPathDigestCache::default();
554 let expected =
555 digest_labeled_paths_composable("exclusions-v1", paths, &[], &mut cache).unwrap();
556 assert!(
557 digest_labeled_paths_composable("exclusions-v1", paths, &[cycle], &mut cache).is_err()
558 );
559 assert_eq!(
562 digest_labeled_paths_composable(
563 "exclusions-v1",
564 paths,
565 &[root.join("missing")],
566 &mut cache,
567 )
568 .unwrap(),
569 expected
570 );
571 assert_eq!(
572 digest_labeled_paths("exclusions-v1", paths, &[]).unwrap(),
573 digest_labeled_paths("exclusions-v1", paths, &[root.join("missing")]).unwrap()
574 );
575 fs::remove_dir_all(root).unwrap();
576 }
577
578 #[test]
579 fn digest_text_preserves_lowercase_hex_and_leading_zeroes() {
580 let digest = super::InputDigest(std::array::from_fn(|index| {
581 u8::try_from(index).expect("digest byte index must fit")
582 }));
583 let expected = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
584 assert_eq!(digest.to_hex(), expected);
585 assert_eq!(digest.to_string(), expected);
586 assert_eq!(super::InputDigest([0xff; 32]).to_string(), "ff".repeat(32));
587 }
588
589 #[test]
590 #[cfg(unix)]
591 fn labeled_path_digests_preserve_native_names_and_sorted_order() {
592 let names: &[&[u8]] = &[
593 b"\xce\xbb",
594 #[cfg(target_os = "linux")]
595 b"\xff",
596 ];
597 for &name in names {
598 let root = unique_temp_directory("native-path-digest");
599 let tree = root.join("tree");
600 fs::create_dir_all(tree.join("nested")).unwrap();
601 fs::write(tree.join(OsStr::from_bytes(name)), b"native").unwrap();
602 fs::write(tree.join("nested/z"), b"last").unwrap();
603 fs::write(tree.join("a"), b"first").unwrap();
604 fs::write(root.join("top"), b"top").unwrap();
605 let mut paths = [
606 (PathBuf::from("tree"), tree),
607 (PathBuf::from("aaa"), root.join("top")),
608 ];
609
610 let tree_fields = |hasher: &mut InputHasher| {
611 hasher.field("directory", b"tree");
612 hasher.field("file-path", b"tree/a");
613 hasher.field("file-content", b"first");
614 hasher.field("directory", b"tree/nested");
615 hasher.field("file-path", b"tree/nested/z");
616 hasher.field("file-content", b"last");
617 hasher.field("file-path", &[b"tree/".as_slice(), name].concat());
618 hasher.field("file-content", b"native");
619 };
620 let mut expected = InputHasher::new("native-path-test-v1");
621 expected.field("file-path", b"aaa");
622 expected.field("file-content", b"top");
623 tree_fields(&mut expected);
624 let expected = expected.finish();
625
626 let mut top = InputHasher::new("native-path-test-v1/root-v1");
627 top.field("file-path", b"aaa");
628 top.field("file-content", b"top");
629 let mut tree = InputHasher::new("native-path-test-v1/root-v1");
630 tree_fields(&mut tree);
631 let mut composable = InputHasher::new("native-path-test-v1/composable-v1");
632 composable.field("input-label", b"aaa");
633 composable.field("input-digest", top.finish().as_bytes());
634 composable.field("input-label", b"tree");
635 composable.field("input-digest", tree.finish().as_bytes());
636 let composable = composable.finish();
637
638 for _ in 0..2 {
639 assert_eq!(
640 digest_labeled_paths(
641 "native-path-test-v1",
642 paths.iter().map(|(label, path)| (label, path)),
643 &[],
644 )
645 .unwrap(),
646 expected,
647 );
648 assert_eq!(
649 digest_labeled_paths_composable(
650 "native-path-test-v1",
651 paths
652 .iter()
653 .map(|(label, path)| (label.as_path(), path.as_path())),
654 &[],
655 &mut LabeledPathDigestCache::default(),
656 )
657 .unwrap(),
658 composable,
659 );
660 paths.reverse();
661 }
662 fs::remove_dir_all(root).unwrap();
663 }
664 }
665
666 #[test]
667 #[cfg(unix)]
668 fn native_bytes_preserve_non_utf8_without_a_filesystem_roundtrip() {
669 assert_eq!(
670 super::os_bytes(OsStr::from_bytes(b"name\xff")).as_ref(),
671 b"name\xff"
672 );
673 }
674
675 #[test]
676 #[cfg(windows)]
677 fn native_names_preserve_utf16_little_endian_encoding() {
678 let value = OsString::from_wide(&[0x0061, 0xd800, 0x0100]);
679 assert_eq!(super::os_bytes(&value).as_ref(), &[0x61, 0, 0, 0xd8, 0, 1]);
680 }
681
682 #[test]
683 fn streamed_fields_preserve_bytes_across_different_file_sizes() {
684 let root = unique_temp_directory("streamed-field-sizes");
685 let source = root.join("source");
686 let contents = (0..192 * 1024 + 37)
687 .map(|index| u8::try_from(index % 251).unwrap())
688 .collect::<Vec<_>>();
689 let mut streamed = super::InputHasher::new("streamed-fields-v1");
690 let mut expected = super::InputHasher::new("streamed-fields-v1");
691 for length in [1, 64 * 1024 - 1, contents.len(), 0, 7, 1024, 64 * 1024 + 1] {
692 let bytes = &contents[..length];
693 fs::write(&source, bytes).unwrap();
694 assert_eq!(streamed.file_field("part", &source).unwrap(), length as u64);
695 expected.field("part", bytes);
696 }
697 assert_eq!(streamed.finish(), expected.finish());
698 fs::remove_dir_all(root).unwrap();
699 }
700
701 #[test]
702 fn streaming_digest_and_atomic_copy_preserve_exact_bytes() {
703 let root = unique_temp_directory("streaming-digest");
704 let source = root.join("source");
705 let destination = root.join("destination");
706 let mut contents = vec![0_u8; 192 * 1024 + 37];
707 for (index, byte) in contents.iter_mut().enumerate() {
708 *byte = u8::try_from(index % 251).expect("test byte must fit");
709 }
710 for length in [
711 0,
712 1,
713 1024,
714 16 * 1024,
715 64 * 1024 - 1,
716 64 * 1024,
717 64 * 1024 + 1,
718 contents.len(),
719 ] {
720 let data = &contents[..length];
721 fs::write(&source, data).expect("write source");
722 let streamed = digest_file("streaming-test-v1", &source).expect("digest file");
723 assert_eq!(
724 streamed.bytes,
725 u64::try_from(length).expect("fixture length must fit in u64")
726 );
727 assert_eq!(streamed.digest, digest_bytes("streaming-test-v1", data));
728 }
729
730 ic_host_fs::durable::write_bytes(&destination, b"old").expect("write original destination");
731 assert_eq!(
732 copy_file_atomic(&source, &destination).expect("copy source atomically"),
733 u64::try_from(contents.len()).expect("fixture length must fit in u64")
734 );
735 assert_eq!(
736 fs::read(&destination).expect("read copied destination"),
737 contents
738 );
739
740 let missing = root.join("missing");
741 let error = copy_file_atomic(&missing, &destination).expect_err("missing source must fail");
742 let message = error.to_string();
743 assert!(message.contains(&missing.display().to_string()));
744 assert!(message.contains(&destination.display().to_string()));
745 fs::remove_dir_all(root).expect("remove streaming-digest test directory");
746 }
747
748 #[test]
749 #[cfg(unix)]
750 fn atomic_copy_retains_publication_phase_and_original_output_on_failure() {
751 use ic_host_fs::durable::NamedWriteError;
752
753 let root = unique_temp_directory("atomic-copy-publication-errors");
754 let destination = root.join("destination");
755 fs::write(&destination, b"retained").unwrap();
756 let error = copy_file_atomic(&root, &destination).unwrap_err();
759 let context = error
760 .get_ref()
761 .unwrap()
762 .downcast_ref::<super::AtomicCopyErrorContext>()
763 .unwrap();
764 let publication = context
765 .source
766 .get_ref()
767 .unwrap()
768 .downcast_ref::<NamedWriteError<std::io::Error>>()
769 .unwrap();
770 assert!(matches!(
771 publication,
772 NamedWriteError::Producer {
773 cleanup_error: None,
774 ..
775 }
776 ));
777 assert_eq!(fs::read(&destination).unwrap(), b"retained");
778 assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
779 fs::remove_dir_all(root).unwrap();
780 }
781
782 #[test]
783 #[cfg(unix)]
784 fn atomic_publication_supports_long_destination_names() {
785 let root = unique_temp_directory("atomic-long-destination");
786 let destination = root.join("a".repeat(255));
787 fs::write(&destination, b"original output").unwrap();
789 let source = root.join("source");
790 fs::write(&source, b"copied output").unwrap();
791 assert_eq!(copy_file_atomic(&source, &destination).unwrap(), 13);
792 assert_eq!(fs::read(&destination).unwrap(), b"copied output");
793 assert_eq!(fs::read_dir(&root).unwrap().count(), 2);
794 fs::remove_dir_all(root).unwrap();
795 }
796
797 #[test]
798 fn composable_digest_reuses_roots_across_irrelevant_exclusion_changes() {
799 let root = unique_temp_directory("composable-digest-cache");
800 let input = root.join("input");
801 fs::create_dir_all(&input).expect("create composable input");
802 fs::create_dir_all(root.join("generated-a")).expect("create first generated root");
803 fs::create_dir_all(root.join("generated-b")).expect("create second generated root");
804 fs::write(input.join("source"), b"source").expect("write composable input");
805 let paths = [(PathBuf::from("shared"), input)];
806 let mut cache = LabeledPathDigestCache::default();
807
808 let first = digest_labeled_paths_composable(
809 "composable-test-v1",
810 paths
811 .iter()
812 .map(|(label, path)| (label.as_path(), path.as_path())),
813 &[root.join("generated-a")],
814 &mut cache,
815 )
816 .expect("hash first composable input");
817 let second = digest_labeled_paths_composable(
818 "composable-test-v1",
819 paths
820 .iter()
821 .map(|(label, path)| (label.as_path(), path.as_path())),
822 &[root.join("generated-b")],
823 &mut cache,
824 )
825 .expect("reuse composable input root");
826
827 assert_eq!(first, second);
828 assert_eq!(cache.entries.len(), 1);
829 fs::remove_dir_all(root).expect("remove composable digest fixture");
830 }
831
832 #[test]
833 fn composable_digest_rehashes_changed_descendant_exclusions_and_rejects_ancestors() {
834 let root = unique_temp_directory("composable-relevant-exclusions");
835 let input = root.join("input");
836 let generated = input.join("generated");
837 fs::create_dir_all(&generated).unwrap();
838 fs::write(input.join("source"), b"source").unwrap();
839 fs::write(generated.join("artifact"), b"generated").unwrap();
840 let paths = [(PathBuf::from("input"), input.clone())];
841 let digest = |exclusions: &[PathBuf], cache: &mut LabeledPathDigestCache| {
842 digest_labeled_paths_composable(
843 "exclusions-test-v1",
844 paths
845 .iter()
846 .map(|(label, path)| (label.as_path(), path.as_path())),
847 exclusions,
848 cache,
849 )
850 };
851 let mut cache = LabeledPathDigestCache::default();
852 let excluded = digest(std::slice::from_ref(&generated), &mut cache).unwrap();
853 let included = digest(&[], &mut cache).unwrap();
854 assert_ne!(included, excluded);
855 assert_eq!(
856 included,
857 digest(&[], &mut LabeledPathDigestCache::default()).unwrap(),
858 );
859 for ancestor in [&input, &root] {
860 assert_eq!(
861 digest(std::slice::from_ref(ancestor), &mut cache)
862 .unwrap_err()
863 .kind(),
864 std::io::ErrorKind::InvalidInput,
865 );
866 }
867 assert_eq!(
868 digest(std::slice::from_ref(&generated), &mut cache).unwrap(),
869 excluded,
870 );
871 fs::remove_dir_all(root).unwrap();
872 }
873
874 #[test]
875 #[cfg(unix)]
876 fn composable_digest_tracks_exclusions_beyond_an_external_symlink() {
877 let root = unique_temp_directory("composable-external-exclusions");
878 let input = root.join("input");
879 let external = root.join("external");
880 fs::create_dir_all(&input).unwrap();
881 fs::create_dir_all(external.join("first")).unwrap();
882 fs::create_dir_all(external.join("second")).unwrap();
883 fs::write(input.join("source"), b"source").unwrap();
884 fs::write(external.join("first/file"), b"first").unwrap();
885 fs::write(external.join("second/file"), b"second").unwrap();
886 std::os::unix::fs::symlink(&external, input.join("linked")).unwrap();
887 let paths = [(PathBuf::from("input"), input)];
888 let digest = |exclusion: &PathBuf, cache: &mut LabeledPathDigestCache| {
889 digest_labeled_paths_composable(
890 "external-exclusions-test-v1",
891 paths
892 .iter()
893 .map(|(label, path)| (label.as_path(), path.as_path())),
894 std::slice::from_ref(exclusion),
895 cache,
896 )
897 };
898 let mut cache = LabeledPathDigestCache::default();
899 let first = digest(&external.join("first"), &mut cache).unwrap();
900 let second = digest(&external.join("second"), &mut cache).unwrap();
901 assert_ne!(first, second);
902 assert_eq!(
903 second,
904 digest(
905 &external.join("second"),
906 &mut LabeledPathDigestCache::default(),
907 )
908 .unwrap(),
909 );
910 assert_eq!(digest(&external.join("first"), &mut cache).unwrap(), first);
911 fs::remove_dir_all(root).unwrap();
912 }
913}