Skip to main content

ic_backup/policy/consistency/
mod.rs

1//! Pure original-guarantee and current stopped/drained/fence matching; no effects.
2
3use crate::model::{
4    artifacts::ArtifactChecksumRecord,
5    consistency::{
6        ApplicationFenceEvidence, ApplicationFenceState, CaptureState, ConsistencyEvidence,
7        ConsistencyGuaranteeRecord, ConsistencyObservation, ConsistencyRequest,
8        TargetCaptureEvidence,
9    },
10};
11use thiserror::Error;
12
13/// Read-only matched current evidence; no capture, restart, release or spending permit.
14#[derive(Clone, Debug)]
15pub struct ConsistencyView<'a> {
16    request: ArtifactChecksumRecord,
17    requirement: ArtifactChecksumRecord,
18    observation: &'a ConsistencyObservation,
19}
20impl ConsistencyView<'_> {
21    /// Read exact challenge/boundary/fence-bound current request digest.
22    #[must_use]
23    pub const fn request(&self) -> &ArtifactChecksumRecord {
24        &self.request
25    }
26    /// Read immutable original consistency requirement digest.
27    #[must_use]
28    pub const fn requirement(&self) -> &ArtifactChecksumRecord {
29        &self.requirement
30    }
31    /// Read matched exact selected stopped/drained target evidence.
32    #[must_use]
33    pub fn targets(&self) -> &[TargetCaptureEvidence] {
34        self.observation.targets()
35    }
36    /// Read matched active application fence when the original guarantee requires one.
37    #[must_use]
38    pub fn fence(&self) -> Option<&ApplicationFenceEvidence> {
39        match self.observation.consistency() {
40            ConsistencyEvidence::PerCanister => None,
41            ConsistencyEvidence::ApplicationCoordinated(fence) => Some(fence),
42        }
43    }
44    /// Read opaque integration-qualified current evidence.
45    #[must_use]
46    pub const fn evidence(&self) -> &ArtifactChecksumRecord {
47        self.observation.evidence()
48    }
49    /// Read actual call reporting; grants no paid-call admission/replenishment.
50    #[must_use]
51    pub const fn remote_observations(&self) -> u32 {
52        self.observation.remote_observations()
53    }
54}
55/// Match original guarantee, current context/inventory/selection/stopped state and exact fence.
56///
57/// Integrations qualify evidence authenticity, actual freshness/drain and continuous
58/// fence custody. Policy cannot prove these through hashes, echoed labels or matching
59/// before/after observations. It performs no IO/serialization/provider calls, plan or
60/// journal changes, dispatch, restart or fence release. Restore safety remains separate.
61/// # Errors
62/// Rejects changed request/context/inventory/selection/lane, non-stopped targets,
63/// excess calls, changed retained fence identity or unbound membership revision.
64pub fn validate<'a>(
65    request: &ConsistencyRequest<'_>,
66    observation: &'a ConsistencyObservation,
67) -> Result<ConsistencyView<'a>, ConsistencyError> {
68    let digest = request.digest();
69    if *observation.request() != digest {
70        return Err(ConsistencyError::RequestMismatch);
71    }
72    let binding = request.binding();
73    if let Some(field) = super::observed_context::first_mismatch(binding, observation.context()) {
74        return Err(ConsistencyError::ContextMismatch(field));
75    }
76    if observation.inventory() != request.inventory() {
77        return Err(ConsistencyError::InventoryMismatch);
78    }
79    if !observation
80        .targets()
81        .iter()
82        .map(|target| &target.target)
83        .eq(request.selected_targets())
84    {
85        return Err(ConsistencyError::SelectionMismatch);
86    }
87    if observation.remote_observations() > request.max_remote_observations() {
88        return Err(ConsistencyError::ObservationLimitExceeded {
89            limit: request.max_remote_observations(),
90            reported: observation.remote_observations(),
91        });
92    }
93    if observation
94        .targets()
95        .iter()
96        .any(|target| target.state != CaptureState::Stopped)
97    {
98        return Err(ConsistencyError::TargetNotStopped);
99    }
100    match (request.requirement().guarantee(), observation.consistency()) {
101        (ConsistencyGuaranteeRecord::PerCanister, ConsistencyEvidence::PerCanister) => {}
102        (
103            ConsistencyGuaranteeRecord::ApplicationCoordinated,
104            ConsistencyEvidence::ApplicationCoordinated(fence),
105        ) => {
106            let expected = request
107                .expected_fence()
108                .ok_or(ConsistencyError::FenceMismatch)?;
109            if fence.identity != expected.identity {
110                return Err(ConsistencyError::FenceMismatch);
111            }
112            if fence.state != ApplicationFenceState::Active {
113                return Err(ConsistencyError::FenceNotActive);
114            }
115            let original_revision_matches =
116                observation.membership_revision() == Some(&expected.membership_revision);
117            let fence_revision_matches = fence.membership_revision == expected.membership_revision;
118            if !original_revision_matches || !fence_revision_matches {
119                return Err(ConsistencyError::MembershipRevisionMismatch);
120            }
121        }
122        _ => return Err(ConsistencyError::GuaranteeMismatch),
123    }
124    Ok(ConsistencyView {
125        request: digest,
126        requirement: request.requirement().digest(),
127        observation,
128    })
129}
130/// Typed current evidence denial; no failure releases fences or replenishes allowances.
131#[derive(Debug, Eq, Error, PartialEq)]
132pub enum ConsistencyError {
133    /// Original requirement/operation/challenge/boundary/fence/ceiling differs.
134    #[error("consistency request mismatch")]
135    RequestMismatch,
136    /// Actually observed context differs.
137    #[error("consistency observed {0} mismatch")]
138    ContextMismatch(&'static str),
139    /// Complete actually observed inventory differs, including unselected parent metadata.
140    #[error("consistency inventory mismatch")]
141    InventoryMismatch,
142    /// Actual target evidence differs from the exact original selected set.
143    #[error("consistency selected targets mismatch")]
144    SelectionMismatch,
145    /// Evidence cannot upgrade or downgrade the original declared guarantee.
146    #[error("consistency evidence guarantee mismatch")]
147    GuaranteeMismatch,
148    /// At least one actual target is running or still stopping.
149    #[error("consistency target is not stopped")]
150    TargetNotStopped,
151    /// Actual fence differs from the retained exact obligation.
152    #[error("consistency fence identity mismatch")]
153    FenceMismatch,
154    /// Current exact fence is known inactive; retain the obligation and deny capture.
155    #[error("consistency fence is not active")]
156    FenceNotActive,
157    /// Missing/changed actual revision is not bound to the application fence.
158    #[error("consistency fence membership revision mismatch")]
159    MembershipRevisionMismatch,
160    /// Actual call reporting exceeds the descriptive ceiling.
161    #[error("consistency reports {reported} observations above ceiling {limit}")]
162    ObservationLimitExceeded {
163        /// Original descriptive ceiling, separate from allowances.
164        limit: u32,
165        /// Reported actual calls.
166        reported: u32,
167    },
168}
169
170#[cfg(test)]
171mod tests;