Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-evidence/src/rollback.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-evidence / src / rollback.rs` 505 lines ยท 17322 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 //! Machine 1 native-boot rollback verdict (docs/NATIVE_BOOT_ONE_TIME.md). 17 //! 18 //! Compares the pre-boot and post-return captures written by 19 //! `scripts/verify_native_rollback.sh --capture-pre/--capture-post` and prints 20 //! the report and verdict. Exit status: 0 PASS, 1 FAIL, 3 BLOCKED, and 2 when a 21 //! capture cannot be read or does not have the capture shape. 22 //! 23 //! This replaces the former embedded Python verifier. The report lines keep 24 //! that verifier's wording, including its rendering of missing values as 25 //! `None`, booleans as `True`/`False` and lists as `['a', 'b']`, so earlier 26 //! reports stay comparable. 27 28 use serde_json::{Map, Value}; 29 30 #[derive(Debug, Eq, PartialEq)] 31 pub enum Verdict { 32 Pass, 33 Fail, 34 Blocked, 35 } 36 37 impl Verdict { 38 pub fn exit_code(&self) -> i32 { 39 match self { 40 Verdict::Pass => 0, 41 Verdict::Fail => 1, 42 Verdict::Blocked => 3, 43 } 44 } 45 } 46 47 /// Exit status when a capture file is unreadable or malformed. 48 pub const EXIT_UNPARSEABLE: i32 = 2; 49 50 /// Top-level fields that must be strings when present (the verifier lowercases, 51 /// splits or trims them). 52 const STRING_FIELDS: [&str; 4] = ["secure_boot", "boot_order", "boot_current", "boot_next"]; 53 54 /// Reads and parses one capture, checking the shape the verifier relies on. 55 /// The error text follows `ERROR: Cannot parse : `. 56 pub fn load(path: &str) -> Result { 57 let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?; 58 let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; 59 check_shape(&v)?; 60 Ok(v) 61 } 62 63 /// A capture must be a JSON object; the fields the verifier transforms must be 64 /// strings when present, and `root`/`esp` must be objects when present. 65 pub fn check_shape(v: &Value) -> Result<(), String> { 66 let obj = v 67 .as_object() 68 .ok_or("capture is not a JSON object".to_string())?; 69 for key in STRING_FIELDS { 70 if let Some(f) = obj.get(key) { 71 if !f.is_string() { 72 return Err(format!("field `{key}` is not a string")); 73 } 74 } 75 } 76 for key in ["root", "esp"] { 77 if let Some(f) = obj.get(key) { 78 if !f.is_object() { 79 return Err(format!("field `{key}` is not an object")); 80 } 81 } 82 } 83 if let Some(opts) = obj.get("root").and_then(|r| r.get("options")) { 84 if !opts.is_string() { 85 return Err("field `root.options` is not a string".into()); 86 } 87 } 88 Ok(()) 89 } 90 91 fn text<'a>(v: &'a Value, key: &str) -> &'a str { 92 v.get(key).and_then(Value::as_str).unwrap_or("") 93 } 94 95 fn section<'a>(v: &'a Value, key: &str) -> Option<&'a Map> { 96 v.get(key).and_then(Value::as_object) 97 } 98 99 /// `section.get(key)` with a missing section or key read as JSON null. 100 fn field<'a>(sec: Option<&'a Map>, key: &str) -> &'a Value { 101 sec.and_then(|s| s.get(key)).unwrap_or(&Value::Null) 102 } 103 104 /// Python truthiness of a JSON value. 105 fn truthy(v: &Value) -> bool { 106 match v { 107 Value::Null => false, 108 Value::Bool(b) => *b, 109 Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0), 110 Value::String(s) => !s.is_empty(), 111 Value::Array(a) => !a.is_empty(), 112 Value::Object(o) => !o.is_empty(), 113 } 114 } 115 116 /// Python `str()` of a JSON value, as the former report printed it. 117 fn show(v: &Value) -> String { 118 match v { 119 Value::Null => "None".into(), 120 Value::Bool(true) => "True".into(), 121 Value::Bool(false) => "False".into(), 122 Value::String(s) => s.clone(), 123 other => other.to_string(), 124 } 125 } 126 127 fn py_bool(b: bool) -> &'static str { 128 if b { 129 "True" 130 } else { 131 "False" 132 } 133 } 134 135 /// Python `repr()` of a list of strings: `['0001', '0003']`. 136 fn py_list>(items: &[S]) -> String { 137 let quoted: Vec = items 138 .iter() 139 .map(|s| { 140 let s = s.as_ref(); 141 let q = if s.contains('\'') && !s.contains('"') { 142 '"' 143 } else { 144 '\'' 145 }; 146 let mut out = String::from(q); 147 for c in s.chars() { 148 match c { 149 '\\' => out.push_str("\\\\"), 150 '\n' => out.push_str("\\n"), 151 '\r' => out.push_str("\\r"), 152 '\t' => out.push_str("\\t"), 153 c if c == q => { 154 out.push('\\'); 155 out.push(c); 156 } 157 c => out.push(c), 158 } 159 } 160 out.push(q); 161 out 162 }) 163 .collect(); 164 format!("[{}]", quoted.join(", ")) 165 } 166 167 fn boot_order(v: &Value) -> Vec { 168 text(v, "boot_order") 169 .split(',') 170 .map(str::trim) 171 .filter(|s| !s.is_empty()) 172 .map(String::from) 173 .collect() 174 } 175 176 /// Returns the full report text and the verdict. 177 pub fn verify(pre: &Value, post: &Value) -> (String, Verdict) { 178 let mut errors: Vec = Vec::new(); 179 // Nothing blocks today: Secure Boot is OFF for development (owner decision, 180 // 2026-10-01), so its state is reported as an observed fact. A release gate 181 // that requires "enabled" must be added separately. 182 let blocked: Vec = Vec::new(); 183 184 // 1. Secure Boot is observed (reported below), not required to be on during 185 // development. It must still be unchanged across the candidate boot. 186 let sb_pre = text(pre, "secure_boot").to_lowercase(); 187 let sb_post = text(post, "secure_boot").to_lowercase(); 188 if sb_pre != sb_post { 189 errors.push(format!( 190 "Secure Boot state changed from '{sb_pre}' to '{sb_post}'" 191 )); 192 } 193 194 // 2. BootOrder: default entry and relative order of every original entry kept. 195 let bo_pre = boot_order(pre); 196 let bo_post = boot_order(post); 197 if bo_pre.is_empty() { 198 errors.push("Pre-boot BootOrder is empty".into()); 199 } 200 if bo_post.is_empty() { 201 errors.push("Post-boot BootOrder is empty".into()); 202 } 203 if let (Some(first_pre), Some(first_post)) = (bo_pre.first(), bo_post.first()) { 204 if first_pre != first_post { 205 errors.push(format!( 206 "Permanent default boot entry altered: pre was {first_pre}, post is {first_post}" 207 )); 208 } 209 let common_post: Vec<&String> = bo_post.iter().filter(|x| bo_pre.contains(x)).collect(); 210 if !common_post.iter().copied().eq(bo_pre.iter()) { 211 errors.push(format!( 212 "BootOrder sequence changed: pre={}, filtered_post={}", 213 py_list(&bo_pre), 214 py_list(&common_post) 215 )); 216 } 217 } 218 219 // 3. Returned to the default entry. 220 let cur_post = text(post, "boot_current").trim(); 221 if let Some(first_pre) = bo_pre.first() { 222 if cur_post != first_pre { 223 errors.push(format!( 224 "Post-boot did not return to default entry: expected {first_pre}, got {cur_post}" 225 )); 226 } 227 } 228 229 // 4. BootNext consumed by firmware. 230 let next_post = text(post, "boot_next").trim(); 231 if !next_post.is_empty() { 232 errors.push(format!( 233 "BootNext was not consumed by firmware: still set to {next_post}" 234 )); 235 } 236 237 // 5. Root filesystem unchanged and writable. 238 let (root_pre, root_post) = (section(pre, "root"), section(post, "root")); 239 let (root_uuid_pre, root_uuid_post) = (field(root_pre, "uuid"), field(root_post, "uuid")); 240 if truthy(root_uuid_pre) && root_uuid_pre != root_uuid_post { 241 errors.push(format!( 242 "Root UUID changed: pre={}, post={}", 243 show(root_uuid_pre), 244 show(root_uuid_post) 245 )); 246 } 247 let root_opts = field(root_post, "options"); 248 if !root_opts 249 .as_str() 250 .unwrap_or("") 251 .split(',') 252 .any(|o| o == "rw") 253 { 254 errors.push(format!( 255 "Root filesystem not mounted rw after return: {}", 256 show(root_opts) 257 )); 258 } 259 260 // 6. ESP unchanged. 261 let (esp_pre, esp_post) = (section(pre, "esp"), section(post, "esp")); 262 let (esp_uuid_pre, esp_uuid_post) = (field(esp_pre, "uuid"), field(esp_post, "uuid")); 263 if truthy(esp_uuid_pre) && esp_uuid_pre != esp_uuid_post { 264 errors.push(format!( 265 "ESP UUID changed: pre={}, post={}", 266 show(esp_uuid_pre), 267 show(esp_uuid_post) 268 )); 269 } 270 271 let top = |v: &Value, key: &str| show(v.get(key).unwrap_or(&Value::Null)); 272 let mut r = String::new(); 273 r.push_str("=== NATIVE BOOT ROLLBACK VERIFICATION REPORT ===\n"); 274 r.push_str(&format!( 275 "Pre-capture: {} on {}\n", 276 top(pre, "captured_utc"), 277 top(pre, "host") 278 )); 279 r.push_str(&format!( 280 "Post-capture: {} on {}\n", 281 top(post, "captured_utc"), 282 top(post, "host") 283 )); 284 r.push_str(&format!("Secure Boot: before={sb_pre}, after={sb_post}\n")); 285 r.push_str(&format!( 286 "BootOrder: before={}, after={}\n", 287 py_list(&bo_pre), 288 py_list(&bo_post) 289 )); 290 r.push_str(&format!( 291 "BootCurrent: after={cur_post} (expected={})\n", 292 bo_pre.first().map_or("unknown", String::as_str) 293 )); 294 r.push_str(&format!( 295 "BootNext: after={}\n", 296 if next_post.is_empty() { 297 "" 298 } else { 299 next_post 300 } 301 )); 302 r.push_str(&format!( 303 "Root UUID: {} (matched={})\n", 304 show(root_uuid_post), 305 py_bool(root_uuid_pre == root_uuid_post) 306 )); 307 r.push_str(&format!( 308 "ESP UUID: {} (matched={})\n", 309 show(esp_uuid_post), 310 py_bool(esp_uuid_pre == esp_uuid_post) 311 )); 312 313 if !blocked.is_empty() { 314 r.push_str("\n--- BLOCKED REASONS ---\n"); 315 for b in &blocked { 316 r.push_str(&format!("* {b}\n")); 317 } 318 r.push_str("\nVERDICT: BLOCKED\n"); 319 return (r, Verdict::Blocked); 320 } 321 if !errors.is_empty() { 322 r.push_str("\n--- VIOLATIONS ---\n"); 323 for e in &errors { 324 r.push_str(&format!("* FAIL: {e}\n")); 325 } 326 r.push_str("\nVERDICT: FAIL\n"); 327 return (r, Verdict::Fail); 328 } 329 r.push_str("\nAll rollback assertions verified.\nVERDICT: PASS\n"); 330 (r, Verdict::Pass) 331 } 332 333 #[cfg(test)] 334 mod tests { 335 use super::*; 336 use serde_json::json; 337 338 fn capture() -> Value { 339 json!({ 340 "captured_utc": "2026-09-25T00:00:00Z", "host": "spark", 341 "secure_boot": "enabled", "boot_order": "0001,0003,0004", 342 "boot_current": "0001", "boot_next": "", 343 "root": {"uuid": "r-1", "options": "rw,relatime"}, 344 "esp": {"uuid": "e-1"} 345 }) 346 } 347 348 #[test] 349 fn identical_return_passes() { 350 let (report, v) = verify(&capture(), &capture()); 351 assert_eq!(v, Verdict::Pass, "{report}"); 352 assert_eq!(v.exit_code(), 0); 353 assert!(report.ends_with("\nAll rollback assertions verified.\nVERDICT: PASS\n")); 354 } 355 356 #[test] 357 fn report_lines_match_former_python_rendering() { 358 let (report, _) = verify(&capture(), &capture()); 359 let expected = "=== NATIVE BOOT ROLLBACK VERIFICATION REPORT ===\n\ 360 Pre-capture: 2026-09-25T00:00:00Z on spark\n\ 361 Post-capture: 2026-09-25T00:00:00Z on spark\n\ 362 Secure Boot: before=enabled, after=enabled\n\ 363 BootOrder: before=['0001', '0003', '0004'], after=['0001', '0003', '0004']\n\ 364 BootCurrent: after=0001 (expected=0001)\n\ 365 BootNext: after=\n\ 366 Root UUID: r-1 (matched=True)\n\ 367 ESP UUID: e-1 (matched=True)\n"; 368 assert!(report.starts_with(expected), "{report}"); 369 } 370 371 #[test] 372 fn missing_values_render_as_none() { 373 let mut post = capture(); 374 post.as_object_mut().unwrap().remove("host"); 375 post["root"].as_object_mut().unwrap().remove("uuid"); 376 post["root"].as_object_mut().unwrap().remove("options"); 377 let (report, v) = verify(&capture(), &post); 378 assert_eq!(v, Verdict::Fail); 379 assert!(report.contains("Post-capture: 2026-09-25T00:00:00Z on None\n")); 380 assert!(report.contains("Root UUID: None (matched=False)\n")); 381 assert!(report.contains("* FAIL: Root UUID changed: pre=r-1, post=None\n")); 382 assert!(report.contains("* FAIL: Root filesystem not mounted rw after return: None\n")); 383 } 384 385 #[test] 386 fn added_candidate_entry_outside_order_is_allowed() { 387 let mut post = capture(); 388 post["boot_order"] = json!("0001,0000,0003,0004"); 389 assert_eq!(verify(&capture(), &post).1, Verdict::Pass); 390 } 391 392 #[test] 393 fn unconsumed_boot_next_fails() { 394 let mut post = capture(); 395 post["boot_next"] = json!("0000"); 396 let (report, v) = verify(&capture(), &post); 397 assert_eq!(v, Verdict::Fail); 398 assert_eq!(v.exit_code(), 1); 399 assert!( 400 report.contains("* FAIL: BootNext was not consumed by firmware: still set to 0000\n") 401 ); 402 } 403 404 #[test] 405 fn reordered_or_changed_default_fails() { 406 let mut post = capture(); 407 post["boot_order"] = json!("0003,0001,0004"); 408 post["boot_current"] = json!("0003"); 409 let (report, v) = verify(&capture(), &post); 410 assert_eq!(v, Verdict::Fail); 411 assert!(report.contains("Permanent default boot entry altered: pre was 0001, post is 0003")); 412 assert!(report.contains( 413 "BootOrder sequence changed: pre=['0001', '0003', '0004'], filtered_post=['0003', '0001', '0004']" 414 )); 415 assert!(report.contains("expected 0001, got 0003")); 416 } 417 418 #[test] 419 fn duplicated_entry_changes_sequence() { 420 let mut post = capture(); 421 post["boot_order"] = json!("0001,0003,0003,0004"); 422 assert_eq!(verify(&capture(), &post).1, Verdict::Fail); 423 } 424 425 #[test] 426 fn read_only_root_or_changed_esp_fails() { 427 let mut post = capture(); 428 post["root"]["options"] = json!("ro"); 429 assert_eq!(verify(&capture(), &post).1, Verdict::Fail); 430 let mut post = capture(); 431 post["esp"]["uuid"] = json!("e-2"); 432 let (report, v) = verify(&capture(), &post); 433 assert_eq!(v, Verdict::Fail); 434 assert!(report.contains("* FAIL: ESP UUID changed: pre=e-1, post=e-2\n")); 435 assert!(report.contains("ESP UUID: e-2 (matched=False)\n")); 436 } 437 438 #[test] 439 fn empty_pre_uuid_is_not_compared() { 440 let mut pre = capture(); 441 pre["root"]["uuid"] = json!(""); 442 pre["esp"]["uuid"] = json!(""); 443 assert_eq!(verify(&pre, &capture()).1, Verdict::Pass); 444 } 445 446 #[test] 447 fn secure_boot_is_case_insensitive() { 448 let mut pre = capture(); 449 pre["secure_boot"] = json!("Enabled"); 450 assert_eq!(verify(&pre, &capture()).1, Verdict::Pass); 451 } 452 453 #[test] 454 fn secure_boot_off_is_observed_not_blocking() { 455 let mut pre = capture(); 456 pre["secure_boot"] = json!("disabled"); 457 let mut post = capture(); 458 post["secure_boot"] = json!("disabled"); 459 let (report, v) = verify(&pre, &post); 460 assert_eq!(v, Verdict::Pass); 461 assert!(report.contains("Secure Boot: before=disabled, after=disabled\n")); 462 } 463 464 #[test] 465 fn secure_boot_change_is_still_a_violation() { 466 let mut pre = capture(); 467 pre["secure_boot"] = json!("disabled"); 468 let (report, v) = verify(&pre, &capture()); 469 assert_ne!(v, Verdict::Pass); 470 assert!(report.contains("Secure Boot state changed")); 471 } 472 473 #[test] 474 fn empty_boot_orders_fail() { 475 let mut post = capture(); 476 post["boot_order"] = json!(" , "); 477 let (report, v) = verify(&capture(), &post); 478 assert_eq!(v, Verdict::Fail); 479 assert!(report.contains("* FAIL: Post-boot BootOrder is empty\n")); 480 assert!(report.contains("after=[]")); 481 } 482 483 #[test] 484 fn python_list_repr() { 485 assert_eq!(py_list::<&str>(&[]), "[]"); 486 assert_eq!(py_list(&["a'b"]), "[\"a'b\"]"); 487 assert_eq!(py_list(&["a'b\""]), "['a\\'b\"']"); 488 } 489 490 #[test] 491 fn shape_rejects_values_the_verifier_cannot_use() { 492 assert!(check_shape(&capture()).is_ok()); 493 assert!(check_shape(&json!({})).is_ok()); 494 assert!(check_shape(&json!([])).is_err()); 495 let mut c = capture(); 496 c["boot_next"] = Value::Null; 497 assert!(check_shape(&c).is_err()); 498 let mut c = capture(); 499 c["root"] = json!("x"); 500 assert!(check_shape(&c).is_err()); 501 let mut c = capture(); 502 c["root"]["options"] = json!(1); 503 assert!(check_shape(&c).is_err()); 504 } 505 }