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