Skip to main content

dns_update/providers/
dnsimple.rs

1/*
2 * Copyright Stalwart Labs LLC See the COPYING
3 * file at the top-level directory of this distribution.
4 *
5 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8 * option. This file may not be copied, modified, or distributed
9 * except according to those terms.
10 */
11
12use crate::{
13    CAARecord, DnsRecord, DnsRecordType, Error, IntoFqdn, KeyValue, MXRecord, SRVRecord,
14    TLSARecord, TlsaCertUsage, TlsaMatching, TlsaSelector,
15    http::{HttpClient, HttpClientBuilder},
16    utils::strip_origin_from_name,
17};
18use serde::{Deserialize, Serialize};
19use std::time::Duration;
20
21const DEFAULT_ENDPOINT: &str = "https://api.dnsimple.com/v2";
22
23#[derive(Clone)]
24pub struct DNSimpleProvider {
25    client: HttpClient,
26    account_id: String,
27    endpoint: String,
28}
29
30#[derive(Deserialize, Debug)]
31pub struct ApiResponse<T> {
32    pub data: T,
33}
34
35#[derive(Deserialize, Debug)]
36pub struct RecordEntry {
37    pub id: i64,
38    pub name: String,
39    #[serde(rename = "type")]
40    pub record_type: String,
41    pub content: String,
42    pub ttl: u32,
43    pub priority: Option<u16>,
44}
45
46#[derive(Serialize, Debug)]
47pub struct CreateRecordParams {
48    pub name: String,
49    #[serde(rename = "type")]
50    pub record_type: String,
51    pub content: String,
52    pub ttl: u32,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub priority: Option<u16>,
55}
56
57#[derive(Serialize, Debug)]
58struct ListRecordsQuery<'a> {
59    name: &'a str,
60    #[serde(rename = "type")]
61    type_filter: &'a str,
62    per_page: u32,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66struct RecordContent {
67    content: String,
68    priority: Option<u16>,
69}
70
71#[derive(Debug, Clone)]
72struct ListedRecord {
73    id: i64,
74    content: RecordContent,
75}
76
77impl DNSimpleProvider {
78    pub(crate) fn new(
79        auth_token: impl AsRef<str>,
80        account_id: impl AsRef<str>,
81        timeout: Option<Duration>,
82    ) -> Self {
83        let client = HttpClientBuilder::default()
84            .with_header("Authorization", format!("Bearer {}", auth_token.as_ref()))
85            .with_timeout(timeout)
86            .build();
87        Self {
88            client,
89            account_id: account_id.as_ref().to_string(),
90            endpoint: DEFAULT_ENDPOINT.to_string(),
91        }
92    }
93
94    #[cfg(test)]
95    pub(crate) fn with_endpoint(self, endpoint: impl AsRef<str>) -> Self {
96        Self {
97            endpoint: endpoint.as_ref().to_string(),
98            ..self
99        }
100    }
101
102    fn base_url(&self) -> String {
103        format!("{}/{}/zones", self.endpoint, self.account_id)
104    }
105
106    pub(crate) async fn set_rrset(
107        &self,
108        name: impl IntoFqdn<'_>,
109        record_type: DnsRecordType,
110        ttl: u32,
111        records: Vec<DnsRecord>,
112        origin: impl IntoFqdn<'_>,
113    ) -> crate::Result<()> {
114        let name = name.into_name();
115        let zone = origin.into_name();
116        let subdomain = strip_origin_from_name(&name, &zone, Some(""));
117        let desired = build_contents(record_type, records)?;
118        let existing = self.list_at(&zone, &subdomain, record_type).await?;
119
120        let mut to_add: Vec<RecordContent> = Vec::new();
121        let mut existing_pool = existing;
122
123        for content in desired {
124            if let Some(idx) = existing_pool.iter().position(|r| r.content == content) {
125                existing_pool.swap_remove(idx);
126            } else {
127                to_add.push(content);
128            }
129        }
130
131        for entry in existing_pool {
132            self.delete_record(&zone, entry.id).await?;
133        }
134        for content in to_add {
135            self.create_record(&zone, &subdomain, record_type, ttl, content)
136                .await?;
137        }
138        Ok(())
139    }
140
141    pub(crate) async fn add_to_rrset(
142        &self,
143        name: impl IntoFqdn<'_>,
144        record_type: DnsRecordType,
145        ttl: u32,
146        records: Vec<DnsRecord>,
147        origin: impl IntoFqdn<'_>,
148    ) -> crate::Result<()> {
149        if records.is_empty() {
150            return Ok(());
151        }
152        let name = name.into_name();
153        let zone = origin.into_name();
154        let subdomain = strip_origin_from_name(&name, &zone, Some(""));
155        let desired = build_contents(record_type, records)?;
156        let existing = self.list_at(&zone, &subdomain, record_type).await?;
157
158        for content in desired {
159            if existing.iter().any(|r| r.content == content) {
160                continue;
161            }
162            self.create_record(&zone, &subdomain, record_type, ttl, content)
163                .await?;
164        }
165        Ok(())
166    }
167
168    pub(crate) async fn remove_from_rrset(
169        &self,
170        name: impl IntoFqdn<'_>,
171        record_type: DnsRecordType,
172        records: Vec<DnsRecord>,
173        origin: impl IntoFqdn<'_>,
174    ) -> crate::Result<()> {
175        if records.is_empty() {
176            return Ok(());
177        }
178        let name = name.into_name();
179        let zone = origin.into_name();
180        let subdomain = strip_origin_from_name(&name, &zone, Some(""));
181        let to_remove = build_contents(record_type, records)?;
182        let existing = self.list_at(&zone, &subdomain, record_type).await?;
183
184        for content in to_remove {
185            if let Some(entry) = existing.iter().find(|r| r.content == content) {
186                self.delete_record(&zone, entry.id).await?;
187            }
188        }
189        Ok(())
190    }
191
192    pub(crate) async fn list_rrset(
193        &self,
194        name: impl IntoFqdn<'_>,
195        record_type: DnsRecordType,
196        origin: impl IntoFqdn<'_>,
197    ) -> crate::Result<Vec<DnsRecord>> {
198        let name = name.into_name();
199        let zone = origin.into_name();
200        let subdomain = strip_origin_from_name(&name, &zone, Some(""));
201        let listed = self.list_at(&zone, &subdomain, record_type).await?;
202        listed
203            .into_iter()
204            .map(|r| record_from_content(record_type, &r.content))
205            .collect()
206    }
207
208    async fn list_at(
209        &self,
210        zone: &str,
211        subdomain: &str,
212        record_type: DnsRecordType,
213    ) -> crate::Result<Vec<ListedRecord>> {
214        let query = ListRecordsQuery {
215            name: subdomain,
216            type_filter: record_type.as_str(),
217            per_page: 100,
218        };
219        let url = format!(
220            "{}/{}/records?{}",
221            self.base_url(),
222            zone,
223            serde_urlencoded::to_string(&query).expect("urlencoded encoding of list query")
224        );
225        let response: ApiResponse<Vec<RecordEntry>> =
226            self.client.get(url).send_with_retry(3).await?;
227        let target_type = record_type.as_str();
228        Ok(response
229            .data
230            .into_iter()
231            .filter(|r| r.name == subdomain && r.record_type == target_type)
232            .map(|r| ListedRecord {
233                id: r.id,
234                content: RecordContent {
235                    content: r.content,
236                    priority: r.priority,
237                },
238            })
239            .collect())
240    }
241
242    async fn create_record(
243        &self,
244        zone: &str,
245        subdomain: &str,
246        record_type: DnsRecordType,
247        ttl: u32,
248        content: RecordContent,
249    ) -> crate::Result<()> {
250        self.client
251            .post(format!("{}/{}/records", self.base_url(), zone))
252            .with_body(CreateRecordParams {
253                name: subdomain.to_string(),
254                record_type: record_type.as_str().to_string(),
255                content: content.content,
256                ttl,
257                priority: content.priority,
258            })?
259            .send_with_retry::<serde_json::Value>(3)
260            .await
261            .map(|_| ())
262    }
263
264    async fn delete_record(&self, zone: &str, record_id: i64) -> crate::Result<()> {
265        self.client
266            .delete(format!(
267                "{}/{}/records/{}",
268                self.base_url(),
269                zone,
270                record_id
271            ))
272            .send_with_retry::<serde_json::Value>(3)
273            .await
274            .map(|_| ())
275    }
276}
277
278fn build_contents(
279    expected_type: DnsRecordType,
280    records: Vec<DnsRecord>,
281) -> crate::Result<Vec<RecordContent>> {
282    let mut out = Vec::with_capacity(records.len());
283    for record in records {
284        if record.as_type() != expected_type {
285            return Err(Error::Api(format!(
286                "RRSet record type mismatch: expected {}, got {}",
287                expected_type.as_str(),
288                record.as_type().as_str(),
289            )));
290        }
291        let (content, priority) = record_content_and_priority(&record);
292        out.push(RecordContent { content, priority });
293    }
294    Ok(out)
295}
296
297fn record_content_and_priority(record: &DnsRecord) -> (String, Option<u16>) {
298    match record {
299        DnsRecord::A(content) => (content.to_string(), None),
300        DnsRecord::AAAA(content) => (content.to_string(), None),
301        DnsRecord::CNAME(content) => (content.clone(), None),
302        DnsRecord::NS(content) => (content.clone(), None),
303        DnsRecord::MX(mx) => (mx.exchange.clone(), Some(mx.priority)),
304        DnsRecord::TXT(content) => (content.clone(), None),
305        DnsRecord::SRV(srv) => (
306            format!("{} {} {}", srv.weight, srv.port, srv.target),
307            Some(srv.priority),
308        ),
309        DnsRecord::TLSA(value) => (value.to_string(), None),
310        DnsRecord::CAA(caa) => (caa.to_string(), None),
311    }
312}
313
314fn record_from_content(
315    record_type: DnsRecordType,
316    content: &RecordContent,
317) -> crate::Result<DnsRecord> {
318    match record_type {
319        DnsRecordType::A => content
320            .content
321            .parse()
322            .map(DnsRecord::A)
323            .map_err(|e| Error::Parse(format!("invalid A content {:?}: {e}", content.content))),
324        DnsRecordType::AAAA => {
325            content.content.parse().map(DnsRecord::AAAA).map_err(|e| {
326                Error::Parse(format!("invalid AAAA content {:?}: {e}", content.content))
327            })
328        }
329        DnsRecordType::CNAME => Ok(DnsRecord::CNAME(content.content.clone())),
330        DnsRecordType::NS => Ok(DnsRecord::NS(content.content.clone())),
331        DnsRecordType::MX => Ok(DnsRecord::MX(MXRecord {
332            exchange: content.content.clone(),
333            priority: content.priority.unwrap_or(0),
334        })),
335        DnsRecordType::TXT => Ok(DnsRecord::TXT(content.content.clone())),
336        DnsRecordType::SRV => parse_srv(&content.content, content.priority.unwrap_or(0)),
337        DnsRecordType::TLSA => parse_tlsa(&content.content).map(DnsRecord::TLSA),
338        DnsRecordType::CAA => parse_caa(&content.content).map(DnsRecord::CAA),
339    }
340}
341
342fn parse_srv(content: &str, priority: u16) -> crate::Result<DnsRecord> {
343    let mut parts = content.split_whitespace();
344    let weight: u16 = parts
345        .next()
346        .ok_or_else(|| Error::Parse(format!("SRV missing weight: {content:?}")))?
347        .parse()
348        .map_err(|e| Error::Parse(format!("SRV invalid weight: {e}")))?;
349    let port: u16 = parts
350        .next()
351        .ok_or_else(|| Error::Parse(format!("SRV missing port: {content:?}")))?
352        .parse()
353        .map_err(|e| Error::Parse(format!("SRV invalid port: {e}")))?;
354    let target = parts
355        .next()
356        .ok_or_else(|| Error::Parse(format!("SRV missing target: {content:?}")))?
357        .to_string();
358    if parts.next().is_some() {
359        return Err(Error::Parse(format!("SRV extra fields: {content:?}")));
360    }
361    Ok(DnsRecord::SRV(SRVRecord {
362        priority,
363        weight,
364        port,
365        target,
366    }))
367}
368
369fn parse_tlsa(content: &str) -> crate::Result<TLSARecord> {
370    let mut parts = content.split_whitespace();
371    let usage: u8 = parts
372        .next()
373        .ok_or_else(|| Error::Parse(format!("TLSA missing usage: {content:?}")))?
374        .parse()
375        .map_err(|e| Error::Parse(format!("TLSA invalid usage: {e}")))?;
376    let selector: u8 = parts
377        .next()
378        .ok_or_else(|| Error::Parse(format!("TLSA missing selector: {content:?}")))?
379        .parse()
380        .map_err(|e| Error::Parse(format!("TLSA invalid selector: {e}")))?;
381    let matching: u8 = parts
382        .next()
383        .ok_or_else(|| Error::Parse(format!("TLSA missing matching: {content:?}")))?
384        .parse()
385        .map_err(|e| Error::Parse(format!("TLSA invalid matching: {e}")))?;
386    let cert_hex = parts
387        .next()
388        .ok_or_else(|| Error::Parse(format!("TLSA missing cert data: {content:?}")))?;
389    if parts.next().is_some() {
390        return Err(Error::Parse(format!("TLSA extra fields: {content:?}")));
391    }
392    Ok(TLSARecord {
393        cert_usage: tlsa_cert_usage_from_u8(usage)?,
394        selector: tlsa_selector_from_u8(selector)?,
395        matching: tlsa_matching_from_u8(matching)?,
396        cert_data: decode_hex(cert_hex)?,
397    })
398}
399
400fn parse_caa(content: &str) -> crate::Result<CAARecord> {
401    let mut parts = content.splitn(3, char::is_whitespace);
402    let flags: u8 = parts
403        .next()
404        .ok_or_else(|| Error::Parse(format!("CAA missing flags: {content:?}")))?
405        .trim()
406        .parse()
407        .map_err(|e| Error::Parse(format!("CAA invalid flags: {e}")))?;
408    let tag = parts
409        .next()
410        .ok_or_else(|| Error::Parse(format!("CAA missing tag: {content:?}")))?
411        .trim()
412        .to_string();
413    let raw_value = parts
414        .next()
415        .ok_or_else(|| Error::Parse(format!("CAA missing value: {content:?}")))?
416        .trim();
417    let value = raw_value
418        .strip_prefix('"')
419        .and_then(|s| s.strip_suffix('"'))
420        .unwrap_or(raw_value)
421        .to_string();
422    let issuer_critical = flags & 0x80 != 0;
423    match tag.as_str() {
424        "issue" => {
425            let (name, options) = parse_caa_value(&value);
426            Ok(CAARecord::Issue {
427                issuer_critical,
428                name,
429                options,
430            })
431        }
432        "issuewild" => {
433            let (name, options) = parse_caa_value(&value);
434            Ok(CAARecord::IssueWild {
435                issuer_critical,
436                name,
437                options,
438            })
439        }
440        "iodef" => Ok(CAARecord::Iodef {
441            issuer_critical,
442            url: value,
443        }),
444        other => Err(Error::Parse(format!("unknown CAA tag: {other}"))),
445    }
446}
447
448fn parse_caa_value(value: &str) -> (Option<String>, Vec<KeyValue>) {
449    let mut parts = value.split(';').map(str::trim);
450    let name_part = parts.next().unwrap_or("").trim().to_string();
451    let name = if name_part.is_empty() {
452        None
453    } else {
454        Some(name_part)
455    };
456    let options = parts
457        .filter(|p| !p.is_empty())
458        .map(|p| match p.split_once('=') {
459            Some((k, v)) => KeyValue {
460                key: k.trim().to_string(),
461                value: v.trim().to_string(),
462            },
463            None => KeyValue {
464                key: p.trim().to_string(),
465                value: String::new(),
466            },
467        })
468        .collect();
469    (name, options)
470}
471
472fn tlsa_cert_usage_from_u8(value: u8) -> crate::Result<TlsaCertUsage> {
473    Ok(match value {
474        0 => TlsaCertUsage::PkixTa,
475        1 => TlsaCertUsage::PkixEe,
476        2 => TlsaCertUsage::DaneTa,
477        3 => TlsaCertUsage::DaneEe,
478        255 => TlsaCertUsage::Private,
479        _ => return Err(Error::Parse(format!("unknown TLSA cert usage: {value}"))),
480    })
481}
482
483fn tlsa_selector_from_u8(value: u8) -> crate::Result<TlsaSelector> {
484    Ok(match value {
485        0 => TlsaSelector::Full,
486        1 => TlsaSelector::Spki,
487        255 => TlsaSelector::Private,
488        _ => return Err(Error::Parse(format!("unknown TLSA selector: {value}"))),
489    })
490}
491
492fn tlsa_matching_from_u8(value: u8) -> crate::Result<TlsaMatching> {
493    Ok(match value {
494        0 => TlsaMatching::Raw,
495        1 => TlsaMatching::Sha256,
496        2 => TlsaMatching::Sha512,
497        255 => TlsaMatching::Private,
498        _ => return Err(Error::Parse(format!("unknown TLSA matching: {value}"))),
499    })
500}
501
502fn decode_hex(hex: &str) -> crate::Result<Vec<u8>> {
503    if !hex.len().is_multiple_of(2) {
504        return Err(Error::Parse(format!("invalid hex string: {hex}")));
505    }
506    (0..hex.len())
507        .step_by(2)
508        .map(|i| {
509            u8::from_str_radix(&hex[i..i + 2], 16)
510                .map_err(|e| Error::Parse(format!("invalid hex byte: {e}")))
511        })
512        .collect()
513}