Skip to main content

ic_memory/
policy.rs

1use crate::{
2    constants::DIAGNOSTIC_STRING_MAX_BYTES,
3    key::StableKey,
4    slot::MemoryManagerSlot,
5    text::{DiagnosticTextError, validate_diagnostic_text},
6};
7use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
8
9///
10/// PolicyIdentity
11///
12/// Bounded semantic identity for one runtime bootstrap policy configuration.
13///
14/// The name identifies the policy family, `version` changes when its semantics
15/// change, and the optional digest distinguishes runtime configuration. The
16/// digest is supplied by the policy implementation; ic-memory does not choose
17/// or compute a hashing algorithm.
18///
19/// This identity is an in-memory repeat-call and diagnostic binding. It is not
20/// persisted to the allocation ledger.
21///
22
23#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
24pub struct PolicyIdentity {
25    name: Box<str>,
26    version: u32,
27    configuration_digest: Option<[u8; 32]>,
28}
29
30#[derive(Deserialize)]
31#[serde(deny_unknown_fields)]
32struct PolicyIdentityRepresentation {
33    name: String,
34    version: u32,
35    #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
36    configuration_digest: Option<[u8; 32]>,
37}
38
39impl<'de> Deserialize<'de> for PolicyIdentity {
40    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
41    where
42        D: Deserializer<'de>,
43    {
44        let representation = PolicyIdentityRepresentation::deserialize(deserializer)?;
45        let mut identity =
46            Self::new(representation.name, representation.version).map_err(D::Error::custom)?;
47        identity.configuration_digest = representation.configuration_digest;
48        Ok(identity)
49    }
50}
51
52impl PolicyIdentity {
53    /// Construct a validated policy identity without a configuration digest.
54    pub fn new(name: impl Into<String>, version: u32) -> Result<Self, PolicyIdentityError> {
55        let name = name.into();
56        validate_policy_identity_name(&name)?;
57        if version == 0 {
58            return Err(PolicyIdentityError::ZeroVersion);
59        }
60        Ok(Self {
61            name: name.into_boxed_str(),
62            version,
63            configuration_digest: None,
64        })
65    }
66
67    /// Attach a caller-computed configuration digest.
68    #[must_use]
69    pub const fn with_configuration_digest(mut self, digest: [u8; 32]) -> Self {
70        self.configuration_digest = Some(digest);
71        self
72    }
73
74    /// Borrow the bounded policy-family name.
75    #[must_use]
76    pub fn name(&self) -> &str {
77        &self.name
78    }
79
80    /// Return the nonzero semantic policy version.
81    #[must_use]
82    pub const fn version(&self) -> u32 {
83        self.version
84    }
85
86    /// Borrow the optional caller-computed configuration digest.
87    #[must_use]
88    pub const fn configuration_digest(&self) -> Option<&[u8; 32]> {
89        self.configuration_digest.as_ref()
90    }
91}
92
93///
94/// PolicyIdentityError
95///
96/// Failure to construct a bounded runtime bootstrap policy identity.
97///
98
99#[non_exhaustive]
100#[derive(Clone, Copy, Debug, Eq, thiserror::Error, PartialEq)]
101pub enum PolicyIdentityError {
102    /// Policy-family names must not be empty.
103    #[error("runtime bootstrap policy identity name must not be empty")]
104    EmptyName,
105    /// Policy-family names must remain bounded diagnostic metadata.
106    #[error("runtime bootstrap policy identity name is {length} bytes; maximum is {maximum} bytes")]
107    NameTooLong {
108        /// Actual UTF-8 byte length.
109        length: usize,
110        /// Maximum accepted byte length.
111        maximum: usize,
112    },
113    /// Policy-family names must not require Unicode normalization.
114    #[error("runtime bootstrap policy identity name must be ASCII")]
115    NonAsciiName,
116    /// Policy-family names must be printable diagnostic metadata.
117    #[error("runtime bootstrap policy identity name must not contain ASCII control characters")]
118    ControlCharacterName,
119    /// Semantic policy version zero is reserved as invalid.
120    #[error("runtime bootstrap policy identity version must be greater than zero")]
121    ZeroVersion,
122}
123
124fn validate_policy_identity_name(name: &str) -> Result<(), PolicyIdentityError> {
125    validate_diagnostic_text(name).map_err(|error| match error {
126        DiagnosticTextError::Empty => PolicyIdentityError::EmptyName,
127        DiagnosticTextError::TooLong => PolicyIdentityError::NameTooLong {
128            length: name.len(),
129            maximum: DIAGNOSTIC_STRING_MAX_BYTES,
130        },
131        DiagnosticTextError::NonAscii => PolicyIdentityError::NonAsciiName,
132        DiagnosticTextError::ControlCharacter => PolicyIdentityError::ControlCharacterName,
133    })
134}
135
136///
137/// AllocationPolicy
138///
139/// Framework-supplied rules for whether a key may claim a slot.
140///
141/// Policy is intentionally separate from the durable ledger invariant. The
142/// ledger remembers `stable_key -> allocation_slot`; this trait lets an
143/// integration reject declarations that do not belong to its namespace or
144/// substrate-specific range before staging a generation.
145///
146/// [`crate::MemoryRuntime`] admits host namespace grants and physical pool
147/// eligibility during resolution, before this policy's validation callbacks.
148/// These callbacks receive external declarations only; the internal
149/// allocation-ledger declaration remains exclusively governed by ic-memory.
150/// Framework policies may add restrictions within the host's grants and pool;
151/// they cannot expand the pool or replace host ownership admission.
152///
153
154pub trait AllocationPolicy {
155    /// Policy error type.
156    type Error;
157
158    /// Validate a stable key against framework naming rules.
159    fn validate_key(&self, key: &StableKey) -> Result<(), Self::Error>;
160
161    /// Validate a stable-key to allocation-slot claim.
162    /// The slot already contains a usable ID; policy checks ownership and scope.
163    fn validate_slot(&self, key: &StableKey, slot: &MemoryManagerSlot) -> Result<(), Self::Error>;
164}
165
166///
167/// RuntimeBootstrapPolicy
168///
169/// Allocation policy with an explicit semantic identity for runtime bootstrap.
170///
171/// [`crate::MemoryRuntime`] binds its successful bootstrap to this identity.
172/// Repeated bootstrap is idempotent only when the caller supplies the same
173/// sealed declaration snapshot and the same policy identity. Implementations
174/// should change the identity whenever policy configuration or semantics
175/// change. Configuration-dependent policies should include a digest derived
176/// from their effective configuration.
177///
178
179pub trait RuntimeBootstrapPolicy: AllocationPolicy {
180    /// Admit recovered identity and complete declarations before resolution.
181    ///
182    /// Runs once per cold bootstrap attempt after validated recovery. Warm
183    /// bootstrap/adoption does not replay it. The default selects no historical
184    /// keys. Hosts compose generated consumers here under their existing policy
185    /// and bucket profile. Include these semantics in the policy identity.
186    fn prepare_bootstrap(
187        &self,
188        _admission: &mut crate::BootstrapAdmission<'_>,
189    ) -> Result<(), Self::Error> {
190        Ok(())
191    }
192
193    /// Construct the bounded semantic identity of this policy configuration.
194    fn runtime_bootstrap_identity(&self) -> Result<PolicyIdentity, PolicyIdentityError>;
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn policy_identity_validates_name_version_and_digest() {
203        let digest = [0xA5; 32];
204        let identity = PolicyIdentity::new("canic.memory-bootstrap-policy", 1)
205            .expect("valid identity")
206            .with_configuration_digest(digest);
207
208        assert_eq!(identity.name(), "canic.memory-bootstrap-policy");
209        assert_eq!(identity.version(), 1);
210        assert_eq!(identity.configuration_digest(), Some(&digest));
211    }
212
213    #[test]
214    fn policy_identity_rejects_unbounded_or_noncanonical_metadata() {
215        assert_eq!(
216            PolicyIdentity::new("", 1).expect_err("empty name"),
217            PolicyIdentityError::EmptyName
218        );
219        assert!(matches!(
220            PolicyIdentity::new("x".repeat(DIAGNOSTIC_STRING_MAX_BYTES + 1), 1),
221            Err(PolicyIdentityError::NameTooLong { .. })
222        ));
223        assert_eq!(
224            PolicyIdentity::new("policy\nname", 1).expect_err("control character"),
225            PolicyIdentityError::ControlCharacterName
226        );
227        assert_eq!(
228            PolicyIdentity::new("policé", 1).expect_err("non-ASCII"),
229            PolicyIdentityError::NonAsciiName
230        );
231        assert_eq!(
232            PolicyIdentity::new("policy", 0).expect_err("zero version"),
233            PolicyIdentityError::ZeroVersion
234        );
235    }
236
237    #[test]
238    fn policy_identity_deserialization_revalidates_invariants() {
239        #[derive(Serialize)]
240        struct UncheckedPolicyIdentity<'a> {
241            name: &'a str,
242            version: u32,
243            configuration_digest: Option<[u8; 32]>,
244        }
245
246        let bytes = crate::test_cbor::to_vec(&UncheckedPolicyIdentity {
247            name: "",
248            version: 1,
249            configuration_digest: None,
250        })
251        .expect("invalid diagnostic bytes");
252        let error = crate::test_cbor::from_slice::<PolicyIdentity>(&bytes)
253            .expect_err("deserialization must revalidate identity");
254        assert!(error.to_string().contains("must not be empty"));
255    }
256}