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
//! Pi-hole v6 implementations of the vendor-neutral DNS service traits.
//!
//! Pi-hole is a DNS sinkhole and ad-blocker with a REST API for managing:
//!   - Local DNS records (A, AAAA, CNAME)
//!   - Domain allow/block lists
//!   - Query cache
//!   - Statistics
//!   - Server configuration
//!
//! Zone management (create/delete/import/export) is not supported.

use serde_json::Value;
use tracing::instrument;

use crate::control_plane::config::VendorKind;
use crate::core::dns::capabilities::VendorCapabilities;
use crate::core::dns::logs::{LogLine, LogsOptions, LogsRead};
use crate::core::dns::records::RecordData;
use crate::core::dns::responses::{ListRecordsResponse, ZoneInfo, ZoneRecord};
use crate::core::dns::service::{
    AccessListRead, AccessListWrite, CacheRead, CacheWrite, DnsVendor, ListRecordsOptions,
    RecordWrite, SettingsRead, StatsRead, ZoneExport, ZoneImport, ZoneRead, ZoneWrite,
};
use crate::core::error::{Error, Result};
use crate::vendors::pihole::client::PiholeClient;
use crate::vendors::pihole::mapping::*;

// ─── DnsVendor ────────────────────────────────────────────────────────────────

impl DnsVendor for PiholeClient {
    fn kind(&self) -> VendorKind {
        VendorKind::Pihole
    }

    fn capabilities(&self) -> VendorCapabilities {
        VendorCapabilities {
            zones: false,
            records: true,
            cache: true,
            access_lists: true,
            settings: true,
            zone_import: false,
            zone_export: false,
            logs: false,
        }
    }
}

// ─── ZoneRead ─────────────────────────────────────────────────────────────────

impl ZoneRead for PiholeClient {
    async fn list_zones<'a>(&'a self, _page: u32, _per_page: u32) -> Result<Value> {
        Err(Error::unsupported("Pi-hole", "zone listing"))
    }

    #[instrument(skip(self), fields(vendor = "pihole", operation = "list_records"))]
    async fn list_records<'a>(
        &'a self,
        domain: &'a str,
        zone: Option<&'a str>,
        options: ListRecordsOptions,
    ) -> Result<ListRecordsResponse> {
        let inferred;
        let zone_name = match zone {
            Some(z) => z,
            None => {
                inferred = infer_zone(domain);
                &inferred
            }
        };

        let dns_data = self.get("/api/dns/local_records", &[]).await?;
        let cname_data = self.get("/api/dns/local_cnames", &[]).await?;

        let mut records: Vec<ZoneRecord> = Vec::new();

        let domain_lc = domain.trim_end_matches('.').to_ascii_lowercase();
        let domain_suffix = format!(".{domain_lc}");

        if let Some(arr) = dns_data.get("dns").and_then(|d| d.as_array()) {
            for entry in arr {
                let host = entry.get("host").and_then(|h| h.as_str()).unwrap_or("");
                let host_lc = host.trim_end_matches('.').to_ascii_lowercase();
                if domain.is_empty()
                    || host_lc == domain_lc
                    || (options.all_subdomains && host_lc.ends_with(&domain_suffix))
                {
                    records.push(local_dns_to_zone_record(entry, zone_name));
                }
            }
        }

        if let Some(arr) = cname_data.get("cnames").and_then(|c| c.as_array()) {
            for entry in arr {
                let cname_domain = entry.get("domain").and_then(|d| d.as_str()).unwrap_or("");
                let cname_lc = cname_domain.trim_end_matches('.').to_ascii_lowercase();
                if domain.is_empty()
                    || cname_lc == domain_lc
                    || (options.all_subdomains && cname_lc.ends_with(&domain_suffix))
                {
                    records.push(local_cname_to_zone_record(entry, zone_name));
                }
            }
        }

        let zone_info = ZoneInfo {
            id: None,
            name: zone_name.to_string(),
            zone_type: "Local".to_string(),
            disabled: false,
            dnssec_status: None,
        };

        Ok(ListRecordsResponse::single(zone_info, records))
    }
}

// ─── ZoneWrite ────────────────────────────────────────────────────────────────

impl ZoneWrite for PiholeClient {
    async fn create_zone<'a>(&'a self, _zone: &'a str, _zone_type: &'a str) -> Result<Value> {
        Err(Error::unsupported("Pi-hole", "zone creation"))
    }

    async fn delete_zone<'a>(&'a self, _zone: &'a str) -> Result<Value> {
        Err(Error::unsupported("Pi-hole", "zone deletion"))
    }

    async fn enable_zone<'a>(&'a self, _zone: &'a str) -> Result<Value> {
        Err(Error::unsupported("Pi-hole", "enable zone"))
    }

    async fn disable_zone<'a>(&'a self, _zone: &'a str) -> Result<Value> {
        Err(Error::unsupported("Pi-hole", "disable zone"))
    }
}

// ─── RecordWrite ──────────────────────────────────────────────────────────────

impl RecordWrite for PiholeClient {
    #[instrument(
        skip(self, record),
        fields(vendor = "pihole", operation = "add_record")
    )]
    async fn add_record<'a>(
        &'a self,
        _zone: &'a str,
        domain: &'a str,
        _ttl: u32,
        record: &'a RecordData,
    ) -> Result<Value> {
        let body = record_data_to_local_dns_body(domain, record).ok_or_else(|| {
            Error::unsupported(
                "Pi-hole",
                "record type — only A, AAAA, and CNAME are supported",
            )
        })?;

        let endpoint = match record {
            RecordData::Cname { .. } => "/api/dns/local_cnames",
            _ => "/api/dns/local_records",
        };

        self.post(endpoint, &body).await
    }

    #[instrument(
        skip(self, type_params),
        fields(vendor = "pihole", operation = "delete_record")
    )]
    async fn delete_record<'a>(
        &'a self,
        _zone: &'a str,
        domain: &'a str,
        type_params: &'a [(&'a str, String)],
    ) -> Result<Value> {
        let record_type = type_params
            .iter()
            .find(|(k, _)| *k == "type")
            .map(|(_, v)| v.as_str())
            .unwrap_or("A");

        let ip = type_params
            .iter()
            .find(|(k, _)| *k == "ipAddress" || *k == "ip")
            .map(|(_, v)| v.clone());

        let target = type_params
            .iter()
            .find(|(k, _)| *k == "cname")
            .map(|(_, v)| v.clone());

        match record_type.to_uppercase().as_str() {
            "A" | "AAAA" => {
                let ip_val = ip.ok_or_else(|| {
                    Error::parse("delete A/AAAA record requires 'ip' or 'ipAddress' parameter")
                })?;
                let body = serde_json::json!({ "ip": ip_val, "host": domain });
                self.delete_with_body("/api/dns/local_records", &body).await
            }
            "CNAME" => {
                let cname_target = target.ok_or_else(|| {
                    Error::parse("delete CNAME record requires 'cname' parameter")
                })?;
                let body = serde_json::json!({ "domain": domain, "target": cname_target });
                self.delete_with_body("/api/dns/local_cnames", &body).await
            }
            _ => Err(Error::unsupported(
                "Pi-hole",
                "record type — only A, AAAA, and CNAME can be deleted",
            )),
        }
    }
}

// ─── CacheRead ────────────────────────────────────────────────────────────────

impl CacheRead for PiholeClient {
    #[instrument(skip(self), fields(vendor = "pihole", operation = "list_cache"))]
    async fn list_cache<'a>(&'a self, _domain: &'a str) -> Result<Value> {
        self.get("/api/cache", &[]).await
    }
}

// ─── CacheWrite ───────────────────────────────────────────────────────────────

impl CacheWrite for PiholeClient {
    async fn delete_cache_zone<'a>(&'a self, _domain: &'a str) -> Result<Value> {
        Err(Error::unsupported("Pi-hole", "per-zone cache deletion"))
    }

    #[instrument(skip(self), fields(vendor = "pihole", operation = "flush_cache"))]
    async fn flush_cache(&self) -> Result<Value> {
        self.post("/api/cache/flush", &serde_json::json!({})).await
    }
}

// ─── StatsRead ────────────────────────────────────────────────────────────────

impl StatsRead for PiholeClient {
    #[instrument(skip(self), fields(vendor = "pihole", operation = "get_stats"))]
    async fn get_stats<'a>(&'a self, stats_type: &'a str) -> Result<Value> {
        match stats_type {
            "overTime" | "overtime" | "history" => {
                self.get("/api/stats/overTime/history", &[]).await
            }
            "clients" => self.get("/api/stats/overTime/clients", &[]).await,
            _ => self.get("/api/stats/summary", &[]).await,
        }
    }
}

// ─── AccessListRead ───────────────────────────────────────────────────────────

impl AccessListRead for PiholeClient {
    #[instrument(skip(self), fields(vendor = "pihole", operation = "list_blocked"))]
    async fn list_blocked(&self) -> Result<Value> {
        self.get("/api/domains", &[("type", "block".to_string())])
            .await
    }

    #[instrument(skip(self), fields(vendor = "pihole", operation = "list_allowed"))]
    async fn list_allowed(&self) -> Result<Value> {
        self.get("/api/domains", &[("type", "allow".to_string())])
            .await
    }
}

// ─── AccessListWrite ──────────────────────────────────────────────────────────

impl AccessListWrite for PiholeClient {
    #[instrument(skip(self), fields(vendor = "pihole", operation = "add_blocked"))]
    async fn add_blocked<'a>(&'a self, domain: &'a str) -> Result<Value> {
        self.post(
            &format!("/api/domains/block/exact/{domain}"),
            &serde_json::json!({}),
        )
        .await
    }

    #[instrument(skip(self), fields(vendor = "pihole", operation = "delete_blocked"))]
    async fn delete_blocked<'a>(&'a self, domain: &'a str) -> Result<Value> {
        self.delete(&format!("/api/domains/block/exact/{domain}"))
            .await
    }

    #[instrument(skip(self), fields(vendor = "pihole", operation = "add_allowed"))]
    async fn add_allowed<'a>(&'a self, domain: &'a str) -> Result<Value> {
        self.post(
            &format!("/api/domains/allow/exact/{domain}"),
            &serde_json::json!({}),
        )
        .await
    }

    #[instrument(skip(self), fields(vendor = "pihole", operation = "delete_allowed"))]
    async fn delete_allowed<'a>(&'a self, domain: &'a str) -> Result<Value> {
        self.delete(&format!("/api/domains/allow/exact/{domain}"))
            .await
    }
}

// ─── ZoneImport / ZoneExport ──────────────────────────────────────────────────

impl ZoneImport for PiholeClient {
    async fn import_zone_file<'a>(
        &'a self,
        _zone: &'a str,
        _file_name: String,
        _file_bytes: Vec<u8>,
        _overwrite: bool,
        _overwrite_zone: bool,
        _overwrite_soa_serial: bool,
    ) -> Result<Value> {
        Err(Error::unsupported("Pi-hole", "zone import"))
    }
}

impl ZoneExport for PiholeClient {
    async fn export_zone_file<'a>(&'a self, _zone: &'a str) -> Result<String> {
        Err(Error::unsupported("Pi-hole", "zone export"))
    }
}

// ─── SettingsRead ─────────────────────────────────────────────────────────────

impl SettingsRead for PiholeClient {
    #[instrument(skip(self), fields(vendor = "pihole", operation = "get_settings"))]
    async fn get_settings(&self) -> Result<Value> {
        self.get("/api/config", &[]).await
    }
}

// ─── LogsRead ─────────────────────────────────────────────────────────────────

impl LogsRead for PiholeClient {
    async fn get_logs(&self, _options: LogsOptions) -> Result<Vec<LogLine>> {
        Err(Error::unsupported("Pi-hole", "logs"))
    }
}

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

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

    fn make_client() -> PiholeClient {
        PiholeClient::new(
            "http://pi.hole".to_string(),
            crate::core::secret::ApiToken::new("test-password"),
        )
        .unwrap()
    }

    #[test]
    fn kind_returns_pihole() {
        assert_eq!(make_client().kind(), VendorKind::Pihole);
    }

    #[test]
    fn capabilities_match_supported_operations() {
        let caps = make_client().capabilities();
        assert!(!caps.zones);
        assert!(caps.records);
        assert!(caps.cache);
        assert!(caps.access_lists);
        assert!(caps.settings);
        assert!(!caps.zone_import);
        assert!(!caps.zone_export);
    }

    #[tokio::test]
    async fn list_zones_is_unsupported() {
        let err = make_client().list_zones(1, 100).await.unwrap_err();
        assert!(matches!(
            err,
            Error::Unsupported {
                vendor: "Pi-hole",
                ..
            }
        ));
    }

    #[tokio::test]
    async fn create_zone_is_unsupported() {
        let err = make_client()
            .create_zone("example.com", "Primary")
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Unsupported { vendor: "Pi-hole", .. }));
    }

    #[tokio::test]
    async fn delete_zone_is_unsupported() {
        let err = make_client().delete_zone("example.com").await.unwrap_err();
        assert!(matches!(err, Error::Unsupported { vendor: "Pi-hole", .. }));
    }

    #[tokio::test]
    async fn enable_zone_is_unsupported() {
        let err = make_client().enable_zone("example.com").await.unwrap_err();
        assert!(matches!(err, Error::Unsupported { vendor: "Pi-hole", .. }));
    }

    #[tokio::test]
    async fn disable_zone_is_unsupported() {
        let err = make_client()
            .disable_zone("example.com")
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Unsupported { vendor: "Pi-hole", .. }));
    }

    #[tokio::test]
    async fn delete_cache_zone_is_unsupported() {
        let err = make_client()
            .delete_cache_zone("example.com")
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Unsupported { vendor: "Pi-hole", .. }));
    }

    #[tokio::test]
    async fn zone_import_is_unsupported() {
        let err = make_client()
            .import_zone_file("example.com", "zone.txt".into(), vec![], true, false, false)
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Unsupported { vendor: "Pi-hole", .. }));
    }

    #[tokio::test]
    async fn zone_export_is_unsupported() {
        let err = make_client()
            .export_zone_file("example.com")
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Unsupported { vendor: "Pi-hole", .. }));
    }

    #[tokio::test]
    async fn add_unsupported_record_type_is_unsupported() {
        let record = RecordData::Mx {
            preference: 10,
            exchange: "mail.example.com".into(),
        };
        let err = make_client()
            .add_record("home.lan", "example.com", 300, &record)
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Unsupported { vendor: "Pi-hole", .. }));
    }
}