ckms 5.20.1

Command Line Interface used to manage the Cosmian KMS server. If any assistance is needed, please either visit the Cosmian technical documentation at https://docs.cosmian.com or contact the Cosmian support team on Discord https://discord.com/invite/7kPMNtHpnz
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
#[cfg(feature = "non-fips")]
use std::path::Path;
use std::process::Command;

use assert_cmd::prelude::*;
use clap::ValueEnum;
#[cfg(feature = "non-fips")]
use cosmian_kms_cli_actions::reexport::cosmian_kms_client::{
    kmip_0::kmip_types::BlockCipherMode,
    kmip_2_1::{
        kmip_data_structures::KeyMaterial,
        kmip_types::{CryptographicAlgorithm, RecommendedCurve},
    },
    pad_be_bytes,
};
use cosmian_kms_cli_actions::{
    actions::symmetric::keys::create_key::CreateKeyAction,
    reexport::cosmian_kms_client::{
        kmip_2_1::kmip_types::KeyFormatType,
        read_bytes_from_file, read_object_from_json_ttlv_file,
        reexport::cosmian_kms_client_utils::export_utils::{ExportKeyFormat, WrappingAlgorithm},
    },
};
#[cfg(feature = "non-fips")]
use cosmian_logger::log_init;
#[cfg(feature = "non-fips")]
use openssl::pkey::{Id, PKey};
use tempfile::TempDir;
use test_kms_server::start_default_test_kms_server;

#[cfg(feature = "non-fips")]
use crate::tests::cover_crypt::{
    master_key_pair::create_cc_master_key_pair, user_decryption_keys::create_user_decryption_key,
};
use crate::{
    config::CKMS_CONF_ENV,
    error::{CosmianError, result::CosmianResult},
    tests::{
        PROG_NAME, save_kms_cli_config, symmetric::create_key::create_symmetric_key,
        utils::recover_cmd_logs,
    },
};
#[cfg(feature = "non-fips")]
use crate::{
    error::result::CosmianResultHelper,
    tests::{
        elliptic_curve::create_key_pair::create_ec_key_pair,
        rsa::create_key_pair::{RsaKeyPairOptions, create_rsa_key_pair},
    },
};

#[derive(Debug, Default)]
pub(crate) struct ExportKeyParams {
    pub cli_conf_path: String,
    pub sub_command: String,
    pub key_id: String,
    pub key_file: String,
    pub key_format: Option<ExportKeyFormat>,
    pub unwrap: bool,
    pub wrap_key_id: Option<String>,
    pub allow_revoked: bool,
    pub wrapping_algorithm: Option<WrappingAlgorithm>,
}

pub(crate) fn export_key(params: ExportKeyParams) -> CosmianResult<()> {
    let mut args: Vec<String> = [
        "keys",
        "export",
        "--key-id",
        &params.key_id,
        &params.key_file,
    ]
    .iter()
    .map(std::string::ToString::to_string)
    .collect();
    if let Some(key_format) = params.key_format {
        args.push("--key-format".to_owned());
        let arg_value = match key_format {
            ExportKeyFormat::JsonTtlv => "json-ttlv",
            ExportKeyFormat::Sec1Pem => "sec1-pem",
            ExportKeyFormat::Sec1Der => "sec1-der",
            ExportKeyFormat::Pkcs1Pem => "pkcs1-pem",
            ExportKeyFormat::Pkcs1Der => "pkcs1-der",
            ExportKeyFormat::Pkcs8Pem => "pkcs8-pem",
            ExportKeyFormat::Pkcs8Der => "pkcs8-der",
            ExportKeyFormat::Base64 => "base64",
            ExportKeyFormat::Raw => "raw",
        };
        args.push(arg_value.to_owned());
    }
    if params.unwrap {
        args.push("--unwrap".to_owned());
    }
    if let Some(wrap_key_id) = params.wrap_key_id {
        args.push("--wrap-key-id".to_owned());
        args.push(wrap_key_id);
    }
    if params.allow_revoked {
        args.push("--allow-revoked".to_owned());
    }
    if let Some(wrapping_algorithm) = &params.wrapping_algorithm {
        args.push("--wrapping-algorithm".to_owned());
        let name = wrapping_algorithm
            .to_possible_value()
            .expect("valid wrapping algorithm")
            .get_name()
            .to_string();
        args.push(name);
    }

    let mut cmd = Command::cargo_bin(PROG_NAME)?;
    cmd.env(CKMS_CONF_ENV, params.cli_conf_path);
    // Ensure sufficient stack for the child process on Windows
    cmd.env("RUST_MIN_STACK", "16777216");

    cmd.arg(params.sub_command).args(args);
    let output = recover_cmd_logs(&mut cmd);
    if output.status.success() {
        return Ok(());
    }
    Err(CosmianError::Default(
        std::str::from_utf8(&output.stderr)?.to_owned(),
    ))
}

#[tokio::test]
pub(crate) async fn test_export_sym() -> CosmianResult<()> {
    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate a symmetric key
    let key_id = create_symmetric_key(&owner_client_conf_path, CreateKeyAction::default())?;

    // Export as default (JsonTTLV with Raw Key Format Type)
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "sym".to_owned(),
        key_id: key_id.clone(),
        key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
        ..Default::default()
    })?;

    // read the bytes from the exported file
    let object = read_object_from_json_ttlv_file(&tmp_path.join("output.export"))?;
    let key_block = object.key_block()?;
    assert_eq!(key_block.key_format_type, KeyFormatType::Raw);
    let key_bytes = key_block.key_bytes()?;

    // Export the bytes only
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "sym".to_owned(),
        key_id: key_id.clone(),
        key_file: tmp_path
            .join("output.export.bytes")
            .to_str()
            .unwrap()
            .to_owned(),
        key_format: Some(ExportKeyFormat::Raw),
        ..Default::default()
    })?;
    let bytes = read_bytes_from_file(&tmp_path.join("output.export.bytes"))?;
    assert_eq!(&*key_bytes, bytes.as_slice());

    // wrong export format
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path,
            sub_command: "sym".to_owned(),
            key_id,
            key_file: tmp_path
                .join("output.export.bytes")
                .to_str()
                .unwrap()
                .to_owned(),
            key_format: Some(ExportKeyFormat::Pkcs1Pem),
            ..Default::default()
        })
        .is_err()
    );

    Ok(())
}

#[tokio::test]
pub(crate) async fn test_export_sym_allow_revoked() -> CosmianResult<()> {
    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate a symmetric key
    let key_id = create_symmetric_key(&owner_client_conf_path, CreateKeyAction::default())?;
    // Export
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path,
        sub_command: "sym".to_owned(),
        key_id,
        key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
        allow_revoked: true,
        ..Default::default()
    })?;
    Ok(())
}

#[cfg(feature = "non-fips")]
#[tokio::test]
pub(crate) async fn test_export_wrapped() -> CosmianResult<()> {
    log_init(option_env!("RUST_LOG"));
    // log_init(Some("info,cosmian_kms_server=debug"));

    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate a symmetric key
    let (private_key_id, _public_key_id) =
        create_rsa_key_pair(&owner_client_conf_path, &RsaKeyPairOptions::default())?;

    // generate a symmetric key
    let sym_key_id = create_symmetric_key(&owner_client_conf_path, CreateKeyAction::default())?;

    // Export wrapped key with a symmetric key as default (JsonTTLV with Raw Key Format Type)
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "rsa".to_owned(),
        key_id: private_key_id.clone(),
        key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
        wrap_key_id: Some(sym_key_id.clone()),
        ..Default::default()
    })?;

    let object = read_object_from_json_ttlv_file(&tmp_path.join("output.export"))?;
    let key_bytes = object
        .key_block()?
        .wrapped_key_bytes()
        .context("exported wrapped key")?;
    let cryptographic_parameters = object
        .key_block()?
        .key_wrapping_data
        .clone()
        .unwrap()
        .encryption_key_information
        .unwrap()
        .cryptographic_parameters;
    assert_eq!(cryptographic_parameters, None);

    // Wrapping with symmetric key should be by default with rfc5649
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "rsa".to_owned(),
        key_id: private_key_id.clone(),
        key_file: tmp_path
            .join("output_2.export")
            .to_str()
            .unwrap()
            .to_owned(),
        wrap_key_id: Some(sym_key_id.clone()),
        ..Default::default()
    })?;

    let object_2 = read_object_from_json_ttlv_file(&tmp_path.join("output_2.export"))?;
    let key_bytes_2 = object_2
        .key_block()?
        .wrapped_key_bytes()
        .context("object 2")?;
    let cryptographic_parameters = object_2
        .key_block()?
        .key_wrapping_data
        .clone()
        .unwrap()
        .encryption_key_information
        .unwrap()
        .cryptographic_parameters;
    assert_eq!(cryptographic_parameters, None);

    assert_eq!(key_bytes, key_bytes_2);

    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "rsa".to_owned(),
        key_id: private_key_id.clone(),
        key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
        wrap_key_id: Some(sym_key_id.clone()),
        wrapping_algorithm: Some(WrappingAlgorithm::NistKeyWrap),
        ..Default::default()
    })?;

    // Export wrapped key with a symmetric key using AESGCM as default (JsonTTLV with Raw Key Format Type)
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "rsa".to_owned(),
        key_id: private_key_id.clone(),
        key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
        wrap_key_id: Some(sym_key_id.clone()),
        wrapping_algorithm: Some(WrappingAlgorithm::AesGCM),
        ..Default::default()
    })?;

    let object = read_object_from_json_ttlv_file(&tmp_path.join("output.export"))?;
    let block_cipher_mode = object
        .key_block()?
        .key_wrapping_data
        .clone()
        .unwrap()
        .encryption_key_information
        .unwrap()
        .cryptographic_parameters
        .unwrap()
        .block_cipher_mode
        .unwrap();
    assert_eq!(block_cipher_mode, BlockCipherMode::GCM);

    // Block-cipher-mode option raises an error when not using symmetric key for wrapping
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path,
            sub_command: "rsa".to_owned(),
            key_id: sym_key_id,
            key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
            wrap_key_id: Some(private_key_id),
            wrapping_algorithm: Some(WrappingAlgorithm::AesGCM),
            ..Default::default()
        })
        .is_err()
    );

    Ok(())
}

#[cfg(feature = "non-fips")]
#[tokio::test]
pub(crate) async fn test_export_covercrypt() -> CosmianResult<()> {
    fn export_cc_test(
        key_format_type: KeyFormatType,
        key_id: &str,
        tmp_path: &Path,
        owner_client_conf_path: &str,
    ) -> CosmianResult<()> {
        // Export the key
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path.to_string(),
            sub_command: "cc".to_owned(),
            key_id: key_id.to_owned(),
            key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
            ..Default::default()
        })?;

        // read the bytes from the exported file
        let object = read_object_from_json_ttlv_file(&tmp_path.join("output.export"))?;
        let key_block = object.key_block()?;
        assert_eq!(key_block.key_format_type, key_format_type);
        let key_bytes = key_block.covercrypt_key_bytes()?;

        // Export the key bytes only
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path.to_string(),
            sub_command: "cc".to_owned(),
            key_id: key_id.to_owned(),
            key_file: tmp_path
                .join("output.export.bytes")
                .to_str()
                .unwrap()
                .to_owned(),
            key_format: Some(ExportKeyFormat::Raw),
            ..Default::default()
        })?;
        let bytes = read_bytes_from_file(&tmp_path.join("output.export.bytes"))?;
        assert_eq!(&*key_bytes, bytes.as_slice());
        Ok(())
    }

    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate a new master key pair
    let (master_private_key_id, master_public_key_id) = create_cc_master_key_pair(
        &owner_client_conf_path,
        "--specification",
        "../../../test_data/access_structure_specifications.json",
        &[],
        false,
    )?;

    export_cc_test(
        KeyFormatType::CoverCryptSecretKey,
        &master_private_key_id,
        tmp_path,
        &owner_client_conf_path,
    )?;
    export_cc_test(
        KeyFormatType::CoverCryptPublicKey,
        &master_public_key_id,
        tmp_path,
        &owner_client_conf_path,
    )?;

    let user_key_id = create_user_decryption_key(
        &owner_client_conf_path,
        &master_private_key_id,
        "(Department::MKG || Department::FIN) && Security Level::Top Secret",
        &[],
        false,
    )?;
    export_cc_test(
        KeyFormatType::CoverCryptSecretKey,
        &user_key_id,
        tmp_path,
        &owner_client_conf_path,
    )?;

    Ok(())
}

#[cfg(feature = "non-fips")]
#[tokio::test]
pub(crate) async fn test_export_error_cover_crypt() -> CosmianResult<()> {
    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // key does not exist
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "cc".to_owned(),
        key_id: "does_not_exist".to_owned(),
        key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
        ..Default::default()
    })
    .err()
    .unwrap();

    // generate a new master key pair
    let (master_private_key_id, _master_public_key_id) = create_cc_master_key_pair(
        &owner_client_conf_path,
        "--specification",
        "../../../test_data/access_structure_specifications.json",
        &[],
        false,
    )?;

    // Export to non existing dir
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path,
        sub_command: "cc".to_owned(),
        key_id: master_private_key_id,
        key_file: "/does_not_exist/output.export".to_owned(),
        ..Default::default()
    })
    .err()
    .unwrap();

    Ok(())
}

#[cfg(feature = "non-fips")]
#[tokio::test]
pub(crate) async fn test_export_x25519() -> CosmianResult<()> {
    // create a temp dir

    use cosmian_kms_cli_actions::reexport::cosmian_kms_client::kmip_2_1::kmip_data_structures::KeyValue;
    use cosmian_logger::trace;
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate a new key pair
    let (private_key_id, public_key_id) =
        create_ec_key_pair(&owner_client_conf_path, "x25519", &[], false)?;

    // Private Key
    //
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "ec".to_owned(),
        key_id: private_key_id.clone(),
        key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
        ..Default::default()
    })?;

    // read the bytes from the exported file
    let object = read_object_from_json_ttlv_file(&tmp_path.join("output.export"))?;
    let key_block = object.key_block()?;
    assert_eq!(
        key_block.key_format_type,
        KeyFormatType::TransparentECPrivateKey
    );
    assert_eq!(
        key_block.cryptographic_algorithm,
        Some(CryptographicAlgorithm::ECDH)
    );
    let Some(KeyValue::Structure { key_material, .. }) = &key_block.key_value else {
        panic!("Invalid key value type");
    };
    let KeyMaterial::TransparentECPrivateKey {
        d,
        recommended_curve,
    } = key_material
    else {
        panic!("Invalid key material ");
    };
    assert_eq!(recommended_curve, &RecommendedCurve::CURVE25519);
    let (_, mut d_vec) = d.to_bytes_be();
    // 32 is privkey size on x25519.
    pad_be_bytes(&mut d_vec, 32);
    trace!("d_vec size is {:?}", d_vec.len());
    let pkey_1 = PKey::private_key_from_raw_bytes(&d_vec, Id::X25519).unwrap();

    // Export the bytes only
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "ec".to_owned(),
        key_id: private_key_id,
        key_file: tmp_path
            .join("output.export.bytes")
            .to_str()
            .unwrap()
            .to_owned(),
        key_format: Some(ExportKeyFormat::Pkcs8Der),
        ..Default::default()
    })?;
    let bytes = read_bytes_from_file(&tmp_path.join("output.export.bytes"))?;
    let pkey_2 = PKey::private_key_from_der(&bytes).unwrap();

    assert_eq!(
        pkey_1.private_key_to_pkcs8().unwrap(),
        pkey_2.private_key_to_pkcs8().unwrap()
    );

    // Public Key
    //
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.clone(),
        sub_command: "ec".to_owned(),
        key_id: public_key_id.clone(),
        key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
        ..Default::default()
    })?;

    // read the bytes from the exported file
    let object = read_object_from_json_ttlv_file(&tmp_path.join("output.export"))?;
    let key_block = object.key_block()?;
    assert_eq!(
        key_block.key_format_type,
        KeyFormatType::TransparentECPublicKey
    );
    assert_eq!(
        key_block.cryptographic_algorithm,
        Some(CryptographicAlgorithm::ECDH)
    );
    let Some(KeyValue::Structure { key_material, .. }) = &key_block.key_value else {
        panic!("Invalid key value type");
    };
    let KeyMaterial::TransparentECPublicKey {
        q_string,
        recommended_curve,
    } = key_material
    else {
        panic!("Invalid key value type")
    };
    assert_eq!(recommended_curve, &RecommendedCurve::CURVE25519);
    let pkey_1 = PKey::public_key_from_raw_bytes(q_string, Id::X25519).unwrap();

    // Export the bytes only
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path,
        sub_command: "ec".to_owned(),
        key_id: public_key_id,
        key_file: tmp_path
            .join("output.export.bytes")
            .to_str()
            .unwrap()
            .to_owned(),
        key_format: Some(ExportKeyFormat::Pkcs8Der),
        ..Default::default()
    })?;
    let bytes = read_bytes_from_file(&tmp_path.join("output.export.bytes"))?;
    let pkey_2 = PKey::public_key_from_der(&bytes).unwrap();

    assert_eq!(
        pkey_1.public_key_to_der().unwrap(),
        pkey_2.public_key_to_der().unwrap()
    );

    Ok(())
}

#[tokio::test]
pub(crate) async fn test_sensitive_sym() -> CosmianResult<()> {
    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate a symmetric key
    let key_id = create_symmetric_key(
        &owner_client_conf_path,
        CreateKeyAction {
            sensitive: true,
            ..Default::default()
        },
    )?;

    // the key should not be exportable
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path,
            sub_command: "sym".to_owned(),
            key_id,
            key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
            ..Default::default()
        })
        .is_err()
    );

    Ok(())
}

#[cfg(feature = "non-fips")]
#[tokio::test]
pub(crate) async fn test_sensitive_ec_key() -> CosmianResult<()> {
    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate an ec key pair
    let (private_key_id, public_key_id) =
        create_ec_key_pair(&owner_client_conf_path, "nist-p256", &[], true)?;

    // the private key should not be exportable
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path.clone(),
            sub_command: "ec".to_owned(),
            key_id: private_key_id,
            key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
            ..Default::default()
        })
        .is_err()
    );

    // the public key should be exportable
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path,
            sub_command: "ec".to_owned(),
            key_id: public_key_id,
            key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
            ..Default::default()
        })
        .is_ok()
    );

    Ok(())
}

#[cfg(feature = "non-fips")]
#[tokio::test]
pub(crate) async fn test_sensitive_rsa_key() -> CosmianResult<()> {
    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate an ec key pair
    let (private_key_id, public_key_id) = create_rsa_key_pair(
        &owner_client_conf_path,
        &RsaKeyPairOptions {
            sensitive: true,
            ..Default::default()
        },
    )?;

    // the private key should not be exportable
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path.clone(),
            sub_command: "rsa".to_owned(),
            key_id: private_key_id,
            key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
            ..Default::default()
        })
        .is_err()
    );

    // the public key should be exportable
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path,
            sub_command: "rsa".to_owned(),
            key_id: public_key_id,
            key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
            ..Default::default()
        })
        .is_ok()
    );

    Ok(())
}

#[cfg(feature = "non-fips")]
#[tokio::test]
pub(crate) async fn test_sensitive_covercrypt_key() -> CosmianResult<()> {
    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    // init the test server
    let ctx = start_default_test_kms_server().await;
    let (owner_client_conf_path, _) = save_kms_cli_config(ctx);

    // generate a new master key pair
    let (master_private_key_id, master_public_key_id) = create_cc_master_key_pair(
        &owner_client_conf_path,
        "--specification",
        "../../../test_data/access_structure_specifications.json",
        &[],
        true,
    )?;

    // master secret key should not be exportable
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path.clone(),
            sub_command: "cc".to_owned(),
            key_id: master_private_key_id.clone(),
            key_file: tmp_path
                .join("output.sk.export")
                .to_str()
                .unwrap()
                .to_owned(),
            ..Default::default()
        })
        .is_err()
    );

    // Master public key should be exportable
    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path.clone(),
            sub_command: "cc".to_owned(),
            key_id: master_public_key_id,
            key_file: tmp_path
                .join("output.sk.export")
                .to_str()
                .unwrap()
                .to_owned(),
            ..Default::default()
        })
        .is_ok()
    );

    let user_key_id = create_user_decryption_key(
        &owner_client_conf_path,
        &master_private_key_id,
        "(Department::MKG || Department::FIN) && Security Level::Top Secret",
        &[],
        true,
    )?;

    assert!(
        export_key(ExportKeyParams {
            cli_conf_path: owner_client_conf_path,
            sub_command: "cc".to_owned(),
            key_id: user_key_id,
            key_file: tmp_path.join("output.export").to_str().unwrap().to_owned(),
            ..Default::default()
        })
        .is_err()
    );

    Ok(())
}