townos-api 0.0.3

Client for the Town OS control plane (systemcontroller) HTTP API
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
//! DNS: the `rolodex` zones the box is authoritative for, plus the blocklists it
//! filters resolution through.
//!
//! Reads need only a session; every write is admin-only. The UI checks
//! [`crate::Account::admin`] up front so a read-only account sees the records
//! greyed rather than a 403 after typing one.

use serde::{Deserialize, Serialize};

use crate::{Client, Error, Result};

/// DNS record types, as the protobuf enum integers the API speaks.
///
/// The wire format is the number; the name is ours. Anything the box reports
/// that this build does not know stays legible as `TYPE<n>` rather than being
/// dropped from the table.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct RecordType(pub i32);

impl RecordType {
    pub const A: RecordType = RecordType(0);
    pub const AAAA: RecordType = RecordType(1);
    pub const CNAME: RecordType = RecordType(2);
    pub const MX: RecordType = RecordType(3);
    pub const TXT: RecordType = RecordType(4);
    pub const SRV: RecordType = RecordType(5);
    pub const NS: RecordType = RecordType(6);
    pub const PTR: RecordType = RecordType(7);
    pub const SOA: RecordType = RecordType(8);
    pub const CAA: RecordType = RecordType(9);
    pub const TLSA: RecordType = RecordType(10);

    /// The types offered in the "add record" form, in the order they appear.
    pub const COMMON: [RecordType; 7] = [
        RecordType::A,
        RecordType::AAAA,
        RecordType::CNAME,
        RecordType::MX,
        RecordType::TXT,
        RecordType::SRV,
        RecordType::CAA,
    ];

    pub fn name(self) -> String {
        match self {
            RecordType::A => "A".into(),
            RecordType::AAAA => "AAAA".into(),
            RecordType::CNAME => "CNAME".into(),
            RecordType::MX => "MX".into(),
            RecordType::TXT => "TXT".into(),
            RecordType::SRV => "SRV".into(),
            RecordType::NS => "NS".into(),
            RecordType::PTR => "PTR".into(),
            RecordType::SOA => "SOA".into(),
            RecordType::CAA => "CAA".into(),
            RecordType::TLSA => "TLSA".into(),
            RecordType(other) => format!("TYPE{other}"),
        }
    }

    /// Whether this type carries a priority, which is the only field the add
    /// form shows conditionally.
    pub fn uses_priority(self) -> bool {
        matches!(self, RecordType::MX | RecordType::SRV)
    }
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct DnsStatus {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub running: bool,
    #[serde(default)]
    pub tld: String,
    #[serde(default)]
    pub record_count: u64,
    /// What the operator asked for.
    #[serde(default)]
    pub local_forwarders: bool,
    /// What `rolodex.yml` actually holds. This disagrees with
    /// `local_forwarders` when local-resolver discovery found nothing usable and
    /// the public defaults were kept — worth showing, because the box is then
    /// not doing what the setting says.
    #[serde(default)]
    pub forwarders: Vec<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DnsRecord {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub record_type: i32,
    #[serde(default)]
    pub value: String,
    #[serde(default)]
    pub ttl: u32,
    #[serde(default)]
    pub priority: u32,
    #[serde(default)]
    pub network: String,
    #[serde(default)]
    pub tld: String,
}

impl DnsRecord {
    pub fn kind(&self) -> RecordType {
        RecordType(self.record_type)
    }
}

/// A package service and whether it is published in the zone.
#[derive(Debug, Clone, Deserialize)]
pub struct DnsService {
    #[serde(default)]
    pub repo: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub version: String,
    #[serde(default)]
    pub fqdn: String,
    #[serde(default)]
    pub domains: Vec<String>,
    #[serde(default)]
    pub published: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BlocklistProvider {
    pub zone: String,
    pub enabled: bool,
    /// What "I refused your query" looks like from this provider, as opposed to
    /// "this is listed" — both arrive as the same kind of record and only the
    /// address separates them. Empty reads back as rolodex's built-in set.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub refusal_codes: Vec<String>,
    #[serde(default, skip_serializing_if = "is_zero")]
    pub refusal_cooldown_secs: u64,
}

fn is_zero(v: &u64) -> bool {
    *v == 0
}

/// The single-entry refusal-code list that switches refusal detection off.
///
/// Distinct from an empty list, which means "use rolodex's built-in set" —
/// because an empty list is what every configuration written before refusal
/// detection existed already has, so it cannot also mean "none".
pub const REFUSAL_CODES_NONE: &str = "none";

/// Checks a provider zone the way the box does, answering the normalized form.
///
/// The box lowercases and trims before storing, so a zone typed with different
/// case would otherwise appear to have been rewritten when the config is read
/// back. A fully-qualified name is required: a single label is never a DNSxL.
pub fn validate_blocklist_zone(zone: &str) -> Result<String> {
    let zone = zone.trim().trim_end_matches('.').to_ascii_lowercase();
    if zone.is_empty() {
        return Err(Error::BaseUrl("a provider needs a zone".into()));
    }
    if zone.len() > 253 {
        return Err(Error::BaseUrl(format!(
            "a zone is at most 253 characters, and this is {}",
            zone.len()
        )));
    }
    let labels: Vec<&str> = zone.split('.').collect();
    if labels.len() < 2 {
        return Err(Error::BaseUrl(
            "a zone must be fully qualified, as zen.spamhaus.org".into(),
        ));
    }
    for label in labels {
        if label.is_empty() || label.len() > 63 {
            return Err(Error::BaseUrl(format!("{label:?} is not a usable label")));
        }
        if label.starts_with('-') || label.ends_with('-') {
            return Err(Error::BaseUrl(format!(
                "{label:?} may not start or end with a hyphen"
            )));
        }
        if !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            return Err(Error::BaseUrl(format!(
                "{label:?} must be alphanumeric with optional internal hyphens"
            )));
        }
    }
    Ok(zone)
}

/// Parses a typed refusal-code list — commas or spaces between entries — into the
/// normalized form the box stores.
///
/// Empty answers an empty list, which the box reads as its built-in set;
/// [`REFUSAL_CODES_NONE`] alone switches detection off and is refused alongside
/// real codes, because a list that both disables detection and names codes to
/// detect has no reading to pick.
///
/// Each entry is an IPv4 address or `address/prefix`, and a prefix is masked to
/// its network the way rolodex stores it, so what comes back from a later `GET`
/// matches what was submitted rather than looking like an edit.
pub fn parse_refusal_codes(input: &str) -> Result<Vec<String>> {
    let entries: Vec<&str> = input
        .split([',', ' ', '\t', '\n'])
        .map(str::trim)
        .filter(|e| !e.is_empty())
        .collect();

    if entries.is_empty() {
        return Ok(Vec::new());
    }
    if entries.iter().any(|e| e.eq_ignore_ascii_case(REFUSAL_CODES_NONE)) {
        if entries.len() == 1 {
            return Ok(vec![REFUSAL_CODES_NONE.into()]);
        }
        return Err(Error::BaseUrl(format!(
            "{REFUSAL_CODES_NONE:?} switches refusal detection off and must be the only entry"
        )));
    }

    let mut out: Vec<String> = Vec::with_capacity(entries.len());
    for entry in entries {
        let code = normalize_refusal_code(entry)?;
        if out.contains(&code) {
            return Err(Error::BaseUrl(format!("{code} appears twice")));
        }
        out.push(code);
    }
    Ok(out)
}

/// Normalizes one refusal code, masking a prefix to its network.
///
/// A `/32` renders bare because that is how rolodex renders it back; keeping the
/// suffix would make a code read back from `GET` differ from the one submitted.
fn normalize_refusal_code(code: &str) -> Result<String> {
    let bad = |what: &str| Error::BaseUrl(format!("refusal code {code:?} is invalid: {what}"));

    let (addr, bits) = match code.split_once('/') {
        Some((addr, prefix)) => {
            let bits: u32 = prefix
                .trim()
                .parse()
                .map_err(|_| bad("the prefix must be a number"))?;
            if bits > 32 {
                return Err(bad("the prefix must be between 0 and 32"));
            }
            (addr.trim(), bits)
        }
        None => (code.trim(), 32),
    };

    let octets: Vec<u8> = addr
        .split('.')
        .map(|o| o.parse::<u8>().ok())
        .collect::<Option<_>>()
        .ok_or_else(|| bad("expected an IPv4 address"))?;
    if octets.len() != 4 {
        return Err(bad("expected an IPv4 address"));
    }

    let value = u32::from_be_bytes([octets[0], octets[1], octets[2], octets[3]]);
    // A /0 mask is the whole shift-by-32 edge case, which would be UB-ish
    // wrapping rather than zero.
    let mask = if bits == 0 { 0 } else { u32::MAX << (32 - bits) };
    let masked = value & mask;
    let [a, b, c, d] = masked.to_be_bytes();

    Ok(if bits == 32 {
        format!("{a}.{b}.{c}.{d}")
    } else {
        format!("{a}.{b}.{c}.{d}/{bits}")
    })
}

/// A provider currently out of the rotation because it refused a query.
#[derive(Debug, Clone, Deserialize)]
pub struct RotatedOut {
    #[serde(default)]
    pub zone: String,
    #[serde(default)]
    pub code: String,
    #[serde(default)]
    pub seconds_remaining: u64,
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct BlocklistConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub providers: Vec<BlocklistProvider>,
    #[serde(default)]
    pub refusal_cooldown_secs: u64,
    #[serde(default)]
    pub rotated_out: Vec<RotatedOut>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct BlocklistEntry {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub reason: String,
}

/// Which of the two blocklists a call addresses.
///
/// They are the same shape with independent state: the RBL matches addresses,
/// the DNSBL matches names. One enum keeps the six endpoint pairs from becoming
/// twelve near-identical methods.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Blocklist {
    /// Reverse-IP blocklist.
    Rbl,
    /// Domain blocklist.
    Dnsbl,
}

impl Blocklist {
    fn path(self) -> &'static str {
        match self {
            Blocklist::Rbl => "/dns/rbl",
            Blocklist::Dnsbl => "/dns/dnsbl",
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Blocklist::Rbl => "Address blocklist (RBL)",
            Blocklist::Dnsbl => "Domain blocklist (DNSBL)",
        }
    }
}

impl Client {
    /// Calls `GET /dns/status`.
    pub async fn dns_status(&self) -> Result<DnsStatus> {
        self.get_json("/dns/status").await
    }

    /// Lists records, optionally confined to one TLD.
    ///
    /// With no TLD this spans every network — the global home zone plus each
    /// network's scoped zone — and each row says which it came from.
    ///
    /// Calls `GET /dns/records`.
    pub async fn dns_records(&self, tld: Option<&str>) -> Result<Vec<DnsRecord>> {
        let path = match tld.filter(|t| !t.is_empty()) {
            Some(tld) => format!("/dns/records?tld={}", urlencode(tld)),
            None => "/dns/records".into(),
        };
        self.get_json(&path).await
    }

    /// Calls `POST /dns/records/add` (admin).
    pub async fn add_dns_record(
        &self,
        name: &str,
        record_type: RecordType,
        value: &str,
        ttl: u32,
    ) -> Result<()> {
        self.post_empty(
            "/dns/records/add",
            &serde_json::json!({
                "name": name,
                "record_type": record_type.0,
                "value": value,
                "ttl": ttl,
            }),
        )
        .await
    }

    /// Calls `POST /dns/records/remove` (admin).
    pub async fn remove_dns_record(&self, name: &str, record_type: RecordType) -> Result<()> {
        self.post_empty(
            "/dns/records/remove",
            &serde_json::json!({ "name": name, "record_type": record_type.0 }),
        )
        .await
    }

    /// Calls `GET /dns/tld`.
    pub async fn dns_tld(&self) -> Result<String> {
        #[derive(Deserialize)]
        struct Tld {
            #[serde(default)]
            tld: String,
        }
        let out: Tld = self.get_json("/dns/tld").await?;
        Ok(out.tld)
    }

    /// Calls `POST /dns/tld` (admin).
    pub async fn set_dns_tld(&self, tld: &str) -> Result<()> {
        self.post_empty("/dns/tld", &serde_json::json!({ "tld": tld })).await
    }

    /// Idempotent zone init plus package registration. Calls `POST /dns/setup`.
    pub async fn setup_dns(&self) -> Result<()> {
        self.post_empty("/dns/setup", &serde_json::json!({})).await
    }

    /// Calls `GET /dns/services`.
    pub async fn dns_services(&self) -> Result<Vec<DnsService>> {
        self.get_json("/dns/services").await
    }

    /// Publishes or withdraws a package service in the zone.
    ///
    /// Calls `POST /dns/services/set` (admin).
    pub async fn set_dns_service(&self, repo: &str, name: &str, published: bool) -> Result<()> {
        self.post_empty(
            "/dns/services/set",
            &serde_json::json!({ "repo": repo, "name": name, "published": published }),
        )
        .await
    }

    /// Calls `GET /dns/rbl` or `GET /dns/dnsbl`.
    pub async fn blocklist_config(&self, which: Blocklist) -> Result<BlocklistConfig> {
        self.get_json(which.path()).await
    }

    /// Replaces a blocklist's configuration wholesale.
    ///
    /// Calls `POST /dns/rbl` or `POST /dns/dnsbl` (admin).
    pub async fn set_blocklist_config(
        &self,
        which: Blocklist,
        enabled: bool,
        providers: &[BlocklistProvider],
        refusal_cooldown_secs: u64,
    ) -> Result<()> {
        self.post_empty(
            which.path(),
            &serde_json::json!({
                "enabled": enabled,
                "providers": providers,
                "refusal_cooldown_secs": refusal_cooldown_secs,
            }),
        )
        .await
    }

    /// Calls `GET /dns/rbl/local`.
    pub async fn local_rbl(&self) -> Result<Vec<BlocklistEntry>> {
        self.get_json("/dns/rbl/local").await
    }

    /// Calls `POST /dns/rbl/local/add` (admin).
    pub async fn add_local_rbl(&self, name: &str, reason: &str) -> Result<()> {
        self.post_empty(
            "/dns/rbl/local/add",
            &serde_json::json!({ "name": name, "reason": reason }),
        )
        .await
    }

    /// Calls `POST /dns/rbl/local/remove` (admin).
    pub async fn remove_local_rbl(&self, name: &str) -> Result<()> {
        self.post_empty("/dns/rbl/local/remove", &serde_json::json!({ "name": name }))
            .await
    }

    /// Names exempted from the name-based block, along with everything beneath
    /// them. Calls `GET /dns/dnsbl/allowlist`.
    pub async fn dnsbl_allowlist(&self) -> Result<Vec<BlocklistEntry>> {
        self.get_json("/dns/dnsbl/allowlist").await
    }

    /// Calls `POST /dns/dnsbl/allowlist/add` (admin).
    pub async fn add_dnsbl_allowlist(&self, name: &str, reason: &str) -> Result<()> {
        self.post_empty(
            "/dns/dnsbl/allowlist/add",
            &serde_json::json!({ "name": name, "reason": reason }),
        )
        .await
    }

    /// Calls `POST /dns/dnsbl/allowlist/remove` (admin).
    pub async fn remove_dnsbl_allowlist(&self, name: &str) -> Result<()> {
        self.post_empty(
            "/dns/dnsbl/allowlist/remove",
            &serde_json::json!({ "name": name }),
        )
        .await
    }
}

/// Percent-encodes a query parameter value.
///
/// Only the characters that would change how the query parses are escaped; a
/// TLD is a hostname, so this is a narrow job and pulling in a dependency for it
/// would be the larger cost.
fn urlencode(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char)
            }
            other => out.push_str(&format!("%{other:02X}")),
        }
    }
    out
}

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

    #[test]
    fn unknown_record_types_stay_legible() {
        assert_eq!(RecordType::A.name(), "A");
        assert_eq!(RecordType(42).name(), "TYPE42");
    }

    #[test]
    fn only_mx_and_srv_carry_priority() {
        assert!(RecordType::MX.uses_priority());
        assert!(RecordType::SRV.uses_priority());
        assert!(!RecordType::A.uses_priority());
        assert!(!RecordType::TXT.uses_priority());
    }

    #[test]
    fn query_values_are_escaped() {
        assert_eq!(urlencode("home.town"), "home.town");
        assert_eq!(urlencode("a b&c=d"), "a%20b%26c%3Dd");
    }

    #[test]
    fn provider_zones_are_normalised_not_just_accepted() {
        assert_eq!(validate_blocklist_zone(" ZEN.Spamhaus.ORG. ").unwrap(), "zen.spamhaus.org");
        assert_eq!(validate_blocklist_zone("dbl.spamhaus.org").unwrap(), "dbl.spamhaus.org");
    }

    #[test]
    fn a_single_label_is_never_a_dnsxl() {
        let err = validate_blocklist_zone("spamhaus").unwrap_err().detail();
        assert!(err.contains("fully qualified"), "{err}");
        assert!(validate_blocklist_zone("").is_err());
        assert!(validate_blocklist_zone("a..b").is_err());
        assert!(validate_blocklist_zone("-bad.example.org").is_err());
        assert!(validate_blocklist_zone("bad_label.example.org").is_err());
    }

    #[test]
    fn an_empty_refusal_list_means_the_built_in_set() {
        assert!(parse_refusal_codes("").unwrap().is_empty());
        assert!(parse_refusal_codes("  ,  ").unwrap().is_empty());
    }

    #[test]
    fn none_switches_detection_off_and_stands_alone() {
        assert_eq!(parse_refusal_codes("none").unwrap(), vec!["none".to_string()]);
        assert_eq!(parse_refusal_codes(" NONE ").unwrap(), vec!["none".to_string()]);

        let err = parse_refusal_codes("none, 127.0.0.2").unwrap_err().detail();
        assert!(err.contains("only entry"), "{err}");
    }

    #[test]
    fn codes_are_separated_by_commas_or_spaces() {
        let expected = vec!["127.255.255.254".to_string(), "127.255.255.255".to_string()];
        assert_eq!(
            parse_refusal_codes("127.255.255.254, 127.255.255.255").unwrap(),
            expected
        );
        assert_eq!(
            parse_refusal_codes("127.255.255.254 127.255.255.255").unwrap(),
            expected
        );
    }

    #[test]
    fn a_prefix_is_masked_to_its_network_and_a_32_renders_bare() {
        // Spamhaus reserves the whole of 127.255.255.0/24 for errors, so an
        // operator writes the range and it has to read back unchanged.
        assert_eq!(
            parse_refusal_codes("127.255.255.9/24").unwrap(),
            vec!["127.255.255.0/24".to_string()]
        );
        assert_eq!(
            parse_refusal_codes("127.0.0.2/32").unwrap(),
            vec!["127.0.0.2".to_string()]
        );
        assert_eq!(parse_refusal_codes("10.1.2.3/0").unwrap(), vec!["0.0.0.0/0".to_string()]);
    }

    #[test]
    fn duplicate_and_malformed_codes_are_refused() {
        // The two spellings mask to the same code, which the box calls a duplicate.
        let err = parse_refusal_codes("127.255.255.0/24, 127.255.255.9/24")
            .unwrap_err()
            .detail();
        assert!(err.contains("twice"), "{err}");

        assert!(parse_refusal_codes("127.0.0.2/33").is_err());
        assert!(parse_refusal_codes("127.0.0.2/nine").is_err());
        assert!(parse_refusal_codes("not-an-address").is_err());
        assert!(parse_refusal_codes("127.0.0").is_err());
        assert!(parse_refusal_codes("127.0.0.256").is_err());
        assert!(parse_refusal_codes("::1").is_err());
    }

    #[test]
    fn providers_omit_empty_optional_fields() {
        let p = BlocklistProvider {
            zone: "zen.example".into(),
            enabled: true,
            ..Default::default()
        };
        let json = serde_json::to_string(&p).unwrap();
        assert_eq!(json, r#"{"zone":"zen.example","enabled":true}"#);
    }
}