delivery.rs (22352B)
1 //! Bounded public/private delivery data. Constructors authenticate artifacts only; 2 //! actual protected work, containment, authorization and dispatch belong to 3 //! qualified store/execution owners, never to a report or enum variant. 4 5 use super::{CommitAttempt, OperationError, PublicationArtifact, PublicationWork, SigningTarget}; 6 use crate::workspace::WorkspaceBinding; 7 use core::{fmt, num::NonZeroU64}; 8 use radroots_domain::{EnvelopeEventId, PublicKey, TransactionId, UnixSeconds}; 9 use radroots_event::{ 10 SignedEvent, 11 wire::{EventWireLimits, Nip01EventWire}, 12 }; 13 use radroots_event_codec::verify::{self, Nip01SignatureVerifier, RawEvent}; 14 use radroots_protocol::intent::ArtifactRole; 15 use radroots_transport::{ 16 TargetSet, TransportId, 17 policy::{SatisfactionClass, SatisfactionPolicy}, 18 sink::{DeliveryPayload, DeliveryRequest, DeliveryRequestId}, 19 }; 20 use sha2::{Digest, Sha256}; 21 use std::{boxed::Box, collections::BTreeSet, string::String, vec, vec::Vec}; 22 use zeroize::Zeroizing; 23 24 mod private; 25 pub use self::private::PrivateEnvelopeCandidate; 26 27 const SIGNED_MAX_BYTES: usize = 65_536; 28 const MAX_TIME: u64 = 253_402_300_799; 29 30 pub(crate) fn outer(raw: &str, recipient: PublicKey) -> Result<SignedEvent, OperationError> { 31 if raw.len() > SIGNED_MAX_BYTES { 32 return Err(OperationError::InvalidEvidence); 33 } 34 let limits = EventWireLimits { 35 max_raw_json_bytes: SIGNED_MAX_BYTES, 36 max_extra_fields: 0, 37 max_total_extra_json_bytes: 0, 38 ..Default::default() 39 }; 40 let wire = Nip01EventWire::parse_json_exact_with_limits(raw, limits) 41 .map_err(|_| OperationError::InvalidEvidence)?; 42 if wire.kind != 1059 43 || wire.created_at == 0 44 || wire.created_at > MAX_TIME 45 || wire.tags != [vec![String::from("p"), recipient.to_hex()]] 46 { 47 return Err(OperationError::InvalidEvidence); 48 } 49 let event = SignedEvent::from_wire_verified_id(wire, raw) 50 .map_err(|_| OperationError::InvalidEvidence)?; 51 let checked = verify::id(RawEvent::new(event.envelope().clone())) 52 .map_err(|_| OperationError::InvalidEvidence)?; 53 verify::signature(checked, &Nip01SignatureVerifier) 54 .map_err(|_| OperationError::InvalidEvidence)?; 55 Ok(event) 56 } 57 58 fn public_event(raw: &str, work: PublicationArtifact) -> Result<SignedEvent, OperationError> { 59 if work.target() != SigningTarget::PublicEvent || raw.len() > SIGNED_MAX_BYTES { 60 return Err(OperationError::InvalidEvidence); 61 } 62 let limits = EventWireLimits { 63 max_raw_json_bytes: SIGNED_MAX_BYTES, 64 max_content_bytes: SIGNED_MAX_BYTES, 65 max_tag_count: radroots_protocol::listing::LISTING_TAG_MAX_COUNT, 66 max_total_tag_elements: radroots_protocol::listing::LISTING_TAG_TOTAL_ELEMENT_MAX_COUNT, 67 max_tag_element_bytes: SIGNED_MAX_BYTES, 68 max_total_tag_bytes: SIGNED_MAX_BYTES, 69 max_extra_fields: 0, 70 max_total_extra_json_bytes: 0, 71 }; 72 let wire = Nip01EventWire::parse_json_exact_with_limits(raw, limits) 73 .map_err(|_| OperationError::InvalidEvidence)?; 74 if wire.kind != radroots_protocol::listing::LISTING_KIND 75 || wire.id != work.evidence().event_id().to_string() 76 || <[u8; 32]>::from(Sha256::digest(raw.as_bytes())) != *work.evidence().digest() 77 { 78 return Err(OperationError::InvalidEvidence); 79 } 80 let event = SignedEvent::from_wire_verified_id_with_limits(wire, raw, limits) 81 .map_err(|_| OperationError::InvalidEvidence)?; 82 let id = verify::id(RawEvent::new(event.envelope().clone())) 83 .map_err(|_| OperationError::InvalidEvidence)?; 84 verify::signature(id, &Nip01SignatureVerifier).map_err(|_| OperationError::InvalidEvidence)?; 85 Ok(event) 86 } 87 fn payload(raw: &str, work: PublicationArtifact) -> Result<SignedEvent, OperationError> { 88 match work { 89 PublicationArtifact::Private(v) => outer(raw, v.recipient()), 90 PublicationArtifact::Public(_) => public_event(raw, work), 91 } 92 } 93 94 /// One obtained outer awaiting protected native verification and retention. 95 /// The key is temporary wrapping material, not participant custody. A matching 96 /// signature proves neither original-seal containment nor an actual store link. 97 pub struct EnvelopeCandidate { 98 work: PublicationWork, 99 envelope: PrivateEnvelopeCandidate, 100 } 101 impl EnvelopeCandidate { 102 /// Bounds before copying and verifies the exact one-recipient outer carrier. 103 /// Native capture must independently derive the key and decrypt its content 104 /// against actual original retained seal bytes before any transport right. 105 pub fn from_obtained( 106 work: PublicationWork, 107 raw: &str, 108 wrapping_key: &[u8; 32], 109 ) -> Result<Self, OperationError> { 110 Self::from_private( 111 work, 112 PrivateEnvelopeCandidate::from_obtained(work.recipient(), raw, wrapping_key)?, 113 ) 114 } 115 /// Binds a work-independent candidate to its reported original recipient. 116 /// The store must still authenticate the work and exact inner containment. 117 pub fn from_private( 118 work: PublicationWork, 119 envelope: PrivateEnvelopeCandidate, 120 ) -> Result<Self, OperationError> { 121 if envelope.recipient() != work.recipient() { 122 return Err(OperationError::InvalidEvidence); 123 } 124 Ok(Self { work, envelope }) 125 } 126 /// Reported original work; a getter does not authenticate backend state. 127 pub const fn work(&self) -> PublicationWork { 128 self.work 129 } 130 /// Actual signed outer event identity, separate from the original seal. 131 pub const fn event_id(&self) -> EnvelopeEventId { 132 self.envelope.event_id() 133 } 134 /// Actual outer author; native capture must prove this temporary key. 135 pub const fn author(&self) -> PublicKey { 136 self.envelope.author() 137 } 138 /// Signed randomized outer time, not a grant or trusted clock observation. 139 pub const fn created_at(&self) -> UnixSeconds { 140 self.envelope.created_at() 141 } 142 /// SHA-256 of the exact original outer representation. 143 pub const fn digest(&self) -> &[u8; 32] { 144 self.envelope.digest() 145 } 146 /// Exact obtained bytes for protected handling; never diagnostic output. 147 pub fn raw_json(&self) -> &str { 148 self.envelope.raw_json() 149 } 150 /// Scoped borrow for native containment verification only. 151 pub fn with_wrapping_key<T>(&self, verify: impl FnOnce(&[u8; 32]) -> T) -> T { 152 self.envelope.with_wrapping_key(verify) 153 } 154 /// Explicit bounded owner copy; the caller retains its original until the 155 /// actual outcome is reconciled. This creates no persistence fact. 156 pub fn retained_copy(&self) -> Self { 157 Self { 158 work: self.work, 159 envelope: self.envelope.retained_copy(), 160 } 161 } 162 } 163 impl fmt::Debug for EnvelopeCandidate { 164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 165 f.write_str("EnvelopeCandidate(<redacted>)") 166 } 167 } 168 169 /// Immutable one-attempt transport intent. Every target is explicit; neither 170 /// policy nor target construction proves an original route approval or lease. 171 #[derive(Clone, Eq, PartialEq)] 172 pub struct DeliveryIntent { 173 role: ArtifactRole, 174 request: DeliveryRequestId, 175 event: EnvelopeEventId, 176 targets: TargetSet, 177 policy: SatisfactionPolicy, 178 selection: Box<[radroots_transport::target::TargetFingerprint]>, 179 publication_policy: [u8; 32], 180 deadline: NonZeroU64, 181 digest: [u8; 32], 182 } 183 impl DeliveryIntent { 184 /// Captures a full 256-bit lowercase-hex request identity, at most sixteen 185 /// Nostr targets and explicit relay-acceptance policy. Relay acceptance 186 /// cannot prove recipient delivery. Owned copies shed caller spare capacity. 187 pub fn new( 188 request_id: &str, 189 event: EnvelopeEventId, 190 targets: &TargetSet, 191 policy: &SatisfactionPolicy, 192 deadline: NonZeroU64, 193 ) -> Result<Self, OperationError> { 194 Self::capture( 195 ArtifactRole::GiftWrap, 196 request_id, 197 event, 198 targets, 199 policy, 200 deadline, 201 ) 202 } 203 /// Direct public EVENT intent, without a private carrier or participant. 204 /// Actual original work/targets and dispatch rights remain backend-owned. 205 pub fn public( 206 request_id: &str, 207 event: EnvelopeEventId, 208 targets: &TargetSet, 209 policy: &SatisfactionPolicy, 210 deadline: NonZeroU64, 211 ) -> Result<Self, OperationError> { 212 Self::capture( 213 ArtifactRole::PublicEvent, 214 request_id, 215 event, 216 targets, 217 policy, 218 deadline, 219 ) 220 } 221 fn capture( 222 role: ArtifactRole, 223 request_id: &str, 224 event: EnvelopeEventId, 225 targets: &TargetSet, 226 policy: &SatisfactionPolicy, 227 deadline: NonZeroU64, 228 ) -> Result<Self, OperationError> { 229 if request_id.len() != 64 230 || !request_id 231 .bytes() 232 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) 233 || targets.len() > 16 234 || targets.is_empty() 235 || deadline.get() > MAX_TIME * 1000 + 999 236 || policy.class() != SatisfactionClass::Accepted 237 || targets 238 .targets() 239 .iter() 240 .any(|t| t.kind() != &TransportId::NOSTR || t.uri().as_str().len() > 2048) 241 { 242 return Err(OperationError::InvalidCommand); 243 } 244 policy 245 .validate_for(targets) 246 .map_err(|_| OperationError::InvalidCommand)?; 247 let mut endpoints = BTreeSet::new(); 248 if targets 249 .targets() 250 .iter() 251 .any(|target| !endpoints.insert(target.uri().as_str())) 252 { 253 return Err(OperationError::InvalidCommand); 254 } 255 let request = 256 DeliveryRequestId::parse(request_id).map_err(|_| OperationError::InvalidCommand)?; 257 let mut hash = Sha256::new(); 258 hash.update(if role == ArtifactRole::PublicEvent { 259 b"radroots.public.delivery.publication_policy.v1\0".as_slice() 260 } else { 261 b"radroots.private.delivery.publication_policy.v1\0".as_slice() 262 }); 263 hash.update((targets.len() as u16).to_be_bytes()); 264 for target in targets.targets() { 265 hash.update(target.fingerprint().as_str().as_bytes()); 266 } 267 let selected = policy.targets(); 268 if selected.is_any() { 269 hash.update([0]); 270 } else if selected.is_all() { 271 hash.update([1]); 272 } else if let Some(quorum) = selected.quorum_threshold() { 273 hash.update([2]); 274 hash.update(quorum.to_be_bytes()); 275 } else if let Some(required) = selected.required_targets() { 276 hash.update([3]); 277 hash.update((required.len() as u16).to_be_bytes()); 278 for target in required { 279 hash.update(target.as_str().as_bytes()); 280 } 281 } else { 282 return Err(OperationError::InvalidCommand); 283 } 284 let mut value = Self { 285 role, 286 request, 287 event, 288 targets: targets.clone(), 289 policy: policy.clone(), 290 selection: targets 291 .targets() 292 .iter() 293 .map(|target| target.fingerprint().clone()) 294 .collect(), 295 publication_policy: hash.finalize().into(), 296 deadline, 297 digest: [0; 32], 298 }; 299 value.refresh_digest(); 300 Ok(value) 301 } 302 fn refresh_digest(&mut self) { 303 let mut hash = Sha256::new(); 304 hash.update(if self.role == ArtifactRole::PublicEvent { 305 b"radroots.public.delivery.intent.v1\0".as_slice() 306 } else { 307 b"radroots.private.delivery.intent.v1\0".as_slice() 308 }); 309 hash.update(self.request.as_str().as_bytes()); 310 hash.update(self.event.as_bytes()); 311 hash.update(self.publication_policy); 312 hash.update(self.deadline.get().to_be_bytes()); 313 hash.update((self.selection.len() as u16).to_be_bytes()); 314 for target in &self.selection { 315 hash.update(target.as_str().as_bytes()); 316 } 317 self.digest = hash.finalize().into(); 318 } 319 /// Selects a nonempty exact subset for this potential invocation, retaining 320 /// the full original target set, completion policy and deadline. Only selected 321 /// endpoints spend attempt budgets. Data construction grants no dispatch right. 322 pub fn with_selection(mut self, selected: &TargetSet) -> Result<Self, OperationError> { 323 if selected.is_empty() 324 || selected 325 .targets() 326 .iter() 327 .any(|target| !self.targets.targets().contains(target)) 328 { 329 return Err(OperationError::InvalidCommand); 330 } 331 self.selection = self 332 .targets 333 .targets() 334 .iter() 335 .filter(|target| selected.contains(target.fingerprint())) 336 .map(|target| target.fingerprint().clone()) 337 .collect(); 338 self.refresh_digest(); 339 Ok(self) 340 } 341 /// Actual transport artifact family; the private family is a gift wrap. 342 pub const fn role(&self) -> ArtifactRole { 343 self.role 344 } 345 /// Complete original publication criterion, excluding attempt ID, envelope 346 /// selection and per-attempt deadline. The native owner freezes this 347 /// criterion for the original recipient work. 348 pub const fn publication_policy_digest(&self) -> &[u8; 32] { 349 &self.publication_policy 350 } 351 /// Selected target identities in original full-set order. 352 pub fn selection(&self) -> &[radroots_transport::target::TargetFingerprint] { 353 &self.selection 354 } 355 /// Exact selected descriptors in original full-set order. 356 pub fn selected_targets(&self) -> impl Iterator<Item = &radroots_transport::Target> { 357 self.targets 358 .targets() 359 .iter() 360 .filter(|target| self.selection.contains(target.fingerprint())) 361 } 362 /// Builds the bounded exact subset for `EventSink::deliver_selected`. 363 /// The full original transport request must still be validated separately. 364 pub fn selected_target_set(&self) -> Result<TargetSet, OperationError> { 365 TargetSet::new(self.selected_targets().cloned().collect()) 366 .map_err(|_| OperationError::InvalidCommand) 367 } 368 /// Exact full attempt identity, not diagnostic correlation. 369 pub const fn request_id(&self) -> &DeliveryRequestId { 370 &self.request 371 } 372 /// Actual selected public EVENT or private outer identity. 373 pub const fn event_id(&self) -> EnvelopeEventId { 374 self.event 375 } 376 /// Original selected target descriptors in request order. 377 pub const fn targets(&self) -> &TargetSet { 378 &self.targets 379 } 380 /// Explicit relay-acceptance law, independent of business installation. 381 pub const fn policy(&self) -> &SatisfactionPolicy { 382 &self.policy 383 } 384 /// Original absolute deadline; replay grants no fresh time window. 385 pub const fn deadline_unix_ms(&self) -> NonZeroU64 { 386 self.deadline 387 } 388 /// Commitment to identity, envelope, deadline, ordered target identities and policy. 389 /// Human target labels are diagnostic and excluded. 390 pub const fn digest(&self) -> &[u8; 32] { 391 &self.digest 392 } 393 } 394 impl fmt::Debug for DeliveryIntent { 395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 396 f.write_str("DeliveryIntent(<redacted>)") 397 } 398 } 399 400 /// Selects actual retained publication work for one potential transport attempt. 401 pub struct DeliveryAttemptRequest { 402 binding: WorkspaceBinding, 403 work: PublicationArtifact, 404 intent: DeliveryIntent, 405 } 406 impl DeliveryAttemptRequest { 407 /// Structural scope comparison only; a native owner must authenticate the 408 /// original complete graph, current grant and exact selected routes. 409 pub fn new( 410 binding: WorkspaceBinding, 411 work: impl Into<PublicationArtifact>, 412 intent: DeliveryIntent, 413 ) -> Result<Self, OperationError> { 414 let work = work.into(); 415 if binding.input().workspace_id() != work.evidence().workspace_id() 416 || !matches!( 417 (work, intent.role()), 418 (PublicationArtifact::Private(_), ArtifactRole::GiftWrap) 419 | (PublicationArtifact::Public(_), ArtifactRole::PublicEvent) 420 ) 421 { 422 return Err(OperationError::InvalidCommand); 423 } 424 Ok(Self { 425 binding, 426 work, 427 intent, 428 }) 429 } 430 /// Reported authenticated binding, subject to current native revalidation. 431 pub const fn binding(&self) -> &WorkspaceBinding { 432 &self.binding 433 } 434 /// Immutable reported work; native capture compares its actual protected row. 435 pub const fn work(&self) -> PublicationArtifact { 436 self.work 437 } 438 /// Exact requested transport intent. 439 pub const fn intent(&self) -> &DeliveryIntent { 440 &self.intent 441 } 442 /// Original operation anchor; no outcome is inferred from construction. 443 pub fn identity(&self) -> CommitAttempt { 444 let e = self.work.evidence(); 445 CommitAttempt::new(e.workspace_id(), e.operation_id(), e.command_digest(), None) 446 } 447 } 448 impl fmt::Debug for DeliveryAttemptRequest { 449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 450 f.write_str("DeliveryAttemptRequest(<redacted>)") 451 } 452 } 453 454 /// Complete original attempt report and exact bytes. Constructing or querying 455 /// this value never permits replay of a potential invocation. 456 pub struct DeliveryAttempt { 457 work: PublicationArtifact, 458 intent: DeliveryIntent, 459 raw: Zeroizing<String>, 460 digest: [u8; 32], 461 transaction: TransactionId, 462 retained_at: UnixSeconds, 463 ordinals: Box<[u8]>, 464 } 465 impl DeliveryAttempt { 466 /// Checks scoped data and carrier authenticity only. Native backends must 467 /// independently verify original protected state and execute retention. 468 pub fn from_store_report( 469 work: impl Into<PublicationArtifact>, 470 intent: DeliveryIntent, 471 raw: &str, 472 transaction: TransactionId, 473 retained_at: UnixSeconds, 474 ordinals: Vec<u8>, 475 ) -> Result<Self, OperationError> { 476 let work = work.into(); 477 if !matches!( 478 (work, intent.role()), 479 (PublicationArtifact::Private(_), ArtifactRole::GiftWrap) 480 | (PublicationArtifact::Public(_), ArtifactRole::PublicEvent) 481 ) { 482 return Err(OperationError::InvalidEvidence); 483 } 484 let event = payload(raw, work)?; 485 if event.envelope().id().as_bytes() != intent.event_id().as_bytes() 486 || retained_at < work.queued_at() 487 || event.envelope().created_at_u64() > retained_at.get() 488 || retained_at 489 .get() 490 .checked_mul(1000) 491 .is_none_or(|now| now >= intent.deadline_unix_ms().get()) 492 || ordinals.len() != intent.selection().len() 493 || ordinals.iter().any(|n| !(1..=12).contains(n)) 494 { 495 return Err(OperationError::RecoveryRequired); 496 } 497 Ok(Self { 498 work, 499 intent, 500 raw: Zeroizing::new(String::from(raw)), 501 digest: Sha256::digest(raw.as_bytes()).into(), 502 transaction, 503 retained_at, 504 ordinals: ordinals.into_boxed_slice(), 505 }) 506 } 507 /// Original protected publication reference. 508 pub const fn work(&self) -> PublicationArtifact { 509 self.work 510 } 511 /// Original complete transport intent. 512 pub const fn intent(&self) -> &DeliveryIntent { 513 &self.intent 514 } 515 /// Exact originally retained signed representation. 516 pub fn raw_json(&self) -> &str { 517 &self.raw 518 } 519 /// Digest of the exact retained representation. 520 pub const fn envelope_digest(&self) -> &[u8; 32] { 521 &self.digest 522 } 523 /// Original actual store transaction. 524 pub const fn transaction_id(&self) -> TransactionId { 525 self.transaction 526 } 527 /// Original retention time; never a renewed dispatch deadline. 528 pub const fn retained_at(&self) -> UnixSeconds { 529 self.retained_at 530 } 531 /// Per-target potential invocation numbers, in exact target order. 532 pub fn target_ordinals(&self) -> &[u8] { 533 &self.ordinals 534 } 535 /// Reconstructs the full original request. A qualified owner must use 536 /// `EventSink::deliver_selected` with `intent().selected_target_set()`; 537 /// unselected endpoints have no retained invocation. This data conversion 538 /// grants no dispatch permission or automatic retry. 539 pub fn transport_request(&self) -> Result<DeliveryRequest, OperationError> { 540 let event = payload(self.raw_json(), self.work)?; 541 DeliveryRequest::new( 542 self.intent.request_id().as_str(), 543 DeliveryPayload::new(event), 544 self.intent.targets().clone(), 545 self.intent.policy().clone(), 546 self.intent.deadline_unix_ms().get(), 547 ) 548 .map_err(|_| OperationError::RecoveryRequired) 549 } 550 } 551 impl fmt::Debug for DeliveryAttempt { 552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 553 f.write_str("DeliveryAttempt(<redacted>)") 554 } 555 } 556 557 /// Only an actual freshly committed native claim can permit its qualified 558 /// owner to proceed once after current route/provider/access checks. 559 pub enum DeliveryAttemptOutcome { 560 /// Actual new protected attempt and exact bytes committed before transport. 561 Claimed(Box<DeliveryAttempt>), 562 /// Existing potential invocation, never permission to dispatch again. 563 Retained(Box<DeliveryAttempt>), 564 /// Reconcile this exact original identity before any further scheduling. 565 Unknown { 566 /// Original workspace/operation/command and optional transaction anchor. 567 operation: CommitAttempt, 568 /// Full original transport attempt identity. 569 attempt: DeliveryRequestId, 570 }, 571 } 572 impl fmt::Debug for DeliveryAttemptOutcome { 573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 574 f.write_str("DeliveryAttemptOutcome(<redacted>)") 575 } 576 }