transport.rs (133730B)
1 //! Explicit user-facing transport profile composition. 2 //! 3 //! Profiles retain canonical `radroots_transport` identities, targets, 4 //! policies, and statuses. They select no adapter implicitly and never replace 5 //! an unavailable selection with another transport. 6 7 use radroots_transport::{ 8 Error, SinkStatus, SourceStatus, TargetSet, TransportId, 9 capability::{Availability, Maturity, SinkCapabilities, SourceCapabilities}, 10 policy::SatisfactionPolicy, 11 }; 12 #[cfg(any(feature = "blossom", feature = "nostr"))] 13 use std::sync::{ 14 Arc, RwLock, 15 atomic::{AtomicBool, Ordering}, 16 }; 17 18 #[cfg(feature = "blossom")] 19 use std::{ 20 collections::BTreeSet, 21 net::{IpAddr, Ipv4Addr, Ipv6Addr}, 22 time::{Duration, SystemTime, UNIX_EPOCH}, 23 }; 24 25 #[cfg(feature = "blossom")] 26 use radroots_blossom::{ 27 BlobUrl, ByteVerifiedDescriptor, MediaType, Sha256, 28 authorization::{AuthoredUploadClaim, AuthorizationContent, ServerDomain}, 29 }; 30 31 #[cfg(feature = "nostr")] 32 pub use radroots_transport_nostr::{ 33 ReconnectBackoff, RelayAccess, RelayAggregateState, RelayCapabilityEvidence, RelayCursor, 34 RelayEndpoint, RelayEvidenceState, RelayProfile, RelayProfileKind, RelayStatus, 35 RelayStatusReport, RelayUrl, RelayUrlPolicy, 36 }; 37 38 const PREVIEW_UNAVAILABLE_MESSAGE: &str = "preview transport is unavailable in this SDK release"; 39 40 #[cfg(feature = "blossom")] 41 const MAX_BLOSSOM_ENDPOINTS: usize = 16; 42 #[cfg(feature = "blossom")] 43 const MAX_BLOSSOM_BLOB_BYTES: u64 = 100 * 1024 * 1024; 44 #[cfg(feature = "blossom")] 45 const MAX_BLOSSOM_DESCRIPTOR_BYTES: usize = 64 * 1024; 46 #[cfg(feature = "blossom")] 47 const MAX_BLOSSOM_REDIRECTS: u8 = 5; 48 #[cfg(feature = "blossom")] 49 const MAX_BLOSSOM_ATTEMPTS: u8 = 5; 50 #[cfg(feature = "blossom")] 51 const MAX_BLOSSOM_TIMEOUT: Duration = Duration::from_secs(120); 52 #[cfg(feature = "blossom")] 53 const MAX_BLOSSOM_RETRY_DELAY: Duration = Duration::from_secs(30); 54 #[cfg(feature = "blossom")] 55 const MAX_BLOSSOM_IMAGE_EDGE: u32 = 16_384; 56 #[cfg(feature = "blossom")] 57 const MAX_BLOSSOM_IMAGE_PIXELS: u64 = 100_000_000; 58 59 /// Host environment executing Blossom operations. 60 #[cfg(feature = "blossom")] 61 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 62 #[non_exhaustive] 63 pub enum BlossomHostKind { 64 /// A non-mobile native host. 65 Native, 66 /// An Apple or Android simulator. 67 Simulator, 68 /// A physical mobile device. 69 PhysicalDevice, 70 } 71 72 /// Network authority applied independently to configured Blossom origins. 73 #[cfg(feature = "blossom")] 74 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 75 #[non_exhaustive] 76 pub enum BlossomEndpointAuthority { 77 /// Public HTTPS authenticated by the platform WebPKI roots. 78 PublicWebPki, 79 /// Development-only HTTP or HTTPS resolving exclusively to loopback. 80 LoopbackDevelopment, 81 /// Development-only HTTP or HTTPS using an exact RFC1918 or ULA address. 82 PrivateNetworkDevelopment, 83 } 84 85 /// One canonical configured Blossom origin. 86 #[cfg(feature = "blossom")] 87 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 88 pub struct BlossomEndpoint { 89 origin: String, 90 host: String, 91 port: u16, 92 authority: BlossomEndpointAuthority, 93 } 94 95 #[cfg(feature = "blossom")] 96 impl BlossomEndpoint { 97 fn parse( 98 value: impl AsRef<str>, 99 authority: BlossomEndpointAuthority, 100 ) -> Result<Self, BlossomError> { 101 let value = value.as_ref(); 102 if value.is_empty() || !value.is_ascii() || value.chars().any(char::is_whitespace) { 103 return Err(BlossomError::configuration( 104 BlossomErrorKind::InvalidEndpoint, 105 )); 106 } 107 let parsed = reqwest::Url::parse(value) 108 .map_err(|_| BlossomError::configuration(BlossomErrorKind::InvalidEndpoint))?; 109 if !parsed.username().is_empty() 110 || parsed.password().is_some() 111 || parsed.query().is_some() 112 || parsed.fragment().is_some() 113 || parsed.path() != "/" 114 { 115 return Err(BlossomError::configuration( 116 BlossomErrorKind::InvalidEndpoint, 117 )); 118 } 119 let host = parsed 120 .host_str() 121 .ok_or_else(|| BlossomError::configuration(BlossomErrorKind::InvalidEndpoint))? 122 .to_owned(); 123 let port = parsed 124 .port_or_known_default() 125 .ok_or_else(|| BlossomError::configuration(BlossomErrorKind::InvalidEndpoint))?; 126 if port == 0 || !endpoint_scheme_is_allowed(parsed.scheme(), authority) { 127 return Err(BlossomError::configuration( 128 BlossomErrorKind::EndpointSchemeDenied, 129 )); 130 } 131 validate_blossom_host(host.as_str(), authority)?; 132 ServerDomain::parse(host.as_str()) 133 .map_err(|_| BlossomError::configuration(BlossomErrorKind::InvalidEndpoint))?; 134 // HTTP(S) URLs always have a tuple origin after the scheme and host 135 // checks above, so `ascii_serialization` cannot be the opaque `null` 136 // origin here. 137 let origin = parsed.origin().ascii_serialization(); 138 Ok(Self { 139 origin, 140 host, 141 port, 142 authority, 143 }) 144 } 145 146 /// Returns the canonical origin without a trailing slash. 147 #[must_use] 148 pub fn origin(&self) -> &str { 149 self.origin.as_str() 150 } 151 152 /// Returns the BUD-11 server-domain spelling. 153 #[must_use] 154 pub fn host(&self) -> &str { 155 self.host.as_str() 156 } 157 158 /// Returns the resolved connection port. 159 #[must_use] 160 pub const fn port(&self) -> u16 { 161 self.port 162 } 163 164 /// Returns the authority used before and after DNS resolution. 165 #[must_use] 166 pub const fn authority(&self) -> BlossomEndpointAuthority { 167 self.authority 168 } 169 170 pub(crate) fn upload_url(&self) -> String { 171 format!("{}/upload", self.origin) 172 } 173 174 pub(crate) fn server_domain(&self) -> Result<ServerDomain, BlossomError> { 175 ServerDomain::parse(self.host.as_str()) 176 .map_err(|_| BlossomError::configuration(BlossomErrorKind::InvalidEndpoint)) 177 } 178 179 pub(crate) fn accepts_blob_url(&self, value: &BlobUrl) -> bool { 180 reqwest::Url::parse(value.as_str()) 181 .is_ok_and(|url| url.origin().ascii_serialization() == self.origin) 182 } 183 184 pub(crate) fn validate_resolved_addresses( 185 &self, 186 addresses: impl IntoIterator<Item = IpAddr>, 187 ) -> Result<(), BlossomError> { 188 let mut found = false; 189 for address in addresses { 190 found = true; 191 if !blossom_authority_accepts_address(self.authority, address) { 192 return Err(BlossomError::configuration( 193 BlossomErrorKind::ResolvedAddressDenied, 194 )); 195 } 196 } 197 if !found { 198 return Err(BlossomError::configuration( 199 BlossomErrorKind::ResolutionFailed, 200 )); 201 } 202 Ok(()) 203 } 204 } 205 206 /// Complete validated Blossom origin set for one host environment. 207 #[cfg(feature = "blossom")] 208 #[derive(Clone, Debug, Eq, PartialEq)] 209 pub struct BlossomProfile { 210 host_kind: BlossomHostKind, 211 authority: BlossomEndpointAuthority, 212 primary: BlossomEndpoint, 213 fallbacks: Vec<BlossomEndpoint>, 214 } 215 216 #[cfg(feature = "blossom")] 217 impl BlossomProfile { 218 /// Configures one primary origin and an ordered, explicitly bounded fallback set. 219 pub fn new<I, S>( 220 host_kind: BlossomHostKind, 221 authority: BlossomEndpointAuthority, 222 primary_origin: impl AsRef<str>, 223 fallback_origins: I, 224 ) -> Result<Self, BlossomError> 225 where 226 I: IntoIterator<Item = S>, 227 S: AsRef<str>, 228 { 229 validate_host_authority(host_kind, authority)?; 230 let primary = BlossomEndpoint::parse(primary_origin, authority)?; 231 // The public constructor accepts any iterator, so bound collection 232 // before parsing to prevent an oversized caller from allocating an 233 // unbounded temporary vector only to be rejected afterward. 234 let fallbacks = fallback_origins 235 .into_iter() 236 .take(MAX_BLOSSOM_ENDPOINTS) 237 .map(|origin| BlossomEndpoint::parse(origin, authority)) 238 .collect::<Result<Vec<_>, _>>()?; 239 if fallbacks.len().saturating_add(1) > MAX_BLOSSOM_ENDPOINTS { 240 return Err(BlossomError::configuration( 241 BlossomErrorKind::InvalidEndpointCount, 242 )); 243 } 244 let unique = std::iter::once(&primary) 245 .chain(fallbacks.iter()) 246 .map(BlossomEndpoint::origin) 247 .collect::<BTreeSet<_>>(); 248 if unique.len() != fallbacks.len().saturating_add(1) { 249 return Err(BlossomError::configuration( 250 BlossomErrorKind::DuplicateEndpoint, 251 )); 252 } 253 Ok(Self { 254 host_kind, 255 authority, 256 primary, 257 fallbacks, 258 }) 259 } 260 261 #[must_use] 262 pub const fn host_kind(&self) -> BlossomHostKind { 263 self.host_kind 264 } 265 266 #[must_use] 267 pub const fn authority(&self) -> BlossomEndpointAuthority { 268 self.authority 269 } 270 271 #[must_use] 272 pub const fn primary(&self) -> &BlossomEndpoint { 273 &self.primary 274 } 275 276 #[must_use] 277 pub fn fallbacks(&self) -> &[BlossomEndpoint] { 278 self.fallbacks.as_slice() 279 } 280 281 pub(crate) fn endpoint_for_blob(&self, url: &BlobUrl) -> Option<&BlossomEndpoint> { 282 std::iter::once(&self.primary) 283 .chain(self.fallbacks.iter()) 284 .find(|endpoint| endpoint.accepts_blob_url(url)) 285 } 286 } 287 288 /// Bounded HTTP, response, retry, and redirect policy for Blossom operations. 289 #[cfg(feature = "blossom")] 290 #[derive(Clone, Debug, Eq, PartialEq)] 291 pub struct BlossomConfig { 292 profile: BlossomProfile, 293 max_blob_bytes: u64, 294 max_descriptor_bytes: usize, 295 max_redirects: u8, 296 max_attempts: u8, 297 connect_timeout: Duration, 298 request_timeout: Duration, 299 initial_retry_delay: Duration, 300 } 301 302 #[cfg(feature = "blossom")] 303 impl BlossomConfig { 304 #[must_use] 305 pub fn from_profile(profile: BlossomProfile) -> Self { 306 Self { 307 profile, 308 max_blob_bytes: 20 * 1024 * 1024, 309 max_descriptor_bytes: 16 * 1024, 310 max_redirects: 3, 311 max_attempts: 3, 312 connect_timeout: Duration::from_secs(10), 313 request_timeout: Duration::from_secs(60), 314 initial_retry_delay: Duration::from_millis(250), 315 } 316 } 317 318 pub fn with_limits( 319 mut self, 320 max_blob_bytes: u64, 321 max_descriptor_bytes: usize, 322 max_redirects: u8, 323 ) -> Result<Self, BlossomError> { 324 if max_blob_bytes == 0 325 || max_blob_bytes > MAX_BLOSSOM_BLOB_BYTES 326 || max_descriptor_bytes == 0 327 || max_descriptor_bytes > MAX_BLOSSOM_DESCRIPTOR_BYTES 328 || max_redirects > MAX_BLOSSOM_REDIRECTS 329 { 330 return Err(BlossomError::configuration(BlossomErrorKind::InvalidLimits)); 331 } 332 self.max_blob_bytes = max_blob_bytes; 333 self.max_descriptor_bytes = max_descriptor_bytes; 334 self.max_redirects = max_redirects; 335 Ok(self) 336 } 337 338 pub fn with_network_policy( 339 mut self, 340 connect_timeout: Duration, 341 request_timeout: Duration, 342 max_attempts: u8, 343 initial_retry_delay: Duration, 344 ) -> Result<Self, BlossomError> { 345 if connect_timeout.is_zero() 346 || connect_timeout > MAX_BLOSSOM_TIMEOUT 347 || request_timeout.is_zero() 348 || request_timeout > MAX_BLOSSOM_TIMEOUT 349 || max_attempts == 0 350 || max_attempts > MAX_BLOSSOM_ATTEMPTS 351 || initial_retry_delay.is_zero() 352 || initial_retry_delay > MAX_BLOSSOM_RETRY_DELAY 353 { 354 return Err(BlossomError::configuration(BlossomErrorKind::InvalidLimits)); 355 } 356 self.connect_timeout = connect_timeout; 357 self.request_timeout = request_timeout; 358 self.max_attempts = max_attempts; 359 self.initial_retry_delay = initial_retry_delay; 360 Ok(self) 361 } 362 363 #[must_use] 364 pub const fn profile(&self) -> &BlossomProfile { 365 &self.profile 366 } 367 368 /// Returns the stable identity of every setting that can affect an operation. 369 #[must_use] 370 pub fn fingerprint(&self) -> BlossomConfigFingerprint { 371 let mut material = Vec::new(); 372 material.extend_from_slice(b"radroots-blossom-config-v1\0"); 373 material.push(match self.profile.host_kind { 374 BlossomHostKind::Native => 0, 375 BlossomHostKind::Simulator => 1, 376 BlossomHostKind::PhysicalDevice => 2, 377 }); 378 material.push(match self.profile.authority { 379 BlossomEndpointAuthority::PublicWebPki => 0, 380 BlossomEndpointAuthority::LoopbackDevelopment => 1, 381 BlossomEndpointAuthority::PrivateNetworkDevelopment => 2, 382 }); 383 append_fingerprint_field(&mut material, self.profile.primary.origin.as_bytes()); 384 material.extend_from_slice(&(self.profile.fallbacks.len() as u64).to_be_bytes()); 385 for endpoint in &self.profile.fallbacks { 386 append_fingerprint_field(&mut material, endpoint.origin.as_bytes()); 387 } 388 material.extend_from_slice(&self.max_blob_bytes.to_be_bytes()); 389 material.extend_from_slice(&(self.max_descriptor_bytes as u64).to_be_bytes()); 390 material.push(self.max_redirects); 391 material.push(self.max_attempts); 392 material.extend_from_slice(&(self.connect_timeout.as_millis() as u64).to_be_bytes()); 393 material.extend_from_slice(&(self.request_timeout.as_millis() as u64).to_be_bytes()); 394 material.extend_from_slice(&(self.initial_retry_delay.as_millis() as u64).to_be_bytes()); 395 BlossomConfigFingerprint(Sha256::digest(material.as_slice())) 396 } 397 398 pub(crate) const fn max_blob_bytes(&self) -> u64 { 399 self.max_blob_bytes 400 } 401 402 pub(crate) const fn max_descriptor_bytes(&self) -> usize { 403 self.max_descriptor_bytes 404 } 405 406 pub(crate) const fn max_redirects(&self) -> u8 { 407 self.max_redirects 408 } 409 410 pub(crate) const fn max_attempts(&self) -> u8 { 411 self.max_attempts 412 } 413 414 pub(crate) const fn connect_timeout(&self) -> Duration { 415 self.connect_timeout 416 } 417 418 pub(crate) const fn request_timeout(&self) -> Duration { 419 self.request_timeout 420 } 421 422 pub(crate) const fn initial_retry_delay(&self) -> Duration { 423 self.initial_retry_delay 424 } 425 426 pub(crate) fn retry_delay(&self, attempt: u8) -> Duration { 427 let exponent = u32::from(attempt.saturating_sub(1)).min(16); 428 self.initial_retry_delay() 429 .saturating_mul(1_u32 << exponent) 430 .min(MAX_BLOSSOM_RETRY_DELAY) 431 } 432 } 433 434 /// Stable, non-secret identity of a completely validated Blossom configuration. 435 #[cfg(feature = "blossom")] 436 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 437 pub struct BlossomConfigFingerprint(Sha256); 438 439 #[cfg(feature = "blossom")] 440 impl BlossomConfigFingerprint { 441 #[must_use] 442 pub const fn as_bytes(&self) -> &[u8; 32] { 443 self.0.as_bytes() 444 } 445 446 #[must_use] 447 pub fn to_hex(self) -> String { 448 self.0.to_hex() 449 } 450 } 451 452 #[cfg(feature = "blossom")] 453 impl std::fmt::Display for BlossomConfigFingerprint { 454 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 455 std::fmt::Display::fmt(&self.0, formatter) 456 } 457 } 458 459 #[cfg(feature = "blossom")] 460 fn append_fingerprint_field(material: &mut Vec<u8>, value: &[u8]) { 461 material.extend_from_slice(&(value.len() as u64).to_be_bytes()); 462 material.extend_from_slice(value); 463 } 464 465 #[cfg(feature = "blossom")] 466 pub(crate) fn blossom_now_unix_ms() -> u64 { 467 SystemTime::now() 468 .duration_since(UNIX_EPOCH) 469 .ok() 470 .and_then(|duration| u64::try_from(duration.as_millis()).ok()) 471 .unwrap_or(u64::MAX) 472 .max(1) 473 } 474 475 /// Nonzero dimensions verified from the final image bytes. 476 #[cfg(feature = "blossom")] 477 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 478 pub struct BlossomImageDimensions { 479 width: u32, 480 height: u32, 481 } 482 483 #[cfg(feature = "blossom")] 484 impl BlossomImageDimensions { 485 pub const fn new(width: u32, height: u32) -> Result<Self, BlossomError> { 486 if width == 0 487 || height == 0 488 || width > MAX_BLOSSOM_IMAGE_EDGE 489 || height > MAX_BLOSSOM_IMAGE_EDGE 490 || width as u64 * height as u64 > MAX_BLOSSOM_IMAGE_PIXELS 491 { 492 return Err(BlossomError::configuration( 493 BlossomErrorKind::InvalidDimensions, 494 )); 495 } 496 Ok(Self { width, height }) 497 } 498 499 #[must_use] 500 pub const fn width(self) -> u32 { 501 self.width 502 } 503 504 #[must_use] 505 pub const fn height(self) -> u32 { 506 self.height 507 } 508 } 509 510 /// Exact final image bytes from which Rust derives the BUD-02 destination. 511 #[cfg(feature = "blossom")] 512 #[derive(Clone)] 513 pub struct BlossomUploadRequest { 514 sha256: Sha256, 515 bytes: Arc<[u8]>, 516 media_type: MediaType, 517 dimensions: BlossomImageDimensions, 518 verified_at_unix_ms: u64, 519 } 520 521 #[cfg(feature = "blossom")] 522 impl BlossomUploadRequest { 523 pub fn new( 524 bytes: Arc<[u8]>, 525 media_type: MediaType, 526 dimensions: BlossomImageDimensions, 527 verified_at_unix_ms: u64, 528 ) -> Result<Self, BlossomError> { 529 if bytes.is_empty() || verified_at_unix_ms == 0 { 530 return Err(BlossomError::configuration( 531 BlossomErrorKind::InvalidRequest, 532 )); 533 } 534 crate::adapters::blossom::verify_image(bytes.as_ref(), &media_type, dimensions)?; 535 Ok(Self { 536 sha256: Sha256::digest(bytes.as_ref()), 537 bytes, 538 media_type, 539 dimensions, 540 verified_at_unix_ms, 541 }) 542 } 543 544 #[must_use] 545 pub fn media_type(&self) -> &MediaType { 546 &self.media_type 547 } 548 549 #[must_use] 550 pub const fn dimensions(&self) -> BlossomImageDimensions { 551 self.dimensions 552 } 553 554 #[must_use] 555 pub const fn sha256(&self) -> Sha256 { 556 self.sha256 557 } 558 559 #[must_use] 560 pub fn byte_size(&self) -> u64 { 561 self.bytes.len() as u64 562 } 563 564 pub(crate) fn bytes(&self) -> &[u8] { 565 self.bytes.as_ref() 566 } 567 568 pub(crate) const fn verified_at_unix_ms(&self) -> u64 { 569 self.verified_at_unix_ms 570 } 571 } 572 573 /// Expected signed metadata for one bounded BUD-01 image retrieval. 574 #[cfg(feature = "blossom")] 575 #[derive(Clone, Debug, Eq, PartialEq)] 576 pub struct BlossomInboundRequest { 577 url: BlobUrl, 578 expected_media_type: Option<MediaType>, 579 expected_byte_size: Option<u64>, 580 expected_dimensions: Option<BlossomImageDimensions>, 581 } 582 583 #[cfg(feature = "blossom")] 584 impl BlossomInboundRequest { 585 pub fn new( 586 url: BlobUrl, 587 expected_media_type: Option<MediaType>, 588 expected_byte_size: Option<u64>, 589 expected_dimensions: Option<BlossomImageDimensions>, 590 ) -> Result<Self, BlossomError> { 591 url.clone() 592 .approve() 593 .map_err(|_| BlossomError::configuration(BlossomErrorKind::InvalidRequest))?; 594 if expected_byte_size == Some(0) { 595 return Err(BlossomError::configuration( 596 BlossomErrorKind::InvalidRequest, 597 )); 598 } 599 if let Some(media_type) = &expected_media_type { 600 let extension = canonical_image_extension(media_type)?; 601 if url 602 .hash_path() 603 .extension() 604 .is_none_or(|value| value.as_str() != extension) 605 { 606 return Err(BlossomError::configuration( 607 BlossomErrorKind::MediaTypeMismatch, 608 )); 609 } 610 } 611 Ok(Self { 612 url, 613 expected_media_type, 614 expected_byte_size, 615 expected_dimensions, 616 }) 617 } 618 619 #[must_use] 620 pub const fn url(&self) -> &BlobUrl { 621 &self.url 622 } 623 624 #[must_use] 625 pub const fn expected_media_type(&self) -> Option<&MediaType> { 626 self.expected_media_type.as_ref() 627 } 628 629 #[must_use] 630 pub const fn expected_byte_size(&self) -> Option<u64> { 631 self.expected_byte_size 632 } 633 634 #[must_use] 635 pub const fn expected_dimensions(&self) -> Option<BlossomImageDimensions> { 636 self.expected_dimensions 637 } 638 } 639 640 /// Immutable upload plan binding exact bytes to one complete configuration. 641 #[cfg(feature = "blossom")] 642 #[derive(Clone)] 643 pub struct BlossomUploadTransaction { 644 config: BlossomConfig, 645 config_fingerprint: BlossomConfigFingerprint, 646 endpoint: BlossomEndpoint, 647 expected_url: BlobUrl, 648 request: BlossomUploadRequest, 649 } 650 651 /// Security property observed for the configured primary transport. 652 #[cfg(feature = "blossom")] 653 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 654 #[non_exhaustive] 655 pub enum BlossomTransportSecurity { 656 /// Public HTTPS authenticated by the bundled platform WebPKI roots. 657 PublicWebPki, 658 /// Development HTTPS without a public-origin availability claim. 659 DevelopmentTls, 660 /// Development-only cleartext loopback or exact-private-network HTTP. 661 DevelopmentCleartext, 662 } 663 664 /// Latest redacted evidence state for the configured primary Blossom origin. 665 #[cfg(feature = "blossom")] 666 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 667 #[non_exhaustive] 668 pub enum BlossomEvidenceState { 669 ConfiguredUnobserved, 670 DnsPolicyValidated, 671 TlsHttpObserved, 672 UploadVerified, 673 RetrievalVerified, 674 RetryableFailure, 675 TerminalFailure, 676 } 677 678 /// Versioned, passive, secret-safe evidence for one exact configuration. 679 #[cfg(feature = "blossom")] 680 #[derive(Clone, Debug, Eq, PartialEq)] 681 pub struct BlossomEndpointEvidence { 682 origin: String, 683 config_fingerprint: BlossomConfigFingerprint, 684 state: BlossomEvidenceState, 685 last_successful_state: BlossomEvidenceState, 686 transport_security: BlossomTransportSecurity, 687 observed_at_unix_ms: Option<u64>, 688 http_status: Option<u16>, 689 error_code: Option<&'static str>, 690 server_error_code: Option<String>, 691 error_phase: Option<BlossomPhase>, 692 retryable: bool, 693 possible_orphan: bool, 694 attempts: u8, 695 } 696 697 #[cfg(feature = "blossom")] 698 impl BlossomEndpointEvidence { 699 const SCHEMA_VERSION: u16 = 2; 700 701 fn configured(config: &BlossomConfig) -> Self { 702 let primary = config.profile().primary(); 703 Self { 704 origin: primary.origin().to_owned(), 705 config_fingerprint: config.fingerprint(), 706 state: BlossomEvidenceState::ConfiguredUnobserved, 707 last_successful_state: BlossomEvidenceState::ConfiguredUnobserved, 708 transport_security: match ( 709 primary.origin().starts_with("https://"), 710 primary.authority(), 711 ) { 712 (true, BlossomEndpointAuthority::PublicWebPki) => { 713 BlossomTransportSecurity::PublicWebPki 714 } 715 (true, _) => BlossomTransportSecurity::DevelopmentTls, 716 (false, _) => BlossomTransportSecurity::DevelopmentCleartext, 717 }, 718 observed_at_unix_ms: None, 719 http_status: None, 720 error_code: None, 721 server_error_code: None, 722 error_phase: None, 723 retryable: false, 724 possible_orphan: false, 725 attempts: 0, 726 } 727 } 728 729 #[must_use] 730 pub const fn schema_version(&self) -> u16 { 731 Self::SCHEMA_VERSION 732 } 733 734 #[must_use] 735 pub fn origin(&self) -> &str { 736 self.origin.as_str() 737 } 738 739 #[must_use] 740 pub const fn config_fingerprint(&self) -> BlossomConfigFingerprint { 741 self.config_fingerprint 742 } 743 744 #[must_use] 745 pub const fn state(&self) -> BlossomEvidenceState { 746 self.state 747 } 748 749 #[must_use] 750 pub const fn last_successful_state(&self) -> BlossomEvidenceState { 751 self.last_successful_state 752 } 753 754 #[must_use] 755 pub const fn transport_security(&self) -> BlossomTransportSecurity { 756 self.transport_security 757 } 758 759 #[must_use] 760 pub const fn observed_at_unix_ms(&self) -> Option<u64> { 761 self.observed_at_unix_ms 762 } 763 764 #[must_use] 765 pub const fn http_status(&self) -> Option<u16> { 766 self.http_status 767 } 768 769 #[must_use] 770 pub const fn error_code(&self) -> Option<&'static str> { 771 self.error_code 772 } 773 774 /// Bounded, validated public error identifier returned by the server. 775 #[must_use] 776 pub fn server_error_code(&self) -> Option<&str> { 777 self.server_error_code.as_deref() 778 } 779 780 #[must_use] 781 pub const fn error_phase(&self) -> Option<BlossomPhase> { 782 self.error_phase 783 } 784 785 #[must_use] 786 pub const fn retryable(&self) -> bool { 787 self.retryable 788 } 789 790 #[must_use] 791 pub const fn possible_orphan(&self) -> bool { 792 self.possible_orphan 793 } 794 795 #[must_use] 796 pub const fn attempts(&self) -> u8 { 797 self.attempts 798 } 799 800 fn record_success(&mut self, state: BlossomEvidenceState, http_status: Option<u16>) { 801 self.state = state; 802 self.last_successful_state = state; 803 self.observed_at_unix_ms = Some(blossom_now_unix_ms()); 804 self.http_status = http_status; 805 self.error_code = None; 806 self.server_error_code = None; 807 self.error_phase = None; 808 self.retryable = false; 809 self.possible_orphan = false; 810 self.attempts = 0; 811 } 812 813 fn record_failure(&mut self, error: &BlossomError) { 814 self.state = if error.retryable() { 815 BlossomEvidenceState::RetryableFailure 816 } else { 817 BlossomEvidenceState::TerminalFailure 818 }; 819 self.observed_at_unix_ms = Some(blossom_now_unix_ms()); 820 self.http_status = error.http_status(); 821 self.error_code = Some(error.code()); 822 self.server_error_code = error.server_error_code().map(str::to_owned); 823 self.error_phase = Some(error.phase()); 824 self.retryable = error.retryable(); 825 self.possible_orphan = error.possible_orphan(); 826 self.attempts = error.attempts(); 827 } 828 } 829 830 #[cfg(feature = "blossom")] 831 impl BlossomUploadTransaction { 832 /// Returns the frozen policy's minimum delay before another attempt. 833 /// Zero or exhausted completed-attempt counts admit no retry. This is a 834 /// pure policy query, not evidence of native inactivity, renewed signing 835 /// access, or absence of remote effects. The caller owns those prerequisites 836 /// and the durable attempt count; current slot configuration cannot change 837 /// this transaction's budget. 838 #[must_use] 839 pub fn retry_delay_after(&self, completed_attempts: u8) -> Option<Duration> { 840 (completed_attempts > 0 && completed_attempts < self.config.max_attempts()) 841 .then(|| self.config.retry_delay(completed_attempts)) 842 } 843 844 #[must_use] 845 pub const fn config_fingerprint(&self) -> BlossomConfigFingerprint { 846 self.config_fingerprint 847 } 848 849 #[must_use] 850 pub const fn expected_url(&self) -> &BlobUrl { 851 &self.expected_url 852 } 853 854 #[must_use] 855 pub const fn request(&self) -> &BlossomUploadRequest { 856 &self.request 857 } 858 859 pub(crate) const fn config(&self) -> &BlossomConfig { 860 &self.config 861 } 862 863 pub(crate) const fn endpoint(&self) -> &BlossomEndpoint { 864 &self.endpoint 865 } 866 867 pub(crate) fn into_request(self) -> BlossomUploadRequest { 868 self.request 869 } 870 } 871 872 #[cfg(feature = "blossom")] 873 impl std::fmt::Debug for BlossomUploadTransaction { 874 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 875 formatter 876 .debug_struct("BlossomUploadTransaction") 877 .field("config_fingerprint", &self.config_fingerprint) 878 .field("endpoint", &self.endpoint) 879 .field("expected_url", &self.expected_url) 880 .field("request", &self.request) 881 .finish() 882 } 883 } 884 885 #[cfg(feature = "blossom")] 886 impl std::fmt::Debug for BlossomUploadRequest { 887 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 888 formatter 889 .debug_struct("BlossomUploadRequest") 890 .field("sha256", &self.sha256()) 891 .field("byte_size", &self.byte_size()) 892 .field("media_type", &self.media_type) 893 .field("dimensions", &self.dimensions) 894 .field("bytes", &"<redacted>") 895 .finish() 896 } 897 } 898 899 /// Cooperative cancellation shared by upload, retry, and retrieval phases. 900 #[cfg(feature = "blossom")] 901 #[derive(Clone, Debug, Default)] 902 pub struct BlossomCancellation { 903 state: Arc<BlossomCancellationState>, 904 } 905 906 #[cfg(feature = "blossom")] 907 #[derive(Debug, Default)] 908 struct BlossomCancellationState { 909 cancelled: AtomicBool, 910 notify: tokio::sync::Notify, 911 } 912 913 #[cfg(feature = "blossom")] 914 impl BlossomCancellation { 915 pub fn cancel(&self) { 916 self.state.cancelled.store(true, Ordering::Release); 917 self.state.notify.notify_waiters(); 918 } 919 920 #[must_use] 921 pub fn is_cancelled(&self) -> bool { 922 self.state.cancelled.load(Ordering::Acquire) 923 } 924 925 pub(crate) async fn cancelled(&self) { 926 loop { 927 let notified = self.state.notify.notified(); 928 if self.is_cancelled() { 929 return; 930 } 931 notified.await; 932 } 933 } 934 } 935 936 /// Exact operation phase associated with one redacted Blossom failure. 937 #[cfg(feature = "blossom")] 938 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 939 #[non_exhaustive] 940 pub enum BlossomPhase { 941 Configuration, 942 Probe, 943 Authorization, 944 Upload, 945 Descriptor, 946 Retrieval, 947 Verification, 948 } 949 950 /// Stable, secret-safe Blossom failure classification. 951 #[cfg(feature = "blossom")] 952 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 953 #[non_exhaustive] 954 pub enum BlossomErrorKind { 955 InvalidEndpoint, 956 EndpointSchemeDenied, 957 InvalidEndpointCount, 958 DuplicateEndpoint, 959 EndpointNotConfigured, 960 ConfigurationChanged, 961 ResolutionFailed, 962 ResolvedAddressDenied, 963 InvalidLimits, 964 InvalidRequest, 965 InvalidDimensions, 966 UnsupportedMediaType, 967 MediaTypeMismatch, 968 InvalidImageBytes, 969 DimensionMismatch, 970 Authorization, 971 Transport, 972 Timeout, 973 Cancelled, 974 HttpStatus, 975 UnsafeRedirect, 976 RedirectLimit, 977 ContentEncodingDenied, 978 ResponseTooLarge, 979 ResponseSizeMismatch, 980 ResponseHashMismatch, 981 InvalidDescriptor, 982 DescriptorMismatch, 983 RetrievedBytesMismatch, 984 } 985 986 /// Redacted recoverable state for one Blossom operation failure. 987 #[cfg(feature = "blossom")] 988 #[derive(Clone, Eq, PartialEq)] 989 pub struct BlossomError { 990 kind: BlossomErrorKind, 991 phase: BlossomPhase, 992 retryable: bool, 993 possible_orphan: bool, 994 attempts: u8, 995 http_status: Option<u16>, 996 server_error_code: Option<String>, 997 } 998 999 #[cfg(feature = "blossom")] 1000 impl BlossomError { 1001 pub(crate) const fn new( 1002 kind: BlossomErrorKind, 1003 phase: BlossomPhase, 1004 retryable: bool, 1005 possible_orphan: bool, 1006 attempts: u8, 1007 ) -> Self { 1008 Self { 1009 kind, 1010 phase, 1011 retryable, 1012 possible_orphan, 1013 attempts, 1014 http_status: None, 1015 server_error_code: None, 1016 } 1017 } 1018 1019 const fn configuration(kind: BlossomErrorKind) -> Self { 1020 Self::new(kind, BlossomPhase::Configuration, false, false, 0) 1021 } 1022 1023 #[must_use] 1024 pub const fn kind(&self) -> BlossomErrorKind { 1025 self.kind 1026 } 1027 1028 #[must_use] 1029 pub const fn phase(&self) -> BlossomPhase { 1030 self.phase 1031 } 1032 1033 #[must_use] 1034 pub const fn retryable(&self) -> bool { 1035 self.retryable 1036 } 1037 1038 #[must_use] 1039 pub const fn possible_orphan(&self) -> bool { 1040 self.possible_orphan 1041 } 1042 1043 #[must_use] 1044 pub const fn attempts(&self) -> u8 { 1045 self.attempts 1046 } 1047 1048 #[must_use] 1049 pub const fn http_status(&self) -> Option<u16> { 1050 self.http_status 1051 } 1052 1053 /// Bounded, validated public error identifier returned by the server. 1054 #[must_use] 1055 pub fn server_error_code(&self) -> Option<&str> { 1056 self.server_error_code.as_deref() 1057 } 1058 1059 #[must_use] 1060 pub const fn code(&self) -> &'static str { 1061 match self.kind { 1062 BlossomErrorKind::InvalidEndpoint => "blossom_invalid_endpoint", 1063 BlossomErrorKind::EndpointSchemeDenied => "blossom_endpoint_scheme_denied", 1064 BlossomErrorKind::InvalidEndpointCount => "blossom_invalid_endpoint_count", 1065 BlossomErrorKind::DuplicateEndpoint => "blossom_duplicate_endpoint", 1066 BlossomErrorKind::EndpointNotConfigured => "blossom_endpoint_not_configured", 1067 BlossomErrorKind::ConfigurationChanged => "blossom_configuration_changed", 1068 BlossomErrorKind::ResolutionFailed => "blossom_resolution_failed", 1069 BlossomErrorKind::ResolvedAddressDenied => "blossom_resolved_address_denied", 1070 BlossomErrorKind::InvalidLimits => "blossom_invalid_limits", 1071 BlossomErrorKind::InvalidRequest => "blossom_invalid_request", 1072 BlossomErrorKind::InvalidDimensions => "blossom_invalid_dimensions", 1073 BlossomErrorKind::UnsupportedMediaType => "blossom_unsupported_media_type", 1074 BlossomErrorKind::MediaTypeMismatch => "blossom_media_type_mismatch", 1075 BlossomErrorKind::InvalidImageBytes => "blossom_invalid_image_bytes", 1076 BlossomErrorKind::DimensionMismatch => "blossom_dimension_mismatch", 1077 BlossomErrorKind::Authorization => "blossom_authorization_failed", 1078 BlossomErrorKind::Transport => "blossom_transport_failed", 1079 BlossomErrorKind::Timeout => "blossom_timeout", 1080 BlossomErrorKind::Cancelled => "blossom_cancelled", 1081 BlossomErrorKind::HttpStatus => "blossom_http_status", 1082 BlossomErrorKind::UnsafeRedirect => "blossom_unsafe_redirect", 1083 BlossomErrorKind::RedirectLimit => "blossom_redirect_limit", 1084 BlossomErrorKind::ContentEncodingDenied => "blossom_content_encoding_denied", 1085 BlossomErrorKind::ResponseTooLarge => "blossom_response_too_large", 1086 BlossomErrorKind::ResponseSizeMismatch => "blossom_response_size_mismatch", 1087 BlossomErrorKind::ResponseHashMismatch => "blossom_response_hash_mismatch", 1088 BlossomErrorKind::InvalidDescriptor => "blossom_invalid_descriptor", 1089 BlossomErrorKind::DescriptorMismatch => "blossom_descriptor_mismatch", 1090 BlossomErrorKind::RetrievedBytesMismatch => "blossom_retrieved_bytes_mismatch", 1091 } 1092 } 1093 1094 pub(crate) const fn with_operation(mut self, possible_orphan: bool, attempts: u8) -> Self { 1095 self.possible_orphan |= possible_orphan; 1096 self.attempts = attempts; 1097 self 1098 } 1099 1100 pub(crate) const fn with_http_status(mut self, status: u16) -> Self { 1101 self.http_status = Some(status); 1102 self 1103 } 1104 1105 pub(crate) fn with_server_error_code(mut self, code: String) -> Self { 1106 self.server_error_code = Some(code); 1107 self 1108 } 1109 } 1110 1111 #[cfg(feature = "blossom")] 1112 impl std::fmt::Display for BlossomError { 1113 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 1114 formatter.write_str(self.code()) 1115 } 1116 } 1117 1118 #[cfg(feature = "blossom")] 1119 impl std::fmt::Debug for BlossomError { 1120 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 1121 formatter 1122 .debug_struct("BlossomError") 1123 .field("kind", &self.kind) 1124 .field("phase", &self.phase) 1125 .field("retryable", &self.retryable) 1126 .field("possible_orphan", &self.possible_orphan) 1127 .field("attempts", &self.attempts) 1128 .field("http_status", &self.http_status) 1129 .field("server_error_code", &self.server_error_code) 1130 .finish() 1131 } 1132 } 1133 1134 #[cfg(feature = "blossom")] 1135 impl std::error::Error for BlossomError {} 1136 1137 /// Successful BUD-02 upload plus bounded BUD-01 retrieval verification. 1138 #[cfg(feature = "blossom")] 1139 #[derive(Clone, Debug, Eq, PartialEq)] 1140 pub struct BlossomUploadReceipt { 1141 descriptor: ByteVerifiedDescriptor, 1142 dimensions: BlossomImageDimensions, 1143 attempts: u8, 1144 verified_at_unix_ms: u64, 1145 } 1146 1147 /// Exact verified image bytes returned by a bounded BUD-01 retrieval. 1148 #[cfg(feature = "blossom")] 1149 #[derive(Clone)] 1150 pub struct BlossomInboundReceipt { 1151 final_url: BlobUrl, 1152 commitment: radroots_blossom::descriptor::ByteCommitment, 1153 dimensions: BlossomImageDimensions, 1154 bytes: Arc<[u8]>, 1155 config_fingerprint: BlossomConfigFingerprint, 1156 attempts: u8, 1157 verified_at_unix_ms: u64, 1158 } 1159 1160 #[cfg(feature = "blossom")] 1161 impl std::fmt::Debug for BlossomInboundReceipt { 1162 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 1163 formatter 1164 .debug_struct("BlossomInboundReceipt") 1165 .field("final_url", &self.final_url) 1166 .field("commitment", &self.commitment) 1167 .field("dimensions", &self.dimensions) 1168 .field("bytes", &"<redacted>") 1169 .field("config_fingerprint", &self.config_fingerprint) 1170 .field("attempts", &self.attempts) 1171 .field("verified_at_unix_ms", &self.verified_at_unix_ms) 1172 .finish() 1173 } 1174 } 1175 1176 #[cfg(feature = "blossom")] 1177 impl BlossomInboundReceipt { 1178 pub(crate) fn new( 1179 final_url: BlobUrl, 1180 commitment: radroots_blossom::descriptor::ByteCommitment, 1181 dimensions: BlossomImageDimensions, 1182 bytes: Arc<[u8]>, 1183 config_fingerprint: BlossomConfigFingerprint, 1184 attempts: u8, 1185 verified_at_unix_ms: u64, 1186 ) -> Self { 1187 Self { 1188 final_url, 1189 commitment, 1190 dimensions, 1191 bytes, 1192 config_fingerprint, 1193 attempts, 1194 verified_at_unix_ms, 1195 } 1196 } 1197 1198 #[must_use] 1199 pub const fn final_url(&self) -> &BlobUrl { 1200 &self.final_url 1201 } 1202 1203 #[must_use] 1204 pub const fn commitment(&self) -> &radroots_blossom::descriptor::ByteCommitment { 1205 &self.commitment 1206 } 1207 1208 #[must_use] 1209 pub const fn dimensions(&self) -> BlossomImageDimensions { 1210 self.dimensions 1211 } 1212 1213 #[must_use] 1214 pub fn bytes(&self) -> &[u8] { 1215 self.bytes.as_ref() 1216 } 1217 1218 #[must_use] 1219 pub const fn config_fingerprint(&self) -> BlossomConfigFingerprint { 1220 self.config_fingerprint 1221 } 1222 1223 #[must_use] 1224 pub const fn attempts(&self) -> u8 { 1225 self.attempts 1226 } 1227 1228 #[must_use] 1229 pub const fn verified_at_unix_ms(&self) -> u64 { 1230 self.verified_at_unix_ms 1231 } 1232 } 1233 1234 #[cfg(feature = "blossom")] 1235 impl BlossomUploadReceipt { 1236 pub(crate) const fn new( 1237 descriptor: ByteVerifiedDescriptor, 1238 dimensions: BlossomImageDimensions, 1239 attempts: u8, 1240 verified_at_unix_ms: u64, 1241 ) -> Self { 1242 Self { 1243 descriptor, 1244 dimensions, 1245 attempts, 1246 verified_at_unix_ms, 1247 } 1248 } 1249 1250 #[must_use] 1251 pub const fn descriptor(&self) -> &ByteVerifiedDescriptor { 1252 &self.descriptor 1253 } 1254 1255 #[must_use] 1256 pub const fn dimensions(&self) -> BlossomImageDimensions { 1257 self.dimensions 1258 } 1259 1260 #[must_use] 1261 pub const fn attempts(&self) -> u8 { 1262 self.attempts 1263 } 1264 1265 #[must_use] 1266 pub const fn verified_at_unix_ms(&self) -> u64 { 1267 self.verified_at_unix_ms 1268 } 1269 1270 #[must_use] 1271 pub fn into_descriptor(self) -> ByteVerifiedDescriptor { 1272 self.descriptor 1273 } 1274 } 1275 1276 /// Host-reconfigurable Blossom HTTP adapter slot. 1277 #[cfg(feature = "blossom")] 1278 #[derive(Clone, Default)] 1279 pub struct BlossomSlot { 1280 state: Arc<RwLock<BlossomSlotState>>, 1281 } 1282 1283 #[cfg(feature = "blossom")] 1284 #[derive(Default)] 1285 struct BlossomSlotState { 1286 config: Option<BlossomConfig>, 1287 evidence: Option<BlossomEndpointEvidence>, 1288 } 1289 1290 #[cfg(feature = "blossom")] 1291 impl BlossomSlot { 1292 #[must_use] 1293 pub fn new() -> Self { 1294 Self::default() 1295 } 1296 1297 /// Atomically installs completely validated inert configuration. 1298 pub fn configure(&self, config: BlossomConfig) -> Result<(), BlossomError> { 1299 let evidence = BlossomEndpointEvidence::configured(&config); 1300 let mut state = self 1301 .state 1302 .write() 1303 .map_err(|_| BlossomError::configuration(BlossomErrorKind::EndpointNotConfigured))?; 1304 state.config = Some(config); 1305 state.evidence = Some(evidence); 1306 Ok(()) 1307 } 1308 1309 pub fn clear(&self) { 1310 if let Ok(mut state) = self.state.write() { 1311 state.config = None; 1312 state.evidence = None; 1313 } 1314 } 1315 1316 #[must_use] 1317 pub fn host_kind(&self) -> Option<BlossomHostKind> { 1318 self.snapshot().map(|config| config.profile.host_kind()) 1319 } 1320 1321 #[must_use] 1322 pub fn endpoint_authority(&self) -> Option<BlossomEndpointAuthority> { 1323 self.snapshot().map(|config| config.profile.authority()) 1324 } 1325 1326 #[must_use] 1327 pub fn config_fingerprint(&self) -> Option<BlossomConfigFingerprint> { 1328 self.snapshot().map(|config| config.fingerprint()) 1329 } 1330 1331 /// Returns the configured inert profile without performing network I/O. 1332 #[must_use] 1333 pub fn profile(&self) -> Option<BlossomProfile> { 1334 self.snapshot().map(|config| config.profile) 1335 } 1336 1337 /// Atomically returns the inert profile and its exact configuration identity. 1338 #[must_use] 1339 pub fn configuration(&self) -> Option<(BlossomProfile, BlossomConfigFingerprint)> { 1340 self.snapshot().map(|config| { 1341 let fingerprint = config.fingerprint(); 1342 (config.profile, fingerprint) 1343 }) 1344 } 1345 1346 /// Returns the latest passive evidence without performing network I/O. 1347 #[must_use] 1348 pub fn evidence(&self) -> Option<BlossomEndpointEvidence> { 1349 self.state 1350 .read() 1351 .ok() 1352 .and_then(|state| state.evidence.clone()) 1353 } 1354 1355 /// Performs a bounded non-mutating primary-origin probe. 1356 pub async fn probe( 1357 &self, 1358 cancellation: BlossomCancellation, 1359 ) -> Result<BlossomEndpointEvidence, BlossomError> { 1360 let config = self 1361 .snapshot() 1362 .ok_or_else(|| BlossomError::configuration(BlossomErrorKind::EndpointNotConfigured))?; 1363 let fingerprint = config.fingerprint(); 1364 let result = crate::adapters::blossom::probe( 1365 config.clone(), 1366 config.profile().primary().clone(), 1367 cancellation, 1368 ) 1369 .await; 1370 match result { 1371 Ok(observation) => { 1372 self.record_evidence(fingerprint, BlossomPhase::Probe, false, |evidence| { 1373 evidence.record_success( 1374 BlossomEvidenceState::TlsHttpObserved, 1375 Some(observation.http_status), 1376 ); 1377 }) 1378 } 1379 Err(failure) => { 1380 self.record_evidence(fingerprint, BlossomPhase::Probe, false, |evidence| { 1381 if failure.dns_policy_validated { 1382 evidence.last_successful_state = BlossomEvidenceState::DnsPolicyValidated; 1383 } 1384 evidence.record_failure(&failure.error); 1385 })?; 1386 Err(failure.error) 1387 } 1388 } 1389 } 1390 1391 /// Binds verified bytes to the configured primary origin without network I/O. 1392 pub fn prepare_upload( 1393 &self, 1394 request: BlossomUploadRequest, 1395 ) -> Result<BlossomUploadTransaction, BlossomError> { 1396 let config = self 1397 .snapshot() 1398 .ok_or_else(|| BlossomError::configuration(BlossomErrorKind::EndpointNotConfigured))?; 1399 let config_fingerprint = config.fingerprint(); 1400 let endpoint = config.profile.primary.clone(); 1401 let extension = canonical_image_extension(request.media_type())?; 1402 let expected_url = BlobUrl::parse( 1403 format!("{}/{}.{}", endpoint.origin(), request.sha256(), extension).as_str(), 1404 ) 1405 .map_err(|_| BlossomError::configuration(BlossomErrorKind::InvalidEndpoint))?; 1406 Ok(BlossomUploadTransaction { 1407 config, 1408 config_fingerprint, 1409 endpoint, 1410 expected_url, 1411 request, 1412 }) 1413 } 1414 1415 /// Builds the exact BUD-11 claim for this configured upload destination. 1416 pub fn authored_upload_claim( 1417 &self, 1418 transaction: &BlossomUploadTransaction, 1419 content: AuthorizationContent, 1420 created_at_unix_s: u64, 1421 lifetime_seconds: u64, 1422 ) -> Result<AuthoredUploadClaim, BlossomError> { 1423 self.validate_transaction(transaction)?; 1424 AuthoredUploadClaim::new( 1425 content, 1426 transaction.endpoint.server_domain()?, 1427 transaction.request.sha256(), 1428 created_at_unix_s, 1429 lifetime_seconds, 1430 ) 1431 .map_err(|_| { 1432 BlossomError::new( 1433 BlossomErrorKind::Authorization, 1434 BlossomPhase::Authorization, 1435 false, 1436 false, 1437 0, 1438 ) 1439 }) 1440 } 1441 1442 /// Uploads exact bytes and verifies the returned descriptor and a full GET. 1443 pub async fn upload( 1444 &self, 1445 transaction: BlossomUploadTransaction, 1446 authorization: crate::signing::AuthorizationHeader, 1447 cancellation: BlossomCancellation, 1448 ) -> Result<BlossomUploadReceipt, BlossomError> { 1449 self.validate_transaction(&transaction)?; 1450 let fingerprint = transaction.config_fingerprint(); 1451 let result = 1452 crate::adapters::blossom::upload(transaction, authorization, cancellation).await; 1453 match result { 1454 Ok(receipt) => { 1455 self.record_evidence(fingerprint, BlossomPhase::Verification, true, |evidence| { 1456 evidence.record_success(BlossomEvidenceState::RetrievalVerified, None); 1457 })?; 1458 Ok(receipt) 1459 } 1460 Err(error) => { 1461 self.record_evidence(fingerprint, BlossomPhase::Verification, true, |evidence| { 1462 if error.possible_orphan() 1463 && matches!( 1464 error.phase(), 1465 BlossomPhase::Retrieval | BlossomPhase::Verification 1466 ) 1467 { 1468 evidence.last_successful_state = BlossomEvidenceState::UploadVerified; 1469 } 1470 evidence.record_failure(&error); 1471 })?; 1472 Err(error) 1473 } 1474 } 1475 } 1476 1477 /// Verifies a host-executed BUD-02 response, then performs the canonical 1478 /// BUD-01 exact-byte retrieval before returning an upload receipt. 1479 /// Later verification failure or cancellation preserves the native upload's 1480 /// possible remote effect and includes that upload in the attempt count. 1481 pub async fn complete_native_upload( 1482 &self, 1483 transaction: BlossomUploadTransaction, 1484 status_code: u16, 1485 response_media_type: Option<&str>, 1486 response_content_encoding: Option<&str>, 1487 response_body: &[u8], 1488 cancellation: BlossomCancellation, 1489 ) -> Result<BlossomUploadReceipt, BlossomError> { 1490 self.validate_transaction(&transaction)?; 1491 let fingerprint = transaction.config_fingerprint(); 1492 let result = crate::adapters::blossom::complete_native_upload( 1493 transaction, 1494 status_code, 1495 response_media_type, 1496 response_content_encoding, 1497 response_body, 1498 cancellation, 1499 ) 1500 .await; 1501 match result { 1502 Ok(receipt) => { 1503 self.record_evidence(fingerprint, BlossomPhase::Verification, true, |evidence| { 1504 evidence.record_success(BlossomEvidenceState::RetrievalVerified, None); 1505 })?; 1506 Ok(receipt) 1507 } 1508 Err(error) => { 1509 self.record_evidence(fingerprint, BlossomPhase::Verification, true, |evidence| { 1510 if error.possible_orphan() { 1511 evidence.last_successful_state = BlossomEvidenceState::UploadVerified; 1512 } 1513 evidence.record_failure(&error); 1514 })?; 1515 Err(error) 1516 } 1517 } 1518 } 1519 1520 /// Retrieves and verifies one immutable BUD-01 image under the exact 1521 /// configured DNS, TLS, redirect, retry, and byte limits. 1522 pub async fn retrieve( 1523 &self, 1524 request: BlossomInboundRequest, 1525 cancellation: BlossomCancellation, 1526 ) -> Result<BlossomInboundReceipt, BlossomError> { 1527 let config = self 1528 .snapshot() 1529 .ok_or_else(|| BlossomError::configuration(BlossomErrorKind::EndpointNotConfigured))?; 1530 let fingerprint = config.fingerprint(); 1531 if config.profile().endpoint_for_blob(request.url()).is_none() { 1532 return Err(BlossomError::configuration( 1533 BlossomErrorKind::EndpointNotConfigured, 1534 )); 1535 } 1536 let result = crate::adapters::blossom::retrieve(config, request, cancellation).await; 1537 match result { 1538 Ok(receipt) => { 1539 self.record_evidence(fingerprint, BlossomPhase::Verification, false, |evidence| { 1540 evidence.record_success(BlossomEvidenceState::RetrievalVerified, None); 1541 })?; 1542 Ok(receipt) 1543 } 1544 Err(error) => { 1545 self.record_evidence(fingerprint, BlossomPhase::Verification, false, |evidence| { 1546 evidence.record_failure(&error); 1547 })?; 1548 Err(error) 1549 } 1550 } 1551 } 1552 1553 fn validate_transaction( 1554 &self, 1555 transaction: &BlossomUploadTransaction, 1556 ) -> Result<(), BlossomError> { 1557 let fingerprint = self 1558 .config_fingerprint() 1559 .ok_or_else(|| BlossomError::configuration(BlossomErrorKind::EndpointNotConfigured))?; 1560 if fingerprint != transaction.config_fingerprint { 1561 return Err(BlossomError::configuration( 1562 BlossomErrorKind::ConfigurationChanged, 1563 )); 1564 } 1565 Ok(()) 1566 } 1567 1568 fn snapshot(&self) -> Option<BlossomConfig> { 1569 self.state 1570 .read() 1571 .ok() 1572 .and_then(|state| state.config.clone()) 1573 } 1574 1575 fn record_evidence( 1576 &self, 1577 fingerprint: BlossomConfigFingerprint, 1578 drift_phase: BlossomPhase, 1579 drift_possible_orphan: bool, 1580 update: impl FnOnce(&mut BlossomEndpointEvidence), 1581 ) -> Result<BlossomEndpointEvidence, BlossomError> { 1582 let mut state = self 1583 .state 1584 .write() 1585 .map_err(|_| BlossomError::configuration(BlossomErrorKind::EndpointNotConfigured))?; 1586 let current = state 1587 .config 1588 .as_ref() 1589 .ok_or_else(|| BlossomError::configuration(BlossomErrorKind::EndpointNotConfigured))?; 1590 if current.fingerprint() != fingerprint { 1591 return Err(BlossomError::new( 1592 BlossomErrorKind::ConfigurationChanged, 1593 drift_phase, 1594 false, 1595 drift_possible_orphan, 1596 0, 1597 )); 1598 } 1599 let evidence = state 1600 .evidence 1601 .as_mut() 1602 .ok_or_else(|| BlossomError::configuration(BlossomErrorKind::EndpointNotConfigured))?; 1603 update(evidence); 1604 Ok(evidence.clone()) 1605 } 1606 } 1607 1608 #[cfg(feature = "blossom")] 1609 impl std::fmt::Debug for BlossomSlot { 1610 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 1611 formatter 1612 .debug_struct("BlossomSlot") 1613 .field("configured", &self.host_kind().is_some()) 1614 .finish() 1615 } 1616 } 1617 1618 #[cfg(feature = "blossom")] 1619 fn endpoint_scheme_is_allowed(scheme: &str, authority: BlossomEndpointAuthority) -> bool { 1620 scheme == "https" 1621 || scheme == "http" 1622 && matches!( 1623 authority, 1624 BlossomEndpointAuthority::LoopbackDevelopment 1625 | BlossomEndpointAuthority::PrivateNetworkDevelopment 1626 ) 1627 } 1628 1629 #[cfg(feature = "blossom")] 1630 fn validate_host_authority( 1631 host_kind: BlossomHostKind, 1632 authority: BlossomEndpointAuthority, 1633 ) -> Result<(), BlossomError> { 1634 let accepted = match authority { 1635 BlossomEndpointAuthority::PublicWebPki => true, 1636 BlossomEndpointAuthority::LoopbackDevelopment => host_kind == BlossomHostKind::Simulator, 1637 BlossomEndpointAuthority::PrivateNetworkDevelopment => { 1638 host_kind == BlossomHostKind::PhysicalDevice 1639 } 1640 }; 1641 if accepted { 1642 Ok(()) 1643 } else { 1644 Err(BlossomError::configuration( 1645 BlossomErrorKind::InvalidEndpoint, 1646 )) 1647 } 1648 } 1649 1650 #[cfg(feature = "blossom")] 1651 fn validate_blossom_host( 1652 host: &str, 1653 authority: BlossomEndpointAuthority, 1654 ) -> Result<(), BlossomError> { 1655 let address = host.trim_matches(['[', ']']).parse::<IpAddr>().ok(); 1656 let accepted = match (authority, address) { 1657 (BlossomEndpointAuthority::PublicWebPki, Some(address)) => public_blossom_address(address), 1658 (BlossomEndpointAuthority::PublicWebPki, None) => public_blossom_hostname(host), 1659 (BlossomEndpointAuthority::LoopbackDevelopment, Some(address)) => address.is_loopback(), 1660 (BlossomEndpointAuthority::LoopbackDevelopment, None) => host == "localhost", 1661 (BlossomEndpointAuthority::PrivateNetworkDevelopment, Some(address)) => { 1662 trusted_blossom_address(address) 1663 } 1664 (BlossomEndpointAuthority::PrivateNetworkDevelopment, None) => false, 1665 }; 1666 if accepted { 1667 Ok(()) 1668 } else { 1669 Err(BlossomError::configuration( 1670 BlossomErrorKind::ResolvedAddressDenied, 1671 )) 1672 } 1673 } 1674 1675 #[cfg(feature = "blossom")] 1676 fn public_blossom_hostname(host: &str) -> bool { 1677 host.contains('.') 1678 && !host.ends_with(".localhost") 1679 && !host.ends_with(".local") 1680 && !host.ends_with(".home.arpa") 1681 } 1682 1683 #[cfg(feature = "blossom")] 1684 fn blossom_authority_accepts_address(authority: BlossomEndpointAuthority, address: IpAddr) -> bool { 1685 match authority { 1686 BlossomEndpointAuthority::PublicWebPki => public_blossom_address(address), 1687 BlossomEndpointAuthority::LoopbackDevelopment => address.is_loopback(), 1688 BlossomEndpointAuthority::PrivateNetworkDevelopment => trusted_blossom_address(address), 1689 } 1690 } 1691 1692 #[cfg(feature = "blossom")] 1693 pub(crate) fn canonical_image_extension( 1694 media_type: &MediaType, 1695 ) -> Result<&'static str, BlossomError> { 1696 match media_type.as_str() { 1697 "image/png" => Ok("png"), 1698 "image/jpeg" => Ok("jpg"), 1699 "image/gif" => Ok("gif"), 1700 "image/webp" => Ok("webp"), 1701 _ => Err(BlossomError::new( 1702 BlossomErrorKind::UnsupportedMediaType, 1703 BlossomPhase::Verification, 1704 false, 1705 false, 1706 0, 1707 )), 1708 } 1709 } 1710 1711 #[cfg(feature = "blossom")] 1712 fn public_blossom_address(address: IpAddr) -> bool { 1713 match address { 1714 IpAddr::V4(address) => public_blossom_ipv4(address), 1715 IpAddr::V6(address) => public_blossom_ipv6(address), 1716 } 1717 } 1718 1719 #[cfg(feature = "blossom")] 1720 fn trusted_blossom_address(address: IpAddr) -> bool { 1721 match address { 1722 IpAddr::V4(address) => address.is_private(), 1723 IpAddr::V6(address) => address.segments()[0] & 0xfe00 == 0xfc00, 1724 } 1725 } 1726 1727 #[cfg(feature = "blossom")] 1728 fn public_blossom_ipv4(address: Ipv4Addr) -> bool { 1729 let octets = address.octets(); 1730 !(octets[0] == 0 1731 || address.is_loopback() 1732 || address.is_private() 1733 || address.is_link_local() 1734 || address.is_multicast() 1735 || address.is_documentation() 1736 || octets[0] == 100 && (64..=127).contains(&octets[1]) 1737 || octets[0] == 192 && octets[1] == 0 && octets[2] == 0 1738 || octets[0] == 192 && octets[1] == 88 && octets[2] == 99 1739 || octets[0] == 198 && matches!(octets[1], 18 | 19) 1740 || octets[0] >= 240) 1741 } 1742 1743 #[cfg(feature = "blossom")] 1744 fn public_blossom_ipv6(address: Ipv6Addr) -> bool { 1745 if let Some(mapped) = address.to_ipv4_mapped() { 1746 return public_blossom_ipv4(mapped); 1747 } 1748 let segments = address.segments(); 1749 (segments[0] & 0xe000) == 0x2000 1750 && !(segments[0] == 0x2001 && segments[1] <= 0x01ff) 1751 && !(segments[0] == 0x2001 && segments[1] == 0x0db8) 1752 && segments[0] != 0x2002 1753 && !(segments[0] == 0x3fff && (segments[1] & 0xf000) == 0) 1754 } 1755 1756 /// A side-effect-free transport selection for a client operation. 1757 #[derive(Clone, Debug, Eq, PartialEq)] 1758 pub struct Profile { 1759 selection: Selection, 1760 } 1761 1762 #[derive(Clone, Debug, Eq, PartialEq)] 1763 enum Selection { 1764 LocalOnly, 1765 Delivery { 1766 targets: TargetSet, 1767 satisfaction: SatisfactionPolicy, 1768 }, 1769 UnavailablePreview { 1770 source: SourceStatus, 1771 sink: SinkStatus, 1772 }, 1773 } 1774 1775 impl Profile { 1776 /// Selects local persistence only, with no transport target or fallback. 1777 #[must_use] 1778 pub const fn local_only() -> Self { 1779 Self { 1780 selection: Selection::LocalOnly, 1781 } 1782 } 1783 1784 /// Selects an exact bounded target set and canonical satisfaction policy. 1785 /// 1786 /// Impossible quorum and required-target policies are rejected here by the 1787 /// owning transport contract. Construction performs no network operation. 1788 pub fn delivery(targets: TargetSet, satisfaction: SatisfactionPolicy) -> Result<Self, Error> { 1789 satisfaction.validate_for(&targets)?; 1790 Ok(Self { 1791 selection: Selection::Delivery { 1792 targets, 1793 satisfaction, 1794 }, 1795 }) 1796 } 1797 1798 /// Describes a preview transport that is intentionally not selectable. 1799 /// 1800 /// Both canonical capability directions remain explicitly unconfigured 1801 /// and unavailable. The profile has no targets and therefore cannot fall 1802 /// back to local, Nostr, daemon, or another transport. 1803 #[must_use] 1804 pub fn unavailable_preview(transport_id: TransportId) -> Self { 1805 Self { 1806 selection: Selection::UnavailablePreview { 1807 source: SourceStatus::new( 1808 transport_id, 1809 false, 1810 Maturity::Preview, 1811 Availability::Unavailable, 1812 SourceCapabilities::NONE, 1813 PREVIEW_UNAVAILABLE_MESSAGE, 1814 ), 1815 sink: SinkStatus::new( 1816 transport_id, 1817 false, 1818 Maturity::Preview, 1819 Availability::Unavailable, 1820 SinkCapabilities::NONE, 1821 PREVIEW_UNAVAILABLE_MESSAGE, 1822 ), 1823 }, 1824 } 1825 } 1826 1827 /// Returns whether this profile authorizes no transport operation. 1828 #[must_use] 1829 pub const fn is_local_only(&self) -> bool { 1830 matches!(self.selection, Selection::LocalOnly) 1831 } 1832 1833 /// Returns the exact selected targets, if delivery is authorized. 1834 #[must_use] 1835 pub const fn targets(&self) -> Option<&TargetSet> { 1836 match &self.selection { 1837 Selection::Delivery { targets, .. } => Some(targets), 1838 Selection::LocalOnly | Selection::UnavailablePreview { .. } => None, 1839 } 1840 } 1841 1842 /// Returns the exact selected satisfaction policy, if delivery is authorized. 1843 #[must_use] 1844 pub const fn satisfaction(&self) -> Option<&SatisfactionPolicy> { 1845 match &self.selection { 1846 Selection::Delivery { satisfaction, .. } => Some(satisfaction), 1847 Selection::LocalOnly | Selection::UnavailablePreview { .. } => None, 1848 } 1849 } 1850 1851 /// Returns canonical source status for an unavailable preview. 1852 #[must_use] 1853 pub const fn source_status(&self) -> Option<&SourceStatus> { 1854 match &self.selection { 1855 Selection::UnavailablePreview { source, .. } => Some(source), 1856 Selection::LocalOnly | Selection::Delivery { .. } => None, 1857 } 1858 } 1859 1860 /// Returns canonical sink status for an unavailable preview. 1861 #[must_use] 1862 pub const fn sink_status(&self) -> Option<&SinkStatus> { 1863 match &self.selection { 1864 Selection::UnavailablePreview { sink, .. } => Some(sink), 1865 Selection::LocalOnly | Selection::Delivery { .. } => None, 1866 } 1867 } 1868 } 1869 1870 impl Default for Profile { 1871 fn default() -> Self { 1872 Self::local_only() 1873 } 1874 } 1875 1876 /// Host-configured, client-shareable Nostr transport slot. 1877 /// 1878 /// Reconfiguration closes prior admission and retains already-started calls 1879 /// within a sixteen-relay aggregate budget. Construction and target inspection 1880 /// perform no network I/O; explicit cleanup awaits owned pool disposal. 1881 #[cfg(feature = "nostr")] 1882 #[derive(Clone)] 1883 pub struct NostrSlot { 1884 state: Arc<RwLock<NostrSlotState>>, 1885 transition: Arc<tokio::sync::Mutex<()>>, 1886 admission_closed: Arc<AtomicBool>, 1887 } 1888 1889 #[cfg(feature = "nostr")] 1890 const NOSTR_SESSION_RELAY_LIMIT: usize = 16; 1891 1892 #[cfg(feature = "nostr")] 1893 #[derive(Default)] 1894 struct NostrSlotState { 1895 current: Option<NostrState>, 1896 retired: Vec<NostrState>, 1897 } 1898 1899 #[cfg(feature = "nostr")] 1900 #[derive(Clone)] 1901 struct NostrState { 1902 transport: Arc<radroots_transport_nostr::NostrTransport>, 1903 read_targets: TargetSet, 1904 write_targets: Option<TargetSet>, 1905 } 1906 1907 #[cfg(feature = "nostr")] 1908 enum NostrSlotAccessError { 1909 Closed, 1910 Unavailable, 1911 } 1912 1913 #[cfg(feature = "nostr")] 1914 impl NostrSlotAccessError { 1915 fn transport_error(self) -> radroots_transport::Error { 1916 match self { 1917 Self::Closed => radroots_transport::Error::TransportClosed, 1918 Self::Unavailable => radroots_transport::Error::TransportUnavailable, 1919 } 1920 } 1921 1922 fn sink_failure( 1923 self, 1924 request: &radroots_transport::DeliveryRequest, 1925 ) -> radroots_transport::SinkFailure { 1926 match self { 1927 Self::Closed => radroots_transport::SinkFailure::transport_closed(request), 1928 Self::Unavailable => radroots_transport::SinkFailure::transport_unavailable(request), 1929 } 1930 } 1931 } 1932 1933 #[cfg(feature = "nostr")] 1934 impl NostrSlot { 1935 /// Creates an inert slot with no selected host profile. 1936 #[must_use] 1937 pub fn new() -> Self { 1938 Self { 1939 state: Arc::new(RwLock::new(NostrSlotState::default())), 1940 transition: Arc::new(tokio::sync::Mutex::new(())), 1941 admission_closed: Arc::new(AtomicBool::new(false)), 1942 } 1943 } 1944 1945 /// Validates a profile and installs it while preserving already-started prior calls. 1946 /// 1947 /// Idle prior pools are disposed before installation. Busy prior pools have 1948 /// closed admission and remain owned until later cleanup. Their last call 1949 /// disconnects registered relays without an extra result-losing await. 1950 /// The new and retained pools together may reserve at most sixteen relays. 1951 /// Interrupted or over-budget cleanup leaves prior admission closed for an 1952 /// explicit retry. Permanent shutdown always prevents a new installation. 1953 pub async fn configure(&self, profile: RelayProfile) -> crate::Result<()> { 1954 if self.admission_closed.load(Ordering::Acquire) { 1955 return Err(crate::Error::client_closed()); 1956 } 1957 let config = radroots_transport_nostr::Config::from_profile(profile); 1958 if config.endpoints().len() > NOSTR_SESSION_RELAY_LIMIT { 1959 return Err(crate::Error::invalid_host_configuration_without_source()); 1960 } 1961 let read_targets = TargetSet::new( 1962 config 1963 .read_relays() 1964 .map(radroots_transport_nostr::RelayUrl::to_target) 1965 .collect::<Result<Vec<_>, _>>() 1966 .map_err(crate::Error::invalid_host_configuration)?, 1967 ) 1968 .map_err(|_| crate::Error::invalid_host_configuration_without_source())?; 1969 let write_targets = { 1970 let targets = config 1971 .write_relays() 1972 .map(radroots_transport_nostr::RelayUrl::to_target) 1973 .collect::<Result<Vec<_>, _>>() 1974 .map_err(crate::Error::invalid_host_configuration)?; 1975 if targets.is_empty() { 1976 None 1977 } else { 1978 Some( 1979 TargetSet::new(targets) 1980 .map_err(|_| crate::Error::invalid_host_configuration_without_source())?, 1981 ) 1982 } 1983 }; 1984 let _transition = self.transition.lock().await; 1985 if self.admission_closed.load(Ordering::Acquire) { 1986 return Err(crate::Error::client_closed()); 1987 } 1988 self.cleanup_idle_retired().await?; 1989 let previous = { 1990 let mut state = self 1991 .state 1992 .write() 1993 .map_err(|_| crate::Error::shared_operation_unavailable())?; 1994 if let Some(previous) = &state.current { 1995 previous.transport.close_admission(); 1996 } 1997 let retained = state 1998 .retired 1999 .iter() 2000 .map(|previous| previous.transport.config().endpoints().len()) 2001 .sum::<usize>(); 2002 let busy = state 2003 .current 2004 .as_ref() 2005 .filter(|previous| previous.transport.has_in_flight_operations()) 2006 .map_or(0, |previous| previous.transport.config().endpoints().len()); 2007 if retained + busy + config.endpoints().len() > NOSTR_SESSION_RELAY_LIMIT { 2008 return Err(crate::Error::shared_operation_unavailable()); 2009 } 2010 if busy != 0 { 2011 if let Some(previous) = state.current.take() { 2012 state.retired.push(previous); 2013 } 2014 None 2015 } else { 2016 state.current.clone() 2017 } 2018 }; 2019 if let Some(previous) = previous { 2020 previous.transport.shutdown().await; 2021 } 2022 let mut current = self 2023 .state 2024 .write() 2025 .map_err(|_| crate::Error::shared_operation_unavailable())?; 2026 if self.admission_closed.load(Ordering::Acquire) { 2027 return Err(crate::Error::client_closed()); 2028 } 2029 current.current = Some(NostrState { 2030 transport: Arc::new(radroots_transport_nostr_native::create_transport(config)), 2031 read_targets, 2032 write_targets, 2033 }); 2034 Ok(()) 2035 } 2036 2037 async fn cleanup_idle_retired(&self) -> crate::Result<()> { 2038 loop { 2039 let idle = self 2040 .state 2041 .read() 2042 .map_err(|_| crate::Error::shared_operation_unavailable())? 2043 .retired 2044 .iter() 2045 .find(|previous| !previous.transport.has_in_flight_operations()) 2046 .map(|previous| Arc::clone(&previous.transport)); 2047 let Some(idle) = idle else { return Ok(()) }; 2048 idle.shutdown().await; 2049 let mut state = self 2050 .state 2051 .write() 2052 .map_err(|_| crate::Error::shared_operation_unavailable())?; 2053 if let Some(index) = state 2054 .retired 2055 .iter() 2056 .position(|previous| Arc::ptr_eq(&previous.transport, &idle)) 2057 { 2058 state.retired.remove(index); 2059 } 2060 } 2061 } 2062 2063 /// Shuts down the selected pool before removing its profile. 2064 /// 2065 /// Cancellation retains the selected pool so cleanup can be awaited again. 2066 pub async fn clear(&self) { 2067 let _transition = self.transition.lock().await; 2068 let pools = { 2069 let state = self 2070 .state 2071 .read() 2072 .unwrap_or_else(std::sync::PoisonError::into_inner); 2073 state 2074 .current 2075 .iter() 2076 .chain(state.retired.iter()) 2077 .map(|previous| Arc::clone(&previous.transport)) 2078 .collect::<Vec<_>>() 2079 }; 2080 for pool in &pools { 2081 pool.close_admission(); 2082 } 2083 for pool in pools { 2084 pool.shutdown().await; 2085 } 2086 // Poisoned state cannot authorize work, but its owned resources still 2087 // require disposal. Never reuse the recovered selection for admission. 2088 *self 2089 .state 2090 .write() 2091 .unwrap_or_else(std::sync::PoisonError::into_inner) = NostrSlotState::default(); 2092 } 2093 2094 /// Permanently closes admission and shuts down the selected pool across all clones. 2095 /// 2096 /// An unpolled future is inert. Re-await after interruption to finish 2097 /// disposal; no background cleanup task is detached. 2098 pub async fn shutdown(&self) { 2099 self.admission_closed.store(true, Ordering::Release); 2100 self.clear().await; 2101 } 2102 2103 /// Returns the currently selected canonical read targets. 2104 #[must_use] 2105 pub fn read_targets(&self) -> Option<TargetSet> { 2106 self.snapshot().map(|state| state.read_targets) 2107 } 2108 2109 /// Returns writable targets, or `None` when the profile is intentionally 2110 /// read-only. 2111 #[must_use] 2112 pub fn write_targets(&self) -> Option<TargetSet> { 2113 self.snapshot().and_then(|state| state.write_targets) 2114 } 2115 2116 /// Returns passive per-relay evidence without probing or opening sockets. 2117 #[must_use] 2118 pub fn relay_status(&self) -> Option<RelayStatusReport> { 2119 self.snapshot().map(|state| state.transport.relay_status()) 2120 } 2121 2122 fn snapshot(&self) -> Option<NostrState> { 2123 self.operation_snapshot().ok().flatten() 2124 } 2125 2126 #[cfg(test)] 2127 fn cleanup_snapshot(&self) -> Option<NostrState> { 2128 self.state 2129 .read() 2130 .unwrap_or_else(std::sync::PoisonError::into_inner) 2131 .current 2132 .clone() 2133 } 2134 2135 fn operation_snapshot(&self) -> Result<Option<NostrState>, NostrSlotAccessError> { 2136 if self.admission_closed.load(Ordering::Acquire) { 2137 return Err(NostrSlotAccessError::Closed); 2138 } 2139 let _transition = self 2140 .transition 2141 .try_lock() 2142 .map_err(|_| NostrSlotAccessError::Unavailable)?; 2143 if self.admission_closed.load(Ordering::Acquire) { 2144 return Err(NostrSlotAccessError::Closed); 2145 } 2146 let state = self 2147 .state 2148 .read() 2149 .map_err(|_| NostrSlotAccessError::Unavailable)?; 2150 if state.current.is_none() && !state.retired.is_empty() { 2151 return Err(NostrSlotAccessError::Unavailable); 2152 } 2153 let selected = state.current.clone(); 2154 if selected 2155 .as_ref() 2156 .is_some_and(|state| state.transport.admission_is_closed()) 2157 { 2158 Err(NostrSlotAccessError::Unavailable) 2159 } else { 2160 Ok(selected) 2161 } 2162 } 2163 2164 #[cfg(test)] 2165 pub(crate) async fn hold_transition_for_test(&self) -> tokio::sync::MutexGuard<'_, ()> { 2166 self.transition.lock().await 2167 } 2168 } 2169 2170 #[cfg(feature = "nostr")] 2171 impl radroots_transport::EventSource for NostrSlot { 2172 fn status( 2173 &self, 2174 ) -> radroots_transport::BoxFuture<'_, Result<SourceStatus, radroots_transport::Error>> { 2175 Box::pin(async move { 2176 match self 2177 .operation_snapshot() 2178 .map_err(NostrSlotAccessError::transport_error)? 2179 { 2180 Some(state) => { 2181 radroots_transport::EventSource::status(state.transport.as_ref()).await 2182 } 2183 None => Ok(SourceStatus::new( 2184 TransportId::NOSTR, 2185 false, 2186 Maturity::Stable, 2187 Availability::Unavailable, 2188 SourceCapabilities::FETCH, 2189 "Nostr transport is not configured", 2190 )), 2191 } 2192 }) 2193 } 2194 2195 fn fetch( 2196 &self, 2197 request: radroots_transport::FetchRequest, 2198 ) -> radroots_transport::BoxFuture< 2199 '_, 2200 Result<radroots_transport::FetchPage, radroots_transport::Error>, 2201 > { 2202 Box::pin(async move { 2203 let state = self 2204 .operation_snapshot() 2205 .map_err(NostrSlotAccessError::transport_error)? 2206 .ok_or(radroots_transport::Error::UnsupportedOperation)?; 2207 radroots_transport::EventSource::fetch(state.transport.as_ref(), request).await 2208 }) 2209 } 2210 } 2211 2212 #[cfg(feature = "nostr")] 2213 impl radroots_transport::EventSink for NostrSlot { 2214 fn status( 2215 &self, 2216 ) -> radroots_transport::BoxFuture<'_, Result<SinkStatus, radroots_transport::Error>> { 2217 Box::pin(async move { 2218 match self 2219 .operation_snapshot() 2220 .map_err(NostrSlotAccessError::transport_error)? 2221 { 2222 Some(state) => { 2223 radroots_transport::EventSink::status(state.transport.as_ref()).await 2224 } 2225 None => Ok(SinkStatus::new( 2226 TransportId::NOSTR, 2227 false, 2228 Maturity::Stable, 2229 Availability::Unavailable, 2230 SinkCapabilities::DELIVER, 2231 "Nostr transport is not configured", 2232 )), 2233 } 2234 }) 2235 } 2236 2237 fn deliver( 2238 &self, 2239 request: radroots_transport::DeliveryRequest, 2240 ) -> radroots_transport::BoxFuture< 2241 '_, 2242 Result<radroots_transport::DeliveryReceipt, radroots_transport::SinkFailure>, 2243 > { 2244 Box::pin(async move { 2245 let Some(state) = self 2246 .operation_snapshot() 2247 .map_err(|error| error.sink_failure(&request))? 2248 else { 2249 return Err(radroots_transport::SinkFailure::for_request( 2250 &request, 2251 "nostr_transport_not_configured", 2252 radroots_transport::outcome::Retryability::Terminal, 2253 None, 2254 None, 2255 Vec::new(), 2256 ) 2257 .expect("static unconfigured sink failure is valid")); 2258 }; 2259 radroots_transport::EventSink::deliver(state.transport.as_ref(), request).await 2260 }) 2261 } 2262 2263 fn deliver_selected( 2264 &self, 2265 request: radroots_transport::DeliveryRequest, 2266 selected: radroots_transport::TargetSet, 2267 ) -> radroots_transport::BoxFuture< 2268 '_, 2269 Result<radroots_transport::DeliveryReceipt, radroots_transport::SinkFailure>, 2270 > { 2271 Box::pin(async move { 2272 if request.validate_target_selection(&selected).is_err() { 2273 return Err(radroots_transport::SinkFailure::invalid_contract(&request)); 2274 } 2275 let Some(state) = self 2276 .operation_snapshot() 2277 .map_err(|error| error.sink_failure(&request))? 2278 else { 2279 return Err(radroots_transport::SinkFailure::for_request( 2280 &request, 2281 "nostr_transport_not_configured", 2282 radroots_transport::outcome::Retryability::Terminal, 2283 None, 2284 None, 2285 Vec::new(), 2286 ) 2287 .expect("static unconfigured sink failure is valid")); 2288 }; 2289 radroots_transport::EventSink::deliver_selected( 2290 state.transport.as_ref(), 2291 request, 2292 selected, 2293 ) 2294 .await 2295 }) 2296 } 2297 } 2298 2299 #[cfg(feature = "nostr")] 2300 impl std::fmt::Debug for NostrSlot { 2301 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 2302 formatter 2303 .debug_struct("NostrSlot") 2304 .field("configured", &self.read_targets().is_some()) 2305 .field("writable", &self.write_targets().is_some()) 2306 .finish() 2307 } 2308 } 2309 2310 #[cfg(feature = "nostr")] 2311 impl Default for NostrSlot { 2312 fn default() -> Self { 2313 Self::new() 2314 } 2315 } 2316 2317 /// Explicit daemon adapter authentication configuration. 2318 #[cfg(feature = "radrootsd")] 2319 #[derive(Clone, Eq, PartialEq)] 2320 #[non_exhaustive] 2321 pub enum DaemonAuth { 2322 /// Sends no authorization header. 2323 None, 2324 /// Sends the supplied bearer credential only when delivery is invoked. 2325 BearerToken(String), 2326 } 2327 2328 #[cfg(feature = "radrootsd")] 2329 impl std::fmt::Debug for DaemonAuth { 2330 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 2331 match self { 2332 Self::None => formatter.write_str("None"), 2333 Self::BearerToken(_) => formatter.write_str("BearerToken(<redacted>)"), 2334 } 2335 } 2336 } 2337 2338 /// Explicit daemon endpoint and request deadline configuration. 2339 #[cfg(feature = "radrootsd")] 2340 #[derive(Clone, Debug, Eq, PartialEq)] 2341 pub struct DaemonConfig { 2342 endpoint: String, 2343 auth: DaemonAuth, 2344 timeout: core::time::Duration, 2345 } 2346 2347 #[cfg(feature = "radrootsd")] 2348 impl DaemonConfig { 2349 /// Creates inert configuration; no client is built and no request is sent. 2350 #[must_use] 2351 pub fn new(endpoint: impl Into<String>) -> Self { 2352 Self { 2353 endpoint: endpoint.into(), 2354 auth: DaemonAuth::None, 2355 timeout: core::time::Duration::from_secs(10), 2356 } 2357 } 2358 2359 /// Selects explicit authentication for later invocation. 2360 #[must_use] 2361 pub fn with_auth(mut self, auth: DaemonAuth) -> Self { 2362 self.auth = auth; 2363 self 2364 } 2365 2366 /// Selects the complete HTTP/RPC request deadline. 2367 #[must_use] 2368 pub const fn with_timeout(mut self, timeout: core::time::Duration) -> Self { 2369 self.timeout = timeout; 2370 self 2371 } 2372 } 2373 2374 /// Stable secret-safe daemon execution failure class. 2375 #[cfg(feature = "radrootsd")] 2376 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 2377 #[non_exhaustive] 2378 pub enum DaemonErrorKind { 2379 /// The explicit authentication value cannot be represented safely. 2380 Authentication, 2381 /// The versioned protocol rejected the request. 2382 InvalidRequest, 2383 /// HTTP transport or timeout failed. 2384 Transport, 2385 /// The daemon returned a JSON-RPC error. 2386 Rpc, 2387 /// The response was malformed or did not match the request. 2388 InvalidResponse, 2389 } 2390 2391 /// One redacted daemon failure retaining a private source chain. 2392 #[cfg(feature = "radrootsd")] 2393 pub struct DaemonError { 2394 kind: DaemonErrorKind, 2395 source: crate::adapters::radrootsd::RadrootsdError, 2396 } 2397 2398 #[cfg(feature = "radrootsd")] 2399 impl DaemonError { 2400 /// Returns the stable failure class. 2401 #[must_use] 2402 pub const fn kind(&self) -> DaemonErrorKind { 2403 self.kind 2404 } 2405 2406 fn from_private(source: crate::adapters::radrootsd::RadrootsdError) -> Self { 2407 use crate::adapters::radrootsd::RadrootsdError; 2408 let kind = match &source { 2409 RadrootsdError::InvalidAuthHeader(_) => DaemonErrorKind::Authentication, 2410 RadrootsdError::InvalidRequest(_) => DaemonErrorKind::InvalidRequest, 2411 RadrootsdError::Http(_) => DaemonErrorKind::Transport, 2412 RadrootsdError::JsonRpc { .. } => DaemonErrorKind::Rpc, 2413 RadrootsdError::MalformedResponse(_) => DaemonErrorKind::InvalidResponse, 2414 }; 2415 Self { kind, source } 2416 } 2417 } 2418 2419 #[cfg(feature = "radrootsd")] 2420 impl std::fmt::Display for DaemonError { 2421 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 2422 formatter.write_str(match self.kind { 2423 DaemonErrorKind::Authentication => "daemon authentication configuration is invalid", 2424 DaemonErrorKind::InvalidRequest => "daemon delivery request is invalid", 2425 DaemonErrorKind::Transport => "daemon transport failed", 2426 DaemonErrorKind::Rpc => "daemon RPC failed", 2427 DaemonErrorKind::InvalidResponse => "daemon response is invalid", 2428 }) 2429 } 2430 } 2431 2432 #[cfg(feature = "radrootsd")] 2433 impl std::fmt::Debug for DaemonError { 2434 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 2435 formatter 2436 .debug_struct("DaemonError") 2437 .field("kind", &self.kind) 2438 .finish_non_exhaustive() 2439 } 2440 } 2441 2442 #[cfg(feature = "radrootsd")] 2443 impl std::error::Error for DaemonError { 2444 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { 2445 Some(&self.source) 2446 } 2447 } 2448 2449 /// Explicitly configured daemon execution adapter. 2450 /// 2451 /// Construction is inert. Network contact occurs only in [`Self::deliver`]. 2452 #[cfg(feature = "radrootsd")] 2453 #[derive(Clone, Debug, Eq, PartialEq)] 2454 pub struct DaemonDelivery { 2455 adapter: crate::adapters::radrootsd::RadrootsdPublishAdapter, 2456 } 2457 2458 #[cfg(feature = "radrootsd")] 2459 impl DaemonDelivery { 2460 /// Creates an inert adapter from explicit host configuration. 2461 #[must_use] 2462 pub fn new(config: DaemonConfig) -> Self { 2463 let auth = match config.auth { 2464 DaemonAuth::None => crate::adapters::radrootsd::RadrootsdAuth::None, 2465 DaemonAuth::BearerToken(token) => { 2466 crate::adapters::radrootsd::RadrootsdAuth::BearerToken(token) 2467 } 2468 }; 2469 Self { 2470 adapter: crate::adapters::radrootsd::RadrootsdPublishAdapter::new( 2471 crate::adapters::radrootsd::RadrootsdPublishConfig::new(config.endpoint) 2472 .with_auth(auth) 2473 .with_timeout(config.timeout), 2474 ), 2475 } 2476 } 2477 2478 /// Invokes the generation-5 daemon transport-publish contract. 2479 pub async fn deliver( 2480 &self, 2481 signed_event: radroots_event::SignedEvent, 2482 target_policy: radroots_protocol::radrootsd::transport_publish::v5::TargetPolicy, 2483 delivery_policy: radroots_protocol::radrootsd::transport_publish::v5::DeliveryPolicy, 2484 idempotency_key: Option<String>, 2485 timeout_ms: Option<u64>, 2486 ) -> Result<radroots_protocol::radrootsd::transport_publish::v5::EventResponse, DaemonError> 2487 { 2488 self.adapter 2489 .publish_signed_event(crate::adapters::radrootsd::RadrootsdPublishRequest { 2490 signed_event, 2491 target_policy, 2492 delivery_policy, 2493 idempotency_key, 2494 timeout_ms, 2495 }) 2496 .await 2497 .map_err(DaemonError::from_private) 2498 } 2499 } 2500 2501 #[cfg(all(test, feature = "nostr"))] 2502 #[path = "transport/nostr_retirement_tests.rs"] 2503 mod nostr_retirement_tests; 2504 2505 #[cfg(test)] 2506 mod tests { 2507 use radroots_transport::{ 2508 Error, TARGET_SET_MAX_ITEMS, Target, 2509 capability::{Availability, Maturity}, 2510 policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}, 2511 target::TargetFingerprint, 2512 }; 2513 2514 use super::*; 2515 2516 #[cfg(feature = "nostr")] 2517 fn ready<T>(future: impl std::future::Future<Output = T>) -> T { 2518 let mut future = std::pin::pin!(future); 2519 let mut context = std::task::Context::from_waker(std::task::Waker::noop()); 2520 match std::future::Future::poll(future.as_mut(), &mut context) { 2521 std::task::Poll::Ready(value) => value, 2522 std::task::Poll::Pending => panic!("inert configuration must need no executor or I/O"), 2523 } 2524 } 2525 2526 fn target(index: usize) -> Target { 2527 Target::nostr_relay(format!("wss://relay-{index}.example")).expect("target") 2528 } 2529 2530 #[cfg(feature = "nostr")] 2531 fn signed_event() -> radroots_event::SignedEvent { 2532 let raw = r#"{"id":"56bfc78223bb2221bad82b539efdec1ade0f56d0eb0e1f592fd387df4b2ceee0","pubkey":"585591529da0bab31b3b1b1f986611cf5f435dca84f978c89ee8a40cca7103df","created_at":1700000001,"kind":0,"tags":[],"content":"{}","sig":"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"}"#; 2533 let wire = radroots_event::wire::v1::Nip01EventWire::parse_json(raw).expect("wire event"); 2534 radroots_event::SignedEvent::from_wire_verified_id(wire, raw).expect("signed event") 2535 } 2536 2537 #[test] 2538 fn delivery_profile_preserves_canonical_targets_and_policy() { 2539 let targets = TargetSet::new(vec![target(1), target(2)]).expect("target set"); 2540 let policy = SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()); 2541 let profile = Profile::delivery(targets.clone(), policy.clone()).expect("profile"); 2542 2543 assert_eq!(profile.targets(), Some(&targets)); 2544 assert_eq!(profile.satisfaction(), Some(&policy)); 2545 assert!(!profile.is_local_only()); 2546 assert!(profile.source_status().is_none()); 2547 assert!(profile.sink_status().is_none()); 2548 } 2549 2550 #[test] 2551 fn canonical_target_and_policy_bounds_fail_during_profile_construction() { 2552 assert_eq!(TargetSet::new(Vec::new()), Err(Error::EmptyTargetSet)); 2553 assert_eq!( 2554 TargetSet::new((0..=TARGET_SET_MAX_ITEMS).map(target).collect()), 2555 Err(Error::TargetSetTooLarge) 2556 ); 2557 2558 let targets = TargetSet::new(vec![target(1)]).expect("target set"); 2559 let quorum = SatisfactionPolicy::new( 2560 SatisfactionClass::Delivered, 2561 TargetPolicy::quorum(2).expect("non-zero quorum"), 2562 ); 2563 assert_eq!( 2564 Profile::delivery(targets.clone(), quorum), 2565 Err(Error::InvalidSatisfactionPolicy) 2566 ); 2567 2568 let missing = 2569 TargetFingerprint::from_target(target(2).kind(), target(2).uri(), target(2).scope()); 2570 let required = SatisfactionPolicy::new( 2571 SatisfactionClass::Accepted, 2572 TargetPolicy::required(vec![missing]).expect("required policy"), 2573 ); 2574 assert_eq!( 2575 Profile::delivery(targets, required), 2576 Err(Error::RequiredTargetNotRequested) 2577 ); 2578 } 2579 2580 #[test] 2581 fn preview_transport_is_explicitly_unavailable_and_unselectable() { 2582 let profile = Profile::unavailable_preview(TransportId::RETICULUM); 2583 let source = profile.source_status().expect("source status"); 2584 let sink = profile.sink_status().expect("sink status"); 2585 2586 assert_eq!(source.transport_id(), TransportId::RETICULUM); 2587 assert_eq!(sink.transport_id(), TransportId::RETICULUM); 2588 assert!(!source.is_configured()); 2589 assert!(!sink.is_configured()); 2590 assert_eq!(source.maturity(), Maturity::Preview); 2591 assert_eq!(sink.maturity(), Maturity::Preview); 2592 assert_eq!(source.availability(), Availability::Unavailable); 2593 assert_eq!(sink.availability(), Availability::Unavailable); 2594 assert!(!source.capabilities().can_fetch()); 2595 assert!(!sink.capabilities().can_deliver()); 2596 assert!(profile.targets().is_none()); 2597 assert!(profile.satisfaction().is_none()); 2598 } 2599 2600 #[test] 2601 fn local_and_preview_profiles_never_substitute_fallback_targets() { 2602 let local = Profile::local_only(); 2603 let preview = Profile::unavailable_preview(TransportId::RETICULUM); 2604 assert!(local.is_local_only()); 2605 assert!(local.targets().is_none()); 2606 assert!(preview.targets().is_none()); 2607 2608 let selected = TargetSet::new(vec![target(7)]).expect("selected targets"); 2609 let profile = Profile::delivery( 2610 selected.clone(), 2611 SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::any()), 2612 ) 2613 .expect("profile"); 2614 assert_eq!(profile.targets(), Some(&selected)); 2615 assert!( 2616 profile 2617 .targets() 2618 .expect("targets") 2619 .targets() 2620 .iter() 2621 .all(|target| *target.kind() == TransportId::NOSTR) 2622 ); 2623 } 2624 2625 #[test] 2626 fn default_profile_is_local_only() { 2627 assert_eq!(Profile::default(), Profile::local_only()); 2628 } 2629 2630 #[cfg(feature = "blossom")] 2631 #[test] 2632 fn blossom_profiles_enforce_environment_and_ssrf_boundaries() { 2633 assert!(public_blossom_profile("https://media.example").is_ok()); 2634 assert!(public_blossom_profile("http://media.example").is_err()); 2635 assert!(public_blossom_profile("https://127.0.0.1").is_err()); 2636 assert!(public_blossom_profile("https://10.0.0.1").is_err()); 2637 assert!(simulator_blossom_profile("http://127.0.0.1:3000").is_ok()); 2638 assert!(simulator_blossom_profile("http://localhost:3000").is_ok()); 2639 assert!(simulator_blossom_profile("http://media.example").is_err()); 2640 assert!(device_blossom_profile("https://10.0.0.10:8443").is_ok()); 2641 assert!(device_blossom_profile("http://10.0.0.10:8443").is_ok()); 2642 assert!(device_blossom_profile("http://8.8.8.8:8443").is_err()); 2643 assert!(device_blossom_profile("https://device.example:8443").is_err()); 2644 assert!(device_blossom_profile("https://127.0.0.1:8443").is_err()); 2645 } 2646 2647 #[cfg(feature = "blossom")] 2648 #[test] 2649 fn blossom_configuration_is_bounded_and_debug_is_secret_safe() { 2650 let profile = simulator_blossom_profile("http://127.0.0.1:3000").unwrap(); 2651 assert!( 2652 BlossomConfig::from_profile(profile.clone()) 2653 .with_limits(0, 1, 0) 2654 .is_err() 2655 ); 2656 assert!( 2657 BlossomConfig::from_profile(profile.clone()) 2658 .with_network_policy( 2659 Duration::from_secs(1), 2660 Duration::from_secs(1), 2661 0, 2662 Duration::from_millis(1), 2663 ) 2664 .is_err() 2665 ); 2666 let slot = BlossomSlot::new(); 2667 slot.configure(BlossomConfig::from_profile(profile)) 2668 .unwrap(); 2669 assert_eq!(slot.host_kind(), Some(BlossomHostKind::Simulator)); 2670 assert_eq!( 2671 slot.endpoint_authority(), 2672 Some(BlossomEndpointAuthority::LoopbackDevelopment) 2673 ); 2674 assert_eq!(format!("{slot:?}"), "BlossomSlot { configured: true }"); 2675 } 2676 2677 #[cfg(feature = "blossom")] 2678 #[test] 2679 fn blossom_evidence_is_versioned_passive_and_preserves_last_success() { 2680 let slot = BlossomSlot::new(); 2681 assert!(slot.profile().is_none()); 2682 assert!(slot.configuration().is_none()); 2683 assert!(slot.evidence().is_none()); 2684 2685 let public_config = BlossomConfig::from_profile( 2686 public_blossom_profile("https://media.example").expect("public profile"), 2687 ); 2688 let public_fingerprint = public_config.fingerprint(); 2689 slot.configure(public_config).expect("public config"); 2690 let initial = slot.evidence().expect("initial evidence"); 2691 assert_eq!(initial.schema_version(), 2); 2692 assert_eq!(initial.origin(), "https://media.example"); 2693 assert_eq!(initial.config_fingerprint(), public_fingerprint); 2694 assert_eq!(initial.state(), BlossomEvidenceState::ConfiguredUnobserved); 2695 assert_eq!( 2696 initial.last_successful_state(), 2697 BlossomEvidenceState::ConfiguredUnobserved 2698 ); 2699 assert_eq!( 2700 initial.transport_security(), 2701 BlossomTransportSecurity::PublicWebPki 2702 ); 2703 assert_eq!(initial.observed_at_unix_ms(), None); 2704 assert_eq!(initial.http_status(), None); 2705 assert_eq!(initial.error_code(), None); 2706 assert_eq!(initial.error_phase(), None); 2707 assert!(!initial.retryable()); 2708 assert!(!initial.possible_orphan()); 2709 assert_eq!(initial.attempts(), 0); 2710 assert_eq!(public_fingerprint.to_hex(), public_fingerprint.to_string()); 2711 assert_eq!( 2712 slot.profile().expect("profile").primary().origin(), 2713 initial.origin() 2714 ); 2715 assert_eq!( 2716 slot.configuration().expect("configuration").1, 2717 public_fingerprint 2718 ); 2719 2720 let private_tls = BlossomConfig::from_profile( 2721 device_blossom_profile("https://10.0.0.10:8443").expect("device profile"), 2722 ); 2723 let mut evidence = BlossomEndpointEvidence::configured(&private_tls); 2724 assert_eq!( 2725 evidence.transport_security(), 2726 BlossomTransportSecurity::DevelopmentTls 2727 ); 2728 evidence.record_success(BlossomEvidenceState::UploadVerified, Some(201)); 2729 assert_eq!(evidence.state(), BlossomEvidenceState::UploadVerified); 2730 assert_eq!( 2731 evidence.last_successful_state(), 2732 BlossomEvidenceState::UploadVerified 2733 ); 2734 assert!(evidence.observed_at_unix_ms().is_some()); 2735 assert_eq!(evidence.http_status(), Some(201)); 2736 2737 let failure = BlossomError::new( 2738 BlossomErrorKind::HttpStatus, 2739 BlossomPhase::Retrieval, 2740 false, 2741 true, 2742 2, 2743 ) 2744 .with_http_status(403); 2745 evidence.record_failure(&failure); 2746 assert_eq!(evidence.state(), BlossomEvidenceState::TerminalFailure); 2747 assert_eq!( 2748 evidence.last_successful_state(), 2749 BlossomEvidenceState::UploadVerified 2750 ); 2751 assert_eq!(evidence.http_status(), Some(403)); 2752 assert_eq!(evidence.error_code(), Some("blossom_http_status")); 2753 assert_eq!(evidence.server_error_code(), None); 2754 assert_eq!(evidence.error_phase(), Some(BlossomPhase::Retrieval)); 2755 assert!(!evidence.retryable()); 2756 assert!(evidence.possible_orphan()); 2757 assert_eq!(evidence.attempts(), 2); 2758 2759 let cleartext = BlossomEndpointEvidence::configured(&BlossomConfig::from_profile( 2760 simulator_blossom_profile("http://127.0.0.1:3000").expect("simulator profile"), 2761 )); 2762 assert_eq!( 2763 cleartext.transport_security(), 2764 BlossomTransportSecurity::DevelopmentCleartext 2765 ); 2766 let device_cleartext = BlossomEndpointEvidence::configured(&BlossomConfig::from_profile( 2767 device_blossom_profile("http://10.0.0.10:3000").expect("device profile"), 2768 )); 2769 assert_eq!( 2770 device_cleartext.transport_security(), 2771 BlossomTransportSecurity::DevelopmentCleartext 2772 ); 2773 2774 slot.clear(); 2775 assert!(slot.evidence().is_none()); 2776 } 2777 2778 #[cfg(feature = "blossom")] 2779 fn blossom_png(width: u32, height: u32) -> Vec<u8> { 2780 let mut bytes = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); 2781 bytes.extend_from_slice(&width.to_be_bytes()); 2782 bytes.extend_from_slice(&height.to_be_bytes()); 2783 bytes 2784 } 2785 2786 #[cfg(feature = "blossom")] 2787 fn blossom_request(_origin: &str) -> BlossomUploadRequest { 2788 let bytes = blossom_png(2, 3); 2789 BlossomUploadRequest::new( 2790 Arc::from(bytes), 2791 MediaType::parse("image/png").expect("media type"), 2792 BlossomImageDimensions::new(2, 3).expect("dimensions"), 2793 1_900_000_000_000, 2794 ) 2795 .expect("request") 2796 } 2797 2798 #[cfg(feature = "blossom")] 2799 fn public_blossom_profile(origin: &str) -> Result<BlossomProfile, BlossomError> { 2800 BlossomProfile::new( 2801 BlossomHostKind::Native, 2802 BlossomEndpointAuthority::PublicWebPki, 2803 origin, 2804 std::iter::empty::<&str>(), 2805 ) 2806 } 2807 2808 #[cfg(feature = "blossom")] 2809 #[test] 2810 fn upload_retry_policy_is_bounded_and_frozen_in_the_transaction() { 2811 let profile = public_blossom_profile("https://media.example").unwrap(); 2812 for (maximum, initial_ms) in [(1, 250), (3, 250), (5, 20_000)] { 2813 let config = BlossomConfig::from_profile(profile.clone()) 2814 .with_network_policy( 2815 Duration::from_secs(10), 2816 Duration::from_secs(60), 2817 maximum, 2818 Duration::from_millis(initial_ms), 2819 ) 2820 .unwrap(); 2821 let slot = BlossomSlot::new(); 2822 slot.configure(config.clone()).unwrap(); 2823 let transaction = slot.prepare_upload(blossom_request("ignored")).unwrap(); 2824 for completed in 0..=u8::MAX { 2825 let expected = if completed > 0 && completed < maximum { 2826 Some(Duration::from_millis( 2827 (initial_ms * (1 << (completed - 1))).min(30_000), 2828 )) 2829 } else { 2830 None 2831 }; 2832 assert_eq!(transaction.retry_delay_after(completed), expected); 2833 } 2834 slot.configure( 2835 BlossomConfig::from_profile(profile.clone()) 2836 .with_network_policy( 2837 Duration::from_secs(10), 2838 Duration::from_secs(60), 2839 2, 2840 Duration::from_millis(7), 2841 ) 2842 .unwrap(), 2843 ) 2844 .unwrap(); 2845 let later = slot.prepare_upload(blossom_request("ignored")).unwrap(); 2846 assert_ne!(transaction.config_fingerprint(), later.config_fingerprint()); 2847 assert_eq!(later.retry_delay_after(1), Some(Duration::from_millis(7))); 2848 assert_eq!(later.retry_delay_after(2), None); 2849 assert_eq!(transaction.config_fingerprint(), config.fingerprint()); 2850 assert_eq!( 2851 transaction.retry_delay_after(1), 2852 (maximum > 1).then_some(Duration::from_millis(initial_ms)) 2853 ); 2854 assert_eq!(config.retry_delay(0), Duration::from_millis(initial_ms)); 2855 assert_eq!(config.retry_delay(u8::MAX), Duration::from_secs(30)); 2856 } 2857 } 2858 2859 #[cfg(feature = "blossom")] 2860 fn simulator_blossom_profile(origin: &str) -> Result<BlossomProfile, BlossomError> { 2861 BlossomProfile::new( 2862 BlossomHostKind::Simulator, 2863 BlossomEndpointAuthority::LoopbackDevelopment, 2864 origin, 2865 std::iter::empty::<&str>(), 2866 ) 2867 } 2868 2869 #[cfg(feature = "blossom")] 2870 fn device_blossom_profile(origin: &str) -> Result<BlossomProfile, BlossomError> { 2871 BlossomProfile::new( 2872 BlossomHostKind::PhysicalDevice, 2873 BlossomEndpointAuthority::PrivateNetworkDevelopment, 2874 origin, 2875 std::iter::empty::<&str>(), 2876 ) 2877 } 2878 2879 #[cfg(feature = "blossom")] 2880 #[test] 2881 fn blossom_profiles_expose_exact_identity_and_reject_malformed_sets() { 2882 let public = BlossomProfile::new( 2883 BlossomHostKind::PhysicalDevice, 2884 BlossomEndpointAuthority::PublicWebPki, 2885 "https://media.example:8443", 2886 ["https://fallback.example"], 2887 ) 2888 .expect("public"); 2889 assert_eq!(public.host_kind(), BlossomHostKind::PhysicalDevice); 2890 assert_eq!(public.authority(), BlossomEndpointAuthority::PublicWebPki); 2891 assert_eq!(public.fallbacks().len(), 1); 2892 let endpoint = public.primary(); 2893 assert_eq!(endpoint.origin(), "https://media.example:8443"); 2894 assert_eq!(endpoint.host(), "media.example"); 2895 assert_eq!(endpoint.port(), 8443); 2896 assert_eq!(endpoint.authority(), BlossomEndpointAuthority::PublicWebPki); 2897 2898 let request = blossom_request("https://media.example:8443"); 2899 let slot = BlossomSlot::new(); 2900 slot.configure(BlossomConfig::from_profile(public.clone())) 2901 .unwrap(); 2902 let transaction = slot.prepare_upload(request).unwrap(); 2903 assert!(endpoint.accepts_blob_url(transaction.expected_url())); 2904 assert_eq!( 2905 transaction 2906 .expected_url() 2907 .hash_path() 2908 .extension() 2909 .unwrap() 2910 .as_str(), 2911 "png" 2912 ); 2913 assert_eq!( 2914 transaction.expected_url().hash_path().hash(), 2915 transaction.request().sha256() 2916 ); 2917 assert_eq!(endpoint.upload_url(), "https://media.example:8443/upload"); 2918 assert_eq!(endpoint.server_domain().unwrap().as_str(), "media.example"); 2919 assert_eq!( 2920 public 2921 .endpoint_for_blob(transaction.expected_url()) 2922 .expect("configured endpoint"), 2923 endpoint 2924 ); 2925 2926 assert_eq!( 2927 BlossomProfile::new( 2928 BlossomHostKind::PhysicalDevice, 2929 BlossomEndpointAuthority::PrivateNetworkDevelopment, 2930 "https://10.0.0.10", 2931 std::iter::empty::<&str>(), 2932 ) 2933 .unwrap() 2934 .host_kind(), 2935 BlossomHostKind::PhysicalDevice 2936 ); 2937 assert_eq!( 2938 simulator_blossom_profile("http://localhost:3000") 2939 .unwrap() 2940 .host_kind(), 2941 BlossomHostKind::Simulator 2942 ); 2943 assert_eq!( 2944 BlossomProfile::new( 2945 BlossomHostKind::Native, 2946 BlossomEndpointAuthority::PublicWebPki, 2947 "", 2948 std::iter::empty::<&str>(), 2949 ) 2950 .expect_err("empty profile") 2951 .kind(), 2952 BlossomErrorKind::InvalidEndpoint 2953 ); 2954 assert_eq!( 2955 BlossomProfile::new( 2956 BlossomHostKind::Native, 2957 BlossomEndpointAuthority::PublicWebPki, 2958 "https://primary.example", 2959 std::iter::repeat_n("https://media.example", 16), 2960 ) 2961 .expect_err("bounded profile") 2962 .kind(), 2963 BlossomErrorKind::InvalidEndpointCount 2964 ); 2965 assert_eq!( 2966 BlossomProfile::new( 2967 BlossomHostKind::Native, 2968 BlossomEndpointAuthority::PublicWebPki, 2969 "https://media.example", 2970 ["https://media.example"], 2971 ) 2972 .expect_err("duplicate profile") 2973 .kind(), 2974 BlossomErrorKind::DuplicateEndpoint 2975 ); 2976 2977 for malformed in [ 2978 "", 2979 " https://media.example", 2980 "https://média.example", 2981 "https://user@media.example", 2982 "https://:password@media.example", 2983 "https://media.example/path", 2984 "https://media.example?query=1", 2985 "https://media.example#fragment", 2986 "ftp://media.example", 2987 "https://media.example:0", 2988 ] { 2989 assert!(public_blossom_profile(malformed).is_err(), "{malformed}"); 2990 } 2991 } 2992 2993 #[cfg(feature = "blossom")] 2994 #[test] 2995 fn blossom_upload_transactions_bind_primary_authority_and_complete_config() { 2996 let profile = BlossomProfile::new( 2997 BlossomHostKind::PhysicalDevice, 2998 BlossomEndpointAuthority::PublicWebPki, 2999 "https://media.example:443", 3000 ["https://fallback.example"], 3001 ) 3002 .unwrap(); 3003 assert_eq!(profile.primary().origin(), "https://media.example"); 3004 assert!( 3005 profile 3006 .primary() 3007 .validate_resolved_addresses([IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))]) 3008 .is_err() 3009 ); 3010 3011 let slot = BlossomSlot::new(); 3012 let original = BlossomConfig::from_profile(profile); 3013 let original_fingerprint = original.fingerprint(); 3014 slot.configure(original).unwrap(); 3015 let transaction = slot 3016 .prepare_upload(blossom_request("caller-origin-is-ignored")) 3017 .unwrap(); 3018 assert_eq!(transaction.config_fingerprint(), original_fingerprint); 3019 assert!( 3020 transaction 3021 .expected_url() 3022 .as_str() 3023 .starts_with("https://media.example/") 3024 ); 3025 let claim = slot 3026 .authored_upload_claim( 3027 &transaction, 3028 AuthorizationContent::parse("Upload farm image").unwrap(), 3029 100, 3030 60, 3031 ) 3032 .unwrap(); 3033 assert_eq!(claim.server_domain().as_str(), "media.example"); 3034 3035 let changed = BlossomConfig::from_profile( 3036 BlossomProfile::new( 3037 BlossomHostKind::PhysicalDevice, 3038 BlossomEndpointAuthority::PublicWebPki, 3039 "https://other.example", 3040 ["https://fallback.example"], 3041 ) 3042 .unwrap(), 3043 ); 3044 assert_ne!(changed.fingerprint(), original_fingerprint); 3045 slot.configure(changed).unwrap(); 3046 assert_eq!( 3047 slot.authored_upload_claim( 3048 &transaction, 3049 AuthorizationContent::parse("Upload farm image").unwrap(), 3050 100, 3051 60, 3052 ) 3053 .expect_err("changed configuration"), 3054 BlossomError::configuration(BlossomErrorKind::ConfigurationChanged) 3055 ); 3056 assert_eq!( 3057 slot.validate_transaction(&transaction) 3058 .expect_err("changed upload destination") 3059 .kind(), 3060 BlossomErrorKind::ConfigurationChanged 3061 ); 3062 } 3063 3064 #[cfg(feature = "blossom")] 3065 #[test] 3066 fn blossom_limits_requests_and_errors_cover_the_complete_public_contract() { 3067 let profile = simulator_blossom_profile("http://127.0.0.1:3000").unwrap(); 3068 let valid = BlossomConfig::from_profile(profile.clone()) 3069 .with_limits(1, 1, 5) 3070 .unwrap() 3071 .with_network_policy( 3072 Duration::from_millis(1), 3073 Duration::from_millis(2), 3074 5, 3075 Duration::from_millis(3), 3076 ) 3077 .unwrap(); 3078 assert_eq!(valid.profile(), &profile); 3079 assert_eq!(valid.max_blob_bytes(), 1); 3080 assert_eq!(valid.max_descriptor_bytes(), 1); 3081 assert_eq!(valid.max_redirects(), 5); 3082 assert_eq!(valid.max_attempts(), 5); 3083 assert_eq!(valid.connect_timeout(), Duration::from_millis(1)); 3084 assert_eq!(valid.request_timeout(), Duration::from_millis(2)); 3085 assert_eq!(valid.initial_retry_delay(), Duration::from_millis(3)); 3086 3087 for (blob, descriptor, redirects) in [ 3088 (0, 1, 0), 3089 (MAX_BLOSSOM_BLOB_BYTES + 1, 1, 0), 3090 (1, 0, 0), 3091 (1, MAX_BLOSSOM_DESCRIPTOR_BYTES + 1, 0), 3092 (1, 1, MAX_BLOSSOM_REDIRECTS + 1), 3093 ] { 3094 assert!( 3095 BlossomConfig::from_profile(profile.clone()) 3096 .with_limits(blob, descriptor, redirects) 3097 .is_err() 3098 ); 3099 } 3100 for (connect, request, attempts, delay) in [ 3101 ( 3102 Duration::ZERO, 3103 Duration::from_secs(1), 3104 1, 3105 Duration::from_millis(1), 3106 ), 3107 ( 3108 MAX_BLOSSOM_TIMEOUT + Duration::from_secs(1), 3109 Duration::from_secs(1), 3110 1, 3111 Duration::from_millis(1), 3112 ), 3113 ( 3114 Duration::from_secs(1), 3115 Duration::ZERO, 3116 1, 3117 Duration::from_millis(1), 3118 ), 3119 ( 3120 Duration::from_secs(1), 3121 MAX_BLOSSOM_TIMEOUT + Duration::from_secs(1), 3122 1, 3123 Duration::from_millis(1), 3124 ), 3125 ( 3126 Duration::from_secs(1), 3127 Duration::from_secs(1), 3128 0, 3129 Duration::from_millis(1), 3130 ), 3131 ( 3132 Duration::from_secs(1), 3133 Duration::from_secs(1), 3134 MAX_BLOSSOM_ATTEMPTS + 1, 3135 Duration::from_millis(1), 3136 ), 3137 ( 3138 Duration::from_secs(1), 3139 Duration::from_secs(1), 3140 1, 3141 Duration::ZERO, 3142 ), 3143 ( 3144 Duration::from_secs(1), 3145 Duration::from_secs(1), 3146 1, 3147 MAX_BLOSSOM_RETRY_DELAY + Duration::from_secs(1), 3148 ), 3149 ] { 3150 assert!( 3151 BlossomConfig::from_profile(profile.clone()) 3152 .with_network_policy(connect, request, attempts, delay) 3153 .is_err() 3154 ); 3155 } 3156 3157 assert!(BlossomImageDimensions::new(0, 1).is_err()); 3158 assert!(BlossomImageDimensions::new(1, 0).is_err()); 3159 assert!(BlossomImageDimensions::new(16_385, 1).is_err()); 3160 assert!(BlossomImageDimensions::new(10_001, 10_000).is_err()); 3161 let dimensions = BlossomImageDimensions::new(2, 3).unwrap(); 3162 assert_eq!(dimensions.width(), 2); 3163 assert_eq!(dimensions.height(), 3); 3164 3165 let request = blossom_request("http://127.0.0.1:3000"); 3166 assert_eq!(request.media_type().as_str(), "image/png"); 3167 assert_eq!(request.dimensions(), dimensions); 3168 assert_eq!(request.byte_size(), request.bytes().len() as u64); 3169 assert_eq!(request.sha256(), Sha256::digest(request.bytes())); 3170 assert_eq!(request.verified_at_unix_ms(), 1_900_000_000_000); 3171 assert!(format!("{request:?}").contains("bytes: \"<redacted>\"")); 3172 3173 let media_type = MediaType::parse("image/png").unwrap(); 3174 assert!( 3175 BlossomUploadRequest::new(Arc::from([]), media_type.clone(), dimensions, 1,).is_err() 3176 ); 3177 let bytes = blossom_png(2, 3); 3178 assert!( 3179 BlossomUploadRequest::new( 3180 Arc::from(bytes.clone()), 3181 MediaType::parse("image/jpeg").unwrap(), 3182 dimensions, 3183 1, 3184 ) 3185 .is_err() 3186 ); 3187 assert!(BlossomUploadRequest::new(Arc::from(bytes), media_type, dimensions, 0).is_err()); 3188 3189 let all_kinds = [ 3190 ( 3191 BlossomErrorKind::InvalidEndpoint, 3192 "blossom_invalid_endpoint", 3193 ), 3194 ( 3195 BlossomErrorKind::EndpointSchemeDenied, 3196 "blossom_endpoint_scheme_denied", 3197 ), 3198 ( 3199 BlossomErrorKind::InvalidEndpointCount, 3200 "blossom_invalid_endpoint_count", 3201 ), 3202 ( 3203 BlossomErrorKind::DuplicateEndpoint, 3204 "blossom_duplicate_endpoint", 3205 ), 3206 ( 3207 BlossomErrorKind::EndpointNotConfigured, 3208 "blossom_endpoint_not_configured", 3209 ), 3210 ( 3211 BlossomErrorKind::ConfigurationChanged, 3212 "blossom_configuration_changed", 3213 ), 3214 ( 3215 BlossomErrorKind::ResolutionFailed, 3216 "blossom_resolution_failed", 3217 ), 3218 ( 3219 BlossomErrorKind::ResolvedAddressDenied, 3220 "blossom_resolved_address_denied", 3221 ), 3222 (BlossomErrorKind::InvalidLimits, "blossom_invalid_limits"), 3223 (BlossomErrorKind::InvalidRequest, "blossom_invalid_request"), 3224 ( 3225 BlossomErrorKind::InvalidDimensions, 3226 "blossom_invalid_dimensions", 3227 ), 3228 ( 3229 BlossomErrorKind::UnsupportedMediaType, 3230 "blossom_unsupported_media_type", 3231 ), 3232 ( 3233 BlossomErrorKind::MediaTypeMismatch, 3234 "blossom_media_type_mismatch", 3235 ), 3236 ( 3237 BlossomErrorKind::InvalidImageBytes, 3238 "blossom_invalid_image_bytes", 3239 ), 3240 ( 3241 BlossomErrorKind::DimensionMismatch, 3242 "blossom_dimension_mismatch", 3243 ), 3244 ( 3245 BlossomErrorKind::Authorization, 3246 "blossom_authorization_failed", 3247 ), 3248 (BlossomErrorKind::Transport, "blossom_transport_failed"), 3249 (BlossomErrorKind::Timeout, "blossom_timeout"), 3250 (BlossomErrorKind::Cancelled, "blossom_cancelled"), 3251 (BlossomErrorKind::HttpStatus, "blossom_http_status"), 3252 (BlossomErrorKind::UnsafeRedirect, "blossom_unsafe_redirect"), 3253 (BlossomErrorKind::RedirectLimit, "blossom_redirect_limit"), 3254 ( 3255 BlossomErrorKind::ContentEncodingDenied, 3256 "blossom_content_encoding_denied", 3257 ), 3258 ( 3259 BlossomErrorKind::ResponseTooLarge, 3260 "blossom_response_too_large", 3261 ), 3262 ( 3263 BlossomErrorKind::ResponseSizeMismatch, 3264 "blossom_response_size_mismatch", 3265 ), 3266 ( 3267 BlossomErrorKind::ResponseHashMismatch, 3268 "blossom_response_hash_mismatch", 3269 ), 3270 ( 3271 BlossomErrorKind::InvalidDescriptor, 3272 "blossom_invalid_descriptor", 3273 ), 3274 ( 3275 BlossomErrorKind::DescriptorMismatch, 3276 "blossom_descriptor_mismatch", 3277 ), 3278 ( 3279 BlossomErrorKind::RetrievedBytesMismatch, 3280 "blossom_retrieved_bytes_mismatch", 3281 ), 3282 ]; 3283 for (kind, code) in all_kinds { 3284 let error = BlossomError::new(kind, BlossomPhase::Verification, true, false, 2); 3285 assert_eq!(error.kind(), kind); 3286 assert_eq!(error.phase(), BlossomPhase::Verification); 3287 assert!(error.retryable()); 3288 assert!(!error.possible_orphan()); 3289 assert_eq!(error.attempts(), 2); 3290 assert_eq!(error.code(), code); 3291 assert_eq!(error.to_string(), code); 3292 assert!( 3293 format!("{error:?}").contains(code.trim_start_matches("blossom_")) 3294 || !code.is_empty() 3295 ); 3296 let updated = error.with_operation(true, 3); 3297 assert!(updated.possible_orphan()); 3298 assert_eq!(updated.attempts(), 3); 3299 } 3300 } 3301 3302 #[cfg(feature = "blossom")] 3303 #[test] 3304 fn blossom_address_policy_covers_public_simulator_and_device_networks() { 3305 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 3306 3307 let public_v4 = [ 3308 (Ipv4Addr::new(8, 8, 8, 8), true), 3309 (Ipv4Addr::new(0, 1, 2, 3), false), 3310 (Ipv4Addr::LOCALHOST, false), 3311 (Ipv4Addr::new(10, 0, 0, 1), false), 3312 (Ipv4Addr::new(169, 254, 1, 1), false), 3313 (Ipv4Addr::new(224, 0, 0, 1), false), 3314 (Ipv4Addr::new(192, 0, 2, 1), false), 3315 (Ipv4Addr::new(100, 64, 0, 1), false), 3316 (Ipv4Addr::new(100, 128, 0, 1), true), 3317 (Ipv4Addr::new(192, 0, 0, 1), false), 3318 (Ipv4Addr::new(192, 0, 1, 1), true), 3319 (Ipv4Addr::new(192, 88, 99, 1), false), 3320 (Ipv4Addr::new(192, 88, 98, 1), true), 3321 (Ipv4Addr::new(198, 18, 0, 1), false), 3322 (Ipv4Addr::new(240, 0, 0, 1), false), 3323 ]; 3324 for (address, accepted) in public_v4 { 3325 assert_eq!(public_blossom_ipv4(address), accepted, "{address}"); 3326 assert_eq!(public_blossom_address(IpAddr::V4(address)), accepted); 3327 } 3328 let public_v6 = [ 3329 ("2606:4700:4700::1111", true), 3330 ("::ffff:8.8.8.8", true), 3331 ("::ffff:127.0.0.1", false), 3332 ("2001:100::1", false), 3333 ("2001:db8::1", false), 3334 ("2002::1", false), 3335 ("3fff::1", false), 3336 ("4000::1", false), 3337 ("2001:db9::1", true), 3338 ]; 3339 for (text, accepted) in public_v6 { 3340 let address = text.parse::<Ipv6Addr>().unwrap(); 3341 assert_eq!(public_blossom_ipv6(address), accepted, "{text}"); 3342 assert_eq!(public_blossom_address(IpAddr::V6(address)), accepted); 3343 } 3344 3345 for (host, accepted) in [ 3346 ("media.example", true), 3347 ("localhost", false), 3348 ("farm.localhost", false), 3349 ("farm.local", false), 3350 ("farm.home.arpa", false), 3351 ("intranet", false), 3352 ] { 3353 assert_eq!(public_blossom_hostname(host), accepted, "{host}"); 3354 } 3355 3356 let simulator = simulator_blossom_profile("http://127.0.0.1:3000").unwrap(); 3357 let simulator_endpoint = simulator.primary(); 3358 assert!( 3359 simulator_endpoint 3360 .validate_resolved_addresses([IpAddr::V4(Ipv4Addr::LOCALHOST)]) 3361 .is_ok() 3362 ); 3363 assert!(simulator_endpoint.validate_resolved_addresses([]).is_err()); 3364 assert!( 3365 simulator_endpoint 3366 .validate_resolved_addresses([IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))]) 3367 .is_err() 3368 ); 3369 3370 let public = public_blossom_profile("https://media.example").unwrap(); 3371 assert!( 3372 public 3373 .primary() 3374 .validate_resolved_addresses([IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))]) 3375 .is_ok() 3376 ); 3377 let device = device_blossom_profile("https://10.0.0.10").unwrap(); 3378 assert!( 3379 device 3380 .primary() 3381 .validate_resolved_addresses([IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))]) 3382 .is_ok() 3383 ); 3384 3385 for address in [ 3386 IpAddr::V4(Ipv4Addr::UNSPECIFIED), 3387 IpAddr::V4(Ipv4Addr::LOCALHOST), 3388 IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1)), 3389 IpAddr::V4(Ipv4Addr::BROADCAST), 3390 IpAddr::V6(Ipv6Addr::UNSPECIFIED), 3391 IpAddr::V6(Ipv6Addr::LOCALHOST), 3392 IpAddr::V6("ff02::1".parse().unwrap()), 3393 ] { 3394 assert!(!trusted_blossom_address(address), "{address}"); 3395 } 3396 assert!(trusted_blossom_address(IpAddr::V4(Ipv4Addr::new( 3397 10, 0, 0, 1 3398 )))); 3399 assert!(trusted_blossom_address(IpAddr::V6( 3400 "fd00::1".parse().unwrap() 3401 ))); 3402 assert!(blossom_authority_accepts_address( 3403 BlossomEndpointAuthority::PublicWebPki, 3404 IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)) 3405 )); 3406 assert!(blossom_authority_accepts_address( 3407 BlossomEndpointAuthority::LoopbackDevelopment, 3408 IpAddr::V4(Ipv4Addr::LOCALHOST) 3409 )); 3410 assert!(blossom_authority_accepts_address( 3411 BlossomEndpointAuthority::PrivateNetworkDevelopment, 3412 IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)) 3413 )); 3414 } 3415 3416 #[cfg(feature = "blossom")] 3417 #[test] 3418 fn blossom_device_policy_matches_the_shared_conformance_vectors() { 3419 let document: serde_json::Value = serde_json::from_str(include_str!( 3420 "../../../contracts/conformance/vectors/transport/device_network_policy.v1.json" 3421 )) 3422 .expect("device network policy vectors"); 3423 for vector in document["vectors"].as_array().expect("vectors") { 3424 let input = &vector["input"]; 3425 if input["surface"] != "blossom" { 3426 continue; 3427 } 3428 let endpoint = input["endpoint"].as_str().expect("endpoint"); 3429 let profile = match input["policy"].as_str().expect("policy") { 3430 "public" => public_blossom_profile(endpoint), 3431 "loopback" => simulator_blossom_profile(endpoint), 3432 "private_device" => device_blossom_profile(endpoint), 3433 other => panic!("unknown Blossom policy {other}"), 3434 }; 3435 assert_eq!( 3436 profile.is_ok(), 3437 vector["expected"]["accepted"].as_bool().expect("accepted"), 3438 "{}", 3439 vector["id"].as_str().expect("id") 3440 ); 3441 } 3442 } 3443 3444 #[cfg(feature = "blossom")] 3445 #[tokio::test] 3446 async fn blossom_cancellation_slot_claim_and_receipt_state_are_exact() { 3447 let cancellation = BlossomCancellation::default(); 3448 assert!(!cancellation.is_cancelled()); 3449 let waiting = cancellation.clone(); 3450 let waiter = tokio::spawn(async move { waiting.cancelled().await }); 3451 tokio::task::yield_now().await; 3452 cancellation.cancel(); 3453 waiter.await.unwrap(); 3454 cancellation.cancelled().await; 3455 assert!(cancellation.is_cancelled()); 3456 3457 let request = blossom_request("http://127.0.0.1:3000"); 3458 let slot = BlossomSlot::new(); 3459 assert!(slot.host_kind().is_none()); 3460 let content = AuthorizationContent::parse("Upload farm image").unwrap(); 3461 assert!(slot.prepare_upload(request.clone()).is_err()); 3462 slot.configure(BlossomConfig::from_profile( 3463 simulator_blossom_profile("http://127.0.0.1:3000").unwrap(), 3464 )) 3465 .unwrap(); 3466 let transaction = slot.prepare_upload(request.clone()).unwrap(); 3467 let claim = slot 3468 .authored_upload_claim(&transaction, content.clone(), 100, 60) 3469 .unwrap(); 3470 assert_eq!(claim.server_domain().as_str(), "127.0.0.1"); 3471 assert_eq!(claim.sha256(), request.sha256()); 3472 assert_eq!(claim.lifetime_seconds(), 60); 3473 assert_eq!( 3474 slot.authored_upload_claim(&transaction, content, 100, 0) 3475 .expect_err("invalid lifetime") 3476 .kind(), 3477 BlossomErrorKind::Authorization 3478 ); 3479 slot.clear(); 3480 assert!(slot.host_kind().is_none()); 3481 3482 let descriptor = radroots_blossom::BlobDescriptor::new( 3483 transaction.expected_url().clone(), 3484 request.sha256(), 3485 request.byte_size(), 3486 request.media_type().clone(), 3487 1, 3488 ) 3489 .unwrap() 3490 .approve_reference() 3491 .unwrap() 3492 .verify_bytes(request.bytes(), request.media_type()) 3493 .unwrap(); 3494 let receipt = BlossomUploadReceipt::new(descriptor, request.dimensions(), 2, 3); 3495 assert_eq!(receipt.descriptor().sha256(), request.sha256()); 3496 assert_eq!(receipt.dimensions(), request.dimensions()); 3497 assert_eq!(receipt.attempts(), 2); 3498 assert_eq!(receipt.verified_at_unix_ms(), 3); 3499 assert_eq!(receipt.into_descriptor().size(), request.byte_size()); 3500 3501 let poisoned = BlossomSlot::new(); 3502 let state = Arc::clone(&poisoned.state); 3503 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { 3504 let _guard = state.write().expect("write lock"); 3505 panic!("poison Blossom slot"); 3506 })); 3507 poisoned.clear(); 3508 assert!( 3509 poisoned 3510 .configure(BlossomConfig::from_profile( 3511 simulator_blossom_profile("http://127.0.0.1:3000").unwrap(), 3512 )) 3513 .is_err() 3514 ); 3515 assert!(poisoned.host_kind().is_none()); 3516 } 3517 3518 #[cfg(feature = "radrootsd")] 3519 #[test] 3520 fn daemon_configuration_is_inert_explicit_and_redacted() { 3521 let config = DaemonConfig::new("http://127.0.0.1:1/rpc") 3522 .with_auth(DaemonAuth::BearerToken("secret-token".to_owned())) 3523 .with_timeout(core::time::Duration::from_millis(5)); 3524 let adapter = DaemonDelivery::new(config); 3525 3526 let debug = format!("{adapter:?}"); 3527 assert!(!debug.contains("secret-token")); 3528 assert!(!debug.contains("reqwest")); 3529 assert_eq!(format!("{:?}", DaemonAuth::None), "None"); 3530 assert_eq!( 3531 format!("{:?}", DaemonAuth::BearerToken("private".to_owned())), 3532 "BearerToken(<redacted>)" 3533 ); 3534 } 3535 3536 #[cfg(feature = "radrootsd")] 3537 #[test] 3538 fn daemon_errors_are_stably_classified_and_redacted() { 3539 use std::error::Error as _; 3540 3541 use crate::adapters::radrootsd::RadrootsdError; 3542 3543 let cases = [ 3544 ( 3545 RadrootsdError::InvalidAuthHeader("private".to_owned()), 3546 DaemonErrorKind::Authentication, 3547 "daemon authentication configuration is invalid", 3548 ), 3549 ( 3550 RadrootsdError::InvalidRequest("private".to_owned()), 3551 DaemonErrorKind::InvalidRequest, 3552 "daemon delivery request is invalid", 3553 ), 3554 ( 3555 RadrootsdError::Http("private".to_owned()), 3556 DaemonErrorKind::Transport, 3557 "daemon transport failed", 3558 ), 3559 ( 3560 RadrootsdError::JsonRpc { 3561 code: -1, 3562 message: "private".to_owned(), 3563 }, 3564 DaemonErrorKind::Rpc, 3565 "daemon RPC failed", 3566 ), 3567 ( 3568 RadrootsdError::MalformedResponse("private".to_owned()), 3569 DaemonErrorKind::InvalidResponse, 3570 "daemon response is invalid", 3571 ), 3572 ]; 3573 for (private, kind, display) in cases { 3574 let error = DaemonError::from_private(private); 3575 assert_eq!(error.kind(), kind); 3576 assert_eq!(error.to_string(), display); 3577 assert!(error.source().is_some()); 3578 assert!(!format!("{error:?}").contains("private")); 3579 } 3580 } 3581 3582 #[cfg(feature = "nostr")] 3583 #[test] 3584 fn nostr_slot_reconfiguration_is_atomic_directional_and_inert() { 3585 let slot = NostrSlot::new(); 3586 assert!(slot.read_targets().is_none()); 3587 assert!(slot.relay_status().is_none()); 3588 assert!( 3589 ready( 3590 slot.configure( 3591 RelayProfile::explicit( 3592 RelayProfileKind::Simulator, 3593 [RelayEndpoint::new( 3594 "ws://127.0.0.1:7447", 3595 RelayUrlPolicy::Local, 3596 RelayAccess::ReadWrite, 3597 ) 3598 .expect("endpoint")], 3599 ) 3600 .expect("profile"), 3601 ) 3602 ) 3603 .is_ok() 3604 ); 3605 let original = slot.read_targets().expect("configured targets"); 3606 assert_eq!(slot.write_targets(), Some(original.clone())); 3607 let status = slot.relay_status().expect("status"); 3608 assert_eq!(status.profile_kind(), RelayProfileKind::Simulator); 3609 assert_eq!(status.read_availability(), Availability::Unavailable); 3610 assert_eq!(status.write_availability(), Availability::Unavailable); 3611 ready(slot.clear()); 3612 assert!(slot.read_targets().is_none()); 3613 assert!(slot.write_targets().is_none()); 3614 assert!(format!("{slot:?}").contains("configured: false")); 3615 } 3616 3617 #[cfg(feature = "nostr")] 3618 #[test] 3619 fn poisoned_nostr_slot_fails_closed_for_every_host_operation() { 3620 let slot = NostrSlot::new(); 3621 let state = Arc::clone(&slot.state); 3622 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { 3623 let _guard = state.write().expect("write lock"); 3624 panic!("poison transport slot"); 3625 })); 3626 3627 ready(slot.clear()); 3628 assert!(slot.read_targets().is_none()); 3629 assert!( 3630 ready( 3631 slot.configure( 3632 RelayProfile::explicit( 3633 RelayProfileKind::Simulator, 3634 [RelayEndpoint::new( 3635 "ws://127.0.0.1:7447", 3636 RelayUrlPolicy::Local, 3637 RelayAccess::ReadWrite, 3638 ) 3639 .expect("endpoint")], 3640 ) 3641 .expect("profile"), 3642 ) 3643 ) 3644 .is_err() 3645 ); 3646 } 3647 3648 #[cfg(feature = "nostr")] 3649 #[tokio::test] 3650 async fn transitions_and_cancelled_reconfiguration_never_report_the_old_pool_as_available() { 3651 use radroots_transport::{EventSink, EventSource, FetchRequest, source::FetchBounds}; 3652 let profile = RelayProfile::explicit( 3653 RelayProfileKind::Simulator, 3654 [RelayEndpoint::new( 3655 "ws://127.0.0.1:7447", 3656 RelayUrlPolicy::Local, 3657 RelayAccess::ReadWrite, 3658 ) 3659 .unwrap()], 3660 ) 3661 .unwrap(); 3662 let slot = NostrSlot::new(); 3663 slot.configure(profile.clone()).await.unwrap(); 3664 let previous = slot.cleanup_snapshot().unwrap(); 3665 let targets = slot.read_targets().unwrap(); 3666 let fetch = FetchRequest::new( 3667 "transition-fetch", 3668 targets.clone(), 3669 FetchBounds::new(1, u64::MAX).unwrap(), 3670 ) 3671 .unwrap(); 3672 let delivery = radroots_transport::DeliveryRequest::new( 3673 "transition-delivery", 3674 radroots_transport::sink::DeliveryPayload::new(signed_event()), 3675 TargetSet::new(vec![target(1), target(2)]).unwrap(), 3676 SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), 3677 1, 3678 ) 3679 .unwrap(); 3680 let held = slot.transition.lock().await; 3681 assert!(slot.relay_status().is_none()); 3682 assert!(slot.read_targets().is_none()); 3683 assert_eq!( 3684 EventSource::status(&slot).await.unwrap_err(), 3685 radroots_transport::Error::TransportUnavailable 3686 ); 3687 assert_eq!( 3688 EventSink::status(&slot).await.unwrap_err(), 3689 radroots_transport::Error::TransportUnavailable 3690 ); 3691 assert_eq!( 3692 slot.fetch(fetch.clone()).await.unwrap_err(), 3693 radroots_transport::Error::TransportUnavailable 3694 ); 3695 for failure in [ 3696 slot.deliver(delivery.clone()).await.unwrap_err(), 3697 slot.deliver_selected(delivery.clone(), delivery.target_set().clone()) 3698 .await 3699 .unwrap_err(), 3700 ] { 3701 assert_eq!(failure.code(), "transport_unavailable"); 3702 assert_eq!( 3703 failure.partial_evidence().len(), 3704 delivery.target_set().len() 3705 ); 3706 assert!( 3707 failure 3708 .partial_evidence() 3709 .iter() 3710 .all(|row| !row.was_attempted()) 3711 ); 3712 failure.validate_for_request(&delivery).unwrap(); 3713 } 3714 drop(held); 3715 // This is the retained selection after interrupted predecessor cleanup. 3716 previous.transport.shutdown().await; 3717 assert!(slot.relay_status().is_none()); 3718 assert_eq!( 3719 slot.fetch(fetch).await.unwrap_err(), 3720 radroots_transport::Error::TransportUnavailable 3721 ); 3722 slot.configure(profile).await.unwrap(); 3723 assert!(slot.read_targets().is_some()); 3724 slot.shutdown().await; 3725 assert_eq!( 3726 EventSource::status(&slot).await.unwrap_err(), 3727 radroots_transport::Error::TransportClosed 3728 ); 3729 let failure = slot.deliver(delivery).await.unwrap_err(); 3730 assert_eq!(failure.code(), "transport_closed"); 3731 assert_eq!(failure.partial_evidence().len(), 2); 3732 } 3733 3734 #[cfg(feature = "nostr")] 3735 #[tokio::test] 3736 async fn empty_nostr_slot_reports_unavailable_and_rejects_operations() { 3737 use radroots_transport::{ 3738 DeliveryRequest, EventSink as _, EventSource as _, FetchRequest, sink::DeliveryPayload, 3739 source::FetchBounds, 3740 }; 3741 3742 let slot = NostrSlot::new(); 3743 let source = radroots_transport::EventSource::status(&slot) 3744 .await 3745 .expect("source status"); 3746 assert_eq!(source.availability(), Availability::Unavailable); 3747 3748 let targets = TargetSet::new(vec![target(1)]).expect("targets"); 3749 let fetch = FetchRequest::new( 3750 "fetch", 3751 targets.clone(), 3752 FetchBounds::new(1, 1).expect("bounds"), 3753 ) 3754 .expect("fetch"); 3755 assert_eq!(slot.fetch(fetch).await, Err(Error::UnsupportedOperation)); 3756 3757 let sink = radroots_transport::EventSink::status(&slot) 3758 .await 3759 .expect("sink status"); 3760 assert_eq!(sink.availability(), Availability::Unavailable); 3761 let deliver = DeliveryRequest::new( 3762 "deliver", 3763 DeliveryPayload::new(signed_event()), 3764 targets, 3765 SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::any()), 3766 1, 3767 ) 3768 .expect("delivery"); 3769 let failure = slot 3770 .deliver(deliver.clone()) 3771 .await 3772 .expect_err("unconfigured sink"); 3773 assert_eq!(failure.code(), "nostr_transport_not_configured"); 3774 let failure = slot 3775 .deliver_selected(deliver.clone(), deliver.target_set().clone()) 3776 .await 3777 .unwrap_err(); 3778 assert_eq!(failure.code(), "nostr_transport_not_configured"); 3779 failure.validate_for_request(&deliver).unwrap(); 3780 let foreign = TargetSet::new(vec![target(2)]).unwrap(); 3781 let failure = slot 3782 .deliver_selected(deliver.clone(), foreign) 3783 .await 3784 .unwrap_err(); 3785 assert_eq!(failure.code(), "invalid_transport_contract"); 3786 let subset_request = DeliveryRequest::new( 3787 "selected-delivery", 3788 DeliveryPayload::new(signed_event()), 3789 TargetSet::new(vec![target(1), target(2)]).unwrap(), 3790 SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), 3791 1, 3792 ) 3793 .unwrap(); 3794 slot.configure( 3795 RelayProfile::explicit( 3796 RelayProfileKind::Public, 3797 [RelayEndpoint::new( 3798 "wss://one.example", 3799 RelayUrlPolicy::Public, 3800 RelayAccess::ReadWrite, 3801 ) 3802 .unwrap()], 3803 ) 3804 .unwrap(), 3805 ) 3806 .await 3807 .unwrap(); 3808 let receipt = slot 3809 .deliver_selected(deliver.clone(), deliver.target_set().clone()) 3810 .await 3811 .unwrap(); 3812 receipt.validate_for_request(&deliver).unwrap(); 3813 assert!( 3814 receipt 3815 .target_receipts() 3816 .iter() 3817 .all(|row| !row.was_attempted()) 3818 ); 3819 let subset = 3820 TargetSet::new(vec![subset_request.target_set().targets()[0].clone()]).unwrap(); 3821 let receipt = slot 3822 .deliver_selected(subset_request.clone(), subset) 3823 .await 3824 .unwrap(); 3825 receipt.validate_for_request(&subset_request).unwrap(); 3826 assert!(!receipt.target_receipts()[1].was_attempted()); 3827 assert_eq!( 3828 receipt.target_receipts()[1].outcome().code(), 3829 Some("target_not_selected") 3830 ); 3831 } 3832 }