1#![allow(missing_docs)]
20
21use std::fmt;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::Arc;
24
25#[derive(Clone, Copy, PartialEq, Eq, Hash)]
30pub struct CapId(u128);
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum CapIdError {
35 Entropy(crate::entropy::EntropyError),
37 ReservedZero,
39}
40
41impl CapId {
42 pub const NONE: CapId = CapId(0);
44
45 pub fn random() -> Result<Self, CapIdError> {
51 for _ in 0..8 {
52 let mut bytes = [0u8; 16];
53 crate::entropy::fill_bytes(&mut bytes)?;
54 let raw = u128::from_le_bytes(bytes);
55 if raw != 0 {
56 return Ok(CapId(raw));
57 }
58 }
59 Err(CapIdError::ReservedZero)
60 }
61
62 #[inline]
63 pub const fn is_none(self) -> bool {
64 self.0 == 0
65 }
66
67 #[inline]
68 pub const fn as_u128(self) -> u128 {
69 self.0
70 }
71
72 #[inline]
74 pub(crate) const fn from_raw(raw: u128) -> Self {
75 CapId(raw)
76 }
77}
78
79impl fmt::Debug for CapId {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(f, "CapId({:032x})", self.0)
82 }
83}
84
85impl fmt::Display for CapId {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 if self.is_none() {
88 f.write_str("cap#none")
89 } else {
90 write!(f, "cap#{:08x}…", (self.0 >> 96) as u32)
94 }
95 }
96}
97
98impl From<crate::entropy::EntropyError> for CapIdError {
99 fn from(err: crate::entropy::EntropyError) -> Self {
100 CapIdError::Entropy(err)
101 }
102}
103
104impl std::error::Error for CapIdError {
105 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
106 match self {
107 CapIdError::Entropy(err) => Some(err),
108 CapIdError::ReservedZero => None,
109 }
110 }
111}
112
113impl fmt::Display for CapIdError {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self {
116 CapIdError::Entropy(err) => write!(f, "capability CSPRNG unavailable: {err}"),
117 CapIdError::ReservedZero => f.write_str("capability id draw was the reserved zero"),
118 }
119 }
120}
121
122pub type NativeIdx = u32;
124
125#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
131pub struct CapRights(u32);
132
133impl CapRights {
134 pub const NONE: CapRights = CapRights(0);
135 pub const SEND: CapRights = CapRights(1 << 0);
136 pub const ASK: CapRights = CapRights(1 << 1);
137 pub const RECV: CapRights = CapRights(1 << 2);
138 pub const SPAWN: CapRights = CapRights(1 << 3);
139 pub const LINK: CapRights = CapRights(1 << 4);
140 pub const MONITOR: CapRights = CapRights(1 << 5);
141 pub const ADMIN: CapRights = CapRights(1 << 6);
142 pub const NATIVE: CapRights = CapRights(1 << 7);
143
144 pub const ADDRESSING: CapRights =
146 CapRights(Self::SEND.0 | Self::ASK.0 | Self::LINK.0 | Self::MONITOR.0);
147
148 pub const FLOW: CapRights = CapRights(
153 Self::SEND.0
154 | Self::ASK.0
155 | Self::RECV.0
156 | Self::SPAWN.0
157 | Self::LINK.0
158 | Self::MONITOR.0
159 | Self::NATIVE.0,
160 );
161
162 pub const ROOT: CapRights = Self::FLOW;
165
166 pub const SEND_ASK: CapRights = CapRights(Self::SEND.0 | Self::ASK.0);
168
169 #[inline]
170 pub const fn empty() -> Self {
171 CapRights(0)
172 }
173
174 #[inline]
175 pub const fn union(self, other: CapRights) -> CapRights {
176 CapRights(self.0 | other.0)
177 }
178
179 #[inline]
180 pub const fn intersect(self, other: CapRights) -> CapRights {
181 CapRights(self.0 & other.0)
182 }
183
184 #[inline]
185 pub const fn contains(self, other: CapRights) -> bool {
186 self.0 & other.0 == other.0
187 }
188
189 #[inline]
190 pub const fn is_subset_of(self, other: CapRights) -> bool {
191 self.0 & !other.0 == 0
192 }
193
194 #[inline]
195 pub const fn bits(self) -> u32 {
196 self.0
197 }
198
199 #[inline]
201 pub const fn bits_u8(self) -> u8 {
202 self.0 as u8
203 }
204
205 #[inline]
206 pub const fn from_bits(bits: u32) -> Self {
207 CapRights(bits)
208 }
209
210 #[inline]
211 pub const fn from_u8(bits: u8) -> Self {
212 CapRights(bits as u32)
213 }
214}
215
216#[derive(Clone, Debug, PartialEq, Eq)]
220pub struct NativeMask(Arc<[u64]>);
221
222impl NativeMask {
223 pub fn empty(native_count: usize) -> Self {
224 let words = native_count.div_ceil(64);
225 Self(Arc::from(vec![0u64; words].into_boxed_slice()))
226 }
227
228 pub fn full(native_count: usize) -> Self {
229 let words = native_count.div_ceil(64);
230 let mut v = vec![u64::MAX; words];
231 let rem = native_count % 64;
234 if rem != 0 {
235 if let Some(last) = v.last_mut() {
236 *last &= (1u64 << rem) - 1;
237 }
238 }
239 Self(Arc::from(v.into_boxed_slice()))
240 }
241
242 pub fn from_indices(native_count: usize, idxs: &[NativeIdx]) -> Self {
243 let words = native_count.div_ceil(64);
244 let mut v = vec![0u64; words];
245 for &i in idxs {
246 let (w, b) = (i as usize / 64, i as usize % 64);
247 if w < v.len() && (i as usize) < native_count {
248 v[w] |= 1u64 << b;
249 }
250 }
251 Self(Arc::from(v.into_boxed_slice()))
252 }
253
254 pub fn word_len(&self) -> usize {
255 self.0.len()
256 }
257
258 #[inline]
259 pub fn allows(&self, idx: NativeIdx) -> bool {
260 let (w, b) = (idx as usize / 64, idx as usize % 64);
261 match self.0.get(w) {
262 Some(word) => word & (1u64 << b) != 0,
263 None => false,
264 }
265 }
266
267 pub fn intersect(&self, requested: &NativeMask) -> NativeMask {
270 let n = self.0.len().min(requested.0.len());
271 let words: Vec<u64> = self
272 .0
273 .iter()
274 .zip(requested.0.iter())
275 .take(n)
276 .map(|(a, b)| a & b)
277 .collect();
278 NativeMask(Arc::from(words.into_boxed_slice()))
281 }
282
283 pub fn is_subset_of(&self, other: &NativeMask) -> bool {
285 let n = self.0.len().max(other.0.len());
286 (0..n).all(|idx| {
287 let a = match self.0.get(idx) {
288 Some(w) => *w,
289 None => 0,
290 };
291 let b = match other.0.get(idx) {
292 Some(w) => *w,
293 None => 0,
294 };
295 a & !b == 0
296 })
297 }
298}
299
300#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
303pub enum CapTarget {
304 Flow(u64),
306 NativeTable,
309 Scheduler,
311 Table(u64),
313}
314
315impl CapTarget {
316 pub fn flow_id(self) -> Option<u64> {
317 match self {
318 CapTarget::Flow(id) => Some(id),
319 CapTarget::NativeTable | CapTarget::Scheduler | CapTarget::Table(_) => None,
320 }
321 }
322}
323
324#[derive(Clone, Debug, PartialEq, Eq)]
329pub struct Cap {
330 target: CapTarget,
331 rights: CapRights,
332 native_mask: Option<NativeMask>,
334 epoch: u64,
337}
338
339#[derive(Debug)]
342pub struct RevocationCell(AtomicU64);
343
344impl RevocationCell {
345 pub fn new() -> Self {
346 Self(AtomicU64::new(0))
347 }
348
349 pub fn epoch(&self) -> u64 {
350 self.0.load(Ordering::Acquire)
351 }
352
353 pub fn revoke(&self) {
354 self.0.fetch_add(1, Ordering::AcqRel);
355 }
356}
357
358impl Default for RevocationCell {
359 fn default() -> Self {
360 Self::new()
361 }
362}
363
364impl Cap {
365 pub fn root(
367 target: CapTarget,
368 rights: CapRights,
369 native_mask: Option<NativeMask>,
370 cell: &RevocationCell,
371 ) -> Self {
372 Self {
373 target,
374 rights,
375 native_mask,
376 epoch: cell.epoch(),
377 }
378 }
379
380 #[inline]
381 pub fn target(&self) -> CapTarget {
382 self.target
383 }
384
385 #[inline]
386 pub fn rights(&self) -> CapRights {
387 self.rights
388 }
389
390 #[inline]
391 pub fn native_mask(&self) -> Option<&NativeMask> {
392 self.native_mask.as_ref()
393 }
394
395 pub fn epoch(&self) -> u64 {
396 self.epoch
397 }
398
399 pub fn is_valid(&self, cell: &RevocationCell) -> bool {
400 self.epoch == cell.epoch()
401 }
402
403 pub fn attenuate(&self, want_rights: CapRights, want_native: Option<&NativeMask>) -> Cap {
417 let rights = self.rights.intersect(want_rights);
418 let native_mask = match (&self.native_mask, want_native) {
419 (Some(cur), Some(req)) => Some(cur.intersect(req)),
420 (Some(cur), None) => Some(cur.clone()),
421 (None, _) => None,
422 };
423 Cap {
424 target: self.target,
425 rights,
426 native_mask,
427 epoch: self.epoch,
428 }
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435
436 #[test]
437 fn none_is_zero_and_random_is_not() -> Result<(), CapIdError> {
438 assert!(CapId::NONE.is_none());
439 let a = CapId::random()?;
440 let b = CapId::random()?;
441 assert!(!a.is_none());
442 assert!(!b.is_none());
443 assert_ne!(a, b);
444 Ok(())
445 }
446
447 #[test]
448 fn from_raw_is_crate_internal() {
449 assert_eq!(CapId::from_raw(0), CapId::NONE);
450 assert!(!CapId::from_raw(1).is_none());
451 }
452
453 #[test]
454 fn display_shows_a_prefix_and_debug_keeps_the_token() {
455 let id = CapId::from_raw(0x0123_4567_89ab_cdef_0011_2233_4455_6677);
456 let shown = id.to_string();
457 assert_eq!(shown, "cap#01234567…");
458 assert!(!shown.contains("89abcdef"));
459 let debug = format!("{id:?}");
460 assert!(debug.contains("0123456789abcdef0011223344556677"));
461 assert_eq!(CapId::NONE.to_string(), "cap#none");
462 }
463
464 #[test]
465 fn send_ask_bits_stay_compatible() {
466 assert_eq!(CapRights::SEND.bits(), 0b01);
467 assert_eq!(CapRights::ASK.bits(), 0b10);
468 assert_eq!(CapRights::SEND_ASK.bits(), 0b11);
469 assert!(CapRights::ADMIN.bits() > 0b11);
470 }
471
472 #[test]
473 fn attenuation_never_escalates() {
474 let cell = RevocationCell::new();
475 let nm = NativeMask::from_indices(128, &[3, 5, 9]);
476 let parent = Cap::root(
477 CapTarget::Flow(1),
478 CapRights::SEND.union(CapRights::NATIVE),
479 Some(nm),
480 &cell,
481 );
482
483 let child = parent.attenuate(CapRights::SEND.union(CapRights::ADMIN), None);
484 assert!(!child.rights().contains(CapRights::ADMIN));
485 assert!(child.rights().contains(CapRights::SEND));
486
487 let wide = NativeMask::full(128);
488 let child2 = parent.attenuate(CapRights::NATIVE, Some(&wide));
489 let child_mask = child2.native_mask();
490 assert!(child_mask.is_some_and(|m| m.allows(3)));
491 let parent_mask = parent.native_mask();
492 assert!(parent_mask.is_some_and(|m| !m.allows(7)));
493 }
494
495 #[test]
496 fn attenuation_is_subset_for_all_byte_masks() {
497 let cell = RevocationCell::new();
498 for src in 0u32..=255 {
499 for want in 0u32..=255 {
500 let parent = Cap::root(CapTarget::Flow(1), CapRights::from_bits(src), None, &cell);
501 let child = parent.attenuate(CapRights::from_bits(want), None);
502 assert!(
503 child.rights().is_subset_of(parent.rights()),
504 "escalation src={src:#x} want={want:#x} got={:#x}",
505 child.rights().bits()
506 );
507 assert_eq!(child.rights().bits(), src & want);
508 }
509 }
510 }
511
512 #[test]
513 fn chained_delegate_never_gains_bits() {
514 let cell = RevocationCell::new();
515 let mut cap = Cap::root(
516 CapTarget::Flow(1),
517 CapRights::FLOW,
518 Some(NativeMask::from_indices(32, &[0, 1, 2])),
519 &cell,
520 );
521 let adversarial = [
522 CapRights::ADMIN,
523 CapRights::NATIVE.union(CapRights::ADMIN),
524 CapRights::from_bits(u32::MAX),
525 CapRights::NONE,
526 CapRights::FLOW,
527 ];
528 for want in adversarial {
529 cap = cap.attenuate(want, Some(&NativeMask::full(32)));
530 assert!(cap.rights().is_subset_of(CapRights::FLOW));
531 assert!(!cap.rights().contains(CapRights::ADMIN));
532 if let Some(mask) = cap.native_mask() {
533 assert!(!mask.allows(7));
534 }
535 }
536 }
537
538 #[test]
539 fn revocation_kills_all_derived_caps() {
540 let cell = RevocationCell::new();
541 let root = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
542 let child = root.attenuate(CapRights::SEND, None);
543 assert!(child.is_valid(&cell));
544 cell.revoke();
545 assert!(!child.is_valid(&cell));
546 assert!(!root.is_valid(&cell));
547 }
548}