chie-crypto 0.2.0

Cryptographic primitives for CHIE Protocol
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
//! Key rotation scheduler with configurable policies.
//!
//! This module provides automated key rotation scheduling with various policies
//! for different key types. It supports time-based, usage-based, and event-driven
//! rotation strategies.
//!
//! # Key Rotation Policies
//!
//! - **Time-based**: Rotate keys after a specific duration (e.g., every 30 days)
//! - **Usage-based**: Rotate keys after a certain number of operations
//! - **Hybrid**: Combine time and usage limits (whichever comes first)
//! - **Event-driven**: Rotate on specific events (e.g., suspected compromise)
//!
//! # Example
//!
//! ```
//! use chie_crypto::key_rotation_scheduler::*;
//! use std::time::Duration;
//!
//! // Create a time-based rotation policy (rotate every 30 days)
//! let policy = KeyRotationPolicy::TimeBased {
//!     max_age: Duration::from_secs(30 * 24 * 3600),
//! };
//!
//! // Create scheduler
//! let mut scheduler = KeyRotationScheduler::new(policy);
//!
//! // Register a key
//! let key_id = "signing-key-001".to_string();
//! scheduler.register_key(key_id.clone());
//!
//! // Check if rotation is needed
//! if scheduler.should_rotate(&key_id) {
//!     println!("Time to rotate key: {}", key_id);
//!     // Perform rotation...
//!     scheduler.mark_rotated(&key_id);
//! }
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, SystemTime};

/// Key rotation policy for scheduler
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum KeyRotationPolicy {
    /// Rotate after a specific time period
    TimeBased {
        /// Maximum age before rotation required
        max_age: Duration,
    },
    /// Rotate after a certain number of operations
    UsageBased {
        /// Maximum number of operations before rotation
        max_operations: u64,
    },
    /// Rotate based on both time and usage (whichever comes first)
    Hybrid {
        /// Maximum age before rotation required
        max_age: Duration,
        /// Maximum number of operations before rotation
        max_operations: u64,
    },
    /// Manual rotation only (no automatic triggers)
    Manual,
}

impl KeyRotationPolicy {
    /// Create a time-based policy with specified duration
    pub fn time_based(max_age: Duration) -> Self {
        Self::TimeBased { max_age }
    }

    /// Create a usage-based policy with specified operation limit
    pub fn usage_based(max_operations: u64) -> Self {
        Self::UsageBased { max_operations }
    }

    /// Create a hybrid policy with both time and usage limits
    pub fn hybrid(max_age: Duration, max_operations: u64) -> Self {
        Self::Hybrid {
            max_age,
            max_operations,
        }
    }

    /// Create a manual-only policy
    pub fn manual() -> Self {
        Self::Manual
    }
}

/// Key metadata for rotation tracking
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct KeyMetadata {
    /// Unique identifier for the key
    pub key_id: String,
    /// When the key was created or last rotated
    pub created_at: SystemTime,
    /// Number of operations performed with this key
    pub operation_count: u64,
    /// Whether the key is currently active
    pub active: bool,
    /// Optional expiration time
    pub expires_at: Option<SystemTime>,
}

impl KeyMetadata {
    /// Create new key metadata
    pub fn new(key_id: String) -> Self {
        Self {
            key_id,
            created_at: SystemTime::now(),
            operation_count: 0,
            active: true,
            expires_at: None,
        }
    }

    /// Get the age of the key
    pub fn age(&self) -> Duration {
        SystemTime::now()
            .duration_since(self.created_at)
            .unwrap_or(Duration::ZERO)
    }

    /// Check if the key has expired
    pub fn is_expired(&self) -> bool {
        if let Some(expires_at) = self.expires_at {
            SystemTime::now() >= expires_at
        } else {
            false
        }
    }

    /// Increment operation counter
    pub fn increment_operations(&mut self) {
        self.operation_count += 1;
    }

    /// Mark key as rotated (reset counters, update timestamp)
    pub fn mark_rotated(&mut self) {
        self.created_at = SystemTime::now();
        self.operation_count = 0;
    }

    /// Mark key as inactive (after rotation)
    pub fn deactivate(&mut self) {
        self.active = false;
    }
}

/// Key rotation scheduler
pub struct KeyRotationScheduler {
    /// Rotation policy
    policy: KeyRotationPolicy,
    /// Tracked keys
    keys: HashMap<String, KeyMetadata>,
    /// Grace period after rotation trigger before forcing rotation
    grace_period: Option<Duration>,
}

impl KeyRotationScheduler {
    /// Create a new scheduler with the specified policy
    pub fn new(policy: KeyRotationPolicy) -> Self {
        Self {
            policy,
            keys: HashMap::new(),
            grace_period: None,
        }
    }

    /// Set grace period for rotation
    pub fn with_grace_period(mut self, grace_period: Duration) -> Self {
        self.grace_period = Some(grace_period);
        self
    }

    /// Register a new key for tracking
    pub fn register_key(&mut self, key_id: String) -> &KeyMetadata {
        self.keys
            .entry(key_id.clone())
            .or_insert_with(|| KeyMetadata::new(key_id.clone()));
        &self.keys[&key_id]
    }

    /// Register a key with custom metadata
    pub fn register_key_with_metadata(&mut self, metadata: KeyMetadata) {
        self.keys.insert(metadata.key_id.clone(), metadata);
    }

    /// Record an operation for a key
    pub fn record_operation(&mut self, key_id: &str) -> Result<(), String> {
        let metadata = self
            .keys
            .get_mut(key_id)
            .ok_or_else(|| format!("Key not registered: {}", key_id))?;

        if !metadata.active {
            return Err(format!("Key is inactive: {}", key_id));
        }

        metadata.increment_operations();
        Ok(())
    }

    /// Check if a key should be rotated according to the policy
    pub fn should_rotate(&self, key_id: &str) -> bool {
        let metadata = match self.keys.get(key_id) {
            Some(m) => m,
            None => return false,
        };

        // Inactive keys don't need rotation
        if !metadata.active {
            return false;
        }

        // Check expiration
        if metadata.is_expired() {
            return true;
        }

        // Check policy-specific triggers
        match &self.policy {
            KeyRotationPolicy::TimeBased { max_age } => metadata.age() >= *max_age,
            KeyRotationPolicy::UsageBased { max_operations } => {
                metadata.operation_count >= *max_operations
            }
            KeyRotationPolicy::Hybrid {
                max_age,
                max_operations,
            } => metadata.age() >= *max_age || metadata.operation_count >= *max_operations,
            KeyRotationPolicy::Manual => false,
        }
    }

    /// Force rotation check (ignore grace period)
    pub fn must_rotate(&self, key_id: &str) -> bool {
        if !self.should_rotate(key_id) {
            return false;
        }

        // If there's a grace period, check if we're past it
        if let Some(grace_period) = self.grace_period {
            let metadata = self.keys.get(key_id).unwrap();
            let time_since_trigger = match &self.policy {
                KeyRotationPolicy::TimeBased { max_age } => metadata.age().saturating_sub(*max_age),
                KeyRotationPolicy::Hybrid { max_age, .. } => {
                    metadata.age().saturating_sub(*max_age)
                }
                _ => Duration::ZERO,
            };
            time_since_trigger >= grace_period
        } else {
            true
        }
    }

    /// Mark a key as rotated
    pub fn mark_rotated(&mut self, key_id: &str) -> Result<(), String> {
        let metadata = self
            .keys
            .get_mut(key_id)
            .ok_or_else(|| format!("Key not registered: {}", key_id))?;

        metadata.mark_rotated();
        Ok(())
    }

    /// Deactivate a key (after successful rotation)
    pub fn deactivate_key(&mut self, key_id: &str) -> Result<(), String> {
        let metadata = self
            .keys
            .get_mut(key_id)
            .ok_or_else(|| format!("Key not registered: {}", key_id))?;

        metadata.deactivate();
        Ok(())
    }

    /// Get all keys that need rotation
    pub fn keys_needing_rotation(&self) -> Vec<String> {
        self.keys
            .iter()
            .filter(|(key_id, _)| self.should_rotate(key_id))
            .map(|(key_id, _)| key_id.clone())
            .collect()
    }

    /// Get all keys that must be rotated immediately
    pub fn keys_requiring_immediate_rotation(&self) -> Vec<String> {
        self.keys
            .iter()
            .filter(|(key_id, _)| self.must_rotate(key_id))
            .map(|(key_id, _)| key_id.clone())
            .collect()
    }

    /// Get metadata for a key
    pub fn get_metadata(&self, key_id: &str) -> Option<&KeyMetadata> {
        self.keys.get(key_id)
    }

    /// Get all active keys
    pub fn active_keys(&self) -> Vec<String> {
        self.keys
            .iter()
            .filter(|(_, metadata)| metadata.active)
            .map(|(key_id, _)| key_id.clone())
            .collect()
    }

    /// Get rotation policy
    pub fn policy(&self) -> &KeyRotationPolicy {
        &self.policy
    }
}

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

    #[test]
    fn test_time_based_policy() {
        let policy = KeyRotationPolicy::time_based(Duration::from_millis(100));
        let mut scheduler = KeyRotationScheduler::new(policy);

        let key_id = "test-key".to_string();
        scheduler.register_key(key_id.clone());

        // Should not need rotation immediately
        assert!(!scheduler.should_rotate(&key_id));

        // Wait for policy duration
        sleep(Duration::from_millis(150));

        // Should need rotation now
        assert!(scheduler.should_rotate(&key_id));
    }

    #[test]
    fn test_usage_based_policy() {
        let policy = KeyRotationPolicy::usage_based(5);
        let mut scheduler = KeyRotationScheduler::new(policy);

        let key_id = "test-key".to_string();
        scheduler.register_key(key_id.clone());

        // Perform operations
        for _ in 0..4 {
            scheduler.record_operation(&key_id).unwrap();
        }

        // Should not need rotation yet
        assert!(!scheduler.should_rotate(&key_id));

        // One more operation
        scheduler.record_operation(&key_id).unwrap();

        // Should need rotation now
        assert!(scheduler.should_rotate(&key_id));
    }

    #[test]
    fn test_hybrid_policy() {
        let policy = KeyRotationPolicy::hybrid(Duration::from_millis(100), 10);
        let mut scheduler = KeyRotationScheduler::new(policy);

        let key_id = "test-key".to_string();
        scheduler.register_key(key_id.clone());

        // Test time trigger
        sleep(Duration::from_millis(150));
        assert!(scheduler.should_rotate(&key_id));

        // Reset
        scheduler.mark_rotated(&key_id).unwrap();

        // Test usage trigger
        for _ in 0..10 {
            scheduler.record_operation(&key_id).unwrap();
        }
        assert!(scheduler.should_rotate(&key_id));
    }

    #[test]
    fn test_manual_policy() {
        let policy = KeyRotationPolicy::manual();
        let mut scheduler = KeyRotationScheduler::new(policy);

        let key_id = "test-key".to_string();
        scheduler.register_key(key_id.clone());

        // Perform many operations
        for _ in 0..1000 {
            scheduler.record_operation(&key_id).unwrap();
        }

        // Should never trigger automatic rotation
        assert!(!scheduler.should_rotate(&key_id));
    }

    #[test]
    fn test_grace_period() {
        let policy = KeyRotationPolicy::time_based(Duration::from_millis(50));
        let mut scheduler =
            KeyRotationScheduler::new(policy).with_grace_period(Duration::from_millis(50));

        let key_id = "test-key".to_string();
        scheduler.register_key(key_id.clone());

        sleep(Duration::from_millis(75));

        // Should rotate but not must rotate (within grace period)
        assert!(scheduler.should_rotate(&key_id));
        assert!(!scheduler.must_rotate(&key_id));

        sleep(Duration::from_millis(50));

        // Now must rotate (past grace period)
        assert!(scheduler.must_rotate(&key_id));
    }

    #[test]
    fn test_deactivate_key() {
        let policy = KeyRotationPolicy::manual();
        let mut scheduler = KeyRotationScheduler::new(policy);

        let key_id = "test-key".to_string();
        scheduler.register_key(key_id.clone());

        // Key should be active
        let metadata = scheduler.get_metadata(&key_id).unwrap();
        assert!(metadata.active);

        // Deactivate
        scheduler.deactivate_key(&key_id).unwrap();

        // Should be inactive now
        let metadata = scheduler.get_metadata(&key_id).unwrap();
        assert!(!metadata.active);

        // Should not be able to record operations
        assert!(scheduler.record_operation(&key_id).is_err());
    }

    #[test]
    fn test_keys_needing_rotation() {
        let policy = KeyRotationPolicy::usage_based(5);
        let mut scheduler = KeyRotationScheduler::new(policy);

        scheduler.register_key("key1".to_string());
        scheduler.register_key("key2".to_string());
        scheduler.register_key("key3".to_string());

        // Trigger rotation for key1 and key3
        for _ in 0..5 {
            scheduler.record_operation("key1").unwrap();
            scheduler.record_operation("key3").unwrap();
        }

        let keys = scheduler.keys_needing_rotation();
        assert_eq!(keys.len(), 2);
        assert!(keys.contains(&"key1".to_string()));
        assert!(keys.contains(&"key3".to_string()));
    }

    #[test]
    fn test_mark_rotated_resets_counters() {
        let policy = KeyRotationPolicy::usage_based(5);
        let mut scheduler = KeyRotationScheduler::new(policy);

        let key_id = "test-key".to_string();
        scheduler.register_key(key_id.clone());

        // Trigger rotation
        for _ in 0..5 {
            scheduler.record_operation(&key_id).unwrap();
        }
        assert!(scheduler.should_rotate(&key_id));

        // Mark as rotated
        scheduler.mark_rotated(&key_id).unwrap();

        // Should no longer need rotation
        assert!(!scheduler.should_rotate(&key_id));

        // Operation count should be reset
        let metadata = scheduler.get_metadata(&key_id).unwrap();
        assert_eq!(metadata.operation_count, 0);
    }

    #[test]
    fn test_active_keys() {
        let policy = KeyRotationPolicy::manual();
        let mut scheduler = KeyRotationScheduler::new(policy);

        scheduler.register_key("key1".to_string());
        scheduler.register_key("key2".to_string());
        scheduler.register_key("key3".to_string());

        assert_eq!(scheduler.active_keys().len(), 3);

        scheduler.deactivate_key("key2").unwrap();

        let active = scheduler.active_keys();
        assert_eq!(active.len(), 2);
        assert!(!active.contains(&"key2".to_string()));
    }

    #[test]
    fn test_key_expiration() {
        let mut metadata = KeyMetadata::new("test-key".to_string());

        // Set expiration in the past
        metadata.expires_at = Some(SystemTime::now() - Duration::from_secs(1));

        assert!(metadata.is_expired());

        // Set expiration in the future
        metadata.expires_at = Some(SystemTime::now() + Duration::from_secs(3600));

        assert!(!metadata.is_expired());
    }

    #[test]
    fn test_policy_serialization() {
        let policy = KeyRotationPolicy::hybrid(Duration::from_secs(3600), 1000);

        let serialized = crate::codec::encode(&policy).unwrap();
        let deserialized: KeyRotationPolicy = crate::codec::decode(&serialized).unwrap();

        match deserialized {
            KeyRotationPolicy::Hybrid {
                max_age,
                max_operations,
            } => {
                assert_eq!(max_age, Duration::from_secs(3600));
                assert_eq!(max_operations, 1000);
            }
            _ => panic!("Wrong policy type"),
        }
    }

    #[test]
    fn test_metadata_serialization() {
        let metadata = KeyMetadata::new("test-key".to_string());

        let serialized = crate::codec::encode(&metadata).unwrap();
        let deserialized: KeyMetadata = crate::codec::decode(&serialized).unwrap();

        assert_eq!(metadata.key_id, deserialized.key_id);
        assert_eq!(metadata.active, deserialized.active);
    }
}