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)]
35pub struct MemoryAuthority {
36 authority: String,
37 prefix: String,
38}
39
40impl MemoryAuthority {
41 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#[derive(Clone, Debug, Eq, PartialEq)]
57pub struct AllocationGrants(Vec<MemoryAuthority>);
58impl AllocationGrants {
59 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#[derive(Clone, Debug, Eq, PartialEq)]
84pub struct MemoryRequest {
85 authority: String,
86 key: StableKey,
87}
88
89impl MemoryRequest {
90 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 #[must_use]
104 pub fn authority(&self) -> &str {
105 &self.authority
106 }
107
108 #[must_use]
110 pub const fn stable_key(&self) -> &StableKey {
111 &self.key
112 }
113}
114
115#[derive(Clone, Debug, Eq, PartialEq)]
117pub struct SealedDeclarationSnapshot(Vec<MemoryRequest>);
118impl SealedDeclarationSnapshot {
119 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 #[must_use]
130 pub fn requests(&self) -> &[MemoryRequest] {
131 &self.0
132 }
133}
134
135#[derive(Clone, Copy, Debug, Eq, PartialEq)]
137pub struct PolicyIdentity([u8; 32]);
138impl PolicyIdentity {
139 #[must_use]
141 pub const fn new(bytes: [u8; 32]) -> Self {
142 Self(bytes)
143 }
144}
145
146pub 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 #[must_use]
181 pub const fn recovered_allocations(&self) -> &[(StableKey, AllocationId, u64)] {
182 self.recovered
183 }
184
185 #[must_use]
187 pub fn is_declared(&self, key: &StableKey) -> bool {
188 self.keys.contains(key)
189 }
190
191 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
227pub trait RuntimeBootstrapPolicy {
229 type Error;
231 fn validate_allocation(&self, key: &StableKey) -> Result<(), Self::Error>;
233 fn prepare_bootstrap(
235 &self,
236 _admission: &mut BootstrapAdmission<'_>,
237 ) -> Result<(), Self::Error> {
238 Ok(())
239 }
240
241 fn runtime_bootstrap_identity(&self) -> PolicyIdentity;
243}
244
245pub 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}