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-capability-ffi / src / lib.rs

783 lines · 24293 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//! C binding for the 32-bit-generation Rust capability authority
17//! (`aienos-capability`).
18//!
19//! This is NOT the native AIENOS capability ABI. The production ABI is the C
20//! library in `native/capability` (`aienos_capability.h`): 64-bit
21//! generations, `AienosCapRef` of 16 bytes, symbols `aienos_cap_*`. That is
22//! the library omega links into the reaction world.
23//!
24//! This crate is a separate implementation with a different layout
25//! (`AienosCapRef` of 8 bytes, 32-bit generation). So that a program built
26//! against the C header can never resolve against this archive by accident,
27//! every exported symbol carries its own versioned prefix, `aienos_cap32_*`,
28//! and [`aienos_cap32_abi_layout`] reports the layout it was built with.
29//! `scripts/test-cap-abi-isolation.sh` checks that the two archives share no
30//! symbol and that a C caller of `aienos_cap_*` fails to link against this
31//! one.
32//!
33//! The view pointer can validate. The admin pointer can change the table.
34//! They share the table, and only the admin holds the office token.
35
36use std::fs::File;
37use std::io::Read;
38use std::sync::{Arc, Mutex};
39
40use aienos_capability::{
41 AuthorityAdmin, AuthorityState, CapRef, Entry, Mint, ERR_IO, ERR_STATE, OK,
42};
43
44/// Capability reference in the 32-bit-generation Rust authority ABI
45/// (8 bytes, align 4, generation at offset 4). NOT the native AIENOS
46/// capability ABI, whose `AienosCapRef` is 16 bytes with a 64-bit
47/// generation at offset 8.
48#[repr(C)]
49#[derive(Clone, Copy)]
50pub struct AienosCapRef {
51 pub cap_id: u32,
52 pub generation: u32,
53}
54
55/// Table entry in the 32-bit-generation Rust authority ABI (64 bytes).
56/// NOT the native AIENOS capability ABI (88 bytes there).
57#[repr(C)]
58#[derive(Clone, Copy)]
59pub struct AienosCapEntry {
60 pub cap_id: u32,
61 pub generation: u32,
62 pub state: u32,
63 pub issuer: u32,
64 pub subject: u32,
65 pub rights: u32,
66 pub resource: u64,
67 pub epoch: u64,
68 pub lease_expiry: u64,
69 pub parent_id: u32,
70 pub parent_generation: u32,
71 pub minted_by_id: u32,
72 pub minted_by_generation: u32,
73}
74
75/// Mint request in the 32-bit-generation Rust authority ABI (48 bytes).
76/// NOT the native AIENOS capability ABI (64 bytes there).
77#[repr(C)]
78#[derive(Clone, Copy)]
79pub struct AienosCapMint {
80 pub issuer: u32,
81 pub subject: u32,
82 pub resource: u64,
83 pub rights: u32,
84 pub lease_ticks: u64,
85 pub parent: AienosCapRef,
86 pub authority: AienosCapRef,
87}
88
89/// Version of the `aienos_cap32_*` binary contract. Bump it, and the symbol
90/// prefix, if any exported layout or signature changes.
91pub const AIENOS_CAP32_ABI_VERSION: u32 = 1;
92
93/// Width in bits of every generation field in this ABI.
94pub const AIENOS_CAP32_GENERATION_BITS: u32 = 32;
95
96/// Number of `u32` words [`aienos_cap32_abi_layout`] writes.
97pub const AIENOS_CAP32_LAYOUT_WORDS: usize = 4;
98
99const REF_SIZE: usize = 8;
100const REF_ALIGN: usize = 4;
101const REF_GENERATION_OFFSET: usize = 4;
102const ENTRY_SIZE: usize = 64;
103const MINT_SIZE: usize = 48;
104
105const _: () = assert!(core::mem::size_of::<AienosCapRef>() == REF_SIZE);
106const _: () = assert!(core::mem::align_of::<AienosCapRef>() == REF_ALIGN);
107const _: () = assert!(core::mem::offset_of!(AienosCapRef, cap_id) == 0);
108const _: () = assert!(core::mem::offset_of!(AienosCapRef, generation) == REF_GENERATION_OFFSET);
109const _: () = assert!(core::mem::size_of::<u32>() * 8 == AIENOS_CAP32_GENERATION_BITS as usize);
110const _: () = assert!(core::mem::size_of::<AienosCapEntry>() == ENTRY_SIZE);
111const _: () = assert!(core::mem::align_of::<AienosCapEntry>() == 8);
112const _: () = assert!(core::mem::offset_of!(AienosCapEntry, generation) == 4);
113const _: () = assert!(core::mem::offset_of!(AienosCapEntry, resource) == 24);
114const _: () = assert!(core::mem::offset_of!(AienosCapEntry, parent_generation) == 52);
115const _: () = assert!(core::mem::offset_of!(AienosCapEntry, minted_by_generation) == 60);
116const _: () = assert!(core::mem::size_of::<AienosCapMint>() == MINT_SIZE);
117const _: () = assert!(core::mem::offset_of!(AienosCapMint, lease_ticks) == 24);
118const _: () = assert!(core::mem::offset_of!(AienosCapMint, parent) == 32);
119const _: () = assert!(core::mem::offset_of!(AienosCapMint, authority) == 40);
120
121/// Report the layout this archive was built with, so a caller can refuse to
122/// run against a different one. Writes, in order: size of `AienosCapRef`,
123/// offset of its `generation`, size of that `generation` field, size of
124/// `AienosCapEntry`. Returns [`AIENOS_CAP32_ABI_VERSION`], or 0 when `out`
125/// is null.
126///
127/// # Safety
128/// `out` is null or points to [`AIENOS_CAP32_LAYOUT_WORDS`] writable `u32`s.
129#[no_mangle]
130pub unsafe extern "C" fn aienos_cap32_abi_layout(out: *mut u32) -> u32 {
131 if out.is_null() {
132 return 0;
133 }
134 let words: [u32; AIENOS_CAP32_LAYOUT_WORDS] = [
135 REF_SIZE as u32,
136 REF_GENERATION_OFFSET as u32,
137 core::mem::size_of::<u32>() as u32,
138 ENTRY_SIZE as u32,
139 ];
140 for (i, word) in words.iter().enumerate() {
141 unsafe { *out.add(i) = *word };
142 }
143 AIENOS_CAP32_ABI_VERSION
144}
145
146pub struct AienosCapShared {
147 state: Mutex<AuthorityState>,
148 admin: Mutex<AuthorityAdmin>,
149}
150
151pub struct AienosCapAdmin {
152 shared: Arc<AienosCapShared>,
153}
154
155pub struct AienosCapView {
156 shared: Arc<AienosCapShared>,
157}
158
159fn fill_token(token: &mut [u8; 32]) -> bool {
160 let mut file = match File::open("/dev/urandom") {
161 Ok(file) => file,
162 Err(_) => return false,
163 };
164 file.read_exact(token).is_ok()
165}
166
167fn to_ref(cap: AienosCapRef) -> CapRef {
168 CapRef {
169 cap_id: cap.cap_id,
170 generation: cap.generation,
171 }
172}
173
174fn from_ref(cap: CapRef) -> AienosCapRef {
175 AienosCapRef {
176 cap_id: cap.cap_id,
177 generation: cap.generation,
178 }
179}
180
181fn to_mint(request: AienosCapMint) -> Mint {
182 Mint {
183 issuer: request.issuer,
184 subject: request.subject,
185 resource: request.resource,
186 rights: request.rights,
187 lease_ticks: request.lease_ticks,
188 parent: to_ref(request.parent),
189 authority: to_ref(request.authority),
190 }
191}
192
193fn from_entry(entry: Entry) -> AienosCapEntry {
194 AienosCapEntry {
195 cap_id: entry.cap_id,
196 generation: entry.generation,
197 state: entry.state,
198 issuer: entry.issuer,
199 subject: entry.subject,
200 rights: entry.rights,
201 resource: entry.resource,
202 epoch: entry.epoch,
203 lease_expiry: entry.lease_expiry,
204 parent_id: entry.parent_id,
205 parent_generation: entry.parent_generation,
206 minted_by_id: entry.minted_by_id,
207 minted_by_generation: entry.minted_by_generation,
208 }
209}
210
211fn write_entry(out: *mut AienosCapEntry, entry: Entry) {
212 if !out.is_null() {
213 unsafe { *out = from_entry(entry) };
214 }
215}
216
217fn write_ref(out: *mut AienosCapRef, cap: CapRef) {
218 if !out.is_null() {
219 unsafe { *out = from_ref(cap) };
220 }
221}
222
223/// # Safety
224/// `admin_out` and `view_out` must be writable pointers.
225#[no_mangle]
226pub unsafe extern "C" fn aienos_cap32_start(
227 admin_out: *mut *mut AienosCapAdmin,
228 view_out: *mut *mut AienosCapView,
229) -> i32 {
230 if admin_out.is_null() || view_out.is_null() {
231 return ERR_STATE;
232 }
233 let boot = match aienos_capability::take_boot_gen() {
234 Ok(boot) => boot,
235 Err(code) => return code,
236 };
237 let state = match AuthorityState::bootstrap(boot) {
238 Ok(state) => state,
239 Err(code) => return code,
240 };
241 let mut token = [0u8; 32];
242 if !fill_token(&mut token) {
243 return ERR_IO;
244 }
245 let shared = Arc::new(AienosCapShared {
246 state: Mutex::new(state),
247 admin: Mutex::new(AuthorityAdmin::new(token)),
248 });
249 let admin = Box::new(AienosCapAdmin {
250 shared: Arc::clone(&shared),
251 });
252 let view = Box::new(AienosCapView { shared });
253 unsafe {
254 *admin_out = Box::into_raw(admin);
255 *view_out = Box::into_raw(view);
256 }
257 OK
258}
259
260/// # Safety
261/// Both pointers came from [`aienos_cap32_start`] and have not been stopped.
262#[no_mangle]
263pub unsafe extern "C" fn aienos_cap32_stop(admin: *mut AienosCapAdmin, view: *mut AienosCapView) {
264 if !admin.is_null() {
265 drop(unsafe { Box::from_raw(admin) });
266 }
267 if !view.is_null() {
268 drop(unsafe { Box::from_raw(view) });
269 }
270}
271
272fn with_state<T>(shared: &AienosCapShared, f: impl FnOnce(&AuthorityState) -> T) -> T {
273 let state = shared
274 .state
275 .lock()
276 .unwrap_or_else(|poison| poison.into_inner());
277 f(&state)
278}
279
280fn with_state_mut<T>(shared: &AienosCapShared, f: impl FnOnce(&mut AuthorityState) -> T) -> T {
281 let mut state = shared
282 .state
283 .lock()
284 .unwrap_or_else(|poison| poison.into_inner());
285 f(&mut state)
286}
287
288/// # Safety
289/// `admin` came from [`aienos_cap32_start`].
290#[no_mangle]
291pub unsafe extern "C" fn aienos_cap32_office(
292 admin: *const AienosCapAdmin,
293 out: *mut AienosCapRef,
294) -> i32 {
295 if admin.is_null() {
296 return ERR_STATE;
297 }
298 let cap = with_state(&unsafe { &*admin }.shared, |state| state.office());
299 write_ref(out, cap);
300 OK
301}
302
303/// # Safety
304/// `admin` came from [`aienos_cap32_start`]. `out` may be null.
305#[no_mangle]
306pub unsafe extern "C" fn aienos_cap32_mint(
307 admin: *mut AienosCapAdmin,
308 request: *const AienosCapMint,
309 out: *mut AienosCapRef,
310) -> i32 {
311 if admin.is_null() || request.is_null() {
312 return ERR_STATE;
313 }
314 let request = unsafe { *request };
315 let result = with_state_mut(&unsafe { &*admin }.shared, |state| {
316 state.mint(to_mint(request))
317 });
318 match result {
319 Ok(cap) => {
320 write_ref(out, cap);
321 OK
322 }
323 Err(code) => code,
324 }
325}
326
327/// # Safety
328/// `admin` came from [`aienos_cap32_start`].
329#[no_mangle]
330pub unsafe extern "C" fn aienos_cap32_revoke(
331 admin: *mut AienosCapAdmin,
332 authority: AienosCapRef,
333 target: AienosCapRef,
334) -> i32 {
335 if admin.is_null() {
336 return ERR_STATE;
337 }
338 with_state_mut(&unsafe { &*admin }.shared, |state| {
339 state.revoke(to_ref(authority), to_ref(target))
340 })
341 .err()
342 .unwrap_or(OK)
343}
344
345/// # Safety
346/// `admin` came from [`aienos_cap32_start`].
347#[no_mangle]
348pub unsafe extern "C" fn aienos_cap32_reclaim(
349 admin: *mut AienosCapAdmin,
350 authority: AienosCapRef,
351 cap_id: u32,
352) -> i32 {
353 if admin.is_null() {
354 return ERR_STATE;
355 }
356 with_state_mut(&unsafe { &*admin }.shared, |state| {
357 state.reclaim(to_ref(authority), cap_id)
358 })
359 .err()
360 .unwrap_or(OK)
361}
362
363/// # Safety
364/// `admin` came from [`aienos_cap32_start`].
365#[no_mangle]
366pub unsafe extern "C" fn aienos_cap32_advance_clock(
367 admin: *mut AienosCapAdmin,
368 authority: AienosCapRef,
369 ticks: u64,
370) -> i32 {
371 if admin.is_null() {
372 return ERR_STATE;
373 }
374 with_state_mut(&unsafe { &*admin }.shared, |state| {
375 state.advance_clock(to_ref(authority), ticks)
376 })
377 .err()
378 .unwrap_or(OK)
379}
380
381/// # Safety
382/// `admin` came from [`aienos_cap32_start`].
383#[no_mangle]
384pub unsafe extern "C" fn aienos_cap32_bump_epoch(
385 admin: *mut AienosCapAdmin,
386 authority: AienosCapRef,
387) -> i32 {
388 if admin.is_null() {
389 return ERR_STATE;
390 }
391 with_state_mut(&unsafe { &*admin }.shared, |state| {
392 state.bump_epoch(to_ref(authority))
393 })
394 .err()
395 .unwrap_or(OK)
396}
397
398/// # Safety
399/// `admin` came from [`aienos_cap32_start`].
400#[no_mangle]
401pub unsafe extern "C" fn aienos_cap32_kill(admin: *mut AienosCapAdmin) -> i32 {
402 if admin.is_null() {
403 return ERR_STATE;
404 }
405 with_state_mut(&unsafe { &*admin }.shared, |state| state.kill_writer());
406 OK
407}
408
409/// Replace the table with the next boot generation. The new table starts
410/// above every generation the old one used (fix mirrored from the native
411/// authority, b1fa747), so outstanding references fail against it even
412/// after reclaims. The office token is replaced.
413///
414/// # Safety
415/// `admin` came from [`aienos_cap32_start`].
416#[no_mangle]
417pub unsafe extern "C" fn aienos_cap32_restart(admin: *mut AienosCapAdmin) -> i32 {
418 if admin.is_null() {
419 return ERR_STATE;
420 }
421 let mut token = [0u8; 32];
422 if !fill_token(&mut token) {
423 return ERR_IO;
424 }
425 let shared = &unsafe { &*admin }.shared;
426 let swapped = with_state_mut(shared, |slot| {
427 let boot = aienos_capability::take_boot_gen_above(slot.generation_floor())?;
428 *slot = AuthorityState::bootstrap(boot)?;
429 Ok::<(), i32>(())
430 });
431 if let Err(code) = swapped {
432 return code;
433 }
434 let mut admin_token = shared
435 .admin
436 .lock()
437 .unwrap_or_else(|poison| poison.into_inner());
438 *admin_token = AuthorityAdmin::new(token);
439 OK
440}
441
442/// # Safety
443/// `view` came from [`aienos_cap32_start`]. `out` may be null.
444#[no_mangle]
445pub unsafe extern "C" fn aienos_cap32_validate(
446 view: *const AienosCapView,
447 cap: AienosCapRef,
448 subject: u32,
449 resource: u64,
450 rights: u32,
451 out: *mut AienosCapEntry,
452) -> i32 {
453 if view.is_null() {
454 return ERR_STATE;
455 }
456 let result = with_state(&unsafe { &*view }.shared, |state| {
457 state.validate(to_ref(cap), subject, resource, rights)
458 });
459 match result {
460 Ok(entry) => {
461 write_entry(out, entry);
462 OK
463 }
464 Err(code) => code,
465 }
466}
467
468/// # Safety
469/// `view` came from [`aienos_cap32_start`]. `out` may be null.
470#[no_mangle]
471pub unsafe extern "C" fn aienos_cap32_inspect(
472 view: *const AienosCapView,
473 cap: AienosCapRef,
474 out: *mut AienosCapEntry,
475) -> i32 {
476 if view.is_null() {
477 return ERR_STATE;
478 }
479 let result = with_state(&unsafe { &*view }.shared, |state| {
480 state.inspect(to_ref(cap))
481 });
482 match result {
483 Ok(entry) => {
484 write_entry(out, entry);
485 OK
486 }
487 Err(code) => code,
488 }
489}
490
491/// # Safety
492/// `view` came from [`aienos_cap32_start`].
493#[no_mangle]
494pub unsafe extern "C" fn aienos_cap32_clock(view: *const AienosCapView) -> u64 {
495 if view.is_null() {
496 return 0;
497 }
498 with_state(&unsafe { &*view }.shared, |state| state.clock())
499}
500
501/// Cognition's mint attempt. The view has no office token, so this cannot
502/// change the table no matter what reference or token bytes are supplied.
503///
504/// # Safety
505/// `view` came from [`aienos_cap32_start`]. `token` may be null.
506#[no_mangle]
507pub unsafe extern "C" fn aienos_cap32_cognition_mint(
508 view: *const AienosCapView,
509 _request: *const AienosCapMint,
510 _token: *const u8,
511) -> i32 {
512 if view.is_null() {
513 return ERR_STATE;
514 }
515 let _ = with_state(&unsafe { &*view }.shared, |state| state.clock());
516 aienos_capability::ERR_UNAUTHORIZED
517}
518
519/// # Safety
520/// `view` came from [`aienos_cap32_start`].
521#[no_mangle]
522pub unsafe extern "C" fn aienos_cap32_cognition_admin(
523 view: *const AienosCapView,
524 _op: u32,
525 _authority: AienosCapRef,
526 _target: AienosCapRef,
527) -> i32 {
528 if view.is_null() {
529 return ERR_STATE;
530 }
531 aienos_capability::ERR_UNAUTHORIZED
532}
533
534/// # Safety
535/// `out` may be null. When it is not, it must be writable.
536#[no_mangle]
537pub unsafe extern "C" fn aienos_cap32_generation_advance(generation: u32, out: *mut u32) -> i32 {
538 match aienos_capability::generation_advance(generation) {
539 Ok(next) => {
540 if !out.is_null() {
541 unsafe { *out = next };
542 }
543 OK
544 }
545 Err(code) => code,
546 }
547}
548
549/// # Safety
550/// `admin` came from [`aienos_cap32_start`] and is the test harness, not cognition.
551#[no_mangle]
552pub unsafe extern "C" fn aienos_cap32_force_generation(
553 admin: *mut AienosCapAdmin,
554 cap_id: u32,
555 generation: u32,
556) -> i32 {
557 if admin.is_null() {
558 return ERR_STATE;
559 }
560 with_state_mut(&unsafe { &*admin }.shared, |state| {
561 state.set_generation_for_test(cap_id, generation)
562 })
563 .err()
564 .unwrap_or(OK)
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570 use aienos_capability::{
571 ERR_EXHAUSTED, ERR_REVOKED, ERR_STALE_GEN, ERR_SUBJECT, ERR_UNAUTHORIZED, RIGHT_READ,
572 };
573 use core::ptr;
574
575 #[test]
576 fn layout_matches_the_cap32_contract() {
577 assert_eq!(core::mem::size_of::<AienosCapRef>(), 8);
578 assert_eq!(core::mem::align_of::<AienosCapRef>(), 4);
579 assert_eq!(core::mem::offset_of!(AienosCapRef, generation), 4);
580 assert_eq!(core::mem::size_of::<AienosCapEntry>(), 64);
581 assert_eq!(core::mem::size_of::<AienosCapMint>(), 48);
582 let mut words = [0u32; AIENOS_CAP32_LAYOUT_WORDS];
583 let version = unsafe { aienos_cap32_abi_layout(words.as_mut_ptr()) };
584 assert_eq!(version, AIENOS_CAP32_ABI_VERSION);
585 assert_eq!(version, 1);
586 assert_eq!(words, [8, 4, 4, 64]);
587 assert_eq!(unsafe { aienos_cap32_abi_layout(ptr::null_mut()) }, 0);
588 // The native C ABI is 16 bytes with the generation at offset 8. A
589 // caller that checks this report cannot mistake one for the other.
590 assert_ne!(words[0], 16);
591 assert_ne!(words[1], 8);
592 }
593
594 struct Auth {
595 admin: *mut AienosCapAdmin,
596 view: *mut AienosCapView,
597 }
598
599 impl Auth {
600 fn start() -> Self {
601 let mut admin = ptr::null_mut();
602 let mut view = ptr::null_mut();
603 assert_eq!(unsafe { aienos_cap32_start(&mut admin, &mut view) }, OK);
604 Self { admin, view }
605 }
606
607 fn office(&self) -> AienosCapRef {
608 let mut out = AienosCapRef {
609 cap_id: 0,
610 generation: 0,
611 };
612 assert_eq!(unsafe { aienos_cap32_office(self.admin, &mut out) }, OK);
613 out
614 }
615
616 fn mint(&self, subject: u32, resource: u64) -> AienosCapRef {
617 let request = AienosCapMint {
618 issuer: 3,
619 subject,
620 resource,
621 rights: RIGHT_READ,
622 lease_ticks: 0,
623 parent: AienosCapRef {
624 cap_id: aienos_capability::PARENT_NONE,
625 generation: 0,
626 },
627 authority: self.office(),
628 };
629 let mut out = AienosCapRef {
630 cap_id: 0,
631 generation: 0,
632 };
633 assert_eq!(
634 unsafe { aienos_cap32_mint(self.admin, &request, &mut out) },
635 OK
636 );
637 out
638 }
639
640 fn validate(&self, cap: AienosCapRef, subject: u32, resource: u64) -> i32 {
641 unsafe {
642 aienos_cap32_validate(
643 self.view,
644 cap,
645 subject,
646 resource,
647 RIGHT_READ,
648 ptr::null_mut(),
649 )
650 }
651 }
652 }
653
654 impl Drop for Auth {
655 fn drop(&mut self) {
656 unsafe { aienos_cap32_stop(self.admin, self.view) };
657 }
658 }
659
660 /// Mirror of the C test reclaimed_reference_stays_dead_after_restart
661 /// (fix b1fa747): a reference minted after one reclaim must not validate
662 /// again once the same slot is minted for the same subject and resource
663 /// after a restart.
664 #[test]
665 fn reclaimed_reference_stays_dead_after_restart() {
666 let a = Auth::start();
667 let first = a.mint(1, 0x40);
668 assert_eq!(
669 unsafe { aienos_cap32_revoke(a.admin, a.office(), first) },
670 OK
671 );
672 assert_eq!(
673 unsafe { aienos_cap32_reclaim(a.admin, a.office(), first.cap_id) },
674 OK
675 );
676 let second = a.mint(1, 0x40);
677 assert_eq!(second.cap_id, first.cap_id);
678 assert_eq!(second.generation, first.generation + 1);
679 assert_eq!(unsafe { aienos_cap32_restart(a.admin) }, OK);
680 let fresh = a.mint(1, 0x40);
681 assert_eq!(fresh.cap_id, second.cap_id);
682 assert!(fresh.generation > second.generation);
683 assert_eq!(a.validate(second, 1, 0x40), ERR_STALE_GEN);
684 assert_eq!(a.validate(first, 1, 0x40), ERR_STALE_GEN);
685 assert_eq!(a.validate(fresh, 1, 0x40), OK);
686 }
687
688 /// Mirror of the C test generation_exhaustion_fails_closed.
689 #[test]
690 fn generation_exhaustion_fails_closed() {
691 let mut next = 0u32;
692 assert_eq!(
693 unsafe { aienos_cap32_generation_advance(u32::MAX, &mut next) },
694 ERR_EXHAUSTED
695 );
696 assert_eq!(
697 unsafe { aienos_cap32_generation_advance(u32::MAX - 1, &mut next) },
698 OK
699 );
700 assert_eq!(next, u32::MAX);
701 let a = Auth::start();
702 let cap = a.mint(1, 0x10);
703 assert_eq!(unsafe { aienos_cap32_revoke(a.admin, a.office(), cap) }, OK);
704 assert_eq!(
705 unsafe { aienos_cap32_force_generation(a.admin, cap.cap_id, u32::MAX) },
706 OK
707 );
708 assert_eq!(
709 unsafe { aienos_cap32_reclaim(a.admin, a.office(), cap.cap_id) },
710 ERR_EXHAUSTED
711 );
712 assert_eq!(a.validate(cap, 1, 0x10), ERR_STALE_GEN);
713 let replacement = a.mint(1, 0x11);
714 assert_ne!(replacement.cap_id, cap.cap_id);
715 assert_eq!(
716 unsafe { aienos_cap32_force_generation(a.admin, replacement.cap_id, 99) },
717 ERR_STATE
718 );
719 // No start above an exhausted generation exists, so restart refuses
720 // rather than reuse one, and the table is left as it was.
721 assert_eq!(unsafe { aienos_cap32_restart(a.admin) }, ERR_EXHAUSTED);
722 assert_eq!(a.validate(replacement, 1, 0x11), OK);
723 }
724
725 #[test]
726 fn stale_and_unauthorized_use_is_refused() {
727 let a = Auth::start();
728 let cap = a.mint(1, 0x20);
729 assert_eq!(a.validate(cap, 2, 0x20), ERR_SUBJECT);
730 let before = unsafe { aienos_cap32_clock(a.view) };
731 let request = AienosCapMint {
732 issuer: 1,
733 subject: 1,
734 resource: 1,
735 rights: RIGHT_READ,
736 lease_ticks: 0,
737 parent: AienosCapRef {
738 cap_id: aienos_capability::PARENT_NONE,
739 generation: 0,
740 },
741 authority: a.office(),
742 };
743 let guess = [0u8; 32];
744 assert_eq!(
745 unsafe { aienos_cap32_cognition_mint(a.view, &request, guess.as_ptr()) },
746 ERR_UNAUTHORIZED
747 );
748 assert_eq!(
749 unsafe { aienos_cap32_cognition_admin(a.view, 1, a.office(), cap) },
750 ERR_UNAUTHORIZED
751 );
752 assert_eq!(unsafe { aienos_cap32_clock(a.view) }, before);
753 // An ordinary reference cannot act as the office.
754 let mut as_office = request;
755 as_office.authority = cap;
756 let mut out = AienosCapRef {
757 cap_id: 0,
758 generation: 0,
759 };
760 assert_eq!(
761 unsafe { aienos_cap32_mint(a.admin, &as_office, &mut out) },
762 ERR_UNAUTHORIZED
763 );
764 assert_eq!(
765 unsafe { aienos_cap32_advance_clock(a.admin, cap, 1) },
766 ERR_UNAUTHORIZED
767 );
768 assert_eq!(unsafe { aienos_cap32_revoke(a.admin, a.office(), cap) }, OK);
769 assert_eq!(a.validate(cap, 1, 0x20), ERR_REVOKED);
770 assert_eq!(
771 unsafe { aienos_cap32_reclaim(a.admin, a.office(), cap.cap_id) },
772 OK
773 );
774 assert_eq!(a.validate(cap, 1, 0x20), ERR_STALE_GEN);
775 // Null handles fail closed.
776 assert_eq!(
777 unsafe {
778 aienos_cap32_validate(ptr::null(), cap, 1, 0x20, RIGHT_READ, ptr::null_mut())
779 },
780 ERR_STATE
781 );
782 }
783}