1133 lines
40 KiB
Rust
1133 lines
40 KiB
Rust
//! EasyDNS configuration: schema, loading (YAML/JSON), ENV overrides and validation.
|
||
//!
|
||
//! Precedence: CLI > ENV > config file > defaults. CLI overrides are applied by the
|
||
//! binaries through [`Config::apply_overrides`]; ENV overrides by [`Config::apply_env`].
|
||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||
|
||
use std::net::SocketAddr;
|
||
use std::path::{Path, PathBuf};
|
||
use std::time::Duration;
|
||
|
||
use ipnet::IpNet;
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
mod bindconf;
|
||
pub mod duration;
|
||
mod include;
|
||
pub mod update_policy;
|
||
pub mod upstream;
|
||
mod validate;
|
||
|
||
pub use validate::{ConfigError, ValidationIssue};
|
||
|
||
/// Root configuration document.
|
||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct Config {
|
||
/// Additional files with zone definitions (and keys, ACLs, forward zones), like BIND's
|
||
/// `include "named.conf.zones";`. Paths and `*`/`?` globs in the last path component,
|
||
/// relative to this file's directory, e.g. `["zones.d/*.yaml"]`.
|
||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||
pub include: Vec<String>,
|
||
pub server: ServerConfig,
|
||
pub logging: LoggingConfig,
|
||
/// Named TSIG keys (`keys:` in BIND).
|
||
pub keys: Vec<KeyConfig>,
|
||
/// Named address match lists that can be referenced as `acl:<name>`.
|
||
pub acls: std::collections::BTreeMap<String, Vec<String>>,
|
||
pub recursion: RecursionConfig,
|
||
pub zones: Vec<ZoneConfig>,
|
||
pub forward_zones: Vec<ForwardZoneConfig>,
|
||
pub upstreams: UpstreamsConfig,
|
||
pub resolution: ResolutionConfig,
|
||
pub cache: CacheConfig,
|
||
pub policy: PolicyConfig,
|
||
/// Names answered from hosts files (`/etc/hosts` format) before anything else, like dnsmasq.
|
||
pub hosts: HostsConfig,
|
||
pub rate_limit: RateLimitConfig,
|
||
pub tls: TlsConfig,
|
||
pub api: ApiConfig,
|
||
pub metrics: MetricsConfig,
|
||
}
|
||
|
||
/// Declared operating mode. Roles are actually defined by zones/recursion/upstreams;
|
||
/// the mode is validated against them so mistakes are caught early.
|
||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||
#[serde(rename_all = "kebab-case")]
|
||
pub enum Mode {
|
||
#[serde(alias = "master")]
|
||
Primary,
|
||
#[serde(alias = "slave")]
|
||
Secondary,
|
||
#[serde(alias = "resolver")]
|
||
Recursive,
|
||
Forwarder,
|
||
#[default]
|
||
#[serde(alias = "mixed")]
|
||
Hybrid,
|
||
CacheOnly,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct ServerConfig {
|
||
pub mode: Mode,
|
||
pub listen: Vec<SocketAddr>,
|
||
pub udp: bool,
|
||
pub tcp: bool,
|
||
/// Directory for persistent state (secondary snapshots, IXFR journals, audit log).
|
||
pub data_dir: PathBuf,
|
||
pub max_tcp_connections: usize,
|
||
#[serde(with = "duration")]
|
||
pub tcp_idle_timeout: Duration,
|
||
/// Largest UDP response we send (EDNS). 1232 avoids IP fragmentation.
|
||
pub max_udp_payload: u16,
|
||
/// Max in-flight queries handled concurrently (backpressure).
|
||
pub max_inflight: usize,
|
||
/// UDP sockets per listen address, bound with SO_REUSEPORT so the kernel spreads
|
||
/// queries over them and each gets its own receive loop. 0 = one per CPU (max 16).
|
||
/// Platforms without SO_REUSEPORT fall back to one socket.
|
||
pub udp_sockets: usize,
|
||
/// Base directory used to resolve relative paths (defaults to the config file's dir).
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
pub base_dir: Option<PathBuf>,
|
||
/// NSID / version.bind answers are disabled unless set.
|
||
pub identity: Option<String>,
|
||
}
|
||
|
||
impl Default for ServerConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
mode: Mode::Hybrid,
|
||
// IPv4 on all interfaces, IPv6 loopback; recursion is limited by `recursion.allowed_clients`
|
||
listen: vec![SocketAddr::from(([0, 0, 0, 0], 53)), SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, 53))],
|
||
udp: true,
|
||
tcp: true,
|
||
data_dir: PathBuf::from("data"),
|
||
max_tcp_connections: 1024,
|
||
tcp_idle_timeout: Duration::from_secs(10),
|
||
max_udp_payload: 1232,
|
||
max_inflight: 10_000,
|
||
udp_sockets: 0,
|
||
base_dir: None,
|
||
identity: None,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||
#[serde(rename_all = "lowercase")]
|
||
pub enum LogFormat {
|
||
#[default]
|
||
Text,
|
||
Json,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct LoggingConfig {
|
||
pub level: String,
|
||
pub format: LogFormat,
|
||
/// Per-query logging (off by default – privacy).
|
||
pub query_log: bool,
|
||
/// Mask client IPs in query logs (/24 and /48).
|
||
pub anonymize_clients: bool,
|
||
}
|
||
|
||
impl Default for LoggingConfig {
|
||
fn default() -> Self {
|
||
Self { level: "info".into(), format: LogFormat::Text, query_log: false, anonymize_clients: true }
|
||
}
|
||
}
|
||
|
||
/// A TSIG key. `secret` is a reference: `env:VAR`, `file:/path` or `base64:...`.
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct KeyConfig {
|
||
pub name: String,
|
||
#[serde(default = "default_tsig_alg")]
|
||
pub algorithm: String,
|
||
pub secret: String,
|
||
/// Set when the key was read from a BIND-format key file (`include: [keys.conf]`).
|
||
#[serde(skip)]
|
||
pub imported_from: Option<String>,
|
||
}
|
||
|
||
fn default_tsig_alg() -> String {
|
||
"hmac-sha256".into()
|
||
}
|
||
|
||
/// Remove `.` and resolve `..` components without touching the file system.
|
||
fn normalize(p: &Path) -> PathBuf {
|
||
use std::path::Component;
|
||
let mut out = PathBuf::new();
|
||
for c in p.components() {
|
||
match c {
|
||
Component::CurDir => {}
|
||
Component::ParentDir => {
|
||
if !out.pop() {
|
||
out.push("..");
|
||
}
|
||
}
|
||
other => out.push(other.as_os_str()),
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
/// File name of the local control token inside `data_dir`.
|
||
pub const CONTROL_TOKEN_FILE: &str = "control.token";
|
||
|
||
/// Default recursion clients: the usual home/office LAN ranges and loopback.
|
||
/// (172.16.0.0/12 is not included; add it to `acls.lan` if your network uses it.)
|
||
pub const DEFAULT_LAN: &[&str] = &["192.168.0.0/16", "10.0.0.0/8", "127.0.0.1/32", "::1/128"];
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct RecursionConfig {
|
||
pub enabled: bool,
|
||
pub root_hints: Option<PathBuf>,
|
||
/// Clients allowed to use recursion/forwarding (default: private LAN ranges + loopback,
|
||
/// see [`DEFAULT_LAN`]).
|
||
pub allowed_clients: Vec<String>,
|
||
pub qname_minimization: bool,
|
||
pub dnssec_validation: bool,
|
||
/// Trust anchor file (DS or DNSKEY records, zone-file format). Built-in root KSK used if unset.
|
||
pub trust_anchors: Option<PathBuf>,
|
||
pub max_depth: u32,
|
||
pub max_queries: u32,
|
||
pub max_cname_chain: u32,
|
||
#[serde(with = "duration")]
|
||
pub query_timeout: Duration,
|
||
#[serde(with = "duration")]
|
||
pub total_timeout: Duration,
|
||
/// Port used to reach authoritative servers (53; changeable only for test fixtures).
|
||
pub authority_port: u16,
|
||
/// Never send queries for these suffixes to the Internet (RFC 6761/6303 + private).
|
||
pub local_only_suffixes: Vec<String>,
|
||
pub use_ipv6_transport: bool,
|
||
}
|
||
|
||
impl Default for RecursionConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
enabled: false,
|
||
root_hints: None,
|
||
allowed_clients: DEFAULT_LAN.iter().map(|s| (*s).to_string()).collect(),
|
||
qname_minimization: true,
|
||
dnssec_validation: false,
|
||
trust_anchors: None,
|
||
max_depth: 30,
|
||
max_queries: 100,
|
||
max_cname_chain: 8,
|
||
query_timeout: Duration::from_millis(1500),
|
||
total_timeout: Duration::from_secs(10),
|
||
authority_port: 53,
|
||
local_only_suffixes: Vec::new(),
|
||
use_ipv6_transport: false,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||
#[serde(rename_all = "lowercase")]
|
||
pub enum ZoneType {
|
||
#[serde(alias = "master")]
|
||
Primary,
|
||
#[serde(alias = "slave")]
|
||
Secondary,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||
#[serde(rename_all = "lowercase")]
|
||
pub enum TransferPreference {
|
||
#[default]
|
||
Ixfr,
|
||
Axfr,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct TransferClientConfig {
|
||
pub prefer: TransferPreference,
|
||
pub fallback_axfr: bool,
|
||
/// Name of a key from `keys:` used to sign SOA/IXFR/AXFR requests.
|
||
pub tsig_key: Option<String>,
|
||
#[serde(with = "duration")]
|
||
pub timeout: Duration,
|
||
pub max_records: usize,
|
||
}
|
||
|
||
impl Default for TransferClientConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
prefer: TransferPreference::Ixfr,
|
||
fallback_axfr: true,
|
||
tsig_key: None,
|
||
timeout: Duration::from_secs(120),
|
||
max_records: 2_000_000,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct ZoneConfig {
|
||
/// File this zone was defined in (set by the loader, for error messages).
|
||
#[serde(skip)]
|
||
pub source: Option<String>,
|
||
pub name: String,
|
||
#[serde(rename = "type")]
|
||
pub zone_type: ZoneType,
|
||
/// Zone file. A relative path is relative to `server.data_dir` (e.g. `zones/primary/example.com.zone`
|
||
/// = `<data_dir>/zones/primary/example.com.zone`). Primary: required. Secondary: optional; defaults to
|
||
/// `<data_dir>/zones/secondary/<zone>.zone`.
|
||
#[serde(default)]
|
||
pub file: Option<PathBuf>,
|
||
/// Clients allowed to AXFR/IXFR this zone (default: nobody).
|
||
#[serde(default)]
|
||
pub transfer_acl: Vec<String>,
|
||
/// Require this TSIG key for transfers (in addition to `transfer_acl`).
|
||
#[serde(default)]
|
||
pub transfer_tsig_key: Option<String>,
|
||
/// Secondaries to NOTIFY after a change (primary only).
|
||
#[serde(default)]
|
||
pub notify: Vec<SocketAddr>,
|
||
/// Key used to sign outgoing NOTIFY (primary).
|
||
#[serde(default)]
|
||
pub notify_tsig_key: Option<String>,
|
||
/// Primary servers to synchronise from (secondary only).
|
||
#[serde(default)]
|
||
pub primaries: Vec<SocketAddr>,
|
||
#[serde(default)]
|
||
pub transfer: TransferClientConfig,
|
||
/// Sources allowed to send NOTIFY (secondary). Defaults to the `primaries` addresses.
|
||
#[serde(default)]
|
||
pub allow_notify: Vec<String>,
|
||
/// RFC 2136 dynamic updates. Exactly one model is used, chosen by what is set:
|
||
/// * `update_policy` – per-record rules by TSIG key (BIND `update-policy`);
|
||
/// * `update_keys` – any of these keys may change the whole zone;
|
||
/// * only `update_acl` – unsigned updates from these addresses (BIND `allow-update { IPs; }`).
|
||
///
|
||
/// `update_acl`, when set together with keys or a policy, additionally restricts the
|
||
/// source addresses. Nothing set = updates refused.
|
||
#[serde(default)]
|
||
pub update_keys: Vec<String>,
|
||
/// Source addresses allowed to send updates (alias: `allow_update`).
|
||
#[serde(default, alias = "allow_update")]
|
||
pub update_acl: Vec<String>,
|
||
#[serde(default)]
|
||
pub update_policy: Vec<update_policy::UpdateRule>,
|
||
#[serde(default)]
|
||
pub serial_strategy: dns_core::serial::SerialStrategy,
|
||
/// Views (by name) in which this zone is visible; empty = all.
|
||
#[serde(default)]
|
||
pub views: Vec<String>,
|
||
/// Number of IXFR journal entries to keep.
|
||
#[serde(default = "default_journal")]
|
||
pub journal_size: usize,
|
||
/// Online DNSSEC signing (primary zones only).
|
||
#[serde(default)]
|
||
pub dnssec: Option<DnssecZoneConfig>,
|
||
}
|
||
|
||
/// DNSSEC signing settings for a primary zone.
|
||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct DnssecZoneConfig {
|
||
/// Directory with private keys (`<zone>.<tag>.<ksk|zsk|csk>.key`), mode 0700.
|
||
pub keys_dir: PathBuf,
|
||
pub algorithm: dns_core::dnssec::KeyAlgorithm,
|
||
/// Generate a combined signing key (CSK) when the directory holds none.
|
||
pub auto_generate: bool,
|
||
#[serde(with = "duration")]
|
||
pub signature_validity: Duration,
|
||
/// Re-sign when signatures expire sooner than this.
|
||
#[serde(with = "duration")]
|
||
pub resign_before: Duration,
|
||
}
|
||
|
||
impl Default for DnssecZoneConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
keys_dir: PathBuf::from("keys"),
|
||
algorithm: dns_core::dnssec::KeyAlgorithm::Ed25519,
|
||
auto_generate: true,
|
||
signature_validity: Duration::from_secs(14 * 86_400),
|
||
resign_before: Duration::from_secs(7 * 86_400),
|
||
}
|
||
}
|
||
}
|
||
|
||
fn default_journal() -> usize {
|
||
100
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||
#[serde(rename_all = "kebab-case")]
|
||
pub enum Strategy {
|
||
RoundRobin,
|
||
Fastest,
|
||
#[default]
|
||
Failover,
|
||
Random,
|
||
Priority,
|
||
}
|
||
|
||
/// An upstream address: `1.1.1.1:53`, `tcp://1.1.1.1:53`, `tls://1.1.1.1:853#cloudflare-dns.com`,
|
||
/// `https://dns.example/dns-query`.
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct ForwardZoneConfig {
|
||
pub domain: String,
|
||
pub upstreams: Vec<String>,
|
||
#[serde(default)]
|
||
pub strategy: Strategy,
|
||
/// Optional client networks this rule applies to (empty = all).
|
||
#[serde(default)]
|
||
pub clients: Vec<String>,
|
||
/// Fall back to local recursion if all upstreams fail.
|
||
#[serde(default)]
|
||
pub fallback_recursion: bool,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct UpstreamsConfig {
|
||
pub strategy: Strategy,
|
||
/// `IP[:port]` (UDP+TCP), `tcp://IP`, `tls://IP[:853]#name` (DoT), `https://IP/path#name` (DoH).
|
||
pub servers: Vec<String>,
|
||
/// Extra CA certificates (PEM) trusted for DoT/DoH upstreams, e.g. a private CA of an
|
||
/// internal resolver. Public resolvers need nothing: the Mozilla root store is built in.
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
pub tls_ca_file: Option<PathBuf>,
|
||
#[serde(with = "duration::option", skip_serializing_if = "Option::is_none")]
|
||
pub timeout: Option<Duration>,
|
||
#[serde(with = "duration::option", skip_serializing_if = "Option::is_none")]
|
||
pub health_check_interval: Option<Duration>,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||
#[serde(rename_all = "lowercase")]
|
||
pub enum DefaultResolution {
|
||
/// Iterative resolution from the root.
|
||
Recursive,
|
||
/// Send to `upstreams`.
|
||
Forward,
|
||
/// Forward first, fall back to recursion when all upstreams fail.
|
||
ForwardThenRecursive,
|
||
/// No resolution beyond local zones (authoritative-only).
|
||
#[default]
|
||
Refuse,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct ResolutionConfig {
|
||
pub default: DefaultResolution,
|
||
/// Split-horizon views, evaluated in order; first matching view wins.
|
||
pub views: Vec<ViewConfig>,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct ViewConfig {
|
||
pub name: String,
|
||
pub clients: Vec<String>,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct CacheConfig {
|
||
pub enabled: bool,
|
||
pub max_entries: usize,
|
||
pub min_ttl: u32,
|
||
pub max_ttl: u32,
|
||
pub max_negative_ttl: u32,
|
||
/// Serve expired data (RFC 8767) when upstreams fail. Off by default.
|
||
pub serve_stale: bool,
|
||
pub stale_ttl: u32,
|
||
/// Cache of complete encoded answers (packet cache) answering repeated queries without
|
||
/// parsing or lookup; 0 disables it. Bounded memory: about 0.3–1 KiB per entry.
|
||
pub answer_entries: usize,
|
||
/// How long an answer from a local zone is reused. Zone changes invalidate it at once;
|
||
/// this only bounds the age. Resolved answers use their TTL (max 60 s).
|
||
#[serde(with = "duration")]
|
||
pub answer_max_age: Duration,
|
||
/// Refresh popular entries in the background shortly before they expire.
|
||
pub prefetch: bool,
|
||
}
|
||
|
||
impl Default for CacheConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
enabled: true,
|
||
max_entries: 100_000,
|
||
min_ttl: 0,
|
||
max_ttl: 86_400,
|
||
max_negative_ttl: 3_600,
|
||
serve_stale: false,
|
||
stale_ttl: 30,
|
||
answer_entries: 20_000,
|
||
answer_max_age: Duration::from_secs(30),
|
||
prefetch: true,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||
#[serde(rename_all = "lowercase")]
|
||
pub enum BlockAction {
|
||
#[default]
|
||
Nxdomain,
|
||
Refused,
|
||
/// 0.0.0.0 / :: for A/AAAA, NODATA for other types.
|
||
Null,
|
||
/// Configured `block_address_v4/v6` for A/AAAA, NODATA otherwise.
|
||
Address,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct BlocklistConfig {
|
||
pub name: String,
|
||
/// Local file (hosts format or one domain per line, `*.` for wildcard, `/re/` regex).
|
||
#[serde(default)]
|
||
pub file: Option<PathBuf>,
|
||
/// Remote list URL (fetched by `easydns blocklists update`; cached to data_dir).
|
||
#[serde(default)]
|
||
pub url: Option<String>,
|
||
#[serde(default)]
|
||
pub category: Option<String>,
|
||
#[serde(default = "yes")]
|
||
pub enabled: bool,
|
||
}
|
||
|
||
fn yes() -> bool {
|
||
true
|
||
}
|
||
|
||
/// Hosts files answered locally (dnsmasq `addn-hosts` / reading `/etc/hosts`).
|
||
///
|
||
/// Every `address name [alias...]` line yields A/AAAA records for the names and a PTR
|
||
/// record for the address (first name). Names found here are answered before local
|
||
/// zones, forwarding and recursion, to clients allowed to resolve
|
||
/// (`recursion.allowed_clients`). Off while `files` is empty.
|
||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct HostsConfig {
|
||
/// Files in hosts format, e.g. `["/etc/hosts", "/etc/hosts.d/*.hosts"]`. Relative paths
|
||
/// are resolved against the configuration directory; `*`/`?` globs are allowed in the
|
||
/// file name. A missing file is a warning, not an error (it is picked up once it appears).
|
||
pub files: Vec<String>,
|
||
/// TTL of the answers (dnsmasq `local-ttl`, default 0: clients do not cache them).
|
||
pub ttl: u32,
|
||
/// Domain appended to names without a dot (dnsmasq `expand-hosts` + `domain=`):
|
||
/// with `domain: lan` the line `192.168.1.10 nas` answers both `nas` and `nas.lan`.
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
pub domain: Option<String>,
|
||
/// How often the files are checked for changes (modification time and size); changed
|
||
/// files are re-read without a reload. `0s` turns it off (then only `easydns reload`).
|
||
#[serde(with = "duration")]
|
||
pub reload_interval: Duration,
|
||
}
|
||
|
||
impl Default for HostsConfig {
|
||
fn default() -> Self {
|
||
Self { files: Vec::new(), ttl: 0, domain: None, reload_interval: Duration::from_secs(5) }
|
||
}
|
||
}
|
||
|
||
impl HostsConfig {
|
||
pub fn enabled(&self) -> bool {
|
||
!self.files.is_empty()
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct PolicyConfig {
|
||
pub blocklists: Vec<BlocklistConfig>,
|
||
pub allowlist: Vec<String>,
|
||
pub block_action: BlockAction,
|
||
pub block_address_v4: std::net::Ipv4Addr,
|
||
pub block_address_v6: std::net::Ipv6Addr,
|
||
pub block_ttl: u32,
|
||
/// Clients exempt from blocking.
|
||
pub exempt_clients: Vec<String>,
|
||
pub log_blocked: bool,
|
||
}
|
||
|
||
impl Default for PolicyConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
blocklists: Vec::new(),
|
||
allowlist: Vec::new(),
|
||
block_action: BlockAction::Nxdomain,
|
||
block_address_v4: std::net::Ipv4Addr::UNSPECIFIED,
|
||
block_address_v6: std::net::Ipv6Addr::UNSPECIFIED,
|
||
block_ttl: 60,
|
||
exempt_clients: Vec::new(),
|
||
log_blocked: true,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct RateLimitConfig {
|
||
pub enabled: bool,
|
||
/// Sustained queries/second per client IP (IPv4 /32, IPv6 /56).
|
||
pub per_client_qps: u32,
|
||
pub burst: u32,
|
||
/// Server-wide UDP query ceiling; 0 (default) = no global limit, only per-client limits.
|
||
pub global_qps: u32,
|
||
/// Every Nth limited UDP query gets a truncated answer (RRL "slip"), others dropped.
|
||
pub slip: u32,
|
||
pub exempt_clients: Vec<String>,
|
||
}
|
||
|
||
impl Default for RateLimitConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
enabled: true,
|
||
per_client_qps: 200,
|
||
burst: 400,
|
||
global_qps: 0,
|
||
slip: 2,
|
||
exempt_clients: vec!["127.0.0.0/8".into(), "::1/128".into()],
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct TlsConfig {
|
||
pub cert_file: Option<PathBuf>,
|
||
pub key_file: Option<PathBuf>,
|
||
/// DNS-over-TLS listeners (e.g. `0.0.0.0:853`).
|
||
pub dot_listen: Vec<SocketAddr>,
|
||
/// DNS-over-HTTPS listeners (e.g. `0.0.0.0:443`).
|
||
pub doh_listen: Vec<SocketAddr>,
|
||
/// Serve DoH over plain HTTP (only behind a TLS-terminating reverse proxy!).
|
||
pub doh_plaintext_behind_proxy: bool,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||
#[serde(rename_all = "kebab-case")]
|
||
pub enum ApiRole {
|
||
Admin,
|
||
ReadOnly,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct ApiTokenConfig {
|
||
pub name: String,
|
||
pub role: ApiRole,
|
||
/// `env:VAR`, `file:/path` or `sha256:<hex>` (hash of the token).
|
||
pub token: String,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct ApiConfig {
|
||
pub enabled: bool,
|
||
/// Default 127.0.0.1:9953 (loopback, non-standard port).
|
||
pub listen: SocketAddr,
|
||
pub auth_required: bool,
|
||
/// Create `<data_dir>/control.token` (mode 0640) on start and accept it as an admin
|
||
/// token. The `easydns` CLI reads it automatically, so local administration works
|
||
/// after installation without generating or passing a key; access is controlled by
|
||
/// file permissions (root and the `easydns` group).
|
||
pub local_token: bool,
|
||
pub tokens: Vec<ApiTokenConfig>,
|
||
pub allowed_clients: Vec<String>,
|
||
pub requests_per_minute: u32,
|
||
}
|
||
|
||
impl Default for ApiConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
enabled: true,
|
||
listen: SocketAddr::from(([127, 0, 0, 1], 9953)),
|
||
auth_required: true,
|
||
local_token: true,
|
||
tokens: Vec::new(),
|
||
allowed_clients: vec!["127.0.0.0/8".into(), "::1/128".into()],
|
||
requests_per_minute: 600,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields, default)]
|
||
pub struct MetricsConfig {
|
||
pub enabled: bool,
|
||
pub listen: SocketAddr,
|
||
}
|
||
|
||
impl Default for MetricsConfig {
|
||
fn default() -> Self {
|
||
Self { enabled: true, listen: SocketAddr::from(([127, 0, 0, 1], 9090)) }
|
||
}
|
||
}
|
||
|
||
/// Changes made through the REST API, persisted in `<data_dir>/api-overlay.yaml`.
|
||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||
#[serde(default)]
|
||
pub struct ApiOverlay {
|
||
pub zones: Vec<ZoneConfig>,
|
||
pub upstreams: Vec<String>,
|
||
pub allowlist: Option<Vec<String>>,
|
||
pub block_action: Option<BlockAction>,
|
||
pub block_rules: Vec<String>,
|
||
}
|
||
|
||
/// CLI-level overrides (highest precedence).
|
||
#[derive(Debug, Clone, Default)]
|
||
pub struct Overrides {
|
||
pub listen: Vec<SocketAddr>,
|
||
pub log_level: Option<String>,
|
||
pub data_dir: Option<PathBuf>,
|
||
pub api_listen: Option<SocketAddr>,
|
||
}
|
||
|
||
impl Config {
|
||
/// Parse a configuration document (YAML is a superset of JSON).
|
||
pub fn from_str_any(text: &str, origin: &str) -> Result<Self, ConfigError> {
|
||
let trimmed = text.trim_start();
|
||
let cfg: Config = if trimmed.starts_with('{') {
|
||
serde_json::from_str(text).map_err(|e| ConfigError::Parse {
|
||
file: origin.into(),
|
||
line: Some(e.line()),
|
||
message: e.to_string(),
|
||
})?
|
||
} else {
|
||
serde_norway::from_str(text).map_err(|e| ConfigError::Parse {
|
||
file: origin.into(),
|
||
line: e.location().map(|l| l.line()),
|
||
message: e.to_string(),
|
||
})?
|
||
};
|
||
Ok(cfg)
|
||
}
|
||
|
||
/// Load from a file, apply ENV overrides, resolve relative paths, validate.
|
||
pub fn load(path: &Path) -> Result<Self, ConfigError> {
|
||
let text =
|
||
std::fs::read_to_string(path).map_err(|e| ConfigError::Io { file: path.display().to_string(), message: e.to_string() })?;
|
||
let mut cfg = Self::from_str_any(&text, &path.display().to_string())?;
|
||
if cfg.server.base_dir.is_none() {
|
||
cfg.server.base_dir = path.parent().map(Path::to_path_buf);
|
||
}
|
||
cfg.expand_includes(path)?;
|
||
cfg.apply_env(|k| std::env::var(k).ok())?;
|
||
cfg.merge_api_overlay()?;
|
||
Ok(cfg)
|
||
}
|
||
|
||
/// Load with full precedence: file < ENV < CLI overrides, then the API overlay
|
||
/// (which lives in the effective data directory).
|
||
pub fn load_with(path: &Path, overrides: &Overrides) -> Result<Self, ConfigError> {
|
||
let text =
|
||
std::fs::read_to_string(path).map_err(|e| ConfigError::Io { file: path.display().to_string(), message: e.to_string() })?;
|
||
let mut cfg = Self::from_str_any(&text, &path.display().to_string())?;
|
||
if cfg.server.base_dir.is_none() {
|
||
cfg.server.base_dir = path.parent().map(Path::to_path_buf);
|
||
}
|
||
cfg.expand_includes(path)?;
|
||
cfg.apply_env(|k| std::env::var(k).ok())?;
|
||
cfg.apply_overrides(overrides);
|
||
cfg.merge_api_overlay()?;
|
||
Ok(cfg)
|
||
}
|
||
|
||
/// Read every `include:` file (recursively, max depth 8) and merge its zones, keys,
|
||
/// ACLs and forward zones into this configuration. Zones remember their source file.
|
||
pub fn expand_includes(&mut self, main: &Path) -> Result<(), ConfigError> {
|
||
let main_s = main.display().to_string();
|
||
for z in &mut self.zones {
|
||
z.source.get_or_insert_with(|| main_s.clone());
|
||
}
|
||
let base = main.parent().map(Path::to_path_buf).unwrap_or_default();
|
||
let patterns = std::mem::take(&mut self.include);
|
||
let mut seen = std::collections::HashSet::new();
|
||
if let Ok(c) = std::fs::canonicalize(main) {
|
||
seen.insert(c);
|
||
}
|
||
self.include_patterns(&patterns, &base, &main_s, 0, &mut seen)?;
|
||
self.include = patterns;
|
||
Ok(())
|
||
}
|
||
|
||
fn include_patterns(
|
||
&mut self,
|
||
patterns: &[String],
|
||
base: &Path,
|
||
from: &str,
|
||
depth: u32,
|
||
seen: &mut std::collections::HashSet<PathBuf>,
|
||
) -> Result<(), ConfigError> {
|
||
if depth > 8 {
|
||
return Err(ConfigError::Io { file: from.into(), message: "include nesting deeper than 8 levels".into() });
|
||
}
|
||
for pat in patterns {
|
||
for file in include::expand(base, pat).map_err(|m| ConfigError::Io { file: from.into(), message: m })? {
|
||
let canon = std::fs::canonicalize(&file).unwrap_or_else(|_| file.clone());
|
||
if !seen.insert(canon) {
|
||
return Err(ConfigError::Io {
|
||
file: from.into(),
|
||
message: format!("{} is included twice (or recursively)", file.display()),
|
||
});
|
||
}
|
||
let fname = file.display().to_string();
|
||
let text = std::fs::read_to_string(&file).map_err(|e| ConfigError::Io { file: fname.clone(), message: e.to_string() })?;
|
||
let inc = include::parse(&text, &fname)?;
|
||
for mut z in inc.zones {
|
||
z.source = Some(fname.clone());
|
||
self.zones.push(z);
|
||
}
|
||
self.keys.extend(inc.keys);
|
||
self.forward_zones.extend(inc.forward_zones);
|
||
for (name, list) in inc.acls {
|
||
if self.acls.contains_key(&name) {
|
||
return Err(ConfigError::Io { file: fname.clone(), message: format!("ACL '{name}' is already defined") });
|
||
}
|
||
self.acls.insert(name, list);
|
||
}
|
||
let nested_base = file.parent().map(Path::to_path_buf).unwrap_or_default();
|
||
self.include_patterns(&inc.include, &nested_base, &fname, depth + 1, seen)?;
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// Path of the overlay file holding changes made through the REST API.
|
||
pub fn overlay_path(&self) -> PathBuf {
|
||
self.data_dir().join("api-overlay.yaml")
|
||
}
|
||
|
||
/// Load the API overlay (empty when absent).
|
||
pub fn load_overlay(&self) -> Result<ApiOverlay, ConfigError> {
|
||
let p = self.overlay_path();
|
||
let Ok(text) = std::fs::read_to_string(&p) else { return Ok(ApiOverlay::default()) };
|
||
serde_norway::from_str(&text).map_err(|e| ConfigError::Parse {
|
||
file: p.display().to_string(),
|
||
line: e.location().map(|l| l.line()),
|
||
message: e.to_string(),
|
||
})
|
||
}
|
||
|
||
/// Merge changes made through the API (`<data_dir>/api-overlay.yaml`).
|
||
pub fn merge_api_overlay(&mut self) -> Result<(), ConfigError> {
|
||
let o = self.load_overlay()?;
|
||
for z in o.zones {
|
||
if !self.zones.iter().any(|c| c.name.trim_end_matches('.').eq_ignore_ascii_case(z.name.trim_end_matches('.'))) {
|
||
self.zones.push(z);
|
||
}
|
||
}
|
||
for u in o.upstreams {
|
||
if !self.upstreams.servers.contains(&u) {
|
||
self.upstreams.servers.push(u);
|
||
}
|
||
}
|
||
if let Some(a) = o.allowlist {
|
||
self.policy.allowlist = a;
|
||
}
|
||
if let Some(a) = o.block_action {
|
||
self.policy.block_action = a;
|
||
}
|
||
if !o.block_rules.is_empty() {
|
||
self.policy.blocklists.push(BlocklistConfig {
|
||
name: "api".into(),
|
||
file: Some(self.data_dir().join("blocklists").join("api.txt")),
|
||
url: None,
|
||
category: Some("api".into()),
|
||
enabled: true,
|
||
});
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// Apply `EASYDNS_*` environment overrides.
|
||
pub fn apply_env(&mut self, get: impl Fn(&str) -> Option<String>) -> Result<(), ConfigError> {
|
||
if let Some(v) = get("EASYDNS_LISTEN") {
|
||
let mut out = Vec::new();
|
||
for a in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
|
||
out.push(
|
||
a.parse()
|
||
.map_err(|_| ConfigError::Env { var: "EASYDNS_LISTEN".into(), message: format!("invalid socket address '{a}'") })?,
|
||
);
|
||
}
|
||
self.server.listen = out;
|
||
}
|
||
if let Some(v) = get("EASYDNS_LOG_LEVEL") {
|
||
self.logging.level = v;
|
||
}
|
||
if let Some(v) = get("EASYDNS_DATA_DIR") {
|
||
self.server.data_dir = v.into();
|
||
}
|
||
if let Some(v) = get("EASYDNS_API_LISTEN") {
|
||
self.api.listen = v
|
||
.parse()
|
||
.map_err(|_| ConfigError::Env { var: "EASYDNS_API_LISTEN".into(), message: format!("invalid socket address '{v}'") })?;
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// Apply CLI overrides.
|
||
pub fn apply_overrides(&mut self, o: &Overrides) {
|
||
if !o.listen.is_empty() {
|
||
self.server.listen = o.listen.clone();
|
||
}
|
||
if let Some(l) = &o.log_level {
|
||
self.logging.level = l.clone();
|
||
}
|
||
if let Some(d) = &o.data_dir {
|
||
self.server.data_dir = d.clone();
|
||
}
|
||
if let Some(a) = o.api_listen {
|
||
self.api.listen = a;
|
||
}
|
||
}
|
||
|
||
/// Expand `hosts.files` (paths relative to the config directory, `*`/`?` globs in the
|
||
/// file name). Returns the existing files (sorted per pattern, without duplicates) and
|
||
/// the literal paths that do not exist.
|
||
pub fn hosts_file_paths(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
|
||
let base = self.server.base_dir.clone().unwrap_or_default();
|
||
let (mut found, mut missing) = (Vec::new(), Vec::new());
|
||
for pat in &self.hosts.files {
|
||
match include::expand(&base, pat) {
|
||
Ok(v) => {
|
||
for f in v {
|
||
if !found.contains(&f) {
|
||
found.push(f);
|
||
}
|
||
}
|
||
}
|
||
Err(_) => missing.push(self.resolve_path(Path::new(pat))),
|
||
}
|
||
}
|
||
(found, missing)
|
||
}
|
||
|
||
/// Resolve a path relative to the config file directory.
|
||
pub fn resolve_path(&self, p: &Path) -> PathBuf {
|
||
if p.is_absolute() {
|
||
return p.to_path_buf();
|
||
}
|
||
match &self.server.base_dir {
|
||
Some(b) => b.join(p),
|
||
None => p.to_path_buf(),
|
||
}
|
||
}
|
||
|
||
/// Local control token file used by the CLI (`api.local_token`).
|
||
pub fn control_token_path(&self) -> PathBuf {
|
||
self.data_dir().join(CONTROL_TOKEN_FILE)
|
||
}
|
||
|
||
/// Data directory (resolved).
|
||
pub fn data_dir(&self) -> PathBuf {
|
||
self.resolve_path(&self.server.data_dir)
|
||
}
|
||
|
||
/// Resolve a zone `file:`. Relative paths are relative to the data directory
|
||
/// (`zones/primary/example.com.zone` → `<data_dir>/zones/primary/example.com.zone`). For configurations
|
||
/// written before this rule, a relative path that exists only relative to the config
|
||
/// directory is still accepted.
|
||
pub fn zone_file_path(&self, p: &Path) -> PathBuf {
|
||
if p.is_absolute() {
|
||
return p.to_path_buf();
|
||
}
|
||
// lexical normalisation: `../x` must work before the data directory exists
|
||
let in_data = normalize(&self.data_dir().join(p));
|
||
if !in_data.exists() {
|
||
let legacy = self.resolve_path(p);
|
||
if legacy.is_file() {
|
||
return legacy;
|
||
}
|
||
}
|
||
in_data
|
||
}
|
||
|
||
/// Expand an ACL list (CIDRs, bare IPs, `acl:<name>`, `any`, `none`) into networks.
|
||
pub fn expand_acl(&self, items: &[String]) -> Result<Vec<IpNet>, String> {
|
||
let mut out = Vec::new();
|
||
self.expand_acl_inner(items, &mut out, 0)?;
|
||
Ok(out)
|
||
}
|
||
|
||
fn expand_acl_inner(&self, items: &[String], out: &mut Vec<IpNet>, depth: u32) -> Result<(), String> {
|
||
if depth > 8 {
|
||
return Err("ACL references nested too deeply (loop?)".into());
|
||
}
|
||
for it in items {
|
||
let s = it.trim();
|
||
if let Some(name) = s.strip_prefix("acl:") {
|
||
let list = self.acls.get(name).ok_or_else(|| format!("unknown ACL '{name}'"))?;
|
||
self.expand_acl_inner(list, out, depth + 1)?;
|
||
} else if s == "any" {
|
||
out.push("0.0.0.0/0".parse().map_err(|_| "acl")?);
|
||
out.push("::/0".parse().map_err(|_| "acl")?);
|
||
} else if s == "none" {
|
||
} else if let Ok(n) = s.parse::<IpNet>() {
|
||
out.push(n.trunc());
|
||
} else if let Ok(ip) = s.parse::<std::net::IpAddr>() {
|
||
out.push(IpNet::from(ip));
|
||
} else {
|
||
return Err(format!("invalid ACL entry '{s}'"));
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// Resolve a secret reference (`env:`, `file:`, `base64:`).
|
||
pub fn resolve_secret(&self, reference: &str) -> Result<String, String> {
|
||
if let Some(var) = reference.strip_prefix("env:") {
|
||
std::env::var(var).map_err(|_| format!("environment variable {var} is not set"))
|
||
} else if let Some(p) = reference.strip_prefix("file:") {
|
||
let path = self.resolve_path(Path::new(p));
|
||
std::fs::read_to_string(&path)
|
||
.map(|s| s.trim().to_string())
|
||
.map_err(|e| format!("cannot read secret file {}: {e}", path.display()))
|
||
} else if let Some(v) = reference.strip_prefix("base64:") {
|
||
Ok(v.to_string())
|
||
} else {
|
||
Err("secret must be a reference: env:VAR, file:/path or base64:<value>".into())
|
||
}
|
||
}
|
||
|
||
/// Build the TSIG key ring.
|
||
pub fn key_ring(&self) -> Result<dns_core::tsig::KeyRing, String> {
|
||
let mut ring = dns_core::tsig::KeyRing::default();
|
||
for k in &self.keys {
|
||
let secret = self.resolve_secret(&k.secret).map_err(|e| format!("key {}: {e}", k.name))?;
|
||
let key = dns_core::tsig::TsigKey::new(&k.name, &k.algorithm, &secret).map_err(|e| e.to_string())?;
|
||
ring.insert(key);
|
||
}
|
||
Ok(ring)
|
||
}
|
||
|
||
/// Validate; returns all issues found (errors and warnings).
|
||
pub fn validate(&self) -> Vec<ValidationIssue> {
|
||
validate::validate(self)
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn hosts_section_parses_and_validates() {
|
||
let c: super::Config =
|
||
serde_norway::from_str("hosts: { files: [/etc/hosts, /nonexistent/x.hosts], ttl: 60, domain: lan, reload_interval: 2s }\n")
|
||
.unwrap();
|
||
assert!(c.hosts.enabled());
|
||
assert_eq!(c.hosts.ttl, 60);
|
||
assert_eq!(c.hosts.reload_interval, std::time::Duration::from_secs(2));
|
||
let issues = c.validate();
|
||
assert!(issues.iter().any(|i| i.path == "hosts.files" && !i.is_error()), "{issues:?}");
|
||
let bad: super::Config = serde_norway::from_str("hosts: { files: [/etc/hosts], domain: \"a..b\" }\n").unwrap();
|
||
assert!(bad.validate().iter().any(|i| i.path == "hosts.domain" && i.is_error()));
|
||
assert!(!super::Config::default().hosts.enabled());
|
||
}
|
||
|
||
#[test]
|
||
fn zone_path_with_parent_dir_before_data_dir_exists() {
|
||
let d = std::env::temp_dir().join(format!("edns-zp-{}", std::process::id()));
|
||
std::fs::create_dir_all(&d).unwrap();
|
||
std::fs::write(d.join("z.zone"), "x").unwrap();
|
||
let mut c = super::Config::default();
|
||
c.server.base_dir = Some(d.clone());
|
||
c.server.data_dir = "not-created-yet".into();
|
||
assert_eq!(c.zone_file_path(std::path::Path::new("../z.zone")), d.join("z.zone"));
|
||
assert_eq!(c.zone_file_path(std::path::Path::new("zones/a.zone")), d.join("not-created-yet/zones/a.zone"));
|
||
let _ = std::fs::remove_dir_all(&d);
|
||
}
|
||
|
||
use super::*;
|
||
|
||
const SAMPLE: &str = r#"
|
||
server:
|
||
mode: hybrid
|
||
listen: ["127.0.0.1:5353"]
|
||
recursion:
|
||
enabled: true
|
||
allowed_clients: ["127.0.0.0/8", "acl:lan"]
|
||
acls:
|
||
lan: ["192.168.0.0/16"]
|
||
zones:
|
||
- name: example.net
|
||
type: slave
|
||
primaries: ["192.0.2.1:53"]
|
||
transfer:
|
||
prefer: ixfr
|
||
timeout: 30s
|
||
forward_zones:
|
||
- domain: corp.internal
|
||
upstreams: ["192.168.1.1:53"]
|
||
upstreams:
|
||
strategy: fastest
|
||
servers: ["1.1.1.1:53", "tls://9.9.9.9#dns.quad9.net"]
|
||
resolution:
|
||
default: recursive
|
||
"#;
|
||
|
||
#[test]
|
||
fn parse_sample() {
|
||
let c = Config::from_str_any(SAMPLE, "t").unwrap();
|
||
assert_eq!(c.zones[0].zone_type, ZoneType::Secondary);
|
||
assert_eq!(c.zones[0].transfer.timeout.as_secs(), 30);
|
||
let issues = c.validate();
|
||
let errs: Vec<_> = issues.iter().filter(|i| i.is_error()).collect();
|
||
assert!(errs.is_empty(), "{errs:?}");
|
||
let acl = c.expand_acl(&c.recursion.allowed_clients).unwrap();
|
||
assert_eq!(acl.len(), 2);
|
||
}
|
||
|
||
#[test]
|
||
fn unknown_field_rejected_with_line() {
|
||
let e = Config::from_str_any("server:\n lisen: []\n", "c.yaml").unwrap_err();
|
||
let s = e.to_string();
|
||
assert!(s.contains("c.yaml:2"), "{s}");
|
||
assert!(s.contains("lisen"));
|
||
}
|
||
|
||
#[test]
|
||
fn detects_errors() {
|
||
let y = r#"
|
||
server: { mode: recursive }
|
||
zones:
|
||
- { name: "bad..name", type: primary }
|
||
- { name: example.org, type: secondary }
|
||
resolution: { default: forward }
|
||
api: { listen: "0.0.0.0:8080", auth_required: false }
|
||
"#;
|
||
let c = Config::from_str_any(y, "t").unwrap();
|
||
let issues = c.validate();
|
||
let paths: Vec<_> = issues.iter().filter(|i| i.is_error()).map(|i| i.path.clone()).collect();
|
||
for p in ["zones[0].name", "zones[0].file", "zones[1].primaries", "resolution.default", "server.mode", "api.auth_required"] {
|
||
assert!(paths.iter().any(|x| x == p), "missing {p} in {paths:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn env_and_cli_precedence() {
|
||
let mut c = Config::from_str_any(SAMPLE, "t").unwrap();
|
||
c.apply_env(|k| (k == "EASYDNS_LISTEN").then(|| "127.0.0.1:1053".into())).unwrap();
|
||
assert_eq!(c.server.listen[0].port(), 1053);
|
||
c.apply_overrides(&Overrides { listen: vec!["127.0.0.1:2053".parse().unwrap()], ..Default::default() });
|
||
assert_eq!(c.server.listen[0].port(), 2053);
|
||
assert!(c.apply_env(|k| (k == "EASYDNS_LISTEN").then(|| "nope".into())).is_err());
|
||
}
|
||
|
||
#[test]
|
||
fn open_resolver_warns() {
|
||
let c =
|
||
Config::from_str_any("recursion: { enabled: true, allowed_clients: [any] }\nresolution: {default: recursive}", "t").unwrap();
|
||
assert!(c.validate().iter().any(|i| i.path == "recursion.allowed_clients" && !i.is_error()));
|
||
}
|
||
}
|