merka-vault 0.3.2

Vault provisioning and management crate integrating with merka-core
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
use log::info;
use merka_vault::database::{DatabaseManager, VaultCredentials};
use serde_json::{json, Value};
use serial_test::serial;

mod database_utils;
mod test_utils;

use database_utils::{load_vault_credentials, save_vault_credentials, setup_test_database};
use test_utils::{is_server_running, setup_logging, DockerComposeEnv};

// This is a comprehensive integration test that mirrors the functionality
// in examples/test_client.rs but follows proper testing patterns
#[tokio::test]
#[serial]
async fn test_vault_setup_flow() {
    setup_logging();
    info!("Starting vault setup flow integration test");

    // Check if the server is already running
    if !is_server_running().await {
        info!("Web server not running. This test requires the server to be running.");
        info!("Start the server in another terminal with: cargo run -- server");
        info!("Skipping test_vault_setup_flow");
        return;
    }

    info!("Server is running. Proceeding with test.");

    // Test database path - use unique path to avoid conflicts
    let db_path = "test_integration_flow.db";

    // Clean up any existing test DB
    let _ = std::fs::remove_file(db_path);

    // Start docker-compose for the vault instances
    let mut docker = DockerComposeEnv::new();
    match docker.start() {
        Ok(_) => info!("Docker environment started successfully"),
        Err(e) => {
            info!("Docker environment start failed: {}. Test skipped.", e);
            return;
        }
    }

    // Create database manager for vault credentials
    let db_manager = match setup_test_database("test_integration_flow") {
        Ok(manager) => manager,
        Err(e) => {
            info!("Failed to create database: {}", e);
            // Stop Docker before returning
            if let Err(stop_err) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", stop_err);
            }
            return;
        }
    };

    // Initialize credentials structure
    let mut credentials = VaultCredentials::default();

    // Create HTTP client for API requests
    let client = reqwest::Client::new();

    // Step 1: Check initial vault status
    info!("Checking initial vault status");
    let status_res = client.get("http://localhost:8080/api/status").send().await;

    // Continue with the rest of the test implementation...
    match status_res {
        Ok(res) => {
            if res.status().is_success() {
                let status = match res.json::<Value>().await {
                    Ok(val) => val,
                    Err(e) => {
                        info!("Failed to parse status JSON: {}", e);
                        // Stop Docker before returning
                        if let Err(stop_err) = docker.stop() {
                            info!("Failed to stop Docker Compose: {}", stop_err);
                        }
                        return;
                    }
                };
                info!("Server status: {:?}", status);
            } else {
                let status = res.status();
                let error_text = res
                    .text()
                    .await
                    .unwrap_or_else(|_| "No error text".to_string());
                info!(
                    "Server returned non-success status: {}, {}",
                    status, error_text
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }
        }
        Err(e) => {
            info!("Failed to connect to server status endpoint: {}", e);
            // Stop Docker before returning
            if let Err(e) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", e);
            }
            return;
        }
    }

    // Step 2: Initialize the root vault
    info!("Initializing root vault");
    let init_res = client
        .post("http://localhost:8080/api/vault/init")
        .json(&json!({
            "secret_shares": 1,
            "secret_threshold": 1
        }))
        .send()
        .await;

    match init_res {
        Ok(res) => {
            let status = res.status();
            if status.is_success() {
                let init_result = match res.json::<Value>().await {
                    Ok(val) => val,
                    Err(e) => {
                        info!("Failed to parse init JSON: {}", e);
                        // Stop Docker before returning
                        if let Err(stop_err) = docker.stop() {
                            info!("Failed to stop Docker Compose: {}", stop_err);
                        }
                        return;
                    }
                };
                info!("Initialization result: {:?}", init_result);

                // Extract and store credentials
                if let Some(result) = init_result.get("result") {
                    if let Some(token) = result.get("root_token") {
                        credentials.root_token = token.as_str().unwrap_or("").to_string();
                    }
                    if let Some(keys) = result.get("keys") {
                        credentials.root_unseal_keys = keys
                            .as_array()
                            .unwrap_or(&Vec::new())
                            .iter()
                            .map(|k| k.as_str().unwrap_or("").to_string())
                            .collect();
                    }
                }
            } else {
                let error_text = res
                    .text()
                    .await
                    .unwrap_or_else(|_| "No error text".to_string());
                info!(
                    "Root vault initialization failed with status {}: {}",
                    status, error_text
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }
        }
        Err(e) => {
            info!("Failed to initialize root vault: {}", e);
            // Stop Docker before returning
            if let Err(e) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", e);
            }
            return;
        }
    }

    // Step 3: Unseal the root vault
    info!("Unsealing root vault");
    let unseal_res = client
        .post("http://localhost:8080/api/vault/unseal")
        .json(&json!({
            "keys": credentials.root_unseal_keys
        }))
        .send()
        .await;

    match unseal_res {
        Ok(res) => {
            let status = res.status();
            if status.is_success() {
                let unseal_result = match res.json::<Value>().await {
                    Ok(val) => val,
                    Err(e) => {
                        info!("Failed to parse unseal JSON: {}", e);
                        // Stop Docker before returning
                        if let Err(stop_err) = docker.stop() {
                            info!("Failed to stop Docker Compose: {}", stop_err);
                        }
                        return;
                    }
                };
                info!("Unseal result: {:?}", unseal_result);
            } else {
                let error_text = res
                    .text()
                    .await
                    .unwrap_or_else(|_| "No error text".to_string());
                info!(
                    "Root vault unseal failed with status {}: {}",
                    status, error_text
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }
        }
        Err(e) => {
            info!("Failed to unseal root vault: {}", e);
            // Stop Docker before returning
            if let Err(e) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", e);
            }
            return;
        }
    }

    // Step 4: Set up transit engine
    info!("Setting up transit engine");
    let transit_res = client
        .post("http://localhost:8080/api/vault/setup-transit")
        .json(&json!({
            "token": credentials.root_token
        }))
        .send()
        .await;

    match transit_res {
        Ok(res) => {
            let status = res.status();
            if status.is_success() {
                let transit_result = match res.json::<Value>().await {
                    Ok(val) => val,
                    Err(e) => {
                        info!("Failed to parse transit setup JSON: {}", e);
                        // Stop Docker before returning
                        if let Err(stop_err) = docker.stop() {
                            info!("Failed to stop Docker Compose: {}", stop_err);
                        }
                        return;
                    }
                };
                info!("Transit setup result: {:?}", transit_result);

                // Extract transit token
                if let Some(token) = transit_result.get("transit_token") {
                    credentials.transit_token = token.as_str().unwrap_or("").to_string();
                }
            } else {
                let error_text = res
                    .text()
                    .await
                    .unwrap_or_else(|_| "No error text".to_string());
                info!(
                    "Transit setup failed with status {}: {}",
                    status, error_text
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }
        }
        Err(e) => {
            info!("Failed to set up transit engine: {}", e);
            // Stop Docker before returning
            if let Err(e) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", e);
            }
            return;
        }
    }

    // Step 5: Initialize sub vault
    info!("Initializing sub vault");
    let sub_init_res = client
        .post("http://localhost:8080/api/vault/init-sub")
        .json(&json!({
            "transit_token": credentials.transit_token
        }))
        .send()
        .await;

    match sub_init_res {
        Ok(res) => {
            let status = res.status();
            if status.is_success() {
                let sub_init_result = match res.json::<Value>().await {
                    Ok(val) => val,
                    Err(e) => {
                        info!("Failed to parse sub init JSON: {}", e);
                        // Stop Docker before returning
                        if let Err(stop_err) = docker.stop() {
                            info!("Failed to stop Docker Compose: {}", stop_err);
                        }
                        return;
                    }
                };
                info!("Sub vault initialization result: {:?}", sub_init_result);

                // Extract sub token
                if let Some(token) = sub_init_result.get("token") {
                    credentials.sub_token = token.as_str().unwrap_or("").to_string();
                }
            } else {
                let error_text = res
                    .text()
                    .await
                    .unwrap_or_else(|_| "No error text".to_string());
                info!(
                    "Sub vault initialization failed with status {}: {}",
                    status, error_text
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }
        }
        Err(e) => {
            info!("Failed to initialize sub vault: {}", e);
            // Stop Docker before returning
            if let Err(e) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", e);
            }
            return;
        }
    }

    // Save credentials to database
    info!("Saving vault credentials to database");
    if let Err(e) = save_vault_credentials(&db_manager, &credentials) {
        info!("Failed to save credentials to database: {}", e);
        // Stop Docker before returning
        if let Err(e) = docker.stop() {
            info!("Failed to stop Docker Compose: {}", e);
        }
        return;
    }

    // Step 6: Load credentials to verify
    info!("Loading vault credentials from database");
    match load_vault_credentials(&db_manager) {
        Ok(loaded_creds) => {
            info!("Loaded credentials from database");

            // Check that credentials match what was saved - use if statements instead of assert
            if loaded_creds.root_token != credentials.root_token {
                info!(
                    "Root token mismatch: expected '{}', got '{}'",
                    credentials.root_token, loaded_creds.root_token
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }

            if loaded_creds.root_unseal_keys != credentials.root_unseal_keys {
                info!(
                    "Root unseal keys mismatch: expected {:?}, got {:?}",
                    credentials.root_unseal_keys, loaded_creds.root_unseal_keys
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }

            if loaded_creds.sub_token != credentials.sub_token {
                info!(
                    "Sub token mismatch: expected '{}', got '{}'",
                    credentials.sub_token, loaded_creds.sub_token
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }

            if loaded_creds.transit_token != credentials.transit_token {
                info!(
                    "Transit token mismatch: expected '{}', got '{}'",
                    credentials.transit_token, loaded_creds.transit_token
                );
                // Stop Docker before returning
                if let Err(e) = docker.stop() {
                    info!("Failed to stop Docker Compose: {}", e);
                }
                return;
            }

            info!("All credentials verified successfully");
        }
        Err(e) => {
            info!("Failed to load credentials from database: {}", e);
            // Make sure to stop Docker before returning
            if let Err(e) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", e);
            }
            return;
        }
    }

    // Explicitly stop Docker Compose
    if let Err(e) = docker.stop() {
        info!("Failed to stop Docker Compose: {}", e);
    } else {
        info!("Docker Compose environment stopped successfully");
    }

    info!("Vault setup flow integration test completed successfully");
}

// Test that focuses just on the database functionality
#[tokio::test]
#[serial]
async fn test_database_operations() {
    setup_logging();
    info!("Testing database operations");

    // Start docker-compose environment
    let mut docker = DockerComposeEnv::new();
    match docker.start() {
        Ok(_) => info!("Docker environment started successfully"),
        Err(e) => {
            info!("Docker environment start failed: {}. Test skipped.", e);
            return;
        }
    }

    // Use a dedicated database file for this test
    let db_path = "test_db_operations.db";
    let _ = std::fs::remove_file(db_path);

    // Create database manager
    let db_manager = match DatabaseManager::new(db_path) {
        Ok(manager) => manager,
        Err(e) => {
            info!("Failed to create DatabaseManager: {}", e);
            // Stop Docker before returning
            if let Err(stop_err) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", stop_err);
            }
            return;
        }
    };

    // Test saving and loading credentials
    let test_credentials = VaultCredentials {
        root_token: "test-root-token".to_string(),
        root_unseal_keys: vec!["key1".to_string(), "key2".to_string()],
        sub_token: "test-sub-token".to_string(),
        transit_token: "test-transit-token".to_string(),
    };

    if let Err(e) = save_vault_credentials(&db_manager, &test_credentials) {
        info!("Failed to save credentials: {}", e);
        // Stop Docker before returning
        if let Err(stop_err) = docker.stop() {
            info!("Failed to stop Docker Compose: {}", stop_err);
        }
        return;
    }

    let loaded_credentials = match load_vault_credentials(&db_manager) {
        Ok(creds) => creds,
        Err(e) => {
            info!("Failed to load credentials: {}", e);
            // Stop Docker before returning
            if let Err(stop_err) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", stop_err);
            }
            return;
        }
    };

    // Verify loaded credentials match what was saved
    assert_eq!(
        loaded_credentials.root_token, test_credentials.root_token,
        "Root token mismatch"
    );
    assert_eq!(
        loaded_credentials.sub_token, test_credentials.sub_token,
        "Sub token mismatch"
    );
    assert_eq!(
        loaded_credentials.transit_token, test_credentials.transit_token,
        "Transit token mismatch"
    );
    assert_eq!(
        loaded_credentials.root_unseal_keys.len(),
        test_credentials.root_unseal_keys.len(),
        "Root unseal keys count mismatch"
    );

    // Test saving, loading, and deleting unsealer relationships
    let sub_addr = "http://127.0.0.1:8202";
    let root_addr = "http://127.0.0.1:8200";

    // Save relationship
    if let Err(e) = db_manager.save_unsealer_relationship(sub_addr, root_addr) {
        info!("Failed to save unsealer relationship: {}", e);
        // Stop Docker before returning
        if let Err(stop_err) = docker.stop() {
            info!("Failed to stop Docker Compose: {}", stop_err);
        }
        return;
    }

    // Verify it was saved
    let relationships = match db_manager.load_unsealer_relationships() {
        Ok(rels) => rels,
        Err(e) => {
            info!("Failed to load unsealer relationships: {}", e);
            // Stop Docker before returning
            if let Err(stop_err) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", stop_err);
            }
            return;
        }
    };

    assert_eq!(relationships.len(), 1, "Expected one unsealer relationship");
    assert!(
        relationships.contains_key(sub_addr),
        "Expected sub vault address in relationships"
    );
    assert_eq!(
        relationships.get(sub_addr).unwrap(),
        root_addr,
        "Root vault address mismatch"
    );

    // Add a second relationship
    let sub_addr2 = "http://127.0.0.1:8203";
    if let Err(e) = db_manager.save_unsealer_relationship(sub_addr2, root_addr) {
        info!("Failed to save second unsealer relationship: {}", e);
        // Stop Docker before returning
        if let Err(stop_err) = docker.stop() {
            info!("Failed to stop Docker Compose: {}", stop_err);
        }
        return;
    }

    // Verify both relationships exist
    let relationships = match db_manager.load_unsealer_relationships() {
        Ok(rels) => rels,
        Err(e) => {
            info!("Failed to load unsealer relationships: {}", e);
            // Stop Docker before returning
            if let Err(stop_err) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", stop_err);
            }
            return;
        }
    };

    assert_eq!(
        relationships.len(),
        2,
        "Expected two unsealer relationships"
    );

    // Delete first relationship
    if let Err(e) = db_manager.delete_unsealer_relationship(sub_addr) {
        info!("Failed to delete unsealer relationship: {}", e);
        // Stop Docker before returning
        if let Err(stop_err) = docker.stop() {
            info!("Failed to stop Docker Compose: {}", stop_err);
        }
        return;
    }

    // Verify only the second relationship remains
    let relationships = match db_manager.load_unsealer_relationships() {
        Ok(rels) => rels,
        Err(e) => {
            info!("Failed to load unsealer relationships: {}", e);
            // Stop Docker before returning
            if let Err(stop_err) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", stop_err);
            }
            return;
        }
    };

    assert_eq!(
        relationships.len(),
        1,
        "Expected one unsealer relationship after deletion"
    );
    assert!(
        !relationships.contains_key(sub_addr),
        "Deleted relationship should not be present"
    );
    assert!(
        relationships.contains_key(sub_addr2),
        "Second relationship should still be present"
    );

    // Delete second relationship
    if let Err(e) = db_manager.delete_unsealer_relationship(sub_addr2) {
        info!("Failed to delete second unsealer relationship: {}", e);
        // Stop Docker before returning
        if let Err(stop_err) = docker.stop() {
            info!("Failed to stop Docker Compose: {}", stop_err);
        }
        return;
    }

    // Verify no relationships remain
    let relationships = match db_manager.load_unsealer_relationships() {
        Ok(rels) => rels,
        Err(e) => {
            info!("Failed to load unsealer relationships: {}", e);
            // Stop Docker before returning
            if let Err(stop_err) = docker.stop() {
                info!("Failed to stop Docker Compose: {}", stop_err);
            }
            return;
        }
    };

    assert_eq!(
        relationships.len(),
        0,
        "Expected no unsealer relationships after deletion"
    );

    // Clean up
    let _ = std::fs::remove_file(db_path);

    // Explicitly stop Docker at the end of the test
    if let Err(e) = docker.stop() {
        info!("Failed to stop Docker Compose: {}", e);
    } else {
        info!("Docker Compose environment stopped successfully");
    }

    info!("Database operations test completed successfully");
}