1mod member;
4mod upload;
5mod verification;
6pub use upload::{IcSnapshotDataUploadPreparationError, IcSnapshotUploadArtifactError};
7
8use super::{DownloadJournalError, DownloadJournalGuard};
9use crate::{
10 model::{
11 artifacts::{ArtifactChecksumRecord, ChecksumError},
12 download_journal::{ArtifactStateRecord, ArtifactTransition},
13 ic_snapshot_coverage::{IcSnapshotDataCoverage, IcSnapshotDataCoverageError},
14 ic_snapshot_data::IcSnapshotDataReply,
15 ic_snapshot_metadata::{IcSnapshotMetadataReply, MAX_IC_SNAPSHOT_METADATA_BYTES},
16 },
17 ops::{
18 artifacts::{ArtifactError, checksum_directory, checksum_relative_files},
19 persistence::json::write_encoded,
20 },
21};
22use ic_host_artifacts::artifact::HashingWriter;
23use ic_host_fs::read::open_directory_no_follow;
24use rustix::fs::{self as unix_fs, AtFlags, Dir, FileType, Mode, OFlags};
25use std::{
26 collections::BTreeSet,
27 ffi::OsStr,
28 fmt,
29 fs::{self, File},
30 io::{self, Write},
31 os::fd::AsFd,
32 path::{Path, PathBuf},
33};
34use thiserror::Error;
35
36const FORMAT: &[u8] = b"ic-backup/ic-snapshot-artifact/v1\n";
37const REGIONS: [&str; 3] = ["wasm-module.bin", "wasm-memory.bin", "stable-memory.bin"];
38
39pub struct IcSnapshotArtifactWriter<'journal, 'layout, 'metadata> {
53 journal: &'journal mut DownloadJournalGuard<'layout>,
54 coverage: IcSnapshotDataCoverage<'metadata>,
55 snapshot: String,
56 path: PathBuf,
57 parent: File,
58 directory: File,
59 regions: [HashingWriter<File>; 3],
60 checksums: Vec<(PathBuf, ArtifactChecksumRecord)>,
61}
62
63impl<'layout> DownloadJournalGuard<'layout> {
64 pub fn stage_ic_snapshot_artifact<'journal, 'metadata>(
76 &'journal mut self,
77 snapshot: &str,
78 metadata: &'metadata IcSnapshotMetadataReply<'metadata>,
79 raw_metadata: &[u8],
80 ) -> Result<IcSnapshotArtifactWriter<'journal, 'layout, 'metadata>, IcSnapshotArtifactError>
81 {
82 self.check_usable()?;
83 let entry = self
84 .record
85 .artifact(metadata.request().target(), snapshot)
86 .map_err(DownloadJournalError::from)?;
87 if entry.state() != ArtifactStateRecord::Created
88 || entry.snapshot_taken_at_timestamp() != metadata.metadata().taken_at_timestamp
89 || raw_metadata.len() > MAX_IC_SNAPSHOT_METADATA_BYTES
90 || ArtifactChecksumRecord::from_bytes(raw_metadata) != *metadata.payload_checksum()
91 {
92 return Err(IcSnapshotArtifactError::OriginalMismatch);
93 }
94 self.check_artifact_parent()?;
95 let path = self.layout.root().join(entry.staging_path());
96 let canonical = self.layout.root().join(entry.artifact_path());
97 match fs::symlink_metadata(canonical) {
98 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
99 Err(error) => return Err(error.into()),
100 Ok(_) => return Err(io::Error::from(io::ErrorKind::AlreadyExists).into()),
101 }
102 let parent = open_directory_no_follow(&self.layout.root().join("artifacts"))?;
103 let name = path
104 .file_name()
105 .ok_or(IcSnapshotArtifactError::CustodyChanged)?;
106 unix_fs::mkdirat(&parent, name, Mode::from_bits_truncate(0o700))
107 .map_err(io::Error::from)?;
108 let directory = File::from(
109 unix_fs::openat(
110 &parent,
111 name,
112 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
113 Mode::empty(),
114 )
115 .map_err(io::Error::from)?,
116 );
117 let mut checksums = Vec::new();
118 for (name, bytes) in [
119 ("format", FORMAT),
120 ("metadata.candid", raw_metadata),
121 ("metadata-arguments.candid", metadata.request().arguments()),
122 ] {
123 create_file(&directory, name)?.write_all(bytes)?;
124 checksums.push((name.into(), ArtifactChecksumRecord::from_bytes(bytes)));
125 }
126 let regions = [
127 create_file(&directory, REGIONS[0])?,
128 create_file(&directory, REGIONS[1])?,
129 create_file(&directory, REGIONS[2])?,
130 ]
131 .map(|file| HashingWriter::new(file, u64::MAX));
132 let writer = IcSnapshotArtifactWriter {
133 journal: self,
134 coverage: IcSnapshotDataCoverage::new(metadata),
135 snapshot: snapshot.to_owned(),
136 path,
137 parent,
138 directory,
139 regions,
140 checksums,
141 };
142 writer.check_custody()?;
143 Ok(writer)
144 }
145}
146
147impl<'layout> IcSnapshotArtifactWriter<'_, 'layout, '_> {
148 pub(crate) fn validate_transfer_origin(
151 &self,
152 root: &Path,
153 intent: &str,
154 ) -> Result<(), IcSnapshotArtifactError> {
155 self.check_custody()?;
156 self.check_region_custody()?;
157 if self.journal.layout.root() != root || self.journal.record()?.intent() != intent {
158 return Err(IcSnapshotArtifactError::OriginalMismatch);
159 }
160 Ok(())
161 }
162
163 #[must_use]
165 pub const fn coverage(&self) -> &IcSnapshotDataCoverage<'_> {
166 &self.coverage
167 }
168
169 #[must_use]
171 pub fn path(&self) -> &Path {
172 &self.path
173 }
174
175 pub fn append(
187 mut self,
188 reply: &IcSnapshotDataReply<'_, '_>,
189 ) -> Result<Self, IcSnapshotArtifactError> {
190 self.check_custody()?;
191 self.check_region_custody()?;
192 self.coverage.admit(reply)?;
193 let index = match member::select(reply.request().kind())? {
194 member::Member::Region { region, .. } => region.index(),
195 member::Member::Chunk { name } => {
196 create_file(&self.directory, &name)?.write_all(reply.chunk())?;
197 self.checksums
198 .push((name.into(), reply.chunk_checksum().clone()));
199 self.check_custody()?;
200 return Ok(self);
201 }
202 };
203 self.regions[index].write_all(reply.chunk())?;
204 self.check_custody()?;
205 Ok(self)
206 }
207
208 pub fn finish(self) -> Result<ArtifactChecksumRecord, IcSnapshotArtifactError> {
226 self.finish_with(DownloadJournalGuard::finalize_artifact)
227 }
228
229 fn finish_with(
230 mut self,
231 publish: impl FnOnce(
232 &mut DownloadJournalGuard<'layout>,
233 &str,
234 &str,
235 ) -> Result<(), DownloadJournalError>,
236 ) -> Result<ArtifactChecksumRecord, IcSnapshotArtifactError> {
237 if self.coverage.complete().is_none() {
238 return Err(IcSnapshotArtifactError::IncompleteCoverage);
239 }
240 self.check_custody()?;
241 for (name, region) in REGIONS.into_iter().zip(&self.regions) {
242 self.checksums.push((
243 name.into(),
244 ArtifactChecksumRecord::from_digest(*region.identity().sha256.as_bytes()),
245 ));
246 }
247 self.check_closed_tree()?;
248 let expected = checksum_relative_files(std::mem::take(&mut self.checksums))
249 .map_err(ArtifactError::from)?;
250 checksum_directory(&self.path)?.verify(expected.hash())?;
251 self.check_custody()?;
252 let target = self.coverage.metadata().request().target();
253 let next = self.journal.next(
254 target,
255 &self.snapshot,
256 ArtifactTransition::ChecksumVerified(expected.clone()),
257 )?;
258 self.journal.store(next, write_encoded)?;
259 publish(self.journal, target, &self.snapshot)?;
260 self.journal.check_usable()?;
261 check_directory_identity(
262 self.path
263 .parent()
264 .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
265 &self.parent,
266 )?;
267 let entry = self
268 .journal
269 .record
270 .artifact(target, &self.snapshot)
271 .map_err(DownloadJournalError::from)?;
272 check_directory_identity(
273 &self.journal.layout.root().join(entry.artifact_path()),
274 &self.directory,
275 )?;
276 Ok(expected)
277 }
278
279 fn check_custody(&self) -> Result<(), IcSnapshotArtifactError> {
280 self.journal.check_usable()?;
281 for (path, held) in [
282 (
283 self.path
284 .parent()
285 .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
286 &self.parent,
287 ),
288 (self.path.as_path(), &self.directory),
289 ] {
290 check_directory_identity(path, held)?;
291 }
292 Ok(())
293 }
294
295 fn check_closed_tree(&self) -> Result<(), IcSnapshotArtifactError> {
296 check_closed_tree(
297 &self.directory,
298 self.checksums.iter().map(|(path, _)| path.as_os_str()),
299 )
300 }
301
302 fn check_region_custody(&self) -> Result<(), IcSnapshotArtifactError> {
303 for ((name, file), expected) in REGIONS
304 .iter()
305 .zip(&self.regions)
306 .zip(self.coverage.covered_region_bytes())
307 {
308 let held = unix_fs::fstat(file.get_ref()).map_err(io::Error::from)?;
309 let current = unix_fs::statat(&self.directory, *name, AtFlags::SYMLINK_NOFOLLOW)
310 .map_err(io::Error::from)?;
311 let same_file = (current.st_dev, current.st_ino) == (held.st_dev, held.st_ino);
312 let exact_extent = current.st_size == held.st_size
313 && u64::try_from(held.st_size).ok() == Some(expected);
314 if !FileType::from_raw_mode(current.st_mode).is_file() || !same_file || !exact_extent {
315 return Err(IcSnapshotArtifactError::FileShape);
316 }
317 }
318 Ok(())
319 }
320}
321
322fn check_closed_tree<'a>(
323 directory: &File,
324 names: impl IntoIterator<Item = &'a std::ffi::OsStr>,
325) -> Result<(), IcSnapshotArtifactError> {
326 let mut expected = names
327 .into_iter()
328 .map(|name| name.as_encoded_bytes().to_vec())
329 .collect::<BTreeSet<_>>();
330 let mut directory = Dir::read_from(directory).map_err(io::Error::from)?;
331 while let Some(entry) = directory.read() {
332 let entry = entry.map_err(io::Error::from)?;
333 let name = entry.file_name().to_bytes();
334 if matches!(name, b"." | b"..") {
335 continue;
336 }
337 if !expected.remove(name) {
338 return Err(IcSnapshotArtifactError::UnexpectedEntry);
339 }
340 }
341 if !expected.is_empty() {
342 return Err(IcSnapshotArtifactError::UnexpectedEntry);
343 }
344 Ok(())
345}
346
347impl fmt::Debug for IcSnapshotArtifactWriter<'_, '_, '_> {
348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349 f.debug_struct("IcSnapshotArtifactWriter")
350 .field("coverage", &self.coverage)
351 .finish_non_exhaustive()
352 }
353}
354
355fn with_artifact_directory<T, E: From<IcSnapshotArtifactError>>(
358 root: &Path,
359 artifact: &str,
360 read: impl FnOnce(&File) -> Result<T, E>,
361 finish: impl FnOnce() -> Result<(), E>,
362) -> Result<T, E> {
363 let parent_path = root.join("artifacts");
364 let parent = open_directory_no_follow(&parent_path).map_err(IcSnapshotArtifactError::from)?;
365 let path = root.join(artifact);
366 let directory = File::from(
367 unix_fs::openat(
368 &parent,
369 path.file_name()
370 .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
371 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
372 Mode::empty(),
373 )
374 .map_err(io::Error::from)
375 .map_err(IcSnapshotArtifactError::from)?,
376 );
377 let result = read(&directory)?;
378 check_directory_identity(&parent_path, &parent)?;
379 check_directory_identity(&path, &directory)?;
380 finish()?;
381 Ok(result)
382}
383
384fn check_directory_identity(path: &Path, held: &File) -> Result<(), IcSnapshotArtifactError> {
385 match ic_host_fs::durable::admit_directory(path, held) {
386 Ok(()) => Ok(()),
387 Err(error) if error.kind() == io::ErrorKind::InvalidInput => {
388 Err(IcSnapshotArtifactError::CustodyChanged)
389 }
390 Err(error) => Err(error.into()),
391 }
392}
393
394fn create_file(directory: &File, name: &str) -> io::Result<File> {
395 ic_host_fs::durable::create_retained_at(directory.as_fd(), OsStr::new(name), 0o600)
396}
397
398#[derive(Debug, Error)]
400pub enum IcSnapshotArtifactError {
401 #[error("IC snapshot artifact original evidence mismatch")]
403 OriginalMismatch,
404 #[error("IC snapshot artifact coverage is incomplete")]
406 IncompleteCoverage,
407 #[error("IC snapshot artifact directory custody changed")]
409 CustodyChanged,
410 #[error("IC snapshot artifact tree entries differ")]
412 UnexpectedEntry,
413 #[error("IC snapshot artifact file type or length differs")]
415 FileShape,
416 #[error(transparent)]
418 Integrity(#[from] super::DownloadIntegrityError),
419 #[error(transparent)]
421 Coverage(#[from] IcSnapshotDataCoverageError),
422 #[error(transparent)]
424 Checksum(#[from] ChecksumError),
425 #[error(transparent)]
427 Journal(#[from] DownloadJournalError),
428 #[error(transparent)]
430 Artifact(#[from] ArtifactError),
431 #[error(transparent)]
433 Io(#[from] io::Error),
434}
435
436#[cfg(test)]
437mod tests;