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