rvm-cap 0.1.1

Capability system for RVM with P1/P2 proof verification (ADR-135)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Main capability manager tying together table, derivation tree, and verifier.
//!
//! The `CapabilityManager` is the single integration point for all
//! capability operations: create, grant, revoke, verify.

use crate::derivation::DerivationTree;
use crate::error::{CapError, CapResult, ProofError};
use crate::grant::{validate_grant, GrantPolicy};
use crate::revoke::{revoke_capability, RevokeResult};
use crate::table::CapabilityTable;
use crate::verify::{PolicyContext, ProofVerifier};
use crate::DEFAULT_CAP_TABLE_CAPACITY;
use rvm_types::{CapRights, CapToken, CapType, PartitionId};

/// Configuration for the capability manager.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CapManagerConfig {
    /// Maximum delegation depth (default: 8).
    pub max_delegation_depth: u8,
    /// Whether to track derivation chains (for revocation propagation).
    pub track_derivation: bool,
    /// Initial epoch value.
    pub initial_epoch: u32,
}

impl CapManagerConfig {
    /// Creates a new configuration with default values.
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self {
            max_delegation_depth: crate::DEFAULT_MAX_DELEGATION_DEPTH,
            track_derivation: true,
            initial_epoch: 0,
        }
    }

    /// Sets a custom maximum delegation depth.
    #[inline]
    #[must_use]
    pub const fn with_max_depth(mut self, depth: u8) -> Self {
        self.max_delegation_depth = depth;
        self
    }
}

impl Default for CapManagerConfig {
    fn default() -> Self {
        Self::new()
    }
}

/// Statistics about capability manager operations.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ManagerStats {
    /// Total capabilities created.
    pub caps_created: u64,
    /// Total capabilities granted (derived).
    pub caps_granted: u64,
    /// Total capabilities revoked.
    pub caps_revoked: u64,
    /// Total revoke operations.
    pub revoke_operations: u64,
    /// Maximum derivation depth reached.
    pub max_depth_reached: u8,
}

/// The main capability manager.
///
/// Coordinates capability table, derivation tree, and proof verifier
/// to provide complete capability lifecycle management.
pub struct CapabilityManager<const N: usize = DEFAULT_CAP_TABLE_CAPACITY> {
    table: CapabilityTable<N>,
    derivation: DerivationTree<N>,
    verifier: ProofVerifier<N>,
    config: CapManagerConfig,
    grant_policy: GrantPolicy,
    epoch: u32,
    next_id: u64,
    stats: ManagerStats,
}

impl<const N: usize> CapabilityManager<N> {
    /// Creates a new capability manager with the given configuration.
    #[must_use]
    pub const fn new(config: CapManagerConfig) -> Self {
        Self {
            table: CapabilityTable::new(),
            derivation: DerivationTree::new(),
            verifier: ProofVerifier::new(config.initial_epoch),
            grant_policy: GrantPolicy {
                max_depth: config.max_delegation_depth,
                allow_grant_once: true,
            },
            epoch: config.initial_epoch,
            next_id: 1,
            config,
            stats: ManagerStats {
                caps_created: 0,
                caps_granted: 0,
                caps_revoked: 0,
                revoke_operations: 0,
                max_depth_reached: 0,
            },
        }
    }

    /// Creates a new capability manager with default configuration.
    #[must_use]
    pub const fn with_defaults() -> Self {
        Self::new(CapManagerConfig::new())
    }

    /// Returns the current configuration.
    #[inline]
    #[must_use]
    pub const fn config(&self) -> &CapManagerConfig {
        &self.config
    }

    /// Returns the current statistics.
    #[inline]
    #[must_use]
    pub const fn stats(&self) -> &ManagerStats {
        &self.stats
    }

    /// Returns the current epoch.
    #[inline]
    #[must_use]
    pub const fn epoch(&self) -> u32 {
        self.epoch
    }

    /// Returns the number of active capabilities.
    #[inline]
    #[must_use]
    pub const fn len(&self) -> usize {
        self.table.len()
    }

    /// Returns true if there are no active capabilities.
    #[inline]
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.table.is_empty()
    }

    /// Increments the global epoch, invalidating stale handles.
    pub fn increment_epoch(&mut self) {
        self.epoch = self.epoch.wrapping_add(1);
        self.verifier.set_epoch(self.epoch);
    }

    /// Creates a root capability for a new kernel object (unchecked).
    ///
    /// This is the kernel-internal path; for authorization-checked
    /// creation, use [`create_root_capability_checked`](Self::create_root_capability_checked).
    ///
    /// # Errors
    ///
    /// Returns a [`CapError`] if the table is full or the derivation tree cannot be updated.
    pub fn create_root_capability(
        &mut self,
        cap_type: CapType,
        rights: CapRights,
        badge: u64,
        owner: PartitionId,
    ) -> CapResult<(u32, u32)> {
        self.create_root_capability_inner(cap_type, rights, badge, owner)
    }

    /// Creates a root capability with authorization check.
    ///
    /// Only `PartitionId::HYPERVISOR` (the hypervisor itself) is
    /// authorized to create root capabilities. All other callers are
    /// rejected with [`CapError::GrantNotPermitted`].
    ///
    /// # Errors
    ///
    /// Returns [`CapError::GrantNotPermitted`] if `caller_id` is not the hypervisor.
    /// Returns a [`CapError`] if the table is full or the derivation tree cannot be updated.
    pub fn create_root_capability_checked(
        &mut self,
        cap_type: CapType,
        rights: CapRights,
        badge: u64,
        owner: PartitionId,
        caller_id: PartitionId,
    ) -> CapResult<(u32, u32)> {
        if !caller_id.is_hypervisor() {
            return Err(CapError::GrantNotPermitted);
        }
        self.create_root_capability_inner(cap_type, rights, badge, owner)
    }

    /// Internal root capability creation (shared implementation).
    fn create_root_capability_inner(
        &mut self,
        cap_type: CapType,
        rights: CapRights,
        badge: u64,
        owner: PartitionId,
    ) -> CapResult<(u32, u32)> {
        let id = self.next_id;
        self.next_id = self.next_id.checked_add(1).ok_or(CapError::TableFull)?;

        let token = CapToken::new(id, cap_type, rights, self.epoch);
        let (index, generation) = self.table.insert_root(token, owner, badge)?;

        if self.config.track_derivation {
            self.derivation.add_root(index, u64::from(self.epoch))?;
        }

        self.stats.caps_created = self.stats.caps_created.wrapping_add(1);
        Ok((index, generation))
    }

    /// Grants a derived capability to another partition.
    ///
    /// `caller_id` identifies the partition performing the grant and is
    /// checked against the source capability's owner. Pass `None` to
    /// skip the owner check (kernel-internal use only).
    ///
    /// # Errors
    ///
    /// Returns a [`CapError`] if the source is invalid, the caller does
    /// not own the source, rights escalation is attempted, or the
    /// delegation depth limit is exceeded.
    pub fn grant(
        &mut self,
        source_index: u32,
        source_generation: u32,
        requested_rights: CapRights,
        badge: u64,
        target_owner: PartitionId,
    ) -> CapResult<(u32, u32)> {
        self.grant_with_caller(
            source_index,
            source_generation,
            requested_rights,
            badge,
            target_owner,
            None,
        )
    }

    /// Like [`grant`](Self::grant) but verifies the caller owns the
    /// source capability.
    ///
    /// # Errors
    ///
    /// Returns a [`CapError`] if the source capability is invalid, stale,
    /// or not owned by `caller_id`, or if the requested rights exceed those
    /// of the source capability.
    pub fn grant_checked(
        &mut self,
        source_index: u32,
        source_generation: u32,
        requested_rights: CapRights,
        badge: u64,
        target_owner: PartitionId,
        caller_id: PartitionId,
    ) -> CapResult<(u32, u32)> {
        self.grant_with_caller(
            source_index,
            source_generation,
            requested_rights,
            badge,
            target_owner,
            Some(caller_id),
        )
    }

    /// Internal grant implementation with optional caller verification.
    fn grant_with_caller(
        &mut self,
        source_index: u32,
        source_generation: u32,
        requested_rights: CapRights,
        badge: u64,
        target_owner: PartitionId,
        caller_id: Option<PartitionId>,
    ) -> CapResult<(u32, u32)> {
        let source_slot = self.table.lookup(source_index, source_generation)?;
        let source_copy = *source_slot;

        // Fix 6: verify the caller owns the source capability.
        if let Some(caller) = caller_id {
            if source_copy.owner != caller {
                return Err(CapError::GrantNotPermitted);
            }
        }

        let id = self.next_id;
        self.next_id = self.next_id.checked_add(1).ok_or(CapError::TableFull)?;

        let (derived_token, depth, consume_grant_once) = validate_grant(
            &source_copy,
            requested_rights,
            id,
            badge,
            self.epoch,
            self.grant_policy,
        )?;

        let (child_index, child_generation) =
            self.table
                .insert_derived(derived_token, target_owner, depth, source_index, badge)?;

        // Fix 7: if derivation tracking fails, roll back the table insertion.
        if self.config.track_derivation {
            if let Err(e) =
                self.derivation
                    .add_child(source_index, child_index, depth, u64::from(self.epoch))
            {
                // Roll back the table insertion to prevent a slot leak.
                self.table.force_invalidate(child_index);
                return Err(e);
            }
        }

        // Fix 5: consume GRANT_ONCE from the source after successful grant.
        if consume_grant_once {
            if let Ok(slot) = self.table.lookup_mut(source_index, source_generation) {
                let new_rights = slot.token.rights().difference(CapRights::GRANT_ONCE);
                slot.token = CapToken::new(
                    slot.token.id(),
                    slot.token.cap_type(),
                    new_rights,
                    slot.token.epoch(),
                );
            }
        }

        self.stats.caps_granted = self.stats.caps_granted.wrapping_add(1);
        if depth > self.stats.max_depth_reached {
            self.stats.max_depth_reached = depth;
        }

        Ok((child_index, child_generation))
    }

    /// Revokes a capability and all its descendants.
    ///
    /// # Errors
    ///
    /// Returns a [`CapError`] if the handle is invalid or already revoked.
    pub fn revoke(&mut self, index: u32, generation: u32) -> CapResult<RevokeResult> {
        let result = revoke_capability(&mut self.table, &mut self.derivation, index, generation)?;

        self.stats.caps_revoked = self
            .stats
            .caps_revoked
            .wrapping_add(result.revoked_count as u64);
        self.stats.revoke_operations = self.stats.revoke_operations.wrapping_add(1);

        Ok(result)
    }

    /// P1 verification: capability existence + rights check (< 1 us).
    ///
    /// # Errors
    ///
    /// Returns [`ProofError`] if the handle is invalid, stale, or lacks the required rights.
    pub fn verify_p1(
        &self,
        cap_index: u32,
        cap_generation: u32,
        required_rights: CapRights,
    ) -> Result<(), ProofError> {
        self.verifier
            .verify_p1(&self.table, cap_index, cap_generation, required_rights)
    }

    /// P2 verification: structural invariant validation (< 100 us).
    ///
    /// # Errors
    ///
    /// Returns [`ProofError::PolicyViolation`] if any structural check fails.
    pub fn verify_p2(
        &mut self,
        cap_index: u32,
        cap_generation: u32,
        ctx: &PolicyContext,
    ) -> Result<(), ProofError> {
        self.verifier.verify_p2(
            &self.table,
            &self.derivation,
            cap_index,
            cap_generation,
            ctx,
        )
    }

    /// P3: Deep proof — derivation chain integrity verification.
    ///
    /// Walks the derivation tree from the capability back to its root,
    /// verifying that every ancestor is valid, depth is monotonic, and
    /// epochs are non-decreasing.
    ///
    /// # Errors
    ///
    /// Returns [`ProofError::DerivationChainBroken`] if the chain is invalid.
    pub fn verify_p3(
        &self,
        cap_index: u32,
        cap_generation: u32,
        max_depth: u8,
    ) -> Result<(), ProofError> {
        self.verifier.verify_p3(
            &self.table,
            &self.derivation,
            cap_index,
            cap_generation,
            max_depth,
        )
    }

    /// Returns a reference to the underlying table.
    #[must_use]
    pub fn table(&self) -> &CapabilityTable<N> {
        &self.table
    }
}

impl<const N: usize> Default for CapabilityManager<N> {
    fn default() -> Self {
        Self::with_defaults()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::CapError;

    fn all_rights() -> CapRights {
        CapRights::READ
            .union(CapRights::WRITE)
            .union(CapRights::EXECUTE)
            .union(CapRights::GRANT)
            .union(CapRights::REVOKE)
    }

    #[test]
    fn test_create_root_capability() {
        let mut mgr = CapabilityManager::<64>::with_defaults();
        let owner = PartitionId::new(1);

        let (idx, gen) = mgr
            .create_root_capability(CapType::Region, all_rights(), 0, owner)
            .unwrap();

        assert_eq!(mgr.len(), 1);
        assert!(mgr.table().lookup(idx, gen).is_ok());
        assert_eq!(mgr.stats().caps_created, 1);
    }

    #[test]
    fn test_grant_and_verify() {
        let mut mgr = CapabilityManager::<64>::with_defaults();
        let owner = PartitionId::new(1);
        let target = PartitionId::new(2);

        let (root_idx, root_gen) = mgr
            .create_root_capability(CapType::Region, all_rights(), 0, owner)
            .unwrap();

        let (child_idx, child_gen) = mgr
            .grant(root_idx, root_gen, CapRights::READ, 42, target)
            .unwrap();

        assert_eq!(mgr.len(), 2);
        let child = mgr.table().lookup(child_idx, child_gen).unwrap();
        assert_eq!(child.token.rights(), CapRights::READ);
        assert_eq!(child.depth, 1);
    }

    #[test]
    fn test_revoke_propagation() {
        let mut mgr = CapabilityManager::<64>::with_defaults();
        let owner = PartitionId::new(1);
        let target = PartitionId::new(2);

        let (root_idx, root_gen) = mgr
            .create_root_capability(CapType::Region, all_rights(), 0, owner)
            .unwrap();

        let (c1_idx, c1_gen) = mgr
            .grant(
                root_idx,
                root_gen,
                CapRights::READ.union(CapRights::GRANT),
                1,
                target,
            )
            .unwrap();

        let _ = mgr
            .grant(c1_idx, c1_gen, CapRights::READ, 2, target)
            .unwrap();

        assert_eq!(mgr.len(), 3);
        let result = mgr.revoke(root_idx, root_gen).unwrap();
        assert_eq!(result.revoked_count, 3);
    }

    #[test]
    fn test_delegation_depth_limit() {
        let config = CapManagerConfig::new().with_max_depth(2);
        let mut mgr = CapabilityManager::<64>::new(config);
        let owner = PartitionId::new(1);

        let (i0, g0) = mgr
            .create_root_capability(CapType::Region, all_rights(), 0, owner)
            .unwrap();
        let (i1, g1) = mgr.grant(i0, g0, all_rights(), 1, owner).unwrap();
        let (i2, g2) = mgr.grant(i1, g1, all_rights(), 2, owner).unwrap();

        let result = mgr.grant(i2, g2, CapRights::READ, 3, owner);
        assert_eq!(result, Err(CapError::DelegationDepthExceeded));
    }

    #[test]
    fn test_epoch_invalidation() {
        let mut mgr = CapabilityManager::<64>::with_defaults();
        let owner = PartitionId::new(1);

        let (idx, gen) = mgr
            .create_root_capability(CapType::Region, all_rights(), 0, owner)
            .unwrap();
        assert!(mgr.verify_p1(idx, gen, CapRights::READ).is_ok());

        mgr.increment_epoch();
        assert_eq!(
            mgr.verify_p1(idx, gen, CapRights::READ),
            Err(ProofError::StaleCapability)
        );
    }

    #[test]
    fn test_p3_root_capability_passes() {
        let mut mgr = CapabilityManager::<64>::with_defaults();
        let owner = PartitionId::new(1);
        let (idx, gen) = mgr
            .create_root_capability(CapType::Region, all_rights(), 0, owner)
            .unwrap();

        // Root capability should pass P3 (trivial chain).
        assert!(mgr.verify_p3(idx, gen, 8).is_ok());
    }

    #[test]
    fn test_p3_nonexistent_fails() {
        let mgr = CapabilityManager::<64>::with_defaults();
        assert_eq!(
            mgr.verify_p3(99, 0, 8),
            Err(ProofError::DerivationChainBroken),
        );
    }

    #[test]
    fn test_create_root_checked_hypervisor_allowed() {
        let mut mgr = CapabilityManager::<64>::with_defaults();
        let owner = PartitionId::new(1);
        let result = mgr.create_root_capability_checked(
            CapType::Region,
            all_rights(),
            0,
            owner,
            PartitionId::hypervisor(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_root_checked_non_hypervisor_denied() {
        let mut mgr = CapabilityManager::<64>::with_defaults();
        let owner = PartitionId::new(1);
        let result = mgr.create_root_capability_checked(
            CapType::Region,
            all_rights(),
            0,
            owner,
            PartitionId::new(1), // non-hypervisor caller
        );
        assert_eq!(result, Err(CapError::GrantNotPermitted));
    }
}