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)]
317pub struct Cap {
318 pub target: CapTarget,
319 pub rights: CapRights,
320 pub native_mask: Option<NativeMask>,
322 epoch: u64,
325}
326
327#[derive(Debug)]
330pub struct RevocationCell(AtomicU64);
331
332impl RevocationCell {
333 pub fn new() -> Self {
334 Self(AtomicU64::new(0))
335 }
336
337 pub fn epoch(&self) -> u64 {
338 self.0.load(Ordering::Acquire)
339 }
340
341 pub fn revoke(&self) {
342 self.0.fetch_add(1, Ordering::AcqRel);
343 }
344}
345
346impl Default for RevocationCell {
347 fn default() -> Self {
348 Self::new()
349 }
350}
351
352impl Cap {
353 pub fn root(
355 target: CapTarget,
356 rights: CapRights,
357 native_mask: Option<NativeMask>,
358 cell: &RevocationCell,
359 ) -> Self {
360 Self {
361 target,
362 rights,
363 native_mask,
364 epoch: cell.epoch(),
365 }
366 }
367
368 pub fn epoch(&self) -> u64 {
369 self.epoch
370 }
371
372 pub fn is_valid(&self, cell: &RevocationCell) -> bool {
373 self.epoch == cell.epoch()
374 }
375
376 pub fn attenuate(&self, want_rights: CapRights, want_native: Option<&NativeMask>) -> Cap {
390 let rights = self.rights.intersect(want_rights);
391 let native_mask = match (&self.native_mask, want_native) {
392 (Some(cur), Some(req)) => Some(cur.intersect(req)),
393 (Some(cur), None) => Some(cur.clone()),
394 (None, _) => None,
395 };
396 Cap {
397 target: self.target,
398 rights,
399 native_mask,
400 epoch: self.epoch,
401 }
402 }
403}
404
405#[cfg(test)]
406mod tests {
407 use super::*;
408
409 #[test]
410 fn none_is_zero_and_random_is_not() -> Result<(), CapIdError> {
411 assert!(CapId::NONE.is_none());
412 let a = CapId::random()?;
413 let b = CapId::random()?;
414 assert!(!a.is_none());
415 assert!(!b.is_none());
416 assert_ne!(a, b);
417 Ok(())
418 }
419
420 #[test]
421 fn from_raw_is_crate_internal() {
422 assert_eq!(CapId::from_raw(0), CapId::NONE);
423 assert!(!CapId::from_raw(1).is_none());
424 }
425
426 #[test]
427 fn send_ask_bits_stay_compatible() {
428 assert_eq!(CapRights::SEND.bits(), 0b01);
429 assert_eq!(CapRights::ASK.bits(), 0b10);
430 assert_eq!(CapRights::SEND_ASK.bits(), 0b11);
431 assert!(CapRights::ADMIN.bits() > 0b11);
432 }
433
434 #[test]
435 fn attenuation_never_escalates() {
436 let cell = RevocationCell::new();
437 let nm = NativeMask::from_indices(128, &[3, 5, 9]);
438 let parent = Cap::root(
439 CapTarget::Flow(1),
440 CapRights::SEND.union(CapRights::NATIVE),
441 Some(nm),
442 &cell,
443 );
444
445 let child = parent.attenuate(CapRights::SEND.union(CapRights::ADMIN), None);
446 assert!(!child.rights.contains(CapRights::ADMIN));
447 assert!(child.rights.contains(CapRights::SEND));
448
449 let wide = NativeMask::full(128);
450 let child2 = parent.attenuate(CapRights::NATIVE, Some(&wide));
451 let child_mask = child2.native_mask.as_ref();
452 assert!(child_mask.is_some_and(|m| m.allows(3)));
453 let parent_mask = parent.native_mask.as_ref();
454 assert!(parent_mask.is_some_and(|m| !m.allows(7)));
455 }
456
457 #[test]
458 fn attenuation_is_subset_for_all_byte_masks() {
459 let cell = RevocationCell::new();
460 for src in 0u32..=255 {
461 for want in 0u32..=255 {
462 let parent = Cap::root(CapTarget::Flow(1), CapRights::from_bits(src), None, &cell);
463 let child = parent.attenuate(CapRights::from_bits(want), None);
464 assert!(
465 child.rights.is_subset_of(parent.rights),
466 "escalation src={src:#x} want={want:#x} got={:#x}",
467 child.rights.bits()
468 );
469 assert_eq!(child.rights.bits(), src & want);
470 }
471 }
472 }
473
474 #[test]
475 fn chained_delegate_never_gains_bits() {
476 let cell = RevocationCell::new();
477 let mut cap = Cap::root(
478 CapTarget::Flow(1),
479 CapRights::FLOW,
480 Some(NativeMask::from_indices(32, &[0, 1, 2])),
481 &cell,
482 );
483 let adversarial = [
484 CapRights::ADMIN,
485 CapRights::NATIVE.union(CapRights::ADMIN),
486 CapRights::from_bits(u32::MAX),
487 CapRights::NONE,
488 CapRights::FLOW,
489 ];
490 for want in adversarial {
491 cap = cap.attenuate(want, Some(&NativeMask::full(32)));
492 assert!(cap.rights.is_subset_of(CapRights::FLOW));
493 assert!(!cap.rights.contains(CapRights::ADMIN));
494 if let Some(mask) = &cap.native_mask {
495 assert!(!mask.allows(7));
496 }
497 }
498 }
499
500 #[test]
501 fn revocation_kills_all_derived_caps() {
502 let cell = RevocationCell::new();
503 let root = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
504 let child = root.attenuate(CapRights::SEND, None);
505 assert!(child.is_valid(&cell));
506 cell.revoke();
507 assert!(!child.is_valid(&cell));
508 assert!(!root.is_valid(&cell));
509 }
510}