Skip to main content

townos_api/
dns.rs

1//! DNS: the `rolodex` zones the box is authoritative for, plus the blocklists it
2//! filters resolution through.
3//!
4//! Reads need only a session; every write is admin-only. The UI checks
5//! [`crate::Account::admin`] up front so a read-only account sees the records
6//! greyed rather than a 403 after typing one.
7
8use serde::{Deserialize, Serialize};
9
10use crate::{Client, Error, Result};
11
12/// DNS record types, as the protobuf enum integers the API speaks.
13///
14/// The wire format is the number; the name is ours. Anything the box reports
15/// that this build does not know stays legible as `TYPE<n>` rather than being
16/// dropped from the table.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18pub struct RecordType(pub i32);
19
20impl RecordType {
21    pub const A: RecordType = RecordType(0);
22    pub const AAAA: RecordType = RecordType(1);
23    pub const CNAME: RecordType = RecordType(2);
24    pub const MX: RecordType = RecordType(3);
25    pub const TXT: RecordType = RecordType(4);
26    pub const SRV: RecordType = RecordType(5);
27    pub const NS: RecordType = RecordType(6);
28    pub const PTR: RecordType = RecordType(7);
29    pub const SOA: RecordType = RecordType(8);
30    pub const CAA: RecordType = RecordType(9);
31    pub const TLSA: RecordType = RecordType(10);
32
33    /// The types offered in the "add record" form, in the order they appear.
34    pub const COMMON: [RecordType; 7] = [
35        RecordType::A,
36        RecordType::AAAA,
37        RecordType::CNAME,
38        RecordType::MX,
39        RecordType::TXT,
40        RecordType::SRV,
41        RecordType::CAA,
42    ];
43
44    pub fn name(self) -> String {
45        match self {
46            RecordType::A => "A".into(),
47            RecordType::AAAA => "AAAA".into(),
48            RecordType::CNAME => "CNAME".into(),
49            RecordType::MX => "MX".into(),
50            RecordType::TXT => "TXT".into(),
51            RecordType::SRV => "SRV".into(),
52            RecordType::NS => "NS".into(),
53            RecordType::PTR => "PTR".into(),
54            RecordType::SOA => "SOA".into(),
55            RecordType::CAA => "CAA".into(),
56            RecordType::TLSA => "TLSA".into(),
57            RecordType(other) => format!("TYPE{other}"),
58        }
59    }
60
61    /// Whether this type carries a priority, which is the only field the add
62    /// form shows conditionally.
63    pub fn uses_priority(self) -> bool {
64        matches!(self, RecordType::MX | RecordType::SRV)
65    }
66}
67
68#[derive(Debug, Clone, Default, Deserialize)]
69pub struct DnsStatus {
70    #[serde(default)]
71    pub enabled: bool,
72    #[serde(default)]
73    pub running: bool,
74    #[serde(default)]
75    pub tld: String,
76    #[serde(default)]
77    pub record_count: u64,
78    /// What the operator asked for.
79    #[serde(default)]
80    pub local_forwarders: bool,
81    /// What `rolodex.yml` actually holds. This disagrees with
82    /// `local_forwarders` when local-resolver discovery found nothing usable and
83    /// the public defaults were kept — worth showing, because the box is then
84    /// not doing what the setting says.
85    #[serde(default)]
86    pub forwarders: Vec<String>,
87}
88
89#[derive(Debug, Clone, Deserialize)]
90pub struct DnsRecord {
91    #[serde(default)]
92    pub name: String,
93    #[serde(default)]
94    pub record_type: i32,
95    #[serde(default)]
96    pub value: String,
97    #[serde(default)]
98    pub ttl: u32,
99    #[serde(default)]
100    pub priority: u32,
101    #[serde(default)]
102    pub network: String,
103    #[serde(default)]
104    pub tld: String,
105}
106
107impl DnsRecord {
108    pub fn kind(&self) -> RecordType {
109        RecordType(self.record_type)
110    }
111}
112
113/// A package service and whether it is published in the zone.
114#[derive(Debug, Clone, Deserialize)]
115pub struct DnsService {
116    #[serde(default)]
117    pub repo: String,
118    #[serde(default)]
119    pub name: String,
120    #[serde(default)]
121    pub version: String,
122    #[serde(default)]
123    pub fqdn: String,
124    #[serde(default)]
125    pub domains: Vec<String>,
126    #[serde(default)]
127    pub published: bool,
128}
129
130#[derive(Debug, Clone, Default, Serialize, Deserialize)]
131pub struct BlocklistProvider {
132    pub zone: String,
133    pub enabled: bool,
134    /// What "I refused your query" looks like from this provider, as opposed to
135    /// "this is listed" — both arrive as the same kind of record and only the
136    /// address separates them. Empty reads back as rolodex's built-in set.
137    #[serde(default, skip_serializing_if = "Vec::is_empty")]
138    pub refusal_codes: Vec<String>,
139    #[serde(default, skip_serializing_if = "is_zero")]
140    pub refusal_cooldown_secs: u64,
141}
142
143fn is_zero(v: &u64) -> bool {
144    *v == 0
145}
146
147/// The single-entry refusal-code list that switches refusal detection off.
148///
149/// Distinct from an empty list, which means "use rolodex's built-in set" —
150/// because an empty list is what every configuration written before refusal
151/// detection existed already has, so it cannot also mean "none".
152pub const REFUSAL_CODES_NONE: &str = "none";
153
154/// Checks a provider zone the way the box does, answering the normalized form.
155///
156/// The box lowercases and trims before storing, so a zone typed with different
157/// case would otherwise appear to have been rewritten when the config is read
158/// back. A fully-qualified name is required: a single label is never a DNSxL.
159pub fn validate_blocklist_zone(zone: &str) -> Result<String> {
160    let zone = zone.trim().trim_end_matches('.').to_ascii_lowercase();
161    if zone.is_empty() {
162        return Err(Error::BaseUrl("a provider needs a zone".into()));
163    }
164    if zone.len() > 253 {
165        return Err(Error::BaseUrl(format!(
166            "a zone is at most 253 characters, and this is {}",
167            zone.len()
168        )));
169    }
170    let labels: Vec<&str> = zone.split('.').collect();
171    if labels.len() < 2 {
172        return Err(Error::BaseUrl(
173            "a zone must be fully qualified, as zen.spamhaus.org".into(),
174        ));
175    }
176    for label in labels {
177        if label.is_empty() || label.len() > 63 {
178            return Err(Error::BaseUrl(format!("{label:?} is not a usable label")));
179        }
180        if label.starts_with('-') || label.ends_with('-') {
181            return Err(Error::BaseUrl(format!(
182                "{label:?} may not start or end with a hyphen"
183            )));
184        }
185        if !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
186            return Err(Error::BaseUrl(format!(
187                "{label:?} must be alphanumeric with optional internal hyphens"
188            )));
189        }
190    }
191    Ok(zone)
192}
193
194/// Parses a typed refusal-code list — commas or spaces between entries — into the
195/// normalized form the box stores.
196///
197/// Empty answers an empty list, which the box reads as its built-in set;
198/// [`REFUSAL_CODES_NONE`] alone switches detection off and is refused alongside
199/// real codes, because a list that both disables detection and names codes to
200/// detect has no reading to pick.
201///
202/// Each entry is an IPv4 address or `address/prefix`, and a prefix is masked to
203/// its network the way rolodex stores it, so what comes back from a later `GET`
204/// matches what was submitted rather than looking like an edit.
205pub fn parse_refusal_codes(input: &str) -> Result<Vec<String>> {
206    let entries: Vec<&str> = input
207        .split([',', ' ', '\t', '\n'])
208        .map(str::trim)
209        .filter(|e| !e.is_empty())
210        .collect();
211
212    if entries.is_empty() {
213        return Ok(Vec::new());
214    }
215    if entries.iter().any(|e| e.eq_ignore_ascii_case(REFUSAL_CODES_NONE)) {
216        if entries.len() == 1 {
217            return Ok(vec![REFUSAL_CODES_NONE.into()]);
218        }
219        return Err(Error::BaseUrl(format!(
220            "{REFUSAL_CODES_NONE:?} switches refusal detection off and must be the only entry"
221        )));
222    }
223
224    let mut out: Vec<String> = Vec::with_capacity(entries.len());
225    for entry in entries {
226        let code = normalize_refusal_code(entry)?;
227        if out.contains(&code) {
228            return Err(Error::BaseUrl(format!("{code} appears twice")));
229        }
230        out.push(code);
231    }
232    Ok(out)
233}
234
235/// Normalizes one refusal code, masking a prefix to its network.
236///
237/// A `/32` renders bare because that is how rolodex renders it back; keeping the
238/// suffix would make a code read back from `GET` differ from the one submitted.
239fn normalize_refusal_code(code: &str) -> Result<String> {
240    let bad = |what: &str| Error::BaseUrl(format!("refusal code {code:?} is invalid: {what}"));
241
242    let (addr, bits) = match code.split_once('/') {
243        Some((addr, prefix)) => {
244            let bits: u32 = prefix
245                .trim()
246                .parse()
247                .map_err(|_| bad("the prefix must be a number"))?;
248            if bits > 32 {
249                return Err(bad("the prefix must be between 0 and 32"));
250            }
251            (addr.trim(), bits)
252        }
253        None => (code.trim(), 32),
254    };
255
256    let octets: Vec<u8> = addr
257        .split('.')
258        .map(|o| o.parse::<u8>().ok())
259        .collect::<Option<_>>()
260        .ok_or_else(|| bad("expected an IPv4 address"))?;
261    if octets.len() != 4 {
262        return Err(bad("expected an IPv4 address"));
263    }
264
265    let value = u32::from_be_bytes([octets[0], octets[1], octets[2], octets[3]]);
266    // A /0 mask is the whole shift-by-32 edge case, which would be UB-ish
267    // wrapping rather than zero.
268    let mask = if bits == 0 { 0 } else { u32::MAX << (32 - bits) };
269    let masked = value & mask;
270    let [a, b, c, d] = masked.to_be_bytes();
271
272    Ok(if bits == 32 {
273        format!("{a}.{b}.{c}.{d}")
274    } else {
275        format!("{a}.{b}.{c}.{d}/{bits}")
276    })
277}
278
279/// A provider currently out of the rotation because it refused a query.
280#[derive(Debug, Clone, Deserialize)]
281pub struct RotatedOut {
282    #[serde(default)]
283    pub zone: String,
284    #[serde(default)]
285    pub code: String,
286    #[serde(default)]
287    pub seconds_remaining: u64,
288}
289
290#[derive(Debug, Clone, Default, Deserialize)]
291pub struct BlocklistConfig {
292    #[serde(default)]
293    pub enabled: bool,
294    #[serde(default)]
295    pub providers: Vec<BlocklistProvider>,
296    #[serde(default)]
297    pub refusal_cooldown_secs: u64,
298    #[serde(default)]
299    pub rotated_out: Vec<RotatedOut>,
300}
301
302#[derive(Debug, Clone, Deserialize)]
303pub struct BlocklistEntry {
304    #[serde(default)]
305    pub name: String,
306    #[serde(default)]
307    pub reason: String,
308}
309
310/// Which of the two blocklists a call addresses.
311///
312/// They are the same shape with independent state: the RBL matches addresses,
313/// the DNSBL matches names. One enum keeps the six endpoint pairs from becoming
314/// twelve near-identical methods.
315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
316pub enum Blocklist {
317    /// Reverse-IP blocklist.
318    Rbl,
319    /// Domain blocklist.
320    Dnsbl,
321}
322
323impl Blocklist {
324    fn path(self) -> &'static str {
325        match self {
326            Blocklist::Rbl => "/dns/rbl",
327            Blocklist::Dnsbl => "/dns/dnsbl",
328        }
329    }
330
331    pub fn label(self) -> &'static str {
332        match self {
333            Blocklist::Rbl => "Address blocklist (RBL)",
334            Blocklist::Dnsbl => "Domain blocklist (DNSBL)",
335        }
336    }
337}
338
339impl Client {
340    /// Calls `GET /dns/status`.
341    pub async fn dns_status(&self) -> Result<DnsStatus> {
342        self.get_json("/dns/status").await
343    }
344
345    /// Lists records, optionally confined to one TLD.
346    ///
347    /// With no TLD this spans every network — the global home zone plus each
348    /// network's scoped zone — and each row says which it came from.
349    ///
350    /// Calls `GET /dns/records`.
351    pub async fn dns_records(&self, tld: Option<&str>) -> Result<Vec<DnsRecord>> {
352        let path = match tld.filter(|t| !t.is_empty()) {
353            Some(tld) => format!("/dns/records?tld={}", urlencode(tld)),
354            None => "/dns/records".into(),
355        };
356        self.get_json(&path).await
357    }
358
359    /// Calls `POST /dns/records/add` (admin).
360    pub async fn add_dns_record(
361        &self,
362        name: &str,
363        record_type: RecordType,
364        value: &str,
365        ttl: u32,
366    ) -> Result<()> {
367        self.post_empty(
368            "/dns/records/add",
369            &serde_json::json!({
370                "name": name,
371                "record_type": record_type.0,
372                "value": value,
373                "ttl": ttl,
374            }),
375        )
376        .await
377    }
378
379    /// Calls `POST /dns/records/remove` (admin).
380    pub async fn remove_dns_record(&self, name: &str, record_type: RecordType) -> Result<()> {
381        self.post_empty(
382            "/dns/records/remove",
383            &serde_json::json!({ "name": name, "record_type": record_type.0 }),
384        )
385        .await
386    }
387
388    /// Calls `GET /dns/tld`.
389    pub async fn dns_tld(&self) -> Result<String> {
390        #[derive(Deserialize)]
391        struct Tld {
392            #[serde(default)]
393            tld: String,
394        }
395        let out: Tld = self.get_json("/dns/tld").await?;
396        Ok(out.tld)
397    }
398
399    /// Calls `POST /dns/tld` (admin).
400    pub async fn set_dns_tld(&self, tld: &str) -> Result<()> {
401        self.post_empty("/dns/tld", &serde_json::json!({ "tld": tld })).await
402    }
403
404    /// Idempotent zone init plus package registration. Calls `POST /dns/setup`.
405    pub async fn setup_dns(&self) -> Result<()> {
406        self.post_empty("/dns/setup", &serde_json::json!({})).await
407    }
408
409    /// Calls `GET /dns/services`.
410    pub async fn dns_services(&self) -> Result<Vec<DnsService>> {
411        self.get_json("/dns/services").await
412    }
413
414    /// Publishes or withdraws a package service in the zone.
415    ///
416    /// Calls `POST /dns/services/set` (admin).
417    pub async fn set_dns_service(&self, repo: &str, name: &str, published: bool) -> Result<()> {
418        self.post_empty(
419            "/dns/services/set",
420            &serde_json::json!({ "repo": repo, "name": name, "published": published }),
421        )
422        .await
423    }
424
425    /// Calls `GET /dns/rbl` or `GET /dns/dnsbl`.
426    pub async fn blocklist_config(&self, which: Blocklist) -> Result<BlocklistConfig> {
427        self.get_json(which.path()).await
428    }
429
430    /// Replaces a blocklist's configuration wholesale.
431    ///
432    /// Calls `POST /dns/rbl` or `POST /dns/dnsbl` (admin).
433    pub async fn set_blocklist_config(
434        &self,
435        which: Blocklist,
436        enabled: bool,
437        providers: &[BlocklistProvider],
438        refusal_cooldown_secs: u64,
439    ) -> Result<()> {
440        self.post_empty(
441            which.path(),
442            &serde_json::json!({
443                "enabled": enabled,
444                "providers": providers,
445                "refusal_cooldown_secs": refusal_cooldown_secs,
446            }),
447        )
448        .await
449    }
450
451    /// Calls `GET /dns/rbl/local`.
452    pub async fn local_rbl(&self) -> Result<Vec<BlocklistEntry>> {
453        self.get_json("/dns/rbl/local").await
454    }
455
456    /// Calls `POST /dns/rbl/local/add` (admin).
457    pub async fn add_local_rbl(&self, name: &str, reason: &str) -> Result<()> {
458        self.post_empty(
459            "/dns/rbl/local/add",
460            &serde_json::json!({ "name": name, "reason": reason }),
461        )
462        .await
463    }
464
465    /// Calls `POST /dns/rbl/local/remove` (admin).
466    pub async fn remove_local_rbl(&self, name: &str) -> Result<()> {
467        self.post_empty("/dns/rbl/local/remove", &serde_json::json!({ "name": name }))
468            .await
469    }
470
471    /// Names exempted from the name-based block, along with everything beneath
472    /// them. Calls `GET /dns/dnsbl/allowlist`.
473    pub async fn dnsbl_allowlist(&self) -> Result<Vec<BlocklistEntry>> {
474        self.get_json("/dns/dnsbl/allowlist").await
475    }
476
477    /// Calls `POST /dns/dnsbl/allowlist/add` (admin).
478    pub async fn add_dnsbl_allowlist(&self, name: &str, reason: &str) -> Result<()> {
479        self.post_empty(
480            "/dns/dnsbl/allowlist/add",
481            &serde_json::json!({ "name": name, "reason": reason }),
482        )
483        .await
484    }
485
486    /// Calls `POST /dns/dnsbl/allowlist/remove` (admin).
487    pub async fn remove_dnsbl_allowlist(&self, name: &str) -> Result<()> {
488        self.post_empty(
489            "/dns/dnsbl/allowlist/remove",
490            &serde_json::json!({ "name": name }),
491        )
492        .await
493    }
494}
495
496/// Percent-encodes a query parameter value.
497///
498/// Only the characters that would change how the query parses are escaped; a
499/// TLD is a hostname, so this is a narrow job and pulling in a dependency for it
500/// would be the larger cost.
501fn urlencode(value: &str) -> String {
502    let mut out = String::with_capacity(value.len());
503    for byte in value.bytes() {
504        match byte {
505            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
506                out.push(byte as char)
507            }
508            other => out.push_str(&format!("%{other:02X}")),
509        }
510    }
511    out
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    #[test]
519    fn unknown_record_types_stay_legible() {
520        assert_eq!(RecordType::A.name(), "A");
521        assert_eq!(RecordType(42).name(), "TYPE42");
522    }
523
524    #[test]
525    fn only_mx_and_srv_carry_priority() {
526        assert!(RecordType::MX.uses_priority());
527        assert!(RecordType::SRV.uses_priority());
528        assert!(!RecordType::A.uses_priority());
529        assert!(!RecordType::TXT.uses_priority());
530    }
531
532    #[test]
533    fn query_values_are_escaped() {
534        assert_eq!(urlencode("home.town"), "home.town");
535        assert_eq!(urlencode("a b&c=d"), "a%20b%26c%3Dd");
536    }
537
538    #[test]
539    fn provider_zones_are_normalised_not_just_accepted() {
540        assert_eq!(validate_blocklist_zone(" ZEN.Spamhaus.ORG. ").unwrap(), "zen.spamhaus.org");
541        assert_eq!(validate_blocklist_zone("dbl.spamhaus.org").unwrap(), "dbl.spamhaus.org");
542    }
543
544    #[test]
545    fn a_single_label_is_never_a_dnsxl() {
546        let err = validate_blocklist_zone("spamhaus").unwrap_err().detail();
547        assert!(err.contains("fully qualified"), "{err}");
548        assert!(validate_blocklist_zone("").is_err());
549        assert!(validate_blocklist_zone("a..b").is_err());
550        assert!(validate_blocklist_zone("-bad.example.org").is_err());
551        assert!(validate_blocklist_zone("bad_label.example.org").is_err());
552    }
553
554    #[test]
555    fn an_empty_refusal_list_means_the_built_in_set() {
556        assert!(parse_refusal_codes("").unwrap().is_empty());
557        assert!(parse_refusal_codes("  ,  ").unwrap().is_empty());
558    }
559
560    #[test]
561    fn none_switches_detection_off_and_stands_alone() {
562        assert_eq!(parse_refusal_codes("none").unwrap(), vec!["none".to_string()]);
563        assert_eq!(parse_refusal_codes(" NONE ").unwrap(), vec!["none".to_string()]);
564
565        let err = parse_refusal_codes("none, 127.0.0.2").unwrap_err().detail();
566        assert!(err.contains("only entry"), "{err}");
567    }
568
569    #[test]
570    fn codes_are_separated_by_commas_or_spaces() {
571        let expected = vec!["127.255.255.254".to_string(), "127.255.255.255".to_string()];
572        assert_eq!(
573            parse_refusal_codes("127.255.255.254, 127.255.255.255").unwrap(),
574            expected
575        );
576        assert_eq!(
577            parse_refusal_codes("127.255.255.254 127.255.255.255").unwrap(),
578            expected
579        );
580    }
581
582    #[test]
583    fn a_prefix_is_masked_to_its_network_and_a_32_renders_bare() {
584        // Spamhaus reserves the whole of 127.255.255.0/24 for errors, so an
585        // operator writes the range and it has to read back unchanged.
586        assert_eq!(
587            parse_refusal_codes("127.255.255.9/24").unwrap(),
588            vec!["127.255.255.0/24".to_string()]
589        );
590        assert_eq!(
591            parse_refusal_codes("127.0.0.2/32").unwrap(),
592            vec!["127.0.0.2".to_string()]
593        );
594        assert_eq!(parse_refusal_codes("10.1.2.3/0").unwrap(), vec!["0.0.0.0/0".to_string()]);
595    }
596
597    #[test]
598    fn duplicate_and_malformed_codes_are_refused() {
599        // The two spellings mask to the same code, which the box calls a duplicate.
600        let err = parse_refusal_codes("127.255.255.0/24, 127.255.255.9/24")
601            .unwrap_err()
602            .detail();
603        assert!(err.contains("twice"), "{err}");
604
605        assert!(parse_refusal_codes("127.0.0.2/33").is_err());
606        assert!(parse_refusal_codes("127.0.0.2/nine").is_err());
607        assert!(parse_refusal_codes("not-an-address").is_err());
608        assert!(parse_refusal_codes("127.0.0").is_err());
609        assert!(parse_refusal_codes("127.0.0.256").is_err());
610        assert!(parse_refusal_codes("::1").is_err());
611    }
612
613    #[test]
614    fn providers_omit_empty_optional_fields() {
615        let p = BlocklistProvider {
616            zone: "zen.example".into(),
617            enabled: true,
618            ..Default::default()
619        };
620        let json = serde_json::to_string(&p).unwrap();
621        assert_eq!(json, r#"{"zone":"zen.example","enabled":true}"#);
622    }
623}