1use crate::utils::build_caa;
13use crate::utils::unquote_txt;
14use crate::utils::{
15 decode_hex, tlsa_cert_usage_from_u8, tlsa_matching_from_u8, tlsa_selector_from_u8,
16};
17use crate::{
18 DnsRecord, DnsRecordType, Error, IntoFqdn, MXRecord, SRVRecord, TLSARecord,
19 http::{HttpClient, HttpClientBuilder},
20 utils::txt_chunks_to_text,
21};
22use serde::{Deserialize, Serialize};
23use serde_json::Value;
24use std::{
25 borrow::Cow,
26 net::{Ipv4Addr, Ipv6Addr},
27 time::Duration,
28};
29
30#[derive(Clone)]
31pub struct CloudflareProvider {
32 client: HttpClient,
33 endpoint: Cow<'static, str>,
34}
35
36#[derive(Deserialize, Debug)]
37pub struct IdMap {
38 pub id: String,
39 pub name: String,
40}
41
42#[derive(Serialize, Debug)]
43pub struct Query {
44 name: String,
45 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
46 record_type: Option<&'static str>,
47 #[serde(rename = "match", skip_serializing_if = "Option::is_none")]
48 match_mode: Option<&'static str>,
49}
50
51#[derive(Serialize, Clone, Debug)]
52pub struct CreateDnsRecordParams<'a> {
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub ttl: Option<u32>,
55 #[serde(skip_serializing_if = "Option::is_none")]
56 pub priority: Option<u16>,
57 #[serde(skip_serializing_if = "Option::is_none")]
58 pub proxied: Option<bool>,
59 pub name: &'a str,
60 #[serde(flatten)]
61 pub content: DnsContent,
62}
63
64#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
65#[serde(tag = "type")]
66#[allow(clippy::upper_case_acronyms)]
67pub enum DnsContent {
68 A { content: Ipv4Addr },
69 AAAA { content: Ipv6Addr },
70 CNAME { content: String },
71 NS { content: String },
72 MX { content: String, priority: u16 },
73 TXT { content: String },
74 SRV { data: SrvData },
75 TLSA { data: TlsaData },
76 CAA { data: CaaData },
77}
78
79#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
80pub struct SrvData {
81 pub priority: u16,
82 pub weight: u16,
83 pub port: u16,
84 pub target: String,
85}
86
87#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
88pub struct TlsaData {
89 pub usage: u8,
90 pub selector: u8,
91 pub matching_type: u8,
92 pub certificate: String,
93}
94
95#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
96pub struct CaaData {
97 pub flags: u8,
98 pub tag: String,
99 pub value: String,
100}
101
102#[derive(Deserialize, Debug, Clone)]
103struct ListedRecord {
104 id: String,
105 #[serde(flatten)]
106 content: DnsContent,
107}
108
109#[derive(Deserialize, Serialize, Debug)]
110struct ApiResult<T> {
111 errors: Vec<ApiError>,
112 success: bool,
113 result: T,
114}
115
116const DEFAULT_API_ENDPOINT: &str = "https://api.cloudflare.com/client/v4";
117
118#[derive(Deserialize, Serialize, Debug)]
119pub struct ApiError {
120 pub code: u16,
121 pub message: String,
122}
123
124impl CloudflareProvider {
125 pub(crate) fn new(secret: impl AsRef<str>, timeout: Option<Duration>) -> crate::Result<Self> {
126 let client = HttpClientBuilder::default()
127 .with_header("Authorization", format!("Bearer {}", secret.as_ref()))
128 .with_timeout(timeout)
129 .build();
130
131 Ok(Self {
132 client,
133 endpoint: Cow::Borrowed(DEFAULT_API_ENDPOINT),
134 })
135 }
136
137 #[cfg(test)]
138 pub(crate) fn with_endpoint(self, endpoint: impl Into<Cow<'static, str>>) -> Self {
139 Self {
140 endpoint: endpoint.into(),
141 ..self
142 }
143 }
144
145 async fn obtain_zone_id(&self, origin: impl IntoFqdn<'_>) -> crate::Result<String> {
146 let origin = origin.into_name();
147 let mut candidate: &str = origin.as_ref();
148 loop {
149 let zones = self
150 .client
151 .get(format!(
152 "{}/zones?{}",
153 self.endpoint,
154 Query::name(candidate).serialize()
155 ))
156 .send_with_retry::<ApiResult<Vec<IdMap>>>(3)
157 .await
158 .and_then(|r| r.unwrap_response("list zones"))?;
159 if let Some(zone) = zones.into_iter().find(|zone| zone.name == candidate) {
160 return Ok(zone.id);
161 }
162 match candidate.split_once('.') {
163 Some((_, rest)) if rest.contains('.') => candidate = rest,
164 _ => {
165 return Err(Error::Api(format!(
166 "No Cloudflare zone found for {}",
167 origin.as_ref()
168 )));
169 }
170 }
171 }
172 }
173
174 pub(crate) async fn set_rrset(
175 &self,
176 name: impl IntoFqdn<'_>,
177 record_type: DnsRecordType,
178 ttl: u32,
179 records: Vec<DnsRecord>,
180 origin: impl IntoFqdn<'_>,
181 ) -> crate::Result<()> {
182 let zone_id = self.obtain_zone_id(origin).await?;
183 let name = name.into_name().into_owned();
184 let desired = build_contents(record_type, records)?;
185 let existing = self.list_at(&zone_id, &name, record_type).await?;
186
187 let mut to_add = Vec::new();
188 let mut existing_unmatched: Vec<ListedRecord> = Vec::new();
189 let mut existing_iter = existing.into_iter();
190 let mut existing_pool: Vec<ListedRecord> = existing_iter.by_ref().collect();
191
192 for content in desired {
193 if let Some(idx) = existing_pool.iter().position(|r| r.content == content) {
194 existing_pool.swap_remove(idx);
195 } else {
196 to_add.push(content);
197 }
198 }
199 existing_unmatched.append(&mut existing_pool);
200
201 for entry in existing_unmatched {
202 self.delete_record(&zone_id, &entry.id).await?;
203 }
204 for content in to_add {
205 self.create_record(&zone_id, &name, ttl, content).await?;
206 }
207 Ok(())
208 }
209
210 pub(crate) async fn add_to_rrset(
211 &self,
212 name: impl IntoFqdn<'_>,
213 record_type: DnsRecordType,
214 ttl: u32,
215 records: Vec<DnsRecord>,
216 origin: impl IntoFqdn<'_>,
217 ) -> crate::Result<()> {
218 if records.is_empty() {
219 return Ok(());
220 }
221 let zone_id = self.obtain_zone_id(origin).await?;
222 let name = name.into_name().into_owned();
223 let desired = build_contents(record_type, records)?;
224 let existing = self.list_at(&zone_id, &name, record_type).await?;
225
226 for content in desired {
227 if existing.iter().any(|r| r.content == content) {
228 continue;
229 }
230 self.create_record(&zone_id, &name, ttl, content).await?;
231 }
232 Ok(())
233 }
234
235 pub(crate) async fn remove_from_rrset(
236 &self,
237 name: impl IntoFqdn<'_>,
238 record_type: DnsRecordType,
239 records: Vec<DnsRecord>,
240 origin: impl IntoFqdn<'_>,
241 ) -> crate::Result<()> {
242 if records.is_empty() {
243 return Ok(());
244 }
245 let zone_id = self.obtain_zone_id(origin).await?;
246 let name = name.into_name().into_owned();
247 let to_remove = build_contents(record_type, records)?;
248 let existing = self.list_at(&zone_id, &name, record_type).await?;
249
250 for content in to_remove {
251 if let Some(entry) = existing.iter().find(|r| r.content == content) {
252 self.delete_record(&zone_id, &entry.id).await?;
253 }
254 }
255 Ok(())
256 }
257
258 pub(crate) async fn list_rrset(
259 &self,
260 name: impl IntoFqdn<'_>,
261 record_type: DnsRecordType,
262 origin: impl IntoFqdn<'_>,
263 ) -> crate::Result<Vec<DnsRecord>> {
264 let zone_id = self.obtain_zone_id(origin).await?;
265 let name = name.into_name().into_owned();
266 let listed = self.list_at(&zone_id, &name, record_type).await?;
267 listed.into_iter().map(|r| r.content.try_into()).collect()
268 }
269
270 #[cfg(test)]
271 pub(crate) async fn list_contents_for_tests(
272 &self,
273 name: impl IntoFqdn<'_>,
274 record_type: DnsRecordType,
275 origin: impl IntoFqdn<'_>,
276 ) -> crate::Result<Vec<DnsContent>> {
277 let zone_id = self.obtain_zone_id(origin).await?;
278 let name = name.into_name().into_owned();
279 let listed = self.list_at(&zone_id, &name, record_type).await?;
280 Ok(listed.into_iter().map(|r| r.content).collect())
281 }
282
283 async fn list_at(
284 &self,
285 zone_id: &str,
286 name: &str,
287 record_type: DnsRecordType,
288 ) -> crate::Result<Vec<ListedRecord>> {
289 let url = format!(
290 "{}/zones/{zone_id}/dns_records?{}&per_page=100",
291 self.endpoint,
292 Query::name_and_type(name, record_type).serialize()
293 );
294 let response: ApiResult<Vec<ListedRecord>> =
295 self.client.get(url).send_with_retry(3).await?;
296 response.unwrap_response("list DNS records")
297 }
298
299 async fn create_record(
300 &self,
301 zone_id: &str,
302 name: &str,
303 ttl: u32,
304 content: DnsContent,
305 ) -> crate::Result<()> {
306 let priority = match &content {
307 DnsContent::MX { priority, .. } => Some(*priority),
308 _ => None,
309 };
310 self.client
311 .post(format!("{}/zones/{zone_id}/dns_records", self.endpoint))
312 .with_body(CreateDnsRecordParams {
313 ttl: Some(ttl),
314 priority,
315 proxied: Some(false),
316 name,
317 content,
318 })?
319 .send_with_retry::<ApiResult<Value>>(3)
320 .await
321 .map(|_| ())
322 }
323
324 async fn delete_record(&self, zone_id: &str, record_id: &str) -> crate::Result<()> {
325 self.client
326 .delete(format!(
327 "{}/zones/{zone_id}/dns_records/{record_id}",
328 self.endpoint
329 ))
330 .send_with_retry::<ApiResult<Value>>(3)
331 .await
332 .map(|_| ())
333 }
334}
335
336fn build_contents(
337 expected_type: DnsRecordType,
338 records: Vec<DnsRecord>,
339) -> crate::Result<Vec<DnsContent>> {
340 let mut out = Vec::with_capacity(records.len());
341 for record in records {
342 if record.as_type() != expected_type {
343 return Err(Error::Api(format!(
344 "RRSet record type mismatch: expected {}, got {}",
345 expected_type.as_str(),
346 record.as_type().as_str(),
347 )));
348 }
349 out.push(record.into());
350 }
351 Ok(out)
352}
353
354impl<T> ApiResult<T> {
355 fn unwrap_response(self, action_name: &str) -> crate::Result<T> {
356 if self.success {
357 Ok(self.result)
358 } else {
359 Err(Error::Api(format!(
360 "Failed to {action_name}: {:?}",
361 self.errors
362 )))
363 }
364 }
365}
366
367impl Query {
368 pub fn name(name: impl Into<String>) -> Self {
369 Self {
370 name: name.into(),
371 record_type: None,
372 match_mode: None,
373 }
374 }
375
376 pub fn name_and_type(name: impl Into<String>, record_type: DnsRecordType) -> Self {
377 Self {
378 name: name.into(),
379 record_type: Some(record_type.as_str()),
380 match_mode: Some("all"),
381 }
382 }
383
384 pub fn serialize(&self) -> String {
385 serde_urlencoded::to_string(self).unwrap()
386 }
387}
388
389impl From<DnsRecord> for DnsContent {
390 fn from(record: DnsRecord) -> Self {
391 match record {
392 DnsRecord::A(content) => DnsContent::A { content },
393 DnsRecord::AAAA(content) => DnsContent::AAAA { content },
394 DnsRecord::CNAME(content) => DnsContent::CNAME { content },
395 DnsRecord::NS(content) => DnsContent::NS { content },
396 DnsRecord::MX(mx) => DnsContent::MX {
397 content: mx.exchange,
398 priority: mx.priority,
399 },
400 DnsRecord::TXT(content) => {
401 let mut out = String::with_capacity(content.len() + 4);
402 txt_chunks_to_text(&mut out, &content, " ");
403 DnsContent::TXT { content: out }
404 }
405 DnsRecord::SRV(srv) => DnsContent::SRV {
406 data: SrvData {
407 priority: srv.priority,
408 weight: srv.weight,
409 port: srv.port,
410 target: srv.target,
411 },
412 },
413 DnsRecord::TLSA(tlsa) => DnsContent::TLSA {
414 data: TlsaData {
415 usage: u8::from(tlsa.cert_usage),
416 selector: u8::from(tlsa.selector),
417 matching_type: u8::from(tlsa.matching),
418 certificate: tlsa.cert_data.iter().map(|b| format!("{b:02x}")).collect(),
419 },
420 },
421 DnsRecord::CAA(caa) => {
422 let (flags, tag, value) = caa.decompose();
423 DnsContent::CAA {
424 data: CaaData { flags, tag, value },
425 }
426 }
427 }
428 }
429}
430
431impl TryFrom<DnsContent> for DnsRecord {
432 type Error = Error;
433
434 fn try_from(content: DnsContent) -> crate::Result<Self> {
435 Ok(match content {
436 DnsContent::A { content } => DnsRecord::A(content),
437 DnsContent::AAAA { content } => DnsRecord::AAAA(content),
438 DnsContent::CNAME { content } => DnsRecord::CNAME(content),
439 DnsContent::NS { content } => DnsRecord::NS(content),
440 DnsContent::MX { content, priority } => DnsRecord::MX(MXRecord {
441 exchange: content,
442 priority,
443 }),
444 DnsContent::TXT { content } => DnsRecord::TXT(unquote_txt(&content)),
445 DnsContent::SRV { data } => DnsRecord::SRV(SRVRecord {
446 priority: data.priority,
447 weight: data.weight,
448 port: data.port,
449 target: data.target,
450 }),
451 DnsContent::TLSA { data } => DnsRecord::TLSA(TLSARecord {
452 cert_usage: tlsa_cert_usage_from_u8(data.usage)?,
453 selector: tlsa_selector_from_u8(data.selector)?,
454 matching: tlsa_matching_from_u8(data.matching_type)?,
455 cert_data: decode_hex(&data.certificate)?,
456 }),
457 DnsContent::CAA { data } => {
458 DnsRecord::CAA(build_caa(data.flags, &data.tag, &data.value)?)
459 }
460 })
461 }
462}