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