manydns 1.1.1

Provider-agnostic DNS zone and record management, inspired by the Go libdns project
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! Low-level Cloudflare DNS API client.
//!
//! This module provides direct access to the Cloudflare DNS API.
//!
//! # API Reference
//!
//! - [DNS Records](https://developers.cloudflare.com/api/resources/dns/subresources/records/)
//! - [Zones](https://developers.cloudflare.com/api/resources/zones/)

use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::HttpClientConfig;

/// The Cloudflare API base URL.
const CLOUDFLARE_API_URL: &str = "https://api.cloudflare.com/client/v4";

/// Errors that may occur when interacting with the Cloudflare API.
#[derive(Debug, Error)]
pub enum CloudflareError {
    /// The API returned an error response.
    #[error("API error: {0}")]
    Api(ApiError),

    /// An HTTP request error occurred.
    #[error("HTTP request error: {0}")]
    Request(#[from] reqwest::Error),

    /// Failed to serialize/deserialize.
    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),
}

/// Cloudflare API error.
#[derive(Debug, Clone, Deserialize)]
pub struct ApiError {
    /// Error code.
    pub code: i32,
    /// Error message.
    pub message: String,
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code, self.message)
    }
}

/// Cloudflare API response wrapper.
#[derive(Debug, Deserialize)]
struct ApiResponse<T> {
    success: bool,
    errors: Vec<ApiError>,
    #[serde(default)]
    #[allow(dead_code)]
    messages: Vec<serde_json::Value>,
    result: Option<T>,
    result_info: Option<ResultInfo>,
}

/// Pagination info.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct ResultInfo {
    page: u32,
    per_page: u32,
    total_pages: u32,
    count: u32,
    total_count: u32,
}

// =============================================================================
// Zone Types
// =============================================================================

/// A Cloudflare zone.
#[derive(Debug, Clone, Deserialize)]
pub struct Zone {
    /// Zone ID (32-character hex string).
    pub id: String,
    /// Domain name.
    pub name: String,
    /// Zone status.
    pub status: String,
    /// Whether the zone is paused.
    #[serde(default)]
    pub paused: bool,
    /// Zone type (full, partial, secondary).
    #[serde(rename = "type")]
    pub zone_type: Option<String>,
}

// =============================================================================
// DNS Record Types
// =============================================================================

/// A DNS record from Cloudflare.
#[derive(Debug, Clone, Deserialize)]
pub struct DnsRecord {
    /// Record ID (32-character hex string).
    pub id: String,
    /// Zone ID.
    #[serde(default)]
    pub zone_id: Option<String>,
    /// Zone name.
    #[serde(default)]
    pub zone_name: Option<String>,
    /// DNS record name (e.g., "example.com").
    pub name: String,
    /// Record type (A, AAAA, CNAME, etc.).
    #[serde(rename = "type")]
    pub record_type: String,
    /// Record content/value.
    pub content: String,
    /// Whether the record is proxied through Cloudflare.
    #[serde(default)]
    pub proxied: bool,
    /// TTL in seconds. 1 = automatic.
    pub ttl: u32,
    /// Priority for MX/SRV records.
    #[serde(default)]
    pub priority: Option<u16>,
    /// Record comment.
    #[serde(default)]
    pub comment: Option<String>,
    /// Record tags.
    #[serde(default)]
    pub tags: Vec<String>,
    /// SRV record data.
    #[serde(default)]
    pub data: Option<SrvData>,
}

/// SRV record data structure.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SrvData {
    /// Service name (without underscore prefix).
    #[serde(default)]
    pub service: Option<String>,
    /// Protocol (without underscore prefix).
    #[serde(default)]
    pub proto: Option<String>,
    /// Record name.
    #[serde(default)]
    pub name: Option<String>,
    /// Priority.
    #[serde(default)]
    pub priority: Option<u16>,
    /// Weight.
    #[serde(default)]
    pub weight: Option<u16>,
    /// Port.
    #[serde(default)]
    pub port: Option<u16>,
    /// Target hostname.
    #[serde(default)]
    pub target: Option<String>,
}

/// Request body for creating/updating DNS records.
#[derive(Debug, Serialize)]
pub struct CreateRecordRequest {
    /// Record type.
    #[serde(rename = "type")]
    pub record_type: String,
    /// DNS record name (e.g., "subdomain" or "subdomain.example.com").
    pub name: String,
    /// Record content/value.
    pub content: String,
    /// TTL in seconds. 1 = automatic.
    pub ttl: u32,
    /// Whether to proxy through Cloudflare.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxied: Option<bool>,
    /// Priority for MX records.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<u16>,
    /// SRV record data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<SrvData>,
}

/// Supported DNS record types for Cloudflare.
const SUPPORTED_RECORD_TYPES: &[&str] = &["A", "AAAA", "CNAME", "MX", "NS", "TXT", "SRV"];

/// Error returned when a record cannot be converted to a [`crate::Record`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecordConversionError {
    /// The record type that failed to convert.
    pub record_type: String,
    /// Description of what went wrong.
    pub reason: &'static str,
}

impl std::fmt::Display for RecordConversionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "failed to convert {} record: {}",
            self.record_type, self.reason
        )
    }
}

impl std::error::Error for RecordConversionError {}

/// A DNS record with its associated zone name for conversion.
///
/// This wrapper is used to implement `TryFrom` for converting Cloudflare
/// DNS records to generic [`crate::Record`] types, since the zone name
/// is needed to extract the subdomain.
pub struct DnsRecordWithZone<'a> {
    /// The DNS record.
    pub record: &'a DnsRecord,
    /// The zone domain name.
    pub zone_name: &'a str,
}

impl<'a> DnsRecordWithZone<'a> {
    /// Creates a new record-with-zone wrapper.
    pub fn new(record: &'a DnsRecord, zone_name: &'a str) -> Self {
        Self { record, zone_name }
    }
}

impl TryFrom<DnsRecordWithZone<'_>> for crate::Record {
    type Error = RecordConversionError;

    fn try_from(value: DnsRecordWithZone<'_>) -> Result<Self, Self::Error> {
        use crate::RecordData;

        let record = value.record;
        let zone_name = value.zone_name;

        // Extract the subdomain from the full record name
        let host = if record.name == zone_name {
            "@".to_string()
        } else if record.name.ends_with(&format!(".{}", zone_name)) {
            record.name[..record.name.len() - zone_name.len() - 1].to_string()
        } else {
            record.name.clone()
        };

        let data =
            match record.record_type.as_str() {
                "A" => record.content.parse().map(RecordData::A).map_err(|_| {
                    RecordConversionError {
                        record_type: record.record_type.clone(),
                        reason: "invalid IPv4 address",
                    }
                })?,
                "AAAA" => record.content.parse().map(RecordData::AAAA).map_err(|_| {
                    RecordConversionError {
                        record_type: record.record_type.clone(),
                        reason: "invalid IPv6 address",
                    }
                })?,
                "CNAME" => RecordData::CNAME(record.content.clone()),
                "MX" => RecordData::MX {
                    priority: record.priority.unwrap_or(10),
                    mail_server: record.content.clone(),
                },
                "NS" => RecordData::NS(record.content.clone()),
                "TXT" => RecordData::TXT(record.content.clone()),
                "SRV" => {
                    // SRV records have structured data
                    if let Some(data) = &record.data {
                        RecordData::SRV {
                            priority: data.priority.unwrap_or(0),
                            weight: data.weight.unwrap_or(0),
                            port: data.port.unwrap_or(0),
                            target: data.target.clone().unwrap_or_default(),
                        }
                    } else {
                        // Fallback: parse from content "priority weight port target"
                        let parts: Vec<&str> = record.content.split_whitespace().collect();
                        if parts.len() >= 4 {
                            RecordData::SRV {
                                priority: parts[0].parse().unwrap_or(0),
                                weight: parts[1].parse().unwrap_or(0),
                                port: parts[2].parse().unwrap_or(0),
                                target: parts[3].to_string(),
                            }
                        } else {
                            return Err(RecordConversionError {
                                record_type: record.record_type.clone(),
                                reason: "SRV record requires 4 parts: priority weight port target",
                            });
                        }
                    }
                }
                _ => {
                    return Err(RecordConversionError {
                        record_type: record.record_type.clone(),
                        reason: "unsupported record type",
                    });
                }
            };

        Ok(crate::Record {
            id: record.id.clone(),
            host,
            data,
            ttl: record.ttl as u64,
        })
    }
}

/// Error returned when building a [`CreateRecordRequest`] fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CreateRequestError {
    /// The record type is not supported by Cloudflare.
    UnsupportedType,
}

impl CreateRecordRequest {
    /// Creates a new record request from generic record data.
    ///
    /// # Arguments
    ///
    /// * `host` - The subdomain or "@" for the zone apex.
    /// * `data` - The record data.
    /// * `ttl` - Time to live in seconds. Use 0 for automatic.
    /// * `zone_name` - The zone domain name.
    ///
    /// # Returns
    ///
    /// Returns an error if the record type is not supported.
    pub fn from_record_data(
        host: &str,
        data: &crate::RecordData,
        ttl: u64,
        zone_name: &str,
    ) -> Result<Self, CreateRequestError> {
        use crate::RecordData;

        // Build the full record name
        let name = if host == "@" || host.is_empty() {
            zone_name.to_string()
        } else if host.ends_with(zone_name) {
            host.to_string()
        } else {
            format!("{}.{}", host, zone_name)
        };

        let (record_type, content, priority, srv_data) = match data {
            RecordData::A(ip) => ("A".to_string(), ip.to_string(), None, None),
            RecordData::AAAA(ip) => ("AAAA".to_string(), ip.to_string(), None, None),
            RecordData::CNAME(target) => ("CNAME".to_string(), target.clone(), None, None),
            RecordData::MX {
                priority,
                mail_server,
            } => ("MX".to_string(), mail_server.clone(), Some(*priority), None),
            RecordData::NS(ns) => ("NS".to_string(), ns.clone(), None, None),
            RecordData::TXT(txt) => ("TXT".to_string(), txt.clone(), None, None),
            RecordData::SRV {
                priority,
                weight,
                port,
                target,
            } => {
                // For SRV records, we need to use the data field
                let srv_data = SrvData {
                    service: None, // Parsed from name by Cloudflare
                    proto: None,   // Parsed from name by Cloudflare
                    name: None,
                    priority: Some(*priority),
                    weight: Some(*weight),
                    port: Some(*port),
                    target: Some(target.clone()),
                };
                // Content format for SRV: "weight port target"
                let content = format!("{} {} {}", weight, port, target);
                ("SRV".to_string(), content, Some(*priority), Some(srv_data))
            }
            RecordData::Other { typ, value } => {
                // Pass through other record types as-is
                (typ.clone(), value.clone(), None, None)
            }
        };

        // Check if record type is supported
        if !SUPPORTED_RECORD_TYPES.contains(&record_type.as_str()) {
            return Err(CreateRequestError::UnsupportedType);
        }

        Ok(Self {
            record_type,
            name,
            content,
            ttl: if ttl == 0 { 1 } else { ttl as u32 }, // 1 = automatic TTL
            proxied: Some(false),                       // Don't proxy DNS records by default
            priority,
            data: srv_data,
        })
    }
}

/// Delete response.
#[derive(Debug, Deserialize)]
pub struct DeleteResponse {
    pub id: String,
}

// =============================================================================
// API Client
// =============================================================================

/// Cloudflare API client.
pub struct Client {
    http_client: reqwest::Client,
    api_token: String,
    base_url: String,
}

impl Client {
    /// Creates a new Cloudflare API client.
    ///
    /// # Arguments
    ///
    /// * `api_token` - Cloudflare API token (Bearer token)
    pub fn new(api_token: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        Self::with_base_url(api_token, CLOUDFLARE_API_URL, HttpClientConfig::default())
    }

    /// Creates a new Cloudflare API client with custom HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `api_token` - Cloudflare API token (Bearer token)
    /// * `config` - HTTP client configuration for network binding
    pub fn with_config(
        api_token: &str,
        config: HttpClientConfig,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        Self::with_base_url(api_token, CLOUDFLARE_API_URL, config)
    }

    /// Creates a new Cloudflare API client with a custom base URL.
    ///
    /// This is primarily useful for testing with mock servers.
    ///
    /// # Arguments
    ///
    /// * `api_token` - Cloudflare API token (Bearer token)
    /// * `base_url` - Custom base URL for the API
    /// * `config` - HTTP client configuration for network binding
    pub fn with_base_url(
        api_token: &str,
        base_url: &str,
        config: HttpClientConfig,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        let mut builder = reqwest::Client::builder()
            .timeout(config.timeout.unwrap_or(std::time::Duration::from_secs(30)));

        if let Some(addr) = config.local_address {
            builder = builder.local_address(addr);
        }

        #[cfg(any(
            target_os = "android",
            target_os = "fuchsia",
            target_os = "linux",
            target_os = "macos",
            target_os = "ios",
            target_os = "tvos",
            target_os = "watchos",
            target_os = "illumos",
            target_os = "solaris",
        ))]
        if let Some(ref iface) = config.interface {
            builder = builder.interface(iface);
        }

        let http_client = builder.build()?;

        Ok(Self {
            http_client,
            api_token: api_token.to_string(),
            base_url: base_url.to_string(),
        })
    }

    /// Build headers for API requests.
    fn headers(&self) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTHORIZATION,
            HeaderValue::from_str(&format!("Bearer {}", self.api_token)).unwrap(),
        );
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
        headers
    }

    /// Make a GET request.
    async fn get<T: for<'de> Deserialize<'de>>(&self, path: &str) -> Result<T, CloudflareError> {
        let url = format!("{}{}", self.base_url, path);
        let response = self
            .http_client
            .get(&url)
            .headers(self.headers())
            .send()
            .await?;

        let api_response: ApiResponse<T> = response.json().await?;

        if !api_response.success {
            let error = api_response.errors.into_iter().next().unwrap_or(ApiError {
                code: 0,
                message: "Unknown error".to_string(),
            });
            return Err(CloudflareError::Api(error));
        }

        api_response.result.ok_or_else(|| {
            CloudflareError::Api(ApiError {
                code: 0,
                message: "No result in response".to_string(),
            })
        })
    }

    /// Make a paginated GET request returning a list.
    async fn get_list<T: for<'de> Deserialize<'de>>(
        &self,
        path: &str,
    ) -> Result<Vec<T>, CloudflareError> {
        let mut all_results = Vec::new();
        let mut page = 1u32;

        loop {
            let url = if path.contains('?') {
                format!("{}{}&page={}&per_page=100", self.base_url, path, page)
            } else {
                format!("{}{}?page={}&per_page=100", self.base_url, path, page)
            };

            let response = self
                .http_client
                .get(&url)
                .headers(self.headers())
                .send()
                .await?;

            let api_response: ApiResponse<Vec<T>> = response.json().await?;

            if !api_response.success {
                let error = api_response.errors.into_iter().next().unwrap_or(ApiError {
                    code: 0,
                    message: "Unknown error".to_string(),
                });
                return Err(CloudflareError::Api(error));
            }

            if let Some(results) = api_response.result {
                let count = results.len();
                all_results.extend(results);

                // Check if we have more pages
                if let Some(info) = api_response.result_info {
                    if page >= info.total_pages || count == 0 {
                        break;
                    }
                    page += 1;
                } else {
                    break;
                }
            } else {
                break;
            }
        }

        Ok(all_results)
    }

    /// Make a POST request.
    async fn post<Req: Serialize, Resp: for<'de> Deserialize<'de>>(
        &self,
        path: &str,
        body: &Req,
    ) -> Result<Resp, CloudflareError> {
        let url = format!("{}{}", self.base_url, path);
        let response = self
            .http_client
            .post(&url)
            .headers(self.headers())
            .json(body)
            .send()
            .await?;

        let api_response: ApiResponse<Resp> = response.json().await?;

        if !api_response.success {
            let error = api_response.errors.into_iter().next().unwrap_or(ApiError {
                code: 0,
                message: "Unknown error".to_string(),
            });
            return Err(CloudflareError::Api(error));
        }

        api_response.result.ok_or_else(|| {
            CloudflareError::Api(ApiError {
                code: 0,
                message: "No result in response".to_string(),
            })
        })
    }

    /// Make a DELETE request.
    async fn delete<T: for<'de> Deserialize<'de>>(&self, path: &str) -> Result<T, CloudflareError> {
        let url = format!("{}{}", self.base_url, path);
        let response = self
            .http_client
            .delete(&url)
            .headers(self.headers())
            .send()
            .await?;

        let api_response: ApiResponse<T> = response.json().await?;

        if !api_response.success {
            let error = api_response.errors.into_iter().next().unwrap_or(ApiError {
                code: 0,
                message: "Unknown error".to_string(),
            });
            return Err(CloudflareError::Api(error));
        }

        api_response.result.ok_or_else(|| {
            CloudflareError::Api(ApiError {
                code: 0,
                message: "No result in response".to_string(),
            })
        })
    }

    // =========================================================================
    // Zone APIs
    // =========================================================================

    /// Lists all zones accessible by the API token.
    pub async fn list_zones(&self) -> Result<Vec<Zone>, CloudflareError> {
        self.get_list("/zones").await
    }

    /// Gets a zone by ID.
    pub async fn get_zone(&self, zone_id: &str) -> Result<Zone, CloudflareError> {
        self.get(&format!("/zones/{}", zone_id)).await
    }

    /// Gets a zone by name (domain).
    pub async fn get_zone_by_name(&self, name: &str) -> Result<Zone, CloudflareError> {
        let zones: Vec<Zone> = self.get_list(&format!("/zones?name={}", name)).await?;
        zones.into_iter().next().ok_or_else(|| {
            CloudflareError::Api(ApiError {
                code: 1003,
                message: format!("Zone '{}' not found", name),
            })
        })
    }

    // =========================================================================
    // DNS Record APIs
    // =========================================================================

    /// Lists all DNS records in a zone.
    pub async fn list_records(&self, zone_id: &str) -> Result<Vec<DnsRecord>, CloudflareError> {
        self.get_list(&format!("/zones/{}/dns_records", zone_id))
            .await
    }

    /// Gets a DNS record by ID.
    pub async fn get_record(
        &self,
        zone_id: &str,
        record_id: &str,
    ) -> Result<DnsRecord, CloudflareError> {
        self.get(&format!("/zones/{}/dns_records/{}", zone_id, record_id))
            .await
    }

    /// Creates a new DNS record.
    pub async fn create_record(
        &self,
        zone_id: &str,
        request: &CreateRecordRequest,
    ) -> Result<DnsRecord, CloudflareError> {
        self.post(&format!("/zones/{}/dns_records", zone_id), request)
            .await
    }

    /// Deletes a DNS record.
    pub async fn delete_record(
        &self,
        zone_id: &str,
        record_id: &str,
    ) -> Result<DeleteResponse, CloudflareError> {
        self.delete(&format!("/zones/{}/dns_records/{}", zone_id, record_id))
            .await
    }
}