interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / caps.rs

497 lines · 17664 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Fixed-capacity capability handles with generation checks and revocation.
17//!
18//! The task table below is unchanged. The native authority, with subject,
19//! epoch, lease, a 64-bit resource, and an office that cognition cannot hold,
20//! is [`aienos_capability`] re-exported here.
21
22pub use crate::abi::Handle;
23
24pub use aienos_capability::{
25 add_u64 as authority_add_u64, generation_advance as authority_generation_advance,
26 narrow_resource, widen_resource, AuthorityAdmin, AuthorityState, AuthorityView, CapRef,
27 Entry as AuthorityEntry, Mint as AuthorityMint, CAP_MAX as AUTHORITY_CAP_MAX,
28 ERR_AMPLIFY as AUTHORITY_ERR_AMPLIFY, ERR_CHAIN as AUTHORITY_ERR_CHAIN,
29 ERR_EPOCH as AUTHORITY_ERR_EPOCH, ERR_EXHAUSTED as AUTHORITY_ERR_EXHAUSTED,
30 ERR_EXPIRED as AUTHORITY_ERR_EXPIRED, ERR_RESOURCE as AUTHORITY_ERR_RESOURCE,
31 ERR_STALE_GEN as AUTHORITY_ERR_STALE_GEN, ERR_SUBJECT as AUTHORITY_ERR_SUBJECT,
32 ERR_UNAUTHORIZED as AUTHORITY_ERR_UNAUTHORIZED, RES_AUTHORITY, RIGHT_DELEGATE,
33 RIGHT_PRIVILEGED,
34};
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct Rights(u8);
38
39impl Rights {
40 pub const NONE: Self = Self(0);
41 pub const READ: Self = Self(1 << 0);
42 pub const WRITE: Self = Self(1 << 1);
43 pub const MAP: Self = Self(1 << 2);
44 pub const GRANT: Self = Self(1 << 3);
45 pub const DERIVE: Self = Self(1 << 4);
46 pub const REVOKE: Self = Self(1 << 5);
47 const ALL: u8 = (1 << 6) - 1;
48
49 pub const fn from_bits(bits: u8) -> Option<Self> {
50 if bits & !Self::ALL == 0 {
51 Some(Self(bits))
52 } else {
53 None
54 }
55 }
56 pub const fn bits(self) -> u8 {
57 self.0
58 }
59 pub const fn contains(self, other: Self) -> bool {
60 self.0 & other.0 == other.0
61 }
62 pub const fn is_subset_of(self, other: Self) -> bool {
63 other.contains(self)
64 }
65}
66
67impl core::ops::BitOr for Rights {
68 type Output = Self;
69 fn bitor(self, rhs: Self) -> Self {
70 Self(self.0 | rhs.0)
71 }
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub enum CapError {
76 Full,
77 InvalidHandle,
78 MissingRights,
79 RightsEscalation,
80 DuplicateTable,
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84struct Location {
85 table: u32,
86 handle: Handle,
87}
88
89#[derive(Clone, Copy)]
90struct Slot {
91 generation: u32,
92 resource: u32,
93 rights: Rights,
94 parent: Option<Location>,
95 /// Something was derived from this capability (possibly into another table).
96 derived: bool,
97 /// Removed by its holder but kept so descendants' parent chains stay
98 /// intact for revocation. Invisible to every operation except revocation.
99 tombstone: bool,
100}
101
102/// A task's capability table. `id` must be unique among tables passed to
103/// cross-table operations; resource IDs are opaque to this data structure.
104pub struct CapTable<const N: usize> {
105 id: u32,
106 slots: [Option<Slot>; N],
107 generations: [u32; N],
108}
109
110impl<const N: usize> CapTable<N> {
111 pub const fn new(id: u32) -> Self {
112 Self {
113 id,
114 slots: [None; N],
115 generations: [0; N],
116 }
117 }
118
119 pub const fn id(&self) -> u32 {
120 self.id
121 }
122
123 /// Occupied slots, including tombstones kept for revocation.
124 pub fn live_count(&self) -> usize {
125 self.slots.iter().filter(|slot| slot.is_some()).count()
126 }
127
128 pub fn insert(&mut self, resource: u32, rights: Rights) -> Result<Handle, CapError> {
129 self.allocate(resource, rights, None)
130 }
131
132 fn allocate(
133 &mut self,
134 resource: u32,
135 rights: Rights,
136 parent: Option<Location>,
137 ) -> Result<Handle, CapError> {
138 let index = self
139 .slots
140 .iter()
141 .enumerate()
142 .find_map(|(index, slot)| {
143 (slot.is_none() && self.generations[index] != u32::MAX).then_some(index)
144 })
145 .ok_or(CapError::Full)?;
146 let generation = self.generations[index] + 1;
147 self.generations[index] = generation;
148 self.slots[index] = Some(Slot {
149 generation,
150 resource,
151 rights,
152 parent,
153 derived: false,
154 tombstone: false,
155 });
156 Ok(Handle {
157 index: index as u32,
158 generation,
159 })
160 }
161
162 /// A live capability (tombstones are invisible).
163 fn slot(&self, handle: Handle) -> Result<&Slot, CapError> {
164 self.slot_any(handle)
165 .filter(|slot| !slot.tombstone)
166 .ok_or(CapError::InvalidHandle)
167 }
168
169 /// Any occupied slot, including tombstones (for ancestry walks only).
170 fn slot_any(&self, handle: Handle) -> Option<&Slot> {
171 self.slots
172 .get(handle.index as usize)
173 .and_then(Option::as_ref)
174 .filter(|slot| slot.generation == handle.generation)
175 }
176
177 pub fn lookup(&self, handle: Handle, required_rights: Rights) -> Result<u32, CapError> {
178 let slot = self.slot(handle)?;
179 if !slot.rights.contains(required_rights) {
180 return Err(CapError::MissingRights);
181 }
182 Ok(slot.resource)
183 }
184
185 pub fn rights(&self, handle: Handle) -> Result<Rights, CapError> {
186 Ok(self.slot(handle)?.rights)
187 }
188
189 /// Drop this handle. Descendants are not revoked (use `revoke` for that),
190 /// but a capability that has been derived from becomes a tombstone rather
191 /// than a free slot, so its descendants stay reachable from any ancestor's
192 /// `revoke`. Freeing it would break their parent chains and leave the
193 /// subtree unrevocable from above.
194 pub fn remove(&mut self, handle: Handle) -> Result<(), CapError> {
195 let derived = self.slot(handle)?.derived;
196 let index = handle.index as usize;
197 if derived {
198 if let Some(slot) = self.slots[index].as_mut() {
199 slot.tombstone = true;
200 }
201 } else {
202 self.slots[index] = None;
203 }
204 Ok(())
205 }
206
207 pub fn derive(&mut self, handle: Handle, rights: Rights) -> Result<Handle, CapError> {
208 let source = *self.slot(handle)?;
209 if !source.rights.contains(Rights::DERIVE) {
210 return Err(CapError::MissingRights);
211 }
212 if !rights.is_subset_of(source.rights) {
213 return Err(CapError::RightsEscalation);
214 }
215 let child = self.allocate(
216 source.resource,
217 rights,
218 Some(Location {
219 table: self.id,
220 handle,
221 }),
222 )?;
223 if let Some(slot) = self.slots[handle.index as usize].as_mut() {
224 slot.derived = true;
225 }
226 Ok(child)
227 }
228
229 /// Derive into another table, retaining a parent link for tree revocation.
230 pub fn derive_into<const M: usize>(
231 from: &mut Self,
232 handle: Handle,
233 to: &mut CapTable<M>,
234 rights: Rights,
235 ) -> Result<Handle, CapError> {
236 let source = *from.slot(handle)?;
237 if !source.rights.contains(Rights::DERIVE) {
238 return Err(CapError::MissingRights);
239 }
240 if !rights.is_subset_of(source.rights) {
241 return Err(CapError::RightsEscalation);
242 }
243 let parent = Location {
244 table: from.id,
245 handle,
246 };
247 let child = to.allocate(source.resource, rights, Some(parent))?;
248 if let Some(slot) = from.slots[handle.index as usize].as_mut() {
249 slot.derived = true;
250 }
251 Ok(child)
252 }
253
254 pub fn transfer<const M: usize>(
255 from: &mut Self,
256 handle: Handle,
257 to: &mut CapTable<M>,
258 ) -> Result<Handle, CapError> {
259 let source = *from.slot(handle)?;
260 if !source.rights.contains(Rights::GRANT) {
261 return Err(CapError::MissingRights);
262 }
263 to.allocate(source.resource, source.rights, None)
264 }
265
266 /// Remove a capability and all descendants found in the supplied table set.
267 /// The caller supplies every table that may contain descendants.
268 pub fn revoke<const M: usize>(
269 table_id: u32,
270 handle: Handle,
271 tables: &mut [&mut CapTable<M>],
272 ) -> Result<(), CapError> {
273 if tables.iter().filter(|table| table.id == table_id).count() != 1 {
274 return Err(CapError::DuplicateTable);
275 }
276 let root_index = tables
277 .iter()
278 .position(|table| table.id == table_id)
279 .unwrap();
280 if !tables[root_index]
281 .slot(handle)?
282 .rights
283 .contains(Rights::REVOKE)
284 {
285 return Err(CapError::MissingRights);
286 }
287 let root = Location {
288 table: table_id,
289 handle,
290 };
291 let capacity = M.saturating_mul(tables.len());
292
293 // Validate every parent chain before changing any slot. The table set
294 // bounds each walk, including malformed cyclic derivation metadata.
295 for table in tables.iter() {
296 for (index, slot) in table.slots.iter().enumerate() {
297 if slot.is_some() {
298 let start = Location {
299 table: table.id,
300 handle: Handle {
301 index: index as u32,
302 generation: slot.unwrap().generation,
303 },
304 };
305 let _ = Self::revocation_depth(start, root, tables, capacity)?;
306 }
307 }
308 }
309
310 // Remove deepest descendants first so their parent chains remain
311 // available while calculating the shallower depths.
312 for _ in 0..capacity {
313 let mut deepest: Option<(Location, usize)> = None;
314 for table in tables.iter() {
315 for (index, slot) in table.slots.iter().enumerate() {
316 if let Some(slot) = slot {
317 let loc = Location {
318 table: table.id,
319 handle: Handle {
320 index: index as u32,
321 generation: slot.generation,
322 },
323 };
324 if let Some(depth) = Self::revocation_depth(loc, root, tables, capacity)? {
325 if deepest.is_none_or(|(_, deepest_depth)| depth > deepest_depth) {
326 deepest = Some((loc, depth));
327 }
328 }
329 }
330 }
331 }
332 let Some((loc, _)) = deepest else { break };
333 let table = tables
334 .iter_mut()
335 .find(|table| table.id == loc.table)
336 .unwrap();
337 table.slots[loc.handle.index as usize] = None;
338 }
339 Ok(())
340 }
341
342 fn revocation_depth<const M: usize>(
343 mut current: Location,
344 root: Location,
345 tables: &[&mut CapTable<M>],
346 capacity: usize,
347 ) -> Result<Option<usize>, CapError> {
348 for depth in 0..=capacity {
349 if current == root {
350 return Ok(Some(depth));
351 }
352 let Some(table) = tables.iter().find(|table| table.id == current.table) else {
353 return Ok(None);
354 };
355 // Walk through tombstones: they keep removed ancestors' links.
356 let Some(slot) = table.slot_any(current.handle) else {
357 return Ok(None);
358 };
359 let Some(parent) = slot.parent else {
360 return Ok(None);
361 };
362 current = parent;
363 }
364 Err(CapError::Full)
365 }
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371
372 #[test]
373 fn stale_handle_rejected_after_slot_reuse() {
374 let mut table = CapTable::<1>::new(1);
375 let old = table.insert(7, Rights::READ).unwrap();
376 table.remove(old).unwrap();
377 let new = table.insert(8, Rights::READ).unwrap();
378 assert_ne!(old.generation, new.generation);
379 assert_eq!(
380 table.lookup(old, Rights::READ),
381 Err(CapError::InvalidHandle)
382 );
383 }
384
385 #[test]
386 fn generation_exhaustion_retires_slot_without_reviving_old_handle() {
387 let mut table = CapTable::<2>::new(1);
388 let old = table.insert(7, Rights::READ).unwrap();
389 table.generations[old.index as usize] = u32::MAX - 1;
390 table.remove(old).unwrap();
391
392 let final_handle = table.insert(8, Rights::READ).unwrap();
393 assert_eq!(final_handle.index, old.index);
394 assert_eq!(final_handle.generation, u32::MAX);
395 table.remove(final_handle).unwrap();
396
397 let replacement = table.insert(9, Rights::READ).unwrap();
398 assert_ne!(replacement.index, old.index);
399 assert_eq!(
400 table.lookup(old, Rights::READ),
401 Err(CapError::InvalidHandle)
402 );
403 assert_eq!(
404 table.lookup(final_handle, Rights::READ),
405 Err(CapError::InvalidHandle)
406 );
407 }
408
409 #[test]
410 fn derive_cannot_add_rights() {
411 let mut table = CapTable::<3>::new(1);
412 let parent = table.insert(7, Rights::READ | Rights::DERIVE).unwrap();
413 assert_eq!(
414 table.derive(parent, Rights::READ | Rights::WRITE),
415 Err(CapError::RightsEscalation)
416 );
417 let child = table.derive(parent, Rights::READ).unwrap();
418 assert_eq!(table.rights(child), Ok(Rights::READ));
419 }
420
421 #[test]
422 fn revoke_cascades_two_levels_across_tables() {
423 let mut a = CapTable::<4>::new(1);
424 let mut b = CapTable::<4>::new(2);
425 let root = a
426 .insert(7, Rights::READ | Rights::DERIVE | Rights::REVOKE)
427 .unwrap();
428 let child =
429 CapTable::derive_into(&mut a, root, &mut b, Rights::READ | Rights::DERIVE).unwrap();
430 let grandchild = b.derive(child, Rights::READ).unwrap();
431 CapTable::<4>::revoke(1, root, &mut [&mut a, &mut b]).unwrap();
432 assert_eq!(a.lookup(root, Rights::READ), Err(CapError::InvalidHandle));
433 assert_eq!(b.lookup(child, Rights::READ), Err(CapError::InvalidHandle));
434 assert_eq!(
435 b.lookup(grandchild, Rights::READ),
436 Err(CapError::InvalidHandle)
437 );
438 }
439
440 #[test]
441 fn revoke_with_single_slot_tables_removes_cross_table_child() {
442 let mut a = CapTable::<1>::new(1);
443 let mut b = CapTable::<1>::new(2);
444 let root = a
445 .insert(7, Rights::READ | Rights::DERIVE | Rights::REVOKE)
446 .unwrap();
447 let child = CapTable::derive_into(&mut a, root, &mut b, Rights::READ).unwrap();
448
449 CapTable::<1>::revoke(1, root, &mut [&mut a, &mut b]).unwrap();
450
451 assert_eq!(a.lookup(root, Rights::READ), Err(CapError::InvalidHandle));
452 assert_eq!(b.lookup(child, Rights::READ), Err(CapError::InvalidHandle));
453 }
454
455 #[test]
456 fn transfer_needs_grant_and_table_full_is_reported() {
457 let mut source = CapTable::<2>::new(1);
458 let mut target = CapTable::<1>::new(2);
459 let denied = source.insert(1, Rights::READ).unwrap();
460 assert_eq!(
461 CapTable::transfer(&mut source, denied, &mut target),
462 Err(CapError::MissingRights)
463 );
464 let granted = source.insert(2, Rights::READ | Rights::GRANT).unwrap();
465 let received = CapTable::transfer(&mut source, granted, &mut target).unwrap();
466 assert_eq!(target.lookup(received, Rights::READ), Ok(2));
467 assert_eq!(target.insert(3, Rights::READ), Err(CapError::Full));
468 }
469 #[test]
470 fn removing_a_derived_parent_keeps_the_subtree_revocable() {
471 // Review regression: removing an intermediate capability used to free
472 // its slot, breaking the child's parent chain so revoking the
473 // grandparent no longer reached the child.
474 let mut a = CapTable::<4>::new(1);
475 let mut b = CapTable::<4>::new(2);
476 let all = Rights::READ | Rights::DERIVE | Rights::REVOKE;
477 let root = a.insert(9, all).unwrap();
478 let mid = a.derive(root, all).unwrap();
479 let leaf = CapTable::derive_into(&mut a, mid, &mut b, Rights::READ).unwrap();
480 a.remove(mid).unwrap();
481 // The removed handle is dead; the leaf is still usable (remove != revoke).
482 assert_eq!(a.lookup(mid, Rights::READ), Err(CapError::InvalidHandle));
483 assert_eq!(b.lookup(leaf, Rights::READ), Ok(9));
484 // Revoking the grandparent still reaches the leaf through the tombstone.
485 CapTable::<4>::revoke(1, root, &mut [&mut a, &mut b]).unwrap();
486 assert_eq!(b.lookup(leaf, Rights::READ), Err(CapError::InvalidHandle));
487 assert_eq!(a.lookup(root, Rights::READ), Err(CapError::InvalidHandle));
488 }
489
490 #[test]
491 fn removing_a_never_derived_capability_frees_its_slot() {
492 let mut t = CapTable::<1>::new(1);
493 let h = t.insert(3, Rights::READ).unwrap();
494 t.remove(h).unwrap();
495 assert!(t.insert(4, Rights::READ).is_ok(), "slot reusable");
496 }
497}