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 = CapRights(
121 Self::SEND.0 | Self::ASK.0 | Self::LINK.0 | Self::MONITOR.0,
122 );
123
124 pub const FLOW: CapRights = CapRights(
129 Self::SEND.0
130 | Self::ASK.0
131 | Self::RECV.0
132 | Self::SPAWN.0
133 | Self::LINK.0
134 | Self::MONITOR.0
135 | Self::NATIVE.0,
136 );
137
138 pub const ROOT: CapRights = Self::FLOW;
141
142 pub const SEND_ASK: CapRights = CapRights(Self::SEND.0 | Self::ASK.0);
144
145 #[inline]
146 pub const fn empty() -> Self {
147 CapRights(0)
148 }
149
150 #[inline]
151 pub const fn union(self, other: CapRights) -> CapRights {
152 CapRights(self.0 | other.0)
153 }
154
155 #[inline]
156 pub const fn intersect(self, other: CapRights) -> CapRights {
157 CapRights(self.0 & other.0)
158 }
159
160 #[inline]
161 pub const fn contains(self, other: CapRights) -> bool {
162 self.0 & other.0 == other.0
163 }
164
165 #[inline]
166 pub const fn is_subset_of(self, other: CapRights) -> bool {
167 self.0 & !other.0 == 0
168 }
169
170 #[inline]
171 pub const fn bits(self) -> u32 {
172 self.0
173 }
174
175 #[inline]
177 pub const fn bits_u8(self) -> u8 {
178 self.0 as u8
179 }
180
181 #[inline]
182 pub const fn from_bits(bits: u32) -> Self {
183 CapRights(bits)
184 }
185
186 #[inline]
187 pub const fn from_u8(bits: u8) -> Self {
188 CapRights(bits as u32)
189 }
190}
191
192#[derive(Clone, Debug, PartialEq, Eq)]
196pub struct NativeMask(Arc<[u64]>);
197
198impl NativeMask {
199 pub fn empty(native_count: usize) -> Self {
200 let words = native_count.div_ceil(64);
201 Self(Arc::from(vec![0u64; words].into_boxed_slice()))
202 }
203
204 pub fn full(native_count: usize) -> Self {
205 let words = native_count.div_ceil(64);
206 let mut v = vec![u64::MAX; words];
207 let rem = native_count % 64;
210 if rem != 0 {
211 if let Some(last) = v.last_mut() {
212 *last &= (1u64 << rem) - 1;
213 }
214 }
215 Self(Arc::from(v.into_boxed_slice()))
216 }
217
218 pub fn from_indices(native_count: usize, idxs: &[NativeIdx]) -> Self {
219 let words = native_count.div_ceil(64);
220 let mut v = vec![0u64; words];
221 for &i in idxs {
222 let (w, b) = (i as usize / 64, i as usize % 64);
223 if w < v.len() && (i as usize) < native_count {
224 v[w] |= 1u64 << b;
225 }
226 }
227 Self(Arc::from(v.into_boxed_slice()))
228 }
229
230 pub fn word_len(&self) -> usize {
231 self.0.len()
232 }
233
234 #[inline]
235 pub fn allows(&self, idx: NativeIdx) -> bool {
236 let (w, b) = (idx as usize / 64, idx as usize % 64);
237 match self.0.get(w) {
238 Some(word) => word & (1u64 << b) != 0,
239 None => false,
240 }
241 }
242
243 pub fn intersect(&self, requested: &NativeMask) -> NativeMask {
246 let n = self.0.len().min(requested.0.len());
247 let mut words = vec![0u64; n];
248 for i in 0..n {
249 let a = match self.0.get(i) {
250 Some(w) => *w,
251 None => 0,
252 };
253 let b = match requested.0.get(i) {
254 Some(w) => *w,
255 None => 0,
256 };
257 words[i] = a & b;
258 }
259 NativeMask(Arc::from(words.into_boxed_slice()))
260 }
261
262 pub fn is_subset_of(&self, other: &NativeMask) -> bool {
264 let n = self.0.len().max(other.0.len());
265 for i in 0..n {
266 let a = match self.0.get(i) {
267 Some(w) => *w,
268 None => 0,
269 };
270 let b = match other.0.get(i) {
271 Some(w) => *w,
272 None => 0,
273 };
274 if a & !b != 0 {
275 return false;
276 }
277 }
278 true
279 }
280}
281
282#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
285pub enum CapTarget {
286 Flow(u64),
288 NativeTable,
291 Scheduler,
293}
294
295impl CapTarget {
296 pub fn flow_id(self) -> Option<u64> {
297 match self {
298 CapTarget::Flow(id) => Some(id),
299 CapTarget::NativeTable | CapTarget::Scheduler => None,
300 }
301 }
302}
303
304#[derive(Clone, Debug, PartialEq, Eq)]
306pub struct Cap {
307 pub target: CapTarget,
308 pub rights: CapRights,
309 pub native_mask: Option<NativeMask>,
311 epoch: u64,
314}
315
316#[derive(Debug)]
319pub struct RevocationCell(AtomicU64);
320
321impl RevocationCell {
322 pub fn new() -> Self {
323 Self(AtomicU64::new(0))
324 }
325
326 pub fn epoch(&self) -> u64 {
327 self.0.load(Ordering::Acquire)
328 }
329
330 pub fn revoke(&self) {
331 self.0.fetch_add(1, Ordering::AcqRel);
332 }
333}
334
335impl Default for RevocationCell {
336 fn default() -> Self {
337 Self::new()
338 }
339}
340
341impl Cap {
342 pub fn root(
344 target: CapTarget,
345 rights: CapRights,
346 native_mask: Option<NativeMask>,
347 cell: &RevocationCell,
348 ) -> Self {
349 Self {
350 target,
351 rights,
352 native_mask,
353 epoch: cell.epoch(),
354 }
355 }
356
357 pub fn epoch(&self) -> u64 {
358 self.epoch
359 }
360
361 pub fn is_valid(&self, cell: &RevocationCell) -> bool {
362 self.epoch == cell.epoch()
363 }
364
365 pub fn attenuate(&self, want_rights: CapRights, want_native: Option<&NativeMask>) -> Cap {
379 let rights = self.rights.intersect(want_rights);
380 let native_mask = match (&self.native_mask, want_native) {
381 (Some(cur), Some(req)) => Some(cur.intersect(req)),
382 (Some(cur), None) => Some(cur.clone()),
383 (None, _) => None,
384 };
385 Cap {
386 target: self.target,
387 rights,
388 native_mask,
389 epoch: self.epoch,
390 }
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 #[test]
399 fn none_is_zero_and_random_is_not() -> Result<(), CapIdError> {
400 assert!(CapId::NONE.is_none());
401 let a = CapId::random()?;
402 let b = CapId::random()?;
403 assert!(!a.is_none());
404 assert!(!b.is_none());
405 assert_ne!(a, b);
406 Ok(())
407 }
408
409 #[test]
410 fn from_raw_is_crate_internal() {
411 assert_eq!(CapId::from_raw(0), CapId::NONE);
412 assert!(!CapId::from_raw(1).is_none());
413 }
414
415 #[test]
416 fn send_ask_bits_stay_compatible() {
417 assert_eq!(CapRights::SEND.bits(), 0b01);
418 assert_eq!(CapRights::ASK.bits(), 0b10);
419 assert_eq!(CapRights::SEND_ASK.bits(), 0b11);
420 assert!(CapRights::ADMIN.bits() > 0b11);
421 }
422
423 #[test]
424 fn attenuation_never_escalates() {
425 let cell = RevocationCell::new();
426 let nm = NativeMask::from_indices(128, &[3, 5, 9]);
427 let parent = Cap::root(
428 CapTarget::Flow(1),
429 CapRights::SEND.union(CapRights::NATIVE),
430 Some(nm),
431 &cell,
432 );
433
434 let child = parent.attenuate(CapRights::SEND.union(CapRights::ADMIN), None);
435 assert!(!child.rights.contains(CapRights::ADMIN));
436 assert!(child.rights.contains(CapRights::SEND));
437
438 let wide = NativeMask::full(128);
439 let child2 = parent.attenuate(CapRights::NATIVE, Some(&wide));
440 let child_mask = child2.native_mask.as_ref();
441 assert!(child_mask.is_some_and(|m| m.allows(3)));
442 let parent_mask = parent.native_mask.as_ref();
443 assert!(parent_mask.is_some_and(|m| !m.allows(7)));
444 }
445
446 #[test]
447 fn attenuation_is_subset_for_all_byte_masks() {
448 let cell = RevocationCell::new();
449 for src in 0u32..=255 {
450 for want in 0u32..=255 {
451 let parent = Cap::root(
452 CapTarget::Flow(1),
453 CapRights::from_bits(src),
454 None,
455 &cell,
456 );
457 let child = parent.attenuate(CapRights::from_bits(want), None);
458 assert!(
459 child.rights.is_subset_of(parent.rights),
460 "escalation src={src:#x} want={want:#x} got={:#x}",
461 child.rights.bits()
462 );
463 assert_eq!(child.rights.bits(), src & want);
464 }
465 }
466 }
467
468 #[test]
469 fn chained_delegate_never_gains_bits() {
470 let cell = RevocationCell::new();
471 let mut cap = Cap::root(
472 CapTarget::Flow(1),
473 CapRights::FLOW,
474 Some(NativeMask::from_indices(32, &[0, 1, 2])),
475 &cell,
476 );
477 let adversarial = [
478 CapRights::ADMIN,
479 CapRights::NATIVE.union(CapRights::ADMIN),
480 CapRights::from_bits(u32::MAX),
481 CapRights::NONE,
482 CapRights::FLOW,
483 ];
484 for want in adversarial {
485 cap = cap.attenuate(want, Some(&NativeMask::full(32)));
486 assert!(cap.rights.is_subset_of(CapRights::FLOW));
487 assert!(!cap.rights.contains(CapRights::ADMIN));
488 if let Some(mask) = &cap.native_mask {
489 assert!(!mask.allows(7));
490 }
491 }
492 }
493
494 #[test]
495 fn revocation_kills_all_derived_caps() {
496 let cell = RevocationCell::new();
497 let root = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
498 let child = root.attenuate(CapRights::SEND, None);
499 assert!(child.is_valid(&cell));
500 cell.revoke();
501 assert!(!child.is_valid(&cell));
502 assert!(!root.is_valid(&cell));
503 }
504}