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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Forward inner service: SPEC §5 steps 8–9, §8.
//!
//! [`ForwardService`] is the **leaf** of the DNS pipeline — the innermost
//! [`tower::Service`], reached on a cache miss (the [`CacheService`] sits
//! directly above it).  It:
//!
//! 1. Forwards the query to an upstream resolver via [`SharedUpstreamPool`].
//! 2. Decides the cache-store policy (positive vs. negative vs. not-cached) and
//!    emits it as a [`CacheDirective`] — the [`CacheService`] executes the store.
//! 3. Patches the transaction ID in the reply back to the client's query ID.
//! 4. Returns [`Outcome::Forwarded`] on success or [`Outcome::Servfail`] when
//!    all upstreams have failed, bundled with the directive in a [`ForwardOutput`].
//!
//! # Cache-store policy (SPEC §8)
//!
//! | Response type | Directive | Expiry |
//! |---|---|---|
//! | Positive (has real RRs) | `Store` | `scan.min_ttl` |
//! | Positive (no real TTL RRs) | `Skip` | — |
//! | Negative with SOA | `Store` | `min(negative_ttl, cap)` |
//! | Negative without SOA | `Skip` | — |
//! | Scan error | `Skip` | — |
//!
//! The policy lives here because the upstream metadata (TTL-field offsets, the
//! positive min TTL, the RFC 2308 negative TTL) is only available at this leaf.
//! The [`CacheService`] owns the mechanism and clamps the expiry to
//! `[cache_min_ttl, cache_max_ttl]` on insert.
//!
//! # Transaction-ID patching
//!
//! The upstream bytes carry hickory's internal transaction ID, not the client's.
//! [`DnsMessageBytes::with_txn_id`] copies the bytes and overwrites the first two
//! bytes with the client's query ID for the reply.  The directive caches the **un-patched**
//! upstream bytes; patching (and TTL decrement) happens at serve time in
//! [`DnsCache::get`](crate::resolver::cache::DnsCache::get).
//!
//! [`CacheService`]: crate::resolver::pipeline::cache_layer::CacheService

use std::{
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use bytes::{Bytes, BytesMut};
use tower::Service;

use crate::{
    codec::{
        header::Rcode,
        synth::{EdnsInfo, Response},
        ttl::TtlScan,
    },
    resolver::{
        pipeline::{
            BoxError, DnsRequest, Outcome, PipelineResponse,
            cache_layer::{CacheDirective, ForwardOutput},
        },
        state::ResolverState,
        upstream::SharedUpstreamPool,
    },
};

// ── ForwardService ────────────────────────────────────────────────────────────

/// The innermost leaf [`tower::Service`] of the DNS pipeline.
///
/// Forwards the query to the upstream pool, decides the cache-store policy
/// (emitted as a [`CacheDirective`] for the cache layer to execute), patches
/// the transaction ID for the client reply, and returns a [`ForwardOutput`].
///
/// Both fields are [`Arc`]-wrapped so the service is cheaply [`Clone`]able —
/// a requirement because the [`CacheService`](super::cache_layer::CacheService)
/// that wraps it must be `Clone`.
#[derive(Clone)]
pub struct ForwardService {
    pool: Arc<SharedUpstreamPool>,
    state: Arc<ResolverState>,
}

impl ForwardService {
    /// Create a new [`ForwardService`].
    pub fn new(pool: Arc<SharedUpstreamPool>, state: Arc<ResolverState>) -> Self {
        Self { pool, state }
    }
}

// ── tower::Service impl ───────────────────────────────────────────────────────

impl Service<DnsRequest> for ForwardService {
    type Response = ForwardOutput;
    type Error = BoxError;
    type Future = Pin<Box<dyn Future<Output = Result<ForwardOutput, BoxError>> + Send>>;

    /// The leaf service is always ready — it has no inner service to poll.
    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: DnsRequest) -> Self::Future {
        // Clone the Arcs into the future. No clone-and-replace dance is needed
        // here because this is a leaf service (no inner service to protect).
        let pool = self.pool.clone();
        let state = self.state.clone();

        Box::pin(async move {
            // Extract owned values before the first await so there are no
            // borrows of `req` across await points.
            let question = req.question().clone();
            let client_id = req.header().id;
            let edns = EdnsInfo::scan(req.query()); // for the SERVFAIL path

            match pool.forward(&question).await {
                Ok(fr) => {
                    // ── Cache-store policy (SPEC §5 step 9, §8) ───────────────
                    //
                    // We decide *whether and for how long* to cache here — the
                    // upstream metadata (TTL-field offsets, positive min TTL,
                    // RFC 2308 negative TTL) lives only at this leaf — and hand
                    // the decision to the cache layer as a `CacheDirective`,
                    // which executes the store. `settings_full()` returns an
                    // owned Arc, safe across awaits.
                    let settings = state.settings_full();
                    // Scan the upstream bytes for the TTL-field offsets and the
                    // positive min TTL (OPT pseudo-RRs already excluded).
                    let scan = TtlScan::scan(&fr.bytes);

                    let directive = if let Ok(s) = scan.as_ref() {
                        let expiry = if fr.is_negative {
                            // Negatives: RFC 2308 negative TTL, capped at the
                            // configured cap. None (no SOA) → do NOT cache.
                            fr.negative_ttl.map(|t| t.min(settings.negative_ttl_cap))
                        } else {
                            // Positives: the scan's min non-OPT RR TTL.
                            // None (no TTL-bearing RRs) → do NOT cache.
                            s.min_ttl
                        };
                        match expiry {
                            Some(expiry) => CacheDirective::Store {
                                bytes: fr.bytes.clone(),
                                ttl_offsets: s.ttl_offsets.clone(),
                                expiry,
                            },
                            None => CacheDirective::Skip,
                        }
                    } else {
                        // Unscannable upstream response — reply but do not cache.
                        CacheDirective::Skip
                    };

                    // Patch the transaction ID for the client reply: the upstream
                    // bytes carry hickory's internal txn-id, not the client's.
                    // (The cache stores the un-patched bytes; DnsCache::get
                    // re-patches per requesting client on serve.)
                    let reply = fr.bytes.with_txn_id(client_id);
                    Ok(ForwardOutput::new(
                        PipelineResponse::new(reply, Outcome::Forwarded),
                        directive,
                    ))
                }
                Err(e) => {
                    // All upstreams failed (or the pool is empty) → SERVFAIL.
                    tracing::warn!(
                        qname = %question.name,
                        qtype = ?question.qtype,
                        error = %e,
                        "all upstreams failed; returning SERVFAIL"
                    );
                    let bytes =
                        Response::error_response(req.query(), Rcode::ServFail, edns.as_ref());
                    Ok(ForwardOutput::new(
                        PipelineResponse::new(bytes, Outcome::Servfail),
                        CacheDirective::Skip,
                    ))
                }
            }
        })
    }
}

// ── DNS message bytes helpers ──────────────────────────────────────────────────

/// Rewrites the transaction id on a raw DNS message buffer.
trait DnsMessageBytes {
    /// Copy the message and overwrite the first two bytes (the DNS transaction
    /// id) with `id` in big-endian order.
    ///
    /// Bounds-guarded: a buffer shorter than 2 bytes is returned unchanged.
    fn with_txn_id(&self, id: u16) -> Bytes;
}

impl DnsMessageBytes for Bytes {
    fn with_txn_id(&self, id: u16) -> Bytes {
        if self.len() < 2 {
            return self.clone();
        }
        let mut buf = BytesMut::from(&self[..]);
        buf[0..2].copy_from_slice(&id.to_be_bytes());
        buf.freeze()
    }
}

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

#[cfg(test)]
mod tests {
    use std::{net::SocketAddr, sync::Arc, time::Duration};

    use bytes::Bytes;
    use hickory_net::proto::op::{Message, MessageType, ResponseCode};
    use hickory_net::proto::rr::rdata::{A, SOA};
    use hickory_net::proto::rr::{Name, RData, Record};
    use tempfile::TempDir;
    use tokio::net::UdpSocket;
    use tokio::time::timeout;
    use tokio_util::task::TaskTracker;
    use tower::ServiceExt as _;

    use super::*;
    use crate::{
        codec::{
            header::Header, message::Query, name::Name as DnsName, reader::Reader, writer::Writer,
        },
        resolver::{
            state::ResolverState,
            upstream::{UpstreamConfig, UpstreamPool, UpstreamTransport},
        },
        storage::Db,
    };

    #[test]
    fn with_txn_id_rewrites_first_two_bytes() {
        let msg = Bytes::from_static(&[0x12, 0x34, 0xAA, 0xBB]);
        let patched = msg.with_txn_id(0xBEEF);
        assert_eq!(&patched[..], &[0xBE, 0xEF, 0xAA, 0xBB]);
    }

    #[test]
    fn with_txn_id_short_buffer_is_unchanged() {
        let one = Bytes::from_static(&[0xAA]);
        assert_eq!(&one.with_txn_id(0xBEEF)[..], &[0xAA]);
        assert_eq!(Bytes::new().with_txn_id(0x1234).len(), 0);
    }

    // ── Test helpers ──────────────────────────────────────────────────────────

    /// Open a temporary SQLite database and return the handle.
    async fn open_temp_db() -> (TempDir, Db) {
        let dir = TempDir::new().expect("temp dir");
        let path = dir.path().join("test.db");
        let db = Db::connect(&path).await.expect("connect");
        (dir, db)
    }

    /// Build a UDP [`UpstreamConfig`] pointing at `addr`.
    fn udp_config(addr: SocketAddr) -> UpstreamConfig {
        UpstreamConfig {
            addr,
            transport: UpstreamTransport::Udp,
            tls_server_name: None,
            http_endpoint: None,
        }
    }

    /// Build a minimal DNS A query datagram for `name` with `id`.
    fn build_a_query(id: u16, name: &str) -> Bytes {
        let mut w = Writer::with_capacity(64);
        Header::new(id).with_qdcount(1).with_rd(true).write(&mut w);
        let n: DnsName = name.parse().expect("valid name");
        n.write(&mut w);
        w.write_u16(1u16); // QTYPE A
        w.write_u16(1u16); // QCLASS IN
        w.finish()
    }

    /// Build a [`DnsRequest`] from a raw datagram.
    fn make_request(raw: Bytes) -> DnsRequest {
        let client: SocketAddr = "127.0.0.1:5353".parse().unwrap();
        let query = Query::try_from(raw).expect("valid query");
        DnsRequest::new(query, client)
    }

    /// Spawn a UDP mock upstream on an ephemeral port.
    ///
    /// For each datagram received the request is parsed with hickory, handed to
    /// `handler`, and — if it returns `Some(response)` — the response is
    /// serialised and sent back.  Returning `None` simulates a dead / silent
    /// upstream.
    async fn spawn_mock_udp<F>(mut handler: F) -> SocketAddr
    where
        F: FnMut(Message) -> Option<Message> + Send + 'static,
    {
        let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let addr = sock.local_addr().unwrap();

        tokio::spawn(async move {
            let mut buf = vec![0u8; 512];
            loop {
                let Ok((len, peer)) = sock.recv_from(&mut buf).await else {
                    break;
                };
                let Ok(req) = Message::from_vec(&buf[..len]) else {
                    continue;
                };
                if let Some(resp) = handler(req)
                    && let Ok(resp_bytes) = resp.to_vec()
                {
                    let _ = sock.send_to(&resp_bytes, peer).await;
                }
            }
        });

        addr
    }

    /// Parse the DNS header from raw bytes.
    fn parse_header(bytes: &Bytes) -> Header {
        let mut r = Reader::new(bytes.clone());
        Header::read(&mut r).expect("valid DNS header")
    }

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

    /// The forward service returns the reply with the **client's** query id,
    /// even though the mock returns a response with hickory's internal id
    /// (which echoes the request id — same for a real round-trip, but proves
    /// we patch it when they differ by using a known fixed id in the response).
    /// Outcome must be `Forwarded`.
    #[tokio::test]
    async fn forward_returns_reply_with_client_id() {
        let client_query_id: u16 = 0xBEEF;

        let addr = spawn_mock_udp(|req| {
            let mut resp = req.clone();
            resp.metadata.message_type = MessageType::Response;
            resp.metadata.response_code = ResponseCode::NoError;
            let name = Name::from_ascii("example.com.").unwrap();
            let rdata = RData::A(A::new(93, 184, 216, 34));
            resp.add_answer(Record::from_rdata(name, 300, rdata));
            Some(resp)
        })
        .await;

        let tracker = TaskTracker::new();
        let pool = UpstreamPool::connect(
            &[udp_config(addr)],
            &tracker,
            Arc::new(crate::resolver::upstream::RandomSelector),
            0,
            Duration::from_millis(500),
        )
        .await;
        let pool = Arc::new(SharedUpstreamPool::new(pool));

        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        let svc = ForwardService::new(pool, state);

        let raw = build_a_query(client_query_id, "example.com");
        let req = make_request(raw);

        let out = timeout(Duration::from_secs(5), svc.oneshot(req))
            .await
            .expect("safety timeout")
            .expect("service must not error");

        assert_eq!(
            out.reply.outcome,
            Outcome::Forwarded,
            "outcome must be Forwarded"
        );

        // The reply's transaction ID must equal the client's query id.
        let hdr = parse_header(&out.reply.bytes);
        assert_eq!(
            hdr.id, client_query_id,
            "reply txn-id must be patched to the client's query id"
        );
    }

    /// A positive A-record answer must yield a `Store` directive carrying the
    /// min-TTL (the cache layer executes the actual insert — see
    /// `cache_layer` tests).
    #[tokio::test]
    async fn positive_answer_directive_stores_min_ttl() {
        let addr = spawn_mock_udp(|req| {
            let mut resp = req.clone();
            resp.metadata.message_type = MessageType::Response;
            resp.metadata.response_code = ResponseCode::NoError;
            let name = Name::from_ascii("example.com.").unwrap();
            let rdata = RData::A(A::new(93, 184, 216, 34));
            resp.add_answer(Record::from_rdata(name, 300, rdata));
            Some(resp)
        })
        .await;

        let tracker = TaskTracker::new();
        let pool = UpstreamPool::connect(
            &[udp_config(addr)],
            &tracker,
            Arc::new(crate::resolver::upstream::RandomSelector),
            0,
            Duration::from_millis(500),
        )
        .await;
        let pool = Arc::new(SharedUpstreamPool::new(pool));

        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        let svc = ForwardService::new(pool, state);

        let raw = build_a_query(0x1234, "example.com");
        let req = make_request(raw);

        let out = timeout(Duration::from_secs(5), svc.oneshot(req))
            .await
            .expect("safety timeout")
            .expect("service must not error");

        assert_eq!(out.reply.outcome, Outcome::Forwarded);
        assert!(
            matches!(out.directive, CacheDirective::Store { expiry: 300, .. }),
            "positive answer → Store with min TTL 300, got {:?}",
            out.directive
        );
    }

    /// NXDOMAIN with a SOA (so `negative_ttl` is `Some`) must yield a `Store`
    /// directive with the RFC 2308 negative TTL.  Outcome is `Forwarded` (the
    /// leaf does not distinguish sign — it forwards and emits a directive).
    #[tokio::test]
    async fn negative_with_soa_directive_stores() {
        let addr = spawn_mock_udp(|req| {
            let mut resp = req.clone();
            resp.metadata.message_type = MessageType::Response;
            resp.metadata.response_code = ResponseCode::NXDomain;
            // Add a SOA to the authority section.
            let zone = Name::from_ascii("example.com.").unwrap();
            let mname = Name::from_ascii("ns1.example.com.").unwrap();
            let rname = Name::from_ascii("hostmaster.example.com.").unwrap();
            let soa = SOA::new(mname, rname, 1, 3600, 900, 604800, 60);
            resp.add_authority(Record::from_rdata(zone, 120, RData::SOA(soa)));
            Some(resp)
        })
        .await;

        let tracker = TaskTracker::new();
        let pool = UpstreamPool::connect(
            &[udp_config(addr)],
            &tracker,
            Arc::new(crate::resolver::upstream::RandomSelector),
            0,
            Duration::from_millis(500),
        )
        .await;
        let pool = Arc::new(SharedUpstreamPool::new(pool));

        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        let svc = ForwardService::new(pool, state);

        let raw = build_a_query(0x5678, "example.com");
        let req = make_request(raw);

        let out = timeout(Duration::from_secs(5), svc.oneshot(req))
            .await
            .expect("safety timeout")
            .expect("service must not error");

        assert_eq!(
            out.reply.outcome,
            Outcome::Forwarded,
            "NXDOMAIN with SOA must still return Forwarded"
        );
        // RFC 2308: min(soa_ttl=120, soa_minimum=60) = 60, under the cap.
        assert!(
            matches!(out.directive, CacheDirective::Store { expiry: 60, .. }),
            "NXDOMAIN with SOA → Store with negative TTL 60, got {:?}",
            out.directive
        );
    }

    /// NXDOMAIN with **no** SOA (`negative_ttl == None`) must yield `Skip`.
    #[tokio::test]
    async fn negative_without_soa_directive_skips() {
        let addr = spawn_mock_udp(|req| {
            let mut resp = req.clone();
            resp.metadata.message_type = MessageType::Response;
            resp.metadata.response_code = ResponseCode::NXDomain;
            // No SOA in authority — negative_ttl will be None.
            Some(resp)
        })
        .await;

        let tracker = TaskTracker::new();
        let pool = UpstreamPool::connect(
            &[udp_config(addr)],
            &tracker,
            Arc::new(crate::resolver::upstream::RandomSelector),
            0,
            Duration::from_millis(500),
        )
        .await;
        let pool = Arc::new(SharedUpstreamPool::new(pool));

        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        let svc = ForwardService::new(pool, state);

        let raw = build_a_query(0x9ABC, "example.com");
        let req = make_request(raw);

        let out = timeout(Duration::from_secs(5), svc.oneshot(req))
            .await
            .expect("safety timeout")
            .expect("service must not error");

        assert!(
            matches!(out.directive, CacheDirective::Skip),
            "NXDOMAIN without SOA → Skip (not cacheable), got {:?}",
            out.directive
        );
    }

    /// When all upstreams fail (empty pool → `AllUpstreamsFailed` immediately),
    /// the service must return `Outcome::Servfail` and the reply must parse
    /// with `Rcode::ServFail` and the client's query id.
    #[tokio::test]
    async fn all_upstreams_fail_returns_servfail() {
        // Empty pool: connect with no configs → AllUpstreamsFailed { attempts: 0 }.
        let tracker = TaskTracker::new();
        let pool = UpstreamPool::connect(
            &[],
            &tracker,
            Arc::new(crate::resolver::upstream::RandomSelector),
            0,
            Duration::from_millis(500),
        )
        .await;
        let pool = Arc::new(SharedUpstreamPool::new(pool));

        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        let svc = ForwardService::new(pool, state);

        let client_id: u16 = 0xDEAD;
        let raw = build_a_query(client_id, "example.com");
        let req = make_request(raw);

        let out = timeout(Duration::from_secs(5), svc.oneshot(req))
            .await
            .expect("safety timeout")
            .expect("service must not error");

        assert_eq!(
            out.reply.outcome,
            Outcome::Servfail,
            "outcome must be Servfail"
        );
        assert!(
            matches!(out.directive, CacheDirective::Skip),
            "SERVFAIL must not be cached"
        );

        let hdr = parse_header(&out.reply.bytes);
        assert_eq!(
            hdr.id, client_id,
            "SERVFAIL reply must echo the client's query id"
        );
        assert_eq!(
            hdr.rcode(),
            crate::codec::header::Rcode::ServFail,
            "RCODE must be ServFail"
        );
    }
}