sagittarius 0.2.0

A fast, self-hosted DNS sinkhole in a single Rust binary
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
//! Repository for the singleton `settings` row.
//!
//! Provides the [`SettingsRepository`] trait and its [`SqliteSettingsRepo`]
//! implementation.  All DB interaction uses compile-time-checked `sqlx::query_as!`
//! / `sqlx::query!` macros against the `settings` table defined in the schema
//! migration.

use std::{
    fmt,
    future::Future,
    net::{Ipv4Addr, Ipv6Addr},
    str::FromStr,
};

use sqlx::SqlitePool;

use super::Error;

// ── Result alias ────────────────────────────────────────────────────────────

pub type Result<T> = std::result::Result<T, Error>;

// ── BlockingMode ─────────────────────────────────────────────────────────────

/// How the DNS sinkhole responds to blocked domains.
///
/// Maps to/from the `blocking_mode` TEXT column values `'nxdomain'`,
/// `'null-ip'`, and `'custom'`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
pub enum BlockingMode {
    /// Reply with `NXDOMAIN` (domain does not exist).
    #[strum(serialize = "nxdomain")]
    NxDomain,
    /// Reply with `0.0.0.0` / `::` (null IP addresses).
    #[strum(serialize = "null-ip")]
    NullIp,
    /// Reply with the admin-configured custom IP addresses.
    #[strum(serialize = "custom")]
    Custom,
}

impl BlockingMode {
    /// Returns the canonical TEXT representation stored in the database.
    ///
    /// Driven by `#[strum(serialize)]` ([`strum::IntoStaticStr`]); the
    /// value-carrying [`FromStr`] below is the inverse.
    pub fn as_str(&self) -> &'static str {
        self.into()
    }
}

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

impl FromStr for BlockingMode {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "nxdomain" => Ok(Self::NxDomain),
            "null-ip" => Ok(Self::NullIp),
            "custom" => Ok(Self::Custom),
            other => Err(Error::Decode(format!(
                "unknown blocking_mode value: {other:?}"
            ))),
        }
    }
}

// ── SelectionStrategy ────────────────────────────────────────────────────────

/// How the upstream pool picks a resolver per query (E15).
///
/// Maps to/from the `upstream_selection_strategy` TEXT column values
/// `'random'`, `'latency-weighted'`, and `'parallel'`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, strum::IntoStaticStr)]
pub enum SelectionStrategy {
    /// Uniform shuffle across upstreams (the v0.1 default).
    #[default]
    #[strum(serialize = "random")]
    Random,
    /// Weighted-random bias toward faster, healthier upstreams.
    #[strum(serialize = "latency-weighted")]
    LatencyWeighted,
    /// Race the first N upstreams concurrently; take the first success.
    #[strum(serialize = "parallel")]
    Parallel,
}

impl SelectionStrategy {
    /// The canonical TEXT representation stored in the database.
    pub fn as_str(&self) -> &'static str {
        self.into()
    }
}

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

impl FromStr for SelectionStrategy {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "random" => Ok(Self::Random),
            "latency-weighted" => Ok(Self::LatencyWeighted),
            "parallel" => Ok(Self::Parallel),
            other => Err(Error::Decode(format!(
                "unknown upstream_selection_strategy value: {other:?}"
            ))),
        }
    }
}

// ── Settings ──────────────────────────────────────────────────────────────────

/// Typed representation of the singleton `settings` row (id = 1).
#[derive(Debug, Clone, PartialEq)]
pub struct Settings {
    /// Minimum TTL to serve from the cache, in seconds.
    pub cache_min_ttl: u32,
    /// Maximum TTL to serve from the cache, in seconds.
    pub cache_max_ttl: u32,
    /// Cap applied to NXDOMAIN/NODATA negative cache entries, in seconds.
    pub cache_negative_ttl_cap: u32,
    /// Maximum number of cache entries.
    pub cache_capacity: u64,
    /// How blocked domains are answered.
    pub blocking_mode: BlockingMode,
    /// Custom IPv4 address used when `blocking_mode` is `Custom`.
    pub custom_block_ipv4: Option<Ipv4Addr>,
    /// Custom IPv6 address used when `blocking_mode` is `Custom`.
    pub custom_block_ipv6: Option<Ipv6Addr>,
    /// How often blocklists are refreshed, in seconds.
    pub blocklist_refresh_interval: u32,
    /// UI colour-scheme preference (e.g. `"auto"`, `"light"`, `"dark"`).
    pub ui_theme: String,
    /// Whether per-query events are persisted to the query log (E10). When
    /// `false` the writer task drops events without enqueuing them.
    pub query_log_enabled: bool,
    /// How many days of query-log history to retain before the hourly purge
    /// removes older rows (E10).
    pub query_log_retention_days: u32,
    /// How the upstream pool selects a resolver per query (E15).
    pub upstream_selection_strategy: SelectionStrategy,
    /// Fan-out N for [`SelectionStrategy::Parallel`]; ignored by other
    /// strategies. At least 1.
    pub upstream_parallel_fanout: u32,
}

// ── Private row struct ────────────────────────────────────────────────────────

/// Private projection returned by `query_as!` — all primitive SQLite types so
/// the macro can type-check the column names and types at compile time.
struct SettingsRow {
    cache_min_ttl: i64,
    cache_max_ttl: i64,
    cache_negative_ttl_cap: i64,
    cache_capacity: i64,
    blocking_mode: String,
    custom_block_ipv4: Option<String>,
    custom_block_ipv6: Option<String>,
    blocklist_refresh_interval: i64,
    ui_theme: String,
    query_log_enabled: i64,
    query_log_retention_days: i64,
    upstream_selection_strategy: String,
    upstream_parallel_fanout: i64,
}

/// Narrow a non-negative `i64` DB value to `u32`, returning a decode error
/// when out of range.
fn narrow_u32(value: i64, column: &'static str) -> Result<u32> {
    u32::try_from(value)
        .map_err(|_| Error::Decode(format!("column {column} value {value} is out of u32 range")))
}

/// Narrow a non-negative `i64` DB value to `u64`.
fn narrow_u64(value: i64, column: &'static str) -> Result<u64> {
    u64::try_from(value)
        .map_err(|_| Error::Decode(format!("column {column} value {value} is out of u64 range")))
}

impl TryFrom<SettingsRow> for Settings {
    type Error = Error;

    fn try_from(row: SettingsRow) -> Result<Self> {
        let blocking_mode: BlockingMode = row.blocking_mode.parse()?;

        let custom_block_ipv4 = row
            .custom_block_ipv4
            .as_deref()
            .map(|s| {
                s.parse::<Ipv4Addr>()
                    .map_err(|e| Error::Decode(format!("invalid custom_block_ipv4 {s:?}: {e}")))
            })
            .transpose()?;

        let custom_block_ipv6 = row
            .custom_block_ipv6
            .as_deref()
            .map(|s| {
                s.parse::<Ipv6Addr>()
                    .map_err(|e| Error::Decode(format!("invalid custom_block_ipv6 {s:?}: {e}")))
            })
            .transpose()?;

        Ok(Settings {
            cache_min_ttl: narrow_u32(row.cache_min_ttl, "cache_min_ttl")?,
            cache_max_ttl: narrow_u32(row.cache_max_ttl, "cache_max_ttl")?,
            cache_negative_ttl_cap: narrow_u32(
                row.cache_negative_ttl_cap,
                "cache_negative_ttl_cap",
            )?,
            cache_capacity: narrow_u64(row.cache_capacity, "cache_capacity")?,
            blocking_mode,
            custom_block_ipv4,
            custom_block_ipv6,
            blocklist_refresh_interval: narrow_u32(
                row.blocklist_refresh_interval,
                "blocklist_refresh_interval",
            )?,
            ui_theme: row.ui_theme,
            query_log_enabled: row.query_log_enabled != 0,
            query_log_retention_days: narrow_u32(
                row.query_log_retention_days,
                "query_log_retention_days",
            )?,
            upstream_selection_strategy: row.upstream_selection_strategy.parse()?,
            upstream_parallel_fanout: narrow_u32(
                row.upstream_parallel_fanout,
                "upstream_parallel_fanout",
            )?,
        })
    }
}

// ── SettingsRepository trait ─────────────────────────────────────────────────

/// Repository for reading and writing the singleton `settings` row.
///
/// Methods return `impl Future` rather than `async fn` so the trait sidesteps the
/// `async_fn_in_trait` lint without committing every implementation to a `Send`
/// bound — callers are concrete, so `Send` still leaks through where it's needed
/// (axum handlers, spawned tasks).
pub trait SettingsRepository {
    /// Read the singleton settings row (id = 1).
    fn get(&self) -> impl Future<Output = Result<Settings>>;

    /// Persist all mutable fields of `settings` back to the database.
    fn update(&self, settings: &Settings) -> impl Future<Output = Result<()>>;
}

// ── SqliteSettingsRepo ────────────────────────────────────────────────────────

/// SQLite-backed [`SettingsRepository`].
pub struct SqliteSettingsRepo {
    pool: SqlitePool,
}

impl SqliteSettingsRepo {
    /// Construct a new repository from an open [`crate::storage::Db`].
    pub fn new(pool: SqlitePool) -> Self {
        Self { pool }
    }
}

impl SettingsRepository for SqliteSettingsRepo {
    async fn get(&self) -> Result<Settings> {
        let row = sqlx::query_as!(
            SettingsRow,
            r#"SELECT
                cache_min_ttl,
                cache_max_ttl,
                cache_negative_ttl_cap,
                cache_capacity,
                blocking_mode,
                custom_block_ipv4,
                custom_block_ipv6,
                blocklist_refresh_interval,
                ui_theme,
                query_log_enabled,
                query_log_retention_days,
                upstream_selection_strategy,
                upstream_parallel_fanout
            FROM settings
            WHERE id = 1"#
        )
        .fetch_one(&self.pool)
        .await?;

        Settings::try_from(row)
    }

    async fn update(&self, settings: &Settings) -> Result<()> {
        let blocking_mode = settings.blocking_mode.as_str();
        let custom_block_ipv4 = settings.custom_block_ipv4.map(|ip| ip.to_string());
        let custom_block_ipv6 = settings.custom_block_ipv6.map(|ip| ip.to_string());
        let cache_min_ttl = settings.cache_min_ttl as i64;
        let cache_max_ttl = settings.cache_max_ttl as i64;
        let cache_negative_ttl_cap = settings.cache_negative_ttl_cap as i64;
        let cache_capacity = settings.cache_capacity as i64;
        let blocklist_refresh_interval = settings.blocklist_refresh_interval as i64;
        let query_log_enabled = settings.query_log_enabled as i64;
        let query_log_retention_days = settings.query_log_retention_days as i64;
        let upstream_selection_strategy = settings.upstream_selection_strategy.as_str();
        let upstream_parallel_fanout = settings.upstream_parallel_fanout as i64;

        sqlx::query!(
            r#"UPDATE settings SET
                cache_min_ttl               = ?,
                cache_max_ttl               = ?,
                cache_negative_ttl_cap      = ?,
                cache_capacity              = ?,
                blocking_mode               = ?,
                custom_block_ipv4           = ?,
                custom_block_ipv6           = ?,
                blocklist_refresh_interval  = ?,
                ui_theme                    = ?,
                query_log_enabled           = ?,
                query_log_retention_days    = ?,
                upstream_selection_strategy = ?,
                upstream_parallel_fanout    = ?
            WHERE id = 1"#,
            cache_min_ttl,
            cache_max_ttl,
            cache_negative_ttl_cap,
            cache_capacity,
            blocking_mode,
            custom_block_ipv4,
            custom_block_ipv6,
            blocklist_refresh_interval,
            settings.ui_theme,
            query_log_enabled,
            query_log_retention_days,
            upstream_selection_strategy,
            upstream_parallel_fanout,
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::Db;
    use tempfile::TempDir;

    async fn open_repo() -> (TempDir, SqliteSettingsRepo) {
        let dir = TempDir::new().expect("temp dir");
        let path = dir.path().join("test.db");
        let db = Db::connect(&path).await.expect("connect");
        let repo = SqliteSettingsRepo::new(db.pool().clone());
        (dir, repo)
    }

    // ── BlockingMode unit tests ───────────────────────────────────────────────

    #[test]
    fn blocking_mode_display() {
        assert_eq!(BlockingMode::NxDomain.to_string(), "nxdomain");
        assert_eq!(BlockingMode::NullIp.to_string(), "null-ip");
        assert_eq!(BlockingMode::Custom.to_string(), "custom");
    }

    #[test]
    fn blocking_mode_from_str_valid() {
        assert_eq!(
            "nxdomain".parse::<BlockingMode>().unwrap(),
            BlockingMode::NxDomain
        );
        assert_eq!(
            "null-ip".parse::<BlockingMode>().unwrap(),
            BlockingMode::NullIp
        );
        assert_eq!(
            "custom".parse::<BlockingMode>().unwrap(),
            BlockingMode::Custom
        );
    }

    #[test]
    fn blocking_mode_from_str_invalid() {
        let err = "unknown".parse::<BlockingMode>();
        assert!(err.is_err(), "invalid blocking mode must fail");
        let msg = err.unwrap_err().to_string();
        assert!(
            msg.contains("unknown"),
            "error message must mention the bad value: {msg}"
        );
    }

    // ── get() returns seeded defaults ────────────────────────────────────────

    #[tokio::test]
    async fn get_returns_seeded_defaults() {
        let (_dir, repo) = open_repo().await;
        let settings = repo.get().await.expect("get settings");

        assert_eq!(settings.cache_min_ttl, 1u32);
        assert_eq!(settings.cache_max_ttl, 86400u32);
        assert_eq!(settings.cache_negative_ttl_cap, 3600u32);
        assert_eq!(settings.cache_capacity, 100_000u64);
        assert_eq!(settings.blocking_mode, BlockingMode::NullIp);
        assert!(settings.custom_block_ipv4.is_none());
        assert!(settings.custom_block_ipv6.is_none());
        assert_eq!(settings.blocklist_refresh_interval, 86400u32);
        assert_eq!(settings.ui_theme, "auto");
        assert!(settings.query_log_enabled, "query log enabled by default");
        assert_eq!(settings.query_log_retention_days, 30u32);
        assert_eq!(
            settings.upstream_selection_strategy,
            SelectionStrategy::Random,
            "default strategy is random"
        );
        assert_eq!(settings.upstream_parallel_fanout, 2u32);
    }

    // ── SelectionStrategy unit tests ──────────────────────────────────────────

    #[test]
    fn selection_strategy_round_trips_via_str() {
        for strategy in [
            SelectionStrategy::Random,
            SelectionStrategy::LatencyWeighted,
            SelectionStrategy::Parallel,
        ] {
            let token = strategy.as_str();
            assert_eq!(token.parse::<SelectionStrategy>().unwrap(), strategy);
        }
        assert!("bogus".parse::<SelectionStrategy>().is_err());
    }

    #[tokio::test]
    async fn update_round_trips_selection_strategy() {
        let (_dir, repo) = open_repo().await;
        let mut settings = repo.get().await.expect("get");

        settings.upstream_selection_strategy = SelectionStrategy::Parallel;
        settings.upstream_parallel_fanout = 4;
        repo.update(&settings).await.expect("update");

        let fetched = repo.get().await.expect("re-get");
        assert_eq!(
            fetched.upstream_selection_strategy,
            SelectionStrategy::Parallel
        );
        assert_eq!(fetched.upstream_parallel_fanout, 4u32);
    }

    // ── update() round-trips ──────────────────────────────────────────────────

    #[tokio::test]
    async fn update_round_trips() {
        let (_dir, repo) = open_repo().await;

        let mut settings = repo.get().await.expect("get");

        // Change several fields.
        settings.blocking_mode = BlockingMode::Custom;
        settings.custom_block_ipv4 = Some("203.0.113.1".parse().unwrap());
        settings.custom_block_ipv6 = Some("2001:db8::1".parse().unwrap());
        settings.cache_max_ttl = 43200;
        settings.ui_theme = "dark".to_owned();
        settings.query_log_enabled = false;
        settings.query_log_retention_days = 14;

        repo.update(&settings).await.expect("update");

        let fetched = repo.get().await.expect("re-get");
        assert_eq!(fetched.blocking_mode, BlockingMode::Custom);
        assert!(!fetched.query_log_enabled);
        assert_eq!(fetched.query_log_retention_days, 14u32);
        assert_eq!(
            fetched.custom_block_ipv4,
            Some("203.0.113.1".parse().unwrap())
        );
        assert_eq!(
            fetched.custom_block_ipv6,
            Some("2001:db8::1".parse().unwrap())
        );
        assert_eq!(fetched.cache_max_ttl, 43200u32);
        assert_eq!(fetched.ui_theme, "dark");
    }

    #[tokio::test]
    async fn update_clears_custom_ips() {
        let (_dir, repo) = open_repo().await;

        // Set custom IPs first.
        let mut settings = repo.get().await.expect("get");
        settings.custom_block_ipv4 = Some("10.0.0.1".parse().unwrap());
        repo.update(&settings).await.expect("update with IP");

        // Now clear them.
        settings.custom_block_ipv4 = None;
        repo.update(&settings).await.expect("update clearing IP");

        let fetched = repo.get().await.expect("re-get");
        assert!(fetched.custom_block_ipv4.is_none());
    }

    #[tokio::test]
    async fn update_blocking_mode_round_trips_all_variants() {
        let (_dir, repo) = open_repo().await;
        let mut settings = repo.get().await.expect("get");

        for mode in [
            BlockingMode::NxDomain,
            BlockingMode::NullIp,
            BlockingMode::Custom,
        ] {
            settings.blocking_mode = mode;
            repo.update(&settings).await.expect("update");
            let fetched = repo.get().await.expect("re-get");
            assert_eq!(fetched.blocking_mode, mode, "round-trip for {mode}");
        }
    }
}