lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

event_verify.rs (9523B)


      1 //! NIP-01 identity/signature verification for inbound Nostr events.
      2 //!
      3 //! Cryptographic verification does not establish product-contract admission,
      4 //! referenced-event existence, relay trust, or application authorization.
      5 
      6 #![forbid(unsafe_code)]
      7 
      8 use radroots_event::{
      9     admission::{Error as VerificationError, RawEvent, SignatureVerifier},
     10     envelope::EventEnvelope,
     11 };
     12 use radroots_event_codec::verify;
     13 
     14 /// Deterministic BIP-340 verification supplied by the Nostr adapter.
     15 #[derive(Clone, Copy, Debug, Default)]
     16 pub struct NostrSignatureVerifier;
     17 
     18 impl SignatureVerifier for NostrSignatureVerifier {
     19     fn verify_signature(&self, event: &EventEnvelope) -> Result<(), VerificationError> {
     20         validate_nostr_kind(event)?;
     21         let public_key = nostr::secp256k1::XOnlyPublicKey::from_slice(event.author().as_bytes())
     22             .map_err(|_| VerificationError::MalformedEnvelope)?;
     23         let signature = nostr::secp256k1::schnorr::Signature::from_slice(event.sig().as_bytes())
     24             .map_err(|_| VerificationError::MalformedEnvelope)?;
     25         let message = nostr::secp256k1::Message::from_digest(*event.id().as_bytes());
     26         nostr::SECP256K1
     27             .verify_schnorr(&signature, &message, &public_key)
     28             .map_err(|_| VerificationError::SignatureInvalid)
     29     }
     30 }
     31 
     32 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     33 pub enum Verification {
     34     Verified,
     35     IdVerified,
     36     IdMismatch,
     37     SignatureInvalid,
     38     MalformedEnvelope,
     39 }
     40 
     41 pub fn verify_event(event: &EventEnvelope) -> Verification {
     42     let result = validate_nostr_kind(event)
     43         .and_then(|()| verify::id(RawEvent::new(event.clone())))
     44         .and_then(|event| verify::signature(event, &NostrSignatureVerifier));
     45     match result {
     46         Ok(_) => Verification::Verified,
     47         Err(error) => verification_error_status(&error),
     48     }
     49 }
     50 
     51 pub fn verify_event_id(event: &EventEnvelope) -> Verification {
     52     let result = validate_nostr_kind(event).and_then(|()| verify::id(RawEvent::new(event.clone())));
     53     match result {
     54         Ok(_) => Verification::IdVerified,
     55         Err(error) => verification_error_status(&error),
     56     }
     57 }
     58 
     59 fn validate_nostr_kind(event: &EventEnvelope) -> Result<(), VerificationError> {
     60     u16::try_from(event.kind_u32())
     61         .map(|_| ())
     62         .map_err(|_| VerificationError::MalformedEnvelope)
     63 }
     64 
     65 fn verification_error_status(error: &VerificationError) -> Verification {
     66     match error {
     67         VerificationError::IdMismatch { .. } => Verification::IdMismatch,
     68         VerificationError::SignatureInvalid => Verification::SignatureInvalid,
     69         VerificationError::MalformedEnvelope | VerificationError::ContractValidation(_) => {
     70             Verification::MalformedEnvelope
     71         }
     72         _ => Verification::MalformedEnvelope,
     73     }
     74 }
     75 
     76 #[cfg(any(
     77     feature = "nip17",
     78     feature = "private_ingress",
     79     feature = "public_ingress"
     80 ))]
     81 #[derive(Clone, Copy)]
     82 pub(crate) enum SignedReadError {
     83     InvalidInput,
     84     LimitExceeded,
     85     Unauthenticated,
     86 }
     87 
     88 /// Admit original signed JSON before any upstream conversion or callback.
     89 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
     90 pub(crate) fn signed_json(raw: &str) -> Result<EventEnvelope, SignedReadError> {
     91     use radroots_event::wire::EventWireLimits;
     92     const LIMIT: usize = 65_536;
     93     signed_json_with_limits(
     94         raw,
     95         EventWireLimits {
     96             max_raw_json_bytes: LIMIT,
     97             max_content_bytes: LIMIT,
     98             ..Default::default()
     99         },
    100     )
    101 }
    102 
    103 #[cfg(any(
    104     feature = "nip17",
    105     feature = "private_ingress",
    106     feature = "public_ingress"
    107 ))]
    108 pub(crate) fn signed_json_with_limits(
    109     raw: &str,
    110     limits: radroots_event::wire::EventWireLimits,
    111 ) -> Result<EventEnvelope, SignedReadError> {
    112     use radroots_event::{
    113         envelope::{EventEnvelopeLimits, EventEnvelopeParts},
    114         wire::{EventWireError, Nip01EventWire},
    115     };
    116     let wire =
    117         Nip01EventWire::parse_json_exact_with_limits(raw, limits).map_err(|error| match error {
    118             EventWireError::EventIdMismatch { .. } => SignedReadError::Unauthenticated,
    119             EventWireError::RawJsonTooLarge { .. }
    120             | EventWireError::ContentTooLarge { .. }
    121             | EventWireError::TooManyTags { .. }
    122             | EventWireError::TooManyTagElements { .. }
    123             | EventWireError::TagElementTooLarge { .. }
    124             | EventWireError::TagsTooLarge { .. } => SignedReadError::LimitExceeded,
    125             _ => SignedReadError::InvalidInput,
    126         })?;
    127     let event = EventEnvelope::new_with_limits(
    128         EventEnvelopeParts {
    129             id: wire.id,
    130             author: wire.pubkey,
    131             created_at: wire.created_at,
    132             kind: wire.kind,
    133             tags: wire.tags,
    134             content: wire.content,
    135             sig: wire.sig,
    136         },
    137         EventEnvelopeLimits {
    138             max_content_bytes: limits.max_content_bytes,
    139             max_tag_count: limits.max_tag_count,
    140             max_total_tag_elements: limits.max_total_tag_elements,
    141             max_tag_element_bytes: limits.max_tag_element_bytes,
    142             max_total_tag_bytes: limits.max_total_tag_bytes,
    143         },
    144     )
    145     .map_err(|_| SignedReadError::InvalidInput)?;
    146     match verify_event(&event) {
    147         Verification::Verified => Ok(event),
    148         Verification::MalformedEnvelope => Err(SignedReadError::InvalidInput),
    149         _ => Err(SignedReadError::Unauthenticated),
    150     }
    151 }
    152 
    153 #[cfg(test)]
    154 mod tests {
    155     use super::*;
    156     use crate::event_convert::from_nostr;
    157     use crate::events::build_event_unchecked;
    158     use crate::test_fixtures::FIXTURE_ALICE;
    159     use crate::types::{RadrootsNostrKeys, RadrootsNostrTimestamp};
    160     use nostr::SecretKey;
    161     use radroots_event::{
    162         envelope::EventEnvelopeParts, envelope::kind::KIND_POST,
    163         wire::compute_canonical_nip01_event_id,
    164     };
    165 
    166     fn fixture_keys() -> RadrootsNostrKeys {
    167         let secret_key = SecretKey::from_hex(FIXTURE_ALICE.secret_key_hex).expect("secret key");
    168         RadrootsNostrKeys::new(secret_key)
    169     }
    170 
    171     fn signed_event() -> EventEnvelope {
    172         let raw_event = build_event_unchecked(
    173             KIND_POST,
    174             "hello",
    175             vec![vec!["t".to_owned(), "soil".to_owned()]],
    176         )
    177         .expect("builder")
    178         .custom_created_at(RadrootsNostrTimestamp::from_secs(1_700_000_000))
    179         .sign_with_keys(&fixture_keys())
    180         .expect("signed event");
    181         from_nostr(&raw_event).expect("Radroots event envelope")
    182     }
    183 
    184     fn envelope_with(
    185         event: &EventEnvelope,
    186         content: String,
    187         kind: u32,
    188         sig: String,
    189     ) -> EventEnvelope {
    190         EventEnvelope::new(EventEnvelopeParts {
    191             id: event.id_hex(),
    192             author: event.author().to_hex().to_owned(),
    193             created_at: event.created_at_u64(),
    194             kind,
    195             tags: event.tags_as_vec(),
    196             content,
    197             sig,
    198         })
    199         .expect("envelope")
    200     }
    201 
    202     #[test]
    203     fn verifies_signed_event_id_and_signature() {
    204         let event = signed_event();
    205 
    206         assert_eq!(verify_event(&event), Verification::Verified);
    207         assert_eq!(verify_event_id(&event), Verification::IdVerified);
    208     }
    209 
    210     #[test]
    211     fn reports_id_mismatch_before_signature_checks() {
    212         let original = signed_event();
    213         let event = envelope_with(
    214             &original,
    215             "tampered".to_owned(),
    216             original.kind_u32(),
    217             original.signature_hex(),
    218         );
    219 
    220         assert_eq!(verify_event(&event), Verification::IdMismatch);
    221     }
    222 
    223     #[test]
    224     fn reports_signature_invalid_for_valid_id_with_wrong_signature() {
    225         let original = signed_event();
    226         let mut sig = original.signature_hex();
    227         let replacement = if sig.starts_with('0') { "1" } else { "0" };
    228         sig.replace_range(0..1, replacement);
    229         let event = envelope_with(
    230             &original,
    231             original.content().to_owned(),
    232             original.kind_u32(),
    233             sig,
    234         );
    235 
    236         assert_eq!(verify_event(&event), Verification::SignatureInvalid);
    237     }
    238 
    239     #[test]
    240     fn out_of_range_kind_precedes_id_mismatch() {
    241         let original = signed_event();
    242         let event = envelope_with(
    243             &original,
    244             original.content().to_owned(),
    245             u32::from(u16::MAX) + 1,
    246             original.signature_hex(),
    247         );
    248 
    249         assert_eq!(verify_event(&event), Verification::MalformedEnvelope);
    250         assert_eq!(verify_event_id(&event), Verification::MalformedEnvelope);
    251     }
    252 
    253     #[test]
    254     fn reports_malformed_envelope_for_id_valid_out_of_range_kind() {
    255         let original = signed_event();
    256         let kind = u32::from(u16::MAX) + 1;
    257         let id = compute_canonical_nip01_event_id(
    258             &original.author().to_hex(),
    259             original.created_at_u64(),
    260             kind,
    261             &original.tags_as_vec(),
    262             original.content(),
    263         )
    264         .expect("canonical id")
    265         .into_string();
    266         let event = EventEnvelope::new(EventEnvelopeParts {
    267             id,
    268             author: original.author().to_hex().to_owned(),
    269             created_at: original.created_at_u64(),
    270             kind,
    271             tags: original.tags_as_vec(),
    272             content: original.content().to_owned(),
    273             sig: original.signature_hex(),
    274         })
    275         .expect("envelope");
    276 
    277         assert_eq!(verify_event(&event), Verification::MalformedEnvelope);
    278         assert_eq!(verify_event_id(&event), Verification::MalformedEnvelope);
    279     }
    280 }