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