lib-q-random 0.0.3

Unified secure random number generation for libQ post-quantum cryptography library
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
//! Custom Entropy Source System for `no_std` and WASM Environments
//!
//! This module provides a secure, callback-based entropy source system that allows
//! developers to plug in custom entropy sources for `no_std` and WASM environments.
//! The system uses function pointers and thread-local storage to avoid global state
//! while maintaining security and performance.

use core::sync::atomic::{
    AtomicPtr,
    Ordering,
};
use core::{
    fmt,
    ptr,
};

use crate::{
    Error,
    Result,
};

/// Function pointer type for custom entropy sources
///
/// This function should fill the provided buffer with cryptographically secure
/// random bytes. The function must be thread-safe and should not block indefinitely.
///
/// # Arguments
///
/// * `dest` - Buffer to fill with random bytes
/// * `len` - Number of bytes to generate
/// * `context` - Optional context data passed to the entropy source
///
/// # Returns
///
/// Returns `Ok(())` on success, or an error if entropy generation fails.
///
/// # Safety
///
/// The `dest` pointer must be valid for `len` bytes and must not be null.
/// The function must not cause undefined behavior.
pub type EntropyCallback = unsafe extern "C" fn(dest: *mut u8, len: usize, context: *mut u8) -> i32;

/// Context data for entropy callbacks
///
/// This structure can be used to pass additional context to entropy callbacks,
/// such as user data or configuration.
#[derive(Debug, Clone, Copy)]
pub struct EntropyContext {
    /// User-defined context data
    pub user_data: *mut u8,
    /// Context size in bytes
    pub size: usize,
}

impl EntropyContext {
    /// Create a new entropy context
    ///
    /// # Arguments
    ///
    /// * `user_data` - User-defined context data
    /// * `size` - Size of the context data in bytes
    ///
    /// # Safety
    ///
    /// The `user_data` pointer must be valid for `size` bytes if `size > 0`.
    pub const unsafe fn new(user_data: *mut u8, size: usize) -> Self {
        Self { user_data, size }
    }

    /// Create an empty entropy context
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            user_data: ptr::null_mut(),
            size: 0,
        }
    }
}

/// Entropy source quality levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum EntropyQuality {
    /// Hardware-based entropy source (highest quality)
    Hardware,
    /// OS-provided entropy source
    Os,
    /// User-provided entropy source
    User,
    /// Deterministic source (lowest quality, testing only)
    Deterministic,
}

impl EntropyQuality {
    /// Get the numeric quality value (0.0 to 1.0)
    #[must_use]
    pub fn as_f64(self) -> f64 {
        match self {
            Self::Hardware => 1.0,
            Self::Os => 0.95,
            Self::User => 0.8,
            Self::Deterministic => 0.0,
        }
    }

    /// Check if this quality level is cryptographically secure
    #[must_use]
    pub fn is_secure(self) -> bool {
        matches!(self, Self::Hardware | Self::Os | Self::User)
    }
}

/// Custom entropy source configuration
#[derive(Debug, Clone)]
pub struct CustomEntropyConfig {
    /// Minimum entropy quality required
    pub min_quality: EntropyQuality,
    /// Maximum bytes per entropy call
    pub max_bytes_per_call: usize,
    /// Whether to validate entropy quality
    pub validate_quality: bool,
    /// Timeout for entropy generation (in some unit)
    pub timeout_ms: u32,
}

impl Default for CustomEntropyConfig {
    fn default() -> Self {
        Self {
            min_quality: EntropyQuality::User,
            max_bytes_per_call: 1024,
            validate_quality: true,
            timeout_ms: 1000,
        }
    }
}

/// Custom entropy source registration
///
/// This structure manages the registration of custom entropy sources
/// for the current thread.
#[derive(Debug)]
pub struct CustomEntropySource {
    /// Callback function for entropy generation
    pub callback: EntropyCallback,
    /// Context data for the callback
    pub context: EntropyContext,
    /// Quality level of this entropy source
    pub quality: EntropyQuality,
    /// Configuration for this entropy source
    pub config: CustomEntropyConfig,
    /// Source identifier
    pub source_id: &'static str,
}

impl CustomEntropySource {
    /// Create a new custom entropy source
    ///
    /// # Arguments
    ///
    /// * `callback` - Function to call for entropy generation
    /// * `context` - Context data for the callback
    /// * `quality` - Quality level of this entropy source
    /// * `config` - Configuration for this entropy source
    /// * `source_id` - Unique identifier for this source
    ///
    /// # Safety
    ///
    /// The `callback` function must be thread-safe and must not cause
    /// undefined behavior. The `context.user_data` must be valid for
    /// `context.size` bytes if `context.size > 0`.
    pub const unsafe fn new(
        callback: EntropyCallback,
        context: EntropyContext,
        quality: EntropyQuality,
        config: CustomEntropyConfig,
        source_id: &'static str,
    ) -> Self {
        Self {
            callback,
            context,
            quality,
            config,
            source_id,
        }
    }

    /// Get the callback function
    #[must_use]
    pub fn callback(&self) -> EntropyCallback {
        self.callback
    }

    /// Get the context data
    #[must_use]
    pub fn context(&self) -> EntropyContext {
        self.context
    }

    /// Get the quality level
    #[must_use]
    pub fn quality(&self) -> EntropyQuality {
        self.quality
    }

    /// Get the configuration
    #[must_use]
    pub fn config(&self) -> &CustomEntropyConfig {
        &self.config
    }

    /// Get the source identifier
    #[must_use]
    pub fn source_id(&self) -> &'static str {
        self.source_id
    }

    /// Generate entropy using this source
    ///
    /// # Arguments
    ///
    /// * `dest` - Buffer to fill with random bytes
    ///
    /// # Errors
    ///
    /// Returns an error if entropy generation fails or if the generated
    /// entropy doesn't meet quality requirements.
    pub fn generate_entropy(&self, dest: &mut [u8]) -> Result<()> {
        if dest.len() > self.config.max_bytes_per_call {
            return Err(Error::EntropySourceUnavailable {
                source: self.source_id,
                context: Some("requested bytes exceed maximum per call"),
            });
        }

        if !self.quality.is_secure() && self.config.validate_quality {
            return Err(Error::EntropyValidationFailed {
                reason: "entropy source quality too low",
                quality: self.quality.as_f64(),
                details: Some("deterministic sources not allowed in secure mode"),
            });
        }

        // Call the custom entropy function
        let result =
            unsafe { (self.callback)(dest.as_mut_ptr(), dest.len(), self.context.user_data) };

        if result == 0 {
            Ok(())
        } else {
            Err(Error::EntropySourceUnavailable {
                source: self.source_id,
                context: Some("custom entropy callback failed"),
            })
        }
    }
}

/// Thread-local entropy source registry
///
/// This structure manages custom entropy sources for the current thread.
/// It uses atomic operations to ensure thread safety.
pub struct ThreadEntropyRegistry {
    /// Currently registered entropy source
    source: AtomicPtr<CustomEntropySource>,
}

impl Default for ThreadEntropyRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl ThreadEntropyRegistry {
    /// Create a new thread entropy registry
    #[must_use]
    pub const fn new() -> Self {
        Self {
            source: AtomicPtr::new(ptr::null_mut()),
        }
    }

    /// Register a custom entropy source for this thread
    ///
    /// # Arguments
    ///
    /// * `source` - The custom entropy source to register
    ///
    /// # Safety
    ///
    /// The `source` must remain valid for the lifetime of the registry.
    /// The caller is responsible for ensuring the source is not dropped
    /// while registered.
    pub unsafe fn register(&self, source: *const CustomEntropySource) {
        self.source.store(source.cast_mut(), Ordering::Release);
    }

    /// Unregister the current entropy source
    pub fn unregister(&self) {
        self.source.store(ptr::null_mut(), Ordering::Release);
    }

    /// Get the currently registered entropy source
    ///
    /// # Returns
    ///
    /// Returns a reference to the registered entropy source, or `None`
    /// if no source is registered.
    ///
    /// # Safety
    ///
    /// The returned reference is only valid as long as the source remains
    /// registered and not dropped.
    pub unsafe fn get_source(&self) -> Option<&CustomEntropySource> {
        let ptr = self.source.load(Ordering::Acquire);
        if ptr.is_null() {
            None
        } else {
            unsafe { Some(&*ptr) }
        }
    }

    /// Generate entropy using the registered source
    ///
    /// # Arguments
    ///
    /// * `dest` - Buffer to fill with random bytes
    ///
    /// # Errors
    ///
    /// Returns an error if no source is registered or if entropy generation fails.
    pub fn generate_entropy(&self, dest: &mut [u8]) -> Result<()> {
        unsafe {
            if let Some(source) = self.get_source() {
                source.generate_entropy(dest)
            } else {
                Err(Error::EntropySourceUnavailable {
                    source: "thread_local",
                    context: Some("no custom entropy source registered"),
                })
            }
        }
    }
}

// Global thread-local registry
static THREAD_REGISTRY: ThreadEntropyRegistry = ThreadEntropyRegistry::new();

/// Register a custom entropy source for the current thread
///
/// # Arguments
///
/// * `source` - The custom entropy source to register
///
/// # Safety
///
/// The `source` must remain valid for the lifetime of the registration.
/// The caller is responsible for ensuring the source is not dropped
/// while registered.
pub unsafe fn register_custom_entropy_source(source: *const CustomEntropySource) {
    unsafe { THREAD_REGISTRY.register(source) };
}

/// Unregister the current custom entropy source
pub fn unregister_custom_entropy_source() {
    THREAD_REGISTRY.unregister();
}

/// Generate entropy using the registered custom source
///
/// # Arguments
///
/// * `dest` - Buffer to fill with random bytes
///
/// # Errors
///
/// Returns an error if no source is registered or if entropy generation fails.
pub fn generate_custom_entropy(dest: &mut [u8]) -> Result<()> {
    THREAD_REGISTRY.generate_entropy(dest)
}

/// Check if a custom entropy source is registered
pub fn has_custom_entropy_source() -> bool {
    unsafe { THREAD_REGISTRY.get_source().is_some() }
}

/// Get information about the registered entropy source
///
/// # Returns
///
/// Returns a tuple of (`source_id`, quality) if a source is registered.
pub fn get_entropy_source_info() -> Option<(&'static str, EntropyQuality)> {
    unsafe {
        THREAD_REGISTRY
            .get_source()
            .map(|source| (source.source_id(), source.quality()))
    }
}

impl fmt::Display for EntropyQuality {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Hardware => write!(f, "Hardware"),
            Self::Os => write!(f, "OS"),
            Self::User => write!(f, "User"),
            Self::Deterministic => write!(f, "Deterministic"),
        }
    }
}

impl fmt::Display for CustomEntropyConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "CustomEntropyConfig {{ min_quality: {}, max_bytes: {}, validate: {}, timeout: {}ms }}",
            self.min_quality, self.max_bytes_per_call, self.validate_quality, self.timeout_ms
        )
    }
}

impl fmt::Display for CustomEntropySource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "CustomEntropySource {{ id: {}, quality: {}, config: {} }}",
            self.source_id, self.quality, self.config
        )
    }
}

// CustomEntropySource is not an RNG itself, it's a source of entropy for RNGs

#[cfg(test)]
mod tests {
    #[cfg(feature = "alloc")]
    use alloc::format;

    use super::*;

    // Test entropy callback that generates predictable data
    #[allow(clippy::cast_possible_truncation)]
    unsafe extern "C" fn test_entropy_callback(
        dest: *mut u8,
        len: usize,
        _context: *mut u8,
    ) -> i32 {
        if dest.is_null() {
            return -1;
        }

        // Generate predictable test data (handle empty buffer case)
        for i in 0..len {
            unsafe {
                *dest.add(i) = (i as u8).wrapping_add(42);
            }
        }

        0
    }

    #[test]
    fn test_entropy_context_creation() {
        let context = EntropyContext::empty();
        assert!(context.user_data.is_null());
        assert_eq!(context.size, 0);

        let data = [1u8, 2, 3, 4];
        let context = unsafe { EntropyContext::new(data.as_ptr().cast_mut(), data.len()) };
        assert!(!context.user_data.is_null());
        assert_eq!(context.size, 4);
    }

    #[test]
    fn test_entropy_quality() {
        assert!(EntropyQuality::Hardware.is_secure());
        assert!(EntropyQuality::Os.is_secure());
        assert!(EntropyQuality::User.is_secure());
        assert!(!EntropyQuality::Deterministic.is_secure());

        assert!((EntropyQuality::Hardware.as_f64() - 1.0).abs() < f64::EPSILON);
        assert!((EntropyQuality::Os.as_f64() - 0.95).abs() < f64::EPSILON);
        assert!((EntropyQuality::User.as_f64() - 0.8).abs() < f64::EPSILON);
        assert!((EntropyQuality::Deterministic.as_f64() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_custom_entropy_config_default() {
        let config = CustomEntropyConfig::default();
        assert_eq!(config.min_quality, EntropyQuality::User);
        assert_eq!(config.max_bytes_per_call, 1024);
        assert!(config.validate_quality);
        assert_eq!(config.timeout_ms, 1000);
    }

    #[test]
    fn test_custom_entropy_source_creation() {
        let context = EntropyContext::empty();
        let config = CustomEntropyConfig::default();

        let source = unsafe {
            CustomEntropySource::new(
                test_entropy_callback,
                context,
                EntropyQuality::User,
                config,
                "test_source",
            )
        };

        assert_eq!(source.source_id(), "test_source");
        assert_eq!(source.quality(), EntropyQuality::User);
    }

    #[test]
    #[allow(clippy::cast_possible_truncation)]
    fn test_custom_entropy_generation() {
        let context = EntropyContext::empty();
        let config = CustomEntropyConfig::default();

        let source = unsafe {
            CustomEntropySource::new(
                test_entropy_callback,
                context,
                EntropyQuality::User,
                config,
                "test_source",
            )
        };

        let mut buffer = [0u8; 16];
        source.generate_entropy(&mut buffer).unwrap();

        // Check that the callback was called (predictable test data)
        for (i, &byte) in buffer.iter().enumerate() {
            let expected = (i as u8).wrapping_add(42);
            assert_eq!(byte, expected);
        }
    }

    #[test]
    fn test_custom_entropy_max_bytes_validation() {
        let context = EntropyContext::empty();
        let config = CustomEntropyConfig {
            max_bytes_per_call: 8,
            ..Default::default()
        };

        let source = unsafe {
            CustomEntropySource::new(
                test_entropy_callback,
                context,
                EntropyQuality::User,
                config,
                "test_source",
            )
        };

        let mut buffer = [0u8; 16]; // Exceeds max_bytes_per_call
        let result = source.generate_entropy(&mut buffer);
        assert!(result.is_err());
    }

    #[test]
    fn test_custom_entropy_quality_validation() {
        let context = EntropyContext::empty();
        let config = CustomEntropyConfig {
            validate_quality: true,
            ..Default::default()
        };

        let source = unsafe {
            CustomEntropySource::new(
                test_entropy_callback,
                context,
                EntropyQuality::Deterministic, // Low quality
                config,
                "test_source",
            )
        };

        let mut buffer = [0u8; 8];
        let result = source.generate_entropy(&mut buffer);
        assert!(result.is_err());
    }

    #[test]
    fn test_thread_entropy_registry() {
        let _registry = ThreadEntropyRegistry::new();

        // Initially no source registered
        assert!(!has_custom_entropy_source());
        assert!(get_entropy_source_info().is_none());

        let context = EntropyContext::empty();
        let config = CustomEntropyConfig::default();
        let source = CustomEntropySource {
            callback: test_entropy_callback,
            context,
            quality: EntropyQuality::User,
            config,
            source_id: "test_registry",
        };

        // Register the source
        unsafe {
            register_custom_entropy_source(&raw const source);
        }

        assert!(has_custom_entropy_source());
        let info = get_entropy_source_info().unwrap();
        assert_eq!(info.0, "test_registry");
        assert_eq!(info.1, EntropyQuality::User);

        // Test entropy generation
        let mut buffer = [0u8; 8];
        generate_custom_entropy(&mut buffer).unwrap();

        // Unregister the source
        unregister_custom_entropy_source();
        assert!(!has_custom_entropy_source());
        assert!(get_entropy_source_info().is_none());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn test_entropy_source_display() {
        let context = EntropyContext::empty();
        let config = CustomEntropyConfig::default();

        let source = unsafe {
            CustomEntropySource::new(
                test_entropy_callback,
                context,
                EntropyQuality::Hardware,
                config,
                "display_test",
            )
        };

        let display = format!("{source}");
        assert!(display.contains("display_test"));
        assert!(display.contains("Hardware"));
    }
}