sagittarius 0.1.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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Repositories for the `blacklist` and `allowlist` tables.
//!
//! Provides the [`BlacklistRepository`] / [`AllowlistRepository`] traits and
//! their [`SqliteBlacklistRepo`] / [`SqliteAllowlistRepo`] implementations.
//!
//! # Domain normalization
//!
//! All domain inputs go through [`crate::codec::name::Name`] before touching
//! the database.  `Name::from_str` lowercases and appends a trailing dot, so
//! `"Ads.Example.COM"` and `"ads.example.com."` are stored identically and
//! compare equal when loaded via `load_all`.  Invalid domains (empty labels,
//! labels > 63 bytes, etc.) produce [`Error::InvalidDomain`].

use std::str::FromStr;

use sqlx::SqlitePool;

use crate::codec::name::Name;

use super::Error;

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

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

// ── ListEntry ────────────────────────────────────────────────────────────────

/// A single row returned by [`BlacklistRepository::list`] /
/// [`AllowlistRepository::list`] — suitable for the admin UI.
#[derive(Debug, Clone, PartialEq)]
pub struct ListEntry {
    /// Row primary key.
    pub id: i64,
    /// Normalized domain (lowercase, trailing dot), e.g. `"ads.example.com."`.
    pub domain: String,
    /// Unix epoch seconds of when the domain was added.
    pub created_at: i64,
}

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

/// Private projection for `query_as!` — primitive SQLite types only.
///
/// `id` and `created_at` use the non-null override `AS "col!"` because
/// sqlx-SQLite infers NOT NULL INTEGER columns as `Option<i64>` in some query
/// shapes.
struct ListRow {
    id: i64,
    domain: String,
    created_at: i64,
}

impl From<ListRow> for ListEntry {
    fn from(row: ListRow) -> Self {
        Self {
            id: row.id,
            domain: row.domain,
            created_at: row.created_at,
        }
    }
}

// ── Helper: normalize a domain through Name ──────────────────────────────────

/// Parse `domain` through [`Name`] and return the normalized string
/// (e.g. `"ads.example.com."`), or an [`Error::InvalidDomain`] if the input
/// is not a valid DNS name.
fn normalize(domain: &str) -> Result<String> {
    Name::from_str(domain)
        .map(|n| n.as_str().to_owned())
        .map_err(|e| Error::InvalidDomain(format!("{domain:?}: {e}")))
}

// ── BlacklistRepository trait ─────────────────────────────────────────────────

/// Repository for reading and writing admin-blacklisted domains.
///
/// # Note on `async_fn_in_trait`
///
/// We use `async fn` directly in the trait.  All implementations live in this
/// crate, so we control the full `impl` surface and have no need for
/// `Send`-bound flexibility across dynamic dispatch.  The lint is suppressed
/// here rather than desugaring to `impl Future`.
#[allow(async_fn_in_trait)]
pub trait BlacklistRepository {
    /// Add `domain` to the blacklist.
    ///
    /// The domain is first normalized through [`Name`] (lowercase + trailing
    /// dot).  If the normalized domain already exists in the table the call
    /// succeeds silently (idempotent — `INSERT … ON CONFLICT DO NOTHING`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidDomain`] if `domain` cannot be parsed as a
    /// valid DNS name.  Database errors surface as [`Error::Sqlx`].
    async fn add(&self, domain: &str) -> Result<()>;

    /// Remove `domain` from the blacklist.
    ///
    /// The domain is normalized before the delete.  If the domain is not
    /// present the call succeeds silently (no-op).
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidDomain`] if `domain` cannot be parsed.
    async fn remove(&self, domain: &str) -> Result<()>;

    /// List all blacklisted domains ordered by domain name.
    ///
    /// Returns entries with `id`, normalized `domain`, and `created_at`
    /// (unix epoch seconds) — intended for the admin UI.
    async fn list(&self) -> Result<Vec<ListEntry>>;

    /// Load all blacklisted domain names as parsed [`Name`] values.
    ///
    /// This is the bulk-read entry point used by the resolver (E4) to
    /// hydrate its in-memory `HashSet<Name>`.
    async fn load_all(&self) -> Result<Vec<Name>>;
}

// ── AllowlistRepository trait ─────────────────────────────────────────────────

/// Repository for reading and writing admin-allowlisted domains.
///
/// Identical contract to [`BlacklistRepository`] but operates on the separate
/// `allowlist` table.
#[allow(async_fn_in_trait)]
pub trait AllowlistRepository {
    /// Add `domain` to the allowlist (idempotent).
    async fn add(&self, domain: &str) -> Result<()>;

    /// Remove `domain` from the allowlist (no-op if absent).
    async fn remove(&self, domain: &str) -> Result<()>;

    /// List all allowlisted domains ordered by domain name.
    async fn list(&self) -> Result<Vec<ListEntry>>;

    /// Load all allowlisted domain names as parsed [`Name`] values.
    async fn load_all(&self) -> Result<Vec<Name>>;
}

// ── SqliteBlacklistRepo ───────────────────────────────────────────────────────

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

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

impl BlacklistRepository for SqliteBlacklistRepo {
    async fn add(&self, domain: &str) -> Result<()> {
        let normalized = normalize(domain)?;
        sqlx::query!(
            "INSERT INTO blacklist (domain) VALUES (?) ON CONFLICT(domain) DO NOTHING",
            normalized,
        )
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn remove(&self, domain: &str) -> Result<()> {
        let normalized = normalize(domain)?;
        sqlx::query!("DELETE FROM blacklist WHERE domain = ?", normalized)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    async fn list(&self) -> Result<Vec<ListEntry>> {
        let rows = sqlx::query_as!(
            ListRow,
            r#"SELECT
                id          AS "id!",
                domain,
                created_at  AS "created_at!"
            FROM blacklist
            ORDER BY domain"#
        )
        .fetch_all(&self.pool)
        .await?;

        Ok(rows.into_iter().map(ListEntry::from).collect())
    }

    async fn load_all(&self) -> Result<Vec<Name>> {
        let rows = sqlx::query_as!(
            ListRow,
            r#"SELECT
                id          AS "id!",
                domain,
                created_at  AS "created_at!"
            FROM blacklist"#
        )
        .fetch_all(&self.pool)
        .await?;

        rows.into_iter()
            .map(|row| {
                Name::from_str(&row.domain)
                    .map_err(|e| Error::Decode(format!("stored domain {:?}: {e}", row.domain)))
            })
            .collect()
    }
}

// ── SqliteAllowlistRepo ───────────────────────────────────────────────────────

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

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

impl AllowlistRepository for SqliteAllowlistRepo {
    async fn add(&self, domain: &str) -> Result<()> {
        let normalized = normalize(domain)?;
        sqlx::query!(
            "INSERT INTO allowlist (domain) VALUES (?) ON CONFLICT(domain) DO NOTHING",
            normalized,
        )
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn remove(&self, domain: &str) -> Result<()> {
        let normalized = normalize(domain)?;
        sqlx::query!("DELETE FROM allowlist WHERE domain = ?", normalized)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    async fn list(&self) -> Result<Vec<ListEntry>> {
        let rows = sqlx::query_as!(
            ListRow,
            r#"SELECT
                id          AS "id!",
                domain,
                created_at  AS "created_at!"
            FROM allowlist
            ORDER BY domain"#
        )
        .fetch_all(&self.pool)
        .await?;

        Ok(rows.into_iter().map(ListEntry::from).collect())
    }

    async fn load_all(&self) -> Result<Vec<Name>> {
        let rows = sqlx::query_as!(
            ListRow,
            r#"SELECT
                id          AS "id!",
                domain,
                created_at  AS "created_at!"
            FROM allowlist"#
        )
        .fetch_all(&self.pool)
        .await?;

        rows.into_iter()
            .map(|row| {
                Name::from_str(&row.domain)
                    .map_err(|e| Error::Decode(format!("stored domain {:?}: {e}", row.domain)))
            })
            .collect()
    }
}

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

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::*;
    use crate::storage::Db;
    use tempfile::TempDir;

    // ── Helpers ───────────────────────────────────────────────────────────────

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

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

    // ── normalize helper ──────────────────────────────────────────────────────

    #[test]
    fn normalize_lowercases_and_adds_dot() {
        let result = normalize("Ads.Example.COM").unwrap();
        assert_eq!(result, "ads.example.com.");
    }

    #[test]
    fn normalize_already_normalized_is_idempotent() {
        let result = normalize("ads.example.com.").unwrap();
        assert_eq!(result, "ads.example.com.");
    }

    #[test]
    fn normalize_invalid_domain_returns_error() {
        let err = normalize("foo..bar").unwrap_err();
        assert!(
            matches!(err, Error::InvalidDomain(_)),
            "expected InvalidDomain, got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("foo..bar"),
            "error must mention the bad input: {msg}"
        );
    }

    // ── BlacklistRepository ───────────────────────────────────────────────────

    #[tokio::test]
    async fn blacklist_add_then_list_round_trips() {
        let (_dir, repo) = open_blacklist_repo().await;
        repo.add("ads.example.com").await.expect("add");
        let entries = repo.list().await.expect("list");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].domain, "ads.example.com.");
        assert!(entries[0].id > 0);
        assert!(entries[0].created_at > 0);
    }

    #[tokio::test]
    async fn blacklist_add_then_load_all_round_trips() {
        let (_dir, repo) = open_blacklist_repo().await;
        repo.add("tracker.example.org").await.expect("add");
        let names = repo.load_all().await.expect("load_all");
        assert_eq!(names.len(), 1);
        assert_eq!(names[0].as_str(), "tracker.example.org.");
    }

    #[tokio::test]
    async fn blacklist_mixed_case_input_normalizes() {
        let (_dir, repo) = open_blacklist_repo().await;
        repo.add("Ads.Example.COM").await.expect("add mixed-case");

        let names = repo.load_all().await.expect("load_all");
        assert_eq!(names.len(), 1);
        // The stored Name must equal the normalized form regardless of casing.
        let expected: Name = "ads.example.com".parse().unwrap();
        assert_eq!(
            names[0], expected,
            "stored name must normalize to ads.example.com."
        );

        // A lookup with different casing must match.
        let lookup: Name = "ADS.EXAMPLE.COM".parse().unwrap();
        let set: HashSet<Name> = names.into_iter().collect();
        assert!(
            set.contains(&lookup),
            "case-insensitive HashSet lookup must find the stored name"
        );
    }

    #[tokio::test]
    async fn blacklist_duplicate_add_is_noop() {
        let (_dir, repo) = open_blacklist_repo().await;
        repo.add("ads.example.com").await.expect("first add");
        // Second add must not error and must not create a duplicate.
        repo.add("ads.example.com")
            .await
            .expect("duplicate add must not error");
        let entries = repo.list().await.expect("list");
        assert_eq!(entries.len(), 1, "exactly one row after duplicate add");
    }

    #[tokio::test]
    async fn blacklist_duplicate_add_different_case_is_noop() {
        let (_dir, repo) = open_blacklist_repo().await;
        repo.add("ads.example.com").await.expect("first add");
        // Mixed-case duplicate normalizes to the same domain → idempotent.
        repo.add("ADS.EXAMPLE.COM")
            .await
            .expect("mixed-case duplicate add must not error");
        let entries = repo.list().await.expect("list");
        assert_eq!(entries.len(), 1, "one row after mixed-case duplicate add");
    }

    #[tokio::test]
    async fn blacklist_remove_deletes_entry() {
        let (_dir, repo) = open_blacklist_repo().await;
        repo.add("ads.example.com").await.expect("add");
        repo.remove("ads.example.com").await.expect("remove");
        let entries = repo.list().await.expect("list");
        assert!(entries.is_empty(), "entry must be gone after remove");
    }

    #[tokio::test]
    async fn blacklist_remove_nonexistent_is_noop() {
        let (_dir, repo) = open_blacklist_repo().await;
        // Removing something that was never added must not error.
        repo.remove("nothere.example.com")
            .await
            .expect("remove non-existent must not error");
    }

    #[tokio::test]
    async fn blacklist_list_ordered_by_domain() {
        let (_dir, repo) = open_blacklist_repo().await;
        repo.add("zzz.example.com").await.expect("add zzz");
        repo.add("aaa.example.com").await.expect("add aaa");
        repo.add("mmm.example.com").await.expect("add mmm");

        let entries = repo.list().await.expect("list");
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].domain, "aaa.example.com.");
        assert_eq!(entries[1].domain, "mmm.example.com.");
        assert_eq!(entries[2].domain, "zzz.example.com.");
    }

    #[tokio::test]
    async fn blacklist_invalid_domain_returns_error() {
        let (_dir, repo) = open_blacklist_repo().await;
        let err = repo.add("foo..bar").await.unwrap_err();
        assert!(
            matches!(err, Error::InvalidDomain(_)),
            "invalid domain must produce InvalidDomain error, got {err:?}"
        );
    }

    // ── AllowlistRepository ───────────────────────────────────────────────────

    #[tokio::test]
    async fn allowlist_add_then_list_round_trips() {
        let (_dir, repo) = open_allowlist_repo().await;
        repo.add("safe.example.com").await.expect("add");
        let entries = repo.list().await.expect("list");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].domain, "safe.example.com.");
    }

    #[tokio::test]
    async fn allowlist_add_then_load_all_round_trips() {
        let (_dir, repo) = open_allowlist_repo().await;
        repo.add("allow.example.net").await.expect("add");
        let names = repo.load_all().await.expect("load_all");
        assert_eq!(names.len(), 1);
        assert_eq!(names[0].as_str(), "allow.example.net.");
    }

    #[tokio::test]
    async fn allowlist_mixed_case_input_normalizes() {
        let (_dir, repo) = open_allowlist_repo().await;
        repo.add("Safe.EXAMPLE.Net").await.expect("add");
        let names = repo.load_all().await.expect("load_all");
        assert_eq!(names.len(), 1);
        let expected: Name = "safe.example.net".parse().unwrap();
        assert_eq!(names[0], expected);
    }

    #[tokio::test]
    async fn allowlist_duplicate_add_is_noop() {
        let (_dir, repo) = open_allowlist_repo().await;
        repo.add("safe.example.com").await.expect("first add");
        repo.add("safe.example.com")
            .await
            .expect("duplicate add must not error");
        let entries = repo.list().await.expect("list");
        assert_eq!(entries.len(), 1, "exactly one row after duplicate add");
    }

    #[tokio::test]
    async fn allowlist_remove_deletes_entry() {
        let (_dir, repo) = open_allowlist_repo().await;
        repo.add("safe.example.com").await.expect("add");
        repo.remove("safe.example.com").await.expect("remove");
        let entries = repo.list().await.expect("list");
        assert!(entries.is_empty());
    }

    #[tokio::test]
    async fn allowlist_remove_nonexistent_is_noop() {
        let (_dir, repo) = open_allowlist_repo().await;
        repo.remove("nothere.example.com")
            .await
            .expect("remove non-existent must not error");
    }

    #[tokio::test]
    async fn allowlist_invalid_domain_returns_error() {
        let (_dir, repo) = open_allowlist_repo().await;
        let err = repo.add("bad..domain").await.unwrap_err();
        assert!(
            matches!(err, Error::InvalidDomain(_)),
            "invalid domain must produce InvalidDomain error, got {err:?}"
        );
    }

    // ── Isolation: blacklist and allowlist are independent ────────────────────

    #[tokio::test]
    async fn blacklist_and_allowlist_are_independent() {
        let dir = TempDir::new().expect("temp dir");
        let path = dir.path().join("test.db");
        let db = Db::connect(&path).await.expect("connect");

        let bl = SqliteBlacklistRepo::new(db.pool().clone());
        let al = SqliteAllowlistRepo::new(db.pool().clone());

        bl.add("domain.example.com")
            .await
            .expect("add to blacklist");
        al.add("domain.example.com")
            .await
            .expect("add to allowlist");

        // Both tables contain one entry.
        assert_eq!(bl.list().await.expect("bl list").len(), 1);
        assert_eq!(al.list().await.expect("al list").len(), 1);

        // Removing from one does not affect the other.
        bl.remove("domain.example.com")
            .await
            .expect("remove from blacklist");
        assert!(bl.list().await.expect("bl list after remove").is_empty());
        assert_eq!(
            al.list().await.expect("al list after bl remove").len(),
            1,
            "allowlist must be unaffected by blacklist removal"
        );
    }
}