capsec-core 0.2.2

Core capability types for compile-time capability-based security in Rust
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
//! Capability prescripts: audit-trail and dual-authorization wrappers.
//!
//! [`LoggedCap<P>`] wraps a [`Cap<P>`](crate::cap::Cap) with an append-only audit log
//! that records every [`try_cap()`](LoggedCap::try_cap) invocation.
//! [`DualKeyCap<P>`] wraps a `Cap<P>` with a dual-authorization gate that requires
//! two independent approvals before [`try_cap()`](DualKeyCap::try_cap) succeeds.
//!
//! Neither type implements [`Has<P>`](crate::has::Has) — callers must use `try_cap()`
//! and handle the fallible result explicitly.
//!
//! These types implement Saltzer & Schroeder's "prescript" concept — actions
//! triggered before capability exercise — specifically Design Principle #5
//! (Separation of Privilege) and #8 (Compromise Recording).

use crate::cap::Cap;
use crate::error::CapSecError;
use crate::permission::Permission;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;

// ============================================================================
// LogEntry
// ============================================================================

/// A record of a single capability exercise attempt.
///
/// Created automatically by [`LoggedCap::try_cap`] and stored in the
/// shared audit log.
#[derive(Debug, Clone)]
pub struct LogEntry {
    /// Monotonic timestamp of the exercise attempt.
    pub timestamp: Instant,
    /// The permission type name (via [`std::any::type_name`]).
    pub permission: &'static str,
    /// Whether the capability was granted (`true`) or denied (`false`).
    pub granted: bool,
}

// ============================================================================
// LoggedCap<P>
// ============================================================================

/// An audited capability token that logs every exercise attempt.
///
/// Created via [`LoggedCap::new`], which consumes a [`Cap<P>`] as proof of
/// possession. Every call to [`try_cap`](LoggedCap::try_cap) appends a
/// [`LogEntry`] to the shared audit log.
///
/// `!Send + !Sync` by default — use [`make_send`](LoggedCap::make_send) for
/// cross-thread transfer. Cloning shares the same audit log: entries from
/// any clone appear in the same log.
pub struct LoggedCap<P: Permission> {
    _phantom: PhantomData<P>,
    _not_send: PhantomData<*const ()>,
    log: Arc<Mutex<Vec<LogEntry>>>,
}

impl<P: Permission> LoggedCap<P> {
    /// Creates an audited capability by consuming a [`Cap<P>`] as proof of possession.
    pub fn new(_cap: Cap<P>) -> Self {
        Self {
            _phantom: PhantomData,
            _not_send: PhantomData,
            log: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Attempts to obtain a [`Cap<P>`] and records the attempt in the audit log.
    ///
    /// Always succeeds (since `LoggedCap` wraps a `Cap<P>` directly). The
    /// `granted` field in the log entry is always `true`.
    pub fn try_cap(&self) -> Result<Cap<P>, CapSecError> {
        let entry = LogEntry {
            timestamp: Instant::now(),
            permission: std::any::type_name::<P>(),
            granted: true,
        };
        let mut log = self.log.lock().unwrap_or_else(|e| e.into_inner());
        log.push(entry);
        Ok(Cap::new())
    }

    /// Advisory check — always returns `true` for `LoggedCap`.
    pub fn is_active(&self) -> bool {
        true
    }

    /// Returns a cloned snapshot of the audit log.
    pub fn entries(&self) -> Vec<LogEntry> {
        let log = self.log.lock().unwrap_or_else(|e| e.into_inner());
        log.clone()
    }

    /// Returns the number of entries in the audit log.
    pub fn entry_count(&self) -> usize {
        let log = self.log.lock().unwrap_or_else(|e| e.into_inner());
        log.len()
    }

    /// Converts this capability into a [`LoggedSendCap`] that can cross thread boundaries.
    pub fn make_send(self) -> LoggedSendCap<P> {
        LoggedSendCap {
            _phantom: PhantomData,
            log: self.log,
        }
    }
}

impl<P: Permission> Clone for LoggedCap<P> {
    fn clone(&self) -> Self {
        Self {
            _phantom: PhantomData,
            _not_send: PhantomData,
            log: Arc::clone(&self.log),
        }
    }
}

// ============================================================================
// LoggedSendCap<P>
// ============================================================================

/// A thread-safe audited capability token.
///
/// Created via [`LoggedCap::make_send`]. Unlike [`LoggedCap`], this implements
/// `Send + Sync`, making it usable with `std::thread::spawn`, `tokio::spawn`, etc.
pub struct LoggedSendCap<P: Permission> {
    _phantom: PhantomData<P>,
    log: Arc<Mutex<Vec<LogEntry>>>,
}

// SAFETY: LoggedSendCap is explicitly opted into cross-thread transfer via make_send().
// The inner Arc<Mutex<Vec<LogEntry>>> is already Send+Sync.
unsafe impl<P: Permission> Send for LoggedSendCap<P> {}
unsafe impl<P: Permission> Sync for LoggedSendCap<P> {}

impl<P: Permission> LoggedSendCap<P> {
    /// Attempts to obtain a [`Cap<P>`] and records the attempt in the audit log.
    pub fn try_cap(&self) -> Result<Cap<P>, CapSecError> {
        let entry = LogEntry {
            timestamp: Instant::now(),
            permission: std::any::type_name::<P>(),
            granted: true,
        };
        let mut log = self.log.lock().unwrap_or_else(|e| e.into_inner());
        log.push(entry);
        Ok(Cap::new())
    }

    /// Advisory check — always returns `true`.
    pub fn is_active(&self) -> bool {
        true
    }

    /// Returns a cloned snapshot of the audit log.
    pub fn entries(&self) -> Vec<LogEntry> {
        let log = self.log.lock().unwrap_or_else(|e| e.into_inner());
        log.clone()
    }

    /// Returns the number of entries in the audit log.
    pub fn entry_count(&self) -> usize {
        let log = self.log.lock().unwrap_or_else(|e| e.into_inner());
        log.len()
    }
}

impl<P: Permission> Clone for LoggedSendCap<P> {
    fn clone(&self) -> Self {
        Self {
            _phantom: PhantomData,
            log: Arc::clone(&self.log),
        }
    }
}

// ============================================================================
// DualKeyCap<P>
// ============================================================================

/// A dual-authorization capability requiring two independent approvals.
///
/// Created via [`DualKeyCap::new`], which consumes a [`Cap<P>`] and returns
/// a `(DualKeyCap<P>, ApproverA, ApproverB)` triple. Both approvers must call
/// [`approve()`](ApproverA::approve) before [`try_cap()`](DualKeyCap::try_cap)
/// will succeed.
///
/// Implements Saltzer & Schroeder's Separation of Privilege principle:
/// no single entity can exercise the capability alone.
///
/// `!Send + !Sync` by default — use [`make_send`](DualKeyCap::make_send) for
/// cross-thread transfer. Cloning shares the same approval state.
pub struct DualKeyCap<P: Permission> {
    _phantom: PhantomData<P>,
    _not_send: PhantomData<*const ()>,
    approvals: Arc<AtomicU8>,
}

impl<P: Permission> DualKeyCap<P> {
    /// Creates a dual-authorization capability by consuming a [`Cap<P>`].
    ///
    /// Returns a `(DualKeyCap<P>, ApproverA, ApproverB)` triple. Distribute
    /// the approver handles to separate subsystems to enforce separation of
    /// privilege.
    pub fn new(_cap: Cap<P>) -> (Self, ApproverA, ApproverB) {
        let approvals = Arc::new(AtomicU8::new(0));
        let cap = Self {
            _phantom: PhantomData,
            _not_send: PhantomData,
            approvals: Arc::clone(&approvals),
        };
        let a = ApproverA {
            approvals: Arc::clone(&approvals),
        };
        let b = ApproverB { approvals };
        (cap, a, b)
    }

    /// Attempts to obtain a [`Cap<P>`] from this dual-authorization capability.
    ///
    /// Returns `Ok(Cap<P>)` if both approvers have called [`approve()`](ApproverA::approve),
    /// or `Err(CapSecError::InsufficientApprovals)` if not.
    pub fn try_cap(&self) -> Result<Cap<P>, CapSecError> {
        if self.approvals.load(Ordering::Acquire) == 3 {
            Ok(Cap::new())
        } else {
            Err(CapSecError::InsufficientApprovals)
        }
    }

    /// Advisory check — returns `true` if both approvals have been granted.
    pub fn is_active(&self) -> bool {
        self.approvals.load(Ordering::Acquire) == 3
    }

    /// Converts this capability into a [`DualKeySendCap`] that can cross thread boundaries.
    pub fn make_send(self) -> DualKeySendCap<P> {
        DualKeySendCap {
            _phantom: PhantomData,
            approvals: self.approvals,
        }
    }
}

impl<P: Permission> Clone for DualKeyCap<P> {
    fn clone(&self) -> Self {
        Self {
            _phantom: PhantomData,
            _not_send: PhantomData,
            approvals: Arc::clone(&self.approvals),
        }
    }
}

// ============================================================================
// DualKeySendCap<P>
// ============================================================================

/// A thread-safe dual-authorization capability token.
///
/// Created via [`DualKeyCap::make_send`]. Unlike [`DualKeyCap`], this implements
/// `Send + Sync`.
pub struct DualKeySendCap<P: Permission> {
    _phantom: PhantomData<P>,
    approvals: Arc<AtomicU8>,
}

// SAFETY: DualKeySendCap is explicitly opted into cross-thread transfer via make_send().
// The inner Arc<AtomicU8> is already Send+Sync.
unsafe impl<P: Permission> Send for DualKeySendCap<P> {}
unsafe impl<P: Permission> Sync for DualKeySendCap<P> {}

impl<P: Permission> DualKeySendCap<P> {
    /// Attempts to obtain a [`Cap<P>`] from this dual-authorization capability.
    pub fn try_cap(&self) -> Result<Cap<P>, CapSecError> {
        if self.approvals.load(Ordering::Acquire) == 3 {
            Ok(Cap::new())
        } else {
            Err(CapSecError::InsufficientApprovals)
        }
    }

    /// Advisory check — returns `true` if both approvals have been granted.
    pub fn is_active(&self) -> bool {
        self.approvals.load(Ordering::Acquire) == 3
    }
}

impl<P: Permission> Clone for DualKeySendCap<P> {
    fn clone(&self) -> Self {
        Self {
            _phantom: PhantomData,
            approvals: Arc::clone(&self.approvals),
        }
    }
}

// ============================================================================
// ApproverA / ApproverB
// ============================================================================

/// First approval handle for a [`DualKeyCap`].
///
/// `Send + Sync` so it can be passed to another thread or subsystem.
/// **Not `Clone`** — each approver handle is unique to enforce separation
/// of privilege. Distribute `ApproverA` and `ApproverB` to different
/// principals.
pub struct ApproverA {
    approvals: Arc<AtomicU8>,
}

impl ApproverA {
    /// Records approval from the first authority. Idempotent.
    pub fn approve(&self) {
        self.approvals.fetch_or(0b01, Ordering::Release);
    }

    /// Returns `true` if this approver has already approved.
    pub fn is_approved(&self) -> bool {
        self.approvals.load(Ordering::Acquire) & 0b01 != 0
    }
}

/// Second approval handle for a [`DualKeyCap`].
///
/// `Send + Sync` so it can be passed to another thread or subsystem.
/// **Not `Clone`** — each approver handle is unique to enforce separation
/// of privilege.
pub struct ApproverB {
    approvals: Arc<AtomicU8>,
}

impl ApproverB {
    /// Records approval from the second authority. Idempotent.
    pub fn approve(&self) {
        self.approvals.fetch_or(0b10, Ordering::Release);
    }

    /// Returns `true` if this approver has already approved.
    pub fn is_approved(&self) -> bool {
        self.approvals.load(Ordering::Acquire) & 0b10 != 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::permission::FsRead;
    use std::mem::size_of;

    // ====== LoggedCap tests ======

    #[test]
    fn logged_cap_try_cap_succeeds() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let lcap = LoggedCap::new(cap);
        assert!(lcap.try_cap().is_ok());
    }

    #[test]
    fn logged_cap_records_entry() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let lcap = LoggedCap::new(cap);
        let _ = lcap.try_cap();
        let entries = lcap.entries();
        assert_eq!(entries.len(), 1);
        assert!(entries[0].permission.contains("FsRead"));
        assert!(entries[0].granted);
    }

    #[test]
    fn logged_cap_multiple_entries() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let lcap = LoggedCap::new(cap);
        let _ = lcap.try_cap();
        let _ = lcap.try_cap();
        let _ = lcap.try_cap();
        assert_eq!(lcap.entry_count(), 3);
    }

    #[test]
    fn logged_cap_entries_snapshot() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let lcap = LoggedCap::new(cap);
        let _ = lcap.try_cap();
        let snapshot = lcap.entries();
        let _ = lcap.try_cap();
        // Snapshot should still have 1 entry, live log has 2
        assert_eq!(snapshot.len(), 1);
        assert_eq!(lcap.entry_count(), 2);
    }

    #[test]
    fn logged_send_cap_crosses_threads() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let lcap = LoggedCap::new(cap);
        let send_cap = lcap.make_send();

        std::thread::spawn(move || {
            assert!(send_cap.try_cap().is_ok());
        })
        .join()
        .unwrap();
    }

    #[test]
    fn cloned_logged_cap_shares_log() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let lcap = LoggedCap::new(cap);
        let lcap2 = lcap.clone();

        let _ = lcap.try_cap();
        let _ = lcap2.try_cap();

        assert_eq!(lcap.entry_count(), 2);
        assert_eq!(lcap2.entry_count(), 2);
    }

    #[test]
    fn logged_cap_is_small() {
        assert!(size_of::<LoggedCap<FsRead>>() <= 2 * size_of::<usize>());
    }

    #[test]
    fn logged_cap_entry_has_correct_permission_name() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let lcap = LoggedCap::new(cap);
        let _ = lcap.try_cap();
        let entries = lcap.entries();
        assert!(entries[0].permission.contains("FsRead"));
    }

    // ====== DualKeyCap tests ======

    #[test]
    fn dual_key_try_cap_fails_without_approvals() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let (dcap, _a, _b) = DualKeyCap::new(cap);
        assert!(matches!(
            dcap.try_cap(),
            Err(CapSecError::InsufficientApprovals)
        ));
    }

    #[test]
    fn dual_key_try_cap_fails_with_one_approval() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let (dcap, a, _b) = DualKeyCap::new(cap);
        a.approve();
        assert!(matches!(
            dcap.try_cap(),
            Err(CapSecError::InsufficientApprovals)
        ));
    }

    #[test]
    fn dual_key_try_cap_succeeds_with_both_approvals() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let (dcap, a, b) = DualKeyCap::new(cap);
        a.approve();
        b.approve();
        assert!(dcap.try_cap().is_ok());
    }

    #[test]
    fn dual_key_approval_order_irrelevant() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let (dcap, a, b) = DualKeyCap::new(cap);
        b.approve();
        a.approve();
        assert!(dcap.try_cap().is_ok());
    }

    #[test]
    fn dual_key_approve_is_idempotent() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let (dcap, a, _b) = DualKeyCap::new(cap);
        a.approve();
        a.approve(); // should not panic
        // Still needs B
        assert!(matches!(
            dcap.try_cap(),
            Err(CapSecError::InsufficientApprovals)
        ));
    }

    #[test]
    fn dual_key_approvers_are_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<ApproverA>();
        assert_send_sync::<ApproverB>();
    }

    #[test]
    fn dual_key_send_cap_crosses_threads() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let (dcap, a, b) = DualKeyCap::new(cap);
        a.approve();
        b.approve();
        let send_cap = dcap.make_send();

        std::thread::spawn(move || {
            assert!(send_cap.try_cap().is_ok());
        })
        .join()
        .unwrap();
    }

    #[test]
    fn dual_key_approval_crosses_threads() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let (dcap, a, b) = DualKeyCap::new(cap);

        a.approve();

        std::thread::spawn(move || {
            b.approve();
        })
        .join()
        .unwrap();

        assert!(dcap.try_cap().is_ok());
    }

    #[test]
    fn cloned_dual_key_shares_approval() {
        let root = crate::root::test_root();
        let cap = root.grant::<FsRead>();
        let (dcap, a, b) = DualKeyCap::new(cap);
        let dcap2 = dcap.clone();

        a.approve();
        b.approve();

        assert!(dcap.try_cap().is_ok());
        assert!(dcap2.try_cap().is_ok());
    }

    #[test]
    fn dual_key_cap_is_small() {
        assert!(size_of::<DualKeyCap<FsRead>>() <= 2 * size_of::<usize>());
    }
}