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    evidence_digest::EvidenceDigest,
14    ic_request::{IcManagementMethodRecord, IcManagementRequestRecord, IcRequestError},
15    inventory::{InventoryRecord, MAX_INVENTORY_TARGETS},
16    operation_plan::{OperationPlanError, OperationPlanRecord, PlanContextRecord},
17};
18use ic_management_canister_types::CanisterStatusType;
19use thiserror::Error;
20
21/// Maximum descriptive remote observations per invocation; no spending allowance.
22pub const MAX_RESTORE_SAFETY_REMOTE_OBSERVATIONS: u32 = 1024;
23/// Passive current parameters; the exact load/start boundary is derived from original wire bytes.
24#[derive(Clone, Debug)]
25pub struct RestoreSafetyRequestInput {
26    /// Exact original load/start operation sequence.
27    pub operation_sequence: u64,
28    /// Integration-owned fresh challenge, qualified independently of hash equality.
29    pub challenge: ArtifactChecksumRecord,
30    /// Descriptive call ceiling; every actual call needs separate prior accounting.
31    pub max_remote_observations: u32,
32}
33/// Ephemeral original-source/safety/challenge request; no dispatch or paid-call permit.
34#[derive(Clone, Debug)]
35pub struct RestoreSafetyRequest<'a> {
36    plan: &'a OperationPlanRecord,
37    requirement: &'a RestoreSafetyRequirementRecord,
38    binding: OperationBindingRecord,
39    wire: &'a IcManagementRequestRecord,
40    input: RestoreSafetyRequestInput,
41}
42impl<'a> RestoreSafetyRequest<'a> {
43    /// Validate exact original plans, requirement and load/start mutation bytes.
44    ///
45    /// The integration admits the retained requirement before effect-boundary
46    /// use and retains original source artifacts and fence obligations. This
47    /// constructor performs no IO and cannot prove that custody.
48    /// # Errors
49    /// Rejects changed source/plan/payload, other methods or excessive descriptive calls.
50    pub fn new(
51        plan: &'a OperationPlanRecord,
52        source: &OperationPlanRecord,
53        requirement: &'a RestoreSafetyRequirementRecord,
54        wire: &'a IcManagementRequestRecord,
55        input: RestoreSafetyRequestInput,
56    ) -> Result<Self, RestoreSafetyRequestError> {
57        requirement.validate_plans(plan, source)?;
58        if input.max_remote_observations > MAX_RESTORE_SAFETY_REMOTE_OBSERVATIONS {
59            return Err(RestoreSafetyRequestError::ObservationLimitTooLarge);
60        }
61        if !matches!(
62            wire.method(),
63            IcManagementMethodRecord::LoadCanisterSnapshot
64                | IcManagementMethodRecord::StartCanister
65        ) {
66            return Err(RestoreSafetyRequestError::UnsupportedMethod);
67        }
68        let binding = plan
69            .attempt_authority(input.operation_sequence)?
70            .binding()
71            .clone();
72        wire.validate_mutation_binding(&binding)?;
73        Ok(Self {
74            plan,
75            requirement,
76            binding,
77            wire,
78            input,
79        })
80    }
81    /// Read exact original operation, context, target and request identity.
82    #[must_use]
83    pub const fn binding(&self) -> &OperationBindingRecord {
84        &self.binding
85    }
86    /// Read original full inventory, including unselected metadata.
87    #[must_use]
88    pub const fn inventory(&self) -> &InventoryRecord {
89        self.plan.inventory()
90    }
91    /// Read exact original selected IDs in canonical order, not dispatch order.
92    #[must_use]
93    pub fn selected_targets(&self) -> &[String] {
94        self.plan.selected_targets()
95    }
96    /// Read original immutable source and safety requirement.
97    #[must_use]
98    pub const fn requirement(&self) -> &RestoreSafetyRequirementRecord {
99        self.requirement
100    }
101    /// Read exact original load/start wire request; codecs confer no load settlement.
102    #[must_use]
103    pub const fn wire(&self) -> &IcManagementRequestRecord {
104        self.wire
105    }
106    /// Read challenge; matching values alone prove no freshness.
107    #[must_use]
108    pub const fn challenge(&self) -> &ArtifactChecksumRecord {
109        &self.input.challenge
110    }
111    /// Read descriptive call ceiling without spending/replenishment.
112    #[must_use]
113    pub const fn max_remote_observations(&self) -> u32 {
114        self.input.max_remote_observations
115    }
116    /// Hash v1 NUL-terminated ASCII domain, 64 ASCII requirement-digest bytes,
117    /// u64 BE sequence, 64 ASCII wire-digest bytes, 64 ASCII challenge bytes and
118    /// u32 BE descriptive ceiling. Wire digest distinguishes load from start.
119    #[must_use]
120    pub fn digest(&self) -> ArtifactChecksumRecord {
121        let mut framing = EvidenceDigest::new(b"ic-backup/restore-safety-request/v1\0");
122        framing.checksum(&self.requirement.digest());
123        framing.u64_be(self.binding.operation_sequence());
124        framing.checksum(&self.wire.digest());
125        framing.checksum(self.challenge());
126        framing.u32_be(self.max_remote_observations());
127        framing.finish()
128    }
129}
130/// Passive actual lifecycle and integration-qualified source-specific restored acceptance.
131#[derive(Clone, Debug)]
132pub struct TargetRestoreEvidence {
133    /// Actual physical target, normalized at model admission.
134    pub target: String,
135    /// Actual upstream lifecycle state; never inferred from a process exit status.
136    pub state: CanisterStatusType,
137    /// Evidence qualifying lifecycle and, when stopped, drained application work.
138    pub lifecycle_evidence: ArtifactChecksumRecord,
139    /// Current application acceptance of this exact source's restored state, required before start.
140    /// A module hash or load acknowledgement alone cannot supply this evidence.
141    pub restored_acceptance: Option<ArtifactChecksumRecord>,
142}
143impl super::observed_targets::ObservedTargetRow for TargetRestoreEvidence {
144    fn target(&self) -> &str {
145        &self.target
146    }
147
148    fn target_mut(&mut self) -> &mut String {
149        &mut self.target
150    }
151}
152/// Passive exact fence evidence; every opaque field requires application qualification.
153#[derive(Clone, Debug)]
154pub struct RestoreFenceEvidence {
155    /// Actually observed active/inactive custody; unknown custody fails at the provider.
156    pub state: ApplicationFenceState,
157    /// Actually observed fence and current authority revisions, matched to original retention.
158    pub binding: RestoreFenceBindingRecord,
159    /// Whole-selection write, membership, timer, external-work fencing and drained-work evidence.
160    pub whole_selection: ArtifactChecksumRecord,
161    /// Fence and obligation custody outside the source's rewindable state, across failure/recovery.
162    pub rewind_independent_custody: ArtifactChecksumRecord,
163    /// Qualified external-obligation disposition and prevention of replayed irreversible work.
164    /// Settlement alone is insufficient if restored intent can replay that work.
165    pub external_obligations_and_replay: ArtifactChecksumRecord,
166    /// Current allowance for isolated restored execution under the retained fence, required before start.
167    /// This is application evidence, not a release token, future guarantee or dispatch permit.
168    pub controlled_execution: Option<ArtifactChecksumRecord>,
169}
170/// Actual application safety lane; no generic default or serialized Proven admission.
171#[derive(Clone, Debug)]
172pub enum RestoreSafetyEvidence {
173    /// Qualified absence of irreversible external effects, including restored intent/timers.
174    NoIrreversibleEffects(ArtifactChecksumRecord),
175    /// Qualified whole-selection custody outside rewindable state and external-work replay safety.
176    ApplicationFenced(Box<RestoreFenceEvidence>),
177    /// Known unsafe or unresolved external obligations; pure policy rejects this evidence.
178    Unresolved(ArtifactChecksumRecord),
179}
180/// Passive provider data; exact original context/source and current evidence are independent inputs.
181#[derive(Clone, Debug)]
182pub struct RestoreSafetyObservationInput {
183    /// Exact current challenge-bound request digest.
184    pub request: ArtifactChecksumRecord,
185    /// Actual current canonical network/caller/release, not echoed expected labels.
186    pub context: PlanContextRecord,
187    /// Complete actual current inventory, including unselected parent metadata.
188    pub inventory: InventoryRecord,
189    /// Qualified exact original source plan identity.
190    pub source_plan_intent: ArtifactChecksumRecord,
191    /// Qualified complete original source artifacts in stable retained custody,
192    /// including exact target-local load snapshot association when checking load.
193    pub source_artifacts: ArtifactChecksumRecord,
194    /// Actual lifecycle and restored acceptance for the exact selected set.
195    pub targets: Vec<TargetRestoreEvidence>,
196    /// Actual application safety lane and evidence for this exact source/selection/boundary.
197    pub safety: RestoreSafetyEvidence,
198    /// Opaque integration-qualified evidence identity; no signature or permission.
199    pub evidence: ArtifactChecksumRecord,
200    /// Actual remote observations, each needing separate prior spending authority.
201    pub remote_observations: u32,
202}
203/// Canonical immutable ephemeral observation; no Serde, expiry or persisted authority flag.
204#[derive(Clone, Debug)]
205pub struct RestoreSafetyObservation {
206    input: RestoreSafetyObservationInput,
207}
208impl RestoreSafetyObservation {
209    /// Normalize/sort nonempty bounded unique actual targets under the actual full inventory.
210    /// # Errors
211    /// Rejects excessive/empty rows, malformed principals, duplicates or unknown targets.
212    pub fn new(
213        mut input: RestoreSafetyObservationInput,
214    ) -> Result<Self, RestoreSafetyObservationError> {
215        input.targets = super::observed_targets::canonicalize(
216            input.targets,
217            &input.inventory,
218            || RestoreSafetyObservationError::InvalidTargetCount,
219            || RestoreSafetyObservationError::InvalidPrincipal,
220            || RestoreSafetyObservationError::TargetAbsentFromInventory,
221            || 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;