heliosdb-nano 3.23.2

PostgreSQL-compatible embedded database with TDE + ZKE encryption, HNSW vector search, Product Quantization, git-like branching, time-travel queries, materialized views, row-level security, and 50+ enterprise features
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Zero-Knowledge Encryption (ZKE) implementation
//!
//! Zero-Knowledge Encryption ensures that encryption keys **never leave the client**.
//! The server only ever sees encrypted data and cannot decrypt it without the client
//! providing the key for each request.
//!
//! # Architecture
//!
//! ```text
//! Client                              Server
//!   |                                   |
//!   | key = derive(password, salt)      |
//!   | encrypted_query = encrypt(sql)    |
//!   |                                   |
//!   |--- encrypted_query + key_hash --->|
//!   |                                   |
//!   |                    Validate key_hash
//!   |                    Execute on encrypted data
//!   |                    Encrypt response
//!   |                                   |
//!   |<--- encrypted_response -----------|
//!   |                                   |
//!   | plaintext = decrypt(response)     |
//! ```
//!
//! # Security Properties
//!
//! - **Client-Side Encryption**: All data encrypted before transmission
//! - **Per-Request Keys**: Keys provided with each request, never stored
//! - **Key Hash Validation**: Server validates key via SHA-256 hash
//! - **Nonce-Based Replay Protection**: Each request has unique nonce
//! - **Memory Zeroization**: Keys zeroed immediately after use
//!
//! # Example
//!
//! ```rust,ignore
//! use heliosdb_nano::crypto::{ZeroKnowledgeSession, ZkeKeyDerivation};
//!
//! // Client-side: Derive separate keys for auth and encryption
//! let keys = ZkeKeyDerivation::derive_keys("password", "user@example.com")?;
//!
//! // Create session with encryption key (deref Zeroizing wrapper)
//! let session = ZeroKnowledgeSession::new(*keys.encryption_key)?;
//!
//! // Encrypt data before sending
//! let encrypted = session.encrypt(b"SELECT * FROM users")?;
//!
//! // Server validates and processes, returns encrypted_response...
//! // Client decrypts response
//! let decrypted = session.decrypt(&encrypted)?;
//! # Ok::<(), heliosdb_nano::Error>(())
//! ```

use crate::crypto::{derive_key_from_password, encrypt, decrypt, EncryptionKey};
use crate::{Error, Result};
use sha2::{Sha256, Digest};
use std::collections::HashSet;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use zeroize::Zeroizing;

/// Zero-Knowledge Encryption mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ZkeMode {
    /// Full zero-knowledge: server never sees plaintext
    /// - Client encrypts data before sending
    /// - Server stores only ciphertext
    /// - No server-side search capabilities
    Full,

    /// Hybrid mode: metadata unencrypted, data encrypted
    /// - Table/column names visible to server
    /// - Row data encrypted
    /// - Basic metadata search possible
    Hybrid,

    /// Per-request decryption: key provided per-request
    /// - Server temporarily decrypts for query execution
    /// - Key immediately zeroized after use
    /// - Full SQL capabilities
    PerRequest,
}

impl Default for ZkeMode {
    fn default() -> Self {
        Self::PerRequest
    }
}

/// Zero-Knowledge Encryption configuration
#[derive(Debug, Clone)]
pub struct ZkeConfig {
    /// ZKE mode
    pub mode: ZkeMode,
    /// Require key hash validation
    pub require_key_hash: bool,
    /// Enable replay protection
    pub replay_protection: bool,
    /// Nonce validity window (seconds)
    pub nonce_window_secs: u64,
    /// Maximum cached nonces (for replay protection)
    pub max_cached_nonces: usize,
}

impl Default for ZkeConfig {
    fn default() -> Self {
        Self {
            mode: ZkeMode::PerRequest,
            require_key_hash: true,
            replay_protection: true,
            nonce_window_secs: 300, // 5 minutes
            max_cached_nonces: 10000,
        }
    }
}

/// Derived keys for Zero-Knowledge operations
///
/// Separates authentication from encryption:
/// - `auth_key`: Used for login/authentication (can be sent to server as hash)
/// - `encryption_key`: Used for data encryption (NEVER sent to server)
#[derive(Clone)]
pub struct ZkeDerivedKeys {
    /// Authentication key (for server authentication)
    pub auth_key: Zeroizing<EncryptionKey>,
    /// Encryption key (never leaves client)
    pub encryption_key: Zeroizing<EncryptionKey>,
    /// Key hash for validation
    pub encryption_key_hash: [u8; 32],
}

impl ZkeDerivedKeys {
    /// Get the encryption key hash as hex string
    pub fn key_hash_hex(&self) -> String {
        hex::encode(self.encryption_key_hash)
    }
}

/// Client-side key derivation for ZKE
pub struct ZkeKeyDerivation;

impl ZkeKeyDerivation {
    /// Derive separate authentication and encryption keys from password
    ///
    /// This implements the recommended pattern where:
    /// - Auth key: Derived with "auth" salt suffix (sent to server for login)
    /// - Encryption key: Derived with "encrypt" salt suffix (NEVER sent to server)
    ///
    /// # Arguments
    ///
    /// * `password` - User's password
    /// * `identifier` - Unique identifier (email, username, etc.) used as salt base
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use heliosdb_nano::crypto::ZkeKeyDerivation;
    ///
    /// let keys = ZkeKeyDerivation::derive_keys("my_password", "user@example.com")?;
    /// // keys.auth_key - for authentication
    /// // keys.encryption_key - for encryption (never send to server!)
    /// # Ok::<(), heliosdb_nano::Error>(())
    /// ```
    pub fn derive_keys(password: &str, identifier: &str) -> Result<ZkeDerivedKeys> {
        // Create deterministic salt from identifier
        let base_salt = Self::create_salt(identifier);

        // Derive auth key (salt + "auth")
        let mut auth_salt = base_salt.clone();
        auth_salt.extend_from_slice(b"auth");
        let auth_key = derive_key_from_password(password, &auth_salt)?;

        // Derive encryption key (salt + "encrypt")
        let mut encrypt_salt = base_salt;
        encrypt_salt.extend_from_slice(b"encrypt");
        let encryption_key = derive_key_from_password(password, &encrypt_salt)?;

        // Compute key hash for validation
        let encryption_key_hash = Self::compute_key_hash(&encryption_key);

        Ok(ZkeDerivedKeys {
            auth_key: Zeroizing::new(auth_key),
            encryption_key: Zeroizing::new(encryption_key),
            encryption_key_hash,
        })
    }

    /// Create salt from identifier using SHA-256
    fn create_salt(identifier: &str) -> Vec<u8> {
        let mut hasher = Sha256::new();
        hasher.update(identifier.as_bytes());
        hasher.update(b"heliosdb.zke.salt");
        hasher.finalize().to_vec()
    }

    /// Compute SHA-256 hash of encryption key
    pub fn compute_key_hash(key: &EncryptionKey) -> [u8; 32] {
        let mut hasher = Sha256::new();
        hasher.update(key);
        let result = hasher.finalize();
        let mut hash = [0u8; 32];
        hash.copy_from_slice(&result);
        hash
    }
}

/// Per-request Zero-Knowledge session
///
/// Holds the encryption key for a single request/session.
/// Key is automatically zeroed when session is dropped.
pub struct ZeroKnowledgeSession {
    /// Encryption key (zeroed on drop)
    key: Zeroizing<EncryptionKey>,
    /// Key hash for validation
    key_hash: [u8; 32],
    /// Creation timestamp
    created_at: Instant,
    /// Request nonce (for replay protection)
    nonce: Option<[u8; 16]>,
}

impl ZeroKnowledgeSession {
    /// Create a new ZKE session with the provided key
    pub fn new(key: EncryptionKey) -> Result<Self> {
        let key_hash = ZkeKeyDerivation::compute_key_hash(&key);

        Ok(Self {
            key: Zeroizing::new(key),
            key_hash,
            created_at: Instant::now(),
            nonce: None,
        })
    }

    /// Create session from hex-encoded key
    pub fn from_hex_key(hex_key: &str) -> Result<Self> {
        let key = Self::parse_hex_key(hex_key)?;
        Self::new(key)
    }

    /// Create session from derived keys
    pub fn from_derived_keys(keys: &ZkeDerivedKeys) -> Result<Self> {
        Ok(Self {
            key: keys.encryption_key.clone(),
            key_hash: keys.encryption_key_hash,
            created_at: Instant::now(),
            nonce: None,
        })
    }

    /// Set request nonce for replay protection
    pub fn with_nonce(mut self, nonce: [u8; 16]) -> Self {
        self.nonce = Some(nonce);
        self
    }

    /// Generate and set a random nonce
    pub fn with_random_nonce(mut self) -> Self {
        self.nonce = Some(rand::random());
        self
    }

    /// Get the request nonce
    pub fn nonce(&self) -> Option<&[u8; 16]> {
        self.nonce.as_ref()
    }

    /// Get nonce as hex string
    pub fn nonce_hex(&self) -> Option<String> {
        self.nonce.map(|n| hex::encode(n))
    }

    /// Encrypt data using the session key
    pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
        encrypt(&self.key, plaintext)
    }

    /// Decrypt data using the session key
    pub fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>> {
        decrypt(&self.key, ciphertext)
    }

    /// Get the encryption key (for internal use)
    pub fn key(&self) -> &EncryptionKey {
        &self.key
    }

    /// Get the key hash
    pub fn key_hash(&self) -> &[u8; 32] {
        &self.key_hash
    }

    /// Get key hash as hex string
    pub fn key_hash_hex(&self) -> String {
        hex::encode(self.key_hash)
    }

    /// Validate that provided hash matches the session key
    pub fn validate_key_hash(&self, expected_hash: &[u8; 32]) -> bool {
        // Constant-time comparison to prevent timing attacks
        constant_time_compare(&self.key_hash, expected_hash)
    }

    /// Validate hex-encoded hash
    pub fn validate_key_hash_hex(&self, expected_hash_hex: &str) -> Result<bool> {
        let expected = hex::decode(expected_hash_hex)
            .map_err(|e| Error::encryption(format!("Invalid hash hex: {}", e)))?;

        if expected.len() != 32 {
            return Err(Error::encryption("Hash must be 32 bytes"));
        }

        let mut hash = [0u8; 32];
        hash.copy_from_slice(&expected);

        Ok(self.validate_key_hash(&hash))
    }

    /// Session age in seconds
    pub fn age_secs(&self) -> u64 {
        self.created_at.elapsed().as_secs()
    }

    /// Parse hex-encoded key
    fn parse_hex_key(hex_str: &str) -> Result<EncryptionKey> {
        let hex_str = hex_str.trim();

        if hex_str.len() != 64 {
            return Err(Error::encryption(format!(
                "Hex key must be 64 characters (32 bytes), got {}",
                hex_str.len()
            )));
        }

        let mut key = [0u8; 32];
        for (i, chunk) in hex_str.as_bytes().chunks(2).enumerate() {
            let hex_byte = std::str::from_utf8(chunk)
                .map_err(|_| Error::encryption("Invalid hex string"))?;
            let dest = key.get_mut(i).ok_or_else(|| Error::encryption("Key index out of bounds"))?;
            *dest = u8::from_str_radix(hex_byte, 16)
                .map_err(|_| Error::encryption(format!("Invalid hex byte: {}", hex_byte)))?;
        }

        Ok(key)
    }
}

/// Constant-time comparison to prevent timing attacks
fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }

    let mut result = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        result |= x ^ y;
    }
    result == 0
}

/// Nonce tracker for replay protection
pub struct NonceTracker {
    /// Seen nonces with timestamps
    nonces: RwLock<HashSet<[u8; 16]>>,
    /// Nonce expiration timestamps
    expiry: RwLock<Vec<(Instant, [u8; 16])>>,
    /// Validity window
    window: Duration,
    /// Maximum cached nonces
    max_nonces: usize,
}

impl NonceTracker {
    /// Create a new nonce tracker
    pub fn new(window_secs: u64, max_nonces: usize) -> Self {
        Self {
            nonces: RwLock::new(HashSet::new()),
            expiry: RwLock::new(Vec::new()),
            window: Duration::from_secs(window_secs),
            max_nonces,
        }
    }

    /// Check if nonce is valid (not seen before)
    /// Returns true if valid, false if replay detected
    pub fn check_and_record(&self, nonce: &[u8; 16]) -> bool {
        // Clean up expired nonces first
        self.cleanup_expired();

        let mut nonces = self.nonces.write().unwrap_or_else(|e| e.into_inner());
        let mut expiry = self.expiry.write().unwrap_or_else(|e| e.into_inner());

        // Check if at capacity
        if nonces.len() >= self.max_nonces {
            // Force cleanup of oldest entries
            self.force_cleanup(&mut nonces, &mut expiry);
        }

        // Check if nonce was already seen
        if nonces.contains(nonce) {
            return false; // Replay attack!
        }

        // Record nonce
        nonces.insert(*nonce);
        expiry.push((Instant::now(), *nonce));

        true
    }

    /// Clean up expired nonces
    fn cleanup_expired(&self) {
        let now = Instant::now();
        let mut nonces = self.nonces.write().unwrap_or_else(|e| e.into_inner());
        let mut expiry = self.expiry.write().unwrap_or_else(|e| e.into_inner());

        expiry.retain(|(created, nonce)| {
            if now.duration_since(*created) > self.window {
                nonces.remove(nonce);
                false
            } else {
                true
            }
        });
    }

    /// Force cleanup when at capacity
    fn force_cleanup(
        &self,
        nonces: &mut HashSet<[u8; 16]>,
        expiry: &mut Vec<(Instant, [u8; 16])>,
    ) {
        // Remove oldest 10%
        let remove_count = self.max_nonces / 10;
        for _ in 0..remove_count {
            if let Some((_, nonce)) = expiry.first() {
                nonces.remove(nonce);
            }
            if !expiry.is_empty() {
                expiry.remove(0);
            }
        }
    }

    /// Get number of tracked nonces
    pub fn len(&self) -> usize {
        self.nonces.read().unwrap_or_else(|e| e.into_inner()).len()
    }

    /// Check if tracker is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Default for NonceTracker {
    fn default() -> Self {
        Self::new(300, 10000) // 5 minute window, 10k max
    }
}

/// Request timestamp validator
pub struct TimestampValidator {
    /// Maximum allowed clock skew (seconds)
    max_skew_secs: u64,
}

impl TimestampValidator {
    /// Create with specified max skew
    pub fn new(max_skew_secs: u64) -> Self {
        Self { max_skew_secs }
    }

    /// Validate request timestamp is within acceptable range
    pub fn validate(&self, request_timestamp_secs: u64) -> bool {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        let diff = request_timestamp_secs.abs_diff(now);

        diff <= self.max_skew_secs
    }

    /// Get current timestamp
    pub fn current_timestamp() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    }
}

impl Default for TimestampValidator {
    fn default() -> Self {
        Self::new(300) // 5 minute tolerance
    }
}

/// ZKE request context (for server-side validation)
pub struct ZkeRequestContext {
    /// Session with encryption key
    session: ZeroKnowledgeSession,
    /// Nonce tracker
    nonce_tracker: Arc<NonceTracker>,
    /// Timestamp validator
    timestamp_validator: TimestampValidator,
    /// Configuration
    config: ZkeConfig,
}

impl ZkeRequestContext {
    /// Create new request context
    pub fn new(
        session: ZeroKnowledgeSession,
        nonce_tracker: Arc<NonceTracker>,
        config: ZkeConfig,
    ) -> Self {
        Self {
            session,
            nonce_tracker,
            timestamp_validator: TimestampValidator::new(config.nonce_window_secs),
            config,
        }
    }

    /// Validate the request
    pub fn validate(
        &self,
        expected_key_hash: Option<&str>,
        nonce: Option<&[u8; 16]>,
        timestamp: Option<u64>,
    ) -> Result<()> {
        // Validate key hash if required
        if self.config.require_key_hash {
            if let Some(hash) = expected_key_hash {
                if !self.session.validate_key_hash_hex(hash)? {
                    return Err(Error::encryption("Key hash validation failed"));
                }
            } else {
                return Err(Error::encryption("Key hash required but not provided"));
            }
        }

        // Validate replay protection
        if self.config.replay_protection {
            // Check nonce
            if let Some(n) = nonce {
                if !self.nonce_tracker.check_and_record(n) {
                    return Err(Error::encryption("Replay attack detected: nonce already used"));
                }
            } else {
                return Err(Error::encryption("Nonce required for replay protection"));
            }

            // Check timestamp
            if let Some(ts) = timestamp {
                if !self.timestamp_validator.validate(ts) {
                    return Err(Error::encryption("Request timestamp out of valid range"));
                }
            }
        }

        Ok(())
    }

    /// Get the session
    pub fn session(&self) -> &ZeroKnowledgeSession {
        &self.session
    }

    /// Encrypt data
    pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
        self.session.encrypt(plaintext)
    }

    /// Decrypt data
    pub fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>> {
        self.session.decrypt(ciphertext)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_derive_keys() {
        let keys = ZkeKeyDerivation::derive_keys("password123", "user@example.com")
            .expect("Key derivation failed");

        assert_eq!(keys.auth_key.len(), 32);
        assert_eq!(keys.encryption_key.len(), 32);
        assert_eq!(keys.encryption_key_hash.len(), 32);

        // Auth and encryption keys should be different
        assert_ne!(*keys.auth_key, *keys.encryption_key);
    }

    #[test]
    fn test_derive_keys_deterministic() {
        let keys1 = ZkeKeyDerivation::derive_keys("password", "user@test.com").unwrap();
        let keys2 = ZkeKeyDerivation::derive_keys("password", "user@test.com").unwrap();

        // Same inputs should produce same outputs
        assert_eq!(*keys1.auth_key, *keys2.auth_key);
        assert_eq!(*keys1.encryption_key, *keys2.encryption_key);
        assert_eq!(keys1.encryption_key_hash, keys2.encryption_key_hash);
    }

    #[test]
    fn test_derive_keys_different_passwords() {
        let keys1 = ZkeKeyDerivation::derive_keys("password1", "user@test.com").unwrap();
        let keys2 = ZkeKeyDerivation::derive_keys("password2", "user@test.com").unwrap();

        // Different passwords should produce different keys
        assert_ne!(*keys1.encryption_key, *keys2.encryption_key);
    }

    #[test]
    fn test_zke_session_encrypt_decrypt() {
        let keys = ZkeKeyDerivation::derive_keys("test", "test@test.com").unwrap();
        let session = ZeroKnowledgeSession::from_derived_keys(&keys).unwrap();

        let plaintext = b"SELECT * FROM secret_data";
        let ciphertext = session.encrypt(plaintext).unwrap();
        let decrypted = session.decrypt(&ciphertext).unwrap();

        assert_eq!(plaintext, &decrypted[..]);
    }

    #[test]
    fn test_zke_session_from_hex() {
        let hex_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        let session = ZeroKnowledgeSession::from_hex_key(hex_key).unwrap();

        let plaintext = b"test data";
        let ciphertext = session.encrypt(plaintext).unwrap();
        let decrypted = session.decrypt(&ciphertext).unwrap();

        assert_eq!(plaintext, &decrypted[..]);
    }

    #[test]
    fn test_key_hash_validation() {
        let keys = ZkeKeyDerivation::derive_keys("test", "user").unwrap();
        let session = ZeroKnowledgeSession::from_derived_keys(&keys).unwrap();

        // Valid hash
        assert!(session.validate_key_hash(&keys.encryption_key_hash));

        // Invalid hash
        let mut wrong_hash = keys.encryption_key_hash;
        wrong_hash[0] ^= 0xFF;
        assert!(!session.validate_key_hash(&wrong_hash));
    }

    #[test]
    fn test_key_hash_hex_validation() {
        let keys = ZkeKeyDerivation::derive_keys("test", "user").unwrap();
        let session = ZeroKnowledgeSession::from_derived_keys(&keys).unwrap();

        let hash_hex = keys.key_hash_hex();
        assert!(session.validate_key_hash_hex(&hash_hex).unwrap());
    }

    #[test]
    fn test_nonce_tracker() {
        let tracker = NonceTracker::new(300, 100);

        let nonce1: [u8; 16] = rand::random();
        let nonce2: [u8; 16] = rand::random();

        // First use should succeed
        assert!(tracker.check_and_record(&nonce1));
        assert!(tracker.check_and_record(&nonce2));

        // Replay should fail
        assert!(!tracker.check_and_record(&nonce1));
        assert!(!tracker.check_and_record(&nonce2));
    }

    #[test]
    fn test_timestamp_validator() {
        let validator = TimestampValidator::new(60); // 1 minute tolerance

        let now = TimestampValidator::current_timestamp();

        // Current time should be valid
        assert!(validator.validate(now));

        // 30 seconds ago should be valid
        assert!(validator.validate(now - 30));

        // 30 seconds in future should be valid
        assert!(validator.validate(now + 30));

        // 2 minutes ago should be invalid
        assert!(!validator.validate(now - 120));

        // 2 minutes in future should be invalid
        assert!(!validator.validate(now + 120));
    }

    #[test]
    fn test_session_with_nonce() {
        let key: EncryptionKey = rand::random();
        let session = ZeroKnowledgeSession::new(key)
            .unwrap()
            .with_random_nonce();

        assert!(session.nonce().is_some());
        assert!(session.nonce_hex().is_some());
    }

    #[test]
    fn test_request_context_validation() {
        let keys = ZkeKeyDerivation::derive_keys("test", "user").unwrap();
        let session = ZeroKnowledgeSession::from_derived_keys(&keys)
            .unwrap()
            .with_random_nonce();

        let nonce = *session.nonce().unwrap();
        let nonce_tracker = Arc::new(NonceTracker::default());
        let config = ZkeConfig::default();

        let context = ZkeRequestContext::new(session, nonce_tracker, config);

        let timestamp = TimestampValidator::current_timestamp();
        let hash_hex = keys.key_hash_hex();

        // Valid request
        assert!(context.validate(Some(&hash_hex), Some(&nonce), Some(timestamp)).is_ok());
    }

    #[test]
    fn test_constant_time_compare() {
        let a = [1u8, 2, 3, 4];
        let b = [1u8, 2, 3, 4];
        let c = [1u8, 2, 3, 5];

        assert!(constant_time_compare(&a, &b));
        assert!(!constant_time_compare(&a, &c));
    }
}