Skip to main content

hyprstream_core/account/
tls.rs

1//! DNS-01 wildcard certificate issuance for the account zone
2//! (epic #1158, ticket #1162 / A3).
3//!
4//! `rustls-acme`, which the crate already uses for HTTP-01/TLS-ALPN-01,
5//! **only fulfills TLS-ALPN-01 challenges** — its `AcmeState` cannot perform
6//! DNS-01, and DNS-01 is the *only* validation method public CAs accept for a
7//! wildcard identifier (`*.<apex>`). Wildcards cannot use HTTP-01.
8//!
9//! hyprstream therefore defines the issuance path itself, **behind a trait**:
10//! [`WildcardCertIssuer`] owns the ACME DNS-01 dance (order → authorization →
11//! publish TXT via the [`DnsProvider`](super::dns::DnsProvider) seam → poll →
12//! finalize), and returns a DER-encoded cert+key. The concrete ACME-directory
13//! client and the DNS backend are both product-layer concerns above this crate —
14//! hyprstream must not depend on a specific DNS server (the self-hoster rule).
15//!
16//! What hyprstream *does* own here is:
17//! - the shape of the request (zone, zone-scoped credential, ACME directory),
18//! - the **sane-degrade** when no zone is configured (clear error, no panic,
19//!   no synthesized default),
20//! - the renewal + expiry-alarm plumbing (see [`super::renewal`]).
21//!
22//! Converting an [`IssuedCert`] into a live `rustls::ServerConfig` for the
23//! account HTTP face is the job of B3 (the credential-free origin, #1165); A3
24//! stops at the issuance contract and its monitoring.
25
26use async_trait::async_trait;
27use thiserror::Error;
28use time::OffsetDateTime;
29use tokio::sync::watch;
30use zeroize::Zeroizing;
31
32use super::config::AccountZoneConfig;
33use super::dns::{DnsError, DnsProvider};
34use super::zone::{AccountZone, AccountZoneError};
35
36/// A DER-encoded wildcard certificate + its private key, freshly issued.
37///
38/// The key is wrapped in `Zeroizing` so it is cleared on drop.
39#[derive(Debug, Clone)]
40pub struct IssuedCert {
41    /// End-entity certificate DER (leaf).
42    pub cert_der: Vec<u8>,
43    /// Optional intermediate issuer DERs.
44    pub chain_der: Vec<Vec<u8>>,
45    /// The private key DER (PKCS#8 or SEC1).
46    pub key_der: Zeroizing<Vec<u8>>,
47    /// The certificate's NotAfter, for renewal scheduling + the expiry alarm.
48    pub not_after: OffsetDateTime,
49    /// The name this cert was issued for (`*.<apex>`).
50    pub san: String,
51}
52
53/// An error from the DNS-01 wildcard issuance path.
54#[derive(Debug, Error)]
55pub enum IssuanceError {
56    /// The deployment configured no account zone / credential. **Sane-degrade**.
57    #[error("account zone DNS-01 issuance not provisioned: {0}")]
58    Unprovisioned(String),
59    /// The configured zone name was invalid.
60    #[error(transparent)]
61    InvalidZone(#[from] AccountZoneError),
62    /// The DNS backend failed to publish/clean the challenge TXT record.
63    #[error(transparent)]
64    Dns(#[from] DnsError),
65    /// The issuer backend returned an ACME/protocol error.
66    #[error("ACME DNS-01 issuance failed for {san}: {reason}")]
67    Backend { san: String, reason: String },
68}
69
70/// The interface a deployment's DNS-01 wildcard issuer implements.
71///
72/// Implementations live **outside** this crate (metal repo / product layer):
73/// they drive an ACME directory against `*.<apex>`, publish the `_acme-challenge`
74/// TXT record via the supplied [`DnsProvider`] (so the same zone-scoped
75/// credential plumbing is reused), poll the authorization to completion,
76/// finalize with a CSR, and return the resulting [`IssuedCert`].
77///
78/// [`NullWildcardCertIssuer`] is the in-crate fail-closed default.
79#[async_trait]
80pub trait WildcardCertIssuer: Send + Sync {
81    /// Issue (or renew) the wildcard certificate for `zone`. `dns` is the
82    /// deployment's DNS provider; `cfg` carries the ACME directory, contact,
83    /// and zone-scoped credential.
84    async fn issue(
85        &self,
86        zone: &AccountZone,
87        cfg: &AccountZoneConfig,
88        dns: &dyn DnsProvider,
89    ) -> Result<IssuedCert, IssuanceError>;
90}
91
92/// Fail-closed issuer for deployments that wired no ACME-DNS-01 backend.
93///
94/// Every call returns [`IssuanceError::Unprovisioned`]. The process keeps
95/// running on whatever TLS materials it already has (self-signed or operator
96/// `files`), and account minting surfaces the missing zone; nothing panics and
97/// no certificate is synthesized.
98#[derive(Debug, Default, Clone, Copy)]
99pub struct NullWildcardCertIssuer;
100
101#[async_trait]
102impl WildcardCertIssuer for NullWildcardCertIssuer {
103    async fn issue(
104        &self,
105        zone: &AccountZone,
106        _cfg: &AccountZoneConfig,
107        _dns: &dyn DnsProvider,
108    ) -> Result<IssuedCert, IssuanceError> {
109        Err(IssuanceError::Unprovisioned(format!(
110            "no ACME DNS-01 wildcard issuer wired up by the deployment; cannot obtain a certificate for {}",
111            zone.wildcard_domain()
112        )))
113    }
114}
115
116/// Validate that the deployment has provisioned DNS-01 wildcard issuance.
117///
118/// Returns the resolved [`AccountZone`] on success, or an
119/// [`IssuanceError::Unprovisioned`] / [`IssuanceError::InvalidZone`] otherwise.
120/// This is the sane-degrade check the serving/renewal layers call before
121/// attempting issuance — it never panics and never synthesizes a zone.
122pub fn require_provisioned(cfg: &AccountZoneConfig) -> Result<AccountZone, IssuanceError> {
123    if !cfg.is_configured() {
124        return Err(IssuanceError::Unprovisioned(
125            "no [account] zone configured — did:web minting and wildcard DNS-01 TLS issuance are disabled. Set [account] zone to enable.".to_owned(),
126        ));
127    }
128    if !cfg.dns01_ready() {
129        return Err(IssuanceError::Unprovisioned(
130            "account zone is set but [account] dns01_credential is missing — wildcard DNS-01 TLS issuance is disabled. Set dns01_credential (zone-scoped) to enable.".to_owned(),
131        ));
132    }
133    Ok(cfg.resolve_zone()?)
134}
135
136/// A live, hot-swappable handle to the currently-served account-zone cert.
137///
138/// The renewal task pushes freshly issued [`IssuedCert`]s into the underlying
139/// `watch::Sender`; consumers read [`CertHandle::current`] for the latest. This
140/// is the total-outage surface the expiry alarm watches — one cert failing
141/// breaks all account resolution for the deployment.
142#[derive(Clone)]
143pub struct CertHandle {
144    rx: watch::Receiver<Option<IssuedCert>>,
145}
146
147impl CertHandle {
148    /// Create a handle plus the sender the renewal task writes to.
149    pub fn channel() -> (watch::Sender<Option<IssuedCert>>, Self) {
150        let (tx, rx) = watch::channel(None);
151        (tx, Self { rx })
152    }
153
154    /// The currently-served cert, if one has been issued.
155    pub fn current(&self) -> Option<IssuedCert> {
156        self.rx.borrow().clone()
157    }
158
159    /// The cert NotAfter, if a cert has been issued.
160    pub fn not_after(&self) -> Option<OffsetDateTime> {
161        self.rx.borrow().as_ref().map(|c| c.not_after)
162    }
163}
164
165#[cfg(test)]
166#[allow(clippy::unwrap_used)]
167mod tests {
168    use super::*;
169    use crate::account::dns::UnconfiguredDnsProvider;
170
171    fn cfg(zone: Option<&str>, cred: Option<&str>) -> AccountZoneConfig {
172        AccountZoneConfig {
173            zone: zone.map(str::to_owned),
174            dns01_credential: cred.map(str::to_owned),
175            ..Default::default()
176        }
177    }
178
179    #[tokio::test]
180    async fn null_issuer_fails_closed() {
181        let zone = AccountZone::new("acct.example.com").unwrap();
182        let issuer = NullWildcardCertIssuer;
183        let cfg = cfg(Some("acct.example.com"), Some("ref:tok"));
184        let dns = UnconfiguredDnsProvider::new();
185        let err = issuer.issue(&zone, &cfg, &dns).await.unwrap_err();
186        assert!(matches!(err, IssuanceError::Unprovisioned(_)));
187    }
188
189    #[test]
190    fn require_provisioned_degrades_sanely() {
191        // No zone.
192        assert!(matches!(
193            require_provisioned(&cfg(None, None)),
194            Err(IssuanceError::Unprovisioned(_))
195        ));
196        // Zone but no credential.
197        assert!(matches!(
198            require_provisioned(&cfg(Some("acct.example.com"), None)),
199            Err(IssuanceError::Unprovisioned(_))
200        ));
201        // Both → ok.
202        let z = require_provisioned(&cfg(Some("acct.example.com"), Some("ref:tok"))).unwrap();
203        assert_eq!(z.wildcard_domain(), "*.acct.example.com");
204    }
205}