public_command.rs (37020B)
1 #![cfg(feature = "listing")] 2 use radroots_domain::{ 3 ActorRef, ActorRole, AuthorityRef, CommandContextData, ExecutorId, Generation, GrantId, 4 OperationId, PublicKey, RouteDigest, ThreadId, UnixSeconds, WorkspaceId, 5 }; 6 use radroots_protocol::{ 7 command::{CapturedChatCommand, CapturedCommand, CommandError, InquireInput}, 8 listing::{CapturedListingCommand, PublishInput}, 9 }; 10 use serde_json::{Value, json}; 11 fn key() -> PublicKey { 12 PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() 13 } 14 fn context() -> CommandContextData { 15 CommandContextData::new( 16 OperationId::from_bytes([7; 32]), 17 ActorRef::new( 18 key(), 19 ActorRole::Seller, 20 None, 21 Some(GrantId::from_bytes([3; 32])), 22 ), 23 WorkspaceId::from_bytes([1; 32]), 24 AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()), 25 RouteDigest::from_bytes([5; 32]), 26 None, 27 None, 28 UnixSeconds::new(150).unwrap(), 29 None, 30 ) 31 .unwrap() 32 } 33 fn input() -> Value { 34 json!({"id":"01".repeat(16),"title":"Carrots","summary":"One bunch; quote required","description_markdown":"Public terms","published_at":"100","profile":{"profile":"radroots.listing","version":1,"state":"active","product":{"name":"Carrots","description":"Public description","producer":null,"origin_summary":null},"default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch","unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}},"increment":"1","minimum":"1","price":{"type":"quote_required"},"supply":{"type":"available","amount":"10"},"lead_seconds":"0"}],"fulfillment":{"modes":["pickup"],"area":"Example region","lead_seconds":"0"},"authority":null,"media":[]}}) 35 } 36 37 #[test] 38 fn profile_keys_require_canonical_spelling_in_public_input_and_command_dispatch() { 39 let mut public = input(); 40 public["profile"]["product"]["producer"] = json!(key().to_hex()); 41 let parsed = PublishInput::parse(&serde_json::to_vec(&public).unwrap()).unwrap(); 42 let captured = CapturedListingCommand::capture(context(), parsed).unwrap(); 43 let mut base: Value = serde_json::from_slice(captured.protected_wire()).unwrap(); 44 base["context"]["actor"]["organization"] = json!(key().to_hex()); 45 for path in [ 46 "/context/actor/participant", 47 "/context/actor/organization", 48 "/input/profile/product/producer", 49 ] { 50 let mut altered = base.clone(); 51 *altered.pointer_mut(path).unwrap() = json!(key().to_hex().to_ascii_uppercase()); 52 let wire = serde_json::to_vec(&altered).unwrap(); 53 assert!(CapturedListingCommand::parse(&wire).is_err(), "{path}"); 54 assert!(CapturedCommand::parse(&wire).is_err(), "dispatcher {path}"); 55 } 56 public["profile"]["product"]["producer"] = json!(key().to_hex().to_ascii_uppercase()); 57 assert!(PublishInput::parse(&serde_json::to_vec(&public).unwrap()).is_err()); 58 } 59 60 #[test] 61 fn empty_tagged_public_snapshot_alternatives_never_discard_unknown_fields() { 62 let mut base = input(); 63 base["profile"]["options"][0]["supply"] = json!({"type":"unknown"}); 64 let command = CapturedListingCommand::capture( 65 context(), 66 PublishInput::parse(&serde_json::to_vec(&base).unwrap()).unwrap(), 67 ) 68 .unwrap(); 69 let wire: Value = serde_json::from_slice(command.protected_wire()).unwrap(); 70 for path in [ 71 "/profile/options/0/price", 72 "/profile/options/0/supply", 73 "/profile/options/0/unit/contents", 74 ] { 75 let mut altered = base.clone(); 76 altered 77 .pointer_mut(path) 78 .unwrap() 79 .as_object_mut() 80 .unwrap() 81 .insert("unexpected".into(), Value::Null); 82 assert!( 83 PublishInput::parse(&serde_json::to_vec(&altered).unwrap()).is_err(), 84 "{path}" 85 ); 86 let mut changed = wire.clone(); 87 changed["input"] = altered; 88 let raw = serde_json::to_vec(&changed).unwrap(); 89 assert!( 90 CapturedListingCommand::parse(&raw).is_err(), 91 "command {path}" 92 ); 93 assert!(CapturedCommand::parse(&raw).is_err(), "dispatcher {path}"); 94 } 95 } 96 97 #[test] 98 fn public_command_root_and_context_reject_positional_arrays() { 99 let command = CapturedListingCommand::capture( 100 context(), 101 PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), 102 ) 103 .unwrap(); 104 let base: Value = serde_json::from_slice(command.protected_wire()).unwrap(); 105 let mut accepted = Vec::new(); 106 for (pointer, keys) in [ 107 ("", &["type", "context", "input"][..]), 108 ( 109 "/context", 110 &[ 111 "operation_id", 112 "actor", 113 "workspace_id", 114 "authority", 115 "route_digest", 116 "approval", 117 "expected", 118 "not_after", 119 "correlation_id", 120 ][..], 121 ), 122 ( 123 "/context/actor", 124 &["participant", "role", "organization", "grant_id"][..], 125 ), 126 ("/context/authority", &["executor_id", "generation"][..]), 127 ] { 128 let mut value = base.clone(); 129 let array = Value::Array( 130 keys.iter() 131 .map(|key| value.pointer(pointer).unwrap()[key].clone()) 132 .collect(), 133 ); 134 *value.pointer_mut(pointer).unwrap() = array; 135 let raw = serde_json::to_vec(&value).unwrap(); 136 if CapturedListingCommand::parse(&raw).is_ok() { 137 accepted.push(format!("listing:{pointer}")); 138 } 139 if CapturedCommand::parse(&raw).is_ok() { 140 accepted.push(format!("dispatch:{pointer}")); 141 } 142 } 143 assert!( 144 accepted.is_empty(), 145 "object fields accepted positional arrays: {accepted:?}" 146 ); 147 } 148 149 #[test] 150 fn listing_objects_reject_positional_arrays_at_every_struct_boundary() { 151 let mut accepted = Vec::new(); 152 for (pointer, fields) in [ 153 ( 154 "", 155 &[ 156 "id", 157 "title", 158 "summary", 159 "description_markdown", 160 "published_at", 161 "profile", 162 ][..], 163 ), 164 ( 165 "/profile", 166 &[ 167 "profile", 168 "version", 169 "state", 170 "product", 171 "default_option", 172 "options", 173 "fulfillment", 174 "authority", 175 "media", 176 ][..], 177 ), 178 ( 179 "/profile/product", 180 &["name", "description", "producer", "origin_summary"][..], 181 ), 182 ( 183 "/profile/options/0", 184 &[ 185 "id", 186 "label", 187 "unit", 188 "increment", 189 "minimum", 190 "price", 191 "supply", 192 "lead_seconds", 193 ][..], 194 ), 195 ( 196 "/profile/fulfillment", 197 &["modes", "area", "lead_seconds"][..], 198 ), 199 ] { 200 let mut value = input(); 201 let object = value.pointer(pointer).unwrap(); 202 let array = Value::Array(fields.iter().map(|key| object[*key].clone()).collect()); 203 *value.pointer_mut(pointer).unwrap() = array; 204 if PublishInput::parse(&serde_json::to_vec(&value).unwrap()).is_ok() { 205 accepted.push(pointer); 206 } 207 } 208 assert!( 209 accepted.is_empty(), 210 "object-only fields accepted arrays: {accepted:?}" 211 ); 212 } 213 214 fn fixed_price(code: &str, minor: &str, exponent: u8) -> Value { 215 json!({"type":"fixed","rate":{"currency":code,"minor":minor,"exponent":exponent}, 216 "basis":"2","discount_bps":1000,"tiers":[]}) 217 } 218 219 fn estimated_supply(window: Value) -> Value { 220 json!({"type":"estimated","amount":"10","window":window}) 221 } 222 fn absolute_window() -> Value { 223 json!({"start":"1793480400","end":"1793487600","timezone":"America/Toronto"}) 224 } 225 226 #[test] 227 fn estimated_supply_preserves_explicit_null_and_exact_absolute_window_in_commands_and_events() { 228 use radroots_protocol::listing::ListingEvent; 229 for window in [Value::Null, absolute_window()] { 230 let mut wire = input(); 231 wire["profile"]["options"][0]["supply"] = estimated_supply(window); 232 let parsed = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 233 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire); 234 let event = ListingEvent::new(&parsed, key(), UnixSeconds::new(101).unwrap()).unwrap(); 235 let profile = event 236 .fields() 237 .tags 238 .iter() 239 .find(|tag| tag[0] == "radroots:listing") 240 .unwrap(); 241 assert_eq!( 242 serde_json::from_str::<Value>(&profile[1]).unwrap(), 243 wire["profile"] 244 ); 245 let captured = CapturedListingCommand::capture(context(), parsed).unwrap(); 246 let replay = CapturedListingCommand::parse(captured.protected_wire()).unwrap(); 247 assert_eq!(captured.digest(), replay.digest()); 248 assert_eq!(captured.protected_wire(), replay.protected_wire()); 249 } 250 } 251 252 #[test] 253 fn estimated_supply_refuses_missing_duplicate_array_noncanonical_and_ambiguous_window_data() { 254 let mut original = input(); 255 original["profile"]["options"][0]["supply"] = estimated_supply(absolute_window()); 256 for (pointer, bad) in [ 257 ( 258 "/profile/options/0/supply", 259 json!({"type":"estimated","amount":"10"}), 260 ), 261 ("/profile/options/0/supply/amount", json!("0.5")), 262 ("/profile/options/0/supply/amount", json!("-1")), 263 ("/profile/options/0/supply/amount", json!(10)), 264 ( 265 "/profile/options/0/supply/window", 266 json!(["1793480400", "1793487600", "America/Toronto"]), 267 ), 268 ( 269 "/profile/options/0/supply/window", 270 json!({"start":"100","timezone":"Etc/UTC"}), 271 ), 272 ("/profile/options/0/supply/window/start", json!(1793480400)), 273 ( 274 "/profile/options/0/supply/window/start", 275 json!("01793480400"), 276 ), 277 ("/profile/options/0/supply/window/start", json!("-1")), 278 ( 279 "/profile/options/0/supply/window/start", 280 json!("253402300800"), 281 ), 282 ("/profile/options/0/supply/window/end", json!("1793480400")), 283 ("/profile/options/0/supply/window/end", json!("0")), 284 ( 285 "/profile/options/0/supply/window/timezone", 286 json!("america/toronto"), 287 ), 288 ( 289 "/profile/options/0/supply/window/timezone", 290 json!("Invented/Zone"), 291 ), 292 ( 293 "/profile/options/0/supply/window/timezone", 294 json!("America/Toronto "), 295 ), 296 ( 297 "/profile/options/0/supply/window/timezone", 298 json!("a".repeat(81)), 299 ), 300 ("/profile/options/0/supply/window/timezone", json!(null)), 301 ] { 302 let mut wire = original.clone(); 303 *wire.pointer_mut(pointer).unwrap() = bad; 304 assert_eq!( 305 PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap_err(), 306 CommandError::InvalidInput, 307 "{pointer}" 308 ); 309 } 310 for key in ["start", "end", "timezone"] { 311 let mut missing = original.clone(); 312 missing["profile"]["options"][0]["supply"]["window"] 313 .as_object_mut() 314 .unwrap() 315 .remove(key); 316 assert!(PublishInput::parse(&serde_json::to_vec(&missing).unwrap()).is_err()); 317 } 318 for (key, value) in [ 319 ("offset", json!("-04:00")), 320 ("fold", json!(1)), 321 ("wall_time", json!("2026-11-01T01:30:00")), 322 ] { 323 let mut extra = original.clone(); 324 extra["profile"]["options"][0]["supply"]["window"][key] = value; 325 assert!(PublishInput::parse(&serde_json::to_vec(&extra).unwrap()).is_err()); 326 } 327 let raw = serde_json::to_string(&original).unwrap(); 328 for (needle, replacement) in [ 329 ( 330 "\"start\":\"1793480400\"", 331 "\"start\":\"1793480400\",\"start\":\"1793480401\"", 332 ), 333 ("\"window\":{", "\"window\":null,\"window\":{"), 334 ] { 335 assert!(raw.contains(needle)); 336 assert!(PublishInput::parse(raw.replacen(needle, replacement, 1).as_bytes()).is_err()); 337 } 338 let mut measured = original; 339 measured["profile"]["options"][0]["unit"] = json!({"type":"measured","unit":"kg"}); 340 measured["profile"]["options"][0]["supply"]["amount"] = json!("0.5"); 341 assert!(PublishInput::parse(&serde_json::to_vec(&measured).unwrap()).is_ok()); 342 measured["profile"]["options"][0]["supply"]["amount"] = json!("0"); 343 assert!(PublishInput::parse(&serde_json::to_vec(&measured).unwrap()).is_ok()); 344 } 345 346 #[test] 347 fn media_references_round_trip_without_upload_fetch_or_empty_profile_fallback() { 348 use radroots_protocol::listing::ListingEvent; 349 let reference = json!({"url":"https://media.fixture.invalid/carrot?version=1", 350 "sha256":"ab".repeat(32),"mime":"image/jpeg","alt":"Carrot 🥕\nExact text"}); 351 for count in [0, 1, 8] { 352 let mut wire = input(); 353 wire["profile"]["media"] = Value::Array(vec![reference.clone(); count]); 354 let parsed = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 355 assert_eq!(parsed.terms().media().len(), count); 356 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire); 357 let event = ListingEvent::new(&parsed, key(), UnixSeconds::new(101).unwrap()).unwrap(); 358 let profile = event 359 .fields() 360 .tags 361 .iter() 362 .find(|tag| tag[0] == "radroots:listing") 363 .unwrap(); 364 let observed: Value = serde_json::from_str(&profile[1]).unwrap(); 365 assert_eq!(observed, wire["profile"]); 366 let public = CapturedListingCommand::capture(context(), parsed).unwrap(); 367 assert_eq!( 368 CapturedListingCommand::parse(public.protected_wire()) 369 .unwrap() 370 .protected_wire(), 371 public.protected_wire() 372 ); 373 } 374 } 375 376 #[test] 377 fn media_admission_refuses_missing_unknown_duplicate_array_and_out_of_bound_values() { 378 let reference = json!({"url":"https://media.fixture.invalid/carrot", 379 "sha256":"ab".repeat(32),"mime":"image/jpeg","alt":""}); 380 let mut original = input(); 381 original["profile"]["media"] = json!([reference.clone()]); 382 for (pointer, bad) in [ 383 ("/profile/media", json!(vec![reference.clone(); 9])), 384 ("/profile/media", json!(null)), 385 ( 386 "/profile/media/0", 387 json!([ 388 "https://media.fixture.invalid/carrot", 389 "ab".repeat(32), 390 "image/jpeg", 391 "" 392 ]), 393 ), 394 ( 395 "/profile/media/0", 396 json!({"url":"https://media.fixture.invalid/carrot"}), 397 ), 398 ("/profile/media/0/sha256", json!("AB".repeat(32))), 399 ("/profile/media/0/sha256", json!("ab".repeat(31))), 400 ("/profile/media/0/sha256", json!(vec![0; 32])), 401 ("/profile/media/0/url", json!("x".repeat(2049))), 402 ("/profile/media/0/mime", json!("x".repeat(81))), 403 ("/profile/media/0/alt", json!("🥕".repeat(241))), 404 ] { 405 let mut wire = original.clone(); 406 *wire.pointer_mut(pointer).unwrap() = bad; 407 assert!( 408 PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).is_err(), 409 "{pointer}" 410 ); 411 } 412 let mut missing = original.clone(); 413 missing["profile"].as_object_mut().unwrap().remove("media"); 414 assert!(PublishInput::parse(&serde_json::to_vec(&missing).unwrap()).is_err()); 415 let mut extra = original.clone(); 416 extra["profile"]["media"][0]["verified"] = json!(true); 417 assert!(PublishInput::parse(&serde_json::to_vec(&extra).unwrap()).is_err()); 418 let raw = serde_json::to_string(&original).unwrap(); 419 let duplicate = raw.replacen( 420 "\"mime\":\"image/jpeg\"", 421 "\"mime\":\"image/jpeg\",\"mime\":\"image/jpeg\"", 422 1, 423 ); 424 assert_ne!(duplicate, raw); 425 assert!(PublishInput::parse(duplicate.as_bytes()).is_err()); 426 } 427 428 #[test] 429 fn fixed_default_projection_preserves_basis_currency_and_full_command_plan_replay() { 430 use radroots_protocol::{ 431 intent::SigningReplay, 432 listing::{ListingEvent, PublicSigningPlan}, 433 }; 434 for (code, minor, exponent, amount) in [ 435 ("JPY", "101", 0, "101"), 436 ("CAD", "101", 2, "1.01"), 437 ("KWD", "101", 3, "0.101"), 438 ("CLF", "101", 4, "0.0101"), 439 ("CAD", "0", 2, "0.00"), 440 ] { 441 let mut wire = input(); 442 wire["profile"]["options"][0]["price"] = fixed_price(code, minor, exponent); 443 wire["summary"] = json!("Carrot offering"); 444 wire["profile"]["options"][0]["unit"]["contents"] = 445 json!({"type":"fixed","quantity":{"amount":"0.5","unit":"kg"}}); 446 let mut cheaper = wire["profile"]["options"][0].clone(); 447 cheaper["id"] = json!("03".repeat(32)); 448 cheaper["price"]["rate"]["minor"] = json!("0"); 449 wire["profile"]["options"] 450 .as_array_mut() 451 .unwrap() 452 .push(cheaper); 453 let parsed = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 454 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire); 455 let event = ListingEvent::new(&parsed, key(), UnixSeconds::new(101).unwrap()).unwrap(); 456 let fields = event.fields(); 457 let prices: Vec<_> = fields.tags.iter().filter(|tag| tag[0] == "price").collect(); 458 assert_eq!(prices.len(), 1); 459 assert_eq!(prices[0].as_slice(), ["price", amount, code]); 460 assert_eq!(fields.tags.len(), 9); 461 assert_eq!(fields.tags.iter().map(Vec::len).sum::<usize>(), 19); 462 let summary = &fields.tags.iter().find(|tag| tag[0] == "summary").unwrap()[1]; 463 assert!(summary.contains("per 2 bunch")); 464 assert!(summary.contains("discount 1000 bps")); 465 assert!(summary.contains("One bunch")); 466 let public = CapturedListingCommand::capture(context(), parsed).unwrap(); 467 let captured = CapturedListingCommand::parse(public.protected_wire()).unwrap(); 468 assert_eq!(captured.digest(), public.digest()); 469 assert_eq!(captured.protected_wire(), public.protected_wire()); 470 let plan = PublicSigningPlan::capture( 471 &public, 472 UnixSeconds::new(101).unwrap(), 473 &["wss://listing.fixture.example".into()], 474 SigningReplay::LocalReplaySafe, 475 ) 476 .unwrap(); 477 let restored = PublicSigningPlan::parse(&captured, plan.protected_wire()).unwrap(); 478 assert_eq!(restored.event().event_id(), event.event_id()); 479 assert_eq!(restored.protected_wire(), plan.protected_wire()); 480 } 481 } 482 483 #[test] 484 fn variable_per_sale_unit_profile_preserves_all_bounds_and_estimated_contents_without_fixed_price() 485 { 486 use radroots_protocol::listing::ListingEvent; 487 let mut wire = input(); 488 wire["profile"]["options"][0]["price"] = json!({"type":"variable_weight","measurement_unit":"kg", 489 "minimum_per_sale_unit":"0.8","maximum_per_sale_unit":"1.2","rate":{"currency":"CAD","minor":"325","exponent":2}, 490 "basis":"1","maximum_per_sale_unit_total":{"currency":"CAD","minor":"400","exponent":2}}); 491 wire["profile"]["options"][0]["unit"]["contents"] = 492 json!({"type":"estimated","quantity":{"amount":"1","unit":"kg"}}); 493 let parsed = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 494 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire); 495 let event = ListingEvent::new(&parsed, key(), UnixSeconds::new(101).unwrap()).unwrap(); 496 assert!(!event.fields().tags.iter().any(|tag| tag[0] == "price")); 497 let summary = &event 498 .fields() 499 .tags 500 .iter() 501 .find(|tag| tag[0] == "summary") 502 .unwrap()[1]; 503 assert!(summary.contains("0.8..1.2 kg per sale unit")); 504 assert!(summary.contains("cap 4.00 CAD")); 505 assert!(summary.contains("per 1 kg")); 506 assert!( 507 parsed 508 .terms() 509 .default_option() 510 .unit() 511 .contents() 512 .unwrap() 513 .fixed_quantity() 514 .is_none() 515 ); 516 let public = CapturedListingCommand::capture(context(), parsed).unwrap(); 517 assert_eq!( 518 CapturedListingCommand::parse(public.protected_wire()) 519 .unwrap() 520 .digest(), 521 public.digest() 522 ); 523 } 524 525 #[test] 526 fn monetary_profile_admission_rejects_incomplete_inconsistent_duplicate_and_array_values() { 527 let mut original = input(); 528 original["profile"]["options"][0]["price"] = fixed_price("CAD", "325", 2); 529 for (pointer, invalid) in [ 530 ( 531 "/profile/options/0/price", 532 json!({"type":"fixed","rate":{"currency":"CAD","minor":"325","exponent":2}}), 533 ), 534 ("/profile/options/0/price/basis", json!("0")), 535 ("/profile/options/0/price/discount_bps", json!(10001)), 536 ("/profile/options/0/price/rate/exponent", json!(3)), 537 ("/profile/options/0/price/rate/minor", json!(325)), 538 ("/profile/options/0/price/rate", json!(["CAD", "325", 2])), 539 ( 540 "/profile/options/0/price/tiers", 541 json!([["1",{"currency":"CAD","minor":"300","exponent":2}]]), 542 ), 543 ( 544 "/profile/options/0/price/tiers", 545 json!([{"from":"1","rate":{"currency":"USD","minor":"300","exponent":2}}]), 546 ), 547 ( 548 "/profile/options/0/unit/contents", 549 json!({"type":"fixed","quantity":["1","kg"]}), 550 ), 551 ( 552 "/profile/options/0/unit/contents", 553 json!({"type":"fixed","quantity":{"amount":"0.5","unit":"each"}}), 554 ), 555 ] { 556 let mut wire = original.clone(); 557 *wire.pointer_mut(pointer).unwrap() = invalid; 558 assert!( 559 PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).is_err(), 560 "{pointer}" 561 ); 562 } 563 let raw = serde_json::to_string(&original).unwrap(); 564 for (needle, duplicate) in [ 565 ("\"basis\":\"2\"", "\"basis\":\"2\",\"basis\":\"2\""), 566 ("\"minor\":\"325\"", "\"minor\":\"325\",\"minor\":\"325\""), 567 ] { 568 let changed = raw.replacen(needle, duplicate, 1); 569 assert_ne!(changed, raw); 570 assert!(PublishInput::parse(changed.as_bytes()).is_err()); 571 } 572 let mut extra = original.clone(); 573 extra["profile"]["options"][0]["price"]["unapproved"] = json!(true); 574 assert!(PublishInput::parse(&serde_json::to_vec(&extra).unwrap()).is_err()); 575 } 576 577 #[test] 578 fn variable_wire_terms_refuse_inverted_ranges_infeasible_caps_and_currency_changes() { 579 let mut original = input(); 580 original["profile"]["options"][0]["price"] = json!({"type":"variable_weight","measurement_unit":"kg", 581 "minimum_per_sale_unit":"0.8","maximum_per_sale_unit":"1.2","rate":{"currency":"CAD","minor":"325","exponent":2}, 582 "basis":"1","maximum_per_sale_unit_total":{"currency":"CAD","minor":"400","exponent":2}}); 583 for (pointer, bad) in [ 584 ( 585 "/profile/options/0/price/minimum_per_sale_unit", 586 json!("1.3"), 587 ), 588 ("/profile/options/0/price/maximum_per_sale_unit", json!("0")), 589 ("/profile/options/0/price/basis", json!("0")), 590 ("/profile/options/0/price/measurement_unit", json!("each")), 591 ( 592 "/profile/options/0/price/maximum_per_sale_unit_total/minor", 593 json!("259"), 594 ), 595 ( 596 "/profile/options/0/price/maximum_per_sale_unit_total/currency", 597 json!("USD"), 598 ), 599 ] { 600 let mut wire = original.clone(); 601 *wire.pointer_mut(pointer).unwrap() = bad; 602 assert_eq!( 603 PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap_err(), 604 CommandError::InvalidInput 605 ); 606 } 607 let mut extra = original; 608 extra["profile"]["options"][0]["price"]["discount_bps"] = json!(0); 609 assert!(PublishInput::parse(&serde_json::to_vec(&extra).unwrap()).is_err()); 610 } 611 612 #[test] 613 fn monetary_listing_limits_include_projection_profile_and_complete_signed_framing() { 614 use radroots_protocol::{ 615 listing::{LISTING_EVENT_MAX_BYTES, ListingEvent}, 616 nip01::{self, WireError}, 617 }; 618 let mut wire = input(); 619 wire["description_markdown"] = json!(""); 620 wire["profile"]["options"][0]["price"] = fixed_price("CAD", "325", 2); 621 let make = |wire: &Value| PublishInput::parse(&serde_json::to_vec(wire).unwrap()).unwrap(); 622 let base = ListingEvent::new(&make(&wire), key(), UnixSeconds::new(101).unwrap()).unwrap(); 623 let free = LISTING_EVENT_MAX_BYTES 624 - nip01::signed_json_len(&base.fields(), LISTING_EVENT_MAX_BYTES).unwrap(); 625 let body = "\u{0001}".repeat(free / 6) + &"a".repeat(free % 6); 626 assert!(body.chars().count() <= 16_384); 627 wire["description_markdown"] = json!(body); 628 let exact = ListingEvent::new(&make(&wire), key(), UnixSeconds::new(101).unwrap()).unwrap(); 629 assert_eq!( 630 nip01::signed_json_len(&exact.fields(), LISTING_EVENT_MAX_BYTES).unwrap(), 631 LISTING_EVENT_MAX_BYTES 632 ); 633 let larger = wire["description_markdown"].as_str().unwrap().to_owned() + "a"; 634 wire["description_markdown"] = json!(larger); 635 assert!(matches!( 636 ListingEvent::new(&make(&wire), key(), UnixSeconds::new(101).unwrap()), 637 Err(WireError::LimitExceeded) 638 )); 639 } 640 641 #[test] 642 fn both_families_round_trip_without_rehashing_or_fabricating_chat_data() { 643 let chat = CapturedChatCommand::inquire( 644 context(), 645 InquireInput::new( 646 ThreadId::from_bytes([6; 32]), 647 key(), 648 None, 649 "Original private text", 650 ) 651 .unwrap(), 652 ) 653 .unwrap(); 654 let wire = chat.protected_wire().to_vec(); 655 let digest = chat.digest(); 656 let intent = chat.approval_intent_digest(); 657 let common = CapturedCommand::from(chat); 658 assert_eq!(common.protected_wire(), wire); 659 assert_eq!(common.digest(), digest); 660 assert_eq!(common.approval_intent_digest(), intent); 661 assert!(common.listing().is_none()); 662 let replay = CapturedCommand::parse(&wire).unwrap(); 663 assert_eq!(replay.protected_wire(), wire); 664 assert_eq!(replay.chat().unwrap().text(), "Original private text"); 665 let public = CapturedListingCommand::capture( 666 context(), 667 PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), 668 ) 669 .unwrap(); 670 let common = CapturedCommand::from(public); 671 let replay = CapturedCommand::parse(common.protected_wire()).unwrap(); 672 assert_eq!(replay.digest(), common.digest()); 673 assert_eq!(replay.protected_wire(), common.protected_wire()); 674 assert_eq!(replay.kind().as_str(), "listing.publish"); 675 assert!(replay.chat().is_none()); 676 assert!(!replay.requires_history()); 677 assert_eq!( 678 replay.listing().unwrap().input().id().to_string(), 679 "01".repeat(16) 680 ); 681 assert!(!format!("{replay:?}").contains("Carrots")); 682 } 683 684 #[test] 685 fn diagnostic_correlation_and_approval_projections_reuse_the_common_context_contract() { 686 let public = CapturedListingCommand::capture( 687 context(), 688 PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), 689 ) 690 .unwrap(); 691 let mut wire: Value = serde_json::from_slice(public.protected_wire()).unwrap(); 692 wire["context"]["correlation_id"] = json!("diagnostic-two"); 693 let diagnostic = CapturedListingCommand::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 694 assert_eq!(diagnostic.digest(), public.digest()); 695 assert_eq!( 696 diagnostic.approval_intent_digest(), 697 public.approval_intent_digest() 698 ); 699 assert_ne!(diagnostic.protected_wire(), public.protected_wire()); 700 wire["context"]["approval"] = json!({"intent_digest":"11".repeat(32),"scope":"synthetic approval metadata","expires_at":"140"}); 701 let approved = CapturedListingCommand::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 702 assert_ne!(approved.digest(), public.digest()); 703 assert_eq!( 704 approved.approval_intent_digest(), 705 public.approval_intent_digest() 706 ); 707 } 708 709 #[test] 710 fn closed_input_refuses_unknown_duplicate_missing_nullable_and_invalid_value_paths() { 711 let original = input(); 712 let bytes = serde_json::to_vec(&original).unwrap(); 713 PublishInput::parse(&bytes).unwrap(); 714 for pointer in [ 715 "/profile/authority", 716 "/profile/product/producer", 717 "/profile/product/origin_summary", 718 ] { 719 let mut value = original.clone(); 720 let (parent, key) = pointer.rsplit_once('/').unwrap(); 721 value 722 .pointer_mut(parent) 723 .unwrap() 724 .as_object_mut() 725 .unwrap() 726 .remove(key); 727 assert!( 728 PublishInput::parse(&serde_json::to_vec(&value).unwrap()).is_err(), 729 "{pointer}" 730 ); 731 } 732 for (pointer, bad) in [ 733 ("/profile/options/0/minimum", json!("1.5")), 734 ("/profile/options/0/supply/amount", json!("0.5")), 735 ("/profile/default_option", json!("03".repeat(32))), 736 ("/profile/fulfillment/modes", json!(["pickup", "pickup"])), 737 ("/published_at", json!(100)), 738 ] { 739 let mut value = original.clone(); 740 *value.pointer_mut(pointer).unwrap() = bad; 741 assert!( 742 PublishInput::parse(&serde_json::to_vec(&value).unwrap()).is_err(), 743 "{pointer}" 744 ); 745 } 746 let mut unknown = original.clone(); 747 unknown["profile"]["options"][0]["pool_id"] = json!("private inventory selector"); 748 assert!(PublishInput::parse(&serde_json::to_vec(&unknown).unwrap()).is_err()); 749 let raw = String::from_utf8(bytes).unwrap(); 750 let duplicate = raw.replacen("\"version\":1", "\"version\":1,\"version\":1", 1); 751 assert!(PublishInput::parse(duplicate.as_bytes()).is_err()); 752 assert_eq!( 753 CapturedCommand::parse(&vec![b' '; 65537]).unwrap_err(), 754 CommandError::LimitExceeded 755 ); 756 } 757 758 #[test] 759 fn unsupported_profile_features_are_refused_without_silent_fallback() { 760 for (pointer, bad) in [ 761 ("/profile/version", json!(2)), 762 ("/profile/profile", json!("other.profile")), 763 ( 764 "/profile/options/0/price", 765 json!({"type":"future_price","rate":{"currency":"CAD","minor":"325","exponent":2}}), 766 ), 767 ( 768 "/profile/options/0/supply", 769 json!({"type":"future_supply","amount":"10","window":null}), 770 ), 771 ( 772 "/profile/options/0/unit/contents", 773 json!({"type":"future_contents","quantity":{"amount":"1","unit":"kg"}}), 774 ), 775 ] { 776 let mut value = input(); 777 *value.pointer_mut(pointer).unwrap() = bad; 778 assert_eq!( 779 PublishInput::parse(&serde_json::to_vec(&value).unwrap()).unwrap_err(), 780 CommandError::UnsupportedProfile, 781 "{pointer}" 782 ); 783 } 784 } 785 786 #[test] 787 fn exact_public_plan_reconstructs_original_event_and_refuses_changed_framing_or_command() { 788 use radroots_protocol::{ 789 intent::SigningReplay, listing::PublicSigningPlan, plan::CapturedSigningPlan, 790 }; 791 let public = CapturedListingCommand::capture( 792 context(), 793 PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), 794 ) 795 .unwrap(); 796 let targets = vec![ 797 "wss://listing.fixture.example/a".to_string(), 798 "wss://listing.fixture.example/b".to_string(), 799 ]; 800 let plan = PublicSigningPlan::capture( 801 &public, 802 UnixSeconds::new(100).unwrap(), 803 &targets, 804 SigningReplay::NonReplayable, 805 ) 806 .unwrap(); 807 let wire = plan.protected_wire().to_vec(); 808 let digest = *plan.digest(); 809 let event_id = *plan.event().event_id(); 810 assert_eq!( 811 plan.selected_targets() 812 .iter() 813 .map(|s| s.as_ref()) 814 .collect::<Vec<_>>(), 815 targets 816 ); 817 let common = CapturedCommand::from(public); 818 let retained = CapturedSigningPlan::parse(&common, &wire).unwrap(); 819 assert_eq!(retained.protected_wire(), wire); 820 assert_eq!(retained.digest(), &digest); 821 assert_eq!(retained.listing().unwrap().event().event_id(), &event_id); 822 #[cfg(feature = "chat")] 823 assert!(retained.chat().is_none()); 824 assert!(!format!("{retained:?}").contains("Carrots")); 825 let changed = PublicSigningPlan::capture( 826 common.listing().unwrap(), 827 UnixSeconds::new(101).unwrap(), 828 &targets, 829 SigningReplay::NonReplayable, 830 ) 831 .unwrap(); 832 assert_ne!(changed.digest(), &digest); 833 for replay in [ 834 SigningReplay::LocalReplaySafe, 835 SigningReplay::ExactReplayByRequestId, 836 ] { 837 let changed = PublicSigningPlan::capture( 838 common.listing().unwrap(), 839 UnixSeconds::new(100).unwrap(), 840 &targets, 841 replay, 842 ) 843 .unwrap(); 844 assert_ne!(changed.digest(), &digest); 845 assert_eq!( 846 PublicSigningPlan::parse(common.listing().unwrap(), changed.protected_wire()) 847 .unwrap() 848 .replay(), 849 replay 850 ); 851 } 852 let prefix = b"radroots.listing.signing_plan.v1\0".len(); 853 for offset in [ 854 0, 855 prefix, 856 prefix + 32, 857 prefix + 64 + 8, 858 prefix + 64 + 9, 859 prefix + 64 + 10, 860 ] { 861 let mut changed = wire.clone(); 862 changed[offset] ^= 0x80; 863 assert!(CapturedSigningPlan::parse(&common, &changed).is_err()); 864 } 865 let mut changed = wire.clone(); 866 let offset = changed.windows(7).position(|w| w == b"Carrots").unwrap(); 867 changed[offset] = b'P'; 868 assert!(CapturedSigningPlan::parse(&common, &changed).is_err()); 869 let mut changed = wire.clone(); 870 changed.push(0); 871 assert!(CapturedSigningPlan::parse(&common, &changed).is_err()); 872 for end in [0, 1, prefix, prefix + 32, wire.len() - 1] { 873 assert!(CapturedSigningPlan::parse(&common, &wire[..end]).is_err()); 874 } 875 let chat = CapturedCommand::from( 876 CapturedChatCommand::inquire( 877 context(), 878 InquireInput::new(ThreadId::from_bytes([6; 32]), key(), None, "Private").unwrap(), 879 ) 880 .unwrap(), 881 ); 882 assert!(CapturedSigningPlan::parse(&chat, &wire).is_err()); 883 assert!( 884 PublicSigningPlan::capture( 885 common.listing().unwrap(), 886 UnixSeconds::new(100).unwrap(), 887 &[], 888 SigningReplay::NonReplayable 889 ) 890 .is_err() 891 ); 892 assert!( 893 PublicSigningPlan::capture( 894 common.listing().unwrap(), 895 UnixSeconds::new(100).unwrap(), 896 &vec![targets[0].clone(); 2], 897 SigningReplay::NonReplayable 898 ) 899 .is_err() 900 ); 901 } 902 903 #[test] 904 fn artifact_selection_has_no_public_participant_and_preserves_private_keys() { 905 use radroots_protocol::plan::SigningTarget; 906 let public = SigningTarget::PublicEvent; 907 assert_eq!(public.recipient(), None); 908 assert_eq!(public.key(), [0]); 909 assert_eq!(SigningTarget::from_key(&[0]).unwrap(), public); 910 let key = radroots_domain::PublicKey::from_hex( 911 "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", 912 ) 913 .unwrap(); 914 let private = SigningTarget::BusinessSeal(key); 915 assert_eq!(private.recipient(), Some(key)); 916 assert_eq!(private.key(), key.as_bytes()); 917 assert_eq!(SigningTarget::from_key(key.as_bytes()).unwrap(), private); 918 for invalid in [&[][..], &[1][..], &[0, 0][..], &[1; 31][..], &[1; 33][..]] { 919 assert!(SigningTarget::from_key(invalid).is_err()); 920 } 921 } 922 923 #[test] 924 fn public_plans_require_bounded_explicit_targets_without_scheme_or_whitespace_fallback() { 925 use radroots_protocol::{intent::SigningReplay, listing::PublicSigningPlan}; 926 let command = CapturedListingCommand::capture( 927 context(), 928 PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), 929 ) 930 .unwrap(); 931 let capture = |targets: &[String]| { 932 PublicSigningPlan::capture( 933 &command, 934 UnixSeconds::new(100).unwrap(), 935 targets, 936 SigningReplay::NonReplayable, 937 ) 938 }; 939 assert!(capture(&["wss://route.example/".into()]).is_ok()); 940 let maximum = format!("wss://{}", "x".repeat(2048 - "wss://".len())); 941 assert_eq!(maximum.len(), 2048); 942 assert!(capture(std::slice::from_ref(&maximum)).is_ok()); 943 let excessive = (0..17) 944 .map(|i| format!("wss://route.example/{i}")) 945 .collect::<Vec<_>>(); 946 assert!(capture(&excessive).is_err()); 947 for target in [ 948 format!("{maximum}x"), 949 "https://route.example/".into(), 950 "wss://route.example/a ".into(), 951 "wss://route.example/a\nb".into(), 952 ] { 953 assert!( 954 capture(std::slice::from_ref(&target)).is_err(), 955 "{target:?}" 956 ); 957 } 958 }