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