dns-update 0.5.1

Dynamic DNS update (RFC 2136 and cloud) library for Rust
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
/*
 * Copyright Stalwart Labs LLC See the COPYING
 * file at the top-level directory of this distribution.
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */

use crate::http::{HttpClient, HttpClientBuilder};
use crate::{
    CAARecord, DnsRecord, DnsRecordType, Error, IntoFqdn, KeyValue, MXRecord, SRVRecord,
    TLSARecord, TlsaCertUsage, TlsaMatching, TlsaSelector, crypto, utils::strip_origin_from_name,
};
use reqwest::Method;
use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

#[derive(Clone)]
pub struct OvhProvider {
    application_key: String,
    application_secret: String,
    consumer_key: String,
    pub(crate) endpoint: String,
    client: HttpClient,
}

#[derive(Serialize, Debug)]
pub struct CreateDnsRecordParams {
    #[serde(rename = "fieldType")]
    pub field_type: String,
    #[serde(rename = "subDomain")]
    pub sub_domain: String,
    pub target: String,
    pub ttl: u32,
}

#[derive(Serialize, Debug)]
pub struct UpdateDnsRecordParams {
    pub target: String,
    pub ttl: u32,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OvhRecordFormat {
    pub field_type: String,
    pub target: String,
}

#[derive(Deserialize, Debug)]
struct OvhRecordBody {
    id: u64,
    #[serde(rename = "fieldType")]
    field_type: String,
    target: String,
}

#[derive(Debug)]
pub enum OvhEndpoint {
    OvhEu,
    OvhCa,
    KimsufiEu,
    KimsufiCa,
    SoyoustartEu,
    SoyoustartCa,
}

impl OvhEndpoint {
    fn api_url(&self) -> &'static str {
        match self {
            OvhEndpoint::OvhEu => "https://eu.api.ovh.com/1.0",
            OvhEndpoint::OvhCa => "https://ca.api.ovh.com/1.0",
            OvhEndpoint::KimsufiEu => "https://eu.api.kimsufi.com/1.0",
            OvhEndpoint::KimsufiCa => "https://ca.api.kimsufi.com/1.0",
            OvhEndpoint::SoyoustartEu => "https://eu.api.soyoustart.com/1.0",
            OvhEndpoint::SoyoustartCa => "https://ca.api.soyoustart.com/1.0",
        }
    }
}

impl std::str::FromStr for OvhEndpoint {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ovh-eu" => Ok(OvhEndpoint::OvhEu),
            "ovh-ca" => Ok(OvhEndpoint::OvhCa),
            "kimsufi-eu" => Ok(OvhEndpoint::KimsufiEu),
            "kimsufi-ca" => Ok(OvhEndpoint::KimsufiCa),
            "soyoustart-eu" => Ok(OvhEndpoint::SoyoustartEu),
            "soyoustart-ca" => Ok(OvhEndpoint::SoyoustartCa),
            _ => Err(Error::Parse(format!("Invalid OVH endpoint: {}", s))),
        }
    }
}

impl From<&DnsRecord> for OvhRecordFormat {
    fn from(record: &DnsRecord) -> Self {
        match record {
            DnsRecord::A(content) => OvhRecordFormat {
                field_type: "A".to_string(),
                target: content.to_string(),
            },
            DnsRecord::AAAA(content) => OvhRecordFormat {
                field_type: "AAAA".to_string(),
                target: content.to_string(),
            },
            DnsRecord::CNAME(content) => OvhRecordFormat {
                field_type: "CNAME".to_string(),
                target: format!("{}.", content.trim_end_matches('.')),
            },
            DnsRecord::NS(content) => OvhRecordFormat {
                field_type: "NS".to_string(),
                target: format!("{}.", content.trim_end_matches('.')),
            },
            DnsRecord::MX(mx) => OvhRecordFormat {
                field_type: "MX".to_string(),
                target: format!("{} {}.", mx.priority, mx.exchange.trim_end_matches('.')),
            },
            DnsRecord::TXT(content) => OvhRecordFormat {
                field_type: "TXT".to_string(),
                target: content.clone(),
            },
            DnsRecord::SRV(srv) => OvhRecordFormat {
                field_type: "SRV".to_string(),
                target: format!(
                    "{} {} {} {}.",
                    srv.priority,
                    srv.weight,
                    srv.port,
                    srv.target.trim_end_matches('.')
                ),
            },
            DnsRecord::TLSA(tlsa) => OvhRecordFormat {
                field_type: "TLSA".to_string(),
                target: tlsa.to_string(),
            },
            DnsRecord::CAA(caa) => OvhRecordFormat {
                field_type: "CAA".to_string(),
                target: caa.to_string(),
            },
        }
    }
}

impl OvhProvider {
    pub(crate) fn new(
        application_key: impl AsRef<str>,
        application_secret: impl AsRef<str>,
        consumer_key: impl AsRef<str>,
        endpoint: OvhEndpoint,
        timeout: Option<Duration>,
    ) -> crate::Result<Self> {
        let client = HttpClientBuilder::default()
            .with_timeout(timeout.or(Some(Duration::from_secs(30))))
            .build();
        Ok(Self {
            application_key: application_key.as_ref().to_string(),
            application_secret: application_secret.as_ref().to_string(),
            consumer_key: consumer_key.as_ref().to_string(),
            endpoint: endpoint.api_url().to_string(),
            client,
        })
    }

    fn generate_signature(&self, method: &str, url: &str, body: &str, timestamp: u64) -> String {
        let data = format!(
            "{}+{}+{}+{}+{}+{}",
            self.application_secret, self.consumer_key, method, url, body, timestamp
        );

        let hash = crypto::sha1_digest(data.as_bytes());
        let hex_string = hash
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>();
        format!("$1${}", hex_string)
    }

    async fn send_authenticated_request(
        &self,
        method: Method,
        url: &str,
        body: &str,
    ) -> crate::Result<String> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| Error::Client(format!("Failed to get timestamp: {}", e)))?
            .as_secs();

        let signature = self.generate_signature(method.as_str(), url, body, timestamp);

        let mut request = match method {
            Method::GET => self.client.get(url),
            Method::POST => self.client.post(url),
            Method::PUT => self.client.put(url),
            Method::DELETE => self.client.delete(url),
            Method::PATCH => self.client.patch(url),
            other => {
                return Err(Error::Unsupported(format!(
                    "OVH unsupported method: {other}"
                )));
            }
        };
        request = request
            .with_header("X-Ovh-Application", &self.application_key)
            .with_header("X-Ovh-Consumer", &self.consumer_key)
            .with_header("X-Ovh-Signature", signature)
            .with_header("X-Ovh-Timestamp", timestamp.to_string());

        if !body.is_empty() {
            request = request.with_raw_body(body.to_string());
        }

        request.send_raw().await
    }

    async fn get_zone_name(&self, origin: impl IntoFqdn<'_>) -> crate::Result<String> {
        let domain = origin.into_name();
        let domain_name = domain.trim_end_matches('.');

        let url = format!("{}/domain/zone/{}", self.endpoint, domain_name);
        self.send_authenticated_request(Method::GET, &url, "")
            .await
            .map(|_| domain_name.to_string())
            .map_err(|_| Error::Api(format!("Zone {} not found or not accessible", domain_name)))
    }

    async fn list_record_ids(
        &self,
        zone: &str,
        subdomain: &str,
        record_type: DnsRecordType,
    ) -> crate::Result<Vec<u64>> {
        let url = format!(
            "{}/domain/zone/{}/record?fieldType={}&subDomain={}",
            self.endpoint,
            zone,
            record_type.as_str(),
            subdomain
        );
        let body = self
            .send_authenticated_request(Method::GET, &url, "")
            .await?;
        serde_json::from_str(&body)
            .map_err(|e| Error::Api(format!("Failed to parse record list: {}", e)))
    }

    async fn fetch_record(&self, zone: &str, id: u64) -> crate::Result<OvhRecordBody> {
        let url = format!("{}/domain/zone/{}/record/{}", self.endpoint, zone, id);
        let body = self
            .send_authenticated_request(Method::GET, &url, "")
            .await?;
        serde_json::from_str(&body)
            .map_err(|e| Error::Api(format!("Failed to parse record {}: {}", id, e)))
    }

    async fn list_at(
        &self,
        zone: &str,
        subdomain: &str,
        record_type: DnsRecordType,
    ) -> crate::Result<Vec<OvhRecordBody>> {
        let ids = self.list_record_ids(zone, subdomain, record_type).await?;
        let mut out = Vec::with_capacity(ids.len());
        for id in ids {
            let body = self.fetch_record(zone, id).await?;
            if body.field_type == record_type.as_str() {
                out.push(body);
            }
        }
        Ok(out)
    }

    async fn refresh_zone(&self, zone: &str) -> crate::Result<()> {
        let url = format!("{}/domain/zone/{}/refresh", self.endpoint, zone);
        self.send_authenticated_request(Method::POST, &url, "")
            .await
            .map(|_| ())
    }

    async fn post_record(
        &self,
        zone: &str,
        subdomain: &str,
        ttl: u32,
        wire: &OvhRecordFormat,
    ) -> crate::Result<()> {
        let params = CreateDnsRecordParams {
            field_type: wire.field_type.clone(),
            sub_domain: subdomain.to_string(),
            target: wire.target.clone(),
            ttl,
        };
        let body = serde_json::to_string(&params)
            .map_err(|e| Error::Serialize(format!("Failed to serialize record: {}", e)))?;

        let url = format!("{}/domain/zone/{}/record", self.endpoint, zone);
        self.send_authenticated_request(Method::POST, &url, &body)
            .await
            .map(|_| ())
    }

    async fn delete_record_id(&self, zone: &str, id: u64) -> crate::Result<()> {
        let url = format!("{}/domain/zone/{}/record/{}", self.endpoint, zone, id);
        self.send_authenticated_request(Method::DELETE, &url, "")
            .await
            .map(|_| ())
    }

    fn subdomain_for<'a>(&self, zone: &str, name: impl IntoFqdn<'a>) -> String {
        let name = name.into_name();
        let subdomain = strip_origin_from_name(&name, zone, Some(""));
        if subdomain == "@" {
            String::new()
        } else {
            subdomain
        }
    }

    pub(crate) async fn set_rrset(
        &self,
        name: impl IntoFqdn<'_>,
        record_type: DnsRecordType,
        ttl: u32,
        records: Vec<DnsRecord>,
        origin: impl IntoFqdn<'_>,
    ) -> crate::Result<()> {
        let desired = build_wire(record_type, &records)?;
        let zone = self.get_zone_name(origin).await?;
        let subdomain = self.subdomain_for(&zone, name);

        let existing = self.list_at(&zone, &subdomain, record_type).await?;

        let mut to_add: Vec<OvhRecordFormat> = Vec::new();
        let mut leftovers: Vec<&OvhRecordBody> = existing.iter().collect();

        for wanted in &desired {
            if let Some(pos) = leftovers.iter().position(|e| target_equivalent(e, wanted)) {
                leftovers.swap_remove(pos);
            } else {
                to_add.push(wanted.clone());
            }
        }

        let mut mutated = false;
        for stale in leftovers {
            self.delete_record_id(&zone, stale.id).await?;
            mutated = true;
        }
        for wire in to_add {
            self.post_record(&zone, &subdomain, ttl, &wire).await?;
            mutated = true;
        }

        if mutated {
            self.refresh_zone(&zone).await?;
        }
        Ok(())
    }

    pub(crate) async fn add_to_rrset(
        &self,
        name: impl IntoFqdn<'_>,
        record_type: DnsRecordType,
        ttl: u32,
        records: Vec<DnsRecord>,
        origin: impl IntoFqdn<'_>,
    ) -> crate::Result<()> {
        if records.is_empty() {
            return Ok(());
        }
        let desired = build_wire(record_type, &records)?;
        let zone = self.get_zone_name(origin).await?;
        let subdomain = self.subdomain_for(&zone, name);

        let existing = self.list_at(&zone, &subdomain, record_type).await?;

        let mut mutated = false;
        for wire in desired {
            if existing.iter().any(|e| target_equivalent(e, &wire)) {
                continue;
            }
            self.post_record(&zone, &subdomain, ttl, &wire).await?;
            mutated = true;
        }

        if mutated {
            self.refresh_zone(&zone).await?;
        }
        Ok(())
    }

    pub(crate) async fn remove_from_rrset(
        &self,
        name: impl IntoFqdn<'_>,
        record_type: DnsRecordType,
        records: Vec<DnsRecord>,
        origin: impl IntoFqdn<'_>,
    ) -> crate::Result<()> {
        if records.is_empty() {
            return Ok(());
        }
        let to_remove = build_wire(record_type, &records)?;
        let zone = self.get_zone_name(origin).await?;
        let subdomain = self.subdomain_for(&zone, name);

        let existing = self.list_at(&zone, &subdomain, record_type).await?;

        let mut mutated = false;
        for wire in to_remove {
            if let Some(entry) = existing.iter().find(|e| target_equivalent(e, &wire)) {
                self.delete_record_id(&zone, entry.id).await?;
                mutated = true;
            }
        }

        if mutated {
            self.refresh_zone(&zone).await?;
        }
        Ok(())
    }

    pub(crate) async fn list_rrset(
        &self,
        name: impl IntoFqdn<'_>,
        record_type: DnsRecordType,
        origin: impl IntoFqdn<'_>,
    ) -> crate::Result<Vec<DnsRecord>> {
        let zone = self.get_zone_name(origin).await?;
        let subdomain = self.subdomain_for(&zone, name);
        let existing = self.list_at(&zone, &subdomain, record_type).await?;
        existing
            .into_iter()
            .map(|e| parse_ovh_target(record_type, &e.target))
            .collect()
    }
}

fn build_wire(
    expected_type: DnsRecordType,
    records: &[DnsRecord],
) -> crate::Result<Vec<OvhRecordFormat>> {
    let mut out = Vec::with_capacity(records.len());
    for record in records {
        if record.as_type() != expected_type {
            return Err(Error::Api(format!(
                "RRSet record type mismatch: expected {}, got {}",
                expected_type.as_str(),
                record.as_type().as_str(),
            )));
        }
        out.push(record.into());
    }
    Ok(out)
}

fn target_equivalent(existing: &OvhRecordBody, wanted: &OvhRecordFormat) -> bool {
    if existing.field_type != wanted.field_type {
        return false;
    }
    if existing.target == wanted.target {
        return true;
    }
    match wanted.field_type.as_str() {
        "CNAME" | "NS" => existing
            .target
            .trim_end_matches('.')
            .eq_ignore_ascii_case(wanted.target.trim_end_matches('.')),
        "MX" | "SRV" => {
            normalize_priority_target(&existing.target) == normalize_priority_target(&wanted.target)
        }
        "TLSA" => existing.target.eq_ignore_ascii_case(&wanted.target),
        _ => false,
    }
}

fn normalize_priority_target(value: &str) -> String {
    let trimmed = value.trim();
    let last_space = trimmed.rfind(char::is_whitespace);
    match last_space {
        Some(idx) => {
            let (prefix, tail) = trimmed.split_at(idx);
            let tail_trimmed = tail.trim().trim_end_matches('.').to_ascii_lowercase();
            format!("{} {}", prefix.trim(), tail_trimmed)
        }
        None => trimmed.trim_end_matches('.').to_ascii_lowercase(),
    }
}

fn parse_ovh_target(record_type: DnsRecordType, target: &str) -> crate::Result<DnsRecord> {
    match record_type {
        DnsRecordType::A => target
            .parse()
            .map(DnsRecord::A)
            .map_err(|e| Error::Parse(format!("invalid A target {}: {}", target, e))),
        DnsRecordType::AAAA => target
            .parse()
            .map(DnsRecord::AAAA)
            .map_err(|e| Error::Parse(format!("invalid AAAA target {}: {}", target, e))),
        DnsRecordType::CNAME => Ok(DnsRecord::CNAME(target.to_string())),
        DnsRecordType::NS => Ok(DnsRecord::NS(target.to_string())),
        DnsRecordType::TXT => Ok(DnsRecord::TXT(target.to_string())),
        DnsRecordType::MX => {
            let mut parts = target.splitn(2, char::is_whitespace);
            let priority = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("invalid MX target: {}", target)))?
                .parse::<u16>()
                .map_err(|e| Error::Parse(format!("invalid MX priority in {}: {}", target, e)))?;
            let exchange = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("MX target missing exchange: {}", target)))?
                .trim()
                .to_string();
            Ok(DnsRecord::MX(MXRecord { exchange, priority }))
        }
        DnsRecordType::SRV => {
            let mut parts = target.split_whitespace();
            let priority = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("invalid SRV target: {}", target)))?
                .parse::<u16>()
                .map_err(|e| Error::Parse(format!("invalid SRV priority in {}: {}", target, e)))?;
            let weight = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("invalid SRV target: {}", target)))?
                .parse::<u16>()
                .map_err(|e| Error::Parse(format!("invalid SRV weight in {}: {}", target, e)))?;
            let port = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("invalid SRV target: {}", target)))?
                .parse::<u16>()
                .map_err(|e| Error::Parse(format!("invalid SRV port in {}: {}", target, e)))?;
            let srv_target = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("SRV target missing host: {}", target)))?
                .to_string();
            Ok(DnsRecord::SRV(SRVRecord {
                priority,
                weight,
                port,
                target: srv_target,
            }))
        }
        DnsRecordType::TLSA => {
            let mut parts = target.split_whitespace();
            let usage = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("invalid TLSA target: {}", target)))?
                .parse::<u8>()
                .map_err(|e| Error::Parse(format!("invalid TLSA usage in {}: {}", target, e)))?;
            let selector = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("invalid TLSA target: {}", target)))?
                .parse::<u8>()
                .map_err(|e| Error::Parse(format!("invalid TLSA selector in {}: {}", target, e)))?;
            let matching = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("invalid TLSA target: {}", target)))?
                .parse::<u8>()
                .map_err(|e| Error::Parse(format!("invalid TLSA matching in {}: {}", target, e)))?;
            let cert_hex = parts
                .next()
                .ok_or_else(|| Error::Parse(format!("TLSA target missing data: {}", target)))?;
            Ok(DnsRecord::TLSA(TLSARecord {
                cert_usage: tlsa_cert_usage_from_u8(usage)?,
                selector: tlsa_selector_from_u8(selector)?,
                matching: tlsa_matching_from_u8(matching)?,
                cert_data: decode_hex(cert_hex)?,
            }))
        }
        DnsRecordType::CAA => parse_caa(target),
    }
}

fn tlsa_cert_usage_from_u8(value: u8) -> crate::Result<TlsaCertUsage> {
    Ok(match value {
        0 => TlsaCertUsage::PkixTa,
        1 => TlsaCertUsage::PkixEe,
        2 => TlsaCertUsage::DaneTa,
        3 => TlsaCertUsage::DaneEe,
        255 => TlsaCertUsage::Private,
        _ => return Err(Error::Parse(format!("unknown TLSA cert usage: {}", value))),
    })
}

fn tlsa_selector_from_u8(value: u8) -> crate::Result<TlsaSelector> {
    Ok(match value {
        0 => TlsaSelector::Full,
        1 => TlsaSelector::Spki,
        255 => TlsaSelector::Private,
        _ => return Err(Error::Parse(format!("unknown TLSA selector: {}", value))),
    })
}

fn tlsa_matching_from_u8(value: u8) -> crate::Result<TlsaMatching> {
    Ok(match value {
        0 => TlsaMatching::Raw,
        1 => TlsaMatching::Sha256,
        2 => TlsaMatching::Sha512,
        255 => TlsaMatching::Private,
        _ => return Err(Error::Parse(format!("unknown TLSA matching: {}", value))),
    })
}

fn decode_hex(hex: &str) -> crate::Result<Vec<u8>> {
    if !hex.len().is_multiple_of(2) {
        return Err(Error::Parse(format!("invalid hex string: {}", hex)));
    }
    (0..hex.len())
        .step_by(2)
        .map(|i| {
            u8::from_str_radix(&hex[i..i + 2], 16)
                .map_err(|e| Error::Parse(format!("invalid hex byte: {}", e)))
        })
        .collect()
}

fn parse_caa(target: &str) -> crate::Result<DnsRecord> {
    let mut parts = target.splitn(3, char::is_whitespace);
    let flags = parts
        .next()
        .ok_or_else(|| Error::Parse(format!("invalid CAA target: {}", target)))?
        .parse::<u8>()
        .map_err(|e| Error::Parse(format!("invalid CAA flags in {}: {}", target, e)))?;
    let tag = parts
        .next()
        .ok_or_else(|| Error::Parse(format!("CAA target missing tag: {}", target)))?
        .to_string();
    let raw_value = parts
        .next()
        .ok_or_else(|| Error::Parse(format!("CAA target missing value: {}", target)))?
        .trim();
    let unquoted_full = strip_caa_quotes(raw_value);

    let issuer_critical = flags & 0x80 != 0;
    match tag.as_str() {
        "issue" => {
            let (name, options) = parse_caa_value(&unquoted_full);
            Ok(DnsRecord::CAA(CAARecord::Issue {
                issuer_critical,
                name,
                options,
            }))
        }
        "issuewild" => {
            let (name, options) = parse_caa_value(&unquoted_full);
            Ok(DnsRecord::CAA(CAARecord::IssueWild {
                issuer_critical,
                name,
                options,
            }))
        }
        "iodef" => Ok(DnsRecord::CAA(CAARecord::Iodef {
            issuer_critical,
            url: unquoted_full,
        })),
        other => Err(Error::Parse(format!("unknown CAA tag: {}", other))),
    }
}

fn strip_caa_quotes(s: &str) -> String {
    let s = s.trim();
    if let Some(inner) = s.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
        inner.to_string()
    } else {
        s.to_string()
    }
}

fn parse_caa_value(value: &str) -> (Option<String>, Vec<KeyValue>) {
    let mut parts = value.split(';').map(str::trim);
    let name_part = parts.next().unwrap_or("").trim().to_string();
    let name = if name_part.is_empty() {
        None
    } else {
        Some(name_part)
    };
    let options = parts
        .filter(|p| !p.is_empty())
        .map(|p| match p.split_once('=') {
            Some((k, v)) => KeyValue {
                key: k.trim().to_string(),
                value: v.trim().to_string(),
            },
            None => KeyValue {
                key: p.trim().to_string(),
                value: String::new(),
            },
        })
        .collect();
    (name, options)
}