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
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
use std::collections::HashMap;

use cosmian_kmip::{
    kmip_0::kmip_messages::ResponseMessageBatchItemVersioned,
    kmip_2_1::{
        kmip_data_structures::{KeyMaterial, KeyValue},
        kmip_objects::Object,
        kmip_types::{LinkedObjectIdentifier, UniqueIdentifier},
    },
};
use cosmian_kms_client::cosmian_kmip::{
    kmip_0::kmip_messages::ResponseMessage, kmip_2_1::kmip_operations::Operation,
};
use cosmian_logger::trace;

// KMIP 1.4 helper: substitute placeholder UID strings using the map of real values
fn substitute_uid_text(test_name: &str, uid: &mut String, uid_map: &HashMap<usize, String>) {
    let idx_opt = uid
        .strip_prefix(&format!("{test_name}-uid-"))
        .and_then(|n| n.parse::<usize>().ok())
        .map_or_else(
            || {
                uid.strip_prefix("uid-")
                    .and_then(|n| n.parse::<usize>().ok())
                    .map_or_else(
                        || {
                            uid.strip_prefix("$UNIQUE_IDENTIFIER_")
                                .and_then(|rest| rest.parse::<usize>().ok())
                        },
                        Some,
                    )
            },
            Some,
        );
    if let Some(index) = idx_opt {
        if let Some(real) = uid_map.get(&index) {
            *uid = real.clone();
        }
    }
}

/// Consolidated expected response preparation: applies all placeholder substitutions
/// needed to make KMIP test vector expected responses match actual server responses.
pub(crate) fn prepare_expected_response(
    test_name: &str,
    expected: &mut ResponseMessage,
    actual: &ResponseMessage,
    uid_placeholder_map: &HashMap<usize, String>,
) {
    // For Create/Register responses, adopt the actual UniqueIdentifier first to avoid
    // placeholder index collisions when prior Locate responses populated the map.
    substitute_create_register_uids_from_actual(expected, actual);
    substitute_placeholders_in_expected_response(test_name, expected, uid_placeholder_map);
    substitute_encrypt_response_data_iv_from_actual(expected, actual);
    substitute_key_material_from_actual(expected, actual);
    substitute_pkcs11_correlation_from_actual(expected, actual);
    substitute_short_unique_identifier_from_actual(expected, actual);
    substitute_sign_response_signature_from_actual(expected, actual);
    substitute_locate_response_from_actual(expected, actual);
}

/// Capture real UIDs from responses and store them in the placeholder map for future use
pub(crate) fn capture_real_uids_from_response(
    test_name: &str,
    resp: &ResponseMessage,
    uid_map: &mut HashMap<usize, String>,
) {
    for bi in &resp.batch_item {
        match bi {
            ResponseMessageBatchItemVersioned::V21(inner) => {
                if let Some(op) = &inner.response_payload {
                    match op {
                        Operation::CreateResponse(cr) => {
                            log_insert(test_name, uid_map, &cr.unique_identifier);
                        }
                        Operation::RegisterResponse(rr) => {
                            log_insert(test_name, uid_map, &rr.unique_identifier);
                        }
                        Operation::ActivateResponse(ar) => {
                            log_insert(test_name, uid_map, &ar.unique_identifier);
                        }
                        Operation::GetResponse(gr) => {
                            log_insert(test_name, uid_map, &gr.unique_identifier);
                        }
                        Operation::GetAttributesResponse(gar) => {
                            log_insert(test_name, uid_map, &gar.unique_identifier);
                        }
                        Operation::CreateKeyPairResponse(ckpr) => {
                            log_insert(test_name, uid_map, &ckpr.private_key_unique_identifier);
                            log_insert(test_name, uid_map, &ckpr.public_key_unique_identifier);
                        }
                        Operation::CheckResponse(cr) => {
                            if let Some(uid) = &cr.unique_identifier {
                                log_insert(test_name, uid_map, uid);
                            }
                        }
                        Operation::LocateResponse(lr) => {
                            if let Some(list) = &lr.unique_identifier {
                                for uid in list {
                                    log_insert(test_name, uid_map, uid);
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
            ResponseMessageBatchItemVersioned::V14(inner) => {
                use cosmian_kmip::kmip_1_4::kmip_operations::Operation as Op14;
                if let Some(op) = &inner.response_payload {
                    match op {
                        Op14::CreateResponse(cr) => {
                            log_insert_text(test_name, uid_map, &cr.unique_identifier);
                        }
                        Op14::RegisterResponse(rr) => {
                            log_insert_text(test_name, uid_map, &rr.unique_identifier);
                        }
                        Op14::ActivateResponse(ar) => {
                            log_insert_text(test_name, uid_map, &ar.unique_identifier);
                        }
                        Op14::GetResponse(gr) => {
                            log_insert_text(test_name, uid_map, &gr.unique_identifier);
                        }
                        Op14::GetAttributesResponse(gar) => {
                            log_insert_text(test_name, uid_map, &gar.unique_identifier);
                        }
                        Op14::CreateKeyPairResponse(ckpr) => {
                            log_insert_text(
                                test_name,
                                uid_map,
                                &ckpr.private_key_unique_identifier,
                            );
                            log_insert_text(test_name, uid_map, &ckpr.public_key_unique_identifier);
                        }
                        Op14::CheckResponse(cr) => {
                            log_insert_text(test_name, uid_map, &cr.unique_identifier);
                        }
                        Op14::LocateResponse(lr) => {
                            if let Some(list) = &lr.unique_identifier {
                                for uid in list {
                                    log_insert_text(test_name, uid_map, uid);
                                }
                            }
                        }
                        Op14::AddAttributeResponse(ar) => {
                            log_insert_text(test_name, uid_map, &ar.unique_identifier);
                        }
                        _ => {}
                    }
                }
            }
        }
    }
}

// Substitute uid-N placeholders in the expected ResponseMessage using the uid map
// captured from prior actual responses. This aligns vector placeholders with
// real server-assigned UniqueIdentifiers for strict field comparisons.
fn substitute_placeholders_in_expected_response(
    test_name: &str,
    expected: &mut ResponseMessage,
    uid_map: &HashMap<usize, String>,
) {
    // Helper to substitute UIDs within KeyWrappingData
    fn substitute_kwd_uids(
        kwd: &mut cosmian_kms_client::cosmian_kmip::kmip_2_1::kmip_data_structures::KeyWrappingData,
        test_name: &str,
        uid_map: &HashMap<usize, String>,
    ) {
        if let Some(eki) = &mut kwd.encryption_key_information {
            substitute_uid(test_name, &mut eki.unique_identifier, uid_map);
        }
        if let Some(mski) = &mut kwd.mac_signature_key_information {
            substitute_uid(test_name, &mut mski.unique_identifier, uid_map);
        }
    }

    // Helper to substitute UIDs within KMIP 1.4 KeyWrappingData
    fn substitute_kwd_uids_v14(
        kwd: &mut cosmian_kms_client::cosmian_kmip::kmip_1_4::kmip_data_structures::KeyWrappingData,
        test_name: &str,
        uid_map: &HashMap<usize, String>,
    ) {
        if let Some(eki) = &mut kwd.encryption_key_information {
            substitute_uid_text(test_name, &mut eki.unique_identifier, uid_map);
        }
        if let Some(mski) = &mut kwd.mac_signature_key_information {
            substitute_uid_text(test_name, &mut mski.unique_identifier, uid_map);
        }
    }

    // Helper to walk KMIP 1.4 object variants and substitute UIDs inside KeyWrappingData
    fn substitute_object_wrapping_uids_v14(
        obj: &mut cosmian_kms_client::cosmian_kmip::kmip_1_4::kmip_objects::Object,
        test_name: &str,
        uid_map: &HashMap<usize, String>,
    ) {
        use cosmian_kms_client::cosmian_kmip::kmip_1_4::kmip_objects::Object as Obj14;
        match obj {
            Obj14::SymmetricKey(sk) => {
                if let Some(kwd) = &mut sk.key_block.key_wrapping_data {
                    substitute_kwd_uids_v14(kwd, test_name, uid_map);
                }
            }
            Obj14::PrivateKey(pk) => {
                if let Some(kwd) = &mut pk.key_block.key_wrapping_data {
                    substitute_kwd_uids_v14(kwd, test_name, uid_map);
                }
            }
            Obj14::PublicKey(pk) => {
                if let Some(kwd) = &mut pk.key_block.key_wrapping_data {
                    substitute_kwd_uids_v14(kwd, test_name, uid_map);
                }
            }
            Obj14::SecretData(sd) => {
                if let Some(kwd) = &mut sd.key_block.key_wrapping_data {
                    substitute_kwd_uids_v14(kwd, test_name, uid_map);
                }
            }
            Obj14::SplitKey(sk) => {
                if let Some(kwd) = &mut sk.key_block.key_wrapping_data {
                    substitute_kwd_uids_v14(kwd, test_name, uid_map);
                }
            }
            _ => {}
        }
    }
    // Helper to walk object variants and substitute UIDs inside KeyWrappingData
    fn substitute_object_wrapping_uids(
        obj: &mut cosmian_kms_client::cosmian_kmip::kmip_2_1::kmip_objects::Object,
        test_name: &str,
        uid_map: &HashMap<usize, String>,
    ) {
        use cosmian_kms_client::cosmian_kmip::kmip_2_1::kmip_objects::Object as Obj;
        match obj {
            Obj::SymmetricKey(sk) => {
                if let Some(kwd) = &mut sk.key_block.key_wrapping_data {
                    substitute_kwd_uids(kwd, test_name, uid_map);
                }
            }
            Obj::PrivateKey(pk) => {
                if let Some(kwd) = &mut pk.key_block.key_wrapping_data {
                    substitute_kwd_uids(kwd, test_name, uid_map);
                }
            }
            Obj::PublicKey(pk) => {
                if let Some(kwd) = &mut pk.key_block.key_wrapping_data {
                    substitute_kwd_uids(kwd, test_name, uid_map);
                }
            }
            Obj::SecretData(sd) => {
                if let Some(kwd) = &mut sd.key_block.key_wrapping_data {
                    substitute_kwd_uids(kwd, test_name, uid_map);
                }
            }
            Obj::SplitKey(sk) => {
                if let Some(kwd) = &mut sk.key_block.key_wrapping_data {
                    substitute_kwd_uids(kwd, test_name, uid_map);
                }
            }
            _ => {}
        }
    }
    for bi in &mut expected.batch_item {
        match bi {
            ResponseMessageBatchItemVersioned::V21(inner) => {
                if let Some(op) = &mut inner.response_payload {
                    match op {
                        Operation::CreateResponse(cr) => {
                            substitute_uid(test_name, &mut cr.unique_identifier, uid_map);
                        }
                        Operation::RegisterResponse(cr) => {
                            substitute_uid(test_name, &mut cr.unique_identifier, uid_map);
                        }
                        Operation::ActivateResponse(cr) => {
                            substitute_uid(test_name, &mut cr.unique_identifier, uid_map);
                        }
                        Operation::GetResponse(cr) => {
                            substitute_uid(test_name, &mut cr.unique_identifier, uid_map);
                            substitute_object_wrapping_uids(&mut cr.object, test_name, uid_map);
                        }
                        Operation::CreateKeyPairResponse(ckpr) => {
                            substitute_uid(
                                test_name,
                                &mut ckpr.private_key_unique_identifier,
                                uid_map,
                            );
                            substitute_uid(
                                test_name,
                                &mut ckpr.public_key_unique_identifier,
                                uid_map,
                            );
                        }
                        Operation::CheckResponse(cr) => {
                            if let Some(uid) = &mut cr.unique_identifier {
                                substitute_uid(test_name, uid, uid_map);
                            }
                        }
                        Operation::DestroyResponse(dr) => {
                            substitute_uid(test_name, &mut dr.unique_identifier, uid_map);
                        }
                        Operation::LocateResponse(lr) => {
                            if let Some(list) = &mut lr.unique_identifier {
                                for uid in list {
                                    substitute_uid(test_name, uid, uid_map);
                                }
                            }
                        }
                        Operation::AddAttributeResponse(ar) => {
                            substitute_uid(test_name, &mut ar.unique_identifier, uid_map);
                        }
                        Operation::ModifyAttributeResponse(ar) => {
                            if let Some(uid) = &mut ar.unique_identifier {
                                substitute_uid(test_name, uid, uid_map);
                            }
                        }
                        Operation::GetAttributesResponse(gar) => {
                            substitute_uid(test_name, &mut gar.unique_identifier, uid_map);
                            if let Some(inner_uid) = &mut gar.attributes.unique_identifier {
                                substitute_uid(test_name, inner_uid, uid_map);
                            }
                            // Also substitute any Unique Identifier attribute present in the Links
                            if let Some(links) = &mut gar.attributes.link {
                                for link in links.iter_mut() {
                                    substitute_linked_uid(
                                        test_name,
                                        &mut link.linked_object_identifier,
                                        uid_map,
                                    );
                                }
                            }
                        }
                        Operation::GetAttributeListResponse(resp) => {
                            substitute_uid(test_name, &mut resp.unique_identifier, uid_map);
                        }
                        Operation::EncryptResponse(er) => {
                            substitute_uid(test_name, &mut er.unique_identifier, uid_map);
                        }
                        Operation::DecryptResponse(dr) => {
                            substitute_uid(test_name, &mut dr.unique_identifier, uid_map);
                        }
                        Operation::SignResponse(sr) => {
                            substitute_uid(test_name, &mut sr.unique_identifier, uid_map);
                        }
                        Operation::SignatureVerifyResponse(svr) => {
                            substitute_uid(test_name, &mut svr.unique_identifier, uid_map);
                        }
                        Operation::MACResponse(mr) => {
                            substitute_uid(test_name, &mut mr.unique_identifier, uid_map);
                        }
                        Operation::MACVerifyResponse(mvr) => {
                            substitute_uid(test_name, &mut mvr.unique_identifier, uid_map);
                        }
                        Operation::RevokeResponse(rr) => {
                            substitute_uid(test_name, &mut rr.unique_identifier, uid_map);
                        }
                        Operation::DeleteAttributeResponse(dr) => {
                            substitute_uid(test_name, &mut dr.unique_identifier, uid_map);
                        }
                        _ => {}
                    }
                }
            }
            ResponseMessageBatchItemVersioned::V14(inner) => {
                use cosmian_kmip::kmip_1_4::{
                    kmip_attributes::Attribute as Attr14, kmip_operations::Operation as Op14,
                };
                if let Some(op) = &mut inner.response_payload {
                    match op {
                        Op14::CreateResponse(cr) => {
                            substitute_uid_text(test_name, &mut cr.unique_identifier, uid_map);
                        }
                        Op14::RegisterResponse(rr) => {
                            substitute_uid_text(test_name, &mut rr.unique_identifier, uid_map);
                        }
                        Op14::ActivateResponse(ar) => {
                            substitute_uid_text(test_name, &mut ar.unique_identifier, uid_map);
                        }
                        Op14::GetResponse(gr) => {
                            substitute_uid_text(test_name, &mut gr.unique_identifier, uid_map);
                            substitute_object_wrapping_uids_v14(&mut gr.object, test_name, uid_map);
                        }
                        Op14::CreateKeyPairResponse(ckpr) => {
                            substitute_uid_text(
                                test_name,
                                &mut ckpr.private_key_unique_identifier,
                                uid_map,
                            );
                            substitute_uid_text(
                                test_name,
                                &mut ckpr.public_key_unique_identifier,
                                uid_map,
                            );
                        }
                        Op14::CheckResponse(cr) => {
                            substitute_uid_text(test_name, &mut cr.unique_identifier, uid_map);
                        }
                        Op14::DestroyResponse(dr) => {
                            substitute_uid_text(test_name, &mut dr.unique_identifier, uid_map);
                        }
                        Op14::LocateResponse(lr) => {
                            if let Some(list) = &mut lr.unique_identifier {
                                for uid in list {
                                    substitute_uid_text(test_name, uid, uid_map);
                                }
                            }
                        }
                        Op14::GetAttributesResponse(gar) => {
                            // Substitute outer UniqueIdentifier of the response
                            substitute_uid_text(test_name, &mut gar.unique_identifier, uid_map);
                            // Also substitute any Unique Identifier attribute present in the attribute list
                            if let Some(attrs) = &mut gar.attribute {
                                for a in attrs.iter_mut() {
                                    match a {
                                        Attr14::UniqueIdentifier(s) => {
                                            substitute_uid_text(test_name, s, uid_map);
                                        }
                                        Attr14::Link(link) => {
                                            substitute_uid_text(
                                                test_name,
                                                &mut link.linked_object_identifier,
                                                uid_map,
                                            );
                                        }
                                        _ => {}
                                    }
                                }
                            }
                        }
                        Op14::GetAttributeListResponse(resp) => {
                            substitute_uid_text(test_name, &mut resp.unique_identifier, uid_map);
                        }
                        Op14::EncryptResponse(er) => {
                            substitute_uid_text(test_name, &mut er.unique_identifier, uid_map);
                        }
                        Op14::DecryptResponse(dr) => {
                            substitute_uid_text(test_name, &mut dr.unique_identifier, uid_map);
                        }
                        Op14::SignResponse(sr) => {
                            substitute_uid_text(test_name, &mut sr.unique_identifier, uid_map);
                        }
                        Op14::SignatureVerifyResponse(svr) => {
                            substitute_uid_text(test_name, &mut svr.unique_identifier, uid_map);
                        }
                        Op14::MACResponse(mr) => {
                            substitute_uid_text(test_name, &mut mr.unique_identifier, uid_map);
                        }
                        Op14::MACVerifyResponse(mvr) => {
                            substitute_uid_text(test_name, &mut mvr.unique_identifier, uid_map);
                        }
                        Op14::RevokeResponse(rr) => {
                            substitute_uid_text(test_name, &mut rr.unique_identifier, uid_map);
                        }
                        Op14::DeleteAttributeResponse(dr) => {
                            substitute_uid_text(test_name, &mut dr.unique_identifier, uid_map);
                        }
                        Op14::AddAttributeResponse(ar) => {
                            substitute_uid_text(test_name, &mut ar.unique_identifier, uid_map);
                        }
                        Op14::ModifyAttributeResponse(ar) => {
                            substitute_uid_text(test_name, &mut ar.unique_identifier, uid_map);
                        }
                        _ => {}
                    }
                }
            }
        }
    }
}

/// For `EncryptResponse` payloads in the expected response, substitute placeholder fields
/// like $`DATA_25`, $`IV_COUNTER_NONCE`, and $`AUTHENTICATED_ENCRYPTION_TAG` by copying the actual
/// response values when the expected fields are absent, empty, or contain these explicit placeholders.
/// This makes vectors that leave these as placeholders compare strictly without relaxing byte equality elsewhere.
fn substitute_encrypt_response_data_iv_from_actual(
    expected: &mut ResponseMessage,
    actual: &ResponseMessage,
) {
    // Helper functions to check for placeholder patterns
    let is_data_placeholder = |v: &Vec<u8>| v.starts_with(b"$DATA"); // e.g., "$DATA_25"
    let is_iv_placeholder = |v: &Vec<u8>| v.as_slice() == b"$IV_COUNTER_NONCE";
    let is_tag_placeholder = |v: &Vec<u8>| v.as_slice() == b"$AUTHENTICATED_ENCRYPTION_TAG";

    for (exp_bi, act_bi) in expected.batch_item.iter_mut().zip(actual.batch_item.iter()) {
        match (exp_bi, act_bi) {
            // Handle KMIP 2.1 responses
            (
                ResponseMessageBatchItemVersioned::V21(exp_inner),
                ResponseMessageBatchItemVersioned::V21(act_inner),
            ) => {
                if let (
                    Some(Operation::EncryptResponse(exp_er)),
                    Some(Operation::EncryptResponse(act_er)),
                ) = (&mut exp_inner.response_payload, &act_inner.response_payload)
                {
                    // Data: substitute if empty/missing or contains placeholder
                    let needs_data = match &exp_er.data {
                        None => true,
                        Some(d) if d.is_empty() => true,
                        Some(d) if is_data_placeholder(d) => true,
                        _ => false,
                    };
                    if needs_data {
                        exp_er.data = act_er.data.clone();
                    }

                    // IV/Counter/Nonce: substitute if empty/missing or contains placeholder
                    let needs_iv = match &exp_er.i_v_counter_nonce {
                        None => true,
                        Some(v) if v.is_empty() => true,
                        Some(v) if is_iv_placeholder(v) => true,
                        _ => false,
                    };
                    if needs_iv {
                        exp_er.i_v_counter_nonce = act_er.i_v_counter_nonce.clone();
                    }

                    // AEAD tag: substitute if empty/missing or contains placeholder
                    let needs_tag = match &exp_er.authenticated_encryption_tag {
                        None => true,
                        Some(v) if v.is_empty() => true,
                        Some(v) if is_tag_placeholder(v) => true,
                        _ => false,
                    };
                    if needs_tag {
                        exp_er.authenticated_encryption_tag =
                            act_er.authenticated_encryption_tag.clone();
                    }
                }
            }
            // Handle KMIP 1.4 responses
            (
                ResponseMessageBatchItemVersioned::V14(exp_inner),
                ResponseMessageBatchItemVersioned::V14(act_inner),
            ) => {
                use cosmian_kmip::kmip_1_4::kmip_operations::Operation as Op14;
                if let (Some(Op14::EncryptResponse(exp_er)), Some(Op14::EncryptResponse(act_er))) =
                    (&mut exp_inner.response_payload, &act_inner.response_payload)
                {
                    // Data: substitute if empty/missing or contains placeholder
                    let needs_data = match &exp_er.data {
                        None => true,
                        Some(d) if d.is_empty() => true,
                        Some(d) if is_data_placeholder(d) => true,
                        _ => false,
                    };
                    if needs_data {
                        exp_er.data = act_er.data.clone();
                    }

                    // IV/Counter/Nonce: substitute if empty/missing or contains placeholder
                    let needs_iv = match &exp_er.i_v_counter_nonce {
                        None => true,
                        Some(v) if v.is_empty() => true,
                        Some(v) if is_iv_placeholder(v) => true,
                        _ => false,
                    };
                    if needs_iv {
                        exp_er.i_v_counter_nonce = act_er.i_v_counter_nonce.clone();
                    }

                    // AEAD tag: substitute if empty/missing or contains placeholder
                    let needs_tag = match &exp_er.authenticated_encryption_tag {
                        None => true,
                        Some(v) if v.is_empty() => true,
                        Some(v) if is_tag_placeholder(v) => true,
                        _ => false,
                    };
                    if needs_tag {
                        exp_er.authenticated_encryption_tag =
                            act_er.authenticated_encryption_tag.clone();
                    }
                }
            }
            _ => {
                // Mixed versions or other combinations - skip
            }
        }
    }
}

/// For `SignResponse` payloads in the expected response, substitute placeholder fields
/// like $`SIGNATURE_DATA` by copying the actual response value when the expected field
/// is absent or empty.
fn substitute_sign_response_signature_from_actual(
    expected: &mut ResponseMessage,
    actual: &ResponseMessage,
) {
    for (exp_bi, act_bi) in expected.batch_item.iter_mut().zip(actual.batch_item.iter()) {
        match (exp_bi, act_bi) {
            (
                ResponseMessageBatchItemVersioned::V21(exp_inner),
                ResponseMessageBatchItemVersioned::V21(act_inner),
            ) => {
                if let (
                    Some(Operation::SignResponse(exp_sr)),
                    Some(Operation::SignResponse(act_sr)),
                ) = (&mut exp_inner.response_payload, &act_inner.response_payload)
                {
                    exp_sr.signature_data = act_sr.signature_data.clone();
                }
            }
            (
                ResponseMessageBatchItemVersioned::V14(exp_inner),
                ResponseMessageBatchItemVersioned::V14(act_inner),
            ) => {
                use cosmian_kmip::kmip_1_4::kmip_operations::Operation as Op14;
                if let (Some(Op14::SignResponse(exp_sr)), Some(Op14::SignResponse(act_sr))) =
                    (&mut exp_inner.response_payload, &act_inner.response_payload)
                {
                    exp_sr.signature_data = act_sr.signature_data.clone();
                }
            }
            _ => {}
        }
    }
}

/// Substitute `$KEY_MATERIAL_N` style placeholders in expected responses by copying the
/// actual key material bytes returned by the server. This covers both `KeyValue::ByteString`
/// and `KeyValue::Structure(TransparentSymmetricKey)` cases where vectors avoid embedding
/// literal key bytes.
fn substitute_key_material_from_actual(expected: &mut ResponseMessage, actual: &ResponseMessage) {
    fn is_placeholder_bytes_slice(v: &[u8]) -> bool {
        if v.is_empty() {
            return true;
        }
        let s = String::from_utf8_lossy(v);
        s.starts_with("$KEY_MATERIAL_")
    }

    for (exp_bi, act_bi) in expected.batch_item.iter_mut().zip(actual.batch_item.iter()) {
        let (
            ResponseMessageBatchItemVersioned::V21(exp_inner),
            ResponseMessageBatchItemVersioned::V21(act_inner),
        ) = (exp_bi, act_bi)
        else {
            continue;
        };
        if let (Some(Operation::GetResponse(exp_gr)), Some(Operation::GetResponse(act_gr))) =
            (&mut exp_inner.response_payload, &act_inner.response_payload)
        {
            let (exp_kv_opt, act_kv_opt) = match (&mut exp_gr.object, &act_gr.object) {
                (Object::SymmetricKey(e), Object::SymmetricKey(a)) => {
                    (&mut e.key_block.key_value, &a.key_block.key_value)
                }
                (Object::PrivateKey(e), Object::PrivateKey(a)) => {
                    (&mut e.key_block.key_value, &a.key_block.key_value)
                }
                (Object::PublicKey(e), Object::PublicKey(a)) => {
                    (&mut e.key_block.key_value, &a.key_block.key_value)
                }
                (Object::SecretData(e), Object::SecretData(a)) => {
                    (&mut e.key_block.key_value, &a.key_block.key_value)
                }
                (Object::SplitKey(e), Object::SplitKey(a)) => {
                    (&mut e.key_block.key_value, &a.key_block.key_value)
                }
                _ => (&mut None, &None),
            };

            if let (Some(exp_kv), Some(act_kv)) = (exp_kv_opt.as_mut(), act_kv_opt.as_ref()) {
                match (exp_kv, act_kv) {
                    (KeyValue::ByteString(ebs), KeyValue::ByteString(abs))
                        if is_placeholder_bytes_slice(&ebs[..]) =>
                    {
                        *ebs = abs.clone();
                    }
                    (
                        KeyValue::Structure {
                            key_material: ekm, ..
                        },
                        KeyValue::Structure {
                            key_material: akm, ..
                        },
                    ) => match (ekm, akm) {
                        (KeyMaterial::ByteString(ebs), KeyMaterial::ByteString(abs))
                            if is_placeholder_bytes_slice(&ebs[..]) =>
                        {
                            *ebs = abs.clone();
                        }
                        (
                            KeyMaterial::TransparentSymmetricKey { key: ekey },
                            KeyMaterial::TransparentSymmetricKey { key: akey },
                        ) if ekey.is_empty() => {
                            *ekey = akey.clone();
                        }
                        _ => {}
                    },
                    _ => {}
                }
            }
        }
    }
}

/// For `PKCS11Response` payloads in the expected response, substitute the
/// `$CORRELATION_VALUE` placeholder by copying the actual response bytes.
fn substitute_pkcs11_correlation_from_actual(
    expected: &mut ResponseMessage,
    actual: &ResponseMessage,
) {
    let placeholder = b"$CORRELATION_VALUE";
    for (exp_bi, act_bi) in expected.batch_item.iter_mut().zip(actual.batch_item.iter()) {
        let (
            ResponseMessageBatchItemVersioned::V21(exp_inner),
            ResponseMessageBatchItemVersioned::V21(act_inner),
        ) = (exp_bi, act_bi)
        else {
            continue;
        };
        if let (Some(Operation::PKCS11Response(exp_pk)), Some(Operation::PKCS11Response(act_pk))) =
            (&mut exp_inner.response_payload, &act_inner.response_payload)
        {
            let needs = exp_pk
                .correlation_value
                .as_ref()
                .is_none_or(|v| v.is_empty() || v.as_slice() == placeholder);
            if needs {
                exp_pk.correlation_value = act_pk.correlation_value.clone();
            }
        }
    }
}

/// Substitute `$SHORT_UNIQUE_IDENTIFIER_N` placeholders in expected `GetAttributesResponse`
/// by copying the actual `ShortUniqueIdentifier` from the server response.
fn substitute_short_unique_identifier_from_actual(
    expected: &mut ResponseMessage,
    actual: &ResponseMessage,
) {
    for (exp_bi, act_bi) in expected.batch_item.iter_mut().zip(actual.batch_item.iter()) {
        let (
            ResponseMessageBatchItemVersioned::V21(exp_inner),
            ResponseMessageBatchItemVersioned::V21(act_inner),
        ) = (exp_bi, act_bi)
        else {
            continue;
        };
        if let (
            Some(Operation::GetAttributesResponse(exp_ga)),
            Some(Operation::GetAttributesResponse(act_ga)),
        ) = (&mut exp_inner.response_payload, &act_inner.response_payload)
        {
            if let Some(exp_short) = &mut exp_ga.attributes.short_unique_identifier {
                if exp_short.starts_with("$SHORT_UNIQUE_IDENTIFIER_") {
                    if let Some(act_short) = &act_ga.attributes.short_unique_identifier {
                        *exp_short = act_short.clone();
                    }
                }
            }
        }
    }
}

/// For Create/Register responses, always copy the `UniqueIdentifier` from the actual
/// response into the expected response. This avoids mismatches when a prior Locate
/// (in the same vector) inserted an entry in the UID placeholder map before a Create/Register
/// occurs, shifting index expectations.
fn substitute_create_register_uids_from_actual(
    expected: &mut ResponseMessage,
    actual: &ResponseMessage,
) {
    for (exp_bi, act_bi) in expected.batch_item.iter_mut().zip(actual.batch_item.iter()) {
        match (exp_bi, act_bi) {
            (
                ResponseMessageBatchItemVersioned::V21(exp_inner),
                ResponseMessageBatchItemVersioned::V21(act_inner),
            ) => {
                use cosmian_kms_client::cosmian_kmip::kmip_2_1::kmip_operations::Operation as Op21;
                match (&mut exp_inner.response_payload, &act_inner.response_payload) {
                    (Some(Op21::CreateResponse(exp_cr)), Some(Op21::CreateResponse(act_cr))) => {
                        exp_cr.unique_identifier = act_cr.unique_identifier.clone();
                    }
                    (
                        Some(Op21::RegisterResponse(exp_rr)),
                        Some(Op21::RegisterResponse(act_rr)),
                    ) => {
                        exp_rr.unique_identifier = act_rr.unique_identifier.clone();
                    }
                    _ => {}
                }
            }
            (
                ResponseMessageBatchItemVersioned::V14(exp_inner),
                ResponseMessageBatchItemVersioned::V14(act_inner),
            ) => {
                use cosmian_kms_client::cosmian_kmip::kmip_1_4::kmip_operations::Operation as Op14;
                match (&mut exp_inner.response_payload, &act_inner.response_payload) {
                    (Some(Op14::CreateResponse(exp_cr)), Some(Op14::CreateResponse(act_cr))) => {
                        exp_cr.unique_identifier = act_cr.unique_identifier.clone();
                    }
                    (
                        Some(Op14::RegisterResponse(exp_rr)),
                        Some(Op14::RegisterResponse(act_rr)),
                    ) => {
                        exp_rr.unique_identifier = act_rr.unique_identifier.clone();
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }
}

// Adjust LocateResponse when the shared server returns more objects than the original
// vector anticipated (expected usually lists only one). To keep the semantics (the
// expected UID must be among the located ones) we copy the full list & count from
// the actual response if the expected list is shorter.
fn substitute_locate_response_from_actual(
    expected: &mut ResponseMessage,
    actual: &ResponseMessage,
) {
    use cosmian_kmip::kmip_0::kmip_messages::ResponseMessageBatchItemVersioned;
    use cosmian_kms_client::cosmian_kmip::kmip_2_1::kmip_operations::Operation;

    for (exp_bi, act_bi) in expected.batch_item.iter_mut().zip(actual.batch_item.iter()) {
        match (exp_bi, act_bi) {
            (
                ResponseMessageBatchItemVersioned::V21(exp_inner),
                ResponseMessageBatchItemVersioned::V21(act_inner),
            ) => {
                if let (
                    Some(Operation::LocateResponse(exp_lr)),
                    Some(Operation::LocateResponse(act_lr)),
                ) = (&mut exp_inner.response_payload, &act_inner.response_payload)
                {
                    let exp_count = exp_lr.located_items;
                    let act_count = act_lr.located_items;
                    let exp_list_len = exp_lr
                        .unique_identifier
                        .as_ref()
                        .map_or(0, std::vec::Vec::len);
                    let act_list_len = act_lr
                        .unique_identifier
                        .as_ref()
                        .map_or(0, std::vec::Vec::len);

                    // If the number of returned UIDs differs in any way, adopt the actual
                    // list and the corresponding count to keep the expected response consistent.
                    if act_list_len != exp_list_len {
                        exp_lr.unique_identifier = act_lr.unique_identifier.clone();
                        exp_lr.located_items = act_count;
                    } else if exp_count != act_count {
                        // counts differ but list lengths are the same (rare); adopt actual count
                        exp_lr.located_items = act_count;
                    }
                }
            }
            (
                ResponseMessageBatchItemVersioned::V14(exp_inner),
                ResponseMessageBatchItemVersioned::V14(act_inner),
            ) => {
                use cosmian_kmip::kmip_1_4::kmip_operations::Operation as Op14;
                if let (Some(Op14::LocateResponse(exp_lr)), Some(Op14::LocateResponse(act_lr))) =
                    (&mut exp_inner.response_payload, &act_inner.response_payload)
                {
                    let exp_len = exp_lr
                        .unique_identifier
                        .as_ref()
                        .map_or(0, std::vec::Vec::len);
                    let act_len = act_lr
                        .unique_identifier
                        .as_ref()
                        .map_or(0, std::vec::Vec::len);

                    // If expected omits the list or the lengths differ, adopt actual list
                    if act_len != exp_len {
                        exp_lr.unique_identifier = act_lr.unique_identifier.clone();
                    }
                }
            }
            _ => {}
        }
    }
}

// Insert the real UID into the map if it's new; log mapping with namespaced placeholder
fn log_insert(test_name: &str, uid_map: &mut HashMap<usize, String>, uid: &UniqueIdentifier) {
    if let Some(idx) = store_next_uid(uid_map, uid) {
        if let UniqueIdentifier::TextString(s) = uid {
            trace!(
                "[{}] mapped {} -> {}",
                test_name,
                format!("{}-uid-{}", test_name, idx),
                s
            );
        }
    }
}

fn log_insert_text(test_name: &str, uid_map: &mut HashMap<usize, String>, uid: &str) {
    if let Some(idx) = store_next_uid_text(uid_map, uid) {
        trace!(
            "[{}] mapped {} -> {}",
            test_name,
            format!("{}-uid-{}", test_name, idx),
            uid
        );
    }
}

// Store next UID if it is not already present. Return index used when inserted.
fn store_next_uid(uid_map: &mut HashMap<usize, String>, uid: &UniqueIdentifier) -> Option<usize> {
    let UniqueIdentifier::TextString(s) = uid else {
        return None;
    };
    // Avoid duplicates
    if uid_map.values().any(|v| v == s) {
        return None;
    }
    let idx = uid_map.len();
    uid_map.insert(idx, s.clone());
    Some(idx)
}

fn store_next_uid_text(uid_map: &mut HashMap<usize, String>, uid: &str) -> Option<usize> {
    if uid_map.values().any(|v| v == uid) {
        return None;
    }
    let idx = uid_map.len();
    uid_map.insert(idx, uid.to_string());
    Some(idx)
}

// Substitute a placeholder UID (namespaced or legacy) with the real value from the map.
fn substitute_uid(test_name: &str, uid: &mut UniqueIdentifier, uid_map: &HashMap<usize, String>) {
    let UniqueIdentifier::TextString(s) = uid else {
        return;
    };
    // Accept patterns:
    //   {test_name}-uid-{n}
    //   uid-{n}
    //   $UNIQUE_IDENTIFIER_{n}
    let idx_opt = s
        .strip_prefix(test_name)
        .and_then(|r| r.strip_prefix("-uid-"))
        .map_or_else(
            || {
                s.strip_prefix("uid-").map_or_else(
                    || {
                        s.strip_prefix("$UNIQUE_IDENTIFIER_")
                            .and_then(|rest| rest.parse::<usize>().ok())
                    },
                    |rest| rest.parse::<usize>().ok(),
                )
            },
            |rest| rest.parse::<usize>().ok(),
        );
    if let Some(idx) = idx_opt {
        if let Some(real) = uid_map.get(&idx) {
            *s = real.clone();
        }
    }
}

// Substitute a placeholder LinkedObjectIdentifier with the real value from the map.
fn substitute_linked_uid(
    test_name: &str,
    uid: &mut LinkedObjectIdentifier,
    uid_map: &HashMap<usize, String>,
) {
    let LinkedObjectIdentifier::TextString(s) = uid else {
        return;
    };
    // Accept patterns:
    //   {test_name}-uid-{n}
    //   uid-{n}
    //   $UNIQUE_IDENTIFIER_{n}
    let idx_opt = s
        .strip_prefix(test_name)
        .and_then(|r| r.strip_prefix("uid-"))
        .map_or_else(
            || {
                s.strip_prefix("uid-").map_or_else(
                    || {
                        s.strip_prefix("$UNIQUE_IDENTIFIER_")
                            .and_then(|rest| rest.parse::<usize>().ok())
                    },
                    |rest| rest.parse::<usize>().ok(),
                )
            },
            |rest| rest.parse::<usize>().ok(),
        );
    if let Some(idx) = idx_opt {
        if let Some(real) = uid_map.get(&idx) {
            *s = real.clone();
        }
    }
}