dnsync 0.2.1

DNS Sync and Control with MCP
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
703
704
705
706
707
708
//! UniFi DNS policy ↔ dnsync `ZoneRecord` / `RecordData` mapping.
//!
//! UniFi DNS policies are site-scoped, not zone-scoped, so dnsync derives
//! logical zones by domain suffix. `FORWARD_DOMAIN` is preserved in listings
//! as provider-specific metadata but is not treated as a normal DNS RRset
//! — `record_data_to_unifi_body` rejects it for create/update calls.

use serde_json::{Value, json};

use crate::core::dns::records::RecordData;
use crate::core::dns::responses::ZoneRecord;
use crate::core::error::{Error, Result};

use super::responses::{UnifiDnsPolicy, UnifiDnsPolicyType};

/// Strip `.{zone}` suffix from a fully qualified UniFi domain.
/// Returns `"@"` when `fqdn` is the zone apex.
pub fn extract_relative_name(fqdn: &str, zone: &str) -> String {
    let fqdn_lower = fqdn.to_lowercase();
    let zone_lower = zone.to_lowercase();

    if fqdn_lower == zone_lower {
        return "@".to_string();
    }

    let suffix = format!(".{zone_lower}");
    if fqdn_lower.ends_with(&suffix) {
        fqdn[..fqdn.len() - suffix.len()].to_string()
    } else {
        fqdn.to_string()
    }
}

/// True when `domain` is `zone` itself or sits below it.
///
/// Comparisons are case-insensitive. Used to filter the flat UniFi policy
/// list down to one logical zone.
pub fn domain_matches_zone(domain: &str, zone: &str) -> bool {
    let d = domain.to_lowercase();
    let z = zone.to_lowercase();
    d == z || d.ends_with(&format!(".{z}"))
}

/// Build the dnsync `rData` JSON for a UniFi policy.
///
/// Standard record types map to the shapes documented in
/// `docs/new-vendor.md`. `FORWARD_DOMAIN` produces a provider-specific
/// object (no equivalent `RecordData` variant) so consumers can still see
/// the metadata even though it is not a true RR.
pub fn policy_to_rdata(policy: &UnifiDnsPolicy) -> Value {
    match policy.policy_type {
        UnifiDnsPolicyType::ARecord => json!({
            "ipAddress": policy.ipv4_address.clone().unwrap_or_default(),
        }),
        UnifiDnsPolicyType::AaaaRecord => json!({
            "ipAddress": policy.ipv6_address.clone().unwrap_or_default(),
        }),
        UnifiDnsPolicyType::CnameRecord => json!({
            "cname": policy.target_domain.clone().unwrap_or_default(),
        }),
        UnifiDnsPolicyType::MxRecord => json!({
            "preference": policy.priority.unwrap_or(10),
            "exchange": policy.mail_server_domain.clone().unwrap_or_default(),
        }),
        UnifiDnsPolicyType::TxtRecord => json!({
            "text": policy.text.clone().unwrap_or_default(),
            "splitText": false,
        }),
        UnifiDnsPolicyType::SrvRecord => json!({
            "priority": policy.priority.unwrap_or(0),
            "weight": policy.weight.unwrap_or(0),
            "port": policy.port.unwrap_or(0),
            "target": policy.server_domain.clone().unwrap_or_default(),
        }),
        UnifiDnsPolicyType::ForwardDomain => json!({
            "forwardDomain": policy.domain.clone(),
            "ipAddress": policy.ip_address.clone().unwrap_or_default(),
            "providerType": "FORWARD_DOMAIN",
        }),
    }
}

/// Convert a UniFi DNS policy into a normalised `ZoneRecord` for display.
///
/// The UniFi policy `id` is preserved on `data["id"]` so callers can target
/// it for update/delete. The `enabled` flag is preserved via the standard
/// `ZoneRecord::disabled` field (`disabled = !enabled`).
pub fn policy_to_zone_record(policy: &UnifiDnsPolicy, zone: &str) -> ZoneRecord {
    let record_type = policy.policy_type.dnsync_record_type().to_string();
    let name = extract_relative_name(&policy.domain, zone);
    let ttl = policy.ttl_seconds.unwrap_or(0);

    let mut data = policy_to_rdata(policy);
    if let Some(obj) = data.as_object_mut() {
        obj.insert("id".into(), Value::String(policy.id.clone()));
        obj.insert("enabled".into(), Value::Bool(policy.enabled));
        obj.insert("fullDomain".into(), Value::String(policy.domain.clone()));
        obj.insert(
            "unifiType".into(),
            Value::String(policy.policy_type.as_str().to_string()),
        );
    }

    ZoneRecord {
        name,
        record_type,
        ttl,
        disabled: !policy.enabled,
        comments: String::new(),
        expiry_ttl: 0,
        data,
        parsed: None,
    }
}

/// Build the JSON body for `POST /sites/{siteId}/dns/policies` (create) or
/// `PUT /sites/{siteId}/dns/policies/{id}` (update).
///
/// FORWARD_DOMAIN, ANAME, APP, CAA, DS, FWD, HTTPS, NAPTR, NS, PTR, SVCB,
/// TLSA, URI, and unknown types return `Error::unsupported`. UniFi DNS
/// policies only model A/AAAA/CNAME/MX/TXT/SRV (and FORWARD_DOMAIN, which is
/// not a normal RRset and cannot be created through dnsync's record API).
pub fn record_data_to_unifi_body(
    domain: &str,
    ttl: u32,
    enabled: bool,
    record: &RecordData,
) -> Result<Value> {
    let body = match record {
        RecordData::A { ip } => json!({
            "type": "A_RECORD",
            "enabled": enabled,
            "domain": domain,
            "ipv4Address": ip.to_string(),
            "ttlSeconds": ttl,
        }),
        RecordData::Aaaa { ip } => json!({
            "type": "AAAA_RECORD",
            "enabled": enabled,
            "domain": domain,
            "ipv6Address": ip.to_string(),
            "ttlSeconds": ttl,
        }),
        RecordData::Cname { target } => json!({
            "type": "CNAME_RECORD",
            "enabled": enabled,
            "domain": domain,
            "targetDomain": target,
            "ttlSeconds": ttl,
        }),
        RecordData::Mx {
            exchange,
            preference,
        } => json!({
            "type": "MX_RECORD",
            "enabled": enabled,
            "domain": domain,
            "mailServerDomain": exchange,
            "priority": preference,
            "ttlSeconds": ttl,
        }),
        RecordData::Txt { text, .. } => json!({
            "type": "TXT_RECORD",
            "enabled": enabled,
            "domain": domain,
            "text": text,
            "ttlSeconds": ttl,
        }),
        RecordData::Srv {
            target,
            port,
            priority,
            weight,
        } => {
            let (service, protocol) = split_srv_labels(domain);
            json!({
                "type": "SRV_RECORD",
                "enabled": enabled,
                "domain": domain,
                "serverDomain": target,
                "service": service,
                "protocol": protocol,
                "port": port,
                "priority": priority,
                "weight": weight,
                "ttlSeconds": ttl,
            })
        }
        _ => {
            return Err(Error::unsupported(
                "UniFi",
                "record type (only A/AAAA/CNAME/MX/TXT/SRV are supported)",
            ));
        }
    };
    Ok(body)
}

/// Pull the `_service._protocol` labels out of an SRV-style domain.
///
/// `_sip._tcp.example.com` → `("_sip", "_tcp")`. Falls back to empty strings
/// when the leading labels do not match the SRV convention — UniFi will
/// reject the create call, surfacing a vendor error to the user.
fn split_srv_labels(domain: &str) -> (String, String) {
    let mut parts = domain.split('.');
    let service = parts.next().unwrap_or("").to_string();
    let protocol = parts.next().unwrap_or("").to_string();
    (service, protocol)
}

/// Compare a UniFi policy against a `type_params` payload used by
/// `RecordWrite::delete_record`. Returns true when the policy is the one the
/// caller wants to delete (matches type + the value-bearing field).
pub fn policy_matches_delete_params(
    policy: &UnifiDnsPolicy,
    domain: &str,
    type_params: &[(&str, String)],
) -> bool {
    if !policy.domain.eq_ignore_ascii_case(domain) {
        return false;
    }

    let target_type = type_params
        .iter()
        .find(|(k, _)| *k == "type")
        .map(|(_, v)| v.as_str())
        .unwrap_or("");

    if policy.policy_type.dnsync_record_type() != target_type.to_uppercase() {
        return false;
    }

    // Match the value-bearing field if the caller supplied one. Structured
    // types fall back to first-match by domain+type (rare for UniFi where
    // the same domain+type usually has at most one policy).
    let value_field = |key: &str| -> Option<&str> {
        type_params
            .iter()
            .find(|(k, _)| *k == key)
            .map(|(_, v)| v.as_str())
    };

    match policy.policy_type {
        UnifiDnsPolicyType::ARecord => value_field("ipAddress")
            .map(|want| policy.ipv4_address.as_deref() == Some(want))
            .unwrap_or(true),
        UnifiDnsPolicyType::AaaaRecord => value_field("ipAddress")
            .map(|want| policy.ipv6_address.as_deref() == Some(want))
            .unwrap_or(true),
        UnifiDnsPolicyType::CnameRecord => value_field("cname")
            .map(|want| policy.target_domain.as_deref() == Some(want))
            .unwrap_or(true),
        UnifiDnsPolicyType::TxtRecord => value_field("text")
            .map(|want| policy.text.as_deref() == Some(want))
            .unwrap_or(true),
        UnifiDnsPolicyType::MxRecord => {
            value_field("exchange")
                .map(|want| policy.mail_server_domain.as_deref() == Some(want))
                .unwrap_or(true)
                && value_field("preference")
                    .map(|want| {
                        policy.priority.map(|p| p.to_string()).as_deref() == Some(want)
                    })
                    .unwrap_or(true)
        }
        UnifiDnsPolicyType::SrvRecord => {
            value_field("target")
                .map(|want| policy.server_domain.as_deref() == Some(want))
                .unwrap_or(true)
                && value_field("port")
                    .map(|want| policy.port.map(|v| v.to_string()).as_deref() == Some(want))
                    .unwrap_or(true)
                && value_field("priority")
                    .map(|want| {
                        policy.priority.map(|v| v.to_string()).as_deref() == Some(want)
                    })
                    .unwrap_or(true)
                && value_field("weight")
                    .map(|want| policy.weight.map(|v| v.to_string()).as_deref() == Some(want))
                    .unwrap_or(true)
        }
        UnifiDnsPolicyType::ForwardDomain => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn a_policy() -> UnifiDnsPolicy {
        serde_json::from_value(json!({
            "id": "p1",
            "type": "A_RECORD",
            "enabled": true,
            "domain": "www.example.com",
            "ipv4Address": "192.168.1.10",
            "ttlSeconds": 300
        }))
        .unwrap()
    }

    fn disabled_aaaa_policy() -> UnifiDnsPolicy {
        serde_json::from_value(json!({
            "id": "p2",
            "type": "AAAA_RECORD",
            "enabled": false,
            "domain": "v6.example.com",
            "ipv6Address": "2001:db8::1",
            "ttlSeconds": 600
        }))
        .unwrap()
    }

    fn cname_policy() -> UnifiDnsPolicy {
        serde_json::from_value(json!({
            "id": "p3",
            "type": "CNAME_RECORD",
            "enabled": true,
            "domain": "alias.example.com",
            "targetDomain": "www.example.com",
            "ttlSeconds": 60
        }))
        .unwrap()
    }

    fn forward_policy() -> UnifiDnsPolicy {
        serde_json::from_value(json!({
            "id": "p4",
            "type": "FORWARD_DOMAIN",
            "enabled": true,
            "domain": "lan.example.com",
            "ipAddress": "192.168.1.1"
        }))
        .unwrap()
    }

    // ── extract_relative_name / domain_matches_zone ─────────────────────────

    #[test]
    fn apex_extracts_to_at() {
        assert_eq!(extract_relative_name("example.com", "example.com"), "@");
    }

    #[test]
    fn subdomain_strips_zone_suffix() {
        assert_eq!(
            extract_relative_name("a.b.example.com", "example.com"),
            "a.b"
        );
    }

    #[test]
    fn unrelated_returns_as_is() {
        assert_eq!(extract_relative_name("foo.net", "example.com"), "foo.net");
    }

    #[test]
    fn domain_matches_zone_covers_apex_and_subdomains() {
        assert!(domain_matches_zone("example.com", "example.com"));
        assert!(domain_matches_zone("a.example.com", "example.com"));
        assert!(domain_matches_zone("A.Example.COM", "example.com"));
        assert!(!domain_matches_zone("notexample.com", "example.com"));
        assert!(!domain_matches_zone("example.net", "example.com"));
    }

    // ── policy_to_zone_record ───────────────────────────────────────────────

    #[test]
    fn a_record_normalises_to_ip_address() {
        let rec = policy_to_zone_record(&a_policy(), "example.com");
        assert_eq!(rec.name, "www");
        assert_eq!(rec.record_type, "A");
        assert_eq!(rec.ttl, 300);
        assert!(!rec.disabled);
        assert_eq!(rec.data["ipAddress"], "192.168.1.10");
        assert_eq!(rec.data["id"], "p1");
        assert_eq!(rec.data["enabled"], true);
        assert_eq!(rec.data["unifiType"], "A_RECORD");
    }

    #[test]
    fn disabled_policy_maps_to_disabled_record() {
        let rec = policy_to_zone_record(&disabled_aaaa_policy(), "example.com");
        assert!(rec.disabled);
        assert_eq!(rec.data["enabled"], false);
        assert_eq!(rec.data["ipAddress"], "2001:db8::1");
        assert_eq!(rec.record_type, "AAAA");
    }

    #[test]
    fn cname_record_maps_to_cname_field() {
        let rec = policy_to_zone_record(&cname_policy(), "example.com");
        assert_eq!(rec.name, "alias");
        assert_eq!(rec.record_type, "CNAME");
        assert_eq!(rec.data["cname"], "www.example.com");
    }

    #[test]
    fn mx_record_normalises_priority_to_preference() {
        let mx: UnifiDnsPolicy = serde_json::from_value(json!({
            "id": "p5", "type": "MX_RECORD", "enabled": true,
            "domain": "example.com",
            "mailServerDomain": "mail.example.com",
            "priority": 10
        }))
        .unwrap();
        let rec = policy_to_zone_record(&mx, "example.com");
        assert_eq!(rec.record_type, "MX");
        assert_eq!(rec.data["preference"], 10);
        assert_eq!(rec.data["exchange"], "mail.example.com");
    }

    #[test]
    fn txt_record_includes_split_text_default() {
        let txt: UnifiDnsPolicy = serde_json::from_value(json!({
            "id": "p6", "type": "TXT_RECORD", "enabled": true,
            "domain": "_acme.example.com",
            "text": "challenge"
        }))
        .unwrap();
        let rec = policy_to_zone_record(&txt, "example.com");
        assert_eq!(rec.data["text"], "challenge");
        assert_eq!(rec.data["splitText"], false);
    }

    #[test]
    fn srv_record_includes_all_components() {
        let srv: UnifiDnsPolicy = serde_json::from_value(json!({
            "id": "p7", "type": "SRV_RECORD", "enabled": true,
            "domain": "_sip._tcp.example.com",
            "serverDomain": "sip.example.com",
            "service": "_sip", "protocol": "_tcp",
            "port": 5060, "priority": 10, "weight": 20
        }))
        .unwrap();
        let rec = policy_to_zone_record(&srv, "example.com");
        assert_eq!(rec.record_type, "SRV");
        assert_eq!(rec.data["priority"], 10);
        assert_eq!(rec.data["weight"], 20);
        assert_eq!(rec.data["port"], 5060);
        assert_eq!(rec.data["target"], "sip.example.com");
    }

    #[test]
    fn forward_domain_keeps_provider_metadata() {
        let rec = policy_to_zone_record(&forward_policy(), "example.com");
        assert_eq!(rec.record_type, "FORWARD_DOMAIN");
        assert_eq!(rec.data["ipAddress"], "192.168.1.1");
        assert_eq!(rec.data["forwardDomain"], "lan.example.com");
        assert_eq!(rec.data["providerType"], "FORWARD_DOMAIN");
    }

    // ── record_data_to_unifi_body ───────────────────────────────────────────

    #[test]
    fn a_body_uses_ipv4_address_field() {
        let body = record_data_to_unifi_body(
            "www.example.com",
            300,
            true,
            &RecordData::A {
                ip: "1.2.3.4".parse().unwrap(),
            },
        )
        .unwrap();
        assert_eq!(body["type"], "A_RECORD");
        assert_eq!(body["enabled"], true);
        assert_eq!(body["domain"], "www.example.com");
        assert_eq!(body["ipv4Address"], "1.2.3.4");
        assert_eq!(body["ttlSeconds"], 300);
    }

    #[test]
    fn aaaa_body_uses_ipv6_address_field() {
        let body = record_data_to_unifi_body(
            "v6.example.com",
            120,
            true,
            &RecordData::Aaaa {
                ip: "2001:db8::1".parse().unwrap(),
            },
        )
        .unwrap();
        assert_eq!(body["type"], "AAAA_RECORD");
        assert_eq!(body["ipv6Address"], "2001:db8::1");
    }

    #[test]
    fn mx_body_uses_mail_server_domain_and_priority() {
        let body = record_data_to_unifi_body(
            "example.com",
            300,
            true,
            &RecordData::Mx {
                exchange: "mail.example.com".into(),
                preference: 10,
            },
        )
        .unwrap();
        assert_eq!(body["type"], "MX_RECORD");
        assert_eq!(body["mailServerDomain"], "mail.example.com");
        assert_eq!(body["priority"], 10);
        assert_eq!(body["ttlSeconds"], 300);
    }

    #[test]
    fn srv_body_extracts_service_and_protocol_labels() {
        let body = record_data_to_unifi_body(
            "_sip._tcp.example.com",
            300,
            true,
            &RecordData::Srv {
                target: "sip.example.com".into(),
                port: 5060,
                priority: 10,
                weight: 20,
            },
        )
        .unwrap();
        assert_eq!(body["type"], "SRV_RECORD");
        assert_eq!(body["service"], "_sip");
        assert_eq!(body["protocol"], "_tcp");
        assert_eq!(body["port"], 5060);
        assert_eq!(body["serverDomain"], "sip.example.com");
        assert_eq!(body["ttlSeconds"], 300);
    }

    #[test]
    fn txt_body_uses_text_field() {
        let body = record_data_to_unifi_body(
            "_acme.example.com",
            120,
            true,
            &RecordData::Txt {
                text: "challenge".into(),
                split_text: false,
            },
        )
        .unwrap();
        assert_eq!(body["type"], "TXT_RECORD");
        assert_eq!(body["text"], "challenge");
        assert_eq!(body["ttlSeconds"], 120);
    }

    #[test]
    fn cname_body_uses_target_domain_field() {
        let body = record_data_to_unifi_body(
            "alias.example.com",
            60,
            false,
            &RecordData::Cname {
                target: "www.example.com".into(),
            },
        )
        .unwrap();
        assert_eq!(body["type"], "CNAME_RECORD");
        assert_eq!(body["targetDomain"], "www.example.com");
        assert_eq!(body["enabled"], false);
    }

    #[test]
    fn unsupported_type_is_rejected() {
        let err = record_data_to_unifi_body(
            "example.com",
            300,
            true,
            &RecordData::Ns {
                nameserver: "ns1.example.com".into(),
                glue: None,
            },
        )
        .unwrap_err();
        assert!(matches!(
            err,
            Error::Unsupported {
                vendor: "UniFi",
                ..
            }
        ));
    }

    // ── policy_matches_delete_params ────────────────────────────────────────

    #[test]
    fn delete_matches_by_type_and_value() {
        let pol = a_policy();
        assert!(policy_matches_delete_params(
            &pol,
            "www.example.com",
            &[("type", "A".into()), ("ipAddress", "192.168.1.10".into())],
        ));
        assert!(!policy_matches_delete_params(
            &pol,
            "www.example.com",
            &[("type", "A".into()), ("ipAddress", "10.0.0.1".into())],
        ));
    }

    #[test]
    fn delete_requires_matching_domain() {
        let pol = a_policy();
        assert!(!policy_matches_delete_params(
            &pol,
            "other.example.com",
            &[("type", "A".into())],
        ));
    }

    #[test]
    fn delete_requires_matching_type() {
        let pol = a_policy();
        assert!(!policy_matches_delete_params(
            &pol,
            "www.example.com",
            &[("type", "AAAA".into())],
        ));
    }

    #[test]
    fn delete_never_matches_forward_domain() {
        let pol = forward_policy();
        assert!(!policy_matches_delete_params(
            &pol,
            "lan.example.com",
            &[("type", "FORWARD_DOMAIN".into())],
        ));
    }

    #[test]
    fn delete_mx_distinguishes_by_preference() {
        let mx: UnifiDnsPolicy = serde_json::from_value(json!({
            "id": "mx1", "type": "MX_RECORD", "enabled": true,
            "domain": "example.com",
            "mailServerDomain": "mail.example.com",
            "priority": 10
        }))
        .unwrap();
        // Same exchange but wrong preference must NOT match.
        assert!(!policy_matches_delete_params(
            &mx,
            "example.com",
            &[
                ("type", "MX".into()),
                ("exchange", "mail.example.com".into()),
                ("preference", "20".into()),
            ],
        ));
        // Matching preference and exchange does match.
        assert!(policy_matches_delete_params(
            &mx,
            "example.com",
            &[
                ("type", "MX".into()),
                ("exchange", "mail.example.com".into()),
                ("preference", "10".into()),
            ],
        ));
    }

    #[test]
    fn delete_srv_distinguishes_by_port_priority_weight() {
        let srv: UnifiDnsPolicy = serde_json::from_value(json!({
            "id": "srv1", "type": "SRV_RECORD", "enabled": true,
            "domain": "_sip._tcp.example.com",
            "serverDomain": "sip.example.com",
            "service": "_sip", "protocol": "_tcp",
            "port": 5060, "priority": 10, "weight": 20
        }))
        .unwrap();
        // Wrong port must NOT match even when target/priority/weight align.
        assert!(!policy_matches_delete_params(
            &srv,
            "_sip._tcp.example.com",
            &[
                ("type", "SRV".into()),
                ("target", "sip.example.com".into()),
                ("port", "5061".into()),
                ("priority", "10".into()),
                ("weight", "20".into()),
            ],
        ));
        // Wrong weight must NOT match either.
        assert!(!policy_matches_delete_params(
            &srv,
            "_sip._tcp.example.com",
            &[
                ("type", "SRV".into()),
                ("target", "sip.example.com".into()),
                ("port", "5060".into()),
                ("priority", "10".into()),
                ("weight", "30".into()),
            ],
        ));
        // All four match → policy is deletable.
        assert!(policy_matches_delete_params(
            &srv,
            "_sip._tcp.example.com",
            &[
                ("type", "SRV".into()),
                ("target", "sip.example.com".into()),
                ("port", "5060".into()),
                ("priority", "10".into()),
                ("weight", "20".into()),
            ],
        ));
    }
}