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 #[must_use]
150 pub const fn coverage(&self) -> &IcSnapshotDataCoverage<'_> {
151 &self.coverage
152 }
153
154 #[must_use]
156 pub fn path(&self) -> &Path {
157 &self.path
158 }
159
160 pub fn append(
170 mut self,
171 reply: &IcSnapshotDataReply<'_, '_>,
172 ) -> Result<Self, IcSnapshotArtifactError> {
173 self.check_custody()?;
174 self.check_region_custody()?;
175 self.coverage.admit(reply)?;
176 let index = match reply.request().kind() {
177 SnapshotDataKind::WasmModule { .. } => 0,
178 SnapshotDataKind::WasmMemory { .. } => 1,
179 SnapshotDataKind::StableMemory { .. } => 2,
180 SnapshotDataKind::WasmChunk { hash } => {
181 let name = format!("chunk-{}.bin", hex_bytes(hash));
182 create_file(&self.directory, &name)?.write_all(reply.chunk())?;
183 self.checksums
184 .push((name.into(), reply.chunk_checksum().clone()));
185 self.check_custody()?;
186 return Ok(self);
187 }
188 };
189 self.regions[index].write_all(reply.chunk())?;
190 self.hashes[index].update(reply.chunk());
191 self.check_custody()?;
192 Ok(self)
193 }
194
195 pub fn finish(self) -> Result<ArtifactChecksumRecord, IcSnapshotArtifactError> {
213 self.finish_with(DownloadJournalGuard::finalize_artifact)
214 }
215
216 fn finish_with(
217 mut self,
218 publish: impl FnOnce(
219 &mut DownloadJournalGuard<'layout>,
220 &str,
221 &str,
222 ) -> Result<(), DownloadJournalError>,
223 ) -> Result<ArtifactChecksumRecord, IcSnapshotArtifactError> {
224 if self.coverage.complete().is_none() {
225 return Err(IcSnapshotArtifactError::IncompleteCoverage);
226 }
227 self.check_custody()?;
228 for (name, hash) in REGIONS.into_iter().zip(self.hashes.iter()) {
229 self.checksums.push((
230 name.into(),
231 ArtifactChecksumRecord::from_digest(hash.clone().finalize().into()),
232 ));
233 }
234 self.check_closed_tree()?;
235 let expected = checksum_relative_files(std::mem::take(&mut self.checksums))
236 .map_err(ArtifactError::from)?;
237 checksum_directory(&self.path)?.verify(expected.hash())?;
238 self.check_custody()?;
239 let target = self.coverage.metadata().request().target();
240 let mut next = self.journal.next(
241 target,
242 &self.snapshot,
243 ArtifactStateRecord::Downloaded,
244 None,
245 )?;
246 next.advance(
247 target,
248 &self.snapshot,
249 ArtifactStateRecord::ChecksumVerified,
250 Some(expected.clone()),
251 )
252 .map_err(DownloadJournalError::from)?;
253 self.journal.store(next, write_json_durable)?;
254 publish(self.journal, target, &self.snapshot)?;
255 self.journal.check_usable()?;
256 check_directory_identity(
257 self.path
258 .parent()
259 .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
260 &self.parent,
261 )?;
262 let entry = self
263 .journal
264 .record
265 .artifact(target, &self.snapshot)
266 .map_err(DownloadJournalError::from)?;
267 check_directory_identity(
268 &self.journal.layout.root().join(entry.artifact_path()),
269 &self.directory,
270 )?;
271 Ok(expected)
272 }
273
274 fn check_custody(&self) -> Result<(), IcSnapshotArtifactError> {
275 self.journal.check_usable()?;
276 for (path, held) in [
277 (
278 self.path
279 .parent()
280 .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
281 &self.parent,
282 ),
283 (self.path.as_path(), &self.directory),
284 ] {
285 check_directory_identity(path, held)?;
286 }
287 Ok(())
288 }
289
290 fn check_closed_tree(&self) -> Result<(), IcSnapshotArtifactError> {
291 check_closed_tree(&self.directory, &self.checksums)
292 }
293
294 fn check_region_custody(&self) -> Result<(), IcSnapshotArtifactError> {
295 for ((name, file), expected) in REGIONS
296 .iter()
297 .zip(&self.regions)
298 .zip(self.coverage.covered_region_bytes())
299 {
300 let held = unix_fs::fstat(file).map_err(io::Error::from)?;
301 let current = unix_fs::statat(&self.directory, *name, AtFlags::SYMLINK_NOFOLLOW)
302 .map_err(io::Error::from)?;
303 let same_file = (current.st_dev, current.st_ino) == (held.st_dev, held.st_ino);
304 let exact_extent = current.st_size == held.st_size
305 && u64::try_from(held.st_size).ok() == Some(expected);
306 if !FileType::from_raw_mode(current.st_mode).is_file() || !same_file || !exact_extent {
307 return Err(IcSnapshotArtifactError::FileShape);
308 }
309 }
310 Ok(())
311 }
312}
313
314fn check_closed_tree(
315 directory: &File,
316 checksums: &[(PathBuf, ArtifactChecksumRecord)],
317) -> Result<(), IcSnapshotArtifactError> {
318 let mut expected = checksums
319 .iter()
320 .map(|(path, _)| path.as_os_str().as_encoded_bytes().to_vec())
321 .collect::<BTreeSet<_>>();
322 let mut directory = Dir::read_from(directory).map_err(io::Error::from)?;
323 while let Some(entry) = directory.read() {
324 let entry = entry.map_err(io::Error::from)?;
325 let name = entry.file_name().to_bytes();
326 if matches!(name, b"." | b"..") {
327 continue;
328 }
329 if !expected.remove(name) {
330 return Err(IcSnapshotArtifactError::UnexpectedEntry);
331 }
332 }
333 if !expected.is_empty() {
334 return Err(IcSnapshotArtifactError::UnexpectedEntry);
335 }
336 Ok(())
337}
338
339impl fmt::Debug for IcSnapshotArtifactWriter<'_, '_, '_> {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 f.debug_struct("IcSnapshotArtifactWriter")
342 .field("coverage", &self.coverage)
343 .finish_non_exhaustive()
344 }
345}
346
347fn open_directory(path: &Path) -> io::Result<File> {
348 unix_fs::open(
349 path,
350 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
351 Mode::empty(),
352 )
353 .map(File::from)
354 .map_err(io::Error::from)
355}
356
357fn check_directory_identity(path: &Path, held: &File) -> Result<(), IcSnapshotArtifactError> {
358 let current = fs::symlink_metadata(path)?;
359 let original = held.metadata()?;
360 if !current.is_dir() || current.dev() != original.dev() || current.ino() != original.ino() {
361 return Err(IcSnapshotArtifactError::CustodyChanged);
362 }
363 Ok(())
364}
365
366fn create_file(directory: &File, name: &str) -> io::Result<File> {
367 unix_fs::openat(
368 directory,
369 name,
370 OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
371 Mode::from_bits_truncate(0o600),
372 )
373 .map(File::from)
374 .map_err(io::Error::from)
375}
376
377#[derive(Debug, Error)]
379pub enum IcSnapshotArtifactError {
380 #[error("IC snapshot artifact original evidence mismatch")]
382 OriginalMismatch,
383 #[error("IC snapshot artifact coverage is incomplete")]
385 IncompleteCoverage,
386 #[error("IC snapshot artifact directory custody changed")]
388 CustodyChanged,
389 #[error("IC snapshot artifact tree entries differ")]
391 UnexpectedEntry,
392 #[error("IC snapshot artifact file type or length differs")]
394 FileShape,
395 #[error(transparent)]
397 Integrity(#[from] super::DownloadIntegrityError),
398 #[error(transparent)]
400 Coverage(#[from] IcSnapshotDataCoverageError),
401 #[error(transparent)]
403 Checksum(#[from] ChecksumError),
404 #[error(transparent)]
406 Journal(#[from] DownloadJournalError),
407 #[error(transparent)]
409 Artifact(#[from] ArtifactError),
410 #[error(transparent)]
412 Io(#[from] io::Error),
413}
414
415#[cfg(test)]
416mod tests;