vta-service 0.2.1

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
//! KMS-based secret bootstrap for Nitro Enclaves.
//!
//! On first boot (no existing ciphertext), generates a BIP-39 seed and JWT
//! signing key inside the TEE, encrypts them with KMS, writes the ciphertext
//! to external storage, and stores a JWT key fingerprint for tamper detection.
//!
//! On subsequent boots, decrypts the ciphertext using KMS, verifies the JWT
//! key fingerprint, and returns the secrets for use.
//!
//! # Attestation
//!
//! Both encrypt and decrypt paths use Nitro attestation when `/dev/nsm` is
//! available (real Nitro hardware):
//!
//! - **Encrypt** uses `GenerateDataKey` with a `Recipient` parameter. KMS
//!   generates a random data key and returns it encrypted to an ephemeral RSA
//!   key bound to the enclave's attestation document (CMS envelope). The
//!   enclave unwraps the data key locally and uses it to AES-GCM encrypt the
//!   secret. The stored blob contains the KMS-encrypted data key + AES-GCM
//!   ciphertext ("sealed blob" format).
//!
//! - **Decrypt** uses `Decrypt` with a `Recipient` parameter. KMS re-encrypts
//!   the plaintext to an ephemeral RSA key bound to the attestation document.
//!
//! This ensures the KMS key policy's PCR conditions (PCR0 image hash, PCR8
//! signing cert hash) are enforced on **both** encrypt and decrypt, preventing
//! an attacker with IAM role access from encrypting rogue data that could
//! overwrite legitimate ciphertexts in storage.
//!
//! When NSM is not available (simulated mode or development), both paths fall
//! back to direct KMS calls without attestation.

use sha2::{Digest, Sha256};
use tracing::{debug, error, info, warn};
use zeroize::Zeroize;

use crate::config::TeeKmsConfig;
use crate::error::{AppError, tee_attestation_error};

/// Secrets bootstrapped from KMS, held only in TEE memory.
///
/// All secret fields are zeroed on drop via the `Drop` implementation.
pub struct BootstrappedSecrets {
    /// BIP-39 seed (32 bytes).
    pub seed: Vec<u8>,
    /// JWT signing key (32 bytes).
    pub jwt_signing_key: [u8; 32],
    /// AES-256 storage encryption key (32 bytes), derived from seed via HKDF.
    pub storage_key: [u8; 32],
    /// BIP-39 entropy bytes (only on first boot — `None` on subsequent boots).
    pub entropy: Option<[u8; 32]>,
    /// Whether this is a first boot (new secrets generated).
    pub is_first_boot: bool,
}

impl Drop for BootstrappedSecrets {
    fn drop(&mut self) {
        self.seed.zeroize();
        self.jwt_signing_key.zeroize();
        self.storage_key.zeroize();
        if let Some(ref mut e) = self.entropy {
            e.zeroize();
        }
    }
}


/// Well-known keys in the bootstrap keyspace.
///
/// The data key is generated via KMS `GenerateDataKey` (with attestation when
/// available). Both secrets are AES-GCM encrypted with the same data key but
/// unique nonces. The nonce is prepended to each ciphertext entry.
const BOOTSTRAP_DK_CT_KEY: &str = "bootstrap:data_key_ciphertext";
const BOOTSTRAP_SEED_CT_KEY: &str = "bootstrap:seed_ciphertext";
const BOOTSTRAP_JWT_CT_KEY: &str = "bootstrap:jwt_ciphertext";
const BOOTSTRAP_JWT_FINGERPRINT_KEY: &str = "bootstrap:jwt_fingerprint";

/// Bootstrap secrets from KMS.
///
/// - If ciphertext files exist: decrypt via KMS, verify JWT fingerprint (subsequent boot)
/// - If no ciphertext files: generate new secrets, encrypt with KMS, store (first boot)
pub async fn bootstrap_secrets(
    kms_config: &TeeKmsConfig,
    storage_key_salt: &str,
    store: &crate::store::Store,
) -> Result<BootstrappedSecrets, AppError> {
    // Bootstrap keyspace — no encryption (data is KMS-protected)
    let bs_ks = store.keyspace("bootstrap")?;

    let dk_ct = bs_ks.get_raw(BOOTSTRAP_DK_CT_KEY).await?;
    let seed_ct = bs_ks.get_raw(BOOTSTRAP_SEED_CT_KEY).await?;
    let jwt_ct = bs_ks.get_raw(BOOTSTRAP_JWT_CT_KEY).await?;

    if let (Some(dk_ciphertext), Some(seed_ciphertext), Some(jwt_ciphertext)) =
        (dk_ct, seed_ct, jwt_ct)
    {
        // ── Subsequent boot: decrypt existing ciphertexts ──
        info!("found existing secret ciphertexts in store — decrypting via KMS");

        match kms_decrypt_data_key(kms_config, &dk_ciphertext).await {
            Ok(data_key) => {
                let seed = aes_gcm_decrypt(&data_key, &seed_ciphertext)?;
                let jwt_bytes = aes_gcm_decrypt(&data_key, &jwt_ciphertext)?;
                let jwt_key: [u8; 32] = jwt_bytes.try_into().map_err(|_| {
                    tee_attestation_error("JWT key must be exactly 32 bytes")
                })?;

                verify_jwt_fingerprint(&bs_ks, &jwt_key).await?;
                info!("secrets decrypted from KMS — subsequent boot");

                let storage_key = derive_storage_key(&seed, storage_key_salt);
                return Ok(BootstrappedSecrets {
                    seed,
                    jwt_signing_key: jwt_key,
                    storage_key,
                    entropy: None,
                    is_first_boot: false,
                });
            }
            Err(e) => {
                // KMS decrypt failed — likely a PCR0 mismatch after image rebuild.
                // Clear the stale bootstrap data and fall through to first boot.
                warn!(
                    error = %e,
                    "KMS decrypt of existing ciphertexts failed — clearing stale \
                     bootstrap data and starting fresh. This is expected after an \
                     image rebuild with a new PCR0. The VTA will generate a new \
                     identity."
                );
                bs_ks.remove(BOOTSTRAP_DK_CT_KEY).await?;
                bs_ks.remove(BOOTSTRAP_SEED_CT_KEY).await?;
                bs_ks.remove(BOOTSTRAP_JWT_CT_KEY).await?;
                bs_ks.remove(BOOTSTRAP_JWT_FINGERPRINT_KEY).await?;
                store.persist().await?;
                // Fall through to first boot path below
            }
        }
    }

    // ── First boot: generate new secrets inside the TEE ──
    info!("first boot — generating new secrets in TEE");

    let mut entropy = [0u8; 32];
    rand::fill(&mut entropy);
    let mnemonic = bip39::Mnemonic::from_entropy(&entropy)
        .map_err(|e| tee_attestation_error(format!("failed to generate mnemonic: {e}")))?;

    info!("master seed generated inside TEE (mnemonic NOT displayed)");
    info!("to export the mnemonic, restart with VTA_MNEMONIC_EXPORT_WINDOW=<seconds>");

    let full_seed = mnemonic.to_seed("").to_vec();
    let seed = full_seed[..32].to_vec();

    let mut jwt_key_bytes = [0u8; 32];
    rand::fill(&mut jwt_key_bytes);
    let jwt_key = jwt_key_bytes;

    // Generate a data key via KMS, encrypt both secrets with it
    let (dk_ciphertext, data_key) = kms_generate_data_key(kms_config).await?;
    let seed_ciphertext = aes_gcm_encrypt(&data_key, &seed)?;
    let jwt_ciphertext = aes_gcm_encrypt(&data_key, &jwt_key)?;

    bs_ks.insert_raw(BOOTSTRAP_DK_CT_KEY, dk_ciphertext).await?;
    bs_ks.insert_raw(BOOTSTRAP_SEED_CT_KEY, seed_ciphertext).await?;
    bs_ks.insert_raw(BOOTSTRAP_JWT_CT_KEY, jwt_ciphertext).await?;
    store_jwt_fingerprint(&bs_ks, &jwt_key).await?;

    // Flush to ensure ciphertexts survive if the enclave crashes during startup
    store.persist().await?;

    info!("secrets generated and encrypted to KMS — ciphertexts stored");

    Ok(BootstrappedSecrets {
        storage_key: derive_storage_key(&seed, storage_key_salt),
        seed,
        jwt_signing_key: jwt_key,
        entropy: Some(entropy),
        is_first_boot: true,
    })
}

// ---------------------------------------------------------------------------
// Re-encrypt secrets for backup import
// ---------------------------------------------------------------------------

/// Re-encrypt an imported seed and JWT key with KMS.
///
/// Called during backup import in TEE mode. Generates a new KMS data key,
/// AES-GCM encrypts both secrets, and stores the ciphertexts in the bootstrap
/// keyspace. On next restart, `bootstrap_secrets()` finds existing ciphertexts
/// and takes the normal "subsequent boot" decrypt path.
pub async fn re_encrypt_bootstrap_secrets(
    kms_config: &TeeKmsConfig,
    store: &crate::store::Store,
    seed: &[u8],
    jwt_key: &[u8; 32],
) -> Result<(), AppError> {
    let bs_ks = store.keyspace("bootstrap")?;

    // Clear any existing ciphertexts first
    let _ = bs_ks.remove(BOOTSTRAP_DK_CT_KEY).await;
    let _ = bs_ks.remove(BOOTSTRAP_SEED_CT_KEY).await;
    let _ = bs_ks.remove(BOOTSTRAP_JWT_CT_KEY).await;
    let _ = bs_ks.remove(BOOTSTRAP_JWT_FINGERPRINT_KEY).await;

    // Generate a new data key via KMS (with attestation if on real Nitro)
    let (dk_ciphertext, data_key) = kms_generate_data_key(kms_config).await?;

    // AES-GCM encrypt both secrets with the data key
    let seed_ciphertext = aes_gcm_encrypt(&data_key, seed)?;
    let jwt_ciphertext = aes_gcm_encrypt(&data_key, jwt_key)?;

    // Store everything in the bootstrap keyspace
    bs_ks.insert_raw(BOOTSTRAP_DK_CT_KEY, dk_ciphertext).await?;
    bs_ks.insert_raw(BOOTSTRAP_SEED_CT_KEY, seed_ciphertext).await?;
    bs_ks.insert_raw(BOOTSTRAP_JWT_CT_KEY, jwt_ciphertext).await?;
    store_jwt_fingerprint(&bs_ks, jwt_key).await?;

    // Flush immediately so ciphertexts survive if enclave restarts
    store.persist().await?;

    info!("imported secrets re-encrypted to KMS — stored in bootstrap keyspace");
    Ok(())
}

// ---------------------------------------------------------------------------
// JWT key fingerprint (tamper detection)
// ---------------------------------------------------------------------------

/// Compute a SHA-256 fingerprint of the JWT signing key.
fn jwt_fingerprint(key: &[u8; 32]) -> String {
    let hash = Sha256::digest(key);
    hex::encode(&hash[..16]) // First 16 bytes = 32 hex chars
}

// ---------------------------------------------------------------------------
// JWT key fingerprint (tamper detection)
// ---------------------------------------------------------------------------

/// Store the JWT key fingerprint in the bootstrap keyspace.
async fn store_jwt_fingerprint(
    bs_ks: &crate::store::KeyspaceHandle,
    key: &[u8; 32],
) -> Result<(), AppError> {
    let fingerprint = jwt_fingerprint(key);
    bs_ks.insert_raw(BOOTSTRAP_JWT_FINGERPRINT_KEY, fingerprint.as_bytes().to_vec()).await?;
    debug!(fingerprint = %fingerprint, "JWT key fingerprint stored");
    Ok(())
}

/// Verify the JWT key matches the stored fingerprint.
async fn verify_jwt_fingerprint(
    bs_ks: &crate::store::KeyspaceHandle,
    key: &[u8; 32],
) -> Result<(), AppError> {
    let stored_bytes = match bs_ks.get_raw(BOOTSTRAP_JWT_FINGERPRINT_KEY).await? {
        Some(bytes) => bytes,
        None => {
            warn!("no JWT fingerprint found — storing one now (first boot after upgrade)");
            return store_jwt_fingerprint(bs_ks, key).await;
        }
    };

    let stored = String::from_utf8_lossy(&stored_bytes);
    let computed = jwt_fingerprint(key);

    if stored.trim() != computed {
        error!(
            stored = %stored.trim(),
            computed = %computed,
            "JWT key fingerprint MISMATCH — possible key tampering or KMS key rotation"
        );
        return Err(tee_attestation_error(
            "JWT key fingerprint mismatch — the decrypted JWT key does not match the key \
             used on first boot. This could indicate tampering with the ciphertext \
             or a KMS key change. If this is intentional (e.g., disaster recovery), \
             clear the bootstrap keyspace and restart.",
        ));
    }

    debug!(fingerprint = %computed, "JWT key fingerprint verified");
    Ok(())
}

// ---------------------------------------------------------------------------
// Storage key derivation
// ---------------------------------------------------------------------------

/// Derive the AES-256 storage encryption key from the master seed using HKDF.
///
/// Uses HMAC-SHA256 as the PRF. The salt and info strings ensure domain separation.
/// Deterministic: same seed + salt → same key (survives enclave restarts).
pub(crate) fn derive_storage_key(seed: &[u8], salt: &str) -> [u8; 32] {
    use hmac::{Hmac, Mac};
    type HmacSha256 = Hmac<Sha256>;

    // HKDF-Extract: PRK = HMAC-SHA256(salt, seed)
    let mut mac = HmacSha256::new_from_slice(salt.as_bytes())
        .expect("HMAC accepts any key length");
    mac.update(seed);
    let prk = mac.finalize().into_bytes();

    // HKDF-Expand: OKM = HMAC-SHA256(PRK, info || 0x01)
    let info = b"aes-256-gcm-storage";
    let mut mac = HmacSha256::new_from_slice(&prk)
        .expect("HMAC accepts any key length");
    mac.update(info);
    mac.update(&[0x01]);
    let okm = mac.finalize().into_bytes();

    let mut key = [0u8; 32];
    key.copy_from_slice(&okm);
    key
}

// ---------------------------------------------------------------------------
// KMS helpers
// ---------------------------------------------------------------------------

/// Create a KMS client for the configured region.
async fn kms_client(config: &TeeKmsConfig) -> aws_sdk_kms::Client {
    let sdk_config = aws_config::defaults(aws_config::BehaviorVersion::latest())
        .region(aws_config::Region::new(config.region.clone()))
        .load()
        .await;
    aws_sdk_kms::Client::new(&sdk_config)
}

/// Generate an ephemeral RSA-2048 keypair and obtain an NSM attestation
/// document binding the public key. Returns `(private_key, recipient_info)`
/// for use with KMS attested operations.
fn nsm_attested_recipient() -> Result<
    (rsa::RsaPrivateKey, aws_sdk_kms::types::RecipientInfo),
    AppError,
> {
    use rsa::pkcs8::EncodePublicKey;

    let mut rng = rsa::rand_core::OsRng;
    let private_key = rsa::RsaPrivateKey::new(&mut rng, 2048).map_err(|e| {
        tee_attestation_error(format!("RSA key generation failed: {e}"))
    })?;

    let public_key_der = private_key
        .to_public_key()
        .to_public_key_der()
        .map_err(|e| {
            tee_attestation_error(format!("RSA public key DER encoding failed: {e}"))
        })?;

    let attestation_doc =
        super::nitro::request_nsm_attestation_for_kms(public_key_der.as_ref())?;

    let recipient = aws_sdk_kms::types::RecipientInfo::builder()
        .attestation_document(aws_sdk_kms::primitives::Blob::new(attestation_doc))
        .key_encryption_algorithm(
            aws_sdk_kms::types::KeyEncryptionMechanism::RsaesOaepSha256,
        )
        .build();

    Ok((private_key, recipient))
}

/// Extract the plaintext from an attested KMS response's CMS envelope.
///
/// When a `Recipient` is provided, KMS returns `CiphertextForRecipient`
/// (CMS EnvelopedData, RFC 5652) instead of `Plaintext`. This function
/// unwraps that envelope using the ephemeral RSA private key.
fn unwrap_cms_response(
    cms_blob: Option<&aws_sdk_kms::primitives::Blob>,
    private_key: &rsa::RsaPrivateKey,
) -> Result<Vec<u8>, AppError> {
    let cms_bytes = cms_blob.ok_or_else(|| {
        tee_attestation_error(
            "KMS response missing CiphertextForRecipient — \
             the KMS key may not support attestation-based operations",
        )
    })?;
    decrypt_cms_envelope(cms_bytes.as_ref(), private_key)
}

// ---------------------------------------------------------------------------
// KMS operations
// ---------------------------------------------------------------------------

/// Decrypt a KMS data key ciphertext (the `CiphertextBlob` from `GenerateDataKey`).
///
/// On real Nitro hardware (`/dev/nsm` available), uses attestation-based
/// KMS Decrypt with the `Recipient` parameter. Falls back to direct KMS
/// Decrypt if attestation fails.
async fn kms_decrypt_data_key(
    config: &TeeKmsConfig,
    ciphertext: &[u8],
) -> Result<Vec<u8>, AppError> {
    if std::path::Path::new("/dev/nsm").exists() {
        match kms_decrypt_attested(config, ciphertext).await {
            Ok(plaintext) => {
                info!("KMS Decrypt succeeded with Nitro attestation");
                return Ok(plaintext);
            }
            Err(e) => {
                warn!(
                    error = %e,
                    "attestation-based KMS Decrypt failed — falling back to direct Decrypt"
                );
            }
        }
    }

    kms_decrypt_direct(config, ciphertext).await
}

/// KMS Decrypt with Nitro attestation via the Recipient parameter.
async fn kms_decrypt_attested(
    config: &TeeKmsConfig,
    ciphertext: &[u8],
) -> Result<Vec<u8>, AppError> {
    let (private_key, recipient) = nsm_attested_recipient()?;
    let client = kms_client(config).await;

    let resp = client
        .decrypt()
        .ciphertext_blob(aws_sdk_kms::primitives::Blob::new(ciphertext))
        .key_id(&config.key_arn)
        .recipient(recipient)
        .send()
        .await
        .map_err(|e| classify_kms_error("Decrypt(attested)", e))?;

    unwrap_cms_response(resp.ciphertext_for_recipient(), &private_key)
}

/// Direct KMS Decrypt without the Recipient parameter.
async fn kms_decrypt_direct(
    config: &TeeKmsConfig,
    ciphertext: &[u8],
) -> Result<Vec<u8>, AppError> {
    let client = kms_client(config).await;

    let resp = client
        .decrypt()
        .ciphertext_blob(aws_sdk_kms::primitives::Blob::new(ciphertext))
        .key_id(&config.key_arn)
        .send()
        .await
        .map_err(|e| classify_kms_error("Decrypt", e))?;

    resp.plaintext()
        .map(|b| b.as_ref().to_vec())
        .ok_or_else(|| tee_attestation_error("KMS Decrypt returned no plaintext"))
}

/// Generate a KMS data key, returning (kms_ciphertext, plaintext_key).
///
/// On real Nitro hardware, uses the `Recipient` parameter so KMS enforces
/// PCR conditions on `kms:GenerateDataKey`. The plaintext key is returned
/// via a CMS envelope decrypted with an ephemeral RSA key inside the enclave.
///
/// Without NSM, calls `GenerateDataKey` directly (KMS returns plaintext in
/// the response — suitable for development/simulated mode only).
async fn kms_generate_data_key(
    config: &TeeKmsConfig,
) -> Result<(Vec<u8>, [u8; 32]), AppError> {
    if std::path::Path::new("/dev/nsm").exists() {
        match kms_generate_data_key_attested(config).await {
            Ok(result) => {
                info!("KMS GenerateDataKey succeeded with Nitro attestation");
                return Ok(result);
            }
            Err(e) => {
                warn!(
                    error = %e,
                    "attestation-based GenerateDataKey failed — falling back to direct"
                );
            }
        }
    }

    kms_generate_data_key_direct(config).await
}

/// `GenerateDataKey` with Nitro attestation via the `Recipient` parameter.
async fn kms_generate_data_key_attested(
    config: &TeeKmsConfig,
) -> Result<(Vec<u8>, [u8; 32]), AppError> {
    let (private_key, recipient) = nsm_attested_recipient()?;
    let client = kms_client(config).await;

    let resp = client
        .generate_data_key()
        .key_id(&config.key_arn)
        .key_spec(aws_sdk_kms::types::DataKeySpec::Aes256)
        .recipient(recipient)
        .send()
        .await
        .map_err(|e| classify_kms_error("GenerateDataKey(attested)", e))?;

    let kms_ciphertext = resp
        .ciphertext_blob()
        .ok_or_else(|| tee_attestation_error("GenerateDataKey returned no CiphertextBlob"))?
        .as_ref()
        .to_vec();

    let data_key_vec = unwrap_cms_response(resp.ciphertext_for_recipient(), &private_key)?;
    let data_key: [u8; 32] = data_key_vec.try_into().map_err(|_| {
        tee_attestation_error("data key is not 32 bytes")
    })?;

    debug!(kms_ct_len = kms_ciphertext.len(), "obtained attested data key");
    Ok((kms_ciphertext, data_key))
}

/// `GenerateDataKey` without attestation (development/simulated mode).
async fn kms_generate_data_key_direct(
    config: &TeeKmsConfig,
) -> Result<(Vec<u8>, [u8; 32]), AppError> {
    let client = kms_client(config).await;

    let resp = client
        .generate_data_key()
        .key_id(&config.key_arn)
        .key_spec(aws_sdk_kms::types::DataKeySpec::Aes256)
        .send()
        .await
        .map_err(|e| classify_kms_error("GenerateDataKey", e))?;

    let kms_ciphertext = resp
        .ciphertext_blob()
        .ok_or_else(|| tee_attestation_error("GenerateDataKey returned no CiphertextBlob"))?
        .as_ref()
        .to_vec();

    let plaintext = resp
        .plaintext()
        .ok_or_else(|| tee_attestation_error("GenerateDataKey returned no Plaintext"))?;
    let data_key: [u8; 32] = plaintext.as_ref().try_into().map_err(|_| {
        tee_attestation_error("data key is not 32 bytes")
    })?;

    Ok((kms_ciphertext, data_key))
}

// ---------------------------------------------------------------------------
// Local AES-GCM envelope (nonce-prepended)
// ---------------------------------------------------------------------------

/// AES-256-GCM encrypt, returning `[nonce: 12 bytes][ciphertext]`.
fn aes_gcm_encrypt(key: &[u8; 32], plaintext: &[u8]) -> Result<Vec<u8>, AppError> {
    use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
    use aes_gcm::aead::generic_array::GenericArray;

    let cipher = Aes256Gcm::new(GenericArray::from_slice(key));
    let mut nonce_bytes = [0u8; 12];
    rand::fill(&mut nonce_bytes);
    let nonce = GenericArray::from_slice(&nonce_bytes);
    let ciphertext = cipher.encrypt(nonce, plaintext).map_err(|e| {
        tee_attestation_error(format!("AES-GCM encryption failed: {e}"))
    })?;

    let mut out = Vec::with_capacity(12 + ciphertext.len());
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(&ciphertext);
    Ok(out)
}

/// AES-256-GCM decrypt a `[nonce: 12 bytes][ciphertext]` blob.
fn aes_gcm_decrypt(key: &[u8], blob: &[u8]) -> Result<Vec<u8>, AppError> {
    use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
    use aes_gcm::aead::generic_array::GenericArray;

    if key.len() != 32 {
        return Err(tee_attestation_error(format!(
            "data key is {} bytes, expected 32",
            key.len()
        )));
    }
    if blob.len() < 12 + 1 {
        return Err(tee_attestation_error("AES-GCM blob too short"));
    }

    let nonce = GenericArray::from_slice(&blob[..12]);
    let ciphertext = &blob[12..];
    let cipher = Aes256Gcm::new(GenericArray::from_slice(key));
    cipher.decrypt(nonce, ciphertext).map_err(|e| {
        tee_attestation_error(format!("AES-GCM decryption failed: {e}"))
    })
}

// ---------------------------------------------------------------------------
// CMS EnvelopedData decryption (RFC 5652)
// ---------------------------------------------------------------------------

/// Decrypt a CMS EnvelopedData envelope returned by KMS CiphertextForRecipient.
///
/// KMS produces a CMS EnvelopedData (RFC 5652) with:
/// - One `KeyTransRecipientInfo` containing the CEK encrypted with RSA-OAEP-SHA256
/// - `EncryptedContentInfo` with AES-256-GCM encrypted plaintext
///
/// We parse the DER structure manually (the format from KMS is fixed), unwrap the
/// CEK with the ephemeral RSA private key, then decrypt the content with AES-256-GCM.
fn decrypt_cms_envelope(
    cms_bytes: &[u8],
    private_key: &rsa::RsaPrivateKey,
) -> Result<Vec<u8>, AppError> {
    // Log first bytes for diagnosing BER structure issues with real KMS responses
    debug!(
        cms_len = cms_bytes.len(),
        cms_hex_head = %hex::encode(cms_bytes),
        "raw CMS envelope"
    );

    // Parse the CMS EnvelopedData to extract the three fields we need
    let fields = cms_der::parse_enveloped_data(cms_bytes)?;

    // RSA-OAEP decrypt the content-encryption key (CEK).
    // We request RSAES_OAEP_SHA_256 in the Recipient parameter, but KMS may
    // use SHA-256 for the hash and SHA-1 for the MGF1 mask generation function.
    // Try SHA-256 first, then fall back to the mixed SHA-256/SHA-1 variant.
    use rsa::Oaep;
    let cek = private_key
        .decrypt(Oaep::new::<sha2::Sha256>(), &fields.encrypted_key)
        .or_else(|_| {
            // KMS may use SHA-256 hash + SHA-1 MGF1 (common in PKCS#11 implementations)
            let padding = Oaep::new_with_mgf_hash::<sha2::Sha256, sha1::Sha1>();
            private_key.decrypt(padding, &fields.encrypted_key)
        })
        .map_err(|e| {
            tee_attestation_error(format!("RSA-OAEP decryption of CEK failed: {e}"))
        })?;

    debug!(
        cek_len = cek.len(),
        oid_hex = %hex::encode(&fields.content_encryption_oid),
        iv_hex = %hex::encode(&fields.iv),
        ciphertext_len = fields.ciphertext.len(),
        encrypted_key_len = fields.encrypted_key.len(),
        "CMS envelope fields extracted"
    );

    if cek.len() != 32 {
        return Err(tee_attestation_error(format!(
            "unexpected CEK length: {} (expected 32 for AES-256)",
            cek.len()
        )));
    }

    // KMS uses AES-256-CBC for CMS CiphertextForRecipient content encryption.
    // OID 2.16.840.1.101.3.4.1.42 = AES-256-CBC
    // OID 2.16.840.1.101.3.4.1.46 = AES-256-GCM (also supported)
    let aes_256_cbc_oid: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2a];
    let aes_256_gcm_oid: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2e];

    let plaintext = if fields.content_encryption_oid == aes_256_cbc_oid {
        // AES-256-CBC with PKCS#7 padding
        use cbc::cipher::{BlockDecryptMut, KeyIvInit};
        type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;

        if fields.iv.len() != 16 {
            return Err(tee_attestation_error(format!(
                "AES-256-CBC IV must be 16 bytes, got {}",
                fields.iv.len()
            )));
        }

        let mut buf = fields.ciphertext.clone();
        let decryptor = Aes256CbcDec::new_from_slices(&cek, &fields.iv).map_err(|e| {
            tee_attestation_error(format!("AES-256-CBC init failed: {e}"))
        })?;
        let plaintext = decryptor
            .decrypt_padded_mut::<cbc::cipher::block_padding::Pkcs7>(&mut buf)
            .map_err(|e| {
                tee_attestation_error(format!("AES-256-CBC decryption of CMS content failed: {e}"))
            })?;
        plaintext.to_vec()
    } else if fields.content_encryption_oid == aes_256_gcm_oid {
        // AES-256-GCM
        use aes_gcm::{AesGcm, KeyInit, aead::Aead};
        use aes_gcm::aead::generic_array::GenericArray;

        match fields.iv.len() {
            12 => {
                let cipher = AesGcm::<aes_gcm::aes::Aes256, aes_gcm::aead::consts::U12>::new(
                    GenericArray::from_slice(&cek),
                );
                cipher
                    .decrypt(GenericArray::from_slice(&fields.iv), fields.ciphertext.as_ref())
                    .map_err(|e| {
                        tee_attestation_error(format!("AES-GCM decryption failed: {e}"))
                    })?
            }
            16 => {
                let cipher = AesGcm::<aes_gcm::aes::Aes256, aes_gcm::aead::consts::U16>::new(
                    GenericArray::from_slice(&cek),
                );
                cipher
                    .decrypt(GenericArray::from_slice(&fields.iv), fields.ciphertext.as_ref())
                    .map_err(|e| {
                        tee_attestation_error(format!("AES-GCM decryption failed: {e}"))
                    })?
            }
            n => {
                return Err(tee_attestation_error(format!(
                    "unsupported GCM nonce length: {n}"
                )));
            }
        }
    } else {
        return Err(tee_attestation_error(format!(
            "unsupported content encryption algorithm OID: {}",
            hex::encode(&fields.content_encryption_oid)
        )));
    };

    debug!(plaintext_len = plaintext.len(), "CMS envelope decrypted successfully");
    Ok(plaintext)
}

/// Minimal DER parser for the CMS EnvelopedData structure from KMS.
///
/// Parses just enough ASN.1 to extract the encrypted CEK, AES-GCM nonce,
/// and ciphertext. No external DER/ASN.1 crate needed — the structure
/// from KMS is predictable and constrained.
mod cms_der {
    use crate::error::{AppError, tee_attestation_error};

    /// Parsed fields from a CMS EnvelopedData needed for decryption.
    pub(super) struct CmsFields {
        pub encrypted_key: Vec<u8>,
        /// Algorithm OID bytes (e.g., AES-256-CBC or AES-256-GCM).
        pub content_encryption_oid: Vec<u8>,
        /// IV (for CBC) or nonce (for GCM).
        pub iv: Vec<u8>,
        pub ciphertext: Vec<u8>,
    }

    /// Parse a CMS ContentInfo → EnvelopedData and extract the three fields needed
    /// for decryption.
    ///
    /// ASN.1 structure (simplified):
    /// ```text
    /// ContentInfo ::= SEQUENCE {
    ///   contentType  OID (envelopedData)
    ///   content      [0] EXPLICIT EnvelopedData
    /// }
    /// EnvelopedData ::= SEQUENCE {
    ///   version          INTEGER
    ///   recipientInfos   SET { KeyTransRecipientInfo SEQUENCE {
    ///     version          INTEGER
    ///     rid              RecipientIdentifier
    ///     keyEncAlg        AlgorithmIdentifier
    ///     encryptedKey     OCTET STRING
    ///   }}
    ///   encryptedContentInfo SEQUENCE {
    ///     contentType      OID
    ///     contentEncAlg    SEQUENCE { OID, SEQUENCE { nonce OCTET STRING, ... } }
    ///     encryptedContent [0] IMPLICIT OCTET STRING
    ///   }
    /// }
    /// ```
    pub(super) fn parse_enveloped_data(data: &[u8]) -> Result<CmsFields, AppError> {
        let mut pos = 0;

        // ContentInfo SEQUENCE
        let (_, ci_body) = read_tlv(data, &mut pos, "ContentInfo")?;

        let mut ci_pos = 0;
        // contentType OID — skip
        let _ = read_tlv(ci_body, &mut ci_pos, "contentType OID")?;
        // content [0] EXPLICIT
        let (_, ctx0_body) = read_tlv(ci_body, &mut ci_pos, "[0] content")?;

        // EnvelopedData SEQUENCE
        let mut env_pos = 0;
        let (_, env_body) = read_tlv(ctx0_body, &mut env_pos, "EnvelopedData")?;

        let mut ed_pos = 0;
        // version INTEGER — skip
        let _ = read_tlv(env_body, &mut ed_pos, "EnvelopedData version")?;
        // recipientInfos SET
        let (_, ri_set) = read_tlv(env_body, &mut ed_pos, "recipientInfos SET")?;
        // encryptedContentInfo SEQUENCE
        let (_, eci_body) = read_tlv(env_body, &mut ed_pos, "encryptedContentInfo")?;

        // Parse KeyTransRecipientInfo (first element in SET)
        let encrypted_key = parse_key_trans_ri(ri_set)?;

        // Parse EncryptedContentInfo
        let (oid, iv, ciphertext) = parse_encrypted_content_info(eci_body)?;

        Ok(CmsFields {
            encrypted_key,
            content_encryption_oid: oid,
            iv,
            ciphertext,
        })
    }

    fn parse_key_trans_ri(set_data: &[u8]) -> Result<Vec<u8>, AppError> {
        let mut pos = 0;
        // KeyTransRecipientInfo SEQUENCE
        let (_, ktri_body) = read_tlv(set_data, &mut pos, "KeyTransRI")?;

        let mut kp = 0;
        // version INTEGER — skip
        let _ = read_tlv(ktri_body, &mut kp, "KeyTransRI version")?;
        // rid (RecipientIdentifier) — skip
        let _ = read_tlv(ktri_body, &mut kp, "KeyTransRI rid")?;
        // keyEncryptionAlgorithm — skip
        let _ = read_tlv(ktri_body, &mut kp, "KeyTransRI keyEncAlg")?;
        // encryptedKey OCTET STRING
        let (_, ek_value) = read_tlv(ktri_body, &mut kp, "encryptedKey")?;

        Ok(ek_value.to_vec())
    }

    /// Returns (algorithm_oid, iv_or_nonce, ciphertext).
    fn parse_encrypted_content_info(
        eci_data: &[u8],
    ) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), AppError> {
        let mut pos = 0;
        // contentType OID — skip
        let _ = read_tlv(eci_data, &mut pos, "ECI contentType")?;
        // contentEncryptionAlgorithm SEQUENCE
        let (_, alg_body) = read_tlv(eci_data, &mut pos, "ECI algorithm")?;

        // encryptedContent [0] IMPLICIT OCTET STRING
        //
        // This is raw ciphertext, not structured ASN.1. If it uses BER
        // indefinite-length (tag 0xA0, length 0x80), the generic read_tlv
        // would try to walk TLV children inside raw bytes and fail.
        //
        // Handle it directly: read the tag+length, and for indefinite-length
        // take all remaining data (stripping trailing EOC if present).
        if pos >= eci_data.len() {
            return Err(tee_attestation_error(
                "CMS: missing encryptedContent in EncryptedContentInfo",
            ));
        }
        let _tag = eci_data[pos];
        pos += 1;

        if pos >= eci_data.len() {
            return Err(tee_attestation_error("CMS: truncated encryptedContent length"));
        }
        let first_len = eci_data[pos];
        pos += 1;

        let ct_value = if first_len < 0x80 {
            let len = first_len as usize;
            &eci_data[pos..pos + len]
        } else if first_len == 0x80 {
            // Indefinite length on raw octets — take everything remaining,
            // strip trailing 0x00 0x00 EOC if present.
            let remaining = &eci_data[pos..];
            if remaining.len() >= 2
                && remaining[remaining.len() - 2] == 0x00
                && remaining[remaining.len() - 1] == 0x00
            {
                &remaining[..remaining.len() - 2]
            } else {
                remaining
            }
        } else {
            let num_bytes = (first_len & 0x7F) as usize;
            let mut len = 0usize;
            for i in 0..num_bytes {
                len = (len << 8) | (eci_data[pos + i] as usize);
            }
            pos += num_bytes;
            &eci_data[pos..pos + len]
        };

        // Parse algorithm to get the OID and IV/nonce
        let (oid, iv) = parse_content_encryption_params(alg_body)?;

        // The ciphertext may be wrapped in an inner OCTET STRING if KMS used
        // EXPLICIT tagging on [0] instead of IMPLICIT. Unwrap if present.
        let ciphertext = if ct_value.len() > 2 && ct_value[0] == 0x04 {
            let mut inner_pos = 0;
            let (_, inner) = read_tlv(ct_value, &mut inner_pos, "inner encryptedContent")?;
            inner.to_vec()
        } else {
            ct_value.to_vec()
        };

        Ok((oid, iv, ciphertext))
    }

    /// Parse the AlgorithmIdentifier to extract the OID and IV/nonce.
    /// Returns (algorithm_oid_bytes, iv_or_nonce).
    fn parse_content_encryption_params(alg_data: &[u8]) -> Result<(Vec<u8>, Vec<u8>), AppError> {
        let mut pos = 0;
        // algorithm OID
        let (_, oid_bytes) = read_tlv(alg_data, &mut pos, "algorithm OID")?;
        // parameters: OCTET STRING (CBC IV) or SEQUENCE (GCM params)
        let (param_tag, params_body) = read_tlv(alg_data, &mut pos, "algorithm parameters")?;

        let iv = if param_tag == 0x04 {
            // OCTET STRING — direct IV (CBC) or bare nonce (some GCM encodings)
            params_body.to_vec()
        } else {
            // SEQUENCE wrapper (GCMParameters): first child is nonce OCTET STRING
            let mut pp = 0;
            let (_, nonce_value) = read_tlv(params_body, &mut pp, "GCM nonce")?;
            nonce_value.to_vec()
        };

        Ok((oid_bytes.to_vec(), iv))
    }

    /// Read a BER/DER TLV (tag-length-value) at the given position.
    ///
    /// Returns (tag_byte, value_bytes) and advances `pos` past the TLV.
    /// Handles both definite-length (DER) and indefinite-length (BER)
    /// encoding — KMS CiphertextForRecipient uses BER with indefinite
    /// length on multiple constructed elements.
    fn read_tlv<'a>(
        data: &'a [u8],
        pos: &mut usize,
        context: &str,
    ) -> Result<(u8, &'a [u8]), AppError> {
        if *pos >= data.len() {
            return Err(tee_attestation_error(format!(
                "CMS: unexpected end of data reading {context}"
            )));
        }

        let tag = data[*pos];
        *pos += 1;

        // Read length
        if *pos >= data.len() {
            return Err(tee_attestation_error(format!(
                "CMS: truncated length for {context}"
            )));
        }

        let first_len = data[*pos];
        *pos += 1;

        let len: usize = if first_len < 0x80 {
            // Short form: length in single byte
            first_len as usize
        } else if first_len == 0x80 {
            // BER indefinite length: content ends at a matching EOC (0x00 0x00).
            // Walk through child TLVs to find it (0x00 0x00 can appear inside
            // primitive values like ciphertext, so we can't just scan for it).
            let content_start = *pos;
            while *pos + 1 < data.len() {
                // Check for EOC marker
                if data[*pos] == 0x00 && data[*pos + 1] == 0x00 {
                    let value = &data[content_start..*pos];
                    *pos += 2; // skip EOC
                    return Ok((tag, value));
                }
                // Skip one child TLV
                skip_ber_tlv(data, pos).map_err(|_| {
                    tee_attestation_error(format!(
                        "CMS: malformed BER child element inside {context}"
                    ))
                })?;
            }
            return Err(tee_attestation_error(format!(
                "CMS: no EOC marker found for indefinite-length {context}"
            )));
        } else {
            // Long form: first_len & 0x7F = number of length bytes
            let num_bytes = (first_len & 0x7F) as usize;
            if *pos + num_bytes > data.len() {
                return Err(tee_attestation_error(format!(
                    "CMS: truncated length bytes for {context}"
                )));
            }
            let mut len: usize = 0;
            for i in 0..num_bytes {
                len = (len << 8) | (data[*pos + i] as usize);
            }
            *pos += num_bytes;
            len
        };

        if *pos + len > data.len() {
            return Err(tee_attestation_error(format!(
                "CMS: value overflows buffer for {context} (need {len} bytes at offset {pos}, have {})",
                data.len()
            )));
        }

        let value = &data[*pos..*pos + len];
        *pos += len;

        Ok((tag, value))
    }

    /// Skip one complete BER/DER TLV element, advancing `pos` past it.
    /// Handles indefinite-length by recursively skipping child elements.
    fn skip_ber_tlv(data: &[u8], pos: &mut usize) -> Result<(), ()> {
        if *pos + 1 >= data.len() {
            return Err(());
        }

        // Skip tag
        *pos += 1;

        // Read length
        let first_len = data[*pos];
        *pos += 1;

        if first_len < 0x80 {
            // Definite short form
            let len = first_len as usize;
            if *pos + len > data.len() {
                return Err(());
            }
            *pos += len;
        } else if first_len == 0x80 {
            // Indefinite length — skip children until EOC
            while *pos + 1 < data.len() {
                if data[*pos] == 0x00 && data[*pos + 1] == 0x00 {
                    *pos += 2; // skip EOC
                    return Ok(());
                }
                skip_ber_tlv(data, pos)?;
            }
            return Err(());
        } else {
            // Definite long form
            let num_bytes = (first_len & 0x7F) as usize;
            if *pos + num_bytes > data.len() {
                return Err(());
            }
            let mut len: usize = 0;
            for i in 0..num_bytes {
                len = (len << 8) | (data[*pos + i] as usize);
            }
            *pos += num_bytes;
            if *pos + len > data.len() {
                return Err(());
            }
            *pos += len;
        }

        Ok(())
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn test_read_tlv_short_form() {
            // OCTET STRING, length 3, value [0x01, 0x02, 0x03]
            let data = [0x04, 0x03, 0x01, 0x02, 0x03];
            let mut pos = 0;
            let (tag, value) = read_tlv(&data, &mut pos, "test").unwrap();
            assert_eq!(tag, 0x04);
            assert_eq!(value, &[0x01, 0x02, 0x03]);
            assert_eq!(pos, 5);
        }

        #[test]
        fn test_read_tlv_long_form() {
            // OCTET STRING, length 128 (0x81 0x80), then 128 bytes of 0xAA
            let mut data = vec![0x04, 0x81, 0x80];
            data.extend_from_slice(&[0xAA; 128]);
            let mut pos = 0;
            let (tag, value) = read_tlv(&data, &mut pos, "test").unwrap();
            assert_eq!(tag, 0x04);
            assert_eq!(value.len(), 128);
            assert_eq!(pos, 131);
        }

        #[test]
        fn test_read_tlv_truncated() {
            let data = [0x04, 0x05, 0x01]; // claims 5 bytes but only 1
            let mut pos = 0;
            assert!(read_tlv(&data, &mut pos, "test").is_err());
        }
    }
}

/// Classify KMS errors for operator diagnostics.
fn classify_kms_error<E: std::error::Error>(operation: &str, err: E) -> AppError {
    // Build the full error chain string so classification catches nested causes
    // (the AWS SDK wraps the actual error type several layers deep).
    let mut full_msg = format!("{err}");
    let mut source = std::error::Error::source(&err);
    while let Some(cause) = source {
        full_msg.push_str(&format!("\n  caused by: {cause}"));
        source = cause.source();
    }

    // Classify by error message patterns for clear operator guidance
    let classification = if full_msg.contains("AccessDeniedException") {
        "ACCESS_DENIED — check KMS key policy allows this action and PCR conditions match"
    } else if full_msg.contains("NotFoundException") || full_msg.contains("not found") {
        "KEY_NOT_FOUND — verify the KMS key ARN in config.toml"
    } else if full_msg.contains("InvalidCiphertextException") {
        "INVALID_CIPHERTEXT — ciphertext may be corrupt or encrypted with a different key"
    } else if full_msg.contains("KMSInternalException") {
        "KMS_INTERNAL — transient AWS error, retry may help"
    } else if full_msg.contains("connect") || full_msg.contains("timeout") {
        "NETWORK — cannot reach KMS endpoint, check vsock proxy and allowlist"
    } else {
        "UNKNOWN"
    };

    let msg = format!("KMS {operation} failed [{classification}]: {full_msg}");

    error!(operation, classification, "KMS error");
    tee_attestation_error(msg)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a synthetic CMS EnvelopedData that mimics what KMS returns
    /// with CiphertextForRecipient. This allows us to test the full
    /// decrypt_cms_envelope round-trip without needing real KMS or NSM.
    #[test]
    fn test_cms_envelope_roundtrip() {
        use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
        use aes_gcm::aead::generic_array::GenericArray;
        use rsa::{RsaPrivateKey, Oaep};
        use rsa::pkcs8::EncodePublicKey;

        // Generate RSA keypair (the "ephemeral" key the enclave would create)
        let mut rng = rsa::rand_core::OsRng;
        let private_key = RsaPrivateKey::new(&mut rng, 2048).unwrap();

        // The plaintext KMS would return (e.g., a 32-byte seed)
        let original_plaintext = b"this is a secret seed value!!!!!"; // 32 bytes

        // Generate random AES-256 CEK and GCM nonce
        let mut cek = [0u8; 32];
        rand::fill(&mut cek);
        let mut nonce_bytes = [0u8; 12];
        rand::fill(&mut nonce_bytes);

        // AES-GCM encrypt the plaintext
        let cipher = Aes256Gcm::new(GenericArray::from_slice(&cek));
        let nonce = GenericArray::from_slice(&nonce_bytes);
        let aes_ciphertext = cipher.encrypt(nonce, original_plaintext.as_ref()).unwrap();

        // RSA-OAEP-SHA256 encrypt the CEK
        let encrypted_cek = private_key
            .to_public_key()
            .encrypt(&mut rng, Oaep::new::<sha2::Sha256>(), &cek)
            .unwrap();

        // Build the CMS EnvelopedData DER structure
        let cms_bytes = build_test_cms_envelope(&encrypted_cek, &nonce_bytes, &aes_ciphertext);

        // Now decrypt it using our implementation
        let recovered = decrypt_cms_envelope(&cms_bytes, &private_key).unwrap();

        assert_eq!(recovered, original_plaintext);
    }

    /// Construct a minimal CMS ContentInfo/EnvelopedData DER structure.
    fn build_test_cms_envelope(
        encrypted_cek: &[u8],
        nonce: &[u8],
        aes_ciphertext: &[u8],
    ) -> Vec<u8> {
        // OID for envelopedData: 1.2.840.113549.1.7.3
        let enveloped_data_oid = &[
            0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x03,
        ];

        // OID for data: 1.2.840.113549.1.7.1
        let data_oid = &[
            0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01,
        ];

        // OID for AES-256-GCM: 2.16.840.1.101.3.4.1.46
        let aes_256_gcm_oid = &[
            0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2E,
        ];

        // OID for RSAES-OAEP: 1.2.840.113549.1.1.7
        let rsaes_oaep_oid = &[
            0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x07,
        ];

        // GCMParameters SEQUENCE { nonce OCTET STRING }
        let nonce_tlv = der_octet_string(nonce);
        let gcm_params = der_sequence(&nonce_tlv);

        // AlgorithmIdentifier SEQUENCE { OID, GCMParameters }
        let mut alg_id_content = Vec::new();
        alg_id_content.extend_from_slice(aes_256_gcm_oid);
        alg_id_content.extend_from_slice(&gcm_params);
        let alg_id = der_sequence(&alg_id_content);

        // encryptedContent [0] IMPLICIT OCTET STRING
        let encrypted_content = der_context_implicit(0, aes_ciphertext);

        // EncryptedContentInfo SEQUENCE
        let mut eci_content = Vec::new();
        eci_content.extend_from_slice(data_oid);
        eci_content.extend_from_slice(&alg_id);
        eci_content.extend_from_slice(&encrypted_content);
        let eci = der_sequence(&eci_content);

        // Fake RecipientIdentifier (IssuerAndSerialNumber — minimal)
        let fake_rid = der_sequence(&[0x30, 0x00, 0x02, 0x01, 0x01]); // SEQUENCE{SEQUENCE{}, INTEGER 1}

        // KeyEncryptionAlgorithm (RSAES-OAEP — simplified, just OID)
        let key_enc_alg = der_sequence(rsaes_oaep_oid);

        // KeyTransRecipientInfo SEQUENCE
        let mut ktri_content = Vec::new();
        ktri_content.extend_from_slice(&[0x02, 0x01, 0x00]); // version INTEGER 0
        ktri_content.extend_from_slice(&fake_rid);
        ktri_content.extend_from_slice(&key_enc_alg);
        ktri_content.extend_from_slice(&der_octet_string(encrypted_cek));
        let ktri = der_sequence(&ktri_content);

        // RecipientInfos SET
        let ri_set = der_set(&ktri);

        // EnvelopedData SEQUENCE
        let mut env_content = Vec::new();
        env_content.extend_from_slice(&[0x02, 0x01, 0x00]); // version INTEGER 0
        env_content.extend_from_slice(&ri_set);
        env_content.extend_from_slice(&eci);
        let enveloped_data = der_sequence(&env_content);

        // [0] EXPLICIT EnvelopedData
        let ctx0 = der_context_explicit(0, &enveloped_data);

        // ContentInfo SEQUENCE
        let mut ci_content = Vec::new();
        ci_content.extend_from_slice(enveloped_data_oid);
        ci_content.extend_from_slice(&ctx0);
        der_sequence(&ci_content)
    }

    fn der_sequence(content: &[u8]) -> Vec<u8> {
        der_tlv(0x30, content)
    }

    fn der_set(content: &[u8]) -> Vec<u8> {
        der_tlv(0x31, content)
    }

    fn der_octet_string(content: &[u8]) -> Vec<u8> {
        der_tlv(0x04, content)
    }

    fn der_context_explicit(tag_num: u8, content: &[u8]) -> Vec<u8> {
        der_tlv(0xA0 | tag_num, content) // constructed context-specific
    }

    fn der_context_implicit(tag_num: u8, content: &[u8]) -> Vec<u8> {
        der_tlv(0x80 | tag_num, content) // primitive context-specific
    }

    fn der_tlv(tag: u8, content: &[u8]) -> Vec<u8> {
        let mut buf = vec![tag];
        let len = content.len();
        if len < 0x80 {
            buf.push(len as u8);
        } else if len < 0x100 {
            buf.push(0x81);
            buf.push(len as u8);
        } else if len < 0x10000 {
            buf.push(0x82);
            buf.push((len >> 8) as u8);
            buf.push(len as u8);
        } else {
            buf.push(0x83);
            buf.push((len >> 16) as u8);
            buf.push((len >> 8) as u8);
            buf.push(len as u8);
        }
        buf.extend_from_slice(content);
        buf
    }

    #[test]
    fn test_derive_storage_key_deterministic() {
        let seed = [0x42u8; 32];
        let key1 = derive_storage_key(&seed, "test-salt");
        let key2 = derive_storage_key(&seed, "test-salt");
        assert_eq!(key1, key2, "same seed + salt must produce same key");
    }

    #[test]
    fn test_derive_storage_key_different_salts() {
        let seed = [0x42u8; 32];
        let key1 = derive_storage_key(&seed, "salt-a");
        let key2 = derive_storage_key(&seed, "salt-b");
        assert_ne!(key1, key2, "different salts must produce different keys");
    }

    #[test]
    fn test_derive_storage_key_different_seeds() {
        let key1 = derive_storage_key(&[0x01u8; 32], "same-salt");
        let key2 = derive_storage_key(&[0x02u8; 32], "same-salt");
        assert_ne!(key1, key2, "different seeds must produce different keys");
    }

    #[test]
    fn test_jwt_fingerprint_deterministic() {
        let key = [0xABu8; 32];
        let fp1 = jwt_fingerprint(&key);
        let fp2 = jwt_fingerprint(&key);
        assert_eq!(fp1, fp2);
        assert_eq!(fp1.len(), 32); // 16 bytes = 32 hex chars
    }
}