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#{:032x}", self.0)
87 }
88 }
89}
90
91impl From<crate::entropy::EntropyError> for CapIdError {
92 fn from(err: crate::entropy::EntropyError) -> Self {
93 CapIdError::Entropy(err)
94 }
95}
96
97impl std::error::Error for CapIdError {
98 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
99 match self {
100 CapIdError::Entropy(err) => Some(err),
101 CapIdError::ReservedZero => None,
102 }
103 }
104}
105
106impl fmt::Display for CapIdError {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 match self {
109 CapIdError::Entropy(err) => write!(f, "capability CSPRNG unavailable: {err}"),
110 CapIdError::ReservedZero => f.write_str("capability id draw was the reserved zero"),
111 }
112 }
113}
114
115pub type NativeIdx = u32;
117
118#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
124pub struct CapRights(u32);
125
126impl CapRights {
127 pub const NONE: CapRights = CapRights(0);
128 pub const SEND: CapRights = CapRights(1 << 0);
129 pub const ASK: CapRights = CapRights(1 << 1);
130 pub const RECV: CapRights = CapRights(1 << 2);
131 pub const SPAWN: CapRights = CapRights(1 << 3);
132 pub const LINK: CapRights = CapRights(1 << 4);
133 pub const MONITOR: CapRights = CapRights(1 << 5);
134 pub const ADMIN: CapRights = CapRights(1 << 6);
135 pub const NATIVE: CapRights = CapRights(1 << 7);
136
137 pub const ADDRESSING: CapRights =
139 CapRights(Self::SEND.0 | Self::ASK.0 | Self::LINK.0 | Self::MONITOR.0);
140
141 pub const FLOW: CapRights = CapRights(
146 Self::SEND.0
147 | Self::ASK.0
148 | Self::RECV.0
149 | Self::SPAWN.0
150 | Self::LINK.0
151 | Self::MONITOR.0
152 | Self::NATIVE.0,
153 );
154
155 pub const ROOT: CapRights = Self::FLOW;
158
159 pub const SEND_ASK: CapRights = CapRights(Self::SEND.0 | Self::ASK.0);
161
162 #[inline]
163 pub const fn empty() -> Self {
164 CapRights(0)
165 }
166
167 #[inline]
168 pub const fn union(self, other: CapRights) -> CapRights {
169 CapRights(self.0 | other.0)
170 }
171
172 #[inline]
173 pub const fn intersect(self, other: CapRights) -> CapRights {
174 CapRights(self.0 & other.0)
175 }
176
177 #[inline]
178 pub const fn contains(self, other: CapRights) -> bool {
179 self.0 & other.0 == other.0
180 }
181
182 #[inline]
183 pub const fn is_subset_of(self, other: CapRights) -> bool {
184 self.0 & !other.0 == 0
185 }
186
187 #[inline]
188 pub const fn bits(self) -> u32 {
189 self.0
190 }
191
192 #[inline]
194 pub const fn bits_u8(self) -> u8 {
195 self.0 as u8
196 }
197
198 #[inline]
199 pub const fn from_bits(bits: u32) -> Self {
200 CapRights(bits)
201 }
202
203 #[inline]
204 pub const fn from_u8(bits: u8) -> Self {
205 CapRights(bits as u32)
206 }
207}
208
209#[derive(Clone, Debug, PartialEq, Eq)]
213pub struct NativeMask(Arc<[u64]>);
214
215impl NativeMask {
216 pub fn empty(native_count: usize) -> Self {
217 let words = native_count.div_ceil(64);
218 Self(Arc::from(vec![0u64; words].into_boxed_slice()))
219 }
220
221 pub fn full(native_count: usize) -> Self {
222 let words = native_count.div_ceil(64);
223 let mut v = vec![u64::MAX; words];
224 let rem = native_count % 64;
227 if rem != 0 {
228 if let Some(last) = v.last_mut() {
229 *last &= (1u64 << rem) - 1;
230 }
231 }
232 Self(Arc::from(v.into_boxed_slice()))
233 }
234
235 pub fn from_indices(native_count: usize, idxs: &[NativeIdx]) -> Self {
236 let words = native_count.div_ceil(64);
237 let mut v = vec![0u64; words];
238 for &i in idxs {
239 let (w, b) = (i as usize / 64, i as usize % 64);
240 if w < v.len() && (i as usize) < native_count {
241 v[w] |= 1u64 << b;
242 }
243 }
244 Self(Arc::from(v.into_boxed_slice()))
245 }
246
247 pub fn word_len(&self) -> usize {
248 self.0.len()
249 }
250
251 #[inline]
252 pub fn allows(&self, idx: NativeIdx) -> bool {
253 let (w, b) = (idx as usize / 64, idx as usize % 64);
254 match self.0.get(w) {
255 Some(word) => word & (1u64 << b) != 0,
256 None => false,
257 }
258 }
259
260 pub fn intersect(&self, requested: &NativeMask) -> NativeMask {
263 let n = self.0.len().min(requested.0.len());
264 let words: Vec<u64> = self
265 .0
266 .iter()
267 .zip(requested.0.iter())
268 .take(n)
269 .map(|(a, b)| a & b)
270 .collect();
271 NativeMask(Arc::from(words.into_boxed_slice()))
274 }
275
276 pub fn is_subset_of(&self, other: &NativeMask) -> bool {
278 let n = self.0.len().max(other.0.len());
279 (0..n).all(|idx| {
280 let a = match self.0.get(idx) {
281 Some(w) => *w,
282 None => 0,
283 };
284 let b = match other.0.get(idx) {
285 Some(w) => *w,
286 None => 0,
287 };
288 a & !b == 0
289 })
290 }
291}
292
293#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
296pub enum CapTarget {
297 Flow(u64),
299 NativeTable,
302 Scheduler,
304}
305
306impl CapTarget {
307 pub fn flow_id(self) -> Option<u64> {
308 match self {
309 CapTarget::Flow(id) => Some(id),
310 CapTarget::NativeTable | CapTarget::Scheduler => None,
311 }
312 }
313}
314
315#[derive(Clone, Debug, PartialEq, Eq)]
320pub struct Cap {
321 target: CapTarget,
322 rights: CapRights,
323 native_mask: Option<NativeMask>,
325 epoch: u64,
328}
329
330#[derive(Debug)]
333pub struct RevocationCell(AtomicU64);
334
335impl RevocationCell {
336 pub fn new() -> Self {
337 Self(AtomicU64::new(0))
338 }
339
340 pub fn epoch(&self) -> u64 {
341 self.0.load(Ordering::Acquire)
342 }
343
344 pub fn revoke(&self) {
345 self.0.fetch_add(1, Ordering::AcqRel);
346 }
347}
348
349impl Default for RevocationCell {
350 fn default() -> Self {
351 Self::new()
352 }
353}
354
355impl Cap {
356 pub fn root(
358 target: CapTarget,
359 rights: CapRights,
360 native_mask: Option<NativeMask>,
361 cell: &RevocationCell,
362 ) -> Self {
363 Self {
364 target,
365 rights,
366 native_mask,
367 epoch: cell.epoch(),
368 }
369 }
370
371 #[inline]
372 pub fn target(&self) -> CapTarget {
373 self.target
374 }
375
376 #[inline]
377 pub fn rights(&self) -> CapRights {
378 self.rights
379 }
380
381 #[inline]
382 pub fn native_mask(&self) -> Option<&NativeMask> {
383 self.native_mask.as_ref()
384 }
385
386 pub fn epoch(&self) -> u64 {
387 self.epoch
388 }
389
390 pub fn is_valid(&self, cell: &RevocationCell) -> bool {
391 self.epoch == cell.epoch()
392 }
393
394 pub fn attenuate(&self, want_rights: CapRights, want_native: Option<&NativeMask>) -> Cap {
408 let rights = self.rights.intersect(want_rights);
409 let native_mask = match (&self.native_mask, want_native) {
410 (Some(cur), Some(req)) => Some(cur.intersect(req)),
411 (Some(cur), None) => Some(cur.clone()),
412 (None, _) => None,
413 };
414 Cap {
415 target: self.target,
416 rights,
417 native_mask,
418 epoch: self.epoch,
419 }
420 }
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 #[test]
428 fn none_is_zero_and_random_is_not() -> Result<(), CapIdError> {
429 assert!(CapId::NONE.is_none());
430 let a = CapId::random()?;
431 let b = CapId::random()?;
432 assert!(!a.is_none());
433 assert!(!b.is_none());
434 assert_ne!(a, b);
435 Ok(())
436 }
437
438 #[test]
439 fn from_raw_is_crate_internal() {
440 assert_eq!(CapId::from_raw(0), CapId::NONE);
441 assert!(!CapId::from_raw(1).is_none());
442 }
443
444 #[test]
445 fn send_ask_bits_stay_compatible() {
446 assert_eq!(CapRights::SEND.bits(), 0b01);
447 assert_eq!(CapRights::ASK.bits(), 0b10);
448 assert_eq!(CapRights::SEND_ASK.bits(), 0b11);
449 assert!(CapRights::ADMIN.bits() > 0b11);
450 }
451
452 #[test]
453 fn attenuation_never_escalates() {
454 let cell = RevocationCell::new();
455 let nm = NativeMask::from_indices(128, &[3, 5, 9]);
456 let parent = Cap::root(
457 CapTarget::Flow(1),
458 CapRights::SEND.union(CapRights::NATIVE),
459 Some(nm),
460 &cell,
461 );
462
463 let child = parent.attenuate(CapRights::SEND.union(CapRights::ADMIN), None);
464 assert!(!child.rights().contains(CapRights::ADMIN));
465 assert!(child.rights().contains(CapRights::SEND));
466
467 let wide = NativeMask::full(128);
468 let child2 = parent.attenuate(CapRights::NATIVE, Some(&wide));
469 let child_mask = child2.native_mask();
470 assert!(child_mask.is_some_and(|m| m.allows(3)));
471 let parent_mask = parent.native_mask();
472 assert!(parent_mask.is_some_and(|m| !m.allows(7)));
473 }
474
475 #[test]
476 fn attenuation_is_subset_for_all_byte_masks() {
477 let cell = RevocationCell::new();
478 for src in 0u32..=255 {
479 for want in 0u32..=255 {
480 let parent = Cap::root(CapTarget::Flow(1), CapRights::from_bits(src), None, &cell);
481 let child = parent.attenuate(CapRights::from_bits(want), None);
482 assert!(
483 child.rights().is_subset_of(parent.rights()),
484 "escalation src={src:#x} want={want:#x} got={:#x}",
485 child.rights().bits()
486 );
487 assert_eq!(child.rights().bits(), src & want);
488 }
489 }
490 }
491
492 #[test]
493 fn chained_delegate_never_gains_bits() {
494 let cell = RevocationCell::new();
495 let mut cap = Cap::root(
496 CapTarget::Flow(1),
497 CapRights::FLOW,
498 Some(NativeMask::from_indices(32, &[0, 1, 2])),
499 &cell,
500 );
501 let adversarial = [
502 CapRights::ADMIN,
503 CapRights::NATIVE.union(CapRights::ADMIN),
504 CapRights::from_bits(u32::MAX),
505 CapRights::NONE,
506 CapRights::FLOW,
507 ];
508 for want in adversarial {
509 cap = cap.attenuate(want, Some(&NativeMask::full(32)));
510 assert!(cap.rights().is_subset_of(CapRights::FLOW));
511 assert!(!cap.rights().contains(CapRights::ADMIN));
512 if let Some(mask) = cap.native_mask() {
513 assert!(!mask.allows(7));
514 }
515 }
516 }
517
518 #[test]
519 fn revocation_kills_all_derived_caps() {
520 let cell = RevocationCell::new();
521 let root = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
522 let child = root.attenuate(CapRights::SEND, None);
523 assert!(child.is_valid(&cell));
524 cell.revoke();
525 assert!(!child.is_valid(&cell));
526 assert!(!root.is_valid(&cell));
527 }
528}