aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-kernel / src / recovery_core.rs
| 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 | //! Deterministic Recovery Core entry, inspection and operator-authorised |
| 17 | //! actions over System Store v1 and continuity (ADR 0006, ADR 0007, ADR 0016). |
| 18 | //! |
| 19 | //! No model, no network. Inspection never writes. Every write is an explicit |
| 20 | //! operator action whose challenge is bound to the exact on-disk state it |
| 21 | //! acts on, so an authorisation cannot be replayed onto a different state or |
| 22 | //! used for a different action. No action here can create an identity on a |
| 23 | //! store that already holds data it cannot account for. |
| 24 | |
| 25 | use crate::continuity::{self, Continuity, ContinuityError, ProvisionSource}; |
| 26 | use crate::crypto::sha256::Sha256; |
| 27 | use crate::recovery::OperatorAuth; |
| 28 | use crate::store::engine::{MountError, MountState, PeerCondition, Store, StoreDevice}; |
| 29 | use crate::store::v1::{FormatError, Superblock, STORE_UNIT_BYTES}; |
| 30 | |
| 31 | /// What one superblock slot holds. |
| 32 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 33 | pub enum SlotView { |
| 34 | Zero, |
| 35 | Superblock { generation: u64 }, |
| 36 | Undecodable(FormatError), |
| 37 | ReadError, |
| 38 | } |
| 39 | |
| 40 | /// Why the Recovery Core was entered (or `None` when a normal boot may proceed). |
| 41 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 42 | pub enum EntryReason { |
| 43 | StoreUnformatted, |
| 44 | StoreMount(MountError), |
| 45 | Unprovisioned, |
| 46 | Conflict, |
| 47 | ContinuityCorrupt(&'static str), |
| 48 | Degraded(PeerCondition), |
| 49 | } |
| 50 | |
| 51 | /// Operator actions the Recovery Core can perform. |
| 52 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 53 | pub enum Action { |
| 54 | /// Zero the inactive superblock slot of a `DegradedRecovery` store so it |
| 55 | /// mounts writable again on its valid root. |
| 56 | RepairDegradedPeer = 1, |
| 57 | /// Create the one identity on a formatted store with no agent root. |
| 58 | ProvisionIdentity = 2, |
| 59 | } |
| 60 | |
| 61 | impl Action { |
| 62 | pub const fn name(self) -> &'static str { |
| 63 | match self { |
| 64 | Action::RepairDegradedPeer => "repair-degraded-peer", |
| 65 | Action::ProvisionIdentity => "provision-identity", |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// The read-only raw system record printed on entry. |
| 71 | #[derive(Clone, Debug)] |
| 72 | pub struct SystemRecord { |
| 73 | pub slots: [SlotView; 2], |
| 74 | /// SHA-256 over both raw superblock units: binds challenges to this state. |
| 75 | pub state_digest: [u8; 32], |
| 76 | pub store_uuid: Option<[u8; 16]>, |
| 77 | pub mount: Option<(MountState, PeerCondition, u64)>, |
| 78 | pub reason: Option<EntryReason>, |
| 79 | pub continuity: Option<Continuity>, |
| 80 | /// Catalog entry counts: agent roots, manifests, other. |
| 81 | pub catalog: Option<(usize, usize, usize)>, |
| 82 | } |
| 83 | |
| 84 | impl SystemRecord { |
| 85 | /// The action this state admits, if any. |
| 86 | /// Failure semantics fail toward preservation (ADR 0007): |
| 87 | /// - repair only a *malformed* peer, and only when the valid root still |
| 88 | /// resolves the identity, so the repair cannot lose it; |
| 89 | /// - never discard a CRC-valid newer root whose graph is broken: that |
| 90 | /// would roll back committed state, so it is an out-of-band decision; |
| 91 | /// - provision only on a healthy (`Valid`) mount with no continuity |
| 92 | /// objects at all. A degraded mount is never treated as unprovisioned, |
| 93 | /// because the identity may live in the root that did not validate. |
| 94 | pub fn applicable(&self) -> Option<Action> { |
| 95 | let (mount, _, _) = self.mount?; |
| 96 | match self.reason? { |
| 97 | EntryReason::Degraded(PeerCondition::Malformed) if self.continuity.is_some() => { |
| 98 | Some(Action::RepairDegradedPeer) |
| 99 | } |
| 100 | EntryReason::Unprovisioned if mount == MountState::Valid => { |
| 101 | Some(Action::ProvisionIdentity) |
| 102 | } |
| 103 | _ => None, |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | /// Challenge for `action` on exactly this state: |
| 108 | /// SHA-256(domain || store uuid || generation || action || state digest). |
| 109 | pub fn challenge(&self, action: Action) -> Option<[u8; 32]> { |
| 110 | let uuid = self.store_uuid?; |
| 111 | let (_, _, generation) = self.mount?; |
| 112 | let mut h = Sha256::new(); |
| 113 | h.update(b"AIENOS-RECOVERY-CHALLENGE-v1\0"); |
| 114 | h.update(&uuid); |
| 115 | h.update(&generation.to_le_bytes()); |
| 116 | h.update(&[action as u8]); |
| 117 | h.update(&self.state_digest); |
| 118 | Some(h.finalize()) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /// Inspects `device` in place. Never writes. |
| 123 | pub fn inspect<D: StoreDevice>(device: &mut D) -> SystemRecord { |
| 124 | let mut raw = [[0u8; STORE_UNIT_BYTES]; 2]; |
| 125 | let mut slots = [SlotView::ReadError; 2]; |
| 126 | let mut uuid = None; |
| 127 | for slot in 0..2 { |
| 128 | if device.read_unit(slot as u64, &mut raw[slot]).is_err() { |
| 129 | continue; |
| 130 | } |
| 131 | slots[slot] = if raw[slot].iter().all(|b| *b == 0) { |
| 132 | SlotView::Zero |
| 133 | } else { |
| 134 | match Superblock::decode(&raw[slot], slot as u32) { |
| 135 | Ok(sb) => { |
| 136 | uuid.get_or_insert(sb.store_uuid); |
| 137 | SlotView::Superblock { |
| 138 | generation: sb.generation, |
| 139 | } |
| 140 | } |
| 141 | Err(e) => SlotView::Undecodable(e), |
| 142 | } |
| 143 | }; |
| 144 | } |
| 145 | let mut h = Sha256::new(); |
| 146 | h.update(&raw[0]); |
| 147 | h.update(&raw[1]); |
| 148 | let state_digest = h.finalize(); |
| 149 | |
| 150 | let mut record = SystemRecord { |
| 151 | slots, |
| 152 | state_digest, |
| 153 | store_uuid: uuid, |
| 154 | mount: None, |
| 155 | reason: None, |
| 156 | continuity: None, |
| 157 | catalog: None, |
| 158 | }; |
| 159 | |
| 160 | let mut store = match Store::open(Borrowed(device)) { |
| 161 | Ok(store) => store, |
| 162 | Err(e) => { |
| 163 | record.reason = Some(match e { |
| 164 | MountError::Unformatted => EntryReason::StoreUnformatted, |
| 165 | other => EntryReason::StoreMount(other), |
| 166 | }); |
| 167 | return record; |
| 168 | } |
| 169 | }; |
| 170 | record.mount = Some(( |
| 171 | store.mount_state(), |
| 172 | store.peer_condition(), |
| 173 | store.generation(), |
| 174 | )); |
| 175 | let entries = &store.catalog().entries; |
| 176 | let roots = entries |
| 177 | .iter() |
| 178 | .filter(|e| e.kind == continuity::KIND_AGENT_ROOT) |
| 179 | .count(); |
| 180 | let manifests = entries |
| 181 | .iter() |
| 182 | .filter(|e| e.kind == continuity::KIND_MANIFEST) |
| 183 | .count(); |
| 184 | record.catalog = Some((roots, manifests, entries.len() - roots - manifests)); |
| 185 | |
| 186 | let resolved = continuity::resolve(&mut store); |
| 187 | record.reason = if store.mount_state() == MountState::DegradedRecovery { |
| 188 | // Degraded takes precedence: what the valid (older) root says about |
| 189 | // continuity is not the whole story. |
| 190 | Some(EntryReason::Degraded(store.peer_condition())) |
| 191 | } else { |
| 192 | match &resolved { |
| 193 | Ok(_) => None, |
| 194 | Err(ContinuityError::Unprovisioned) => Some(EntryReason::Unprovisioned), |
| 195 | Err(ContinuityError::Conflict) => Some(EntryReason::Conflict), |
| 196 | Err(ContinuityError::Corrupt(why)) => Some(EntryReason::ContinuityCorrupt(why)), |
| 197 | Err(_) => Some(EntryReason::ContinuityCorrupt("continuity unreadable")), |
| 198 | } |
| 199 | }; |
| 200 | record.continuity = resolved.ok(); |
| 201 | record |
| 202 | } |
| 203 | |
| 204 | /// Borrowing adapter: `Store::open` takes its device by value, and a failed |
| 205 | /// mount must not lose the caller's device. |
| 206 | struct Borrowed<'a, D: StoreDevice>(&'a mut D); |
| 207 | |
| 208 | impl<D: StoreDevice> StoreDevice for Borrowed<'_, D> { |
| 209 | type Error = D::Error; |
| 210 | fn region_units(&self) -> u64 { |
| 211 | self.0.region_units() |
| 212 | } |
| 213 | fn read_unit(&mut self, unit: u64, out: &mut [u8; STORE_UNIT_BYTES]) -> Result<(), D::Error> { |
| 214 | self.0.read_unit(unit, out) |
| 215 | } |
| 216 | fn write_unit(&mut self, unit: u64, bytes: &[u8; STORE_UNIT_BYTES]) -> Result<(), D::Error> { |
| 217 | self.0.write_unit(unit, bytes) |
| 218 | } |
| 219 | fn flush(&mut self) -> Result<(), D::Error> { |
| 220 | self.0.flush() |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 225 | pub enum RecoveryError { |
| 226 | /// The state does not admit this action. |
| 227 | NotApplicable, |
| 228 | /// The operator response did not verify for this state and action. |
| 229 | Unauthorised, |
| 230 | Io, |
| 231 | Continuity(ContinuityError), |
| 232 | } |
| 233 | |
| 234 | fn authorise( |
| 235 | record: &SystemRecord, |
| 236 | action: Action, |
| 237 | operator_key: &[u8; 32], |
| 238 | response: &[u8; 32], |
| 239 | ) -> Result<(), RecoveryError> { |
| 240 | if record.applicable() != Some(action) { |
| 241 | return Err(RecoveryError::NotApplicable); |
| 242 | } |
| 243 | let challenge = record |
| 244 | .challenge(action) |
| 245 | .ok_or(RecoveryError::NotApplicable)?; |
| 246 | if !OperatorAuth::verify_offline_credentials(operator_key, &challenge, response) { |
| 247 | return Err(RecoveryError::Unauthorised); |
| 248 | } |
| 249 | Ok(()) |
| 250 | } |
| 251 | |
| 252 | /// Zeroes the inactive superblock slot of a degraded store after verifying |
| 253 | /// the operator's response. Nothing is written unless authorisation passes. |
| 254 | pub fn repair_degraded_peer<D: StoreDevice>( |
| 255 | device: &mut D, |
| 256 | operator_key: &[u8; 32], |
| 257 | response: &[u8; 32], |
| 258 | ) -> Result<SystemRecord, RecoveryError> { |
| 259 | let record = inspect(device); |
| 260 | authorise(&record, Action::RepairDegradedPeer, operator_key, response)?; |
| 261 | // The valid root is the decodable slot the engine mounted; the other goes. |
| 262 | let active = { |
| 263 | let store = Store::open(Borrowed(device)).map_err(|_| RecoveryError::Io)?; |
| 264 | store.active_slot() as u64 |
| 265 | }; |
| 266 | let peer = 1 - active; |
| 267 | device |
| 268 | .write_unit(peer, &[0u8; STORE_UNIT_BYTES]) |
| 269 | .map_err(|_| RecoveryError::Io)?; |
| 270 | device.flush().map_err(|_| RecoveryError::Io)?; |
| 271 | Ok(inspect(device)) |
| 272 | } |
| 273 | |
| 274 | /// Provisions the one identity on an unprovisioned store after verifying the |
| 275 | /// operator's response. Refused on any other state. |
| 276 | pub fn provision_identity<D: StoreDevice>( |
| 277 | device: &mut D, |
| 278 | operator_key: &[u8; 32], |
| 279 | response: &[u8; 32], |
| 280 | agent_id: [u8; 32], |
| 281 | ) -> Result<Continuity, RecoveryError> { |
| 282 | let record = inspect(device); |
| 283 | authorise(&record, Action::ProvisionIdentity, operator_key, response)?; |
| 284 | let uuid = record.store_uuid.ok_or(RecoveryError::NotApplicable)?; |
| 285 | let mut store = Store::open(Borrowed(device)).map_err(|_| RecoveryError::Io)?; |
| 286 | continuity::provision(&mut store, agent_id, uuid, ProvisionSource::Operator) |
| 287 | .map_err(RecoveryError::Continuity) |
| 288 | } |
| 289 | |
| 290 | #[cfg(test)] |
| 291 | #[path = "recovery_core_tests.rs"] |
| 292 | mod tests; |