1use crate::utils::split_caa_value;
13use crate::utils::unquote_txt;
14use crate::{
15 CAARecord, DnsRecord, DnsRecordType, Error, IntoFqdn, MXRecord, SRVRecord,
16 http::{HttpClient, HttpClientBuilder},
17 utils::txt_chunks_to_text,
18};
19use serde::{Deserialize, Serialize};
20use std::time::Duration;
21
22const DEFAULT_API_ENDPOINT: &str = "https://api.ukfast.io/safedns/v1";
23const LIST_PAGE_SIZE: u32 = 200;
24
25#[derive(Clone)]
26pub struct SafeDnsProvider {
27 client: HttpClient,
28 endpoint: String,
29}
30
31#[derive(Serialize, Debug, Clone)]
32pub struct SafeDnsRecordPayload<'a> {
33 pub name: &'a str,
34 #[serde(rename = "type")]
35 pub record_type: &'a str,
36 pub content: String,
37 pub ttl: u32,
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub priority: Option<u16>,
40}
41
42#[derive(Deserialize, Debug, Clone)]
43pub struct SafeDnsRecord {
44 pub id: i64,
45 pub name: String,
46 #[serde(rename = "type")]
47 pub record_type: String,
48 #[serde(default)]
49 pub content: String,
50 #[serde(default)]
51 pub priority: Option<u16>,
52}
53
54#[derive(Deserialize, Debug)]
55pub struct ListRecordsResponse {
56 pub data: Vec<SafeDnsRecord>,
57 #[serde(default)]
58 pub meta: ListMeta,
59}
60
61#[derive(Deserialize, Debug, Default)]
62pub struct ListMeta {
63 #[serde(default)]
64 pub pagination: Pagination,
65}
66
67#[derive(Deserialize, Debug, Default)]
68pub struct Pagination {
69 #[serde(default)]
70 pub total_pages: u32,
71}
72
73#[derive(Deserialize, Debug)]
74pub struct AddRecordResponse {
75 #[allow(dead_code)]
76 pub data: SafeDnsRecord,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct SafeDnsRecordContent {
81 pub record_type: &'static str,
82 pub content: String,
83 pub priority: Option<u16>,
84}
85
86impl SafeDnsProvider {
87 pub(crate) fn new(auth_token: impl AsRef<str>, timeout: Option<Duration>) -> Self {
88 let client = HttpClientBuilder::default()
89 .with_header("Authorization", auth_token.as_ref())
90 .with_timeout(timeout)
91 .build();
92 Self {
93 client,
94 endpoint: DEFAULT_API_ENDPOINT.to_string(),
95 }
96 }
97
98 #[cfg(test)]
99 pub(crate) fn with_endpoint(self, endpoint: impl AsRef<str>) -> Self {
100 Self {
101 endpoint: endpoint.as_ref().to_string(),
102 ..self
103 }
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 reject_unsupported(record_type)?;
115 let fqdn = name.into_name().into_owned();
116 let zone = origin.into_name().into_owned();
117 let desired = build_contents(record_type, records)?;
118 let existing = self.list_at(&zone, &fqdn, record_type).await?;
119
120 let mut existing_pool: Vec<SafeDnsRecord> = existing;
121 let mut to_add: Vec<SafeDnsRecordContent> = Vec::new();
122
123 for content in desired {
124 if let Some(idx) = existing_pool
125 .iter()
126 .position(|r| record_matches(r, &content))
127 {
128 existing_pool.swap_remove(idx);
129 } else {
130 to_add.push(content);
131 }
132 }
133
134 for entry in existing_pool {
135 self.delete_record(&zone, entry.id).await?;
136 }
137 for content in to_add {
138 self.create_record(&zone, &fqdn, ttl, &content).await?;
139 }
140 Ok(())
141 }
142
143 pub(crate) async fn add_to_rrset(
144 &self,
145 name: impl IntoFqdn<'_>,
146 record_type: DnsRecordType,
147 ttl: u32,
148 records: Vec<DnsRecord>,
149 origin: impl IntoFqdn<'_>,
150 ) -> crate::Result<()> {
151 reject_unsupported(record_type)?;
152 if records.is_empty() {
153 return Ok(());
154 }
155 let fqdn = name.into_name().into_owned();
156 let zone = origin.into_name().into_owned();
157 let desired = build_contents(record_type, records)?;
158 let existing = self.list_at(&zone, &fqdn, record_type).await?;
159
160 for content in desired {
161 if existing.iter().any(|r| record_matches(r, &content)) {
162 continue;
163 }
164 self.create_record(&zone, &fqdn, ttl, &content).await?;
165 }
166 Ok(())
167 }
168
169 pub(crate) async fn remove_from_rrset(
170 &self,
171 name: impl IntoFqdn<'_>,
172 record_type: DnsRecordType,
173 records: Vec<DnsRecord>,
174 origin: impl IntoFqdn<'_>,
175 ) -> crate::Result<()> {
176 reject_unsupported(record_type)?;
177 if records.is_empty() {
178 return Ok(());
179 }
180 let fqdn = name.into_name().into_owned();
181 let zone = origin.into_name().into_owned();
182 let to_remove = build_contents(record_type, records)?;
183 let existing = self.list_at(&zone, &fqdn, record_type).await?;
184
185 for content in to_remove {
186 if let Some(entry) = existing.iter().find(|r| record_matches(r, &content)) {
187 self.delete_record(&zone, entry.id).await?;
188 }
189 }
190 Ok(())
191 }
192
193 pub(crate) async fn list_rrset(
194 &self,
195 name: impl IntoFqdn<'_>,
196 record_type: DnsRecordType,
197 origin: impl IntoFqdn<'_>,
198 ) -> crate::Result<Vec<DnsRecord>> {
199 let fqdn = name.into_name().into_owned();
200 let zone = origin.into_name().into_owned();
201 let listed = self.list_at(&zone, &fqdn, record_type).await?;
202 listed
203 .into_iter()
204 .map(|r| safedns_record_to_dns_record(r, record_type))
205 .collect()
206 }
207
208 async fn list_at(
209 &self,
210 zone: &str,
211 name: &str,
212 record_type: DnsRecordType,
213 ) -> crate::Result<Vec<SafeDnsRecord>> {
214 let type_str = record_type.as_str();
215 let mut out: Vec<SafeDnsRecord> = Vec::new();
216 let mut page: u32 = 1;
217 loop {
218 let url = format!(
219 "{endpoint}/zones/{zone}/records?name:eq={name}&type:eq={type_str}&per_page={LIST_PAGE_SIZE}&page={page}",
220 endpoint = self.endpoint
221 );
222 let response: ListRecordsResponse = self.client.get(url).send_with_retry(3).await?;
223 let total_pages = response.meta.pagination.total_pages;
224 for record in response.data {
225 if record.name == name && record.record_type == type_str {
226 out.push(record);
227 }
228 }
229 if total_pages <= page {
230 break;
231 }
232 page += 1;
233 }
234 Ok(out)
235 }
236
237 async fn create_record(
238 &self,
239 zone: &str,
240 name: &str,
241 ttl: u32,
242 content: &SafeDnsRecordContent,
243 ) -> crate::Result<()> {
244 let body = SafeDnsRecordPayload {
245 name,
246 record_type: content.record_type,
247 content: content.content.clone(),
248 ttl,
249 priority: content.priority,
250 };
251
252 self.client
253 .post(format!(
254 "{endpoint}/zones/{zone}/records",
255 endpoint = self.endpoint
256 ))
257 .with_body(&body)?
258 .send_with_retry::<serde_json::Value>(3)
259 .await
260 .map(|_| ())
261 }
262
263 async fn delete_record(&self, zone: &str, record_id: i64) -> crate::Result<()> {
264 self.client
265 .delete(format!(
266 "{endpoint}/zones/{zone}/records/{record_id}",
267 endpoint = self.endpoint
268 ))
269 .send_with_retry::<serde_json::Value>(3)
270 .await
271 .map(|_| ())
272 }
273}
274
275fn reject_unsupported(record_type: DnsRecordType) -> crate::Result<()> {
276 if record_type == DnsRecordType::TLSA {
277 return Err(Error::Unsupported(
278 "TLSA records are not supported by SafeDNS".to_string(),
279 ));
280 }
281 Ok(())
282}
283
284fn build_contents(
285 expected_type: DnsRecordType,
286 records: Vec<DnsRecord>,
287) -> crate::Result<Vec<SafeDnsRecordContent>> {
288 let mut out = Vec::with_capacity(records.len());
289 for record in records {
290 if record.as_type() != expected_type {
291 return Err(Error::Api(format!(
292 "RRSet record type mismatch: expected {}, got {}",
293 expected_type.as_str(),
294 record.as_type().as_str(),
295 )));
296 }
297 out.push(SafeDnsRecordContent::try_from(record)?);
298 }
299 Ok(out)
300}
301
302fn record_matches(record: &SafeDnsRecord, content: &SafeDnsRecordContent) -> bool {
303 record.record_type == content.record_type
304 && record.content == content.content
305 && record.priority == content.priority
306}
307
308fn safedns_record_to_dns_record(
309 record: SafeDnsRecord,
310 record_type: DnsRecordType,
311) -> crate::Result<DnsRecord> {
312 match record_type {
313 DnsRecordType::A => record
314 .content
315 .parse()
316 .map(DnsRecord::A)
317 .map_err(|e| Error::Parse(format!("invalid A content {}: {e}", record.content))),
318 DnsRecordType::AAAA => record
319 .content
320 .parse()
321 .map(DnsRecord::AAAA)
322 .map_err(|e| Error::Parse(format!("invalid AAAA content {}: {e}", record.content))),
323 DnsRecordType::CNAME => Ok(DnsRecord::CNAME(record.content)),
324 DnsRecordType::NS => Ok(DnsRecord::NS(record.content)),
325 DnsRecordType::MX => Ok(DnsRecord::MX(MXRecord {
326 exchange: record.content,
327 priority: record.priority.unwrap_or(0),
328 })),
329 DnsRecordType::TXT => Ok(DnsRecord::TXT(unquote_txt(&record.content))),
330 DnsRecordType::SRV => parse_srv(&record.content, record.priority.unwrap_or(0)),
331 DnsRecordType::TLSA => Err(Error::Unsupported(
332 "TLSA records are not supported by SafeDNS".to_string(),
333 )),
334 DnsRecordType::CAA => parse_caa(&record.content),
335 }
336}
337
338fn parse_srv(content: &str, priority: u16) -> crate::Result<DnsRecord> {
339 let parts: Vec<&str> = content.split_whitespace().collect();
340 if parts.len() != 3 {
341 return Err(Error::Parse(format!(
342 "invalid SRV content (expected `<weight> <port> <target>`): {content}"
343 )));
344 }
345 let weight: u16 = parts[0]
346 .parse()
347 .map_err(|e| Error::Parse(format!("invalid SRV weight {}: {e}", parts[0])))?;
348 let port: u16 = parts[1]
349 .parse()
350 .map_err(|e| Error::Parse(format!("invalid SRV port {}: {e}", parts[1])))?;
351 Ok(DnsRecord::SRV(SRVRecord {
352 priority,
353 weight,
354 port,
355 target: parts[2].to_string(),
356 }))
357}
358
359fn parse_caa(content: &str) -> crate::Result<DnsRecord> {
360 let trimmed = content.trim();
361 let (flags_str, rest) = trimmed
362 .split_once(char::is_whitespace)
363 .ok_or_else(|| Error::Parse(format!("invalid CAA content: {content}")))?;
364 let (tag, value_part) = rest
365 .trim_start()
366 .split_once(char::is_whitespace)
367 .ok_or_else(|| Error::Parse(format!("invalid CAA content: {content}")))?;
368 let flags: u8 = flags_str
369 .parse()
370 .map_err(|e| Error::Parse(format!("invalid CAA flags {flags_str}: {e}")))?;
371 let value = value_part
372 .trim()
373 .trim_start_matches('"')
374 .trim_end_matches('"')
375 .to_string();
376 let issuer_critical = flags & 0x80 != 0;
377 match tag.trim() {
378 "issue" => {
379 let (name, options) = split_caa_value(&value);
380 Ok(DnsRecord::CAA(CAARecord::Issue {
381 issuer_critical,
382 name,
383 options,
384 }))
385 }
386 "issuewild" => {
387 let (name, options) = split_caa_value(&value);
388 Ok(DnsRecord::CAA(CAARecord::IssueWild {
389 issuer_critical,
390 name,
391 options,
392 }))
393 }
394 "iodef" => Ok(DnsRecord::CAA(CAARecord::Iodef {
395 issuer_critical,
396 url: value,
397 })),
398 other => Err(Error::Parse(format!("unknown CAA tag: {other}"))),
399 }
400}
401
402impl TryFrom<DnsRecord> for SafeDnsRecordContent {
403 type Error = Error;
404
405 fn try_from(record: DnsRecord) -> Result<Self, Self::Error> {
406 match record {
407 DnsRecord::A(addr) => Ok(SafeDnsRecordContent {
408 record_type: "A",
409 content: addr.to_string(),
410 priority: None,
411 }),
412 DnsRecord::AAAA(addr) => Ok(SafeDnsRecordContent {
413 record_type: "AAAA",
414 content: addr.to_string(),
415 priority: None,
416 }),
417 DnsRecord::CNAME(target) => Ok(SafeDnsRecordContent {
418 record_type: "CNAME",
419 content: target,
420 priority: None,
421 }),
422 DnsRecord::NS(target) => Ok(SafeDnsRecordContent {
423 record_type: "NS",
424 content: target,
425 priority: None,
426 }),
427 DnsRecord::MX(mx) => Ok(SafeDnsRecordContent {
428 record_type: "MX",
429 content: mx.exchange,
430 priority: Some(mx.priority),
431 }),
432 DnsRecord::TXT(text) => {
433 let mut buf = String::new();
434 txt_chunks_to_text(&mut buf, &text, " ");
435 Ok(SafeDnsRecordContent {
436 record_type: "TXT",
437 content: buf,
438 priority: None,
439 })
440 }
441 DnsRecord::SRV(srv) => Ok(SafeDnsRecordContent {
442 record_type: "SRV",
443 content: format!("{} {} {}", srv.weight, srv.port, srv.target),
444 priority: Some(srv.priority),
445 }),
446 DnsRecord::TLSA(_) => Err(Error::Unsupported(
447 "TLSA records are not supported by SafeDNS".to_string(),
448 )),
449 DnsRecord::CAA(caa) => {
450 let (flags, tag, value) = caa.decompose();
451 Ok(SafeDnsRecordContent {
452 record_type: "CAA",
453 content: format!("{flags} {tag} \"{value}\""),
454 priority: None,
455 })
456 }
457 }
458 }
459}