aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / tools / aien-test / src / evidence.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 | //! EvidenceReceiptV1 (ADR 0028 Decision 4): canonical JSON, sha256 digest, |
| 17 | //! content-addressed stdout/stderr blobs, immutable write (never overwrite), |
| 18 | //! and read-back of the receipts already in a store. |
| 19 | |
| 20 | use crate::verdict::{DepFact, Verdict}; |
| 21 | use serde_json::{json, Value}; |
| 22 | use sha2::{Digest, Sha256}; |
| 23 | use std::fmt; |
| 24 | use std::fs; |
| 25 | use std::io::{ErrorKind, Write}; |
| 26 | use std::os::unix::fs::OpenOptionsExt; |
| 27 | use std::path::{Path, PathBuf}; |
| 28 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 29 | use std::time::SystemTime; |
| 30 | |
| 31 | pub const SCHEMA: &str = "aien-test/EvidenceReceiptV1"; |
| 32 | |
| 33 | /// Makes every blob temp file name unique inside one process, so gates |
| 34 | /// running on different threads can store the same bytes (an empty stderr, |
| 35 | /// say) at the same moment. |
| 36 | static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); |
| 37 | |
| 38 | pub fn sha256_hex(bytes: &[u8]) -> String { |
| 39 | let mut h = Sha256::new(); |
| 40 | h.update(bytes); |
| 41 | let digest = h.finalize(); |
| 42 | let mut s = String::with_capacity(64); |
| 43 | for b in digest.iter() { |
| 44 | s.push_str(&format!("{b:02x}")); |
| 45 | } |
| 46 | s |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 50 | pub enum StoreError { |
| 51 | /// A float or other value that canonical encoding forbids (C3). |
| 52 | Canon(String), |
| 53 | Io(String), |
| 54 | /// A file already exists at the content address with different bytes. |
| 55 | Collision(String), |
| 56 | /// Bytes read back after writing did not match their digest. |
| 57 | Verify(String), |
| 58 | } |
| 59 | |
| 60 | impl fmt::Display for StoreError { |
| 61 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 62 | match self { |
| 63 | StoreError::Canon(s) => write!(f, "canonical encoding error: {s}"), |
| 64 | StoreError::Io(s) => write!(f, "io error: {s}"), |
| 65 | StoreError::Collision(s) => write!(f, "evidence collision: {s}"), |
| 66 | StoreError::Verify(s) => write!(f, "evidence verify failed: {s}"), |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | fn io_err(what: &str, e: std::io::Error) -> StoreError { |
| 72 | StoreError::Io(format!("{what}: {e}")) |
| 73 | } |
| 74 | |
| 75 | fn write_str(s: &str, out: &mut Vec<u8>) { |
| 76 | out.push(b'"'); |
| 77 | for c in s.chars() { |
| 78 | match c { |
| 79 | '"' => out.extend_from_slice(b"\\\""), |
| 80 | '\\' => out.extend_from_slice(b"\\\\"), |
| 81 | '\n' => out.extend_from_slice(b"\\n"), |
| 82 | '\r' => out.extend_from_slice(b"\\r"), |
| 83 | '\t' => out.extend_from_slice(b"\\t"), |
| 84 | c if (c as u32) < 0x20 => { |
| 85 | out.extend_from_slice(format!("\\u{:04x}", c as u32).as_bytes()) |
| 86 | } |
| 87 | c => { |
| 88 | let mut buf = [0u8; 4]; |
| 89 | out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()); |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | out.push(b'"'); |
| 94 | } |
| 95 | |
| 96 | fn write_value(v: &Value, out: &mut Vec<u8>) -> Result<(), StoreError> { |
| 97 | match v { |
| 98 | Value::Null => out.extend_from_slice(b"null"), |
| 99 | Value::Bool(true) => out.extend_from_slice(b"true"), |
| 100 | Value::Bool(false) => out.extend_from_slice(b"false"), |
| 101 | Value::Number(n) => { |
| 102 | if let Some(i) = n.as_i64() { |
| 103 | out.extend_from_slice(i.to_string().as_bytes()); |
| 104 | } else if let Some(u) = n.as_u64() { |
| 105 | out.extend_from_slice(u.to_string().as_bytes()); |
| 106 | } else { |
| 107 | return Err(StoreError::Canon(format!( |
| 108 | "floating point not allowed: {n}" |
| 109 | ))); |
| 110 | } |
| 111 | } |
| 112 | Value::String(s) => write_str(s, out), |
| 113 | Value::Array(a) => { |
| 114 | out.push(b'['); |
| 115 | for (i, x) in a.iter().enumerate() { |
| 116 | if i > 0 { |
| 117 | out.push(b','); |
| 118 | } |
| 119 | write_value(x, out)?; |
| 120 | } |
| 121 | out.push(b']'); |
| 122 | } |
| 123 | Value::Object(m) => { |
| 124 | let mut keys: Vec<&String> = m.keys().collect(); |
| 125 | keys.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); |
| 126 | out.push(b'{'); |
| 127 | for (i, k) in keys.iter().enumerate() { |
| 128 | if i > 0 { |
| 129 | out.push(b','); |
| 130 | } |
| 131 | write_str(k, out); |
| 132 | out.push(b':'); |
| 133 | write_value(&m[k.as_str()], out)?; |
| 134 | } |
| 135 | out.push(b'}'); |
| 136 | } |
| 137 | } |
| 138 | Ok(()) |
| 139 | } |
| 140 | |
| 141 | /// Canonical bytes (C1 to C5): sorted keys, integers only, minimal escapes. |
| 142 | pub fn canonical(v: &Value) -> Result<Vec<u8>, StoreError> { |
| 143 | let mut out = Vec::new(); |
| 144 | write_value(v, &mut out)?; |
| 145 | Ok(out) |
| 146 | } |
| 147 | |
| 148 | pub fn canonical_digest(v: &Value) -> Result<String, StoreError> { |
| 149 | Ok(sha256_hex(&canonical(v)?)) |
| 150 | } |
| 151 | |
| 152 | pub fn build_receipt(core: Value, volatile: Value) -> Value { |
| 153 | json!({ "schema": SCHEMA, "core": core, "volatile": volatile }) |
| 154 | } |
| 155 | |
| 156 | pub struct Store { |
| 157 | dir: PathBuf, |
| 158 | } |
| 159 | |
| 160 | impl Store { |
| 161 | pub fn new(dir: &Path) -> Store { |
| 162 | Store { |
| 163 | dir: dir.to_path_buf(), |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | pub fn dir(&self) -> &Path { |
| 168 | &self.dir |
| 169 | } |
| 170 | |
| 171 | /// Store a blob at `blobs/<sha256>.log` via temp file and rename, then |
| 172 | /// re-verify. An existing blob with the same digest is success; an |
| 173 | /// existing file with other bytes is a collision. |
| 174 | pub fn put_blob(&self, bytes: &[u8]) -> Result<String, StoreError> { |
| 175 | let sha = sha256_hex(bytes); |
| 176 | let blobs = self.dir.join("blobs"); |
| 177 | fs::create_dir_all(&blobs).map_err(|e| io_err("create blobs dir", e))?; |
| 178 | let path = blobs.join(format!("{sha}.log")); |
| 179 | if path.exists() { |
| 180 | let existing = fs::read(&path).map_err(|e| io_err("read blob", e))?; |
| 181 | if sha256_hex(&existing) != sha { |
| 182 | return Err(StoreError::Collision(format!( |
| 183 | "blob {sha} exists with other bytes" |
| 184 | ))); |
| 185 | } |
| 186 | return Ok(sha); |
| 187 | } |
| 188 | let n = TMP_COUNTER.fetch_add(1, Ordering::SeqCst); |
| 189 | let tmp = blobs.join(format!(".tmp-{sha}-{}-{n}", std::process::id())); |
| 190 | { |
| 191 | let mut f = fs::OpenOptions::new() |
| 192 | .write(true) |
| 193 | .create_new(true) |
| 194 | .mode(0o444) |
| 195 | .open(&tmp) |
| 196 | .map_err(|e| io_err("create blob temp", e))?; |
| 197 | f.write_all(bytes).map_err(|e| io_err("write blob", e))?; |
| 198 | f.sync_all().map_err(|e| io_err("sync blob", e))?; |
| 199 | } |
| 200 | fs::rename(&tmp, &path).map_err(|e| io_err("rename blob", e))?; |
| 201 | let back = fs::read(&path).map_err(|e| io_err("read back blob", e))?; |
| 202 | if sha256_hex(&back) != sha { |
| 203 | return Err(StoreError::Verify(format!( |
| 204 | "blob {sha} digest mismatch after write" |
| 205 | ))); |
| 206 | } |
| 207 | Ok(sha) |
| 208 | } |
| 209 | |
| 210 | /// True if the stdout/stderr blob `sha` is present in this store (it is |
| 211 | /// not read or re-hashed here). |
| 212 | pub fn blob_exists(&self, sha: &str) -> bool { |
| 213 | sha.len() == 64 |
| 214 | && sha |
| 215 | .bytes() |
| 216 | .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) |
| 217 | && self.dir.join("blobs").join(format!("{sha}.log")).is_file() |
| 218 | } |
| 219 | |
| 220 | /// Write `<digest>.json` exclusively, mode 0444, canonical bytes plus one |
| 221 | /// LF. Identical existing content is success; different content is a |
| 222 | /// fatal collision. Never overwrites. |
| 223 | pub fn put_receipt(&self, receipt: &Value) -> Result<(String, PathBuf), StoreError> { |
| 224 | let bytes = canonical(receipt)?; |
| 225 | let digest = sha256_hex(&bytes); |
| 226 | fs::create_dir_all(&self.dir).map_err(|e| io_err("create evidence dir", e))?; |
| 227 | let path = self.dir.join(format!("{digest}.json")); |
| 228 | let mut want = bytes; |
| 229 | want.push(b'\n'); |
| 230 | let mut opts = fs::OpenOptions::new(); |
| 231 | opts.write(true).create_new(true).mode(0o444); |
| 232 | match opts.open(&path) { |
| 233 | Ok(mut f) => { |
| 234 | f.write_all(&want).map_err(|e| io_err("write receipt", e))?; |
| 235 | f.sync_all().map_err(|e| io_err("sync receipt", e))?; |
| 236 | } |
| 237 | Err(e) if e.kind() == ErrorKind::AlreadyExists => { |
| 238 | let existing = fs::read(&path).map_err(|e| io_err("read existing receipt", e))?; |
| 239 | if existing != want { |
| 240 | return Err(StoreError::Collision(format!( |
| 241 | "receipt {digest} exists with different bytes" |
| 242 | ))); |
| 243 | } |
| 244 | } |
| 245 | Err(e) => return Err(io_err("open receipt", e)), |
| 246 | } |
| 247 | let back = fs::read(&path).map_err(|e| io_err("read back receipt", e))?; |
| 248 | if back != want { |
| 249 | return Err(StoreError::Verify(format!( |
| 250 | "receipt {digest} differs after write" |
| 251 | ))); |
| 252 | } |
| 253 | Ok((digest, path)) |
| 254 | } |
| 255 | |
| 256 | /// The bytes of blob `sha`, only if they still hash to `sha`. |
| 257 | pub fn read_blob(&self, sha: &str) -> Option<Vec<u8>> { |
| 258 | if !self.blob_exists(sha) { |
| 259 | return None; |
| 260 | } |
| 261 | let bytes = fs::read(self.dir.join("blobs").join(format!("{sha}.log"))).ok()?; |
| 262 | (sha256_hex(&bytes) == sha).then_some(bytes) |
| 263 | } |
| 264 | |
| 265 | /// The one receipt `<digest>.json`, with the same checks `Index::load` |
| 266 | /// makes (bytes hash to the name, JSON, receipt schema). None otherwise. |
| 267 | pub fn get_receipt(&self, digest: &str) -> Option<Stored> { |
| 268 | if !is_sha256_hex(digest) { |
| 269 | return None; |
| 270 | } |
| 271 | let path = self.dir.join(format!("{digest}.json")); |
| 272 | let bytes = fs::read(&path).ok()?; |
| 273 | let body = bytes.strip_suffix(b"\n").unwrap_or(&bytes); |
| 274 | if sha256_hex(body) != digest { |
| 275 | return None; |
| 276 | } |
| 277 | let value: Value = serde_json::from_slice(body).ok()?; |
| 278 | if value["schema"] != SCHEMA { |
| 279 | return None; |
| 280 | } |
| 281 | let modified = fs::metadata(&path).and_then(|m| m.modified()).ok(); |
| 282 | Some(Stored { |
| 283 | digest: digest.to_string(), |
| 284 | value, |
| 285 | modified, |
| 286 | }) |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | /// A receipt read back from a store. `digest` comes from the file name and |
| 291 | /// has been checked against the file's bytes. |
| 292 | #[derive(Debug, Clone)] |
| 293 | pub struct Stored { |
| 294 | pub digest: String, |
| 295 | pub value: Value, |
| 296 | modified: Option<SystemTime>, |
| 297 | } |
| 298 | |
| 299 | impl Stored { |
| 300 | fn text(&self, section: &str, key: &str) -> &str { |
| 301 | self.value[section][key].as_str().unwrap_or("") |
| 302 | } |
| 303 | |
| 304 | pub fn gate(&self) -> &str { |
| 305 | self.text("core", "gate") |
| 306 | } |
| 307 | |
| 308 | pub fn commit(&self) -> &str { |
| 309 | self.text("core", "commit") |
| 310 | } |
| 311 | |
| 312 | pub fn reason(&self) -> &str { |
| 313 | self.text("core", "reason") |
| 314 | } |
| 315 | |
| 316 | pub fn finished_utc(&self) -> &str { |
| 317 | self.text("volatile", "finished_utc") |
| 318 | } |
| 319 | |
| 320 | pub fn verdict(&self) -> Option<Verdict> { |
| 321 | Verdict::parse(self.text("core", "derived_verdict")) |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | fn is_sha256_hex(s: &str) -> bool { |
| 326 | s.len() == 64 |
| 327 | && s.bytes() |
| 328 | .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) |
| 329 | } |
| 330 | |
| 331 | /// All verified receipts of one store, oldest first. |
| 332 | #[derive(Debug, Clone, Default)] |
| 333 | pub struct Index { |
| 334 | receipts: Vec<Stored>, |
| 335 | } |
| 336 | |
| 337 | impl Index { |
| 338 | /// Read every `<digest>.json` in the store. A file is skipped, never |
| 339 | /// trusted, if its bytes do not hash to its name, it is not JSON, or it |
| 340 | /// does not carry the receipt schema. Order is by recorded finish time, |
| 341 | /// then by file modification time (receipts finished in the same second), |
| 342 | /// then by digest. |
| 343 | pub fn load(store: &Store) -> Index { |
| 344 | let mut receipts = Vec::new(); |
| 345 | let rd = match fs::read_dir(store.dir()) { |
| 346 | Ok(r) => r, |
| 347 | Err(_) => return Index::default(), |
| 348 | }; |
| 349 | for e in rd.flatten() { |
| 350 | let name = e.file_name().to_string_lossy().into_owned(); |
| 351 | let digest = match name.strip_suffix(".json") { |
| 352 | Some(d) if is_sha256_hex(d) => d.to_string(), |
| 353 | _ => continue, |
| 354 | }; |
| 355 | let bytes = match fs::read(e.path()) { |
| 356 | Ok(b) => b, |
| 357 | Err(_) => continue, |
| 358 | }; |
| 359 | let body = bytes.strip_suffix(b"\n").unwrap_or(&bytes); |
| 360 | if sha256_hex(body) != digest { |
| 361 | continue; |
| 362 | } |
| 363 | let value: Value = match serde_json::from_slice(body) { |
| 364 | Ok(v) => v, |
| 365 | Err(_) => continue, |
| 366 | }; |
| 367 | if value["schema"] != SCHEMA { |
| 368 | continue; |
| 369 | } |
| 370 | let modified = e.metadata().and_then(|m| m.modified()).ok(); |
| 371 | receipts.push(Stored { |
| 372 | digest, |
| 373 | value, |
| 374 | modified, |
| 375 | }); |
| 376 | } |
| 377 | receipts.sort_by(|a, b| { |
| 378 | a.finished_utc() |
| 379 | .cmp(b.finished_utc()) |
| 380 | .then_with(|| a.modified.cmp(&b.modified)) |
| 381 | .then_with(|| a.digest.cmp(&b.digest)) |
| 382 | }); |
| 383 | Index { receipts } |
| 384 | } |
| 385 | |
| 386 | /// Every verified receipt, oldest first. |
| 387 | pub fn receipts(&self) -> &[Stored] { |
| 388 | &self.receipts |
| 389 | } |
| 390 | |
| 391 | /// The receipt with exactly this digest, if the store has it. |
| 392 | pub fn get(&self, digest: &str) -> Option<&Stored> { |
| 393 | self.receipts.iter().find(|r| r.digest == digest) |
| 394 | } |
| 395 | |
| 396 | pub fn len(&self) -> usize { |
| 397 | self.receipts.len() |
| 398 | } |
| 399 | |
| 400 | pub fn is_empty(&self) -> bool { |
| 401 | self.receipts.is_empty() |
| 402 | } |
| 403 | |
| 404 | /// The newest receipt of `gate`, for any commit. |
| 405 | pub fn latest(&self, gate: &str) -> Option<&Stored> { |
| 406 | self.receipts.iter().rev().find(|r| r.gate() == gate) |
| 407 | } |
| 408 | |
| 409 | /// The newest receipt of `gate` made at exactly `commit`. |
| 410 | pub fn latest_at(&self, gate: &str, commit: &str) -> Option<&Stored> { |
| 411 | self.receipts |
| 412 | .iter() |
| 413 | .rev() |
| 414 | .find(|r| r.gate() == gate && r.commit() == commit) |
| 415 | } |
| 416 | |
| 417 | /// What is known about each of `deps` at `commit`, in the given order. A |
| 418 | /// dependency without a receipt for this commit has no verdict. |
| 419 | pub fn dep_facts(&self, deps: &[String], commit: &str) -> Vec<DepFact> { |
| 420 | deps.iter() |
| 421 | .map(|d| match self.latest_at(d, commit) { |
| 422 | Some(r) => DepFact { |
| 423 | gate: d.clone(), |
| 424 | verdict: r.verdict(), |
| 425 | receipt: Some(r.digest.clone()), |
| 426 | }, |
| 427 | None => DepFact { |
| 428 | gate: d.clone(), |
| 429 | verdict: None, |
| 430 | receipt: None, |
| 431 | }, |
| 432 | }) |
| 433 | .collect() |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | /// Format seconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SSZ`. |
| 438 | pub fn utc_string(secs: u64) -> String { |
| 439 | let days = (secs / 86_400) as i64; |
| 440 | let rem = secs % 86_400; |
| 441 | // Howard Hinnant's civil-from-days algorithm. |
| 442 | let z = days + 719_468; |
| 443 | let era = z.div_euclid(146_097); |
| 444 | let doe = z.rem_euclid(146_097); |
| 445 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 446 | let y = yoe + era * 400; |
| 447 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 448 | let mp = (5 * doy + 2) / 153; |
| 449 | let d = doy - (153 * mp + 2) / 5 + 1; |
| 450 | let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| 451 | let y = if m <= 2 { y + 1 } else { y }; |
| 452 | format!( |
| 453 | "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", |
| 454 | rem / 3600, |
| 455 | (rem % 3600) / 60, |
| 456 | rem % 60 |
| 457 | ) |
| 458 | } |
| 459 | |
| 460 | /// The inverse of `utc_string`: seconds since the Unix epoch for a |
| 461 | /// `YYYY-MM-DDTHH:MM:SSZ` string; None for anything else. |
| 462 | pub fn utc_secs(s: &str) -> Option<u64> { |
| 463 | let b = s.as_bytes(); |
| 464 | if b.len() != 20 |
| 465 | || b[4] != b'-' |
| 466 | || b[7] != b'-' |
| 467 | || b[10] != b'T' |
| 468 | || b[13] != b':' |
| 469 | || b[16] != b':' |
| 470 | || b[19] != b'Z' |
| 471 | { |
| 472 | return None; |
| 473 | } |
| 474 | let num = |from: usize, to: usize| -> Option<i64> { |
| 475 | let t = &s[from..to]; |
| 476 | if !t.bytes().all(|c| c.is_ascii_digit()) { |
| 477 | return None; |
| 478 | } |
| 479 | t.parse::<i64>().ok() |
| 480 | }; |
| 481 | let (y, m, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?); |
| 482 | let (hh, mm, ss) = (num(11, 13)?, num(14, 16)?, num(17, 19)?); |
| 483 | if !(1..=12).contains(&m) || !(1..=31).contains(&d) || hh > 23 || mm > 59 || ss > 59 { |
| 484 | return None; |
| 485 | } |
| 486 | // Howard Hinnant's days-from-civil algorithm. |
| 487 | let y = if m <= 2 { y - 1 } else { y }; |
| 488 | let era = y.div_euclid(400); |
| 489 | let yoe = y.rem_euclid(400); |
| 490 | let mp = if m > 2 { m - 3 } else { m + 9 }; |
| 491 | let doy = (153 * mp + 2) / 5 + d - 1; |
| 492 | let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; |
| 493 | let days = era * 146_097 + doe - 719_468; |
| 494 | let secs = days * 86_400 + hh * 3600 + mm * 60 + ss; |
| 495 | u64::try_from(secs).ok() |
| 496 | } |
| 497 | |
| 498 | #[cfg(test)] |
| 499 | mod tests { |
| 500 | use super::*; |
| 501 | use crate::testutil::TempDir; |
| 502 | use std::os::unix::fs::PermissionsExt; |
| 503 | |
| 504 | #[test] |
| 505 | fn sha256_known_vectors() { |
| 506 | assert_eq!( |
| 507 | sha256_hex(b""), |
| 508 | "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" |
| 509 | ); |
| 510 | assert_eq!( |
| 511 | sha256_hex(b"abc"), |
| 512 | "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" |
| 513 | ); |
| 514 | } |
| 515 | |
| 516 | #[test] |
| 517 | fn canonical_sorts_keys_and_is_compact() { |
| 518 | let v = json!({"b": [1, true, null], "a": {"z": "x", "y": -3}}); |
| 519 | assert_eq!( |
| 520 | String::from_utf8(canonical(&v).unwrap()).unwrap(), |
| 521 | r#"{"a":{"y":-3,"z":"x"},"b":[1,true,null]}"# |
| 522 | ); |
| 523 | } |
| 524 | |
| 525 | #[test] |
| 526 | fn canonical_escapes_per_c4() { |
| 527 | let v = json!("a\"b\\c\nd\r\te\u{1f}f\u{7f}\u{e9}"); |
| 528 | let s = String::from_utf8(canonical(&v).unwrap()).unwrap(); |
| 529 | assert_eq!(s, "\"a\\\"b\\\\c\\nd\\r\\te\\u001ff\u{7f}\u{e9}\""); |
| 530 | } |
| 531 | |
| 532 | #[test] |
| 533 | fn canonical_rejects_floats() { |
| 534 | assert!(canonical(&json!({"x": 1.5})).is_err()); |
| 535 | assert!(canonical(&json!([0.0])).is_err()); |
| 536 | } |
| 537 | |
| 538 | #[test] |
| 539 | fn canonical_digest_is_stable_across_key_order() { |
| 540 | let a = json!({"x": 1, "y": 2}); |
| 541 | let b = json!({"y": 2, "x": 1}); |
| 542 | assert_eq!(canonical_digest(&a).unwrap(), canonical_digest(&b).unwrap()); |
| 543 | } |
| 544 | |
| 545 | #[test] |
| 546 | fn utc_formatting() { |
| 547 | assert_eq!(utc_string(0), "1970-01-01T00:00:00Z"); |
| 548 | assert_eq!(utc_string(1_700_000_000), "2023-11-14T22:13:20Z"); |
| 549 | assert_eq!(utc_string(951_782_400), "2000-02-29T00:00:00Z"); |
| 550 | } |
| 551 | |
| 552 | #[test] |
| 553 | fn receipt_roundtrip_mode_and_name() { |
| 554 | let t = TempDir::new("ev1"); |
| 555 | let store = Store::new(t.path()); |
| 556 | let r = build_receipt(json!({"gate": "G"}), json!({"duration_ms": 5})); |
| 557 | let (digest, path) = store.put_receipt(&r).unwrap(); |
| 558 | assert_eq!(path, t.path().join(format!("{digest}.json"))); |
| 559 | let bytes = fs::read(&path).unwrap(); |
| 560 | assert_eq!(*bytes.last().unwrap(), b'\n'); |
| 561 | assert_eq!(sha256_hex(&bytes[..bytes.len() - 1]), digest); |
| 562 | let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777; |
| 563 | assert_eq!(mode, 0o444); |
| 564 | let back: Value = serde_json::from_slice(&bytes).unwrap(); |
| 565 | assert_eq!(back["schema"], SCHEMA); |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn identical_receipt_twice_is_success() { |
| 570 | let t = TempDir::new("ev2"); |
| 571 | let store = Store::new(t.path()); |
| 572 | let r = build_receipt(json!({"gate": "G"}), json!({})); |
| 573 | let a = store.put_receipt(&r).unwrap(); |
| 574 | let b = store.put_receipt(&r).unwrap(); |
| 575 | assert_eq!(a, b); |
| 576 | } |
| 577 | |
| 578 | #[test] |
| 579 | fn receipt_overwrite_is_refused() { |
| 580 | let t = TempDir::new("ev3"); |
| 581 | let store = Store::new(t.path()); |
| 582 | let r = build_receipt(json!({"gate": "G"}), json!({})); |
| 583 | let (_, path) = store.put_receipt(&r).unwrap(); |
| 584 | // Tamper with the stored file, then try to write the same receipt again. |
| 585 | fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); |
| 586 | fs::write(&path, b"tampered").unwrap(); |
| 587 | match store.put_receipt(&r) { |
| 588 | Err(StoreError::Collision(_)) => {} |
| 589 | other => panic!("expected collision, got {other:?}"), |
| 590 | } |
| 591 | assert_eq!(fs::read(&path).unwrap(), b"tampered"); |
| 592 | } |
| 593 | |
| 594 | #[test] |
| 595 | fn blob_is_content_addressed_and_idempotent() { |
| 596 | let t = TempDir::new("ev4"); |
| 597 | let store = Store::new(t.path()); |
| 598 | let sha = store.put_blob(b"hello\n").unwrap(); |
| 599 | assert_eq!(sha, sha256_hex(b"hello\n")); |
| 600 | let p = t.path().join("blobs").join(format!("{sha}.log")); |
| 601 | assert_eq!(fs::read(&p).unwrap(), b"hello\n"); |
| 602 | assert_eq!( |
| 603 | fs::metadata(&p).unwrap().permissions().mode() & 0o777, |
| 604 | 0o444 |
| 605 | ); |
| 606 | assert_eq!(store.put_blob(b"hello\n").unwrap(), sha); |
| 607 | } |
| 608 | |
| 609 | #[test] |
| 610 | fn blob_collision_detected() { |
| 611 | let t = TempDir::new("ev5"); |
| 612 | let store = Store::new(t.path()); |
| 613 | let sha = store.put_blob(b"hello\n").unwrap(); |
| 614 | let p = t.path().join("blobs").join(format!("{sha}.log")); |
| 615 | fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap(); |
| 616 | fs::write(&p, b"evil").unwrap(); |
| 617 | match store.put_blob(b"hello\n") { |
| 618 | Err(StoreError::Collision(_)) => {} |
| 619 | other => panic!("expected collision, got {other:?}"), |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | fn receipt(gate: &str, commit: &str, verdict: &str, finished: &str) -> Value { |
| 624 | build_receipt( |
| 625 | json!({"gate": gate, "commit": commit, "derived_verdict": verdict, "reason": ""}), |
| 626 | json!({"finished_utc": finished}), |
| 627 | ) |
| 628 | } |
| 629 | |
| 630 | #[test] |
| 631 | fn index_finds_the_newest_receipt_per_gate_and_commit() { |
| 632 | let t = TempDir::new("ev6"); |
| 633 | let store = Store::new(t.path()); |
| 634 | let c1 = "1".repeat(40); |
| 635 | let c2 = "2".repeat(40); |
| 636 | store |
| 637 | .put_receipt(&receipt("G", &c1, "FAIL", "2026-10-02T01:00:00Z")) |
| 638 | .unwrap(); |
| 639 | let (newer, _) = store |
| 640 | .put_receipt(&receipt("G", &c1, "PASS", "2026-10-02T02:00:00Z")) |
| 641 | .unwrap(); |
| 642 | let (other_commit, _) = store |
| 643 | .put_receipt(&receipt("G", &c2, "FAIL", "2026-10-02T03:00:00Z")) |
| 644 | .unwrap(); |
| 645 | store |
| 646 | .put_receipt(&receipt( |
| 647 | "H", |
| 648 | &c1, |
| 649 | "BLOCKED_HARDWARE", |
| 650 | "2026-10-02T01:30:00Z", |
| 651 | )) |
| 652 | .unwrap(); |
| 653 | let ix = Index::load(&store); |
| 654 | assert_eq!(ix.len(), 4); |
| 655 | assert!(!ix.is_empty()); |
| 656 | assert_eq!(ix.latest("G").unwrap().digest, other_commit); |
| 657 | let at = ix.latest_at("G", &c1).unwrap(); |
| 658 | assert_eq!(at.digest, newer); |
| 659 | assert_eq!(at.verdict(), Some(Verdict::Pass)); |
| 660 | assert_eq!((at.gate(), at.commit()), ("G", c1.as_str())); |
| 661 | assert!(ix.latest_at("G", &"3".repeat(40)).is_none()); |
| 662 | assert!(ix.latest("nope").is_none()); |
| 663 | let want = vec!["H".to_string(), "G".to_string(), "Z".to_string()]; |
| 664 | let facts = ix.dep_facts(&want, &c1); |
| 665 | assert_eq!(facts.len(), 3); |
| 666 | assert_eq!(facts[0].verdict, Some(Verdict::BlockedHardware)); |
| 667 | assert_eq!(facts[1].verdict, Some(Verdict::Pass)); |
| 668 | assert_eq!(facts[1].receipt.as_deref(), Some(newer.as_str())); |
| 669 | assert_eq!( |
| 670 | facts[2], |
| 671 | DepFact { |
| 672 | gate: "Z".to_string(), |
| 673 | verdict: None, |
| 674 | receipt: None |
| 675 | } |
| 676 | ); |
| 677 | } |
| 678 | |
| 679 | #[test] |
| 680 | fn index_skips_files_that_are_not_trustworthy_receipts() { |
| 681 | let t = TempDir::new("ev7"); |
| 682 | let store = Store::new(t.path()); |
| 683 | let c = "1".repeat(40); |
| 684 | store |
| 685 | .put_receipt(&receipt("G", &c, "PASS", "2026-10-02T01:00:00Z")) |
| 686 | .unwrap(); |
| 687 | // The file name does not match the bytes. |
| 688 | let forged = canonical(&receipt("G", &c, "FAIL", "2026-10-02T09:00:00Z")).unwrap(); |
| 689 | fs::write(t.path().join(format!("{}.json", "0".repeat(64))), forged).unwrap(); |
| 690 | // The right name, but not a receipt of this schema. |
| 691 | let alien = canonical(&json!({"schema": "something/else", "core": {"gate": "G"}})).unwrap(); |
| 692 | fs::write( |
| 693 | t.path().join(format!("{}.json", sha256_hex(&alien))), |
| 694 | &alien, |
| 695 | ) |
| 696 | .unwrap(); |
| 697 | // Not JSON at all, with the right name. |
| 698 | let junk = b"not json".to_vec(); |
| 699 | fs::write(t.path().join(format!("{}.json", sha256_hex(&junk))), &junk).unwrap(); |
| 700 | fs::write(t.path().join("notes.txt"), b"hello").unwrap(); |
| 701 | let ix = Index::load(&store); |
| 702 | assert_eq!(ix.len(), 1); |
| 703 | assert_eq!(ix.latest("G").unwrap().verdict(), Some(Verdict::Pass)); |
| 704 | let missing = Store::new(&t.path().join("no-such-dir")); |
| 705 | assert!(Index::load(&missing).is_empty()); |
| 706 | } |
| 707 | |
| 708 | #[test] |
| 709 | fn identical_blobs_stored_at_the_same_moment_do_not_collide() { |
| 710 | let t = TempDir::new("ev8"); |
| 711 | let store = Store::new(t.path()); |
| 712 | let barrier = std::sync::Barrier::new(8); |
| 713 | std::thread::scope(|s| { |
| 714 | for _ in 0..8 { |
| 715 | s.spawn(|| { |
| 716 | barrier.wait(); |
| 717 | for _ in 0..20 { |
| 718 | store.put_blob(b"same bytes").expect("concurrent put_blob"); |
| 719 | } |
| 720 | }); |
| 721 | } |
| 722 | }); |
| 723 | let sha = sha256_hex(b"same bytes"); |
| 724 | let blob = t.path().join("blobs").join(format!("{sha}.log")); |
| 725 | assert_eq!(fs::read(blob).unwrap(), b"same bytes"); |
| 726 | let leftovers = fs::read_dir(t.path().join("blobs")) |
| 727 | .unwrap() |
| 728 | .flatten() |
| 729 | .filter(|e| e.file_name().to_string_lossy().starts_with(".tmp-")) |
| 730 | .count(); |
| 731 | assert_eq!(leftovers, 0, "no temp file may be left behind"); |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | #[cfg(test)] |
| 736 | mod utc_tests { |
| 737 | use super::*; |
| 738 | |
| 739 | #[test] |
| 740 | fn utc_secs_inverts_utc_string() { |
| 741 | for secs in [ |
| 742 | 0u64, |
| 743 | 1, |
| 744 | 86_399, |
| 745 | 86_400, |
| 746 | 951_782_400, |
| 747 | 1_700_000_000, |
| 748 | 1_791_000_000, |
| 749 | 4_102_444_800, |
| 750 | ] { |
| 751 | assert_eq!(utc_secs(&utc_string(secs)), Some(secs), "{secs}"); |
| 752 | } |
| 753 | assert_eq!(utc_secs("2026-10-11T00:00:00Z"), Some(1_791_676_800)); |
| 754 | for bad in [ |
| 755 | "", |
| 756 | "2026-10-11", |
| 757 | "2026-10-11T00:00:00", |
| 758 | "2026-13-11T00:00:00Z", |
| 759 | "x026-10-11T00:00:00Z", |
| 760 | "2026-10-11T24:00:00Z", |
| 761 | ] { |
| 762 | assert_eq!(utc_secs(bad), None, "{bad}"); |
| 763 | } |
| 764 | } |
| 765 | } |