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/// RuntimeBootstrapPolicy
138///
139/// Host policy for recovered admission, allocation checks and runtime identity.
140///
141/// The runtime admits host grants and pool eligibility before calling the
142/// allocation check for each external declaration. Governance stays private;
143/// historical ownership checks still apply to every declaration.
144///
145/// [`crate::MemoryRuntime`] binds its successful bootstrap to this identity.
146/// Repeated bootstrap is idempotent only when the caller supplies the same
147/// sealed declaration snapshot and the same policy identity. Implementations
148/// should change the identity whenever policy configuration or semantics
149/// change. Configuration-dependent policies should include a digest derived
150/// from their effective configuration.
151///
152
153pub trait RuntimeBootstrapPolicy {
154    /// Policy error type.
155    type Error;
156
157    /// Validate one resolved stable-key and allocation-slot claim.
158    /// The runtime checks host grants and pool eligibility before this callback;
159    /// historical ownership checks follow it. Governance bypasses this callback.
160    fn validate_allocation(
161        &self,
162        key: &StableKey,
163        slot: &MemoryManagerSlot,
164    ) -> Result<(), Self::Error>;
165
166    /// Admit recovered identity and complete declarations before resolution.
167    ///
168    /// Runs once per cold bootstrap attempt after validated recovery. Warm
169    /// bootstrap/adoption does not replay it. The default selects no historical
170    /// keys. Hosts compose generated consumers here under their existing policy
171    /// and bucket profile. Include these semantics in the policy identity.
172    fn prepare_bootstrap(
173        &self,
174        _admission: &mut crate::BootstrapAdmission<'_>,
175    ) -> Result<(), Self::Error> {
176        Ok(())
177    }
178
179    /// Construct the bounded semantic identity of this policy configuration.
180    fn runtime_bootstrap_identity(&self) -> Result<PolicyIdentity, PolicyIdentityError>;
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn policy_identity_validates_name_version_and_digest() {
189        let digest = [0xA5; 32];
190        let identity = PolicyIdentity::new("canic.memory-bootstrap-policy", 1)
191            .expect("valid identity")
192            .with_configuration_digest(digest);
193
194        assert_eq!(identity.name(), "canic.memory-bootstrap-policy");
195        assert_eq!(identity.version(), 1);
196        assert_eq!(identity.configuration_digest(), Some(&digest));
197    }
198
199    #[test]
200    fn policy_identity_rejects_unbounded_or_noncanonical_metadata() {
201        assert_eq!(
202            PolicyIdentity::new("", 1).expect_err("empty name"),
203            PolicyIdentityError::EmptyName
204        );
205        assert!(matches!(
206            PolicyIdentity::new("x".repeat(DIAGNOSTIC_STRING_MAX_BYTES + 1), 1),
207            Err(PolicyIdentityError::NameTooLong { .. })
208        ));
209        assert_eq!(
210            PolicyIdentity::new("policy\nname", 1).expect_err("control character"),
211            PolicyIdentityError::ControlCharacterName
212        );
213        assert_eq!(
214            PolicyIdentity::new("policé", 1).expect_err("non-ASCII"),
215            PolicyIdentityError::NonAsciiName
216        );
217        assert_eq!(
218            PolicyIdentity::new("policy", 0).expect_err("zero version"),
219            PolicyIdentityError::ZeroVersion
220        );
221    }
222
223    #[test]
224    fn policy_identity_deserialization_revalidates_invariants() {
225        #[derive(Serialize)]
226        struct UncheckedPolicyIdentity<'a> {
227            name: &'a str,
228            version: u32,
229            configuration_digest: Option<[u8; 32]>,
230        }
231
232        let bytes = crate::test_cbor::to_vec(&UncheckedPolicyIdentity {
233            name: "",
234            version: 1,
235            configuration_digest: None,
236        })
237        .expect("invalid diagnostic bytes");
238        let error = crate::test_cbor::from_slice::<PolicyIdentity>(&bytes)
239            .expect_err("deserialization must revalidate identity");
240        assert!(error.to_string().contains("must not be empty"));
241    }
242}