cosmian_kms_cli 5.20.0

Command Line Interface used to manage the 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
use cosmian_kms_client::{
    kmip_0::kmip_types::CryptographicUsageMask,
    kmip_2_1::{
        extra::tagging::VENDOR_ID_COSMIAN,
        kmip_types::{CryptographicAlgorithm, LinkType, Name, Tag, VendorAttribute},
    },
    reexport::cosmian_kms_client_utils::{
        certificate_utils::Algorithm,
        create_utils::SecretDataType,
        import_utils::{KeyUsage, build_usage_mask_from_key_usage},
    },
};
use cosmian_logger::trace;
use strum::IntoEnumIterator;
use test_kms_server::{TestsContext, start_default_test_kms_server};

use crate::{
    actions::kms::{
        attributes::{
            CCryptographicAlgorithm, CLinkType, DeleteAttributesAction, GetAttributesAction,
            SetAttributesAction, SetOrDeleteAttributes, VendorAttributeCli,
        },
        certificates::certify::CertifyAction,
        secret_data::create_secret::CreateSecretDataAction,
        symmetric::keys::create_key::CreateKeyAction,
    },
    error::result::KmsCliResult,
};

fn get_all_attribute_tags() -> Vec<Tag> {
    let mut tags = Vec::new();
    for tag in Tag::iter() {
        tags.push(tag);
    }
    tags
}

fn get_all_link_types() -> Vec<CLinkType> {
    let mut links = Vec::new();
    for link_type in CLinkType::iter() {
        links.push(link_type);
    }
    links
}

async fn get_and_check_attributes(
    ctx: &TestsContext,
    uid: &str,
    requested_attributes: &SetOrDeleteAttributes,
) -> KmsCliResult<()> {
    let get_attributes = GetAttributesAction {
        id: Some(uid.to_owned()),
        tags: None,
        attribute_tags: get_all_attribute_tags(),
        attribute_link_types: get_all_link_types(),
        output_file: None,
    }
    .run(ctx.get_owner_client())
    .await?;
    trace!("{get_attributes:?}");

    if let Some(activation_date) = requested_attributes.activation_date {
        let date: i64 =
            serde_json::from_value(get_attributes[&Tag::ActivationDate.to_string()].clone())?;

        assert_eq!(date, activation_date);
    }
    if let Some(cryptographic_length) = requested_attributes.cryptographic_length {
        let length: i32 =
            serde_json::from_value(get_attributes[&Tag::CryptographicLength.to_string()].clone())?;
        assert_eq!(length, cryptographic_length);
    }
    if let Some(cryptographic_algorithm) = requested_attributes.cryptographic_algorithm {
        let algo: CryptographicAlgorithm = serde_json::from_value(
            get_attributes[&Tag::CryptographicAlgorithm.to_string()].clone(),
        )?;
        assert_eq!(algo, cryptographic_algorithm.into());
    }
    if let Some(key_usage) = &requested_attributes.key_usage {
        let get_key_usage: CryptographicUsageMask = serde_json::from_value(
            get_attributes[&Tag::CryptographicUsageMask.to_string()].clone(),
        )?;
        assert_eq!(
            get_key_usage,
            build_usage_mask_from_key_usage(key_usage).unwrap()
        );
    }
    if let Some(public_key_id) = &requested_attributes.public_key_id {
        let id: String =
            serde_json::from_value(get_attributes[&LinkType::PublicKeyLink.to_string()].clone())?;
        assert_eq!(&id, public_key_id);
    }
    if let Some(private_key_id) = &requested_attributes.private_key_id {
        let id: String =
            serde_json::from_value(get_attributes[&LinkType::PrivateKeyLink.to_string()].clone())?;
        assert_eq!(&id, private_key_id);
    }
    if let Some(certificate_id) = &requested_attributes.certificate_id {
        let certificate_link_id: String =
            serde_json::from_value(get_attributes[&LinkType::CertificateLink.to_string()].clone())?;
        assert_eq!(certificate_id, &certificate_link_id);
    }
    if let Some(pkcs12_certificate_id) = &requested_attributes.pkcs12_certificate_id {
        let pkcs12_id: String = serde_json::from_value(
            get_attributes[&LinkType::PKCS12CertificateLink.to_string()].clone(),
        )?;

        assert_eq!(&pkcs12_id, pkcs12_certificate_id);
    }
    if let Some(pkcs12_password_certificate) = &requested_attributes.pkcs12_password_certificate {
        let pkcs12_password_link: String = serde_json::from_value(
            get_attributes[&LinkType::PKCS12PasswordLink.to_string()].clone(),
        )?;
        assert_eq!(&pkcs12_password_link, pkcs12_password_certificate);
    }
    if let Some(name_value) = &requested_attributes.name {
        let names: Vec<Name> =
            serde_json::from_value(get_attributes[&Tag::Name.to_string()].clone())?;
        assert!(
            names.iter().any(|n| &n.name_value == name_value),
            "Expected name '{name_value}' not found in {names:?}"
        );
    }
    if let Some(vendor_attributes) = &requested_attributes.vendor_attributes {
        let vendor_attributes_: Vec<VendorAttribute> =
            serde_json::from_value(get_attributes[&Tag::VendorExtension.to_string()].clone())?;
        let input_vendor_attributes = [VendorAttribute::try_from(vendor_attributes)?];
        assert_eq!(vendor_attributes_.len(), input_vendor_attributes.len());
        for (a, b) in vendor_attributes_
            .iter()
            .zip(input_vendor_attributes.iter())
        {
            assert_eq!(a, b);
        }
    }

    Ok(())
}

async fn get_and_check_none_attributes(
    ctx: &TestsContext,
    uid: &str,
    requested_attributes: &SetOrDeleteAttributes,
) -> KmsCliResult<()> {
    let get_attributes = GetAttributesAction {
        id: Some(uid.to_owned()),
        tags: None,
        attribute_tags: get_all_attribute_tags(),
        attribute_link_types: get_all_link_types(),
        output_file: None,
    }
    .run(ctx.get_owner_client())
    .await?;
    trace!("{get_attributes:?}");

    if let Some(_activation_date) = requested_attributes.activation_date {
        assert!(!get_attributes.contains_key(&Tag::ActivationDate.to_string()));
    }
    if let Some(_cryptographic_length) = requested_attributes.cryptographic_length {
        assert!(!get_attributes.contains_key(&Tag::CryptographicLength.to_string()));
    }
    if let Some(_cryptographic_algorithm) = requested_attributes.cryptographic_algorithm {
        assert!(!get_attributes.contains_key(&Tag::CryptographicAlgorithm.to_string()));
    }
    if let Some(_key_usage) = &requested_attributes.key_usage {
        assert!(!get_attributes.contains_key(&Tag::CryptographicUsageMask.to_string()));
    }
    if let Some(_public_key_id) = &requested_attributes.public_key_id {
        assert!(!get_attributes.contains_key(&LinkType::PublicKeyLink.to_string()));
    }
    if let Some(_private_key_id) = &requested_attributes.private_key_id {
        assert!(!get_attributes.contains_key(&LinkType::PrivateKeyLink.to_string()));
    }
    if let Some(_certificate_id) = &requested_attributes.certificate_id {
        assert!(!get_attributes.contains_key(&LinkType::CertificateLink.to_string()));
    }
    if let Some(_pkcs12_certificate_id) = &requested_attributes.pkcs12_certificate_id {
        assert!(!get_attributes.contains_key(&LinkType::PKCS12CertificateLink.to_string()));
    }
    if let Some(_pkcs12_password_certificate) = &requested_attributes.pkcs12_password_certificate {
        assert!(!get_attributes.contains_key(&LinkType::PKCS12PasswordLink.to_string()));
    }
    if let Some(_name) = &requested_attributes.name {
        assert!(!get_attributes.contains_key(&Tag::Name.to_string()));
    }
    if let Some(_vendor_attributes) = &requested_attributes.vendor_attributes {
        assert!(!get_attributes.contains_key(&Tag::VendorExtension.to_string()));
    }

    Ok(())
}

async fn check_set_delete_attributes(uid: &str, ctx: &TestsContext) -> KmsCliResult<()> {
    let key_usage = Some(vec![KeyUsage::Encrypt, KeyUsage::Decrypt]);
    for activation_date in [None, Some(5)] {
        for cryptographic_length in [None, Some(256)] {
            let requested_attributes = SetOrDeleteAttributes {
                id: Some(uid.to_owned()),
                activation_date,
                cryptographic_length,
                key_usage: key_usage.clone(),
                public_key_id: Some("public_key_id".to_owned()),
                private_key_id: Some("private_key_id".to_owned()),
                certificate_id: Some("certificate_id".to_owned()),
                pkcs12_certificate_id: Some("pkcs12_certificate_id".to_owned()),
                pkcs12_password_certificate: Some("toto".to_owned()),
                parent_id: Some("parent_id".to_owned()),
                child_id: Some("child_id".to_owned()),
                name: Some("my-object-name".to_owned()),
                vendor_attributes: Some(VendorAttributeCli {
                    vendor_identification: Some(VENDOR_ID_COSMIAN.to_owned()),
                    attribute_name: Some("my_new_attribute".to_owned()),
                    attribute_value: Some("AABBCCDDEEFF".to_owned()),
                }),
                ..SetOrDeleteAttributes::default()
            };

            // Set attributes
            SetAttributesAction {
                requested_attributes: requested_attributes.clone(),
            }
            .process(ctx.get_owner_client())
            .await?;

            // Get and check attributes
            get_and_check_attributes(ctx, uid, &requested_attributes).await?;

            // Delete attributes
            DeleteAttributesAction {
                requested_attributes: requested_attributes.clone(),
                attribute_tags: None,
            }
            .process(ctx.get_owner_client())
            .await?;

            // Get and check none attributes
            get_and_check_none_attributes(ctx, uid, &requested_attributes).await?;
        }
    }

    // Test cryptographic algorithm one by one
    for cryptographic_algorithm in CCryptographicAlgorithm::iter() {
        let requested_attributes = SetOrDeleteAttributes {
            id: Some(uid.to_owned()),
            cryptographic_algorithm: Some(cryptographic_algorithm),
            ..SetOrDeleteAttributes::default()
        };

        // Set attributes
        SetAttributesAction {
            requested_attributes: requested_attributes.clone(),
        }
        .process(ctx.get_owner_client())
        .await?;

        // Get and check attributes
        get_and_check_attributes(ctx, uid, &requested_attributes).await?;

        // Delete attributes
        DeleteAttributesAction {
            requested_attributes: requested_attributes.clone(),
            attribute_tags: None,
        }
        .process(ctx.get_owner_client())
        .await?;

        // Get and check none attributes
        get_and_check_none_attributes(ctx, uid, &requested_attributes).await?;
    }

    // Test key usage one by one
    for key_usage in KeyUsage::iter() {
        let requested_attributes = SetOrDeleteAttributes {
            id: Some(uid.to_owned()),
            key_usage: Some(vec![key_usage.clone()]),
            ..SetOrDeleteAttributes::default()
        };
        // Set attributes
        SetAttributesAction {
            requested_attributes: requested_attributes.clone(),
        }
        .process(ctx.get_owner_client())
        .await?;

        // Get and check attributes
        get_and_check_attributes(ctx, uid, &requested_attributes).await?;

        // Delete attributes
        DeleteAttributesAction {
            requested_attributes: requested_attributes.clone(),
            attribute_tags: None,
        }
        .process(ctx.get_owner_client())
        .await?;

        // Get and check none attributes
        get_and_check_none_attributes(ctx, uid, &requested_attributes).await?;
    }

    trace!("Test delete all attributes by references");
    for tag in Tag::iter() {
        DeleteAttributesAction {
            requested_attributes: SetOrDeleteAttributes {
                id: Some(uid.to_owned()),
                ..SetOrDeleteAttributes::default()
            },
            attribute_tags: Some(vec![tag]),
        }
        .process(ctx.get_owner_client())
        .await?;
    }

    // Accumulate all values of AttributeTag in a Vec
    let mut attribute_tags = Vec::new();
    for tag in Tag::iter() {
        attribute_tags.push(tag);
    }

    DeleteAttributesAction {
        requested_attributes: SetOrDeleteAttributes {
            id: Some(uid.to_owned()),
            ..SetOrDeleteAttributes::default()
        },
        attribute_tags: Some(attribute_tags),
    }
    .process(ctx.get_owner_client())
    .await?;

    Ok(())
}

/// This asynchronous test function performs a series of operations to validate the setting,
/// getting, and deleting of attributes in a Key Management System (KMS) server. It follows
/// these steps:
///
/// 1. Starts a default test KMS server.
/// 2. Creates an AES 256-bit symmetric key and verifies its attributes.
/// 3. Certifies a Certificate Signing Request (CSR) without an issuer (self-signed) and verifies its attributes.
///
/// The function uses various helper functions to set, get, and delete attributes, and checks
/// the correctness of these operations by comparing the expected and actual values.
///
/// # Returns
///
/// This function returns a `KmsCliResult<()>`, which is an alias for `Result<(), KmsCliError>`.
///
/// # Errors
///
/// This function will return an error if any of the attribute operations (set, get, delete)
/// fail or if the test KMS server fails to start.
/// ```
#[ignore = "Too much verbosity"]
#[tokio::test]
async fn test_set_attribute() -> KmsCliResult<()> {
    // Create a test server
    let ctx = start_default_test_kms_server().await;

    // AES 256 bit key
    let uid = CreateKeyAction::default()
        .run(ctx.get_owner_client())
        .await?;
    check_set_delete_attributes(uid.as_str().unwrap(), ctx).await?;

    // Issue self signed certificate
    let uid = CertifyAction {
        generate_key_pair: true,
        subject_name: Some("C = FR, ST = IdF, L = Paris, O = AcmeTest, CN = Test Leaf".to_owned()),
        algorithm: Algorithm::NistP256,
        tags: vec!["certify_self_signed".to_owned()],
        ..CertifyAction::default()
    }
    .run(ctx.get_owner_client())
    .await?;

    check_set_delete_attributes(uid.as_str().unwrap(), ctx).await?;

    Ok(())
}

/// Regression test for GitHub issue #746.
///
/// **Bug**: Setting the `Name` attribute via
/// `--attribute-name Name --attribute-value <hex> --vendor-identification ""`
/// stored the name as a `VendorAttribute` (hex bytes inside `VendorExtension`)
/// instead of the standard KMIP `Name` attribute.
///
/// **Fix**: A dedicated `--name <value>` flag was added to `ckms attributes set`
/// (and `modify` / `delete`) that creates an `Attribute::Name` directly.
///
/// This test reproduces the exact CLI commands from the issue report:
///
/// ```text
/// $ cosmian kms secret-data create --value "fa6c1bfbf9f5..."
/// $ cosmian kms attributes set --id <uid> --name "0c1eecd2-9c1a-47f3-9c4c-482310d14af6"
/// $ cosmian kms attributes get -i <uid>
/// # → Name must appear under "Name" key, not in "VendorExtension"
/// ```
#[tokio::test]
pub(crate) async fn test_issue_746_name_attribute_on_secret_data() -> KmsCliResult<()> {
    let ctx = start_default_test_kms_server().await;

    // Reproduce the exact command from the issue:
    // $ cosmian kms secret-data create --value "fa6c1bfbf9f5..."
    let secret_data_id = CreateSecretDataAction {
        secret_value: Some(
            "fa6c1bfbf9f5073ca9f0cecac48248dd3b59b3a37f06b95280013c7004097872f\
             5908d1f536e2990880c25d23f0bb4c21eabf5cb08c3f6a660fac5a813d802a81\
             442186e448fffc8"
                .to_owned(),
        ),
        secret_type: SecretDataType::Password,
        ..Default::default()
    }
    .run(ctx.get_owner_client())
    .await?;
    let uid = secret_data_id.as_str().unwrap();

    // The Name value from the issue: the attribute-value hex string
    // "30633165656364322d396331612d343766332d396334632d343832333130643134616636"
    // decodes (UTF-8) to "0c1eecd2-9c1a-47f3-9c4c-482310d14af6".
    //
    // With the fix, the user sets the Name attribute using the new `--name` flag:
    // $ cosmian kms attributes set --id <uid> --name "0c1eecd2-9c1a-47f3-9c4c-482310d14af6"
    let name_value = "0c1eecd2-9c1a-47f3-9c4c-482310d14af6";

    SetAttributesAction {
        requested_attributes: SetOrDeleteAttributes {
            id: Some(uid.to_owned()),
            name: Some(name_value.to_owned()),
            ..SetOrDeleteAttributes::default()
        },
    }
    .process(ctx.get_owner_client())
    .await?;

    // $ cosmian kms attributes get -i <uid>
    let get_attributes = GetAttributesAction {
        id: Some(uid.to_owned()),
        tags: None,
        attribute_tags: get_all_attribute_tags(),
        attribute_link_types: get_all_link_types(),
        output_file: None,
    }
    .run(ctx.get_owner_client())
    .await?;

    // The Name MUST be stored as standard KMIP attribute (under Tag::Name key).
    assert!(
        get_attributes.contains_key(&Tag::Name.to_string()),
        "Name attribute must be stored as standard KMIP Name attribute (issue #746)"
    );
    let names: Vec<Name> = serde_json::from_value(get_attributes[&Tag::Name.to_string()].clone())?;
    assert!(
        names.iter().any(|n| n.name_value == name_value),
        "Expected name '{name_value}' in standard KMIP Name attribute, got: {names:?}"
    );

    // The Name must NOT appear in VendorExtension (that was the bug in #746).
    assert!(
        !get_attributes.contains_key(&Tag::VendorExtension.to_string()),
        "Name attribute must NOT be stored in VendorExtension (regression for issue #746)"
    );

    Ok(())
}