grindvakt-core 1.3.0

The Grindvakt dynamic DNS engine as a library: keep A, AAAA, TXT (including libp2p _dnsaddr) and CNAME records current on DNSimple or DigitalOcean. Separate IPv4/IPv6 discovery that reports when there is no global address, a plan/apply split with dry runs, a provider trait and typed errors. Caller-owned secrets and paths, no CLI, no prompts, no scheduler. Optional encrypted token vault.
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
//! Provider names, record-name helpers, and (feature `standalone`) the Grindvakt app's own
//! config file.
//!
//! [`AppConfig`] is the TOML that the standalone Grindvakt app writes to `config.toml`.
//! Embedding apps normally keep their own settings and call [`crate::plan()`] directly; the
//! type is here so the Grindvakt app and tools that read its files (such as
//! [`crate::standalone::find_conflicts`]) agree on the format:
//!
//! ```toml
//! provider = "dnsimple"
//! account_id = 1234
//! zone = "example.net"
//! name = "home"
//! ttl = 300
//! sandbox = false
//!
//! [schedule]
//! interval_secs = 300
//! ```
//!
//! The record is an `A` record by default. `record = "cname"` makes it a `CNAME` instead, with
//! its content from a `[cname]` table: exactly one of `target` (a host name) or
//! `weirdnet_link` (a `weirdnet-<app>://<name>/<path>` link whose name becomes the target,
//! needs feature `weirdnet`):
//!
//! ```toml
//! provider = "digitalocean"
//! zone = "example.net"
//! name = "www"
//! record = "cname"
//!
//! [cname]
//! weirdnet_link = "weirdnet-morph://home.example.com/site"
//! ```

#[cfg(feature = "standalone")]
use crate::error::IoContext;
use crate::error::{Error, Result};
#[cfg(feature = "standalone")]
use crate::fs::{Privacy, atomic_write_private_with};
pub use crate::record::{DEFAULT_TTL, MIN_TTL};
use serde::{Deserialize, Serialize};
use std::fmt;
#[cfg(feature = "standalone")]
use std::path::Path;
use std::str::FromStr;

/// File name the Grindvakt app uses for the config inside its data directory.
#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
pub const CONFIG_FILE_NAME: &str = "config.toml";

/// A supported DNS provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Provider {
    /// DNSimple (<https://dnsimple.com>).
    #[default]
    Dnsimple,
    /// DigitalOcean DNS (<https://www.digitalocean.com>).
    Digitalocean,
}

impl Provider {
    /// Every provider, in a stable order.
    pub const ALL: [Provider; 2] = [Provider::Dnsimple, Provider::Digitalocean];

    /// The lowercase name used in config files and on the command line.
    pub fn as_str(self) -> &'static str {
        match self {
            Provider::Dnsimple => "dnsimple",
            Provider::Digitalocean => "digitalocean",
        }
    }
}

impl fmt::Display for Provider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for Provider {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "dnsimple" => Ok(Provider::Dnsimple),
            "digitalocean" => Ok(Provider::Digitalocean),
            other => Err(Error::Config(format!(
                "unsupported provider {other:?}; choose dnsimple or digitalocean"
            ))),
        }
    }
}

#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
/// When the standalone app runs: a calendar expression or a fixed interval. This crate only
/// stores it; it has no scheduler.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Schedule {
    /// A systemd `OnCalendar` expression (interpreted by the Grindvakt app, not this crate).
    #[serde(default)]
    pub calendar: Option<String>,
    /// Polling interval in seconds (at least 60).
    #[serde(default)]
    pub interval_secs: Option<u64>,
}

#[cfg(feature = "standalone")]
impl Default for Schedule {
    fn default() -> Self {
        Self {
            calendar: None,
            interval_secs: Some(300),
        }
    }
}

#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
/// Which kind of record the standalone app keeps current.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum RecordType {
    /// An `A` record holding this machine's public IPv4 address.
    #[default]
    A,
    /// A `CNAME` record whose content comes from [`AppConfig::cname`].
    Cname,
}

#[cfg(feature = "standalone")]
impl RecordType {
    /// The lowercase name used in config files and on the command line.
    pub fn as_str(self) -> &'static str {
        match self {
            RecordType::A => "a",
            RecordType::Cname => "cname",
        }
    }
}

#[cfg(feature = "standalone")]
impl fmt::Display for RecordType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(feature = "standalone")]
impl FromStr for RecordType {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "a" => Ok(RecordType::A),
            "cname" => Ok(RecordType::Cname),
            other => Err(Error::Config(format!(
                "unsupported record type {other:?}; choose a or cname"
            ))),
        }
    }
}

#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
/// The `[cname]` table: where a `CNAME` record's content comes from. Set exactly one field.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CnameConfig {
    /// A full host name to point at, such as `home.example.com`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    /// A Weirdnet resource link, `weirdnet-<app>://<name>/<path>`; the name is the target.
    /// Needs feature `weirdnet`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub weirdnet_link: Option<String>,
}

#[cfg(feature = "standalone")]
impl CnameConfig {
    /// The content source, or an [`Error::Config`] unless exactly one field is set.
    pub fn source(&self) -> Result<crate::cname::CnameSource> {
        match (&self.target, &self.weirdnet_link) {
            (Some(t), None) => Ok(crate::cname::CnameSource::Target(t.clone())),
            (None, Some(l)) => Ok(crate::cname::CnameSource::WeirdnetLink(l.clone())),
            (None, None) => Err(Error::Config(
                "[cname] needs one of target or weirdnet_link".into(),
            )),
            (Some(_), Some(_)) => Err(Error::Config(
                "[cname] takes either target or weirdnet_link, not both".into(),
            )),
        }
    }
}

#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
/// The standalone Grindvakt app's configuration (`config.toml`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppConfig {
    /// Active DNS provider.
    #[serde(default)]
    pub provider: Provider,
    /// DNSimple account id. When unset, DNSimple's `whoami` supplies it.
    #[serde(default)]
    pub account_id: Option<u64>,
    /// DNS zone, for example `example.com`.
    pub zone: String,
    /// Record name: `@` for the apex, a relative label such as `www`, or a full name.
    pub name: String,
    /// The kind of record to keep: `a` (the default) or `cname`.
    #[serde(default, skip_serializing_if = "is_default_record")]
    pub record: RecordType,
    /// Content of the `CNAME` record; required for, and only allowed with, `record = "cname"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cname: Option<CnameConfig>,
    /// TTL in seconds (at least [`MIN_TTL`]).
    #[serde(default = "default_ttl")]
    pub ttl: u32,
    /// Use the DNSimple sandbox API.
    #[serde(default)]
    pub sandbox: bool,
    /// Override the provider API base URL (tests and mocks).
    #[serde(default)]
    pub api_base_url: Option<String>,
    /// When to run.
    #[serde(default)]
    pub schedule: Schedule,
}

#[cfg(feature = "standalone")]
fn is_default_record(r: &RecordType) -> bool {
    *r == RecordType::A
}

#[cfg(feature = "standalone")]
fn default_ttl() -> u32 {
    DEFAULT_TTL
}

#[cfg(feature = "standalone")]
impl Default for AppConfig {
    fn default() -> Self {
        Self {
            provider: Provider::default(),
            account_id: None,
            zone: "example.com".to_string(),
            name: "@".to_string(),
            record: RecordType::A,
            cname: None,
            ttl: DEFAULT_TTL,
            sandbox: false,
            api_base_url: None,
            schedule: Schedule::default(),
        }
    }
}

#[cfg(feature = "standalone")]
impl AppConfig {
    /// Checks TTL, zone, name, and that a schedule is set with an interval of at least 60 s.
    /// (Calendar expressions are checked by the app that runs them.)
    pub fn validate(&self) -> Result<()> {
        if self.ttl < MIN_TTL {
            return Err(Error::Config(format!("ttl must be >= {MIN_TTL}")));
        }
        if self.zone.trim().is_empty() {
            return Err(Error::Config("zone must be set".into()));
        }
        if self.name.trim().is_empty() {
            return Err(Error::Config("name must be set".into()));
        }
        if self.schedule.calendar.is_none() && self.schedule.interval_secs.is_none() {
            return Err(Error::Config(
                "schedule must set either calendar or interval_secs".into(),
            ));
        }
        if !crate::record::is_valid_name(&self.zone, &self.name) {
            return Err(Error::Config(format!(
                "{:?} is not a valid record name",
                self.name
            )));
        }
        match (self.record, &self.cname) {
            (RecordType::A, Some(_)) => {
                return Err(Error::Config(
                    "[cname] is only used with record = \"cname\"".into(),
                ));
            }
            (RecordType::A, None) => {}
            (RecordType::Cname, None) => {
                return Err(Error::Config(
                    "record = \"cname\" needs a [cname] table with target or weirdnet_link".into(),
                ));
            }
            (RecordType::Cname, Some(c)) => {
                if self
                    .record_fqdn()
                    .eq_ignore_ascii_case(self.zone.trim_end_matches('.'))
                {
                    return Err(Error::Config(
                        "a CNAME cannot be at the zone apex; set a name such as www".into(),
                    ));
                }
                c.source()?
                    .target()
                    .map_err(|e| Error::Config(e.to_string()))?;
            }
        }
        Ok(())
    }

    /// The record's fully qualified name, without a trailing dot.
    pub fn record_fqdn(&self) -> String {
        normalize_fqdn(&self.zone, &self.name)
    }

    /// Parses and validates TOML.
    pub fn from_toml_str(text: &str) -> Result<Self> {
        let cfg: AppConfig = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?;
        cfg.validate()?;
        Ok(cfg)
    }

    /// Serializes to the same pretty TOML the Grindvakt app writes.
    pub fn to_toml_string(&self) -> Result<String> {
        toml::to_string_pretty(self).map_err(|e| Error::Config(e.to_string()))
    }

    /// Reads, parses and validates a config file.
    pub fn load(path: &Path) -> Result<Self> {
        let text = std::fs::read_to_string(path).ctx(|| format!("reading {}", path.display()))?;
        Self::from_toml_str(&text)
            .map_err(|e| Error::Config(format!("parsing {}: {e}", path.display())))
    }

    /// Writes the config atomically, private to the current user
    /// (see [`crate::fs::atomic_write_private`]).
    pub fn save(&self, path: &Path) -> Result<()> {
        self.save_with(path, Privacy::CurrentUser)
    }

    /// [`AppConfig::save`] under an explicit [`Privacy`] policy, such as
    /// [`Privacy::Service`] for data a system service reads.
    pub fn save_with(&self, path: &Path, privacy: Privacy) -> Result<()> {
        let text = self.to_toml_string()?;
        atomic_write_private_with(path, text.as_bytes(), privacy)
    }
}

/// Joins a zone and a record name into one name without a trailing dot.
///
/// ```
/// use grindvakt_core::config::normalize_fqdn;
/// assert_eq!(normalize_fqdn("example.com", "@"), "example.com");
/// assert_eq!(normalize_fqdn("example.com.", "www"), "www.example.com");
/// assert_eq!(normalize_fqdn("example.com", "api.example.com."), "api.example.com");
/// ```
pub fn normalize_fqdn(zone: &str, name: &str) -> String {
    let z = zone.trim_end_matches('.').to_string();
    let n = name.trim().trim_end_matches('.');
    if n == "@" || n.is_empty() || n.eq_ignore_ascii_case(&z) {
        z
    } else if ends_with_zone(n, &z) {
        n.to_string()
    } else {
        format!("{}.", n) + &z
    }
}

/// The record name relative to its zone: `""` for the apex (DNSimple's convention).
///
/// ```
/// use grindvakt_core::config::relative_name;
/// assert_eq!(relative_name("example.com", "@"), "");
/// assert_eq!(relative_name("example.com", "home.example.com"), "home");
/// assert_eq!(relative_name("example.com", "www"), "www");
/// assert_eq!(relative_name("example.com", "notexample.com"), "notexample.com");
/// ```
pub fn relative_name(zone: &str, name: &str) -> String {
    let zone = zone.trim_end_matches('.').to_string();
    let name = name.trim().trim_end_matches('.');
    if name == "@" || name.is_empty() || name.eq_ignore_ascii_case(&zone) {
        String::new()
    } else if ends_with_zone(name, &zone) {
        name[..name.len() - zone.len() - 1].to_string()
    } else {
        name.to_string()
    }
}

/// `name` is `<something>.<zone>` (case-insensitive), not merely ending in the same letters.
fn ends_with_zone(name: &str, zone: &str) -> bool {
    name.len() > zone.len() + 1
        && name.is_char_boundary(name.len() - zone.len())
        && name.as_bytes()[name.len() - zone.len() - 1] == b'.'
        && name[name.len() - zone.len()..].eq_ignore_ascii_case(zone)
}

/// Input checks for domains and record names.
pub mod validate {
    use regex::Regex;
    use std::sync::LazyLock;

    static FQDN: LazyLock<Regex> = LazyLock::new(|| {
        let label = r"(?i)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])";
        Regex::new(&format!("^({label}\\.)+[a-z{{2,}}A-Z{{2,}}]+$")).expect("static regex")
    });
    static LABEL: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?i)^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])$").expect("static regex")
    });

    /// A domain such as `example.com` (labels of letters, digits and hyphens; a dot needed).
    ///
    /// ```
    /// use grindvakt_core::config::validate::is_valid_fqdn;
    /// assert!(is_valid_fqdn("api.example.co.uk"));
    /// assert!(!is_valid_fqdn("bad_underscore.example.com"));
    /// ```
    pub fn is_valid_fqdn(s: &str) -> bool {
        FQDN.is_match(s.trim_end_matches('.'))
    }

    /// One DNS label of two or more characters.
    pub fn is_valid_label(label: &str) -> bool {
        LABEL.is_match(label)
    }

    /// `@`, relative labels such as `www` or `home.office`, or a full name inside `zone`.
    /// Stricter than [`crate::record::is_valid_name`] (no `_`, labels of two or more
    /// characters); kept for the Grindvakt app's interactive setup.
    pub fn is_valid_record_name(zone: &str, name: &str) -> bool {
        let n = name.trim();
        if n == "@" {
            return true;
        }
        if n.split('.')
            .all(|lbl| !lbl.is_empty() && is_valid_label(lbl))
        {
            return true;
        }
        is_valid_fqdn(n) && n.ends_with(zone.trim_end_matches('.'))
    }
}