Skip to main content

ic_backup/model/ic_request/
mod.rs

1//! Closed host-ingress IC request codec; no transport, authority or effect admission.
2
3use crate::model::evidence_digest::EvidenceDigest;
4use ic_platform::candid_codec as contract;
5mod method;
6pub use method::{IcManagementMethodRecord, IcRequestEffect};
7
8use crate::model::{
9    artifacts::ArtifactChecksumRecord, attempt_journal::OperationBindingRecord, bounded_sequence,
10};
11use ic_platform::management_canister_types::{
12    CanisterIdRecord, LoadCanisterSnapshotArgs, TakeCanisterSnapshotArgs,
13};
14use serde::{Deserialize, Deserializer, Serialize};
15use thiserror::Error;
16
17/// Maximum raw snapshot identifier bytes, distinct from any backend's rendered token.
18pub const MAX_IC_SNAPSHOT_ID_BYTES: usize = 256;
19/// Maximum derived Candid argument bytes; checked before a request is admitted.
20pub const MAX_IC_ARGUMENT_BYTES: usize = 4096;
21/// Bound callers must use for encoded JSON input/output when retaining this record.
22pub const MAX_IC_REQUEST_RECORD_BYTES: u64 = 8192;
23
24/// Passive method/target/snapshot input; network, caller and permissions stay with their owners.
25#[derive(Clone, Debug)]
26pub struct IcManagementRequest {
27    /// One of the closed supported management methods.
28    pub method: IcManagementMethodRecord,
29    /// Exact effective canister principal; normalized on admission.
30    pub target: String,
31    /// Raw nonempty snapshot bytes required only for load; otherwise exactly None.
32    pub snapshot_id: Option<Vec<u8>>,
33}
34
35/// Immutable v1 request declaration with model-derived exact Candid bytes.
36///
37/// All supported methods use replicated update ingress, including observations.
38/// Network/caller selection, signing, freshness, budgets, custody and lifecycle
39/// safety are not granted by this record or its digest.
40#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
41#[serde(try_from = "RequestFields")]
42pub struct IcManagementRequestRecord {
43    version: u16,
44    method: IcManagementMethodRecord,
45    target: String,
46    snapshot_id: Option<Vec<u8>>,
47    #[serde(skip)]
48    target_bytes: Vec<u8>,
49    #[serde(skip)]
50    arguments: Vec<u8>,
51}
52#[derive(Deserialize)]
53#[serde(deny_unknown_fields)]
54struct RequestFields {
55    version: u16,
56    method: IcManagementMethodRecord,
57    target: String,
58    #[serde(deserialize_with = "required_snapshot")]
59    snapshot_id: Option<Vec<u8>>,
60}
61impl TryFrom<RequestFields> for IcManagementRequestRecord {
62    type Error = IcRequestError;
63    fn try_from(fields: RequestFields) -> Result<Self, Self::Error> {
64        if fields.version != 1 {
65            return Err(IcRequestError::UnsupportedVersion(fields.version));
66        }
67        Self::new(IcManagementRequest {
68            method: fields.method,
69            target: fields.target,
70            snapshot_id: fields.snapshot_id,
71        })
72    }
73}
74impl IcManagementRequestRecord {
75    /// Validate the closed request and encode exact host-ingress arguments.
76    ///
77    /// Capture retains code and creates a new snapshot; sender canister version
78    /// stays absent for host ingress. Load names exact raw bytes, with no identity remap.
79    ///
80    /// # Errors
81    /// Rejects malformed principals, missing/unexpected/oversized snapshot IDs,
82    /// Candid encoding failure and excessive derived argument bytes.
83    pub fn new(request: IcManagementRequest) -> Result<Self, IcRequestError> {
84        let (target, principal) = crate::model::principal::canonical_parts(&request.target)
85            .ok_or(IcRequestError::InvalidTarget)?;
86        let arguments = match (request.method, request.snapshot_id.as_deref()) {
87            (IcManagementMethodRecord::LoadCanisterSnapshot, None) => {
88                return Err(IcRequestError::SnapshotRequired);
89            }
90            (IcManagementMethodRecord::LoadCanisterSnapshot, Some(bytes)) => {
91                if !admits_snapshot_id(bytes) {
92                    return Err(IcRequestError::InvalidSnapshotId);
93                }
94                encode_arguments(LoadCanisterSnapshotArgs {
95                    canister_id: principal,
96                    snapshot_id: bytes.to_vec(),
97                    sender_canister_version: None,
98                })
99            }
100            (_, Some(_)) => return Err(IcRequestError::UnexpectedSnapshot),
101            (IcManagementMethodRecord::TakeCanisterSnapshot, None) => {
102                encode_arguments(TakeCanisterSnapshotArgs {
103                    canister_id: principal,
104                    replace_snapshot: None,
105                    uninstall_code: Some(false),
106                    sender_canister_version: None,
107                })
108            }
109            (
110                IcManagementMethodRecord::CanisterStatus
111                | IcManagementMethodRecord::ListCanisterSnapshots
112                | IcManagementMethodRecord::StartCanister
113                | IcManagementMethodRecord::StopCanister,
114                None,
115            ) => encode_arguments(CanisterIdRecord {
116                canister_id: principal,
117            }),
118        }?;
119        Ok(Self {
120            version: 1,
121            method: request.method,
122            target,
123            snapshot_id: request.snapshot_id,
124            target_bytes: principal.as_slice().to_vec(),
125            arguments,
126        })
127    }
128    /// Read the exact closed method; its effect class does not grant spending authority.
129    #[must_use]
130    pub const fn method(&self) -> IcManagementMethodRecord {
131        self.method
132    }
133    /// Read the canonical effective routing target, also encoded inside the arguments.
134    #[must_use]
135    pub fn target(&self) -> &str {
136        &self.target
137    }
138    /// Read exact raw load snapshot bytes, without backend token interpretation.
139    #[must_use]
140    pub fn snapshot_id(&self) -> Option<&[u8]> {
141        self.snapshot_id.as_deref()
142    }
143    /// Read derived exact Candid bytes for a future qualified update-ingress transport.
144    #[must_use]
145    pub fn arguments(&self) -> &[u8] {
146        &self.arguments
147    }
148    /// Read the fixed management receiver; the effective routing target is separate.
149    #[must_use]
150    pub const fn receiver(&self) -> &'static str {
151        "aaaaa-aa"
152    }
153    /// Hash fixed receiver, effective target, update mode, exact method and Candid bytes.
154    ///
155    /// Network/caller/intent/release/budgets stay outside this nonrecursive payload
156    /// digest and are bound by the existing operation plan/attempt authority.
157    #[must_use]
158    pub fn digest(&self) -> ArtifactChecksumRecord {
159        management_request_digest(&self.target_bytes, self.method.name(), &self.arguments)
160    }
161    /// Check exact payload target/digest and mutation class against original declared binding.
162    ///
163    /// This verifies bytes only; it does not authenticate the binding or admit dispatch.
164    /// # Errors
165    /// Rejects observation methods and changed target or request digest.
166    pub fn validate_mutation_binding(
167        &self,
168        binding: &OperationBindingRecord,
169    ) -> Result<(), IcRequestError> {
170        self.require_effect(IcRequestEffect::Mutation)?;
171        self.validate_identity(binding, binding.request())
172    }
173    /// Check an observation payload against its exact target and reserved observation digest.
174    ///
175    /// The original binding still names the mutation. The observation digest is
176    /// separately retained by the existing journal's observation reservation.
177    /// # Errors
178    /// Rejects mutation methods, changed target or a different observation digest.
179    pub fn validate_observation_binding(
180        &self,
181        binding: &OperationBindingRecord,
182        request: &ArtifactChecksumRecord,
183    ) -> Result<(), IcRequestError> {
184        self.require_effect(IcRequestEffect::Observation)?;
185        self.validate_identity(binding, request.hash())
186    }
187    fn require_effect(&self, expected: IcRequestEffect) -> Result<(), IcRequestError> {
188        if self.method.effect() != expected {
189            return Err(IcRequestError::EffectMismatch { expected });
190        }
191        Ok(())
192    }
193    fn validate_identity(
194        &self,
195        binding: &OperationBindingRecord,
196        expected: &str,
197    ) -> Result<(), IcRequestError> {
198        if self.target != binding.target() {
199            return Err(IcRequestError::TargetMismatch);
200        }
201        if self.digest().hash() != expected {
202            return Err(IcRequestError::DigestMismatch);
203        }
204        Ok(())
205    }
206}
207
208pub(super) fn encode_arguments(value: impl contract::Encode) -> Result<Vec<u8>, IcRequestError> {
209    let arguments =
210        contract::encode_one(&value, MAX_IC_ARGUMENT_BYTES).map_err(|error| match error {
211            contract::Error::Limit => IcRequestError::ArgumentsTooLarge,
212            contract::Error::Schema => IcRequestError::Encoding(format!("{error:?}")),
213        })?;
214    if arguments.len() > MAX_IC_ARGUMENT_BYTES {
215        return Err(IcRequestError::ArgumentsTooLarge);
216    }
217    Ok(arguments)
218}
219
220// Shared scalar admission; callers retain method-specific absence/source-ID rules
221// and JSON/Candid visitors retain their separate bounded decoding behavior.
222pub(super) fn admits_snapshot_id(bytes: &[u8]) -> bool {
223    !bytes.is_empty() && bytes.len() <= MAX_IC_SNAPSHOT_ID_BYTES
224}
225
226// Callers own canonical principal bytes, a fixed ASCII method and bounded arguments.
227pub(super) fn management_request_digest(
228    target_bytes: &[u8],
229    method: &str,
230    arguments: &[u8],
231) -> ArtifactChecksumRecord {
232    let mut bytes = EvidenceDigest::new(b"ic-backup/ic-management-request/v1\0");
233    bytes.byte(0); // Management receiver principal has zero raw bytes.
234    bytes.bytes_u8(target_bytes);
235    bytes.byte(1); // Replicated update ingress.
236    bytes.bytes_u8(method.as_bytes());
237    bytes.bytes_u32(arguments);
238    bytes.finish()
239}
240
241fn required_snapshot<'de, D: Deserializer<'de>>(
242    deserializer: D,
243) -> Result<Option<Vec<u8>>, D::Error> {
244    Ok(Option::<SnapshotBytes>::deserialize(deserializer)?.map(|bytes| bytes.0))
245}
246struct SnapshotBytes(Vec<u8>);
247impl<'de> Deserialize<'de> for SnapshotBytes {
248    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
249        bounded_sequence::deserialize::<_, u8, MAX_IC_SNAPSHOT_ID_BYTES>(
250            deserializer,
251            "at most 256 exact snapshot bytes",
252            IcRequestError::InvalidSnapshotId,
253        )
254        .map(Self)
255    }
256}
257
258/// Typed closed IC request, exact byte binding or codec admission failure.
259#[derive(Debug, Error, Eq, PartialEq)]
260pub enum IcRequestError {
261    /// Other product generations are not maintained.
262    #[error("unsupported IC request version {0}")]
263    UnsupportedVersion(u16),
264    /// Target text is not a bounded canonicalizable principal.
265    #[error("invalid IC request target principal")]
266    InvalidTarget,
267    /// Load requires exact raw snapshot bytes.
268    #[error("load snapshot request requires snapshot_id")]
269    SnapshotRequired,
270    /// A method that has no snapshot argument received one.
271    #[error("snapshot_id is not admitted for this IC request method")]
272    UnexpectedSnapshot,
273    /// Snapshot bytes are empty or exceed their finite bound.
274    #[error("snapshot_id must contain 1..={MAX_IC_SNAPSHOT_ID_BYTES} raw bytes")]
275    InvalidSnapshotId,
276    /// The pinned upstream Candid encoder rejected the typed arguments.
277    #[error("IC request Candid encoding failed: {0}")]
278    Encoding(String),
279    /// Derived argument size exceeds the codec bound.
280    #[error("IC request arguments exceed {MAX_IC_ARGUMENT_BYTES} bytes")]
281    ArgumentsTooLarge,
282    /// A mutation and observation request cannot substitute for each other.
283    #[error("IC request must have effect class {expected:?}")]
284    EffectMismatch {
285        /// Required semantic class, independent of replicated call mode.
286        expected: IcRequestEffect,
287    },
288    /// The payload/routing target differs from the original operation target.
289    #[error("IC request target differs from original binding")]
290    TargetMismatch,
291    /// Exact method/argument digest differs from its original reservation.
292    #[error("IC request digest differs from original binding")]
293    DigestMismatch,
294}
295
296#[cfg(test)]
297mod tests;