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