trelent-hyok 0.1.12

A Rust library implementing Hold Your Own Key (HYOK) encryption patterns with support for multiple cloud providers
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Builder pattern for HYOK service configuration.
//!
//! This module provides a flexible builder interface for configuring the HYOK
//! service with different components:
//!
//! - Key generation strategies
//! - Caching mechanisms
//! - Persistence backends
//! - Customer Managed Keys (CMKs)
//!
//! The builder pattern ensures type-safe configuration while supporting
//! multiple cloud providers and custom implementations.

use std::sync::Arc;

use crate::cache::{CustomCache, DEKCache, MokaCache};
#[cfg(feature = "aws")]
use crate::cmk::AwsCMK;
#[cfg(feature = "azure")]
use crate::cmk::AzureCMK;
use crate::cmk::{CustomCMK, CMK};
use crate::dek::generator::key_generator::custom::CustomGenerator;
use crate::dek::generator::key_generator::fixed::FixedLengthGenerator;
#[cfg(feature = "debug")]
use crate::dek::generator::key_generator::string::StringGenerator;
use crate::dek::generator::DEKGenerator;
#[cfg(feature = "aws")]
use crate::dek::persistence::AWSPersister;
#[cfg(feature = "azure")]
use crate::dek::persistence::AzurePersister;
#[cfg(feature = "debug")]
use crate::dek::persistence::MemPersister;
use crate::dek::persistence::{CustomPersister, DEKPersistService, DEKPersister};
use crate::encryption::EncryptionStrategy;
use crate::error::cache::CacheError;
use crate::error::cmk::CMKError;
use crate::error::generator::{GenerateKeyError, PersistError};
use crate::HYOKService;
#[cfg(feature = "aws")]
use aws_sdk_kms::types::EncryptionAlgorithmSpec;
#[cfg(feature = "azure")]
use azure_security_keyvault::prelude::CryptographParamtersEncryption;
use std::time::Duration;

/// Configuration options for DEK generation.
///
/// Supports different strategies for generating Data Encryption Keys:
/// - Fixed-length cryptographically secure keys
/// - String-based keys for testing (debug feature)
/// - Custom generation logic
pub enum GeneratorConfig {
    /// Fixed-length random key generation
    FixedLength(usize),
    /// String-based keys for testing
    #[cfg(feature = "debug")]
    String(String),
    /// Custom key generation implementation
    Custom {
        generate_fn: Arc<dyn (Fn() -> Result<Vec<u8>, GenerateKeyError>) + Send + Sync>,
    },
}

/// Configuration options for DEK caching.
///
/// Provides different caching strategies:
/// - No caching (direct persistence)
/// - Custom cache implementation
/// - Moka-based caching with TTL
pub enum CacheConfig {
    /// Disable caching
    NoCache,
    /// Custom cache implementation
    Custom {
        get_fn: Arc<dyn (Fn(&String) -> Option<Vec<u8>>) + Send + Sync>,
        set_fn: Arc<dyn (Fn(String, Vec<u8>) -> Result<Vec<u8>, CacheError>) + Send + Sync>,
    },
    /// Moka-based caching with configuration
    Moka {
        cache_size: u64,
        time_to_live: Duration,
        time_to_idle: Duration,
    },
}

/// Configuration options for DEK persistence.
///
/// Supports multiple storage backends:
/// - AWS Secrets Manager
/// - Azure Key Vault
/// - In-memory storage (debug)
/// - Custom implementations
pub enum PersisterConfig {
    /// AWS Secrets Manager persistence
    #[cfg(feature = "aws")]
    Aws {
        client: aws_sdk_secretsmanager::Client,
    },
    /// Azure Key Vault persistence
    #[cfg(feature = "azure")]
    Azure {
        client: azure_security_keyvault::KeyvaultClient,
    },
    /// In-memory persistence for testing
    #[cfg(feature = "debug")]
    Memory,
    /// Custom persistence implementation
    Custom {
        persist_fn: Arc<
            dyn (Fn(
                Vec<u8>,
                String
            ) -> futures::future::BoxFuture<'static, Result<Vec<u8>, PersistError>>) +
                Send +
                Sync
        >,
        fetch_fn: Arc<
            dyn (Fn(String) -> futures::future::BoxFuture<'static, Result<Vec<u8>, PersistError>>) +
                Send +
                Sync
        >,
    },
}

/// Configuration options for Customer Managed Keys (CMKs).
///
/// Supports different key management services:
/// - AWS KMS
/// - Azure Key Vault
/// - Custom implementations
pub enum CMKConfig {
    /// AWS KMS configuration
    #[cfg(feature = "aws")]
    Aws {
        client: aws_sdk_kms::Client,
        key_name: String,
        algorithm: EncryptionAlgorithmSpec,
    },
    /// Azure Key Vault configuration
    #[cfg(feature = "azure")]
    Azure {
        client: azure_security_keyvault::KeyvaultClient,
        key_name: String,
        params: CryptographParamtersEncryption,
    },
    /// Custom CMK implementation
    Custom {
        encrypt_fn: Arc<
            dyn (Fn(Vec<u8>) -> futures::future::BoxFuture<'static, Result<Vec<u8>, CMKError>>) +
                Send +
                Sync
        >,
        decrypt_fn: Arc<
            dyn (Fn(Vec<u8>) -> futures::future::BoxFuture<'static, Result<Vec<u8>, CMKError>>) +
                Send +
                Sync
        >,
    },
}

/// Builder for configuring and creating HYOK service instances.
///
/// This builder provides a fluent interface for configuring all aspects
/// of the HYOK service, including:
///
/// - Key generation strategy
/// - Caching mechanism
/// - Persistence backend
/// - Customer Managed Key
///
/// # Example
/// ```no_run
/// use hyokashi::HYOKServiceBuilder;
/// use std::time::Duration;
///
///     let service = HYOKServiceBuilder::new()
///         .with_fixed_length_generator(32)
///         .with_moka_cache(
///             1000,
///             Duration::from_secs(3600),
///             Duration::from_secs(1800)
///         )
///         .with_aws_persistence(aws_client)
///         .with_aws_cmk(
///             kms_client,
///             "alias/my-key",
///             EncryptionAlgorithmSpec::RsaesOaepSha256
///         )
///         .build(encryption_strategy)?;
/// ```
pub struct HYOKServiceBuilder {
    persist_config: Option<PersisterConfig>,
    cmk_config: Option<CMKConfig>,
    cache_config: Option<CacheConfig>,
    generator_config: Option<GeneratorConfig>,
}

impl Default for HYOKServiceBuilder {
    fn default() -> Self {
        Self {
            cmk_config: None,
            cache_config: Some(CacheConfig::Moka {
                cache_size: 10000,
                time_to_live: Duration::from_secs(300),
                time_to_idle: Duration::from_secs(120),
            }),
            generator_config: Some(GeneratorConfig::FixedLength(32)),
            persist_config: None,
        }
    }
}

impl HYOKServiceBuilder {
    /// Creates a new builder instance with no configuration.
    pub fn new() -> Self {
        Self {
            cmk_config: None,
            cache_config: None,
            persist_config: None,
            generator_config: None,
        }
    }

    /// Configures AWS KMS as the Customer Managed Key provider.
    ///
    /// # Arguments
    ///
    /// * `client` - AWS KMS client
    /// * `key_name` - Name or ARN of the KMS key
    /// * `algorithm` - Encryption algorithm to use
    #[cfg(feature = "aws")]
    pub fn with_aws_cmk(
        mut self,
        client: aws_sdk_kms::Client,
        key_name: impl Into<String>,
        algorithm: EncryptionAlgorithmSpec
    ) -> Self {
        self.cmk_config = Some(CMKConfig::Aws {
            client,
            key_name: key_name.into(),
            algorithm,
        });
        self
    }

    /// Configures Azure Key Vault as the Customer Managed Key provider.
    ///
    /// # Arguments
    ///
    /// * `key_name` - Name of the key in Key Vault
    /// * `params` - Encryption parameters
    /// * `client` - Azure Key Vault client
    #[cfg(feature = "azure")]
    pub fn with_azure_cmk(
        mut self,
        key_name: impl Into<String>,
        params: CryptographParamtersEncryption,
        client: azure_security_keyvault::KeyvaultClient
    ) -> Self {
        self.cmk_config = Some(CMKConfig::Azure {
            client,
            key_name: key_name.into(),
            params,
        });
        self
    }

    /// Configures a custom Customer Managed Key implementation.
    ///
    /// # Arguments
    ///
    /// * `encrypt_fn` - Function for encrypting DEKs
    /// * `decrypt_fn` - Function for decrypting DEKs
    pub fn with_custom_cmk<E, D>(mut self, encrypt_fn: E, decrypt_fn: D) -> Self
        where
            E: Fn(Vec<u8>) -> futures::future::BoxFuture<'static, Result<Vec<u8>, CMKError>> +
                Send +
                Sync +
                'static,
            D: Fn(Vec<u8>) -> futures::future::BoxFuture<'static, Result<Vec<u8>, CMKError>> +
                Send +
                Sync +
                'static
    {
        self.cmk_config = Some(CMKConfig::Custom {
            encrypt_fn: Arc::new(encrypt_fn),
            decrypt_fn: Arc::new(decrypt_fn),
        });
        self
    }

    /// Configures Moka-based caching with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `cache_size` - Maximum number of entries
    /// * `time_to_live` - Maximum time to keep entries
    /// * `time_to_idle` - Maximum time without access
    pub fn with_moka_cache(
        mut self,
        cache_size: u64,
        time_to_live: Duration,
        time_to_idle: Duration
    ) -> Self {
        self.cache_config = Some(CacheConfig::Moka {
            cache_size,
            time_to_live,
            time_to_idle,
        });
        self
    }

    /// Configures a custom cache implementation.
    ///
    /// # Arguments
    ///
    /// * `get_fn` - Function for retrieving cached values
    /// * `set_fn` - Function for storing values in cache
    ///
    /// # Example
    /// ```no_run
    /// use std::collections::HashMap;
    /// use std::sync::Mutex;
    ///
    /// let cache = Arc::new(Mutex::new(HashMap::new()));
    /// let cache_clone = cache.clone();
    ///
    /// builder.with_custom_cache(
    ///     move |key| {
    ///         cache.lock().unwrap().get(key).cloned()
    ///     },
    ///     move |key, value| {
    ///         cache_clone.lock().unwrap().insert(key, value.clone());
    ///         Ok(value)
    ///     }
    /// );
    /// ```
    pub fn with_custom_cache<G, S>(mut self, get_fn: G, set_fn: S) -> Self
        where
            G: Fn(&String) -> Option<Vec<u8>> + Send + Sync + 'static,
            S: Fn(String, Vec<u8>) -> Result<Vec<u8>, CacheError> + Send + Sync + 'static
    {
        self.cache_config = Some(CacheConfig::Custom {
            get_fn: Arc::new(get_fn),
            set_fn: Arc::new(set_fn),
        });
        self
    }

    /// Disables caching, causing all operations to directly access persistence.
    pub fn with_no_cache(mut self) -> Self {
        self.cache_config = Some(CacheConfig::NoCache);
        self
    }

    /// Configures fixed-length key generation.
    ///
    /// # Arguments
    ///
    /// * `key_length` - Length of generated keys in bytes
    ///
    /// # Security
    ///
    /// Choose an appropriate key length for your encryption needs:
    /// - AES-256: 32 bytes
    /// - AES-192: 24 bytes
    /// - AES-128: 16 bytes
    pub fn with_fixed_length_generator(mut self, key_length: usize) -> Self {
        self.generator_config = Some(GeneratorConfig::FixedLength(key_length));
        self
    }

    /// Configures string-based key generation for testing.
    ///
    /// # Arguments
    ///
    /// * `key` - String to use as key material
    ///
    /// # Warning
    ///
    /// This method is only available in debug builds and should not be
    /// used in production as it is not cryptographically secure.
    #[cfg(feature = "debug")]
    pub fn with_string_generator(mut self, key: String) -> Self {
        self.generator_config = Some(GeneratorConfig::String(key));
        self
    }

    /// Configures custom key generation logic.
    ///
    /// # Arguments
    ///
    /// * `generate_fn` - Function that generates key material
    ///
    /// # Security
    ///
    /// The provided function should:
    /// - Use cryptographically secure random number generation
    /// - Generate keys of appropriate length
    /// - Handle errors appropriately
    pub fn with_custom_generator<G>(mut self, generate_fn: G) -> Self
        where G: Fn() -> Result<Vec<u8>, GenerateKeyError> + Send + Sync + 'static
    {
        self.generator_config = Some(GeneratorConfig::Custom {
            generate_fn: Arc::new(generate_fn),
        });
        self
    }

    /// Configures Azure Key Vault as the persistence backend.
    ///
    /// # Arguments
    ///
    /// * `client` - Azure Key Vault client for API operations
    ///
    /// # Authentication
    ///
    /// The client should be properly configured with:
    /// - Valid credentials
    /// - Appropriate permissions
    /// - Correct vault URL
    #[cfg(feature = "azure")]
    pub fn with_azure_persistence(
        mut self,
        client: azure_security_keyvault::KeyvaultClient
    ) -> Self {
        self.persist_config = Some(PersisterConfig::Azure {
            client,
        });
        self
    }

    /// Configures AWS Secrets Manager as the persistence backend.
    ///
    /// # Arguments
    ///
    /// * `client` - AWS Secrets Manager client for API operations
    ///
    /// # Authentication
    ///
    /// The client should be properly configured with:
    /// - Valid credentials
    /// - Appropriate IAM permissions
    /// - Correct region settings
    #[cfg(feature = "aws")]
    pub fn with_aws_persistence(mut self, client: aws_sdk_secretsmanager::Client) -> Self {
        self.persist_config = Some(PersisterConfig::Aws {
            client,
        });
        self
    }

    /// Configures in-memory persistence for testing.
    ///
    /// # Warning
    ///
    /// This method is only available in debug builds and should not be
    /// used in production as data will not persist across restarts.
    #[cfg(feature = "debug")]
    pub fn with_memory_persistence(mut self) -> Self {
        self.persist_config = Some(PersisterConfig::Memory);
        self
    }

    /// Configures custom persistence logic.
    ///
    /// # Arguments
    ///
    /// * `persist_fn` - Function for storing keys
    /// * `fetch_fn` - Function for retrieving keys
    ///
    /// # Security
    ///
    /// The provided functions should:
    /// - Ensure secure storage of key material
    /// - Implement proper access controls
    /// - Handle errors appropriately
    /// - Maintain data integrity
    pub fn with_custom_persistence<P, F>(mut self, persist_fn: P, fetch_fn: F) -> Self
        where
            P: Fn(
                Vec<u8>,
                String
            ) -> futures::future::BoxFuture<'static, Result<Vec<u8>, PersistError>> +
                Send +
                Sync +
                'static,
            F: Fn(String) -> futures::future::BoxFuture<'static, Result<Vec<u8>, PersistError>> +
                Send +
                Sync +
                'static
    {
        self.persist_config = Some(PersisterConfig::Custom {
            persist_fn: Arc::new(persist_fn),
            fetch_fn: Arc::new(fetch_fn),
        });
        self
    }

    /// Builds the HYOK service with the configured components.
    ///
    /// # Type Parameters
    ///
    /// * `S` - The encryption strategy type
    /// * `ED` - The encryption metadata type
    ///
    /// # Arguments
    ///
    /// * `strategy` - The encryption strategy to use
    ///
    /// # Returns
    ///
    /// A configured HYOK service or an error if the configuration is invalid
    pub fn build<S: EncryptionStrategy<EncryptionData = ED> + Send + Sync, ED: Send>(
        self,
        strategy: S
    ) -> Result<HYOKService<S>, String> {
        let generator = match self.generator_config.ok_or("Generator config required")? {
            GeneratorConfig::FixedLength(length) =>
                DEKGenerator::Fixed(FixedLengthGenerator::new(length)),
            #[cfg(feature = "debug")]
            GeneratorConfig::String(length) => DEKGenerator::String(StringGenerator::new(length)),
            GeneratorConfig::Custom { generate_fn } =>
                DEKGenerator::Custom(CustomGenerator::new(move || generate_fn())),
        };

        let cmk = match self.cmk_config.ok_or("CMK config required")? {
            #[cfg(feature = "aws")]
            CMKConfig::Aws { client, key_name, algorithm } => {
                CMK::AWS(AwsCMK::new(Arc::new(client), key_name, algorithm))
            }
            #[cfg(feature = "azure")]
            CMKConfig::Azure { client, key_name, params } => {
                CMK::Azure(AzureCMK::new(Arc::new(client), key_name, params))
            }
            CMKConfig::Custom { encrypt_fn, decrypt_fn } => {
                CMK::Custom(
                    CustomCMK::new(
                        move |key| encrypt_fn(key),
                        move |key| decrypt_fn(key)
                    )
                )
            }
        };

        let cache = match self.cache_config.ok_or("Cache config required")? {
            CacheConfig::NoCache => DEKCache::NoCache,
            CacheConfig::Custom { get_fn, set_fn } => {
                DEKCache::Custom(
                    CustomCache::new(
                        move |key| get_fn(key),
                        move |key, value| set_fn(key, value)
                    )
                )
            }
            CacheConfig::Moka { cache_size, time_to_live, time_to_idle } => {
                DEKCache::Moka(MokaCache::new(cache_size, time_to_live, time_to_idle))
            }
        };

        let persister = match self.persist_config.ok_or("Persister config required")? {
            #[cfg(feature = "aws")]
            PersisterConfig::Aws { client } =>
                DEKPersister::AWS(AWSPersister::new(Arc::new(client))),
            #[cfg(feature = "azure")]
            PersisterConfig::Azure { client } =>
                DEKPersister::Azure(AzurePersister::new(Arc::new(client))),
            #[cfg(feature = "debug")]
            PersisterConfig::Memory => DEKPersister::Mem(MemPersister::new()),
            PersisterConfig::Custom { persist_fn, fetch_fn } => {
                DEKPersister::Custom(
                    CustomPersister::new(
                        move |key, context| persist_fn(key, context),
                        move |context| fetch_fn(context)
                    )
                )
            }
        };

        let persist_service = DEKPersistService::new(
            Arc::new(persister),
            Arc::new(cmk),
            Some(Arc::new(cache))
        );

        Ok(HYOKService::new(Arc::new(persist_service), generator, strategy))
    }
}