dinio_sdk/ops/certificates.rs
1//! Certificates addressed by a host name they cover, instead of uuid.
2
3use uuid::Uuid;
4
5use crate::client::Client;
6use crate::error::{Error, Result};
7use crate::models::Certificate;
8
9/// A certificate by uuid, or by a host name it covers (as Relay would pick it).
10///
11/// # Errors
12///
13/// * [`Error::NotFound`] if no visible certificate covers the name.
14/// * [`Error::InvalidInput`] if several do; the message lists their uuids.
15/// * Any error of [`Certificates::get`](crate::api::Certificates::get) or
16/// [`Certificates::covering`](crate::api::Certificates::covering).
17///
18/// # Examples
19///
20/// ```no_run
21/// # async fn example(client: &dinio_sdk::Client) -> dinio_sdk::Result<()> {
22/// let cert = dinio_sdk::ops::find_certificate(client, "www.example.com").await?;
23/// println!("expires at {}", cert.valid_to);
24/// # Ok(())
25/// # }
26/// ```
27pub async fn find_certificate(client: &Client, reference: &str) -> Result<Certificate> {
28 let reference = reference.trim();
29 if let Ok(uuid) = reference.parse::<Uuid>() {
30 return client.certificates().get(uuid).await;
31 }
32 let mut found = client.certificates().covering(reference).await?;
33 match found.len() {
34 0 => Err(Error::NotFound(format!(
35 "no certificate you can access covers {reference}"
36 ))),
37 1 => Ok(found.remove(0)),
38 _ => {
39 let ids: Vec<String> = found.iter().map(|c| c.uuid.to_string()).collect();
40 Err(Error::InvalidInput(format!(
41 "several certificates cover {reference} ({}); pick one by uuid",
42 ids.join(", ")
43 )))
44 }
45 }
46}