lib-q-aead 0.0.5

Post-quantum Authenticated Encryption for lib-Q
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
//! AEAD Algorithm Registry
//!
//! This module provides a flexible registry system for AEAD algorithms that allows
//! dynamic registration and creation of algorithm instances.

use alloc::boxed::Box;
use alloc::collections::BTreeMap;
#[cfg(feature = "alloc")]
use alloc::string::ToString;
use alloc::vec::Vec;
#[cfg(feature = "std")]
use core::hash::Hasher;

/// Custom hasher for Algorithm to ensure consistent hashing
/// This provides deterministic hashing for Algorithm keys
/// Available for future HashMap usage when security requirements allow
#[cfg(feature = "std")]
#[derive(Default)]
#[allow(dead_code)] // Reserved for future HashMap implementation
struct AlgorithmHasher {
    state: u64,
}

#[cfg(feature = "std")]
impl Hasher for AlgorithmHasher {
    fn write(&mut self, bytes: &[u8]) {
        for &byte in bytes {
            self.state = self.state.wrapping_mul(31).wrapping_add(byte as u64);
        }
    }

    fn finish(&self) -> u64 {
        self.state
    }
}

/// Type alias for algorithm storage
/// Uses BTreeMap for consistent cross-platform behavior and security
/// AlgorithmHasher is available for future HashMap usage if needed
type AlgorithmHashMap = BTreeMap<Algorithm, AeadConstructor>;
#[cfg(feature = "std")]
use std::sync::RwLock;

use lib_q_core::{
    Algorithm,
    AlgorithmCategory,
    Error,
    Result,
};
#[cfg(not(feature = "std"))]
use spin::RwLock;

use crate::AeadWithMetadata;
use crate::metadata::AeadMetadata;
use crate::plugin::AeadPlugin;

/// Constructor function type for creating AEAD instances
pub type AeadConstructor = Box<dyn Fn() -> Result<Box<dyn AeadWithMetadata>> + Send + Sync>;

/// Registry for AEAD algorithms
pub struct AeadRegistry {
    constructors: RwLock<AlgorithmHashMap>,
    plugins: RwLock<Vec<Box<dyn AeadPlugin>>>,
    metadata: BTreeMap<Algorithm, &'static AeadMetadata>,
}

impl AeadRegistry {
    /// Create a new AEAD registry
    pub fn new() -> Self {
        Self {
            constructors: RwLock::new(AlgorithmHashMap::new()),
            plugins: RwLock::new(Vec::new()),
            metadata: Self::create_metadata_map(),
        }
    }

    /// Create the metadata map for all known algorithms
    fn create_metadata_map() -> BTreeMap<Algorithm, &'static AeadMetadata> {
        let mut metadata = BTreeMap::new();
        let known_algorithms = [
            Algorithm::Saturnin,
            Algorithm::Shake256Aead,
            Algorithm::DuplexSpongeAead,
            Algorithm::TweakAead,
            Algorithm::RomulusN,
            Algorithm::RomulusM,
        ];

        for algorithm in known_algorithms {
            if let Some(algorithm_metadata) = crate::metadata::get_metadata(algorithm) {
                metadata.insert(algorithm, algorithm_metadata);
            }
        }

        metadata
    }

    /// Register an algorithm constructor
    pub fn register_algorithm<F>(&self, algorithm: Algorithm, constructor: F) -> Result<()>
    where
        F: Fn() -> Result<Box<dyn AeadWithMetadata>> + Send + Sync + 'static,
    {
        // Validate algorithm category
        if algorithm.category() != AlgorithmCategory::Aead {
            return Err(Error::InvalidAlgorithm {
                algorithm: "Algorithm is not an AEAD algorithm",
            });
        }

        #[cfg(feature = "std")]
        {
            let mut constructors = self.constructors.write().map_err(|_| Error::InvalidState {
                operation: "register_algorithm".to_string(),
                reason: "Failed to acquire write lock".to_string(),
            })?;
            constructors.insert(algorithm, Box::new(constructor));
        }
        #[cfg(not(feature = "std"))]
        {
            let mut constructors = self.constructors.write();
            constructors.insert(algorithm, Box::new(constructor));
        }
        Ok(())
    }

    /// Register a plugin
    pub fn register_plugin(&self, plugin: Box<dyn AeadPlugin>) -> Result<()> {
        #[cfg(feature = "std")]
        {
            let mut plugins = self.plugins.write().map_err(|_| Error::InvalidState {
                operation: "register_plugin".to_string(),
                reason: "Failed to acquire write lock".to_string(),
            })?;
            plugins.push(plugin);
        }
        #[cfg(not(feature = "std"))]
        {
            let mut plugins = self.plugins.write();
            plugins.push(plugin);
        }
        Ok(())
    }

    /// Create an AEAD instance for the specified algorithm
    pub fn create_aead(&self, algorithm: Algorithm) -> Result<Box<dyn AeadWithMetadata>> {
        // First try direct constructors
        #[cfg(feature = "std")]
        {
            let constructors = self.constructors.read().map_err(|_| Error::InvalidState {
                operation: "create_aead".to_string(),
                reason: "Failed to acquire read lock".to_string(),
            })?;
            if let Some(constructor) = constructors.get(&algorithm) {
                return constructor();
            }
        }
        #[cfg(not(feature = "std"))]
        {
            let constructors = self.constructors.read();
            if let Some(constructor) = constructors.get(&algorithm) {
                return constructor();
            }
        }

        // Then try plugins
        #[cfg(feature = "std")]
        {
            let plugins = self.plugins.read().map_err(|_| Error::InvalidState {
                operation: "create_aead".to_string(),
                reason: "Failed to acquire read lock".to_string(),
            })?;
            for plugin in plugins.iter() {
                if plugin.algorithm() == algorithm {
                    return plugin.create();
                }
            }
        }
        #[cfg(not(feature = "std"))]
        {
            let plugins = self.plugins.read();
            for plugin in plugins.iter() {
                if plugin.algorithm() == algorithm {
                    return plugin.create();
                }
            }
        }

        Err(Error::UnsupportedAlgorithm {
            algorithm: "Algorithm not registered".to_string(),
        })
    }

    /// Get available algorithms
    pub fn available_algorithms(&self) -> Vec<Algorithm> {
        let mut algorithms = Vec::new();

        // Add algorithms from constructors
        #[cfg(feature = "std")]
        {
            if let Ok(constructors) = self.constructors.read() {
                algorithms.extend(constructors.keys().copied());
            }
        }
        #[cfg(not(feature = "std"))]
        {
            let constructors = self.constructors.read();
            algorithms.extend(constructors.keys().copied());
        }

        // Add algorithms from plugins
        #[cfg(feature = "std")]
        {
            if let Ok(plugins) = self.plugins.read() {
                for plugin in plugins.iter() {
                    let algorithm = plugin.algorithm();
                    if !algorithms.contains(&algorithm) {
                        algorithms.push(algorithm);
                    }
                }
            }
        }
        #[cfg(not(feature = "std"))]
        {
            let plugins = self.plugins.read();
            for plugin in plugins.iter() {
                let algorithm = plugin.algorithm();
                if !algorithms.contains(&algorithm) {
                    algorithms.push(algorithm);
                }
            }
        }

        algorithms.sort();
        algorithms
    }

    /// Check if an algorithm is available
    pub fn is_available(&self, algorithm: Algorithm) -> bool {
        // Check constructors
        #[cfg(feature = "std")]
        {
            if let Ok(constructors) = self.constructors.read() &&
                constructors.contains_key(&algorithm)
            {
                return true;
            }
        }
        #[cfg(not(feature = "std"))]
        {
            let constructors = self.constructors.read();
            if constructors.contains_key(&algorithm) {
                return true;
            }
        }

        // Check plugins
        #[cfg(feature = "std")]
        {
            if let Ok(plugins) = self.plugins.read() {
                for plugin in plugins.iter() {
                    if plugin.algorithm() == algorithm {
                        return true;
                    }
                }
            }
        }
        #[cfg(not(feature = "std"))]
        {
            let plugins = self.plugins.read();
            for plugin in plugins.iter() {
                if plugin.algorithm() == algorithm {
                    return true;
                }
            }
        }

        false
    }

    /// Get algorithm metadata
    pub fn get_metadata(&self, algorithm: Algorithm) -> Option<&'static AeadMetadata> {
        self.metadata.get(&algorithm).copied()
    }

    /// Get all registered algorithms with their metadata
    pub fn get_all_metadata(&self) -> Vec<&'static AeadMetadata> {
        let available = self.available_algorithms();
        available
            .iter()
            .filter_map(|&algorithm| self.get_metadata(algorithm))
            .collect()
    }
}

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

#[cfg(test)]
mod tests {
    use lib_q_core::{
        Aead,
        AeadKey,
        Nonce,
    };

    use super::*;

    // Test-only stub: Layer A + metadata only (no `AeadDecryptSemantic`); mirrors `plugin` tests.
    struct MockAead {
        algorithm: Algorithm,
    }

    impl Aead for MockAead {
        fn encrypt(
            &self,
            _key: &AeadKey,
            _nonce: &Nonce,
            _plaintext: &[u8],
            _associated_data: Option<&[u8]>,
        ) -> Result<Vec<u8>> {
            Ok(alloc::vec![1, 2, 3, 4])
        }

        fn decrypt(
            &self,
            _key: &AeadKey,
            _nonce: &Nonce,
            _ciphertext: &[u8],
            _associated_data: Option<&[u8]>,
        ) -> Result<Vec<u8>> {
            Ok(alloc::vec![5, 6, 7, 8])
        }
    }

    impl AeadWithMetadata for MockAead {
        fn metadata(&self) -> &'static AeadMetadata {
            crate::metadata::get_metadata(self.algorithm).expect("Metadata not found")
        }

        fn supports_semantic_decrypt(&self) -> bool {
            false
        }
    }

    #[test]
    fn test_registry_creation() {
        let registry = AeadRegistry::new();
        assert!(registry.available_algorithms().is_empty());
    }

    #[test]
    fn test_algorithm_registration() {
        let registry = AeadRegistry::new();

        let result = registry.register_algorithm(Algorithm::Saturnin, || {
            Ok(Box::new(MockAead {
                algorithm: Algorithm::Saturnin,
            }) as Box<dyn AeadWithMetadata>)
        });

        assert!(result.is_ok());
        assert!(registry.is_available(Algorithm::Saturnin));
        assert!(
            registry
                .available_algorithms()
                .contains(&Algorithm::Saturnin)
        );
    }

    #[test]
    fn test_algorithm_creation() {
        let registry = AeadRegistry::new();

        registry
            .register_algorithm(Algorithm::Saturnin, || {
                Ok(Box::new(MockAead {
                    algorithm: Algorithm::Saturnin,
                }) as Box<dyn AeadWithMetadata>)
            })
            .unwrap();

        let aead = registry.create_aead(Algorithm::Saturnin);
        assert!(aead.is_ok());
    }

    #[test]
    fn test_invalid_algorithm_registration() {
        let registry = AeadRegistry::new();

        let result = registry.register_algorithm(Algorithm::MlKem512, || {
            Ok(Box::new(MockAead {
                algorithm: Algorithm::MlKem512,
            }) as Box<dyn AeadWithMetadata>)
        });

        assert!(result.is_err());
        if let Err(Error::InvalidAlgorithm { algorithm }) = result {
            assert!(algorithm.contains("not an AEAD algorithm"));
        } else {
            panic!("Expected InvalidAlgorithm error");
        }
    }

    #[test]
    fn test_metadata_retrieval() {
        let registry = AeadRegistry::new();

        let metadata = registry.get_metadata(Algorithm::Saturnin);
        assert!(metadata.is_some());

        if let Some(meta) = metadata {
            assert_eq!(meta.algorithm, Algorithm::Saturnin);
            assert_eq!(meta.name, "Saturnin");
            assert!(meta.key_size > 0);
            assert!(meta.nonce_size > 0);
            assert!(meta.tag_size > 0);
        }
    }

    #[test]
    fn test_unsupported_algorithm() {
        let registry = AeadRegistry::new();

        let result = registry.create_aead(Algorithm::Shake256Aead);
        assert!(result.is_err());

        if let Err(Error::UnsupportedAlgorithm { algorithm }) = result {
            assert!(algorithm.contains("not registered"));
        } else {
            panic!("Expected UnsupportedAlgorithm error");
        }
    }
}