Skip to main content

hyprstream_core/account/
dns.rs

1//! The DNS management interface (epic #1158, ticket #1162 / Phase A3).
2//!
3//! hyprstream **defines** this interface; it does **not** depend on any specific
4//! DNS implementation. Managed DNS (PowerDNS, Route53, Cloudflare, a hand-rolled
5//! RFC 2136 client, an out-of-process HTTP webhook, …) is a *product layer
6//! above* hyprstream — if this crate ever required a particular DNS server,
7//! self-hosters could not run it.
8//!
9//! Two jobs flow through this trait:
10//!
11//! 1. **ACME DNS-01 challenge responses** — publish/delete a TXT record at the
12//!    `_acme-challenge.<apex>` owner name so a public CA can validate the
13//!    `*.<apex>` wildcard certificate.
14//! 2. **Wildcard address records** — publish wildcard A/AAAA for the delegated
15//!    zone so `alice.<apex>` resolves to the hyprstream node. The wildcard
16//!    covers **exactly one** label (the A2 depth invariant; see
17//!    [`crate::account::zone`]).
18//!
19//! The credential a deployment hands to its `DnsProvider` implementation must be
20//! **zone-scoped** — able to write records only inside the delegated account
21//! zone and nowhere else. The plan is explicit: do not hand a zone-wide DNS
22//! credential to the ACME client.
23
24use std::fmt;
25use std::net::{Ipv4Addr, Ipv6Addr};
26
27use async_trait::async_trait;
28use thiserror::Error;
29
30use super::zone::AccountZone;
31
32/// A DNS operation failed. Implementations wrap their backend's native error.
33#[derive(Debug, Error)]
34pub enum DnsError {
35    /// The configured credential is missing or refused.
36    #[error("DNS provider is unconfigured or unauthorized for {0}: {1}")]
37    Unconfigured(String, String),
38    /// The backend returned an error.
39    #[error("DNS backend error: {0}")]
40    Backend(String),
41    /// The caller asked for an operation outside the delegated zone.
42    #[error("owner name {0} is outside the delegated account zone")]
43    OutOfZone(String),
44}
45
46/// The interface a deployment's DNS management layer implements.
47///
48/// Implementations live **outside** this crate (metal repo / product layer).
49/// [`UnconfiguredDnsProvider`] is the in-crate fail-closed default used when a
50/// deployment has not wired one up: every operation returns
51/// [`DnsError::Unconfigured`], so the ACME DNS-01 issuance path fails loudly
52/// rather than silently no-op'ing or inventing records.
53#[async_trait]
54pub trait DnsProvider: Send + Sync {
55    /// Human-readable backend identifier (e.g. `"unconfigured"`, `"powerdns"`,
56    /// `"route53"`). Used in logs and the expiry alarm.
57    fn backend(&self) -> &'static str;
58
59    /// Publish a TXT record at `owner` (a fully-qualified name, no trailing
60    /// dot) with `value` for the ACME DNS-01 challenge. `ttl` is a hint in
61    /// seconds; backends may clamp. The record must be retrievable by public
62    /// resolvers within ~minutes.
63    ///
64    /// Implementations MUST reject `owner` values outside `zone` (the delegated
65    /// account zone) with [`DnsError::OutOfZone`].
66    async fn publish_txt(
67        &self,
68        zone: &AccountZone,
69        owner: &str,
70        value: &str,
71        ttl: u32,
72    ) -> Result<(), DnsError>;
73
74    /// Delete the TXT record previously published by [`Self::publish_txt`].
75    /// Must be idempotent (deleting a record that is already gone is success).
76    async fn delete_txt(
77        &self,
78        zone: &AccountZone,
79        owner: &str,
80        value: &str,
81    ) -> Result<(), DnsError>;
82
83    /// Publish the wildcard A record (`*.<apex>`) for the delegated zone. The
84    /// record covers exactly one label — `alice.<apex>` resolves, but
85    /// `a.b.<apex>` does not.
86    async fn publish_wildcard_a(
87        &self,
88        zone: &AccountZone,
89        target: Ipv4Addr,
90        ttl: u32,
91    ) -> Result<(), DnsError>;
92
93    /// Publish the wildcard AAAA record (`*.<apex>`) for the delegated zone.
94    async fn publish_wildcard_aaaa(
95        &self,
96        zone: &AccountZone,
97        target: Ipv6Addr,
98        ttl: u32,
99    ) -> Result<(), DnsError>;
100}
101
102/// Fail-closed no-op provider used when a deployment wires no DNS backend.
103///
104/// Every operation returns [`DnsError::Unconfigured`]. This is the sane-degrade
105/// behavior at the DNS layer: DNS-01 wildcard issuance cannot proceed without a
106/// real backend, and silent success would leave the deployment serving a
107/// self-signed cert (or none) under a zone it never proved control of.
108#[derive(Debug, Default, Clone, Copy)]
109pub struct UnconfiguredDnsProvider;
110
111impl UnconfiguredDnsProvider {
112    pub const fn new() -> Self {
113        Self
114    }
115}
116
117#[async_trait]
118impl DnsProvider for UnconfiguredDnsProvider {
119    fn backend(&self) -> &'static str {
120        "unconfigured"
121    }
122
123    async fn publish_txt(
124        &self,
125        _zone: &AccountZone,
126        owner: &str,
127        _value: &str,
128        _ttl: u32,
129    ) -> Result<(), DnsError> {
130        Err(DnsError::Unconfigured(
131            owner.to_owned(),
132            "no DNS provider wired up by the deployment".to_owned(),
133        ))
134    }
135
136    async fn delete_txt(
137        &self,
138        _zone: &AccountZone,
139        owner: &str,
140        _value: &str,
141    ) -> Result<(), DnsError> {
142        Err(DnsError::Unconfigured(
143            owner.to_owned(),
144            "no DNS provider wired up by the deployment".to_owned(),
145        ))
146    }
147
148    async fn publish_wildcard_a(
149        &self,
150        zone: &AccountZone,
151        _target: Ipv4Addr,
152        _ttl: u32,
153    ) -> Result<(), DnsError> {
154        Err(DnsError::Unconfigured(
155            zone.wildcard_domain().to_owned(),
156            "no DNS provider wired up by the deployment".to_owned(),
157        ))
158    }
159
160    async fn publish_wildcard_aaaa(
161        &self,
162        zone: &AccountZone,
163        _target: Ipv6Addr,
164        _ttl: u32,
165    ) -> Result<(), DnsError> {
166        Err(DnsError::Unconfigured(
167            zone.wildcard_domain().to_owned(),
168            "no DNS provider wired up by the deployment".to_owned(),
169        ))
170    }
171}
172
173impl fmt::Display for UnconfiguredDnsProvider {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        f.write_str("unconfigured")
176    }
177}
178
179#[cfg(test)]
180#[allow(clippy::unwrap_used)]
181mod tests {
182    use super::*;
183
184    #[tokio::test]
185    async fn unconfigured_fails_closed() {
186        let p = UnconfiguredDnsProvider::new();
187        let z = AccountZone::new("acct.example.com").unwrap();
188        let owner = z.dns01_validation_name();
189        assert!(matches!(
190            p.publish_txt(&z, &owner, "token", 60).await,
191            Err(DnsError::Unconfigured(_, _))
192        ));
193        assert!(matches!(
194            p.delete_txt(&z, &owner, "token").await,
195            Err(DnsError::Unconfigured(_, _))
196        ));
197        assert!(matches!(
198            p.publish_wildcard_a(&z, "127.0.0.1".parse().unwrap(), 60)
199                .await,
200            Err(DnsError::Unconfigured(_, _))
201        ));
202        assert!(matches!(
203            p.publish_wildcard_aaaa(&z, "::1".parse().unwrap(), 60)
204                .await,
205            Err(DnsError::Unconfigured(_, _))
206        ));
207        assert_eq!(p.backend(), "unconfigured");
208    }
209}