1use crate::utils::build_caa;
2use crate::{
3 DnsRecord, DnsRecordType, Error, IntoFqdn, MXRecord, SRVRecord,
4 http::{HttpClient, HttpClientBuilder},
5 utils::strip_origin_from_name,
6};
7use serde::{Deserialize, Serialize};
8use std::{
9 borrow::Cow,
10 net::{Ipv4Addr, Ipv6Addr},
11 time::Duration,
12};
13
14const LIST_PAGE_SIZE: u32 = 200;
15
16#[derive(Clone)]
17pub struct DigitalOceanProvider {
18 client: HttpClient,
19 endpoint: Cow<'static, str>,
20}
21
22#[derive(Deserialize, Serialize, Clone, Debug)]
23pub struct ListDomainRecord {
24 domain_records: Vec<DomainRecord>,
25 #[serde(default)]
26 links: ListLinks,
27}
28
29#[derive(Deserialize, Serialize, Clone, Debug, Default)]
30pub struct ListLinks {
31 #[serde(default)]
32 pages: ListPages,
33}
34
35#[derive(Deserialize, Serialize, Clone, Debug, Default)]
36pub struct ListPages {
37 #[serde(default)]
38 next: Option<String>,
39}
40
41#[derive(Deserialize, Serialize, Clone, Debug)]
42pub struct UpdateDomainRecord<'a> {
43 ttl: u32,
44 name: &'a str,
45 #[serde(flatten)]
46 data: RecordData,
47}
48
49#[derive(Deserialize, Serialize, Clone, Debug)]
50pub struct DomainRecord {
51 id: i64,
52 ttl: u32,
53 name: String,
54 #[serde(flatten)]
55 data: RecordData,
56}
57
58#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
59#[serde(tag = "type")]
60#[allow(clippy::upper_case_acronyms)]
61pub enum RecordData {
62 A {
63 data: Ipv4Addr,
64 },
65 AAAA {
66 data: Ipv6Addr,
67 },
68 CNAME {
69 data: String,
70 },
71 NS {
72 data: String,
73 },
74 MX {
75 data: String,
76 priority: u16,
77 },
78 TXT {
79 data: String,
80 },
81 SRV {
82 data: String,
83 priority: u16,
84 port: u16,
85 weight: u16,
86 },
87 CAA {
88 data: String,
89 flags: u8,
90 tag: String,
91 },
92}
93
94#[derive(Serialize, Debug)]
95pub struct Query<'a> {
96 name: &'a str,
97 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
98 record_type: Option<&'static str>,
99}
100
101impl DigitalOceanProvider {
102 pub(crate) fn new(auth_token: impl AsRef<str>, timeout: Option<Duration>) -> Self {
103 let client = HttpClientBuilder::default()
104 .with_header("Authorization", format!("Bearer {}", auth_token.as_ref()))
105 .with_timeout(timeout)
106 .build();
107 Self {
108 client,
109 endpoint: crate::config::digitalocean_endpoint(),
110 }
111 }
112
113 #[cfg(test)]
114 pub(crate) fn with_endpoint(self, endpoint: impl Into<Cow<'static, str>>) -> Self {
115 Self {
116 endpoint: endpoint.into(),
117 ..self
118 }
119 }
120
121 pub(crate) async fn set_rrset(
122 &self,
123 name: impl IntoFqdn<'_>,
124 record_type: DnsRecordType,
125 ttl: u32,
126 records: Vec<DnsRecord>,
127 origin: impl IntoFqdn<'_>,
128 ) -> crate::Result<()> {
129 reject_unsupported(record_type)?;
130 let name = name.into_name().into_owned();
131 let domain = origin.into_name().into_owned();
132 let subdomain = strip_origin_from_name(&name, &domain, None);
133 let desired = build_record_data(record_type, records)?;
134 let existing = self
135 .list_at(&domain, &name, &subdomain, record_type)
136 .await?;
137
138 let mut existing_pool: Vec<DomainRecord> = existing;
139 let mut to_add: Vec<RecordData> = Vec::new();
140
141 for data in desired {
142 if let Some(idx) = existing_pool.iter().position(|r| r.data == data) {
143 existing_pool.swap_remove(idx);
144 } else {
145 to_add.push(data);
146 }
147 }
148
149 for entry in existing_pool {
150 self.delete_record(&domain, entry.id).await?;
151 }
152 for data in to_add {
153 self.create_record(&domain, &subdomain, ttl, data).await?;
154 }
155 Ok(())
156 }
157
158 pub(crate) async fn add_to_rrset(
159 &self,
160 name: impl IntoFqdn<'_>,
161 record_type: DnsRecordType,
162 ttl: u32,
163 records: Vec<DnsRecord>,
164 origin: impl IntoFqdn<'_>,
165 ) -> crate::Result<()> {
166 reject_unsupported(record_type)?;
167 if records.is_empty() {
168 return Ok(());
169 }
170 let name = name.into_name().into_owned();
171 let domain = origin.into_name().into_owned();
172 let subdomain = strip_origin_from_name(&name, &domain, None);
173 let desired = build_record_data(record_type, records)?;
174 let existing = self
175 .list_at(&domain, &name, &subdomain, record_type)
176 .await?;
177
178 for data in desired {
179 if existing.iter().any(|r| r.data == data) {
180 continue;
181 }
182 self.create_record(&domain, &subdomain, ttl, data).await?;
183 }
184 Ok(())
185 }
186
187 pub(crate) async fn remove_from_rrset(
188 &self,
189 name: impl IntoFqdn<'_>,
190 record_type: DnsRecordType,
191 records: Vec<DnsRecord>,
192 origin: impl IntoFqdn<'_>,
193 ) -> crate::Result<()> {
194 reject_unsupported(record_type)?;
195 if records.is_empty() {
196 return Ok(());
197 }
198 let name = name.into_name().into_owned();
199 let domain = origin.into_name().into_owned();
200 let subdomain = strip_origin_from_name(&name, &domain, None);
201 let to_remove = build_record_data(record_type, records)?;
202 let existing = self
203 .list_at(&domain, &name, &subdomain, record_type)
204 .await?;
205
206 for data in to_remove {
207 if let Some(entry) = existing.iter().find(|r| r.data == data) {
208 self.delete_record(&domain, entry.id).await?;
209 }
210 }
211 Ok(())
212 }
213
214 pub(crate) async fn list_rrset(
215 &self,
216 name: impl IntoFqdn<'_>,
217 record_type: DnsRecordType,
218 origin: impl IntoFqdn<'_>,
219 ) -> crate::Result<Vec<DnsRecord>> {
220 let name = name.into_name().into_owned();
221 let domain = origin.into_name().into_owned();
222 let subdomain = strip_origin_from_name(&name, &domain, None);
223 let listed = self
224 .list_at(&domain, &name, &subdomain, record_type)
225 .await?;
226 listed.into_iter().map(|r| r.data.try_into()).collect()
227 }
228
229 async fn list_at(
230 &self,
231 domain: &str,
232 name: &str,
233 subdomain: &str,
234 record_type: DnsRecordType,
235 ) -> crate::Result<Vec<DomainRecord>> {
236 let mut out: Vec<DomainRecord> = Vec::new();
237 let mut page: u32 = 1;
238 loop {
239 let url = format!(
240 "{}/v2/domains/{domain}/records?{}&per_page={LIST_PAGE_SIZE}&page={page}",
241 self.endpoint,
242 Query::name_and_type(name, record_type).serialize()
243 );
244 let response: ListDomainRecord = self.client.get(url).send_with_retry(3).await?;
245 let returned = response.domain_records.len() as u32;
246 for record in response.domain_records {
247 if record.name == subdomain && record.data.is_type(record_type) {
248 out.push(record);
249 }
250 }
251 if response.links.pages.next.is_none() || returned < LIST_PAGE_SIZE {
252 break;
253 }
254 page += 1;
255 }
256 Ok(out)
257 }
258
259 async fn create_record(
260 &self,
261 domain: &str,
262 subdomain: &str,
263 ttl: u32,
264 data: RecordData,
265 ) -> crate::Result<()> {
266 self.client
267 .post(format!("{}/v2/domains/{domain}/records", self.endpoint))
268 .with_body(UpdateDomainRecord {
269 ttl,
270 name: subdomain,
271 data,
272 })?
273 .send_raw()
274 .await
275 .map(|_| ())
276 }
277
278 async fn delete_record(&self, domain: &str, record_id: i64) -> crate::Result<()> {
279 self.client
280 .delete(format!(
281 "{}/v2/domains/{domain}/records/{record_id}",
282 self.endpoint
283 ))
284 .send_raw()
285 .await
286 .map(|_| ())
287 }
288}
289
290fn reject_unsupported(record_type: DnsRecordType) -> crate::Result<()> {
291 if record_type == DnsRecordType::TLSA {
292 return Err(Error::Unsupported(
293 "TLSA records are not supported by DigitalOcean".to_string(),
294 ));
295 }
296 Ok(())
297}
298
299fn build_record_data(
300 expected_type: DnsRecordType,
301 records: Vec<DnsRecord>,
302) -> crate::Result<Vec<RecordData>> {
303 let mut out = Vec::with_capacity(records.len());
304 for record in records {
305 if record.as_type() != expected_type {
306 return Err(Error::Api(format!(
307 "RRSet record type mismatch: expected {}, got {}",
308 expected_type.as_str(),
309 record.as_type().as_str(),
310 )));
311 }
312 out.push(RecordData::try_from(record).map_err(|err| Error::Api(err.to_string()))?);
313 }
314 Ok(out)
315}
316
317fn ensure_absolute(host: String) -> String {
318 if host.is_empty() || host.ends_with('.') {
319 host
320 } else {
321 format!("{host}.")
322 }
323}
324
325impl RecordData {
326 fn is_type(&self, record_type: DnsRecordType) -> bool {
327 matches!(
328 (self, record_type),
329 (RecordData::A { .. }, DnsRecordType::A)
330 | (RecordData::AAAA { .. }, DnsRecordType::AAAA)
331 | (RecordData::CNAME { .. }, DnsRecordType::CNAME)
332 | (RecordData::NS { .. }, DnsRecordType::NS)
333 | (RecordData::MX { .. }, DnsRecordType::MX)
334 | (RecordData::TXT { .. }, DnsRecordType::TXT)
335 | (RecordData::SRV { .. }, DnsRecordType::SRV)
336 | (RecordData::CAA { .. }, DnsRecordType::CAA)
337 )
338 }
339}
340
341impl<'a> Query<'a> {
342 pub fn name(name: impl Into<&'a str>) -> Self {
343 Self {
344 name: name.into(),
345 record_type: None,
346 }
347 }
348
349 pub fn name_and_type(name: impl Into<&'a str>, record_type: DnsRecordType) -> Self {
350 Self {
351 name: name.into(),
352 record_type: Some(record_type.as_str()),
353 }
354 }
355
356 pub fn serialize(&self) -> String {
357 serde_urlencoded::to_string(self)
358 .expect("query parameters are statically serializable to urlencoding")
359 }
360}
361
362impl TryFrom<DnsRecord> for RecordData {
363 type Error = &'static str;
364
365 fn try_from(record: DnsRecord) -> Result<Self, Self::Error> {
366 match record {
367 DnsRecord::A(content) => Ok(RecordData::A { data: content }),
368 DnsRecord::AAAA(content) => Ok(RecordData::AAAA { data: content }),
369 DnsRecord::CNAME(content) => Ok(RecordData::CNAME {
370 data: ensure_absolute(content),
371 }),
372 DnsRecord::NS(content) => Ok(RecordData::NS {
373 data: ensure_absolute(content),
374 }),
375 DnsRecord::MX(mx) => Ok(RecordData::MX {
376 data: ensure_absolute(mx.exchange),
377 priority: mx.priority,
378 }),
379 DnsRecord::TXT(content) => Ok(RecordData::TXT { data: content }),
380 DnsRecord::SRV(srv) => Ok(RecordData::SRV {
381 data: ensure_absolute(srv.target),
382 priority: srv.priority,
383 weight: srv.weight,
384 port: srv.port,
385 }),
386 DnsRecord::TLSA(_) => Err("TLSA records are not supported by DigitalOcean"),
387 DnsRecord::CAA(caa) => {
388 let (flags, tag, value) = caa.decompose();
389 Ok(RecordData::CAA {
390 data: value,
391 flags,
392 tag,
393 })
394 }
395 DnsRecord::HTTPS(_) => Err("HTTPS records are not supported by DigitalOcean"),
396 }
397 }
398}
399
400impl TryFrom<RecordData> for DnsRecord {
401 type Error = Error;
402
403 fn try_from(data: RecordData) -> crate::Result<Self> {
404 Ok(match data {
405 RecordData::A { data } => DnsRecord::A(data),
406 RecordData::AAAA { data } => DnsRecord::AAAA(data),
407 RecordData::CNAME { data } => DnsRecord::CNAME(data),
408 RecordData::NS { data } => DnsRecord::NS(data),
409 RecordData::MX { data, priority } => DnsRecord::MX(MXRecord {
410 exchange: data,
411 priority,
412 }),
413 RecordData::TXT { data } => DnsRecord::TXT(data),
414 RecordData::SRV {
415 data,
416 priority,
417 port,
418 weight,
419 } => DnsRecord::SRV(SRVRecord {
420 priority,
421 weight,
422 port,
423 target: data,
424 }),
425 RecordData::CAA { data, flags, tag } => DnsRecord::CAA(build_caa(flags, &tag, &data)?),
426 })
427 }
428}