signing.rs (9228B)
1 //! Concrete local Nostr implementation of the generic signing SPI. 2 //! 3 //! Signing is local and in-memory. Success returns a cryptographically verified 4 //! exact-plan receipt without persistence or publication. 5 6 use core::fmt; 7 use std::{ 8 time::{SystemTime, UNIX_EPOCH}, 9 vec, 10 }; 11 12 use radroots_identity::PublicKey; 13 use radroots_signing::{ 14 Error as SigningError, SignReceipt, SignRequest, Signer, SignerStatus, 15 capability::{CancellationSupport, SignerCapability, SignerKind}, 16 error::Kind, 17 recovery::ReplayCapability, 18 signer::BoxFuture, 19 status::{SignProgress, SignProgressStage, SignerAvailability}, 20 }; 21 22 use crate::{Error as NostrError, key::SecretKey}; 23 24 #[cfg(feature = "nip17")] 25 pub mod gift_wrap; 26 mod issuance; 27 mod private; 28 pub use private::OsNonceSource; 29 30 type Clock = fn() -> Result<u64, SigningError>; 31 32 /// A local Nostr key-backed signer adapter. 33 pub struct LocalSigner { 34 keys: nostr::Keys, 35 public_key: PublicKey, 36 clock: Clock, 37 nonce_source: 38 Option<radroots_signing::host::Shared<dyn radroots_signing::provider::NonceSource>>, 39 } 40 41 impl LocalSigner { 42 pub fn new(secret_key: SecretKey) -> Result<Self, crate::Error> { 43 Self::with_clock(secret_key, system_time_unix_ms) 44 } 45 46 pub fn generate() -> Result<Self, crate::Error> { 47 Self::new(SecretKey::generate()) 48 } 49 50 #[must_use] 51 pub const fn public_key(&self) -> PublicKey { 52 self.public_key 53 } 54 55 /// Constructs the adapter with an explicit host clock. 56 pub fn with_clock(secret_key: SecretKey, clock: Clock) -> Result<Self, crate::Error> { 57 let public_key = secret_key.public_key()?; 58 Ok(Self { 59 keys: secret_key.into_keys(), 60 public_key, 61 clock, 62 nonce_source: None, 63 }) 64 } 65 66 /// Enables private encryption with explicitly injected nonce entropy. 67 /// Identity observation and decryption never export this provider's key. 68 pub fn with_nonce_source( 69 mut self, 70 source: radroots_signing::host::Shared<dyn radroots_signing::provider::NonceSource>, 71 ) -> Self { 72 self.nonce_source = Some(source); 73 self 74 } 75 } 76 77 impl fmt::Debug for LocalSigner { 78 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 79 formatter 80 .debug_struct("LocalSigner") 81 .field("public_key", &self.public_key) 82 .field("secret_key", &"[redacted]") 83 .finish() 84 } 85 } 86 87 impl Signer for LocalSigner { 88 fn status(&self) -> BoxFuture<'_, Result<SignerStatus, SigningError>> { 89 Box::pin(async { 90 Ok(SignerStatus::new( 91 SignerAvailability::Ready, 92 vec![SignerCapability::new( 93 SignerKind::Local, 94 ReplayCapability::LocalReplaySafe, 95 CancellationSupport::BeforePublication, 96 true, 97 false, 98 )], 99 None, 100 )) 101 }) 102 } 103 104 fn sign(&self, request: SignRequest) -> BoxFuture<'_, Result<SignReceipt, SigningError>> { 105 Box::pin(async move { 106 request.ensure_active((self.clock)()?)?; 107 request.report_progress( 108 &SignProgress::stage(SignProgressStage::Validating) 109 .expect("validating has no challenge"), 110 ); 111 if request.expected_author() != &self.public_key { 112 return Err(SigningError::new(Kind::AuthorizationDenied)); 113 } 114 let signed_event = crate::plan_signing::sign_request(&self.keys, &request) 115 .map_err(normalize_nostr_error)?; 116 request.report_progress( 117 &SignProgress::stage(SignProgressStage::VerifyingOutput) 118 .expect("verification has no challenge"), 119 ); 120 let completed_at_unix_ms = (self.clock)()?; 121 request.ensure_active(completed_at_unix_ms)?; 122 let receipt = 123 SignReceipt::from_signed_event(&request, signed_event, completed_at_unix_ms)?; 124 request.report_progress( 125 &SignProgress::stage(SignProgressStage::Complete) 126 .expect("completion has no challenge"), 127 ); 128 Ok(receipt) 129 }) 130 } 131 } 132 133 fn system_time_unix_ms() -> Result<u64, SigningError> { 134 SystemTime::now() 135 .duration_since(UNIX_EPOCH) 136 .map_err(|source| SigningError::with_source(Kind::InternalError, source)) 137 .and_then(|duration| { 138 u64::try_from(duration.as_millis()) 139 .map_err(|source| SigningError::with_source(Kind::InternalError, source)) 140 }) 141 } 142 143 fn normalize_nostr_error(source: NostrError) -> SigningError { 144 let kind = match &source { 145 NostrError::ExternalSigningAuthorMismatch { .. } => Kind::AuthorizationDenied, 146 NostrError::ExternalSigningEventIdMismatch { .. } 147 | NostrError::ExternalSigningEventInvalid(_) 148 | NostrError::ExternalSigningPlanMismatch { .. } => Kind::SignerOutputInvalid, 149 _ => Kind::InternalError, 150 }; 151 SigningError::with_source(kind, source) 152 } 153 154 #[cfg(test)] 155 mod tests { 156 use super::*; 157 use radroots_event::{GenericEventDraft, contract::AuthorRole}; 158 use radroots_event_codec::authoring::AuthoredEventPlan; 159 use radroots_protocol::runtime::v1::OperationId; 160 use radroots_signing::{ 161 Actor, AuthoredArtifactId, SigningIntentId, SigningOperationId, 162 actor::ActorSource, 163 request::{CancellationPolicy, CancellationSignal, SignPolicy}, 164 }; 165 166 use crate::{ 167 key::parse_secret_key, 168 test_fixtures::{FIXTURE_ALICE, FIXTURE_BOB}, 169 }; 170 171 const CREATED_AT: u64 = 1_700_000_000; 172 const DEADLINE_MS: u64 = 1_700_000_100_000; 173 174 fn before_deadline() -> Result<u64, SigningError> { 175 Ok(DEADLINE_MS - 1) 176 } 177 178 fn at_deadline() -> Result<u64, SigningError> { 179 Ok(DEADLINE_MS) 180 } 181 182 fn fixture_secret(value: &str) -> SecretKey { 183 parse_secret_key(value).expect("secret fixture") 184 } 185 186 fn request() -> SignRequest { 187 let actor = Actor::from_public_key_hex( 188 FIXTURE_ALICE.public_key_hex, 189 ActorSource::ExplicitPublicKey, 190 [AuthorRole::Any], 191 ) 192 .unwrap(); 193 let draft = GenericEventDraft::new( 194 "radroots.social.geochat.v1", 195 20_000, 196 CREATED_AT, 197 Vec::new(), 198 "private-fixture-content", 199 FIXTURE_ALICE.public_key_hex, 200 ) 201 .unwrap(); 202 SignRequest::new( 203 OperationId::SyncPush, 204 SigningIntentId::new( 205 SigningOperationId::new([1; 16]).unwrap(), 206 AuthoredArtifactId::new([2; 16]).unwrap(), 207 ), 208 actor, 209 AuthoredEventPlan::from_generic(draft).unwrap(), 210 SignPolicy::new(DEADLINE_MS, CancellationPolicy::LocalCooperative).unwrap(), 211 ) 212 .unwrap() 213 } 214 215 #[tokio::test] 216 async fn local_signer_reports_safe_replay_and_returns_verified_exact_plan() { 217 let signer = LocalSigner::with_clock( 218 fixture_secret(FIXTURE_ALICE.secret_key_hex), 219 before_deadline, 220 ) 221 .unwrap(); 222 let status = signer.status().await.unwrap(); 223 assert_eq!( 224 status.capabilities()[0].replay(), 225 ReplayCapability::LocalReplaySafe 226 ); 227 let request = request(); 228 let expected_id = request.expected_event_id().to_hex(); 229 let receipt = signer.sign(request).await.unwrap(); 230 assert_eq!(receipt.signed_event().id_str(), expected_id); 231 assert_eq!(receipt.completed_at_unix_ms(), DEADLINE_MS - 1); 232 } 233 234 #[tokio::test] 235 async fn wrong_key_deadline_and_cancellation_fail_closed() { 236 let wrong = 237 LocalSigner::with_clock(fixture_secret(FIXTURE_BOB.secret_key_hex), before_deadline) 238 .unwrap(); 239 assert_eq!( 240 wrong.sign(request()).await.unwrap_err().kind(), 241 Kind::AuthorizationDenied 242 ); 243 let expired = 244 LocalSigner::with_clock(fixture_secret(FIXTURE_ALICE.secret_key_hex), at_deadline) 245 .unwrap(); 246 assert_eq!( 247 expired.sign(request()).await.unwrap_err().kind(), 248 Kind::DeadlineExceeded 249 ); 250 let signal = CancellationSignal::new(); 251 let cancelled = request().with_cancellation_signal(signal.clone()); 252 signal.cancel(); 253 assert_eq!( 254 LocalSigner::with_clock( 255 fixture_secret(FIXTURE_ALICE.secret_key_hex), 256 before_deadline, 257 ) 258 .unwrap() 259 .sign(cancelled) 260 .await 261 .unwrap_err() 262 .kind(), 263 Kind::SignerCancelled 264 ); 265 } 266 267 #[test] 268 fn debug_never_exposes_local_secret_material() { 269 let signer = LocalSigner::with_clock( 270 fixture_secret(FIXTURE_ALICE.secret_key_hex), 271 before_deadline, 272 ) 273 .unwrap(); 274 let debug = format!("{signer:?}"); 275 assert!(!debug.contains(FIXTURE_ALICE.secret_key_hex)); 276 assert!(!debug.contains(FIXTURE_ALICE.nsec)); 277 } 278 }