latticearc 0.5.0

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), post-quantum TLS, and FIPS 140-3 backend — one crate, zero unsafe.
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
//! Memory Safety Testing for Prelude Utilities
//!
//! This module provides memory safety validation for utility functions
//! and error handling mechanisms. It tests hex encoding/decoding, UUID
//! generation, error handling, and concurrent access patterns.

#![deny(unsafe_code)]
#![deny(missing_docs)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::panic)]

use crate::prelude::error::{LatticeArcError, Result};

/// Memory safety tester for utilities.
///
/// Provides comprehensive memory safety testing for common utility operations
/// used throughout the LatticeArc library.
pub struct UtilityMemorySafetyTester;

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

impl UtilityMemorySafetyTester {
    /// Creates a new memory safety tester instance.
    #[must_use]
    pub fn new() -> Self {
        Self {}
    }

    /// Test memory safety of utility operations.
    ///
    /// # Errors
    ///
    /// Returns an error if any memory safety test fails validation.
    pub fn test_memory_safety_succeeds(&self) -> Result<()> {
        tracing::info!("Testing utility memory safety");

        // Test hex operations memory safety
        let invalid_hex = ["g", "gg", "invalid", "z", "G", "xyz", "123", "abcdefg"];
        for &hex_str in &invalid_hex {
            let result = hex::decode(hex_str);
            if result.is_ok() {
                return Err(LatticeArcError::ValidationError {
                    message: format!("Hex string '{}' should be invalid", hex_str),
                });
            }
        }
        // Empty string is actually valid (decodes to empty bytes)
        if hex::decode("").is_err() {
            return Err(LatticeArcError::ValidationError {
                message: "Empty hex string should be valid".to_string(),
            });
        }

        // Test UUID operations memory safety
        for _ in 0..100 {
            let uuid = uuid::Uuid::new_v4();
            if uuid.is_nil() {
                return Err(LatticeArcError::ValidationError {
                    message: "UUID should not be nil".to_string(),
                });
            }
            let uuid_str = uuid.to_string();
            if uuid_str.len() != 36 {
                return Err(LatticeArcError::ValidationError {
                    message: format!("UUID string should be 36 chars, got {}", uuid_str.len()),
                });
            }
        }

        // Test error operations memory safety
        let test_errors = vec![
            LatticeArcError::InvalidInput("test".to_string()),
            LatticeArcError::IoError(
                std::io::Error::new(std::io::ErrorKind::NotFound, "test").to_string(),
            ),
        ];

        for error in test_errors {
            let _display = format!("{}", error);
            let _debug = format!("{:?}", error);
            // Should not panic
        }

        tracing::info!("Utility memory safety tests passed");
        Ok(())
    }

    /// Test hex operations memory safety.
    ///
    /// # Errors
    ///
    /// Returns an error if hex encoding/decoding memory safety tests fail.
    pub fn test_hex_memory_safety_succeeds(&self) -> Result<()> {
        // Test invalid hex strings - hex decode requires even length and valid hex chars
        let invalid_hex = ["g", "gg", "invalid", "z", "G", "xyz", "123", "abcdefg"];
        for &hex_str in &invalid_hex {
            let result = hex::decode(hex_str);
            if result.is_ok() {
                return Err(LatticeArcError::ValidationError {
                    message: format!("Hex string '{}' should be invalid", hex_str),
                });
            }
        }

        // Empty string is actually valid (decodes to empty bytes)
        if hex::decode("").is_err() {
            return Err(LatticeArcError::ValidationError {
                message: "Empty hex string should be valid".to_string(),
            });
        }

        Ok(())
    }

    /// Test UUID operations memory safety.
    ///
    /// # Errors
    ///
    /// Returns an error if UUID parsing fails during memory safety validation.
    pub fn test_uuid_memory_safety_succeeds(&self) -> Result<()> {
        // Test UUID generation (should never panic)
        for _ in 0..100 {
            let uuid = uuid::Uuid::new_v4();
            if uuid.is_nil() {
                return Err(LatticeArcError::ValidationError {
                    message: "UUID should not be nil".to_string(),
                });
            }
            if uuid.get_version_num() != 4 {
                return Err(LatticeArcError::ValidationError {
                    message: format!("UUID version should be 4, got {}", uuid.get_version_num()),
                });
            }

            // Test string conversion
            let uuid_str = uuid.to_string();
            if uuid_str.len() != 36 {
                return Err(LatticeArcError::ValidationError {
                    message: format!("UUID string should be 36 chars, got {}", uuid_str.len()),
                });
            }

            // Test parsing back
            let parsed = uuid::Uuid::parse_str(&uuid_str)?;
            if parsed != uuid {
                return Err(LatticeArcError::ValidationError {
                    message: "Parsed UUID should match original".to_string(),
                });
            }
        }

        Ok(())
    }

    /// Test error handling memory safety.
    ///
    /// # Errors
    ///
    /// Returns an error if error serialization/deserialization fails.
    pub fn test_error_memory_safety_fails(&self) -> Result<()> {
        // Test various error types for serialization safety
        let errors = vec![
            LatticeArcError::InvalidInput("test".to_string()),
            LatticeArcError::NetworkError("connection failed".to_string()),
            LatticeArcError::IoError("file not found".to_string()),
            LatticeArcError::EncryptionError("cipher failed".to_string()),
        ];

        for error in errors {
            // Test serialization roundtrip — should not panic or leak memory
            let json = serde_json::to_string(&error)?;
            let deserialized: LatticeArcError = serde_json::from_str(&json)?;
            if error != deserialized {
                return Err(LatticeArcError::ValidationError {
                    message: "Deserialized error should match original".to_string(),
                });
            }
        }

        Ok(())
    }

    /// Test concurrent access safety.
    ///
    /// # Errors
    ///
    /// Returns an error if a thread panics or concurrent operations fail.
    pub fn test_concurrent_safety_succeeds(&self) -> Result<()> {
        use std::thread;

        let mut handles = vec![];

        // Spawn threads performing utility operations
        for i in 0..4 {
            let handle: thread::JoinHandle<Result<()>> = thread::spawn(move || {
                for j in 0..100 {
                    // Test hex operations
                    let data = format!("thread_{}_{}", i, j).into_bytes();
                    let encoded = hex::encode(&data);
                    let _decoded = hex::decode(&encoded)?;

                    // Test UUID generation
                    let _uuid = uuid::Uuid::new_v4();

                    // Test error handling
                    let _error = LatticeArcError::InvalidInput(format!("test_{}_{}", i, j));
                }
                Ok::<(), LatticeArcError>(())
            });
            handles.push(handle);
        }

        // Wait for all threads
        for handle in handles {
            handle
                .join()
                // Thread join errors are Box<dyn Any> which can't be formatted,
                // but we can try to downcast to common panic types
                .map_err(|e| {
                    let msg = e
                        .downcast_ref::<&str>()
                        .map(ToString::to_string)
                        .or_else(|| e.downcast_ref::<String>().cloned())
                        .unwrap_or_else(|| "Unknown panic payload".to_string());
                    LatticeArcError::ConcurrencyError(format!("Thread panic: {}", msg))
                })??;
        }

        Ok(())
    }
}

/// Leak detector for utilities.
///
/// Monitors utility operations for potential resource leaks by
/// repeatedly executing operations and tracking success/failure rates.
pub struct UtilityLeakDetector;

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

impl UtilityLeakDetector {
    /// Creates a new leak detector instance.
    #[must_use]
    pub fn new() -> Self {
        Self
    }

    /// Monitor for resource leaks in utility operations.
    ///
    /// Executes the provided operation 1000 times and tracks success/failure
    /// rates to detect potential resource leaks or instability.
    ///
    /// # Errors
    ///
    /// Returns an error if the monitored operation fails during leak detection.
    pub fn monitor_leaks<F>(&self, operation: F) -> Result<()>
    where
        F: Fn() -> Result<()>,
    {
        // Comprehensive leak detection through repeated execution and error monitoring
        let mut success_count = 0;
        let mut error_count = 0;
        for i in 0..1000 {
            match operation() {
                #[allow(clippy::arithmetic_side_effects)]
                Ok(_) => success_count += 1,
                #[allow(clippy::arithmetic_side_effects)]
                Err(e) => {
                    error_count += 1;
                    tracing::warn!("Operation {} failed: {}", i, e);
                    // Continue testing to see if it's consistent
                }
            }
        }
        tracing::info!(
            "Leak detection completed: {} successes, {} errors out of 1000 operations",
            success_count,
            error_count
        );
        Ok(())
    }
}

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

    #[test]
    fn test_memory_safety_passes_for_utility_tester_succeeds() {
        let tester = UtilityMemorySafetyTester::new();
        assert!(tester.test_memory_safety_succeeds().is_ok());
    }

    #[test]
    fn test_concurrent_safety_passes_for_utility_tester_succeeds() {
        let tester = UtilityMemorySafetyTester::new();
        assert!(tester.test_concurrent_safety_succeeds().is_ok());
    }

    #[test]
    fn test_hex_memory_safety_passes_for_utility_tester_succeeds() {
        let tester = UtilityMemorySafetyTester::new();
        assert!(tester.test_hex_memory_safety_succeeds().is_ok());
    }

    #[test]
    fn test_uuid_memory_safety_passes_for_utility_tester_succeeds() {
        let tester = UtilityMemorySafetyTester::new();
        assert!(tester.test_uuid_memory_safety_succeeds().is_ok());
    }

    #[test]
    fn test_error_memory_safety_passes_for_utility_tester_fails() {
        let tester = UtilityMemorySafetyTester::new();
        assert!(tester.test_error_memory_safety_fails().is_ok());
    }

    #[test]
    fn test_leak_detector_monitor_leaks_succeeds() {
        let detector = UtilityLeakDetector::new();

        let result = detector.monitor_leaks(|| {
            let _data = vec![0u8; 100];
            let _encoded = hex::encode(&_data);
            Ok(())
        });

        assert!(result.is_ok());
    }

    #[test]
    fn test_memory_safety_tester_default_passes_memory_safety_succeeds() {
        let tester = UtilityMemorySafetyTester;
        assert!(tester.test_memory_safety_succeeds().is_ok());
    }

    #[test]
    fn test_leak_detector_default_monitor_leaks_succeeds() {
        let detector = UtilityLeakDetector;
        let result = detector.monitor_leaks(|| Ok(()));
        assert!(result.is_ok());
    }

    #[test]
    fn test_leak_detector_with_failing_operation_fails() {
        let detector = UtilityLeakDetector::new();
        // Operation that always fails — monitor_leaks should still succeed
        // (it counts errors but doesn't propagate them)
        let result = detector.monitor_leaks(|| {
            Err(LatticeArcError::InvalidInput("intentional failure".to_string()))
        });
        assert!(result.is_ok());
    }

    #[test]
    fn test_leak_detector_with_intermittent_failures_fails() {
        let detector = UtilityLeakDetector::new();
        let counter = std::sync::atomic::AtomicUsize::new(0);
        let result = detector.monitor_leaks(|| {
            let val = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if val.is_multiple_of(3) {
                Err(LatticeArcError::InvalidInput("every third fails".to_string()))
            } else {
                Ok(())
            }
        });
        assert!(result.is_ok());
    }

    #[test]
    fn test_memory_safety_tester_new_and_default_are_equivalent_succeeds() {
        let t1 = UtilityMemorySafetyTester::new();
        let t2 = UtilityMemorySafetyTester;
        // Both should work identically
        assert!(t1.test_hex_memory_safety_succeeds().is_ok());
        assert!(t2.test_hex_memory_safety_succeeds().is_ok());
    }

    #[test]
    fn test_leak_detector_new_and_default_are_equivalent_succeeds() {
        let d1 = UtilityLeakDetector::new();
        let d2 = UtilityLeakDetector;
        assert!(d1.monitor_leaks(|| Ok(())).is_ok());
        assert!(d2.monitor_leaks(|| Ok(())).is_ok());
    }

    #[test]
    fn test_uuid_memory_safety_standalone_succeeds() {
        let tester = UtilityMemorySafetyTester::new();
        assert!(tester.test_uuid_memory_safety_succeeds().is_ok());
    }

    #[test]
    fn test_error_memory_safety_standalone_succeeds() {
        let tester = UtilityMemorySafetyTester::new();
        assert!(tester.test_error_memory_safety_fails().is_ok());
    }

    #[test]
    fn test_hex_roundtrip_large_data_roundtrip() {
        let tester = UtilityMemorySafetyTester::new();
        // Ensure large data hex encode/decode works
        let data = vec![0xABu8; 4096];
        let encoded = hex::encode(&data);
        let decoded = hex::decode(&encoded);
        assert!(decoded.is_ok());
        if let Ok(ref bytes) = decoded {
            assert_eq!(bytes, &data);
        }
        // Basic tester should still pass
        assert!(tester.test_hex_memory_safety_succeeds().is_ok());
    }

    #[test]
    fn test_concurrent_safety_produces_no_errors_fails() {
        let tester = UtilityMemorySafetyTester::new();
        // Run concurrent safety test multiple times to increase confidence
        for _ in 0..3 {
            assert!(tester.test_concurrent_safety_succeeds().is_ok());
        }
    }

    #[test]
    fn test_leak_detector_monitor_many_successes_runs_1000_iterations_succeeds() {
        let detector = UtilityLeakDetector::new();
        let counter = std::sync::atomic::AtomicUsize::new(0);
        let result = detector.monitor_leaks(|| {
            counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(())
        });
        assert!(result.is_ok());
        // Should have run 1000 iterations
        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1000);
    }

    // ---- Coverage: monitor_leaks edge cases ----

    #[test]
    fn test_monitor_leaks_with_allocating_operation_succeeds() {
        let detector = UtilityLeakDetector::new();
        let result = detector.monitor_leaks(|| {
            // Allocate and free memory within the operation
            let data = vec![0xABu8; 256];
            let encoded = hex::encode(&data);
            let _decoded = hex::decode(&encoded);
            Ok(())
        });
        assert!(result.is_ok());
    }

    #[test]
    fn test_monitor_leaks_sequential_runs_all_succeed_succeeds() {
        let detector = UtilityLeakDetector::new();
        // Run monitor_leaks multiple times sequentially
        for _ in 0..3 {
            let result = detector.monitor_leaks(|| Ok(()));
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_utility_memory_safety_tester_default_passes_memory_safety_succeeds() {
        let tester = UtilityMemorySafetyTester::new();
        assert!(tester.test_memory_safety_succeeds().is_ok());
    }

    #[test]
    fn test_hex_roundtrip_empty_and_single_byte_roundtrip() {
        // Empty data
        let empty: Vec<u8> = vec![];
        let encoded = hex::encode(&empty);
        assert_eq!(encoded, "");
        let decoded = hex::decode(&encoded);
        assert!(decoded.is_ok());
        if let Ok(ref bytes) = decoded {
            assert!(bytes.is_empty());
        }

        // Single byte
        let single = vec![0xFFu8];
        let encoded = hex::encode(&single);
        assert_eq!(encoded, "ff");
        let decoded = hex::decode(&encoded);
        assert!(decoded.is_ok());
        if let Ok(ref bytes) = decoded {
            assert_eq!(bytes, &single);
        }
    }
}