Skip to main content

khive_capability/
capability.rs

1//! Keyed, process-local grants over one capability kernel.
2
3use std::collections::HashSet;
4
5use lion_core::state::RevocationState;
6use lion_core::{CapId, Capability, Kernel, PluginId, Right, Rights, SealedTag, SecurityLevel};
7
8use crate::error::KernelError;
9use crate::namespace::NamespaceMap;
10
11// Kernel-minted grants grow upward in the low half. Private anchors grow
12// downward in the high half; MAX cannot be a parent in the seal encoding.
13const PRIVATE_ID_START: CapId = 1_u128 << 127;
14
15/// Trusted grant management, separate from caller authorization at a wire boundary.
16///
17/// The manager owns one kernel and its process-local seal key. It does not expose
18/// raw insertion, mutable kernel access, or private bootstrap anchors as grants.
19pub struct CapabilityManager {
20    kernel: Kernel,
21    anchors: HashSet<CapId>,
22    next_anchor_id: CapId,
23}
24
25impl CapabilityManager {
26    /// Construct with caller-supplied random key bytes; an all-zero key is refused.
27    ///
28    /// The caller must obtain these bytes from a cryptographically suitable source.
29    /// It does not generate the seal key and cannot establish the supplied key's entropy.
30    pub fn with_key(key: [u8; 32]) -> Result<Self, KernelError> {
31        Ok(Self {
32            kernel: Kernel::with_key(key).map_err(|e| KernelError::Core(e.to_string()))?,
33            anchors: HashSet::new(),
34            next_anchor_id: CapId::MAX - 1,
35        })
36    }
37
38    pub fn register_actor(
39        &mut self,
40        plugin_id: PluginId,
41        level: SecurityLevel,
42    ) -> Result<(), KernelError> {
43        if plugin_id == 0 {
44            return Err(KernelError::Core("actor id must be nonzero".into()));
45        }
46        self.kernel
47            .register_plugin(plugin_id, level, 0)
48            .map_err(|e| KernelError::Core(e.to_string()))
49    }
50
51    /// Mint a sealed grant with exactly the requested nonempty rights.
52    ///
53    /// A private, unsealed anchor supplies this mint's namespace and rights. Only
54    /// the kernel-delegated, sealed child is returned. This is a library operation,
55    /// not a boot hook or an authorization decision for an untrusted caller.
56    pub fn mint(
57        &mut self,
58        plugin_id: PluginId,
59        namespace: &str,
60        rights: Rights,
61    ) -> Result<CapId, KernelError> {
62        self.require_actor(plugin_id)?;
63        if rights.is_empty() {
64            return Err(KernelError::DelegationFailed(
65                "rights cannot be empty".into(),
66            ));
67        }
68        self.ensure_grant_id_available()?;
69        let anchor_id = self.next_anchor_id;
70        if !(PRIVATE_ID_START..CapId::MAX).contains(&anchor_id) {
71            return Err(KernelError::IdSpaceExhausted);
72        }
73        let anchor = Capability::new(
74            anchor_id,
75            plugin_id,
76            NamespaceMap::resource_id(namespace),
77            rights,
78            None,
79            self.kernel.state().kernel().key_epoch(),
80            SealedTag::from_bytes([0; 32]),
81        )
82        .map_err(|e| KernelError::Core(e.to_string()))?;
83        self.kernel
84            .insert_cap_raw(anchor, plugin_id)
85            .map_err(|e| KernelError::Core(e.to_string()))?;
86        self.anchors.insert(anchor_id);
87        self.next_anchor_id -= 1;
88        self.kernel
89            .delegate_cap(anchor_id, plugin_id, rights)
90            .map_err(|e| KernelError::DelegationFailed(e.to_string()))
91    }
92
93    /// Compatibility name for [`Self::mint`]; the returned grant is now sealed.
94    ///
95    /// Its parent is a private anchor, not another publicly usable grant.
96    pub fn bootstrap_root_capability(
97        &mut self,
98        plugin_id: PluginId,
99        namespace: &str,
100        rights: Rights,
101    ) -> Result<CapId, KernelError> {
102        self.mint(plugin_id, namespace, rights)
103    }
104
105    /// Delegate from a current held grant; the kernel performs rights intersection.
106    ///
107    /// Management callers are trusted. This does not add a separate Delegate-bit
108    /// policy or authorize a wire caller to act on another actor's grant.
109    pub fn compose(
110        &mut self,
111        parent_cap_id: CapId,
112        target_plugin: PluginId,
113        requested_rights: Rights,
114    ) -> Result<CapId, KernelError> {
115        self.require_live_grant(parent_cap_id)?;
116        self.require_actor(target_plugin)?;
117        self.ensure_grant_id_available()?;
118        self.kernel
119            .delegate_cap(parent_cap_id, target_plugin, requested_rights)
120            .map_err(|e| KernelError::DelegationFailed(e.to_string()))
121    }
122
123    /// Read a canonical grant, including a revoked grant; private anchors are hidden.
124    pub fn get_cap(&self, cap_id: CapId) -> Option<&Capability> {
125        (cap_id < PRIVATE_ID_START)
126            .then(|| self.kernel.get_cap(cap_id))
127            .flatten()
128    }
129
130    /// Verify only the signed payload under this manager's process-local key.
131    ///
132    /// The kernel seal covers holder, target, rights, parent and epoch. It does not
133    /// cover the capability ID or mutable revocation flag. This predicate alone
134    /// does not establish table membership, a holder's authority or liveness.
135    pub fn verify_seal(&self, cap: &Capability) -> bool {
136        // The core's parent encoding uses parent + 1; reject its sentinel before
137        // invoking that encoding on a caller-supplied capability.
138        cap.parent() != Some(CapId::MAX) && self.kernel.state().kernel().verify_cap_seal(cap)
139    }
140
141    /// Check the stored grant and every ancestor, ending at a known private anchor.
142    ///
143    /// This checks current liveness. Use [`Self::validate`] for holder, seal,
144    /// namespace and right checks together. A later protected write still needs
145    /// its own synchronization with revocation; this predicate is not a transaction.
146    pub fn is_live(&self, cap_id: CapId) -> bool {
147        chain_is_live(
148            self.kernel.state().kernel().revocation(),
149            &self.anchors,
150            cap_id,
151        )
152    }
153
154    pub fn validate(
155        &self,
156        plugin_id: PluginId,
157        cap_id: CapId,
158        namespace: &str,
159        required_right: Right,
160    ) -> Result<(), KernelError> {
161        if !self.kernel.plugin_holds(plugin_id, cap_id) {
162            return Err(KernelError::InsufficientRights {
163                needed: format!("{required_right}"),
164                have: "no capability held".into(),
165            });
166        }
167        let cap = self.require_live_grant(cap_id)?;
168        if cap.holder() != plugin_id {
169            return Err(KernelError::InsufficientRights {
170                needed: format!("{required_right}"),
171                have: "capability belongs to another actor".into(),
172            });
173        }
174        if cap.target() != NamespaceMap::resource_id(namespace) {
175            return Err(KernelError::NamespaceDenied(namespace.to_string()));
176        }
177        if !cap.has_right(required_right) {
178            return Err(KernelError::InsufficientRights {
179                needed: format!("{required_right}"),
180                have: format!("{}", cap.rights()),
181            });
182        }
183        Ok(())
184    }
185
186    pub fn revoke(&mut self, cap_id: CapId) -> Result<(), KernelError> {
187        self.get_cap(cap_id)
188            .ok_or(KernelError::CapabilityRevoked(cap_id))?;
189        self.kernel
190            .revoke_cap(cap_id)
191            .map_err(|e| KernelError::Core(e.to_string()))
192    }
193
194    fn require_actor(&self, plugin_id: PluginId) -> Result<(), KernelError> {
195        if plugin_id == 0 || self.kernel.plugin_level(plugin_id).is_none() {
196            return Err(KernelError::UnknownActor(plugin_id.to_string()));
197        }
198        Ok(())
199    }
200
201    fn ensure_grant_id_available(&self) -> Result<(), KernelError> {
202        if self.kernel.state().kernel().next_cap_id() >= PRIVATE_ID_START {
203            return Err(KernelError::IdSpaceExhausted);
204        }
205        Ok(())
206    }
207
208    fn require_live_grant(&self, cap_id: CapId) -> Result<&Capability, KernelError> {
209        let cap = self
210            .get_cap(cap_id)
211            .ok_or(KernelError::CapabilityRevoked(cap_id))?;
212        if !self.kernel.plugin_holds(cap.holder(), cap_id) {
213            return Err(KernelError::UnknownActor(cap.holder().to_string()));
214        }
215        if !self.verify_seal(cap) {
216            return Err(KernelError::InvalidSeal(cap_id));
217        }
218        if !self.is_live(cap_id) {
219            return Err(KernelError::CapabilityRevoked(cap_id));
220        }
221        Ok(cap)
222    }
223}
224
225// Use table size, not numeric IDs, to bound traversal. Anchors have high IDs and
226// grants have low IDs, so a parent-less-than-child assumption does not apply.
227fn chain_is_live(state: &RevocationState, anchors: &HashSet<CapId>, cap_id: CapId) -> bool {
228    if cap_id >= PRIVATE_ID_START {
229        return false;
230    }
231    let mut current = cap_id;
232    for _ in 0..state.cap_count() {
233        let Some(cap) = state.get(current) else {
234            return false;
235        };
236        if !cap.is_valid() {
237            return false;
238        }
239        if anchors.contains(&current) {
240            return current >= PRIVATE_ID_START && current != CapId::MAX && cap.parent().is_none();
241        }
242        if current >= PRIVATE_ID_START {
243            return false;
244        }
245        match cap.parent() {
246            Some(parent) => current = parent,
247            None => return false,
248        }
249    }
250    false
251}
252
253#[cfg(test)]
254#[path = "capability_tests.rs"]
255mod tests;