private_ingress.rs (7446B)
1 //! Authenticated, protected NIP-59 evidence through participant-owned custody. 2 //! Cryptographic provenance supplies no consent, stock or history authority. 3 use alloc::string::String; 4 use base64::Engine as _; 5 use core::fmt; 6 use radroots_identity::PublicKey; 7 use radroots_protocol::private_rumor::{DecodedRumor, RumorWireError}; 8 use radroots_signing::provider::{ 9 ParticipantProvider, PrivateCiphertext, PrivateCryptoCapability, PrivateText, ProviderCall, 10 ProviderError, 11 }; 12 13 /// Fixed diagnostics without private text or dependency-owned causes. 14 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 15 pub enum OpeningError { 16 InvalidInput, 17 LimitExceeded, 18 Unauthenticated, 19 RecipientMismatch, 20 CarrierMismatch, 21 UnsupportedVersion, 22 Provider(ProviderError), 23 } 24 impl fmt::Display for OpeningError { 25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 26 f.write_str(match self { 27 Self::InvalidInput => "invalid_input", 28 Self::LimitExceeded => "limit_exceeded", 29 Self::Unauthenticated => "unauthenticated", 30 Self::RecipientMismatch => "recipient_mismatch", 31 Self::CarrierMismatch => "carrier_mismatch", 32 Self::UnsupportedVersion => "unsupported_version", 33 Self::Provider(error) => return write!(f, "provider_{error}"), 34 }) 35 } 36 } 37 impl core::error::Error for OpeningError {} 38 impl From<ProviderError> for OpeningError { 39 fn from(value: ProviderError) -> Self { 40 Self::Provider(value) 41 } 42 } 43 impl From<crate::event_verify::SignedReadError> for OpeningError { 44 fn from(value: crate::event_verify::SignedReadError) -> Self { 45 use crate::event_verify::SignedReadError; 46 match value { 47 SignedReadError::InvalidInput => Self::InvalidInput, 48 SignedReadError::LimitExceeded => Self::LimitExceeded, 49 SignedReadError::Unauthenticated => Self::Unauthenticated, 50 } 51 } 52 } 53 54 /// Obtained carrier evidence. Only this module can construct this value after 55 /// complete carrier admission and provider decryption. No automatic cloning or 56 /// serialization exposes its private data. Provider method honesty remains a 57 /// host qualification obligation. 58 pub struct AuthenticatedCarrier { 59 recipient: PublicKey, 60 envelope_id: radroots_event::EventId, 61 seal_id: radroots_event::EventId, 62 raw_outer: String, 63 raw_seal: PrivateText, 64 raw_rumor: PrivateText, 65 rumor: DecodedRumor, 66 } 67 impl fmt::Debug for AuthenticatedCarrier { 68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 69 f.write_str("AuthenticatedCarrier(<redacted>)") 70 } 71 } 72 impl AuthenticatedCarrier { 73 pub const fn recipient(&self) -> PublicKey { 74 self.recipient 75 } 76 pub const fn envelope_id(&self) -> radroots_event::EventId { 77 self.envelope_id 78 } 79 pub const fn seal_id(&self) -> radroots_event::EventId { 80 self.seal_id 81 } 82 pub const fn rumor(&self) -> &DecodedRumor { 83 &self.rumor 84 } 85 /// Borrow original encrypted evidence for protected retention. 86 pub fn protected_outer(&self) -> &str { 87 &self.raw_outer 88 } 89 /// Borrow original decrypted evidence for protected retention. 90 pub fn protected_seal(&self) -> &str { 91 self.raw_seal.expose() 92 } 93 /// Borrow original unsigned evidence, including unsupported content. 94 pub fn protected_rumor(&self) -> &str { 95 self.raw_rumor.expose() 96 } 97 } 98 99 fn ciphertext(value: &str, plaintext_limit: usize) -> Result<PrivateCiphertext, OpeningError> { 100 let encoded = PrivateCiphertext::parse(value).map_err(|error| match error { 101 ProviderError::LimitExceeded => OpeningError::LimitExceeded, 102 ProviderError::UnsupportedVersion => OpeningError::UnsupportedVersion, 103 _ => OpeningError::InvalidInput, 104 })?; 105 let raw = base64::engine::general_purpose::STANDARD 106 .decode(value) 107 .map_err(|_| OpeningError::InvalidInput)?; 108 if raw.first() != Some(&2) { 109 return Err(OpeningError::UnsupportedVersion); 110 } 111 if raw.len() < 99 || (raw.len() - 67) % 32 != 0 { 112 return Err(OpeningError::InvalidInput); 113 } 114 // NIP44's authenticated short-length padding bounds the largest possible 115 // plaintext before asking the provider to allocate/decrypt it. 116 let power = plaintext_limit.next_power_of_two(); 117 let chunk = if power <= 256 { 32 } else { power / 8 }; 118 let padded_limit = plaintext_limit.div_ceil(chunk) * chunk; 119 if raw.len() > padded_limit + 67 { 120 return Err(OpeningError::LimitExceeded); 121 } 122 Ok(encoded) 123 } 124 125 async fn identity( 126 provider: &dyn ParticipantProvider, 127 expected: PublicKey, 128 ) -> Result<(), OpeningError> { 129 let state = provider.provider_state().await?; 130 if state.identity() != expected { 131 return Err(ProviderError::IdentityChanged.into()); 132 } 133 if state.decryption() != PrivateCryptoCapability::Nip44V2 { 134 return Err(ProviderError::CapabilityUnavailable.into()); 135 } 136 Ok(()) 137 } 138 139 /// Admit the original bounded outer before callbacks; authenticate each nested 140 /// signed carrier before decryption and preserve the obtained protected bytes. 141 /// The provider enforces fresh deadlines/cancellation before each crypto call. 142 pub async fn open( 143 provider: &dyn ParticipantProvider, 144 call: ProviderCall, 145 raw_outer: &str, 146 ) -> Result<AuthenticatedCarrier, OpeningError> { 147 let outer = crate::event_verify::signed_json(raw_outer)?; 148 if outer.kind_u32() != 1059 { 149 return Err(OpeningError::CarrierMismatch); 150 } 151 let recipient = call.identity(); 152 let mut selected = false; 153 for tag in outer.tags_as_vec() { 154 if tag.first().map(String::as_str) == Some("p") { 155 if selected || !(2..=3).contains(&tag.len()) || tag[1] != recipient.to_hex() { 156 return Err(OpeningError::RecipientMismatch); 157 } 158 selected = true; 159 } 160 } 161 if !selected { 162 return Err(OpeningError::RecipientMismatch); 163 } 164 let encrypted = ciphertext( 165 outer.content(), 166 radroots_protocol::profile::SIGNED_EVENT_MAX_BYTES, 167 )?; 168 identity(provider, recipient).await?; 169 let raw_seal = provider 170 .decrypt_private(call.clone(), *outer.author(), encrypted) 171 .await?; 172 identity(provider, recipient).await?; 173 let seal = crate::event_verify::signed_json(raw_seal.expose())?; 174 if seal.kind_u32() != 13 || !seal.tags_as_vec().is_empty() { 175 return Err(OpeningError::CarrierMismatch); 176 } 177 let encrypted = ciphertext( 178 seal.content(), 179 radroots_protocol::profile::UNSIGNED_RUMOR_MAX_BYTES, 180 )?; 181 let raw_rumor = provider 182 .decrypt_private(call, *seal.author(), encrypted) 183 .await?; 184 identity(provider, recipient).await?; 185 let rumor = 186 DecodedRumor::decode(raw_rumor.expose().as_bytes()).map_err(|error| match error { 187 RumorWireError::InvalidInput => OpeningError::InvalidInput, 188 RumorWireError::LimitExceeded => OpeningError::LimitExceeded, 189 RumorWireError::IdentityMismatch => OpeningError::Unauthenticated, 190 })?; 191 if rumor.author() != *seal.author() { 192 return Err(OpeningError::CarrierMismatch); 193 } 194 Ok(AuthenticatedCarrier { 195 recipient, 196 envelope_id: *outer.id(), 197 seal_id: *seal.id(), 198 raw_outer: String::from(raw_outer), 199 raw_seal, 200 raw_rumor, 201 rumor, 202 }) 203 }