1mod upload;
4mod verification;
5pub use upload::IcSnapshotUploadArtifactError;
6
7use super::{DownloadJournalError, DownloadJournalGuard};
8use crate::{
9 hash::hex_bytes,
10 model::{
11 artifacts::{ArtifactChecksumRecord, ChecksumError},
12 download_journal::ArtifactStateRecord,
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::write_json_durable,
20 },
21};
22use ic_management_canister_types::SnapshotDataKind;
23use rustix::fs::{self as unix_fs, AtFlags, Dir, FileType, Mode, OFlags};
24use sha2::{Digest, Sha256};
25use std::{
26 collections::BTreeSet,
27 fmt,
28 fs::{self, File},
29 io::{self, Write},
30 os::unix::fs::MetadataExt,
31 path::{Path, PathBuf},
32};
33use thiserror::Error;
34
35const FORMAT: &[u8] = b"ic-backup/ic-snapshot-artifact/v1\n";
36const REGIONS: [&str; 3] = ["wasm-module.bin", "wasm-memory.bin", "stable-memory.bin"];
37
38pub struct IcSnapshotArtifactWriter<'journal, 'layout, 'metadata> {
52 journal: &'journal mut DownloadJournalGuard<'layout>,
53 coverage: IcSnapshotDataCoverage<'metadata>,
54 snapshot: String,
55 path: PathBuf,
56 parent: File,
57 directory: File,
58 regions: [File; 3],
59 hashes: [Sha256; 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(&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 let writer = IcSnapshotArtifactWriter {
132 journal: self,
133 coverage: IcSnapshotDataCoverage::new(metadata),
134 snapshot: snapshot.to_owned(),
135 path,
136 parent,
137 directory,
138 regions,
139 hashes: std::array::from_fn(|_| Sha256::new()),
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(
185 mut self,
186 reply: &IcSnapshotDataReply<'_, '_>,
187 ) -> Result<Self, IcSnapshotArtifactError> {
188 self.check_custody()?;
189 self.check_region_custody()?;
190 self.coverage.admit(reply)?;
191 let index = match reply.request().kind() {
192 SnapshotDataKind::WasmModule { .. } => 0,
193 SnapshotDataKind::WasmMemory { .. } => 1,
194 SnapshotDataKind::StableMemory { .. } => 2,
195 SnapshotDataKind::WasmChunk { hash } => {
196 let name = format!("chunk-{}.bin", hex_bytes(hash));
197 create_file(&self.directory, &name)?.write_all(reply.chunk())?;
198 self.checksums
199 .push((name.into(), reply.chunk_checksum().clone()));
200 self.check_custody()?;
201 return Ok(self);
202 }
203 };
204 self.regions[index].write_all(reply.chunk())?;
205 self.hashes[index].update(reply.chunk());
206 self.check_custody()?;
207 Ok(self)
208 }
209
210 pub fn finish(self) -> Result<ArtifactChecksumRecord, IcSnapshotArtifactError> {
228 self.finish_with(DownloadJournalGuard::finalize_artifact)
229 }
230
231 fn finish_with(
232 mut self,
233 publish: impl FnOnce(
234 &mut DownloadJournalGuard<'layout>,
235 &str,
236 &str,
237 ) -> Result<(), DownloadJournalError>,
238 ) -> Result<ArtifactChecksumRecord, IcSnapshotArtifactError> {
239 if self.coverage.complete().is_none() {
240 return Err(IcSnapshotArtifactError::IncompleteCoverage);
241 }
242 self.check_custody()?;
243 for (name, hash) in REGIONS.into_iter().zip(self.hashes.iter()) {
244 self.checksums.push((
245 name.into(),
246 ArtifactChecksumRecord::from_digest(hash.clone().finalize().into()),
247 ));
248 }
249 self.check_closed_tree()?;
250 let expected = checksum_relative_files(std::mem::take(&mut self.checksums))
251 .map_err(ArtifactError::from)?;
252 checksum_directory(&self.path)?.verify(expected.hash())?;
253 self.check_custody()?;
254 let target = self.coverage.metadata().request().target();
255 let mut next = self.journal.next(
256 target,
257 &self.snapshot,
258 ArtifactStateRecord::Downloaded,
259 None,
260 )?;
261 next.advance(
262 target,
263 &self.snapshot,
264 ArtifactStateRecord::ChecksumVerified,
265 Some(expected.clone()),
266 )
267 .map_err(DownloadJournalError::from)?;
268 self.journal.store(next, write_json_durable)?;
269 publish(self.journal, target, &self.snapshot)?;
270 self.journal.check_usable()?;
271 check_directory_identity(
272 self.path
273 .parent()
274 .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
275 &self.parent,
276 )?;
277 let entry = self
278 .journal
279 .record
280 .artifact(target, &self.snapshot)
281 .map_err(DownloadJournalError::from)?;
282 check_directory_identity(
283 &self.journal.layout.root().join(entry.artifact_path()),
284 &self.directory,
285 )?;
286 Ok(expected)
287 }
288
289 fn check_custody(&self) -> Result<(), IcSnapshotArtifactError> {
290 self.journal.check_usable()?;
291 for (path, held) in [
292 (
293 self.path
294 .parent()
295 .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
296 &self.parent,
297 ),
298 (self.path.as_path(), &self.directory),
299 ] {
300 check_directory_identity(path, held)?;
301 }
302 Ok(())
303 }
304
305 fn check_closed_tree(&self) -> Result<(), IcSnapshotArtifactError> {
306 check_closed_tree(&self.directory, &self.checksums)
307 }
308
309 fn check_region_custody(&self) -> Result<(), IcSnapshotArtifactError> {
310 for ((name, file), expected) in REGIONS
311 .iter()
312 .zip(&self.regions)
313 .zip(self.coverage.covered_region_bytes())
314 {
315 let held = unix_fs::fstat(file).map_err(io::Error::from)?;
316 let current = unix_fs::statat(&self.directory, *name, AtFlags::SYMLINK_NOFOLLOW)
317 .map_err(io::Error::from)?;
318 let same_file = (current.st_dev, current.st_ino) == (held.st_dev, held.st_ino);
319 let exact_extent = current.st_size == held.st_size
320 && u64::try_from(held.st_size).ok() == Some(expected);
321 if !FileType::from_raw_mode(current.st_mode).is_file() || !same_file || !exact_extent {
322 return Err(IcSnapshotArtifactError::FileShape);
323 }
324 }
325 Ok(())
326 }
327}
328
329fn check_closed_tree(
330 directory: &File,
331 checksums: &[(PathBuf, ArtifactChecksumRecord)],
332) -> Result<(), IcSnapshotArtifactError> {
333 let mut expected = checksums
334 .iter()
335 .map(|(path, _)| path.as_os_str().as_encoded_bytes().to_vec())
336 .collect::<BTreeSet<_>>();
337 let mut directory = Dir::read_from(directory).map_err(io::Error::from)?;
338 while let Some(entry) = directory.read() {
339 let entry = entry.map_err(io::Error::from)?;
340 let name = entry.file_name().to_bytes();
341 if matches!(name, b"." | b"..") {
342 continue;
343 }
344 if !expected.remove(name) {
345 return Err(IcSnapshotArtifactError::UnexpectedEntry);
346 }
347 }
348 if !expected.is_empty() {
349 return Err(IcSnapshotArtifactError::UnexpectedEntry);
350 }
351 Ok(())
352}
353
354impl fmt::Debug for IcSnapshotArtifactWriter<'_, '_, '_> {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.debug_struct("IcSnapshotArtifactWriter")
357 .field("coverage", &self.coverage)
358 .finish_non_exhaustive()
359 }
360}
361
362fn open_directory(path: &Path) -> io::Result<File> {
363 unix_fs::open(
364 path,
365 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
366 Mode::empty(),
367 )
368 .map(File::from)
369 .map_err(io::Error::from)
370}
371
372fn check_directory_identity(path: &Path, held: &File) -> Result<(), IcSnapshotArtifactError> {
373 let current = fs::symlink_metadata(path)?;
374 let original = held.metadata()?;
375 if !current.is_dir() || current.dev() != original.dev() || current.ino() != original.ino() {
376 return Err(IcSnapshotArtifactError::CustodyChanged);
377 }
378 Ok(())
379}
380
381fn create_file(directory: &File, name: &str) -> io::Result<File> {
382 unix_fs::openat(
383 directory,
384 name,
385 OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
386 Mode::from_bits_truncate(0o600),
387 )
388 .map(File::from)
389 .map_err(io::Error::from)
390}
391
392#[derive(Debug, Error)]
394pub enum IcSnapshotArtifactError {
395 #[error("IC snapshot artifact original evidence mismatch")]
397 OriginalMismatch,
398 #[error("IC snapshot artifact coverage is incomplete")]
400 IncompleteCoverage,
401 #[error("IC snapshot artifact directory custody changed")]
403 CustodyChanged,
404 #[error("IC snapshot artifact tree entries differ")]
406 UnexpectedEntry,
407 #[error("IC snapshot artifact file type or length differs")]
409 FileShape,
410 #[error(transparent)]
412 Integrity(#[from] super::DownloadIntegrityError),
413 #[error(transparent)]
415 Coverage(#[from] IcSnapshotDataCoverageError),
416 #[error(transparent)]
418 Checksum(#[from] ChecksumError),
419 #[error(transparent)]
421 Journal(#[from] DownloadJournalError),
422 #[error(transparent)]
424 Artifact(#[from] ArtifactError),
425 #[error(transparent)]
427 Io(#[from] io::Error),
428}
429
430#[cfg(test)]
431mod tests;