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 = match CapId::random() {
149 Ok(id) if !id.is_none() => id,
150 Ok(_) | Err(crate::CapIdError::ReservedZero) => {
151 return Err(RuntimeError::ReservedCapId);
152 }
153 Err(crate::CapIdError::Entropy(err)) => {
154 return Err(RuntimeError::EntropyFailed(err));
155 }
156 };
157 if table.contains_key(&id) {
158 continue;
159 }
160 table.insert(id, entry);
161 return Ok(id);
162 }
163 Err(RuntimeError::CapIdCollision)
164 }
165
166 fn insert(&self, holder: FlowId, cap: Cap) -> Result<CapId, RuntimeError> {
167 let mut table = self.lock("CapTable::insert")?;
168 Self::insert_fresh(&mut table.entries, Capability { holder, cap })
169 }
170
171 pub fn mint(
177 &self,
178 holder: FlowId,
179 target: FlowId,
180 rights: CapRights,
181 ) -> Result<CapId, RuntimeError> {
182 let cell = self.bind_flow(target)?;
183 let cap = Cap::root(
184 CapTarget::Flow(target.as_u64()),
185 rights,
186 None,
187 cell.as_ref(),
188 );
189 self.grant(holder, cap)
190 }
191
192 pub fn mint_or_reuse(
201 &self,
202 holder: FlowId,
203 target: FlowId,
204 rights: CapRights,
205 ) -> Result<CapId, RuntimeError> {
206 let mut g = self.lock("CapTable::mint_or_reuse")?;
207 if let Some(&id) = g.reply_index.get(&(holder, target)) {
208 if Self::reply_cap_is_live(&g, id, holder, target, rights) {
209 return Ok(id);
210 }
211 g.reply_index.remove(&(holder, target));
212 }
213 let cell = g
214 .flow_cells
215 .entry(target.as_u64())
216 .or_insert_with(|| Arc::new(RevocationCell::new()))
217 .clone();
218 let cap = Cap::root(
219 CapTarget::Flow(target.as_u64()),
220 rights,
221 None,
222 cell.as_ref(),
223 );
224 let id = Self::insert_fresh(&mut g.entries, Capability { holder, cap })?;
225 g.reply_index.insert((holder, target), id);
226 Ok(id)
227 }
228
229 fn reply_cap_is_live(
230 table: &CapTableInner,
231 id: CapId,
232 holder: FlowId,
233 target: FlowId,
234 rights: CapRights,
235 ) -> bool {
236 let Some(entry) = table.entries.get(&id) else {
237 return false;
238 };
239 if entry.holder != holder {
240 return false;
241 }
242 if entry.cap.target != CapTarget::Flow(target.as_u64()) {
243 return false;
244 }
245 if !entry.cap.rights.contains(rights) {
246 return false;
247 }
248 match table.flow_cells.get(&target.as_u64()) {
249 Some(cell) => entry.cap.is_valid(cell.as_ref()),
250 None => false,
251 }
252 }
253
254 pub fn grant(&self, holder: FlowId, cap: Cap) -> Result<CapId, RuntimeError> {
257 self.insert(holder, cap)
258 }
259
260 pub fn lookup(&self, id: CapId) -> Result<Option<Capability>, RuntimeError> {
262 if id.is_none() {
263 return Ok(None);
264 }
265 Ok(self.lock("CapTable::lookup")?.entries.get(&id).cloned())
266 }
267
268 pub fn resolve(
270 &self,
271 id: CapId,
272 holder: FlowId,
273 required: CapRights,
274 ) -> Result<Capability, CapError> {
275 if id.is_none() {
276 return Err(CapError::Unknown);
277 }
278 let table = self.lock("CapTable::resolve")?;
279 let entry = table.entries.get(&id).cloned().ok_or(CapError::Unknown)?;
280 if entry.holder != holder {
281 return Err(CapError::NotHolder);
282 }
283 if !entry.cap.rights.contains(required) {
284 return Err(CapError::InsufficientRights);
285 }
286 let valid = match entry.cap.target {
287 CapTarget::Flow(fid) => match table.flow_cells.get(&fid) {
288 Some(cell) => entry.cap.is_valid(cell.as_ref()),
289 None => false,
290 },
291 CapTarget::NativeTable => entry.cap.is_valid(self.native_cell.as_ref()),
292 CapTarget::Scheduler => entry.cap.is_valid(self.scheduler_cell.as_ref()),
293 };
294 if !valid {
295 return Err(CapError::Unknown);
296 }
297 Ok(entry)
298 }
299
300 pub fn attenuate(
303 &self,
304 id: CapId,
305 from_holder: FlowId,
306 to_holder: FlowId,
307 want_rights: CapRights,
308 want_native: Option<&NativeMask>,
309 ) -> Result<CapId, CapError> {
310 let src = self.resolve(id, from_holder, CapRights::empty())?;
311 let cell = match src.cap.target {
312 CapTarget::Flow(fid) => self
313 .lock("CapTable::attenuate")?
314 .flow_cells
315 .get(&fid)
316 .cloned()
317 .ok_or(CapError::Unknown)?,
318 CapTarget::NativeTable | CapTarget::Scheduler => {
319 return Err(CapError::WrongTarget);
320 }
321 };
322 let narrowed =
323 match super::delegate::exec_delegate(&src.cap, cell.as_ref(), want_rights, want_native)
324 {
325 Ok(c) => c,
326 Err(super::delegate::DelegateError::SourceRevoked) => {
327 return Err(CapError::Unknown)
328 }
329 Err(super::delegate::DelegateError::SourceLacksNative) => {
330 return Err(CapError::InsufficientRights)
331 }
332 };
333 if !narrowed.is_valid(cell.as_ref()) {
334 return Err(CapError::Unknown);
335 }
336 self.insert(to_holder, narrowed).map_err(CapError::from)
337 }
338
339 pub fn delegate(
341 &self,
342 id: CapId,
343 from_holder: FlowId,
344 to_holder: FlowId,
345 ) -> Result<CapId, CapError> {
346 let src = self.resolve(id, from_holder, CapRights::empty())?;
347 self.attenuate(
348 id,
349 from_holder,
350 to_holder,
351 src.cap.rights,
352 src.cap.native_mask.as_ref(),
353 )
354 }
355
356 pub fn reissue_for(&self, id: CapId, new_holder: FlowId) -> Result<CapId, CapError> {
360 let cap = self.lookup(id)?.ok_or(CapError::Unknown)?;
361 let table = self.lock("CapTable::reissue_for")?;
362 let valid = match cap.cap.target {
363 CapTarget::Flow(fid) => match table.flow_cells.get(&fid) {
364 Some(cell) => cap.cap.is_valid(cell.as_ref()),
365 None => false,
366 },
367 CapTarget::NativeTable => cap.cap.is_valid(self.native_cell.as_ref()),
368 CapTarget::Scheduler => cap.cap.is_valid(self.scheduler_cell.as_ref()),
369 };
370 drop(table);
371 if !valid {
372 return Err(CapError::Unknown);
373 }
374 let narrowed = cap
375 .cap
376 .attenuate(cap.cap.rights, cap.cap.native_mask.as_ref());
377 self.insert(new_holder, narrowed).map_err(CapError::from)
378 }
379
380 pub fn revoke_flow(&self, flow: FlowId) -> Result<usize, RuntimeError> {
383 let mut g = self.lock("CapTable::revoke_flow")?;
384 if let Some(cell) = g.flow_cells.get(&flow.as_u64()) {
385 cell.revoke();
386 }
387 g.flow_cells.remove(&flow.as_u64());
388 let before = g.entries.len();
389 let fid = flow.as_u64();
390 g.entries
391 .retain(|_, e| e.holder != flow && e.cap.target != CapTarget::Flow(fid));
392 g.reply_index.retain(|(h, t), _| *h != flow && *t != flow);
393 Ok(before - g.entries.len())
394 }
395
396 #[cfg(test)]
397 fn entry_count(&self) -> Result<usize, RuntimeError> {
398 Ok(self.lock("CapTable::entry_count")?.entries.len())
399 }
400
401 #[cfg(test)]
402 fn reply_index_len(&self) -> Result<usize, RuntimeError> {
403 Ok(self.lock("CapTable::reply_index_len")?.reply_index.len())
404 }
405
406 #[cfg(test)]
407 fn reply_index_mentions(&self, flow: FlowId) -> Result<bool, RuntimeError> {
408 Ok(self
409 .lock("CapTable::reply_index_mentions")?
410 .reply_index
411 .keys()
412 .any(|(h, t)| *h == flow || *t == flow))
413 }
414}
415
416impl Default for CapTable {
417 fn default() -> Self {
418 Self::new()
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425 use crate::scheduler::process::next_flow_id;
426
427 #[test]
428 fn random_ids_are_not_sequential() -> Result<(), Box<dyn std::error::Error>> {
429 let table = CapTable::new();
430 let h = next_flow_id();
431 let t = next_flow_id();
432 let a = table.mint(h, t, CapRights::SEND)?;
433 let b = table.mint(h, t, CapRights::SEND)?;
434 assert_ne!(a, b);
435 assert!(!a.is_none());
436 assert_eq!(
437 table.resolve(CapId::from_raw(1), h, CapRights::SEND),
438 Err(CapError::Unknown)
439 );
440 Ok(())
441 }
442
443 #[test]
444 fn resolve_requires_holder_and_rights() -> Result<(), Box<dyn std::error::Error>> {
445 let table = CapTable::new();
446 let holder = next_flow_id();
447 let other = next_flow_id();
448 let target = next_flow_id();
449 let cap = table.mint(holder, target, CapRights::SEND)?;
450 assert_eq!(
451 table.resolve(cap, holder, CapRights::SEND)?.target(),
452 Some(target)
453 );
454 assert_eq!(
455 table.resolve(cap, other, CapRights::SEND),
456 Err(CapError::NotHolder)
457 );
458 assert_eq!(
459 table.resolve(cap, holder, CapRights::ASK),
460 Err(CapError::InsufficientRights)
461 );
462 Ok(())
463 }
464
465 #[test]
466 fn capability_isolation_is_per_table() -> Result<(), Box<dyn std::error::Error>> {
467 let a = CapTable::new();
468 let b = CapTable::new();
469 let holder = next_flow_id();
470 let target = next_flow_id();
471 let cap = a.mint(holder, target, CapRights::SEND)?;
472 assert_eq!(
473 b.resolve(cap, holder, CapRights::SEND),
474 Err(CapError::Unknown)
475 );
476 Ok(())
477 }
478
479 #[test]
480 fn finalizing_flow_revokes_held_and_targeted_caps() -> Result<(), Box<dyn std::error::Error>> {
481 let table = CapTable::new();
482 let dead = next_flow_id();
483 let alive = next_flow_id();
484 let target = next_flow_id();
485
486 let held_by_dead = table.mint(dead, target, CapRights::SEND)?;
487 let targeting_dead = table.mint(alive, dead, CapRights::SEND)?;
488 let unrelated = table.mint(alive, target, CapRights::SEND)?;
489
490 let removed = table.revoke_flow(dead)?;
491 assert_eq!(removed, 2);
492 assert_eq!(
493 table.resolve(held_by_dead, dead, CapRights::SEND),
494 Err(CapError::Unknown)
495 );
496 assert_eq!(
497 table.resolve(targeting_dead, alive, CapRights::SEND),
498 Err(CapError::Unknown)
499 );
500 assert!(table.resolve(unrelated, alive, CapRights::SEND).is_ok());
501 Ok(())
502 }
503
504 #[test]
505 fn delegate_issues_a_new_id_for_the_child() -> Result<(), Box<dyn std::error::Error>> {
506 let table = CapTable::new();
507 let parent = next_flow_id();
508 let child = next_flow_id();
509 let target = next_flow_id();
510 let original = table.mint(parent, target, CapRights::SEND_ASK)?;
511 let granted = table.delegate(original, parent, child)?;
512 assert_ne!(granted, original);
513 assert_eq!(
514 table.resolve(granted, child, CapRights::SEND)?.target(),
515 Some(target)
516 );
517 assert_eq!(
518 table.resolve(original, child, CapRights::SEND),
519 Err(CapError::NotHolder)
520 );
521 assert!(table.resolve(original, parent, CapRights::ASK).is_ok());
522 Ok(())
523 }
524
525 #[test]
526 fn attenuate_cannot_escalate() -> Result<(), Box<dyn std::error::Error>> {
527 let table = CapTable::new();
528 let parent = next_flow_id();
529 let child = next_flow_id();
530 let target = next_flow_id();
531 let original = table.mint(parent, target, CapRights::SEND)?;
532 let granted = table.attenuate(
533 original,
534 parent,
535 child,
536 CapRights::SEND.union(CapRights::ADMIN),
537 None,
538 )?;
539 let got = table.resolve(granted, child, CapRights::SEND)?;
540 assert!(!got.rights().contains(CapRights::ADMIN));
541 assert!(got.rights().contains(CapRights::SEND));
542 Ok(())
543 }
544
545 #[test]
546 fn mint_or_reuse_is_stable_per_pair() -> Result<(), Box<dyn std::error::Error>> {
547 let table = CapTable::new();
548 let holder = next_flow_id();
549 let target = next_flow_id();
550 let first = table.mint_or_reuse(holder, target, CapRights::SEND)?;
551 for _ in 0..1_000 {
552 let again = table.mint_or_reuse(holder, target, CapRights::SEND)?;
553 assert_eq!(again, first);
554 }
555 assert_eq!(table.entry_count()?, 1);
556 assert_eq!(table.reply_index_len()?, 1);
557 assert!(table.resolve(first, holder, CapRights::SEND).is_ok());
558 Ok(())
559 }
560
561 #[test]
562 fn mint_or_reuse_distinct_pairs_are_independent() -> Result<(), Box<dyn std::error::Error>> {
563 let table = CapTable::new();
564 let a = next_flow_id();
565 let b = next_flow_id();
566 let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
567 let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
568 assert_ne!(ab, ba);
569 assert_eq!(table.entry_count()?, 2);
570 assert_eq!(table.reply_index_len()?, 2);
571 Ok(())
572 }
573
574 #[test]
575 fn revoke_flow_clears_reply_index_for_holder_and_target(
576 ) -> Result<(), Box<dyn std::error::Error>> {
577 let table = CapTable::new();
578 let a = next_flow_id();
579 let b = next_flow_id();
580 let alive = next_flow_id();
581 let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
582 let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
583 let kept = table.mint_or_reuse(alive, b, CapRights::SEND)?;
584
585 table.revoke_flow(a)?;
586 assert!(!table.reply_index_mentions(a)?);
587 assert_eq!(
588 table.resolve(ab, b, CapRights::SEND),
589 Err(CapError::Unknown)
590 );
591 assert_eq!(
592 table.resolve(ba, a, CapRights::SEND),
593 Err(CapError::Unknown)
594 );
595 assert!(table.resolve(kept, alive, CapRights::SEND).is_ok());
596 assert!(!table.reply_index_mentions(a)?);
597 assert!(table.reply_index_mentions(b)?);
598
599 table.revoke_flow(b)?;
600 assert!(!table.reply_index_mentions(a)?);
601 assert!(!table.reply_index_mentions(b)?);
602 Ok(())
603 }
604
605 #[test]
606 fn mint_or_reuse_after_revoke_issues_a_fresh_id() -> Result<(), Box<dyn std::error::Error>> {
607 let table = CapTable::new();
608 let holder = next_flow_id();
609 let target = next_flow_id();
610 let old = table.mint_or_reuse(holder, target, CapRights::SEND)?;
611 table.revoke_flow(target)?;
612 assert!(!table.reply_index_mentions(target)?);
613 let fresh = table.mint_or_reuse(holder, target, CapRights::SEND)?;
614 assert_ne!(fresh, old);
615 assert_eq!(
616 table.resolve(old, holder, CapRights::SEND),
617 Err(CapError::Unknown)
618 );
619 assert!(table.resolve(fresh, holder, CapRights::SEND).is_ok());
620 Ok(())
621 }
622}
623
624#[cfg(test)]
625mod properties {
626 use super::*;
629 use crate::prng::XorShift64;
630 use crate::scheduler::process::next_flow_id;
631
632 #[test]
633 fn mint_resolves_for_holder() -> Result<(), String> {
634 let mut rng = XorShift64::new(0xCA90_0001);
635 for _ in 0..64 {
636 let table = CapTable::new();
637 let holder = next_flow_id();
638 let target = next_flow_id();
639 let extra = rng.next_u32() & 0b10;
640 let rights = CapRights::SEND.union(CapRights::from_bits(extra));
641 let id = table
642 .mint(holder, target, rights)
643 .map_err(|e| e.to_string())?;
644 let cap = table
645 .resolve(id, holder, CapRights::SEND)
646 .map_err(|e| e.to_string())?;
647 if cap.holder != holder {
648 return Err("holder mismatch".into());
649 }
650 if !cap.cap.rights.contains(CapRights::SEND) {
651 return Err("missing SEND".into());
652 }
653 }
654 Ok(())
655 }
656
657 #[test]
658 fn resolve_rejects_non_holder() -> Result<(), String> {
659 for _ in 0..32 {
660 let table = CapTable::new();
661 let holder = next_flow_id();
662 let stranger = next_flow_id();
663 let target = next_flow_id();
664 let id = table
665 .mint(holder, target, CapRights::SEND)
666 .map_err(|e| e.to_string())?;
667 match table.resolve(id, stranger, CapRights::SEND) {
668 Err(CapError::NotHolder) => {}
669 Ok(_) => return Err("stranger must not resolve".into()),
670 Err(e) => return Err(format!("expected NotHolder, got {e}")),
671 }
672 }
673 Ok(())
674 }
675
676 #[test]
677 fn mint_or_reuse_is_stable_for_pair() -> Result<(), String> {
678 for _ in 0..32 {
679 let table = CapTable::new();
680 let holder = next_flow_id();
681 let target = next_flow_id();
682 let a = table
683 .mint_or_reuse(holder, target, CapRights::SEND)
684 .map_err(|e| e.to_string())?;
685 let b = table
686 .mint_or_reuse(holder, target, CapRights::SEND)
687 .map_err(|e| e.to_string())?;
688 if a != b {
689 return Err("mint_or_reuse not stable".into());
690 }
691 table
692 .resolve(a, holder, CapRights::SEND)
693 .map_err(|e| e.to_string())?;
694 }
695 Ok(())
696 }
697
698 #[test]
699 fn revoke_invalidates_prior_token() -> Result<(), String> {
700 for _ in 0..32 {
701 let table = CapTable::new();
702 let holder = next_flow_id();
703 let target = next_flow_id();
704 let old = table
705 .mint(holder, target, CapRights::SEND)
706 .map_err(|e| e.to_string())?;
707 table.revoke_flow(target).map_err(|e| e.to_string())?;
708 match table.resolve(old, holder, CapRights::SEND) {
709 Err(CapError::Unknown) => {}
710 Ok(_) => return Err("revoked Cap must not resolve".into()),
711 Err(e) => return Err(format!("expected Unknown, got {e}")),
712 }
713 let fresh = table
714 .mint(holder, target, CapRights::SEND)
715 .map_err(|e| e.to_string())?;
716 if fresh == old {
717 return Err("fresh CapId collided with revoked".into());
718 }
719 table
720 .resolve(fresh, holder, CapRights::SEND)
721 .map_err(|e| e.to_string())?;
722 }
723 Ok(())
724 }
725}