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
//! Conditional-forward zone management (SPEC ยง9).
//!
//! List the private reverse zones (and any custom zones), set each zone's
//! router/DHCP `target` resolver, and toggle whether it participates in routing.
//! A convenience "forward all to" action points every seeded reverse zone at one
//! target in a single click โ€” the common LAN setup.
//!
//! This module only persists configuration; the resolver hot path that actually
//! routes queries under an enabled zone to its target is wired up in E13.4, which
//! will rebuild its live forwarder snapshot from these rows on every change.

use std::net::{IpAddr, SocketAddr};

use askama::Template;
use askama_web::WebTemplate;
use axum::{
    extract::State,
    http::StatusCode,
    response::{IntoResponse, Redirect, Response},
};
use serde::Deserialize;

use crate::{
    storage::forward_zones::ForwardZoneRepository,
    web::{
        AppState, Chrome,
        auth::CurrentUser,
        render::{WebError, WebResult},
    },
};

impl AppState {
    /// Rebuild the live conditional-forward zone set from the enabled-and-targeted
    /// rows and swap it into the shared resolver state, so a zone edit takes
    /// effect immediately (mirrors [`rebuild_upstream_pool`](Self::rebuild_upstream_pool)).
    pub(crate) async fn rebuild_forward_zones(&self) -> WebResult<()> {
        let rows = self.db.forward_zones().list_enabled().await?;
        let set = crate::resolver::forward_zone::ForwardZoneSet::build(&rows, &self.tracker).await;
        self.resolver.store_forward_zones(set);
        // A zone edit changes *which authority answers* a reverse name, so flush
        // the shared DNS response cache: an answer cached via the default
        // upstream (e.g. an AS112 NXDOMAIN for a private reverse zone) would
        // otherwise be served by the cache layer โ€” which short-circuits before
        // the forward-target tag is consulted โ€” in place of the newly-routed
        // zone target until it expired.
        self.resolver.cache().clear();
        // The reverse-lookup decoration (E14) is derived from those same answers
        // and shares the DNS cache, so drop its cached results too; the next
        // render re-resolves against the fresh zone routing.
        self.reverse.clear();
        Ok(())
    }

    async fn render_forwarding(
        &self,
        user: &CurrentUser,
        error: Option<String>,
    ) -> WebResult<ForwardingPageTemplate> {
        let zones = self
            .db
            .forward_zones()
            .list()
            .await?
            .into_iter()
            .map(|z| ForwardZoneView {
                id: z.id,
                zone_suffix: z.zone_suffix,
                target: z.target.unwrap_or_default(),
                enabled: z.enabled,
            })
            .collect();
        Ok(ForwardingPageTemplate {
            chrome: self.chrome("forwarding", user).await,
            zones,
            error,
        })
    }

    /// `GET /forwarding`.
    pub async fn forwarding_page(
        user: CurrentUser,
        State(state): State<AppState>,
    ) -> WebResult<Response> {
        Ok(state.render_forwarding(&user, None).await?.into_response())
    }

    /// `POST /forwarding/target` โ€” set or clear one zone's target.
    pub async fn forward_zone_set_target(
        user: CurrentUser,
        State(state): State<AppState>,
        axum::Form(form): axum::Form<SetTargetForm>,
    ) -> WebResult<Response> {
        match state.set_zone_target(form).await {
            Ok(()) => Ok(Redirect::to("/forwarding").into_response()),
            Err(WebError::BadRequest(msg)) => {
                let page = state.render_forwarding(&user, Some(msg)).await?;
                Ok((StatusCode::BAD_REQUEST, page).into_response())
            }
            Err(e) => Err(e),
        }
    }

    async fn set_zone_target(&self, form: SetTargetForm) -> WebResult<()> {
        let target = normalize_target(&form.target)?;
        self.db
            .forward_zones()
            .set_target(form.id, target.as_deref())
            .await?;
        self.rebuild_forward_zones().await
    }

    /// `POST /forwarding/toggle` โ€” enable/disable one zone.
    pub async fn forward_zone_toggle(
        _user: CurrentUser,
        State(state): State<AppState>,
        axum::Form(form): axum::Form<ToggleZoneForm>,
    ) -> WebResult<Response> {
        state
            .db
            .forward_zones()
            .set_enabled(form.id, form.enabled)
            .await?;
        state.rebuild_forward_zones().await?;
        Ok(Redirect::to("/forwarding").into_response())
    }

    /// `POST /forwarding/apply-all` โ€” point every zone at one target and enable
    /// them all.  The one-click LAN reverse-DNS setup.
    pub async fn forward_zone_apply_all(
        user: CurrentUser,
        State(state): State<AppState>,
        axum::Form(form): axum::Form<ApplyAllForm>,
    ) -> WebResult<Response> {
        match state.apply_target_to_all(form).await {
            Ok(()) => Ok(Redirect::to("/forwarding").into_response()),
            Err(WebError::BadRequest(msg)) => {
                let page = state.render_forwarding(&user, Some(msg)).await?;
                Ok((StatusCode::BAD_REQUEST, page).into_response())
            }
            Err(e) => Err(e),
        }
    }

    async fn apply_target_to_all(&self, form: ApplyAllForm) -> WebResult<()> {
        let Some(target) = normalize_target(&form.target)? else {
            return Err(WebError::bad_request(
                "Enter the router/DHCP resolver address to forward all reverse zones to.",
            ));
        };
        let repo = self.db.forward_zones();
        for zone in repo.list().await? {
            repo.set_target(zone.id, Some(&target)).await?;
            repo.set_enabled(zone.id, true).await?;
        }
        self.rebuild_forward_zones().await
    }
}

/// Validate and normalize a target resolver string.
///
/// Accepts a bare IP (`10.0.0.1`) or an `IP:port` socket address
/// (`10.0.0.1:5353`).  An empty/blank string normalizes to `None` (clears the
/// target).  Anything else is a [`WebError::BadRequest`] so a zone never stores
/// an address the resolver could not parse.
fn normalize_target(raw: &str) -> WebResult<Option<String>> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }
    if trimmed.parse::<IpAddr>().is_ok() || trimmed.parse::<SocketAddr>().is_ok() {
        Ok(Some(trimmed.to_owned()))
    } else {
        Err(WebError::bad_request(
            "Target must be an IP address (optionally with :port), e.g. 192.168.1.1 or 192.168.1.1:5353.",
        ))
    }
}

/// Set-target form payload.
#[derive(Debug, Deserialize)]
pub struct SetTargetForm {
    id: i64,
    #[serde(default)]
    target: String,
}

/// Enable/disable form payload.
#[derive(Debug, Deserialize)]
pub struct ToggleZoneForm {
    id: i64,
    enabled: bool,
}

/// Apply-to-all form payload.
#[derive(Debug, Deserialize)]
pub struct ApplyAllForm {
    #[serde(default)]
    target: String,
}

/// One forward-zone row for display.
struct ForwardZoneView {
    id: i64,
    zone_suffix: String,
    target: String,
    enabled: bool,
}

/// The forwarding management page.
#[derive(Template, WebTemplate)]
#[template(path = "forwarding.html")]
struct ForwardingPageTemplate {
    chrome: Chrome,
    zones: Vec<ForwardZoneView>,
    error: Option<String>,
}

// โ”€โ”€ Tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

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

    async fn state() -> (TempDir, AppState) {
        let (dir, db) = crate::test_support::temp_db().await;
        (dir, AppState::for_test(db).await)
    }

    // โ”€โ”€ normalize_target โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    #[test]
    fn normalize_target_accepts_ip_and_socket() {
        assert_eq!(
            normalize_target("192.168.1.1").unwrap().as_deref(),
            Some("192.168.1.1")
        );
        assert_eq!(
            normalize_target(" 10.0.0.1:5353 ").unwrap().as_deref(),
            Some("10.0.0.1:5353")
        );
        assert_eq!(
            normalize_target("fd00::1").unwrap().as_deref(),
            Some("fd00::1")
        );
    }

    #[test]
    fn normalize_target_blank_is_none() {
        assert!(normalize_target("   ").unwrap().is_none());
    }

    #[test]
    fn normalize_target_rejects_garbage() {
        assert!(matches!(
            normalize_target("router.local"),
            Err(WebError::BadRequest(_))
        ));
    }

    // โ”€โ”€ handlers (via the inner helpers) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    #[tokio::test]
    async fn set_target_then_toggle_persists() {
        let (_d, st) = state().await;
        let zones = st.db.forward_zones().list().await.unwrap();
        let id = zones
            .iter()
            .find(|z| z.zone_suffix == "168.192.in-addr.arpa")
            .unwrap()
            .id;

        st.set_zone_target(SetTargetForm {
            id,
            target: "192.168.1.1".to_owned(),
        })
        .await
        .expect("set target");
        st.db
            .forward_zones()
            .set_enabled(id, true)
            .await
            .expect("enable");

        let enabled = st.db.forward_zones().list_enabled().await.unwrap();
        assert_eq!(enabled.len(), 1);
        assert_eq!(enabled[0].target.as_deref(), Some("192.168.1.1"));
    }

    /// A zone edit flushes the shared DNS response cache, so an answer cached
    /// via the default upstream (e.g. an NXDOMAIN for a private reverse zone)
    /// stops being served by the cache layer โ€” which short-circuits before the
    /// forward-target tag โ€” in place of the newly-routed zone target.
    #[tokio::test]
    async fn zone_edit_flushes_the_dns_cache() {
        use crate::codec::{
            header::{Header, Rcode},
            message::{Qclass, Qtype, Question},
            name::Name,
            ttl::TtlScan,
            writer::Writer,
        };

        let (_d, st) = state().await;

        // Seed a cached PTR answer for a private reverse name, as if a prior
        // query had been forwarded to the default upstream and cached.
        let qname: Name = "1.1.168.192.in-addr.arpa".parse().unwrap();
        let question = Question {
            name: qname.clone(),
            qtype: Qtype::Ptr,
            qclass: Qclass::In,
        };
        let mut w = Writer::with_capacity(64);
        Header::new(0x1234)
            .with_qr(true)
            .with_rcode(Rcode::NoError)
            .with_qdcount(1)
            .with_ancount(0)
            .write(&mut w);
        qname.write(&mut w);
        w.write_u16(u16::from(Qtype::Ptr));
        w.write_u16(1);
        let bytes = w.finish();
        let offsets = TtlScan::scan(&bytes)
            .map(|s| s.ttl_offsets)
            .unwrap_or_default();
        st.resolver
            .cache()
            .insert(question.clone(), bytes, offsets, 300)
            .await;
        assert!(
            st.resolver.cache().get(&question, 0x1).await.is_some(),
            "precondition: the stale answer is cached"
        );

        // Configure a forward zone covering that reverse name.
        let id = st
            .db
            .forward_zones()
            .list()
            .await
            .unwrap()
            .into_iter()
            .find(|z| z.zone_suffix == "168.192.in-addr.arpa")
            .unwrap()
            .id;
        st.set_zone_target(SetTargetForm {
            id,
            target: "192.168.1.1".to_owned(),
        })
        .await
        .expect("set target");

        st.resolver.cache().run_pending_tasks().await;
        assert!(
            st.resolver.cache().get(&question, 0x1).await.is_none(),
            "a zone edit must flush the stale cached answer so it routes to the new target"
        );
    }

    #[tokio::test]
    async fn set_target_rejects_bad_address() {
        let (_d, st) = state().await;
        let id = st.db.forward_zones().list().await.unwrap()[0].id;
        let err = st
            .set_zone_target(SetTargetForm {
                id,
                target: "not-an-ip".to_owned(),
            })
            .await
            .unwrap_err();
        assert!(matches!(err, WebError::BadRequest(_)));
    }

    #[tokio::test]
    async fn apply_all_targets_and_enables_every_zone() {
        let (_d, st) = state().await;
        st.apply_target_to_all(ApplyAllForm {
            target: "192.168.1.1".to_owned(),
        })
        .await
        .expect("apply all");

        let all = st.db.forward_zones().list().await.unwrap();
        let enabled = st.db.forward_zones().list_enabled().await.unwrap();
        assert_eq!(
            enabled.len(),
            all.len(),
            "every zone must be enabled and targeted"
        );
        for z in &enabled {
            assert_eq!(z.target.as_deref(), Some("192.168.1.1"));
        }
    }

    #[tokio::test]
    async fn apply_all_requires_a_target() {
        let (_d, st) = state().await;
        let err = st
            .apply_target_to_all(ApplyAllForm {
                target: "  ".to_owned(),
            })
            .await
            .unwrap_err();
        assert!(matches!(err, WebError::BadRequest(_)));
    }

    #[tokio::test]
    async fn render_lists_seeded_zones() {
        let (_d, st) = state().await;
        let user = CurrentUser {
            user_id: 1,
            session_id: "sess".to_owned(),
        };
        let page = st.render_forwarding(&user, None).await.expect("render");
        assert_eq!(page.zones.len(), 20, "all seeded zones must render");
        assert!(page.zones.iter().all(|z| !z.enabled));
    }
}