1use 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::{borrow::Cow, time::Duration};
20
21const DEFAULT_API_ENDPOINT: &str = "https://api.bunny.net";
22
23const BUNNY_TYPE_A: u8 = 0;
24const BUNNY_TYPE_AAAA: u8 = 1;
25const BUNNY_TYPE_CNAME: u8 = 2;
26const BUNNY_TYPE_TXT: u8 = 3;
27const BUNNY_TYPE_MX: u8 = 4;
28const BUNNY_TYPE_SRV: u8 = 8;
29const BUNNY_TYPE_CAA: u8 = 9;
30const BUNNY_TYPE_NS: u8 = 12;
31const BUNNY_TYPE_TLSA: u8 = 15;
32
33#[derive(Clone)]
34pub struct BunnyProvider {
35 client: HttpClient,
36 endpoint: Cow<'static, str>,
37}
38
39impl BunnyProvider {
40 pub(crate) fn new(api_key: impl AsRef<str>, timeout: Option<Duration>) -> crate::Result<Self> {
41 Ok(Self {
42 client: HttpClientBuilder::default()
43 .with_header("AccessKey", api_key.as_ref())
44 .with_timeout(timeout)
45 .build(),
46 endpoint: Cow::Borrowed(DEFAULT_API_ENDPOINT),
47 })
48 }
49
50 #[cfg(test)]
51 pub(crate) fn with_endpoint(self, endpoint: impl Into<Cow<'static, str>>) -> Self {
52 Self {
53 endpoint: endpoint.into(),
54 ..self
55 }
56 }
57
58 pub(crate) async fn set_rrset(
59 &self,
60 name: impl IntoFqdn<'_>,
61 record_type: DnsRecordType,
62 ttl: u32,
63 records: Vec<DnsRecord>,
64 origin: impl IntoFqdn<'_>,
65 ) -> crate::Result<()> {
66 let zone_data = self.get_zone_data(origin).await?;
67 let name = strip_origin_from_name(name.into_name().as_ref(), &zone_data.domain, Some(""));
68 let desired = build_contents(record_type, records)?;
69 let mut existing_pool: Vec<BunnyDnsRecord> = zone_data
70 .records
71 .into_iter()
72 .filter(|r| r.name == name && r.content.matches_type(record_type))
73 .collect();
74
75 let mut to_add = Vec::new();
76 for content in desired {
77 if let Some(idx) = existing_pool
78 .iter()
79 .position(|r| r.content.equivalent(&content))
80 {
81 existing_pool.swap_remove(idx);
82 } else {
83 to_add.push(content);
84 }
85 }
86
87 for stale in existing_pool {
88 self.delete_record(zone_data.id, stale.id).await?;
89 }
90 for content in to_add {
91 self.add_record(zone_data.id, &name, ttl, &content).await?;
92 }
93 Ok(())
94 }
95
96 pub(crate) async fn add_to_rrset(
97 &self,
98 name: impl IntoFqdn<'_>,
99 record_type: DnsRecordType,
100 ttl: u32,
101 records: Vec<DnsRecord>,
102 origin: impl IntoFqdn<'_>,
103 ) -> crate::Result<()> {
104 if records.is_empty() {
105 return Ok(());
106 }
107 let zone_data = self.get_zone_data(origin).await?;
108 let name = strip_origin_from_name(name.into_name().as_ref(), &zone_data.domain, Some(""));
109 let desired = build_contents(record_type, records)?;
110 let existing: Vec<BunnyDnsRecord> = zone_data
111 .records
112 .into_iter()
113 .filter(|r| r.name == name && r.content.matches_type(record_type))
114 .collect();
115
116 for content in desired {
117 if existing.iter().any(|r| r.content.equivalent(&content)) {
118 continue;
119 }
120 self.add_record(zone_data.id, &name, ttl, &content).await?;
121 }
122 Ok(())
123 }
124
125 pub(crate) async fn remove_from_rrset(
126 &self,
127 name: impl IntoFqdn<'_>,
128 record_type: DnsRecordType,
129 records: Vec<DnsRecord>,
130 origin: impl IntoFqdn<'_>,
131 ) -> crate::Result<()> {
132 if records.is_empty() {
133 return Ok(());
134 }
135 let zone_data = self.get_zone_data(origin).await?;
136 let name = strip_origin_from_name(name.into_name().as_ref(), &zone_data.domain, Some(""));
137 let to_remove = build_contents(record_type, records)?;
138 let existing: Vec<BunnyDnsRecord> = zone_data
139 .records
140 .into_iter()
141 .filter(|r| r.name == name && r.content.matches_type(record_type))
142 .collect();
143
144 for content in to_remove {
145 if let Some(entry) = existing.iter().find(|r| r.content.equivalent(&content)) {
146 self.delete_record(zone_data.id, entry.id).await?;
147 }
148 }
149 Ok(())
150 }
151
152 pub(crate) async fn list_rrset(
153 &self,
154 name: impl IntoFqdn<'_>,
155 record_type: DnsRecordType,
156 origin: impl IntoFqdn<'_>,
157 ) -> crate::Result<Vec<DnsRecord>> {
158 let zone_data = self.get_zone_data(origin).await?;
159 let name = strip_origin_from_name(name.into_name().as_ref(), &zone_data.domain, Some(""));
160 zone_data
161 .records
162 .into_iter()
163 .filter(|r| r.name == name && r.content.matches_type(record_type))
164 .map(|r| DnsRecord::try_from(r.content))
165 .collect()
166 }
167
168 async fn add_record(
169 &self,
170 zone_id: u32,
171 name: &str,
172 ttl: u32,
173 content: &BunnyRecordContent,
174 ) -> crate::Result<()> {
175 let body = AddDnsRecordBody { name, ttl, content };
176 self.client
177 .put(format!("{}/dnszone/{zone_id}/records", self.endpoint))
178 .with_body(&body)?
179 .send_with_retry::<serde_json::Value>(3)
180 .await
181 .map(|_| ())
182 }
183
184 async fn delete_record(&self, zone_id: u32, record_id: u32) -> crate::Result<()> {
185 self.client
186 .delete(format!(
187 "{}/dnszone/{zone_id}/records/{record_id}",
188 self.endpoint
189 ))
190 .send_with_retry::<serde_json::Value>(3)
191 .await
192 .map(|_| ())
193 }
194
195 async fn get_zone_data(&self, origin: impl IntoFqdn<'_>) -> crate::Result<PartialDnsZone> {
196 let origin = origin.into_name();
197 let query_string = serde_urlencoded::to_string([("search", origin.as_ref())])
198 .expect("Unable to convert DNS origin into HTTP query string");
199 self.client
200 .get(format!("{}/dnszone?{query_string}", self.endpoint))
201 .send_with_retry::<ApiItems<PartialDnsZone>>(3)
202 .await
203 .and_then(|r| {
204 r.items
205 .into_iter()
206 .find(|z| z.domain == origin.as_ref())
207 .ok_or_else(|| Error::Api(format!("DNS Record {origin} not found")))
208 })
209 }
210}
211
212fn build_contents(
213 expected_type: DnsRecordType,
214 records: Vec<DnsRecord>,
215) -> crate::Result<Vec<BunnyRecordContent>> {
216 let mut out = Vec::with_capacity(records.len());
217 for record in records {
218 if record.as_type() != expected_type {
219 return Err(Error::Api(format!(
220 "RRSet record type mismatch: expected {}, got {}",
221 expected_type.as_str(),
222 record.as_type().as_str(),
223 )));
224 }
225 out.push(BunnyRecordContent::try_from(&record)?);
226 }
227 Ok(out)
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
231#[serde(rename_all = "PascalCase")]
232pub struct BunnyRecordContent {
233 #[serde(rename = "Type")]
234 pub record_type: u8,
235 #[serde(default)]
236 pub value: String,
237 #[serde(default, skip_serializing_if = "is_zero_u16")]
238 pub priority: u16,
239 #[serde(default, skip_serializing_if = "is_zero_u16")]
240 pub weight: u16,
241 #[serde(default, skip_serializing_if = "is_zero_u16")]
242 pub port: u16,
243 #[serde(default, skip_serializing_if = "is_zero_u8")]
244 pub flags: u8,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
246 pub tag: Option<String>,
247}
248
249fn is_zero_u8(v: &u8) -> bool {
250 *v == 0
251}
252
253fn is_zero_u16(v: &u16) -> bool {
254 *v == 0
255}
256
257impl BunnyRecordContent {
258 fn matches_type(&self, record_type: DnsRecordType) -> bool {
259 bunny_type_for(record_type)
260 .map(|t| t == self.record_type)
261 .unwrap_or(false)
262 }
263
264 fn equivalent(&self, other: &Self) -> bool {
265 if self.record_type != other.record_type {
266 return false;
267 }
268 if self.priority != other.priority
269 || self.weight != other.weight
270 || self.port != other.port
271 || self.flags != other.flags
272 || self.tag != other.tag
273 {
274 return false;
275 }
276 match self.record_type {
277 BUNNY_TYPE_CNAME | BUNNY_TYPE_NS | BUNNY_TYPE_MX | BUNNY_TYPE_SRV => {
278 self.value.trim_end_matches('.') == other.value.trim_end_matches('.')
279 }
280 _ => self.value == other.value,
281 }
282 }
283}
284
285fn bunny_type_for(record_type: DnsRecordType) -> Option<u8> {
286 Some(match record_type {
287 DnsRecordType::A => BUNNY_TYPE_A,
288 DnsRecordType::AAAA => BUNNY_TYPE_AAAA,
289 DnsRecordType::CNAME => BUNNY_TYPE_CNAME,
290 DnsRecordType::TXT => BUNNY_TYPE_TXT,
291 DnsRecordType::MX => BUNNY_TYPE_MX,
292 DnsRecordType::SRV => BUNNY_TYPE_SRV,
293 DnsRecordType::CAA => BUNNY_TYPE_CAA,
294 DnsRecordType::NS => BUNNY_TYPE_NS,
295 DnsRecordType::TLSA => BUNNY_TYPE_TLSA,
296 })
297}
298
299impl TryFrom<&DnsRecord> for BunnyRecordContent {
300 type Error = Error;
301
302 fn try_from(record: &DnsRecord) -> crate::Result<Self> {
303 Ok(match record {
304 DnsRecord::A(addr) => BunnyRecordContent {
305 record_type: BUNNY_TYPE_A,
306 value: addr.to_string(),
307 ..Default::default()
308 },
309 DnsRecord::AAAA(addr) => BunnyRecordContent {
310 record_type: BUNNY_TYPE_AAAA,
311 value: addr.to_string(),
312 ..Default::default()
313 },
314 DnsRecord::CNAME(target) => BunnyRecordContent {
315 record_type: BUNNY_TYPE_CNAME,
316 value: target.clone(),
317 ..Default::default()
318 },
319 DnsRecord::NS(target) => BunnyRecordContent {
320 record_type: BUNNY_TYPE_NS,
321 value: target.clone(),
322 ..Default::default()
323 },
324 DnsRecord::TXT(text) => BunnyRecordContent {
325 record_type: BUNNY_TYPE_TXT,
326 value: text.clone(),
327 ..Default::default()
328 },
329 DnsRecord::MX(mx) => BunnyRecordContent {
330 record_type: BUNNY_TYPE_MX,
331 value: mx.exchange.clone(),
332 priority: mx.priority,
333 ..Default::default()
334 },
335 DnsRecord::SRV(srv) => BunnyRecordContent {
336 record_type: BUNNY_TYPE_SRV,
337 value: srv.target.clone(),
338 priority: srv.priority,
339 weight: srv.weight,
340 port: srv.port,
341 ..Default::default()
342 },
343 DnsRecord::TLSA(tlsa) => BunnyRecordContent {
344 record_type: BUNNY_TYPE_TLSA,
345 value: tlsa.to_string(),
346 ..Default::default()
347 },
348 DnsRecord::CAA(caa) => {
349 let (flags, tag, value) = caa.clone().decompose();
350 BunnyRecordContent {
351 record_type: BUNNY_TYPE_CAA,
352 value,
353 flags,
354 tag: Some(tag),
355 ..Default::default()
356 }
357 }
358 })
359 }
360}
361
362impl TryFrom<BunnyRecordContent> for DnsRecord {
363 type Error = Error;
364
365 fn try_from(content: BunnyRecordContent) -> crate::Result<Self> {
366 Ok(match content.record_type {
367 BUNNY_TYPE_A => DnsRecord::A(content.value.parse().map_err(|e| {
368 Error::Parse(format!("invalid IPv4 address {:?}: {e}", content.value))
369 })?),
370 BUNNY_TYPE_AAAA => DnsRecord::AAAA(content.value.parse().map_err(|e| {
371 Error::Parse(format!("invalid IPv6 address {:?}: {e}", content.value))
372 })?),
373 BUNNY_TYPE_CNAME => DnsRecord::CNAME(content.value),
374 BUNNY_TYPE_NS => DnsRecord::NS(content.value),
375 BUNNY_TYPE_TXT => DnsRecord::TXT(content.value),
376 BUNNY_TYPE_MX => DnsRecord::MX(MXRecord {
377 exchange: content.value,
378 priority: content.priority,
379 }),
380 BUNNY_TYPE_SRV => DnsRecord::SRV(SRVRecord {
381 target: content.value,
382 priority: content.priority,
383 weight: content.weight,
384 port: content.port,
385 }),
386 BUNNY_TYPE_CAA => {
387 let tag = content
388 .tag
389 .ok_or_else(|| Error::Parse("CAA record missing Tag field".to_string()))?;
390 DnsRecord::CAA(build_caa(content.flags, &tag, content.value)?)
391 }
392 BUNNY_TYPE_TLSA => DnsRecord::TLSA(parse_tlsa(&content.value)?),
393 other => {
394 return Err(Error::Parse(format!(
395 "unsupported Bunny record type: {other}"
396 )));
397 }
398 })
399 }
400}
401
402fn build_caa(flags: u8, tag: &str, value: String) -> crate::Result<CAARecord> {
403 let issuer_critical = flags & 0x80 != 0;
404 match tag {
405 "issue" => {
406 let (name, options) = parse_caa_value(&value);
407 Ok(CAARecord::Issue {
408 issuer_critical,
409 name,
410 options,
411 })
412 }
413 "issuewild" => {
414 let (name, options) = parse_caa_value(&value);
415 Ok(CAARecord::IssueWild {
416 issuer_critical,
417 name,
418 options,
419 })
420 }
421 "iodef" => Ok(CAARecord::Iodef {
422 issuer_critical,
423 url: value,
424 }),
425 other => Err(Error::Parse(format!("unknown CAA tag: {other}"))),
426 }
427}
428
429fn parse_caa_value(value: &str) -> (Option<String>, Vec<KeyValue>) {
430 let mut parts = value.split(';').map(str::trim);
431 let name_part = parts.next().unwrap_or("").trim().to_string();
432 let name = if name_part.is_empty() {
433 None
434 } else {
435 Some(name_part)
436 };
437 let options = parts
438 .filter(|p| !p.is_empty())
439 .map(|p| match p.split_once('=') {
440 Some((k, v)) => KeyValue {
441 key: k.trim().to_string(),
442 value: v.trim().to_string(),
443 },
444 None => KeyValue {
445 key: p.trim().to_string(),
446 value: String::new(),
447 },
448 })
449 .collect();
450 (name, options)
451}
452
453fn parse_tlsa(value: &str) -> crate::Result<TLSARecord> {
454 let mut parts = value.split_whitespace();
455 let usage = parts
456 .next()
457 .ok_or_else(|| Error::Parse(format!("TLSA missing usage field: {value:?}")))?;
458 let selector = parts
459 .next()
460 .ok_or_else(|| Error::Parse(format!("TLSA missing selector field: {value:?}")))?;
461 let matching = parts
462 .next()
463 .ok_or_else(|| Error::Parse(format!("TLSA missing matching field: {value:?}")))?;
464 let cert_hex = parts
465 .next()
466 .ok_or_else(|| Error::Parse(format!("TLSA missing certificate data: {value:?}")))?;
467 if parts.next().is_some() {
468 return Err(Error::Parse(format!(
469 "TLSA unexpected extra fields: {value:?}"
470 )));
471 }
472 let usage = usage
473 .parse::<u8>()
474 .map_err(|e| Error::Parse(format!("TLSA invalid usage {usage:?}: {e}")))?;
475 let selector = selector
476 .parse::<u8>()
477 .map_err(|e| Error::Parse(format!("TLSA invalid selector {selector:?}: {e}")))?;
478 let matching = matching
479 .parse::<u8>()
480 .map_err(|e| Error::Parse(format!("TLSA invalid matching {matching:?}: {e}")))?;
481 Ok(TLSARecord {
482 cert_usage: tlsa_cert_usage_from_u8(usage)?,
483 selector: tlsa_selector_from_u8(selector)?,
484 matching: tlsa_matching_from_u8(matching)?,
485 cert_data: decode_hex(cert_hex)?,
486 })
487}
488
489fn tlsa_cert_usage_from_u8(value: u8) -> crate::Result<TlsaCertUsage> {
490 Ok(match value {
491 0 => TlsaCertUsage::PkixTa,
492 1 => TlsaCertUsage::PkixEe,
493 2 => TlsaCertUsage::DaneTa,
494 3 => TlsaCertUsage::DaneEe,
495 255 => TlsaCertUsage::Private,
496 _ => return Err(Error::Parse(format!("unknown TLSA cert usage: {value}"))),
497 })
498}
499
500fn tlsa_selector_from_u8(value: u8) -> crate::Result<TlsaSelector> {
501 Ok(match value {
502 0 => TlsaSelector::Full,
503 1 => TlsaSelector::Spki,
504 255 => TlsaSelector::Private,
505 _ => return Err(Error::Parse(format!("unknown TLSA selector: {value}"))),
506 })
507}
508
509fn tlsa_matching_from_u8(value: u8) -> crate::Result<TlsaMatching> {
510 Ok(match value {
511 0 => TlsaMatching::Raw,
512 1 => TlsaMatching::Sha256,
513 2 => TlsaMatching::Sha512,
514 255 => TlsaMatching::Private,
515 _ => return Err(Error::Parse(format!("unknown TLSA matching: {value}"))),
516 })
517}
518
519fn decode_hex(hex: &str) -> crate::Result<Vec<u8>> {
520 if !hex.len().is_multiple_of(2) {
521 return Err(Error::Parse(format!("invalid hex string: {hex}")));
522 }
523 (0..hex.len())
524 .step_by(2)
525 .map(|i| {
526 u8::from_str_radix(&hex[i..i + 2], 16)
527 .map_err(|e| Error::Parse(format!("invalid hex byte: {e}")))
528 })
529 .collect()
530}
531
532#[derive(Serialize, Debug)]
533#[serde(rename_all = "PascalCase")]
534struct AddDnsRecordBody<'a> {
535 name: &'a str,
536 ttl: u32,
537 #[serde(flatten)]
538 content: &'a BunnyRecordContent,
539}
540
541#[derive(Deserialize, Clone, Debug)]
542#[serde(rename_all = "PascalCase")]
543pub struct ApiItems<T> {
544 pub items: Vec<T>,
545 pub current_page: u32,
546 pub total_items: u32,
547 pub has_more_items: bool,
548}
549
550#[derive(Deserialize, Clone, Debug)]
551#[serde(rename_all = "PascalCase")]
552pub struct PartialDnsZone {
553 pub id: u32,
554 pub domain: String,
555 pub records: Vec<BunnyDnsRecord>,
556}
557
558#[derive(Deserialize, Clone, Debug)]
559#[serde(rename_all = "PascalCase")]
560pub struct BunnyDnsRecord {
561 pub id: u32,
562 pub name: String,
563 #[serde(flatten)]
564 pub content: BunnyRecordContent,
565}