khive_capability/
capability.rs1use 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
11const PRIVATE_ID_START: CapId = 1_u128 << 127;
14
15pub struct CapabilityManager {
20 kernel: Kernel,
21 anchors: HashSet<CapId>,
22 next_anchor_id: CapId,
23}
24
25impl CapabilityManager {
26 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 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 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 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 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 pub fn verify_seal(&self, cap: &Capability) -> bool {
136 cap.parent() != Some(CapId::MAX) && self.kernel.state().kernel().verify_cap_seal(cap)
139 }
140
141 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
225fn 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(¤t) {
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;