native_manifest.rs (15785B)
1 // SPDX-License-Identifier: GPL-3.0-only 2 // Native test consumer, using this existing target's exact public Lib189 graph. 3 // No product engine, key, signing, network or parent documentation dependency. 4 #![forbid(unsafe_code)] 5 6 mod support; 7 8 use radroots_blossom::Sha256; 9 use radroots_event::wire::{EventWireError, Nip01EventWire}; 10 use radroots_event_codec::verify::verify_nip01_event; 11 use serde_json::{Value, json}; 12 use std::{ 13 collections::{BTreeMap, BTreeSet}, 14 fs, 15 path::{Component, Path, PathBuf}, 16 }; 17 18 const REVISION: &str = "189c49b74b4bafc142b00b76b296477931139e72"; 19 const PROFILE: &str = "food_availability_profile"; 20 const FOOD: &str = "contracts/interop/food_availability/"; 21 const INPUTS: [&str; 11] = [ 22 "contracts/interop/food_availability/corpus.v1.json", 23 "contracts/interop/food_availability/source_profile.v1.json", 24 "contracts/interop/food_availability/provenance.v1.json", 25 "contracts/interop/food_availability/oracle/src/main.rs", 26 "contracts/interop/food_availability/oracle/Cargo.toml", 27 "radroots.lib.source-lock.v1.toml", 28 "web/tests/conformance/food-writer-rust.v1.json", 29 "contracts/interop/food_availability/web_templates.v1.json", 30 "contracts/interop/food_availability/numeric_boundaries.v1.json", 31 "contracts/interop/food_availability/oracle/tests/native_manifest.rs", 32 "contracts/interop/food_availability/oracle/tests/support/mod.rs", 33 ]; 34 35 type Inputs = BTreeMap<String, Vec<u8>>; 36 37 fn root() -> PathBuf { 38 Path::new(env!("CARGO_MANIFEST_DIR")) 39 .join("../../../..") 40 .canonicalize() 41 .unwrap() 42 } 43 44 fn bounded_read(base: &Path, name: &str) -> Result<Vec<u8>, String> { 45 let mut path = base.to_owned(); 46 for component in Path::new(name).components() { 47 let Component::Normal(segment) = component else { 48 return Err("noncanonical fixture path".into()); 49 }; 50 path.push(segment); 51 if fs::symlink_metadata(&path) 52 .map_err(|error| error.to_string())? 53 .file_type() 54 .is_symlink() 55 { 56 return Err("fixture symlink rejected".into()); 57 } 58 } 59 let metadata = fs::symlink_metadata(&path).map_err(|error| error.to_string())?; 60 if !metadata.is_file() || metadata.len() == 0 || metadata.len() > 1024 * 1024 { 61 return Err("fixture must be a bounded regular file".into()); 62 } 63 let bytes = fs::read(path).map_err(|error| error.to_string())?; 64 if u64::try_from(bytes.len()).unwrap() != metadata.len() { 65 return Err("fixture changed during read".into()); 66 } 67 Ok(bytes) 68 } 69 70 fn load() -> (Value, Inputs) { 71 let base = root(); 72 let manifest = 73 serde_json::from_slice(&bounded_read(&base, "contracts/interop/manifest.json").unwrap()) 74 .unwrap(); 75 let inputs = INPUTS 76 .iter() 77 .map(|name| (name.to_string(), bounded_read(&base, name).unwrap())) 78 .collect(); 79 (manifest, inputs) 80 } 81 82 fn required(condition: bool, message: &str) -> Result<(), String> { 83 if condition { 84 Ok(()) 85 } else { 86 Err(message.into()) 87 } 88 } 89 90 fn parse(inputs: &Inputs, name: &str) -> Result<Value, String> { 91 serde_json::from_slice(inputs.get(name).ok_or("missing input")?) 92 .map_err(|error| error.to_string()) 93 } 94 95 fn descriptor(inputs: &Inputs, row: &Value) -> Result<(), String> { 96 let path = row["path"].as_str().ok_or("missing raw path")?; 97 let bytes = inputs.get(path).ok_or("undeclared raw path")?; 98 required( 99 row["sha256"] == Sha256::digest(bytes).to_hex(), 100 "raw hash mismatch", 101 )?; 102 required( 103 row["bytes"].as_u64() == Some(u64::try_from(bytes.len()).unwrap()), 104 "raw length mismatch", 105 ) 106 } 107 108 fn consume(manifest: &Value, inputs: &Inputs, selected_profile: &str) -> Result<Value, String> { 109 required( 110 manifest["schema_version"] == 1 111 && manifest["qualification"] == "FIXTURE_ONLY_NOT_DEPLOYED_TERA" 112 && manifest["signing"] == "NOT_RUN_NO_KEYS", 113 "qualification metadata changed", 114 )?; 115 required( 116 manifest["oracle"]["revision"] == REVISION 117 && manifest["oracle"]["repository"] == "https://github.com/radrootslabs/lib", 118 "oracle identity changed", 119 )?; 120 let expected_inputs: BTreeSet<_> = INPUTS.iter().copied().collect(); 121 required( 122 inputs.keys().map(String::as_str).collect::<BTreeSet<_>>() == expected_inputs, 123 "input membership changed", 124 )?; 125 let descriptors = manifest["inputs"] 126 .as_array() 127 .ok_or("missing input descriptors")?; 128 required( 129 descriptors.len() == INPUTS.len(), 130 "input descriptor count changed", 131 )?; 132 let paths = descriptors 133 .iter() 134 .map(|row| row["path"].as_str().ok_or("missing input path")) 135 .collect::<Result<BTreeSet<_>, _>>()?; 136 required( 137 paths == expected_inputs, 138 "input descriptor membership changed", 139 )?; 140 for row in descriptors { 141 descriptor(inputs, row)?; 142 } 143 let source_lock = std::str::from_utf8(&inputs["radroots.lib.source-lock.v1.toml"]) 144 .map_err(|error| error.to_string())?; 145 required( 146 source_lock 147 .lines() 148 .filter(|line| line.starts_with("revision = ")) 149 .collect::<Vec<_>>() 150 == [format!("revision = \"{REVISION}\"")], 151 "source lock revision changed", 152 )?; 153 let corpus = parse(inputs, &(FOOD.to_owned() + "corpus.v1.json"))?; 154 let profile = parse(inputs, &(FOOD.to_owned() + "source_profile.v1.json"))?; 155 let provenance = parse(inputs, &(FOOD.to_owned() + "provenance.v1.json"))?; 156 required( 157 corpus["revision"] == REVISION 158 && corpus["contract_version"] == "1.0.0" 159 && profile["contract_version"] == "1.0.0" 160 && profile["suite"] == PROFILE, 161 "public profile changed", 162 )?; 163 required( 164 corpus["source_sha256"] 165 == Sha256::digest(&inputs[&(FOOD.to_owned() + "source_profile.v1.json")]).to_hex() 166 && provenance["public_source"]["sha256"] == corpus["source_sha256"] 167 && provenance["public_source"]["revision"] == REVISION, 168 "public source provenance mismatch", 169 )?; 170 descriptor( 171 inputs, 172 &json!({"path":FOOD.to_owned()+"corpus.v1.json","sha256":provenance["corpus"]["sha256"],"bytes":provenance["corpus"]["bytes"]}), 173 )?; 174 let writers = parse(inputs, &(FOOD.to_owned() + "web_templates.v1.json"))?; 175 let boundaries = parse(inputs, &(FOOD.to_owned() + "numeric_boundaries.v1.json"))?; 176 required( 177 boundaries["revision"] == REVISION 178 && boundaries["profile"] == PROFILE 179 && boundaries["contract_version"] == "1.0.0" 180 && boundaries["schema_version"] == 1, 181 "boundary profile changed", 182 )?; 183 let public = corpus["vectors"] 184 .as_array() 185 .ok_or("missing public vectors")?; 186 let source = profile["vectors"] 187 .as_array() 188 .ok_or("missing source recipes")?; 189 let writers = writers.as_array().ok_or("missing website recipes")?; 190 let boundaries = boundaries["vectors"] 191 .as_array() 192 .ok_or("missing boundary recipes")?; 193 required( 194 public.len() == 40 && source.len() == 40 && writers.len() == 16 && boundaries.len() == 10, 195 "fixture membership changed", 196 )?; 197 let mut recipes = BTreeMap::new(); 198 for (index, row) in public.iter().enumerate() { 199 required( 200 json!({"id":row["id"],"kind":row["kind"],"input":row["input"],"expected":row["expected"]}) 201 == source[index], 202 "public recipe differs from source", 203 )?; 204 recipes.insert( 205 row["id"].as_str().ok_or("missing public ID")?, 206 ("corpus.v1.json", index, row), 207 ); 208 } 209 for (index, row) in writers.iter().enumerate() { 210 required( 211 recipes 212 .insert( 213 row["id"].as_str().ok_or("missing writer ID")?, 214 ("web_templates.v1.json", index, row), 215 ) 216 .is_none(), 217 "duplicate writer ID", 218 )?; 219 } 220 for (index, row) in boundaries.iter().enumerate() { 221 required( 222 recipes 223 .insert( 224 row["id"].as_str().ok_or("missing boundary ID")?, 225 ("numeric_boundaries.v1.json", index, row), 226 ) 227 .is_none(), 228 "duplicate boundary ID", 229 )?; 230 } 231 let cases = manifest["cases"] 232 .as_array() 233 .ok_or("missing manifest cases")?; 234 required( 235 cases.len() == recipes.len() && recipes.len() == 66, 236 "manifest cases missing", 237 )?; 238 let mut seen = BTreeSet::new(); 239 let mut results = Vec::new(); 240 for case in cases { 241 let id = case["id"].as_str().ok_or("missing case ID")?; 242 required(seen.insert(id), "duplicate case ID")?; 243 let (file, index, row) = recipes.get(id).ok_or("unknown case ID")?; 244 required( 245 case["protocol"]["profile"] == PROFILE 246 && case["protocol"]["contract_version"] == "1.0.0" 247 && case["oracle_revision"] == REVISION 248 && case["participation"]["native_consumer"] == "REQUIRED_NATIVE_TEST", 249 "case participation changed", 250 )?; 251 required( 252 case["fixture"]["path"] == FOOD.to_owned() + file 253 && case["fixture"]["case_index"].as_u64() == Some(u64::try_from(*index).unwrap()) 254 && case["fixture"]["case_id"] == id, 255 "raw case pointer changed", 256 )?; 257 descriptor(inputs, &case["fixture"])?; 258 let expected = if *file == "web_templates.v1.json" { 259 json!({"result":"accepted","wire_parts":row["wire_parts"]}) 260 } else { 261 row["expected"].clone() 262 }; 263 required( 264 case["expected"] == expected, 265 "case expectation differs from recipe", 266 )?; 267 if case["protocol"]["profile"] != selected_profile { 268 continue; 269 } 270 let (actual, expected) = match *file { 271 "corpus.v1.json" => { 272 for (field, raw) in row["signed_wires"] 273 .as_object() 274 .ok_or("missing signed wires")? 275 { 276 let raw = raw.as_str().ok_or("invalid signed wire")?; 277 let wire = 278 Nip01EventWire::parse_json(raw).map_err(|error| error.to_string())?; 279 wire.verify_id().map_err(|error| error.to_string())?; 280 required( 281 serde_json::from_str::<Value>(raw).map_err(|error| error.to_string())? 282 == row["input"][field], 283 "signed raw differs from recipe", 284 )?; 285 } 286 (support::actual(row), expected) 287 } 288 "web_templates.v1.json" => { 289 let template = 290 serde_json::from_value((*row).clone()).map_err(|error| error.to_string())?; 291 let mut actual = support::consume_template(&template)?; 292 actual.as_object_mut().unwrap().remove("id"); 293 (actual, expected) 294 } 295 "numeric_boundaries.v1.json" => (support::boundary(row), expected["native"].clone()), 296 _ => return Err("unhandled fixture".into()), 297 }; 298 required( 299 actual == expected, 300 &format!("actual pinned codec differs for {id}"), 301 )?; 302 results.push(json!({"id":id,"result":"PASS","actual":actual})); 303 } 304 required(!results.is_empty(), "zero matching native cases")?; 305 Ok( 306 json!({"consumer":"native_public_food_codec","revision":REVISION,"qualification":"FIXTURE_ONLY_NOT_DEPLOYED_TERA","signing":"NOT_RUN_NO_KEYS","matched_cases":results.len(),"cases":results}), 307 ) 308 } 309 310 #[test] 311 fn native_manifest_executes_actual_pinned_food_codec() { 312 let (manifest, inputs) = load(); 313 let result = consume(&manifest, &inputs, PROFILE).unwrap(); 314 assert_eq!(result["matched_cases"], 66); 315 println!("{}", serde_json::to_string(&result).unwrap()); 316 } 317 318 #[test] 319 fn native_consumer_rejects_corruption_and_zero_matching_cases() { 320 let (manifest, inputs) = load(); 321 for mutation in [ 322 "duplicate", 323 "missing", 324 "hash", 325 "revision", 326 "path", 327 "expected", 328 "participation", 329 ] { 330 let mut changed = manifest.clone(); 331 match mutation { 332 "duplicate" => changed["cases"][1]["id"] = changed["cases"][0]["id"].clone(), 333 "missing" => { 334 changed["cases"].as_array_mut().unwrap().pop(); 335 } 336 "hash" => changed["cases"][0]["fixture"]["sha256"] = json!("0".repeat(64)), 337 "revision" => changed["oracle"]["revision"] = json!("0".repeat(40)), 338 "path" => changed["cases"][0]["fixture"]["path"] = json!("web/static/private.json"), 339 "expected" => changed["cases"][0]["expected"] = json!({"result":"wrong"}), 340 "participation" => { 341 changed["cases"][0]["participation"]["native_consumer"] = json!("PASS") 342 } 343 _ => unreachable!(), 344 } 345 assert!(consume(&changed, &inputs, PROFILE).is_err(), "{mutation}"); 346 } 347 assert_eq!( 348 consume(&manifest, &inputs, "unavailable_profile").unwrap_err(), 349 "zero matching native cases" 350 ); 351 let mut changed = inputs.clone(); 352 changed.get_mut(INPUTS[0]).unwrap().push(b' '); 353 assert!(consume(&manifest, &changed, PROFILE).is_err()); 354 changed = inputs.clone(); 355 changed.remove(INPUTS[0]); 356 assert!(consume(&manifest, &changed, PROFILE).is_err()); 357 } 358 359 #[test] 360 fn actual_native_codec_rejects_noncanonical_price_and_changed_signed_bytes() { 361 let (_, inputs) = load(); 362 let mut writers = parse(&inputs, &(FOOD.to_owned() + "web_templates.v1.json")).unwrap(); 363 let tags = writers[0]["wire_parts"]["tags"].as_array_mut().unwrap(); 364 let price = tags.iter_mut().find(|tag| tag[0] == "price").unwrap(); 365 price[1] = json!("1e3"); 366 let template = serde_json::from_value(writers[0].clone()).unwrap(); 367 assert!(support::consume_template(&template).is_err()); 368 let corpus = parse(&inputs, INPUTS[0]).unwrap(); 369 let mut event: Value = serde_json::from_str( 370 corpus["vectors"][13]["signed_wires"]["event"] 371 .as_str() 372 .unwrap(), 373 ) 374 .unwrap(); 375 let original_signature = event["sig"].clone(); 376 event["sig"] = json!("0".repeat(128)); 377 let wire = Nip01EventWire::parse_json(&serde_json::to_string(&event).unwrap()).unwrap(); 378 wire.verify_id().unwrap(); 379 assert!(verify_nip01_event(wire.into_envelope().unwrap()).is_err()); 380 event["sig"] = original_signature; 381 event["id"] = json!("0".repeat(64)); 382 // This actual public parser checks the canonical identifier before it 383 // returns a wire. Assert that stage, rather than unwrapping a rejection. 384 assert!(matches!( 385 Nip01EventWire::parse_json(&serde_json::to_string(&event).unwrap()), 386 Err(EventWireError::EventIdMismatch { .. }) 387 )); 388 } 389 390 #[test] 391 fn actual_native_boundaries_preserve_full_u64_and_raw_identifier_spelling() { 392 let (_, inputs) = load(); 393 let fixture = parse(&inputs, &(FOOD.to_owned() + "numeric_boundaries.v1.json")).unwrap(); 394 let rows = fixture["vectors"].as_array().unwrap(); 395 for row in rows { 396 assert_eq!(support::boundary(row), row["expected"]["native"]); 397 } 398 assert_eq!( 399 support::boundary(&rows[6])["timestamp"], 400 u64::MAX.to_string() 401 ); 402 assert_ne!( 403 support::boundary(&rows[8])["identifier"], 404 support::boundary(&rows[9])["identifier"] 405 ); 406 }