Skip to main content

dcap_artifact_retrieval/provisioning_client/
mod.rs

1/* Copyright (c) Fortanix, Inc.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 */
7
8use std::collections::BTreeMap;
9use std::convert::{TryFrom, TryInto};
10use std::hash::{DefaultHasher, Hash, Hasher};
11use std::io::Read;
12use std::sync::Mutex;
13use std::time::{Duration, SystemTime};
14
15use lru_cache::LruCache;
16use num_enum::TryFromPrimitive;
17use pcs::{
18    platform, CpuSvn, DcapArtifactIssuer, EncPpid, Fmspc, PceId, PceIsvsvn, PckCert, PckCerts,
19    PckCrl, PckID, PlatformTypeForTcbInfo, QeId, QeIdentitySigned, RawTcbEvaluationDataNumbers,
20    RootCaCrl, TcbComponentType, TcbInfo, Unverified,
21};
22#[cfg(feature = "reqwest")]
23use reqwest::blocking::{Client as ReqwestClient, Response as ReqwestResponse};
24
25use crate::Error;
26
27pub mod azure;
28pub(self) mod common;
29pub mod intel;
30pub mod pccs;
31
32pub use self::azure::AzureProvisioningClientBuilder;
33pub use self::intel::IntelProvisioningClientBuilder;
34pub use self::pccs::PccsProvisioningClientBuilder;
35
36// Taken from https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
37#[derive(Clone, Debug, Eq, PartialEq, TryFromPrimitive)]
38#[repr(u16)]
39pub enum StatusCode {
40    Continue = 100,
41    SwitchingProtocols = 101,
42    Processing = 102,
43    EarlyHints = 103,
44    //104-199	Unassigned
45    Ok = 200,
46    Created = 201,
47    Accepted = 202,
48    NonAuthoritativeInformation = 203,
49    NoContent = 204,
50    ResetContent = 205,
51    PartialContent = 206,
52    MultiStatus = 207,
53    AlreadyReported = 208,
54    //209-225	Unassigned
55    ImUsed = 226,
56    //227-299	Unassigned
57    MultipleChoices = 300,
58    MovedPermanently = 301,
59    Found = 302,
60    SeeOther = 303,
61    NotModified = 304,
62    UseProxy = 305,
63    #[num_enum(alternatives = [418])]
64    Unused = 306,
65    TemporaryRedirect = 307,
66    PermanentRedirect = 308,
67    // 309-399	Unassigned
68    BadRequest = 400,
69    Unauthorized = 401,
70    PaymentRequired = 402,
71    Forbidden = 403,
72    NotFound = 404,
73    MethodNotAllowed = 405,
74    NotAcceptable = 406,
75    ProxyAuthenticationRequired = 407,
76    RequestTimeout = 408,
77    Conflict = 409,
78    Gone = 410,
79    LengthRequired = 411,
80    PreconditionFailed = 412,
81    ContentTooLarge = 413,
82    UriTooLong = 414,
83    UnsupportedMediaType = 415,
84    RangeNotSatisfiable = 416,
85    ExpectationFailed = 417,
86    //418 Unused
87    //419-420	Unassigned,
88    MisdirectedRequest = 421,
89    UnprocessableContent = 422,
90    Locked = 423,
91    FailedDependency = 424,
92    TooEarly = 425,
93    UpgradeRequired = 426,
94    // 427 Unassigned
95    PreconditionRequired = 428,
96    TooManyRequests = 429,
97    //430 Unassigned
98    RequestHeaderFieldsTooLarge = 431,
99    //432-450	Unassigned,
100    UnavailableForLegalReasons = 451,
101    //452-460	Unassigned,
102    NonStandard461 = 461, // used by PCCS
103    NonStandard462 = 462, // used by PCCS
104    //463-499	Unassigned,
105    InternalServerError = 500,
106    NotImplemented = 501,
107    BadGateway = 502,
108    ServiceUnavailable = 503,
109    GatewayTimeout = 504,
110    HttpVersionNotSupported = 505,
111    VariantAlsoNegotiates = 506,
112    InsufficientStorage = 507,
113    LoopDetected = 508,
114    //509 Unassigned
115    NotExtended = 510, // OBSOLETED
116    NetworkAuthenticationRequired = 511,
117    //512-599	Unassigned
118    #[num_enum(alternatives = [104..=199, 209..=225, 227..=299, 309..=399, 419, 420, 427, 430, 432..=450, 452..=460, 463..=499, 509, 512..=598])]
119    Unassigned = 599,
120}
121
122#[derive(Copy, Clone, PartialEq, Eq, Hash)]
123pub enum PcsVersion {
124    #[deprecated(
125        note = "As of May 13, Intel has completed the End-of-Life of the deprecated API versions 2 and 3 of Intel PCS."
126    )]
127    V3 = 3,
128    V4 = 4,
129}
130
131pub trait WithApiVersion {
132    fn api_version(&self) -> PcsVersion;
133}
134
135impl WithApiVersion for PcsVersion {
136    fn api_version(&self) -> PcsVersion {
137        *self
138    }
139}
140
141trait PlatformApiTag {
142    fn tag() -> &'static str;
143}
144
145impl PlatformApiTag for platform::SGX {
146    fn tag() -> &'static str {
147        "sgx"
148    }
149}
150
151impl PlatformApiTag for platform::TDX {
152    fn tag() -> &'static str {
153        "tdx"
154    }
155}
156
157#[derive(Hash)]
158pub struct PckCertsIn<'a> {
159    enc_ppid: &'a EncPpid,
160    pce_id: PceId,
161    api_key: &'a Option<String>,
162    api_version: PcsVersion,
163}
164
165impl WithApiVersion for PckCertsIn<'_> {
166    fn api_version(&self) -> PcsVersion {
167        self.api_version
168    }
169}
170
171pub trait PckCertsService<'inp>:
172    ProvisioningServiceApi<'inp, Input = PckCertsIn<'inp>, Output = PckCerts>
173{
174    fn build_input(
175        &'inp self,
176        enc_ppid: &'inp EncPpid,
177        pce_id: PceId,
178    ) -> <Self as ProvisioningServiceApi<'inp>>::Input;
179}
180
181#[derive(Hash)]
182pub struct PckCertIn<'a> {
183    encrypted_ppid: Option<&'a EncPpid>,
184    pce_id: &'a PceId,
185    cpu_svn: &'a CpuSvn,
186    pce_isvsvn: PceIsvsvn,
187    qe_id: Option<&'a QeId>,
188    api_version: PcsVersion,
189    api_key: &'a Option<String>,
190}
191
192impl WithApiVersion for PckCertIn<'_> {
193    fn api_version(&self) -> PcsVersion {
194        self.api_version
195    }
196}
197
198pub trait PckCertService<'inp>:
199    ProvisioningServiceApi<'inp, Input = PckCertIn<'inp>, Output = PckCert<Unverified>>
200{
201    fn build_input(
202        &'inp self,
203        encrypted_ppid: Option<&'inp EncPpid>,
204        pce_id: &'inp PceId,
205        cpu_svn: &'inp CpuSvn,
206        pce_isvsvn: PceIsvsvn,
207        qe_id: Option<&'inp QeId>,
208    ) -> <Self as ProvisioningServiceApi<'inp>>::Input;
209}
210
211#[derive(Hash)]
212pub struct PckCrlIn {
213    api_version: PcsVersion,
214    ca: DcapArtifactIssuer,
215}
216
217impl WithApiVersion for PckCrlIn {
218    fn api_version(&self) -> PcsVersion {
219        self.api_version
220    }
221}
222
223pub trait PckCrlService<'inp>:
224    ProvisioningServiceApi<'inp, Input = PckCrlIn, Output = PckCrl<Unverified>>
225{
226    fn build_input(
227        &'inp self,
228        ca: DcapArtifactIssuer,
229    ) -> <Self as ProvisioningServiceApi<'inp>>::Input;
230}
231
232#[derive(Hash)]
233pub struct QeIdIn {
234    pub api_version: PcsVersion,
235    pub tcb_evaluation_data_number: Option<u16>,
236}
237
238impl WithApiVersion for QeIdIn {
239    fn api_version(&self) -> PcsVersion {
240        self.api_version
241    }
242}
243
244pub trait QeIdService<'inp>:
245    ProvisioningServiceApi<'inp, Input = QeIdIn, Output = QeIdentitySigned>
246{
247    fn build_input(
248        &'inp self,
249        tcb_evaluation_data_number: Option<u16>,
250    ) -> <Self as ProvisioningServiceApi<'inp>>::Input;
251}
252
253#[derive(Hash)]
254pub struct TcbInfoIn<'i> {
255    pub(crate) api_version: PcsVersion,
256    pub(crate) fmspc: &'i Fmspc,
257    pub(crate) tcb_evaluation_data_number: Option<u16>,
258}
259
260impl WithApiVersion for TcbInfoIn<'_> {
261    fn api_version(&self) -> PcsVersion {
262        self.api_version
263    }
264}
265
266pub trait TcbInfoService<'inp, T: PlatformTypeForTcbInfo>:
267    ProvisioningServiceApi<'inp, Input = TcbInfoIn<'inp>, Output = TcbInfo<T>>
268{
269    fn build_input(
270        &'inp self,
271        fmspc: &'inp Fmspc,
272        tcb_evaluation_data_number: Option<u16>,
273    ) -> <Self as ProvisioningServiceApi<'inp>>::Input;
274}
275
276#[derive(Hash)]
277pub struct TcbEvaluationDataNumbersIn;
278
279impl WithApiVersion for TcbEvaluationDataNumbersIn {
280    fn api_version(&self) -> PcsVersion {
281        PcsVersion::V4
282    }
283}
284
285pub trait TcbEvaluationDataNumbersService<'inp, T: PlatformTypeForTcbInfo>:
286    ProvisioningServiceApi<
287    'inp,
288    Input = TcbEvaluationDataNumbersIn,
289    Output = RawTcbEvaluationDataNumbers<T>,
290>
291{
292    fn build_input(&self) -> <Self as ProvisioningServiceApi<'inp>>::Input;
293}
294
295#[derive(Hash)]
296pub struct RootCaCrlIn;
297
298impl WithApiVersion for RootCaCrlIn {
299    fn api_version(&self) -> PcsVersion {
300        PcsVersion::V4
301    }
302}
303
304pub trait RootCaCrlService<'inp>:
305    ProvisioningServiceApi<'inp, Input = RootCaCrlIn, Output = RootCaCrl<Unverified>>
306{
307    fn build_input(&'inp self) -> <Self as ProvisioningServiceApi<'inp>>::Input;
308}
309
310pub struct ClientBuilder {
311    retry_timeout: Option<Duration>,
312    cache_capacity: usize,
313    cache_shelf_time: Duration,
314}
315
316impl Default for ClientBuilder {
317    fn default() -> Self {
318        ClientBuilder {
319            retry_timeout: None,
320            cache_capacity: 10,
321            cache_shelf_time: Duration::from_secs(60),
322        }
323    }
324}
325
326impl ClientBuilder {
327    pub(crate) fn new() -> Self {
328        ClientBuilder::default()
329    }
330
331    pub(crate) fn set_retry_timeout(mut self, retry_timeout: Duration) -> Self {
332        self.retry_timeout = Some(retry_timeout);
333        self
334    }
335
336    pub(crate) fn build<PSS, PS, PC, QS, TS, TDS, ES, TES, RCC, F>(
337        self,
338        pckcerts_service: PSS,
339        pckcert_service: PS,
340        pckcrl_service: PC,
341        qeid_service: QS,
342        sgx_tcbinfo_service: TS,
343        tdx_tcbinfo_service: TDS,
344        sgx_tcb_evaluation_data_numbers_service: ES,
345        tdx_tcb_evaluation_data_numbers_service: TES,
346        root_ca_crl_service: RCC,
347        fetcher: F,
348    ) -> Client<F>
349    where
350        PSS: for<'a> PckCertsService<'a> + Sync + Send + 'static,
351        PS: for<'a> PckCertService<'a> + Sync + Send + 'static,
352        PC: for<'a> PckCrlService<'a> + Sync + Send + 'static,
353        QS: for<'a> QeIdService<'a> + Sync + Send + 'static,
354        TS: for<'a> TcbInfoService<'a, platform::SGX> + Sync + Send + 'static,
355        TDS: for<'a> TcbInfoService<'a, platform::TDX> + Sync + Send + 'static,
356        ES: for<'a> TcbEvaluationDataNumbersService<'a, platform::SGX> + Sync + Send + 'static,
357        TES: for<'a> TcbEvaluationDataNumbersService<'a, platform::TDX> + Sync + Send + 'static,
358        RCC: for<'a> RootCaCrlService<'a> + Sync + Send + 'static,
359        F: for<'a> Fetcher<'a>,
360    {
361        Client::new(
362            pckcerts_service,
363            pckcert_service,
364            pckcrl_service,
365            qeid_service,
366            sgx_tcbinfo_service,
367            tdx_tcbinfo_service,
368            sgx_tcb_evaluation_data_numbers_service,
369            tdx_tcb_evaluation_data_numbers_service,
370            root_ca_crl_service,
371            fetcher,
372            self.retry_timeout,
373            self.cache_capacity,
374            self.cache_shelf_time,
375        )
376    }
377}
378
379struct PcsService<T: for<'a> ProvisioningServiceApi<'a> + Sync + ?Sized> {
380    service: Box<T>,
381}
382
383impl<T: for<'a> ProvisioningServiceApi<'a> + Sync + ?Sized> PcsService<T> {
384    pub fn new(service: Box<T>) -> Self {
385        Self { service }
386    }
387}
388
389impl<T: for<'a> ProvisioningServiceApi<'a> + Sync + ?Sized> PcsService<T> {
390    pub(crate) fn pcs_service(&self) -> &T {
391        &self.service
392    }
393
394    fn call_service<'a, F: Fetcher<'a>>(
395        &'a self,
396        fetcher: &'a F,
397        input: &<T as ProvisioningServiceApi<'a>>::Input,
398    ) -> Result<<T as ProvisioningServiceApi<'a>>::Output, Error> {
399        let (url, headers) =
400            <T as ProvisioningServiceApi<'a>>::build_request(&self.pcs_service(), input)?;
401        let req = fetcher.build_request(&url, headers)?;
402        let api_version = input.api_version();
403
404        let (status_code, resp) = fetcher.send(req)?;
405        <T as ProvisioningServiceApi<'a>>::validate_response(self.pcs_service(), status_code)?;
406        let (response_body, response_headers) = fetcher.parse_response(resp)?;
407        <T as ProvisioningServiceApi<'a>>::parse_response(
408            self.pcs_service(),
409            response_body,
410            response_headers,
411            api_version,
412        )
413    }
414}
415
416struct CachedService<O: Clone, T: for<'a> ProvisioningServiceApi<'a, Output = O> + Sync + ?Sized> {
417    service: BackoffService<T>,
418    cache: Mutex<LruCache<u64, (O, SystemTime)>>,
419    cache_shelf_time: Duration,
420}
421
422impl<O: Clone, T: for<'a> ProvisioningServiceApi<'a, Output = O> + Sync + ?Sized>
423    CachedService<O, T>
424{
425    pub fn new(service: BackoffService<T>, capacity: usize, cache_shelf_time: Duration) -> Self {
426        Self {
427            service,
428            cache: Mutex::new(LruCache::new(capacity)),
429            cache_shelf_time,
430        }
431    }
432}
433
434impl<O: Clone, T: for<'a> ProvisioningServiceApi<'a, Output = O> + Sync + ?Sized>
435    CachedService<O, T>
436{
437    pub(crate) fn pcs_service(&self) -> &T {
438        &self.service.pcs_service()
439    }
440
441    pub fn call_service<'a, F: Fetcher<'a>>(
442        &'a self,
443        fetcher: &'a F,
444        input: &<T as ProvisioningServiceApi<'a>>::Input,
445    ) -> Result<<T as ProvisioningServiceApi<'a>>::Output, Error> {
446        let key = {
447            let mut hasher = DefaultHasher::new();
448            input.hash(&mut hasher);
449            hasher.finish()
450        };
451
452        let mut cache = self.cache.lock().unwrap();
453        if let Some((value, time)) = cache.get_mut(&key) {
454            if self.cache_shelf_time < time.elapsed().unwrap_or(Duration::MAX) {
455                cache.remove(&key);
456            } else {
457                return Ok(value.to_owned());
458            }
459        }
460        let value = self.service.call_service::<F>(fetcher, input)?;
461        cache.insert(key, (value.clone(), SystemTime::now()));
462        Ok(value)
463    }
464}
465
466struct BackoffService<T: for<'a> ProvisioningServiceApi<'a> + Sync + ?Sized> {
467    service: PcsService<T>,
468    retry_timeout: Option<Duration>,
469}
470
471impl<T: for<'a> ProvisioningServiceApi<'a> + Sync + ?Sized> BackoffService<T> {
472    pub fn new(service: PcsService<T>, retry_timeout: Option<Duration>) -> Self {
473        Self {
474            service,
475            retry_timeout,
476        }
477    }
478}
479
480impl<T: for<'a> ProvisioningServiceApi<'a> + Sync + ?Sized> BackoffService<T> {
481    const RETRY_INITIAL_INTERVAL: Duration = Duration::from_secs(2);
482    const RETRY_INTERVAL_MULTIPLIER: f64 = 2.0;
483
484    pub(crate) fn pcs_service(&self) -> &T {
485        &self.service.pcs_service()
486    }
487
488    pub fn call_service<'a, F: Fetcher<'a>>(
489        &'a self,
490        fetcher: &'a F,
491        input: &<T as ProvisioningServiceApi<'a>>::Input,
492    ) -> Result<<T as ProvisioningServiceApi<'a>>::Output, Error> {
493        if let Some(retry_timeout) = self.retry_timeout {
494            let op = || match self.service.call_service::<F>(fetcher, input) {
495                Ok(output) => Ok(output),
496                Err(err) => match err {
497                    Error::PCSError(status_code, msg) => {
498                        if status_code.clone() as u16 >= 500 {
499                            Err(backoff::Error::transient(Error::PCSError(status_code, msg)))
500                        } else {
501                            Err(backoff::Error::permanent(Error::PCSError(status_code, msg)))
502                        }
503                    }
504                    err @ _ => Err(backoff::Error::Permanent(err)),
505                },
506            };
507
508            let backoff = backoff::ExponentialBackoffBuilder::default()
509                .with_initial_interval(Self::RETRY_INITIAL_INTERVAL)
510                .with_multiplier(Self::RETRY_INTERVAL_MULTIPLIER)
511                .with_max_elapsed_time(Some(retry_timeout))
512                .build();
513            backoff::retry(backoff, op).map_err(|backoff_err| match backoff_err {
514                backoff::Error::Permanent(err) => err,
515                backoff::Error::Transient { err, .. } => err,
516            })
517        } else {
518            self.service.call_service::<F>(fetcher, input)
519        }
520    }
521}
522
523pub struct Client<F: for<'a> Fetcher<'a>> {
524    pckcerts_service: CachedService<PckCerts, dyn for<'a> PckCertsService<'a> + Sync + Send>,
525    pckcert_service:
526        CachedService<PckCert<Unverified>, dyn for<'a> PckCertService<'a> + Sync + Send>,
527    pckcrl_service: CachedService<PckCrl<Unverified>, dyn for<'a> PckCrlService<'a> + Sync + Send>,
528    qeid_service: CachedService<QeIdentitySigned, dyn for<'a> QeIdService<'a> + Sync + Send>,
529    sgx_tcbinfo_service: CachedService<
530        TcbInfo<platform::SGX>,
531        dyn for<'a> TcbInfoService<'a, platform::SGX> + Sync + Send,
532    >,
533    tdx_tcbinfo_service: CachedService<
534        TcbInfo<platform::TDX>,
535        dyn for<'a> TcbInfoService<'a, platform::TDX> + Sync + Send,
536    >,
537    sgx_tcb_evaluation_data_numbers_service: CachedService<
538        RawTcbEvaluationDataNumbers<platform::SGX>,
539        dyn for<'a> TcbEvaluationDataNumbersService<'a, platform::SGX> + Sync + Send,
540    >,
541    tdx_tcb_evaluation_data_numbers_service: CachedService<
542        RawTcbEvaluationDataNumbers<platform::TDX>,
543        dyn for<'a> TcbEvaluationDataNumbersService<'a, platform::TDX> + Sync + Send,
544    >,
545    root_ca_crl_service:
546        CachedService<RootCaCrl<Unverified>, dyn for<'a> RootCaCrlService<'a> + Sync + Send>,
547    fetcher: F,
548}
549
550impl<F: for<'a> Fetcher<'a>> Client<F> {
551    fn new<PSS, PS, PC, QS, TS, TDS, ES, TES, RCC>(
552        pckcerts_service: PSS,
553        pckcert_service: PS,
554        pckcrl_service: PC,
555        qeid_service: QS,
556        sgx_tcbinfo_service: TS,
557        tdx_tcbinfo_service: TDS,
558        sgx_tcb_evaluation_data_numbers_service: ES,
559        tdx_tcb_evaluation_data_numbers_service: TES,
560        root_ca_crl_service: RCC,
561        fetcher: F,
562        retry_timeout: Option<Duration>,
563        cache_capacity: usize,
564        cache_shelf_time: Duration,
565    ) -> Client<F>
566    where
567        PSS: for<'a> PckCertsService<'a> + Sync + Send + 'static,
568        PS: for<'a> PckCertService<'a> + Sync + Send + 'static,
569        PC: for<'a> PckCrlService<'a> + Sync + Send + 'static,
570        QS: for<'a> QeIdService<'a> + Sync + Send + 'static,
571        TS: for<'a> TcbInfoService<'a, platform::SGX> + Sync + Send + 'static,
572        TDS: for<'a> TcbInfoService<'a, platform::TDX> + Sync + Send + 'static,
573        ES: for<'a> TcbEvaluationDataNumbersService<'a, platform::SGX> + Sync + Send + 'static,
574        TES: for<'a> TcbEvaluationDataNumbersService<'a, platform::TDX> + Sync + Send + 'static,
575        RCC: for<'a> RootCaCrlService<'a> + Sync + Send + 'static,
576    {
577        Client {
578            pckcerts_service: CachedService::new(
579                BackoffService::new(
580                    PcsService::new(Box::new(pckcerts_service)),
581                    retry_timeout.clone(),
582                ),
583                cache_capacity,
584                cache_shelf_time,
585            ),
586            pckcert_service: CachedService::new(
587                BackoffService::new(
588                    PcsService::new(Box::new(pckcert_service)),
589                    retry_timeout.clone(),
590                ),
591                cache_capacity,
592                cache_shelf_time,
593            ),
594            pckcrl_service: CachedService::new(
595                BackoffService::new(
596                    PcsService::new(Box::new(pckcrl_service)),
597                    retry_timeout.clone(),
598                ),
599                cache_capacity,
600                cache_shelf_time,
601            ),
602            qeid_service: CachedService::new(
603                BackoffService::new(
604                    PcsService::new(Box::new(qeid_service)),
605                    retry_timeout.clone(),
606                ),
607                cache_capacity,
608                cache_shelf_time,
609            ),
610            sgx_tcbinfo_service: CachedService::new(
611                BackoffService::new(
612                    PcsService::new(Box::new(sgx_tcbinfo_service)),
613                    retry_timeout.clone(),
614                ),
615                cache_capacity,
616                cache_shelf_time,
617            ),
618            tdx_tcbinfo_service: CachedService::new(
619                BackoffService::new(
620                    PcsService::new(Box::new(tdx_tcbinfo_service)),
621                    retry_timeout.clone(),
622                ),
623                cache_capacity,
624                cache_shelf_time,
625            ),
626            sgx_tcb_evaluation_data_numbers_service: CachedService::new(
627                BackoffService::new(
628                    PcsService::new(Box::new(sgx_tcb_evaluation_data_numbers_service)),
629                    retry_timeout.clone(),
630                ),
631                cache_capacity,
632                cache_shelf_time,
633            ),
634            tdx_tcb_evaluation_data_numbers_service: CachedService::new(
635                BackoffService::new(
636                    PcsService::new(Box::new(tdx_tcb_evaluation_data_numbers_service)),
637                    retry_timeout.clone(),
638                ),
639                cache_capacity,
640                cache_shelf_time,
641            ),
642            root_ca_crl_service: CachedService::new(
643                BackoffService::new(
644                    PcsService::new(Box::new(root_ca_crl_service)),
645                    retry_timeout.clone(),
646                ),
647                cache_capacity,
648                cache_shelf_time,
649            ),
650            fetcher,
651        }
652    }
653}
654
655pub trait ProvisioningClient {
656    fn pckcerts(&self, enc_ppid: &EncPpid, pce_id: PceId) -> Result<PckCerts, Error>;
657
658    fn pckcert(
659        &self,
660        encrypted_ppid: Option<&EncPpid>,
661        pce_id: &PceId,
662        cpu_svn: &CpuSvn,
663        pce_isvsvn: PceIsvsvn,
664        qe_id: Option<&QeId>,
665    ) -> Result<PckCert<Unverified>, Error>;
666
667    fn sgx_tcbinfo(
668        &self,
669        fmspc: &Fmspc,
670        evaluation_data_number: Option<u16>,
671    ) -> Result<TcbInfo<platform::SGX>, Error>;
672
673    fn tdx_tcbinfo(
674        &self,
675        fmspc: &Fmspc,
676        evaluation_data_number: Option<u16>,
677    ) -> Result<TcbInfo<platform::TDX>, Error>;
678
679    fn pckcrl(&self, ca: DcapArtifactIssuer) -> Result<PckCrl<Unverified>, Error>;
680
681    fn qe_identity(&self, evaluation_data_number: Option<u16>) -> Result<QeIdentitySigned, Error>;
682
683    /// Retrieve PCK certificates using `pckcerts()` and fallback to the
684    /// following method if that's not supported:
685    /// 1. Call `pckcert()` with PCK ID to get best available PCK cert.
686    /// 2. Try to call `pckcert()` with PCK ID but with CPUSVN all 1's.
687    /// 3. Using the FMSPC value from PCK cert in step 1, call `tcbinfo()` to
688    ///    get TCB info.
689    /// 4. For each TCB level in the result of previous call:
690    ///     - Call `pckcert()` to get the best available PCK cert for that TCB
691    ///       level.
692    ///     - When late microcode value is higher than the early microcode
693    ///       value, also try to get PCK cert with TCB level where the early
694    ///       microcode value is set to the late microcode value.
695    ///
696    /// Note that PCK certs for some TCB levels may be missing.
697    fn pckcerts_with_fallback(&self, pck_id: &PckID) -> Result<PckCerts, Error> {
698        let get_and_collect = |collection: &mut BTreeMap<([u8; 16], u16), PckCert<Unverified>>,
699                               cpu_svn: &[u8; 16],
700                               pce_svn: u16|
701         -> Result<PckCert<Unverified>, Error> {
702            let pck_cert = self.pckcert(
703                Some(&pck_id.enc_ppid),
704                &pck_id.pce_id,
705                cpu_svn,
706                pce_svn,
707                Some(&pck_id.qe_id),
708            )?;
709
710            // Getting PCK cert using CPUSVN from PCKID
711            let ptcb = pck_cert.platform_tcb()?;
712            collection.insert(
713                (ptcb.cpusvn, ptcb.tcb_components.pce_svn()),
714                pck_cert.clone(),
715            );
716            Ok(pck_cert)
717        };
718
719        match self.pckcerts(&pck_id.enc_ppid, pck_id.pce_id) {
720            Ok(pck_certs) => return Ok(pck_certs),
721            Err(Error::RequestNotSupported) => {} // fallback below
722            Err(e) => return Err(e),
723        }
724        // fallback:
725
726        // Use BTreeMap to have an ordered PckCerts at the end
727        let mut pckcerts_map = BTreeMap::new();
728
729        // 1. Use PCK ID to get best available PCK Cert
730        let pck_cert = get_and_collect(&mut pckcerts_map, &pck_id.cpu_svn, pck_id.pce_isvsvn)?;
731
732        // 2. Getting PCK cert using CPUSVN all 1's
733        let _ign_err = get_and_collect(&mut pckcerts_map, &[u8::MAX; 16], pck_id.pce_isvsvn);
734
735        let fmspc = pck_cert.sgx_extension()?.fmspc;
736        let tcb_info = self.sgx_tcbinfo(&fmspc, None)?;
737        let tcb_data = tcb_info.data()?;
738        for (cpu_svn, pce_isvsvn) in tcb_data.iter_tcb_components() {
739            // 3. Get PCK based on TCB levels
740            let _ = get_and_collect(&mut pckcerts_map, &cpu_svn, pce_isvsvn)?;
741
742            // 4. If late loaded microcode version is higher than early loaded microcode,
743            //    also try with highest microcode version of both components. We found cases where
744            //    fetching the PCK Cert that exactly matched the TCB level, did not result in a PCK
745            //    Cert for that level
746            let early_ucode_idx =
747                tcb_data.tcb_component_index(TcbComponentType::EarlyMicrocodeUpdate);
748            let late_ucode_idx =
749                tcb_data.tcb_component_index(TcbComponentType::LateMicrocodeUpdate);
750            if let (Some(early_ucode_idx), Some(late_ucode_idx)) = (early_ucode_idx, late_ucode_idx)
751            {
752                let early_ucode = cpu_svn[early_ucode_idx];
753                let late_ucode = cpu_svn[late_ucode_idx];
754                if early_ucode < late_ucode {
755                    let mut cpu_svn = cpu_svn.clone();
756                    cpu_svn[early_ucode_idx] = late_ucode;
757                    let _ign_err = get_and_collect(&mut pckcerts_map, &cpu_svn, pce_isvsvn);
758                }
759            }
760        }
761
762        // BTreeMap by default is Ascending
763        let pck_certs: Vec<_> = pckcerts_map.into_iter().rev().map(|(_, v)| v).collect();
764        pck_certs
765            .try_into()
766            .map_err(|e| Error::PCSDecodeError(format!("{}", e).into()))
767    }
768
769    fn sgx_tcb_evaluation_data_numbers(
770        &self,
771    ) -> Result<RawTcbEvaluationDataNumbers<platform::SGX>, Error>;
772
773    fn tdx_tcb_evaluation_data_numbers(
774        &self,
775    ) -> Result<RawTcbEvaluationDataNumbers<platform::TDX>, Error>;
776
777    fn root_ca_crl(&self) -> Result<RootCaCrl<Unverified>, Error>;
778}
779
780pub trait ProvisioningClientFuncSelector: PlatformTypeForTcbInfo {
781    fn get_tcb_evaluation_data_numbers(
782        pc: &dyn ProvisioningClient,
783    ) -> Result<RawTcbEvaluationDataNumbers<Self>, Error>;
784    fn get_tcbinfo(
785        pc: &dyn ProvisioningClient,
786        fmspc: &Fmspc,
787        evaluation_data_number: Option<u16>,
788    ) -> Result<TcbInfo<Self>, Error>;
789}
790
791impl ProvisioningClientFuncSelector for platform::SGX {
792    fn get_tcb_evaluation_data_numbers(
793        pc: &dyn ProvisioningClient,
794    ) -> Result<RawTcbEvaluationDataNumbers<platform::SGX>, Error> {
795        pc.sgx_tcb_evaluation_data_numbers()
796    }
797
798    fn get_tcbinfo(
799        pc: &dyn ProvisioningClient,
800        fmspc: &Fmspc,
801        evaluation_data_number: Option<u16>,
802    ) -> Result<TcbInfo<platform::SGX>, Error> {
803        pc.sgx_tcbinfo(fmspc, evaluation_data_number)
804    }
805}
806
807impl ProvisioningClientFuncSelector for platform::TDX {
808    fn get_tcb_evaluation_data_numbers(
809        pc: &dyn ProvisioningClient,
810    ) -> Result<RawTcbEvaluationDataNumbers<platform::TDX>, Error> {
811        pc.tdx_tcb_evaluation_data_numbers()
812    }
813
814    fn get_tcbinfo(
815        pc: &dyn ProvisioningClient,
816        fmspc: &Fmspc,
817        evaluation_data_number: Option<u16>,
818    ) -> Result<TcbInfo<platform::TDX>, Error> {
819        pc.tdx_tcbinfo(fmspc, evaluation_data_number)
820    }
821}
822
823impl<F: for<'a> Fetcher<'a>> ProvisioningClient for Client<F> {
824    fn pckcerts(&self, encrypted_ppid: &EncPpid, pce_id: PceId) -> Result<PckCerts, Error> {
825        let input = self
826            .pckcerts_service
827            .pcs_service()
828            .build_input(encrypted_ppid, pce_id);
829        self.pckcerts_service.call_service(&self.fetcher, &input)
830    }
831
832    fn pckcert(
833        &self,
834        encrypted_ppid: Option<&EncPpid>,
835        pce_id: &PceId,
836        cpu_svn: &CpuSvn,
837        pce_isvsvn: PceIsvsvn,
838        qe_id: Option<&QeId>,
839    ) -> Result<PckCert<Unverified>, Error> {
840        let input = self.pckcert_service.pcs_service().build_input(
841            encrypted_ppid,
842            pce_id,
843            cpu_svn,
844            pce_isvsvn,
845            qe_id,
846        );
847        self.pckcert_service.call_service(&self.fetcher, &input)
848    }
849
850    fn sgx_tcbinfo(
851        &self,
852        fmspc: &Fmspc,
853        tcb_evaluation_data_number: Option<u16>,
854    ) -> Result<TcbInfo<platform::SGX>, Error> {
855        let input = self
856            .sgx_tcbinfo_service
857            .pcs_service()
858            .build_input(fmspc, tcb_evaluation_data_number);
859        self.sgx_tcbinfo_service.call_service(&self.fetcher, &input)
860    }
861
862    fn tdx_tcbinfo(
863        &self,
864        fmspc: &Fmspc,
865        tcb_evaluation_data_number: Option<u16>,
866    ) -> Result<TcbInfo<platform::TDX>, Error> {
867        let input = self
868            .tdx_tcbinfo_service
869            .pcs_service()
870            .build_input(fmspc, tcb_evaluation_data_number);
871        self.tdx_tcbinfo_service.call_service(&self.fetcher, &input)
872    }
873
874    fn pckcrl(&self, ca: DcapArtifactIssuer) -> Result<PckCrl<Unverified>, Error> {
875        let input = self.pckcrl_service.pcs_service().build_input(ca);
876        self.pckcrl_service.call_service(&self.fetcher, &input)
877    }
878
879    fn qe_identity(
880        &self,
881        tcb_evaluation_data_number: Option<u16>,
882    ) -> Result<QeIdentitySigned, Error> {
883        let input = self
884            .qeid_service
885            .pcs_service()
886            .build_input(tcb_evaluation_data_number);
887        self.qeid_service.call_service(&self.fetcher, &input)
888    }
889
890    fn sgx_tcb_evaluation_data_numbers(
891        &self,
892    ) -> Result<RawTcbEvaluationDataNumbers<platform::SGX>, Error> {
893        let input = self
894            .sgx_tcb_evaluation_data_numbers_service
895            .pcs_service()
896            .build_input();
897        self.sgx_tcb_evaluation_data_numbers_service
898            .call_service(&self.fetcher, &input)
899    }
900
901    fn tdx_tcb_evaluation_data_numbers(
902        &self,
903    ) -> Result<RawTcbEvaluationDataNumbers<platform::TDX>, Error> {
904        let input = self
905            .tdx_tcb_evaluation_data_numbers_service
906            .pcs_service()
907            .build_input();
908        self.tdx_tcb_evaluation_data_numbers_service
909            .call_service(&self.fetcher, &input)
910    }
911
912    fn root_ca_crl(&self) -> Result<RootCaCrl<Unverified>, Error> {
913        let input = self.root_ca_crl_service.pcs_service().build_input();
914        self.root_ca_crl_service.call_service(&self.fetcher, &input)
915    }
916}
917
918pub trait Fetcher<'req> {
919    type Request;
920    type Response;
921
922    fn build_request(
923        &'req self,
924        url: &String,
925        headers: Vec<(String, String)>,
926    ) -> Result<Self::Request, Error>;
927
928    fn send(&'req self, request: Self::Request) -> Result<(StatusCode, Self::Response), Error>;
929
930    fn parse_response(
931        &'req self,
932        response: Self::Response,
933    ) -> Result<(String, Vec<(String, String)>), Error>;
934}
935
936#[cfg(feature = "reqwest")]
937impl<'req> Fetcher<'req> for ReqwestClient {
938    type Request = reqwest::blocking::RequestBuilder;
939    type Response = ReqwestResponse;
940
941    fn build_request(
942        &'req self,
943        url: &String,
944        headers: Vec<(String, String)>,
945    ) -> Result<Self::Request, Error> {
946        let url = reqwest::Url::parse(url).map_err(|e| e.to_string())?;
947
948        let mut result = self.get(url);
949
950        for (name, value) in headers {
951            result = result.header(name, value);
952        }
953
954        Ok(result)
955    }
956
957    fn send(&'req self, request: Self::Request) -> Result<(StatusCode, Self::Response), Error> {
958        use std::fmt::Write;
959        // Reqwest does not provide enough info about error
960        fn report(mut err: &(dyn std::error::Error + 'static)) -> String {
961            let mut s = format!("{}", err);
962            while let Some(src) = err.source() {
963                let _ = write!(s, "\n  Caused by: {}", src);
964                err = src;
965            }
966            s
967        }
968        let response = request.send().map_err(|e| report(&e))?;
969        let status_code =
970            StatusCode::try_from(response.status().as_u16()).map_err(|e| e.to_string())?;
971
972        Ok((status_code, response))
973    }
974
975    fn parse_response(
976        &'req self,
977        mut response: Self::Response,
978    ) -> Result<(String, Vec<(String, String)>), Error> {
979        let mut body = Vec::new();
980        response.read_to_end(&mut body).map_err(|e| {
981            Error::ReadResponseError(
982                format!("Error while trying to read response body. Error: {}", e).into(),
983            )
984        })?;
985
986        let body = String::from_utf8(body)
987            .map_err(|e| Error::ReadResponseError(format!("{}", e).into()))?;
988
989        let headers: Vec<(String, String)> = response
990            .headers()
991            .iter()
992            .map(|(header, value)| (header.to_string(), value.to_str().unwrap_or("").to_string()))
993            .collect();
994        Ok((body, headers))
995    }
996}
997
998pub trait ProvisioningServiceApi<'inp> {
999    type Input: 'inp + WithApiVersion + Hash;
1000    type Output: Clone;
1001
1002    fn build_request(
1003        &'inp self,
1004        input: &Self::Input,
1005    ) -> Result<(String, Vec<(String, String)>), Error>;
1006
1007    fn validate_response(&'inp self, code: StatusCode) -> Result<(), Error>;
1008
1009    fn parse_response(
1010        &'inp self,
1011        response_body: String,
1012        response_headers: Vec<(String, String)>,
1013        api_version: PcsVersion,
1014    ) -> Result<Self::Output, Error>;
1015}
1016
1017#[cfg(test)]
1018mod test_helpers {
1019    use pkix::FromBer;
1020
1021    pub fn get_cert_subject(cert: &str) -> String {
1022        let cert = &pkix::pem::pem_to_der(cert.trim(), Some(pkix::pem::PEM_CERTIFICATE))
1023            .ok_or(yasna::ASN1Error::new(yasna::ASN1ErrorKind::Invalid))
1024            .unwrap();
1025        let cert = pkix::x509::GenericCertificate::from_ber(&cert).unwrap();
1026        let name = cert.tbscert.subject.get(&*pkix::oid::commonName).unwrap();
1027        String::from_utf8_lossy(&name.value()).to_string()
1028    }
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033    use super::*;
1034    use std::string::String;
1035
1036    struct MockService;
1037
1038    #[derive(Hash, Clone, PartialEq, Eq, Debug)]
1039    struct MockInput(u64);
1040
1041    impl WithApiVersion for MockInput {
1042        fn api_version(&self) -> PcsVersion {
1043            PcsVersion::V4
1044        }
1045    }
1046
1047    #[derive(Clone, PartialEq, Eq, Debug)]
1048    struct MockOutput(String);
1049
1050    impl<'a> ProvisioningServiceApi<'a> for MockService {
1051        type Input = MockInput;
1052        type Output = MockOutput;
1053
1054        fn build_request(
1055            &'a self,
1056            _input: &Self::Input,
1057        ) -> Result<(String, Vec<(String, String)>), Error> {
1058            Ok((_input.0.to_string(), vec![]))
1059        }
1060
1061        fn validate_response(&'a self, _code: StatusCode) -> Result<(), Error> {
1062            Ok(())
1063        }
1064
1065        fn parse_response(
1066            &'a self,
1067            response_body: String,
1068            _response_headers: Vec<(std::string::String, std::string::String)>,
1069            _api_version: PcsVersion,
1070        ) -> Result<Self::Output, Error> {
1071            Ok(MockOutput(format!("response to: {}", response_body)))
1072        }
1073    }
1074
1075    struct MockFetcher;
1076
1077    impl<'req> Fetcher<'req> for MockFetcher {
1078        type Request = String;
1079        type Response = String;
1080
1081        fn build_request(
1082            &'req self,
1083            url: &String,
1084            _headers: Vec<(String, String)>,
1085        ) -> Result<Self::Request, Error> {
1086            Ok(url.clone())
1087        }
1088
1089        fn send(&'req self, request: Self::Request) -> Result<(StatusCode, Self::Response), Error> {
1090            Ok((StatusCode::Ok, request))
1091        }
1092
1093        fn parse_response(
1094            &'req self,
1095            response: Self::Response,
1096        ) -> Result<(String, Vec<(String, String)>), Error> {
1097            Ok((response, vec![]))
1098        }
1099    }
1100
1101    #[test]
1102    fn test_call_service_cache_miss() {
1103        let service = PcsService {
1104            service: Box::new(MockService),
1105        };
1106        let service = BackoffService::new(service, None);
1107        let cached_service = CachedService::new(service, 5, Duration::from_secs(120));
1108        let fetcher = MockFetcher;
1109        let input_a = MockInput(42);
1110        let input_b = MockInput(420);
1111
1112        // Initial call to populate the cache for `input_a`
1113        cached_service.call_service(&fetcher, &input_a).unwrap();
1114
1115        // input_b should provoke cache miss and add new key to the cache
1116        let result = cached_service.call_service(&fetcher, &input_b).unwrap();
1117
1118        let (cached_value, _) = {
1119            let mut cache = cached_service.cache.lock().unwrap();
1120            cache.get_mut(&calculate_key(&input_b)).unwrap().to_owned()
1121        };
1122
1123        assert_eq!(result, cached_value);
1124    }
1125
1126    #[test]
1127    fn test_call_service_cache_hit() {
1128        let service = PcsService {
1129            service: Box::new(MockService),
1130        };
1131        let service = BackoffService::new(service, None);
1132        let cached_service = CachedService::new(service, 5, Duration::from_secs(120));
1133        let fetcher = MockFetcher;
1134        let input = MockInput(42);
1135
1136        // Initial call to populate the cache
1137        let _ = cached_service.call_service(&fetcher, &input).unwrap();
1138
1139        // Now the service should not be called, and the cached result should be returned
1140        let (cached_value, _) = {
1141            let mut cache = cached_service.cache.lock().unwrap();
1142            cache.get_mut(&calculate_key(&input)).unwrap().to_owned()
1143        };
1144
1145        let result = cached_service.call_service(&fetcher, &input).unwrap();
1146        assert_eq!(result, cached_value);
1147    }
1148
1149    #[test]
1150    fn test_cache_capacity_eviction() {
1151        let service = PcsService {
1152            service: Box::new(MockService),
1153        };
1154        let service = BackoffService::new(service, None);
1155        let cached_service = CachedService::new(service, 2, Duration::from_secs(120));
1156        let fetcher = MockFetcher;
1157
1158        // Insert entries into the cache, exceeding its capacity
1159        for i in 0..3 {
1160            let input = MockInput(i);
1161            let _ = cached_service.call_service(&fetcher, &input).unwrap();
1162        }
1163
1164        // At this point, the cache should have evicted the first inserted entry (MockInput(0))
1165        let mut cache = cached_service.cache.lock().unwrap();
1166
1167        // The cache should only have 2 items (capacity is 2)
1168        assert_eq!(cache.len(), 2);
1169
1170        // The first inserted key (MockInput(0)) should be evicted
1171        let key_first = calculate_key(&MockInput(0));
1172        assert!(!cache.contains_key(&key_first));
1173
1174        // The last inserted key (MockInput(2)) should be present
1175        let key_last = calculate_key(&MockInput(2));
1176        assert!(cache.contains_key(&key_last));
1177    }
1178
1179    // Helper function to calculate the cache key based on the input
1180    fn calculate_key(input: &MockInput) -> u64 {
1181        let mut hasher = DefaultHasher::new();
1182        input.hash(&mut hasher);
1183        hasher.finish()
1184    }
1185}