issuance.rs (22173B)
1 use nostr::JsonUtil; 2 use radroots_domain::OperationId; 3 use radroots_event::GenericEventDraft; 4 use radroots_event_codec::authoring::AuthoredEventPlan; 5 use radroots_identity::PublicKey; 6 use radroots_signing::{ 7 issuance::*, 8 provider::{ProviderCall, ProviderError}, 9 request::CancellationSignal, 10 }; 11 use std::{num::NonZeroU64, str::FromStr}; 12 13 const AUTHOR: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; 14 const CREATED: u64 = 1_700_000_000; 15 #[path = "issuance/exact_recovery.rs"] 16 mod exact_recovery; 17 fn plan(content: &str, tags: Vec<Vec<String>>) -> AuthoredEventPlan { 18 AuthoredEventPlan::from_generic( 19 GenericEventDraft::new( 20 "radroots.social.geochat.v1", 21 20_000, 22 CREATED, 23 tags, 24 content, 25 AUTHOR, 26 ) 27 .unwrap(), 28 ) 29 .unwrap() 30 } 31 fn intent(content: &str, tags: Vec<Vec<String>>, operation: u8, digest: u8) -> SigningIntent { 32 SigningIntent::new( 33 OperationId::from_bytes([operation; 32]), 34 [digest; 32], 35 plan(content, tags), 36 ArtifactRole::PublicEvent, 37 None, 38 ProviderCall::new( 39 PublicKey::from_str(AUTHOR).unwrap(), 40 NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), 41 CancellationSignal::new(), 42 ), 43 ) 44 .unwrap() 45 } 46 fn signed(intent: &SigningIntent) -> String { 47 let keys = nostr::Keys::new( 48 nostr::SecretKey::from_slice(&{ 49 let mut bytes = [0; 32]; 50 bytes[31] = 1; 51 bytes 52 }) 53 .unwrap(), 54 ); 55 intent.with_event(|fields, event_id| { 56 nostr::UnsignedEvent { 57 id: Some(nostr::EventId::from_slice(event_id.as_bytes()).unwrap()), 58 pubkey: keys.public_key(), 59 created_at: nostr::Timestamp::from_secs(fields.created_at), 60 kind: nostr::Kind::Custom(fields.kind as u16), 61 tags: nostr::Tags::from_list( 62 fields 63 .tags 64 .iter() 65 .cloned() 66 .map(|tag| nostr::Tag::parse(tag).unwrap()) 67 .collect(), 68 ), 69 content: fields.content.into(), 70 } 71 .sign_with_keys(&keys) 72 .unwrap() 73 .as_json() 74 }) 75 } 76 #[test] 77 fn measured_complete_wire_budget_matches_the_actual_codec_for_unicode_and_escapes() { 78 for content in [ 79 "", 80 "simple", 81 "café — soil", 82 "quotes\" and \\ slash\n\r\t\u{0000}\u{0008}\u{000c}", 83 ] { 84 let intent = intent( 85 content, 86 vec![vec!["subject".into(), "local\" crop\t".into()]], 87 7, 88 8, 89 ); 90 assert_eq!(intent.signed_json_bytes(), signed(&intent).len()); 91 assert_eq!(intent.binding().operation_id().as_bytes(), &[7; 32]); 92 } 93 let empty = intent("", vec![], 1, 2); 94 let available = SIGNED_EVENT_MAX_BYTES - empty.signed_json_bytes(); 95 let maximum = intent(&"x".repeat(available), vec![], 1, 2); 96 assert_eq!(signed(&maximum).len(), SIGNED_EVENT_MAX_BYTES); 97 let too_big = SigningIntent::new( 98 OperationId::from_bytes([1; 32]), 99 [2; 32], 100 plan(&"x".repeat(available + 1), vec![]), 101 ArtifactRole::PublicEvent, 102 None, 103 ProviderCall::new( 104 PublicKey::from_str(AUTHOR).unwrap(), 105 NonZeroU64::new(CREATED * 1000 + 10000).unwrap(), 106 CancellationSignal::new(), 107 ), 108 ); 109 assert!(matches!(too_big, Err(ProviderError::LimitExceeded))); 110 } 111 #[test] 112 fn authenticated_bytes_survive_unknown_or_out_of_range_observation_and_never_serialize_implicitly() 113 { 114 let intent = intent("synthetic bounded payload", vec![], 7, 8); 115 let raw = signed(&intent); 116 for observed in [None, NonZeroU64::new(1), NonZeroU64::new(u64::MAX)] { 117 let outcome = SigningOutcome::capture(&intent, raw.clone(), observed); 118 let OutcomeKind::Obtained(artifact) = outcome.kind() else { 119 panic!("valid artifact lost: {outcome:?}"); 120 }; 121 assert_eq!(artifact.with_json(str::to_owned), raw); 122 assert_eq!(artifact.event_id(), intent.with_event(|_, id| id)); 123 assert_eq!( 124 artifact.observed_at_unix_ms(), 125 observed.filter(|at| at.get() <= MAX_EVENT_UNIX_SECONDS * 1000 + 999) 126 ); 127 assert!(!format!("{outcome:?}").contains("synthetic bounded payload")); 128 assert_eq!(format!("{intent:?}"), "SigningIntent(<redacted>)"); 129 } 130 } 131 #[test] 132 fn callback_provenance_never_rebinds_another_operation_or_command_as_success() { 133 let original = intent("same body", vec![], 1, 2); 134 let raw = signed(&original); 135 for other in [ 136 intent("same body", vec![], 9, 2), 137 intent("same body", vec![], 1, 9), 138 ] { 139 assert_ne!(original.binding(), other.binding()); 140 let outcome = 141 SigningOutcome::capture(&original, raw.clone(), None).enforce_binding(other.binding()); 142 let OutcomeKind::Rejected(rejected) = outcome.kind() else { 143 panic!("cross-intent success"); 144 }; 145 assert_eq!(rejected.reason(), RejectionReason::BindingMismatch); 146 assert_eq!(rejected.fingerprint().unwrap().total_bytes(), raw.len()); 147 } 148 let expected = original.binding(); 149 assert!(matches!( 150 SigningOutcome::unknown(expected, ProviderError::ProviderFailure) 151 .enforce_binding(expected) 152 .kind(), 153 OutcomeKind::Unknown(_) 154 )); 155 } 156 #[test] 157 fn malformed_wrong_field_signature_and_oversized_output_are_bounded_forensics() { 158 let intent = intent("expected", vec![], 1, 2); 159 let raw = signed(&intent); 160 let mut signature: serde_json::Value = serde_json::from_str(&raw).unwrap(); 161 signature["sig"] = "00".repeat(64).into(); 162 // The callback can preserve every expected field while substituting only 163 // the returned event ID. That response is not authenticated exact evidence. 164 let mut wrong_id: serde_json::Value = serde_json::from_str(&raw).unwrap(); 165 wrong_id["id"] = "11".repeat(32).into(); 166 let different = signed(&self::intent("other", vec![], 1, 2)); 167 for (raw, reason) in [ 168 ( 169 String::from("malformed private response"), 170 RejectionReason::InvalidArtifact, 171 ), 172 (different, RejectionReason::InvalidArtifact), 173 (wrong_id.to_string(), RejectionReason::InvalidArtifact), 174 (signature.to_string(), RejectionReason::InvalidSignature), 175 ( 176 "x".repeat(SIGNED_EVENT_MAX_BYTES + 1), 177 RejectionReason::TooLarge, 178 ), 179 ] { 180 let outcome = SigningOutcome::capture(&intent, raw.clone(), None); 181 let OutcomeKind::Rejected(rejected) = outcome.kind() else { 182 panic!("untrusted output promoted"); 183 }; 184 assert_eq!(rejected.reason(), reason); 185 let fingerprint = rejected.fingerprint().unwrap(); 186 assert_eq!( 187 fingerprint.covered_bytes(), 188 raw.len().min(SIGNED_EVENT_MAX_BYTES) 189 ); 190 assert_eq!(fingerprint.total_bytes(), raw.len()); 191 assert!(!format!("{outcome:?}").contains("malformed private response")); 192 } 193 } 194 #[test] 195 fn input_identity_recipient_role_and_time_are_validated_without_host_effects() { 196 let input = |role, recipient, call| { 197 SigningIntent::new( 198 OperationId::from_bytes([1; 32]), 199 [2; 32], 200 plan("bounded", vec![]), 201 role, 202 recipient, 203 call, 204 ) 205 }; 206 let call = || { 207 ProviderCall::new( 208 PublicKey::from_str(AUTHOR).unwrap(), 209 NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), 210 CancellationSignal::new(), 211 ) 212 }; 213 assert!(matches!( 214 input(ArtifactRole::BusinessSeal, None, call()), 215 Err(ProviderError::InvalidInput) 216 )); 217 assert!(matches!( 218 input( 219 ArtifactRole::GiftWrap, 220 Some(PublicKey::from_str(AUTHOR).unwrap()), 221 call() 222 ), 223 Err(ProviderError::InvalidInput) 224 )); 225 assert!(matches!( 226 input( 227 ArtifactRole::PublicEvent, 228 Some(PublicKey::from_str(AUTHOR).unwrap()), 229 call() 230 ), 231 Err(ProviderError::InvalidInput) 232 )); 233 assert!(matches!( 234 input( 235 ArtifactRole::PublicEvent, 236 None, 237 ProviderCall::new( 238 PublicKey::from_str(AUTHOR).unwrap(), 239 NonZeroU64::new(u64::MAX).unwrap(), 240 CancellationSignal::new() 241 ) 242 ), 243 Err(ProviderError::InvalidInput) 244 )); 245 } 246 247 #[test] 248 fn unsupported_provider_explicitly_refuses_without_invoking_the_legacy_signer() { 249 use radroots_signing::{ 250 SignReceipt, SignRequest, Signer, SignerStatus, 251 provider::{ParticipantProvider, PrivateCiphertext, PrivateText, ProviderState}, 252 recovery::ReplayCapability, 253 signer::BoxFuture, 254 }; 255 use std::{ 256 sync::atomic::{AtomicUsize, Ordering}, 257 task::{Context, Poll, Waker}, 258 }; 259 struct Unsupported(AtomicUsize); 260 impl Signer for Unsupported { 261 fn status(&self) -> BoxFuture<'_, Result<SignerStatus, radroots_signing::Error>> { 262 Box::pin(async { Ok(SignerStatus::unavailable()) }) 263 } 264 fn sign( 265 &self, 266 _: SignRequest, 267 ) -> BoxFuture<'_, Result<SignReceipt, radroots_signing::Error>> { 268 self.0.fetch_add(1, Ordering::SeqCst); 269 Box::pin(async { 270 Err(radroots_signing::Error::new( 271 radroots_signing::error::Kind::SignerUnavailable, 272 )) 273 }) 274 } 275 } 276 impl ParticipantProvider for Unsupported { 277 fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>> { 278 Box::pin(async { 279 Ok(ProviderState::new( 280 PublicKey::from_str(AUTHOR).unwrap(), 281 radroots_signing::provider::PrivateCryptoCapability::Unavailable, 282 radroots_signing::provider::PrivateCryptoCapability::Unavailable, 283 ReplayCapability::NonReplayable, 284 )) 285 }) 286 } 287 fn encrypt_private( 288 &self, 289 _: ProviderCall, 290 _: PublicKey, 291 _: PrivateText, 292 ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> { 293 Box::pin(async { Err(ProviderError::CapabilityUnavailable) }) 294 } 295 fn decrypt_private( 296 &self, 297 _: ProviderCall, 298 _: PublicKey, 299 _: PrivateCiphertext, 300 ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> { 301 Box::pin(async { Err(ProviderError::CapabilityUnavailable) }) 302 } 303 } 304 let provider = Unsupported(AtomicUsize::new(0)); 305 let input = intent("bounded", vec![], 1, 2); 306 let expected = input.binding(); 307 let mut issue = provider.sign_exact(input); 308 let Poll::Ready(outcome) = issue.as_mut().poll(&mut Context::from_waker(Waker::noop())) else { 309 panic!("unsupported call pending"); 310 }; 311 assert_eq!(outcome.binding(), expected); 312 assert!(matches!( 313 outcome.kind(), 314 OutcomeKind::NotDispatched(ProviderError::CapabilityUnavailable) 315 )); 316 assert_eq!(provider.0.load(Ordering::SeqCst), 0); 317 } 318 319 #[test] 320 fn intent_binding_preserves_low_operation_bytes_deadline_role_and_recipient() { 321 let original = intent("bounded", vec![], 1, 2); 322 let mut full_id = [1; 32]; 323 full_id[31] = 2; 324 let different = SigningIntent::new( 325 OperationId::from_bytes(full_id), 326 [2; 32], 327 plan("bounded", vec![]), 328 ArtifactRole::PublicEvent, 329 None, 330 ProviderCall::new( 331 PublicKey::from_str(AUTHOR).unwrap(), 332 NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), 333 CancellationSignal::new(), 334 ), 335 ) 336 .unwrap(); 337 assert_ne!(original.binding().digest(), different.binding().digest()); 338 assert_eq!(different.binding().operation_id().into_bytes(), full_id); 339 assert_eq!(original.binding().command_digest(), &[2; 32]); 340 assert_eq!(original.role(), ArtifactRole::PublicEvent); 341 assert_eq!(original.recipient(), None); 342 let later = SigningIntent::new( 343 OperationId::from_bytes([1; 32]), 344 [2; 32], 345 plan("bounded", vec![]), 346 ArtifactRole::PublicEvent, 347 None, 348 ProviderCall::new( 349 PublicKey::from_str(AUTHOR).unwrap(), 350 NonZeroU64::new(CREATED * 1000 + 10_001).unwrap(), 351 CancellationSignal::new(), 352 ), 353 ) 354 .unwrap(); 355 assert_ne!(later.binding(), original.binding()); 356 let peer = 357 PublicKey::from_str("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") 358 .unwrap(); 359 for (role, contract, kind, tags) in [ 360 ( 361 ArtifactRole::BusinessSeal, 362 "radroots.message.seal.v1", 363 13, 364 vec![], 365 ), 366 ( 367 ArtifactRole::GiftWrap, 368 "radroots.message.gift_wrap.v1", 369 1059, 370 vec![vec!["p".into(), peer.to_hex()]], 371 ), 372 ] { 373 // Ciphertext is opaque at this signing boundary; NIP-44 effects have 374 // their separate concrete provider/interoperability qualification. 375 let opaque = AuthoredEventPlan::from_generic( 376 GenericEventDraft::new( 377 contract, 378 kind, 379 CREATED, 380 tags, 381 "synthetic ciphertext preimage", 382 AUTHOR, 383 ) 384 .unwrap(), 385 ) 386 .unwrap(); 387 // A valid private carrier still requires its separate exact recipient 388 // binding; public seal bytes deliberately contain no recipient tag. 389 assert!(matches!( 390 SigningIntent::new( 391 OperationId::from_bytes([1; 32]), 392 [2; 32], 393 opaque.clone(), 394 role, 395 None, 396 ProviderCall::new( 397 PublicKey::from_str(AUTHOR).unwrap(), 398 NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), 399 CancellationSignal::new(), 400 ), 401 ), 402 Err(ProviderError::InvalidInput) 403 )); 404 let input = SigningIntent::new( 405 OperationId::from_bytes([1; 32]), 406 [2; 32], 407 opaque, 408 role, 409 Some(peer), 410 ProviderCall::new( 411 PublicKey::from_str(AUTHOR).unwrap(), 412 NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), 413 CancellationSignal::new(), 414 ), 415 ) 416 .unwrap(); 417 assert_eq!(input.role(), role); 418 assert_eq!(input.recipient(), Some(peer)); 419 let raw = signed(&input); 420 assert_eq!(input.signed_json_bytes(), raw.len()); 421 let output = SigningOutcome::capture(&input, raw.clone(), None); 422 assert!(matches!(output.kind(), OutcomeKind::Obtained(_))); 423 let mut malformed: serde_json::Value = serde_json::from_str(&raw).unwrap(); 424 malformed["extra"] = "unsupported".into(); 425 assert!(matches!( 426 SigningOutcome::capture(&input, malformed.to_string(), None).kind(), 427 OutcomeKind::Rejected(_) 428 )); 429 } 430 } 431 432 #[test] 433 fn duplicate_escaped_duplicate_unknown_and_deep_root_fields_never_become_signature_facts() { 434 let input = intent("quoted \\\" key: { [ is content", vec![], 1, 2); 435 let raw = signed(&input); 436 assert!(matches!( 437 SigningOutcome::capture(&input, raw.clone(), None).kind(), 438 OutcomeKind::Obtained(_) 439 )); 440 for key in ["id", "\\u0069d", "content", "sig", "unknown"] { 441 let duplicate = format!("{{\"{key}\":\"untrusted first field\",{}", &raw[1..]); 442 assert!(matches!( 443 SigningOutcome::capture(&input, duplicate, None).kind(), 444 OutcomeKind::Rejected(_) 445 )); 446 } 447 let deep = format!( 448 "{{\"id\":{}0{},{}", 449 "[".repeat(17), 450 "]".repeat(17), 451 &raw[1..] 452 ); 453 assert!(matches!( 454 SigningOutcome::capture(&input, deep, None).kind(), 455 OutcomeKind::Rejected(_) 456 )); 457 } 458 459 #[test] 460 fn frozen_identity_time_and_preflight_refuse_changes_without_effects() { 461 let author = PublicKey::from_str(AUTHOR).unwrap(); 462 let peer = 463 PublicKey::from_str("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") 464 .unwrap(); 465 let call = |identity| { 466 ProviderCall::new( 467 identity, 468 NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), 469 CancellationSignal::new(), 470 ) 471 }; 472 assert!(matches!( 473 SigningIntent::new( 474 OperationId::from_bytes([1; 32]), 475 [2; 32], 476 plan("bounded", vec![]), 477 ArtifactRole::PublicEvent, 478 None, 479 call(peer) 480 ), 481 Err(ProviderError::InvalidInput) 482 )); 483 let future = AuthoredEventPlan::from_generic( 484 GenericEventDraft::new( 485 "radroots.social.geochat.v1", 486 20_000, 487 MAX_EVENT_UNIX_SECONDS + 1, 488 vec![], 489 "bounded", 490 AUTHOR, 491 ) 492 .unwrap(), 493 ) 494 .unwrap(); 495 assert!(matches!( 496 SigningIntent::new( 497 OperationId::from_bytes([1; 32]), 498 [2; 32], 499 future, 500 ArtifactRole::PublicEvent, 501 None, 502 call(author) 503 ), 504 Err(ProviderError::InvalidInput) 505 )); 506 let cancellation = CancellationSignal::new(); 507 let input = SigningIntent::new( 508 OperationId::from_bytes([1; 32]), 509 [2; 32], 510 plan("bounded", vec![]), 511 ArtifactRole::PublicEvent, 512 None, 513 ProviderCall::new( 514 author, 515 NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), 516 cancellation.clone(), 517 ), 518 ) 519 .unwrap(); 520 assert_eq!(input.author(), author); 521 assert_eq!( 522 input.check_before_effect(author, CREATED * 1000 + 1), 523 Ok(()) 524 ); 525 assert_eq!( 526 input.check_before_effect(peer, CREATED * 1000 + 1), 527 Err(ProviderError::IdentityChanged) 528 ); 529 assert_eq!( 530 input.check_before_effect(author, CREATED * 1000 + 10_000), 531 Err(ProviderError::DeadlineExceeded) 532 ); 533 cancellation.cancel(); 534 assert_eq!( 535 input.check_before_effect(author, CREATED * 1000 + 1), 536 Err(ProviderError::Cancelled) 537 ); 538 } 539 540 #[test] 541 fn complete_budget_checks_raw_content_and_multiple_tag_encoding() { 542 let huge = plan(&"x".repeat(SIGNED_EVENT_MAX_BYTES + 1), vec![]); 543 let call = ProviderCall::new( 544 PublicKey::from_str(AUTHOR).unwrap(), 545 NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), 546 CancellationSignal::new(), 547 ); 548 assert!(matches!( 549 SigningIntent::new( 550 OperationId::from_bytes([1; 32]), 551 [2; 32], 552 huge, 553 ArtifactRole::PublicEvent, 554 None, 555 call 556 ), 557 Err(ProviderError::LimitExceeded) 558 )); 559 let input = intent( 560 "bounded", 561 vec![ 562 vec!["subject".into(), "first".into()], 563 vec!["local_note".into(), "second".into()], 564 ], 565 1, 566 2, 567 ); 568 assert_eq!(input.signed_json_bytes(), signed(&input).len()); 569 } 570 571 #[test] 572 fn changed_authenticated_fields_are_refused_without_erasing_forensic_identity() { 573 use sha2::{Digest, Sha256}; 574 let input = intent("expected", vec![], 1, 2); 575 let original = nostr::Event::from_json(signed(&input)).unwrap(); 576 for changed in 0..5 { 577 // Fixed public interoperability identities; no custody material. 578 let mut scalar = [0; 32]; 579 scalar[31] = if changed == 0 { 2 } else { 1 }; 580 let keys = nostr::Keys::new(nostr::SecretKey::from_slice(&scalar).unwrap()); 581 let mut unsigned = nostr::UnsignedEvent { 582 id: None, 583 pubkey: keys.public_key(), 584 created_at: original.created_at, 585 kind: original.kind, 586 tags: original.tags.clone(), 587 content: original.content.clone(), 588 }; 589 match changed { 590 0 => {} 591 1 => unsigned.created_at = nostr::Timestamp::from_secs(CREATED + 1), 592 2 => unsigned.kind = nostr::Kind::Custom(20_001), 593 3 => { 594 unsigned.tags = nostr::Tags::from_list(vec![ 595 nostr::Tag::parse(vec!["subject", "different"]).unwrap(), 596 ]) 597 } 598 _ => unsigned.content = "different".into(), 599 } 600 let event = unsigned.sign_with_keys(&keys).unwrap(); 601 event.verify().unwrap(); 602 let raw = event.as_json(); 603 let hash: [u8; 32] = Sha256::digest(raw.as_bytes()).into(); 604 let (binding, kind) = SigningOutcome::capture(&input, raw.clone(), None).into_parts(); 605 assert_eq!(binding, input.binding()); 606 let OutcomeKind::Rejected(rejected) = kind else { 607 panic!("changed authenticated field accepted") 608 }; 609 assert_eq!(rejected.reason(), RejectionReason::InvalidArtifact); 610 let fingerprint = rejected.fingerprint().unwrap(); 611 assert_eq!(fingerprint.sha256(), &hash); 612 assert_eq!(fingerprint.covered_bytes(), raw.len()); 613 } 614 let other = intent("expected", vec![], 2, 2).binding(); 615 let rejected = SigningOutcome::capture(&input, "invalid response".into(), None); 616 let prior = match rejected.kind() { 617 OutcomeKind::Rejected(value) => value.fingerprint(), 618 _ => panic!("untrusted output accepted"), 619 }; 620 let rebound = rejected.enforce_binding(other); 621 let OutcomeKind::Rejected(value) = rebound.kind() else { 622 panic!("mismatch accepted") 623 }; 624 assert_eq!(value.reason(), RejectionReason::BindingMismatch); 625 assert_eq!(value.fingerprint(), prior); 626 let negative = 627 SigningOutcome::not_dispatched(input.binding(), ProviderError::CapabilityUnavailable) 628 .enforce_binding(other); 629 assert!(matches!(negative.kind(), OutcomeKind::Rejected(_))); 630 }