Skip to main content

ic_backup/model/restore_safety/
mod.rs

1//! Original restore/source requirements and ephemeral application-owned safety evidence.
2
3mod requirement;
4pub use requirement::{
5    MAX_RESTORE_SAFETY_REQUIREMENT_BYTES, RestoreFenceBindingRecord, RestoreSafetyLaneRecord,
6    RestoreSafetyRequirementError, RestoreSafetyRequirementRecord, RestoreSafetyRequirementRequest,
7};
8
9use crate::model::{
10    artifacts::ArtifactChecksumRecord,
11    attempt_journal::OperationBindingRecord,
12    consistency::ApplicationFenceState,
13    ic_request::{IcManagementMethodRecord, IcManagementRequestRecord, IcRequestError},
14    inventory::{InventoryRecord, MAX_INVENTORY_TARGETS},
15    operation_plan::{OperationPlanError, OperationPlanRecord, PlanContextRecord},
16};
17use ic_management_canister_types::CanisterStatusType;
18use thiserror::Error;
19
20/// Maximum descriptive remote observations per invocation; no spending allowance.
21pub const MAX_RESTORE_SAFETY_REMOTE_OBSERVATIONS: u32 = 1024;
22/// Passive current parameters; the exact load/start boundary is derived from original wire bytes.
23#[derive(Clone, Debug)]
24pub struct RestoreSafetyRequestInput {
25    /// Exact original load/start operation sequence.
26    pub operation_sequence: u64,
27    /// Integration-owned fresh challenge, qualified independently of hash equality.
28    pub challenge: ArtifactChecksumRecord,
29    /// Descriptive call ceiling; every actual call needs separate prior accounting.
30    pub max_remote_observations: u32,
31}
32/// Ephemeral original-source/safety/challenge request; no dispatch or paid-call permit.
33#[derive(Clone, Debug)]
34pub struct RestoreSafetyRequest<'a> {
35    plan: &'a OperationPlanRecord,
36    requirement: &'a RestoreSafetyRequirementRecord,
37    binding: OperationBindingRecord,
38    wire: &'a IcManagementRequestRecord,
39    input: RestoreSafetyRequestInput,
40}
41impl<'a> RestoreSafetyRequest<'a> {
42    /// Validate exact original plans, requirement and load/start mutation bytes.
43    ///
44    /// The integration admits the retained requirement before effect-boundary
45    /// use and retains original source artifacts and fence obligations. This
46    /// constructor performs no IO and cannot prove that custody.
47    /// # Errors
48    /// Rejects changed source/plan/payload, other methods or excessive descriptive calls.
49    pub fn new(
50        plan: &'a OperationPlanRecord,
51        source: &OperationPlanRecord,
52        requirement: &'a RestoreSafetyRequirementRecord,
53        wire: &'a IcManagementRequestRecord,
54        input: RestoreSafetyRequestInput,
55    ) -> Result<Self, RestoreSafetyRequestError> {
56        requirement.validate_plans(plan, source)?;
57        if input.max_remote_observations > MAX_RESTORE_SAFETY_REMOTE_OBSERVATIONS {
58            return Err(RestoreSafetyRequestError::ObservationLimitTooLarge);
59        }
60        if !matches!(
61            wire.method(),
62            IcManagementMethodRecord::LoadCanisterSnapshot
63                | IcManagementMethodRecord::StartCanister
64        ) {
65            return Err(RestoreSafetyRequestError::UnsupportedMethod);
66        }
67        let binding = plan
68            .attempt_authority(input.operation_sequence)?
69            .binding()
70            .clone();
71        wire.validate_mutation_binding(&binding)?;
72        Ok(Self {
73            plan,
74            requirement,
75            binding,
76            wire,
77            input,
78        })
79    }
80    /// Read exact original operation, context, target and request identity.
81    #[must_use]
82    pub const fn binding(&self) -> &OperationBindingRecord {
83        &self.binding
84    }
85    /// Read original full inventory, including unselected metadata.
86    #[must_use]
87    pub const fn inventory(&self) -> &InventoryRecord {
88        self.plan.inventory()
89    }
90    /// Read exact original selected IDs in canonical order, not dispatch order.
91    #[must_use]
92    pub fn selected_targets(&self) -> &[String] {
93        self.plan.selected_targets()
94    }
95    /// Read original immutable source and safety requirement.
96    #[must_use]
97    pub const fn requirement(&self) -> &RestoreSafetyRequirementRecord {
98        self.requirement
99    }
100    /// Read exact original load/start wire request; codecs confer no load settlement.
101    #[must_use]
102    pub const fn wire(&self) -> &IcManagementRequestRecord {
103        self.wire
104    }
105    /// Read challenge; matching values alone prove no freshness.
106    #[must_use]
107    pub const fn challenge(&self) -> &ArtifactChecksumRecord {
108        &self.input.challenge
109    }
110    /// Read descriptive call ceiling without spending/replenishment.
111    #[must_use]
112    pub const fn max_remote_observations(&self) -> u32 {
113        self.input.max_remote_observations
114    }
115    /// Hash v1 NUL-terminated ASCII domain, 64 ASCII requirement-digest bytes,
116    /// u64 BE sequence, 64 ASCII wire-digest bytes, 64 ASCII challenge bytes and
117    /// u32 BE descriptive ceiling. Wire digest distinguishes load from start.
118    #[must_use]
119    pub fn digest(&self) -> ArtifactChecksumRecord {
120        let mut bytes = b"ic-backup/restore-safety-request/v1\0".to_vec();
121        bytes.extend_from_slice(self.requirement.digest().hash().as_bytes());
122        bytes.extend_from_slice(&self.binding.operation_sequence().to_be_bytes());
123        bytes.extend_from_slice(self.wire.digest().hash().as_bytes());
124        bytes.extend_from_slice(self.challenge().hash().as_bytes());
125        bytes.extend_from_slice(&self.max_remote_observations().to_be_bytes());
126        ArtifactChecksumRecord::from_bytes(&bytes)
127    }
128}
129/// Passive actual lifecycle and integration-qualified source-specific restored acceptance.
130#[derive(Clone, Debug)]
131pub struct TargetRestoreEvidence {
132    /// Actual physical target, normalized at model admission.
133    pub target: String,
134    /// Actual upstream lifecycle state; never inferred from a process exit status.
135    pub state: CanisterStatusType,
136    /// Evidence qualifying lifecycle and, when stopped, drained application work.
137    pub lifecycle_evidence: ArtifactChecksumRecord,
138    /// Current application acceptance of this exact source's restored state, required before start.
139    /// A module hash or load acknowledgement alone cannot supply this evidence.
140    pub restored_acceptance: Option<ArtifactChecksumRecord>,
141}
142/// Passive exact fence evidence; every opaque field requires application qualification.
143#[derive(Clone, Debug)]
144pub struct RestoreFenceEvidence {
145    /// Actually observed active/inactive custody; unknown custody fails at the provider.
146    pub state: ApplicationFenceState,
147    /// Actually observed fence and current authority revisions, matched to original retention.
148    pub binding: RestoreFenceBindingRecord,
149    /// Whole-selection write, membership, timer, external-work fencing and drained-work evidence.
150    pub whole_selection: ArtifactChecksumRecord,
151    /// Fence and obligation custody outside the source's rewindable state, across failure/recovery.
152    pub rewind_independent_custody: ArtifactChecksumRecord,
153    /// Qualified external-obligation disposition and prevention of replayed irreversible work.
154    /// Settlement alone is insufficient if restored intent can replay that work.
155    pub external_obligations_and_replay: ArtifactChecksumRecord,
156    /// Current allowance for isolated restored execution under the retained fence, required before start.
157    /// This is application evidence, not a release token, future guarantee or dispatch permit.
158    pub controlled_execution: Option<ArtifactChecksumRecord>,
159}
160/// Actual application safety lane; no generic default or serialized Proven admission.
161#[derive(Clone, Debug)]
162pub enum RestoreSafetyEvidence {
163    /// Qualified absence of irreversible external effects, including restored intent/timers.
164    NoIrreversibleEffects(ArtifactChecksumRecord),
165    /// Qualified whole-selection custody outside rewindable state and external-work replay safety.
166    ApplicationFenced(Box<RestoreFenceEvidence>),
167    /// Known unsafe or unresolved external obligations; pure policy rejects this evidence.
168    Unresolved(ArtifactChecksumRecord),
169}
170/// Passive provider data; exact original context/source and current evidence are independent inputs.
171#[derive(Clone, Debug)]
172pub struct RestoreSafetyObservationInput {
173    /// Exact current challenge-bound request digest.
174    pub request: ArtifactChecksumRecord,
175    /// Actual current canonical network/caller/release, not echoed expected labels.
176    pub context: PlanContextRecord,
177    /// Complete actual current inventory, including unselected parent metadata.
178    pub inventory: InventoryRecord,
179    /// Qualified exact original source plan identity.
180    pub source_plan_intent: ArtifactChecksumRecord,
181    /// Qualified complete original source artifacts in stable retained custody,
182    /// including exact target-local load snapshot association when checking load.
183    pub source_artifacts: ArtifactChecksumRecord,
184    /// Actual lifecycle and restored acceptance for the exact selected set.
185    pub targets: Vec<TargetRestoreEvidence>,
186    /// Actual application safety lane and evidence for this exact source/selection/boundary.
187    pub safety: RestoreSafetyEvidence,
188    /// Opaque integration-qualified evidence identity; no signature or permission.
189    pub evidence: ArtifactChecksumRecord,
190    /// Actual remote observations, each needing separate prior spending authority.
191    pub remote_observations: u32,
192}
193/// Canonical immutable ephemeral observation; no Serde, expiry or persisted authority flag.
194#[derive(Clone, Debug)]
195pub struct RestoreSafetyObservation {
196    input: RestoreSafetyObservationInput,
197}
198impl RestoreSafetyObservation {
199    /// Normalize/sort nonempty bounded unique actual targets under the actual full inventory.
200    /// # Errors
201    /// Rejects excessive/empty rows, malformed principals, duplicates or unknown targets.
202    pub fn new(
203        mut input: RestoreSafetyObservationInput,
204    ) -> Result<Self, RestoreSafetyObservationError> {
205        if input.targets.is_empty() || input.targets.len() > MAX_INVENTORY_TARGETS {
206            return Err(RestoreSafetyObservationError::InvalidTargetCount);
207        }
208        for target in &mut input.targets {
209            target.target = super::principal::canonical_text(&target.target)
210                .ok_or(RestoreSafetyObservationError::InvalidPrincipal)?;
211            if input.inventory.target(&target.target).is_err() {
212                return Err(RestoreSafetyObservationError::TargetAbsentFromInventory);
213            }
214        }
215        input.targets.sort_by(|a, b| a.target.cmp(&b.target));
216        if input
217            .targets
218            .windows(2)
219            .any(|pair| pair[0].target == pair[1].target)
220        {
221            return Err(RestoreSafetyObservationError::DuplicateTarget);
222        }
223        Ok(Self { input })
224    }
225    /// Read current request identity.
226    #[must_use]
227    pub const fn request(&self) -> &ArtifactChecksumRecord {
228        &self.input.request
229    }
230    /// Read actual canonical current context.
231    #[must_use]
232    pub const fn context(&self) -> &PlanContextRecord {
233        &self.input.context
234    }
235    /// Read complete actual inventory.
236    #[must_use]
237    pub const fn inventory(&self) -> &InventoryRecord {
238        &self.input.inventory
239    }
240    /// Read actual qualified source plan identity.
241    #[must_use]
242    pub const fn source_plan_intent(&self) -> &ArtifactChecksumRecord {
243        &self.input.source_plan_intent
244    }
245    /// Read actual qualified source artifact binding.
246    #[must_use]
247    pub const fn source_artifacts(&self) -> &ArtifactChecksumRecord {
248        &self.input.source_artifacts
249    }
250    /// Read canonical actual selected rows.
251    #[must_use]
252    pub fn targets(&self) -> &[TargetRestoreEvidence] {
253        &self.input.targets
254    }
255    /// Read current application-qualified safety lane.
256    #[must_use]
257    pub const fn safety(&self) -> &RestoreSafetyEvidence {
258        &self.input.safety
259    }
260    /// Read opaque qualified evidence.
261    #[must_use]
262    pub const fn evidence(&self) -> &ArtifactChecksumRecord {
263        &self.input.evidence
264    }
265    /// Read actual descriptive calls, without new authority or accounting.
266    #[must_use]
267    pub const fn remote_observations(&self) -> u32 {
268        self.input.remote_observations
269    }
270}
271/// Typed owning-boundary current evidence admission denial.
272#[derive(Debug, Eq, Error, PartialEq)]
273pub enum RestoreSafetyObservationError {
274    /// Actual rows must be nonempty and within the inventory bound.
275    #[error("restore safety targets must contain 1..={MAX_INVENTORY_TARGETS} entries")]
276    InvalidTargetCount,
277    /// Target principal failed bounded normalization.
278    #[error("invalid restore safety target principal")]
279    InvalidPrincipal,
280    /// Canonical equivalent targets cannot appear twice.
281    #[error("duplicate restore safety target")]
282    DuplicateTarget,
283    /// Actual row is absent from the actual full inventory.
284    #[error("restore safety target absent from inventory")]
285    TargetAbsentFromInventory,
286}
287/// Typed original request denial; changes no source, fence, spending or journal.
288#[derive(Debug, Error)]
289pub enum RestoreSafetyRequestError {
290    /// Original source/safety/plan declarations differ.
291    #[error(transparent)]
292    Requirement(#[from] RestoreSafetyRequirementError),
293    /// Exact original operation cannot be derived.
294    #[error(transparent)]
295    Plan(#[from] OperationPlanError),
296    /// Exact original mutation bytes/target differ.
297    #[error(transparent)]
298    Payload(#[from] IcRequestError),
299    /// Only load/start are within this safety boundary.
300    #[error("restore safety requires exact load or start request")]
301    UnsupportedMethod,
302    /// Descriptive observation ceiling is excessive.
303    #[error("restore safety observation ceiling exceeds {MAX_RESTORE_SAFETY_REMOTE_OBSERVATIONS}")]
304    ObservationLimitTooLarge,
305}
306
307#[cfg(test)]
308mod tests;