dnsync 0.2.2

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
//! Typed response structs for Technitium API responses.
//!
//! `RecordData` in types.rs covers records you can *add or delete*.
//! `ReadOnlyRecordData` here covers records that are server-managed and
//! only ever appear in list_records responses — never in add/delete calls.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

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

// ─── Read-only DNSSEC record data ─────────────────────────────────────────────

/// DNSKEY — public key record, managed by Technitium's DNSSEC key lifecycle.
/// Created when you publish a private key; retired via the DNSSEC key API.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DnskeyData {
    pub flags: u16,
    /// Always 3 per RFC 4034
    pub protocol: u8,
    pub algorithm: DsAlgorithm,
    /// Base64-encoded public key
    pub public_key: String,
    pub computed_key_tag: u16,
    /// Active | Ready | Generated | Retired
    pub dns_key_state: Option<String>,
    pub is_ksk: Option<bool>,
}

/// RRSIG — signature over a record set, generated automatically on every write.
/// Technitium refreshes these before expiry; you cannot add or remove them directly.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RrsigData {
    pub type_covered: String,
    pub algorithm: DsAlgorithm,
    pub labels: u8,
    pub original_ttl: u32,
    /// ISO 8601 datetime
    pub signature_expiration: String,
    /// ISO 8601 datetime
    pub signature_inception: String,
    pub key_tag: u16,
    pub signer_name: String,
    /// Base64-encoded signature
    pub signature: String,
}

/// NSEC — proof of non-existence (ordered linked list of zone names).
/// Generated by the signing engine; not manually manageable.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct NsecData {
    pub next_domain_name: String,
    /// Record types present at this name, e.g. ["A", "RRSIG", "NSEC"]
    pub types: Vec<String>,
}

/// NSEC3 — hashed proof of non-existence.
/// Generated by the signing engine; not manually manageable.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Nsec3Data {
    pub hash_algorithm: String,
    pub flags: u8,
    pub iterations: u16,
    /// Hex-encoded salt
    pub salt: String,
    pub next_hashed_owner_name: String,
    pub types: Vec<String>,
}

/// Record types that appear in list_records responses but cannot be
/// added or deleted via the record API.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "UPPERCASE")]
pub enum ReadOnlyRecordData {
    Dnskey(DnskeyData),
    Rrsig(RrsigData),
    Nsec(NsecData),
    Nsec3(Nsec3Data),
}

// ─── Unified record data ──────────────────────────────────────────────────────

/// Any record that can appear in a list_records response — either a writable
/// record (add/delete supported) or a read-only server-managed DNSSEC record.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum AnyRecordData {
    Writable(RecordData),
    ReadOnly(ReadOnlyRecordData),
}

// ─── Zone record entry ────────────────────────────────────────────────────────

/// A single DNS record as returned by the list_records API.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ZoneRecord {
    pub name: String,
    #[serde(rename = "type")]
    pub record_type: String,
    pub ttl: u32,
    #[serde(default)]
    pub disabled: bool,
    #[serde(default)]
    pub comments: String,
    #[serde(default)]
    pub expiry_ttl: u64,
    #[serde(rename = "rData")]
    pub data: serde_json::Value,
    /// Parsed typed form — None if the type is unrecognised
    #[serde(skip)]
    pub parsed: Option<AnyRecordData>,
}

impl ZoneRecord {
    /// Typed record data for this record. Uses the pre-parsed value when one is
    /// present, otherwise parses on demand from `record_type` + `data` — so it
    /// works regardless of which vendor produced the record.
    pub fn typed(&self) -> Option<AnyRecordData> {
        if let Some(parsed) = &self.parsed {
            return Some(parsed.clone());
        }
        parse_record_data(&self.record_type, &self.data)
    }
}

// ─── List records response ────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ZoneInfo {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    #[serde(rename = "type")]
    pub zone_type: String,
    #[serde(default)]
    pub disabled: bool,
    pub dnssec_status: Option<String>,
}

/// Records for a single DNS zone.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ZoneRecords {
    pub zone: ZoneInfo,
    pub records: Vec<ZoneRecord>,
}

/// Response from list_records — may contain one zone or many (e.g. Pangolin "list all").
///
/// **Serialization shape:**
/// - Single zone → `{"zone": {...}, "records": [...]}` (flat, matches the historical shape)
/// - Multiple zones → `{"zones": [{"zone": {...}, "records": [...]}, ...]}`
#[derive(Debug, Clone)]
pub struct ListRecordsResponse {
    pub zones: Vec<ZoneRecords>,
}

impl serde::Serialize for ListRecordsResponse {
    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        match self.zones.as_slice() {
            [single] => {
                let mut map = s.serialize_map(Some(2))?;
                map.serialize_entry("zone", &single.zone)?;
                map.serialize_entry("records", &single.records)?;
                map.end()
            }
            _ => {
                let mut map = s.serialize_map(Some(1))?;
                map.serialize_entry("zones", &self.zones)?;
                map.end()
            }
        }
    }
}

impl<'de> serde::Deserialize<'de> for ListRecordsResponse {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Repr {
            Multi {
                zones: Vec<ZoneRecords>,
            },
            Single {
                zone: ZoneInfo,
                records: Vec<ZoneRecord>,
            },
        }
        match Repr::deserialize(d)? {
            Repr::Multi { zones } => Ok(Self { zones }),
            Repr::Single { zone, records } => Ok(Self::single(zone, records)),
        }
    }
}

impl ListRecordsResponse {
    /// Convenience constructor for the common single-zone case.
    pub fn single(zone: ZoneInfo, records: Vec<ZoneRecord>) -> Self {
        Self {
            zones: vec![ZoneRecords { zone, records }],
        }
    }

    /// Parse the raw Technitium API JSON into a typed response, populating
    /// `parsed` on each record where the type is recognised.
    pub fn from_value(value: &serde_json::Value) -> Result<Self> {
        let response = value
            .get("response")
            .ok_or_else(|| Error::parse("list_records response missing 'response' key"))?;

        let mut zone: ZoneInfo = serde_json::from_value(
            response
                .get("zone")
                .ok_or_else(|| Error::parse("list_records response missing 'response.zone'"))?
                .clone(),
        )
        .map_err(|e| Error::parse(format!("could not deserialize zone info: {e}")))?;
        if zone.id.is_none() {
            zone.id = Some(zone.name.clone());
        }

        let raw_records = response
            .get("records")
            .and_then(|r| r.as_array())
            .ok_or_else(|| {
                Error::parse("list_records response missing 'response.records' array")
            })?;

        let records = raw_records
            .iter()
            .filter_map(|r| {
                let mut record: ZoneRecord = serde_json::from_value(r.clone()).ok()?;
                record.parsed = parse_record_data(&record.record_type, &record.data);
                Some(record)
            })
            .collect();

        Ok(Self::single(zone, records))
    }
}

fn parse_record_data(record_type: &str, rdata: &serde_json::Value) -> Option<AnyRecordData> {
    // Reconstruct the tagged value that serde expects for RecordData / ReadOnlyRecordData
    let mut tagged = rdata.clone();
    if let Some(obj) = tagged.as_object_mut() {
        obj.insert(
            "type".into(),
            serde_json::Value::String(record_type.to_uppercase()),
        );
    }

    // Try writable first, then read-only
    if let Ok(w) = serde_json::from_value::<RecordData>(tagged.clone()) {
        return Some(AnyRecordData::Writable(w));
    }
    if let Ok(ro) = serde_json::from_value::<ReadOnlyRecordData>(tagged) {
        return Some(AnyRecordData::ReadOnly(ro));
    }
    None
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    // ── Fixtures ──────────────────────────────────────────────────────────────

    #[fixture]
    fn zone_json() -> serde_json::Value {
        json!({ "name": "example.com", "type": "Primary", "disabled": false })
    }

    #[fixture]
    fn a_record_json() -> serde_json::Value {
        json!({
            "name": "www",
            "type": "A",
            "ttl": 3600,
            "disabled": false,
            "comments": "",
            "rData": { "ipAddress": "1.2.3.4" }
        })
    }

    #[fixture]
    fn rrsig_record_json() -> serde_json::Value {
        json!({
            "name": "@",
            "type": "RRSIG",
            "ttl": 86400,
            "disabled": false,
            "comments": "",
            "rData": {
                "typeCovered": "A",
                "algorithm": "ECDSAP256SHA256",
                "labels": 2,
                "originalTtl": 3600,
                "signatureExpiration": "20261231000000",
                "signatureInception": "20260101000000",
                "keyTag": 12345,
                "signerName": "example.com",
                "signature": "abc123=="
            }
        })
    }

    #[fixture]
    fn dnskey_record_json() -> serde_json::Value {
        json!({
            "name": "@",
            "type": "DNSKEY",
            "ttl": 86400,
            "disabled": false,
            "comments": "",
            "rData": {
                "flags": 257,
                "protocol": 3,
                "algorithm": "ECDSAP256SHA256",
                "publicKey": "base64key==",
                "computedKeyTag": 12345,
                "dnsKeyState": "Active",
                "isKsk": true
            }
        })
    }

    fn wrap_response(
        zone: serde_json::Value,
        records: Vec<serde_json::Value>,
    ) -> serde_json::Value {
        json!({ "status": "ok", "response": { "zone": zone, "records": records } })
    }

    // ── from_value — happy paths ──────────────────────────────────────────────

    #[rstest]
    fn parses_zone_info(zone_json: serde_json::Value) {
        let resp = wrap_response(zone_json, vec![]);
        let result = ListRecordsResponse::from_value(&resp).expect("should parse");
        assert_eq!(result.zones.len(), 1);
        assert_eq!(result.zones[0].zone.name, "example.com");
        assert_eq!(result.zones[0].zone.zone_type, "Primary");
        assert!(!result.zones[0].zone.disabled);
    }

    #[rstest]
    fn empty_records_list(zone_json: serde_json::Value) {
        let resp = wrap_response(zone_json, vec![]);
        let result = ListRecordsResponse::from_value(&resp).expect("should parse");
        assert!(result.zones[0].records.is_empty());
    }

    #[rstest]
    fn a_record_parsed_as_writable(zone_json: serde_json::Value, a_record_json: serde_json::Value) {
        let resp = wrap_response(zone_json, vec![a_record_json]);
        let result = ListRecordsResponse::from_value(&resp).expect("should parse");

        let records = &result.zones[0].records;
        assert_eq!(records.len(), 1);
        let record = &records[0];
        assert_eq!(record.record_type, "A");
        assert_eq!(record.ttl, 3600);
        assert_eq!(record.name, "www");

        match &record.parsed {
            Some(AnyRecordData::Writable(RecordData::A { ip })) => {
                assert_eq!(ip.to_string(), "1.2.3.4");
            }
            other => panic!("expected Writable(A), got {other:?}"),
        }
    }

    #[rstest]
    fn rrsig_parsed_as_read_only(
        zone_json: serde_json::Value,
        rrsig_record_json: serde_json::Value,
    ) {
        let resp = wrap_response(zone_json, vec![rrsig_record_json]);
        let result = ListRecordsResponse::from_value(&resp).expect("should parse");

        match &result.zones[0].records[0].parsed {
            Some(AnyRecordData::ReadOnly(ReadOnlyRecordData::Rrsig(data))) => {
                assert_eq!(data.type_covered, "A");
                assert_eq!(data.key_tag, 12345);
                assert_eq!(data.signer_name, "example.com");
            }
            other => panic!("expected ReadOnly(Rrsig), got {other:?}"),
        }
    }

    #[rstest]
    fn dnskey_parsed_as_read_only(
        zone_json: serde_json::Value,
        dnskey_record_json: serde_json::Value,
    ) {
        let resp = wrap_response(zone_json, vec![dnskey_record_json]);
        let result = ListRecordsResponse::from_value(&resp).expect("should parse");

        match &result.zones[0].records[0].parsed {
            Some(AnyRecordData::ReadOnly(ReadOnlyRecordData::Dnskey(data))) => {
                assert_eq!(data.flags, 257);
                assert_eq!(data.computed_key_tag, 12345);
                assert_eq!(data.dns_key_state.as_deref(), Some("Active"));
                assert_eq!(data.is_ksk, Some(true));
            }
            other => panic!("expected ReadOnly(Dnskey), got {other:?}"),
        }
    }

    #[rstest]
    fn unknown_type_produces_none_parsed(zone_json: serde_json::Value) {
        let record = json!({
            "name": "weird",
            "type": "NEWTYPE99",
            "ttl": 300,
            "rData": { "someField": "someValue" }
        });
        let resp = wrap_response(zone_json, vec![record]);
        let result = ListRecordsResponse::from_value(&resp).expect("should parse");
        assert!(
            result.zones[0].records[0].parsed.is_none(),
            "unknown type should produce None"
        );
    }

    #[rstest]
    fn mixed_records_parse_correctly(
        zone_json: serde_json::Value,
        a_record_json: serde_json::Value,
        rrsig_record_json: serde_json::Value,
    ) {
        let unknown = json!({ "name": "x", "type": "MYSTERY", "ttl": 60, "rData": {} });
        let resp = wrap_response(zone_json, vec![a_record_json, rrsig_record_json, unknown]);
        let result = ListRecordsResponse::from_value(&resp).expect("should parse");

        let records = &result.zones[0].records;
        assert_eq!(records.len(), 3);
        assert!(matches!(
            records[0].parsed,
            Some(AnyRecordData::Writable(_))
        ));
        assert!(matches!(
            records[1].parsed,
            Some(AnyRecordData::ReadOnly(_))
        ));
        assert!(records[2].parsed.is_none());
    }

    // ── from_value — error paths ──────────────────────────────────────────────

    #[rstest]
    fn missing_response_key_returns_parse_error() {
        let bad = json!({ "status": "ok" });
        let err = ListRecordsResponse::from_value(&bad).unwrap_err();
        assert!(
            matches!(err, crate::core::error::Error::Parse { ref context } if context.contains("'response'"))
        );
    }

    #[rstest]
    fn missing_zone_key_returns_parse_error() {
        let bad = json!({ "status": "ok", "response": { "records": [] } });
        let err = ListRecordsResponse::from_value(&bad).unwrap_err();
        assert!(
            matches!(err, crate::core::error::Error::Parse { ref context } if context.contains("zone"))
        );
    }

    #[rstest]
    fn missing_records_key_returns_parse_error(zone_json: serde_json::Value) {
        let bad = json!({ "status": "ok", "response": { "zone": zone_json } });
        let err = ListRecordsResponse::from_value(&bad).unwrap_err();
        assert!(
            matches!(err, crate::core::error::Error::Parse { ref context } if context.contains("records"))
        );
    }

    #[rstest]
    #[case(json!({}))]
    #[case(json!(null))]
    #[case(json!([]))]
    fn empty_or_null_json_returns_parse_error(#[case] input: serde_json::Value) {
        assert!(ListRecordsResponse::from_value(&input).is_err());
    }

    #[rstest]
    fn skips_malformed_records_rather_than_failing(
        zone_json: serde_json::Value,
        a_record_json: serde_json::Value,
    ) {
        let bad_record = json!({ "name": "bad", "ttl": 300, "rData": {} });
        let resp = wrap_response(zone_json, vec![bad_record, a_record_json]);
        let result = ListRecordsResponse::from_value(&resp).expect("should parse overall response");
        let records = &result.zones[0].records;
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].record_type, "A");
    }

    // ── ZoneRecord fields ─────────────────────────────────────────────────────

    #[rstest]
    fn record_disabled_defaults_to_false(zone_json: serde_json::Value) {
        let record = json!({
            "name": "test", "type": "A", "ttl": 300,
            "rData": { "ipAddress": "10.0.0.1" }
        });
        let resp = wrap_response(zone_json, vec![record]);
        let result = ListRecordsResponse::from_value(&resp).unwrap();
        assert!(!result.zones[0].records[0].disabled);
    }

    #[rstest]
    fn record_comments_defaults_to_empty(zone_json: serde_json::Value) {
        let record = json!({
            "name": "test", "type": "A", "ttl": 300,
            "rData": { "ipAddress": "10.0.0.1" }
        });
        let resp = wrap_response(zone_json, vec![record]);
        let result = ListRecordsResponse::from_value(&resp).unwrap();
        assert_eq!(result.zones[0].records[0].comments, "");
    }

    // ── ListRecordsResponse::single ───────────────────────────────────────────

    #[rstest]
    fn single_wraps_zone_and_records_in_one_entry(zone_json: serde_json::Value) {
        let zone: ZoneInfo = serde_json::from_value(zone_json).unwrap();
        let result = ListRecordsResponse::single(zone, vec![]);
        assert_eq!(result.zones.len(), 1);
        assert_eq!(result.zones[0].zone.name, "example.com");
        assert!(result.zones[0].records.is_empty());
    }

    // ── Serialization shape ───────────────────────────────────────────────────

    fn make_zone(name: &str) -> ZoneInfo {
        ZoneInfo {
            id: None,
            name: name.to_string(),
            zone_type: "Primary".to_string(),
            disabled: false,
            dnssec_status: None,
        }
    }

    #[test]
    fn single_zone_serializes_flat() {
        let resp = ListRecordsResponse::single(make_zone("example.com"), vec![]);
        let v = serde_json::to_value(&resp).unwrap();
        assert!(v.get("zone").is_some(), "should have top-level 'zone'");
        assert!(
            v.get("records").is_some(),
            "should have top-level 'records'"
        );
        assert!(v.get("zones").is_none(), "should NOT have 'zones' wrapper");
        assert_eq!(v["zone"]["name"], "example.com");
    }

    #[test]
    fn multi_zone_serializes_with_zones_array() {
        let resp = ListRecordsResponse {
            zones: vec![
                ZoneRecords {
                    zone: make_zone("a.example.com"),
                    records: vec![],
                },
                ZoneRecords {
                    zone: make_zone("b.example.com"),
                    records: vec![],
                },
            ],
        };
        let v = serde_json::to_value(&resp).unwrap();
        assert!(v.get("zones").is_some(), "should have 'zones' array");
        assert!(v.get("zone").is_none(), "should NOT have top-level 'zone'");
        assert_eq!(v["zones"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn single_zone_round_trips_through_serde() {
        let original = ListRecordsResponse::single(make_zone("example.com"), vec![]);
        let json = serde_json::to_value(&original).unwrap();
        let restored: ListRecordsResponse = serde_json::from_value(json).unwrap();
        assert_eq!(restored.zones.len(), 1);
        assert_eq!(restored.zones[0].zone.name, "example.com");
    }

    #[test]
    fn multi_zone_round_trips_through_serde() {
        let original = ListRecordsResponse {
            zones: vec![
                ZoneRecords {
                    zone: make_zone("a.example.com"),
                    records: vec![],
                },
                ZoneRecords {
                    zone: make_zone("b.example.com"),
                    records: vec![],
                },
            ],
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ListRecordsResponse = serde_json::from_value(json).unwrap();
        assert_eq!(restored.zones.len(), 2);
        assert_eq!(restored.zones[0].zone.name, "a.example.com");
        assert_eq!(restored.zones[1].zone.name, "b.example.com");
    }
}