1use crate::utils::build_caa;
2use crate::utils::parse_tlsa;
3use crate::{
4 DnsRecord, DnsRecordType, Error, IntoFqdn, MXRecord, SRVRecord,
5 http::{HttpClient, HttpClientBuilder},
6 utils::strip_origin_from_name,
7};
8use serde::{Deserialize, Serialize};
9use std::{borrow::Cow, time::Duration};
10
11const BUNNY_TYPE_A: u8 = 0;
12const BUNNY_TYPE_AAAA: u8 = 1;
13const BUNNY_TYPE_CNAME: u8 = 2;
14const BUNNY_TYPE_TXT: u8 = 3;
15const BUNNY_TYPE_MX: u8 = 4;
16const BUNNY_TYPE_SRV: u8 = 8;
17const BUNNY_TYPE_CAA: u8 = 9;
18const BUNNY_TYPE_NS: u8 = 12;
19const BUNNY_TYPE_HTTPS: u8 = 14;
20const BUNNY_TYPE_TLSA: u8 = 15;
21
22#[derive(Clone)]
23pub struct BunnyProvider {
24 client: HttpClient,
25 endpoint: Cow<'static, str>,
26}
27
28impl BunnyProvider {
29 pub(crate) fn new(api_key: impl AsRef<str>, timeout: Option<Duration>) -> crate::Result<Self> {
30 Ok(Self {
31 client: HttpClientBuilder::default()
32 .with_header("AccessKey", api_key.as_ref())
33 .with_timeout(timeout)
34 .build(),
35 endpoint: crate::config::bunny_endpoint(),
36 })
37 }
38
39 #[cfg(test)]
40 pub(crate) fn with_endpoint(self, endpoint: impl Into<Cow<'static, str>>) -> Self {
41 Self {
42 endpoint: endpoint.into(),
43 ..self
44 }
45 }
46
47 pub(crate) async fn set_rrset(
48 &self,
49 name: impl IntoFqdn<'_>,
50 record_type: DnsRecordType,
51 ttl: u32,
52 records: Vec<DnsRecord>,
53 origin: impl IntoFqdn<'_>,
54 ) -> crate::Result<()> {
55 let zone_data = self.get_zone_data(origin).await?;
56 let name = strip_origin_from_name(name.into_name().as_ref(), &zone_data.domain, Some(""));
57 let desired = build_contents(record_type, records)?;
58 let mut existing_pool: Vec<BunnyDnsRecord> = zone_data
59 .records
60 .into_iter()
61 .filter(|r| r.name == name && r.content.matches_type(record_type))
62 .collect();
63
64 let mut to_add = Vec::new();
65 for content in desired {
66 if let Some(idx) = existing_pool
67 .iter()
68 .position(|r| r.content.equivalent(&content))
69 {
70 existing_pool.swap_remove(idx);
71 } else {
72 to_add.push(content);
73 }
74 }
75
76 for stale in existing_pool {
77 self.delete_record(zone_data.id, stale.id).await?;
78 }
79 for content in to_add {
80 self.add_record(zone_data.id, &name, ttl, &content).await?;
81 }
82 Ok(())
83 }
84
85 pub(crate) async fn add_to_rrset(
86 &self,
87 name: impl IntoFqdn<'_>,
88 record_type: DnsRecordType,
89 ttl: u32,
90 records: Vec<DnsRecord>,
91 origin: impl IntoFqdn<'_>,
92 ) -> crate::Result<()> {
93 if records.is_empty() {
94 return Ok(());
95 }
96 let zone_data = self.get_zone_data(origin).await?;
97 let name = strip_origin_from_name(name.into_name().as_ref(), &zone_data.domain, Some(""));
98 let desired = build_contents(record_type, records)?;
99 let existing: Vec<BunnyDnsRecord> = zone_data
100 .records
101 .into_iter()
102 .filter(|r| r.name == name && r.content.matches_type(record_type))
103 .collect();
104
105 for content in desired {
106 if existing.iter().any(|r| r.content.equivalent(&content)) {
107 continue;
108 }
109 self.add_record(zone_data.id, &name, ttl, &content).await?;
110 }
111 Ok(())
112 }
113
114 pub(crate) async fn remove_from_rrset(
115 &self,
116 name: impl IntoFqdn<'_>,
117 record_type: DnsRecordType,
118 records: Vec<DnsRecord>,
119 origin: impl IntoFqdn<'_>,
120 ) -> crate::Result<()> {
121 if records.is_empty() {
122 return Ok(());
123 }
124 let zone_data = self.get_zone_data(origin).await?;
125 let name = strip_origin_from_name(name.into_name().as_ref(), &zone_data.domain, Some(""));
126 let to_remove = build_contents(record_type, records)?;
127 let existing: Vec<BunnyDnsRecord> = zone_data
128 .records
129 .into_iter()
130 .filter(|r| r.name == name && r.content.matches_type(record_type))
131 .collect();
132
133 for content in to_remove {
134 if let Some(entry) = existing.iter().find(|r| r.content.equivalent(&content)) {
135 self.delete_record(zone_data.id, entry.id).await?;
136 }
137 }
138 Ok(())
139 }
140
141 pub(crate) async fn list_rrset(
142 &self,
143 name: impl IntoFqdn<'_>,
144 record_type: DnsRecordType,
145 origin: impl IntoFqdn<'_>,
146 ) -> crate::Result<Vec<DnsRecord>> {
147 let zone_data = self.get_zone_data(origin).await?;
148 let name = strip_origin_from_name(name.into_name().as_ref(), &zone_data.domain, Some(""));
149 zone_data
150 .records
151 .into_iter()
152 .filter(|r| r.name == name && r.content.matches_type(record_type))
153 .map(|r| DnsRecord::try_from(r.content))
154 .collect()
155 }
156
157 async fn add_record(
158 &self,
159 zone_id: u32,
160 name: &str,
161 ttl: u32,
162 content: &BunnyRecordContent,
163 ) -> crate::Result<()> {
164 let body = AddDnsRecordBody { name, ttl, content };
165 self.client
166 .put(format!("{}/dnszone/{zone_id}/records", self.endpoint))
167 .with_body(&body)?
168 .send_with_retry::<serde_json::Value>(3)
169 .await
170 .map(|_| ())
171 }
172
173 async fn delete_record(&self, zone_id: u32, record_id: u32) -> crate::Result<()> {
174 self.client
175 .delete(format!(
176 "{}/dnszone/{zone_id}/records/{record_id}",
177 self.endpoint
178 ))
179 .send_with_retry::<serde_json::Value>(3)
180 .await
181 .map(|_| ())
182 }
183
184 async fn get_zone_data(&self, origin: impl IntoFqdn<'_>) -> crate::Result<PartialDnsZone> {
185 let origin = origin.into_name();
186 let query_string = serde_urlencoded::to_string([("search", origin.as_ref())])
187 .expect("Unable to convert DNS origin into HTTP query string");
188 self.client
189 .get(format!("{}/dnszone?{query_string}", self.endpoint))
190 .send_with_retry::<ApiItems<PartialDnsZone>>(3)
191 .await
192 .and_then(|r| {
193 r.items
194 .into_iter()
195 .find(|z| z.domain == origin.as_ref())
196 .ok_or_else(|| Error::Api(format!("DNS Record {origin} not found")))
197 })
198 }
199}
200
201fn build_contents(
202 expected_type: DnsRecordType,
203 records: Vec<DnsRecord>,
204) -> crate::Result<Vec<BunnyRecordContent>> {
205 crate::utils::check_record_types(expected_type, &records)?;
206 records.iter().map(BunnyRecordContent::try_from).collect()
207}
208
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
210#[serde(rename_all = "PascalCase")]
211pub struct BunnyRecordContent {
212 #[serde(rename = "Type")]
213 pub record_type: u8,
214 #[serde(default)]
215 pub value: String,
216 #[serde(default, skip_serializing_if = "is_zero")]
217 pub priority: u16,
218 #[serde(default, skip_serializing_if = "is_zero")]
219 pub weight: u16,
220 #[serde(default, skip_serializing_if = "is_zero")]
221 pub port: u16,
222 #[serde(default, skip_serializing_if = "is_zero")]
223 pub flags: u8,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub tag: Option<String>,
226}
227
228fn is_zero<T: PartialEq + Default>(v: &T) -> bool {
229 *v == T::default()
230}
231
232impl BunnyRecordContent {
233 fn matches_type(&self, record_type: DnsRecordType) -> bool {
234 bunny_type_for(record_type)
235 .map(|t| t == self.record_type)
236 .unwrap_or(false)
237 }
238
239 fn equivalent(&self, other: &Self) -> bool {
240 if self.record_type != other.record_type {
241 return false;
242 }
243 if self.priority != other.priority
244 || self.weight != other.weight
245 || self.port != other.port
246 || self.flags != other.flags
247 || self.tag != other.tag
248 {
249 return false;
250 }
251 match self.record_type {
252 BUNNY_TYPE_CNAME | BUNNY_TYPE_NS | BUNNY_TYPE_MX | BUNNY_TYPE_SRV => {
253 self.value.trim_end_matches('.') == other.value.trim_end_matches('.')
254 }
255 _ => self.value == other.value,
256 }
257 }
258}
259
260fn bunny_type_for(record_type: DnsRecordType) -> Option<u8> {
261 Some(match record_type {
262 DnsRecordType::A => BUNNY_TYPE_A,
263 DnsRecordType::AAAA => BUNNY_TYPE_AAAA,
264 DnsRecordType::CNAME => BUNNY_TYPE_CNAME,
265 DnsRecordType::TXT => BUNNY_TYPE_TXT,
266 DnsRecordType::MX => BUNNY_TYPE_MX,
267 DnsRecordType::SRV => BUNNY_TYPE_SRV,
268 DnsRecordType::CAA => BUNNY_TYPE_CAA,
269 DnsRecordType::NS => BUNNY_TYPE_NS,
270 DnsRecordType::TLSA => BUNNY_TYPE_TLSA,
271 DnsRecordType::HTTPS => BUNNY_TYPE_HTTPS,
272 })
273}
274
275impl TryFrom<&DnsRecord> for BunnyRecordContent {
276 type Error = Error;
277
278 fn try_from(record: &DnsRecord) -> crate::Result<Self> {
279 Ok(match record {
280 DnsRecord::A(addr) => BunnyRecordContent {
281 record_type: BUNNY_TYPE_A,
282 value: addr.to_string(),
283 ..Default::default()
284 },
285 DnsRecord::AAAA(addr) => BunnyRecordContent {
286 record_type: BUNNY_TYPE_AAAA,
287 value: addr.to_string(),
288 ..Default::default()
289 },
290 DnsRecord::CNAME(target) => BunnyRecordContent {
291 record_type: BUNNY_TYPE_CNAME,
292 value: target.clone(),
293 ..Default::default()
294 },
295 DnsRecord::NS(target) => BunnyRecordContent {
296 record_type: BUNNY_TYPE_NS,
297 value: target.clone(),
298 ..Default::default()
299 },
300 DnsRecord::TXT(text) => BunnyRecordContent {
301 record_type: BUNNY_TYPE_TXT,
302 value: text.clone(),
303 ..Default::default()
304 },
305 DnsRecord::MX(mx) => BunnyRecordContent {
306 record_type: BUNNY_TYPE_MX,
307 value: mx.exchange.clone(),
308 priority: mx.priority,
309 ..Default::default()
310 },
311 DnsRecord::SRV(srv) => BunnyRecordContent {
312 record_type: BUNNY_TYPE_SRV,
313 value: srv.target.clone(),
314 priority: srv.priority,
315 weight: srv.weight,
316 port: srv.port,
317 ..Default::default()
318 },
319 DnsRecord::TLSA(tlsa) => BunnyRecordContent {
320 record_type: BUNNY_TYPE_TLSA,
321 value: tlsa.to_string(),
322 ..Default::default()
323 },
324 DnsRecord::CAA(caa) => {
325 let (flags, tag, value) = caa.clone().decompose();
326 BunnyRecordContent {
327 record_type: BUNNY_TYPE_CAA,
328 value,
329 flags,
330 tag: Some(tag),
331 ..Default::default()
332 }
333 }
334 DnsRecord::HTTPS(https) => BunnyRecordContent {
335 record_type: BUNNY_TYPE_HTTPS,
336 value: https.to_string(),
337 ..Default::default()
338 },
339 })
340 }
341}
342
343impl TryFrom<BunnyRecordContent> for DnsRecord {
344 type Error = Error;
345
346 fn try_from(content: BunnyRecordContent) -> crate::Result<Self> {
347 Ok(match content.record_type {
348 BUNNY_TYPE_A => DnsRecord::A(content.value.parse().map_err(|e| {
349 Error::Parse(format!("invalid IPv4 address {:?}: {e}", content.value))
350 })?),
351 BUNNY_TYPE_AAAA => DnsRecord::AAAA(content.value.parse().map_err(|e| {
352 Error::Parse(format!("invalid IPv6 address {:?}: {e}", content.value))
353 })?),
354 BUNNY_TYPE_CNAME => DnsRecord::CNAME(content.value),
355 BUNNY_TYPE_NS => DnsRecord::NS(content.value),
356 BUNNY_TYPE_TXT => DnsRecord::TXT(content.value),
357 BUNNY_TYPE_MX => DnsRecord::MX(MXRecord {
358 exchange: content.value,
359 priority: content.priority,
360 }),
361 BUNNY_TYPE_SRV => DnsRecord::SRV(SRVRecord {
362 target: content.value,
363 priority: content.priority,
364 weight: content.weight,
365 port: content.port,
366 }),
367 BUNNY_TYPE_CAA => {
368 let tag = content
369 .tag
370 .ok_or_else(|| Error::Parse("CAA record missing Tag field".to_string()))?;
371 DnsRecord::CAA(build_caa(content.flags, &tag, &content.value)?)
372 }
373 BUNNY_TYPE_TLSA => parse_tlsa(&content.value)?,
374 other => {
375 return Err(Error::Parse(format!(
376 "unsupported Bunny record type: {other}"
377 )));
378 }
379 })
380 }
381}
382
383#[derive(Serialize, Debug)]
384#[serde(rename_all = "PascalCase")]
385struct AddDnsRecordBody<'a> {
386 name: &'a str,
387 ttl: u32,
388 #[serde(flatten)]
389 content: &'a BunnyRecordContent,
390}
391
392#[derive(Deserialize, Clone, Debug)]
393#[serde(rename_all = "PascalCase")]
394pub struct ApiItems<T> {
395 pub items: Vec<T>,
396 pub current_page: u32,
397 pub total_items: u32,
398 pub has_more_items: bool,
399}
400
401#[derive(Deserialize, Clone, Debug)]
402#[serde(rename_all = "PascalCase")]
403pub struct PartialDnsZone {
404 pub id: u32,
405 pub domain: String,
406 pub records: Vec<BunnyDnsRecord>,
407}
408
409#[derive(Deserialize, Clone, Debug)]
410#[serde(rename_all = "PascalCase")]
411pub struct BunnyDnsRecord {
412 pub id: u32,
413 pub name: String,
414 #[serde(flatten)]
415 pub content: BunnyRecordContent,
416}