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
//! Manual + one-click blacklist / allowlist management (SPEC §9, §5).
//!
//! This module owns the **write-through + snapshot-swap** pattern reused by all
//! list mutations: a change is persisted to SQLite (E3.5) first, then the
//! affected in-memory [`MatchSet`](crate::resolver::matchset::MatchSet) snapshot
//! is rebuilt from the database and atomically swapped into the shared
//! [`ResolverState`](crate::resolver::state::ResolverState) (E4.4), so the
//! change takes effect on the very next query.
//!
//! The **one-click** actions from the live query log are keyed purely on each
//! row's [`Outcome`](crate::resolver::pipeline::Outcome) (not on the domain's
//! current list membership):
//! - a resolved row (cached/forwarded) offers *Block* (add to the admin
//!   blacklist),
//! - a blocked row offers *Unblock* — [`AppState::unblock`] removes it from the
//!   admin blacklist if present, otherwise allowlists it to suppress a blocklist
//!   hit,
//! - every other outcome (local answers, errors) renders no action.
//!
//! The full management screens (add/remove/list pages) build on the same core
//! helpers in E8.8.

use std::convert::Infallible;

use askama::Template;
use askama_web::WebTemplate;
use axum::{
    extract::{Query, State},
    response::{IntoResponse, Redirect, Response, Sse, sse::Event},
};
use datastar::prelude::PatchElements;
use serde::Deserialize;

use crate::{
    codec::name::Name,
    storage::lists::{
        AllowlistRepository, BlacklistRepository, SqliteAllowlistRepo, SqliteBlacklistRepo,
    },
    web::{
        AppState,
        auth::CurrentUser,
        render::{DomainDisplay, WebError},
    },
};

impl AppState {
    // ── Write-through + snapshot-swap core ────────────────────────────────────

    /// Rebuild the in-memory admin blacklist snapshot from the database.
    async fn reload_blacklist(&self) -> Result<(), WebError> {
        let names = SqliteBlacklistRepo::new(self.db.pool().clone())
            .load_all()
            .await?;
        self.resolver.blacklist().store(names.into_iter().collect());
        Ok(())
    }

    /// Rebuild the in-memory allowlist snapshot from the database.
    async fn reload_allowlist(&self) -> Result<(), WebError> {
        let names = SqliteAllowlistRepo::new(self.db.pool().clone())
            .load_all()
            .await?;
        self.resolver.allowlist().store(names.into_iter().collect());
        Ok(())
    }

    /// Add `domain` to the admin blacklist (write-through, then swap).
    pub(crate) async fn add_to_blacklist(&self, domain: &str) -> Result<(), WebError> {
        SqliteBlacklistRepo::new(self.db.pool().clone())
            .add(domain)
            .await?;
        self.reload_blacklist().await
    }

    /// Remove `domain` from the admin blacklist (write-through, then swap).
    pub(crate) async fn remove_from_blacklist(&self, domain: &str) -> Result<(), WebError> {
        SqliteBlacklistRepo::new(self.db.pool().clone())
            .remove(domain)
            .await?;
        self.reload_blacklist().await
    }

    /// Add `domain` to the allowlist (write-through, then swap).
    pub(crate) async fn add_to_allowlist(&self, domain: &str) -> Result<(), WebError> {
        SqliteAllowlistRepo::new(self.db.pool().clone())
            .add(domain)
            .await?;
        self.reload_allowlist().await
    }

    /// Remove `domain` from the allowlist (write-through, then swap).
    pub(crate) async fn remove_from_allowlist(&self, domain: &str) -> Result<(), WebError> {
        SqliteAllowlistRepo::new(self.db.pool().clone())
            .remove(domain)
            .await?;
        self.reload_allowlist().await
    }

    /// Make `domain` resolve again.
    ///
    /// If it sits on the admin blacklist we remove it; otherwise it was blocked
    /// by an aggregated blocklist, which the allowlist suppresses.  This keeps a
    /// single Unblock action correct for both kinds of block.
    pub(crate) async fn unblock(&self, domain: &str) -> Result<(), WebError> {
        let on_blacklist = domain
            .parse::<Name>()
            .is_ok_and(|n| self.resolver.blacklist().contains(&n));
        if on_blacklist {
            self.remove_from_blacklist(domain).await
        } else {
            self.add_to_allowlist(domain).await
        }
    }

    // ── One-click handlers (from the live log) ────────────────────────────────

    /// `POST /log/block?domain=…` — block a currently-resolving domain by adding
    /// it to the admin blacklist.
    pub async fn log_block(
        _user: CurrentUser,
        State(state): State<AppState>,
        Query(q): Query<ActionQuery>,
    ) -> Response {
        match state.add_to_blacklist(&q.domain).await {
            Ok(()) => toast(format!(
                "Blocked {} — it is blocked on the next query.",
                q.domain.display_domain()
            )),
            Err(e) => e.into_response(),
        }
    }

    /// `POST /log/unblock?domain=…` — make a blocked domain resolve again.
    ///
    /// If the domain sits on the admin blacklist we remove it; otherwise it was
    /// blocked by an aggregated blocklist, which the allowlist suppresses.  This
    /// keeps a single Unblock action correct for both kinds of block.
    pub async fn log_unblock(
        _user: CurrentUser,
        State(state): State<AppState>,
        Query(q): Query<ActionQuery>,
    ) -> Response {
        match state.unblock(&q.domain).await {
            Ok(()) => toast(format!(
                "Unblocked {} — it resolves on the next query.",
                q.domain.display_domain()
            )),
            Err(e) => e.into_response(),
        }
    }
}

// ── Management screens (E8.8) ─────────────────────────────────────────────────

/// Which explicit list a management page operates on.
#[derive(Debug, Clone, Copy)]
enum ListKind {
    Blacklist,
    Allowlist,
}

impl ListKind {
    fn title(self) -> &'static str {
        match self {
            Self::Blacklist => "Blacklist",
            Self::Allowlist => "Allowlist",
        }
    }
    fn active(self) -> &'static str {
        match self {
            Self::Blacklist => "blacklist",
            Self::Allowlist => "allowlist",
        }
    }
    fn base_path(self) -> &'static str {
        match self {
            Self::Blacklist => "/blacklist",
            Self::Allowlist => "/allowlist",
        }
    }
    fn description(self) -> &'static str {
        match self {
            Self::Blacklist => {
                "Domains you explicitly block. Highest precedence — wins over the allowlist and blocklists."
            }
            Self::Allowlist => {
                "Domains you explicitly allow. An exception that suppresses blocklist matches (but not the blacklist)."
            }
        }
    }
}

impl AppState {
    async fn list_entries(&self, kind: ListKind) -> Result<Vec<String>, WebError> {
        let entries = match kind {
            ListKind::Blacklist => {
                SqliteBlacklistRepo::new(self.db.pool().clone())
                    .list()
                    .await?
            }
            ListKind::Allowlist => {
                SqliteAllowlistRepo::new(self.db.pool().clone())
                    .list()
                    .await?
            }
        };
        // Show (and round-trip on remove) the bare domain; the stored value keeps
        // its canonical trailing dot.
        Ok(entries
            .into_iter()
            .map(|e| e.domain.display_domain().to_owned())
            .collect())
    }

    async fn list_add(&self, kind: ListKind, domain: &str) -> Result<(), WebError> {
        match kind {
            ListKind::Blacklist => self.add_to_blacklist(domain).await,
            ListKind::Allowlist => self.add_to_allowlist(domain).await,
        }
    }

    async fn list_remove(&self, kind: ListKind, domain: &str) -> Result<(), WebError> {
        match kind {
            ListKind::Blacklist => self.remove_from_blacklist(domain).await,
            ListKind::Allowlist => self.remove_from_allowlist(domain).await,
        }
    }

    /// Render a list management page, optionally with an inline error banner.
    async fn render_list(
        &self,
        user: &CurrentUser,
        kind: ListKind,
        error: Option<String>,
    ) -> Result<ListPageTemplate, WebError> {
        Ok(ListPageTemplate {
            chrome: self.chrome(kind.active(), user).await,
            title: kind.title(),
            description: kind.description(),
            base_path: kind.base_path(),
            entries: self.list_entries(kind).await?,
            error,
        })
    }

    /// Shared GET handler body for a list page.
    async fn list_page(&self, user: &CurrentUser, kind: ListKind) -> Response {
        match self.render_list(user, kind, None).await {
            Ok(t) => t.into_response(),
            Err(e) => e.into_response(),
        }
    }

    /// Shared POST-add body: write through, then PRG-redirect on success or
    /// re-render with an inline error on a bad domain.
    async fn list_add_handler(&self, user: &CurrentUser, kind: ListKind, domain: &str) -> Response {
        match self.list_add(kind, domain).await {
            Ok(()) => Redirect::to(kind.base_path()).into_response(),
            Err(WebError::BadRequest(msg)) => match self.render_list(user, kind, Some(msg)).await {
                Ok(t) => (axum::http::StatusCode::BAD_REQUEST, t).into_response(),
                Err(e) => e.into_response(),
            },
            Err(e) => e.into_response(),
        }
    }

    /// Shared POST-remove body: write through, then PRG-redirect.
    async fn list_remove_handler(&self, kind: ListKind, domain: &str) -> Response {
        match self.list_remove(kind, domain).await {
            Ok(()) => Redirect::to(kind.base_path()).into_response(),
            Err(e) => e.into_response(),
        }
    }

    /// `GET /blacklist`.
    pub async fn blacklist_page(user: CurrentUser, State(state): State<AppState>) -> Response {
        state.list_page(&user, ListKind::Blacklist).await
    }
    /// `POST /blacklist/add`.
    pub async fn blacklist_add(
        user: CurrentUser,
        State(state): State<AppState>,
        axum::Form(form): axum::Form<DomainForm>,
    ) -> Response {
        state
            .list_add_handler(&user, ListKind::Blacklist, &form.domain)
            .await
    }
    /// `POST /blacklist/remove`.
    pub async fn blacklist_remove(
        _user: CurrentUser,
        State(state): State<AppState>,
        axum::Form(form): axum::Form<DomainForm>,
    ) -> Response {
        state
            .list_remove_handler(ListKind::Blacklist, &form.domain)
            .await
    }
    /// `GET /allowlist`.
    pub async fn allowlist_page(user: CurrentUser, State(state): State<AppState>) -> Response {
        state.list_page(&user, ListKind::Allowlist).await
    }
    /// `POST /allowlist/add`.
    pub async fn allowlist_add(
        user: CurrentUser,
        State(state): State<AppState>,
        axum::Form(form): axum::Form<DomainForm>,
    ) -> Response {
        state
            .list_add_handler(&user, ListKind::Allowlist, &form.domain)
            .await
    }
    /// `POST /allowlist/remove`.
    pub async fn allowlist_remove(
        _user: CurrentUser,
        State(state): State<AppState>,
        axum::Form(form): axum::Form<DomainForm>,
    ) -> Response {
        state
            .list_remove_handler(ListKind::Allowlist, &form.domain)
            .await
    }
}

/// `domain` form field (the `csrf_token` field is consumed by the CSRF layer
/// and ignored here).
#[derive(Debug, Deserialize)]
pub struct DomainForm {
    pub domain: String,
}

/// Shared management page for the blacklist and allowlist.
#[derive(Template, WebTemplate)]
#[template(path = "list_page.html")]
struct ListPageTemplate {
    chrome: crate::web::Chrome,
    title: &'static str,
    description: &'static str,
    base_path: &'static str,
    entries: Vec<String>,
    error: Option<String>,
}

/// Query parameters for the one-click log actions: just the target `domain`.
#[derive(Debug, Deserialize)]
pub struct ActionQuery {
    pub domain: String,
}

/// Build the one-shot Datastar SSE response confirming a one-click action by
/// patching the `#sgt-toast` notice.  The button itself is not touched — its
/// action is fixed by the row's outcome, and the toast is the click feedback.
fn toast(message: String) -> Response {
    let html = format!(
        r#"<div id="sgt-toast" class="sgt-toast sgt-notice--ok" role="status">{}</div>"#,
        crate::web::render::html_escape(&message)
    );
    let event = PatchElements::new(html).write_as_axum_sse_event();

    Sse::new(async_stream::stream! {
        yield Ok::<Event, Infallible>(event);
    })
    .into_response()
}

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

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

    async fn state() -> (TempDir, AppState) {
        let dir = TempDir::new().unwrap();
        let db = Db::connect(dir.path().join("t.db")).await.unwrap();
        let st = AppState::for_test(db).await;
        (dir, st)
    }

    fn name(s: &str) -> Name {
        s.parse().unwrap()
    }

    #[tokio::test]
    async fn add_to_blacklist_writes_through_and_swaps() {
        let (_d, st) = state().await;
        assert!(!st.resolver.blacklist().contains(&name("ads.example.com")));

        st.add_to_blacklist("ads.example.com").await.expect("add");

        // In-memory set updated immediately ...
        assert!(st.resolver.blacklist().contains(&name("ads.example.com")));
        // ... and persisted.
        let names = SqliteBlacklistRepo::new(st.db.pool().clone())
            .load_all()
            .await
            .unwrap();
        assert!(names.contains(&name("ads.example.com")));
    }

    #[tokio::test]
    async fn add_to_allowlist_writes_through_and_swaps() {
        let (_d, st) = state().await;
        st.add_to_allowlist("safe.example.com").await.expect("add");
        assert!(st.resolver.allowlist().contains(&name("safe.example.com")));
    }

    #[tokio::test]
    async fn invalid_domain_is_bad_request() {
        let (_d, st) = state().await;
        let err = st.add_to_blacklist("not..valid").await.unwrap_err();
        assert!(matches!(err, WebError::BadRequest(_)));
    }

    #[tokio::test]
    async fn unblock_removes_an_admin_blacklisted_domain() {
        let (_d, st) = state().await;
        st.add_to_blacklist("ads.example.com").await.expect("add");
        assert!(st.resolver.blacklist().contains(&name("ads.example.com")));

        st.unblock("ads.example.com").await.expect("unblock");

        // Removed from the blacklist; not shunted onto the allowlist.
        assert!(!st.resolver.blacklist().contains(&name("ads.example.com")));
        assert!(!st.resolver.allowlist().contains(&name("ads.example.com")));
    }

    #[tokio::test]
    async fn unblock_allowlists_a_blocklist_blocked_domain() {
        let (_d, st) = state().await;
        // Not on the admin blacklist → unblock suppresses the blocklist hit via
        // the allowlist.
        st.unblock("tracker.example.com").await.expect("unblock");
        assert!(
            st.resolver
                .allowlist()
                .contains(&name("tracker.example.com"))
        );
    }
}