keeper-secrets-manager-core 17.2.0

Rust SDK for Keeper Secrets Manager
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
// -*- coding: utf-8 -*-
//  _  __
// | |/ /___ ___ _ __  ___ _ _ (R)
// | ' </ -_) -_) '_ \/ -_) '_|
// |_|\_\___\___| .__/\___|_|
//              |_|
//
// Keeper Secrets Manager
// Copyright 2024 Keeper Security Inc.
// Contact: sm@keepersecurity.com
//

#[cfg(test)]
mod file_key_value_tests {
    use crate::config_keys::ConfigKeys;
    use crate::custom_error::KSMRError;
    use crate::storage::{FileKeyValueStorage, KeyValueStorage};

    use std::collections::HashMap;
    use std::fs::remove_file;

    // Helper function to create a temporary config file
    fn setup_temp_config_file(
        function_name: &str,
    ) -> Result<(FileKeyValueStorage, String), KSMRError> {
        let file_name = format!("{}-temp-config.json", function_name); // Create the file name
        let storage_result = FileKeyValueStorage::new(Some(file_name.to_string()))
            .map_err(|err| KSMRError::StorageError(format!("Failed to create storage: {}", err)))?;
        let _ = storage_result
            .create_config_file_if_missing()
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create config file: {}", err))
            })?;
        Ok((storage_result, file_name.clone())) // Return the storage and the file name as a tuple
    }

    #[test]
    fn test_read_storage() {
        let (mut storage, file_name) = setup_temp_config_file("read_storage")
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create unit test storage: {}", err))
            })
            .unwrap();

        // Test reading from an empty file
        let config = storage.read_storage().unwrap();
        assert!(config.is_empty());

        // Test reading after writing to the file
        let mut config: HashMap<ConfigKeys, String> = HashMap::new();
        config.insert(ConfigKeys::KeyAppKey, "SomeValue".to_string());
        storage.save_storage(config.clone()).unwrap();

        let read_config = storage.read_storage().unwrap();
        assert_eq!(read_config, config);
        run_cleanup(file_name)
    }

    #[test]
    fn test_save_storage() {
        let (mut storage, file_name) = setup_temp_config_file("save_storage")
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create unit test storage: {}", err))
            })
            .unwrap();

        // Test saving a configuration
        let mut config: HashMap<ConfigKeys, String> = HashMap::new();
        config.insert(ConfigKeys::KeyAppKey, "SomeValue".to_string());
        storage.save_storage(config.clone()).unwrap();

        // Test reading back the saved configuration
        let read_config = storage.read_storage().unwrap();
        assert_eq!(read_config, config);

        // Test overwriting the configuration
        config.insert(ConfigKeys::KeyClientId, "AnotherValue".to_string());
        storage.save_storage(config.clone()).unwrap();

        let read_config = storage.read_storage().unwrap();
        assert_eq!(read_config, config);
        run_cleanup(file_name);
    }

    #[test]
    fn test_get() {
        let (mut storage, file_name) = setup_temp_config_file("test_get")
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create unit test storage: {}", err))
            })
            .unwrap();

        // Test getting a non-existent key
        let value = storage.get(ConfigKeys::KeyAppKey).unwrap();
        assert_eq!(value, None);

        // Test getting an existing key after setting it
        storage
            .set(ConfigKeys::KeyAppKey, "SomeValue".to_string())
            .unwrap();
        let value = storage.get(ConfigKeys::KeyAppKey).unwrap();
        assert_eq!(value, Some("SomeValue".to_string()));
        run_cleanup(file_name);
    }

    #[test]
    fn test_set() {
        let (mut storage, file_name) = setup_temp_config_file("test_set")
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create unit test storage: {}", err))
            })
            .unwrap();

        // Test setting a new key-value pair
        let updated_config = storage
            .set(ConfigKeys::KeyAppKey, "SomeValue".to_string())
            .unwrap();
        assert_eq!(
            updated_config.get(&ConfigKeys::KeyAppKey),
            Some(&"SomeValue".to_string())
        );

        // Test updating an existing key
        storage
            .set(ConfigKeys::KeyAppKey, "NewValue".to_string())
            .unwrap();
        let updated_config = storage.get(ConfigKeys::KeyAppKey).unwrap();
        assert_eq!(updated_config, Some("NewValue".to_string()));

        // Test updating an non-existing key
        let key = ConfigKeys::get_enum("someRandomString");
        assert!(
            key.is_none(),
            "Expected no valid ConfigKeys enum for 'someRandomString'"
        ); // Attempt to set a value for a non-existing key
        run_cleanup(file_name);
    }

    #[test]
    fn test_delete() {
        let (mut storage, file_name) = setup_temp_config_file("test_delete")
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create unit test storage: {}", err))
            })
            .unwrap();

        // Test deleting a non-existent key
        let updated_config = storage.delete(ConfigKeys::KeyAppKey).unwrap();
        assert!(updated_config.is_empty());

        // Test deleting an existing key
        storage
            .set(ConfigKeys::KeyAppKey, "SomeValue".to_string())
            .unwrap();
        let updated_config = storage.delete(ConfigKeys::KeyAppKey).unwrap();
        assert!(updated_config.get(&ConfigKeys::KeyAppKey).is_none());
        run_cleanup(file_name);
    }

    #[test]
    fn test_delete_all() {
        let (mut storage, file_name) = setup_temp_config_file("test_delete_all")
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create unit test storage: {}", err))
            })
            .unwrap();

        // Test deleting all from an empty storage
        let updated_config = storage.delete_all().unwrap();
        assert!(updated_config.is_empty());

        // Test deleting all after adding some entries
        let mut config: HashMap<ConfigKeys, String> = HashMap::new();
        config.insert(ConfigKeys::KeyAppKey, "SomeValue".to_string());
        config.insert(ConfigKeys::KeyClientId, "AnotherValue".to_string());
        storage.save_storage(config.clone()).unwrap();

        let updated_config = storage.delete_all().unwrap();
        assert!(updated_config.is_empty());
        run_cleanup(file_name);
    }

    #[test]
    fn test_contains() {
        let (mut storage, file_name) = setup_temp_config_file("test_contains")
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create unit test storage: {}", err))
            })
            .unwrap();

        // Test checking for a non-existent key
        assert!(!storage.contains(ConfigKeys::KeyAppKey).unwrap());

        // Test checking for an existing key
        storage
            .set(ConfigKeys::KeyAppKey, "SomeValue".to_string())
            .unwrap();
        assert!(storage.contains(ConfigKeys::KeyAppKey).unwrap());
        run_cleanup(file_name);
    }

    #[test]
    fn test_is_empty() {
        let (mut storage, file_name) = setup_temp_config_file("test_is_empty")
            .map_err(|err| {
                KSMRError::StorageError(format!("Failed to create unit test storage: {}", err))
            })
            .unwrap();
        // Test checking if a newly created storage is empty
        assert!(storage.is_empty().unwrap());

        // Test checking if storage is not empty after adding an entry
        storage
            .set(ConfigKeys::KeyAppKey, "SomeValue".to_string())
            .unwrap();
        assert!(!storage.is_empty().unwrap());
        run_cleanup(file_name);
    }

    fn run_cleanup(file_name: String) {
        let _ = remove_file(file_name);
    }
}

#[cfg(test)]
mod in_memory_storage_tests {
    use crate::{
        config_keys::ConfigKeys,
        storage::{InMemoryKeyValueStorage, KeyValueStorage},
    };
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    use std::collections::HashMap;

    #[test]
    fn test_read_storage() {
        let mut storage = InMemoryKeyValueStorage::new(None).unwrap();

        // Test reading from an empty storage
        let config = storage.read_storage().unwrap();
        assert!(config.is_empty());

        // Test saving to storage
        let mut config: HashMap<ConfigKeys, String> = HashMap::new();
        config.insert(ConfigKeys::KeyAppKey, "SomeValue".to_string());
        storage.save_storage(config.clone()).unwrap();

        let read_config = storage.read_storage().unwrap();
        assert_eq!(read_config, config);
    }

    #[test]
    fn test_save_storage() {
        let mut storage = InMemoryKeyValueStorage::new(None).unwrap();

        // Test saving a configuration
        let mut config: HashMap<ConfigKeys, String> = HashMap::new();
        config.insert(ConfigKeys::KeyAppKey, "SomeValue".to_string());
        storage.save_storage(config.clone()).unwrap();

        // Check that storage reflects saved state
        let read_config = storage.read_storage().unwrap();
        assert_eq!(read_config, config);

        // Test overwriting the configuration
        config.insert(ConfigKeys::KeyClientId, "AnotherValue".to_string());
        storage.save_storage(config.clone()).unwrap();

        let read_config = storage.read_storage().unwrap();
        assert_eq!(read_config, config);
    }

    #[test]
    fn test_get() {
        let storage = create_initialized_storage();

        // Test getting a non-existent key
        let value = storage.get(ConfigKeys::KeyHostname).unwrap();
        assert_eq!(value, None);

        // Test getting an existing key after setting it
        let value = storage.get(ConfigKeys::KeyAppKey).unwrap();
        assert_eq!(value, Some("myAppKey".to_string()));
    }

    #[test]
    fn test_set() {
        let mut storage = create_initialized_storage();

        // Test setting a new key-value pair
        let updated_config = storage
            .set(ConfigKeys::KeyAppKey, "SomeValue".to_string())
            .unwrap();
        assert_eq!(
            updated_config.get(&ConfigKeys::KeyAppKey),
            Some(&"SomeValue".to_string())
        );

        // Test updating an existing key
        storage
            .set(ConfigKeys::KeyAppKey, "NewValue".to_string())
            .unwrap();
        let updated_value = storage.get(ConfigKeys::KeyAppKey).unwrap();
        assert_eq!(updated_value, Some("NewValue".to_string()));

        // Test setting a value for a non-existing key
        let non_existing_key = ConfigKeys::get_enum("someRandomString");
        assert!(non_existing_key.is_none());
    }

    #[test]
    fn test_delete() {
        let mut storage = create_initialized_storage();

        // Test deleting a non-existent key
        let updated_config = storage.delete(ConfigKeys::KeyHostname).unwrap();
        assert!(updated_config
            .get_key_value(&ConfigKeys::KeyHostname)
            .is_none());

        // Test deleting an existing key
        let updated_config = storage.delete(ConfigKeys::KeyAppKey).unwrap();
        assert!(updated_config.get(&ConfigKeys::KeyAppKey).is_none());
    }

    #[test]
    fn test_delete_all() {
        let mut storage = InMemoryKeyValueStorage::new(None).unwrap();

        // Test deleting all from an empty storage
        let updated_config = storage.delete_all().unwrap();
        assert!(updated_config.is_empty());

        // Test deleting all after adding some entries
        let mut storage_second = create_initialized_storage();
        let updated_config = storage_second.delete_all().unwrap();
        assert!(updated_config.is_empty());
    }

    #[test]
    fn test_contains() {
        let storage = create_initialized_storage();

        // Test checking for a non-existent key
        assert!(!storage.contains(ConfigKeys::KeyHostname).unwrap());

        // Test checking for an existing key
        assert!(storage.contains(ConfigKeys::KeyAppKey).unwrap());
    }

    #[test]
    fn test_is_empty() {
        let storage = InMemoryKeyValueStorage::new(None).unwrap();

        // Test checking if newly created storage is empty
        assert!(storage.is_empty().unwrap());

        // Test checking if storage is not empty after adding an entry
        let storage_second = create_initialized_storage();
        assert!(!storage_second.is_empty().unwrap());
    }

    // tests to create a InMemoryKeyValueStorage object with a string config
    #[test]
    fn test_create_storage_from_json() {
        let json_config = r#"{
            "url": "https://example.com",
            "clientId": "myClientId",
            "clientKey": "myClientKey",
            "appKey": "myAppKey",
            "appOwnerPublicKey": "ownerPublicKey",
            "privateKey": "clientPrivateKey",
            "serverPublicKeyId": "serverPublicKeyId",
            "bat": "bindingToken",
            "bindingKey": "bindingKey",
            "hostname": "localhost"
        }"#;

        let storage = InMemoryKeyValueStorage::new(Some(json_config.to_string())).unwrap();

        // Test retrieving values using the get method
        assert_eq!(
            storage.get(ConfigKeys::KeyUrl).unwrap(),
            Some("https://example.com".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyClientId).unwrap(),
            Some("myClientId".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyClientKey).unwrap(),
            Some("myClientKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyAppKey).unwrap(),
            Some("myAppKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyOwnerPublicKey).unwrap(),
            Some("ownerPublicKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyPrivateKey).unwrap(),
            Some("clientPrivateKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyServerPublicKeyId).unwrap(),
            Some("serverPublicKeyId".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyBindingToken).unwrap(),
            Some("bindingToken".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyBindingKey).unwrap(),
            Some("bindingKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyHostname).unwrap(),
            Some("localhost".to_string())
        );
    }

    #[test]
    fn test_create_storage_from_base64_json() {
        let storage = create_initialized_storage();
        // Test retrieving values using the get method
        assert_eq!(
            storage.get(ConfigKeys::KeyUrl).unwrap(),
            Some("https://example.com".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyClientId).unwrap(),
            Some("myClientId".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyClientKey).unwrap(),
            Some("myClientKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyAppKey).unwrap(),
            Some("myAppKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyOwnerPublicKey).unwrap(),
            Some("ownerPublicKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyPrivateKey).unwrap(),
            Some("clientPrivateKey".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyServerPublicKeyId).unwrap(),
            Some("serverPublicKeyId".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyBindingToken).unwrap(),
            Some("bindingToken".to_string())
        );
        assert_eq!(
            storage.get(ConfigKeys::KeyBindingKey).unwrap(),
            Some("bindingKey".to_string())
        );
    }

    #[test]
    fn test_create_storage_with_invalid_json() {
        let invalid_json = r#"{
            "url": "https://example.com",
            "clientId": "myClientId",
            "clientKey": "myClientKey",
            "invalidKey": "value"
        }"#; // This key is not valid

        let result = InMemoryKeyValueStorage::new(Some(invalid_json.to_string()));
        assert!(result.is_err()); // Expecting an error due to invalid key
    }

    #[test]
    fn test_create_storage_with_empty_string() {
        let storage = InMemoryKeyValueStorage::new(Some("".to_string())).unwrap();
        assert!(storage.is_empty().unwrap()); // Expecting storage to be empty
    }

    #[test]
    fn test_get_nonexistent_key() {
        let json_config = r#"{
            "url": "https://example.com"
        }"#;

        let storage = InMemoryKeyValueStorage::new(Some(json_config.to_string())).unwrap();

        // Test getting a key that doesn't exist
        assert_eq!(storage.get(ConfigKeys::KeyClientId).unwrap(), None);
    }

    fn create_initialized_storage() -> InMemoryKeyValueStorage {
        // This function provides an InMemoryStorage  object with all configKeys keys setup except localhost.
        let json_config = r#"{
            "url": "https://example.com",
            "clientId": "myClientId",
            "clientKey": "myClientKey",
            "appKey": "myAppKey",
            "appOwnerPublicKey": "ownerPublicKey",
            "privateKey": "clientPrivateKey",
            "serverPublicKeyId": "serverPublicKeyId",
            "bat": "bindingToken",
            "bindingKey": "bindingKey"
        }"#;

        let base64_config = STANDARD.encode(json_config);

        let storage = InMemoryKeyValueStorage::new(Some(base64_config)).unwrap();
        return storage;
    }
}