1use crate::{AllocationId, StableKey};
3use std::collections::BTreeSet;
4
5#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
7pub enum AdmissionError {
8 #[error("invalid authority or namespace")]
10 Invalid,
11 #[error(transparent)]
13 Key(#[from] crate::StableKeyError),
14 #[error("duplicate key or overlapping namespace")]
16 Duplicate,
17 #[error("namespace is not granted to this authority")]
19 Unauthorized,
20 #[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#[derive(Clone, Debug, Eq, PartialEq)]
39pub struct MemoryAuthority {
40 authority: String,
41 prefix: String,
42}
43
44impl MemoryAuthority {
45 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#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct AllocationGrants(Vec<MemoryAuthority>);
67
68impl AllocationGrants {
69 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#[derive(Clone, Debug, Eq, PartialEq)]
99pub struct MemoryRequest {
100 authority: String,
101 key: StableKey,
102}
103
104impl MemoryRequest {
105 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 #[must_use]
120 pub fn authority(&self) -> &str {
121 &self.authority
122 }
123
124 #[must_use]
126 pub const fn stable_key(&self) -> &StableKey {
127 &self.key
128 }
129}
130
131#[derive(Clone, Debug, Eq, PartialEq)]
137pub struct SealedDeclarationSnapshot(Vec<MemoryRequest>);
138
139impl SealedDeclarationSnapshot {
140 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 #[must_use]
152 pub fn requests(&self) -> &[MemoryRequest] {
153 &self.0
154 }
155}
156
157#[derive(Clone, Copy, Debug, Eq, PartialEq)]
163pub struct PolicyIdentity([u8; 32]);
164
165impl PolicyIdentity {
166 #[must_use]
168 pub const fn new(bytes: [u8; 32]) -> Self {
169 Self(bytes)
170 }
171}
172
173pub 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 #[must_use]
213 pub const fn recovered_allocations(&self) -> &[(StableKey, AllocationId, u64)] {
214 self.recovered
215 }
216
217 #[must_use]
219 pub fn is_declared(&self, key: &StableKey) -> bool {
220 self.keys.contains(key)
221 }
222
223 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
261pub trait RuntimeBootstrapPolicy {
263 type Error;
265 fn validate_allocation(&self, key: &StableKey) -> Result<(), Self::Error>;
267 fn prepare_bootstrap(
269 &self,
270 _admission: &mut BootstrapAdmission<'_>,
271 ) -> Result<(), Self::Error> {
272 Ok(())
273 }
274
275 fn runtime_bootstrap_identity(&self) -> PolicyIdentity;
277}
278
279pub 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}