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

//! Caching module tests
//!
//! Note: These tests modify environment variables and filesystem state.
//! Each test uses a unique cache directory to avoid conflicts.
//! If tests fail due to concurrency, run with: `cargo test --test caching_tests -- --test-threads=1`

#[cfg(test)]
mod caching_tests {
    use keeper_secrets_manager_core::caching::{
        cache_exists, clear_cache, get_cache_file_path, get_cached_data, save_cache,
    };
    use serial_test::serial;
    use std::env;
    use std::fs;
    use std::path::PathBuf;

    use std::sync::atomic::{AtomicU32, Ordering};
    static TEST_COUNTER: AtomicU32 = AtomicU32::new(0);

    /// Helper: Generate unique cache directory for test isolation
    fn get_test_cache_dir() -> PathBuf {
        let counter = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let test_id = format!("{}_{}", std::process::id(), counter);
        let temp_dir = env::temp_dir();
        temp_dir.join(format!("ksm_test_cache_{}", test_id))
    }

    /// Helper: Setup test cache environment
    fn setup_test_cache() -> (String, PathBuf) {
        let test_dir = get_test_cache_dir();
        fs::create_dir_all(&test_dir).unwrap();
        let cache_dir_str = test_dir.to_str().unwrap().to_string();
        (cache_dir_str, test_dir)
    }

    /// Helper: Cleanup test cache
    fn cleanup_test_cache(test_dir: PathBuf) {
        if test_dir.exists() {
            fs::remove_dir_all(&test_dir).ok();
        }
    }

    /// Test: Save and retrieve cache data
    #[test]
    #[serial]
    fn test_save_and_get_cache() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        let test_data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

        // Save cache
        let save_result = save_cache(&test_data);
        assert!(save_result.is_ok());

        // Retrieve cache
        let cached_data = get_cached_data();
        assert!(cached_data.is_some());
        assert_eq!(cached_data.unwrap(), test_data);

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache exists check
    #[test]
    #[serial]
    fn test_cache_exists() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        // Initially no cache
        assert!(!cache_exists());

        // Save some data
        let test_data = vec![1, 2, 3];
        save_cache(&test_data).unwrap();

        // Now cache should exist
        assert!(cache_exists());

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Clear cache
    #[test]
    #[serial]
    fn test_clear_cache() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        // Save some data
        let test_data = vec![1, 2, 3, 4, 5];
        save_cache(&test_data).unwrap();
        assert!(cache_exists());

        // Clear cache
        let clear_result = clear_cache();
        assert!(clear_result.is_ok());
        assert!(!cache_exists());

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Clear cache when no cache exists
    #[test]
    #[serial]
    fn test_clear_cache_when_not_exists() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        // No cache exists
        assert!(!cache_exists());

        // Clear should still succeed
        let clear_result = clear_cache();
        assert!(clear_result.is_ok());

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Get cached data when no cache exists
    #[test]
    #[serial]
    fn test_get_cached_data_not_exists() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        let cached_data = get_cached_data();
        assert!(cached_data.is_none());

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Save empty data to cache
    #[test]
    #[serial]
    fn test_save_empty_cache() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        let empty_data = vec![];
        let save_result = save_cache(&empty_data);
        assert!(save_result.is_ok());

        let cached_data = get_cached_data();
        assert!(cached_data.is_some());
        assert_eq!(cached_data.unwrap().len(), 0);

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Save large data to cache
    #[test]
    #[serial]
    fn test_save_large_cache() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        // 1MB of data
        let large_data = vec![0u8; 1024 * 1024];
        let save_result = save_cache(&large_data);
        assert!(save_result.is_ok());

        let cached_data = get_cached_data();
        assert!(cached_data.is_some());
        assert_eq!(cached_data.unwrap().len(), 1024 * 1024);

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache overwrite
    #[test]
    #[serial]
    fn test_cache_overwrite() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        // Save initial data
        let initial_data = vec![1, 2, 3];
        save_cache(&initial_data).unwrap();

        // Verify initial data
        let cached = get_cached_data().unwrap();
        assert_eq!(cached, initial_data);

        // Overwrite with new data
        let new_data = vec![4, 5, 6, 7, 8];
        save_cache(&new_data).unwrap();

        // Verify new data
        let cached = get_cached_data().unwrap();
        assert_eq!(cached, new_data);
        assert_ne!(cached, initial_data);

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache file path respects KSM_CACHE_DIR environment variable
    #[test]
    #[serial]
    fn test_cache_file_path_custom_dir() {
        let custom_dir = "/custom/cache/dir";
        env::set_var("KSM_CACHE_DIR", custom_dir);

        let cache_path = get_cache_file_path();
        assert!(cache_path.to_str().unwrap().contains(custom_dir));
        assert!(cache_path.to_str().unwrap().contains("ksm_cache.bin"));

        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache file path uses default directory when env var not set
    #[test]
    #[serial]
    fn test_cache_file_path_default_dir() {
        env::remove_var("KSM_CACHE_DIR");

        let cache_path = get_cache_file_path();
        assert!(cache_path.to_str().unwrap().ends_with("ksm_cache.bin"));

        // Should use current directory (".")
        let expected_path = PathBuf::from(".").join("ksm_cache.bin");
        assert_eq!(cache_path, expected_path);
    }

    /// Test: Binary data roundtrip through cache
    #[test]
    #[serial]
    fn test_cache_binary_data_roundtrip() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        let binary_data = vec![
            0x00, 0xFF, 0x42, 0x13, 0x37, 0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE,
        ];

        save_cache(&binary_data).unwrap();
        let cached = get_cached_data().unwrap();

        assert_eq!(cached, binary_data);

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache data integrity with transmission key prefix
    #[test]
    #[serial]
    fn test_cache_transmission_key_format() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        // Simulate cache format: 32-byte transmission key + encrypted response
        let transmission_key = vec![0u8; 32]; // 32-byte key
        let encrypted_response = vec![1, 2, 3, 4, 5, 6, 7, 8]; // Response data

        let mut cache_data = transmission_key.clone();
        cache_data.extend_from_slice(&encrypted_response);

        // Save combined data
        save_cache(&cache_data).unwrap();

        // Retrieve and verify
        let cached = get_cached_data().unwrap();
        assert_eq!(cached.len(), 32 + 8); // Key + response
        assert_eq!(&cached[0..32], &transmission_key[..]);
        assert_eq!(&cached[32..], &encrypted_response[..]);

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Multiple save operations (stress test)
    #[test]
    #[serial]
    fn test_cache_multiple_saves() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        for i in 0..10 {
            let data = vec![i as u8; 100];
            let save_result = save_cache(&data);
            assert!(save_result.is_ok());

            let cached = get_cached_data().unwrap();
            assert_eq!(cached, data);
        }

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache data with minimum size (transmission key only)
    #[test]
    #[serial]
    fn test_cache_minimum_size() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        // Minimum valid cache: 32-byte transmission key
        let minimum_data = vec![0u8; 32];
        save_cache(&minimum_data).unwrap();

        let cached = get_cached_data().unwrap();
        assert_eq!(cached.len(), 32);

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache data with realistic size
    #[test]
    #[serial]
    fn test_cache_realistic_size() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        // Realistic cache size: 32-byte key + ~37KB response (from manual testing)
        let transmission_key = vec![0u8; 32];
        let encrypted_response = vec![1u8; 37_000];

        let mut cache_data = transmission_key;
        cache_data.extend_from_slice(&encrypted_response);

        save_cache(&cache_data).unwrap();
        let cached = get_cached_data().unwrap();

        assert_eq!(cached.len(), 32 + 37_000);

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache survives multiple clear operations
    #[test]
    #[serial]
    fn test_cache_multiple_clears() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        let test_data = vec![1, 2, 3, 4, 5];
        save_cache(&test_data).unwrap();
        assert!(cache_exists());

        // Clear multiple times
        for _ in 0..5 {
            let clear_result = clear_cache();
            assert!(clear_result.is_ok());
            assert!(!cache_exists());
        }

        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Cache file path format
    #[test]
    #[serial]
    fn test_cache_file_path_format() {
        env::set_var("KSM_CACHE_DIR", "/tmp/test");

        let path = get_cache_file_path();
        let path_str = path.to_str().unwrap();

        assert!(path_str.contains("ksm_cache.bin"));
        assert!(path_str.contains("/tmp/test"));

        env::remove_var("KSM_CACHE_DIR");
    }

    /// Test: Caching module is accessible and round-trips data through env-driven path
    #[test]
    #[serial]
    fn test_caching_module_exists() {
        let (cache_dir, test_dir) = setup_test_cache();
        env::set_var("KSM_CACHE_DIR", &cache_dir);

        let cache_path = get_cache_file_path();
        assert!(cache_path.to_str().unwrap().contains("ksm_cache.bin"));

        let _ = clear_cache();
        assert!(!cache_exists(), "Cache should not exist after clearing");

        let test_data = b"test cache data for validation";
        save_cache(test_data).expect("Failed to save cache data");
        assert!(
            cache_exists(),
            "Cache should exist after saving. Path: {:?}",
            cache_path
        );

        let loaded = get_cached_data().expect("Failed to retrieve cached data");
        assert_eq!(loaded, test_data, "Cached data should match original");

        clear_cache().expect("Failed to clear cache");
        cleanup_test_cache(test_dir);
        env::remove_var("KSM_CACHE_DIR");
    }

    /// Regression test for KSM-931: make_caching_post_function must not panic
    /// when called from inside tokio::task::spawn_blocking.
    ///
    /// Without the fix (bare caching_post_function calling Client::builder().build()
    /// per call), this scenario panics with:
    ///   "Cannot drop a runtime in a context where blocking is not allowed"
    ///
    /// With the fix (factory captures a pre-built Client), it returns a clean
    /// network error instead — no panic. Test fails to compile before the fix
    /// because make_caching_post_function does not exist yet.
    #[test]
    fn test_make_caching_post_function_runs_under_spawn_blocking() {
        use keeper_secrets_manager_core::caching::make_caching_post_function;
        use keeper_secrets_manager_core::dto::{EncryptedPayload, TransmissionKey};
        use p256::ecdsa::{signature::Signer, SigningKey};

        // Generate a deterministic signature for the EncryptedPayload constructor.
        // The server is never reached (port 1 is unreachable) so cryptographic
        // validity is irrelevant; we just need a structurally valid value.
        let signing_key = SigningKey::from_slice(&[42u8; 32]).expect("valid test scalar");
        let raw_sig: p256::ecdsa::Signature = signing_key.sign(b"ksm-931-regression-test");
        let der_sig: ecdsa::der::Signature<p256::NistP256> = raw_sig.into();

        let tk = TransmissionKey::new("10".to_string(), vec![0u8; 32], vec![0u8; 32]);
        let ep = EncryptedPayload::new(vec![0u8; 16], der_sig);

        // Build the client OUTSIDE any async context — the correct usage pattern.
        let client = reqwest::blocking::Client::builder()
            .build()
            .expect("build client outside runtime");

        let post_fn = make_caching_post_function(client);

        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("build tokio runtime");

        let result = rt.block_on(async {
            tokio::task::spawn_blocking(move || {
                // Port 1 is unreachable — we expect a network error, not a panic.
                post_fn("http://127.0.0.1:1/test".to_string(), tk, ep)
            })
            .await
        });

        // spawn_blocking must not have panicked — if it did, await returns
        // Err(JoinError::Panicked).
        assert!(
            result.is_ok(),
            "spawn_blocking panicked (nested-runtime bug still present): {:?}",
            result
        );
        // The inner call should return a network error (connection refused), not Ok.
        let inner = result.unwrap();
        assert!(
            inner.is_err(),
            "expected network error against 127.0.0.1:1, got Ok"
        );
    }
}