latticearc 0.8.2

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), 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
498
499
500
501
502
503
504
505
506
507
508
//! Side-Channel Analysis Testing for Utility Functions
//!
//! This module provides basic side-channel analysis for prelude utilities
//! focusing on timing and information leakage in common operations.
//!
//! Side-channel attacks exploit information leaked through timing, power
//! consumption, or other physical characteristics of cryptographic operations.

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

use crate::prelude::error::Result;
use std::time::{Duration, Instant};

/// Timing analyzer for utility functions.
///
/// Measures execution time variations to detect potential timing side-channels.
pub struct UtilityTimingAnalyzer {
    /// Number of samples to collect.
    samples: usize,
    /// Number of warmup iterations before measurement.
    warmup_iterations: usize,
}

impl UtilityTimingAnalyzer {
    /// Minimum sample count required for a meaningful timing analysis.
    ///
    /// `analyze_utility_timing` divides the sum of measured durations by
    /// `samples` to compute the mean — `samples == 0` would panic with
    /// integer division-by-zero before reaching the typed result.
    /// `samples == 1` is mathematically valid but produces a zero
    /// std-dev that the downstream CV calculation collapses to NaN.
    /// Either is a programmer mistake, not a runtime condition.
    pub const MIN_SAMPLES: usize = 2;

    /// Creates a new timing analyzer with the specified sample count and warmup.
    ///
    /// # Errors
    ///
    /// Returns [`LatticeArcError::InvalidInput`] if `samples` is below
    /// [`Self::MIN_SAMPLES`]. The empty / single-sample cases would
    /// either panic in `calculate_mean` (div-by-zero) or produce a
    /// degenerate std-dev that the CV calculation cannot consume.
    pub fn new(samples: usize, warmup_iterations: usize) -> Result<Self> {
        if samples < Self::MIN_SAMPLES {
            return Err(crate::prelude::LatticeArcError::InvalidInput(format!(
                "UtilityTimingAnalyzer requires at least {} samples, got {}",
                Self::MIN_SAMPLES,
                samples
            )));
        }
        Ok(Self { samples, warmup_iterations })
    }

    /// Analyze timing variations in utility operations.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails during timing measurement.
    pub fn analyze_utility_timing<F>(&self, operation: F) -> Result<TimingAnalysis>
    where
        F: Fn() -> Result<()>,
    {
        let mut execution_times = Vec::with_capacity(self.samples);

        // Warmup phase
        for _ in 0..self.warmup_iterations {
            let _ = operation();
        }

        // Measurement phase
        for _ in 0..self.samples {
            let start = Instant::now();
            operation()?;
            let duration = start.elapsed();
            execution_times.push(duration);
        }

        Ok(TimingAnalysis {
            samples: execution_times.clone(),
            mean: calculate_mean(&execution_times),
            std_dev: calculate_std_dev(&execution_times),
            min: *execution_times.iter().min().unwrap_or(&Duration::ZERO),
            max: *execution_times.iter().max().unwrap_or(&Duration::ZERO),
        })
    }

    /// Test timing variations in hex encoding/decoding.
    ///
    /// # Errors
    ///
    /// Returns an error if hex decoding fails during timing analysis.
    pub fn test_hex_timing_succeeds(&self) -> Result<Vec<SideChannelAssessment>> {
        let mut assessments = Vec::new();

        // Test different input sizes for timing variations
        let sizes = [16, 64, 256, 1024];

        for &size in &sizes {
            let data = vec![0u8; size];

            // Test encoding timing
            let encode_analysis = self.analyze_utility_timing(|| {
                let _encoded = hex::encode(&data);
                Ok(())
            })?;

            // Test decoding timing
            let hex_string = hex::encode(&data);
            let decode_analysis = self.analyze_utility_timing(|| {
                let _decoded = hex::decode(&hex_string)?;
                Ok(())
            })?;

            // Check for suspicious timing variations
            #[expect(
                clippy::cast_precision_loss,
                reason = "precision loss is intentional in this measurement/heuristic path"
            )]
            let encode_cv =
                encode_analysis.std_dev.as_nanos() as f64 / encode_analysis.mean.as_nanos() as f64;
            #[expect(
                clippy::cast_precision_loss,
                reason = "precision loss is intentional in this measurement/heuristic path"
            )]
            let decode_cv =
                decode_analysis.std_dev.as_nanos() as f64 / decode_analysis.mean.as_nanos() as f64;

            if encode_cv > 0.05 {
                // More than 5% variation
                assessments.push(SideChannelAssessment {
                    vulnerability_type: SideChannelType::Timing,
                    severity: if encode_cv > 0.1 { Severity::Medium } else { Severity::Low },
                    confidence: (encode_cv * 20.0).min(1.0),
                    description: format!(
                        "High timing variation in hex encoding for {} bytes (CV: {:.3})",
                        size, encode_cv
                    ),
                    mitigation_suggestions: vec!["Hex encoding timing appears stable".to_string()],
                });
            }

            if decode_cv > 0.05 {
                assessments.push(SideChannelAssessment {
                    vulnerability_type: SideChannelType::Timing,
                    severity: if decode_cv > 0.1 { Severity::Medium } else { Severity::Low },
                    confidence: (decode_cv * 20.0).min(1.0),
                    description: format!(
                        "High timing variation in hex decoding for {} bytes (CV: {:.3})",
                        size, decode_cv
                    ),
                    mitigation_suggestions: vec!["Hex decoding timing appears stable".to_string()],
                });
            }
        }

        Ok(assessments)
    }

    /// Test UUID generation timing (should be consistent).
    ///
    /// # Errors
    ///
    /// Returns an error if UUID timing analysis fails.
    pub fn test_uuid_timing_succeeds(&self) -> Result<Vec<SideChannelAssessment>> {
        let mut assessments = Vec::new();

        let analysis = self.analyze_utility_timing(|| {
            let _uuid = uuid::Uuid::new_v4();
            Ok(())
        })?;

        #[expect(
            clippy::cast_precision_loss,
            reason = "precision loss is intentional in this measurement/heuristic path"
        )]
        let cv = analysis.std_dev.as_nanos() as f64 / analysis.mean.as_nanos() as f64;

        if cv > 0.1 {
            // More than 10% variation
            assessments.push(SideChannelAssessment {
                vulnerability_type: SideChannelType::Timing,
                severity: Severity::Low,
                confidence: (cv * 10.0).min(1.0),
                description: format!("UUID generation timing variation detected (CV: {:.3})", cv),
                mitigation_suggestions: vec![
                    "UUID generation timing is within expected bounds".to_string(),
                ],
            });
        }

        Ok(assessments)
    }
}

/// Timing analysis results.
#[derive(Debug, Clone)]
pub struct TimingAnalysis {
    /// Collected timing samples.
    pub samples: Vec<Duration>,
    /// Mean execution time.
    pub mean: Duration,
    /// Standard deviation of execution times.
    pub std_dev: Duration,
    /// Minimum execution time.
    pub min: Duration,
    /// Maximum execution time.
    pub max: Duration,
}

/// Side-channel vulnerability assessment.
#[derive(Debug, Clone)]
pub struct SideChannelAssessment {
    /// Type of side-channel vulnerability.
    pub vulnerability_type: SideChannelType,
    /// Severity level of the vulnerability.
    pub severity: Severity,
    /// Confidence level of the assessment (0.0 to 1.0).
    pub confidence: f64,
    /// Description of the vulnerability.
    pub description: String,
    /// Suggested mitigations.
    pub mitigation_suggestions: Vec<String>,
}

/// Types of side-channel vulnerabilities.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum SideChannelType {
    /// Timing-based side-channel.
    Timing,
    /// Cache-based side-channel.
    Cache,
    /// Power analysis side-channel.
    Power,
    /// Electromagnetic emanation side-channel.
    Electromagnetic,
    /// Acoustic side-channel.
    Acoustic,
    /// Memory access pattern side-channel.
    MemoryAccess,
}

/// Severity levels for side-channel vulnerabilities.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum Severity {
    /// Low severity - minimal security impact.
    Low,
    /// Medium severity - some security impact.
    Medium,
    /// High severity - significant security impact.
    High,
    /// Critical severity - severe security impact.
    Critical,
}

/// Calculate mean duration. Returns `Duration::ZERO` for an empty
/// slice — the public `UtilityTimingAnalyzer::new` rejects
/// `samples == 0` so this branch is unreachable from the public API,
/// but the guard is kept for defense-in-depth against any future
/// internal caller.
#[expect(
    clippy::cast_possible_truncation,
    clippy::arithmetic_side_effects,
    reason = "u128-to-u64 truncation on average nanos: a mean Duration that overflows u64 ns (~584 years) cannot occur on real timing samples; arithmetic on Duration::as_nanos() sums is bounded by the sample count"
)]
fn calculate_mean(durations: &[Duration]) -> Duration {
    if durations.is_empty() {
        return Duration::ZERO;
    }
    let total_nanos: u128 = durations.iter().map(Duration::as_nanos).sum();
    Duration::from_nanos((total_nanos / durations.len() as u128) as u64)
}

/// Calculate standard deviation.
#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "f64-to-u64 cast on variance.sqrt(): a Duration std-dev exceeding u64 nanoseconds (~584 years) cannot occur on real timing samples; sign-loss is sound because variance is non-negative"
)]
fn calculate_std_dev(durations: &[Duration]) -> Duration {
    if durations.is_empty() {
        return Duration::ZERO;
    }
    let mean = calculate_mean(durations);
    #[expect(
        clippy::cast_precision_loss,
        reason = "precision loss is intentional in this measurement/heuristic path"
    )]
    let mean_nanos = mean.as_nanos() as f64;

    #[expect(
        clippy::cast_precision_loss,
        reason = "precision loss is intentional in this measurement/heuristic path"
    )]
    let variance: f64 = durations
        .iter()
        .map(|d| {
            #[expect(
                clippy::cast_precision_loss,
                reason = "precision loss is intentional in this measurement/heuristic path"
            )]
            let diff = d.as_nanos() as f64 - mean_nanos;
            diff * diff
        })
        .sum::<f64>()
        / durations.len() as f64;

    // `variance` is already in ns² (line above squares ns diffs),
    // so `sqrt()` is in ns. The previous `× 1_000_000_000.0` was a
    // leftover from a seconds→ns conversion that doesn't apply here
    // — it inflated every std_dev by 10⁹×, blew CV past every
    // threshold, and made every side-channel report spurious noise.
    // Same class of bug as `f64::to_bits` vs `as u64` for perf-mod
    // std_dev; the symbol-class sweep at the time should have caught
    // this site too.
    Duration::from_nanos(variance.sqrt() as u64)
}

/// Comprehensive utility side-channel analysis.
///
/// Provides full side-channel analysis for utility functions including
/// timing analysis, memory access patterns, and security assessments.
pub struct UtilitySideChannelTester {
    /// Timing analyzer instance.
    timing_analyzer: UtilityTimingAnalyzer,
}

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

impl UtilitySideChannelTester {
    /// Creates a new side-channel tester with default settings.
    ///
    /// 1000 samples is statically `>= UtilityTimingAnalyzer::MIN_SAMPLES`
    /// (= 2), so the `Result` arm of `UtilityTimingAnalyzer::new` is
    /// unreachable here; we field-construct directly to keep this
    /// `pub fn new() -> Self` infallible.
    #[must_use]
    pub fn new() -> Self {
        Self { timing_analyzer: UtilityTimingAnalyzer { samples: 1000, warmup_iterations: 100 } }
    }

    /// Run comprehensive side-channel analysis for utilities.
    ///
    /// # Errors
    ///
    /// Returns an error if any timing analysis operation fails.
    pub fn run_analysis(&self) -> Result<Vec<SideChannelAssessment>> {
        tracing::info!("Running utility side-channel analysis");

        let mut assessments = Vec::new();

        // Test hex encoding/decoding timing
        let hex_assessments = self.timing_analyzer.test_hex_timing_succeeds()?;
        assessments.extend(hex_assessments);

        // Test UUID generation timing
        let uuid_assessments = self.timing_analyzer.test_uuid_timing_succeeds()?;
        assessments.extend(uuid_assessments);

        // Test domain constant access (should be constant time)
        let domain_assessments = self.test_domain_access_timing_succeeds()?;
        assessments.extend(domain_assessments);

        Ok(assessments)
    }

    /// Test domain constant access timing.
    fn test_domain_access_timing_succeeds(&self) -> Result<Vec<SideChannelAssessment>> {
        let mut assessments = Vec::new();

        // Test access to domain constants (should be constant time)
        let analysis = self.timing_analyzer.analyze_utility_timing(|| {
            let _domain = crate::types::domains::CASCADE_OUTER;
            let _domain = crate::types::domains::CASCADE_INNER;
            let _domain = crate::types::domains::HYBRID_KEM_SS_INFO;
            Ok(())
        })?;

        #[expect(
            clippy::cast_precision_loss,
            reason = "precision loss is intentional in this measurement/heuristic path"
        )]
        let cv = analysis.std_dev.as_nanos() as f64 / analysis.mean.as_nanos() as f64;

        if cv > 0.05 {
            // More than 5% variation
            assessments.push(SideChannelAssessment {
                vulnerability_type: SideChannelType::MemoryAccess,
                severity: Severity::Low,
                confidence: (cv * 20.0).min(1.0),
                description: format!("Domain constant access timing variation (CV: {:.3})", cv),
                mitigation_suggestions: vec![
                    "Domain constants are static and should be constant time".to_string(),
                ],
            });
        }

        Ok(assessments)
    }

    /// Generate side-channel security report.
    ///
    /// Creates a markdown-formatted security report from the assessments.
    #[must_use]
    pub fn generate_security_report(&self, assessments: &[SideChannelAssessment]) -> String {
        let mut report = String::from("# Utility Side-Channel Security Assessment Report\n\n");

        let critical_count =
            assessments.iter().filter(|a| a.severity == Severity::Critical).count();
        let high_count = assessments.iter().filter(|a| a.severity == Severity::High).count();
        let medium_count = assessments.iter().filter(|a| a.severity == Severity::Medium).count();
        let low_count = assessments.iter().filter(|a| a.severity == Severity::Low).count();

        report.push_str("## Summary\n\n");
        report.push_str(&format!("- Critical Vulnerabilities: {}\n", critical_count));
        report.push_str(&format!("- High Vulnerabilities: {}\n", high_count));
        report.push_str(&format!("- Medium Vulnerabilities: {}\n", medium_count));
        report.push_str(&format!("- Low Vulnerabilities: {}\n\n", low_count));

        report.push_str("## Detailed Findings\n\n");
        for assessment in assessments {
            report.push_str(&format!(
                "### {} ({:?})\n",
                assessment.vulnerability_type.clone() as u8,
                assessment.severity
            ));
            report.push_str(&format!("**Confidence:** {:.1}%\n", assessment.confidence * 100.0));
            report.push_str(&format!("**Description:** {}\n", assessment.description));
            report.push_str("**Mitigation Suggestions:**\n");
            for suggestion in &assessment.mitigation_suggestions {
                report.push_str(&format!("- {}\n", suggestion));
            }
            report.push('\n');
        }

        report
    }
}

#[cfg(test)]
#[expect(
    clippy::panic_in_result_fn,
    reason = "Test functions use `assert!` macros which expand to panic; if assertions are removed, the suppress will be cleaned automatically"
)]
mod tests {
    use super::*;

    #[test]
    fn test_timing_analyzer_produces_valid_statistics_succeeds()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let analyzer = UtilityTimingAnalyzer::new(10, 5)?;

        // Test with a simple operation
        let analysis = analyzer.analyze_utility_timing(|| {
            let _encoded = hex::encode(b"test");
            Ok(())
        })?;

        assert!(analysis.samples.len() == 10);
        assert!(analysis.mean > Duration::from_nanos(0));
        assert!(analysis.min <= analysis.mean);
        assert!(analysis.max >= analysis.mean);
        Ok(())
    }

    #[test]
    fn test_hex_timing_analysis_has_no_critical_issues_succeeds()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let analyzer = UtilityTimingAnalyzer::new(10, 5)?;
        let assessments = analyzer.test_hex_timing_succeeds()?;
        // Should not have critical issues
        assert!(assessments.iter().all(|a| a.severity != Severity::Critical));
        Ok(())
    }

    #[test]
    fn test_uuid_timing_analysis_has_no_critical_issues_succeeds()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let analyzer = UtilityTimingAnalyzer::new(10, 5)?;
        let assessments = analyzer.test_uuid_timing_succeeds()?;
        // Should not have critical issues
        assert!(assessments.iter().all(|a| a.severity != Severity::Critical));
        Ok(())
    }

    #[test]
    fn test_side_channel_tester_has_no_critical_vulnerabilities_succeeds()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let tester = UtilitySideChannelTester::new();
        let assessments = tester.run_analysis()?;

        // Generate report
        let report = tester.generate_security_report(&assessments);
        assert!(report.contains("Utility Side-Channel Security Assessment Report"));

        // Should not have critical vulnerabilities in utilities
        assert!(assessments.iter().all(|a| a.severity != Severity::Critical));
        Ok(())
    }
}