Skip to main content

ic_storage/runtime/
admission.rs

1//! Canonical declarations, namespace grants and composable host admission.
2use crate::{AllocationId, StableKey};
3use std::collections::BTreeSet;
4
5/// Invalid host declarations or grants; no allocation authority has been granted.
6#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
7pub enum AdmissionError {
8    /// Invalid owner label or namespace.
9    #[error("invalid authority or namespace")]
10    Invalid,
11    /// Stable-key grammar failure.
12    #[error(transparent)]
13    Key(#[from] crate::StableKeyError),
14    /// Duplicate or overlapping declaration/grant.
15    #[error("duplicate key or overlapping namespace")]
16    Duplicate,
17    /// The host has not granted this owner the key's namespace.
18    #[error("namespace is not granted to this authority")]
19    Unauthorized,
20    /// Historical selection is unknown or exceeds the configured count.
21    #[error("unknown historical allocation or declaration budget exceeded")]
22    Limit,
23}
24
25fn owner_valid(owner: &str) -> bool {
26    !owner.is_empty()
27        && owner.len() <= 128
28        && owner
29            .bytes()
30            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
31}
32
33///
34/// MemoryAuthority
35/// Host grant for one owner and a dot-terminated namespace.
36///
37
38#[derive(Clone, Debug, Eq, PartialEq)]
39pub struct MemoryAuthority {
40    authority: String,
41    prefix: String,
42}
43
44impl MemoryAuthority {
45    /// Check owner and namespace syntax. Names do not select numeric IDs.
46    pub fn new(
47        authority: impl Into<String>,
48        prefix: impl Into<String>,
49    ) -> Result<Self, AdmissionError> {
50        let authority = authority.into();
51        let prefix = prefix.into();
52        if !owner_valid(&authority) || !crate::key::is_key_prefix(&prefix) {
53            return Err(AdmissionError::Invalid);
54        }
55
56        Ok(Self { authority, prefix })
57    }
58}
59
60///
61/// AllocationGrants
62/// Canonical, non-overlapping namespace grants for a host composition.
63///
64
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct AllocationGrants(Vec<MemoryAuthority>);
67
68impl AllocationGrants {
69    /// Validate namespace overlap before runtime bootstrap.
70    pub fn new(mut grants: Vec<MemoryAuthority>) -> Result<Self, AdmissionError> {
71        grants.sort_unstable_by(|a, b| a.prefix.cmp(&b.prefix));
72        if grants
73            .windows(2)
74            .any(|pair| pair[1].prefix.starts_with(&pair[0].prefix))
75        {
76            return Err(AdmissionError::Duplicate);
77        }
78
79        Ok(Self(grants))
80    }
81
82    pub(super) fn check(&self, request: &MemoryRequest) -> Result<(), AdmissionError> {
83        if self.0.iter().any(|grant| {
84            grant.authority == request.authority && request.key.as_str().starts_with(&grant.prefix)
85        }) {
86            Ok(())
87        } else {
88            Err(AdmissionError::Unauthorized)
89        }
90    }
91}
92
93///
94/// MemoryRequest
95/// Checked request naming a store under one host-granted authority.
96///
97
98#[derive(Clone, Debug, Eq, PartialEq)]
99pub struct MemoryRequest {
100    authority: String,
101    key: StableKey,
102}
103
104impl MemoryRequest {
105    /// Construct a key-only allocation request.
106    pub fn new(authority: impl Into<String>, key: &str) -> Result<Self, AdmissionError> {
107        let authority = authority.into();
108        if !owner_valid(&authority) {
109            return Err(AdmissionError::Invalid);
110        }
111
112        Ok(Self {
113            authority,
114            key: StableKey::parse(key)?,
115        })
116    }
117
118    /// Declaring authority label.
119    #[must_use]
120    pub fn authority(&self) -> &str {
121        &self.authority
122    }
123
124    /// Requested durable name.
125    #[must_use]
126    pub const fn stable_key(&self) -> &StableKey {
127        &self.key
128    }
129}
130
131///
132/// SealedDeclarationSnapshot
133/// Immutable canonical request set, with duplicate names rejected.
134///
135
136#[derive(Clone, Debug, Eq, PartialEq)]
137pub struct SealedDeclarationSnapshot(Vec<MemoryRequest>);
138
139impl SealedDeclarationSnapshot {
140    /// Seal the complete host-composed requests.
141    pub fn new(mut requests: Vec<MemoryRequest>) -> Result<Self, AdmissionError> {
142        requests.sort_unstable_by(|a, b| a.key.cmp(&b.key));
143        if requests.windows(2).any(|pair| pair[0].key == pair[1].key) {
144            return Err(AdmissionError::Duplicate);
145        }
146
147        Ok(Self(requests))
148    }
149
150    /// Borrow checked requests.
151    #[must_use]
152    pub fn requests(&self) -> &[MemoryRequest] {
153        &self.0
154    }
155}
156
157///
158/// PolicyIdentity
159/// Host-selected token binding the exact configured policy to a runtime.
160///
161
162#[derive(Clone, Copy, Debug, Eq, PartialEq)]
163pub struct PolicyIdentity([u8; 32]);
164
165impl PolicyIdentity {
166    /// Construct a complete policy identity.
167    #[must_use]
168    pub const fn new(bytes: [u8; 32]) -> Self {
169        Self(bytes)
170    }
171}
172
173///
174/// BootstrapAdmission
175/// Read-only recovered entries and explicit current historical admission.
176///
177
178pub struct BootstrapAdmission<'a> {
179    grants: &'a AllocationGrants,
180    recovered: &'a [(StableKey, AllocationId, u64)],
181    selected: Vec<MemoryRequest>,
182    keys: BTreeSet<StableKey>,
183    maximum: usize,
184    failure: Option<AdmissionError>,
185}
186
187impl<'a> BootstrapAdmission<'a> {
188    pub(super) fn new(
189        source: &SealedDeclarationSnapshot,
190        grants: &'a AllocationGrants,
191        recovered: &'a [(StableKey, AllocationId, u64)],
192        maximum: usize,
193    ) -> Result<Self, AdmissionError> {
194        if source.0.len() > maximum {
195            return Err(AdmissionError::Limit);
196        }
197        for request in &source.0 {
198            grants.check(request)?;
199        }
200
201        Ok(Self {
202            grants,
203            recovered,
204            selected: source.0.clone(),
205            keys: source.0.iter().map(|request| request.key.clone()).collect(),
206            maximum,
207            failure: None,
208        })
209    }
210
211    /// Retained names, identities and extents. This grants no memory access.
212    #[must_use]
213    pub const fn recovered_allocations(&self) -> &[(StableKey, AllocationId, u64)] {
214        self.recovered
215    }
216
217    /// Whether this bootstrap has selected a key.
218    #[must_use]
219    pub fn is_declared(&self, key: &StableKey) -> bool {
220        self.keys.contains(key)
221    }
222
223    /// Select a retained name under current grants. An ignored failure still rejects bootstrap.
224    pub fn include_historical(&mut self, authority: &str, key: &str) -> Result<(), AdmissionError> {
225        if let Some(error) = &self.failure {
226            return Err(error.clone());
227        }
228        let result = self.include(authority, key);
229        if let Err(error) = &result {
230            self.failure = Some(error.clone());
231        }
232
233        result
234    }
235
236    fn include(&mut self, authority: &str, key: &str) -> Result<(), AdmissionError> {
237        let request = MemoryRequest::new(authority, key)?;
238        self.grants.check(&request)?;
239        if self.selected.len() >= self.maximum
240            || !self.recovered.iter().any(|(key, _, _)| key == &request.key)
241        {
242            return Err(AdmissionError::Limit);
243        }
244        if !self.keys.insert(request.key.clone()) {
245            return Err(AdmissionError::Duplicate);
246        }
247        self.selected.push(request);
248
249        Ok(())
250    }
251
252    pub(super) fn complete(self) -> Result<Vec<MemoryRequest>, AdmissionError> {
253        if let Some(error) = self.failure {
254            Err(error)
255        } else {
256            Ok(self.selected)
257        }
258    }
259}
260
261/// Host-specific recovered-state and key admission, before durable commitment.
262pub trait RuntimeBootstrapPolicy {
263    /// Policy-specific rejection.
264    type Error;
265    /// Validate one admitted key; numeric placement is owned by Storage.
266    fn validate_allocation(&self, key: &StableKey) -> Result<(), Self::Error>;
267    /// Inspect retained names and optionally select historical keys.
268    fn prepare_bootstrap(
269        &self,
270        _admission: &mut BootstrapAdmission<'_>,
271    ) -> Result<(), Self::Error> {
272        Ok(())
273    }
274
275    /// Bind all effective host policy configuration.
276    fn runtime_bootstrap_identity(&self) -> PolicyIdentity;
277}
278
279///
280/// GenericAllocationPolicy
281/// Standard policy relying on Storage's namespace admission and resource limits.
282///
283
284pub struct GenericAllocationPolicy;
285
286impl RuntimeBootstrapPolicy for GenericAllocationPolicy {
287    type Error = std::convert::Infallible;
288    fn validate_allocation(&self, _key: &StableKey) -> Result<(), Self::Error> {
289        Ok(())
290    }
291
292    fn runtime_bootstrap_identity(&self) -> PolicyIdentity {
293        PolicyIdentity::new(*b"ic-storage.noop-policy..........")
294    }
295}