Skip to main content

ic_backup/ops/persistence/download_journal/ic_snapshot_artifact/
mod.rs

1//! Bounded local snapshot streaming joined to the existing durable download owner.
2
3mod 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, Dir, 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
38/// Exclusive ephemeral writer for one original journal artifact and exact IC metadata.
39///
40/// Each successful append retains decoded bytes in private descriptor-opened files.
41/// It reuses the model's coverage owner and keeps only three hash states plus at most
42/// 1,024 chunk checksums. It borrows the original layout/journal for its whole lifetime.
43/// Appends consume the writer: any rejection or partial IO failure closes it and retains
44/// the partial tree, without a completion transition or permission to repeat reads.
45/// There is no partial-transfer reconstruction or automatic cleanup.
46///
47/// The integration must qualify the generic token's association with the raw IC ID,
48/// authentic capture/metadata/data, original per-call spending, fresh read permission,
49/// complete backend transfer and stable noncooperating byte/command custody. This writer
50/// performs no provider calls and grants no upload/load/start, settlement or release.
51pub 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    /// Create private staging for an existing Created artifact and exact decoded metadata.
65    ///
66    /// The exact generic backend token remains unchanged and is not parsed as a raw IC ID.
67    /// The integration supplies their authoritative association. Target and timestamp must
68    /// match the retained entry; its independently observed total snapshot size is preserved,
69    /// never inferred from a sum of metadata regions. Exact original metadata wire bytes and
70    /// request arguments are retained alongside fixed region/chunk files in a distinct v1
71    /// artifact layout. Existing staging/canonical destinations reject without adoption.
72    /// # Errors
73    /// Rejects wrong identity/state/raw metadata, occupied or unsafe paths and IO failure.
74    /// Failure retains partial bytes and leaves the original journal unchanged.
75    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)).map_err(errno_to_io)?;
107        let directory = File::from(
108            unix_fs::openat(
109                &parent,
110                name,
111                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
112                Mode::empty(),
113            )
114            .map_err(errno_to_io)?,
115        );
116        let mut checksums = Vec::new();
117        for (name, bytes) in [
118            ("format", FORMAT),
119            ("metadata.candid", raw_metadata),
120            ("metadata-arguments.candid", metadata.request().arguments()),
121        ] {
122            create_file(&directory, name)?.write_all(bytes)?;
123            checksums.push((name.into(), ArtifactChecksumRecord::from_bytes(bytes)));
124        }
125        let regions = [
126            create_file(&directory, REGIONS[0])?,
127            create_file(&directory, REGIONS[1])?,
128            create_file(&directory, REGIONS[2])?,
129        ];
130        let writer = IcSnapshotArtifactWriter {
131            journal: self,
132            coverage: IcSnapshotDataCoverage::new(metadata),
133            snapshot: snapshot.to_owned(),
134            path,
135            parent,
136            directory,
137            regions,
138            hashes: std::array::from_fn(|_| Sha256::new()),
139            checksums,
140        };
141        writer.check_custody()?;
142        Ok(writer)
143    }
144}
145
146impl<'layout> IcSnapshotArtifactWriter<'_, 'layout, '_> {
147    /// Read the original declared coverage without changing it.
148    #[must_use]
149    pub const fn coverage(&self) -> &IcSnapshotDataCoverage<'_> {
150        &self.coverage
151    }
152
153    /// Read the fixed private staging path; stable external custody remains required.
154    #[must_use]
155    pub fn path(&self) -> &Path {
156        &self.path
157    }
158
159    /// Append one exact admitted reply without retaining its memory buffer.
160    ///
161    /// Regions may interleave; each region must remain contiguous from zero. Chunk files
162    /// use exact metadata hash names and exclusive creation. No fsync or journal transition
163    /// occurs until explicit finish. Any error consumes this owner and retains all bytes.
164    /// # Errors
165    /// Rejects changed custody, coverage conflicts and filesystem failures.
166    pub fn append(
167        mut self,
168        reply: &IcSnapshotDataReply<'_, '_>,
169    ) -> Result<Self, IcSnapshotArtifactError> {
170        self.check_custody()?;
171        self.coverage.admit(reply)?;
172        let index = match reply.request().kind() {
173            SnapshotDataKind::WasmModule { .. } => 0,
174            SnapshotDataKind::WasmMemory { .. } => 1,
175            SnapshotDataKind::StableMemory { .. } => 2,
176            SnapshotDataKind::WasmChunk { hash } => {
177                let name = format!("chunk-{}.bin", hex_bytes(hash));
178                create_file(&self.directory, &name)?.write_all(reply.chunk())?;
179                self.checksums
180                    .push((name.into(), reply.chunk_checksum().clone()));
181                self.check_custody()?;
182                return Ok(self);
183            }
184        };
185        self.regions[index].write_all(reply.chunk())?;
186        self.hashes[index].update(reply.chunk());
187        self.check_custody()?;
188        Ok(self)
189    }
190
191    /// Verify complete local bytes, retain their exact checksum and durably publish them.
192    ///
193    /// Complete declared coverage is required. The fixed closed tree must match hashes
194    /// computed from the actual admitted bytes, including original metadata and request.
195    /// Existing model transitions derive `Downloaded` and `ChecksumVerified` together; their
196    /// exact checksum is persisted atomically before the existing durable publisher runs.
197    /// On interruption, reopen the journal and use its ordinary `ChecksumVerified` publication
198    /// recovery without another read or transfer. Created partial trees cannot be resumed
199    /// through this writer; preserve them for operator-owned disposition. Ordinary Durable
200    /// replay reads only retained progress, without fresh byte verification.
201    ///
202    /// The caller still owns authentic backend completeness, token/raw-ID association and
203    /// stable custody. A returned checksum is local evidence, not a terminal/effect permit.
204    /// # Errors
205    /// Rejects incomplete coverage, extra/changed/unsafe bytes, replaced custody and failed
206    /// persistence/publication. Failure can leave a verified or published tree; retain it.
207    /// Closing directory-custody rejection can follow a retained `Durable` transition.
208    pub fn finish(self) -> Result<ArtifactChecksumRecord, IcSnapshotArtifactError> {
209        self.finish_with(DownloadJournalGuard::finalize_artifact)
210    }
211
212    fn finish_with(
213        mut self,
214        publish: impl FnOnce(
215            &mut DownloadJournalGuard<'layout>,
216            &str,
217            &str,
218        ) -> Result<(), DownloadJournalError>,
219    ) -> Result<ArtifactChecksumRecord, IcSnapshotArtifactError> {
220        if self.coverage.complete().is_none() {
221            return Err(IcSnapshotArtifactError::IncompleteCoverage);
222        }
223        self.check_custody()?;
224        for (name, hash) in REGIONS.into_iter().zip(self.hashes.iter()) {
225            self.checksums.push((
226                name.into(),
227                ArtifactChecksumRecord::from_digest(hash.clone().finalize().into()),
228            ));
229        }
230        self.check_closed_tree()?;
231        let expected = checksum_relative_files(std::mem::take(&mut self.checksums));
232        checksum_directory(&self.path)?.verify(expected.hash())?;
233        self.check_custody()?;
234        let target = self.coverage.metadata().request().target();
235        let mut next = self.journal.next(
236            target,
237            &self.snapshot,
238            ArtifactStateRecord::Downloaded,
239            None,
240        )?;
241        next.advance(
242            target,
243            &self.snapshot,
244            ArtifactStateRecord::ChecksumVerified,
245            Some(expected.clone()),
246        )
247        .map_err(DownloadJournalError::from)?;
248        self.journal.store(next, write_json_durable)?;
249        publish(self.journal, target, &self.snapshot)?;
250        self.journal.check_usable()?;
251        check_directory_identity(
252            self.path
253                .parent()
254                .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
255            &self.parent,
256        )?;
257        let entry = self
258            .journal
259            .record
260            .artifact(target, &self.snapshot)
261            .map_err(DownloadJournalError::from)?;
262        check_directory_identity(
263            &self.journal.layout.root().join(entry.artifact_path()),
264            &self.directory,
265        )?;
266        Ok(expected)
267    }
268
269    fn check_custody(&self) -> Result<(), IcSnapshotArtifactError> {
270        self.journal.check_usable()?;
271        for (path, held) in [
272            (
273                self.path
274                    .parent()
275                    .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
276                &self.parent,
277            ),
278            (self.path.as_path(), &self.directory),
279        ] {
280            check_directory_identity(path, held)?;
281        }
282        Ok(())
283    }
284
285    fn check_closed_tree(&self) -> Result<(), IcSnapshotArtifactError> {
286        check_closed_tree(&self.directory, &self.checksums)
287    }
288}
289
290fn check_closed_tree(
291    directory: &File,
292    checksums: &[(PathBuf, ArtifactChecksumRecord)],
293) -> Result<(), IcSnapshotArtifactError> {
294    let mut expected = checksums
295        .iter()
296        .map(|(path, _)| path.as_os_str().as_encoded_bytes().to_vec())
297        .collect::<BTreeSet<_>>();
298    let mut directory = Dir::read_from(directory).map_err(errno_to_io)?;
299    while let Some(entry) = directory.read() {
300        let entry = entry.map_err(errno_to_io)?;
301        let name = entry.file_name().to_bytes();
302        if matches!(name, b"." | b"..") {
303            continue;
304        }
305        if !expected.remove(name) {
306            return Err(IcSnapshotArtifactError::UnexpectedEntry);
307        }
308    }
309    if !expected.is_empty() {
310        return Err(IcSnapshotArtifactError::UnexpectedEntry);
311    }
312    Ok(())
313}
314
315impl fmt::Debug for IcSnapshotArtifactWriter<'_, '_, '_> {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        f.debug_struct("IcSnapshotArtifactWriter")
318            .field("coverage", &self.coverage)
319            .finish_non_exhaustive()
320    }
321}
322
323fn open_directory(path: &Path) -> io::Result<File> {
324    unix_fs::open(
325        path,
326        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
327        Mode::empty(),
328    )
329    .map(File::from)
330    .map_err(errno_to_io)
331}
332
333fn check_directory_identity(path: &Path, held: &File) -> Result<(), IcSnapshotArtifactError> {
334    let current = fs::symlink_metadata(path)?;
335    let original = held.metadata()?;
336    if !current.is_dir() || current.dev() != original.dev() || current.ino() != original.ino() {
337        return Err(IcSnapshotArtifactError::CustodyChanged);
338    }
339    Ok(())
340}
341
342fn create_file(directory: &File, name: &str) -> io::Result<File> {
343    unix_fs::openat(
344        directory,
345        name,
346        OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
347        Mode::from_bits_truncate(0o600),
348    )
349    .map(File::from)
350    .map_err(errno_to_io)
351}
352
353fn errno_to_io(error: rustix::io::Errno) -> io::Error {
354    io::Error::from_raw_os_error(error.raw_os_error())
355}
356
357/// Typed local artifact failures; no wire payload or raw snapshot identity is retained.
358#[derive(Debug, Error)]
359pub enum IcSnapshotArtifactError {
360    /// Original journal state, timestamp or raw metadata differs.
361    #[error("IC snapshot artifact original evidence mismatch")]
362    OriginalMismatch,
363    /// Complete declared data coverage has not been retained.
364    #[error("IC snapshot artifact coverage is incomplete")]
365    IncompleteCoverage,
366    /// The original artifact parent or staging directory has been replaced.
367    #[error("IC snapshot artifact directory custody changed")]
368    CustodyChanged,
369    /// The fixed closed artifact tree contains missing or additional entries.
370    #[error("IC snapshot artifact tree entries differ")]
371    UnexpectedEntry,
372    /// A retained direct child is not a regular file of the declared bounded size.
373    #[error("IC snapshot artifact file type or length differs")]
374    FileShape,
375    /// Retained original plan, complete durable selection or journal admission failed.
376    #[error(transparent)]
377    Integrity(#[from] super::DownloadIntegrityError),
378    /// Exact metadata/range/chunk coverage admission failed.
379    #[error(transparent)]
380    Coverage(#[from] IcSnapshotDataCoverageError),
381    /// Local expected admitted bytes differ from the current tree.
382    #[error(transparent)]
383    Checksum(#[from] ChecksumError),
384    /// Original download journal or durable publication failed.
385    #[error(transparent)]
386    Journal(#[from] DownloadJournalError),
387    /// Descriptor-based artifact traversal failed.
388    #[error(transparent)]
389    Artifact(#[from] ArtifactError),
390    /// Private descriptor creation or byte IO failed.
391    #[error(transparent)]
392    Io(#[from] io::Error),
393}
394
395#[cfg(test)]
396mod tests;