cosmian_kms_client_utils 5.25.0

Cosmian KMS Client Utilities - used in WASM and KMS Client
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
use std::{collections::HashMap, str::FromStr};

use clap::ValueEnum;
use cosmian_kmip::kmip_2_1::{
    extra::tagging::VENDOR_ATTR_TAG,
    kmip_attributes::{Attribute, Attributes},
    kmip_types::{
        CryptographicAlgorithm, Link, LinkType, LinkedObjectIdentifier, Name, NameType, Tag,
    },
};
use serde_json::Value;
use strum::{EnumIter, EnumString, IntoEnumIterator};
use time::{OffsetDateTime, format_description};

use crate::{
    error::UtilsError,
    import_utils::{KeyUsage, build_usage_mask_from_key_usage},
};

#[derive(ValueEnum, Debug, Clone, PartialEq, Eq, EnumIter, EnumString)]
#[strum(serialize_all = "kebab-case")]
pub enum CLinkType {
    /// For Certificate objects: the parent certificate for a certificate in a
    /// certificate chain. For Public Key objects: the corresponding
    /// certificate(s), containing the same public key.
    Certificate,
    /// For a Private Key object: the public key corresponding to the private
    /// key. For a Certificate object: the public key contained in the
    /// certificate.
    PublicKey,
    /// For a Public Key object: the private key corresponding to the public
    /// key.
    PrivateKey,
    /// For a derived Symmetric Key or Secret Data object: the object(s) from
    /// which the current symmetric key was derived.
    DerivationBaseObject,
    /// The symmetric key(s) or Secret Data object(s) that were derived from
    /// the current object.
    DerivedKey,
    /// For a Symmetric Key, an Asymmetric Private Key, or an Asymmetric
    /// Public Key object: the key that resulted from the re-key of the current
    /// key. For a Certificate object: the certificate that resulted from the
    /// re- certify. Note that there SHALL be only one such replacement
    /// object per Managed Object.
    ReplacementObject,
    /// For a Symmetric Key, an Asymmetric Private Key, or an Asymmetric
    /// Public Key object: the key that was re-keyed to obtain the current key.
    /// For a Certificate object: the certificate that was re-certified to
    /// obtain the current certificate.
    ReplacedObject,
    /// For all object types: the container or other parent object corresponding
    /// to the object.
    Parent,
    /// For all object types: the subordinate, derived or other child object
    /// corresponding to the object.
    Child,
    /// For all object types: the previous object to this object.
    Previous,
    /// For all object types: the next object to this object.
    Next,
    PKCS12Certificate,
    PKCS12Password,
    /// For wrapped objects: the object that was used to wrap this object.
    WrappingKey,
    // Extensions 8XXXXXXX
}

impl From<CLinkType> for LinkType {
    fn from(value: CLinkType) -> Self {
        match value {
            CLinkType::Certificate => Self::CertificateLink,
            CLinkType::PublicKey => Self::PublicKeyLink,
            CLinkType::PrivateKey => Self::PrivateKeyLink,
            CLinkType::DerivationBaseObject => Self::DerivationBaseObjectLink,
            CLinkType::DerivedKey => Self::DerivedKeyLink,
            CLinkType::ReplacementObject => Self::ReplacementObjectLink,
            CLinkType::ReplacedObject => Self::ReplacedObjectLink,
            CLinkType::Parent => Self::ParentLink,
            CLinkType::Child => Self::ChildLink,
            CLinkType::Previous => Self::PreviousLink,
            CLinkType::Next => Self::NextLink,
            CLinkType::PKCS12Certificate => Self::PKCS12CertificateLink,
            CLinkType::PKCS12Password => Self::PKCS12PasswordLink,
            CLinkType::WrappingKey => Self::WrappingKeyLink,
        }
    }
}

fn add_if_not_empty(tag: Tag, new_value: &str, results: &mut HashMap<String, Value>) {
    if !new_value.is_empty() {
        results.insert(
            tag.to_string(),
            serde_json::to_value(new_value).unwrap_or_default(),
        );
    }
}

pub fn parse_selected_attributes(
    vendor_id: &str,
    attributes: &Attributes,
    attribute_tags: &[Tag],
    attribute_link_types: &[CLinkType],
) -> Result<HashMap<String, Value>, UtilsError> {
    let tags = if attribute_tags.is_empty() {
        Tag::iter().collect()
    } else {
        attribute_tags.to_vec()
    };

    let mut results: HashMap<String, Value> = HashMap::new();
    for tag in &tags {
        match tag {
            Tag::ActivationDate => {
                if let Some(v) = attributes.activation_date.as_ref() {
                    results.insert(
                        tag.to_string(),
                        serde_json::to_value(v.unix_timestamp() * 1000_i64).unwrap_or_default(),
                    );
                }
            }
            Tag::CertificateLength => {
                if let Some(v) = attributes.certificate_length.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::CertificateType => {
                if let Some(v) = attributes.certificate_type.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::CertificateSubjectC => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_c, &mut results);
                }
            }
            Tag::CertificateSubjectCN => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_cn, &mut results);
                }
            }
            Tag::CertificateSubjectDC => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_dc, &mut results);
                }
            }
            Tag::CertificateSubjectEmail => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_email, &mut results);
                }
            }
            Tag::CertificateSubjectL => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_l, &mut results);
                }
            }
            Tag::CertificateSubjectO => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_o, &mut results);
                }
            }
            Tag::CertificateSubjectOU => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_ou, &mut results);
                }
            }
            Tag::CertificateSubjectST => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_st, &mut results);
                }
            }
            Tag::CertificateSubjectDNQualifier => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_dn_qualifier, &mut results);
                }
            }
            Tag::CertificateSubjectSerialNumber => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_serial_number, &mut results);
                }
            }
            Tag::CertificateSubjectTitle => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_title, &mut results);
                }
            }
            Tag::CertificateSubjectUID => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_subject_uid, &mut results);
                }
            }
            Tag::CertificateIssuerC => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_c, &mut results);
                }
            }
            Tag::CertificateIssuerCN => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_cn, &mut results);
                }
            }
            Tag::CertificateIssuerDC => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_dc, &mut results);
                }
            }
            Tag::CertificateIssuerEmail => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_email, &mut results);
                }
            }
            Tag::CertificateIssuerL => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_l, &mut results);
                }
            }
            Tag::CertificateIssuerO => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_o, &mut results);
                }
            }
            Tag::CertificateIssuerOU => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_ou, &mut results);
                }
            }
            Tag::CertificateIssuerST => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_st, &mut results);
                }
            }
            Tag::CertificateIssuerDNQualifier => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_dn_qualifier, &mut results);
                }
            }
            Tag::CertificateIssuerUID => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_uid, &mut results);
                }
            }
            Tag::CertificateIssuerSerialNumber => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_serial_number, &mut results);
                }
            }
            Tag::CertificateIssuerTitle => {
                if let Some(v) = attributes.certificate_attributes.as_ref() {
                    add_if_not_empty(*tag, &v.certificate_issuer_title, &mut results);
                }
            }
            Tag::CryptographicAlgorithm => {
                if let Some(v) = attributes.cryptographic_algorithm.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::CryptographicLength => {
                if let Some(v) = attributes.cryptographic_length.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::CryptographicParameters => {
                if let Some(v) = attributes.cryptographic_parameters.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::CryptographicDomainParameters => {
                if let Some(v) = attributes.cryptographic_domain_parameters.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::CryptographicUsageMask => {
                if let Some(v) = attributes.cryptographic_usage_mask.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::KeyFormatType => {
                if let Some(v) = attributes.key_format_type.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::ObjectType => {
                if let Some(v) = attributes.object_type.as_ref() {
                    results.insert(tag.to_string(), serde_json::to_value(v).unwrap_or_default());
                }
            }
            Tag::Tag => {
                let tags = attributes.get_tags(vendor_id);
                results.insert(
                    tag.to_string(),
                    serde_json::to_value(tags).unwrap_or_default(),
                );
            }
            Tag::Name => {
                if let Some(names) = attributes.name.as_ref() {
                    if !names.is_empty() {
                        results.insert(
                            tag.to_string(),
                            serde_json::to_value(names).unwrap_or_default(),
                        );
                    }
                }
            }
            Tag::VendorExtension => {
                if let Some(vendor_attributes) = attributes.vendor_attributes.as_ref() {
                    // Filter out tag-related vendor attributes to avoid duplication
                    // since tags are already displayed separately under the Tag field
                    let filtered_vendor_attributes: Vec<_> = vendor_attributes
                        .iter()
                        .filter(|va| {
                            !(va.vendor_identification == vendor_id
                                && va.attribute_name == VENDOR_ATTR_TAG)
                        })
                        .collect();

                    // Only include VendorExtension if there are non-tag vendor attributes
                    if !filtered_vendor_attributes.is_empty() {
                        results.insert(
                            tag.to_string(),
                            serde_json::to_value(filtered_vendor_attributes).unwrap_or_default(),
                        );
                    }
                }
            }
            _x => {}
        }
    }

    let link_types: Vec<LinkType> = if attribute_link_types.is_empty() {
        LinkType::iter().collect()
    } else {
        attribute_link_types
            .iter()
            .map(|link| LinkType::from(link.clone()))
            .collect()
    };

    for link_type in &link_types {
        if let Some(v) = attributes.get_link(*link_type).as_ref() {
            results.insert(
                link_type.to_string(),
                serde_json::to_value(v).unwrap_or_default(),
            );
        }
    }

    Ok(results)
}

/// Attribute key names recognised by [`parse_selected_attributes_flatten`].
///
/// This is the canonical list used by the WASM layer to enrich KMIP Locate
/// results.  Add an entry here whenever a new match arm is added to
/// `parse_selected_attributes_flatten` and the attribute should be surfaced in
/// the UI.
pub const LOCATE_ENRICH_ATTRIBUTE_KEYS: &[&str] = &[
    "object_type",
    "state",
    "tags",
    "user_tags",
    "cryptographic_algorithm",
    "cryptographic_length",
    "key_format_type",
    "public_key_id",
    "private_key_id",
    "certificate_id",
    "initial_date",
    "activation_date",
    "original_creation_date",
    "rotate_date",
    "rotate_name",
    "rotate_interval",
    "rotate_offset",
    "rotate_generation",
];

pub fn parse_selected_attributes_flatten(
    vendor_id: &str,
    attributes: &Attributes,
    selected_attributes: &[&str],
) -> Result<HashMap<String, Value>, UtilsError> {
    /// Insert a serializable value into the results map if it is `Some`.
    macro_rules! insert_if_some {
        ($results:expr, $key:expr, $opt:expr) => {
            if let Some(v) = $opt {
                $results.insert($key.to_owned(), serde_json::to_value(v).unwrap_or_default());
            }
        };
    }

    let mut results: HashMap<String, Value> = HashMap::new();
    if selected_attributes.is_empty() {
        let values = serde_json::to_value(attributes)?;

        if let Value::Object(map) = values {
            results = map
                .into_iter()
                .map(|(key, val)| (key, serde_json::to_value(val).unwrap_or(Value::Null)))
                .collect();
        }
        return Ok(results);
    }
    for &selected_attribute_name in selected_attributes {
        match selected_attribute_name {
            "activation_date" => {
                if let Some(v) = attributes.activation_date.as_ref() {
                    results.insert(
                        selected_attribute_name.to_owned(),
                        serde_json::to_value(v.unix_timestamp() * 1000_i64).unwrap_or_default(),
                    );
                }
            }
            "initial_date" => {
                if let Some(v) = attributes.initial_date.as_ref() {
                    results.insert(
                        selected_attribute_name.to_owned(),
                        serde_json::to_value(v.unix_timestamp() * 1000_i64).unwrap_or_default(),
                    );
                }
            }
            "original_creation_date" => {
                if let Some(v) = attributes.original_creation_date.as_ref() {
                    results.insert(
                        selected_attribute_name.to_owned(),
                        serde_json::to_value(v.unix_timestamp() * 1000_i64).unwrap_or_default(),
                    );
                }
            }
            "rotate_automatic" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.rotate_automatic.as_ref()
            ),
            "rotate_date" => {
                if let Some(v) = attributes.rotate_date.as_ref() {
                    results.insert(
                        selected_attribute_name.to_owned(),
                        serde_json::to_value(v.unix_timestamp() * 1000_i64).unwrap_or_default(),
                    );
                }
            }
            "rotate_generation" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.rotate_generation.as_ref()
            ),
            "rotate_interval" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.rotate_interval.as_ref()
            ),
            "rotate_latest" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.rotate_latest.as_ref()
            ),
            "rotate_name" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.rotate_name.as_ref()
            ),
            "rotate_offset" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.rotate_offset.as_ref()
            ),
            "cryptographic_algorithm" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.cryptographic_algorithm.as_ref()
            ),
            "cryptographic_length" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.cryptographic_length.as_ref()
            ),
            "key_usage" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.cryptographic_usage_mask.as_ref()
            ),
            "key_format_type" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.key_format_type.as_ref()
            ),
            "object_type" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.object_type.as_ref()
            ),
            "state" => insert_if_some!(results, selected_attribute_name, attributes.state.as_ref()),
            "tags" | "user_tags" => {
                let tags = attributes.get_tags(vendor_id);
                if !tags.is_empty() {
                    results.insert(
                        selected_attribute_name.to_owned(),
                        serde_json::to_value(tags).unwrap_or_default(),
                    );
                }
            }
            "vendor_attributes" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.vendor_attributes.as_ref()
            ),
            "public_key_id" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.get_link(LinkType::PublicKeyLink).as_ref()
            ),
            "private_key_id" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.get_link(LinkType::PrivateKeyLink).as_ref()
            ),
            "certificate_id" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.get_link(LinkType::CertificateLink).as_ref()
            ),
            "pkcs12_certificate_id" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes
                    .get_link(LinkType::PKCS12CertificateLink)
                    .as_ref()
            ),
            "pkcs12_password_certificate" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.get_link(LinkType::PKCS12PasswordLink).as_ref()
            ),
            "parent_id" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.get_link(LinkType::ParentLink).as_ref()
            ),
            "child_id" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.get_link(LinkType::ChildLink).as_ref()
            ),
            "deactivation_date" => {
                if let Some(v) = attributes.deactivation_date.as_ref() {
                    results.insert(
                        selected_attribute_name.to_owned(),
                        serde_json::to_value(v.unix_timestamp() * 1000_i64).unwrap_or_default(),
                    );
                }
            }
            "description" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.description.as_ref()
            ),
            "comment" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.comment.as_ref()
            ),
            "contact_information" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.contact_information.as_ref()
            ),
            "object_group" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.object_group.as_ref()
            ),
            "sensitive" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.sensitive.as_ref()
            ),
            "extractable" => insert_if_some!(
                results,
                selected_attribute_name,
                attributes.extractable.as_ref()
            ),
            _x => {}
        }
    }
    Ok(results)
}

pub fn build_selected_attribute(
    attribute_name: &str,
    attribute_value: String,
) -> Result<Attribute, UtilsError> {
    let attribute = match attribute_name {
        "activation_date" => {
            let format = format_description::parse_borrowed::<2>(
                "[year]-[month]-[day]T[hour]:[minute]:[second]Z",
            )
            .map_err(|e| UtilsError::Default(e.to_string()))?;
            let activation_date = OffsetDateTime::parse(&attribute_value, &format)
                .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::ActivationDate(activation_date)
        }
        "cryptographic_algorithm" => {
            let cryptographic_algorithm =
                CryptographicAlgorithm::from_str(attribute_value.as_str())
                    .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::CryptographicAlgorithm(cryptographic_algorithm)
        }
        "cryptographic_length" => {
            let cryptographic_length = attribute_value
                .parse::<i32>()
                .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::CryptographicLength(cryptographic_length)
        }
        "key_usage" => {
            let key_usages = attribute_value
                .split(',')
                .map(|s| {
                    s.trim()
                        .parse::<KeyUsage>()
                        .map_err(|e| UtilsError::Default(e.to_string()))
                })
                .collect::<Result<Vec<_>, _>>()?;
            let Some(cryptographic_usage_mask) = build_usage_mask_from_key_usage(&key_usages)
            else {
                return Err(UtilsError::Default(
                    "Error building cryptographic usage mask".to_owned(),
                ));
            };
            Attribute::CryptographicUsageMask(cryptographic_usage_mask)
        }
        "public_key_id" => Attribute::Link(Link {
            link_type: LinkType::PublicKeyLink,
            linked_object_identifier: LinkedObjectIdentifier::TextString(attribute_value),
        }),
        "private_key_id" => Attribute::Link(Link {
            link_type: LinkType::PrivateKeyLink,
            linked_object_identifier: LinkedObjectIdentifier::TextString(attribute_value),
        }),
        "certificate_id" => Attribute::Link(Link {
            link_type: LinkType::CertificateLink,
            linked_object_identifier: LinkedObjectIdentifier::TextString(attribute_value),
        }),
        "pkcs12_certificate_id" => Attribute::Link(Link {
            link_type: LinkType::PKCS12CertificateLink,
            linked_object_identifier: LinkedObjectIdentifier::TextString(attribute_value),
        }),
        "pkcs12_password_certificate" => Attribute::Link(Link {
            link_type: LinkType::PKCS12PasswordLink,
            linked_object_identifier: LinkedObjectIdentifier::TextString(attribute_value),
        }),
        "parent_id" => Attribute::Link(Link {
            link_type: LinkType::ParentLink,
            linked_object_identifier: LinkedObjectIdentifier::TextString(attribute_value),
        }),
        "child_id" => Attribute::Link(Link {
            link_type: LinkType::ChildLink,
            linked_object_identifier: LinkedObjectIdentifier::TextString(attribute_value),
        }),
        "name" => Attribute::Name(Name {
            name_value: attribute_value,
            name_type: NameType::UninterpretedTextString,
        }),
        "rotate_interval" => {
            let v = attribute_value
                .parse::<i64>()
                .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::RotateInterval(v)
        }
        "rotate_name" => Attribute::RotateName(attribute_value),
        "rotate_offset" => {
            let v = attribute_value
                .parse::<i64>()
                .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::RotateOffset(v)
        }
        "rotate_automatic" => {
            let v = attribute_value
                .parse::<bool>()
                .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::RotateAutomatic(v)
        }
        "deactivation_date" => {
            let format = format_description::parse_borrowed::<2>(
                "[year]-[month]-[day]T[hour]:[minute]:[second]Z",
            )
            .map_err(|e| UtilsError::Default(e.to_string()))?;
            let deactivation_date = OffsetDateTime::parse(&attribute_value, &format)
                .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::DeactivationDate(deactivation_date)
        }
        "description" => Attribute::Description(attribute_value),
        "comment" => Attribute::Comment(attribute_value),
        "contact_information" => Attribute::ContactInformation(attribute_value),
        "object_group" => Attribute::ObjectGroup(attribute_value),
        "sensitive" => {
            let v = attribute_value
                .parse::<bool>()
                .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::Sensitive(v)
        }
        "extractable" => {
            let v = attribute_value
                .parse::<bool>()
                .map_err(|e| UtilsError::Default(e.to_string()))?;
            Attribute::Extractable(v)
        }

        _ => {
            return Err(UtilsError::Default(format!(
                "Unknown attribute name: {attribute_name}"
            )));
        }
    };
    Ok(attribute)
}

#[cfg(test)]
#[expect(clippy::unwrap_used, clippy::indexing_slicing, clippy::panic)]
mod tests {
    use super::*;
    use crate::reexport::cosmian_kmip::kmip_2_1::{
        extra::tagging::{VENDOR_ATTR_TAG, VENDOR_ID_COSMIAN},
        kmip_attributes::Attributes,
        kmip_types::{CryptographicAlgorithm, VendorAttribute, VendorAttributeValue},
    };

    #[test]
    fn test_vendor_extension_tag_filtering() {
        // Create test attributes with vendor extensions including tags
        let mut attributes = Attributes {
            cryptographic_algorithm: Some(CryptographicAlgorithm::AES),
            ..Default::default()
        };

        // Add vendor attributes including tag data and other data
        let tag_vendor_attr = VendorAttribute {
            vendor_identification: VENDOR_ID_COSMIAN.to_owned(),
            attribute_name: VENDOR_ATTR_TAG.to_owned(),
            attribute_value: VendorAttributeValue::TextString(
                "[\"_cert\",\"test_cert\"]".to_owned(),
            ),
        };

        let other_vendor_attr = VendorAttribute {
            vendor_identification: VENDOR_ID_COSMIAN.to_owned(),
            attribute_name: "some_other_attr".to_owned(),
            attribute_value: VendorAttributeValue::TextString("some_value".to_owned()),
        };

        attributes.vendor_attributes = Some(vec![tag_vendor_attr, other_vendor_attr]);

        // Test the parsing with no specific tags requested (should return all)
        let result = parse_selected_attributes(VENDOR_ID_COSMIAN, &attributes, &[], &[]).unwrap();

        // Check that VendorExtension exists but doesn't contain tag data
        if let Some(vendor_extension) = result.get("VendorExtension") {
            // Parse as array of vendor attributes and check for tag filtering
            if let Ok(vendor_attrs) =
                serde_json::from_value::<Vec<VendorAttribute>>(vendor_extension.clone())
            {
                let has_tag_attr = vendor_attrs.iter().any(|va| {
                    va.vendor_identification == VENDOR_ID_COSMIAN
                        && va.attribute_name == VENDOR_ATTR_TAG
                });

                assert!(
                    !has_tag_attr,
                    "Tag vendor attribute should be filtered out from VendorExtension"
                );
                assert_eq!(
                    vendor_attrs.len(),
                    1,
                    "Should have exactly one non-tag vendor attribute"
                );
                assert_eq!(vendor_attrs[0].attribute_name, "some_other_attr");
            } else {
                panic!("Failed to parse vendor extension as array of VendorAttribute");
            }
        } else {
            panic!("VendorExtension should be present when there are non-tag vendor attributes");
        }

        // Check that CryptographicAlgorithm is present
        assert!(
            result.contains_key("CryptographicAlgorithm"),
            "CryptographicAlgorithm should be present"
        );

        // Check that Tag is present (should show parsed tags)
        assert!(result.contains_key("Tag"), "Tag field should be present");
    }

    #[test]
    fn test_vendor_extension_only_tags_filtered_out() {
        // Create test attributes with vendor extensions containing only tag data
        let mut attributes = Attributes::default();

        // Add vendor attributes with only tag data
        let tag_vendor_attr = VendorAttribute {
            vendor_identification: VENDOR_ID_COSMIAN.to_owned(),
            attribute_name: VENDOR_ATTR_TAG.to_owned(),
            attribute_value: VendorAttributeValue::TextString("[\"_cert\"]".to_owned()),
        };

        attributes.vendor_attributes = Some(vec![tag_vendor_attr]);

        // Test the parsing
        let result = parse_selected_attributes(VENDOR_ID_COSMIAN, &attributes, &[], &[]).unwrap();

        // Check that VendorExtension is not present when only tag data exists
        assert!(
            !result.contains_key("VendorExtension"),
            "VendorExtension should not be present when it would only contain tag data"
        );

        // Check that Tag is still present
        assert!(
            result.contains_key("Tag"),
            "Tag field should still be present"
        );
    }
}