lib-q-aead 0.0.4

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
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
//! Plugin Architecture for AEAD Algorithms
//!
//! This module provides a plugin system that allows dynamic loading and registration
//! of AEAD algorithms at runtime.

use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::{
    String,
    ToString,
};
use alloc::vec::Vec;

use lib_q_core::{
    Algorithm,
    Error,
    Result,
};

use crate::AeadWithMetadata;
use crate::metadata::AeadMetadata;

/// Plugin dependency information
#[derive(Debug, Clone, PartialEq)]
pub struct PluginDependency {
    /// Name of the dependency
    pub name: String,
    /// Required version range (e.g., ">=1.0.0,<2.0.0")
    pub version_range: String,
    /// Whether the dependency is optional
    pub optional: bool,
}

/// Plugin metadata with versioning and dependency information
#[derive(Debug, Clone)]
pub struct PluginInfo {
    /// Plugin name
    pub name: String,
    /// Plugin version
    pub version: String,
    /// Plugin description
    pub description: String,
    /// Plugin dependencies
    pub dependencies: Vec<PluginDependency>,
    /// Plugin author
    pub author: Option<String>,
    /// Plugin license
    pub license: Option<String>,
    /// Plugin repository URL
    pub repository: Option<String>,
}

/// Version comparison result
#[derive(Debug, Clone, PartialEq)]
pub enum VersionComparison {
    /// Versions are equal
    Equal,
    /// First version is greater than second
    Greater,
    /// First version is less than second
    Less,
    /// Versions cannot be compared (invalid format)
    Incompatible,
}

/// Plugin trait for AEAD algorithms
pub trait AeadPlugin: Send + Sync {
    /// Get the algorithm identifier for this plugin
    fn algorithm(&self) -> Algorithm;

    /// Create a new AEAD instance
    fn create(&self) -> Result<Box<dyn AeadWithMetadata>>;

    /// Get algorithm metadata
    fn metadata(&self) -> &'static AeadMetadata;

    /// Get plugin name
    fn name(&self) -> &'static str;

    /// Get plugin version
    fn version(&self) -> &'static str;

    /// Get plugin description
    fn description(&self) -> &'static str;

    /// Get detailed plugin information including dependencies
    fn info(&self) -> PluginInfo {
        PluginInfo {
            name: self.name().to_string(),
            version: self.version().to_string(),
            description: self.description().to_string(),
            dependencies: Vec::new(),
            author: None,
            license: None,
            repository: None,
        }
    }

    /// Check if plugin dependencies are satisfied
    fn check_dependencies(&self, _available_plugins: &BTreeMap<String, String>) -> Result<()> {
        // Default implementation: no dependencies
        Ok(())
    }
}

/// Version utility functions
impl PluginInfo {
    /// Compare two semantic versions
    pub fn compare_versions(version1: &str, version2: &str) -> VersionComparison {
        let v1_parts: Vec<u32> = version1.split('.').filter_map(|s| s.parse().ok()).collect();
        let v2_parts: Vec<u32> = version2.split('.').filter_map(|s| s.parse().ok()).collect();

        if v1_parts.len() != 3 || v2_parts.len() != 3 {
            return VersionComparison::Incompatible;
        }

        for (a, b) in v1_parts.iter().zip(v2_parts.iter()) {
            match a.cmp(b) {
                core::cmp::Ordering::Less => return VersionComparison::Less,
                core::cmp::Ordering::Greater => return VersionComparison::Greater,
                core::cmp::Ordering::Equal => continue,
            }
        }

        VersionComparison::Equal
    }

    /// Check if a version satisfies a version range
    pub fn version_satisfies_range(version: &str, range: &str) -> bool {
        // Simple version range checking (supports >=, <=, ==, >, <)
        if let Some(required) = range.strip_prefix(">=") {
            matches!(
                Self::compare_versions(version, required),
                VersionComparison::Greater | VersionComparison::Equal
            )
        } else if let Some(required) = range.strip_prefix("<=") {
            matches!(
                Self::compare_versions(version, required),
                VersionComparison::Less | VersionComparison::Equal
            )
        } else if let Some(required) = range.strip_prefix(">") {
            matches!(
                Self::compare_versions(version, required),
                VersionComparison::Greater
            )
        } else if let Some(required) = range.strip_prefix("<") {
            matches!(
                Self::compare_versions(version, required),
                VersionComparison::Less
            )
        } else if let Some(required) = range.strip_prefix("==") {
            matches!(
                Self::compare_versions(version, required),
                VersionComparison::Equal
            )
        } else {
            // Default to exact match
            matches!(
                Self::compare_versions(version, range),
                VersionComparison::Equal
            )
        }
    }
}

/// Registry for AEAD plugins with enhanced dependency management
pub struct PluginRegistry {
    plugins: Vec<Box<dyn AeadPlugin>>,
    plugin_versions: BTreeMap<String, String>,
}

impl PluginRegistry {
    /// Create a new plugin registry
    pub fn new() -> Self {
        Self {
            plugins: Vec::new(),
            plugin_versions: BTreeMap::new(),
        }
    }

    /// Register a plugin with dependency checking
    pub fn register_plugin(&mut self, plugin: Box<dyn AeadPlugin>) -> Result<()> {
        // Check for duplicate algorithms
        let algorithm = plugin.algorithm();
        if self.plugins.iter().any(|p| p.algorithm() == algorithm) {
            return Err(Error::InvalidState {
                operation: "register_plugin".to_string(),
                reason: "Algorithm already registered".to_string(),
            });
        }

        // Check plugin dependencies
        plugin.check_dependencies(&self.plugin_versions)?;

        // Register the plugin
        let plugin_name = plugin.name().to_string();
        let plugin_version = plugin.version().to_string();
        self.plugin_versions
            .insert(plugin_name.clone(), plugin_version);
        self.plugins.push(plugin);

        Ok(())
    }

    /// Get plugin information by name
    pub fn get_plugin_info(&self, name: &str) -> Option<PluginInfo> {
        self.plugins
            .iter()
            .find(|p| p.name() == name)
            .map(|p| p.info())
    }

    /// List all registered plugins with their versions
    pub fn list_plugins(&self) -> Vec<PluginInfo> {
        self.plugins.iter().map(|p| p.info()).collect()
    }

    /// Check if a plugin version is compatible
    pub fn is_plugin_compatible(&self, name: &str, required_version: &str) -> bool {
        if let Some(version) = self.plugin_versions.get(name) {
            PluginInfo::version_satisfies_range(version, required_version)
        } else {
            false
        }
    }

    /// Get a plugin by algorithm
    pub fn get_plugin(&self, algorithm: Algorithm) -> Option<&dyn AeadPlugin> {
        self.plugins
            .iter()
            .find(|p| p.algorithm() == algorithm)
            .map(|p| p.as_ref())
    }

    /// Create an AEAD instance using a plugin
    pub fn create_aead(&self, algorithm: Algorithm) -> Result<Box<dyn AeadWithMetadata>> {
        let plugin = self
            .get_plugin(algorithm)
            .ok_or_else(|| Error::UnsupportedAlgorithm {
                algorithm: "Plugin not found".to_string(),
            })?;

        plugin.create()
    }

    /// Get all registered algorithms
    pub fn available_algorithms(&self) -> Vec<Algorithm> {
        self.plugins.iter().map(|p| p.algorithm()).collect()
    }

    /// Get all plugins
    pub fn plugins(&self) -> &[Box<dyn AeadPlugin>] {
        &self.plugins
    }

    /// Check if an algorithm is available
    pub fn is_available(&self, algorithm: Algorithm) -> bool {
        self.plugins.iter().any(|p| p.algorithm() == algorithm)
    }

    /// Get plugin metadata for an algorithm
    pub fn get_metadata(&self, algorithm: Algorithm) -> Option<&'static AeadMetadata> {
        self.get_plugin(algorithm).map(|p| p.metadata())
    }

    /// Get all plugin metadata
    pub fn get_all_metadata(&self) -> Vec<&'static AeadMetadata> {
        self.plugins.iter().map(|p| p.metadata()).collect()
    }

    /// Remove a plugin
    pub fn remove_plugin(&mut self, algorithm: Algorithm) -> Result<()> {
        let initial_len = self.plugins.len();
        self.plugins.retain(|p| p.algorithm() != algorithm);

        if self.plugins.len() == initial_len {
            Err(Error::UnsupportedAlgorithm {
                algorithm: "Plugin not found".to_string(),
            })
        } else {
            Ok(())
        }
    }

    /// Clear all plugins
    pub fn clear(&mut self) {
        self.plugins.clear();
    }

    /// Get plugin count
    pub fn plugin_count(&self) -> usize {
        self.plugins.len()
    }
}

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

/// Macro to create a plugin implementation
#[macro_export]
macro_rules! impl_aead_plugin {
    ($struct_name:ident, $algorithm:expr, $name:expr, $version:expr, $description:expr) => {
        impl $crate::plugin::AeadPlugin for $struct_name {
            fn algorithm(&self) -> lib_q_core::Algorithm {
                $algorithm
            }

            fn create(&self) -> lib_q_core::Result<alloc::boxed::Box<dyn lib_q_core::Aead>> {
                Ok(alloc::boxed::Box::new(Self::new()))
            }

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

            fn name(&self) -> &'static str {
                $name
            }

            fn version(&self) -> &'static str {
                $version
            }

            fn description(&self) -> &'static str {
                $description
            }
        }
    };
}

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

    use super::*;

    // Mock plugin for testing
    struct MockPlugin {
        algorithm: Algorithm,
    }

    impl MockPlugin {
        fn new(algorithm: Algorithm) -> Self {
            Self { algorithm }
        }
    }

    impl AeadPlugin for MockPlugin {
        fn algorithm(&self) -> Algorithm {
            self.algorithm
        }

        fn create(&self) -> Result<Box<dyn AeadWithMetadata>> {
            Ok(Box::new(MockAead))
        }

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

        fn name(&self) -> &'static str {
            "Mock Plugin"
        }

        fn version(&self) -> &'static str {
            "1.0.0"
        }

        fn description(&self) -> &'static str {
            "Mock plugin for testing"
        }
    }

    /// Minimal AEAD stub for plugin/registry unit tests (**Layer A only**).
    /// Does not implement [`lib_q_core::AeadDecryptSemantic`]; use real algorithm types for Layer B tests.
    struct MockAead;

    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(Algorithm::Saturnin).expect("Metadata not found")
        }

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

    #[test]
    fn test_plugin_registry_creation() {
        let registry = PluginRegistry::new();
        assert_eq!(registry.plugin_count(), 0);
        assert!(registry.available_algorithms().is_empty());
    }

    #[test]
    fn test_plugin_registration() {
        let mut registry = PluginRegistry::new();

        let plugin = Box::new(MockPlugin::new(Algorithm::Saturnin));
        let result = registry.register_plugin(plugin);

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

    #[test]
    fn test_duplicate_plugin_registration() {
        let mut registry = PluginRegistry::new();

        let plugin1 = Box::new(MockPlugin::new(Algorithm::Saturnin));
        let plugin2 = Box::new(MockPlugin::new(Algorithm::Saturnin));

        registry.register_plugin(plugin1).unwrap();
        let result = registry.register_plugin(plugin2);

        assert!(result.is_err());
        if let Err(Error::InvalidState { operation, reason }) = result {
            assert_eq!(operation, "register_plugin");
            assert!(reason.contains("already registered"));
        } else {
            panic!("Expected InvalidState error");
        }
    }

    #[test]
    fn test_plugin_creation() {
        let mut registry = PluginRegistry::new();

        let plugin = Box::new(MockPlugin::new(Algorithm::Saturnin));
        registry.register_plugin(plugin).unwrap();

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

    #[test]
    fn test_mock_aead_disclaims_semantic_decrypt_capability() {
        let mut registry = PluginRegistry::new();
        registry
            .register_plugin(Box::new(MockPlugin::new(Algorithm::Saturnin)))
            .unwrap();
        let aead = registry.create_aead(Algorithm::Saturnin).unwrap();
        assert!(
            !aead.supports_semantic_decrypt(),
            "Layer A test stub must not claim Layer B via metadata defaults"
        );
    }

    #[test]
    fn test_plugin_metadata() {
        let mut registry = PluginRegistry::new();

        let plugin = Box::new(MockPlugin::new(Algorithm::Saturnin));
        registry.register_plugin(plugin).unwrap();

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

        if let Some(meta) = metadata {
            assert_eq!(meta.algorithm, Algorithm::Saturnin);
        }
    }

    #[test]
    fn test_plugin_removal() {
        let mut registry = PluginRegistry::new();

        let plugin = Box::new(MockPlugin::new(Algorithm::Saturnin));
        registry.register_plugin(plugin).unwrap();

        assert_eq!(registry.plugin_count(), 1);

        let result = registry.remove_plugin(Algorithm::Saturnin);
        assert!(result.is_ok());
        assert_eq!(registry.plugin_count(), 0);
        assert!(!registry.is_available(Algorithm::Saturnin));
    }

    #[test]
    fn test_plugin_clear() {
        let mut registry = PluginRegistry::new();

        let plugin1 = Box::new(MockPlugin::new(Algorithm::Saturnin));
        let plugin2 = Box::new(MockPlugin::new(Algorithm::Shake256Aead));

        registry.register_plugin(plugin1).unwrap();
        registry.register_plugin(plugin2).unwrap();

        assert_eq!(registry.plugin_count(), 2);

        registry.clear();
        assert_eq!(registry.plugin_count(), 0);
        assert!(registry.available_algorithms().is_empty());
    }

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

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

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