Skip to main content

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

1//! Fresh original source-byte preparation; payloads confer no upload permission.
2
3mod plan;
4pub use plan::IcSnapshotDataUploadPreparationError;
5
6use super::{
7    DownloadJournalGuard, File, IcSnapshotArtifactError, Mode, OFlags, REGIONS,
8    check_directory_identity, member, open_directory_no_follow, unix_fs,
9    verification::open_regular_child,
10};
11use crate::model::{
12    ic_snapshot_data::{MAX_IC_SNAPSHOT_DATA_CHUNK_BYTES, validate_kind},
13    ic_snapshot_metadata::IcSnapshotMetadataReply,
14    ic_snapshot_upload::{IcSnapshotUploadError, IcSnapshotUploadRequest},
15    operation_plan::OperationPlanRecord,
16};
17use ic_management_canister_types::SnapshotDataKind;
18use std::io::{self, Read, Seek, SeekFrom};
19use thiserror::Error;
20
21impl DownloadJournalGuard<'_> {
22    /// Freshly verify an original published IC source and encode exact upload metadata.
23    ///
24    /// Requires the full retained source plan, unchanged journal and complete Durable
25    /// selection. Target remains the source canister and replacement stays absent.
26    /// The payload must precede its separately retained original upload plan/reservation.
27    /// Stable future bytes, authentic source, actual context/permissions and same-release
28    /// restore obligations stay integration-owned. Nothing is written or dispatched.
29    /// # Errors
30    /// Rejects original/byte/custody drift or unrepresentable original metadata.
31    pub fn prepare_ic_snapshot_upload_metadata<'source>(
32        &self,
33        plan: &'source OperationPlanRecord,
34        snapshot: &str,
35        metadata: &'source IcSnapshotMetadataReply<'source>,
36    ) -> Result<IcSnapshotUploadRequest<'source>, IcSnapshotUploadArtifactError> {
37        let checksum = self.verify_ic_snapshot_artifact(plan, snapshot, metadata)?;
38        Ok(IcSnapshotUploadRequest::metadata(
39            plan, metadata, &checksum,
40        )?)
41    }
42
43    /// Read one bounded exact source extent/chunk and encode a distinct destination ID.
44    ///
45    /// Fresh full IC-tree verification before/after descriptor-relative reading binds
46    /// actual bytes to the original metadata/checksum and guarded source plan/journal.
47    /// This is an explicit local byte operation, not resume or a transfer-completion view.
48    /// Only one <=1 MiB chunk is buffered; no aggregate region or allowance is allocated.
49    /// The caller qualifies destination allocation and retains the new exact data intent
50    /// before its own reservation. No source/restore reference, journal or fence changes.
51    /// # Errors
52    /// Rejects wrong source declaration, ranges/hash/IDs, changed/unsafe files or custody,
53    /// short reads, encoding failures and mismatching retained original evidence.
54    pub fn prepare_ic_snapshot_upload_data<'source>(
55        &self,
56        plan: &OperationPlanRecord,
57        snapshot: &str,
58        metadata_upload: &IcSnapshotUploadRequest<'source>,
59        snapshot_id: &[u8],
60        source_kind: SnapshotDataKind,
61    ) -> Result<IcSnapshotUploadRequest<'source>, IcSnapshotUploadArtifactError> {
62        let metadata = metadata_upload.source();
63        metadata_upload.validate_data_destination(snapshot_id)?;
64        validate_kind(metadata, &source_kind).map_err(IcSnapshotUploadError::from)?;
65        self.require_upload_source(plan, snapshot, metadata_upload)?;
66        let entry = self
67            .record
68            .artifact(metadata.request().target(), snapshot)
69            .map_err(super::DownloadJournalError::from)
70            .map_err(IcSnapshotArtifactError::from)?;
71        let parent_path = self.layout.root().join("artifacts");
72        let parent =
73            open_directory_no_follow(&parent_path).map_err(IcSnapshotArtifactError::from)?;
74        let path = self.layout.root().join(entry.artifact_path());
75        let directory = File::from(
76            unix_fs::openat(
77                &parent,
78                path.file_name()
79                    .ok_or(IcSnapshotArtifactError::CustodyChanged)?,
80                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
81                Mode::empty(),
82            )
83            .map_err(io::Error::from)
84            .map_err(IcSnapshotArtifactError::from)?,
85        );
86        let chunk = read_chunk(&directory, metadata, &source_kind)?;
87        let payload =
88            IcSnapshotUploadRequest::data(metadata_upload, snapshot_id, source_kind, &chunk)?;
89        check_directory_identity(&parent_path, &parent)?;
90        check_directory_identity(&path, &directory)?;
91        self.require_upload_source(plan, snapshot, metadata_upload)?;
92        Ok(payload)
93    }
94
95    fn require_upload_source(
96        &self,
97        plan: &OperationPlanRecord,
98        snapshot: &str,
99        upload: &IcSnapshotUploadRequest<'_>,
100    ) -> Result<(), IcSnapshotUploadArtifactError> {
101        if plan.digest() != upload.source_plan().digest() {
102            return Err(IcSnapshotUploadArtifactError::SourceMismatch);
103        }
104        let actual = self.verify_ic_snapshot_artifact(plan, snapshot, upload.source())?;
105        if actual != *upload.source_checksum() {
106            return Err(IcSnapshotUploadArtifactError::SourceMismatch);
107        }
108        Ok(())
109    }
110}
111
112fn read_chunk(
113    directory: &File,
114    metadata: &IcSnapshotMetadataReply<'_>,
115    kind: &SnapshotDataKind,
116) -> Result<Vec<u8>, IcSnapshotArtifactError> {
117    let values = metadata.metadata();
118    let (name, length, offset, size) = match member::select(kind)? {
119        member::Member::Region {
120            index,
121            offset,
122            size,
123        } => {
124            let sizes = [
125                values.wasm_module_size,
126                values.wasm_memory_size,
127                values.stable_memory_size,
128            ];
129            (
130                REGIONS[index].to_owned(),
131                Some(sizes[index]),
132                offset,
133                Some(size),
134            )
135        }
136        member::Member::Chunk { name } => (name, None, 0, None),
137    };
138    let maximum = length.unwrap_or(MAX_IC_SNAPSHOT_DATA_CHUNK_BYTES as u64);
139    let (mut file, original) = open_regular_child(directory, &name, length, maximum)?;
140    file.seek(SeekFrom::Start(offset))?;
141    let size = size.unwrap_or(original.len());
142    let limit = usize::try_from(size)
143        .ok()
144        .filter(|size| *size <= MAX_IC_SNAPSHOT_DATA_CHUNK_BYTES)
145        .ok_or(IcSnapshotArtifactError::FileShape)?;
146    ic_host_artifacts::artifact::read_exact_reader(file.take(size), limit).map_err(|error| {
147        use ic_host_artifacts::artifact::ArtifactError;
148        match error {
149            ArtifactError::LimitExceeded { .. } | ArtifactError::LengthMismatch { .. } => {
150                IcSnapshotArtifactError::FileShape
151            }
152            error => IcSnapshotArtifactError::Io(error.into()),
153        }
154    })
155}
156
157/// Typed local preparation failure; all original bytes, spending and references survive.
158#[derive(Debug, Error)]
159pub enum IcSnapshotUploadArtifactError {
160    /// Original declared source checksum differs from the freshly verified retained tree.
161    #[error("snapshot upload source checksum differs")]
162    SourceMismatch,
163    /// Existing guarded IC artifact admission or descriptor IO failed.
164    #[error(transparent)]
165    Artifact(#[from] IcSnapshotArtifactError),
166    /// Canonical pure bounded upload construction failed.
167    #[error(transparent)]
168    Upload(#[from] IcSnapshotUploadError),
169}