lib

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

tests.rs (13120B)


      1 use super::*;
      2 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
      3 use crate::test_fixtures::FIXTURE_CAROL;
      4 use crate::{
      5     key::parse_secret_key,
      6     test_fixtures::{FIXTURE_ALICE, FIXTURE_BOB},
      7 };
      8 use core::num::NonZeroU64;
      9 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
     10 use radroots_signing::provider::PRIVATE_CRYPTO_MAX_BYTES;
     11 use radroots_signing::{host::Shared, recovery::ReplayCapability, request::CancellationSignal};
     12 use std::sync::atomic::{AtomicUsize, Ordering};
     13 
     14 fn clock() -> Result<u64, radroots_signing::Error> {
     15     Ok(100)
     16 }
     17 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
     18 fn unavailable_clock() -> Result<u64, radroots_signing::Error> {
     19     Err(radroots_signing::Error::new(
     20         radroots_signing::error::Kind::InternalError,
     21     ))
     22 }
     23 fn signer(secret: &str) -> LocalSigner {
     24     LocalSigner::with_clock(parse_secret_key(secret).unwrap(), clock).unwrap()
     25 }
     26 fn call(signer: &LocalSigner) -> ProviderCall {
     27     ProviderCall::new(
     28         signer.public_key(),
     29         NonZeroU64::new(200).unwrap(),
     30         CancellationSignal::new(),
     31     )
     32 }
     33 
     34 struct FixedNonce {
     35     calls: AtomicUsize,
     36     fail: bool,
     37     nonce: [u8; 32],
     38 }
     39 impl NonceSource for FixedNonce {
     40     fn next_nonce(&self) -> Result<[u8; 32], ProviderError> {
     41         self.calls.fetch_add(1, Ordering::SeqCst);
     42         if self.fail {
     43             Err(ProviderError::CapabilityUnavailable)
     44         } else {
     45             Ok(self.nonce)
     46         }
     47     }
     48 }
     49 fn nonce_source(fail: bool) -> Shared<FixedNonce> {
     50     let mut nonce = [0; 32];
     51     nonce[31] = 1;
     52     Shared::new(FixedNonce {
     53         calls: AtomicUsize::new(0),
     54         fail,
     55         nonce,
     56     })
     57 }
     58 
     59 #[tokio::test]
     60 async fn identity_and_caps_report_the_actual_configuration() {
     61     let local = signer(FIXTURE_ALICE.secret_key_hex);
     62     let state = local.provider_state().await.unwrap();
     63     assert_eq!(state.identity(), local.public_key());
     64     assert_eq!(state.encryption(), PrivateCryptoCapability::Unavailable);
     65     assert_eq!(
     66         state.decryption(),
     67         if cfg!(any(feature = "nip17", feature = "private_ingress")) {
     68             PrivateCryptoCapability::Nip44V2
     69         } else {
     70             PrivateCryptoCapability::Unavailable
     71         }
     72     );
     73     assert_eq!(state.signing_replay(), ReplayCapability::LocalReplaySafe);
     74     let peer = signer(FIXTURE_BOB.secret_key_hex).public_key();
     75     assert_eq!(
     76         local
     77             .encrypt_private(
     78                 call(&local),
     79                 peer,
     80                 PrivateText::new("private question").unwrap()
     81             )
     82             .await
     83             .unwrap_err(),
     84         ProviderError::CapabilityUnavailable
     85     );
     86     let local = local.with_nonce_source(nonce_source(false));
     87     assert_eq!(
     88         local.provider_state().await.unwrap().encryption(),
     89         if cfg!(any(feature = "nip17", feature = "private_ingress")) {
     90             PrivateCryptoCapability::Nip44V2
     91         } else {
     92             PrivateCryptoCapability::Unavailable
     93         }
     94     );
     95     if !cfg!(any(feature = "nip17", feature = "private_ingress")) {
     96         let encoded = PrivateCiphertext::parse(&"A".repeat(132)).unwrap();
     97         assert_eq!(
     98             local
     99                 .decrypt_private(call(&local), peer, encoded)
    100                 .await
    101                 .unwrap_err(),
    102             ProviderError::CapabilityUnavailable
    103         );
    104     }
    105 }
    106 
    107 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    108 #[tokio::test]
    109 async fn exact_primary_vector_and_both_participant_directions() {
    110     let vector: serde_json::Value = serde_json::from_str(include_str!(
    111         "../../../tests/fixtures/nip44_provider.v1.json"
    112     ))
    113     .unwrap();
    114     let encoded_nonce = vector["nonce"].as_str().unwrap();
    115     assert_eq!(encoded_nonce.len(), 64);
    116     let mut nonce_bytes = [0; 32];
    117     for (index, byte) in nonce_bytes.iter_mut().enumerate() {
    118         *byte = u8::from_str_radix(&encoded_nonce[index * 2..index * 2 + 2], 16).unwrap();
    119     }
    120     let nonce = Shared::new(FixedNonce {
    121         calls: AtomicUsize::new(0),
    122         fail: false,
    123         nonce: nonce_bytes,
    124     });
    125     let alice = signer(vector["secret_a"].as_str().unwrap()).with_nonce_source(nonce.clone());
    126     let bob = signer(vector["secret_b"].as_str().unwrap()).with_nonce_source(nonce_source(false));
    127     let encrypted = alice
    128         .encrypt_private(
    129             call(&alice),
    130             bob.public_key(),
    131             PrivateText::new(vector["plaintext"].as_str().unwrap()).unwrap(),
    132         )
    133         .await
    134         .unwrap();
    135     assert_eq!(encrypted.as_str(), vector["ciphertext"].as_str().unwrap());
    136     assert_eq!(nonce.calls.load(Ordering::SeqCst), 1);
    137     let opened = bob
    138         .decrypt_private(call(&bob), alice.public_key(), encrypted)
    139         .await
    140         .unwrap();
    141     assert_eq!(opened.expose(), vector["plaintext"].as_str().unwrap());
    142     let reply = bob
    143         .encrypt_private(
    144             call(&bob),
    145             alice.public_key(),
    146             PrivateText::new("fresh tomatoes — pickup tomorrow").unwrap(),
    147         )
    148         .await
    149         .unwrap();
    150     assert_eq!(
    151         alice
    152             .decrypt_private(call(&alice), bob.public_key(), reply)
    153             .await
    154             .unwrap()
    155             .expose(),
    156         "fresh tomatoes — pickup tomorrow"
    157     );
    158 }
    159 
    160 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    161 #[tokio::test]
    162 async fn tampering_foreign_key_and_unsupported_version_remain_distinct() {
    163     use base64::Engine;
    164     let alice = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(nonce_source(false));
    165     let bob = signer(FIXTURE_BOB.secret_key_hex);
    166     let carol = signer(FIXTURE_CAROL.secret_key_hex);
    167     let encrypted = alice
    168         .encrypt_private(
    169             call(&alice),
    170             bob.public_key(),
    171             PrivateText::new("private food inquiry").unwrap(),
    172         )
    173         .await
    174         .unwrap();
    175     let raw = base64::engine::general_purpose::STANDARD
    176         .decode(encrypted.as_str())
    177         .unwrap();
    178     assert_eq!(
    179         bob.decrypt_private(
    180             call(&bob),
    181             carol.public_key(),
    182             PrivateCiphertext::parse(encrypted.as_str()).unwrap()
    183         )
    184         .await
    185         .unwrap_err(),
    186         ProviderError::AuthenticationFailed
    187     );
    188     let mut damaged = raw.clone();
    189     *damaged.last_mut().unwrap() ^= 1;
    190     let encoded = base64::engine::general_purpose::STANDARD.encode(damaged);
    191     assert_eq!(
    192         bob.decrypt_private(
    193             call(&bob),
    194             alice.public_key(),
    195             PrivateCiphertext::parse(&encoded).unwrap()
    196         )
    197         .await
    198         .unwrap_err(),
    199         ProviderError::AuthenticationFailed
    200     );
    201     let mut future = raw;
    202     future[0] = 3;
    203     let encoded = base64::engine::general_purpose::STANDARD.encode(future);
    204     assert_eq!(
    205         bob.decrypt_private(
    206             call(&bob),
    207             alice.public_key(),
    208             PrivateCiphertext::parse(&encoded).unwrap()
    209         )
    210         .await
    211         .unwrap_err(),
    212         ProviderError::UnsupportedVersion
    213     );
    214 }
    215 
    216 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    217 #[tokio::test]
    218 async fn identity_cancel_deadline_and_capacity_refuse_before_nonce_use() {
    219     let entropy = nonce_source(false);
    220     let alice = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(entropy.clone());
    221     let bob = signer(FIXTURE_BOB.secret_key_hex);
    222     let mismatched = ProviderCall::new(
    223         bob.public_key(),
    224         NonZeroU64::new(200).unwrap(),
    225         CancellationSignal::new(),
    226     );
    227     assert_eq!(
    228         alice
    229             .encrypt_private(
    230                 mismatched,
    231                 bob.public_key(),
    232                 PrivateText::new("private").unwrap()
    233             )
    234             .await
    235             .unwrap_err(),
    236         ProviderError::IdentityChanged
    237     );
    238     let cancelled = CancellationSignal::new();
    239     cancelled.cancel();
    240     let context = ProviderCall::new(alice.public_key(), NonZeroU64::new(200).unwrap(), cancelled);
    241     assert_eq!(
    242         alice
    243             .encrypt_private(
    244                 context,
    245                 bob.public_key(),
    246                 PrivateText::new("private").unwrap()
    247             )
    248             .await
    249             .unwrap_err(),
    250         ProviderError::Cancelled
    251     );
    252     let expired = ProviderCall::new(
    253         alice.public_key(),
    254         NonZeroU64::new(100).unwrap(),
    255         CancellationSignal::new(),
    256     );
    257     assert_eq!(
    258         alice
    259             .encrypt_private(
    260                 expired,
    261                 bob.public_key(),
    262                 PrivateText::new("private").unwrap()
    263             )
    264             .await
    265             .unwrap_err(),
    266         ProviderError::DeadlineExceeded
    267     );
    268     let oversized = "x".repeat(PRIVATE_CRYPTO_MAX_BYTES);
    269     assert_eq!(
    270         alice
    271             .encrypt_private(
    272                 call(&alice),
    273                 bob.public_key(),
    274                 PrivateText::new(&oversized).unwrap()
    275             )
    276             .await
    277             .unwrap_err(),
    278         ProviderError::LimitExceeded
    279     );
    280     assert_eq!(entropy.calls.load(Ordering::SeqCst), 0);
    281     let failed = LocalSigner::with_clock(
    282         parse_secret_key(FIXTURE_ALICE.secret_key_hex).unwrap(),
    283         unavailable_clock,
    284     )
    285     .unwrap()
    286     .with_nonce_source(entropy.clone());
    287     assert_eq!(
    288         failed
    289             .encrypt_private(
    290                 call(&failed),
    291                 bob.public_key(),
    292                 PrivateText::new("private").unwrap()
    293             )
    294             .await
    295             .unwrap_err(),
    296         ProviderError::ProviderFailure
    297     );
    298     assert_eq!(entropy.calls.load(Ordering::SeqCst), 0);
    299 }
    300 
    301 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    302 #[tokio::test]
    303 async fn bounded_full_rumor_and_entropy_failure_execute_the_real_codec() {
    304     let entropy = nonce_source(false);
    305     let alice = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(entropy.clone());
    306     let bob = signer(FIXTURE_BOB.secret_key_hex);
    307     for length in [1, 32, 33, 256, 257, 4096, 16384, 24576] {
    308         let text = "a".repeat(length);
    309         let encrypted = alice
    310             .encrypt_private(
    311                 call(&alice),
    312                 bob.public_key(),
    313                 PrivateText::new(&text).unwrap(),
    314             )
    315             .await
    316             .unwrap();
    317         assert!(encrypted.as_str().len() <= PRIVATE_CRYPTO_MAX_BYTES);
    318         assert_eq!(
    319             bob.decrypt_private(call(&bob), alice.public_key(), encrypted)
    320                 .await
    321                 .unwrap()
    322                 .expose(),
    323             text
    324         );
    325     }
    326     let failed_source = nonce_source(true);
    327     let failed = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(failed_source.clone());
    328     assert_eq!(
    329         failed
    330             .encrypt_private(
    331                 call(&failed),
    332                 bob.public_key(),
    333                 PrivateText::new("private").unwrap()
    334             )
    335             .await
    336             .unwrap_err(),
    337         ProviderError::CapabilityUnavailable
    338     );
    339     assert_eq!(failed_source.calls.load(Ordering::SeqCst), 1);
    340 }
    341 
    342 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    343 #[tokio::test]
    344 async fn malformed_payloads_and_encoded_size_refuse_without_entropy() {
    345     let entropy = nonce_source(false);
    346     let alice = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(entropy.clone());
    347     let bob = signer(FIXTURE_BOB.secret_key_hex);
    348     // This fits the codec's plaintext bound, but its encoded output would
    349     // exceed the independent public-event boundary.
    350     assert_eq!(
    351         alice
    352             .encrypt_private(
    353                 call(&alice),
    354                 bob.public_key(),
    355                 PrivateText::new(&"x".repeat(60_000)).unwrap(),
    356             )
    357             .await
    358             .unwrap_err(),
    359         ProviderError::LimitExceeded
    360     );
    361     for encoded in ["=".repeat(132), "A".repeat(130) + "=="] {
    362         assert_eq!(
    363             bob.decrypt_private(
    364                 call(&bob),
    365                 alice.public_key(),
    366                 PrivateCiphertext::parse(&encoded).unwrap(),
    367             )
    368             .await
    369             .unwrap_err(),
    370             ProviderError::InvalidInput
    371         );
    372     }
    373     assert_eq!(entropy.calls.load(Ordering::SeqCst), 0);
    374 }
    375 
    376 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    377 #[test]
    378 fn codec_nonce_consumption_is_exact_and_has_no_rng_quality_claim() {
    379     use nostr::secp256k1::rand::RngCore;
    380     let mut source = NonceTranscript {
    381         nonce: [7; 32],
    382         consumed: false,
    383         invalid: false,
    384     };
    385     let mut bytes = [0; 32];
    386     source.try_fill_bytes(&mut bytes).unwrap();
    387     assert_eq!(bytes, [7; 32]);
    388     assert!(source.try_fill_bytes(&mut bytes).is_err());
    389     for length in [0, 1, 31, 33, 64] {
    390         let mut source = NonceTranscript {
    391             nonce: [7; 32],
    392             consumed: false,
    393             invalid: false,
    394         };
    395         source.fill_bytes(&mut vec![0; length]);
    396         assert!(source.invalid);
    397     }
    398     let mut source = NonceTranscript {
    399         nonce: [7; 32],
    400         consumed: false,
    401         invalid: false,
    402     };
    403     assert_eq!(source.next_u32(), 0);
    404     assert_eq!(source.next_u64(), 0);
    405     assert!(source.invalid);
    406 }