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
use crate::account::Account;
use crate::error::*;
use crate::helpers::Identifier;
use crate::helpers::*;
use crate::jws::Jwk;
use crate::order::Order;
use openssl::hash::hash;
use openssl::hash::MessageDigest;
use serde::Deserialize;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use tracing::debug;
use tracing::field;
use tracing::instrument;
use tracing::Level;
use tracing::Span;

#[derive(Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
/// The status of this authorization.
///
/// Possible values are "pending", "valid", "invalid", "deactivated",
/// "expired", and "revoked".
pub enum AuthorizationStatus {
  Pending,
  Valid,
  Invalid,
  Deactivated,
  Expired,
  Revoked,
}

/// An autorization represents the server's authorization of a certain
/// domain being represented by an account.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Authorization {
  #[serde(skip)]
  pub(crate) account: Option<Arc<Account>>,
  #[serde(skip)]
  pub(crate) url: String,

  /// The identifier (domain) that the account is authorized to represent.
  pub identifier: Identifier,
  /// The status of this authorization.
  pub status: AuthorizationStatus,
  /// The timestamp after which the server will consider this
  /// authorization invalid.
  pub expires: Option<String>,
  /// For pending authorizations, the challenges that the client can
  /// fulfill in order to prove possession of the identifier. For
  /// valid authorizations, the challenge that was validated. For
  /// invalid authorizations, the challenge that was attempted and
  /// failed.
  pub challenges: Vec<Challenge>,
  /// Whether this authorization was created for a wildcard identifier
  /// (domain).
  pub wildcard: Option<bool>,
}

/// The status of this challenge.
///
/// Possible values are "pending", "processing", "valid", and "invalid".
#[derive(Deserialize, Debug, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub enum ChallengeStatus {
  Pending,
  Processing,
  Valid,
  Invalid,
}

/// A challenge represents a means for the server to validate
/// that an account has control over an identifier (domain).
///
/// A challenge can only be acquired through an [`Authorization`].
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Challenge {
  #[serde(skip)]
  pub(crate) account: Option<Arc<Account>>,

  /// The type of challenge encoded in the object.
  pub r#type: String,
  /// The URL to which a response can be posted.
  pub(crate) url: String,
  /// The status of this challenge.
  pub status: ChallengeStatus,
  /// The time at which the server validated this challenge.
  pub validated: Option<String>,

  /// Error that occurred while the server was validating the
  /// challenge, if any.
  pub error: Option<ServerError>,

  /// A random value that uniquely identifies the challenge.
  pub token: Option<String>,
}

impl Order {
  /// Retrieve all of the [`Authorization`]s needed for this order.
  ///
  /// The authorization may already be in a `Valid` state, if an
  /// authorization for this identifier was already completed through
  /// a seperate order.
  #[instrument(level = Level::INFO, name = "acme2::Order::authorizations", err, skip(self), fields(order = %self.url, authorization_urls = ?self.authorization_urls))]
  pub async fn authorizations(&self) -> Result<Vec<Authorization>, Error> {
    let account = self.account.clone().unwrap();
    let directory = account.directory.clone().unwrap();

    let mut authorizations = vec![];

    for authorization_url in self.authorization_urls.clone() {
      let (res, _) = directory
        .authenticated_request::<_, Authorization>(
          &authorization_url,
          "",
          account.private_key.clone().unwrap(),
          Some(account.id.clone()),
        )
        .await?;

      let res: Result<Authorization, Error> = res.into();

      let mut authorization = res?;
      authorization.account = Some(account.clone());
      authorization.url = authorization_url;
      for challenge in &mut authorization.challenges {
        challenge.account = Some(account.clone())
      }
      authorizations.push(authorization)
    }

    Ok(authorizations)
  }
}

impl Authorization {
  /// Get a certain type of challenge to complete.
  ///
  /// Example: `http-01`, or `dns-01`
  pub fn get_challenge(&self, r#type: &str) -> Option<Challenge> {
    for challenge in &self.challenges {
      if challenge.r#type == r#type {
        return Some(challenge.clone());
      }
    }
    None
  }

  /// Update the authorization to match the current server state.
  ///
  /// Most users should use [`Authorization::wait_done`].
  #[instrument(level = Level::DEBUG, name = "acme2::Authorization::poll", err, skip(self), fields(url = ?self.url, status = field::Empty))]
  pub async fn poll(self) -> Result<Authorization, Error> {
    let account = self.account.clone().unwrap();
    let directory = account.directory.clone().unwrap();

    let (res, _) = directory
      .authenticated_request::<_, Authorization>(
        &self.url,
        json!(""),
        account.private_key.clone().unwrap(),
        Some(account.id.clone()),
      )
      .await?;
    let res: Result<Authorization, Error> = res.into();
    let mut authorization = res?;
    authorization.url = self.url.clone();
    authorization.account = Some(account.clone());
    Span::current().record("status", &field::debug(&authorization.status));
    Ok(authorization)
  }

  /// Wait for the authorization to go into a state other than
  /// [`AuthorizationStatus::Pending`].
  ///
  /// This will only happen once one of the challenges in an authorization
  /// is completed. You can use [`Challenge::wait_done`] to wait until
  /// this is the case.
  ///
  /// Will complete immediately if the authorization is already in a
  /// state other than [`AuthorizationStatus::Pending`].
  ///
  /// Specify the interval at which to poll the acme server, and how often to
  /// attempt polling before timing out. Polling should not happen faster than
  /// about every 5 seconds to avoid rate limits in the acme server.
  #[instrument(level = Level::INFO, name = "acme2::Authorization::wait_done", err, skip(self), fields(url = ?self.url))]
  pub async fn wait_done(
    self,
    poll_interval: Duration,
    attempts: usize,
  ) -> Result<Authorization, Error> {
    let mut authorization = self;

    let mut i: usize = 0;

    while authorization.status == AuthorizationStatus::Pending {
      if i >= attempts {
        return Err(Error::MaxAttemptsExceeded);
      }
      debug!(
        { delay = ?poll_interval },
        "Authorization still pending. Waiting to poll."
      );
      tokio::time::sleep(poll_interval).await;
      authorization = authorization.poll().await?;
      i += 1;
    }

    Ok(authorization)
  }
}

impl Challenge {
  /// The key authorization is the token that the HTTP01, or DNS01
  // challenges should be serving for the ACME server to inspect.
  pub fn key_authorization(&self) -> Result<Option<String>, Error> {
    if let Some(token) = self.token.clone() {
      let account = self.account.clone().unwrap();

      let key_authorization = format!(
        "{}.{}",
        token,
        b64(&hash(
          MessageDigest::sha256(),
          &serde_json::to_string(&Jwk::new(
            &account.private_key.clone().unwrap()
          ))?
          .into_bytes()
        )?)
      );

      Ok(Some(key_authorization))
    } else {
      Ok(None)
    }
  }

  /// Initiate validation of the challenge by the ACME server.
  ///
  /// Before calling this method, you should have set up your challenge token
  /// so it is available for the ACME server to check.
  ///
  /// In most cases this will not complete immediately. You should always
  /// call [`Challenge::wait_done`] after this operation to wait until the
  /// ACME server has finished validation.
  #[instrument(level = Level::INFO, name = "acme2::Challenge::validate", err, skip(self), fields(url = ?self.url, status = field::Empty))]
  pub async fn validate(&self) -> Result<Challenge, Error> {
    let account = self.account.clone().unwrap();
    let directory = account.directory.clone().unwrap();

    let (res, _) = directory
      .authenticated_request::<_, Challenge>(
        &self.url,
        json!({}),
        account.private_key.clone().unwrap(),
        Some(account.id.clone()),
      )
      .await?;
    let res: Result<Challenge, Error> = res.into();
    let mut challenge = res?;
    challenge.account = Some(account.clone());
    Span::current().record("status", &field::debug(&challenge.status));

    Ok(challenge)
  }

  /// Update the challenge to match the current server state.
  ///
  /// Most users should use [`Challenge::wait_done`].
  #[instrument(level = Level::DEBUG, name = "acme2::Challenge::poll", err, skip(self), fields(url = ?self.url, status = field::Empty))]
  pub async fn poll(&self) -> Result<Challenge, Error> {
    let account = self.account.clone().unwrap();
    let directory = account.directory.clone().unwrap();

    let (res, _) = directory
      .authenticated_request::<_, Challenge>(
        &self.url,
        json!(""),
        account.private_key.clone().unwrap(),
        Some(account.id.clone()),
      )
      .await?;
    let res: Result<Challenge, Error> = res.into();
    let mut challenge = res?;
    challenge.account = Some(account.clone());
    Span::current().record("status", &field::debug(&challenge.status));
    Ok(challenge)
  }

  /// Wait for the authorization to go into the [`AuthorizationStatus::Valid`]
  /// or [`AuthorizationStatus::Invalid`] state.
  ///
  /// Will complete immediately if the authorization is already
  /// in one of these states.
  ///
  /// Specify the interval at which to poll the acme server, and how often to
  /// attempt polling before timing out. Polling should not happen faster than
  /// about every 5 seconds to avoid rate limits in the acme server.
  #[instrument(level = Level::INFO, name = "acme2::Challenge::wait_done", err, skip(self), fields(url = ?self.url))]
  pub async fn wait_done(
    self,
    poll_interval: Duration,
    attempts: usize,
  ) -> Result<Challenge, Error> {
    let mut challenge = self;

    let mut i: usize = 0;

    while challenge.status == ChallengeStatus::Pending
      || challenge.status == ChallengeStatus::Processing
    {
      if i >= attempts {
        return Err(Error::MaxAttemptsExceeded);
      }
      debug!(
        { delay = ?poll_interval, status = ?challenge.status },
        "Challenge not done. Waiting to poll."
      );
      tokio::time::sleep(poll_interval).await;
      challenge = challenge.poll().await?;
      i += 1;
    }

    Ok(challenge)
  }
}