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
//! HTTP responses which adhere to RFC 8885
//!
//! [RFC 8885][] does not constrain HTTP responses from the ACME service
//! strongly, except that they should contain a [nonce][crate::jose::Nonce].
//!
//! The response type here also implements [`crate::fmt::AcmeFormat`] so that
//! it can be displayed in a form similar to those in [RFC 8885][] while
//! debugging.
//!
//! [RFC 8885]: https://datatracker.ietf.org/doc/html/rfc8555

use std::fmt::Write;

use chrono::{DateTime, Utc};
use http::HeaderMap;
use serde::de::DeserializeOwned;

use crate::fmt::{self, HttpCase};
use crate::jose::Nonce;
use crate::request::Encode;
use crate::AcmeError;
use crate::Url;

/// Helper trait for any type which can be decoded from a
/// response from an ACME server.
///
/// This trait is blanket-implemetned for [`serde::de::DeserializeOwned`]
/// so most types should implement or derive [`serde::Deserialize`]
/// rather than implementing this type.
pub trait Decode: Sized {
    /// Decode an ACME response from a byte slice.
    fn decode(data: &[u8]) -> Result<Self, AcmeError>;
}

impl<T> Decode for T
where
    T: DeserializeOwned,
{
    fn decode(data: &[u8]) -> Result<Self, AcmeError> {
        serde_json::from_slice(data).map_err(AcmeError::de)
    }
}

/// A HTTP response from an ACME service
#[derive(Debug, Clone)]
pub struct Response<T> {
    url: Url,
    status: http::StatusCode,
    headers: http::HeaderMap,
    payload: T,
}

impl<T> Response<T>
where
    T: Decode,
{
    pub(crate) async fn from_decoded_response(
        response: reqwest::Response,
    ) -> Result<Self, AcmeError> {
        let url = response.url().clone().into();
        let status = response.status();
        let headers = response.headers().clone();
        let body = response.bytes().await?;
        let payload: T = T::decode(&body)?;

        Ok(Response {
            url,
            status,
            headers,
            payload,
        })
    }
}

impl<T> Response<T> {
    /// Response [`http::StatusCode`]
    pub fn status(&self) -> http::StatusCode {
        self.status
    }

    /// Destination URL from the original request.
    pub fn url(&self) -> &Url {
        &self.url
    }

    /// The headers returned with this response
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// The seconds to wait for a retry, from now.
    pub fn retry_after(&self) -> Option<std::time::Duration> {
        self.headers()
            .get(http::header::RETRY_AFTER)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| {
                if v.contains("GMT") {
                    DateTime::parse_from_rfc2822(v)
                        .map(|ts| ts.signed_duration_since(Utc::now()))
                        .ok()
                        .and_then(|d| d.to_std().ok())
                } else {
                    v.parse::<u64>().ok().map(std::time::Duration::from_secs)
                }
            })
    }

    /// Get the [`Nonce`] from this response.
    ///
    /// Normally, this is unnecessay, as [`crate::Client`] will automatically handle
    /// and track [`Nonce`] values.
    pub fn nonce(&self) -> Option<Nonce> {
        crate::client::extract_nonce(&self.headers).ok()
    }

    /// The URL from the `Location` HTTP header.
    pub fn location(&self) -> Option<Url> {
        self.headers.get(http::header::LOCATION).map(|value| {
            value
                .to_str()
                .unwrap_or_else(|_| {
                    panic!("valid text encoding in {} header", http::header::LOCATION)
                })
                .parse()
                .unwrap_or_else(|_| panic!("valid URL in {} header", http::header::LOCATION))
        })
    }

    /// The [`mime::Mime`] from the `Content-Type` header.
    pub fn content_type(&self) -> Option<mime::Mime> {
        self.headers.get(http::header::CONTENT_TYPE).map(|v| {
            v.to_str()
                .unwrap_or_else(|_| {
                    panic!(
                        "valid text encoding in {} header",
                        http::header::CONTENT_TYPE
                    )
                })
                .parse()
                .unwrap_or_else(|_| {
                    panic!("valid MIME type in {} header", http::header::CONTENT_TYPE)
                })
        })
    }

    /// The response payload.
    pub fn payload(&self) -> &T {
        &self.payload
    }

    /// Extract just the response payload.
    pub fn into_inner(self) -> T {
        self.payload
    }
}

impl<T> fmt::AcmeFormat for Response<T>
where
    T: Encode,
{
    fn fmt<W: fmt::Write>(&self, f: &mut fmt::IndentWriter<'_, W>) -> fmt::Result {
        writeln!(
            f,
            "HTTP/1.1 {} {}",
            self.status.as_u16(),
            self.status.canonical_reason().unwrap_or("")
        )?;
        for (header, value) in self.headers.iter() {
            writeln!(f, "{}: {}", header.titlecase(), value.to_str().unwrap())?;
        }

        writeln!(f)?;

        write!(f, "{}", self.payload.encode().unwrap())
    }
}