1use std::fmt;
18use std::sync::atomic::{AtomicU64, Ordering};
19use std::sync::Arc;
20
21#[derive(Clone, Copy, PartialEq, Eq, Hash)]
26pub struct CapId(u128);
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum CapIdError {
31 Entropy,
33}
34
35impl CapId {
36 pub const NONE: CapId = CapId(0);
38
39 pub fn random() -> Result<Self, CapIdError> {
41 for _ in 0..8 {
42 let mut bytes = [0u8; 16];
43 if crate::entropy::fill_bytes(&mut bytes).is_err() {
44 return Err(CapIdError::Entropy);
45 }
46 let raw = u128::from_le_bytes(bytes);
47 if raw != 0 {
48 return Ok(CapId(raw));
49 }
50 }
51 Err(CapIdError::Entropy)
52 }
53
54 #[inline]
55 pub const fn is_none(self) -> bool {
56 self.0 == 0
57 }
58
59 #[inline]
60 pub const fn as_u128(self) -> u128 {
61 self.0
62 }
63
64 #[inline]
66 pub(crate) const fn from_raw(raw: u128) -> Self {
67 CapId(raw)
68 }
69}
70
71impl fmt::Debug for CapId {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "CapId({:032x})", self.0)
74 }
75}
76
77impl fmt::Display for CapId {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 if self.is_none() {
80 f.write_str("cap#none")
81 } else {
82 write!(f, "cap#{:032x}", self.0)
83 }
84 }
85}
86
87impl std::error::Error for CapIdError {}
88
89impl fmt::Display for CapIdError {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 match self {
92 CapIdError::Entropy => f.write_str("capability CSPRNG unavailable"),
93 }
94 }
95}
96
97pub type NativeIdx = u32;
99
100#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
106pub struct CapRights(u32);
107
108impl CapRights {
109 pub const NONE: CapRights = CapRights(0);
110 pub const SEND: CapRights = CapRights(1 << 0);
111 pub const ASK: CapRights = CapRights(1 << 1);
112 pub const RECV: CapRights = CapRights(1 << 2);
113 pub const SPAWN: CapRights = CapRights(1 << 3);
114 pub const LINK: CapRights = CapRights(1 << 4);
115 pub const MONITOR: CapRights = CapRights(1 << 5);
116 pub const ADMIN: CapRights = CapRights(1 << 6);
117 pub const NATIVE: CapRights = CapRights(1 << 7);
118
119 pub const ADDRESSING: CapRights =
121 CapRights(Self::SEND.0 | Self::ASK.0 | Self::LINK.0 | Self::MONITOR.0);
122
123 pub const FLOW: CapRights = CapRights(
128 Self::SEND.0
129 | Self::ASK.0
130 | Self::RECV.0
131 | Self::SPAWN.0
132 | Self::LINK.0
133 | Self::MONITOR.0
134 | Self::NATIVE.0,
135 );
136
137 pub const ROOT: CapRights = Self::FLOW;
140
141 pub const SEND_ASK: CapRights = CapRights(Self::SEND.0 | Self::ASK.0);
143
144 #[inline]
145 pub const fn empty() -> Self {
146 CapRights(0)
147 }
148
149 #[inline]
150 pub const fn union(self, other: CapRights) -> CapRights {
151 CapRights(self.0 | other.0)
152 }
153
154 #[inline]
155 pub const fn intersect(self, other: CapRights) -> CapRights {
156 CapRights(self.0 & other.0)
157 }
158
159 #[inline]
160 pub const fn contains(self, other: CapRights) -> bool {
161 self.0 & other.0 == other.0
162 }
163
164 #[inline]
165 pub const fn is_subset_of(self, other: CapRights) -> bool {
166 self.0 & !other.0 == 0
167 }
168
169 #[inline]
170 pub const fn bits(self) -> u32 {
171 self.0
172 }
173
174 #[inline]
176 pub const fn bits_u8(self) -> u8 {
177 self.0 as u8
178 }
179
180 #[inline]
181 pub const fn from_bits(bits: u32) -> Self {
182 CapRights(bits)
183 }
184
185 #[inline]
186 pub const fn from_u8(bits: u8) -> Self {
187 CapRights(bits as u32)
188 }
189}
190
191#[derive(Clone, Debug, PartialEq, Eq)]
195pub struct NativeMask(Arc<[u64]>);
196
197impl NativeMask {
198 pub fn empty(native_count: usize) -> Self {
199 let words = native_count.div_ceil(64);
200 Self(Arc::from(vec![0u64; words].into_boxed_slice()))
201 }
202
203 pub fn full(native_count: usize) -> Self {
204 let words = native_count.div_ceil(64);
205 let mut v = vec![u64::MAX; words];
206 let rem = native_count % 64;
209 if rem != 0 {
210 if let Some(last) = v.last_mut() {
211 *last &= (1u64 << rem) - 1;
212 }
213 }
214 Self(Arc::from(v.into_boxed_slice()))
215 }
216
217 pub fn from_indices(native_count: usize, idxs: &[NativeIdx]) -> Self {
218 let words = native_count.div_ceil(64);
219 let mut v = vec![0u64; words];
220 for &i in idxs {
221 let (w, b) = (i as usize / 64, i as usize % 64);
222 if w < v.len() && (i as usize) < native_count {
223 v[w] |= 1u64 << b;
224 }
225 }
226 Self(Arc::from(v.into_boxed_slice()))
227 }
228
229 pub fn word_len(&self) -> usize {
230 self.0.len()
231 }
232
233 #[inline]
234 pub fn allows(&self, idx: NativeIdx) -> bool {
235 let (w, b) = (idx as usize / 64, idx as usize % 64);
236 match self.0.get(w) {
237 Some(word) => word & (1u64 << b) != 0,
238 None => false,
239 }
240 }
241
242 pub fn intersect(&self, requested: &NativeMask) -> NativeMask {
245 let n = self.0.len().min(requested.0.len());
246 let words: Vec<u64> = self
247 .0
248 .iter()
249 .zip(requested.0.iter())
250 .take(n)
251 .map(|(a, b)| a & b)
252 .collect();
253 NativeMask(Arc::from(words.into_boxed_slice()))
256 }
257
258 pub fn is_subset_of(&self, other: &NativeMask) -> bool {
260 let n = self.0.len().max(other.0.len());
261 (0..n).all(|idx| {
262 let a = match self.0.get(idx) {
263 Some(w) => *w,
264 None => 0,
265 };
266 let b = match other.0.get(idx) {
267 Some(w) => *w,
268 None => 0,
269 };
270 a & !b == 0
271 })
272 }
273}
274
275#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
278pub enum CapTarget {
279 Flow(u64),
281 NativeTable,
284 Scheduler,
286}
287
288impl CapTarget {
289 pub fn flow_id(self) -> Option<u64> {
290 match self {
291 CapTarget::Flow(id) => Some(id),
292 CapTarget::NativeTable | CapTarget::Scheduler => None,
293 }
294 }
295}
296
297#[derive(Clone, Debug, PartialEq, Eq)]
299pub struct Cap {
300 pub target: CapTarget,
301 pub rights: CapRights,
302 pub native_mask: Option<NativeMask>,
304 epoch: u64,
307}
308
309#[derive(Debug)]
312pub struct RevocationCell(AtomicU64);
313
314impl RevocationCell {
315 pub fn new() -> Self {
316 Self(AtomicU64::new(0))
317 }
318
319 pub fn epoch(&self) -> u64 {
320 self.0.load(Ordering::Acquire)
321 }
322
323 pub fn revoke(&self) {
324 self.0.fetch_add(1, Ordering::AcqRel);
325 }
326}
327
328impl Default for RevocationCell {
329 fn default() -> Self {
330 Self::new()
331 }
332}
333
334impl Cap {
335 pub fn root(
337 target: CapTarget,
338 rights: CapRights,
339 native_mask: Option<NativeMask>,
340 cell: &RevocationCell,
341 ) -> Self {
342 Self {
343 target,
344 rights,
345 native_mask,
346 epoch: cell.epoch(),
347 }
348 }
349
350 pub fn epoch(&self) -> u64 {
351 self.epoch
352 }
353
354 pub fn is_valid(&self, cell: &RevocationCell) -> bool {
355 self.epoch == cell.epoch()
356 }
357
358 pub fn attenuate(&self, want_rights: CapRights, want_native: Option<&NativeMask>) -> Cap {
372 let rights = self.rights.intersect(want_rights);
373 let native_mask = match (&self.native_mask, want_native) {
374 (Some(cur), Some(req)) => Some(cur.intersect(req)),
375 (Some(cur), None) => Some(cur.clone()),
376 (None, _) => None,
377 };
378 Cap {
379 target: self.target,
380 rights,
381 native_mask,
382 epoch: self.epoch,
383 }
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 #[test]
392 fn none_is_zero_and_random_is_not() -> Result<(), CapIdError> {
393 assert!(CapId::NONE.is_none());
394 let a = CapId::random()?;
395 let b = CapId::random()?;
396 assert!(!a.is_none());
397 assert!(!b.is_none());
398 assert_ne!(a, b);
399 Ok(())
400 }
401
402 #[test]
403 fn from_raw_is_crate_internal() {
404 assert_eq!(CapId::from_raw(0), CapId::NONE);
405 assert!(!CapId::from_raw(1).is_none());
406 }
407
408 #[test]
409 fn send_ask_bits_stay_compatible() {
410 assert_eq!(CapRights::SEND.bits(), 0b01);
411 assert_eq!(CapRights::ASK.bits(), 0b10);
412 assert_eq!(CapRights::SEND_ASK.bits(), 0b11);
413 assert!(CapRights::ADMIN.bits() > 0b11);
414 }
415
416 #[test]
417 fn attenuation_never_escalates() {
418 let cell = RevocationCell::new();
419 let nm = NativeMask::from_indices(128, &[3, 5, 9]);
420 let parent = Cap::root(
421 CapTarget::Flow(1),
422 CapRights::SEND.union(CapRights::NATIVE),
423 Some(nm),
424 &cell,
425 );
426
427 let child = parent.attenuate(CapRights::SEND.union(CapRights::ADMIN), None);
428 assert!(!child.rights.contains(CapRights::ADMIN));
429 assert!(child.rights.contains(CapRights::SEND));
430
431 let wide = NativeMask::full(128);
432 let child2 = parent.attenuate(CapRights::NATIVE, Some(&wide));
433 let child_mask = child2.native_mask.as_ref();
434 assert!(child_mask.is_some_and(|m| m.allows(3)));
435 let parent_mask = parent.native_mask.as_ref();
436 assert!(parent_mask.is_some_and(|m| !m.allows(7)));
437 }
438
439 #[test]
440 fn attenuation_is_subset_for_all_byte_masks() {
441 let cell = RevocationCell::new();
442 for src in 0u32..=255 {
443 for want in 0u32..=255 {
444 let parent = Cap::root(CapTarget::Flow(1), CapRights::from_bits(src), None, &cell);
445 let child = parent.attenuate(CapRights::from_bits(want), None);
446 assert!(
447 child.rights.is_subset_of(parent.rights),
448 "escalation src={src:#x} want={want:#x} got={:#x}",
449 child.rights.bits()
450 );
451 assert_eq!(child.rights.bits(), src & want);
452 }
453 }
454 }
455
456 #[test]
457 fn chained_delegate_never_gains_bits() {
458 let cell = RevocationCell::new();
459 let mut cap = Cap::root(
460 CapTarget::Flow(1),
461 CapRights::FLOW,
462 Some(NativeMask::from_indices(32, &[0, 1, 2])),
463 &cell,
464 );
465 let adversarial = [
466 CapRights::ADMIN,
467 CapRights::NATIVE.union(CapRights::ADMIN),
468 CapRights::from_bits(u32::MAX),
469 CapRights::NONE,
470 CapRights::FLOW,
471 ];
472 for want in adversarial {
473 cap = cap.attenuate(want, Some(&NativeMask::full(32)));
474 assert!(cap.rights.is_subset_of(CapRights::FLOW));
475 assert!(!cap.rights.contains(CapRights::ADMIN));
476 if let Some(mask) = &cap.native_mask {
477 assert!(!mask.allows(7));
478 }
479 }
480 }
481
482 #[test]
483 fn revocation_kills_all_derived_caps() {
484 let cell = RevocationCell::new();
485 let root = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
486 let child = root.attenuate(CapRights::SEND, None);
487 assert!(child.is_valid(&cell));
488 cell.revoke();
489 assert!(!child.is_valid(&cell));
490 assert!(!root.is_valid(&cell));
491 }
492}