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

1296 lines · 43180 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//! Rust capability authority, 32-bit generations.
17//!
18//! A separate implementation of the AIENOS capability rules. The production
19//! ABI is the C authority in `native/capability` (64-bit generations,
20//! symbols `aienos_cap_*`); this crate and its C binding
21//! `aienos-capability-ffi` (symbols `aienos_cap32_*`) are not interchangeable
22//! with it. See `docs/CAPABILITY_ABI.md`.
23//!
24//! This is the AIENOS side of the host reference root. The slot rules match
25//! that root: a reference is an index plus a generation, a reused slot does
26//! not honor the old reference, generation never wraps, delegation can only
27//! narrow rights, and revoking an ancestor revokes the descendants.
28//!
29//! What the older capability table does not carry lives here: the subject the
30//! capability was issued to, the epoch, the lease, a full 64-bit resource
31//! identity, and office rights that cannot be delegated.
32//!
33//! [`AuthorityView`] can check a reference. It cannot mint, revoke, reclaim,
34//! move the clock, or change the epoch. Those operations live on
35//! [`AuthorityAdmin`], and they refuse to run unless the caller still holds
36//! the office token that was never written into the table.
37
38#![no_std]
39
40use core::sync::atomic::{AtomicU32, Ordering};
41
42pub const CAP_MAX: usize = 256;
43pub const MAX_DEPTH: u32 = 8;
44pub const TOKEN_LEN: usize = 32;
45pub const RES_AUTHORITY: u64 = 0;
46
47pub const OK: i32 = 0;
48pub const ERR_BOUNDS: i32 = -1;
49pub const ERR_STALE_GEN: i32 = -2;
50pub const ERR_REVOKED: i32 = -3;
51pub const ERR_EPOCH: i32 = -4;
52pub const ERR_SUBJECT: i32 = -5;
53pub const ERR_RESOURCE: i32 = -6;
54pub const ERR_RIGHTS: i32 = -7;
55pub const ERR_EXPIRED: i32 = -8;
56pub const ERR_CHAIN: i32 = -9;
57pub const ERR_AMPLIFY: i32 = -10;
58pub const ERR_NOT_DELEGABLE: i32 = -11;
59pub const ERR_FULL: i32 = -12;
60pub const ERR_IO: i32 = -13;
61pub const ERR_STATE: i32 = -14;
62pub const ERR_UNAUTHORIZED: i32 = -15;
63pub const ERR_OVERFLOW: i32 = -16;
64pub const ERR_EXHAUSTED: i32 = -17;
65
66pub const RIGHT_READ: u32 = 0x1;
67pub const RIGHT_WRITE: u32 = 0x2;
68pub const RIGHT_EFFECT: u32 = 0x4;
69pub const RIGHT_DELEGATE: u32 = 0x8;
70pub const RIGHT_MINT: u32 = 0x10;
71pub const RIGHT_REVOKE: u32 = 0x20;
72pub const RIGHT_RECLAIM: u32 = 0x40;
73pub const RIGHT_EPOCH: u32 = 0x80;
74pub const RIGHT_CLOCK: u32 = 0x100;
75/// Authorizes a lineage transition. Intelligence may propose the next
76/// generation. Only a holder of this right may promote it, and the right
77/// cannot be handed on.
78pub const RIGHT_PROMOTE: u32 = 0x200;
79pub const RIGHT_PRIVILEGED: u32 =
80 RIGHT_MINT | RIGHT_REVOKE | RIGHT_RECLAIM | RIGHT_EPOCH | RIGHT_CLOCK | RIGHT_PROMOTE;
81pub const RIGHT_KNOWN: u32 =
82 RIGHT_READ | RIGHT_WRITE | RIGHT_EFFECT | RIGHT_DELEGATE | RIGHT_PRIVILEGED;
83
84pub const STATE_FREE: u32 = 0;
85pub const STATE_LIVE: u32 = 1;
86pub const STATE_REVOKED: u32 = 2;
87
88pub const PARENT_NONE: u32 = u32::MAX;
89
90static NEXT_BOOT_GEN: AtomicU32 = AtomicU32::new(1);
91
92/// A 32-bit resource widened without dropping any bits.
93pub const fn widen_resource(id: u32) -> u64 {
94 id as u64
95}
96
97/// Narrow a resource only when the top half is zero. Anything else is refused
98/// rather than silently truncated.
99pub const fn narrow_resource(id: u64) -> Result<u32, i32> {
100 if id > u32::MAX as u64 {
101 Err(ERR_RESOURCE)
102 } else {
103 Ok(id as u32)
104 }
105}
106
107pub const fn generation_advance(generation: u32) -> Result<u32, i32> {
108 if generation == u32::MAX {
109 Err(ERR_EXHAUSTED)
110 } else {
111 Ok(generation + 1)
112 }
113}
114
115pub const fn add_u64(a: u64, b: u64) -> Result<u64, i32> {
116 if b > u64::MAX - a {
117 Err(ERR_OVERFLOW)
118 } else {
119 Ok(a + b)
120 }
121}
122
123/// Take the next boot generation. A later authority starts higher, so a
124/// reference from a stopped authority cannot validate against the new one.
125pub fn take_boot_gen() -> Result<u32, i32> {
126 take_boot_gen_above(0)
127}
128
129/// Take the next boot generation, no lower than `floor`. A restart passes
130/// [`AuthorityState::generation_floor`] of the table it replaces, so the new
131/// table starts above every generation the old one handed out, including
132/// generations a reclaim moved past the old boot generation. Fails closed
133/// with [`ERR_EXHAUSTED`] rather than reuse a generation.
134pub fn take_boot_gen_above(floor: u32) -> Result<u32, i32> {
135 let mut cur = NEXT_BOOT_GEN.load(Ordering::Relaxed);
136 loop {
137 let start = if floor > cur { floor } else { cur };
138 if start == 0 || start == u32::MAX {
139 return Err(ERR_EXHAUSTED);
140 }
141 match NEXT_BOOT_GEN.compare_exchange_weak(
142 cur,
143 start + 1,
144 Ordering::AcqRel,
145 Ordering::Relaxed,
146 ) {
147 Ok(_) => return Ok(start),
148 Err(observed) => cur = observed,
149 }
150 }
151}
152
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub struct CapRef {
155 pub cap_id: u32,
156 pub generation: u32,
157}
158
159impl CapRef {
160 pub const NONE: Self = Self {
161 cap_id: PARENT_NONE,
162 generation: 0,
163 };
164}
165
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub struct Entry {
168 pub cap_id: u32,
169 pub generation: u32,
170 pub state: u32,
171 pub issuer: u32,
172 pub subject: u32,
173 pub rights: u32,
174 pub resource: u64,
175 pub epoch: u64,
176 pub lease_expiry: u64,
177 pub parent_id: u32,
178 pub parent_generation: u32,
179 pub minted_by_id: u32,
180 pub minted_by_generation: u32,
181}
182
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub struct Mint {
185 pub issuer: u32,
186 pub subject: u32,
187 pub resource: u64,
188 pub rights: u32,
189 pub lease_ticks: u64,
190 pub parent: CapRef,
191 pub authority: CapRef,
192}
193
194/// The table itself. Checking it does not confer the right to change it.
195#[derive(Clone, Debug)]
196pub struct AuthorityState {
197 boot_gen: u32,
198 epoch: u64,
199 clock: u64,
200 entries: [Entry; CAP_MAX],
201 delivered: [bool; CAP_MAX],
202 writer_alive: bool,
203}
204
205impl AuthorityState {
206 pub fn bootstrap(boot_gen: u32) -> Result<Self, i32> {
207 if boot_gen == 0 || boot_gen == u32::MAX {
208 return Err(ERR_EXHAUSTED);
209 }
210 let mut entries = [Entry {
211 cap_id: 0,
212 generation: boot_gen,
213 state: STATE_FREE,
214 issuer: 0,
215 subject: 0,
216 rights: 0,
217 resource: 0,
218 epoch: 0,
219 lease_expiry: 0,
220 parent_id: PARENT_NONE,
221 parent_generation: 0,
222 minted_by_id: 0,
223 minted_by_generation: 0,
224 }; CAP_MAX];
225 let mut i = 0;
226 while i < CAP_MAX {
227 entries[i].cap_id = i as u32;
228 i += 1;
229 }
230 let mut state = Self {
231 boot_gen,
232 epoch: 1,
233 clock: 0,
234 entries,
235 delivered: [false; CAP_MAX],
236 writer_alive: true,
237 };
238 let office = &mut state.entries[0];
239 office.state = STATE_LIVE;
240 office.issuer = 0;
241 office.subject = 0;
242 office.resource = RES_AUTHORITY;
243 office.rights = RIGHT_PRIVILEGED;
244 office.epoch = 1;
245 office.parent_id = PARENT_NONE;
246 state.delivered[0] = true;
247 Ok(state)
248 }
249
250 pub fn boot_gen(&self) -> u32 {
251 self.boot_gen
252 }
253
254 /// One past the largest generation anywhere in the table, including the
255 /// generations recorded for parents and minters. A table restarted at or
256 /// above this value honours no reference this table handed out. Returns
257 /// `u32::MAX` when no such start exists, which
258 /// [`take_boot_gen_above`] refuses.
259 pub fn generation_floor(&self) -> u32 {
260 let mut top = self.boot_gen;
261 let mut i = 0;
262 while i < CAP_MAX {
263 let e = &self.entries[i];
264 if e.generation > top {
265 top = e.generation;
266 }
267 if e.parent_generation > top {
268 top = e.parent_generation;
269 }
270 if e.minted_by_generation > top {
271 top = e.minted_by_generation;
272 }
273 i += 1;
274 }
275 top.saturating_add(1)
276 }
277
278 pub fn epoch(&self) -> u64 {
279 self.epoch
280 }
281
282 pub fn clock(&self) -> u64 {
283 self.clock
284 }
285
286 pub fn office(&self) -> CapRef {
287 CapRef {
288 cap_id: 0,
289 generation: self.entries[0].generation,
290 }
291 }
292
293 pub fn writer_alive(&self) -> bool {
294 self.writer_alive
295 }
296
297 pub fn kill_writer(&mut self) {
298 self.writer_alive = false;
299 }
300
301 pub fn inspect(&self, cap: CapRef) -> Result<Entry, i32> {
302 if cap.cap_id as usize >= CAP_MAX {
303 return Err(ERR_BOUNDS);
304 }
305 let entry = self.entries[cap.cap_id as usize];
306 if entry.generation != cap.generation {
307 return Err(ERR_STALE_GEN);
308 }
309 if entry.state == STATE_FREE {
310 return Err(ERR_STATE);
311 }
312 Ok(entry)
313 }
314
315 pub fn validate(
316 &self,
317 cap: CapRef,
318 subject: u32,
319 resource: u64,
320 rights: u32,
321 ) -> Result<Entry, i32> {
322 if cap.cap_id as usize >= CAP_MAX {
323 return Err(ERR_BOUNDS);
324 }
325 let mut chain = [Entry {
326 cap_id: 0,
327 generation: 0,
328 state: 0,
329 issuer: 0,
330 subject: 0,
331 rights: 0,
332 resource: 0,
333 epoch: 0,
334 lease_expiry: 0,
335 parent_id: 0,
336 parent_generation: 0,
337 minted_by_id: 0,
338 minted_by_generation: 0,
339 }; (MAX_DEPTH as usize) + 1];
340 let mut n = 0u32;
341 let mut id = cap.cap_id;
342 while id != PARENT_NONE {
343 if n > MAX_DEPTH || id as usize >= CAP_MAX {
344 return Err(ERR_CHAIN);
345 }
346 chain[n as usize] = self.entries[id as usize];
347 id = chain[n as usize].parent_id;
348 n += 1;
349 }
350 let entry = chain[0];
351 if entry.generation != cap.generation {
352 return Err(ERR_STALE_GEN);
353 }
354 if entry.state != STATE_LIVE {
355 return Err(ERR_REVOKED);
356 }
357 if entry.epoch != self.epoch {
358 return Err(ERR_EPOCH);
359 }
360 if entry.lease_expiry != 0 && self.clock >= entry.lease_expiry {
361 return Err(ERR_EXPIRED);
362 }
363 let mut i = 1u32;
364 while i < n {
365 let parent = chain[i as usize];
366 let child = chain[(i - 1) as usize];
367 if parent.generation != child.parent_generation {
368 return Err(ERR_CHAIN);
369 }
370 if parent.state != STATE_LIVE {
371 return Err(ERR_CHAIN);
372 }
373 if parent.epoch != self.epoch {
374 return Err(ERR_CHAIN);
375 }
376 if parent.lease_expiry != 0 && self.clock >= parent.lease_expiry {
377 return Err(ERR_CHAIN);
378 }
379 i += 1;
380 }
381 if entry.subject != subject {
382 return Err(ERR_SUBJECT);
383 }
384 if entry.resource != resource {
385 return Err(ERR_RESOURCE);
386 }
387 if entry.rights & rights != rights {
388 return Err(ERR_RIGHTS);
389 }
390 Ok(entry)
391 }
392
393 fn chain_ok(&self, mut entry_id: u32) -> Result<(), i32> {
394 let mut depth = 0u32;
395 loop {
396 let entry = self.entries[entry_id as usize];
397 if entry.parent_id == PARENT_NONE {
398 return Ok(());
399 }
400 depth += 1;
401 if depth > MAX_DEPTH {
402 return Err(ERR_CHAIN);
403 }
404 if entry.parent_id as usize >= CAP_MAX {
405 return Err(ERR_CHAIN);
406 }
407 let parent = self.entries[entry.parent_id as usize];
408 if parent.generation != entry.parent_generation || parent.state != STATE_LIVE {
409 return Err(ERR_CHAIN);
410 }
411 entry_id = entry.parent_id;
412 }
413 }
414
415 fn ancestor_hops(&self, mut entry_id: u32) -> u32 {
416 let mut hops = 0u32;
417 loop {
418 let entry = self.entries[entry_id as usize];
419 if entry.parent_id == PARENT_NONE || hops > MAX_DEPTH {
420 return hops;
421 }
422 if entry.parent_id as usize >= CAP_MAX {
423 return MAX_DEPTH + 1;
424 }
425 hops += 1;
426 entry_id = entry.parent_id;
427 }
428 }
429
430 fn auth_use(&self, authority: CapRef, need: u32) -> Result<usize, i32> {
431 if authority.cap_id as usize >= CAP_MAX {
432 return Err(ERR_UNAUTHORIZED);
433 }
434 let index = authority.cap_id as usize;
435 if !self.delivered[index] {
436 return Err(ERR_UNAUTHORIZED);
437 }
438 let entry = self.entries[index];
439 if entry.generation != authority.generation {
440 return Err(ERR_STALE_GEN);
441 }
442 if entry.state != STATE_LIVE {
443 return Err(ERR_REVOKED);
444 }
445 if entry.epoch != self.epoch {
446 return Err(ERR_EPOCH);
447 }
448 if entry.lease_expiry != 0 && self.clock >= entry.lease_expiry {
449 return Err(ERR_EXPIRED);
450 }
451 self.chain_ok(authority.cap_id)?;
452 if entry.rights & need != need {
453 return Err(ERR_UNAUTHORIZED);
454 }
455 Ok(index)
456 }
457
458 fn lease_expiry(&self, ticks: u64) -> Result<u64, i32> {
459 if ticks == 0 {
460 Ok(0)
461 } else {
462 add_u64(self.clock, ticks)
463 }
464 }
465
466 pub fn mint(&mut self, request: Mint) -> Result<CapRef, i32> {
467 if !self.writer_alive {
468 return Err(ERR_IO);
469 }
470 if request.rights == 0 || request.rights & !RIGHT_KNOWN != 0 {
471 return Err(ERR_RIGHTS);
472 }
473 if request.rights & RIGHT_PRIVILEGED != 0 && request.rights & RIGHT_DELEGATE != 0 {
474 return Err(ERR_NOT_DELEGABLE);
475 }
476 let auth_index = if request.parent.cap_id == PARENT_NONE {
477 let index = self.auth_use(request.authority, RIGHT_MINT)?;
478 let auth = self.entries[index];
479 if (request.rights & RIGHT_PRIVILEGED) & !auth.rights != 0 {
480 return Err(ERR_UNAUTHORIZED);
481 }
482 index
483 } else {
484 if request.authority.cap_id != request.parent.cap_id
485 || request.authority.generation != request.parent.generation
486 {
487 return Err(ERR_UNAUTHORIZED);
488 }
489 let index = self.auth_use(request.authority, 0)?;
490 let auth = self.entries[index];
491 if auth.rights & RIGHT_DELEGATE == 0 {
492 return Err(ERR_NOT_DELEGABLE);
493 }
494 if request.parent.cap_id as usize >= CAP_MAX {
495 return Err(ERR_BOUNDS);
496 }
497 if auth.resource != request.resource {
498 return Err(ERR_RESOURCE);
499 }
500 if request.rights & !auth.rights != 0 {
501 return Err(ERR_AMPLIFY);
502 }
503 if request.rights & RIGHT_PRIVILEGED != 0 {
504 return Err(ERR_NOT_DELEGABLE);
505 }
506 if self.ancestor_hops(request.parent.cap_id) >= MAX_DEPTH {
507 return Err(ERR_CHAIN);
508 }
509 if auth.lease_expiry != 0 {
510 let child = self.lease_expiry(request.lease_ticks)?;
511 if child == 0 || child > auth.lease_expiry {
512 return Err(ERR_AMPLIFY);
513 }
514 }
515 index
516 };
517 let expiry = self.lease_expiry(request.lease_ticks)?;
518 let auth = self.entries[auth_index];
519 let mut saw_exhausted = false;
520 let mut i = 0usize;
521 while i < CAP_MAX {
522 if self.entries[i].state == STATE_FREE {
523 if self.entries[i].generation == u32::MAX {
524 saw_exhausted = true;
525 } else {
526 let entry = &mut self.entries[i];
527 entry.state = STATE_LIVE;
528 entry.issuer = request.issuer;
529 entry.subject = request.subject;
530 entry.resource = request.resource;
531 entry.rights = request.rights;
532 entry.epoch = self.epoch;
533 entry.lease_expiry = expiry;
534 entry.parent_id = request.parent.cap_id;
535 entry.parent_generation = if request.parent.cap_id == PARENT_NONE {
536 0
537 } else {
538 request.parent.generation
539 };
540 entry.minted_by_id = auth.cap_id;
541 entry.minted_by_generation = auth.generation;
542 self.delivered[i] = true;
543 return Ok(CapRef {
544 cap_id: entry.cap_id,
545 generation: entry.generation,
546 });
547 }
548 }
549 i += 1;
550 }
551 Err(if saw_exhausted {
552 ERR_EXHAUSTED
553 } else {
554 ERR_FULL
555 })
556 }
557
558 fn cascade_revoke(&mut self) {
559 let mut guard = 0;
560 loop {
561 if guard >= CAP_MAX {
562 break;
563 }
564 guard += 1;
565 let mut changed = false;
566 let mut i = 0usize;
567 while i < CAP_MAX {
568 let parent_id = self.entries[i].parent_id;
569 let live = self.entries[i].state == STATE_LIVE && parent_id != PARENT_NONE;
570 if live && (parent_id as usize) < CAP_MAX {
571 let parent = self.entries[parent_id as usize];
572 if parent.generation == self.entries[i].parent_generation
573 && parent.state == STATE_REVOKED
574 {
575 self.entries[i].state = STATE_REVOKED;
576 changed = true;
577 }
578 }
579 i += 1;
580 }
581 if !changed {
582 break;
583 }
584 }
585 }
586
587 pub fn revoke(&mut self, authority: CapRef, target: CapRef) -> Result<(), i32> {
588 if !self.writer_alive {
589 return Err(ERR_IO);
590 }
591 let auth_index = self.auth_use(authority, RIGHT_REVOKE)?;
592 if target.cap_id as usize >= CAP_MAX {
593 return Err(ERR_BOUNDS);
594 }
595 let auth_rights = self.entries[auth_index].rights;
596 let entry = &mut self.entries[target.cap_id as usize];
597 if entry.generation != target.generation {
598 return Err(ERR_STALE_GEN);
599 }
600 if entry.state != STATE_LIVE {
601 return Err(ERR_STATE);
602 }
603 if (entry.rights & RIGHT_PRIVILEGED) & !auth_rights != 0 {
604 return Err(ERR_UNAUTHORIZED);
605 }
606 entry.state = STATE_REVOKED;
607 self.cascade_revoke();
608 Ok(())
609 }
610
611 pub fn reclaim(&mut self, authority: CapRef, cap_id: u32) -> Result<(), i32> {
612 if !self.writer_alive {
613 return Err(ERR_IO);
614 }
615 self.auth_use(authority, RIGHT_RECLAIM)?;
616 if cap_id as usize >= CAP_MAX {
617 return Err(ERR_BOUNDS);
618 }
619 let entry = &mut self.entries[cap_id as usize];
620 if entry.state != STATE_REVOKED {
621 return Err(ERR_STATE);
622 }
623 let next = generation_advance(entry.generation)?;
624 entry.generation = next;
625 entry.state = STATE_FREE;
626 entry.rights = 0;
627 entry.lease_expiry = 0;
628 entry.parent_id = PARENT_NONE;
629 entry.parent_generation = 0;
630 self.delivered[cap_id as usize] = false;
631 Ok(())
632 }
633
634 pub fn advance_clock(&mut self, authority: CapRef, ticks: u64) -> Result<(), i32> {
635 if !self.writer_alive {
636 return Err(ERR_IO);
637 }
638 self.auth_use(authority, RIGHT_CLOCK)?;
639 self.clock = add_u64(self.clock, ticks)?;
640 Ok(())
641 }
642
643 pub fn bump_epoch(&mut self, authority: CapRef) -> Result<(), i32> {
644 if !self.writer_alive {
645 return Err(ERR_IO);
646 }
647 self.auth_use(authority, RIGHT_EPOCH)?;
648 self.epoch = add_u64(self.epoch, 1)?;
649 Ok(())
650 }
651
652 /// Test seam. Puts a free or revoked slot on a chosen generation so the
653 /// exhaustion rule can be shown without four billion reclamations.
654 /// Refuses a live slot, so it cannot mint a forged generation.
655 pub fn set_generation_for_test(&mut self, cap_id: u32, generation: u32) -> Result<(), i32> {
656 if cap_id as usize >= CAP_MAX {
657 return Err(ERR_BOUNDS);
658 }
659 let entry = &mut self.entries[cap_id as usize];
660 if entry.state == STATE_LIVE {
661 return Err(ERR_STATE);
662 }
663 if generation == 0 {
664 return Err(ERR_EXHAUSTED);
665 }
666 entry.generation = generation;
667 Ok(())
668 }
669}
670
671/// Read-only handle. Cognition and the reaction world may hold this.
672/// It has no office token and no operation that changes the table.
673#[derive(Clone, Copy)]
674pub struct AuthorityView<'a> {
675 state: &'a AuthorityState,
676}
677
678impl<'a> AuthorityView<'a> {
679 pub fn new(state: &'a AuthorityState) -> Self {
680 Self { state }
681 }
682
683 pub fn inspect(self, cap: CapRef) -> Result<Entry, i32> {
684 self.state.inspect(cap)
685 }
686
687 pub fn validate(
688 self,
689 cap: CapRef,
690 subject: u32,
691 resource: u64,
692 rights: u32,
693 ) -> Result<Entry, i32> {
694 self.state.validate(cap, subject, resource, rights)
695 }
696
697 /// The only mint-shaped call cognition is allowed to make. It does not
698 /// look at the table and it does not change it.
699 pub fn cognition_attempt_mint(self, _request: Mint) -> i32 {
700 ERR_UNAUTHORIZED
701 }
702
703 pub fn cognition_attempt_revoke(self, _authority: CapRef, _target: CapRef) -> i32 {
704 ERR_UNAUTHORIZED
705 }
706
707 pub fn cognition_attempt_reclaim(self, _authority: CapRef, _cap_id: u32) -> i32 {
708 ERR_UNAUTHORIZED
709 }
710
711 pub fn cognition_attempt_clock(self, _authority: CapRef, _ticks: u64) -> i32 {
712 ERR_UNAUTHORIZED
713 }
714
715 pub fn cognition_attempt_epoch(self, _authority: CapRef) -> i32 {
716 ERR_UNAUTHORIZED
717 }
718}
719
720/// Office holder. The token never enters [`AuthorityState`].
721pub struct AuthorityAdmin {
722 token: [u8; TOKEN_LEN],
723}
724
725impl AuthorityAdmin {
726 pub fn new(token: [u8; TOKEN_LEN]) -> Self {
727 Self { token }
728 }
729
730 pub fn token_matches(&self, presented: &[u8; TOKEN_LEN]) -> bool {
731 let mut diff = 0u8;
732 let mut i = 0;
733 while i < TOKEN_LEN {
734 diff |= self.token[i] ^ presented[i];
735 i += 1;
736 }
737 diff == 0
738 }
739
740 pub fn authorize(&self, presented: &[u8; TOKEN_LEN]) -> Result<(), i32> {
741 if self.token_matches(presented) {
742 Ok(())
743 } else {
744 Err(ERR_UNAUTHORIZED)
745 }
746 }
747}
748
749#[cfg(test)]
750mod tests {
751 use super::*;
752
753 fn boot() -> AuthorityState {
754 AuthorityState::bootstrap(1).unwrap()
755 }
756
757 fn office(state: &AuthorityState) -> CapRef {
758 state.office()
759 }
760
761 fn root_mint(
762 state: &mut AuthorityState,
763 subject: u32,
764 resource: u64,
765 rights: u32,
766 ) -> Result<CapRef, i32> {
767 state.mint(Mint {
768 issuer: 3,
769 subject,
770 resource,
771 rights,
772 lease_ticks: 0,
773 parent: CapRef::NONE,
774 authority: office(state),
775 })
776 }
777
778 /// The b1fa747 defect, Rust side: a reclaim moves a slot to boot + 1, and
779 /// a restart at boot + 1 made the reference minted after the reclaim
780 /// valid again. A restart must start at or above the old table's floor.
781 #[test]
782 fn reclaimed_reference_stays_dead_after_restart() {
783 let mut state = boot();
784 let first = root_mint(&mut state, 1, 0x40, RIGHT_READ).unwrap();
785 state.revoke(office(&state), first).unwrap();
786 state.reclaim(office(&state), first.cap_id).unwrap();
787 let second = root_mint(&mut state, 1, 0x40, RIGHT_READ).unwrap();
788 assert_eq!(second.cap_id, first.cap_id);
789 assert_eq!(second.generation, first.generation + 1);
790 // The old restart start (boot + 1) is exactly the reused generation.
791 assert_eq!(state.boot_gen() + 1, second.generation);
792 let floor = state.generation_floor();
793 assert!(floor > second.generation);
794 let start = take_boot_gen_above(floor).unwrap();
795 assert!(start >= floor);
796 let mut restarted = AuthorityState::bootstrap(start).unwrap();
797 let fresh = root_mint(&mut restarted, 1, 0x40, RIGHT_READ).unwrap();
798 assert_eq!(fresh.cap_id, second.cap_id);
799 assert!(fresh.generation > second.generation);
800 assert_eq!(
801 restarted.validate(second, 1, 0x40, RIGHT_READ).unwrap_err(),
802 ERR_STALE_GEN
803 );
804 assert_eq!(
805 restarted.validate(first, 1, 0x40, RIGHT_READ).unwrap_err(),
806 ERR_STALE_GEN
807 );
808 assert!(restarted.validate(fresh, 1, 0x40, RIGHT_READ).is_ok());
809 }
810
811 #[test]
812 fn restart_refuses_above_an_exhausted_generation() {
813 let mut state = boot();
814 let cap = root_mint(&mut state, 1, 0x10, RIGHT_READ).unwrap();
815 state.revoke(office(&state), cap).unwrap();
816 state.set_generation_for_test(cap.cap_id, u32::MAX).unwrap();
817 assert_eq!(state.generation_floor(), u32::MAX);
818 assert_eq!(take_boot_gen_above(u32::MAX).unwrap_err(), ERR_EXHAUSTED);
819 assert_eq!(
820 AuthorityState::bootstrap(u32::MAX).unwrap_err(),
821 ERR_EXHAUSTED
822 );
823 let a = take_boot_gen_above(0).unwrap();
824 let b = take_boot_gen_above(0).unwrap();
825 assert!(b > a);
826 }
827
828 #[test]
829 fn high_half_resource_is_kept() {
830 let wide = (1u64 << 32) | 0x51;
831 assert_eq!(narrow_resource(wide), Err(ERR_RESOURCE));
832 assert_eq!(widen_resource(0x51), 0x51);
833 let mut state = boot();
834 let cap = root_mint(&mut state, 1, wide, RIGHT_READ).unwrap();
835 assert!(state.validate(cap, 1, wide, RIGHT_READ).is_ok());
836 assert_eq!(
837 state.validate(cap, 1, 0x51, RIGHT_READ).unwrap_err(),
838 ERR_RESOURCE
839 );
840 }
841
842 #[test]
843 fn forged_stale_subject_resource_and_rights_fail_closed() {
844 let mut state = boot();
845 let cap = root_mint(&mut state, 1, 0x20, RIGHT_WRITE).unwrap();
846 assert_eq!(
847 state
848 .validate(
849 CapRef {
850 cap_id: 200,
851 generation: 7
852 },
853 1,
854 0x20,
855 RIGHT_WRITE
856 )
857 .unwrap_err(),
858 ERR_STALE_GEN
859 );
860 assert_eq!(
861 state
862 .validate(
863 CapRef {
864 cap_id: 300,
865 generation: 1
866 },
867 1,
868 0x20,
869 RIGHT_WRITE
870 )
871 .unwrap_err(),
872 ERR_BOUNDS
873 );
874 state.revoke(office(&state), cap).unwrap();
875 state.reclaim(office(&state), cap.cap_id).unwrap();
876 let reused = root_mint(&mut state, 7, 0x20, RIGHT_WRITE).unwrap();
877 assert_eq!(reused.cap_id, cap.cap_id);
878 assert_eq!(reused.generation, cap.generation + 1);
879 assert_eq!(
880 state.validate(cap, 1, 0x20, RIGHT_WRITE).unwrap_err(),
881 ERR_STALE_GEN
882 );
883 let live = root_mint(&mut state, 1, 0x20, RIGHT_READ).unwrap();
884 assert_eq!(
885 state.validate(live, 9, 0x20, RIGHT_READ).unwrap_err(),
886 ERR_SUBJECT
887 );
888 assert_eq!(
889 state.validate(live, 1, 0x30, RIGHT_READ).unwrap_err(),
890 ERR_RESOURCE
891 );
892 assert_eq!(
893 state.validate(live, 1, 0x20, RIGHT_WRITE).unwrap_err(),
894 ERR_RIGHTS
895 );
896 }
897
898 #[test]
899 fn amplification_lease_epoch_and_revoked_ancestor_fail() {
900 let mut state = boot();
901 let parent = root_mint(&mut state, 1, 0x20, RIGHT_READ | RIGHT_DELEGATE).unwrap();
902 let amplify = state.mint(Mint {
903 issuer: 1,
904 subject: 2,
905 resource: 0x20,
906 rights: RIGHT_READ | RIGHT_WRITE,
907 lease_ticks: 0,
908 parent,
909 authority: parent,
910 });
911 assert_eq!(amplify.unwrap_err(), ERR_AMPLIFY);
912 let child = state
913 .mint(Mint {
914 issuer: 1,
915 subject: 2,
916 resource: 0x20,
917 rights: RIGHT_READ,
918 lease_ticks: 0,
919 parent,
920 authority: parent,
921 })
922 .unwrap();
923 state.revoke(office(&state), parent).unwrap();
924 assert_eq!(state.inspect(child).unwrap().state, STATE_REVOKED);
925 assert_eq!(
926 state.validate(child, 2, 0x20, RIGHT_READ).unwrap_err(),
927 ERR_REVOKED
928 );
929
930 let mut state = boot();
931 let leased = state
932 .mint(Mint {
933 issuer: 3,
934 subject: 1,
935 resource: 0x10,
936 rights: RIGHT_READ,
937 lease_ticks: 5,
938 parent: CapRef::NONE,
939 authority: office(&state),
940 })
941 .unwrap();
942 state.advance_clock(office(&state), 10).unwrap();
943 assert_eq!(
944 state.validate(leased, 1, 0x10, RIGHT_READ).unwrap_err(),
945 ERR_EXPIRED
946 );
947
948 let fresh = root_mint(&mut state, 1, 0x10, RIGHT_READ).unwrap();
949 state.bump_epoch(office(&state)).unwrap();
950 assert_eq!(
951 state.validate(fresh, 1, 0x10, RIGHT_READ).unwrap_err(),
952 ERR_EPOCH
953 );
954 assert_eq!(state.bump_epoch(office(&state)).unwrap_err(), ERR_EPOCH);
955 }
956
957 #[test]
958 fn privileged_rights_cannot_be_delegated_and_office_stays() {
959 let mut state = boot();
960 let both = root_mint(&mut state, 1, RES_AUTHORITY, RIGHT_REVOKE | RIGHT_DELEGATE);
961 assert_eq!(both.unwrap_err(), ERR_NOT_DELEGABLE);
962 let revoker = root_mint(&mut state, 1, RES_AUTHORITY, RIGHT_REVOKE).unwrap();
963 let passed = state.mint(Mint {
964 issuer: 3,
965 subject: 2,
966 resource: RES_AUTHORITY,
967 rights: RIGHT_REVOKE,
968 lease_ticks: 0,
969 parent: revoker,
970 authority: revoker,
971 });
972 assert_eq!(passed.unwrap_err(), ERR_NOT_DELEGABLE);
973 assert_eq!(
974 state.revoke(revoker, office(&state)).unwrap_err(),
975 ERR_UNAUTHORIZED
976 );
977 assert!(state
978 .validate(office(&state), 0, RES_AUTHORITY, RIGHT_MINT)
979 .is_ok());
980 }
981
982 #[test]
983 fn promote_right_cannot_be_delegated() {
984 let mut state = boot();
985 let combined = root_mint(&mut state, 4, 0x905, RIGHT_PROMOTE | RIGHT_DELEGATE);
986 assert_eq!(combined.unwrap_err(), ERR_NOT_DELEGABLE);
987 let promoter = root_mint(&mut state, 4, 0x905, RIGHT_PROMOTE).unwrap();
988 let handed_on = state.mint(Mint {
989 issuer: 4,
990 subject: 5,
991 resource: 0x905,
992 rights: RIGHT_PROMOTE,
993 lease_ticks: 0,
994 parent: promoter,
995 authority: promoter,
996 });
997 assert_eq!(handed_on.unwrap_err(), ERR_NOT_DELEGABLE);
998 assert!(state.validate(promoter, 4, 0x905, RIGHT_PROMOTE).is_ok());
999 assert_eq!(
1000 state
1001 .validate(promoter, 9, 0x905, RIGHT_PROMOTE)
1002 .unwrap_err(),
1003 ERR_SUBJECT
1004 );
1005 }
1006
1007 #[test]
1008 fn generation_wrap_restarts_and_cognition_cannot_mint() {
1009 assert_eq!(generation_advance(u32::MAX).unwrap_err(), ERR_EXHAUSTED);
1010 let mut state = boot();
1011 let cap = root_mint(&mut state, 1, 0x10, RIGHT_READ).unwrap();
1012 state.revoke(office(&state), cap).unwrap();
1013 state.set_generation_for_test(cap.cap_id, u32::MAX).unwrap();
1014 assert_eq!(
1015 state.reclaim(office(&state), cap.cap_id).unwrap_err(),
1016 ERR_EXHAUSTED
1017 );
1018 assert_eq!(
1019 state.validate(cap, 1, 0x10, RIGHT_READ).unwrap_err(),
1020 ERR_STALE_GEN
1021 );
1022 let replacement = root_mint(&mut state, 1, 0x11, RIGHT_READ).unwrap();
1023 assert_ne!(replacement.cap_id, cap.cap_id);
1024
1025 let old = root_mint(&mut state, 1, 0x12, RIGHT_READ).unwrap();
1026 state.kill_writer();
1027 assert_eq!(
1028 root_mint(&mut state, 1, 0x13, RIGHT_READ).unwrap_err(),
1029 ERR_IO
1030 );
1031 let recovered = AuthorityState::bootstrap(state.boot_gen() + 1).unwrap();
1032 assert_eq!(
1033 recovered.validate(old, 1, 0x12, RIGHT_READ).unwrap_err(),
1034 ERR_STALE_GEN
1035 );
1036 assert_ne!(
1037 recovered
1038 .validate(state.office(), 0, RES_AUTHORITY, RIGHT_MINT)
1039 .unwrap_err(),
1040 OK
1041 );
1042
1043 let view = AuthorityView::new(&recovered);
1044 let before = recovered.clock();
1045 assert_eq!(
1046 view.cognition_attempt_mint(Mint {
1047 issuer: 1,
1048 subject: 1,
1049 resource: 1,
1050 rights: RIGHT_READ,
1051 lease_ticks: 0,
1052 parent: CapRef::NONE,
1053 authority: recovered.office(),
1054 }),
1055 ERR_UNAUTHORIZED
1056 );
1057 assert_eq!(
1058 view.cognition_attempt_revoke(recovered.office(), old),
1059 ERR_UNAUTHORIZED
1060 );
1061 assert_eq!(
1062 view.cognition_attempt_epoch(recovered.office()),
1063 ERR_UNAUTHORIZED
1064 );
1065 assert_eq!(recovered.clock(), before);
1066 let admin = AuthorityAdmin::new([9; TOKEN_LEN]);
1067 assert_eq!(
1068 admin.authorize(&[0; TOKEN_LEN]).unwrap_err(),
1069 ERR_UNAUTHORIZED
1070 );
1071 assert!(admin.authorize(&[9; TOKEN_LEN]).is_ok());
1072 }
1073
1074 #[test]
1075 fn ordinary_capability_cannot_administer_and_depth_stops() {
1076 let mut state = boot();
1077 let world = root_mint(&mut state, 1, 0x10, RIGHT_READ).unwrap();
1078 assert_eq!(state.revoke(world, world).unwrap_err(), ERR_UNAUTHORIZED);
1079 assert_eq!(state.advance_clock(world, 1).unwrap_err(), ERR_UNAUTHORIZED);
1080 assert_eq!(state.bump_epoch(world).unwrap_err(), ERR_UNAUTHORIZED);
1081 assert_eq!(
1082 state.reclaim(world, world.cap_id).unwrap_err(),
1083 ERR_UNAUTHORIZED
1084 );
1085 let mut cur = root_mint(&mut state, 1, 0x20, RIGHT_READ | RIGHT_DELEGATE).unwrap();
1086 for _ in 0..8 {
1087 cur = state
1088 .mint(Mint {
1089 issuer: 3,
1090 subject: 2,
1091 resource: 0x20,
1092 rights: RIGHT_READ | RIGHT_DELEGATE,
1093 lease_ticks: 0,
1094 parent: cur,
1095 authority: cur,
1096 })
1097 .unwrap();
1098 }
1099 let too_deep = state.mint(Mint {
1100 issuer: 3,
1101 subject: 2,
1102 resource: 0x20,
1103 rights: RIGHT_READ | RIGHT_DELEGATE,
1104 lease_ticks: 0,
1105 parent: cur,
1106 authority: cur,
1107 });
1108 assert_eq!(too_deep.unwrap_err(), ERR_CHAIN);
1109 }
1110
1111 // ---- ABI-qualification regression set (mirrors native/capability/tests) ----
1112
1113 #[test]
1114 fn stale_reference_after_revoke_is_refused() {
1115 let mut state = boot();
1116 let cap = root_mint(&mut state, 1, 0x60, RIGHT_READ).unwrap();
1117 assert!(state.validate(cap, 1, 0x60, RIGHT_READ).is_ok());
1118 state.revoke(office(&state), cap).unwrap();
1119 assert_eq!(
1120 state.validate(cap, 1, 0x60, RIGHT_READ).unwrap_err(),
1121 ERR_REVOKED
1122 );
1123 assert_eq!(state.revoke(office(&state), cap).unwrap_err(), ERR_STATE);
1124 state.reclaim(office(&state), cap.cap_id).unwrap();
1125 assert_eq!(
1126 state.validate(cap, 1, 0x60, RIGHT_READ).unwrap_err(),
1127 ERR_STALE_GEN
1128 );
1129 assert_eq!(state.inspect(cap).unwrap_err(), ERR_STALE_GEN);
1130 // A revoked minting authority cannot mint.
1131 let minter = root_mint(&mut state, 0, RES_AUTHORITY, RIGHT_MINT).unwrap();
1132 state.revoke(office(&state), minter).unwrap();
1133 let refused = state.mint(Mint {
1134 issuer: 3,
1135 subject: 1,
1136 resource: 0x61,
1137 rights: RIGHT_READ,
1138 lease_ticks: 0,
1139 parent: CapRef::NONE,
1140 authority: minter,
1141 });
1142 assert_eq!(refused.unwrap_err(), ERR_REVOKED);
1143 }
1144
1145 #[test]
1146 fn recycled_slot_does_not_honour_old_reference() {
1147 let mut state = boot();
1148 let old = root_mint(&mut state, 1, 0x70, RIGHT_READ | RIGHT_DELEGATE).unwrap();
1149 state.revoke(office(&state), old).unwrap();
1150 state.reclaim(office(&state), old.cap_id).unwrap();
1151 let new = root_mint(&mut state, 1, 0x70, RIGHT_READ | RIGHT_DELEGATE).unwrap();
1152 assert_eq!(new.cap_id, old.cap_id);
1153 assert!(new.generation > old.generation);
1154 assert_eq!(
1155 state.validate(old, 1, 0x70, RIGHT_READ).unwrap_err(),
1156 ERR_STALE_GEN
1157 );
1158 assert_eq!(state.inspect(old).unwrap_err(), ERR_STALE_GEN);
1159 // The old reference cannot revoke or delegate from the new holder.
1160 assert_eq!(
1161 state.revoke(office(&state), old).unwrap_err(),
1162 ERR_STALE_GEN
1163 );
1164 let via_old = state.mint(Mint {
1165 issuer: 1,
1166 subject: 2,
1167 resource: 0x70,
1168 rights: RIGHT_READ,
1169 lease_ticks: 0,
1170 parent: old,
1171 authority: old,
1172 });
1173 assert_eq!(via_old.unwrap_err(), ERR_STALE_GEN);
1174 assert!(state.validate(new, 1, 0x70, RIGHT_READ).is_ok());
1175 }
1176
1177 #[test]
1178 fn generation_exhaustion_fails_closed() {
1179 assert_eq!(generation_advance(u32::MAX).unwrap_err(), ERR_EXHAUSTED);
1180 assert_eq!(generation_advance(u32::MAX - 1), Ok(u32::MAX));
1181 let mut state = boot();
1182 let cap = root_mint(&mut state, 1, 0x10, RIGHT_READ).unwrap();
1183 state.revoke(office(&state), cap).unwrap();
1184 state.set_generation_for_test(cap.cap_id, u32::MAX).unwrap();
1185 assert_eq!(
1186 state.reclaim(office(&state), cap.cap_id).unwrap_err(),
1187 ERR_EXHAUSTED
1188 );
1189 assert_eq!(
1190 state.validate(cap, 1, 0x10, RIGHT_READ).unwrap_err(),
1191 ERR_STALE_GEN
1192 );
1193 let replacement = root_mint(&mut state, 1, 0x11, RIGHT_READ).unwrap();
1194 assert_ne!(replacement.cap_id, cap.cap_id);
1195 // A live slot cannot be moved onto a chosen generation.
1196 assert_eq!(
1197 state
1198 .set_generation_for_test(replacement.cap_id, 99)
1199 .unwrap_err(),
1200 ERR_STATE
1201 );
1202 // Every free slot exhausted: mint refuses rather than reuse one.
1203 for id in 0..CAP_MAX as u32 {
1204 let _ = state.set_generation_for_test(id, u32::MAX);
1205 }
1206 assert_eq!(
1207 root_mint(&mut state, 1, 0x12, RIGHT_READ).unwrap_err(),
1208 ERR_EXHAUSTED
1209 );
1210 }
1211
1212 #[test]
1213 fn unauthorized_capability_use_is_refused() {
1214 let mut state = boot();
1215 let cap = root_mint(&mut state, 1, 0x80, RIGHT_READ).unwrap();
1216 assert_eq!(
1217 state.validate(cap, 2, 0x80, RIGHT_READ).unwrap_err(),
1218 ERR_SUBJECT
1219 );
1220 assert_eq!(
1221 state.validate(cap, 1, 0x81, RIGHT_READ).unwrap_err(),
1222 ERR_RESOURCE
1223 );
1224 assert_eq!(
1225 state.validate(cap, 1, 0x80, RIGHT_WRITE).unwrap_err(),
1226 ERR_RIGHTS
1227 );
1228 let request = |authority: CapRef, rights: u32| Mint {
1229 issuer: 3,
1230 subject: 1,
1231 resource: 0x82,
1232 rights,
1233 lease_ticks: 0,
1234 parent: CapRef::NONE,
1235 authority,
1236 };
1237 // An ordinary capability is not an office authority.
1238 assert_eq!(
1239 state.mint(request(cap, RIGHT_READ)).unwrap_err(),
1240 ERR_UNAUTHORIZED
1241 );
1242 // A slot never handed out, and one out of range, authorize nothing.
1243 let undelivered = CapRef {
1244 cap_id: 200,
1245 generation: state.boot_gen(),
1246 };
1247 assert_eq!(
1248 state.mint(request(undelivered, RIGHT_READ)).unwrap_err(),
1249 ERR_UNAUTHORIZED
1250 );
1251 let out_of_range = CapRef {
1252 cap_id: CAP_MAX as u32,
1253 generation: state.boot_gen(),
1254 };
1255 assert_eq!(
1256 state.mint(request(out_of_range, RIGHT_READ)).unwrap_err(),
1257 ERR_UNAUTHORIZED
1258 );
1259 // A minting authority cannot hand out a privilege it does not hold.
1260 let minter = root_mint(&mut state, 0, RES_AUTHORITY, RIGHT_MINT).unwrap();
1261 assert!(state.mint(request(minter, RIGHT_READ)).is_ok());
1262 assert_eq!(
1263 state.mint(request(minter, RIGHT_REVOKE)).unwrap_err(),
1264 ERR_UNAUTHORIZED
1265 );
1266 // Delegation must be authorized by the parent itself.
1267 let parent = root_mint(&mut state, 1, 0x83, RIGHT_READ | RIGHT_DELEGATE).unwrap();
1268 let mismatched = state.mint(Mint {
1269 issuer: 1,
1270 subject: 2,
1271 resource: 0x83,
1272 rights: RIGHT_READ,
1273 lease_ticks: 0,
1274 parent,
1275 authority: office(&state),
1276 });
1277 assert_eq!(mismatched.unwrap_err(), ERR_UNAUTHORIZED);
1278 // A non-office reference cannot reclaim, revoke, move the clock or epoch.
1279 assert_eq!(
1280 state.reclaim(cap, cap.cap_id).unwrap_err(),
1281 ERR_UNAUTHORIZED
1282 );
1283 assert_eq!(state.revoke(cap, parent).unwrap_err(), ERR_UNAUTHORIZED);
1284 assert_eq!(state.advance_clock(cap, 1).unwrap_err(), ERR_UNAUTHORIZED);
1285 assert_eq!(state.bump_epoch(cap).unwrap_err(), ERR_UNAUTHORIZED);
1286 let view = AuthorityView::new(&state);
1287 assert_eq!(
1288 view.cognition_attempt_reclaim(office(&state), cap.cap_id),
1289 ERR_UNAUTHORIZED
1290 );
1291 assert_eq!(
1292 view.cognition_attempt_clock(office(&state), 1),
1293 ERR_UNAUTHORIZED
1294 );
1295 }
1296}