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
use std::sync::Arc;
use std::time::Duration;

use async_acme::cache::AcmeCache;
use async_trait::async_trait;
use bonsaidb_core::arc_bytes::serde::Bytes;
use bonsaidb_core::connection::AsyncConnection;
use bonsaidb_core::define_basic_unique_mapped_view;
use bonsaidb_core::document::{CollectionDocument, Emit, KeyId};
use bonsaidb_core::schema::{Collection, SerializedCollection};
use serde::{Deserialize, Serialize};

use crate::{Backend, CustomServer, Error};

#[derive(Clone, Debug, Serialize, Deserialize, Collection)]
#[collection(name = "acme-accounts", authority = "khonsulabs", views = [AcmeAccountByContacts])]
#[collection(encryption_key = Some(KeyId::Master), encryption_optional, core = bonsaidb_core)]
pub struct AcmeAccount {
    pub contacts: Vec<String>,
    pub data: Bytes,
}

define_basic_unique_mapped_view!(
    AcmeAccountByContacts,
    AcmeAccount,
    1,
    "by-contacts",
    String,
    |document: CollectionDocument<AcmeAccount>| {
        document
            .header
            .emit_key(document.contents.contacts.join(";"))
    }
);

#[async_trait]
impl<B: Backend> AcmeCache for CustomServer<B> {
    type Error = Error;

    async fn read_account(&self, contacts: &[&str]) -> Result<Option<Vec<u8>>, Self::Error> {
        let db = self.hosted().await;
        let contact = db
            .view::<AcmeAccountByContacts>()
            .with_key(&contacts.join(";"))
            .query_with_collection_docs()
            .await?
            .documents
            .into_iter()
            .next();

        if let Some((_, contact)) = contact {
            Ok(Some(contact.contents.data.into_vec()))
        } else {
            Ok(None)
        }
    }

    async fn write_account(&self, contacts: &[&str], contents: &[u8]) -> Result<(), Self::Error> {
        let db = self.hosted().await;
        let mapped_account = db
            .view::<AcmeAccountByContacts>()
            .with_key(&contacts.join(";"))
            .query_with_collection_docs()
            .await?
            .documents
            .into_iter()
            .next();
        if let Some((_, mut account)) = mapped_account {
            account.contents.data = Bytes::from(contents);
            account.update_async(&db).await?;
        } else {
            AcmeAccount {
                contacts: contacts.iter().map(|&c| c.to_string()).collect(),
                data: Bytes::from(contents),
            }
            .push_into_async(&db)
            .await?;
        }

        Ok(())
    }

    async fn write_certificate(
        &self,
        _domains: &[String],
        _directory_url: &str,
        key_pem: &str,
        certificate_pem: &str,
    ) -> Result<(), Self::Error> {
        self.install_pem_certificate(certificate_pem.as_bytes(), key_pem.as_bytes())
            .await
    }
}

impl<B: Backend> CustomServer<B> {
    pub(crate) async fn update_acme_certificates(&self) -> Result<(), Error> {
        loop {
            {
                let key = self.data.primary_tls_key.lock().clone();
                while async_acme::rustls_helper::duration_until_renewal_attempt(key.as_deref(), 0)
                    > Duration::from_secs(24 * 60 * 60 * 14)
                {
                    tokio::time::sleep(Duration::from_secs(60 * 60)).await;
                }
            }

            log::info!(
                "requesting new tls certificate for {}",
                self.data.primary_domain
            );
            let domains = vec![self.data.primary_domain.clone()];
            async_acme::rustls_helper::order(
                |domain, key| {
                    let mut auth_keys = self.data.alpn_keys.lock();
                    auth_keys.insert(domain, Arc::new(key));
                    Ok(())
                },
                &self.data.acme.directory,
                &domains,
                Some(self),
                &self
                    .data
                    .acme
                    .contact_email
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>(),
            )
            .await?;
        }
    }
}