Skip to main content

rustflexstack/security/pki_client/
transport.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! HTTP transport of the PKI messages.
5//!
6//! ETSI TS 102 941 V2.2.1 Annex C: requests are HTTP POSTs to the access point
7//! of the EA / AA (`application/x-its-request`, response
8//! `application/x-its-response`). Annexes D and E: CTL, CRL and ECTL are
9//! fetched with HTTP GET from the DC / CPOC. The transport is a trait so that
10//! tests (and other carriers) can replace it.
11
12use std::fmt;
13use std::sync::Arc;
14use std::time::Duration;
15
16use crate::security::pki_client::client::PkiClock;
17
18/// The PKI could not be reached or answered with an HTTP error.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct PkiTransportError(pub String);
21
22impl fmt::Display for PkiTransportError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        f.write_str(&self.0)
25    }
26}
27
28impl std::error::Error for PkiTransportError {}
29
30/// Carrier of the PKI messages.
31pub trait PkiTransport: Send + Sync {
32    /// POST `body` to `url`; returns the response body.
33    fn post(
34        &self,
35        url: &str,
36        body: &[u8],
37        content_type: &str,
38    ) -> Result<Vec<u8>, PkiTransportError>;
39    /// GET `url`; returns the response body.
40    fn get(&self, url: &str) -> Result<Vec<u8>, PkiTransportError>;
41}
42
43/// `ureq` transport with a timeout.
44#[derive(Debug, Clone)]
45pub struct HttpTransport {
46    pub timeout: Duration,
47}
48
49impl HttpTransport {
50    pub fn new(timeout: Duration) -> Self {
51        Self { timeout }
52    }
53}
54
55impl Default for HttpTransport {
56    fn default() -> Self {
57        Self::new(Duration::from_secs(30))
58    }
59}
60
61fn read(
62    response: Result<ureq::Response, ureq::Error>,
63    what: &str,
64) -> Result<Vec<u8>, PkiTransportError> {
65    match response {
66        Ok(r) => {
67            let mut body = Vec::new();
68            std::io::Read::read_to_end(&mut r.into_reader(), &mut body)
69                .map_err(|e| PkiTransportError(format!("{what}: {e}")))?;
70            Ok(body)
71        }
72        Err(ureq::Error::Status(code, _)) => Err(PkiTransportError(format!("{what}: HTTP {code}"))),
73        Err(e) => Err(PkiTransportError(format!("{what}: {e}"))),
74    }
75}
76
77impl PkiTransport for HttpTransport {
78    fn post(
79        &self,
80        url: &str,
81        body: &[u8],
82        content_type: &str,
83    ) -> Result<Vec<u8>, PkiTransportError> {
84        read(
85            ureq::post(url)
86                .timeout(self.timeout)
87                .set("Content-Type", content_type)
88                .send_bytes(body),
89            &format!("POST {url}"),
90        )
91    }
92
93    fn get(&self, url: &str) -> Result<Vec<u8>, PkiTransportError> {
94        read(
95            ureq::get(url).timeout(self.timeout).call(),
96            &format!("GET {url}"),
97        )
98    }
99}
100
101/// Wait (seconds) between two transmissions of a request.
102pub type PkiSleep = Arc<dyn Fn(f64) + Send + Sync>;
103
104/// Repetition of a request whose response is not received (ETSI TS 103 601
105/// V2.1.1 clauses 5.1.4 and 5.2.4): the same message is sent again `th1`
106/// seconds after the previous transmission (timer T1 / T4), at most `n1` times
107/// in all (N1 / N2), and not after `th2` seconds from the first one (T2 / T5,
108/// TH2 > TH1 x N1; NOTE 1 recommends 60 minutes).
109#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct RetryPolicy {
111    pub th1: f64,
112    pub n1: u32,
113    pub th2: f64,
114}
115
116impl Default for RetryPolicy {
117    fn default() -> Self {
118        Self {
119            th1: 30.0,
120            n1: 3,
121            th2: 3600.0,
122        }
123    }
124}
125
126/// A [`RetryPolicy`] with the clock and the wait it runs on.
127#[derive(Clone)]
128pub struct Retry {
129    pub policy: RetryPolicy,
130    pub clock: PkiClock,
131    pub sleep: PkiSleep,
132}
133
134/// POST `body` (always the same message) until a response is received,
135/// following `retry` (one transmission when None). The error when no response
136/// came: the caller then drops the request and its session key (clause 5.1.2,
137/// case 2).
138pub fn post_with_retry(
139    transport: &dyn PkiTransport,
140    url: &str,
141    body: &[u8],
142    content_type: &str,
143    retry: Option<&Retry>,
144) -> Result<Vec<u8>, PkiTransportError> {
145    let Some(retry) = retry else {
146        return transport.post(url, body, content_type);
147    };
148    let policy = retry.policy;
149    let first = (retry.clock)();
150    for attempt in 1..=policy.n1 {
151        let sent = (retry.clock)();
152        if let Ok(response) = transport.post(url, body, content_type) {
153            return Ok(response);
154        }
155        let resend = sent + policy.th1;
156        if attempt == policy.n1 || resend >= first + policy.th2 {
157            return Err(PkiTransportError(format!(
158                "POST {url}: no response after {attempt} transmissions"
159            )));
160        }
161        (retry.sleep)((resend - (retry.clock)()).max(0.0));
162    }
163    Err(PkiTransportError(format!(
164        "POST {url}: no transmission allowed (n1 = {})",
165        policy.n1
166    )))
167}