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 / recovery_core_tests.rs

330 lines · 11284 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
16use super::*;
17use crate::continuity::{self, CortexRecord, Epistemic, ProvisionSource, Update};
18use crate::store::genesis::genesis_units;
19use alloc::vec;
20use alloc::vec::Vec;
21
22const UUID: [u8; 16] = [0x5a; 16];
23const AGENT: [u8; 32] = [0x11; 32];
24const OPERATOR: [u8; 32] = [0x0f; 32];
25
26#[derive(Clone, PartialEq, Eq)]
27struct Mem {
28 units: Vec<[u8; STORE_UNIT_BYTES]>,
29}
30
31impl StoreDevice for Mem {
32 type Error = ();
33 fn region_units(&self) -> u64 {
34 self.units.len() as u64
35 }
36 fn read_unit(
37 &mut self,
38 unit: u64,
39 out: &mut [u8; STORE_UNIT_BYTES],
40 ) -> core::result::Result<(), ()> {
41 *out = *self.units.get(unit as usize).ok_or(())?;
42 Ok(())
43 }
44 fn write_unit(
45 &mut self,
46 unit: u64,
47 bytes: &[u8; STORE_UNIT_BYTES],
48 ) -> core::result::Result<(), ()> {
49 *self.units.get_mut(unit as usize).ok_or(())? = *bytes;
50 Ok(())
51 }
52 fn flush(&mut self) -> core::result::Result<(), ()> {
53 Ok(())
54 }
55}
56
57fn blank() -> Mem {
58 Mem {
59 units: vec![[0u8; STORE_UNIT_BYTES]; 256],
60 }
61}
62
63fn formatted() -> Mem {
64 let mut dev = blank();
65 for (i, u) in genesis_units(UUID, 256).iter().enumerate() {
66 dev.units[i] = *u;
67 }
68 dev
69}
70
71/// Provisioned, with one remembered fact committed.
72fn remembered() -> Mem {
73 let mut store = Store::open(formatted()).unwrap();
74 let c = continuity::provision(&mut store, AGENT, UUID, ProvisionSource::Qualification).unwrap();
75 continuity::commit(
76 &mut store,
77 &c,
78 Update {
79 state: None,
80 cortex: vec![CortexRecord {
81 status: Epistemic::OperatorDecision,
82 evidence_hash: [0; 32],
83 statement: b"keep this".to_vec(),
84 }],
85 },
86 false,
87 )
88 .unwrap();
89 store.into_device()
90}
91
92fn degraded() -> Mem {
93 let mut dev = remembered();
94 let active = Store::open(dev.clone()).unwrap().active_slot() as usize;
95 dev.units[1 - active] = [0xa5; STORE_UNIT_BYTES];
96 dev
97}
98
99fn respond(record: &SystemRecord, action: Action, key: &[u8; 32]) -> [u8; 32] {
100 OperatorAuth::expected_response(key, &record.challenge(action).unwrap())
101}
102
103#[test]
104fn inspection_never_writes_and_names_the_reason() {
105 let cases: [(Mem, Option<EntryReason>); 4] = [
106 (blank(), Some(EntryReason::StoreUnformatted)),
107 (formatted(), Some(EntryReason::Unprovisioned)),
108 (remembered(), None),
109 (
110 degraded(),
111 Some(EntryReason::Degraded(PeerCondition::Malformed)),
112 ),
113 ];
114 for (dev, want) in cases {
115 let mut probe = dev.clone();
116 let record = inspect(&mut probe);
117 assert!(probe == dev, "inspection wrote to the device");
118 assert_eq!(record.reason, want);
119 }
120 let r = inspect(&mut remembered());
121 assert_eq!(r.continuity.unwrap().root.agent_id, AGENT);
122 assert_eq!(r.catalog.unwrap().0, 1, "one agent root");
123}
124
125#[test]
126fn degraded_repair_needs_the_operator_and_restores_a_writable_store() {
127 let mut dev = degraded();
128 let record = inspect(&mut dev);
129 assert_eq!(record.applicable(), Some(Action::RepairDegradedPeer));
130 let good = respond(&record, Action::RepairDegradedPeer, &OPERATOR);
131
132 // Wrong key, wrong action, zero response: refused, nothing written.
133 let before = dev.clone();
134 let wrong_key = respond(&record, Action::RepairDegradedPeer, &[0x0e; 32]);
135 let wrong_action = respond(&record, Action::ProvisionIdentity, &OPERATOR);
136 for bad in [wrong_key, wrong_action, [0; 32]] {
137 assert_eq!(
138 repair_degraded_peer(&mut dev, &OPERATOR, &bad).map(|_| ()),
139 Err(RecoveryError::Unauthorised)
140 );
141 assert!(dev == before, "a refused repair wrote to the device");
142 }
143 // Provisioning is not the applicable action here.
144 assert_eq!(
145 provision_identity(&mut dev, &OPERATOR, &wrong_action, [0x22; 32]).map(|_| ()),
146 Err(RecoveryError::NotApplicable)
147 );
148
149 let after = repair_degraded_peer(&mut dev, &OPERATOR, &good).unwrap();
150 assert_eq!(after.reason, None, "store is healthy after repair");
151 let (mount, peer, _) = after.mount.unwrap();
152 assert_eq!((mount, peer), (MountState::Valid, PeerCondition::Zero));
153
154 // Same identity and memory, and it is writable again.
155 let mut store = Store::open(dev.clone()).unwrap();
156 let (c, committed) = continuity::resume(&mut store).unwrap();
157 assert!(committed);
158 assert_eq!(c.root.agent_id, AGENT);
159 assert_eq!(c.cortex[0].statement, b"keep this".to_vec());
160
161 // Replaying the old authorisation on the new state does nothing.
162 let mut dev = store.into_device();
163 let snapshot = dev.clone();
164 assert!(repair_degraded_peer(&mut dev, &OPERATOR, &good).is_err());
165 assert!(dev == snapshot);
166}
167
168#[test]
169fn provisioning_is_operator_only_and_only_on_an_unprovisioned_store() {
170 let mut dev = formatted();
171 let record = inspect(&mut dev);
172 assert_eq!(record.applicable(), Some(Action::ProvisionIdentity));
173 let before = dev.clone();
174 assert_eq!(
175 provision_identity(&mut dev, &OPERATOR, &[7; 32], AGENT).map(|_| ()),
176 Err(RecoveryError::Unauthorised)
177 );
178 assert!(dev == before);
179
180 let good = respond(&record, Action::ProvisionIdentity, &OPERATOR);
181 let c = provision_identity(&mut dev, &OPERATOR, &good, AGENT).unwrap();
182 assert_eq!(c.root.agent_id, AGENT);
183 assert_eq!(c.root.source, ProvisionSource::Operator);
184
185 // The same authorisation cannot provision again.
186 assert_eq!(
187 provision_identity(&mut dev, &OPERATOR, &good, [0x33; 32]).map(|_| ()),
188 Err(RecoveryError::NotApplicable)
189 );
190}
191
192#[test]
193fn identity_lost_in_the_newest_root_never_looks_unprovisioned() {
194 // Found by the QEMU campaign: provision (generation 2) then corrupt the
195 // agent root. The graph-broken generation-2 root makes the Store mount
196 // degraded on generation 1 (genesis, no identity). That must not read as
197 // "unprovisioned", even to an operator holding a valid key.
198 let mut store = Store::open(formatted()).unwrap();
199 continuity::provision(&mut store, AGENT, UUID, ProvisionSource::Qualification).unwrap();
200 let mut dev = store.into_device();
201 let root_unit = Store::open(dev.clone())
202 .unwrap()
203 .catalog()
204 .entries
205 .iter()
206 .find(|e| e.kind == continuity::KIND_AGENT_ROOT)
207 .unwrap()
208 .first_unit;
209 dev.units[root_unit as usize][20] ^= 0xff;
210
211 let record = inspect(&mut dev);
212 assert_eq!(
213 record.reason,
214 Some(EntryReason::Degraded(PeerCondition::GraphBadNewer))
215 );
216 assert_eq!(record.applicable(), None);
217
218 // A response that is genuinely valid for this exact state still cannot
219 // provision or repair: the refusal is the preservation rule, not the key.
220 let before = dev.clone();
221 for action in [Action::ProvisionIdentity, Action::RepairDegradedPeer] {
222 let valid = respond(&record, action, &OPERATOR);
223 let result = match action {
224 Action::ProvisionIdentity => {
225 provision_identity(&mut dev, &OPERATOR, &valid, [0x22; 32]).map(|_| ())
226 }
227 Action::RepairDegradedPeer => {
228 repair_degraded_peer(&mut dev, &OPERATOR, &valid).map(|_| ())
229 }
230 };
231 assert_eq!(result, Err(RecoveryError::NotApplicable), "{action:?}");
232 }
233 assert!(dev == before, "nothing was written");
234}
235
236#[test]
237fn malformed_peer_without_a_resolvable_identity_is_not_repaired() {
238 // Garbage in slot B of a formatted store that never had an identity: the
239 // valid root resolves no identity, so repair is not offered either.
240 let mut dev = formatted();
241 dev.units[1] = [0xa5; STORE_UNIT_BYTES];
242 let record = inspect(&mut dev);
243 assert_eq!(
244 record.reason,
245 Some(EntryReason::Degraded(PeerCondition::Malformed))
246 );
247 assert_eq!(record.applicable(), None);
248}
249
250#[test]
251fn orphaned_continuity_objects_are_corrupt_not_unprovisioned() {
252 // A manifest without its agent root means the identity was lost.
253 let mut store = Store::open(formatted()).unwrap();
254 let orphan = continuity::Manifest {
255 root: crate::store::v1::ObjectId([0x77; 32]),
256 previous: None,
257 sequence: 1,
258 incarnation: 1,
259 agent_state: None,
260 cortex_wal: Vec::new(),
261 }
262 .encode()
263 .unwrap();
264 store
265 .transact(&[crate::store::engine::ObjectInput {
266 kind: continuity::KIND_MANIFEST,
267 version: continuity::STORE_OBJECT_VERSION,
268 bytes: &orphan,
269 }])
270 .unwrap();
271 let mut dev = store.into_device();
272 let record = inspect(&mut dev);
273 assert!(
274 matches!(record.reason, Some(EntryReason::ContinuityCorrupt(_))),
275 "{:?}",
276 record.reason
277 );
278 assert_eq!(record.applicable(), None);
279}
280
281#[test]
282fn identity_loss_through_corruption_offers_no_action_that_mints() {
283 // Corrupt the agent root object's bytes: the Store graph no longer
284 // validates, so the Recovery Core must stop, not provision.
285 let mut dev = remembered();
286 let root_unit = {
287 let store = Store::open(dev.clone()).unwrap();
288 store
289 .catalog()
290 .entries
291 .iter()
292 .find(|e| e.kind == continuity::KIND_AGENT_ROOT)
293 .unwrap()
294 .first_unit
295 };
296 dev.units[root_unit as usize][20] ^= 0xff;
297 let record = inspect(&mut dev);
298 assert!(
299 matches!(
300 record.reason,
301 Some(EntryReason::StoreMount(_) | EntryReason::ContinuityCorrupt(_))
302 ),
303 "{:?}",
304 record.reason
305 );
306 assert_eq!(record.applicable(), None);
307 let before = dev.clone();
308 let forged = [0x55; 32];
309 assert!(provision_identity(&mut dev, &OPERATOR, &forged, [0x22; 32]).is_err());
310 assert!(repair_degraded_peer(&mut dev, &OPERATOR, &forged).is_err());
311 assert!(dev == before, "no action wrote after identity loss");
312}
313
314#[test]
315fn challenges_bind_state_and_action() {
316 let r1 = inspect(&mut degraded());
317 let mut other = degraded();
318 let active = Store::open(other.clone()).unwrap().active_slot() as usize;
319 other.units[1 - active] = [0x5a; STORE_UNIT_BYTES];
320 let r2 = inspect(&mut other);
321 assert_ne!(
322 r1.challenge(Action::RepairDegradedPeer),
323 r2.challenge(Action::RepairDegradedPeer),
324 "different on-disk state, different challenge"
325 );
326 assert_ne!(
327 r1.challenge(Action::RepairDegradedPeer),
328 r1.challenge(Action::ProvisionIdentity)
329 );
330}