dcap-qvl 0.3.7

This crate implements the quote verification logic for DCAP (Data Center Attestation Primitives) in pure Rust.
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
use alloc::string::{String, ToString};
use anyhow::{anyhow, bail, Context, Result};
use der::Decode as DerDecode;
use scale::Decode;
use serde::Deserialize;
use x509_cert::{
    ext::pkix::{
        name::{DistributionPointName, GeneralName},
        CrlDistributionPoints,
    },
    Certificate,
};

use crate::constants::{
    PCK_ID_ENCRYPTED_PPID_2048, PCK_ID_ENCRYPTED_PPID_3072, PCK_ID_PCK_CERT_CHAIN,
};
use crate::quote::{EncryptedPpidParams, Quote};
use crate::verify::VerifiedReport;
use crate::QuoteCollateralV3;

#[derive(Deserialize)]
struct TcbInfoResponse {
    #[serde(rename = "tcbInfo")]
    tcb_info: serde_json::Value,
    signature: String,
}

#[derive(Deserialize)]
struct QeIdentityResponse {
    #[serde(rename = "enclaveIdentity")]
    enclave_identity: serde_json::Value,
    signature: String,
}

#[cfg(not(feature = "js"))]
use core::time::Duration;
use std::time::SystemTime;

/// Default PCCS URL (Phala Network's PCCS server).
/// This is the recommended default for most users as it provides better availability
/// and lower rate limits compared to Intel's PCS.
pub const PHALA_PCCS_URL: &str = "https://pccs.phala.network";

/// Intel's official PCS (Provisioning Certification Service) URL.
/// Use `get_collateral_from_pcs()` to fetch collateral directly from Intel.
const INTEL_PCS_URL: &str = "https://api.trustedservices.intel.com";

struct PcsEndpoints {
    base_url: String,
    tee: &'static str,
    fmspc: String,
    ca: &'static str,
}

impl PcsEndpoints {
    fn new(base_url: &str, for_sgx: bool, fmspc: String, ca: &'static str) -> Self {
        let tee = if for_sgx { "sgx" } else { "tdx" };
        let base_url = base_url
            .trim_end_matches('/')
            .trim_end_matches("/sgx/certification/v4")
            .trim_end_matches("/tdx/certification/v4")
            .to_owned();
        Self {
            base_url,
            tee,
            fmspc,
            ca,
        }
    }

    fn is_pcs(&self) -> bool {
        self.base_url.starts_with(INTEL_PCS_URL)
    }

    fn url_pckcrl(&self) -> String {
        self.mk_url("sgx", &format!("pckcrl?ca={}&encoding=der", self.ca))
    }

    fn url_rootcacrl(&self) -> String {
        self.mk_url("sgx", "rootcacrl")
    }

    fn url_tcb(&self) -> String {
        self.mk_url(self.tee, &format!("tcb?fmspc={}", self.fmspc))
    }

    fn url_qe_identity(&self) -> String {
        self.mk_url(self.tee, "qe/identity?update=standard")
    }

    fn mk_url(&self, tee: &str, path: &str) -> String {
        format!("{}/{}/certification/v4/{}", self.base_url, tee, path)
    }
}

fn get_header(response: &reqwest::Response, name: &str) -> Result<String> {
    let value = response
        .headers()
        .get(name)
        .ok_or_else(|| anyhow!("Missing {name}"))?
        .to_str()?;
    let value = urlencoding::decode(value)?;
    Ok(value.into_owned())
}

/// Extracts the CRL Distribution Point URL from a certificate.
///
/// This function parses the certificate and looks for the CRL Distribution Points extension (OID 2.5.29.31).
/// It then extracts the first URL found in the extension's FullName field.
///
/// # Arguments
/// * `cert_der` - The DER-encoded certificate bytes
///
/// # Returns
/// * `Ok(Some(String))` - The CRL distribution point URL if found
/// * `Ok(None)` - If no CRL distribution point was found in the certificate
/// * `Err(_)` - If there was an error parsing the certificate or the extension
fn extract_crl_url(cert_der: &[u8]) -> Result<Option<String>> {
    let cert: Certificate = DerDecode::from_der(cert_der).context("Failed to parse certificate")?;

    let Some(extensions) = &cert.tbs_certificate.extensions else {
        return Ok(None);
    };
    for ext in extensions.iter() {
        if ext.extn_id.to_string() != "2.5.29.31" {
            continue;
        }
        let crl_dist_points: CrlDistributionPoints = DerDecode::from_der(ext.extn_value.as_bytes())
            .context("Failed to parse CRL Distribution Points")?;

        for dist_point in crl_dist_points.0.iter() {
            let Some(dist_point_name) = &dist_point.distribution_point else {
                continue;
            };
            let DistributionPointName::FullName(general_names) = dist_point_name else {
                continue;
            };
            for general_name in general_names.iter() {
                let GeneralName::UniformResourceIdentifier(uri) = general_name else {
                    continue;
                };
                return Ok(Some(uri.to_string()));
            }
        }
    }
    Ok(None)
}

/// Fetch PCK certificate from PCCS using encrypted PPID parameters.
async fn fetch_pck_certificate(
    client: &reqwest::Client,
    pccs_url: &str,
    qeid: &[u8],
    params: &EncryptedPpidParams,
) -> Result<String> {
    // PCCS normalizes parameters to uppercase, Intel PCS accepts both
    // Use uppercase for compatibility with both
    let qeid = hex::encode_upper(qeid);
    let encrypted_ppid = hex::encode_upper(&params.encrypted_ppid);
    let cpusvn = hex::encode_upper(params.cpusvn);
    let pcesvn = hex::encode_upper(params.pcesvn.to_le_bytes());
    let pceid = hex::encode_upper(params.pceid);

    let base_url = pccs_url
        .trim_end_matches('/')
        .trim_end_matches("/sgx/certification/v4")
        .trim_end_matches("/tdx/certification/v4");
    let url = format!(
        "{base_url}/sgx/certification/v4/pckcert?qeid={qeid}&encrypted_ppid={encrypted_ppid}&cpusvn={cpusvn}&pcesvn={pcesvn}&pceid={pceid}"
    );
    let response = client.get(&url).send().await?;

    if !response.status().is_success() {
        bail!(
            "Failed to fetch PCK certificate from {}: {}",
            url,
            response.status()
        );
    }

    // Check if Intel returned a certificate for a different TCB level
    // SGX-TCBm header format: cpusvn (16 bytes) + pcesvn (2 bytes, little-endian)
    if let Some(tcbm) = response.headers().get("SGX-TCBm") {
        let tcbm_str = tcbm
            .to_str()
            .context("SGX-TCBm header contains invalid characters")?;
        let tcbm_bytes =
            hex::decode(tcbm_str).map_err(|e| anyhow!("SGX-TCBm header is not valid hex: {e}"))?;
        let (matched_cpusvn, matched_pcesvn) = <([u8; 16], u16)>::decode(&mut &tcbm_bytes[..])
            .context("SGX-TCBm header too short: expected 18 bytes")?;

        if matched_cpusvn != params.cpusvn || matched_pcesvn != params.pcesvn {
            bail!(
                "TCB level mismatch: Platform's current TCB (cpusvn={}, pcesvn={}) \
                is not registered with Intel PCS. Intel matched to a lower TCB level \
                (cpusvn={}, pcesvn={}). This typically means the platform had a \
                microcode/firmware update but MPA registration was not re-run afterward. \
                Solution: Run 'mpa_manage -c mpa_registration.conf' on the platform \
                to register the new TCB level with Intel.",
                hex::encode(params.cpusvn),
                params.pcesvn,
                hex::encode(matched_cpusvn),
                matched_pcesvn
            );
        }
    }

    // The response includes the PCK certificate chain in a header
    let pck_cert_chain = get_header(&response, "SGX-PCK-Certificate-Issuer-Chain")?;

    // The body is the leaf PCK certificate
    let pck_cert = response.text().await?;

    // Combine into a full PEM chain (leaf first, then issuer chain)
    Ok(format!("{pck_cert}\n{pck_cert_chain}"))
}

/// Extract FMSPC and CA type from a PEM certificate chain.
fn extract_fmspc_and_ca(pem_chain: &str) -> Result<(String, &'static str)> {
    let certs = crate::utils::extract_certs(pem_chain.as_bytes())
        .context("Failed to extract certificates from PEM chain")?;
    let cert = certs
        .first()
        .ok_or_else(|| anyhow!("Empty certificate chain"))?;

    // Extract FMSPC from Intel extension
    let extension = crate::utils::get_intel_extension(cert)
        .context("Failed to get Intel extension from certificate")?;
    let fmspc = crate::utils::get_fmspc(&extension)?;
    let fmspc_hex = hex::encode_upper(fmspc);

    // Extract CA type from issuer
    let cert_der: Certificate =
        der::Decode::from_der(cert).context("Failed to decode certificate")?;
    let issuer = cert_der.tbs_certificate.issuer.to_string();
    let ca = if issuer.contains(crate::constants::PROCESSOR_ISSUER) {
        crate::constants::PROCESSOR_ISSUER_ID
    } else if issuer.contains(crate::constants::PLATFORM_ISSUER) {
        crate::constants::PLATFORM_ISSUER_ID
    } else {
        crate::constants::PROCESSOR_ISSUER_ID
    };

    Ok((fmspc_hex, ca))
}

/// Build HTTP client with appropriate settings.
fn build_http_client() -> Result<reqwest::Client> {
    let builder = reqwest::Client::builder();
    #[cfg(not(feature = "js"))]
    let builder = builder
        .danger_accept_invalid_certs(true)
        .timeout(Duration::from_secs(180));
    Ok(builder.build()?)
}

/// Get PCK certificate chain for a quote.
/// - cert_type 5: extracts from quote
/// - cert_type 2/3: fetches from PCCS using encrypted PPID
async fn get_pck_chain(client: &reqwest::Client, pccs_url: &str, quote: &Quote) -> Result<String> {
    match quote.inner_cert_type() {
        PCK_ID_PCK_CERT_CHAIN => Ok(String::from_utf8_lossy(quote.inner_cert_data()).to_string()),
        PCK_ID_ENCRYPTED_PPID_2048 | PCK_ID_ENCRYPTED_PPID_3072 => {
            let params = quote.encrypted_ppid_params()?;
            fetch_pck_certificate(client, pccs_url, quote.qeid(), &params).await
        }
        other => bail!("Unsupported certification data type: {other}"),
    }
}

/// Get collateral given DCAP quote and base URL of PCCS server URL.
///
/// # Arguments
///
/// * `pccs_url` - The base URL of PCCS server. (e.g. `https://pccs.example.com/sgx/certification/v4`)
/// * `quote` - The raw quote to verify. Supported SGX and TDX quotes.
///
/// # Returns
///
/// * `Ok(QuoteCollateralV3)` - The quote collateral
/// * `Err(Error)` - The error
pub async fn get_collateral(pccs_url: &str, mut quote: &[u8]) -> Result<QuoteCollateralV3> {
    let parsed_quote = Quote::decode(&mut quote)?;
    let client = build_http_client()?;

    // Get PCK certificate chain (from quote or PCCS)
    let pck_chain = get_pck_chain(&client, pccs_url, &parsed_quote)
        .await
        .context("Failed to get PCK certificate chain")?;

    // Extract FMSPC and CA from the certificate
    let (fmspc, ca) = extract_fmspc_and_ca(&pck_chain)?;

    // Fetch the rest of the collateral
    let mut collateral =
        get_collateral_for_fmspc_impl(&client, pccs_url, fmspc, ca, parsed_quote.header.is_sgx())
            .await?;

    // Attach the PCK certificate chain for offline verification
    collateral.pck_certificate_chain = Some(pck_chain);

    Ok(collateral)
}

/// Get collateral for a known FMSPC (public API, builds its own HTTP client).
pub async fn get_collateral_for_fmspc(
    pccs_url: &str,
    fmspc: String,
    ca: &'static str,
    for_sgx: bool,
) -> Result<QuoteCollateralV3> {
    let client = build_http_client()?;
    get_collateral_for_fmspc_impl(&client, pccs_url, fmspc, ca, for_sgx).await
}

/// Internal implementation that uses a provided HTTP client.
async fn get_collateral_for_fmspc_impl(
    client: &reqwest::Client,
    pccs_url: &str,
    fmspc: String,
    ca: &'static str,
    for_sgx: bool,
) -> Result<QuoteCollateralV3> {
    let endpoints = PcsEndpoints::new(pccs_url, for_sgx, fmspc, ca);

    let pck_crl_issuer_chain;
    let pck_crl;
    {
        let response = client.get(endpoints.url_pckcrl()).send().await?;
        pck_crl_issuer_chain = get_header(&response, "SGX-PCK-CRL-Issuer-Chain")?;
        pck_crl = response.bytes().await?.to_vec();
    };

    let tcb_info_issuer_chain;
    let raw_tcb_info;
    {
        let response = client.get(endpoints.url_tcb()).send().await?;
        tcb_info_issuer_chain = get_header(&response, "SGX-TCB-Info-Issuer-Chain")
            .or(get_header(&response, "TCB-Info-Issuer-Chain"))?;
        raw_tcb_info = response.text().await?;
    };
    let qe_identity_issuer_chain;
    let raw_qe_identity;
    {
        let response = client.get(endpoints.url_qe_identity()).send().await?;
        qe_identity_issuer_chain = get_header(&response, "SGX-Enclave-Identity-Issuer-Chain")?;
        raw_qe_identity = response.text().await?;
    };

    async fn http_get(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
        let response = client.get(url).send().await?;
        if !response.status().is_success() {
            bail!("Failed to fetch {url}: {}", response.status());
        }
        Ok(response.bytes().await?.to_vec())
    }

    // First try to get root CA CRL directly from the PCCS endpoint
    let mut root_ca_crl = None;
    if !endpoints.is_pcs() {
        root_ca_crl = http_get(client, &endpoints.url_rootcacrl()).await.ok();

        if let Some(ref crl) = root_ca_crl {
            // PCCS returns hex-encoded CRL instead of binary DER.
            let hex_str =
                core::str::from_utf8(crl).context("Failed to convert hex-encoded CRL to string")?;
            let ca_crl = hex::decode(hex_str)
                .map_err(|_| anyhow!("Failed to decode hex-encoded root CA CRL"))?;
            root_ca_crl = Some(ca_crl);
        }
    }
    let root_ca_crl = match root_ca_crl {
        Some(crl) => crl,
        None => {
            let certs = crate::utils::extract_certs(qe_identity_issuer_chain.as_bytes())
                .context("Failed to extract certificates from PCK CRL issuer chain")?;
            let root_cert_der = certs
                .last()
                .context("No certificate found in PCK CRL issuer chain")?;
            let crl_url = extract_crl_url(root_cert_der)?;
            let Some(url) = crl_url else {
                bail!("Could not find CRL distribution point in root certificate");
            };
            http_get(client, &url).await?
        }
    };

    let tcb_info_resp: TcbInfoResponse =
        serde_json::from_str(&raw_tcb_info).context("TCB Info should be valid JSON")?;
    let tcb_info = tcb_info_resp.tcb_info.to_string();
    let tcb_info_signature = hex::decode(&tcb_info_resp.signature)
        .ok()
        .context("TCB Info signature must be valid hex")?;

    let qe_identity_resp: QeIdentityResponse =
        serde_json::from_str(&raw_qe_identity).context("QE Identity should be valid JSON")?;
    let qe_identity = qe_identity_resp.enclave_identity.to_string();
    let qe_identity_signature = hex::decode(&qe_identity_resp.signature)
        .ok()
        .context("QE Identity signature must be valid hex")?;

    Ok(QuoteCollateralV3 {
        pck_crl_issuer_chain,
        root_ca_crl,
        pck_crl,
        tcb_info_issuer_chain,
        tcb_info,
        tcb_info_signature,
        qe_identity_issuer_chain,
        qe_identity,
        qe_identity_signature,
        pck_certificate_chain: None,
    })
}

/// Get collateral given DCAP quote from Intel PCS.
///
/// # Arguments
///
/// * `quote` - The raw quote to verify. Supported SGX and TDX quotes.
///
/// # Returns
///
/// * `Ok(QuoteCollateralV3)` - The quote collateral
/// * `Err(Error)` - The error
pub async fn get_collateral_from_pcs(quote: &[u8]) -> Result<QuoteCollateralV3> {
    get_collateral(INTEL_PCS_URL, quote).await
}

/// Get collateral and verify the quote.
///
/// # Arguments
///
/// * `quote` - The raw quote to verify.
/// * `pccs_url` - Optional PCCS URL. Defaults to Phala PCCS if not provided.
pub async fn get_collateral_and_verify(
    quote: &[u8],
    pccs_url: Option<&str>,
) -> Result<VerifiedReport> {
    let pccs_url = pccs_url
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .unwrap_or(PHALA_PCCS_URL);
    let collateral = get_collateral(pccs_url, quote).await?;
    let now = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .context("Failed to get current time")?
        .as_secs();
    crate::verify::verify(quote, &collateral, now)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use super::*;
    use crate::constants::{PLATFORM_ISSUER_ID, PROCESSOR_ISSUER_ID};

    // Sample PCK certificate chain (processor CA) for testing - extracted from sample/sgx_quote
    const TEST_PCK_CHAIN_PROCESSOR: &str = r#"-----BEGIN CERTIFICATE-----
MIIEjTCCBDSgAwIBAgIVAIG3dzK3YemOubljpKvR5bm/XdjWMAoGCCqGSM49BAMC
MHExIzAhBgNVBAMMGkludGVsIFNHWCBQQ0sgUHJvY2Vzc29yIENBMRowGAYDVQQK
DBFJbnRlbCBDb3Jwb3JhdGlvbjEUMBIGA1UEBwwLU2FudGEgQ2xhcmExCzAJBgNV
BAgMAkNBMQswCQYDVQQGEwJVUzAeFw0yMzA5MjAyMTUzNDNaFw0zMDA5MjAyMTUz
NDNaMHAxIjAgBgNVBAMMGUludGVsIFNHWCBQQ0sgQ2VydGlmaWNhdGUxGjAYBgNV
BAoMEUludGVsIENvcnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkG
A1UECAwCQ0ExCzAJBgNVBAYTAlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE
kgmE7N3D+RspyaCZ2YoDTLDCuh5pnvAu4crPn2uAGujq9tOgwU8/y7jttShCB603
U6r+h9ayOk2nZ9jewk25lqOCAqgwggKkMB8GA1UdIwQYMBaAFNDoqtp11/kuSReY
PHsUZdDV8llNM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AkGA1UECAwCQ0ExCzAJ
BgNVBAYTAlVTMB4XDTE4MDUyMTEwNDUxMFoXDTQ5MTIzMTIzNTk1OVowaDEaMBgG
A1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENvcnBvcmF0
aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJBgNVBAYT
AlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEC6nEwMDIYZOj/iPWsCzaEKi7
1OiOSLRFhWGjbnBVJfVnkY4u3IjkDYYL0MxO4mqsyYjlBalTVYxFP2sJBK5zlKOB
uzCBuDAfBgNVHSMEGDAWgBQiZQzWWp00ifODtJVSv1AbOScGrDBSBgNVHR8ESzBJ
MEegRaBDhkFodHRwczovL2NlcnRpZmljYXRlcy50cnVzdGVkc2VydmljZXMuaW50
ZWwuY29tL0ludGVsU0dYUm9vdENBLmRlcjAdBgNVHQ4EFgQUImUM1lqdNInzg7SV
Ur9QGzknBqwwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwCgYI
KoZIzj0EAwIDSQAwRgIhAOW/5QkR+S9CiSDcNoowLuPRLsWGf/Yi7GSX94BgwTwg
AiEA4J0lrHoMs+Xo5o/sX6O9QWxHRAvZUGOdRQ7cvqRXaqI=
-----END CERTIFICATE-----
"#;

    #[test]
    fn test_extract_fmspc_and_ca_processor() {
        let (fmspc, ca) = extract_fmspc_and_ca(TEST_PCK_CHAIN_PROCESSOR).unwrap();
        assert_eq!(fmspc, "00A067110000");
        assert_eq!(ca, PROCESSOR_ISSUER_ID);
    }

    #[test]
    fn test_pcs_endpoints_new() {
        // Test SGX endpoint initialization
        let sgx_endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            true,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(sgx_endpoints.base_url, "https://pccs.example.com");
        assert_eq!(sgx_endpoints.tee, "sgx");
        assert_eq!(sgx_endpoints.fmspc, "B0C06F000000");
        assert_eq!(sgx_endpoints.ca, PROCESSOR_ISSUER_ID);

        // Test TDX endpoint initialization
        let tdx_endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            false,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(tdx_endpoints.base_url, "https://pccs.example.com");
        assert_eq!(tdx_endpoints.tee, "tdx");
        assert_eq!(tdx_endpoints.fmspc, "B0C06F000000");
        assert_eq!(tdx_endpoints.ca, PROCESSOR_ISSUER_ID);

        // Test URL normalization during initialization
        let endpoints_with_trailing_slash = PcsEndpoints::new(
            "https://pccs.example.com/",
            true,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(
            endpoints_with_trailing_slash.base_url,
            "https://pccs.example.com"
        );

        // Test URL normalization with SGX certification path
        let endpoints_with_sgx_path = PcsEndpoints::new(
            "https://pccs.example.com/sgx/certification/v4",
            true,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(endpoints_with_sgx_path.base_url, "https://pccs.example.com");

        // Test URL normalization with TDX certification path
        let endpoints_with_tdx_path = PcsEndpoints::new(
            "https://pccs.example.com/tdx/certification/v4",
            false,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(endpoints_with_tdx_path.base_url, "https://pccs.example.com");
    }

    #[test]
    fn test_pcs_endpoints_url_pckcrl() {
        // Test with processor CA
        let processor_endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            true,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(
            processor_endpoints.url_pckcrl(),
            "https://pccs.example.com/sgx/certification/v4/pckcrl?ca=processor&encoding=der"
        );

        // Test with platform CA
        let platform_endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            true,
            "B0C06F000000".to_string(),
            PLATFORM_ISSUER_ID,
        );
        assert_eq!(
            platform_endpoints.url_pckcrl(),
            "https://pccs.example.com/sgx/certification/v4/pckcrl?ca=platform&encoding=der"
        );
    }

    #[test]
    fn test_pcs_endpoints_url_rootcacrl() {
        let endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            true,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(
            endpoints.url_rootcacrl(),
            "https://pccs.example.com/sgx/certification/v4/rootcacrl"
        );
    }

    #[test]
    fn test_pcs_endpoints_url_tcb() {
        // Test SGX TCB URL
        let sgx_endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            true,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(
            sgx_endpoints.url_tcb(),
            "https://pccs.example.com/sgx/certification/v4/tcb?fmspc=B0C06F000000"
        );

        // Test TDX TCB URL
        let tdx_endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            false,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(
            tdx_endpoints.url_tcb(),
            "https://pccs.example.com/tdx/certification/v4/tcb?fmspc=B0C06F000000"
        );
    }

    #[test]
    fn test_pcs_endpoints_url_qe_identity() {
        // Test SGX QE identity URL
        let sgx_endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            true,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(
            sgx_endpoints.url_qe_identity(),
            "https://pccs.example.com/sgx/certification/v4/qe/identity?update=standard"
        );

        // Test TDX QE identity URL
        let tdx_endpoints = PcsEndpoints::new(
            "https://pccs.example.com",
            false,
            "B0C06F000000".to_string(),
            PROCESSOR_ISSUER_ID,
        );
        assert_eq!(
            tdx_endpoints.url_qe_identity(),
            "https://pccs.example.com/tdx/certification/v4/qe/identity?update=standard"
        );
    }

    #[test]
    fn test_intel_pcs_url() {
        // Test the Intel PCS URL constant
        assert_eq!(INTEL_PCS_URL, "https://api.trustedservices.intel.com");

        // Test the Phala PCCS URL constant
        assert_eq!(PHALA_PCCS_URL, "https://pccs.phala.network");

        // Test with the known FMSPC from memory
        let fmspc = "B0C06F000000";
        let intel_endpoints =
            PcsEndpoints::new(INTEL_PCS_URL, true, fmspc.to_string(), PROCESSOR_ISSUER_ID);

        assert_eq!(
            intel_endpoints.url_pckcrl(),
            "https://api.trustedservices.intel.com/sgx/certification/v4/pckcrl?ca=processor&encoding=der"
        );

        assert_eq!(
            intel_endpoints.url_rootcacrl(),
            "https://api.trustedservices.intel.com/sgx/certification/v4/rootcacrl"
        );

        assert_eq!(
            intel_endpoints.url_tcb(),
            "https://api.trustedservices.intel.com/sgx/certification/v4/tcb?fmspc=B0C06F000000"
        );

        assert_eq!(
            intel_endpoints.url_qe_identity(),
            "https://api.trustedservices.intel.com/sgx/certification/v4/qe/identity?update=standard"
        );
    }
}