venice-e2ee-proxy 0.1.3

OpenAI-compatible proxy for Venice.ai E2EE models
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
1314
1315
1316
1317
1318
1319
1320
1321
1322
//! Attestation fetch, verification policy, and fail-closed checks.
//!
//! This module intentionally does not cache attestation results internally.
//! Attestation/model-key state is tied to the session lifetime, so callers should
//! store a successful [`VerifiedAttestation`] in the session manager only for
//! that session's TTL/request budget. Calling
//! [`AttestationVerifier::verify_model_attestation`] always generates a fresh
//! nonce and fetches fresh Venice evidence.
//!
//! v0.1 deliberately does not implement measurement allowlists for TDX RTMR/MRTD
//! or NVIDIA claims. It verifies the basic Venice attestation envelope, performs
//! local key/address validation, enforces debug-mode policy where evidence exposes
//! it, and exposes strict fail-closed gates for required TDX/NRAS verification.
//! Full DCAP/QVL and NRAS cryptographic verification is not linked; when those
//! verifiers are required by policy, verification fails closed with
//! [`AttestationError::ExternalVerifierUnavailable`].

use std::{fmt, time::SystemTime};

use k256::{PublicKey, elliptic_curve::sec1::ToEncodedPoint};
use rand_core::{OsRng, RngCore};
use serde::Deserialize;
use serde_json::Value;
use sha2::{Digest as Sha2Digest, Sha256};
use sha3::Keccak256;
use thiserror::Error;

use crate::{
    config::{AttestationConfig, NvidiaRequirement, ProxyConfig},
    venice::{VeniceClient, VeniceClientError},
};

const ATTESTATION_NONCE_BYTES: usize = 32;
const ATTESTATION_NONCE_HEX_CHARS: usize = ATTESTATION_NONCE_BYTES * 2;
const TDX_TEE_TYPE: u32 = 0x81;
const TDX_QUOTE_HEADER_LEN: usize = 48;
const TDX_QUOTE_TEE_TYPE_OFFSET: usize = 4;
const TDX_QUOTE_TEE_TYPE_END: usize = TDX_QUOTE_TEE_TYPE_OFFSET + 4;
const TDX_REPORT_BODY_OFFSET: usize = TDX_QUOTE_HEADER_LEN;
const TDX_REPORT_TD_ATTRIBUTES_OFFSET: usize = TDX_REPORT_BODY_OFFSET + 120;
const TDX_REPORT_TD_ATTRIBUTES_END: usize = TDX_REPORT_TD_ATTRIBUTES_OFFSET + 8;
const TDX_REPORT_DATA_OFFSET: usize = TDX_REPORT_BODY_OFFSET + 520;
const TDX_REPORT_DATA_LEN: usize = 64;
const TDX_REPORT_DATA_END: usize = TDX_REPORT_DATA_OFFSET + TDX_REPORT_DATA_LEN;

/// Verifies Venice model attestation evidence according to the configured policy.
#[derive(Clone, Debug)]
pub struct AttestationVerifier {
    policy: AttestationConfig,
    venice_client: VeniceClient,
}

/// Fresh random nonce sent to Venice and checked against attestation evidence.
#[derive(Clone, PartialEq, Eq)]
pub struct AttestationNonce(String);

/// Successful attestation result cached with a session and exposed through proxy metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedAttestation {
    pub model_id: String,
    pub model_public_key: String,
    pub signing_address: Option<String>,
    pub tee_provider: Option<String>,
    pub debug: Option<bool>,
    pub tdx: TdxVerificationSummary,
    pub nvidia: NvidiaVerificationSummary,
    pub verified_at: SystemTime,
}

/// Summary of TDX evidence presence, local checks, and debug status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TdxVerificationSummary {
    pub present: bool,
    pub verified: bool,
    pub debug: Option<bool>,
    pub tee_type: Option<u32>,
}

/// Summary of NVIDIA attestation evidence presence and verification status.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NvidiaVerificationSummary {
    pub present: bool,
    pub verified: NvidiaVerificationStatus,
}

/// Verification status for NVIDIA attestation evidence under the configured policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NvidiaVerificationStatus {
    NotPresent,
    IgnoredByPolicy,
    PresentVerifierUnavailable,
}

/// Errors returned while fetching or validating attestation evidence.
#[derive(Debug, Error)]
pub enum AttestationError {
    #[error("invalid attestation request: {message}")]
    InvalidRequest { message: String },
    #[error("TEE attestation fetch failed: {0}")]
    Fetch(#[from] VeniceClientError),
    #[error("TEE attestation response is malformed: {message}")]
    MalformedResponse { message: String },
    #[error("TEE attestation evidence is missing required field {field}")]
    MissingField { field: &'static str },
    #[error("TEE attestation verification failed: {message}")]
    PolicyViolation {
        code: AttestationFailureCode,
        message: String,
    },
    #[error("TEE attestation verifier unavailable: {message}")]
    ExternalVerifierUnavailable {
        verifier: &'static str,
        message: String,
    },
}

/// Stable failure codes for attestation policy violations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttestationFailureCode {
    UpstreamNotVerified,
    NonceMismatch,
    ModelMismatch,
    InvalidSigningKey,
    SigningAddressMismatch,
    DebugModeDetected,
    MissingTdxEvidence,
    InvalidTdxEvidence,
    MissingNvidiaEvidence,
    InvalidNvidiaEvidence,
}

/// TDX quote fields used by local policy checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ParsedTdxQuote {
    tee_type: u32,
    debug: bool,
}

/// Typed Venice ACI attestation response used by the production E2EE endpoint.
#[derive(Debug, Clone, Deserialize)]
struct VeniceAttestationResponse {
    attestation: AciAttestationEnvelope,
    #[serde(flatten)]
    fields: VeniceAttestationFields,
}

/// Root Venice attestation fields containing verification decision and model key binding.
#[derive(Debug, Clone, Default, Deserialize)]
struct VeniceAttestationFields {
    #[serde(default)]
    verified: Option<bool>,
    #[serde(default)]
    nonce: Option<String>,
    #[serde(default)]
    model: Option<String>,
    #[serde(default)]
    tee_provider: Option<String>,
    #[serde(default)]
    signing_public_key: Option<String>,
    #[serde(default)]
    signing_address: Option<String>,
    #[serde(default)]
    debug: Option<bool>,
    #[serde(default)]
    nvidia_payload: Option<Value>,
}

/// ACI nested attestation object containing hardware evidence.
#[derive(Debug, Clone, Deserialize)]
struct AciAttestationEnvelope {
    #[serde(default)]
    evidence: AciEvidenceFields,
}

/// ACI nested hardware evidence fields used by the local verifier.
#[derive(Debug, Clone, Default, Deserialize)]
struct AciEvidenceFields {
    #[serde(default)]
    quote: Option<String>,
    #[serde(default)]
    quote_report_data: Option<String>,
}

impl AttestationVerifier {
    /// Builds a verifier from proxy configuration and the Venice client used to fetch evidence.
    pub fn from_config(config: &ProxyConfig, venice_client: VeniceClient) -> Self {
        Self::new(config.attestation.clone(), venice_client)
    }

    /// Builds a verifier from an attestation policy and Venice client.
    pub fn new(policy: AttestationConfig, venice_client: VeniceClient) -> Self {
        Self {
            policy,
            venice_client,
        }
    }

    /// Returns the attestation policy used by this verifier.
    pub fn policy(&self) -> &AttestationConfig {
        &self.policy
    }

    /// Fetches Venice attestation evidence with a fresh nonce and verifies it
    /// according to the configured fail-closed policy.
    pub async fn verify_model_attestation(
        &self,
        model_id: &str,
    ) -> Result<VerifiedAttestation, AttestationError> {
        if model_id.trim().is_empty() {
            return Err(AttestationError::InvalidRequest {
                message: "model id must not be empty".to_owned(),
            });
        }

        let nonce = AttestationNonce::generate();
        let evidence = self
            .venice_client
            .fetch_attestation_evidence(model_id, nonce.as_str())
            .await
            .map_err(AttestationError::Fetch)?;

        self.verify_evidence(model_id, nonce.as_str(), evidence)
    }

    /// Verifies already-fetched evidence for a requested model and nonce.
    pub fn verify_evidence(
        &self,
        requested_model_id: &str,
        client_nonce: &str,
        upstream_response: Value,
    ) -> Result<VerifiedAttestation, AttestationError> {
        verify_attestation_evidence(
            &self.policy,
            requested_model_id,
            client_nonce,
            upstream_response,
        )
    }
}

impl AttestationNonce {
    /// Generates a 32-byte nonce encoded as lowercase hex.
    pub fn generate() -> Self {
        let mut bytes = [0_u8; ATTESTATION_NONCE_BYTES];
        OsRng.fill_bytes(&mut bytes);
        Self(hex::encode(bytes))
    }

    /// Returns the nonce as a hex string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for AttestationNonce {
    /// Formats the nonce for diagnostics.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("AttestationNonce").field(&self.0).finish()
    }
}

impl TdxVerificationSummary {
    /// Returns a summary representing absent TDX evidence.
    fn not_present() -> Self {
        Self {
            present: false,
            verified: false,
            debug: None,
            tee_type: None,
        }
    }
}

impl NvidiaVerificationSummary {
    /// Returns a summary representing absent NVIDIA evidence.
    fn not_present() -> Self {
        Self {
            present: false,
            verified: NvidiaVerificationStatus::NotPresent,
        }
    }
}

impl NvidiaVerificationStatus {
    /// Returns the metadata header value for this NVIDIA verification status.
    pub fn as_header_value(self) -> &'static str {
        match self {
            Self::NotPresent => "not-present",
            Self::IgnoredByPolicy => "ignored",
            Self::PresentVerifierUnavailable => "verifier-unavailable",
        }
    }
}

impl AttestationError {
    /// Returns the OpenAI-compatible error type exposed for this attestation error.
    pub fn api_error_type(&self) -> &'static str {
        match self {
            Self::InvalidRequest { .. } => "invalid_request_error",
            Self::ExternalVerifierUnavailable { .. } => "proxy_attestation_verifier_unavailable",
            Self::Fetch(_)
            | Self::MalformedResponse { .. }
            | Self::MissingField { .. }
            | Self::PolicyViolation { .. } => "proxy_attestation_error",
        }
    }

    /// Returns the proxy error code exposed for this attestation error.
    pub fn api_error_code(&self) -> &'static str {
        match self {
            Self::InvalidRequest { .. } => "invalid_attestation_request",
            Self::Fetch(_) => "attestation_fetch_failed",
            Self::MalformedResponse { .. } => "attestation_malformed_response",
            Self::MissingField { .. } => "attestation_missing_required_field",
            Self::PolicyViolation { code, .. } => code.as_str(),
            Self::ExternalVerifierUnavailable { .. } => "attestation_verifier_unavailable",
        }
    }

    /// Returns whether the error indicates a required external attestation verifier is unavailable.
    pub fn verifier_unavailable(&self) -> bool {
        matches!(self, Self::ExternalVerifierUnavailable { .. })
    }
}

impl AttestationFailureCode {
    /// Returns the stable string form used in proxy error responses.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::UpstreamNotVerified => "attestation_upstream_not_verified",
            Self::NonceMismatch => "attestation_nonce_mismatch",
            Self::ModelMismatch => "attestation_model_mismatch",
            Self::InvalidSigningKey => "attestation_invalid_signing_key",
            Self::SigningAddressMismatch => "attestation_signing_address_mismatch",
            Self::DebugModeDetected => "attestation_debug_mode_detected",
            Self::MissingTdxEvidence => "attestation_missing_tdx_evidence",
            Self::InvalidTdxEvidence => "attestation_invalid_tdx_evidence",
            Self::MissingNvidiaEvidence => "attestation_missing_nvidia_evidence",
            Self::InvalidNvidiaEvidence => "attestation_invalid_nvidia_evidence",
        }
    }
}

impl VeniceAttestationResponse {
    /// Parses the raw Venice payload into the supported attestation response model.
    fn parse(value: Value) -> Result<Self, AttestationError> {
        serde_json::from_value(value).map_err(|source| AttestationError::MalformedResponse {
            message: source.to_string(),
        })
    }

    /// Returns the root fields containing Venice's verification decision and model key binding.
    fn fields(&self) -> &VeniceAttestationFields {
        &self.fields
    }

    /// Returns the TDX quote from ACI hardware evidence.
    fn tdx_quote(&self) -> Option<&str> {
        non_empty(self.attestation.evidence.quote.as_deref())
    }

    /// Returns TDX report data from ACI hardware evidence.
    fn quote_report_data(&self) -> Option<&str> {
        non_empty(self.attestation.evidence.quote_report_data.as_deref())
    }
}

impl VeniceAttestationFields {
    /// Reads Venice's required `verified` decision.
    fn required_verified(&self) -> Result<bool, AttestationError> {
        self.verified
            .ok_or(AttestationError::MissingField { field: "verified" })
    }

    /// Reads a required non-empty string field from this attestation model.
    fn required_string<'a>(
        &'a self,
        field: &'static str,
        value: Option<&'a str>,
    ) -> Result<&'a str, AttestationError> {
        match value {
            Some(value) if !value.trim().is_empty() => Ok(value),
            Some(_) => Err(AttestationError::MalformedResponse {
                message: format!("field {field} must not be empty"),
            }),
            None => Err(AttestationError::MissingField { field }),
        }
    }

    fn nonce(&self) -> Option<&str> {
        self.nonce.as_deref()
    }

    fn model(&self) -> Option<&str> {
        self.model.as_deref()
    }

    fn tee_provider(&self) -> Option<&str> {
        non_empty(self.tee_provider.as_deref())
    }

    fn signing_public_key(&self) -> Option<&str> {
        non_empty(self.signing_public_key.as_deref())
    }

    fn signing_address(&self) -> Option<&str> {
        non_empty(self.signing_address.as_deref())
    }

    fn debug(&self) -> Option<bool> {
        self.debug
    }

    fn nvidia_payload(&self) -> Option<&Value> {
        self.nvidia_payload
            .as_ref()
            .filter(|value| !value.is_null())
    }
}

/// Validates a Venice attestation response against the expected model, nonce, and policy.
fn verify_attestation_evidence(
    policy: &AttestationConfig,
    requested_model_id: &str,
    client_nonce: &str,
    upstream_response: Value,
) -> Result<VerifiedAttestation, AttestationError> {
    validate_nonce_hex(client_nonce)?;

    let response_model = VeniceAttestationResponse::parse(upstream_response)?;
    let evidence = response_model.fields();
    let verified = evidence.required_verified()?;

    if !verified {
        return policy_error(
            AttestationFailureCode::UpstreamNotVerified,
            "Venice did not mark the attestation evidence as verified",
        );
    }

    let nonce = evidence.required_string("nonce", evidence.nonce())?;

    if nonce != client_nonce {
        return policy_error(
            AttestationFailureCode::NonceMismatch,
            "attestation nonce does not match the client nonce; evidence may be stale or replayed",
        );
    }

    let model = evidence.required_string("model", evidence.model())?;

    if model != requested_model_id {
        return policy_error(
            AttestationFailureCode::ModelMismatch,
            format!(
                "attestation model {model:?} does not match requested model {requested_model_id:?}"
            ),
        );
    }

    let signing_key = evidence
        .signing_public_key()
        .ok_or(AttestationError::MissingField {
            field: "signing_public_key",
        })?;
    let normalized_signing_key = normalize_public_key_hex(signing_key)?;
    let derived_address = ethereum_address_from_uncompressed_key_hex(&normalized_signing_key)?;
    let signing_address = evidence
        .signing_address()
        .map(normalize_ethereum_address)
        .transpose()?;

    if let Some(signing_address) = &signing_address
        && signing_address != &derived_address
    {
        return policy_error(
            AttestationFailureCode::SigningAddressMismatch,
            format!(
                "signing_address {signing_address} does not match address {derived_address} derived from signing key"
            ),
        );
    }

    let debug = evidence.debug();

    if debug == Some(true) && !policy.allow_debug {
        return policy_error(
            AttestationFailureCode::DebugModeDetected,
            "attestation evidence reports debug mode and attestation.allow_debug=false",
        );
    }

    let tdx = evaluate_tdx_policy(
        policy,
        &response_model,
        &normalized_signing_key,
        signing_address.as_deref(),
    )?;
    let nvidia = evaluate_nvidia_policy(policy, evidence)?;

    Ok(VerifiedAttestation {
        model_id: requested_model_id.to_owned(),
        model_public_key: normalized_signing_key,
        signing_address,
        tee_provider: evidence.tee_provider().map(ToOwned::to_owned),
        debug,
        tdx,
        nvidia,
        verified_at: SystemTime::now(),
    })
}

/// Evaluates TDX evidence fields against the configured TDX policy.
fn evaluate_tdx_policy(
    policy: &AttestationConfig,
    response: &VeniceAttestationResponse,
    signing_key: &str,
    signing_address: Option<&str>,
) -> Result<TdxVerificationSummary, AttestationError> {
    let Some(tdx_quote) = response.tdx_quote() else {
        return if policy.require_tdx {
            policy_error(
                AttestationFailureCode::MissingTdxEvidence,
                "attestation.require_tdx=true but attestation.evidence.quote is absent",
            )
        } else {
            Ok(TdxVerificationSummary::not_present())
        };
    };

    let parsed = parse_tdx_quote(tdx_quote)?;

    if parsed.tee_type != TDX_TEE_TYPE {
        return policy_error(
            AttestationFailureCode::InvalidTdxEvidence,
            format!(
                "Intel quote teeType 0x{:x} is not TDX teeType 0x{TDX_TEE_TYPE:x}",
                parsed.tee_type
            ),
        );
    }

    if parsed.debug && !policy.allow_debug {
        return policy_error(
            AttestationFailureCode::DebugModeDetected,
            "Intel TDX quote reports debug mode and attestation.allow_debug=false",
        );
    }

    if let Some(reportdata) = response.quote_report_data() {
        verify_reportdata_binding(reportdata, signing_key, signing_address)?;
    }

    if policy.require_tdx {
        let message = if policy.pccs_url.trim().is_empty() {
            "attestation.require_tdx=true requires independent DCAP/QVL quote verification, but no DCAP verifier is linked and attestation.pccs_url is empty".to_owned()
        } else {
            "attestation.require_tdx=true requires independent DCAP/QVL quote verification; PCCS URL is configured but this v0.1 verifier has no DCAP/QVL backend linked".to_owned()
        };

        return Err(AttestationError::ExternalVerifierUnavailable {
            verifier: "tdx-dcap-qvl",
            message,
        });
    }

    Ok(TdxVerificationSummary {
        present: true,
        verified: false,
        debug: Some(parsed.debug),
        tee_type: Some(parsed.tee_type),
    })
}

/// Evaluates NVIDIA evidence fields against the configured NVIDIA policy.
fn evaluate_nvidia_policy(
    policy: &AttestationConfig,
    evidence: &VeniceAttestationFields,
) -> Result<NvidiaVerificationSummary, AttestationError> {
    let nvidia_payload = evidence.nvidia_payload();

    match (policy.require_nvidia, nvidia_payload) {
        (NvidiaRequirement::Required, None) => policy_error(
            AttestationFailureCode::MissingNvidiaEvidence,
            "attestation.require_nvidia=required but nvidia_payload is absent",
        ),
        (NvidiaRequirement::Never, None) => Ok(NvidiaVerificationSummary::not_present()),
        (NvidiaRequirement::Never, Some(_)) => Ok(NvidiaVerificationSummary {
            present: true,
            verified: NvidiaVerificationStatus::IgnoredByPolicy,
        }),
        (_, Some(Value::Object(_))) | (_, Some(Value::String(_))) => {
            Err(AttestationError::ExternalVerifierUnavailable {
                verifier: "nvidia-nras",
                message: "NVIDIA attestation payload is present and policy requires verification, but this v0.1 verifier has no NRAS/local NVIDIA verifier backend linked".to_owned(),
            })
        }
        (_, Some(_)) => policy_error(
            AttestationFailureCode::InvalidNvidiaEvidence,
            "nvidia_payload is present but is not an object or encoded string",
        ),
        (NvidiaRequirement::WhenPresent, None) => Ok(NvidiaVerificationSummary::not_present()),
    }
}

/// Parses a TDX quote string and returns the fields needed by policy evaluation.
fn parse_tdx_quote(value: &str) -> Result<ParsedTdxQuote, AttestationError> {
    let bytes = decode_tdx_quote(value)?;

    if bytes.len() < TDX_REPORT_DATA_END {
        return policy_error(
            AttestationFailureCode::InvalidTdxEvidence,
            format!(
                "Intel TDX quote is too short: got {} bytes, need at least {TDX_REPORT_DATA_END}",
                bytes.len()
            ),
        );
    }

    let tee_type = u32::from_le_bytes(
        bytes[TDX_QUOTE_TEE_TYPE_OFFSET..TDX_QUOTE_TEE_TYPE_END]
            .try_into()
            .expect("TDX tee_type slice length is fixed"),
    );
    let td_attributes = u64::from_le_bytes(
        bytes[TDX_REPORT_TD_ATTRIBUTES_OFFSET..TDX_REPORT_TD_ATTRIBUTES_END]
            .try_into()
            .expect("TDX attributes slice length is fixed"),
    );
    let debug = td_attributes & 1 == 1;

    Ok(ParsedTdxQuote { tee_type, debug })
}

/// Decodes a hex-encoded TDX quote.
fn decode_tdx_quote(value: &str) -> Result<Vec<u8>, AttestationError> {
    let value = value.trim();
    let hex = value.strip_prefix("0x").unwrap_or(value);
    hex::decode(hex).map_err(|source| AttestationError::PolicyViolation {
        code: AttestationFailureCode::InvalidTdxEvidence,
        message: format!("attestation.evidence.quote is not valid hex: {source}"),
    })
}

/// Verifies that TDX report data binds to the attested signing key or signing address.
fn verify_reportdata_binding(
    reportdata_hex: &str,
    signing_key: &str,
    signing_address: Option<&str>,
) -> Result<(), AttestationError> {
    let reportdata =
        hex::decode(reportdata_hex).map_err(|error| AttestationError::PolicyViolation {
            code: AttestationFailureCode::InvalidTdxEvidence,
            message: format!("quote_report_data is not valid hex: {error}"),
        })?;
    if reportdata.len() != TDX_REPORT_DATA_LEN {
        return policy_error(
            AttestationFailureCode::InvalidTdxEvidence,
            format!(
                "quote_report_data has {} bytes, expected {TDX_REPORT_DATA_LEN}",
                reportdata.len()
            ),
        );
    }

    let signing_key_bytes =
        hex::decode(signing_key).map_err(|error| AttestationError::PolicyViolation {
            code: AttestationFailureCode::InvalidSigningKey,
            message: format!("normalized signing key is not valid hex: {error}"),
        })?;
    let signing_key_hash = Sha256::digest(&signing_key_bytes);
    if reportdata.starts_with(&signing_key_hash[..]) {
        return Ok(());
    }

    if let Some(signing_address) = signing_address {
        let signing_address_hash = Sha256::digest(signing_address.as_bytes());
        if reportdata.starts_with(&signing_address_hash[..]) {
            return Ok(());
        }

        let signing_address_hex = signing_address
            .strip_prefix("0x")
            .unwrap_or(signing_address);
        let signing_address_bytes = hex::decode(signing_address_hex).map_err(|error| {
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::SigningAddressMismatch,
                message: format!("normalized signing address is not valid hex: {error}"),
            }
        })?;
        if signing_address_bytes.len() == 20 && reportdata.starts_with(&signing_address_bytes) {
            return Ok(());
        }
    }

    policy_error(
        AttestationFailureCode::InvalidTdxEvidence,
        "TDX REPORTDATA does not bind the attested signing key or signing address",
    )
}

/// Returns a non-empty string slice after trimming-only emptiness checks.
fn non_empty(value: Option<&str>) -> Option<&str> {
    value.filter(|value| !value.trim().is_empty())
}

/// Parses a secp256k1 public key hex string and returns uncompressed SEC1 lowercase hex.
fn normalize_public_key_hex(value: &str) -> Result<String, AttestationError> {
    let value = value.trim().strip_prefix("0x").unwrap_or(value.trim());
    let mut bytes = hex::decode(value).map_err(|error| AttestationError::PolicyViolation {
        code: AttestationFailureCode::InvalidSigningKey,
        message: error.to_string(),
    })?;

    if bytes.len() == 64 {
        let mut uncompressed = Vec::with_capacity(65);
        uncompressed.push(0x04);
        uncompressed.extend_from_slice(&bytes);
        bytes = uncompressed;
    }

    if !matches!(bytes.len(), 33 | 65) {
        return policy_error(
            AttestationFailureCode::InvalidSigningKey,
            format!(
                "signing key must be 33-byte compressed, 64-byte x/y, or 65-byte uncompressed SEC1 public key; got {} bytes",
                bytes.len()
            ),
        );
    }

    let public_key =
        PublicKey::from_sec1_bytes(&bytes).map_err(|_| AttestationError::PolicyViolation {
            code: AttestationFailureCode::InvalidSigningKey,
            message: "signing key is not a valid secp256k1 public key".to_owned(),
        })?;
    Ok(hex::encode(public_key.to_encoded_point(false).as_bytes()))
}

/// Derives the lowercase Ethereum address for an uncompressed secp256k1 public key hex string.
fn ethereum_address_from_uncompressed_key_hex(value: &str) -> Result<String, AttestationError> {
    let bytes = hex::decode(value).map_err(|error| AttestationError::PolicyViolation {
        code: AttestationFailureCode::InvalidSigningKey,
        message: error.to_string(),
    })?;
    if bytes.len() != 65 || bytes.first() != Some(&0x04) {
        return policy_error(
            AttestationFailureCode::InvalidSigningKey,
            "normalized signing key is not an uncompressed 65-byte SEC1 key",
        );
    }

    let hash = Keccak256::digest(&bytes[1..]);
    Ok(format!("0x{}", hex::encode(&hash[12..])))
}

/// Validates an Ethereum address string and returns it in lowercase `0x` form.
fn normalize_ethereum_address(value: &str) -> Result<String, AttestationError> {
    let value = value.trim();
    let stripped = value.strip_prefix("0x").unwrap_or(value);
    if stripped.len() != 40 || stripped.chars().any(|ch| !ch.is_ascii_hexdigit()) {
        return policy_error(
            AttestationFailureCode::SigningAddressMismatch,
            "signing_address must be a 20-byte Ethereum address encoded as hex",
        );
    }
    Ok(format!("0x{}", stripped.to_ascii_lowercase()))
}

/// Validates that a nonce is the expected number of hex characters.
fn validate_nonce_hex(value: &str) -> Result<(), AttestationError> {
    if value.len() != ATTESTATION_NONCE_HEX_CHARS {
        return Err(AttestationError::InvalidRequest {
            message: format!(
                "attestation nonce must be {ATTESTATION_NONCE_HEX_CHARS} hex characters"
            ),
        });
    }
    if value.chars().any(|ch| !ch.is_ascii_hexdigit()) {
        return Err(AttestationError::InvalidRequest {
            message: "attestation nonce must contain only hex characters".to_owned(),
        });
    }
    Ok(())
}

/// Returns an attestation policy-violation error with the supplied code and message.
fn policy_error<T>(
    code: AttestationFailureCode,
    message: impl Into<String>,
) -> Result<T, AttestationError> {
    Err(AttestationError::PolicyViolation {
        code,
        message: message.into(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{collections::HashMap, net::SocketAddr, time::Duration};

    use axum::{
        Router,
        body::Body,
        extract::Query,
        http::{Response, StatusCode},
        response::IntoResponse,
        routing::get,
    };
    use k256::SecretKey;
    use serde_json::json;
    use tokio::net::TcpListener;

    const MODEL: &str = "e2ee-qwen3-5-122b-a10b";
    const NONCE: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

    fn policy_for_basic_success() -> AttestationConfig {
        AttestationConfig {
            require_tdx: false,
            require_nvidia: NvidiaRequirement::WhenPresent,
            ..AttestationConfig::default()
        }
    }

    fn verifier(policy: AttestationConfig) -> AttestationVerifier {
        AttestationVerifier::new(policy, test_venice_client("http://127.0.0.1:1/api/v1"))
    }

    fn test_venice_client(base_url: &str) -> VeniceClient {
        VeniceClient::new(base_url, "test-api-key", Duration::from_secs(1))
            .expect("test Venice client should build")
    }

    fn key_material() -> (String, String) {
        let secret_key = SecretKey::from_slice(&[7_u8; 32]).expect("fixed secret key is valid");
        let public_key = secret_key.public_key();
        let public_key_hex = hex::encode(public_key.to_encoded_point(false).as_bytes());
        let address = ethereum_address_from_uncompressed_key_hex(&public_key_hex)
            .expect("test public key should derive address");
        (public_key_hex, address)
    }

    fn reportdata_for_address(signing_address: &str) -> String {
        let mut reportdata = vec![0_u8; TDX_REPORT_DATA_LEN];
        let address = hex::decode(
            signing_address
                .strip_prefix("0x")
                .expect("test signing address should be normalized"),
        )
        .expect("test signing address should be hex");
        reportdata[..address.len()].copy_from_slice(&address);
        hex::encode(reportdata)
    }

    fn valid_evidence() -> Value {
        let (signing_key, signing_address) = key_material();
        json!({
            "api_version": "aci/1",
            "attestation": {
                "tee_type": "tdx",
                "evidence": {}
            },
            "verified": true,
            "nonce": NONCE,
            "model": MODEL,
            "tee_provider": "phala",
            "debug": false,
            "signing_public_key": signing_key,
            "signing_address": signing_address
        })
    }

    fn set_tdx_quote(evidence: &mut Value, quote: String) {
        evidence["attestation"]["evidence"]["quote"] = json!(quote);
    }

    #[test]
    fn generated_nonce_is_32_bytes_lower_hex() {
        let nonce = AttestationNonce::generate();

        assert_eq!(nonce.as_str().len(), 64);
        assert!(nonce.as_str().chars().all(|ch| ch.is_ascii_hexdigit()));
        assert!(!nonce.as_str().chars().any(|ch| ch.is_ascii_uppercase()));
    }

    #[test]
    fn valid_basic_evidence_passes_without_optional_hardware_requirements() {
        let result = verifier(policy_for_basic_success())
            .verify_evidence(MODEL, NONCE, valid_evidence())
            .expect("valid basic attestation should pass");

        let (expected_key, expected_address) = key_material();
        assert_eq!(result.model_id, MODEL);
        assert_eq!(result.model_public_key, expected_key);
        assert_eq!(
            result.signing_address.as_deref(),
            Some(expected_address.as_str())
        );
        assert_eq!(result.tee_provider.as_deref(), Some("phala"));
        assert!(!result.tdx.present);
        assert_eq!(result.nvidia.verified, NvidiaVerificationStatus::NotPresent);
    }

    #[test]
    fn aci_envelope_uses_root_verification_fields_and_nested_hardware_evidence() {
        let (signing_key, signing_address) = key_material();
        let reportdata = reportdata_for_address(&signing_address);
        let result = verifier(AttestationConfig {
            require_tdx: false,
            require_nvidia: NvidiaRequirement::Never,
            ..AttestationConfig::default()
        })
        .verify_evidence(
            MODEL,
            NONCE,
            json!({
                "api_version": "aci/1",
                "attestation": {
                    "tee_type": "tdx",
                    "evidence": {
                        "quote": tdx_quote_hex(false, TDX_TEE_TYPE),
                        "quote_report_data": reportdata
                    }
                },
                "verified": true,
                "nonce": NONCE,
                "model": MODEL,
                "tee_provider": "phala",
                "signing_public_key": signing_key,
                "signing_address": signing_address,
                "nvidia_payload": {"nonce": NONCE}
            }),
        )
        .expect("ACI attestation envelope should verify from root fields");

        assert_eq!(result.model_id, MODEL);
        assert_eq!(result.model_public_key, key_material().0);
        assert_eq!(result.tee_provider.as_deref(), Some("phala"));
        assert!(result.tdx.present);
        assert_eq!(
            result.nvidia.verified,
            NvidiaVerificationStatus::IgnoredByPolicy
        );
    }

    #[test]
    fn missing_required_fields_fail_closed() {
        let mut evidence = valid_evidence();
        evidence.as_object_mut().unwrap().remove("verified");

        let error = verifier(policy_for_basic_success())
            .verify_evidence(MODEL, NONCE, evidence)
            .expect_err("missing verified field must fail");

        assert!(matches!(
            error,
            AttestationError::MissingField { field: "verified" }
        ));
        assert_eq!(error.api_error_code(), "attestation_missing_required_field");
    }

    #[test]
    fn debug_evidence_fails_when_debug_is_not_allowed() {
        let mut evidence = valid_evidence();
        evidence
            .as_object_mut()
            .unwrap()
            .insert("debug".to_owned(), json!(true));

        let error = verifier(policy_for_basic_success())
            .verify_evidence(MODEL, NONCE, evidence)
            .expect_err("debug attestation must fail");

        assert!(matches!(
            error,
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::DebugModeDetected,
                ..
            }
        ));
    }

    #[test]
    fn tdx_required_mode_fails_on_missing_tdx_evidence() {
        let error = verifier(AttestationConfig {
            require_tdx: true,
            require_nvidia: NvidiaRequirement::Never,
            ..AttestationConfig::default()
        })
        .verify_evidence(MODEL, NONCE, valid_evidence())
        .expect_err("missing required TDX evidence must fail");

        assert!(matches!(
            error,
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::MissingTdxEvidence,
                ..
            }
        ));
    }

    #[test]
    fn tdx_required_mode_fails_on_invalid_tdx_evidence() {
        let mut evidence = valid_evidence();
        set_tdx_quote(&mut evidence, "not quote encoding".to_owned());

        let error = verifier(AttestationConfig {
            require_tdx: true,
            require_nvidia: NvidiaRequirement::Never,
            ..AttestationConfig::default()
        })
        .verify_evidence(MODEL, NONCE, evidence)
        .expect_err("invalid TDX evidence must fail");

        assert!(matches!(
            error,
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::InvalidTdxEvidence,
                ..
            }
        ));
    }

    #[test]
    fn tdx_debug_quote_fails_when_debug_is_not_allowed() {
        let mut evidence = valid_evidence();
        set_tdx_quote(&mut evidence, tdx_quote_hex(true, TDX_TEE_TYPE));

        let error = verifier(AttestationConfig {
            require_tdx: false,
            require_nvidia: NvidiaRequirement::Never,
            allow_debug: false,
            ..AttestationConfig::default()
        })
        .verify_evidence(MODEL, NONCE, evidence)
        .expect_err("debug quote must fail");

        assert!(matches!(
            error,
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::DebugModeDetected,
                ..
            }
        ));
    }

    #[test]
    fn tdx_required_mode_fails_closed_when_dcap_verifier_is_unavailable() {
        let mut evidence = valid_evidence();
        set_tdx_quote(&mut evidence, tdx_quote_hex(false, TDX_TEE_TYPE));

        let error = verifier(AttestationConfig {
            require_tdx: true,
            require_nvidia: NvidiaRequirement::Never,
            ..AttestationConfig::default()
        })
        .verify_evidence(MODEL, NONCE, evidence)
        .expect_err("strict TDX should fail without DCAP verifier");

        assert!(matches!(
            error,
            AttestationError::ExternalVerifierUnavailable {
                verifier: "tdx-dcap-qvl",
                ..
            }
        ));
        assert_eq!(error.api_error_code(), "attestation_verifier_unavailable");
    }

    #[test]
    fn nvidia_required_mode_fails_on_missing_nvidia_evidence() {
        let error = verifier(AttestationConfig {
            require_tdx: false,
            require_nvidia: NvidiaRequirement::Required,
            ..AttestationConfig::default()
        })
        .verify_evidence(MODEL, NONCE, valid_evidence())
        .expect_err("missing required NVIDIA evidence must fail");

        assert!(matches!(
            error,
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::MissingNvidiaEvidence,
                ..
            }
        ));
    }

    #[test]
    fn nvidia_required_mode_fails_on_invalid_nvidia_evidence() {
        let mut evidence = valid_evidence();
        evidence
            .as_object_mut()
            .unwrap()
            .insert("nvidia_payload".to_owned(), json!(42));

        let error = verifier(AttestationConfig {
            require_tdx: false,
            require_nvidia: NvidiaRequirement::Required,
            ..AttestationConfig::default()
        })
        .verify_evidence(MODEL, NONCE, evidence)
        .expect_err("invalid NVIDIA evidence must fail");

        assert!(matches!(
            error,
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::InvalidNvidiaEvidence,
                ..
            }
        ));
    }

    #[test]
    fn nvidia_payload_when_present_fails_closed_without_nras_verifier() {
        let mut evidence = valid_evidence();
        evidence
            .as_object_mut()
            .unwrap()
            .insert("nvidia_payload".to_owned(), json!({ "nonce": NONCE }));

        let error = verifier(policy_for_basic_success())
            .verify_evidence(MODEL, NONCE, evidence)
            .expect_err("present NVIDIA evidence must be verified");

        assert!(matches!(
            error,
            AttestationError::ExternalVerifierUnavailable {
                verifier: "nvidia-nras",
                ..
            }
        ));
    }

    #[test]
    fn nonce_mismatch_fails_closed_as_stale_or_replayed_evidence() {
        let mut evidence = valid_evidence();
        evidence.as_object_mut().unwrap().insert(
            "nonce".to_owned(),
            json!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"),
        );

        let error = verifier(policy_for_basic_success())
            .verify_evidence(MODEL, NONCE, evidence)
            .expect_err("nonce mismatch must fail");

        assert!(matches!(
            error,
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::NonceMismatch,
                ..
            }
        ));
    }

    #[test]
    fn signing_address_mismatch_fails_closed() {
        let mut evidence = valid_evidence();
        evidence.as_object_mut().unwrap().insert(
            "signing_address".to_owned(),
            json!("0x0000000000000000000000000000000000000000"),
        );

        let error = verifier(policy_for_basic_success())
            .verify_evidence(MODEL, NONCE, evidence)
            .expect_err("address mismatch must fail");

        assert!(matches!(
            error,
            AttestationError::PolicyViolation {
                code: AttestationFailureCode::SigningAddressMismatch,
                ..
            }
        ));
    }

    #[test]
    fn malformed_upstream_response_shape_fails_closed() {
        let error = verifier(policy_for_basic_success())
            .verify_evidence(MODEL, NONCE, json!([]))
            .expect_err("array response must fail");

        assert!(matches!(error, AttestationError::MalformedResponse { .. }));
    }

    #[tokio::test]
    async fn fetches_attestation_with_model_and_nonce_then_verifies() {
        let base_url = spawn_attestation_server(|query| {
            assert_eq!(query.get("model").map(String::as_str), Some(MODEL));
            let nonce = query
                .get("nonce")
                .expect("nonce query parameter should be present");
            assert_eq!(nonce.len(), 64);
            assert!(nonce.chars().all(|ch| ch.is_ascii_hexdigit()));

            let (signing_key, signing_address) = key_material();
            (
                StatusCode::OK,
                serde_json::to_vec(&json!({
                    "api_version": "aci/1",
                    "attestation": {
                        "tee_type": "tdx",
                        "evidence": {}
                    },
                    "verified": true,
                    "nonce": nonce,
                    "model": MODEL,
                    "tee_provider": "phala",
                    "signing_public_key": signing_key,
                    "signing_address": signing_address
                }))
                .expect("response should serialize"),
            )
        })
        .await;
        let verifier =
            AttestationVerifier::new(policy_for_basic_success(), test_venice_client(&base_url));

        let result = verifier
            .verify_model_attestation(MODEL)
            .await
            .expect("mock attestation should verify");

        assert_eq!(result.model_id, MODEL);
        assert_eq!(result.model_public_key, key_material().0);
    }

    #[tokio::test]
    async fn malformed_upstream_json_fails_closed() {
        let base_url = spawn_raw_attestation_server(StatusCode::OK, b"{".to_vec()).await;
        let verifier =
            AttestationVerifier::new(policy_for_basic_success(), test_venice_client(&base_url));

        let error = verifier
            .verify_model_attestation(MODEL)
            .await
            .expect_err("malformed upstream JSON must fail");

        assert!(matches!(
            error,
            AttestationError::Fetch(VeniceClientError::MalformedAttestationPayload { .. })
        ));
        assert_eq!(error.api_error_code(), "attestation_fetch_failed");
    }

    #[tokio::test]
    async fn upstream_fetch_errors_fail_closed() {
        let verifier = AttestationVerifier::new(
            policy_for_basic_success(),
            test_venice_client("http://127.0.0.1:1/api/v1"),
        );

        let error = verifier
            .verify_model_attestation(MODEL)
            .await
            .expect_err("connection failure must fail closed");

        assert!(matches!(error, AttestationError::Fetch(_)));
        assert_eq!(error.api_error_code(), "attestation_fetch_failed");
    }

    fn tdx_quote_hex(debug: bool, tee_type: u32) -> String {
        hex::encode(tdx_quote_bytes(debug, tee_type))
    }

    fn tdx_quote_bytes(debug: bool, tee_type: u32) -> Vec<u8> {
        let mut bytes = vec![0_u8; TDX_REPORT_DATA_END];
        bytes[TDX_QUOTE_TEE_TYPE_OFFSET..TDX_QUOTE_TEE_TYPE_END]
            .copy_from_slice(&tee_type.to_le_bytes());
        let td_attributes = if debug { 1_u64 } else { 0_u64 };
        bytes[TDX_REPORT_TD_ATTRIBUTES_OFFSET..TDX_REPORT_TD_ATTRIBUTES_END]
            .copy_from_slice(&td_attributes.to_le_bytes());
        bytes
    }

    async fn spawn_attestation_server<F>(handler: F) -> String
    where
        F: Fn(HashMap<String, String>) -> (StatusCode, Vec<u8>) + Clone + Send + Sync + 'static,
    {
        async fn route<F>(
            Query(query): Query<HashMap<String, String>>,
            handler: F,
        ) -> Response<Body>
        where
            F: Fn(HashMap<String, String>) -> (StatusCode, Vec<u8>) + Clone + Send + Sync + 'static,
        {
            let (status, body) = handler(query);
            (status, body).into_response()
        }

        let app = Router::new().route(
            "/api/v1/tee/attestation",
            get({
                let handler = handler.clone();
                move |query| route(query, handler.clone())
            }),
        );
        spawn_router(app).await
    }

    async fn spawn_raw_attestation_server(status: StatusCode, body: Vec<u8>) -> String {
        let app = Router::new().route(
            "/api/v1/tee/attestation",
            get(move || async move { (status, body.clone()) }),
        );
        spawn_router(app).await
    }

    async fn spawn_router(app: Router) -> String {
        let listener = TcpListener::bind(("127.0.0.1", 0))
            .await
            .expect("test listener should bind");
        let addr: SocketAddr = listener.local_addr().expect("listener should have address");
        tokio::spawn(async move {
            axum::serve(listener, app)
                .await
                .expect("test server should run");
        });
        format!("http://{addr}/api/v1")
    }
}