1use std::collections::HashMap;
19use std::sync::{Arc, Mutex};
20
21use crate::bytecode::{Cap, CapId, CapTarget, NativeMask, RevocationCell};
22
23pub use crate::bytecode::CapRights;
24
25use super::error::RuntimeError;
26use super::process::FlowId;
27use super::sync_lock;
28
29const MINT_ATTEMPTS: u32 = 32;
30
31#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct Capability {
34 pub holder: FlowId,
36 pub cap: Cap,
37}
38
39impl Capability {
40 pub fn target(&self) -> Option<FlowId> {
42 self.cap.target.flow_id().map(FlowId)
43 }
44
45 pub fn rights(&self) -> CapRights {
46 self.cap.rights
47 }
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum CapError {
53 Unknown,
54 NotHolder,
55 InsufficientRights,
56 WrongTarget,
57 Unavailable,
59}
60
61impl std::fmt::Display for CapError {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 match self {
64 CapError::Unknown => f.write_str("unknown or revoked capability"),
65 CapError::NotHolder => f.write_str("calling flow does not hold this capability"),
66 CapError::InsufficientRights => f.write_str("capability lacks required rights"),
67 CapError::WrongTarget => f.write_str("capability target is not a flow"),
68 CapError::Unavailable => f.write_str("capability table unavailable (poisoned lock)"),
69 }
70 }
71}
72
73impl std::error::Error for CapError {}
74
75impl From<RuntimeError> for CapError {
76 fn from(_err: RuntimeError) -> Self {
77 CapError::Unavailable
78 }
79}
80
81struct CapTableInner {
82 entries: HashMap<CapId, Capability>,
83 flow_cells: HashMap<u64, Arc<RevocationCell>>,
84 reply_index: HashMap<(FlowId, FlowId), CapId>,
89}
90
91pub struct CapTable {
93 inner: Mutex<CapTableInner>,
94 native_cell: Arc<RevocationCell>,
95 scheduler_cell: Arc<RevocationCell>,
96}
97
98impl CapTable {
99 pub fn new() -> Self {
100 Self {
101 inner: Mutex::new(CapTableInner {
102 entries: HashMap::new(),
103 flow_cells: HashMap::new(),
104 reply_index: HashMap::new(),
105 }),
106 native_cell: Arc::new(RevocationCell::new()),
107 scheduler_cell: Arc::new(RevocationCell::new()),
108 }
109 }
110
111 pub fn native_cell(&self) -> Arc<RevocationCell> {
112 Arc::clone(&self.native_cell)
113 }
114
115 fn lock(
116 &self,
117 where_: &'static str,
118 ) -> Result<std::sync::MutexGuard<'_, CapTableInner>, RuntimeError> {
119 sync_lock::lock(&self.inner, where_)
120 }
121
122 pub fn bind_flow(&self, flow: FlowId) -> Result<Arc<RevocationCell>, RuntimeError> {
124 let mut g = self.lock("CapTable::bind_flow")?;
125 Ok(g.flow_cells
126 .entry(flow.as_u64())
127 .or_insert_with(|| Arc::new(RevocationCell::new()))
128 .clone())
129 }
130
131 pub fn flow_cell(&self, flow: FlowId) -> Result<Option<Arc<RevocationCell>>, RuntimeError> {
132 Ok(self
133 .lock("CapTable::flow_cell")?
134 .flow_cells
135 .get(&flow.as_u64())
136 .cloned())
137 }
138
139 pub fn scheduler_cell(&self) -> Arc<RevocationCell> {
140 Arc::clone(&self.scheduler_cell)
141 }
142
143 fn insert_fresh(
144 table: &mut HashMap<CapId, Capability>,
145 entry: Capability,
146 ) -> Result<CapId, RuntimeError> {
147 for _ in 0..MINT_ATTEMPTS {
148 let id = CapId::random().map_err(|_| RuntimeError::EntropyFailed)?;
149 if id.is_none() || table.contains_key(&id) {
150 continue;
151 }
152 table.insert(id, entry);
153 return Ok(id);
154 }
155 Err(RuntimeError::CapIdCollision)
156 }
157
158 fn insert(&self, holder: FlowId, cap: Cap) -> Result<CapId, RuntimeError> {
159 let mut table = self.lock("CapTable::insert")?;
160 Self::insert_fresh(&mut table.entries, Capability { holder, cap })
161 }
162
163 pub fn mint(
169 &self,
170 holder: FlowId,
171 target: FlowId,
172 rights: CapRights,
173 ) -> Result<CapId, RuntimeError> {
174 let cell = self.bind_flow(target)?;
175 let cap = Cap::root(
176 CapTarget::Flow(target.as_u64()),
177 rights,
178 None,
179 cell.as_ref(),
180 );
181 self.grant(holder, cap)
182 }
183
184 pub fn mint_or_reuse(
193 &self,
194 holder: FlowId,
195 target: FlowId,
196 rights: CapRights,
197 ) -> Result<CapId, RuntimeError> {
198 let mut g = self.lock("CapTable::mint_or_reuse")?;
199 if let Some(&id) = g.reply_index.get(&(holder, target)) {
200 if Self::reply_cap_is_live(&g, id, holder, target, rights) {
201 return Ok(id);
202 }
203 g.reply_index.remove(&(holder, target));
204 }
205 let cell = g
206 .flow_cells
207 .entry(target.as_u64())
208 .or_insert_with(|| Arc::new(RevocationCell::new()))
209 .clone();
210 let cap = Cap::root(
211 CapTarget::Flow(target.as_u64()),
212 rights,
213 None,
214 cell.as_ref(),
215 );
216 let id = Self::insert_fresh(&mut g.entries, Capability { holder, cap })?;
217 g.reply_index.insert((holder, target), id);
218 Ok(id)
219 }
220
221 fn reply_cap_is_live(
222 table: &CapTableInner,
223 id: CapId,
224 holder: FlowId,
225 target: FlowId,
226 rights: CapRights,
227 ) -> bool {
228 let Some(entry) = table.entries.get(&id) else {
229 return false;
230 };
231 if entry.holder != holder {
232 return false;
233 }
234 if entry.cap.target != CapTarget::Flow(target.as_u64()) {
235 return false;
236 }
237 if !entry.cap.rights.contains(rights) {
238 return false;
239 }
240 match table.flow_cells.get(&target.as_u64()) {
241 Some(cell) => entry.cap.is_valid(cell.as_ref()),
242 None => false,
243 }
244 }
245
246 pub fn grant(&self, holder: FlowId, cap: Cap) -> Result<CapId, RuntimeError> {
249 self.insert(holder, cap)
250 }
251
252 pub fn lookup(&self, id: CapId) -> Result<Option<Capability>, RuntimeError> {
254 if id.is_none() {
255 return Ok(None);
256 }
257 Ok(self.lock("CapTable::lookup")?.entries.get(&id).cloned())
258 }
259
260 pub fn resolve(
262 &self,
263 id: CapId,
264 holder: FlowId,
265 required: CapRights,
266 ) -> Result<Capability, CapError> {
267 if id.is_none() {
268 return Err(CapError::Unknown);
269 }
270 let table = self.lock("CapTable::resolve")?;
271 let entry = table.entries.get(&id).cloned().ok_or(CapError::Unknown)?;
272 if entry.holder != holder {
273 return Err(CapError::NotHolder);
274 }
275 if !entry.cap.rights.contains(required) {
276 return Err(CapError::InsufficientRights);
277 }
278 let valid = match entry.cap.target {
279 CapTarget::Flow(fid) => match table.flow_cells.get(&fid) {
280 Some(cell) => entry.cap.is_valid(cell.as_ref()),
281 None => false,
282 },
283 CapTarget::NativeTable => entry.cap.is_valid(self.native_cell.as_ref()),
284 CapTarget::Scheduler => entry.cap.is_valid(self.scheduler_cell.as_ref()),
285 };
286 if !valid {
287 return Err(CapError::Unknown);
288 }
289 Ok(entry)
290 }
291
292 pub fn attenuate(
295 &self,
296 id: CapId,
297 from_holder: FlowId,
298 to_holder: FlowId,
299 want_rights: CapRights,
300 want_native: Option<&NativeMask>,
301 ) -> Result<CapId, CapError> {
302 let src = self.resolve(id, from_holder, CapRights::empty())?;
303 let cell = match src.cap.target {
304 CapTarget::Flow(fid) => self
305 .lock("CapTable::attenuate")?
306 .flow_cells
307 .get(&fid)
308 .cloned()
309 .ok_or(CapError::Unknown)?,
310 CapTarget::NativeTable | CapTarget::Scheduler => {
311 return Err(CapError::WrongTarget);
312 }
313 };
314 let narrowed =
315 match super::delegate::exec_delegate(&src.cap, cell.as_ref(), want_rights, want_native)
316 {
317 Ok(c) => c,
318 Err(super::delegate::DelegateError::SourceRevoked) => {
319 return Err(CapError::Unknown)
320 }
321 Err(super::delegate::DelegateError::SourceLacksNative) => {
322 return Err(CapError::InsufficientRights)
323 }
324 };
325 if !narrowed.is_valid(cell.as_ref()) {
326 return Err(CapError::Unknown);
327 }
328 self.insert(to_holder, narrowed).map_err(CapError::from)
329 }
330
331 pub fn delegate(
333 &self,
334 id: CapId,
335 from_holder: FlowId,
336 to_holder: FlowId,
337 ) -> Result<CapId, CapError> {
338 let src = self.resolve(id, from_holder, CapRights::empty())?;
339 self.attenuate(
340 id,
341 from_holder,
342 to_holder,
343 src.cap.rights,
344 src.cap.native_mask.as_ref(),
345 )
346 }
347
348 pub fn reissue_for(&self, id: CapId, new_holder: FlowId) -> Result<CapId, CapError> {
352 let cap = self.lookup(id)?.ok_or(CapError::Unknown)?;
353 let table = self.lock("CapTable::reissue_for")?;
354 let valid = match cap.cap.target {
355 CapTarget::Flow(fid) => match table.flow_cells.get(&fid) {
356 Some(cell) => cap.cap.is_valid(cell.as_ref()),
357 None => false,
358 },
359 CapTarget::NativeTable => cap.cap.is_valid(self.native_cell.as_ref()),
360 CapTarget::Scheduler => cap.cap.is_valid(self.scheduler_cell.as_ref()),
361 };
362 drop(table);
363 if !valid {
364 return Err(CapError::Unknown);
365 }
366 let narrowed = cap
367 .cap
368 .attenuate(cap.cap.rights, cap.cap.native_mask.as_ref());
369 self.insert(new_holder, narrowed).map_err(CapError::from)
370 }
371
372 pub fn revoke_flow(&self, flow: FlowId) -> Result<usize, RuntimeError> {
375 let mut g = self.lock("CapTable::revoke_flow")?;
376 if let Some(cell) = g.flow_cells.get(&flow.as_u64()) {
377 cell.revoke();
378 }
379 g.flow_cells.remove(&flow.as_u64());
380 let before = g.entries.len();
381 let fid = flow.as_u64();
382 g.entries
383 .retain(|_, e| e.holder != flow && e.cap.target != CapTarget::Flow(fid));
384 g.reply_index.retain(|(h, t), _| *h != flow && *t != flow);
385 Ok(before - g.entries.len())
386 }
387
388 #[cfg(test)]
389 fn entry_count(&self) -> Result<usize, RuntimeError> {
390 Ok(self.lock("CapTable::entry_count")?.entries.len())
391 }
392
393 #[cfg(test)]
394 fn reply_index_len(&self) -> Result<usize, RuntimeError> {
395 Ok(self.lock("CapTable::reply_index_len")?.reply_index.len())
396 }
397
398 #[cfg(test)]
399 fn reply_index_mentions(&self, flow: FlowId) -> Result<bool, RuntimeError> {
400 Ok(self
401 .lock("CapTable::reply_index_mentions")?
402 .reply_index
403 .keys()
404 .any(|(h, t)| *h == flow || *t == flow))
405 }
406}
407
408impl Default for CapTable {
409 fn default() -> Self {
410 Self::new()
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417 use crate::scheduler::process::next_flow_id;
418
419 #[test]
420 fn random_ids_are_not_sequential() -> Result<(), Box<dyn std::error::Error>> {
421 let table = CapTable::new();
422 let h = next_flow_id();
423 let t = next_flow_id();
424 let a = table.mint(h, t, CapRights::SEND)?;
425 let b = table.mint(h, t, CapRights::SEND)?;
426 assert_ne!(a, b);
427 assert!(!a.is_none());
428 assert_eq!(
429 table.resolve(CapId::from_raw(1), h, CapRights::SEND),
430 Err(CapError::Unknown)
431 );
432 Ok(())
433 }
434
435 #[test]
436 fn resolve_requires_holder_and_rights() -> Result<(), Box<dyn std::error::Error>> {
437 let table = CapTable::new();
438 let holder = next_flow_id();
439 let other = next_flow_id();
440 let target = next_flow_id();
441 let cap = table.mint(holder, target, CapRights::SEND)?;
442 assert_eq!(
443 table.resolve(cap, holder, CapRights::SEND)?.target(),
444 Some(target)
445 );
446 assert_eq!(
447 table.resolve(cap, other, CapRights::SEND),
448 Err(CapError::NotHolder)
449 );
450 assert_eq!(
451 table.resolve(cap, holder, CapRights::ASK),
452 Err(CapError::InsufficientRights)
453 );
454 Ok(())
455 }
456
457 #[test]
458 fn capability_isolation_is_per_table() -> Result<(), Box<dyn std::error::Error>> {
459 let a = CapTable::new();
460 let b = CapTable::new();
461 let holder = next_flow_id();
462 let target = next_flow_id();
463 let cap = a.mint(holder, target, CapRights::SEND)?;
464 assert_eq!(
465 b.resolve(cap, holder, CapRights::SEND),
466 Err(CapError::Unknown)
467 );
468 Ok(())
469 }
470
471 #[test]
472 fn finalizing_flow_revokes_held_and_targeted_caps() -> Result<(), Box<dyn std::error::Error>> {
473 let table = CapTable::new();
474 let dead = next_flow_id();
475 let alive = next_flow_id();
476 let target = next_flow_id();
477
478 let held_by_dead = table.mint(dead, target, CapRights::SEND)?;
479 let targeting_dead = table.mint(alive, dead, CapRights::SEND)?;
480 let unrelated = table.mint(alive, target, CapRights::SEND)?;
481
482 let removed = table.revoke_flow(dead)?;
483 assert_eq!(removed, 2);
484 assert_eq!(
485 table.resolve(held_by_dead, dead, CapRights::SEND),
486 Err(CapError::Unknown)
487 );
488 assert_eq!(
489 table.resolve(targeting_dead, alive, CapRights::SEND),
490 Err(CapError::Unknown)
491 );
492 assert!(table.resolve(unrelated, alive, CapRights::SEND).is_ok());
493 Ok(())
494 }
495
496 #[test]
497 fn delegate_issues_a_new_id_for_the_child() -> Result<(), Box<dyn std::error::Error>> {
498 let table = CapTable::new();
499 let parent = next_flow_id();
500 let child = next_flow_id();
501 let target = next_flow_id();
502 let original = table.mint(parent, target, CapRights::SEND_ASK)?;
503 let granted = table.delegate(original, parent, child)?;
504 assert_ne!(granted, original);
505 assert_eq!(
506 table.resolve(granted, child, CapRights::SEND)?.target(),
507 Some(target)
508 );
509 assert_eq!(
510 table.resolve(original, child, CapRights::SEND),
511 Err(CapError::NotHolder)
512 );
513 assert!(table.resolve(original, parent, CapRights::ASK).is_ok());
514 Ok(())
515 }
516
517 #[test]
518 fn attenuate_cannot_escalate() -> Result<(), Box<dyn std::error::Error>> {
519 let table = CapTable::new();
520 let parent = next_flow_id();
521 let child = next_flow_id();
522 let target = next_flow_id();
523 let original = table.mint(parent, target, CapRights::SEND)?;
524 let granted = table.attenuate(
525 original,
526 parent,
527 child,
528 CapRights::SEND.union(CapRights::ADMIN),
529 None,
530 )?;
531 let got = table.resolve(granted, child, CapRights::SEND)?;
532 assert!(!got.rights().contains(CapRights::ADMIN));
533 assert!(got.rights().contains(CapRights::SEND));
534 Ok(())
535 }
536
537 #[test]
538 fn mint_or_reuse_is_stable_per_pair() -> Result<(), Box<dyn std::error::Error>> {
539 let table = CapTable::new();
540 let holder = next_flow_id();
541 let target = next_flow_id();
542 let first = table.mint_or_reuse(holder, target, CapRights::SEND)?;
543 for _ in 0..1_000 {
544 let again = table.mint_or_reuse(holder, target, CapRights::SEND)?;
545 assert_eq!(again, first);
546 }
547 assert_eq!(table.entry_count()?, 1);
548 assert_eq!(table.reply_index_len()?, 1);
549 assert!(table.resolve(first, holder, CapRights::SEND).is_ok());
550 Ok(())
551 }
552
553 #[test]
554 fn mint_or_reuse_distinct_pairs_are_independent() -> Result<(), Box<dyn std::error::Error>> {
555 let table = CapTable::new();
556 let a = next_flow_id();
557 let b = next_flow_id();
558 let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
559 let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
560 assert_ne!(ab, ba);
561 assert_eq!(table.entry_count()?, 2);
562 assert_eq!(table.reply_index_len()?, 2);
563 Ok(())
564 }
565
566 #[test]
567 fn revoke_flow_clears_reply_index_for_holder_and_target(
568 ) -> Result<(), Box<dyn std::error::Error>> {
569 let table = CapTable::new();
570 let a = next_flow_id();
571 let b = next_flow_id();
572 let alive = next_flow_id();
573 let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
574 let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
575 let kept = table.mint_or_reuse(alive, b, CapRights::SEND)?;
576
577 table.revoke_flow(a)?;
578 assert!(!table.reply_index_mentions(a)?);
579 assert_eq!(
580 table.resolve(ab, b, CapRights::SEND),
581 Err(CapError::Unknown)
582 );
583 assert_eq!(
584 table.resolve(ba, a, CapRights::SEND),
585 Err(CapError::Unknown)
586 );
587 assert!(table.resolve(kept, alive, CapRights::SEND).is_ok());
588 assert!(!table.reply_index_mentions(a)?);
589 assert!(table.reply_index_mentions(b)?);
590
591 table.revoke_flow(b)?;
592 assert!(!table.reply_index_mentions(a)?);
593 assert!(!table.reply_index_mentions(b)?);
594 Ok(())
595 }
596
597 #[test]
598 fn mint_or_reuse_after_revoke_issues_a_fresh_id() -> Result<(), Box<dyn std::error::Error>> {
599 let table = CapTable::new();
600 let holder = next_flow_id();
601 let target = next_flow_id();
602 let old = table.mint_or_reuse(holder, target, CapRights::SEND)?;
603 table.revoke_flow(target)?;
604 assert!(!table.reply_index_mentions(target)?);
605 let fresh = table.mint_or_reuse(holder, target, CapRights::SEND)?;
606 assert_ne!(fresh, old);
607 assert_eq!(
608 table.resolve(old, holder, CapRights::SEND),
609 Err(CapError::Unknown)
610 );
611 assert!(table.resolve(fresh, holder, CapRights::SEND).is_ok());
612 Ok(())
613 }
614}
615
616#[cfg(test)]
617mod properties {
618 use super::*;
621 use crate::prng::XorShift64;
622 use crate::scheduler::process::next_flow_id;
623
624 #[test]
625 fn mint_resolves_for_holder() -> Result<(), String> {
626 let mut rng = XorShift64::new(0xCA90_0001);
627 for _ in 0..64 {
628 let table = CapTable::new();
629 let holder = next_flow_id();
630 let target = next_flow_id();
631 let extra = rng.next_u32() & 0b10;
632 let rights = CapRights::SEND.union(CapRights::from_bits(extra));
633 let id = table
634 .mint(holder, target, rights)
635 .map_err(|e| e.to_string())?;
636 let cap = table
637 .resolve(id, holder, CapRights::SEND)
638 .map_err(|e| e.to_string())?;
639 if cap.holder != holder {
640 return Err("holder mismatch".into());
641 }
642 if !cap.cap.rights.contains(CapRights::SEND) {
643 return Err("missing SEND".into());
644 }
645 }
646 Ok(())
647 }
648
649 #[test]
650 fn resolve_rejects_non_holder() -> Result<(), String> {
651 for _ in 0..32 {
652 let table = CapTable::new();
653 let holder = next_flow_id();
654 let stranger = next_flow_id();
655 let target = next_flow_id();
656 let id = table
657 .mint(holder, target, CapRights::SEND)
658 .map_err(|e| e.to_string())?;
659 match table.resolve(id, stranger, CapRights::SEND) {
660 Err(CapError::NotHolder) => {}
661 Ok(_) => return Err("stranger must not resolve".into()),
662 Err(e) => return Err(format!("expected NotHolder, got {e}")),
663 }
664 }
665 Ok(())
666 }
667
668 #[test]
669 fn mint_or_reuse_is_stable_for_pair() -> Result<(), String> {
670 for _ in 0..32 {
671 let table = CapTable::new();
672 let holder = next_flow_id();
673 let target = next_flow_id();
674 let a = table
675 .mint_or_reuse(holder, target, CapRights::SEND)
676 .map_err(|e| e.to_string())?;
677 let b = table
678 .mint_or_reuse(holder, target, CapRights::SEND)
679 .map_err(|e| e.to_string())?;
680 if a != b {
681 return Err("mint_or_reuse not stable".into());
682 }
683 table
684 .resolve(a, holder, CapRights::SEND)
685 .map_err(|e| e.to_string())?;
686 }
687 Ok(())
688 }
689
690 #[test]
691 fn revoke_invalidates_prior_token() -> Result<(), String> {
692 for _ in 0..32 {
693 let table = CapTable::new();
694 let holder = next_flow_id();
695 let target = next_flow_id();
696 let old = table
697 .mint(holder, target, CapRights::SEND)
698 .map_err(|e| e.to_string())?;
699 table.revoke_flow(target).map_err(|e| e.to_string())?;
700 match table.resolve(old, holder, CapRights::SEND) {
701 Err(CapError::Unknown) => {}
702 Ok(_) => return Err("revoked Cap must not resolve".into()),
703 Err(e) => return Err(format!("expected Unknown, got {e}")),
704 }
705 let fresh = table
706 .mint(holder, target, CapRights::SEND)
707 .map_err(|e| e.to_string())?;
708 if fresh == old {
709 return Err("fresh CapId collided with revoked".into());
710 }
711 table
712 .resolve(fresh, holder, CapRights::SEND)
713 .map_err(|e| e.to_string())?;
714 }
715 Ok(())
716 }
717}