Skip to main content

canic_backup/journal/
validation.rs

1//! Module: journal::validation
2//!
3//! Responsibility: validate durable artifact journal records before resume.
4//! Does not own: journal persistence, download execution, or reporting.
5//! Boundary: returns typed validation errors for persisted journal input.
6
7use crate::journal::{ArtifactJournalEntry, ArtifactState, DownloadJournal};
8
9use std::{
10    collections::BTreeSet,
11    path::{Component, PathBuf},
12    str::FromStr,
13};
14
15use candid::Principal;
16use thiserror::Error as ThisError;
17
18const SUPPORTED_JOURNAL_VERSION: u16 = 1;
19const SHA256_ALGORITHM: &str = "sha256";
20
21impl DownloadJournal {
22    /// Validate resumable artifact state for one backup run.
23    pub fn validate(&self) -> Result<(), JournalValidationError> {
24        validate_journal_version(self.journal_version)?;
25        validate_nonempty("backup_id", &self.backup_id)?;
26        validate_hash("discovery_topology_hash", &self.discovery_topology_hash)?;
27        validate_hash(
28            "pre_snapshot_topology_hash",
29            &self.pre_snapshot_topology_hash,
30        )?;
31
32        if self.artifacts.is_empty() {
33            return Err(JournalValidationError::EmptyCollection("artifacts"));
34        }
35
36        let mut keys = BTreeSet::new();
37        for artifact in &self.artifacts {
38            artifact.validate()?;
39            let key = (artifact.canister_id.clone(), artifact.snapshot_id.clone());
40            if !keys.insert(key) {
41                return Err(JournalValidationError::DuplicateArtifact {
42                    canister_id: artifact.canister_id.clone(),
43                    snapshot_id: artifact.snapshot_id.clone(),
44                });
45            }
46        }
47
48        Ok(())
49    }
50}
51
52impl ArtifactJournalEntry {
53    /// Validate one artifact's resumable state.
54    fn validate(&self) -> Result<(), JournalValidationError> {
55        validate_principal("artifacts[].canister_id", &self.canister_id)?;
56        validate_nonempty("artifacts[].snapshot_id", &self.snapshot_id)?;
57        validate_nonempty("artifacts[].artifact_path", &self.artifact_path)?;
58        validate_relative_artifact_path("artifacts[].artifact_path", &self.artifact_path)?;
59        validate_nonempty("artifacts[].checksum_algorithm", &self.checksum_algorithm)?;
60        validate_nonempty("artifacts[].updated_at", &self.updated_at)?;
61
62        if self.checksum_algorithm != SHA256_ALGORITHM {
63            return Err(JournalValidationError::UnsupportedHashAlgorithm(
64                self.checksum_algorithm.clone(),
65            ));
66        }
67
68        if matches!(
69            self.state,
70            ArtifactState::Downloaded | ArtifactState::ChecksumVerified
71        ) {
72            validate_required_option("artifacts[].temp_path", self.temp_path.as_deref())?;
73        }
74
75        if matches!(
76            self.state,
77            ArtifactState::ChecksumVerified | ArtifactState::Durable
78        ) {
79            validate_required_hash("artifacts[].checksum", self.checksum.as_deref())?;
80        }
81
82        Ok(())
83    }
84}
85
86///
87/// JournalValidationError
88///
89/// Typed validation failure for durable artifact journals.
90/// Owned by backup journaling and returned before unsafe resume.
91///
92
93#[derive(Debug, ThisError)]
94pub enum JournalValidationError {
95    #[error("duplicate artifact entry for canister {canister_id} snapshot {snapshot_id}")]
96    DuplicateArtifact {
97        canister_id: String,
98        snapshot_id: String,
99    },
100
101    #[error("collection {0} must not be empty")]
102    EmptyCollection(&'static str),
103
104    #[error("field {0} must not be empty")]
105    EmptyField(&'static str),
106
107    #[error("field {field} must be a relative artifact path under the backup root: {value}")]
108    InvalidArtifactPath { field: &'static str, value: String },
109
110    #[error("field {0} must be a non-empty sha256 hex string")]
111    InvalidHash(&'static str),
112
113    #[error("field {field} must be a valid principal: {value}")]
114    InvalidPrincipal { field: &'static str, value: String },
115
116    #[error("invalid journal transition from {from:?} to {to:?}")]
117    InvalidStateTransition {
118        from: ArtifactState,
119        to: ArtifactState,
120    },
121
122    #[error("unsupported hash algorithm {0}")]
123    UnsupportedHashAlgorithm(String),
124
125    #[error("unsupported journal version {0}")]
126    UnsupportedJournalVersion(u16),
127}
128
129const fn validate_journal_version(version: u16) -> Result<(), JournalValidationError> {
130    if version == SUPPORTED_JOURNAL_VERSION {
131        Ok(())
132    } else {
133        Err(JournalValidationError::UnsupportedJournalVersion(version))
134    }
135}
136
137fn validate_nonempty(field: &'static str, value: &str) -> Result<(), JournalValidationError> {
138    if value.trim().is_empty() {
139        Err(JournalValidationError::EmptyField(field))
140    } else {
141        Ok(())
142    }
143}
144
145fn validate_relative_artifact_path(
146    field: &'static str,
147    value: &str,
148) -> Result<(), JournalValidationError> {
149    let path = PathBuf::from(value);
150    if path.is_absolute()
151        || !path
152            .components()
153            .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
154    {
155        return Err(JournalValidationError::InvalidArtifactPath {
156            field,
157            value: value.to_string(),
158        });
159    }
160    Ok(())
161}
162
163fn validate_required_option(
164    field: &'static str,
165    value: Option<&str>,
166) -> Result<(), JournalValidationError> {
167    match value {
168        Some(value) => validate_nonempty(field, value),
169        None => Err(JournalValidationError::EmptyField(field)),
170    }
171}
172
173fn validate_principal(field: &'static str, value: &str) -> Result<(), JournalValidationError> {
174    validate_nonempty(field, value)?;
175    Principal::from_str(value)
176        .map(|_| ())
177        .map_err(|_| JournalValidationError::InvalidPrincipal {
178            field,
179            value: value.to_string(),
180        })
181}
182
183fn validate_required_hash(
184    field: &'static str,
185    value: Option<&str>,
186) -> Result<(), JournalValidationError> {
187    match value {
188        Some(value) => validate_hash(field, value),
189        None => Err(JournalValidationError::EmptyField(field)),
190    }
191}
192
193fn validate_hash(field: &'static str, value: &str) -> Result<(), JournalValidationError> {
194    const SHA256_HEX_LEN: usize = 64;
195    validate_nonempty(field, value)?;
196    if value.len() == SHA256_HEX_LEN && value.bytes().all(|b| b.is_ascii_hexdigit()) {
197        Ok(())
198    } else {
199        Err(JournalValidationError::InvalidHash(field))
200    }
201}