Skip to main content

ic_backup/model/download_journal/
mod.rs

1//! Exact local artifact identity and model-owned download lifecycle transitions.
2
3use crate::model::evidence_digest::EvidenceDigest;
4mod view;
5pub use view::{DownloadArtifactView, DownloadJournalView, ResumeAction};
6
7use super::{
8    artifacts::{ArtifactChecksumRecord, ChecksumError, canonical_hash},
9    bounded_sequence,
10};
11use serde::{Deserialize, Deserializer, Serialize};
12use thiserror::Error;
13
14/// Maximum artifact entries in a local download journal.
15pub const MAX_DOWNLOAD_ARTIFACTS: usize = 1024;
16/// Maximum encoded journal bytes admitted by persistence operations.
17pub const MAX_DOWNLOAD_JOURNAL_BYTES: u64 = 1024 * 1024;
18/// Maximum ASCII bytes in an opaque backend snapshot identifier.
19pub const MAX_SNAPSHOT_ID_BYTES: usize = 256;
20
21/// Snapshot identity admitted by the caller after authoritative capture observation.
22///
23/// This passive request grants no remote authority and contains no signing material.
24#[derive(Clone, Debug)]
25pub struct DownloadArtifactRequest {
26    /// Exact source canister principal, normalized on admission.
27    pub canister_id: String,
28    /// Exact backend snapshot token; no case folding or inferred identity.
29    pub snapshot_id: String,
30    /// Observed snapshot timestamp in nanoseconds.
31    pub snapshot_taken_at_timestamp: u64,
32    /// Observed snapshot size, not the encoded artifact directory's byte length.
33    pub snapshot_total_size_bytes: u64,
34}
35
36/// Ordered local artifact lifecycle adapted from Canic's download journal.
37#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
38pub enum ArtifactStateRecord {
39    /// Exact snapshot identity retained before local download completion.
40    Created,
41    /// Caller attested a complete staged backend artifact.
42    Downloaded,
43    /// Local bytes verified and their canonical checksum retained.
44    ChecksumVerified,
45    /// Verified bytes durably published at the canonical location.
46    Durable,
47}
48
49impl ArtifactStateRecord {
50    const fn can_advance_to(self, next: Self) -> bool {
51        matches!(
52            (self, next),
53            (Self::Created, Self::Downloaded)
54                | (Self::Downloaded, Self::ChecksumVerified)
55                | (Self::ChecksumVerified, Self::Durable)
56        )
57    }
58}
59
60// Internal transition inputs cannot pair a state with inappropriate checksum
61// evidence. Persisted fields retain their independent decoding/corruption checks.
62pub(crate) enum ArtifactTransition {
63    Downloaded,
64    ChecksumVerified(ArtifactChecksumRecord),
65    Durable,
66}
67
68impl ArtifactTransition {
69    const fn state(&self) -> ArtifactStateRecord {
70        match self {
71            Self::Downloaded => ArtifactStateRecord::Downloaded,
72            Self::ChecksumVerified(_) => ArtifactStateRecord::ChecksumVerified,
73            Self::Durable => ArtifactStateRecord::Durable,
74        }
75    }
76}
77
78/// Immutable exact snapshot identity with validated local progress evidence.
79#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
80#[serde(try_from = "ArtifactFields")]
81pub struct DownloadArtifactRecord {
82    canister_id: String,
83    snapshot_id: String,
84    snapshot_taken_at_timestamp: u64,
85    snapshot_total_size_bytes: u64,
86    staging_path: String,
87    artifact_path: String,
88    state: ArtifactStateRecord,
89    checksum: Option<ArtifactChecksumRecord>,
90}
91
92#[derive(Deserialize)]
93#[serde(deny_unknown_fields)]
94struct ArtifactFields {
95    canister_id: String,
96    snapshot_id: String,
97    snapshot_taken_at_timestamp: u64,
98    snapshot_total_size_bytes: u64,
99    staging_path: String,
100    artifact_path: String,
101    state: ArtifactStateRecord,
102    #[serde(deserialize_with = "crate::model::required_option::deserialize")]
103    checksum: Option<ArtifactChecksumRecord>,
104}
105
106impl TryFrom<ArtifactFields> for DownloadArtifactRecord {
107    type Error = DownloadJournalRecordError;
108    fn try_from(fields: ArtifactFields) -> Result<Self, Self::Error> {
109        let mut record = Self::new(DownloadArtifactRequest {
110            canister_id: fields.canister_id,
111            snapshot_id: fields.snapshot_id,
112            snapshot_taken_at_timestamp: fields.snapshot_taken_at_timestamp,
113            snapshot_total_size_bytes: fields.snapshot_total_size_bytes,
114        })?;
115        // Persisted paths must agree with normalized identity, never with a label.
116        if fields.staging_path != record.staging_path
117            || fields.artifact_path != record.artifact_path
118        {
119            return Err(DownloadJournalRecordError::ArtifactPathMismatch);
120        }
121        let requires_checksum = matches!(
122            fields.state,
123            ArtifactStateRecord::ChecksumVerified | ArtifactStateRecord::Durable
124        );
125        if requires_checksum != fields.checksum.is_some() {
126            return Err(DownloadJournalRecordError::InvalidChecksumState(
127                fields.state,
128            ));
129        }
130        record.state = fields.state;
131        record.checksum = fields.checksum;
132        Ok(record)
133    }
134}
135
136impl DownloadArtifactRecord {
137    fn new(request: DownloadArtifactRequest) -> Result<Self, DownloadJournalRecordError> {
138        let canister_id = normalize_principal(&request.canister_id)?;
139        if request.snapshot_id.is_empty()
140            || request.snapshot_id.len() > MAX_SNAPSHOT_ID_BYTES
141            || !request
142                .snapshot_id
143                .bytes()
144                .all(|byte| byte.is_ascii_graphic())
145        {
146            return Err(DownloadJournalRecordError::InvalidSnapshotId);
147        }
148        Ok(Self {
149            staging_path: format!("artifacts/{canister_id}.tmp"),
150            artifact_path: format!("artifacts/{canister_id}"),
151            canister_id,
152            snapshot_id: request.snapshot_id,
153            snapshot_taken_at_timestamp: request.snapshot_taken_at_timestamp,
154            snapshot_total_size_bytes: request.snapshot_total_size_bytes,
155            state: ArtifactStateRecord::Created,
156            checksum: None,
157        })
158    }
159
160    /// Return the normalized exact source principal.
161    #[must_use]
162    pub fn canister_id(&self) -> &str {
163        &self.canister_id
164    }
165    /// Return the exact backend snapshot token.
166    #[must_use]
167    pub fn snapshot_id(&self) -> &str {
168        &self.snapshot_id
169    }
170    /// Return the observed snapshot timestamp in nanoseconds.
171    #[must_use]
172    pub const fn snapshot_taken_at_timestamp(&self) -> u64 {
173        self.snapshot_taken_at_timestamp
174    }
175    /// Return the observed snapshot size; encoded directory size may differ.
176    #[must_use]
177    pub const fn snapshot_total_size_bytes(&self) -> u64 {
178        self.snapshot_total_size_bytes
179    }
180    /// Return the fixed relative staging directory for this principal.
181    #[must_use]
182    pub fn staging_path(&self) -> &str {
183        &self.staging_path
184    }
185    /// Return the fixed relative canonical directory for this principal.
186    #[must_use]
187    pub fn artifact_path(&self) -> &str {
188        &self.artifact_path
189    }
190    /// Return retained local lifecycle state.
191    #[must_use]
192    pub const fn state(&self) -> ArtifactStateRecord {
193        self.state
194    }
195    /// Return the retained exact checksum when verification has completed.
196    #[must_use]
197    pub const fn checksum(&self) -> Option<&ArtifactChecksumRecord> {
198        self.checksum.as_ref()
199    }
200}
201
202/// Maintained v1 local artifact journal bound to a caller-supplied intent digest.
203///
204/// This record neither authenticates that intent nor proves current remote authority.
205#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
206#[serde(try_from = "JournalFields")]
207pub struct DownloadJournalRecord {
208    version: u16,
209    intent: String,
210    artifacts: Vec<DownloadArtifactRecord>,
211}
212
213#[derive(Deserialize)]
214#[serde(deny_unknown_fields)]
215struct JournalFields {
216    version: u16,
217    intent: String,
218    #[serde(deserialize_with = "read_bounded_artifacts")]
219    artifacts: Vec<DownloadArtifactRecord>,
220}
221
222impl TryFrom<JournalFields> for DownloadJournalRecord {
223    type Error = DownloadJournalRecordError;
224    fn try_from(mut fields: JournalFields) -> Result<Self, Self::Error> {
225        if fields.version != 1 {
226            return Err(DownloadJournalRecordError::UnsupportedVersion(
227                fields.version,
228            ));
229        }
230        validate_entries(&mut fields.artifacts)?;
231        Ok(Self {
232            version: 1,
233            intent: canonical_hash(&fields.intent)?,
234            artifacts: fields.artifacts,
235        })
236    }
237}
238
239impl DownloadJournalRecord {
240    /// Admit a nonempty exact physical set before any local transfer completion.
241    ///
242    /// # Errors
243    /// Rejects invalid identities/digests, duplicate principals and exceeded count bounds.
244    pub fn new(
245        intent: &str,
246        requests: Vec<DownloadArtifactRequest>,
247    ) -> Result<Self, DownloadJournalRecordError> {
248        if requests.len() > MAX_DOWNLOAD_ARTIFACTS {
249            return Err(DownloadJournalRecordError::TooManyArtifacts);
250        }
251        let artifacts = requests
252            .into_iter()
253            .map(DownloadArtifactRecord::new)
254            .collect::<Result<Vec<_>, _>>()?;
255        JournalFields {
256            version: 1,
257            intent: intent.to_owned(),
258            artifacts,
259        }
260        .try_into()
261    }
262
263    /// Return the canonical caller-supplied immutable intent digest.
264    #[must_use]
265    pub fn intent(&self) -> &str {
266        &self.intent
267    }
268    /// Read entries in canonical principal-text order.
269    #[must_use]
270    pub fn artifacts(&self) -> &[DownloadArtifactRecord] {
271        &self.artifacts
272    }
273
274    /// Hash canonical original intent, exact snapshot metadata, paths and local evidence.
275    ///
276    /// The NUL-terminated v1 domain precedes 64 ASCII intent bytes and a big-endian
277    /// u64 entry count. Each canonical entry has four u32-length-prefixed UTF-8
278    /// strings (principal, snapshot token, staging path, artifact path), two u64
279    /// metadata values, a state byte (Created=0 through Durable=3), then a checksum
280    /// presence byte and its 64 ASCII hash when present. Integers are big-endian.
281    /// This grants no transfer, snapshot authenticity or terminal proof.
282    #[must_use]
283    pub fn digest(&self) -> ArtifactChecksumRecord {
284        let mut bytes = EvidenceDigest::new(b"ic-backup/download-journal/v1\0");
285        bytes.append(self.intent.as_bytes());
286        bytes.u64_be(self.artifacts.len() as u64);
287        for entry in &self.artifacts {
288            for value in [
289                entry.canister_id(),
290                entry.snapshot_id(),
291                entry.staging_path(),
292                entry.artifact_path(),
293            ] {
294                bytes.bytes_u32(value.as_bytes());
295            }
296            bytes.u64_be(entry.snapshot_taken_at_timestamp);
297            bytes.u64_be(entry.snapshot_total_size_bytes);
298            bytes.byte(match entry.state {
299                ArtifactStateRecord::Created => 0,
300                ArtifactStateRecord::Downloaded => 1,
301                ArtifactStateRecord::ChecksumVerified => 2,
302                ArtifactStateRecord::Durable => 3,
303            });
304            bytes.byte(u8::from(entry.checksum.is_some()));
305            if let Some(checksum) = &entry.checksum {
306                bytes.checksum(checksum);
307            }
308        }
309        bytes.finish()
310    }
311
312    pub(crate) fn artifact(
313        &self,
314        canister: &str,
315        snapshot: &str,
316    ) -> Result<&DownloadArtifactRecord, DownloadJournalRecordError> {
317        Ok(&self.artifacts[self.artifact_index(canister, snapshot)?])
318    }
319
320    fn artifact_index(
321        &self,
322        canister: &str,
323        snapshot: &str,
324    ) -> Result<usize, DownloadJournalRecordError> {
325        let canister = normalize_principal(canister)?;
326        let index = self
327            .artifacts
328            .binary_search_by(|entry| entry.canister_id.cmp(&canister))
329            .map_err(|_| DownloadJournalRecordError::UnknownArtifact)?;
330        if self.artifacts[index].snapshot_id != snapshot {
331            return Err(DownloadJournalRecordError::SnapshotMismatch);
332        }
333        Ok(index)
334    }
335
336    pub(crate) fn advance(
337        &mut self,
338        canister: &str,
339        snapshot: &str,
340        transition: ArtifactTransition,
341    ) -> Result<(), DownloadJournalRecordError> {
342        let index = self.artifact_index(canister, snapshot)?;
343        let entry = &mut self.artifacts[index];
344        let from = entry.state;
345        let next = transition.state();
346        if !from.can_advance_to(next) {
347            return Err(DownloadJournalRecordError::InvalidStateTransition { from, to: next });
348        }
349        let checksum = match transition {
350            ArtifactTransition::Downloaded => None,
351            ArtifactTransition::ChecksumVerified(checksum) => Some(checksum),
352            ArtifactTransition::Durable => entry.checksum.clone(),
353        };
354        entry.state = next;
355        entry.checksum = checksum;
356        Ok(())
357    }
358}
359
360fn normalize_principal(value: &str) -> Result<String, DownloadJournalRecordError> {
361    super::principal::canonical_text(value).ok_or(DownloadJournalRecordError::InvalidPrincipal)
362}
363
364fn validate_entries(
365    entries: &mut [DownloadArtifactRecord],
366) -> Result<(), DownloadJournalRecordError> {
367    if entries.is_empty() {
368        return Err(DownloadJournalRecordError::EmptyArtifacts);
369    }
370    if entries.len() > MAX_DOWNLOAD_ARTIFACTS {
371        return Err(DownloadJournalRecordError::TooManyArtifacts);
372    }
373    entries.sort_by(|left, right| left.canister_id.cmp(&right.canister_id));
374    if entries
375        .windows(2)
376        .any(|pair| pair[0].canister_id == pair[1].canister_id)
377    {
378        return Err(DownloadJournalRecordError::DuplicateCanister);
379    }
380    Ok(())
381}
382
383fn read_bounded_artifacts<'de, D: Deserializer<'de>>(
384    deserializer: D,
385) -> Result<Vec<DownloadArtifactRecord>, D::Error> {
386    bounded_sequence::deserialize::<_, _, MAX_DOWNLOAD_ARTIFACTS>(
387        deserializer,
388        "a bounded artifact list",
389        DownloadJournalRecordError::TooManyArtifacts,
390    )
391}
392
393/// Typed local journal identity, schema or transition rejection.
394#[derive(Debug, Error)]
395pub enum DownloadJournalRecordError {
396    /// Only v1 records are maintained.
397    #[error("unsupported download journal version {0}")]
398    UnsupportedVersion(u16),
399    /// An empty physical set cannot claim completion.
400    #[error("download journal artifacts must not be empty")]
401    EmptyArtifacts,
402    /// The bounded artifact count was exceeded.
403    #[error("download journal artifact count exceeds {MAX_DOWNLOAD_ARTIFACTS}")]
404    TooManyArtifacts,
405    /// More than one snapshot was selected for the same physical canister.
406    #[error("duplicate download canister identity")]
407    DuplicateCanister,
408    /// The supplied principal failed canonical admission.
409    #[error("invalid download canister principal")]
410    InvalidPrincipal,
411    /// The exact snapshot token is empty, excessive or contains nongraphic bytes.
412    #[error("invalid download snapshot token")]
413    InvalidSnapshotId,
414    /// A persisted path differs from its immutable identity-derived location.
415    #[error("download artifact path does not match source identity")]
416    ArtifactPathMismatch,
417    /// The requested physical target is not retained.
418    #[error("unknown download artifact")]
419    UnknownArtifact,
420    /// The supplied snapshot differs from the retained exact token.
421    #[error("download snapshot identity mismatch")]
422    SnapshotMismatch,
423    /// Progress cannot be reset, repeated or advanced over an intermediate state.
424    #[error("invalid download state transition from {from:?} to {to:?}")]
425    InvalidStateTransition {
426        /// Retained state.
427        from: ArtifactStateRecord,
428        /// Rejected next state.
429        to: ArtifactStateRecord,
430    },
431    /// Checksum evidence disagrees with lifecycle state.
432    #[error("invalid checksum evidence for download state {0:?}")]
433    InvalidChecksumState(ArtifactStateRecord),
434    /// The immutable intent or checksum is malformed.
435    #[error(transparent)]
436    Checksum(#[from] ChecksumError),
437}
438
439#[cfg(test)]
440mod tests;