Skip to main content

ts_runtime/
magic_dns.rs

1//! MagicDNS responder with a split-DNS / recursive forwarder.
2//!
3//! An in-netstack DNS server bound to `100.100.100.100:53`. It is authoritative for in-tailnet
4//! peer names and control-pushed [`ExtraRecord`][ts_control::ExtraRecord]s, answering `A`/`AAAA`/
5//! `PTR` for those directly — plus, for a peer control has marked with the `dns-subdomain-resolve`
6//! node attribute ([`Node::resolves_subdomains`]), every name *under* that peer's name
7//! ([`DnsView::subdomain_host_for`]). For names it is *not* authoritative for, it brings tsnet-style
8//! split-DNS and recursive resolution:
9//!
10//! - **Split DNS** ([`DnsConfig::routes`]): the longest matching suffix route forwards the query
11//!   to one of that route's upstream resolvers. A route with an **empty** upstream list is a
12//!   negative route — names under it are `NXDOMAIN` (Go keeps them on the built-in resolver; for
13//!   us that means fail-closed unless an overlay/extra record matched first).
14//! - **Recursive** ([`DnsConfig::fallback_resolvers`] / [`DnsConfig::resolvers`]): names matching
15//!   no route are forwarded to the fallback resolvers, else the global resolvers.
16//! - **Fail closed**: if no route and no resolver is configured, an unknown name is `NXDOMAIN`.
17//! - **A refusing upstream does not end a forward**: a `REFUSED` or `SERVFAIL` from one upstream is
18//!   a *soft* error — the next upstream on the route (or in the fallback list) is tried. A refusal
19//!   is relayed to the client only when every upstream refused; a mix of failures is a SERVFAIL
20//!   (see [`forward_query`]).
21//!
22//! Anti-leak / IPv6-off posture: upstream forwarding binds `0.0.0.0:0` on the overlay netstack —
23//! UDP for the query, TCP for the hop raced against it, IPv4 only either way — and never opens an
24//! IPv6 socket, nor a host socket. AAAA handling is gated on [`DnsView::enable_ipv6`] (default
25//! off): with the gate OFF an AAAA query for a tailnet/overlay/self name returns NoError with an
26//! empty answer (NODATA) rather than the overlay v6 address — answering a v6 the IPv4-only client
27//! can't route would only create dead connections and a fingerprint. With the gate ON, AAAA is
28//! answered from overlay data (the v6 overlay addr), as historically. AAAA for tailnet names is
29//! never forwarded to a recursive upstream regardless of the gate.
30//!
31//! - MagicDNS disabled (`dns_config == None` or `magic_dns == false`), OR the node does not accept
32//!   the tailnet DNS config ([`DnsView::accept_dns`] is `false`, i.e. `--accept-dns` / `CorpDNS`
33//!   off) => `REFUSED` for every query (the responder serves nothing, mirroring Go applying an empty
34//!   `dns.Config` when `CorpDNS` is off).
35//! - A qtype/class we don't serve authoritatively (anything but IN-class A/AAAA/PTR — TXT, SRV, MX,
36//!   HTTPS/SVCB, a CHAOS-class query, …) => NODATA (empty NOERROR) for a tailnet-authoritative name,
37//!   forwarded verbatim to upstream for an off-tailnet name — exactly like Go's resolver, NOT
38//!   `REFUSED` (a stub reads REFUSED as "won't serve me" and abandons the resolver). Tailnet reverse
39//!   zones (CGNAT `in-addr.arpa` / any `ip6.arpa`) still fail closed to NXDOMAIN for every qtype
40//!   (never forwarded — anti-leak).
41//! - A **negative** answer this node is authoritative for — an NXDOMAIN for a name inside a zone we
42//!   serve (a tailnet search domain, a negative split-DNS route, or the CGNAT reverse zone), or a
43//!   NODATA for such a name — carries that zone's `SOA` in the authority section, advertising a
44//!   10-second negative-caching bound (RFC 2308). Without one, macOS `mDNSResponder` keeps an
45//!   SOA-less negative answer on its own schedule, so a name queried shortly *before* a node was
46//!   renamed to it stays unresolvable until something flushes the cache. Positive answers carry a
47//!   5-second TTL for the same reason in the other direction. `SERVFAIL`, `REFUSED` and the blanket
48//!   `ip6.arpa` refusal claim no zone and carry no SOA.
49//! - Malformed query => dropped (no response).
50//! - A reply larger than the UDP payload size the query advertised — its EDNS(0) OPT record, or 512
51//!   bytes when it carried none or carried one this node will not act on (RFC 1035) — comes back
52//!   with the `TC` (truncated) bit set and its body intact, so the stub resolver knows to retry over
53//!   TCP ([`check_response_size_and_set_tc`]). This applies to forwarded replies, where the query is
54//!   relayed verbatim and so this is what catches an upstream that ignores the size its requestor
55//!   asked for, and equally to answers this node composes itself. The retry that bit asks for is served
56//!   by the `dns_over_tcp` server (TUN mode), which reaches the same [`decide`] through
57//!   the same view — and which is never handed a `TC` bit for size, since a TCP client has no
58//!   datagram to overflow (see [`ClientTransport`]).
59//! - The hop to the **upstream** resolver makes the same retry on the client's behalf: a forwarded
60//!   answer that comes back with `TC` set is re-asked of the same resolver over TCP, over the same
61//!   overlay netstack channel the UDP hop uses and never a host socket ([`ask_upstream`]). Without
62//!   it the client's own TCP retry lands back on a UDP hop and is answered with the same truncated
63//!   message, and a name whose answer does not fit a datagram simply does not resolve through this
64//!   node. The TCP hop is also **raced** against a slow or failed UDP hop, as Go's forwarder races
65//!   them: it joins after [`UDP_RACE_TIMEOUT`] (at once for a TCP client, or when the UDP hop has
66//!   already failed), so a resolver whose UDP path drops but whose TCP path answers still resolves.
67//!   Control's `dns-forwarder-disable-tcp-retries` node attribute is the *off* switch for all of it
68//!   ([`DnsView::upstream_tcp_retry`]); the TCP hop is on by default.
69
70use std::{
71    net::{IpAddr, Ipv4Addr, SocketAddr},
72    sync::Arc,
73    time::Duration,
74};
75
76use kameo::{
77    actor::ActorRef,
78    message::{Context, Message},
79};
80use netstack::{CreateSocket, netcore::Channel};
81use tokio::{
82    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
83    sync::{Semaphore, watch},
84    task::JoinSet,
85    time::timeout,
86};
87use ts_control::{DnsConfig, DnsResolver, Node};
88use ts_dns_wire::{Name, QType, RData, Rcode, SoaZone, decode_query, encode_response};
89
90use crate::{
91    Error,
92    env::Env,
93    peer_tracker::{PeerDb, PeerState},
94};
95
96/// How long to wait for an upstream resolver to answer a forwarded query before giving up.
97const UPSTREAM_TIMEOUT: Duration = Duration::from_secs(5);
98/// Cap on concurrent in-flight forwarded queries on the local `100.100.100.100:53` responder.
99///
100/// Each forward is spawned onto a task that holds an overlay UDP socket until the upstream answers
101/// or [`UPSTREAM_TIMEOUT`] elapses. Without a cap, a local/tailnet client spraying distinct
102/// forwardable names opens unbounded concurrent overlay sockets + tasks (a resource-exhaustion DoS
103/// on a slow/black-holed upstream, since each lingers for the full timeout). Bound it the same way
104/// the peerAPI DoH server bounds its request handlers ([`crate::peerapi`]'s `MAX_INFLIGHT`): acquire
105/// a permit before spawning and drop the query fail-closed when saturated. A dropped DNS query is a
106/// benign outcome — the stub resolver simply retries or times out — and Go's resolver likewise
107/// bounds outstanding forwards rather than spawning without limit.
108const MAX_INFLIGHT_FORWARDS: usize = 512;
109/// Cap on how much of a forwarded upstream response we relay back to the stub resolver (a single
110/// UDP datagram).
111///
112/// This is Go's `maxResponseBytes` — `const maxResponseBytes = 4095`, defined in
113/// net/dns/resolver/tsdns.go @ 9ea7cba44591e0cd840c6c94d23274dd222059bf and used by the forwarder.
114/// The odd-looking 4095 is deliberate upstream: `sendUDP` reads into a `maxResponseBytes+1` buffer
115/// precisely so that a 4096-byte read is *detectable* as "the answer did not fit", and then cuts the
116/// reply back to 4095 and sets `TC`. A 4096-byte answer is a truncated answer everywhere else in a
117/// tailnet, so it has to be one here too: relaying it whole with `TC` clear is a message a Go peer
118/// would have handed its stub resolver as truncated.
119///
120/// *Where the bound applies differs from Go*: here it is not a read bound and it does not bound
121/// memory. [`forward_query`] reads with `recv_from_bytes`, which issues `Recv { max_len: None }`, so
122/// the netstack has already copied the whole queued datagram out before [`cap_response`] sees it.
123/// What bounds the read is the netstack UDP socket's receive ring —
124/// `netcore::Config::udp_buffer_size`, 4 KiB by default and not overridden by `ts_runtime` — and
125/// smoltcp drops a datagram larger than that ring at enqueue rather than delivering a chopped one.
126/// That ring is 4096 and this cap is 4095, so the ring plays exactly the part Go's `+1` byte plays:
127/// the one datagram size it can deliver and this cap cannot pass is the full-ring 4096-byte answer,
128/// which [`cap_response`] then chops to 4095 and marks `TC` (pinned by
129/// `full_ring_datagram_is_chopped_and_marked_truncated`).
130///
131/// The client's query is forwarded verbatim, so a client advertising a large EDNS UDP size can
132/// elicit a legitimately large (1300–4095 byte) UDP answer (big TXT sets, DNSSEC, many-record
133/// round-robins). Capping at the old 1232 truncated those and set TC, forcing a TCP retry — which
134/// nothing served at the time, so the large answer became unreachable. 4095 relays them intact.
135///
136/// It is a **datagram** bound, and since [`ask_upstream`] gained its TCP retry it is applied as one:
137/// an answer that came over the TCP hop and is going back to a TCP client never crossed a datagram
138/// and is not cut here (see [`cap_response`]). Every other combination is, because a UDP hop could
139/// not have delivered more than the receive ring anyway and a UDP client cannot be answered with
140/// more than one datagram. So an answer over 4095 bytes still reaches a UDP stub resolver as a
141/// `TC`-marked 4095 bytes — which is the retry RFC 1035 §4.2.1 asks it to make, and `dns_over_tcp`
142/// answers that retry whole.
143const MAX_UPSTREAM_RESPONSE: usize = 4095;
144
145/// The MagicDNS service IP. The netstack interface owns this address, so a `udp_bind` here
146/// receives the tailnet's DNS traffic.
147const MAGIC_DNS_IP: Ipv4Addr = Ipv4Addr::new(100, 100, 100, 100);
148/// The DNS service port.
149const MAGIC_DNS_PORT: u16 = 53;
150
151/// The latest view the answer loop resolves queries against.
152///
153/// Updated by the actor's message handlers (from control `StateUpdate` and peer `PeerState`
154/// updates) and read fresh by the answer loop for every packet.
155#[derive(Clone, Default)]
156pub(crate) struct DnsView {
157    /// The DNS configuration. `magic_dns == false` (the default) means serve nothing.
158    pub(crate) cfg: DnsConfig,
159    /// The current peer database, if we've seen a peer update.
160    pub(crate) peers: Option<Arc<PeerDb>>,
161    /// This node, if we've seen a self-node update.
162    pub(crate) self_node: Option<Node>,
163    /// The peerAPI DoH socket address of the currently-selected exit node, if one is active and can
164    /// proxy DNS ([`Node::peerapi_doh_addr`]). When set, the MagicDNS *client* serve loop delegates
165    /// recursive resolution to this address over the overlay instead of forwarding to the locally
166    /// configured upstream resolvers — so recursive DNS egresses from the exit node, not this host.
167    ///
168    /// Only consumed by the local MagicDNS responder's serve loop (the client side). The peerAPI
169    /// DoH *server* shares this same view but ignores this field: an exit-node DNS proxy resolves
170    /// recursively itself (gated by `forward_exit_egress`), it never re-delegates to its own exit
171    /// node. `None` means no active exit node / no DoH delegation — recursion stays local.
172    pub(crate) exit_doh: Option<SocketAddr>,
173    /// Whether IPv6 is enabled on the tailnet overlay (from [`Env::enable_ipv6`], default `false`).
174    ///
175    /// Governs the AAAA answer path only: with the gate OFF (default) an AAAA query for a
176    /// tailnet/overlay/self name is answered NoError-with-empty-answer (NODATA) instead of the
177    /// overlay v6 address; with it ON, AAAA is answered from overlay data as historically. Set once
178    /// from the runtime `Env` when the actor starts; never changes for the life of the runtime.
179    pub(crate) enable_ipv6: bool,
180    /// Whether the tailnet's DNS configuration is accepted (`--accept-dns` / `CorpDNS`, from
181    /// [`Env::accept_dns`]). When `false`, [`decide`] refuses every query (the responder serves
182    /// nothing), mirroring Go applying an empty `dns.Config` when `CorpDNS` is off — so a node can
183    /// join for connectivity without taking over DNS.
184    ///
185    /// Unlike [`enable_ipv6`](DnsView::enable_ipv6) (snapshotted once at actor spawn), this is
186    /// runtime-settable via `Device::set_accept_dns`, so it is re-read from the live
187    /// [`Env::accept_dns`] cell on **every** view rebuild (the `StateUpdate` and `PeerState`
188    /// handlers), not just at spawn — otherwise a runtime toggle would never reach the served view.
189    pub(crate) accept_dns: bool,
190}
191
192impl DnsView {
193    /// Find the node (peer or self) that answers to `name`, case/dot-insensitively.
194    fn node_by_name(&self, name: &str) -> Option<Node> {
195        if let Some(node) = self
196            .peers
197            .as_ref()
198            .and_then(|p| p.get(&name).map(|(_, n)| n.clone()))
199        {
200            return Some(node);
201        }
202
203        self.self_node
204            .as_ref()
205            .filter(|n| n.matches_name(name))
206            .cloned()
207    }
208
209    /// Find the node a **parent** of `canon` names, when that node is a *subdomain host* — a node
210    /// control has set the `dns-subdomain-resolve` attribute on
211    /// ([`Node::resolves_subdomains`]), meaning every name under it resolves to its addresses.
212    ///
213    /// Mirrors the miss path of Go's resolver (`net/dns/resolver/tsdns.go`): a name that matches no
214    /// host walks its parents (`util/dnsname`'s `Parent`) and answers from the first parent that is
215    /// a subdomain host. The walk is over *every* parent, not one level: for a node `machine`, both
216    /// `my.machine` and `be.my.machine` resolve to it.
217    ///
218    /// Two bounds keep the walk from becoming a wildcard:
219    ///
220    /// - It stops at a **tailnet search domain**. `user.ts.net` is the zone apex, not a host under
221    ///   it, so the walk never climbs past it into names this node is not authoritative for.
222    /// - A candidate parent must be **fully qualified** (at least two labels) and is matched
223    ///   *exactly*, with no search-domain qualification. Unlike [`DnsView::resolve_addr`]'s exact
224    ///   lookup, the walk must not expand a short name against the search list: the peer-name index
225    ///   also holds bare hostnames, so a peer named after a public suffix (`com`, `dev`) carrying
226    ///   the attribute would otherwise swallow every name under that suffix — a hijack Go cannot
227    ///   perform, because its resolver does no search-list expansion at all (the client stub does).
228    ///   A stub resolver qualifies a short name against the search list before asking, so the
229    ///   fully-qualified form is what arrives here anyway.
230    fn subdomain_host_for(&self, canon: &str) -> Option<Node> {
231        let mut parent = canon;
232        while let Some((_, rest)) = parent.split_once('.') {
233            parent = rest;
234            // A bare label is never a candidate (see the doc comment): nothing is left to walk.
235            if !parent.contains('.') {
236                return None;
237            }
238            // The tailnet zone apex itself: stop rather than climb out of the zone we serve.
239            if self.cfg.search_domains.iter().any(|zone| zone == parent) {
240                return None;
241            }
242            if let Some(node) = self.node_by_name(parent)
243                && node.resolves_subdomains()
244            {
245                return Some(node);
246            }
247        }
248        None
249    }
250
251    /// Resolve `canon` to an answer address of the requested family. A tailnet peer/self match
252    /// wins first — tried as written and then qualified by each tailnet search domain (so a
253    /// short/partially-qualified name like `host` or `host.user` still resolves to
254    /// `host.user.ts.net`). Failing that, a control-pushed [`ExtraRecord`] of the matching family
255    /// answers, matched as a fully-qualified name only (no search-domain expansion — like Go tsnet,
256    /// ExtraRecords are authoritative FQDN entries, not subject to client search-list qualification).
257    /// Only when nothing matched the name *exactly* does the subdomain-host parent walk run
258    /// ([`DnsView::subdomain_host_for`]) — so an exact name always beats a parent match, as it does
259    /// upstream, where the parent walk is the lookup-miss path.
260    /// Still fail-closed: only ever resolves to a known tailnet peer/self or an explicitly
261    /// control-pushed static record — never anything else.
262    fn resolve_addr(&self, canon: &str, want_v4: bool) -> Option<IpAddr> {
263        let addr_of = |node: Node| -> IpAddr {
264            if want_v4 {
265                IpAddr::from(node.tailnet_address.ipv4.addr())
266            } else {
267                IpAddr::from(node.tailnet_address.ipv6.addr())
268            }
269        };
270
271        if let Some(node) = self.node_by_name(canon) {
272            return Some(addr_of(node));
273        }
274        for suffix in &self.cfg.search_domains {
275            if let Some(node) = self.node_by_name(&format!("{canon}.{suffix}")) {
276                return Some(addr_of(node));
277            }
278        }
279
280        // Control-pushed static records match the fully-qualified query name only.
281        let mut named_by_extra_record = false;
282        for rec in &self.cfg.extra_records {
283            if rec.name != canon {
284                continue;
285            }
286            named_by_extra_record = true;
287            if matches!(
288                (rec.addr, want_v4),
289                (IpAddr::V4(_), true) | (IpAddr::V6(_), false)
290            ) {
291                return Some(rec.addr);
292            }
293        }
294        // An extra record for this exact name but of the other family means the name *exists* and
295        // simply holds no address of the queried type — Go's lookup found it, so the parent walk
296        // (its miss path) does not run and the answer stays NODATA.
297        if named_by_extra_record {
298            return None;
299        }
300
301        // Nothing answers this name exactly: fall back to a parent that resolves its subdomains.
302        self.subdomain_host_for(canon).map(addr_of)
303    }
304
305    /// Find the node (peer or self) that owns the tailnet IP `ip`.
306    fn node_by_ip(&self, ip: IpAddr) -> Option<Node> {
307        if let Some(node) = self
308            .peers
309            .as_ref()
310            .and_then(|p| p.get(&ip).map(|(_, n)| n.clone()))
311        {
312            return Some(node);
313        }
314
315        self.self_node
316            .as_ref()
317            .filter(|n| {
318                IpAddr::from(n.tailnet_address.ipv4.addr()) == ip
319                    || IpAddr::from(n.tailnet_address.ipv6.addr()) == ip
320            })
321            .cloned()
322    }
323
324    /// Decide how to resolve a non-overlay `name` against the split-DNS routes and recursive
325    /// resolvers, returning the upstreams to forward to.
326    ///
327    /// Longest-suffix wins among [`DnsConfig::routes`]: a route's suffix matches `name` if `name`
328    /// equals it or ends with `.suffix`. A matched route with a non-empty upstream list forwards
329    /// there; a matched route with an **empty** list is a negative route ([`Upstreams::Block`] =>
330    /// NXDOMAIN). With no route match, [`DnsConfig::fallback_resolvers`] (preferred) or
331    /// [`DnsConfig::resolvers`] resolve recursively; if neither is configured we stay fail-closed
332    /// ([`Upstreams::None`] => NXDOMAIN).
333    fn route_for(&self, name: &str) -> Upstreams<'_> {
334        let mut best: Option<(&str, &Vec<DnsResolver>)> = None;
335        for (suffix, upstreams) in &self.cfg.routes {
336            if suffix_matches(name, suffix) && best.is_none_or(|(b, _)| suffix.len() > b.len()) {
337                best = Some((suffix.as_str(), upstreams));
338            }
339        }
340
341        if let Some((_, upstreams)) = best {
342            return if upstreams.is_empty() {
343                Upstreams::Block
344            } else {
345                // A deliberately-configured split-DNS route: not eligible for exit-node DoH
346                // delegation — these upstreams (e.g. an internal resolver reachable over a subnet
347                // route) must keep receiving the query directly.
348                Upstreams::Route(upstreams)
349            };
350        }
351
352        if !self.cfg.fallback_resolvers.is_empty() {
353            return Upstreams::Recursive(&self.cfg.fallback_resolvers);
354        }
355        if !self.cfg.resolvers.is_empty() {
356            return Upstreams::Recursive(&self.cfg.resolvers);
357        }
358        Upstreams::None
359    }
360
361    /// Whether the forwarder may use TCP to an upstream resolver — to re-ask a truncated answer, or
362    /// to race a slow or failed UDP hop ([`ask_upstream`]).
363    ///
364    /// On unless control's `dns-forwarder-disable-tcp-retries` node attribute is set on the **self**
365    /// node ([`Node::disable_dns_forwarder_tcp_retries`]) — the attribute is the retry's *off*
366    /// switch, not its on switch, so a node with no self-node update yet (and every tailnet that
367    /// never set it) retries. Go reads the same knob at the same point:
368    /// `skipTCP := skipTCPRetry() || (f.controlKnobs != nil &&
369    /// f.controlKnobs.DisableDNSForwarderTCPRetries.Load())`, net/dns/resolver/forwarder.go:677 @
370    /// `023255e8a27ec9f6a21d24e3eda21c052ff72af3`.
371    ///
372    /// Go's other disjunct, `skipTCPRetry()`, is a process-level environment knob and has no
373    /// counterpart here: this tree carries no `envknob` equivalent, and the deployment switch a
374    /// tailnet operator actually reaches for is the node attribute.
375    pub(crate) fn upstream_tcp_retry(&self) -> TcpRetry {
376        match &self.self_node {
377            Some(node) if node.disable_dns_forwarder_tcp_retries() => TcpRetry::Disabled,
378            _ => TcpRetry::Enabled,
379        }
380    }
381}
382
383/// Whether the forwarder may ask an upstream over **TCP** at all — to re-ask a truncated answer, or
384/// to race a slow or failed UDP hop. Decided per query from the current view
385/// ([`DnsView::upstream_tcp_retry`]) and carried to [`ask_upstream`], which is the only thing that
386/// reads it.
387#[derive(Clone, Copy, Debug, PartialEq, Eq)]
388pub(crate) enum TcpRetry {
389    /// Race the TCP hop against the UDP hop, and retry a `TC`-marked UDP answer over TCP, to the
390    /// same resolver. The default.
391    Enabled,
392    /// UDP only, on every arm: relay whatever the UDP hop brings back, truncated or not, and never
393    /// open a TCP connection. Control's `dns-forwarder-disable-tcp-retries` attribute.
394    Disabled,
395}
396
397/// The upstreams a non-overlay query should be forwarded to (or why it should not be forwarded).
398enum Upstreams<'a> {
399    /// A split-DNS route matched: forward to these route-specific upstreams (never DoH-delegated).
400    Route(&'a [DnsResolver]),
401    /// No route matched: forward to these recursive (fallback/global) resolvers. Eligible for
402    /// exit-node DoH delegation in the client serve loop.
403    Recursive(&'a [DnsResolver]),
404    /// A negative split-DNS route matched: do not resolve (NXDOMAIN). The route's suffix is a zone
405    /// this node is authoritative for — Go's `localDomains` is exactly the set of routes configured
406    /// with no resolvers — so [`authoritative_zone_for`] finds it again when naming the negative
407    /// answer's SOA zone.
408    Block,
409    /// No route and no resolver configured: fail closed (NXDOMAIN).
410    None,
411}
412
413/// What the (sync) decision step concluded for a query: either a complete response to send back,
414/// or a request to forward the original query to an upstream resolver.
415pub(crate) enum Decision {
416    /// A fully-formed response is ready to send.
417    Reply(Vec<u8>),
418    /// Forward the original query datagram to one of these upstream UDP resolvers; on success
419    /// relay the upstream answer, on failure/timeout answer with the prebuilt `servfail` buffer
420    /// (an off-tailnet name we failed to forward is a soft failure, not a cacheable non-existence —
421    /// Go forwarder.go:1297-1307).
422    Forward {
423        /// UDP upstreams to try, in order.
424        upstreams: Vec<SocketAddr>,
425        /// The original query bytes to forward verbatim.
426        query: Vec<u8>,
427        /// Fallback SERVFAIL response if every upstream fails or times out.
428        servfail: Vec<u8>,
429        /// Whether this is a *recursive* (catch-all fallback/global resolver) forward, as opposed
430        /// to a deliberately-configured split-DNS route. Only recursive forwards are eligible for
431        /// exit-node DoH delegation in the client serve loop (see [`DnsView::exit_doh`]); split-DNS
432        /// routes always stay on their configured upstreams (typically subnet-reachable internal
433        /// resolvers). The peerAPI DoH *server* ignores this flag entirely.
434        recursive: bool,
435    },
436}
437
438/// Whether `name` is `suffix` or sits under it at a label boundary: `"a.corp"` matches `"corp"`,
439/// `"acorp"` does not. An **empty** suffix never matches (defense-in-depth: an empty suffix would
440/// otherwise make `ends_with("")` match every name and either over-route or treat everything as a
441/// tailnet name — both leak-prone).
442fn suffix_matches(name: &str, suffix: &str) -> bool {
443    if suffix.is_empty() {
444        return false;
445    }
446    name == suffix
447        || (name.len() > suffix.len()
448            && name.ends_with(suffix)
449            && name.as_bytes()[name.len() - suffix.len() - 1] == b'.')
450}
451
452/// Returns `true` if `name` falls under one of the tailnet search domains. Such names are
453/// authoritative MagicDNS names and are NEVER forwarded to an upstream resolver — anti-leak: a
454/// tailnet name (and the fact that it was queried) must not escape to a third-party resolver.
455fn is_tailnet_name(view: &DnsView, name: &str) -> bool {
456    view.cfg
457        .search_domains
458        .iter()
459        .any(|suffix| suffix_matches(name, suffix))
460}
461
462/// Whether `name` is an IPv6 reverse-DNS (`PTR`) name (ends in `ip6.arpa`). This fork is IPv4-only
463/// on the tailnet; an IPv6 reverse lookup must NEVER be forwarded to a third-party resolver
464/// (anti-leak: it would reveal that a tailnet v6 address — e.g. a ULA `fd7a:…` — was probed). All
465/// such queries fail closed to NXDOMAIN.
466fn is_ip6_arpa(name: &str) -> bool {
467    suffix_matches(name, "ip6.arpa")
468}
469
470/// Whether `ip` is in the Tailscale CGNAT range `100.64.0.0/10` (RFC 6598, the tailnet IPv4 space).
471/// Reverse (`PTR`) queries for these addresses are authoritative to MagicDNS: if no peer owns the
472/// IP we fail closed to NXDOMAIN rather than forwarding the probe to a third-party resolver.
473fn is_tailnet_cgnat(ip: Ipv4Addr) -> bool {
474    let o = ip.octets();
475    o[0] == 100 && (64..=127).contains(&o[1])
476}
477
478/// The zone this node is authoritative for that contains `canon`, or `None` when it is not
479/// authoritative for the name.
480///
481/// Mirrors Go `net/dns/resolver/tsdns.go` `authoritativeZoneFor`, which scans `Resolver.localDomains`.
482/// Go's `localDomains` is exactly the set of control-pushed routes with **no** resolvers
483/// (`net/dns/manager.go` `compileConfig`), so the equivalent set here is the union of:
484///
485/// - the tailnet search domains — what [`is_tailnet_name`] tests, and the zone a tailnet-suffix
486///   NXDOMAIN belongs to;
487/// - the negative split-DNS routes (a route with an empty upstream list), the literal shape of
488///   Go's `localDomains`;
489/// - the CGNAT reverse zone `<b>.100.in-addr.arpa` covering a `100.64.0.0/10` reverse name.
490///   Synthesized rather than read from the routes: this fork's reverse guard is structural
491///   ([`is_tailnet_cgnat`]) and holds whether or not control pushed the matching route, and the
492///   zone it names is the same per-/16 chunk real tailscaled advertises.
493///
494/// `ip6.arpa` is deliberately absent. This fork NXDOMAINs *every* `ip6.arpa` name as an anti-leak
495/// measure ([`is_ip6_arpa`]) rather than because it serves that zone, and an SOA naming `ip6.arpa`
496/// would claim authority over the whole IPv6 reverse tree — a claim we do not have and one that
497/// would have a client negative-cache far more than this node answers for.
498///
499/// The longest match wins. Go returns the first match from an unordered slice; longest gives the
500/// same answer whenever the zones nest (the usual case) and is a defensible tie-break when they
501/// do not.
502fn authoritative_zone_for(view: &DnsView, name: &Name, canon: &str) -> Option<String> {
503    if let Some(octets) = name.ptr_to_ipv4() {
504        let v4: Ipv4Addr = octets.into();
505        if is_tailnet_cgnat(v4) {
506            return Some(format!("{}.100.in-addr.arpa", v4.octets()[1]));
507        }
508    }
509
510    view.cfg
511        .search_domains
512        .iter()
513        .map(String::as_str)
514        .chain(
515            view.cfg
516                .routes
517                .iter()
518                .filter(|(_, upstreams)| upstreams.is_empty())
519                .map(|(suffix, _)| suffix.as_str()),
520        )
521        .filter(|zone| suffix_matches(canon, zone))
522        .max_by_key(|zone| zone.len())
523        .map(str::to_owned)
524}
525
526/// The SOA record to attach to an authoritative **negative** answer (NXDOMAIN, or NODATA for a
527/// name we serve), or `None` when this node is not authoritative for a zone containing the name.
528///
529/// Without it, a downstream cache decides for itself how long to remember the nonexistence: macOS
530/// `mDNSResponder` holds an SOA-less negative answer for a long time, so a name queried shortly
531/// *before* a node was renamed to it keeps failing until something flushes the cache. The SOA
532/// bounds that at 10 seconds (RFC 2308), which is what Go's resolver advertises.
533fn soa_for(view: &DnsView, name: &Name, canon: &str) -> Option<SoaZone> {
534    let zone = authoritative_zone_for(view, name, canon)?;
535    Some(SoaZone {
536        zone: Name(zone.split('.').map(str::to_owned).collect()),
537        serial: soa_serial(),
538    })
539}
540
541/// The SOA SERIAL to publish: the response time in unix seconds.
542///
543/// A serial is meant to change only when the zone data does, but nothing consumes ours — this node
544/// has no secondaries and serves no zone transfers — so Go uses the current time and so do we. It
545/// is monotonic, cheap, and fits in a `u32` until 2106. A clock before the epoch yields 0 rather
546/// than panicking; the value carries no meaning either way.
547fn soa_serial() -> u32 {
548    std::time::SystemTime::now()
549        .duration_since(std::time::UNIX_EPOCH)
550        .map_or(0, |since| since.as_secs() as u32)
551}
552
553/// Decide what to do with a single DNS query against `view`: either a complete response is ready
554/// ([`Decision::Reply`]), the query should be forwarded to upstream resolvers
555/// ([`Decision::Forward`]), or the packet should be dropped without answering (`None`).
556///
557/// Factored out of the socket loop so it can be unit-tested without a netstack: it does no I/O and
558/// reads no state but `view` and the wall clock (the SOA SERIAL of a negative answer, which nothing
559/// consumes — see [`soa_serial`]). It never panics and fails closed: an unknown, unroutable, or
560/// tailnet-suffix name resolves to NXDOMAIN rather than leaking to an upstream resolver.
561pub(crate) fn decide(view: &DnsView, buf: &[u8]) -> Option<Decision> {
562    // Malformed / non-query input is dropped: we never answer something we can't parse.
563    let query = decode_query(buf).ok()?;
564    let q = &query.question;
565    let id = query.id;
566    // Echo the query's RD bit (and set RA when set) on the response — Go derives the response header
567    // from the query header.
568    let rd = query.recursion_desired;
569
570    let reply = |rcode, answers: &[RData]| {
571        Decision::Reply(encode_response(id, q, rd, rcode, answers, None))
572    };
573    // A negative answer (NXDOMAIN, or NODATA) for a name inside a zone we serve carries that zone's
574    // SOA in the authority section, which bounds how long a downstream resolver may cache the
575    // nonexistence (RFC 2308). `soa_for` returns `None` when we are not authoritative for the name,
576    // in which case this is exactly `reply`.
577    let reply_negative = |rcode, canon: &str| {
578        Decision::Reply(encode_response(
579            id,
580            q,
581            rd,
582            rcode,
583            &[],
584            soa_for(view, &q.name, canon).as_ref(),
585        ))
586    };
587
588    // Fail closed: MagicDNS off, or the node doesn't accept the tailnet's DNS config
589    // (`--accept-dns` / `CorpDNS` is false) => serve nothing. The `accept_dns` gate mirrors Go
590    // applying an empty `dns.Config` when `CorpDNS` is off: the node ignores the control-pushed DNS
591    // config and refuses every query. This one read site covers the netstack responder, the peerAPI
592    // DoH server that shares the view, and (via `tun_actor::plan_intercept`) the TUN query path.
593    if !view.cfg.magic_dns || !view.accept_dns {
594        return Some(reply(Rcode::Refused, &[]));
595    }
596
597    let canon = q.name.to_canon();
598
599    // We only serve the internet (IN) class authoritatively. A non-IN class (CHAOS, HESIOD, the
600    // ANY/255 class, ...) is NOT refused outright: Go's local resolver does no class check and
601    // forwards such a query like any other name. Treat it as an unsupported authoritative type —
602    // NODATA for a tailnet name, forward for an off-tailnet name — so a `CH TXT version.bind`
603    // diagnostic or a `qclass=ANY` probe reaches upstream instead of getting REFUSED.
604    const CLASS_IN: u16 = 1;
605    if q.qclass != CLASS_IN {
606        return Some(forward_or_nodata(view, &canon, buf, id, q, rd));
607    }
608
609    Some(match &q.qtype {
610        QType::A => match view.resolve_addr(&canon, true) {
611            Some(IpAddr::V4(v4)) => reply(Rcode::NoError, &[RData::A(v4.octets())]),
612            // No overlay/extra-record answer: try split-DNS / recursive upstreams.
613            _ => forward_or_nxdomain(view, &canon, buf, id, q, rd),
614        },
615        QType::Aaaa => match view.resolve_addr(&canon, false) {
616            // A tailnet/overlay/self (or extra-record) AAAA match. Gate on IPv6: with IPv6 OFF
617            // (default) the client is IPv4-only, so answering with the overlay v6 address would
618            // only hand out an unroutable address — dead connections plus a fingerprint. Return
619            // NoError with an empty answer (NODATA) instead. With the gate ON, answer from overlay
620            // data as historically. We never forward this name to a recursive upstream either way:
621            // a positive overlay match is authoritative.
622            Some(IpAddr::V6(v6)) if view.enable_ipv6 => {
623                reply(Rcode::NoError, &[RData::Aaaa(v6.octets())])
624            }
625            // NODATA: the name exists but we hold no address of the queried family for it, so it
626            // takes the SOA — Go sets `SOAZone` on exactly this case (`rcode == RCodeSuccess &&
627            // !ip.IsValid()` for an A/AAAA/ALL question).
628            Some(IpAddr::V6(_)) => reply_negative(Rcode::NoError, &canon),
629            // No overlay/extra-record answer: split-DNS / recursive upstreams (off-tailnet names);
630            // tailnet names fail closed to NXDOMAIN inside `forward_or_nxdomain`.
631            _ => forward_or_nxdomain(view, &canon, buf, id, q, rd),
632        },
633        QType::Ptr => match q.name.ptr_to_ipv4() {
634            Some(octets) => {
635                let v4: Ipv4Addr = octets.into();
636                let ip = IpAddr::V4(v4);
637                match view.node_by_ip(ip) {
638                    Some(node) => {
639                        let fqdn = node.fqdn(false);
640                        let labels: Vec<String> = fqdn.split('.').map(str::to_owned).collect();
641                        reply(Rcode::NoError, &[RData::Ptr(Name(labels))])
642                    }
643                    // Anti-leak: a reverse query for an IP in the tailnet CGNAT range
644                    // (100.64.0.0/10) that misses the peer set is authoritative-but-unknown; fail
645                    // closed to NXDOMAIN rather than leaking the probed tailnet IP upstream. Only
646                    // genuinely off-tailnet reverse queries are forwarded.
647                    None if is_tailnet_cgnat(v4) => reply_negative(Rcode::NxDomain, &canon),
648                    None => forward_or_nxdomain(view, &canon, buf, id, q, rd),
649                }
650            }
651            // Anti-leak / IPv4-only-tailnet: an IPv6 reverse (`ip6.arpa`) PTR must never be
652            // forwarded — relaying it would reveal that a tailnet v6 address (e.g. a ULA `fd7a:…`)
653            // was probed. Fail closed to NXDOMAIN, exactly like the IPv4 CGNAT guard above. No SOA:
654            // this blanket refusal is anti-leak, not a claim to serve `ip6.arpa` (see
655            // [`authoritative_zone_for`]).
656            None if is_ip6_arpa(&canon) => reply(Rcode::NxDomain, &[]),
657            None => forward_or_nxdomain(view, &canon, buf, id, q, rd),
658        },
659        // Anything else (TXT, SRV, MX, HTTPS/SVCB, CNAME, ...): we hold no authoritative record of
660        // that type, so — like Go's resolver — forward it to upstream for an off-tailnet name and
661        // return NODATA (empty NOERROR) for a tailnet-authoritative name. NOT REFUSED: a stub reads
662        // REFUSED as "this server won't serve me" and abandons the resolver, which would break
663        // ordinary client lookups (notably HTTPS/SVCB type 65, issued routinely by browsers for
664        // HTTP/3 + ECH) for the same off-tailnet names whose A/AAAA already forward.
665        QType::Other(_) => forward_or_nodata(view, &canon, buf, id, q, rd),
666    })
667}
668
669/// For a name with no overlay answer, consult the split-DNS routes + recursive resolvers and
670/// either forward (to UDP upstreams), answer authoritatively absent (NXDOMAIN), or fail soft
671/// (SERVFAIL) when an off-tailnet name simply can't be forwarded.
672///
673/// Rcode parity with Go's resolver (`net/dns/resolver/tsdns.go` resolution order + `forwarder.go`):
674/// - A **tailnet-authoritative** name (search-domain suffix) or a **negative split-DNS route**
675///   (`Upstreams::Block` — a route configured with no resolvers, which Go answers authoritatively
676///   from Hosts, so an unmatched name under it is authoritatively absent) → **NXDOMAIN**.
677/// - An **off-tailnet** name we cannot forward — no route and no resolver configured
678///   (`Upstreams::None`), or a route whose resolvers are all filtered out (IPv6-only under the
679///   IPv4-only egress) → **SERVFAIL**, matching Go forwarder.go:1207 ("no upstream resolvers set,
680///   returning SERVFAIL"). A cacheable NXDOMAIN on a transient/structural inability to forward would
681///   make a downstream stub cache the *non-existence* of a real name; SERVFAIL is a soft failure the
682///   stub retries.
683///
684/// Anti-leak: a tailnet-suffix name is authoritative and is never forwarded — neither the name nor
685/// the query leaks to a third-party resolver. (The CGNAT `in-addr.arpa` / `ip6.arpa` reverse-zone
686/// NXDOMAIN guards live in the PTR arm of [`decide`] and are likewise unaffected.)
687fn forward_or_nxdomain(
688    view: &DnsView,
689    canon: &str,
690    buf: &[u8],
691    id: u16,
692    q: &ts_dns_wire::Question,
693    rd: bool,
694) -> Decision {
695    // NXDOMAIN for authoritative-absent names; SERVFAIL for an off-tailnet name we can't forward.
696    // An authoritative NXDOMAIN carries the zone's SOA so a downstream cache bounds how long it
697    // remembers the nonexistence (RFC 2308); a SERVFAIL never does — it asserts nothing to cache,
698    // and we are not authoritative for the name we failed to forward.
699    let nxdomain = |canon: &str| {
700        encode_response(
701            id,
702            q,
703            rd,
704            Rcode::NxDomain,
705            &[],
706            soa_for(view, &q.name, canon).as_ref(),
707        )
708    };
709    let servfail = servfail_for_query(buf, id, q);
710
711    if is_tailnet_name(view, canon) {
712        return Decision::Reply(nxdomain(canon));
713    }
714
715    let (resolvers, recursive) = match view.route_for(canon) {
716        Upstreams::Route(resolvers) => (resolvers, false),
717        Upstreams::Recursive(resolvers) => (resolvers, true),
718        // A negative split-DNS route is authoritative-absent (Go answers it from Hosts): NXDOMAIN.
719        // Go's `localDomains` *is* this route set, so the route's own suffix names the zone.
720        Upstreams::Block => return Decision::Reply(nxdomain(canon)),
721        // No route and no resolver: an off-tailnet name we have nowhere to forward — SERVFAIL, not
722        // a cacheable non-existence (Go forwarder.go:1207).
723        Upstreams::None => return Decision::Reply(servfail),
724    };
725
726    let upstreams: Vec<SocketAddr> = resolvers
727        .iter()
728        .map(DnsResolver::udp_addr)
729        // Anti-leak / IPv6-off: only forward over IPv4 upstreams; never open a v6 socket.
730        .filter(SocketAddr::is_ipv4)
731        .collect();
732    if upstreams.is_empty() {
733        // We had a route but every resolver was filtered out (IPv6-only): we cannot forward this
734        // off-tailnet name, so soft-fail rather than assert non-existence.
735        Decision::Reply(servfail)
736    } else {
737        Decision::Forward {
738            upstreams,
739            query: buf.to_vec(),
740            // All upstreams failing at runtime is also an inability to forward, not a non-existence
741            // (Go forwarder.go:1297-1307): hand the forwarder a SERVFAIL fallback, not NXDOMAIN.
742            servfail,
743            recursive,
744        }
745    }
746}
747
748/// The SERVFAIL this node synthesizes for an off-tailnet name it could not forward: no upstream to
749/// ask, or — as [`Decision::Forward`]'s fallback — every upstream failed without leaving a response
750/// [`forward_walk`] relays.
751///
752/// Go's `servfailResponse` (net/dns/resolver/forwarder.go @
753/// `e2ed432399c9b0fda7aa14e9eb27784d2d893c55`) builds it from the *query's* parsed header: ID,
754/// opcode, TC, RD, RA, AD and CD stay as the client sent them, and only QR, AA and RCODE are set.
755/// That is not [`encode_response`]'s header, which sets RA whenever RD is and clears the opcode and
756/// CD, so the flags words are copied here instead. For the RD=1, RA=0 query every stub resolver
757/// sends, the visible difference is RA: Go's SERVFAIL leaves it clear. Z is not copied, because
758/// `dnsmessage.Header` has no field to carry it. The question is echoed and nothing else is added
759/// — no OPT record, as in Go.
760fn servfail_for_query(buf: &[u8], id: u16, q: &ts_dns_wire::Question) -> Vec<u8> {
761    let mut resp = encode_response(id, q, false, Rcode::ServFail, &[], None);
762    if let ([_, _, hi, lo, ..], [_, _, query_hi, query_lo, ..]) = (resp.as_mut_slice(), buf) {
763        // QR | opcode (0x78) | AA | TC and RD (0x03) as sent.
764        *hi = 0x80 | (query_hi & 0x78) | 0x04 | (query_hi & 0x03);
765        // RA (0x80), AD (0x20) and CD (0x10) as sent; Z (0x40) dropped; RCODE = SERVFAIL.
766        *lo = (query_lo & 0xB0) | RCODE_SERVFAIL;
767    }
768    resp
769}
770
771/// The DNS query types Go's resolver explicitly leaves unimplemented for a tailnet-authoritative
772/// name, answering `RCodeNotImplemented` (NOTIMP) rather than NODATA (`net/dns/resolver/tsdns.go`
773/// `resolveLocal`: `case dns.TypeNS, dns.TypeSOA, dns.TypeAXFR, dns.TypeHINFO`). The numeric type
774/// codes: NS=2, SOA=6, HINFO=13, AXFR=252.
775fn is_unimplemented_tailnet_qtype(qtype: &ts_dns_wire::QType) -> bool {
776    matches!(qtype, ts_dns_wire::QType::Other(2 | 6 | 13 | 252))
777}
778
779/// For a query whose *qtype/qclass* we don't serve authoritatively (anything other than an IN-class
780/// A/AAAA/PTR — e.g. TXT, SRV, MX, HTTPS/SVCB, or a CHAOS-class query): forward it to upstream like
781/// any other name, but for a tailnet-authoritative name return an empty NOERROR (NODATA) instead of
782/// NXDOMAIN — except the NS/SOA/HINFO/AXFR types Go answers NOTIMP for
783/// ([`is_unimplemented_tailnet_qtype`]).
784///
785/// This mirrors Go's resolver: an authoritative name with no record of the requested type returns
786/// `RCodeSuccess` with no answers ("the name exists, but no records of that type"), NOT NXDOMAIN and
787/// NOT REFUSED; a non-authoritative name is forwarded verbatim regardless of qtype. The fork
788/// previously REFUSED every non-A/AAAA/PTR qtype (and every non-IN class) for *all* names, which a
789/// stub resolver reads as "this server won't serve me" — so it would abandon the resolver, breaking
790/// ordinary client lookups (HTTPS/SVCB type 65 issued routinely by browsers for HTTP/3 + ECH, plus
791/// MX/TXT/SRV) for off-tailnet names that A/AAAA queries already forward. Refusing these was never an
792/// anti-leak measure (the same name's A/AAAA already egresses); it was just broken interop.
793///
794/// Anti-leak is preserved: a tailnet-suffix name still never leaves this node (NODATA, not forward),
795/// exactly as the A/AAAA path keeps a positive overlay match authoritative.
796fn forward_or_nodata(
797    view: &DnsView,
798    canon: &str,
799    buf: &[u8],
800    id: u16,
801    q: &ts_dns_wire::Question,
802    rd: bool,
803) -> Decision {
804    // Authoritative tailnet name. For most unsupported types we answer NODATA (empty NOERROR) — the
805    // name exists, we just hold no record of that type. But a small set of types Go's resolver
806    // *explicitly* leaves unimplemented (`net/dns/resolver/tsdns.go` `resolveLocal`:
807    // `case dns.TypeNS, dns.TypeSOA, dns.TypeAXFR, dns.TypeHINFO: return RCodeNotImplemented`) must
808    // answer NOTIMP, not NODATA — a `dig NS`/`SOA`/`HINFO` against the tailnet zone is otherwise a
809    // clean fingerprint distinguishing this fork from real tailscaled. Off-tailnet names are
810    // unaffected (they forward below regardless of type); this NOTIMP applies only to a name we are
811    // authoritative for.
812    if is_tailnet_name(view, canon) {
813        let rcode = if is_unimplemented_tailnet_qtype(&q.qtype) {
814            Rcode::NotImpl
815        } else {
816            Rcode::NoError
817        };
818        // No SOA. Go sets `SOAZone` on a no-data answer only for an A/AAAA/ALL question; a TXT or
819        // SRV miss on a name we serve — and the NOTIMP types — go back bare, as they do upstream.
820        return Decision::Reply(encode_response(id, q, rd, rcode, &[], None));
821    }
822    // Anti-leak parity with the `QType::Ptr` arm: a reverse query for a tailnet CGNAT IPv4
823    // (100.64.0.0/10) or ANY `ip6.arpa` name must NEVER egress to an upstream resolver, regardless
824    // of qtype/class — forwarding it would reveal that a specific tailnet IP was probed. The PTR arm
825    // enforces this (NXDOMAIN) but its guards live only inside that arm; without re-checking here, an
826    // exotic-qtype (TXT/ANY/…) or non-IN-class query for a tailnet reverse name would slip through to
827    // the forward path below. Fail closed to NXDOMAIN, matching the PTR arm's disposition.
828    if is_ip6_arpa(canon) {
829        // No SOA: see the matching guard in [`decide`]'s PTR arm.
830        return Decision::Reply(encode_response(id, q, rd, Rcode::NxDomain, &[], None));
831    }
832    if let Some(octets) = q.name.ptr_to_ipv4()
833        && is_tailnet_cgnat(octets.into())
834    {
835        // Authoritative for the CGNAT reverse zone, so this NXDOMAIN carries its SOA — same
836        // disposition as the PTR arm, whatever the qtype or class that got us here.
837        return Decision::Reply(encode_response(
838            id,
839            q,
840            rd,
841            Rcode::NxDomain,
842            &[],
843            soa_for(view, &q.name, canon).as_ref(),
844        ));
845    }
846    // Off-tailnet, non-reverse-zone: forward verbatim. `forward_or_nxdomain` already forwards
847    // non-tailnet names and soft-fails (SERVFAIL) when no upstream is configured/routable; reuse it
848    // (the tailnet branch above is already handled, so its tailnet→NXDOMAIN and negative-route paths
849    // are unreachable here — this only exercises its off-tailnet forward / SERVFAIL dispositions).
850    forward_or_nxdomain(view, canon, buf, id, q, rd)
851}
852
853/// Client-side plan for a *recursive* forward: keep resolving over local UDP upstreams, or delegate
854/// the query to the active exit node's peerAPI DoH endpoint over the overlay.
855#[derive(Debug, PartialEq, Eq)]
856pub(crate) enum RecursivePlan {
857    /// Forward over UDP to these upstreams. Used when no exit node is active, or when the config
858    /// has `use_with_exit_node` resolvers (kept local even with an exit node selected).
859    Udp(Vec<SocketAddr>),
860    /// Delegate the query to the exit node's peerAPI DoH server at this overlay address.
861    Doh(SocketAddr),
862}
863
864/// Decide whether a recursive forward should stay on local UDP upstreams or be delegated to the
865/// active exit node's DoH endpoint. Pure (no I/O) so the delegation rule is unit-testable.
866///
867/// - No active exit node ([`DnsView::exit_doh`] is `None`) => keep `default_upstreams` (UDP).
868/// - Exit node active, but the config has [`use_with_exit_node`][ts_control::DnsResolver::use_with_exit_node]
869///   resolvers => those resolvers stay local (Go keeps `UseWithExitNode` resolvers when an exit node
870///   is selected); forward to them over UDP, do NOT delegate.
871/// - Exit node active, no kept-local resolvers => delegate to the exit node's DoH. Recursive DNS
872///   then egresses from the exit node, not this host (the whole point of routing through an exit
873///   node: this node's real IP is never used to resolve the peer's public names).
874pub(crate) fn recursive_plan(view: &DnsView, default_upstreams: Vec<SocketAddr>) -> RecursivePlan {
875    let Some(doh) = view.exit_doh else {
876        return RecursivePlan::Udp(default_upstreams);
877    };
878    let kept: Vec<SocketAddr> = view
879        .cfg
880        .resolvers_with_exit_node()
881        .map(DnsResolver::udp_addr)
882        // Anti-leak / IPv6-off: only ever resolve over IPv4 upstreams; never open a v6 socket.
883        .filter(SocketAddr::is_ipv4)
884        .collect();
885    if kept.is_empty() {
886        RecursivePlan::Doh(doh)
887    } else {
888        RecursivePlan::Udp(kept)
889    }
890}
891
892/// Which transport the *client* we are answering reached us over.
893///
894/// The only thing it changes is whether an answer may be marked `TC` for exceeding the
895/// UDP payload size the query advertised. That limit describes the **datagram** we would answer in
896/// (RFC 1035 §4.2.1, RFC 6891 §6.2.3); a client that reached us over TCP has no such bound
897/// (RFC 7766 §8), and marking its answer truncated sends a stub resolver that already retried over
898/// TCP — the retry `TC` asked it to make — straight back into another retry. Go draws the same line:
899/// `checkResponseSizeAndSetTC` is applied on the UDP answer path, while the TCP DNS handler
900/// installed by `acceptTCP`'s `hittingDNS` case writes the answer under a 2-byte length prefix with
901/// no size check (wgengine/netstack/netstack.go, net/dns/resolver/tsdns.go @
902/// 9ea7cba44591e0cd840c6c94d23274dd222059bf).
903#[derive(Clone, Copy, Debug, PartialEq, Eq)]
904pub(crate) enum ClientTransport {
905    /// A UDP client: the EDNS(0)-advertised (or 512-byte) datagram limit applies.
906    Udp,
907    /// A TCP client: no datagram limit applies, so no `TC` bit is added for size.
908    ///
909    /// Two things reach for it: `dns_over_tcp` (compiled with the `tun` feature — the application
910    /// netstack has no TCP listener on `100.100.100.100:53` yet), and the peerAPI DoH *server*,
911    /// which answers as `"tcp"` because the datagram budget belongs to the peer that asked, not to
912    /// us (Go `Resolver.HandlePeerDNSQuery`, see `peerapi_doh::PEER_CLIENT_TRANSPORT`).
913    Tcp,
914}
915
916/// Turn a [`Decision::Forward`] into the plan that will carry it: a recursive forward consults
917/// [`recursive_plan`] (which may delegate to the active exit node's DoH endpoint), a split-DNS
918/// forward always goes to its route's own upstreams over UDP.
919///
920/// One line of logic, but it is the point where "recursive" becomes "may egress from the exit node
921/// instead of this host", so every caller — the UDP serve loop, the `query_dns` handler, the TUN
922/// datapath's `plan_intercept` and the DNS-over-TCP connection loop — reads it from here rather than
923/// spelling the branch out again.
924pub(crate) fn forward_plan(
925    view: &DnsView,
926    upstreams: Vec<SocketAddr>,
927    recursive: bool,
928) -> RecursivePlan {
929    if recursive {
930        recursive_plan(view, upstreams)
931    } else {
932        RecursivePlan::Udp(upstreams)
933    }
934}
935
936/// Cap a forwarded upstream response to a single UDP datagram ([`MAX_UPSTREAM_RESPONSE`]) before
937/// relaying it, then — for a [`ClientTransport::Udp`] client only — mark it truncated if it is
938/// bigger than what `query`'s sender said it can receive ([`check_response_size_and_set_tc`]).
939///
940/// The two checks **compose**; they are not alternatives. The [`MAX_UPSTREAM_RESPONSE`] cap is this
941/// forwarder's own relay bound: when the response is too large it is truncated mid-message, so we
942/// set the `TC` (truncation) flag in the DNS header (byte 2, bit `0x02`) telling the stub resolver
943/// to retry over TCP — relaying a chopped answer without `TC` would surface a
944/// malformed-but-"complete" message. That flag is only set when truncation actually occurs. The
945/// second check is the *client's* bound, and never chops the body.
946///
947/// The cap runs *after* the whole message has been read (see [`MAX_UPSTREAM_RESPONSE`]), so it
948/// bounds what we relay, not what we allocate. The netstack's UDP receive ring (4096) is one byte
949/// wider than the cap (4095), so on the UDP hop the truncating branch is reachable by exactly one
950/// deliverable datagram size — the full-ring 4096-byte answer — which is the same size Go's
951/// `maxResponseBytes+1` read buffer exists to catch.
952///
953/// `via` is the hop the answer came over, and it is why the cap is not unconditional.
954/// [`MAX_UPSTREAM_RESPONSE`] is a **datagram** bound, so it applies to any answer that has to cross
955/// a datagram in either direction: one fetched over the UDP hop ([`UpstreamTransport::Udp`]), or one
956/// relayed to a [`ClientTransport::Udp`] client, which leaves here as a single UDP datagram whatever
957/// it arrived on. The one combination exempt from it is TCP end to end — an answer
958/// [`ask_upstream`] fetched over the TCP hop ([`UpstreamTransport::Tcp`]) *and* handed to a TCP
959/// client, which is the retry path RFC 1035 §4.2.1 exists to provide and the whole point of the
960/// upstream TCP hop: chopping there at 4095 would hand the stub resolver the same truncated answer
961/// it retried over TCP to escape, and the name would still not resolve. Such an answer is bounded
962/// instead by the two-byte length prefix it arrived under (64 KiB), the same bound
963/// `dns_over_tcp`'s framing and [`crate::peerapi_doh`]'s `MAX_CLIENT_RESPONSE` already impose on the
964/// way back out.
965fn cap_response(
966    query: &[u8],
967    mut resp: Vec<u8>,
968    client: ClientTransport,
969    via: UpstreamTransport,
970) -> Vec<u8> {
971    let crosses_a_datagram = client == ClientTransport::Udp || via == UpstreamTransport::Udp;
972    if crosses_a_datagram && resp.len() > MAX_UPSTREAM_RESPONSE {
973        resp.truncate(MAX_UPSTREAM_RESPONSE);
974        // The header is 12 bytes; the TC bit lives in the second flags byte (header byte 2). A
975        // capped datagram is always >= the header length, but guard anyway to never panic.
976        if let Some(flags_hi) = resp.get_mut(2) {
977            *flags_hi |= 0x02;
978        }
979    }
980    check_response_size_and_set_tc(query, resp, client)
981}
982
983/// The RFC 1035 §4.2.1 maximum size of a DNS message carried over UDP by a requestor that did not
984/// advertise an EDNS(0) buffer size. Go's `defaultUDPSize` in `checkResponseSizeAndSetTC`
985/// (net/dns/resolver/forwarder.go @ 9ea7cba44591e0cd840c6c94d23274dd222059bf).
986///
987/// It is **not** a floor under an advertised size. RFC 6891 §6.2.3 says a value below 512 "MUST be
988/// treated as equal to 512", but Go takes the advertised number verbatim (`maxSize = int(ednsSize)`)
989/// and only reaches for this constant when the request carries no usable OPT record at all. A stub
990/// that advertises 200 is told a 300-byte answer is truncated, and a Rust node on the same tailnet
991/// has to say the same thing.
992const NO_EDNS_UDP_LIMIT: usize = 512;
993
994/// The RR TYPE of an EDNS(0) OPT pseudo-record (RFC 6891 §6.1.2). In an OPT record the CLASS field
995/// is repurposed to carry the requestor's UDP payload size.
996const OPT_RR_TYPE: u16 = 41;
997
998/// Wire size of an EDNS(0) OPT record carrying **no** options: NAME (1 byte, the root label) +
999/// TYPE (2) + CLASS (2) + TTL (4) + RDLEN (2). Go's `optFixedBytes`.
1000const OPT_FIXED_BYTES: usize = 11;
1001
1002/// Set the `TC` (truncated) bit on `resp` when it is larger than the UDP payload size the client's
1003/// `query` advertised — the size in its EDNS(0) OPT record, or 512 bytes when it carries none
1004/// (RFC 1035). The body is left **intact**: `TC` tells the stub resolver the answer may not fit the
1005/// datagram it asked for, so it should retry over TCP; it is not a claim that we chopped anything.
1006///
1007/// This is Go's `checkResponseSizeAndSetTC` (net/dns/resolver/forwarder.go @
1008/// 9ea7cba44591e0cd840c6c94d23274dd222059bf), including its first statement — `if family != "udp"
1009/// { return response }`. `client` is that `family`: it names the transport the client **we answer**
1010/// used, never the hop we fetched the answer over. A [`ClientTransport::Tcp`] client has no
1011/// datagram to overflow (RFC 7766 §8) and setting `TC` for it would only send its resolver into
1012/// another retry of a transport that already has no size bound.
1013///
1014/// It runs on every path that returns an answer to a client, exactly as upstream does: the UDP and
1015/// DoH forwards (via [`cap_response`] / `forward_doh`, Go's `forwarder.send`) **and** the answers
1016/// this node builds itself (Go calls it in `Resolver.Query` right after `respond` succeeds). The
1017/// local path is not exempt: `ts_dns_wire` caps an authoritative response at 512 bytes, which only
1018/// bounds it below a *default* client limit — a client that advertised less than that can still be
1019/// overflowed by an answer we composed.
1020pub(crate) fn check_response_size_and_set_tc(
1021    query: &[u8],
1022    mut resp: Vec<u8>,
1023    client: ClientTransport,
1024) -> Vec<u8> {
1025    if client == ClientTransport::Tcp {
1026        return resp;
1027    }
1028    // The header is 12 bytes and the TC bit lives in the second flags byte (header byte 2); a
1029    // response shorter than that is not something we can (or need to) mark. Re-setting a bit that
1030    // is already set is a no-op, so upstream's `truncatedFlagSet` early return needs no analogue.
1031    if resp.len() > client_udp_limit(query)
1032        && let Some(flags_hi) = resp.get_mut(2)
1033    {
1034        *flags_hi |= 0x02;
1035    }
1036    resp
1037}
1038
1039/// The largest UDP DNS response `query`'s sender is willing to receive: the EDNS(0) advertised size
1040/// verbatim, or [`NO_EDNS_UDP_LIMIT`] when the query carries no valid OPT record. Go's
1041/// `getEDNSBufferSize` plus the `hasEDNS` branch of `checkResponseSizeAndSetTC`.
1042fn client_udp_limit(query: &[u8]) -> usize {
1043    find_opt_record(query).map_or(NO_EDNS_UDP_LIMIT, usize::from)
1044}
1045
1046/// Return the requestor's UDP payload size from `query`'s EDNS(0) OPT record, or [`None`] when the
1047/// message carries no OPT record this node will act on.
1048///
1049/// A direct port of Go's `findOPTRecord` (net/dns/resolver/forwarder.go @
1050/// 9ea7cba44591e0cd840c6c94d23274dd222059bf), and deliberately as narrow as it is: the OPT record
1051/// must occupy the **final 11 bytes** of the message, and it must have a root NAME, TYPE `OPT`,
1052/// EDNS version 0 and `RDLEN == 0`. Upstream states the restriction outright — "Only OPT records at
1053/// the very end of the message with no option codes are addressed" — and everything else is
1054/// `(0, nil)`, i.e. *no EDNS*, i.e. the 512-byte RFC 1035 limit.
1055///
1056/// That matters far more often than "malformed query" suggests. A query carrying **any** EDNS
1057/// option — a DNS cookie (RFC 7873) or EDNS Client Subnet, both of which real stub resolvers send
1058/// routinely — has `RDLEN != 0`, so upstream ignores the 4096 it advertises and caps the answer at
1059/// 512. Walking the additional section properly and honouring that 4096 would leave `TC` clear on a
1060/// 900-byte reply that every Go node on the tailnet marks truncated, and the two nodes would hand
1061/// the same stub resolver different answers to the same question. Being generous here is the bug.
1062fn find_opt_record(packet: &[u8]) -> Option<u16> {
1063    /// The only EDNS version defined (RFC 6891 §6.1.3). Go: "Be conservative and don't touch
1064    /// unknown versions."
1065    const EDNS0_VERSION: u8 = 0;
1066
1067    if packet.len() < DNS_HEADER_LEN + OPT_FIXED_BYTES {
1068        return None;
1069    }
1070    // OPT lives in the additional section, so no additional records means no OPT.
1071    if u16::from_be_bytes([packet[10], packet[11]]) == 0 {
1072        return None;
1073    }
1074
1075    let opt = &packet[packet.len() - OPT_FIXED_BYTES..];
1076    if opt[0] != 0 {
1077        return None; // NAME must be the root domain (a single zero byte).
1078    }
1079    if u16::from_be_bytes([opt[1], opt[2]]) != OPT_RR_TYPE {
1080        return None;
1081    }
1082    // CLASS is repurposed as the requestor's UDP payload size (RFC 6891 §6.1.2).
1083    let requested_size = u16::from_be_bytes([opt[3], opt[4]]);
1084    // opt[5] is the extended RCODE: ignored, as upstream ignores it.
1085    if opt[6] != EDNS0_VERSION {
1086        return None;
1087    }
1088    // opt[7..9] are the EDNS flags (DO bit and friends): ignored.
1089    if u16::from_be_bytes([opt[9], opt[10]]) != 0 {
1090        return None; // RDLEN must be 0 — the record carries no options.
1091    }
1092    Some(requested_size)
1093}
1094
1095/// The byte length of a fixed DNS header.
1096const DNS_HEADER_LEN: usize = 12;
1097
1098/// Return the byte range of the first question section (QNAME + QTYPE + QCLASS) within `msg`,
1099/// starting just after the 12-byte header. Returns [`None`] if the name is malformed, uses a
1100/// compression pointer (illegal in a question), or runs past the buffer. Used to byte-compare a
1101/// forwarded query's question against the upstream response's question.
1102fn question_range(msg: &[u8]) -> Option<std::ops::Range<usize>> {
1103    let mut off = DNS_HEADER_LEN;
1104    // Walk the QNAME label sequence to the terminating root label (0x00).
1105    loop {
1106        let len = *msg.get(off)? as usize;
1107        // A compression pointer (top two bits set) is not valid in a question section.
1108        if len & 0xC0 != 0 {
1109            return None;
1110        }
1111        off += 1;
1112        if len == 0 {
1113            break; // root label: QNAME complete.
1114        }
1115        off = off.checked_add(len)?;
1116        if off > msg.len() {
1117            return None;
1118        }
1119    }
1120    // QTYPE (2) + QCLASS (2) follow the name.
1121    let end = off.checked_add(4)?;
1122    if end > msg.len() {
1123        return None;
1124    }
1125    Some(DNS_HEADER_LEN..end)
1126}
1127
1128/// Whether `resp` is a plausible DNS response to `query`: same 16-bit transaction id, the QR
1129/// (response) bit set, and a byte-identical question section (QNAME + QTYPE + QCLASS). Both buffers
1130/// carry the DNS header in the first 12 bytes (id at [0..2], flags at [2..4], QR is the high bit of
1131/// byte 2). Used to reject off-path/forged datagrams before relaying them back to the stub resolver
1132/// as authoritative: matching only the id + QR lets an injector that guesses the id swap in an
1133/// answer for a different question, so we also require the echoed question to match.
1134fn response_matches_query(query: &[u8], resp: &[u8]) -> bool {
1135    if query.len() < DNS_HEADER_LEN || resp.len() < DNS_HEADER_LEN {
1136        return false;
1137    }
1138    let id_matches = query[0..2] == resp[0..2];
1139    let is_response = resp[2] & 0x80 != 0;
1140    if !id_matches || !is_response {
1141        return false;
1142    }
1143    // The response must echo the exact question we asked. Parse both question sections and compare
1144    // their bytes; a parse failure on either side is treated as a non-match (fail closed).
1145    match (question_range(query), question_range(resp)) {
1146        (Some(q), Some(r)) => query[q] == resp[r],
1147        _ => false,
1148    }
1149}
1150
1151/// SERVFAIL (RCODE 2): the upstream could not process the query. A *soft* error to a forwarder — the
1152/// name may still resolve through another resolver.
1153const RCODE_SERVFAIL: u8 = 2;
1154/// REFUSED (RCODE 5): the upstream will not answer this query (policy, an ACL, a view it has no
1155/// data for). Soft for the same reason: another resolver may well serve it.
1156const RCODE_REFUSED: u8 = 5;
1157
1158/// The RCODE `msg` carries: the low 4 bits of header byte 3 (RFC 1035 §4.1.1), or `None` when `msg`
1159/// is too short to have a header. The EDNS(0) *extended* RCODE bits an OPT record can add are
1160/// ignored, as they are in [`find_opt_record`] and in Go's forwarder, which reads the 4-bit
1161/// `dnsmessage.Header.RCode`.
1162fn response_rcode(msg: &[u8]) -> Option<u8> {
1163    msg.get(3).map(|b| b & 0x0F)
1164}
1165
1166/// Whether `msg` carries an RCODE a forwarder must treat as a **soft** error — one that means "this
1167/// resolver could not answer", not "here is the answer": [`RCODE_SERVFAIL`] or [`RCODE_REFUSED`].
1168/// See [`forward_query`] for what that changes.
1169fn is_soft_error(msg: &[u8]) -> bool {
1170    matches!(response_rcode(msg), Some(RCODE_SERVFAIL | RCODE_REFUSED))
1171}
1172
1173/// Forward `query` to each upstream in order over the **overlay** netstack, returning the first
1174/// well-formed response that is not a *soft* error, or — once every upstream has failed — the
1175/// failure [`forward_walk`] chooses to relay, which is often the prebuilt `fallback` buffer.
1176///
1177/// Anti-leak: forwarding goes through the overlay netstack `channel` (a fresh `0.0.0.0:0` overlay
1178/// UDP socket per query, and — whenever the TCP hop runs — a fresh `0.0.0.0:0` overlay TCP
1179/// connection to the same resolver), NEVER a host socket: the real origin IP can't leak to the
1180/// resolver, and split-DNS upstreams reachable only over the tailnet/subnet-router work. Each
1181/// upstream is bounded by [`UPSTREAM_TIMEOUT`] per hop. `client` names the transport the *client* we
1182/// answer used, not the one we fetched over — it sets how long the UDP hop runs alone before TCP
1183/// joins it ([`UDP_RACE_TIMEOUT`]) as well as how the answer is capped; `retry` says whether the
1184/// upstream hop may use TCP at all ([`DnsView::upstream_tcp_retry`]).
1185///
1186/// The socket work is all this function does; which response is relayed to the client is
1187/// [`forward_walk`]'s decision.
1188pub(crate) async fn forward_query(
1189    channel: &Channel,
1190    upstreams: &[SocketAddr],
1191    query: &[u8],
1192    fallback: Vec<u8>,
1193    client: ClientTransport,
1194    retry: TcpRetry,
1195) -> Vec<u8> {
1196    forward_walk(upstreams, query, fallback, client, |upstream| {
1197        ask_upstream(channel, upstream, query, client, retry)
1198    })
1199    .await
1200}
1201
1202/// Which transport an upstream answer was fetched over. Not a property of the client we answer
1203/// (that is [`ClientTransport`]) — it is what [`cap_response`] needs in order to know whether the
1204/// answer has already survived a datagram.
1205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1206enum UpstreamTransport {
1207    /// The UDP hop: one datagram, bounded by the netstack's UDP receive ring.
1208    Udp,
1209    /// The TCP hop: a length-prefixed message, bounded only by its two-byte prefix. Reached only
1210    /// through [`ask_upstream`]'s race: the retry of a truncated UDP answer, or the fallback from a
1211    /// slow or failed UDP hop.
1212    Tcp,
1213}
1214
1215/// One upstream's answer as [`ask_upstream`] hands it to [`forward_walk`]: the bytes, the address
1216/// they arrived from, and the hop they arrived over.
1217#[derive(Debug)]
1218struct UpstreamAnswer {
1219    /// Where the answer came from, **unfiltered** — [`forward_walk`] is what checks it against the
1220    /// upstream we asked.
1221    from: SocketAddr,
1222    /// The DNS response bytes, verbatim.
1223    resp: Vec<u8>,
1224    /// The hop that carried them (see [`UpstreamTransport`]).
1225    via: UpstreamTransport,
1226}
1227
1228/// How one upstream failed, both hops taken together: Go's per-resolver error, which `Race.Start`
1229/// hands back as `errors.Join` of each hop's error, in the order the hops settled
1230/// (util/race/race.go @ `e2ed432399c9b0fda7aa14e9eb27784d2d893c55`).
1231///
1232/// [`forward_walk`] asks two things of that joined error, and these are the two answers. Everything
1233/// else a hop can fail with — a timeout, a connect or framing error, a message that does not answer
1234/// the query — carries no bytes and no refusal, so it only ever leaves the default behind.
1235#[derive(Debug, Default)]
1236struct UpstreamFailure {
1237    /// The first soft-error response (SERVFAIL or REFUSED, [`is_soft_error`]) either hop brought
1238    /// back: what Go's `errors.AsType[rcodeResponseError]` finds first in the joined error.
1239    first_soft: Option<UpstreamAnswer>,
1240    /// Whether either hop was answered REFUSED: Go's `errors.Is(err, errRefused)`, which is true of
1241    /// a joined error when any part of it refused.
1242    refused: bool,
1243}
1244
1245impl UpstreamFailure {
1246    /// A failure whose first soft error is `soft`.
1247    fn soft(soft: UpstreamAnswer) -> Self {
1248        let mut failure = Self::default();
1249        failure.note(soft);
1250        failure
1251    }
1252
1253    /// Add the soft error the next hop to settle came back with.
1254    fn note(&mut self, soft: UpstreamAnswer) {
1255        self.refused |= response_rcode(&soft.resp) == Some(RCODE_REFUSED);
1256        self.first_soft.get_or_insert(soft);
1257    }
1258}
1259
1260/// How long the UDP hop has the upstream to itself before the TCP hop joins the race, when the
1261/// client we answer asked over UDP. A client that asked over TCP gets no head start for UDP at all:
1262/// both hops start together.
1263///
1264/// Go's `udpRaceTimeout` (net/dns/resolver/forwarder.go @
1265/// `e2ed432399c9b0fda7aa14e9eb27784d2d893c55`). It is what lets a resolver whose UDP path drops or
1266/// stalls, but whose TCP path answers, still resolve — in about two seconds rather than not at all.
1267/// It is shorter than [`UPSTREAM_TIMEOUT`] on purpose: waiting that out first would spend the whole
1268/// UDP budget before TCP was ever tried.
1269const UDP_RACE_TIMEOUT: Duration = Duration::from_secs(2);
1270
1271/// Ask one `upstream` for `query` over the overlay and return the answer that came back, or — when
1272/// neither hop produced one — how the upstream failed ([`UpstreamFailure`]).
1273///
1274/// The query is **raced** over UDP and TCP to the same resolver, as Go's forwarder does: `send`
1275/// hands a `firstUDP` and a `thenTCP` closure to `race.New(timeout, firstUDP, thenTCP)`, and
1276/// `util/race`'s `Race.Start` runs the first at once and the second when the timeout elapses or
1277/// the first fails, whichever comes first; the first good answer wins (net/dns/resolver/forwarder.go
1278/// and util/race/race.go @ `e2ed432399c9b0fda7aa14e9eb27784d2d893c55`). [`race_udp_and_tcp`] is
1279/// that race; what it means for one query:
1280///
1281/// - **A slow or failed UDP hop falls back to TCP.** The TCP hop starts after [`UDP_RACE_TIMEOUT`]
1282///   for a [`ClientTransport::Udp`] client, at once for a [`ClientTransport::Tcp`] one, and at once
1283///   whenever the UDP hop has already failed.
1284/// - **A truncated answer is re-asked over TCP**, RFC 1035 §4.2.1. `firstUDP` maps it to an error so
1285///   the race waits for the TCP hop.
1286/// - **A SERVFAIL or REFUSED is a failed hop, not an answer**, on either hop. Go's `sendUDP` and
1287///   `sendTCP` both turn RCODE 2 and 5 into an `rcodeResponseError`, so a soft error over UDP starts
1288///   the TCP hop at once, and a soft error over TCP leaves the race to the UDP hop. The resolver
1289///   answers if either hop does; only when neither does is it a failure, carrying both hops' soft
1290///   errors for [`forward_walk`] to weigh.
1291/// - **The same resolver, never the next one.** Walking on to the next upstream would send the
1292///   query to a resolver the first one already answered — a second party learning a name it was
1293///   never asked about. [`forward_walk`] does the walking; this function only ever talks to the
1294///   `upstream` it was handed.
1295/// - **A failed TCP hop returns the truncated UDP answer**, not `SERVFAIL`. A truncated answer is
1296///   still an answer: its header and question are intact and a stub resolver can act on the `TC`
1297///   bit. Replacing it with a synthesized failure would be strictly worse than what we already had.
1298/// - **A TCP message that does not answer this query is a failed TCP hop**, not an answer. The
1299///   race checks it with [`response_matches_query`] exactly as it checks the datagram, because the
1300///   hop that loses the race is *dropped*: letting a mismatched message win would throw away the
1301///   UDP answer — pending, or held truncated — that [`forward_walk`] would otherwise have relayed,
1302///   and [`forward_walk`] would then discard the mismatch too and resolve nothing.
1303/// - **An answer that fit wins.** Once the UDP hop has one, the TCP hop is dropped (or, before the
1304///   head start runs out, never started) and its answer is never waited for.
1305///
1306/// One place differs from Go, deliberately: Go does **not** re-ask a truncated answer over TCP for
1307/// a UDP client (`firstUDP` returns it as it came "because the client can retry over TCP itself").
1308/// Here it is re-asked for every client, as before, because two of this tree's UDP-labelled clients
1309/// cannot make that retry: the application netstack serves `100.100.100.100:53` over UDP only (the
1310/// `dns_over_tcp` responder is TUN-mode), and `query_dns` is a programmatic caller with no TCP path
1311/// at all. Dropping the retry for them would turn names that resolve today into truncated answers.
1312///
1313/// `retry` is [`DnsView::upstream_tcp_retry`], and [`TcpRetry::Disabled`] shuts the TCP hop out of
1314/// the race entirely — no head-start timer, no fallback, no truncation retry — exactly as Go's
1315/// `thenTCP` waits on the context and never dials under `skipTCP`.
1316///
1317/// Anti-leak: both hops ride the overlay netstack `channel` — the TCP one via `channel.tcp_connect`
1318/// from `0.0.0.0:0`, exactly as the UDP one binds `0.0.0.0:0` there. A host socket would put this
1319/// node's real origin IP in front of the resolver and would not reach a split-DNS upstream that
1320/// only exists inside the tailnet, so the coupling is not a convenience.
1321///
1322/// This is the whole of [`forward_query`]'s I/O, split out from the walk so the policy above it —
1323/// anti-poisoning, the soft-error rules, which response is relayed — is decided (and tested) on
1324/// bytes rather than on sockets. It vouches for nothing about the answer it returns: the source
1325/// address comes back unfiltered precisely so [`forward_walk`] can check it. The checks the race
1326/// does make are not that check moved here — they only decide which hop *wins*, and every answer
1327/// that wins is still handed to [`forward_walk`] to accept or discard on its own terms.
1328async fn ask_upstream(
1329    channel: &Channel,
1330    upstream: SocketAddr,
1331    query: &[u8],
1332    client: ClientTransport,
1333    retry: TcpRetry,
1334) -> Result<UpstreamAnswer, UpstreamFailure> {
1335    race_udp_and_tcp(
1336        upstream,
1337        query,
1338        client,
1339        retry,
1340        || ask_upstream_udp(channel, upstream, query),
1341        || ask_upstream_tcp(channel, upstream, query),
1342    )
1343    .await
1344}
1345
1346/// What the UDP hop produced, as the race reads it.
1347enum UdpOutcome {
1348    /// A good answer: it wins the race.
1349    Answer(UpstreamAnswer),
1350    /// A genuine answer that did not fit the datagram ([`did_not_fit_the_datagram`]): the race
1351    /// waits for the TCP hop, and falls back to this if that hop fails.
1352    Truncated(UpstreamAnswer),
1353    /// A SERVFAIL or REFUSED that does answer this query ([`is_soft_error`]). A failed hop, as Go's
1354    /// `sendUDP` returns it as an `rcodeResponseError`: it starts the TCP hop at once, and it is
1355    /// kept, because it is what [`forward_walk`] relays if the TCP hop does no better.
1356    SoftError(UpstreamAnswer),
1357    /// A datagram from the wrong source, or one that does not echo the question we asked. It is
1358    /// not an answer, and it does not start the TCP hop either — see [`race_udp_and_tcp`].
1359    Unmatched(UpstreamAnswer),
1360    /// Nothing usable came back.
1361    Failed,
1362}
1363
1364/// Read the UDP hop's `(source address, datagram)` as a [`UdpOutcome`].
1365fn classify_udp(
1366    upstream: SocketAddr,
1367    query: &[u8],
1368    got: Option<(SocketAddr, Vec<u8>)>,
1369) -> UdpOutcome {
1370    let Some((from, resp)) = got else {
1371        return UdpOutcome::Failed;
1372    };
1373    let answer = UpstreamAnswer {
1374        from,
1375        resp,
1376        via: UpstreamTransport::Udp,
1377    };
1378    // This repeats `forward_walk`'s check rather than moving it — the answer still goes back
1379    // unfiltered — so that an off-path injector cannot conscript this node into connecting to a
1380    // resolver by spraying forged `TC` datagrams it could never have matched the question of.
1381    if answer.from.ip() != upstream.ip() || !response_matches_query(query, &answer.resp) {
1382        return UdpOutcome::Unmatched(answer);
1383    }
1384    // The RCODE is read before the TC bit, as Go's `sendUDP` returns on it before `firstUDP` ever
1385    // looks for truncation: a truncated SERVFAIL is a SERVFAIL.
1386    if is_soft_error(&answer.resp) {
1387        UdpOutcome::SoftError(answer)
1388    } else if did_not_fit_the_datagram(&answer.resp) {
1389        UdpOutcome::Truncated(answer)
1390    } else {
1391        UdpOutcome::Answer(answer)
1392    }
1393}
1394
1395/// What the TCP hop produced, as the race reads it.
1396enum TcpOutcome {
1397    /// A good answer: it wins the race.
1398    Answer(UpstreamAnswer),
1399    /// A SERVFAIL or REFUSED that answers this query: a failed hop, as Go's `sendTCP` returns it as
1400    /// an `rcodeResponseError`, kept for [`forward_walk`] as the UDP one is.
1401    SoftError(UpstreamAnswer),
1402    /// Nothing usable came back — including a message that does not answer this query.
1403    Failed,
1404}
1405
1406/// Close out a race no hop won. `failure` is what the hops failed with; `unmatched` is a datagram
1407/// the UDP hop brought that does not answer the query, which goes back for [`forward_walk`] to
1408/// discard, as it always has — unless a hop failed with a soft error, whose bytes the walk may
1409/// relay and which the discard would throw away.
1410fn race_lost(
1411    failure: UpstreamFailure,
1412    unmatched: Option<UpstreamAnswer>,
1413) -> Result<UpstreamAnswer, UpstreamFailure> {
1414    match unmatched {
1415        Some(datagram) if failure.first_soft.is_none() => Ok(datagram),
1416        _ => Err(failure),
1417    }
1418}
1419
1420/// The race [`ask_upstream`] runs, over the two hops as plain futures: `udp` returns the
1421/// `(source address, datagram)` of the UDP hop, `tcp` the message body of the TCP hop. `tcp` is
1422/// only called when the TCP hop actually starts, so "was a TCP connection opened" is "was `tcp`
1423/// called".
1424///
1425/// The shape is Go's `Race.Start`, with the UDP hop's result classified as `firstUDP` classifies
1426/// it and the TCP hop's as `sendTCP` does:
1427///
1428/// 1. The UDP hop starts at once. For a [`ClientTransport::Udp`] client it runs alone for
1429///    [`UDP_RACE_TIMEOUT`]; if it settles inside that window, its answer is returned, except that a
1430///    **failed** hop starts TCP straight away (Go closes `startFallback`) — a SERVFAIL or REFUSED
1431///    being one — and a **truncated** one does too (Go's `truncatedResponseError`).
1432/// 2. Otherwise — the head start ran out, or the client asked over TCP and there is none — the TCP
1433///    hop starts and both run. The first good answer wins; a hop that fails leaves the race to the
1434///    other; a truncated UDP answer is held and returned only if TCP does not produce one.
1435///
1436/// When neither hop answers, the result is an [`UpstreamFailure`] holding every soft error the
1437/// hops brought back, in the order they settled — Go's `errors.Join` of the two hops' errors. A
1438/// held truncated answer beats it, as Go's `send` returns a `truncatedResponseError` it finds in the
1439/// joined error in place of the error.
1440///
1441/// A datagram that does not match the query ([`UdpOutcome::Unmatched`]) is the one divergence in
1442/// how a failed UDP hop is treated. Go's `sendUDP` turns a transaction-id mismatch into an error,
1443/// which starts the TCP hop at once; here it never *starts* the TCP hop, so a forged datagram buys
1444/// no connection that silence would not have bought anyway. If the TCP hop is already running it
1445/// is still waited for, and if it is not the datagram is handed on for [`forward_walk`] to discard,
1446/// as it always was.
1447///
1448/// Split from the sockets for the same reason [`forward_walk`] is: the decision — when TCP starts,
1449/// which answer wins — is the part that can regress silently, and here it is testable without a
1450/// netstack.
1451async fn race_udp_and_tcp<UdpFut, TcpFut>(
1452    upstream: SocketAddr,
1453    query: &[u8],
1454    client: ClientTransport,
1455    retry: TcpRetry,
1456    udp: impl FnOnce() -> UdpFut,
1457    tcp: impl FnOnce() -> TcpFut,
1458) -> Result<UpstreamAnswer, UpstreamFailure>
1459where
1460    UdpFut: std::future::Future<Output = Option<(SocketAddr, Vec<u8>)>>,
1461    TcpFut: std::future::Future<Output = Option<Vec<u8>>>,
1462{
1463    // The TCP hop's message as the race reads it. A message that does not echo this query is no
1464    // more use than no message at all: `forward_walk` discards it either way. The difference is
1465    // what it costs on the way, because the hop that loses this race is dropped unfinished: let a
1466    // mismatched message win and the UDP answer it beat is gone, and a query that would have
1467    // resolved resolves as SERVFAIL. So it is scored as a failed hop, which leaves the race to UDP
1468    // — pending, or held truncated — exactly as a connect error would.
1469    let over_tcp = |got: Option<Vec<u8>>| {
1470        let Some(resp) = got else {
1471            return TcpOutcome::Failed;
1472        };
1473        if !response_matches_query(query, &resp) {
1474            tracing::debug!(%upstream, "magic dns dropping mismatched tcp response");
1475            return TcpOutcome::Failed;
1476        }
1477        let answer = UpstreamAnswer {
1478            // The TCP peer is the resolver we connected to, by construction of the handshake, so
1479            // the source address is `upstream` itself and `forward_walk`'s source check passes on
1480            // a fact rather than on a claim in a datagram header.
1481            from: upstream,
1482            resp,
1483            via: UpstreamTransport::Tcp,
1484        };
1485        if is_soft_error(&answer.resp) {
1486            TcpOutcome::SoftError(answer)
1487        } else {
1488            TcpOutcome::Answer(answer)
1489        }
1490    };
1491    // The UDP hop has failed — `failure` is how, `unmatched` any datagram it brought that does not
1492    // answer the query — and the race is the TCP hop's.
1493    let then_tcp = |mut failure: UpstreamFailure,
1494                    unmatched: Option<UpstreamAnswer>,
1495                    got: Option<Vec<u8>>| match over_tcp(got) {
1496        TcpOutcome::Answer(answer) => Ok(answer),
1497        TcpOutcome::SoftError(soft) => {
1498            failure.note(soft);
1499            race_lost(failure, unmatched)
1500        }
1501        TcpOutcome::Failed => race_lost(failure, unmatched),
1502    };
1503    // The TCP hop has failed — `failure` is how — or is not in the race at all, and the race is the
1504    // UDP hop's, whatever it brings: a truncated answer included, which Go returns in place of the
1505    // error.
1506    let then_udp =
1507        |mut failure: UpstreamFailure, got: Option<(SocketAddr, Vec<u8>)>| match classify_udp(
1508            upstream, query, got,
1509        ) {
1510            UdpOutcome::Answer(answer) | UdpOutcome::Truncated(answer) => Ok(answer),
1511            UdpOutcome::SoftError(soft) => {
1512                failure.note(soft);
1513                Err(failure)
1514            }
1515            UdpOutcome::Unmatched(datagram) => race_lost(failure, Some(datagram)),
1516            UdpOutcome::Failed => Err(failure),
1517        };
1518    // A truncated UDP answer is held while the TCP hop retries it; anything short of a TCP answer
1519    // — a failed hop, a mismatched message, a SERVFAIL or REFUSED — returns the held answer.
1520    let retry_truncated = |truncated: UpstreamAnswer, got: Option<Vec<u8>>| match over_tcp(got) {
1521        TcpOutcome::Answer(answer) => answer,
1522        TcpOutcome::SoftError(_) | TcpOutcome::Failed => {
1523            tracing::debug!(
1524                %upstream,
1525                "magic dns upstream tcp hop failed, relaying the udp answer"
1526            );
1527            truncated
1528        }
1529    };
1530
1531    let udp = udp();
1532    if retry == TcpRetry::Disabled {
1533        // Control said no (`dns-forwarder-disable-tcp-retries`): the TCP hop never runs, on any
1534        // arm, so whatever UDP gives us — an answer, truncated or not, a soft error, or nothing —
1535        // is the whole result.
1536        return then_udp(UpstreamFailure::default(), udp.await);
1537    }
1538    let mut udp = std::pin::pin!(udp);
1539
1540    // Step 1: the UDP hop's head start. A TCP client gets none.
1541    if client == ClientTransport::Udp {
1542        let settled = tokio::select! {
1543            biased;
1544            got = &mut udp => Some(classify_udp(upstream, query, got)),
1545            () = tokio::time::sleep(UDP_RACE_TIMEOUT) => None,
1546        };
1547        match settled {
1548            Some(UdpOutcome::Answer(answer) | UdpOutcome::Unmatched(answer)) => {
1549                return Ok(answer);
1550            }
1551            Some(UdpOutcome::Truncated(truncated)) => {
1552                tracing::debug!(%upstream, "magic dns upstream answer truncated, retrying over tcp");
1553                return Ok(retry_truncated(truncated, tcp().await));
1554            }
1555            Some(UdpOutcome::SoftError(soft)) => {
1556                tracing::debug!(
1557                    %upstream,
1558                    rcode = response_rcode(&soft.resp),
1559                    "magic dns upstream udp soft error, trying tcp"
1560                );
1561                return then_tcp(UpstreamFailure::soft(soft), None, tcp().await);
1562            }
1563            Some(UdpOutcome::Failed) => {
1564                tracing::debug!(%upstream, "magic dns upstream udp hop failed, trying tcp");
1565                return then_tcp(UpstreamFailure::default(), None, tcp().await);
1566            }
1567            None => {
1568                tracing::debug!(%upstream, "magic dns upstream udp hop slow, racing tcp");
1569            }
1570        }
1571    }
1572
1573    // Step 2: both hops run; the first good answer wins.
1574    let mut tcp = std::pin::pin!(tcp());
1575    tokio::select! {
1576        biased;
1577        got = &mut udp => match classify_udp(upstream, query, got) {
1578            UdpOutcome::Answer(answer) => Ok(answer),
1579            UdpOutcome::Truncated(held) => Ok(retry_truncated(held, tcp.await)),
1580            UdpOutcome::SoftError(soft) => {
1581                then_tcp(UpstreamFailure::soft(soft), None, tcp.await)
1582            }
1583            UdpOutcome::Unmatched(held) => {
1584                then_tcp(UpstreamFailure::default(), Some(held), tcp.await)
1585            }
1586            UdpOutcome::Failed => then_tcp(UpstreamFailure::default(), None, tcp.await),
1587        },
1588        got = &mut tcp => match over_tcp(got) {
1589            TcpOutcome::Answer(answer) => Ok(answer),
1590            TcpOutcome::SoftError(soft) => then_udp(UpstreamFailure::soft(soft), udp.await),
1591            TcpOutcome::Failed => then_udp(UpstreamFailure::default(), udp.await),
1592        },
1593    }
1594}
1595/// Whether `msg` is an upstream answer that did not fit the datagram it came in — the thing the TCP
1596/// retry exists for. Two ways to be one, and Go's forwarder retries on both:
1597///
1598/// - The resolver said so: the `TC` bit, header byte 2, bit `0x02` (RFC 1035 §4.1.1).
1599/// - It is longer than this forwarder will relay in one datagram ([`MAX_UPSTREAM_RESPONSE`]), so
1600///   [`cap_response`] is about to cut it and set `TC` itself. That is the same "did not fit" Go
1601///   detects by reading `sendUDP` into a `maxResponseBytes+1` buffer and then setting `TC` on the
1602///   reply it returns — which is the very bit its caller then tests. Retrying on it here keeps the
1603///   one deliverable oversize datagram the netstack's 4096-byte receive ring can hand us from being
1604///   a name that resolves only as a cut answer.
1605///
1606/// A message too short to hold a header is neither — it is garbage, and [`forward_walk`] discards
1607/// it.
1608fn did_not_fit_the_datagram(msg: &[u8]) -> bool {
1609    msg.len() > MAX_UPSTREAM_RESPONSE || msg.get(2).is_some_and(|flags_hi| flags_hi & 0x02 != 0)
1610}
1611
1612/// The UDP hop: one `0.0.0.0:0` overlay socket, one datagram out, the first datagram back as
1613/// `(source address, bytes)`. `None` on bind/send/recv failure, [`UPSTREAM_TIMEOUT`], or an empty
1614/// datagram.
1615async fn ask_upstream_udp(
1616    channel: &Channel,
1617    upstream: SocketAddr,
1618    query: &[u8],
1619) -> Option<(SocketAddr, Vec<u8>)> {
1620    let socket = match channel
1621        .udp_bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)))
1622        .await
1623    {
1624        Ok(s) => s,
1625        Err(e) => {
1626            tracing::warn!(error = %e, %upstream, "magic dns upstream bind failed");
1627            return None;
1628        }
1629    };
1630
1631    if let Err(e) = socket.send_to(upstream, query).await {
1632        tracing::warn!(error = %e, %upstream, "magic dns upstream send failed");
1633        return None;
1634    }
1635
1636    match timeout(UPSTREAM_TIMEOUT, socket.recv_from_bytes()).await {
1637        Ok(Ok((from, resp))) if !resp.is_empty() => Some((from, resp.to_vec())),
1638        Ok(Ok(_)) => None,
1639        Ok(Err(e)) => {
1640            tracing::warn!(error = %e, %upstream, "magic dns upstream recv failed");
1641            None
1642        }
1643        Err(_) => {
1644            tracing::debug!(%upstream, "magic dns upstream timed out");
1645            None
1646        }
1647    }
1648}
1649
1650/// The TCP hop: connect to `upstream` over the overlay from `0.0.0.0:0` and exchange one
1651/// length-prefixed message (RFC 1035 §4.2.2). `None` on any failure — connect refused, framing
1652/// error, EOF, or [`UPSTREAM_TIMEOUT`] over the whole exchange — which leaves [`race_udp_and_tcp`]
1653/// with whatever the UDP hop brings, a truncated answer included.
1654///
1655/// The timeout covers connect **and** transfer together, so a resolver that accepts the connection
1656/// and then stalls cannot hold the forward open for longer than a resolver that never answers at
1657/// all.
1658async fn ask_upstream_tcp(
1659    channel: &Channel,
1660    upstream: SocketAddr,
1661    query: &[u8],
1662) -> Option<Vec<u8>> {
1663    let local = SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0));
1664    let exchange = async {
1665        let mut stream = channel
1666            .tcp_connect(local, upstream)
1667            .await
1668            .map_err(|e| std::io::Error::other(e.to_string()))?;
1669        tcp_exchange(&mut stream, query).await
1670    };
1671
1672    match timeout(UPSTREAM_TIMEOUT, exchange).await {
1673        Ok(Ok(resp)) if !resp.is_empty() => Some(resp),
1674        Ok(Ok(_)) => None,
1675        Ok(Err(e)) => {
1676            tracing::warn!(error = %e, %upstream, "magic dns upstream tcp retry failed");
1677            None
1678        }
1679        Err(_) => {
1680            tracing::debug!(%upstream, "magic dns upstream tcp retry timed out");
1681            None
1682        }
1683    }
1684}
1685
1686/// Write `query` and read one response on `stream`, both under the two-byte big-endian length
1687/// prefix DNS-over-TCP frames messages with (RFC 1035 §4.2.2).
1688///
1689/// Generic over the stream so the framing that actually ships is the framing the tests exercise,
1690/// without standing up a netstack — the same reason `dns_over_tcp::serve_conn`, which is this
1691/// framing read from the other end, is generic.
1692///
1693/// The prefix and the query go out in **one** write, as RFC 7766 §8 asks, so the length does not
1694/// leave as its own two-byte segment ahead of the body. The response allocation is bounded by the
1695/// prefix itself: at most 64 KiB, which is every DNS message that can be framed at all.
1696async fn tcp_exchange<S>(stream: &mut S, query: &[u8]) -> std::io::Result<Vec<u8>>
1697where
1698    S: AsyncRead + AsyncWrite + Unpin,
1699{
1700    let len = u16::try_from(query.len()).map_err(|_| {
1701        std::io::Error::new(
1702            std::io::ErrorKind::InvalidInput,
1703            "query too long to frame over tcp",
1704        )
1705    })?;
1706    let mut framed = Vec::with_capacity(2 + query.len());
1707    framed.extend_from_slice(&len.to_be_bytes());
1708    framed.extend_from_slice(query);
1709    stream.write_all(&framed).await?;
1710    stream.flush().await?;
1711
1712    let mut len_buf = [0u8; 2];
1713    stream.read_exact(&mut len_buf).await?;
1714    let len = usize::from(u16::from_be_bytes(len_buf));
1715    if len == 0 {
1716        return Err(std::io::Error::new(
1717            std::io::ErrorKind::InvalidData,
1718            "zero-length dns response over tcp",
1719        ));
1720    }
1721    let mut resp = vec![0u8; len];
1722    stream.read_exact(&mut resp).await?;
1723    Ok(resp)
1724}
1725
1726/// Walk `upstreams` in order, asking `ask` for each one's answer, and decide which response the
1727/// client gets. [`forward_query`] is the only caller; `ask` is its overlay socket exchange
1728/// ([`ask_upstream`]).
1729///
1730/// **REFUSED and SERVFAIL are soft errors, not answers** ([`is_soft_error`]). An upstream that
1731/// answers `REFUSED` (RCODE 5) or `SERVFAIL` (RCODE 2) — on both of [`ask_upstream`]'s hops, since
1732/// a soft error over UDP is first retried over TCP to the same resolver — does not end the forward:
1733/// the walk continues to the next upstream, and how the first failure looked is remembered for when
1734/// the list is exhausted with nothing better. Otherwise a broken or misconfigured resolver that
1735/// refuses instantly beats a healthy one still doing the work, and the stub resolver is handed the
1736/// refusal as though it were the answer — complete DNS failure exactly where a split-DNS route or a
1737/// fallback list names more than one resolver, which is the shape control commonly pushes. Every
1738/// other RCODE — including NXDOMAIN, which is a real answer — ends the walk on the spot.
1739///
1740/// The caller supplies `fallback` (a SERVFAIL response for a forwarded off-tailnet name — an
1741/// all-upstream failure is a soft "couldn't resolve", not a cacheable non-existence, matching Go
1742/// forwarder.go:1297-1307). Keeping it caller-supplied means this fn is rcode-agnostic. When every
1743/// upstream failed, the client gets an upstream's own bytes — which can carry an RFC 8914 extended
1744/// DNS error saying *why* it failed — in exactly the two cases Go's `forwardWithDestChan` relays
1745/// them (net/dns/resolver/forwarder.go @ e2ed432399c9b0fda7aa14e9eb27784d2d893c55, `firstErr` /
1746/// `sawNonRefused`, lines 1309-1383):
1747///
1748/// - **every** upstream was refused: the first failure's first soft error is relayed;
1749/// - otherwise, the first failure's first soft error is relayed only if it is a SERVFAIL.
1750///
1751/// Anything else gets `fallback`. So a REFUSED followed by a SERVFAIL, or by an upstream that never
1752/// answered, is a SERVFAIL — the refusal describes one resolver's policy, not why the forward as a
1753/// whole failed. "Never answered" is every upstream that timed out, errored, or only ever sent
1754/// datagrams the anti-poisoning check discarded; it counts as a failure that is not a refusal, as
1755/// Go's transport errors (and its transaction-id mismatch) do.
1756///
1757/// An upstream's failure is both of its hops together ([`UpstreamFailure`]), read the way Go reads
1758/// the joined error its race returns: the upstream *was refused* when either hop was answered
1759/// REFUSED (`errors.Is(err, errRefused)`), and its soft error is whichever hop's settled first
1760/// (`errors.AsType[rcodeResponseError]`). So a SERVFAIL over UDP and a REFUSED over TCP is a
1761/// refusal whose relayed bytes are the SERVFAIL, as it is in Go.
1762/// "First" upstream is the walk's order here; Go takes it by arrival, since it asks every resolver
1763/// at once.
1764///
1765/// Every relayed answer goes through [`cap_response`], which caps it at [`MAX_UPSTREAM_RESPONSE`]
1766/// unless it was TCP end to end, and — for a [`ClientTransport::Udp`] client — marks it truncated
1767/// when it exceeds what `query` advertised it can receive. That is why an [`UpstreamAnswer`] carries
1768/// the hop it arrived over all the way to here: the walk never inspects it, it only hands it on. A
1769/// relayed soft error does not: Go hands it back as it was read ([`relay_soft_error`]).
1770async fn forward_walk<F, Fut>(
1771    upstreams: &[SocketAddr],
1772    query: &[u8],
1773    fallback: Vec<u8>,
1774    client: ClientTransport,
1775    mut ask: F,
1776) -> Vec<u8>
1777where
1778    F: FnMut(SocketAddr) -> Fut,
1779    Fut: std::future::Future<Output = Result<UpstreamAnswer, UpstreamFailure>>,
1780{
1781    // How the first failing upstream failed: Go's `firstErr`.
1782    let mut first_failure: Option<UpstreamFailure> = None;
1783    // Whether any upstream failed other than by being refused: Go's `sawNonRefused`.
1784    let mut saw_non_refused = false;
1785
1786    for upstream in upstreams {
1787        let failure = match ask(*upstream).await {
1788            // Anti-poisoning: only accept a datagram that came from the upstream we queried and
1789            // whose DNS header matches this query (same transaction id, QR=response bit set). An
1790            // off-path injector racing the real answer is otherwise relayed straight back to the
1791            // stub resolver as authoritative — and this check runs FIRST, so an injected refusal is
1792            // not even eligible to become the soft error a fully-refused forward ends up relaying.
1793            Ok(UpstreamAnswer { from, resp, .. })
1794                if from.ip() != upstream.ip() || !response_matches_query(query, &resp) =>
1795            {
1796                tracing::debug!(%upstream, %from, "magic dns dropping unsolicited/mismatched response");
1797                UpstreamFailure::default()
1798            }
1799            // [`ask_upstream`] hands soft errors back as failures, but a soft error is not an
1800            // answer however it arrives.
1801            Ok(answer) if is_soft_error(&answer.resp) => UpstreamFailure::soft(answer),
1802            Ok(UpstreamAnswer { resp, via, .. }) => return cap_response(query, resp, client, via),
1803            Err(failure) => failure,
1804        };
1805
1806        // A failure is not an answer: note how the first one looked and give the remaining
1807        // upstreams their turn.
1808        tracing::debug!(
1809            %upstream,
1810            refused = failure.refused,
1811            rcode = failure.first_soft.as_ref().and_then(|soft| response_rcode(&soft.resp)),
1812            "magic dns upstream failed, trying the next upstream"
1813        );
1814        saw_non_refused |= !failure.refused;
1815        first_failure.get_or_insert(failure);
1816    }
1817
1818    // Nothing better arrived. Relay an upstream's own bytes (extended DNS error and all) only where
1819    // Go does: the first failure's soft error when every upstream was refused, or when that soft
1820    // error is itself a SERVFAIL. A refusal mixed with any other failure, or nobody answering, is
1821    // `fallback`.
1822    match first_failure.and_then(|failure| failure.first_soft) {
1823        Some(soft) if !saw_non_refused || response_rcode(&soft.resp) == Some(RCODE_SERVFAIL) => {
1824            relay_soft_error(soft, client)
1825        }
1826        _ => fallback,
1827    }
1828}
1829
1830/// An upstream's own SERVFAIL or REFUSED, as [`forward_walk`] relays it when the forward failed.
1831///
1832/// Go relays `rcodeResponseError.res` as it was read. `sendUDP` and `sendTCP` return it from their
1833/// RCODE switch, ahead of the `TC` fix-up, `checkResponseSizeAndSetTC` and `clampEDNSSize` that an
1834/// answer goes through, and neither `forwardWithDestChan` nor `Resolver.Query` size-checks it
1835/// afterwards (net/dns/resolver/forwarder.go and tsdns.go @
1836/// `e2ed432399c9b0fda7aa14e9eb27784d2d893c55`). So, unlike [`cap_response`], this never sets `TC`
1837/// — not for the client's advertised EDNS size, and not for anything else.
1838///
1839/// The one bound it keeps is [`MAX_UPSTREAM_RESPONSE`], applied without `TC`, to a response that
1840/// crosses a datagram. Over the UDP hop that bound is Go's own: `sendUDP` cuts what it read to
1841/// `maxResponseBytes` before it looks at the RCODE. Fetched over TCP for a UDP client, it is this
1842/// node's datagram bound; Go would send the message whole.
1843fn relay_soft_error(soft: UpstreamAnswer, client: ClientTransport) -> Vec<u8> {
1844    let UpstreamAnswer { mut resp, via, .. } = soft;
1845    let crosses_a_datagram = client == ClientTransport::Udp || via == UpstreamTransport::Udp;
1846    if crosses_a_datagram && resp.len() > MAX_UPSTREAM_RESPONSE {
1847        resp.truncate(MAX_UPSTREAM_RESPONSE);
1848    }
1849    resp
1850}
1851
1852/// Run the receive/answer loop for the bound socket until it (or the netstack) goes away.
1853///
1854/// Authoritative answers are sent inline. Forwarded queries are handled on spawned tasks (each
1855/// cloning the overlay `channel`) so a slow upstream never blocks other queries.
1856async fn serve(
1857    socket: netstack::netsock::UdpSocket,
1858    rx: watch::Receiver<Arc<DnsView>>,
1859    channel: Channel,
1860) {
1861    let socket = Arc::new(socket);
1862    let mut forwards = JoinSet::new();
1863    // Bounds concurrent in-flight forwards (see `MAX_INFLIGHT_FORWARDS`); a permit is held for the
1864    // lifetime of each spawned forward task and released on completion.
1865    let inflight = Arc::new(Semaphore::new(MAX_INFLIGHT_FORWARDS));
1866    loop {
1867        let (src, buf) = match socket.recv_from_bytes().await {
1868            Ok(pkt) => pkt,
1869            Err(e) => {
1870                tracing::warn!(error = %e, "magic dns socket recv failed, stopping responder");
1871                return;
1872            }
1873        };
1874
1875        // Read the freshest view per packet.
1876        let view = rx.borrow().clone();
1877
1878        match decide(&view, &buf) {
1879            // Malformed query: drop silently.
1880            None => continue,
1881            Some(Decision::Reply(resp)) => {
1882                // Upstream runs the same size check on a locally-composed answer as on a forwarded
1883                // one (Go `Resolver.Query` calls `checkResponseSizeAndSetTC` right after `respond`).
1884                // An authoritative answer is capped at 512 bytes, but a client that advertised less
1885                // than that is still owed the `TC` bit.
1886                let resp = check_response_size_and_set_tc(&buf, resp, ClientTransport::Udp);
1887                if let Err(e) = socket.send_to(src, &resp).await {
1888                    tracing::warn!(error = %e, %src, "magic dns response send failed");
1889                }
1890            }
1891            Some(Decision::Forward {
1892                upstreams,
1893                query,
1894                servfail,
1895                recursive,
1896            }) => {
1897                // A recursive forward is eligible for exit-node DoH delegation; a split-DNS route
1898                // always stays on its configured upstreams. Decide the plan against the current
1899                // view so a query routed while an exit node is active egresses from that exit node.
1900                let plan = forward_plan(&view, upstreams, recursive);
1901                // Fail closed at the in-flight cap: drop the query (the stub resolver retries or
1902                // times out) rather than spawn an unbounded task that pins an overlay socket for up
1903                // to UPSTREAM_TIMEOUT. The permit is moved into the task as a named `_permit` binding
1904                // (NOT `let _ =`, which would drop it immediately) so it is released only when the
1905                // task body completes.
1906                let Ok(permit) = inflight.clone().try_acquire_owned() else {
1907                    tracing::warn!(
1908                        %src,
1909                        max = MAX_INFLIGHT_FORWARDS,
1910                        "magic dns drop: at max in-flight forwarded queries"
1911                    );
1912                    continue;
1913                };
1914                let socket = socket.clone();
1915                let channel = channel.clone();
1916                // Read the retry switch off the same view this query was decided against, before
1917                // the spawn takes the query away from it.
1918                let retry = view.upstream_tcp_retry();
1919                forwards.spawn(async move {
1920                    let _permit = permit;
1921                    let resp = match plan {
1922                        RecursivePlan::Udp(upstreams) => {
1923                            forward_query(
1924                                &channel,
1925                                &upstreams,
1926                                &query,
1927                                servfail,
1928                                ClientTransport::Udp,
1929                                retry,
1930                            )
1931                            .await
1932                        }
1933                        RecursivePlan::Doh(doh_addr) => {
1934                            crate::peerapi_doh::forward_doh(
1935                                &channel,
1936                                doh_addr,
1937                                &query,
1938                                servfail,
1939                                ClientTransport::Udp,
1940                            )
1941                            .await
1942                        }
1943                    };
1944                    if let Err(e) = socket.send_to(src, &resp).await {
1945                        tracing::warn!(error = %e, %src, "magic dns forwarded response send failed");
1946                    }
1947                });
1948            }
1949        }
1950
1951        // Reap finished forward tasks without blocking. The unreaped completed-handle backlog is
1952        // bounded by MAX_INFLIGHT_FORWARDS (a task spawns only after acquiring a permit, and there
1953        // are at most that many), so this bounds JoinSet memory too — not just the reap cadence.
1954        while forwards.try_join_next().is_some() {}
1955    }
1956}
1957
1958/// The MagicDNS responder actor.
1959///
1960/// Subscribes to control state (for the DNS config + self node) and peer state (for the peer
1961/// database), keeping a [`DnsView`] that the spawned answer loop reads for every query.
1962///
1963/// The peerAPI server task it owns also needs the live packet filter for its DoH source gate. That
1964/// one does **not** arrive on the bus: the `Args` carry a
1965/// [`LiveFilterRx`](crate::packetfilter::LiveFilterRx) written by the packet-filter updater itself,
1966/// because a fail-closed gate cannot use a lossy transport — see that alias for the two ways the bus
1967/// loses a filter, and what each one costs the gate.
1968pub struct MagicDnsActor {
1969    /// Keeps the socket-serving task alive for the lifetime of the actor.
1970    _joinset: JoinSet<()>,
1971    /// The latest view, shared with the answer loop.
1972    view_tx: watch::Sender<Arc<DnsView>>,
1973    /// The runtime [`Env`], retained so each view rebuild (the `StateUpdate` / `PeerState` handlers)
1974    /// can re-read the live [`Env::accept_dns`] cell. Unlike `enable_ipv6` (snapshotted once at
1975    /// spawn), `accept_dns` is runtime-settable via `Device::set_accept_dns`, so it must be read at
1976    /// rebuild time — not captured once — for a toggle to reach the served view.
1977    env: Env,
1978    /// The overlay channel, retained so the [`Query`] handler can run a query through the same
1979    /// forward path the serve loop uses ([`forward_query`] / [`forward_doh`], both binding
1980    /// `0.0.0.0:0` on this channel — never a host socket).
1981    channel: Channel,
1982}
1983
1984/// A programmatic DNS query routed through the live MagicDNS responder (the `100.100.100.100` path),
1985/// for [`Device::query_dns`](crate::Device::query_dns). The handler synthesizes a query packet and
1986/// drives it through the exact same [`decide`]/forward logic as an on-the-wire query, so the result
1987/// (and its anti-leak posture) matches what a tailnet client would observe.
1988pub struct Query {
1989    /// The canonical name to resolve (e.g. `example.com`, no trailing dot).
1990    pub name: String,
1991    /// The DNS query type (`1`=A, `28`=AAAA, `12`=PTR, or any other RFC 1035 TYPE).
1992    pub qtype: u16,
1993}
1994
1995/// The outcome of a `Query`: the raw DNS response bytes, the RCODE, and which upstream resolvers
1996/// (if any) were consulted. The response is returned as raw bytes (matching Go `LocalClient.QueryDNS`)
1997/// rather than parsed records — this fork's wire codec has no answer-record decoder.
1998///
1999/// (`Query` is the crate-internal actor message; not linked here as it is a private item — a
2000/// `pub` doc cannot intra-doc-link to it without erroring under the doc-lint gate.)
2001#[derive(Debug, Clone, kameo::Reply)]
2002pub struct DnsQueryResult {
2003    /// The raw DNS response datagram (header + question + any answer records).
2004    pub response: Vec<u8>,
2005    /// The RCODE from the response header's low 4 bits (`0`=NoError, `2`=SERVFAIL, `3`=NXDOMAIN,
2006    /// `5`=Refused, …).
2007    pub rcode: u8,
2008    /// The upstream resolver(s) the query was forwarded to. For a UDP forward this is the candidate
2009    /// list tried in order (the forwarder returns on the first that answers); for an exit-node DoH
2010    /// forward it is the single DoH endpoint. Empty for a locally-answered query (an authoritative
2011    /// tailnet name, a NODATA, or a fail-closed NXDOMAIN — nothing egressed).
2012    pub resolvers_consulted: Vec<SocketAddr>,
2013}
2014
2015impl kameo::Actor for MagicDnsActor {
2016    type Args = (Env, Channel, crate::packetfilter::LiveFilterRx);
2017    type Error = Error;
2018
2019    /// `filter_rx` is the live compiled packet filter for the peerAPI DoH source gate
2020    /// (`peerapi_doh::dns_source_allowed`, Go `isPeerAPIDNSAllowed`), handed in from
2021    /// `Runtime::spawn` rather than subscribed to here. It is deliberately not part of [`DnsView`]:
2022    /// it is not DNS data and it updates on its own cadence (a netmap can carry a new filter without
2023    /// a new DNS config, and the other way round).
2024    async fn on_start(
2025        (env, channel, filter_rx): Self::Args,
2026        slf: ActorRef<Self>,
2027    ) -> Result<Self, Self::Error> {
2028        env.subscribe::<Arc<ts_control::StateUpdate>>(&slf).await?;
2029        env.subscribe::<Arc<PeerState>>(&slf).await?;
2030        env.subscribe::<crate::route_updater::ActiveExitNode>(&slf)
2031            .await?;
2032
2033        // Seed the view with the runtime's IPv6 gate (default off) and the current accept-dns value.
2034        // Subsequent control/peer updates clone-and-modify this view: `enable_ipv6` (set once here)
2035        // is preserved, while `accept_dns` is re-read live from `Env` on every rebuild (it is
2036        // runtime-settable). The seed value is moot — no query is served before the first
2037        // StateUpdate — but seeding it keeps the pre-update view internally consistent.
2038        let (view_tx, view_rx) = watch::channel(Arc::new(DnsView {
2039            enable_ipv6: env.enable_ipv6,
2040            accept_dns: env.accept_dns(),
2041            ..DnsView::default()
2042        }));
2043
2044        let mut joinset = JoinSet::new();
2045
2046        // Bind the MagicDNS socket. If the bind fails we still start (fail closed: the actor just
2047        // never answers anything) so a transient bind error doesn't take down the runtime.
2048        let addr = SocketAddr::from((MAGIC_DNS_IP, MAGIC_DNS_PORT));
2049        match channel.udp_bind(addr).await {
2050            Ok(socket) => {
2051                tracing::debug!(%addr, "magic dns responder bound");
2052                joinset.spawn(serve(socket, view_rx.clone(), channel.clone()));
2053            }
2054            Err(e) => {
2055                tracing::error!(error = %e, %addr, "magic dns udp bind failed; responder inert");
2056            }
2057        }
2058
2059        // When this node advertises a peerAPI port, run the single peerAPI server on the same shared
2060        // view. It routes `/dns-query` to the exit-node DoH handler (recursive resolution gated by
2061        // `forward_exit_egress`, see `peerapi_doh`) and `/v0/put/<name>` to the Taildrop receive
2062        // handler when a store is configured (access-gated, fail-closed, see `peerapi`).
2063        if let Some(port) = env.peerapi_port {
2064            let channel = channel.clone();
2065            let view_rx = view_rx.clone();
2066            let forward_exit_egress = env.forward_exit_egress;
2067            let taildrop = env.taildrop_store.clone();
2068            let funnel_ingress = env.funnel_ingress.clone();
2069            joinset.spawn(crate::peerapi::serve(
2070                channel,
2071                port,
2072                view_rx,
2073                filter_rx,
2074                forward_exit_egress,
2075                env.exit_host_resolver(),
2076                taildrop,
2077                funnel_ingress,
2078            ));
2079        }
2080
2081        Ok(Self {
2082            _joinset: joinset,
2083            view_tx,
2084            env,
2085            channel,
2086        })
2087    }
2088}
2089
2090/// A bare SERVFAIL response header for a [`Query`] whose name could not be encoded into a
2091/// well-formed query (a non-ASCII label or an over-255-byte name). A 12-byte header with QR=1 (this
2092/// is a response) and RCODE=2 (server failure); no question or answer section (we never produced a
2093/// parseable question). Lets `query_dns` return a definite, honest RCODE instead of an empty buffer
2094/// that would read back as a fabricated NoError.
2095fn servfail_response() -> Vec<u8> {
2096    let mut resp = vec![0u8; 12];
2097    // Flags: QR=1 (byte 2, 0x80) + RCODE=2 (low nibble of byte 3). All other bits clear.
2098    resp[2] = 0x80;
2099    resp[3] = 0x02;
2100    resp
2101}
2102
2103impl Message<Query> for MagicDnsActor {
2104    type Reply = DnsQueryResult;
2105
2106    async fn handle(&mut self, query: Query, _ctx: &mut Context<Self, Self::Reply>) -> Self::Reply {
2107        // Synthesize a query packet and drive it through the SAME decide/forward path the serve loop
2108        // uses, against the freshest view — so the result and its anti-leak posture exactly match an
2109        // on-the-wire query. The id is fixed (0): a programmatic query has no concurrent-demux need,
2110        // and `response_matches_query` validates the echoed id against this same buffer.
2111        //
2112        // Normalize the name into labels: strip a single trailing dot (an FQDN's root marker — Go's
2113        // `dnsname.ToFQDN` does the same) and drop empty labels. An empty label would otherwise encode
2114        // as a lone `0x00`, identical to the QNAME root terminator, truncating the wire query and
2115        // corrupting the QTYPE/QCLASS that follow.
2116        let trimmed = query.name.strip_suffix('.').unwrap_or(&query.name);
2117        let labels: Vec<String> = trimmed
2118            .split('.')
2119            .filter(|label| !label.is_empty())
2120            .map(str::to_owned)
2121            .collect();
2122        let qtype = match query.qtype {
2123            1 => ts_dns_wire::QType::A,
2124            28 => ts_dns_wire::QType::Aaaa,
2125            12 => ts_dns_wire::QType::Ptr,
2126            other => ts_dns_wire::QType::Other(other),
2127        };
2128        // Class IN (1) — the only class the responder serves authoritatively (a non-IN class still
2129        // forwards via `forward_or_nodata`, matching the on-the-wire path).
2130        let buf = ts_dns_wire::encode_query(0, &ts_dns_wire::Name(labels), &qtype, 1);
2131
2132        let view = self.view_tx.borrow().clone();
2133
2134        let (response, resolvers_consulted) = match decide(&view, &buf) {
2135            // `decide` returns `None` only when `decode_query` rejects the buffer we just built. With
2136            // the name normalized above that can still happen for a name `encode_query` accepts but
2137            // `decode_query` rejects — a non-ASCII/IDN label (the caller must pass punycode) or a name
2138            // whose wire form exceeds 255 bytes. Surface a SERVFAIL (RCODE 2: "could not process")
2139            // rather than an empty buffer that would read back as a fabricated NoError. The serve loop
2140            // silently drops here (the on-wire client times out); a programmatic caller gets a
2141            // definite, honest error instead.
2142            None => (servfail_response(), Vec::new()),
2143            Some(Decision::Reply(resp)) => (
2144                check_response_size_and_set_tc(&buf, resp, ClientTransport::Udp),
2145                Vec::new(),
2146            ),
2147            Some(Decision::Forward {
2148                upstreams,
2149                query,
2150                servfail,
2151                recursive,
2152            }) => {
2153                let plan = forward_plan(&view, upstreams, recursive);
2154                match plan {
2155                    RecursivePlan::Udp(upstreams) => {
2156                        let resp = forward_query(
2157                            &self.channel,
2158                            &upstreams,
2159                            &query,
2160                            servfail,
2161                            ClientTransport::Udp,
2162                            view.upstream_tcp_retry(),
2163                        )
2164                        .await;
2165                        (resp, upstreams)
2166                    }
2167                    RecursivePlan::Doh(doh_addr) => {
2168                        let resp = crate::peerapi_doh::forward_doh(
2169                            &self.channel,
2170                            doh_addr,
2171                            &query,
2172                            servfail,
2173                            ClientTransport::Udp,
2174                        )
2175                        .await;
2176                        // The query egressed via the exit node's DoH endpoint, not a local UDP
2177                        // upstream — report the DoH address as the resolver consulted.
2178                        (resp, vec![doh_addr])
2179                    }
2180                }
2181            }
2182        };
2183
2184        // RCODE is the low 4 bits of the second flags byte (header byte 3).
2185        let rcode = response_rcode(&response).unwrap_or(0);
2186
2187        DnsQueryResult {
2188            response,
2189            rcode,
2190            resolvers_consulted,
2191        }
2192    }
2193}
2194
2195impl Message<Arc<ts_control::StateUpdate>> for MagicDnsActor {
2196    type Reply = ();
2197
2198    async fn handle(
2199        &mut self,
2200        update: Arc<ts_control::StateUpdate>,
2201        _ctx: &mut Context<Self, Self::Reply>,
2202    ) {
2203        // Re-read the live accept-dns cell on every rebuild (it is runtime-settable via
2204        // `Device::set_accept_dns`); `enable_ipv6` is preserved from the seed (set once at spawn).
2205        let accept_dns = self.env.accept_dns();
2206        self.view_tx.send_modify(|view| {
2207            let mut next = (**view).clone();
2208            // Most responses are deltas that carry neither the DNS config nor the self node; keep
2209            // the last ones seen rather than resetting them (Go keeps both in its netmap until a
2210            // response replaces them). Resetting dropped this node's own address, which the peerAPI
2211            // Host check needs, and its MagicDNS config on every delta.
2212            if let Some(cfg) = &update.dns_config {
2213                next.cfg = cfg.clone();
2214            }
2215            if let Some(node) = &update.node {
2216                next.self_node = Some(node.clone());
2217            }
2218            next.accept_dns = accept_dns;
2219            *view = Arc::new(next);
2220        });
2221    }
2222}
2223
2224impl Message<Arc<PeerState>> for MagicDnsActor {
2225    type Reply = ();
2226
2227    async fn handle(&mut self, state: Arc<PeerState>, _ctx: &mut Context<Self, Self::Reply>) {
2228        // Re-read the live accept-dns cell on every rebuild: `Device::set_accept_dns` triggers a
2229        // `RepublishState` that lands here, so this is the path that re-applies the gate after a
2230        // runtime toggle (covers the netstack responder AND the peerAPI DoH server sharing the view).
2231        let accept_dns = self.env.accept_dns();
2232        self.view_tx.send_modify(|view| {
2233            let mut next = (**view).clone();
2234            next.peers = Some(state.peers.clone());
2235            next.accept_dns = accept_dns;
2236            *view = Arc::new(next);
2237        });
2238    }
2239}
2240
2241impl Message<crate::route_updater::ActiveExitNode> for MagicDnsActor {
2242    type Reply = ();
2243
2244    async fn handle(
2245        &mut self,
2246        active: crate::route_updater::ActiveExitNode,
2247        _ctx: &mut Context<Self, Self::Reply>,
2248    ) {
2249        // Cache the active exit node's DoH endpoint so the serve loop delegates recursive queries
2250        // to it. `None` (no exit node, or one that can't proxy DNS) keeps recursion local. Resolving
2251        // the address here — once, from the route updater's authoritative selection — means the
2252        // serve loop never re-resolves the selector.
2253        let exit_doh = active.node.as_ref().and_then(|n| n.peerapi_doh_addr());
2254        self.view_tx.send_modify(|view| {
2255            let mut next = (**view).clone();
2256            next.exit_doh = exit_doh;
2257            *view = Arc::new(next);
2258        });
2259    }
2260}
2261
2262#[cfg(test)]
2263mod tests {
2264    use ts_control::{StableNodeId, TailnetAddress};
2265
2266    use super::*;
2267
2268    /// Test wrapper: run [`decide`] and extract the reply bytes. These tests configure no
2269    /// upstream resolvers, so an unresolved name fails closed to a `Reply` (NXDOMAIN), never a
2270    /// `Forward`; a `Forward` here is a bug and panics.
2271    fn answer(view: &DnsView, buf: &[u8]) -> Option<Vec<u8>> {
2272        match decide(view, buf)? {
2273            Decision::Reply(resp) => Some(resp),
2274            Decision::Forward { .. } => panic!("unexpected forward in authoritative-only test"),
2275        }
2276    }
2277
2278    /// Build a `Node` named `host.user.ts.net` with a known v4/v6 tailnet address.
2279    fn test_node() -> Node {
2280        Node {
2281            id: 1,
2282            stable_id: StableNodeId("n1".to_string()),
2283            hostname: "host".to_string(),
2284            user_id: 0,
2285            tailnet: Some("user.ts.net".to_string()),
2286            tags: vec![],
2287            addresses: vec![
2288                "100.64.0.1/32".parse().unwrap(),
2289                "fd7a::1/128".parse().unwrap(),
2290            ],
2291            tailnet_address: TailnetAddress {
2292                ipv4: "100.64.0.1/32".parse().unwrap(),
2293                ipv6: "fd7a::1/128".parse().unwrap(),
2294            },
2295            node_key: [0u8; 32].into(),
2296            node_key_expiry: None,
2297            expired: false,
2298            online: None,
2299            last_seen: None,
2300            key_signature: vec![],
2301            machine_key: None,
2302            disco_key: None,
2303            accepted_routes: vec![],
2304            underlay_addresses: vec![],
2305            derp_region: None,
2306            cap: Default::default(),
2307            cap_map: Default::default(),
2308            peerapi_port: None,
2309            peerapi_dns_proxy: false,
2310            is_wireguard_only: false,
2311            exit_node_dns_resolvers: vec![],
2312            stable_tailnet_id: None,
2313            peer_relay: false,
2314            ssh_host_keys: vec![],
2315            service_vips: Default::default(),
2316            unsigned_peer_api_only: false,
2317        }
2318    }
2319
2320    /// A view with MagicDNS on and a single peer in the db.
2321    fn view_with_peer() -> DnsView {
2322        let mut db = PeerDb::default();
2323        db.upsert(&test_node());
2324
2325        DnsView {
2326            cfg: DnsConfig {
2327                magic_dns: true,
2328                search_domains: vec!["user.ts.net".to_string()],
2329                ..Default::default()
2330            },
2331            peers: Some(Arc::new(db)),
2332            self_node: None,
2333            exit_doh: None,
2334            enable_ipv6: false,
2335            accept_dns: true,
2336        }
2337    }
2338
2339    /// Build a raw DNS query buffer for `labels` with the given id, qtype, qclass.
2340    fn build_query(id: u16, labels: &[&str], qtype: u16, qclass: u16) -> Vec<u8> {
2341        let mut buf: Vec<u8> = Vec::new();
2342        buf.extend_from_slice(&id.to_be_bytes());
2343        buf.extend_from_slice(&0u16.to_be_bytes()); // flags: QR=0 (query)
2344        buf.extend_from_slice(&1u16.to_be_bytes()); // QDCOUNT
2345        buf.extend_from_slice(&0u16.to_be_bytes()); // ANCOUNT
2346        buf.extend_from_slice(&0u16.to_be_bytes()); // NSCOUNT
2347        buf.extend_from_slice(&0u16.to_be_bytes()); // ARCOUNT
2348        for label in labels {
2349            buf.push(label.len() as u8);
2350            buf.extend_from_slice(label.as_bytes());
2351        }
2352        buf.push(0); // root label
2353        buf.extend_from_slice(&qtype.to_be_bytes());
2354        buf.extend_from_slice(&qclass.to_be_bytes());
2355        buf
2356    }
2357
2358    /// `build_query` plus an EDNS(0) OPT record in the additional section advertising `udp_size` as
2359    /// the requestor's UDP payload size (RFC 6891: root NAME, TYPE 41, CLASS = the size), in the
2360    /// only shape Go's `findOPTRecord` accepts: last record in the message, version 0, `RDLEN` 0.
2361    fn build_edns_query(
2362        id: u16,
2363        labels: &[&str],
2364        qtype: u16,
2365        qclass: u16,
2366        udp_size: u16,
2367    ) -> Vec<u8> {
2368        let mut buf = build_query(id, labels, qtype, qclass);
2369        buf[11] = 1; // ARCOUNT = 1
2370        buf.push(0); // NAME: root
2371        buf.extend_from_slice(&41u16.to_be_bytes()); // TYPE: OPT
2372        buf.extend_from_slice(&udp_size.to_be_bytes()); // CLASS: requestor's UDP payload size
2373        buf.extend_from_slice(&0u32.to_be_bytes()); // TTL: extended rcode + flags
2374        buf.extend_from_slice(&0u16.to_be_bytes()); // RDLENGTH: no options
2375        buf
2376    }
2377
2378    /// Like [`build_edns_query`] but with one EDNS option in the OPT record's RDATA, so `RDLEN` is
2379    /// non-zero — the shape a stub resolver sending a DNS cookie (option code 10) produces.
2380    fn build_edns_query_with_option(
2381        id: u16,
2382        labels: &[&str],
2383        qtype: u16,
2384        qclass: u16,
2385        udp_size: u16,
2386        option_code: u16,
2387        option_data: &[u8],
2388    ) -> Vec<u8> {
2389        let mut buf = build_edns_query(id, labels, qtype, qclass, udp_size);
2390        let rdata_len = 4 + option_data.len();
2391        let rdlength_at = buf.len() - 2;
2392        buf[rdlength_at..].copy_from_slice(&(rdata_len as u16).to_be_bytes());
2393        buf.extend_from_slice(&option_code.to_be_bytes());
2394        buf.extend_from_slice(&(option_data.len() as u16).to_be_bytes());
2395        buf.extend_from_slice(option_data);
2396        buf
2397    }
2398
2399    /// Parse a response header: returns `(id, rcode, ancount)`.
2400    fn parse_header(resp: &[u8]) -> (u16, u8, u16) {
2401        let id = u16::from_be_bytes([resp[0], resp[1]]);
2402        let flags = u16::from_be_bytes([resp[2], resp[3]]);
2403        let ancount = u16::from_be_bytes([resp[6], resp[7]]);
2404        (id, (flags & 0x000F) as u8, ancount)
2405    }
2406
2407    #[test]
2408    fn a_query_for_known_peer_answers_v4() {
2409        let view = view_with_peer();
2410        let buf = build_query(0x1234, &["host", "user", "ts", "net"], 1, 1);
2411
2412        let resp = answer(&view, &buf).expect("answers");
2413        let (id, rcode, ancount) = parse_header(&resp);
2414        assert_eq!(id, 0x1234);
2415        assert_eq!(rcode, 0, "NoError");
2416        assert_eq!(ancount, 1);
2417
2418        // The trailing RDATA of the single A record is the peer's tailnet v4 octets.
2419        let tail = &resp[resp.len() - 4..];
2420        assert_eq!(tail, &[100, 64, 0, 1]);
2421    }
2422
2423    #[test]
2424    fn aaaa_query_for_known_peer_is_nodata_when_ipv6_off() {
2425        // Gate OFF (default): an AAAA query for a known overlay peer must return NoError with an
2426        // empty answer (NODATA) — NOT the overlay v6 address, which the IPv4-only client can't
2427        // route. This is the anti-fingerprint / no-dead-connections posture.
2428        let view = view_with_peer();
2429        assert!(!view.enable_ipv6, "default gate is off");
2430        let buf = build_query(0x5, &["host", "user", "ts", "net"], 28, 1);
2431
2432        let resp = answer(&view, &buf).expect("answers");
2433        let (_, rcode, ancount) = parse_header(&resp);
2434        assert_eq!(rcode, 0, "NoError (NODATA)");
2435        assert_eq!(ancount, 0, "empty answer: no AAAA handed out with IPv6 off");
2436    }
2437
2438    #[test]
2439    fn a_query_still_resolves_when_ipv6_off() {
2440        // Gate OFF must not touch the A (v4) path: the v4 answer is byte-for-byte unchanged.
2441        let view = view_with_peer();
2442        let buf = build_query(0x6, &["host", "user", "ts", "net"], 1, 1);
2443
2444        let resp = answer(&view, &buf).expect("answers");
2445        let (_, rcode, ancount) = parse_header(&resp);
2446        assert_eq!(rcode, 0, "NoError");
2447        assert_eq!(ancount, 1);
2448        let tail = &resp[resp.len() - 4..];
2449        assert_eq!(tail, &[100, 64, 0, 1]);
2450    }
2451
2452    #[test]
2453    fn aaaa_query_for_known_peer_answers_v6_when_ipv6_on() {
2454        // Gate ON: historical behavior — answer AAAA from the overlay v6 address.
2455        let mut view = view_with_peer();
2456        view.enable_ipv6 = true;
2457        let buf = build_query(0x5, &["host", "user", "ts", "net"], 28, 1);
2458
2459        let resp = answer(&view, &buf).expect("answers");
2460        let (_, rcode, ancount) = parse_header(&resp);
2461        assert_eq!(rcode, 0, "NoError");
2462        assert_eq!(ancount, 1);
2463
2464        let expected = "fd7a::1".parse::<std::net::Ipv6Addr>().unwrap().octets();
2465        let tail = &resp[resp.len() - 16..];
2466        assert_eq!(tail, expected);
2467    }
2468
2469    #[test]
2470    fn aaaa_for_unknown_tailnet_name_is_nxdomain_not_forwarded_with_ipv6_off() {
2471        // Anti-leak, unchanged by the gate: an AAAA for a name under the tailnet suffix that has no
2472        // overlay match still fails closed to NXDOMAIN — never forwarded to a recursive upstream,
2473        // even with resolvers configured. (Gate OFF only changes the *positive* overlay match into
2474        // NODATA; a non-match still routes through `forward_or_nxdomain`.)
2475        let mut db = PeerDb::default();
2476        db.upsert(&test_node());
2477        let view = DnsView {
2478            cfg: DnsConfig {
2479                magic_dns: true,
2480                search_domains: vec!["user.ts.net".to_string()],
2481                fallback_resolvers: vec![DnsResolver {
2482                    transport: ts_control::ResolverTransport::Udp("9.9.9.9:53".parse().unwrap()),
2483                    use_with_exit_node: false,
2484                }],
2485                ..Default::default()
2486            },
2487            peers: Some(Arc::new(db)),
2488            self_node: None,
2489            exit_doh: None,
2490            enable_ipv6: false,
2491            accept_dns: true,
2492        };
2493        let buf = build_query(0x5A, &["ghost", "user", "ts", "net"], 28, 1);
2494
2495        match decide(&view, &buf).expect("decides") {
2496            Decision::Reply(resp) => {
2497                let (_, rcode, _) = parse_header(&resp);
2498                assert_eq!(rcode, 3, "NxDomain: tailnet AAAA not leaked upstream");
2499            }
2500            Decision::Forward { .. } => panic!("tailnet AAAA must never be forwarded"),
2501        }
2502    }
2503
2504    #[test]
2505    fn bare_hostname_resolves() {
2506        // The name index also stores the bare hostname.
2507        let view = view_with_peer();
2508        let buf = build_query(0x7, &["host"], 1, 1);
2509
2510        let resp = answer(&view, &buf).expect("answers");
2511        let (_, rcode, ancount) = parse_header(&resp);
2512        assert_eq!(rcode, 0);
2513        assert_eq!(ancount, 1);
2514    }
2515
2516    #[test]
2517    fn unknown_off_tailnet_name_with_no_upstream_is_servfail() {
2518        // An off-tailnet name with no resolver configured cannot be forwarded. Go answers SERVFAIL
2519        // (a soft "couldn't resolve"), not NXDOMAIN — asserting non-existence of a real name we
2520        // simply have no upstream for would poison a downstream stub's negative cache. (A *tailnet*
2521        // name with no overlay match stays NXDOMAIN — see `tailnet_name_is_never_forwarded` — and a
2522        // negative split-DNS route stays NXDOMAIN — see `negative_route_is_nxdomain_not_forwarded`.)
2523        let view = view_with_peer();
2524        let buf = build_query(0x9, &["nope", "example", "com"], 1, 1);
2525
2526        let resp = answer(&view, &buf).expect("answers");
2527        let (_, rcode, ancount) = parse_header(&resp);
2528        assert_eq!(
2529            rcode, 2,
2530            "ServFail: off-tailnet name, nothing to forward to"
2531        );
2532        assert_eq!(ancount, 0);
2533    }
2534
2535    #[test]
2536    fn magic_dns_off_is_refused() {
2537        // Fail closed: with MagicDNS disabled, even a known name is refused.
2538        let mut view = view_with_peer();
2539        view.cfg.magic_dns = false;
2540        let buf = build_query(0xAB, &["host", "user", "ts", "net"], 1, 1);
2541
2542        let resp = answer(&view, &buf).expect("answers");
2543        let (_, rcode, ancount) = parse_header(&resp);
2544        assert_eq!(rcode, 5, "Refused");
2545        assert_eq!(ancount, 0);
2546    }
2547
2548    #[test]
2549    fn accept_dns_false_refuses_otherwise_answerable_query() {
2550        // The accept-dns gate (Go `CorpDNS`): with `accept_dns == false` the node ignores the
2551        // tailnet DNS config, so even a known peer name that would normally answer authoritatively is
2552        // REFUSED (the responder serves nothing) — mirroring Go applying an empty `dns.Config`.
2553        let mut view = view_with_peer();
2554        assert!(view.cfg.magic_dns, "MagicDNS itself is on");
2555        view.accept_dns = false;
2556        let buf = build_query(0xDD, &["host", "user", "ts", "net"], 1, 1);
2557
2558        let resp = answer(&view, &buf).expect("answers");
2559        let (_, rcode, ancount) = parse_header(&resp);
2560        assert_eq!(rcode, 5, "Refused: accept_dns off ⇒ serve nothing");
2561        assert_eq!(ancount, 0);
2562
2563        // Flip accept_dns back ON (the config was never destroyed, only gated): the same query now
2564        // answers authoritatively — proving the OFF→ON restore is automatic.
2565        view.accept_dns = true;
2566        let resp = answer(&view, &buf).expect("answers");
2567        let (_, rcode, ancount) = parse_header(&resp);
2568        assert_eq!(rcode, 0, "NoError: accept_dns on ⇒ the known peer answers");
2569        assert_eq!(ancount, 1);
2570        let tail = &resp[resp.len() - 4..];
2571        assert_eq!(tail, &[100, 64, 0, 1], "the peer's tailnet v4 is served");
2572    }
2573
2574    #[test]
2575    fn default_view_serves_nothing() {
2576        // The default (no dns_config seen) has magic_dns == false: fail closed.
2577        let view = DnsView::default();
2578        let buf = build_query(0x1, &["host", "user", "ts", "net"], 1, 1);
2579
2580        let resp = answer(&view, &buf).expect("answers");
2581        let (_, rcode, _) = parse_header(&resp);
2582        assert_eq!(rcode, 5, "Refused");
2583    }
2584
2585    #[test]
2586    fn unsupported_qtype_on_tailnet_name_is_nodata_not_refused() {
2587        // TXT (type 16) for a tailnet-authoritative name: the name exists but we hold no TXT, so —
2588        // like Go — return NODATA (empty NOERROR), NOT REFUSED (which would make a stub abandon the
2589        // resolver) and NOT NXDOMAIN (the name exists). The name is never forwarded (anti-leak).
2590        let view = view_with_peer();
2591        let buf = build_query(0x1, &["host", "user", "ts", "net"], 16, 1);
2592
2593        let resp = answer(&view, &buf).expect("answers");
2594        let (_, rcode, ancount) = parse_header(&resp);
2595        assert_eq!(rcode, 0, "NoError (NODATA), not Refused");
2596        assert_eq!(ancount, 0, "no answer records (NODATA)");
2597    }
2598
2599    #[test]
2600    fn unsupported_qtype_off_tailnet_forwards_or_servfails() {
2601        // A non-A/AAAA/PTR qtype for an OFF-tailnet name must be forwardable like A/AAAA — never
2602        // REFUSED. With no upstream configured in this view it soft-fails to SERVFAIL (the same
2603        // disposition an off-tailnet A query gets here), proving the qtype no longer short-circuits
2604        // to REFUSED. HTTPS/SVCB is type 65 (the browser HTTP/3 + ECH case the old REFUSED broke).
2605        let view = view_with_peer();
2606        let buf = build_query(0x1, &["example", "com"], 65, 1);
2607
2608        let resp = answer(&view, &buf).expect("answers");
2609        let (_, rcode, _) = parse_header(&resp);
2610        assert_eq!(
2611            rcode, 2,
2612            "off-tailnet, no upstream -> SERVFAIL (forwardable, not Refused)"
2613        );
2614    }
2615
2616    #[test]
2617    fn unimplemented_qtype_on_tailnet_name_is_notimp() {
2618        // NS (2), SOA (6), HINFO (13), AXFR (252) for a tailnet-authoritative name must answer NOTIMP
2619        // (rcode 4), matching Go `resolveLocal`'s `case dns.TypeNS, dns.TypeSOA, dns.TypeAXFR,
2620        // dns.TypeHINFO: return RCodeNotImplemented`. Returning NODATA (rcode 0) here was a clean
2621        // fingerprint (a `dig SOA user.ts.net` answer differs from real tailscaled). The name is
2622        // still never forwarded (anti-leak).
2623        let view = view_with_peer();
2624        for qtype in [2u16, 6, 13, 252] {
2625            let buf = build_query(0x1, &["host", "user", "ts", "net"], qtype, 1);
2626            let resp = answer(&view, &buf).expect("answers");
2627            let (_, rcode, ancount) = parse_header(&resp);
2628            assert_eq!(rcode, 4, "qtype {qtype} on a tailnet name must be NOTIMP");
2629            assert_eq!(ancount, 0, "NOTIMP carries no answer records");
2630        }
2631    }
2632
2633    #[test]
2634    fn unimplemented_qtype_off_tailnet_still_forwards_not_notimp() {
2635        // The NOTIMP disposition is ONLY for a name we are authoritative for. An NS query for an
2636        // off-tailnet name must still forward (here: SERVFAIL, no upstream) — NOT NOTIMP — exactly
2637        // like the off-tailnet HTTPS/SVCB case above. Guards the NOTIMP change against over-reach.
2638        let view = view_with_peer();
2639        let buf = build_query(0x1, &["example", "com"], 2, 1); // NS, off-tailnet
2640        let resp = answer(&view, &buf).expect("answers");
2641        let (_, rcode, _) = parse_header(&resp);
2642        assert_eq!(
2643            rcode, 2,
2644            "off-tailnet NS -> SERVFAIL (forwardable), not NOTIMP"
2645        );
2646    }
2647
2648    #[test]
2649    fn malformed_query_is_dropped() {
2650        // A response (QR bit set) is not a query; we drop it (no answer).
2651        let mut buf = build_query(0x1, &["host"], 1, 1);
2652        buf[2] = 0x80; // set QR bit
2653        assert!(answer(&view_with_peer(), &buf).is_none());
2654    }
2655
2656    #[test]
2657    fn ptr_for_known_ip_answers_fqdn() {
2658        let view = view_with_peer();
2659        // Reverse name for 100.64.0.1 => 1.0.64.100.in-addr.arpa
2660        let buf = build_query(0x33, &["1", "0", "64", "100", "in-addr", "arpa"], 12, 1);
2661
2662        let resp = answer(&view, &buf).expect("answers");
2663        let (_, rcode, ancount) = parse_header(&resp);
2664        assert_eq!(rcode, 0, "NoError");
2665        assert_eq!(ancount, 1);
2666
2667        // The PTR rdata encodes the peer's fqdn "host.user.ts.net" as length-prefixed labels.
2668        let expected = {
2669            let mut out = Vec::new();
2670            for label in ["host", "user", "ts", "net"] {
2671                out.push(label.len() as u8);
2672                out.extend_from_slice(label.as_bytes());
2673            }
2674            out.push(0);
2675            out
2676        };
2677        let tail = &resp[resp.len() - expected.len()..];
2678        assert_eq!(tail, expected.as_slice());
2679    }
2680
2681    #[test]
2682    fn ptr_for_unknown_public_ip_off_tailnet_is_servfail() {
2683        let view = view_with_peer();
2684        // 9.9.9.9 is a public IP, not a known tailnet IP and not in the CGNAT reverse zone — so its
2685        // reverse query is an ordinary off-tailnet name. With no upstream to forward it to, that is
2686        // SERVFAIL (soft), not NXDOMAIN. (A CGNAT/ip6.arpa reverse for an unmatched tailnet IP still
2687        // fails closed to NXDOMAIN as an anti-leak guard — see `ptr_for_unknown_tailnet_ip_*`.)
2688        let buf = build_query(0x34, &["9", "9", "9", "9", "in-addr", "arpa"], 12, 1);
2689
2690        let resp = answer(&view, &buf).expect("answers");
2691        let (_, rcode, _) = parse_header(&resp);
2692        assert_eq!(
2693            rcode, 2,
2694            "ServFail: off-tailnet public-IP reverse, no upstream"
2695        );
2696    }
2697
2698    #[test]
2699    fn ptr_for_unknown_tailnet_ip_is_nxdomain_not_forwarded() {
2700        // A view WITH an upstream resolver: an off-tailnet reverse query would forward, but a
2701        // reverse query for an unmatched IP in the CGNAT range (100.64.0.0/10) must fail closed to
2702        // NXDOMAIN — the probed tailnet IP must never leak upstream.
2703        let mut db = PeerDb::default();
2704        db.upsert(&test_node());
2705        let view = DnsView {
2706            cfg: DnsConfig {
2707                magic_dns: true,
2708                search_domains: vec!["user.ts.net".to_string()],
2709                fallback_resolvers: vec![DnsResolver {
2710                    transport: ts_control::ResolverTransport::Udp("9.9.9.9:53".parse().unwrap()),
2711                    use_with_exit_node: false,
2712                }],
2713                ..Default::default()
2714            },
2715            peers: Some(Arc::new(db)),
2716            self_node: None,
2717            exit_doh: None,
2718            enable_ipv6: false,
2719            accept_dns: true,
2720        };
2721
2722        // 100.64.0.9 is in CGNAT range but owned by no peer => NXDOMAIN, never a Forward.
2723        let buf = build_query(0x35, &["9", "0", "64", "100", "in-addr", "arpa"], 12, 1);
2724        match decide(&view, &buf).expect("decides") {
2725            Decision::Reply(resp) => {
2726                let (_, rcode, _) = parse_header(&resp);
2727                assert_eq!(rcode, 3, "NxDomain");
2728            }
2729            Decision::Forward { .. } => {
2730                panic!("tailnet CGNAT PTR must never be forwarded upstream")
2731            }
2732        }
2733    }
2734
2735    /// Anti-leak regression for the exotic-qtype forward path: a NON-PTR query (TXT, type 16) for a
2736    /// tailnet CGNAT reverse name, with an upstream configured, must STILL fail closed to NXDOMAIN —
2737    /// never forward. The PTR arm guards this, but the `QType::Other` path routes through
2738    /// `forward_or_nodata`, which must re-apply the reverse-zone guard or the tailnet IP leaks.
2739    #[test]
2740    fn exotic_qtype_for_tailnet_cgnat_reverse_is_nxdomain_not_forwarded() {
2741        let mut db = PeerDb::default();
2742        db.upsert(&test_node());
2743        let view = DnsView {
2744            cfg: DnsConfig {
2745                magic_dns: true,
2746                search_domains: vec!["user.ts.net".to_string()],
2747                fallback_resolvers: vec![DnsResolver {
2748                    transport: ts_control::ResolverTransport::Udp("9.9.9.9:53".parse().unwrap()),
2749                    use_with_exit_node: false,
2750                }],
2751                ..Default::default()
2752            },
2753            peers: Some(Arc::new(db)),
2754            self_node: None,
2755            exit_doh: None,
2756            enable_ipv6: false,
2757            accept_dns: true,
2758        };
2759
2760        // TXT (16) for a CGNAT reverse name => NXDOMAIN, never a Forward (no tailnet-IP leak).
2761        let buf = build_query(0x36, &["9", "0", "64", "100", "in-addr", "arpa"], 16, 1);
2762        match decide(&view, &buf).expect("decides") {
2763            Decision::Reply(resp) => {
2764                let (_, rcode, _) = parse_header(&resp);
2765                assert_eq!(rcode, 3, "NxDomain");
2766            }
2767            Decision::Forward { .. } => {
2768                panic!("a non-PTR query for a tailnet CGNAT reverse name must never forward")
2769            }
2770        }
2771    }
2772
2773    /// Same anti-leak guard for an `ip6.arpa` reverse name under an exotic qtype: must NXDOMAIN, not
2774    /// forward (revealing a tailnet ULA was probed).
2775    #[test]
2776    fn exotic_qtype_for_ip6_arpa_is_nxdomain_not_forwarded() {
2777        let view = view_with_routes(
2778            std::collections::BTreeMap::new(),
2779            vec![udp("9.9.9.9:53")],
2780            vec![],
2781        );
2782        // An ip6.arpa reverse name with a TXT (16) qtype must fail closed.
2783        let buf = build_query(
2784            0x37,
2785            &[
2786                "1", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
2787                "a", "7", "d", "f", "ip6", "arpa",
2788            ],
2789            16,
2790            1,
2791        );
2792        match decide(&view, &buf).expect("decides") {
2793            Decision::Reply(resp) => {
2794                let (_, rcode, _) = parse_header(&resp);
2795                assert_eq!(rcode, 3, "NxDomain");
2796            }
2797            Decision::Forward { .. } => panic!("an ip6.arpa exotic-qtype query must never forward"),
2798        }
2799    }
2800
2801    #[test]
2802    fn is_tailnet_cgnat_classifies_range() {
2803        assert!(is_tailnet_cgnat("100.64.0.0".parse().unwrap()));
2804        assert!(is_tailnet_cgnat("100.64.0.1".parse().unwrap()));
2805        assert!(is_tailnet_cgnat("100.127.255.255".parse().unwrap()));
2806        // Outside the /10:
2807        assert!(!is_tailnet_cgnat("100.63.255.255".parse().unwrap()));
2808        assert!(!is_tailnet_cgnat("100.128.0.0".parse().unwrap()));
2809        assert!(!is_tailnet_cgnat("9.9.9.9".parse().unwrap()));
2810        // The MagicDNS resolver IP 100.100.100.100 is itself inside the /10.
2811        assert!(is_tailnet_cgnat("100.100.100.100".parse().unwrap()));
2812    }
2813
2814    #[test]
2815    fn response_matches_query_validates_id_and_qr() {
2816        // query id 0x1234, QR=0
2817        let query = build_query(0x1234, &["a", "com"], 1, 1);
2818
2819        // A well-formed response: same id, QR=1.
2820        let mut good = query.clone();
2821        good[2] |= 0x80;
2822        assert!(response_matches_query(&query, &good));
2823
2824        // Same id but QR still 0 (not a response): rejected.
2825        assert!(!response_matches_query(&query, &query));
2826
2827        // QR=1 but a different transaction id: rejected (off-path forgery).
2828        let mut wrong_id = good.clone();
2829        wrong_id[0] ^= 0xFF;
2830        assert!(!response_matches_query(&query, &wrong_id));
2831
2832        // Too-short buffers: rejected.
2833        assert!(!response_matches_query(&query, &[0u8; 2]));
2834        assert!(!response_matches_query(&[0u8; 3], &good));
2835    }
2836
2837    #[test]
2838    fn self_node_resolves_when_no_peer_match() {
2839        // With the peer db empty but a self node set, the self node answers for its own name.
2840        let view = DnsView {
2841            cfg: DnsConfig {
2842                magic_dns: true,
2843                search_domains: vec![],
2844                ..Default::default()
2845            },
2846            peers: None,
2847            self_node: Some(test_node()),
2848            exit_doh: None,
2849            enable_ipv6: false,
2850            accept_dns: true,
2851        };
2852        let buf = build_query(0x44, &["host", "user", "ts", "net"], 1, 1);
2853
2854        let resp = answer(&view, &buf).expect("answers");
2855        let (_, rcode, ancount) = parse_header(&resp);
2856        assert_eq!(rcode, 0);
2857        assert_eq!(ancount, 1);
2858        let tail = &resp[resp.len() - 4..];
2859        assert_eq!(tail, &[100, 64, 0, 1]);
2860    }
2861
2862    #[test]
2863    fn partially_qualified_name_resolves_via_search_domain() {
2864        // "host.user" is not indexed directly, but the "user.ts.net" search domain qualifies it
2865        // to "host.user.user.ts.net"... which does NOT match. The realistic case is "host" (bare,
2866        // already indexed) and "host.user.ts.net" (fqdn). Verify a name needing suffix expansion:
2867        // with search domain "ts.net" the partially-qualified "host.user" => "host.user.ts.net".
2868        let mut view = view_with_peer();
2869        view.cfg.search_domains = vec!["ts.net".to_string()];
2870        let buf = build_query(0x55, &["host", "user"], 1, 1);
2871
2872        let resp = answer(&view, &buf).expect("answers");
2873        let (_, rcode, ancount) = parse_header(&resp);
2874        assert_eq!(rcode, 0, "NoError via search-domain expansion");
2875        assert_eq!(ancount, 1);
2876        let tail = &resp[resp.len() - 4..];
2877        assert_eq!(tail, &[100, 64, 0, 1]);
2878    }
2879
2880    #[test]
2881    fn extra_record_a_answers_when_no_peer_match() {
2882        // A control-pushed static A record answers for a non-peer name, fail-closed otherwise.
2883        let mut view = view_with_peer();
2884        view.cfg.extra_records = vec![ts_control::ExtraRecord {
2885            name: "static.user.ts.net".to_string(),
2886            addr: IpAddr::V4(Ipv4Addr::new(100, 64, 0, 9)),
2887        }];
2888        let buf = build_query(0x77, &["static", "user", "ts", "net"], 1, 1);
2889
2890        let resp = answer(&view, &buf).expect("answers");
2891        let (_, rcode, ancount) = parse_header(&resp);
2892        assert_eq!(rcode, 0, "NoError from extra record");
2893        assert_eq!(ancount, 1);
2894        let tail = &resp[resp.len() - 4..];
2895        assert_eq!(tail, &[100, 64, 0, 9]);
2896    }
2897
2898    #[test]
2899    fn extra_record_matches_query_case_insensitively() {
2900        // The query name is canonicalized (lowercased) at decode time, so a mixed-case query
2901        // matches a lowercase extra record.
2902        let mut view = view_with_peer();
2903        view.cfg.extra_records = vec![ts_control::ExtraRecord {
2904            name: "static.user.ts.net".to_string(),
2905            addr: IpAddr::V4(Ipv4Addr::new(100, 64, 0, 9)),
2906        }];
2907        let buf = build_query(0x7A, &["Static", "User", "TS", "net"], 1, 1);
2908
2909        let resp = answer(&view, &buf).expect("answers");
2910        let (_, rcode, ancount) = parse_header(&resp);
2911        assert_eq!(rcode, 0, "NoError: case-insensitive match");
2912        assert_eq!(ancount, 1);
2913        let tail = &resp[resp.len() - 4..];
2914        assert_eq!(tail, &[100, 64, 0, 9]);
2915    }
2916
2917    #[test]
2918    fn extra_record_not_expanded_by_search_domain() {
2919        // Unlike peer names, an extra record is matched as an FQDN only: a bare query that would
2920        // need search-domain expansion to reach the record name must NOT resolve.
2921        let mut view = view_with_peer();
2922        view.cfg.extra_records = vec![ts_control::ExtraRecord {
2923            name: "static.user.ts.net".to_string(),
2924            addr: IpAddr::V4(Ipv4Addr::new(100, 64, 0, 9)),
2925        }];
2926        // "static" would only reach "static.user.ts.net" via the "user.ts.net" search domain.
2927        let buf = build_query(0x7B, &["static"], 1, 1);
2928
2929        let resp = answer(&view, &buf).expect("answers");
2930        let (_, rcode, _) = parse_header(&resp);
2931        // Not search-expanded → treated as the bare off-tailnet name "static", which has no upstream
2932        // here, so SERVFAIL (soft). The point of the test — that the extra record is NOT reachable
2933        // via search expansion — holds regardless of the failure rcode.
2934        assert_eq!(
2935            rcode, 2,
2936            "ServFail: bare 'static' is not search-expanded to the extra record"
2937        );
2938    }
2939
2940    #[test]
2941    fn extra_record_aaaa_family_is_isolated() {
2942        // An A-only extra record must NOT answer an AAAA query for the same name (NxDomain).
2943        let mut view = view_with_peer();
2944        view.cfg.extra_records = vec![ts_control::ExtraRecord {
2945            name: "v4only.user.ts.net".to_string(),
2946            addr: IpAddr::V4(Ipv4Addr::new(100, 64, 0, 9)),
2947        }];
2948        let buf = build_query(0x78, &["v4only", "user", "ts", "net"], 28, 1);
2949
2950        let resp = answer(&view, &buf).expect("answers");
2951        let (_, rcode, _) = parse_header(&resp);
2952        assert_eq!(rcode, 3, "NxDomain: A record does not satisfy AAAA");
2953    }
2954
2955    #[test]
2956    fn extra_record_ignored_when_magic_dns_off() {
2957        // Fail closed: extra records are never served while MagicDNS is disabled.
2958        let mut view = view_with_peer();
2959        view.cfg.magic_dns = false;
2960        view.cfg.extra_records = vec![ts_control::ExtraRecord {
2961            name: "static.user.ts.net".to_string(),
2962            addr: IpAddr::V4(Ipv4Addr::new(100, 64, 0, 9)),
2963        }];
2964        let buf = build_query(0x79, &["static", "user", "ts", "net"], 1, 1);
2965
2966        let resp = answer(&view, &buf).expect("answers");
2967        let (_, rcode, _) = parse_header(&resp);
2968        assert_eq!(rcode, 5, "Refused");
2969    }
2970
2971    /// The node attribute control sets to make every subdomain of a node resolve to it (Go
2972    /// `tailcfg/nodecap`'s `NodeAttrDNSSubdomainResolve`).
2973    const DNS_SUBDOMAIN_RESOLVE: &str = "dns-subdomain-resolve";
2974
2975    /// A view holding a single peer `host.user.ts.net` that carries the `dns-subdomain-resolve`
2976    /// node attribute, so control has declared every name under it to resolve to its addresses.
2977    fn view_with_subdomain_host() -> DnsView {
2978        let mut node = test_node();
2979        node.cap_map
2980            .insert(DNS_SUBDOMAIN_RESOLVE.to_string(), vec![]);
2981
2982        let mut db = PeerDb::default();
2983        db.upsert(&node);
2984
2985        let mut view = view_with_peer();
2986        view.peers = Some(Arc::new(db));
2987        view
2988    }
2989
2990    #[test]
2991    fn subdomain_of_a_subdomain_host_resolves_to_it() {
2992        // `my.host.user.ts.net` has no record of its own; its parent `host.user.ts.net` carries the
2993        // attribute, so it answers with the parent's address.
2994        let view = view_with_subdomain_host();
2995        let buf = build_query(0x90, &["my", "host", "user", "ts", "net"], 1, 1);
2996
2997        let resp = answer(&view, &buf).expect("answers");
2998        let (_, rcode, ancount) = parse_header(&resp);
2999        assert_eq!(rcode, 0, "NoError from the subdomain host");
3000        assert_eq!(ancount, 1);
3001        assert_eq!(&resp[resp.len() - 4..], &[100, 64, 0, 1]);
3002    }
3003
3004    #[test]
3005    fn a_multi_label_subdomain_of_a_subdomain_host_resolves() {
3006        // The walk climbs every parent, not one level: `be.my.host` reaches `host` just as
3007        // `my.host` does. One level of parent is not what upstream implements.
3008        let view = view_with_subdomain_host();
3009        let buf = build_query(0x91, &["be", "my", "host", "user", "ts", "net"], 1, 1);
3010
3011        let resp = answer(&view, &buf).expect("answers");
3012        let (_, rcode, ancount) = parse_header(&resp);
3013        assert_eq!(rcode, 0, "NoError: the walk is not depth-limited");
3014        assert_eq!(ancount, 1);
3015        assert_eq!(&resp[resp.len() - 4..], &[100, 64, 0, 1]);
3016    }
3017
3018    #[test]
3019    fn subdomain_of_a_peer_without_the_attribute_is_nxdomain() {
3020        // The attribute is what turns the walk on. Without it — the default for every node — a
3021        // subdomain of a peer name is still authoritatively absent.
3022        let view = view_with_peer();
3023        assert!(
3024            !view
3025                .node_by_name("host.user.ts.net")
3026                .expect("peer is present")
3027                .resolves_subdomains(),
3028            "the plain test peer carries no node attribute"
3029        );
3030        let buf = build_query(0x92, &["my", "host", "user", "ts", "net"], 1, 1);
3031
3032        let resp = answer(&view, &buf).expect("answers");
3033        let (_, rcode, ancount) = parse_header(&resp);
3034        assert_eq!(rcode, 3, "NxDomain: no attribute, no subdomain resolution");
3035        assert_eq!(ancount, 0);
3036    }
3037
3038    #[test]
3039    fn an_exact_match_beats_the_subdomain_host() {
3040        // The walk is the *miss* path: a name that resolves exactly — here a control-pushed extra
3041        // record — keeps its own answer, and never takes the parent's.
3042        let mut view = view_with_subdomain_host();
3043        view.cfg.extra_records = vec![ts_control::ExtraRecord {
3044            name: "my.host.user.ts.net".to_string(),
3045            addr: IpAddr::V4(Ipv4Addr::new(100, 64, 0, 9)),
3046        }];
3047        let buf = build_query(0x93, &["my", "host", "user", "ts", "net"], 1, 1);
3048
3049        let resp = answer(&view, &buf).expect("answers");
3050        let (_, rcode, ancount) = parse_header(&resp);
3051        assert_eq!(rcode, 0, "NoError");
3052        assert_eq!(ancount, 1);
3053        assert_eq!(
3054            &resp[resp.len() - 4..],
3055            &[100, 64, 0, 9],
3056            "the exact record answers, not the subdomain host's address"
3057        );
3058    }
3059
3060    #[test]
3061    fn the_subdomain_walk_stops_at_the_tailnet_zone() {
3062        // A node whose own FQDN *is* the search domain must not make the whole zone a wildcard:
3063        // the walk stops at the zone apex rather than climbing into names we do not serve.
3064        let mut zone_node = test_node();
3065        zone_node.hostname = "user".to_string();
3066        zone_node.tailnet = Some("ts.net".to_string());
3067        zone_node
3068            .cap_map
3069            .insert(DNS_SUBDOMAIN_RESOLVE.to_string(), vec![]);
3070        assert_eq!(zone_node.fqdn(false), "user.ts.net", "the zone apex itself");
3071
3072        let mut db = PeerDb::default();
3073        db.upsert(&zone_node);
3074        let mut view = view_with_peer();
3075        view.peers = Some(Arc::new(db));
3076
3077        for labels in [
3078            ["nothing", "user", "ts", "net"].as_slice(),
3079            ["deeper", "nothing", "user", "ts", "net"].as_slice(),
3080        ] {
3081            let buf = build_query(0x94, labels, 1, 1);
3082            let resp = answer(&view, &buf).expect("answers");
3083            let (_, rcode, ancount) = parse_header(&resp);
3084            assert_eq!(rcode, 3, "NxDomain: the walk stopped at {:?}", labels);
3085            assert_eq!(ancount, 0);
3086        }
3087    }
3088
3089    #[test]
3090    fn the_subdomain_walk_does_not_search_expand_a_bare_label() {
3091        // The peer-name index also holds bare hostnames, so a peer named after a public suffix must
3092        // not swallow every name under it: only a fully-qualified parent is a walk candidate. Go
3093        // cannot do this at all — its resolver does no search-list expansion.
3094        let mut suffix_node = test_node();
3095        suffix_node.hostname = "com".to_string();
3096        suffix_node
3097            .cap_map
3098            .insert(DNS_SUBDOMAIN_RESOLVE.to_string(), vec![]);
3099
3100        let mut db = PeerDb::default();
3101        db.upsert(&suffix_node);
3102        let mut view = view_with_peer();
3103        view.peers = Some(Arc::new(db));
3104
3105        let buf = build_query(0x95, &["www", "example", "com"], 1, 1);
3106        let resp = answer(&view, &buf).expect("answers");
3107        let (_, rcode, ancount) = parse_header(&resp);
3108        assert_eq!(
3109            rcode, 2,
3110            "ServFail: an off-tailnet name with no upstream, NOT the peer named 'com'"
3111        );
3112        assert_eq!(ancount, 0, "no answer manufactured from a bare hostname");
3113
3114        // The qualified form of the same peer still resolves its subdomains: the bound rejects the
3115        // bare label, not the subdomain host.
3116        let buf = build_query(0x96, &["www", "com", "user", "ts", "net"], 1, 1);
3117        let resp = answer(&view, &buf).expect("answers");
3118        let (_, rcode, ancount) = parse_header(&resp);
3119        assert_eq!(rcode, 0, "NoError from com.user.ts.net");
3120        assert_eq!(ancount, 1);
3121        assert_eq!(&resp[resp.len() - 4..], &[100, 64, 0, 1]);
3122    }
3123
3124    #[test]
3125    fn aaaa_for_a_subdomain_host_follows_the_ipv6_gate() {
3126        // The subdomain answer is the parent node's address, so it takes the same AAAA gate an
3127        // exact peer match does: NODATA with IPv6 off, the overlay v6 with it on.
3128        let mut view = view_with_subdomain_host();
3129        let buf = build_query(0x97, &["my", "host", "user", "ts", "net"], 28, 1);
3130
3131        let resp = answer(&view, &buf).expect("answers");
3132        let (_, rcode, ancount) = parse_header(&resp);
3133        assert_eq!(rcode, 0, "NoError (NODATA) with the gate off");
3134        assert_eq!(ancount, 0);
3135
3136        view.enable_ipv6 = true;
3137        let resp = answer(&view, &buf).expect("answers");
3138        let (_, rcode, ancount) = parse_header(&resp);
3139        assert_eq!(rcode, 0, "NoError");
3140        assert_eq!(ancount, 1);
3141        let expected = "fd7a::1".parse::<std::net::Ipv6Addr>().unwrap().octets();
3142        assert_eq!(&resp[resp.len() - 16..], expected);
3143    }
3144
3145    #[test]
3146    fn a_subdomain_of_the_self_node_resolves_when_it_has_the_attribute() {
3147        // The walk runs over the same name lookup the exact match uses, so the self node is a
3148        // subdomain host too when control sets the attribute on it.
3149        let mut self_node = test_node();
3150        self_node.hostname = "me".to_string();
3151        self_node
3152            .cap_map
3153            .insert(DNS_SUBDOMAIN_RESOLVE.to_string(), vec![]);
3154
3155        let mut view = view_with_peer();
3156        view.peers = None;
3157        view.self_node = Some(self_node);
3158
3159        let buf = build_query(0x98, &["a", "b", "me", "user", "ts", "net"], 1, 1);
3160        let resp = answer(&view, &buf).expect("answers");
3161        let (_, rcode, ancount) = parse_header(&resp);
3162        assert_eq!(rcode, 0, "NoError from the self node");
3163        assert_eq!(ancount, 1);
3164        assert_eq!(&resp[resp.len() - 4..], &[100, 64, 0, 1]);
3165    }
3166
3167    #[test]
3168    fn non_in_class_on_tailnet_name_is_nodata_not_answered_as_in() {
3169        // A CHAOS-class (3) query for a tailnet name must NOT be answered as IN (no overlay A), and
3170        // must NOT be REFUSED (Go does no class check on the local path). It's an unsupported
3171        // authoritative class -> NODATA (empty NOERROR), and never forwarded (tailnet name).
3172        let view = view_with_peer();
3173        let buf = build_query(0x66, &["host", "user", "ts", "net"], 1, 3);
3174
3175        let resp = answer(&view, &buf).expect("answers");
3176        let (_, rcode, ancount) = parse_header(&resp);
3177        assert_eq!(
3178            rcode, 0,
3179            "NoError (NODATA), not Refused and not an IN answer"
3180        );
3181        assert_eq!(
3182            ancount, 0,
3183            "must not hand out the overlay A for a non-IN class"
3184        );
3185    }
3186
3187    #[test]
3188    fn non_in_class_off_tailnet_forwards_or_servfails() {
3189        // A non-IN class for an OFF-tailnet name is forwardable (Go forwards it), never REFUSED.
3190        // No upstream here -> SERVFAIL, proving the class gate no longer short-circuits to Refused.
3191        let view = view_with_peer();
3192        let buf = build_query(0x66, &["example", "com"], 1, 3);
3193
3194        let resp = answer(&view, &buf).expect("answers");
3195        let (_, rcode, _) = parse_header(&resp);
3196        assert_eq!(
3197            rcode, 2,
3198            "off-tailnet non-IN class, no upstream -> SERVFAIL, not Refused"
3199        );
3200    }
3201
3202    /// A view with MagicDNS on, the `user.ts.net` search domain, and the given split-DNS routes
3203    /// + global resolvers.
3204    fn view_with_routes(
3205        routes: std::collections::BTreeMap<String, Vec<DnsResolver>>,
3206        resolvers: Vec<DnsResolver>,
3207        fallback: Vec<DnsResolver>,
3208    ) -> DnsView {
3209        DnsView {
3210            cfg: DnsConfig {
3211                magic_dns: true,
3212                search_domains: vec!["user.ts.net".to_string()],
3213                routes,
3214                resolvers,
3215                fallback_resolvers: fallback,
3216                ..Default::default()
3217            },
3218            peers: None,
3219            self_node: None,
3220            exit_doh: None,
3221            enable_ipv6: false,
3222            accept_dns: true,
3223        }
3224    }
3225
3226    fn udp(addr: &str) -> DnsResolver {
3227        DnsResolver {
3228            transport: ts_control::ResolverTransport::Udp(addr.parse().unwrap()),
3229            use_with_exit_node: false,
3230        }
3231    }
3232
3233    #[test]
3234    fn split_dns_route_forwards_to_matching_upstream() {
3235        let mut routes = std::collections::BTreeMap::new();
3236        routes.insert("corp.example".to_string(), vec![udp("10.0.0.53:53")]);
3237        let view = view_with_routes(routes, vec![], vec![]);
3238        let buf = build_query(0x100, &["api", "corp", "example"], 1, 1);
3239
3240        match decide(&view, &buf).expect("decides") {
3241            Decision::Forward { upstreams, .. } => {
3242                assert_eq!(upstreams, vec!["10.0.0.53:53".parse().unwrap()]);
3243            }
3244            Decision::Reply(_) => panic!("expected forward to the split-DNS upstream"),
3245        }
3246    }
3247
3248    #[test]
3249    fn exotic_qtype_off_tailnet_forwards_to_upstream() {
3250        // The core of the fix: an HTTPS/SVCB (type 65) query for an off-tailnet name with a matching
3251        // route must FORWARD to the upstream (verbatim), exactly like an A query would — not REFUSE
3252        // and not NXDOMAIN. This is the browser HTTP/3 + ECH case the old blanket-REFUSE broke.
3253        let mut routes = std::collections::BTreeMap::new();
3254        routes.insert("corp.example".to_string(), vec![udp("10.0.0.53:53")]);
3255        let view = view_with_routes(routes, vec![], vec![]);
3256        let buf = build_query(0x102, &["api", "corp", "example"], 65, 1);
3257
3258        match decide(&view, &buf).expect("decides") {
3259            Decision::Forward {
3260                upstreams, query, ..
3261            } => {
3262                assert_eq!(upstreams, vec!["10.0.0.53:53".parse().unwrap()]);
3263                assert_eq!(query, buf, "the exotic-qtype query is forwarded verbatim");
3264            }
3265            Decision::Reply(_) => {
3266                panic!("an off-tailnet HTTPS-record query must forward, not reply")
3267            }
3268        }
3269    }
3270
3271    #[test]
3272    fn non_in_class_off_tailnet_forwards_to_upstream() {
3273        // A non-IN class for an off-tailnet routed name forwards too (Go does no class check on the
3274        // local path). Proves the class gate no longer short-circuits to REFUSED before routing.
3275        let mut routes = std::collections::BTreeMap::new();
3276        routes.insert("corp.example".to_string(), vec![udp("10.0.0.53:53")]);
3277        let view = view_with_routes(routes, vec![], vec![]);
3278        let buf = build_query(0x103, &["api", "corp", "example"], 1, 3);
3279
3280        match decide(&view, &buf).expect("decides") {
3281            Decision::Forward { upstreams, .. } => {
3282                assert_eq!(upstreams, vec!["10.0.0.53:53".parse().unwrap()]);
3283            }
3284            Decision::Reply(_) => {
3285                panic!("an off-tailnet non-IN-class query must forward, not reply")
3286            }
3287        }
3288    }
3289
3290    /// The local responder bounds concurrent in-flight forwards: `serve` acquires one
3291    /// `MAX_INFLIGHT_FORWARDS` permit per spawned forward task and drops the query fail-closed when
3292    /// the pool is exhausted (a client spraying forwardable names can't open unbounded overlay
3293    /// sockets). This pins the gating semantics `serve` relies on — drained pool refuses a new
3294    /// permit; releasing one restores capacity — and the cap constant itself. (The async `serve`
3295    /// loop has no netstack-free test seam, so the semaphore behavior is exercised directly here, the
3296    /// same `Arc<Semaphore>::try_acquire_owned` the loop uses.)
3297    #[test]
3298    fn forward_inflight_cap_fails_closed_when_saturated() {
3299        use std::sync::Arc;
3300
3301        use tokio::sync::Semaphore;
3302
3303        let inflight = Arc::new(Semaphore::new(MAX_INFLIGHT_FORWARDS));
3304
3305        // Drain every permit (one per concurrently in-flight forward).
3306        let mut held = Vec::with_capacity(MAX_INFLIGHT_FORWARDS);
3307        for _ in 0..MAX_INFLIGHT_FORWARDS {
3308            held.push(
3309                inflight
3310                    .clone()
3311                    .try_acquire_owned()
3312                    .expect("permits available below the cap"),
3313            );
3314        }
3315
3316        // At the cap, the next forward is refused — `serve` would drop the query, not spawn.
3317        assert!(
3318            inflight.clone().try_acquire_owned().is_err(),
3319            "a saturated forward pool must refuse a new permit (fail closed)"
3320        );
3321
3322        // Completing an in-flight forward releases its permit and restores capacity.
3323        drop(held.pop());
3324        assert!(
3325            inflight.clone().try_acquire_owned().is_ok(),
3326            "releasing a permit must let the next forward proceed"
3327        );
3328    }
3329
3330    /// A permit moved into a spawned forward task (the `let _permit = permit;` shape `serve` uses)
3331    /// must stay held for the *whole* task body — across the `.await` on the upstream — and release
3332    /// only when the task completes. This guards the regression the saturation test above can't see:
3333    /// "tidying" `let _permit = permit;` to `let _ = permit;` would drop the permit immediately,
3334    /// re-opening unbounded concurrency while leaving the synchronous drain/restore test green. Here a
3335    /// 1-permit pool is consumed by a task that holds it across a yield; the pool must read empty
3336    /// while the task runs and refill once it finishes.
3337    #[tokio::test]
3338    async fn forward_permit_is_held_for_the_task_lifetime_not_dropped_early() {
3339        use std::sync::Arc;
3340
3341        use tokio::sync::Semaphore;
3342
3343        let inflight = Arc::new(Semaphore::new(1));
3344        let permit = inflight
3345            .clone()
3346            .try_acquire_owned()
3347            .expect("the sole permit is available");
3348
3349        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
3350        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
3351        let task = tokio::spawn(async move {
3352            // Same shape as `serve`'s spawned forward: the permit is a named binding moved into the
3353            // task, so it lives until the body ends — not dropped at the `let`.
3354            let _permit = permit;
3355            started_tx.send(()).unwrap();
3356            // Stand in for the `.await` on the upstream forward.
3357            release_rx.await.unwrap();
3358        });
3359
3360        started_rx.await.unwrap();
3361        // While the task runs, the permit it moved in is still held — the pool is empty.
3362        assert!(
3363            inflight.clone().try_acquire_owned().is_err(),
3364            "a permit moved into a running task must stay held across its await"
3365        );
3366
3367        // Let the task finish; its permit drops with the body and capacity returns.
3368        release_tx.send(()).unwrap();
3369        task.await.unwrap();
3370        assert!(
3371            inflight.clone().try_acquire_owned().is_ok(),
3372            "the permit must be released once the task body completes"
3373        );
3374    }
3375
3376    /// The address of the `n`th fake upstream resolver (RFC 5737 documentation range).
3377    fn upstream_addr(n: u8) -> SocketAddr {
3378        SocketAddr::from((Ipv4Addr::new(198, 51, 100, n), 53))
3379    }
3380
3381    /// Turn `query` into an upstream response: echo the header and question back with `QR` set and
3382    /// `rcode` in the header's low nibble, then append `tail` verbatim, counted as `ancount` answer
3383    /// records. The forwarder relays bytes and never parses past the question, so an opaque tail is
3384    /// what tells two upstreams' responses apart — and stands in for the RFC 8914 extended DNS error
3385    /// a real resolver puts in its own SERVFAIL/REFUSED.
3386    fn upstream_response(query: &[u8], rcode: u8, ancount: u16, tail: &[u8]) -> Vec<u8> {
3387        let mut resp = query.to_vec();
3388        resp[2] |= 0x80; // QR = 1 (this is a response)
3389        resp[3] = (resp[3] & 0xF0) | rcode;
3390        resp[6..8].copy_from_slice(&ancount.to_be_bytes());
3391        resp.extend_from_slice(tail);
3392        resp
3393    }
3394
3395    /// One scripted upstream for [`run_forward_walk`]: the upstream's address, and the
3396    /// `(source address, datagram)` it hands back — `None` when nothing came back at all.
3397    type ScriptedUpstream = (SocketAddr, Option<(SocketAddr, Vec<u8>)>);
3398
3399    /// Run the real [`forward_walk`] over a scripted set of upstreams: each entry is
3400    /// `(upstream, answer)`, where `answer` is the `(source address, datagram)` that upstream hands
3401    /// back (`None` = nothing came back — a timeout, a bind/send/recv failure). Returns the bytes
3402    /// the client would get **and** the upstreams the walk actually asked, so a test can tell "the
3403    /// second upstream answered" apart from "the walk stopped at the first".
3404    ///
3405    /// The script stands in for [`ask_upstream`]'s overlay socket exchange only; every decision
3406    /// under test — the source/transaction-id check, the REFUSED/SERVFAIL soft-error rules, which
3407    /// response is relayed — is made by the production code being called. Every scripted answer
3408    /// arrives over the UDP hop, which is the hop the walk's own rules are about, and is read by the
3409    /// production race with the TCP hop switched off ([`TcpRetry::Disabled`]), so a scripted soft
3410    /// error reaches the walk as the failure [`ask_upstream`] would hand it. The TCP hop is
3411    /// [`race_udp_and_tcp`]'s business and is tested there.
3412    async fn run_forward_walk(
3413        script: &[ScriptedUpstream],
3414        query: &[u8],
3415        fallback: Vec<u8>,
3416    ) -> (Vec<u8>, Vec<SocketAddr>) {
3417        let upstreams: Vec<SocketAddr> = script.iter().map(|(upstream, _)| *upstream).collect();
3418        let asked = std::cell::RefCell::new(Vec::new());
3419
3420        let response = forward_walk(
3421            &upstreams,
3422            query,
3423            fallback,
3424            ClientTransport::Udp,
3425            |upstream| {
3426                asked.borrow_mut().push(upstream);
3427                let datagram = script
3428                    .iter()
3429                    .find(|(scripted, _)| *scripted == upstream)
3430                    .and_then(|(_, datagram)| datagram.clone());
3431                race_udp_and_tcp(
3432                    upstream,
3433                    query,
3434                    ClientTransport::Udp,
3435                    TcpRetry::Disabled,
3436                    move || std::future::ready(datagram),
3437                    || std::future::ready(None),
3438                )
3439            },
3440        )
3441        .await;
3442
3443        (response, asked.into_inner())
3444    }
3445
3446    /// A first upstream answering REFUSED must NOT end the forward. A broken or misconfigured
3447    /// resolver refuses instantly and would otherwise beat a healthy one that is still working,
3448    /// handing the stub resolver a refusal as though it were the answer — complete DNS failure
3449    /// wherever a split-DNS route or a fallback list names more than one resolver.
3450    #[tokio::test]
3451    async fn refused_first_upstream_does_not_end_the_walk() {
3452        let query = build_query(0x201, &["api", "example", "com"], 1, 1);
3453        let (first, second) = (upstream_addr(1), upstream_addr(2));
3454        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"refused");
3455        let answer = upstream_response(&query, 0, 1, b"the real answer");
3456        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3457
3458        let (got, asked) = run_forward_walk(
3459            &[
3460                (first, Some((first, refusal))),
3461                (second, Some((second, answer.clone()))),
3462            ],
3463            &query,
3464            fallback,
3465        )
3466        .await;
3467
3468        assert_eq!(
3469            asked,
3470            vec![first, second],
3471            "a REFUSED from the first upstream must not stop the walk"
3472        );
3473        assert_eq!(
3474            got, answer,
3475            "the healthy second upstream's answer is what reaches the client"
3476        );
3477    }
3478
3479    /// SERVFAIL is soft in the same way: the walk goes on and the healthy upstream's answer wins.
3480    #[tokio::test]
3481    async fn servfail_first_upstream_does_not_end_the_walk() {
3482        let query = build_query(0x202, &["api", "example", "com"], 1, 1);
3483        let (first, second) = (upstream_addr(1), upstream_addr(2));
3484        let soft_fail = upstream_response(&query, RCODE_SERVFAIL, 0, b"servfail");
3485        let answer = upstream_response(&query, 0, 1, b"the real answer");
3486        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3487
3488        let (got, asked) = run_forward_walk(
3489            &[
3490                (first, Some((first, soft_fail))),
3491                (second, Some((second, answer.clone()))),
3492            ],
3493            &query,
3494            fallback,
3495        )
3496        .await;
3497
3498        assert_eq!(asked, vec![first, second], "SERVFAIL is a soft error too");
3499        assert_eq!(
3500            got, answer,
3501            "the second upstream's answer reaches the client"
3502        );
3503    }
3504
3505    /// An RCODE that is *not* soft is an answer: NXDOMAIN ends the walk where it is found, and the
3506    /// upstreams after it are never asked. (Making everything soft would turn a legitimate
3507    /// "no such name" into a needless extra round trip — and, with a second refusing upstream, into
3508    /// a different answer entirely.)
3509    #[tokio::test]
3510    async fn nxdomain_ends_the_walk_at_the_first_upstream() {
3511        let query = build_query(0x203, &["nope", "example", "com"], 1, 1);
3512        let (first, second) = (upstream_addr(1), upstream_addr(2));
3513        let nxdomain = upstream_response(&query, 3, 0, b"no such name");
3514        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3515
3516        let (got, asked) = run_forward_walk(
3517            &[
3518                (first, Some((first, nxdomain.clone()))),
3519                (
3520                    second,
3521                    Some((second, upstream_response(&query, 0, 1, b"late"))),
3522                ),
3523            ],
3524            &query,
3525            fallback,
3526        )
3527        .await;
3528
3529        assert_eq!(asked, vec![first], "NXDOMAIN is an answer: stop asking");
3530        assert_eq!(got, nxdomain, "and it is what the client gets");
3531    }
3532
3533    /// When every upstream refuses, the client gets the FIRST refusal, byte for byte — not the
3534    /// caller's synthesized SERVFAIL. The upstream's own bytes can carry an RFC 8914 extended DNS
3535    /// error explaining the refusal; a locally built packet throws that away.
3536    #[tokio::test]
3537    async fn every_upstream_refusing_returns_the_first_refusal_verbatim() {
3538        let query = build_query(0x204, &["api", "example", "com"], 1, 1);
3539        let (first, second) = (upstream_addr(1), upstream_addr(2));
3540        let first_refusal =
3541            upstream_response(&query, RCODE_REFUSED, 0, b"first refusal + extended error");
3542        let second_refusal = upstream_response(&query, RCODE_REFUSED, 0, b"second refusal");
3543        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3544
3545        let (got, asked) = run_forward_walk(
3546            &[
3547                (first, Some((first, first_refusal.clone()))),
3548                (second, Some((second, second_refusal.clone()))),
3549            ],
3550            &query,
3551            fallback.clone(),
3552        )
3553        .await;
3554
3555        assert_eq!(
3556            asked,
3557            vec![first, second],
3558            "every upstream is given its turn"
3559        );
3560        assert_eq!(
3561            got, first_refusal,
3562            "an all-refused forward relays the first upstream's own REFUSED bytes"
3563        );
3564        assert_ne!(
3565            got, fallback,
3566            "the synthesized SERVFAIL must not replace an upstream's own response"
3567        );
3568        assert_ne!(got, second_refusal, "the FIRST refusal is the one kept");
3569    }
3570
3571    /// The first *soft* response is the one kept whichever code it carried: a SERVFAIL followed by a
3572    /// REFUSED relays the upstream's own SERVFAIL, extended error and all, rather than the
3573    /// synthesized one the caller supplied.
3574    #[tokio::test]
3575    async fn every_upstream_soft_failing_returns_the_upstream_servfail_not_the_fallback() {
3576        let query = build_query(0x205, &["api", "example", "com"], 1, 1);
3577        let (first, second) = (upstream_addr(1), upstream_addr(2));
3578        let upstream_servfail = upstream_response(
3579            &query,
3580            RCODE_SERVFAIL,
3581            0,
3582            b"upstream servfail + extended error",
3583        );
3584        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"second refusal");
3585        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3586
3587        let (got, _asked) = run_forward_walk(
3588            &[
3589                (first, Some((first, upstream_servfail.clone()))),
3590                (second, Some((second, refusal))),
3591            ],
3592            &query,
3593            fallback.clone(),
3594        )
3595        .await;
3596
3597        assert_eq!(
3598            got, upstream_servfail,
3599            "the upstream's own SERVFAIL is relayed verbatim, keeping any extended DNS error"
3600        );
3601        assert_ne!(got, fallback, "not the locally synthesized SERVFAIL");
3602    }
3603
3604    /// A first REFUSED is relayed only when every failure was a refusal. When a later upstream
3605    /// answered SERVFAIL, Go's tally has seen a non-refusal and the first failure is not a SERVFAIL,
3606    /// so the client gets the synthesized SERVFAIL — neither the refusal nor the later SERVFAIL.
3607    #[tokio::test]
3608    async fn refusal_then_servfail_returns_the_fallback_not_the_refusal() {
3609        let query = build_query(0x20a, &["api", "example", "com"], 1, 1);
3610        let (first, second) = (upstream_addr(1), upstream_addr(2));
3611        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"first refusal");
3612        let servfail = upstream_response(&query, RCODE_SERVFAIL, 0, b"second servfail");
3613        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3614
3615        let (got, asked) = run_forward_walk(
3616            &[
3617                (first, Some((first, refusal.clone()))),
3618                (second, Some((second, servfail.clone()))),
3619            ],
3620            &query,
3621            fallback.clone(),
3622        )
3623        .await;
3624
3625        assert_eq!(asked, vec![first, second]);
3626        assert_eq!(
3627            got, fallback,
3628            "a SERVFAIL anywhere means the first REFUSED is not what the client is told"
3629        );
3630        assert_ne!(got, refusal);
3631        assert_ne!(got, servfail, "only a FIRST failure's SERVFAIL is relayed");
3632    }
3633
3634    /// The same when the later upstream said nothing at all: a timeout is a non-refusal failure, so
3635    /// the first REFUSED gives way to the synthesized SERVFAIL.
3636    #[tokio::test]
3637    async fn refusal_then_silent_upstream_returns_the_fallback_not_the_refusal() {
3638        let query = build_query(0x20b, &["api", "example", "com"], 1, 1);
3639        let (first, second) = (upstream_addr(1), upstream_addr(2));
3640        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"first refusal");
3641        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3642
3643        let (got, asked) = run_forward_walk(
3644            &[(first, Some((first, refusal.clone()))), (second, None)],
3645            &query,
3646            fallback.clone(),
3647        )
3648        .await;
3649
3650        assert_eq!(asked, vec![first, second]);
3651        assert_eq!(got, fallback, "a silent upstream is not a refusal");
3652    }
3653
3654    /// When the first failure is a silence, a later upstream's SERVFAIL is not relayed either: Go
3655    /// relays an upstream's bytes only when the FIRST error carries them.
3656    #[tokio::test]
3657    async fn silent_upstream_then_servfail_returns_the_fallback() {
3658        let query = build_query(0x20c, &["api", "example", "com"], 1, 1);
3659        let (first, second) = (upstream_addr(1), upstream_addr(2));
3660        let servfail = upstream_response(&query, RCODE_SERVFAIL, 0, b"second servfail");
3661        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3662
3663        let (got, _asked) = run_forward_walk(
3664            &[(first, None), (second, Some((second, servfail.clone())))],
3665            &query,
3666            fallback.clone(),
3667        )
3668        .await;
3669
3670        assert_eq!(got, fallback);
3671        assert_ne!(got, servfail);
3672    }
3673
3674    /// A lone upstream that refuses still has its refusal relayed: with nothing else to wait for,
3675    /// treating REFUSED as soft changes nothing about what the client is told.
3676    #[tokio::test]
3677    async fn lone_refusing_upstream_still_has_its_refusal_relayed() {
3678        let query = build_query(0x206, &["api", "example", "com"], 1, 1);
3679        let only = upstream_addr(1);
3680        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"refused");
3681        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3682
3683        let (got, asked) =
3684            run_forward_walk(&[(only, Some((only, refusal.clone())))], &query, fallback).await;
3685
3686        assert_eq!(asked, vec![only]);
3687        assert_eq!(
3688            got, refusal,
3689            "a single upstream's REFUSED is the client's answer"
3690        );
3691    }
3692
3693    /// The anti-poisoning check still runs BEFORE any of the soft-error handling: a datagram whose
3694    /// transaction id is not the one we asked with is discarded outright and never remembered as
3695    /// "the first REFUSED", so an off-path injector cannot plant the response an all-refused forward
3696    /// ends up relaying.
3697    #[tokio::test]
3698    async fn wrong_transaction_id_response_is_discarded_not_remembered_as_a_soft_error() {
3699        let query = build_query(0x207, &["api", "example", "com"], 1, 1);
3700        let only = upstream_addr(1);
3701        let mut poisoned = upstream_response(&query, RCODE_REFUSED, 0, b"injected");
3702        poisoned[0] ^= 0xFF; // a transaction id we never asked with
3703        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3704
3705        let (got, _asked) = run_forward_walk(
3706            &[(only, Some((only, poisoned.clone())))],
3707            &query,
3708            fallback.clone(),
3709        )
3710        .await;
3711
3712        assert_ne!(
3713            got, poisoned,
3714            "a mismatched transaction id must never be relayed"
3715        );
3716        assert_eq!(
3717            got, fallback,
3718            "with the datagram discarded nothing answered, so the synthesized fallback stands"
3719        );
3720    }
3721
3722    /// The same for the source check: a well-formed REFUSED that echoes the question and the
3723    /// transaction id but arrives from an address we did not query is discarded before it can become
3724    /// the forward's remembered soft error.
3725    #[tokio::test]
3726    async fn off_path_source_response_is_discarded_not_remembered_as_a_soft_error() {
3727        let query = build_query(0x208, &["api", "example", "com"], 1, 1);
3728        let (only, off_path) = (upstream_addr(1), upstream_addr(9));
3729        let poisoned = upstream_response(&query, RCODE_REFUSED, 0, b"injected");
3730        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3731
3732        let (got, _asked) = run_forward_walk(
3733            &[(only, Some((off_path, poisoned.clone())))],
3734            &query,
3735            fallback.clone(),
3736        )
3737        .await;
3738
3739        assert_ne!(
3740            got, poisoned,
3741            "a datagram from an unqueried source must never be relayed"
3742        );
3743        assert_eq!(
3744            got, fallback,
3745            "with the datagram discarded nothing answered, so the synthesized fallback stands"
3746        );
3747    }
3748
3749    /// An upstream that says nothing at all (timeout, bind/send/recv failure) is simply skipped, and
3750    /// the next upstream's answer is what the client gets.
3751    #[tokio::test]
3752    async fn silent_upstream_is_skipped_for_the_next_one() {
3753        let query = build_query(0x209, &["api", "example", "com"], 1, 1);
3754        let (first, second) = (upstream_addr(1), upstream_addr(2));
3755        let answer = upstream_response(&query, 0, 1, b"the real answer");
3756        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3757
3758        let (got, asked) = run_forward_walk(
3759            &[(first, None), (second, Some((second, answer.clone())))],
3760            &query,
3761            fallback,
3762        )
3763        .await;
3764
3765        assert_eq!(asked, vec![first, second]);
3766        assert_eq!(got, answer);
3767    }
3768
3769    /// A REFUSED is relayed only when EVERY upstream refused. Once a later upstream SERVFAILs, the
3770    /// forward did not fail by policy alone, and Go's forwarder answers SERVFAIL: its first error is
3771    /// not a SERVFAIL response, so it synthesizes one rather than relaying the refusal.
3772    #[tokio::test]
3773    async fn refusal_then_servfail_is_the_fallback_not_the_refusal() {
3774        let query = build_query(0x20A, &["api", "example", "com"], 1, 1);
3775        let (first, second) = (upstream_addr(1), upstream_addr(2));
3776        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"refused");
3777        let servfail = upstream_response(&query, RCODE_SERVFAIL, 0, b"second servfail");
3778        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3779
3780        let (got, asked) = run_forward_walk(
3781            &[
3782                (first, Some((first, refusal.clone()))),
3783                (second, Some((second, servfail.clone()))),
3784            ],
3785            &query,
3786            fallback.clone(),
3787        )
3788        .await;
3789
3790        assert_eq!(asked, vec![first, second]);
3791        assert_eq!(
3792            got, fallback,
3793            "a refusal mixed with a SERVFAIL is a SERVFAIL"
3794        );
3795        assert_ne!(got, refusal, "the first refusal must not be relayed");
3796        assert_ne!(
3797            got, servfail,
3798            "nor a later SERVFAIL that was not the first failure"
3799        );
3800    }
3801
3802    /// The same when the later upstream never answers: a transport failure is not a refusal, so the
3803    /// forward is no longer "every upstream refused" and the client gets the SERVFAIL fallback.
3804    #[tokio::test]
3805    async fn refusal_then_silence_is_the_fallback_not_the_refusal() {
3806        let query = build_query(0x20B, &["api", "example", "com"], 1, 1);
3807        let (first, second) = (upstream_addr(1), upstream_addr(2));
3808        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"refused");
3809        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3810
3811        let (got, asked) = run_forward_walk(
3812            &[(first, Some((first, refusal.clone()))), (second, None)],
3813            &query,
3814            fallback.clone(),
3815        )
3816        .await;
3817
3818        assert_eq!(asked, vec![first, second]);
3819        assert_eq!(got, fallback, "a refusal then no answer is a SERVFAIL");
3820    }
3821
3822    /// A datagram the anti-poisoning check discards counts as a non-refusal failure too (Go's
3823    /// transaction-id mismatch is an error that is not `errRefused`), so it also stops an earlier
3824    /// refusal from being relayed.
3825    #[tokio::test]
3826    async fn refusal_then_mismatched_response_is_the_fallback_not_the_refusal() {
3827        let query = build_query(0x20C, &["api", "example", "com"], 1, 1);
3828        let (first, second) = (upstream_addr(1), upstream_addr(2));
3829        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"refused");
3830        let mut mismatched = upstream_response(&query, RCODE_REFUSED, 0, b"wrong txid");
3831        mismatched[0] ^= 0xFF;
3832        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3833
3834        let (got, _asked) = run_forward_walk(
3835            &[
3836                (first, Some((first, refusal))),
3837                (second, Some((second, mismatched))),
3838            ],
3839            &query,
3840            fallback.clone(),
3841        )
3842        .await;
3843
3844        assert_eq!(got, fallback);
3845    }
3846
3847    /// An upstream SERVFAIL is relayed only when it was the FIRST failure. After an upstream that
3848    /// never answered, Go's first error is a transport error, not a SERVFAIL response, so it
3849    /// synthesizes the SERVFAIL rather than relaying the later upstream's.
3850    #[tokio::test]
3851    async fn silence_then_servfail_is_the_fallback_not_the_upstream_servfail() {
3852        let query = build_query(0x20D, &["api", "example", "com"], 1, 1);
3853        let (first, second) = (upstream_addr(1), upstream_addr(2));
3854        let servfail = upstream_response(&query, RCODE_SERVFAIL, 0, b"second servfail");
3855        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3856
3857        let (got, asked) = run_forward_walk(
3858            &[(first, None), (second, Some((second, servfail.clone())))],
3859            &query,
3860            fallback.clone(),
3861        )
3862        .await;
3863
3864        assert_eq!(asked, vec![first, second]);
3865        assert_eq!(got, fallback);
3866        assert_ne!(got, servfail);
3867    }
3868
3869    /// The mirror of the case above, and the only branch that still relays an upstream's bytes once
3870    /// a non-refusal has been seen: the FIRST failure is an upstream SERVFAIL and the second
3871    /// upstream is silent. The held SERVFAIL is relayed verbatim, so its RFC 8914 extended DNS error
3872    /// survives rather than being thrown away for the synthesized one.
3873    ///
3874    /// No other test reaches that branch with `saw_non_refused` set by an upstream that sent
3875    /// nothing at all, so this one pins that a later failure carrying no bytes neither replaces the
3876    /// held SERVFAIL nor demotes the forward to `fallback`.
3877    #[tokio::test]
3878    async fn servfail_then_silent_upstream_relays_the_upstream_servfail() {
3879        let query = build_query(0x20e, &["api", "example", "com"], 1, 1);
3880        let (first, second) = (upstream_addr(1), upstream_addr(2));
3881        let servfail = upstream_response(&query, RCODE_SERVFAIL, 0, b"first servfail");
3882        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3883
3884        let (got, asked) = run_forward_walk(
3885            &[(first, Some((first, servfail.clone()))), (second, None)],
3886            &query,
3887            fallback,
3888        )
3889        .await;
3890
3891        assert_eq!(
3892            asked,
3893            vec![first, second],
3894            "the walk must ask both upstreams"
3895        );
3896        assert_eq!(
3897            got, servfail,
3898            "the first failure's own SERVFAIL bytes are relayed, not the synthesized fallback"
3899        );
3900    }
3901
3902    /// An upstream's own soft error is relayed as it was read, as Go relays `rcodeResponseError.res`:
3903    /// no `TC` for the client's advertised size. This query advertises no EDNS size, so a client
3904    /// limit of 512 applies to an *answer*; a REFUSED padded past it — as a long RFC 8914 extended
3905    /// error text would pad it — still reaches the client whole and with `TC` clear.
3906    #[tokio::test]
3907    async fn a_relayed_soft_error_is_not_marked_truncated_for_the_client_size() {
3908        let query = build_query(0x41A, &["example", "com"], 1, 1);
3909        let only = upstream_addr(1);
3910        let refusal = upstream_response(&query, RCODE_REFUSED, 0, &[0xEE; 700]);
3911        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3912
3913        let (got, _asked) = run_forward_walk(
3914            &[(only, Some((only, refusal.clone())))],
3915            &query,
3916            fallback.clone(),
3917        )
3918        .await;
3919
3920        assert_eq!(got, refusal, "relayed byte for byte");
3921        assert_eq!(got[2] & 0x02, 0, "TC clear, as Go sends it");
3922
3923        // The one bound kept is the datagram's, and it is Go's own for the UDP hop: `sendUDP` cuts
3924        // what it read to `maxResponseBytes` before the RCODE switch returns — without setting TC.
3925        let mut full_ring = upstream_response(&query, RCODE_SERVFAIL, 0, b"");
3926        full_ring.resize(MAX_UPSTREAM_RESPONSE + 1, 0xEE);
3927        let (got, _asked) =
3928            run_forward_walk(&[(only, Some((only, full_ring.clone())))], &query, fallback).await;
3929
3930        assert_eq!(
3931            got,
3932            full_ring[..MAX_UPSTREAM_RESPONSE],
3933            "cut to one datagram"
3934        );
3935        assert_eq!(got[2] & 0x02, 0, "and still not marked truncated");
3936    }
3937
3938    /// Off a datagram entirely — fetched over TCP for a TCP client — a relayed soft error is not cut
3939    /// at all.
3940    #[test]
3941    fn a_soft_error_fetched_over_tcp_for_a_tcp_client_is_relayed_whole() {
3942        let query = build_query(0x41B, &["example", "com"], 1, 1);
3943        let mut big = upstream_response(&query, RCODE_SERVFAIL, 0, b"");
3944        big.resize(MAX_UPSTREAM_RESPONSE + 5000, 0xEE);
3945
3946        let out = relay_soft_error(
3947            UpstreamAnswer {
3948                from: upstream_addr(1),
3949                resp: big.clone(),
3950                via: UpstreamTransport::Tcp,
3951            },
3952            ClientTransport::Tcp,
3953        );
3954        assert_eq!(out, big);
3955    }
3956
3957    /// A discarded datagram counts as a non-refusal failure whatever it claims to carry: a spoofed
3958    /// NOERROR answer with a transaction id we never asked with is neither relayed nor mistaken for
3959    /// the walk's end, and still stops an earlier refusal from being relayed.
3960    #[tokio::test]
3961    async fn refusal_then_discarded_answer_is_the_fallback_not_the_refusal() {
3962        let query = build_query(0x20E, &["api", "example", "com"], 1, 1);
3963        let (first, second) = (upstream_addr(1), upstream_addr(2));
3964        let refusal = upstream_response(&query, RCODE_REFUSED, 0, b"first refusal");
3965        let mut poisoned = upstream_response(&query, 0, 1, b"injected");
3966        poisoned[0] ^= 0xFF; // a transaction id we never asked with
3967        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
3968
3969        let (got, _asked) = run_forward_walk(
3970            &[
3971                (first, Some((first, refusal))),
3972                (second, Some((second, poisoned))),
3973            ],
3974            &query,
3975            fallback.clone(),
3976        )
3977        .await;
3978
3979        assert_eq!(got, fallback);
3980    }
3981
3982    #[test]
3983    fn longest_suffix_route_wins() {
3984        let mut routes = std::collections::BTreeMap::new();
3985        routes.insert("example".to_string(), vec![udp("10.0.0.1:53")]);
3986        routes.insert("corp.example".to_string(), vec![udp("10.0.0.2:53")]);
3987        let view = view_with_routes(routes, vec![], vec![]);
3988        let buf = build_query(0x101, &["api", "corp", "example"], 1, 1);
3989
3990        match decide(&view, &buf).expect("decides") {
3991            Decision::Forward { upstreams, .. } => {
3992                assert_eq!(
3993                    upstreams,
3994                    vec!["10.0.0.2:53".parse().unwrap()],
3995                    "longer suffix wins"
3996                );
3997            }
3998            Decision::Reply(_) => panic!("expected forward"),
3999        }
4000    }
4001
4002    #[test]
4003    fn negative_route_is_nxdomain_not_forwarded() {
4004        // An empty upstream list is a negative route: fail closed, never forward.
4005        let mut routes = std::collections::BTreeMap::new();
4006        routes.insert("blocked.example".to_string(), vec![]);
4007        let view = view_with_routes(routes, vec![udp("8.8.8.8:53")], vec![]);
4008        let buf = build_query(0x102, &["x", "blocked", "example"], 1, 1);
4009
4010        match decide(&view, &buf).expect("decides") {
4011            Decision::Reply(resp) => {
4012                let (_, rcode, _) = parse_header(&resp);
4013                assert_eq!(rcode, 3, "NxDomain: negative route is not forwarded");
4014            }
4015            Decision::Forward { .. } => panic!("negative route must not forward"),
4016        }
4017    }
4018
4019    #[test]
4020    fn unrouted_name_forwards_to_fallback_then_global() {
4021        // No route matches: fallback resolvers are preferred over global resolvers.
4022        let view = view_with_routes(
4023            std::collections::BTreeMap::new(),
4024            vec![udp("8.8.8.8:53")],
4025            vec![udp("1.1.1.1:53")],
4026        );
4027        let buf = build_query(0x103, &["example", "com"], 1, 1);
4028
4029        match decide(&view, &buf).expect("decides") {
4030            Decision::Forward { upstreams, .. } => {
4031                assert_eq!(
4032                    upstreams,
4033                    vec!["1.1.1.1:53".parse().unwrap()],
4034                    "fallback preferred"
4035                );
4036            }
4037            Decision::Reply(_) => panic!("expected forward to fallback"),
4038        }
4039    }
4040
4041    #[test]
4042    fn unrouted_name_forwards_to_global_when_no_fallback() {
4043        let view = view_with_routes(
4044            std::collections::BTreeMap::new(),
4045            vec![udp("8.8.8.8:53")],
4046            vec![],
4047        );
4048        let buf = build_query(0x104, &["example", "com"], 1, 1);
4049
4050        match decide(&view, &buf).expect("decides") {
4051            Decision::Forward { upstreams, .. } => {
4052                assert_eq!(upstreams, vec!["8.8.8.8:53".parse().unwrap()]);
4053            }
4054            Decision::Reply(_) => panic!("expected forward to global resolver"),
4055        }
4056    }
4057
4058    #[test]
4059    fn tailnet_name_is_never_forwarded() {
4060        // Anti-leak: a name under a tailnet search domain that has no overlay match must fail
4061        // closed to NXDOMAIN, never leak to an upstream resolver, even with resolvers configured.
4062        let view = view_with_routes(
4063            std::collections::BTreeMap::new(),
4064            vec![udp("8.8.8.8:53")],
4065            vec![udp("1.1.1.1:53")],
4066        );
4067        // "ghost.user.ts.net" is under the tailnet suffix but matches no peer.
4068        let buf = build_query(0x105, &["ghost", "user", "ts", "net"], 1, 1);
4069
4070        match decide(&view, &buf).expect("decides") {
4071            Decision::Reply(resp) => {
4072                let (_, rcode, _) = parse_header(&resp);
4073                assert_eq!(rcode, 3, "NxDomain: tailnet name not leaked upstream");
4074            }
4075            Decision::Forward { .. } => panic!("tailnet name must never be forwarded"),
4076        }
4077    }
4078
4079    #[test]
4080    fn no_resolvers_off_tailnet_is_servfail_not_nxdomain() {
4081        // No route, no resolvers: an OFF-tailnet name cannot be forwarded. Go answers SERVFAIL
4082        // (forwarder.go:1207 "no upstream resolvers set, returning SERVFAIL"), NOT NXDOMAIN — a
4083        // cacheable non-existence for a real name we merely couldn't forward would poison downstream
4084        // stub caches. We still never forward (the name does not leak); we just soft-fail.
4085        let view = view_with_routes(std::collections::BTreeMap::new(), vec![], vec![]);
4086        let buf = build_query(0x106, &["example", "com"], 1, 1);
4087
4088        match decide(&view, &buf).expect("decides") {
4089            Decision::Reply(resp) => {
4090                let (_, rcode, _) = parse_header(&resp);
4091                assert_eq!(
4092                    rcode, 2,
4093                    "ServFail: off-tailnet name with no upstream to forward to"
4094                );
4095            }
4096            Decision::Forward { .. } => panic!("must not forward with no resolvers"),
4097        }
4098    }
4099
4100    #[test]
4101    fn route_with_only_ipv6_upstreams_off_tailnet_is_servfail() {
4102        // A split-DNS route exists but every resolver is IPv6 (filtered out under the IPv4-only
4103        // egress): we have a route yet nowhere to forward. That is an inability to forward an
4104        // off-tailnet name, so SERVFAIL (soft), not a fabricated NXDOMAIN.
4105        let mut routes = std::collections::BTreeMap::new();
4106        routes.insert("corp.example".to_string(), vec![udp("[2001:db8::53]:53")]);
4107        let view = view_with_routes(routes, vec![], vec![]);
4108        let buf = build_query(0x108, &["host", "corp", "example"], 1, 1);
4109
4110        match decide(&view, &buf).expect("decides") {
4111            Decision::Reply(resp) => {
4112                let (_, rcode, _) = parse_header(&resp);
4113                assert_eq!(
4114                    rcode, 2,
4115                    "ServFail: route's resolvers all filtered out (IPv6-only), cannot forward"
4116                );
4117            }
4118            Decision::Forward { .. } => panic!("must not forward when all upstreams are filtered"),
4119        }
4120    }
4121
4122    /// The SERVFAIL this node synthesizes is Go's `servfailResponse`: the query's own header with
4123    /// QR, AA and RCODE set, and nothing else changed. RA stays as the client sent it — clear, for
4124    /// the RD=1 query every stub resolver sends — where a locally built answer would set it; the
4125    /// AD and CD bits and the opcode survive; Z is dropped. The same bytes stand in both for "no
4126    /// upstream to ask" and, as the forward's fallback, for "every upstream failed".
4127    #[test]
4128    fn a_synthesized_servfail_copies_the_query_header_as_go_does() {
4129        let mut buf = build_query(0x10A, &["example", "com"], 1, 1);
4130        buf[2] = 0x01; // RD
4131        buf[3] = 0x70; // Z | AD | CD, RA clear
4132        let check = |resp: &[u8], what: &str| {
4133            assert_eq!(&resp[..2], &buf[..2], "{what}: the query's id");
4134            assert_eq!(
4135                resp[2], 0x85,
4136                "{what}: QR | AA | RD — nothing else in the high byte"
4137            );
4138            assert_eq!(
4139                resp[3], 0x32,
4140                "{what}: AD | CD as sent, RA not set, Z dropped, RCODE = SERVFAIL"
4141            );
4142            assert_eq!(&resp[4..6], &[0, 1], "{what}: one question, echoed");
4143            assert_eq!(&resp[6..12], &[0; 6], "{what}: no other records");
4144            assert_eq!(&resp[12..], &buf[12..], "{what}: the question as asked");
4145        };
4146
4147        let view = view_with_routes(std::collections::BTreeMap::new(), vec![], vec![]);
4148        match decide(&view, &buf).expect("decides") {
4149            Decision::Reply(resp) => check(&resp, "no upstream"),
4150            Decision::Forward { .. } => panic!("must not forward with no resolvers"),
4151        }
4152
4153        let view = view_with_routes(
4154            std::collections::BTreeMap::new(),
4155            vec![udp("192.0.2.53:53")],
4156            vec![],
4157        );
4158        match decide(&view, &buf).expect("decides") {
4159            Decision::Forward { servfail, .. } => check(&servfail, "forward fallback"),
4160            Decision::Reply(_) => panic!("an off-tailnet name with a resolver is forwarded"),
4161        }
4162
4163        // A non-QUERY opcode and a TC bit on the query are copied too.
4164        buf[2] = 0x13; // opcode 2 (STATUS) | TC | RD
4165        let view = view_with_routes(std::collections::BTreeMap::new(), vec![], vec![]);
4166        match decide(&view, &buf).expect("decides") {
4167            Decision::Reply(resp) => assert_eq!(resp[2], 0x80 | 0x10 | 0x04 | 0x03),
4168            Decision::Forward { .. } => panic!("must not forward with no resolvers"),
4169        }
4170    }
4171
4172    #[test]
4173    fn overlay_match_wins_over_forwarding() {
4174        // A known peer name resolves authoritatively even when upstream resolvers are configured.
4175        let mut db = PeerDb::default();
4176        db.upsert(&test_node());
4177        let view = DnsView {
4178            cfg: DnsConfig {
4179                magic_dns: true,
4180                search_domains: vec!["user.ts.net".to_string()],
4181                resolvers: vec![udp("8.8.8.8:53")],
4182                ..Default::default()
4183            },
4184            peers: Some(Arc::new(db)),
4185            self_node: None,
4186            exit_doh: None,
4187            enable_ipv6: false,
4188            accept_dns: true,
4189        };
4190        let buf = build_query(0x107, &["host", "user", "ts", "net"], 1, 1);
4191
4192        match decide(&view, &buf).expect("decides") {
4193            Decision::Reply(resp) => {
4194                let (_, rcode, ancount) = parse_header(&resp);
4195                assert_eq!(rcode, 0, "authoritative answer wins");
4196                assert_eq!(ancount, 1);
4197            }
4198            Decision::Forward { .. } => panic!("overlay match must not forward"),
4199        }
4200    }
4201
4202    #[test]
4203    fn ipv6_reverse_ptr_is_nxdomain_not_forwarded() {
4204        // Anti-leak: an `ip6.arpa` reverse PTR for a tailnet ULA (fd7a:…) must fail closed to
4205        // NXDOMAIN, never be forwarded — even with an upstream resolver configured. This fork is
4206        // IPv4-only on the tailnet; forwarding would reveal that a v6 address was probed.
4207        let view = view_with_routes(
4208            std::collections::BTreeMap::new(),
4209            vec![udp("8.8.8.8:53")],
4210            vec![udp("1.1.1.1:53")],
4211        );
4212        // Reverse name for fd7a::1 (nibble-reversed) under ip6.arpa. The exact nibble labels don't
4213        // matter to the guard — any name ending in ip6.arpa must fail closed.
4214        let labels = vec![
4215            "1", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
4216            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "a", "7", "d", "f", "ip6",
4217            "arpa",
4218        ];
4219        let buf = build_query(0x200, &labels, 12, 1);
4220
4221        match decide(&view, &buf).expect("decides") {
4222            Decision::Reply(resp) => {
4223                let (_, rcode, _) = parse_header(&resp);
4224                assert_eq!(
4225                    rcode, 3,
4226                    "NxDomain: ip6.arpa reverse must not leak upstream"
4227                );
4228            }
4229            Decision::Forward { .. } => panic!("ip6.arpa PTR must never be forwarded"),
4230        }
4231    }
4232
4233    /// Both transports a client can reach this node over, for the race rules that hold for either.
4234    const BOTH_CLIENTS: [ClientTransport; 2] = [ClientTransport::Udp, ClientTransport::Tcp];
4235
4236    /// A UDP hop that hears nothing and gives up the way [`ask_upstream_udp`] does: after
4237    /// [`UPSTREAM_TIMEOUT`], with `None`. A resolver whose UDP path drops or stalls.
4238    async fn silent_udp_hop() -> Option<(SocketAddr, Vec<u8>)> {
4239        tokio::time::sleep(UPSTREAM_TIMEOUT).await;
4240        None
4241    }
4242
4243    /// The retry this module exists for: an upstream answer with the `TC` bit set is re-asked over
4244    /// TCP, and the TCP answer — not the truncated datagram — is what the walk relays.
4245    ///
4246    /// Two of Go's bounds are pinned here alongside it. The retry goes to the **same** resolver
4247    /// (walking on would hand the query to a resolver the first one already answered), which is why
4248    /// this asserts on `from`; and it re-sends the **same** query, which is why the TCP hop records
4249    /// the bytes it was asked for.
4250    #[tokio::test]
4251    async fn a_truncated_udp_answer_is_retried_over_tcp_to_the_same_resolver() {
4252        let query = build_query(0x400, &["big", "example", "com"], 16, 1);
4253        let upstream = upstream_addr(1);
4254        // What the UDP hop can carry: the resolver cut the record set and said so.
4255        let mut truncated = upstream_response(&query, 0, 1, b"the part that fit");
4256        truncated[2] |= 0x02; // TC
4257        // What TCP can carry: the whole set, far past what any datagram here could hold.
4258        let whole = upstream_response(&query, 0, 40, &[0xAB; 8000]);
4259
4260        for client in BOTH_CLIENTS {
4261            let retries = std::cell::Cell::new(0);
4262            let answer = race_udp_and_tcp(
4263                upstream,
4264                &query,
4265                client,
4266                TcpRetry::Enabled,
4267                || std::future::ready(Some((upstream, truncated.clone()))),
4268                || {
4269                    retries.set(retries.get() + 1);
4270                    std::future::ready(Some(whole.clone()))
4271                },
4272            )
4273            .await
4274            .expect("the upstream answered");
4275
4276            assert_eq!(
4277                answer.resp, whole,
4278                "{client:?}: the TCP answer replaces the truncated datagram"
4279            );
4280            assert_eq!(
4281                answer.via,
4282                UpstreamTransport::Tcp,
4283                "{client:?}: and is labelled as having come over TCP, so the relay cap knows not to \
4284                 chop it"
4285            );
4286            assert_eq!(
4287                answer.from, upstream,
4288                "{client:?}: the retry goes to the SAME resolver, never on to the next one"
4289            );
4290            assert_eq!(
4291                retries.get(),
4292                1,
4293                "{client:?}: one retry, not one per upstream and not one per attempt"
4294            );
4295        }
4296    }
4297
4298    /// Go falls back to the truncated UDP response when the TCP retry fails, rather than to
4299    /// SERVFAIL. A truncated answer still has an intact header and question and a `TC` bit the stub
4300    /// resolver can act on; a synthesized failure is strictly less than we already had.
4301    #[tokio::test]
4302    async fn a_failed_tcp_retry_relays_the_truncated_udp_answer() {
4303        let query = build_query(0x401, &["big", "example", "com"], 16, 1);
4304        let upstream = upstream_addr(1);
4305        let mut truncated = upstream_response(&query, 0, 1, b"the part that fit");
4306        truncated[2] |= 0x02; // TC
4307
4308        for client in BOTH_CLIENTS {
4309            let answer = race_udp_and_tcp(
4310                upstream,
4311                &query,
4312                client,
4313                TcpRetry::Enabled,
4314                || std::future::ready(Some((upstream, truncated.clone()))),
4315                // The resolver refused the connection, reset it, or never framed an answer.
4316                || std::future::ready(None),
4317            )
4318            .await
4319            .expect("a failed retry must not lose the answer we already had");
4320
4321            assert_eq!(
4322                answer.resp, truncated,
4323                "{client:?}: the truncated UDP answer is relayed, not a synthesized failure"
4324            );
4325            assert_eq!(
4326                answer.via,
4327                UpstreamTransport::Udp,
4328                "{client:?}: and it is still a datagram answer, so the relay cap still applies to it"
4329            );
4330        }
4331    }
4332
4333    /// A reply that fit is never retried: the retry exists for the answer that did not, and for
4334    /// nothing else. For a UDP client, whose UDP hop has the resolver to itself for
4335    /// [`UDP_RACE_TIMEOUT`], a prompt answer that fit means no TCP connection at all — one per
4336    /// forwarded query would double the work this node makes every upstream resolver do.
4337    #[tokio::test]
4338    async fn an_answer_that_is_not_truncated_is_never_retried() {
4339        let query = build_query(0x402, &["example", "com"], 1, 1);
4340        let upstream = upstream_addr(1);
4341        let fits = upstream_response(&query, 0, 1, b"a small answer");
4342
4343        let retried = std::cell::Cell::new(false);
4344        let answer = race_udp_and_tcp(
4345            upstream,
4346            &query,
4347            ClientTransport::Udp,
4348            TcpRetry::Enabled,
4349            || std::future::ready(Some((upstream, fits.clone()))),
4350            || {
4351                retried.set(true);
4352                std::future::ready(None)
4353            },
4354        )
4355        .await
4356        .expect("the upstream answered");
4357
4358        assert!(
4359            !retried.get(),
4360            "an untruncated answer must not open a TCP connection"
4361        );
4362        assert_eq!(answer.resp, fits);
4363        assert_eq!(answer.via, UpstreamTransport::Udp);
4364    }
4365
4366    /// A TCP client gets no UDP head start — Go's race timeout is 0 for it — so its TCP hop is
4367    /// already running when the UDP answer lands. An answer that fit still wins: the TCP hop is
4368    /// dropped, not waited for, and its answer never replaces the one UDP brought.
4369    #[tokio::test(start_paused = true)]
4370    async fn a_tcp_client_races_both_hops_and_an_answer_that_fit_still_wins() {
4371        let query = build_query(0x409, &["example", "com"], 1, 1);
4372        let upstream = upstream_addr(1);
4373        let fits = upstream_response(&query, 0, 1, b"a small answer");
4374        let started = tokio::time::Instant::now();
4375
4376        let tcp_started_at = std::cell::Cell::new(None);
4377        let answer = race_udp_and_tcp(
4378            upstream,
4379            &query,
4380            ClientTransport::Tcp,
4381            TcpRetry::Enabled,
4382            async || {
4383                tokio::time::sleep(Duration::from_millis(100)).await;
4384                Some((upstream, fits.clone()))
4385            },
4386            || {
4387                tcp_started_at.set(Some(started.elapsed()));
4388                // A TCP hop still connecting when UDP answers.
4389                std::future::pending()
4390            },
4391        )
4392        .await
4393        .expect("the upstream answered");
4394
4395        assert_eq!(
4396            tcp_started_at.get(),
4397            Some(Duration::ZERO),
4398            "a TCP client's TCP hop starts alongside the UDP hop, not after a head start"
4399        );
4400        assert_eq!(answer.resp, fits, "the answer that fit wins the race");
4401        assert_eq!(answer.via, UpstreamTransport::Udp);
4402        assert_eq!(
4403            started.elapsed(),
4404            Duration::from_millis(100),
4405            "and the race ends when it lands, without waiting on the TCP hop"
4406        );
4407    }
4408
4409    /// Behaviour (1) of Go's race: a resolver that never answers over UDP but answers over TCP
4410    /// still resolves — once the UDP hop's head start runs out, not once [`UPSTREAM_TIMEOUT`] does.
4411    /// Before the race, the UDP hop was waited out in full and returned nothing, so the walk moved on
4412    /// to the next resolver or ended in SERVFAIL without TCP ever being tried.
4413    #[tokio::test(start_paused = true)]
4414    async fn a_silent_udp_hop_falls_back_to_tcp_after_the_race_timeout() {
4415        let query = build_query(0x40A, &["example", "com"], 1, 1);
4416        let upstream = upstream_addr(1);
4417        let over_tcp = upstream_response(&query, 0, 1, b"answered over tcp");
4418
4419        for (client, head_start) in [
4420            (ClientTransport::Udp, UDP_RACE_TIMEOUT),
4421            (ClientTransport::Tcp, Duration::ZERO),
4422        ] {
4423            let started = tokio::time::Instant::now();
4424            let tcp_started_at = std::cell::Cell::new(None);
4425            let answer = race_udp_and_tcp(
4426                upstream,
4427                &query,
4428                client,
4429                TcpRetry::Enabled,
4430                silent_udp_hop,
4431                || {
4432                    tcp_started_at.set(Some(started.elapsed()));
4433                    std::future::ready(Some(over_tcp.clone()))
4434                },
4435            )
4436            .await
4437            .expect("a resolver that answers over TCP resolves");
4438
4439            assert_eq!(answer.resp, over_tcp, "{client:?}");
4440            assert_eq!(answer.via, UpstreamTransport::Tcp, "{client:?}");
4441            assert_eq!(answer.from, upstream, "{client:?}: the same resolver");
4442            assert_eq!(
4443                tcp_started_at.get(),
4444                Some(head_start),
4445                "{client:?}: TCP joins the race when the UDP hop's head start runs out"
4446            );
4447            assert!(
4448                started.elapsed() < UPSTREAM_TIMEOUT,
4449                "{client:?}: the answer must not wait out the UDP hop's own timeout ({:?})",
4450                started.elapsed()
4451            );
4452        }
4453    }
4454
4455    /// A UDP hop that has already **failed** does not sit out its head start: Go's `Race.Start`
4456    /// starts the fallback the moment the first function returns an error, and so does this.
4457    #[tokio::test(start_paused = true)]
4458    async fn a_failed_udp_hop_starts_tcp_at_once() {
4459        let query = build_query(0x40B, &["example", "com"], 1, 1);
4460        let upstream = upstream_addr(1);
4461        let over_tcp = upstream_response(&query, 0, 1, b"answered over tcp");
4462        let started = tokio::time::Instant::now();
4463
4464        let answer = race_udp_and_tcp(
4465            upstream,
4466            &query,
4467            ClientTransport::Udp,
4468            TcpRetry::Enabled,
4469            // Bind or send failed: nothing will come back.
4470            || std::future::ready(None),
4471            || std::future::ready(Some(over_tcp.clone())),
4472        )
4473        .await
4474        .expect("the TCP hop answered");
4475
4476        assert_eq!(answer.resp, over_tcp);
4477        assert_eq!(answer.via, UpstreamTransport::Tcp);
4478        assert_eq!(
4479            started.elapsed(),
4480            Duration::ZERO,
4481            "no head start is waited out for a hop that already failed"
4482        );
4483
4484        // And when both hops fail there is no answer, so the walk moves on.
4485        let answer = race_udp_and_tcp(
4486            upstream,
4487            &query,
4488            ClientTransport::Udp,
4489            TcpRetry::Enabled,
4490            || std::future::ready(None),
4491            || std::future::ready(None),
4492        )
4493        .await;
4494        assert!(answer.is_err(), "both hops failed: nothing to relay");
4495    }
4496
4497    /// The race is symmetric: a TCP hop that fails first leaves it to the UDP hop, which is waited
4498    /// for rather than abandoned.
4499    #[tokio::test(start_paused = true)]
4500    async fn a_failed_tcp_hop_leaves_the_race_to_the_udp_hop() {
4501        let query = build_query(0x40C, &["example", "com"], 1, 1);
4502        let upstream = upstream_addr(1);
4503        let over_udp = upstream_response(&query, 0, 1, b"answered over udp");
4504
4505        let answer = race_udp_and_tcp(
4506            upstream,
4507            &query,
4508            ClientTransport::Tcp,
4509            TcpRetry::Enabled,
4510            async || {
4511                tokio::time::sleep(Duration::from_secs(1)).await;
4512                Some((upstream, over_udp.clone()))
4513            },
4514            || std::future::ready(None),
4515        )
4516        .await
4517        .expect("the UDP hop answered after the TCP hop failed");
4518
4519        assert_eq!(answer.resp, over_udp);
4520        assert_eq!(answer.via, UpstreamTransport::Udp);
4521    }
4522
4523    /// The race sits inside the walk, not beside it: a first resolver that is silent over UDP but
4524    /// answers over TCP is the resolver that answers. The walk never reaches the second one, and the
4525    /// client has its answer after the head start, not after the UDP hop's full timeout.
4526    #[tokio::test(start_paused = true)]
4527    async fn a_resolver_silent_over_udp_answers_the_walk_over_tcp() {
4528        let query = build_query(0x40D, &["example", "com"], 1, 1);
4529        let first = upstream_addr(1);
4530        let second = upstream_addr(2);
4531        let over_tcp = upstream_response(&query, 0, 1, b"the first resolver over tcp");
4532        let started = tokio::time::Instant::now();
4533
4534        let asked = std::cell::RefCell::new(Vec::new());
4535        let response = forward_walk(
4536            &[first, second],
4537            &query,
4538            servfail_response(),
4539            ClientTransport::Udp,
4540            |upstream| {
4541                asked.borrow_mut().push(upstream);
4542                let over_tcp = over_tcp.clone();
4543                race_udp_and_tcp(
4544                    upstream,
4545                    &query,
4546                    ClientTransport::Udp,
4547                    TcpRetry::Enabled,
4548                    silent_udp_hop,
4549                    move || std::future::ready(Some(over_tcp)),
4550                )
4551            },
4552        )
4553        .await;
4554
4555        assert_eq!(response, over_tcp);
4556        assert_eq!(
4557            asked.into_inner(),
4558            vec![first],
4559            "the resolver that answered over TCP ends the walk"
4560        );
4561        assert_eq!(started.elapsed(), UDP_RACE_TIMEOUT);
4562    }
4563
4564    /// The other way an answer did not fit: the upstream sent one this forwarder cannot relay in a
4565    /// single datagram ([`MAX_UPSTREAM_RESPONSE`]), with `TC` clear because it fit the resolver's
4566    /// own idea of a datagram. [`cap_response`] is about to cut it and set `TC` — so the retry has
4567    /// to fire on it too, or that name resolves only ever as a cut answer. Go detects the same
4568    /// case by reading into a `maxResponseBytes+1` buffer and setting `TC` on the reply it hands
4569    /// its own truncation check.
4570    #[tokio::test]
4571    async fn an_oversize_answer_is_retried_even_with_tc_clear() {
4572        let query = build_edns_query(0x407, &["big", "example", "com"], 16, 1, 4096);
4573        let upstream = upstream_addr(1);
4574        // The one oversize datagram the netstack's 4096-byte receive ring can deliver, TC clear.
4575        let mut full_ring = upstream_response(&query, 0, 1, b"");
4576        full_ring.resize(MAX_UPSTREAM_RESPONSE + 1, 0xAB);
4577        assert_eq!(
4578            full_ring[2] & 0x02,
4579            0,
4580            "the upstream did not mark it truncated"
4581        );
4582        let whole = upstream_response(&query, 0, 40, &[0xAB; 8000]);
4583
4584        for client in BOTH_CLIENTS {
4585            let answer = race_udp_and_tcp(
4586                upstream,
4587                &query,
4588                client,
4589                TcpRetry::Enabled,
4590                || std::future::ready(Some((upstream, full_ring.clone()))),
4591                || std::future::ready(Some(whole.clone())),
4592            )
4593            .await
4594            .expect("the upstream answered");
4595
4596            assert_eq!(
4597                answer.resp, whole,
4598                "{client:?}: an answer too big for one datagram is re-asked over TCP, TC bit or no \
4599                 TC bit"
4600            );
4601            assert_eq!(answer.via, UpstreamTransport::Tcp);
4602        }
4603    }
4604
4605    /// `dns-forwarder-disable-tcp-retries` is the TCP hop's **off** switch, and the polarity is the
4606    /// whole point: a node control never set it on keeps using TCP. Read from the self node through
4607    /// the view, and honoured at the one place that would open the connection — on **every** arm of
4608    /// the race: not for a truncated answer, not for a silent UDP hop once its head start runs out,
4609    /// and not alongside UDP for a TCP client.
4610    #[tokio::test(start_paused = true)]
4611    async fn the_node_attribute_turns_the_tcp_retry_off() {
4612        let mut view = view_with_peer();
4613        assert_eq!(
4614            view.upstream_tcp_retry(),
4615            TcpRetry::Enabled,
4616            "no self node yet ⇒ the retry is on, because on is the default"
4617        );
4618
4619        let mut node = test_node();
4620        view.self_node = Some(node.clone());
4621        assert_eq!(
4622            view.upstream_tcp_retry(),
4623            TcpRetry::Enabled,
4624            "a self node without the attribute ⇒ still on"
4625        );
4626
4627        node.cap_map
4628            .insert("dns-forwarder-disable-tcp-retries".to_string(), vec![]);
4629        view.self_node = Some(node);
4630        assert_eq!(
4631            view.upstream_tcp_retry(),
4632            TcpRetry::Disabled,
4633            "the attribute control sets is what turns it off"
4634        );
4635
4636        let query = build_query(0x403, &["big", "example", "com"], 16, 1);
4637        let upstream = upstream_addr(1);
4638        let mut truncated = upstream_response(&query, 0, 1, b"the part that fit");
4639        truncated[2] |= 0x02; // TC
4640
4641        for client in BOTH_CLIENTS {
4642            // With it off, a truncated answer is relayed as it came — no TCP connection at all.
4643            let retried = std::cell::Cell::new(false);
4644            let answer = race_udp_and_tcp(
4645                upstream,
4646                &query,
4647                client,
4648                view.upstream_tcp_retry(),
4649                || std::future::ready(Some((upstream, truncated.clone()))),
4650                || {
4651                    retried.set(true);
4652                    std::future::ready(None)
4653                },
4654            )
4655            .await
4656            .expect("the upstream answered");
4657
4658            assert!(
4659                !retried.get(),
4660                "{client:?}: the attribute must stop the TCP retry being made at all"
4661            );
4662            assert_eq!(
4663                answer.resp, truncated,
4664                "{client:?}: relayed truncated, as control asked"
4665            );
4666            assert_eq!(answer.via, UpstreamTransport::Udp);
4667
4668            // And a UDP hop that never answers is waited out, not raced: no fallback either.
4669            let started = tokio::time::Instant::now();
4670            let raced = std::cell::Cell::new(false);
4671            let answer = race_udp_and_tcp(
4672                upstream,
4673                &query,
4674                client,
4675                view.upstream_tcp_retry(),
4676                silent_udp_hop,
4677                || {
4678                    raced.set(true);
4679                    std::future::ready(Some(truncated.clone()))
4680                },
4681            )
4682            .await;
4683
4684            assert!(
4685                !raced.get(),
4686                "{client:?}: the attribute must keep the TCP hop out of the race too"
4687            );
4688            assert!(answer.is_err(), "{client:?}: UDP said nothing, so nothing");
4689            assert_eq!(
4690                started.elapsed(),
4691                UPSTREAM_TIMEOUT,
4692                "{client:?}: the UDP hop runs to its own timeout, as it did before the race"
4693            );
4694        }
4695    }
4696
4697    /// App-connector attributes on the self node (capability versions 143 and 150) add no DNS
4698    /// route: with each of them, every app domain is answered exactly as without, forwarded to
4699    /// the tailnet's resolver rather than routed to the app (Go conn25's `tailscale-app:<name>`
4700    /// route, `TestAppDNSRoutes` / `TestExtraDNSRoutesHook`). This client has no conn25, as Go's
4701    /// `ts_omit_conn25` build; the control-side half is
4702    /// `ts_control`'s `app_connector_attributes_change_nothing`.
4703    #[test]
4704    fn app_connector_attributes_add_no_dns_route() {
4705        let magicip = r#"{"name":"app1","domains":["example.com","*.wild.example.com"],"connectors":["tag:woo"],"mode":"magicip"}"#;
4706        let subnet = r#"{"name":"subnet-app","domains":["subnet.example.com"],"connectors":["tag:subnet-app"],"mode":"subnet"}"#;
4707        let attributes: [&[(&str, &[&str])]; 4] = [
4708            &[
4709                ("tailscale.com/app-connectors", &[magicip, subnet]),
4710                ("tailscale.com/app-connectors-experimental-ippools", &["{}"]),
4711            ],
4712            &[("tailscale.com/app-connectors-experimental", &[magicip])],
4713            &[("tailscale.com/app-connectors", &[subnet])],
4714            &[("tailscale.com/app-connectors", &[r#""bad""#])],
4715        ];
4716
4717        let mut base = view_with_peer();
4718        base.cfg.fallback_resolvers = vec![udp("192.0.2.53:53")];
4719        base.cfg
4720            .routes
4721            .insert("corp.example".to_string(), vec![udp("192.0.2.54:53")]);
4722        base.self_node = Some(test_node());
4723
4724        // A negative answer's SOA SERIAL is the time of the reply (`soa_serial`), so two replies
4725        // a second apart differ there alone. It is zeroed before the replies are compared.
4726        let summary = |view: &DnsView, buf: &[u8]| match decide(view, buf) {
4727            Some(Decision::Reply(mut reply)) => {
4728                if parse_header(&reply).2 == 0 && parse_soa(&reply).is_some() {
4729                    // The SOA is the last record, and SERIAL is 20 bytes from its end.
4730                    let serial = reply.len() - 20;
4731                    reply[serial..serial + 4].fill(0);
4732                }
4733                (Some(reply), vec![], false)
4734            }
4735            Some(Decision::Forward {
4736                upstreams,
4737                recursive,
4738                ..
4739            }) => (None, upstreams, recursive),
4740            None => panic!("no decision"),
4741        };
4742        let names: [&[&str]; 6] = [
4743            &["example", "com"],
4744            &["wild", "example", "com"],
4745            &["a", "wild", "example", "com"],
4746            &["subnet", "example", "com"],
4747            &["host", "corp", "example"],
4748            &["host", "user", "ts", "net"],
4749        ];
4750        for caps in attributes {
4751            let mut node = test_node();
4752            for (cap, values) in caps {
4753                node.cap_map.insert(
4754                    (*cap).to_string(),
4755                    values.iter().map(|v| (*v).to_string()).collect(),
4756                );
4757            }
4758            let mut view = base.clone();
4759            view.self_node = Some(node);
4760            for labels in names {
4761                for qtype in [1, 28, 65] {
4762                    let buf = build_query(0x501, labels, qtype, 1);
4763                    assert_eq!(
4764                        summary(&view, &buf),
4765                        summary(&base, &buf),
4766                        "{caps:?} {labels:?} {qtype}"
4767                    );
4768                }
4769            }
4770            let buf = build_query(0x502, &["example", "com"], 1, 1);
4771            assert_eq!(
4772                summary(&view, &buf).1,
4773                vec!["192.0.2.53:53".parse::<SocketAddr>().unwrap()],
4774                "forwarded to the tailnet's resolver"
4775            );
4776        }
4777    }
4778
4779    /// An off-path injector must not be able to buy a TCP connection to a resolver with a datagram
4780    /// it forged. A `TC`-marked datagram from the wrong source, or one that does not echo the
4781    /// question we asked, is relayed to [`forward_walk`] exactly as before — which discards it — and
4782    /// costs no connection on the way.
4783    #[tokio::test]
4784    async fn a_forged_truncated_datagram_does_not_buy_a_tcp_connection() {
4785        let query = build_query(0x404, &["example", "com"], 1, 1);
4786        let upstream = upstream_addr(1);
4787
4788        let retried = std::cell::Cell::new(false);
4789        let mut tcp_hop = || {
4790            retried.set(true);
4791            std::future::ready(None)
4792        };
4793
4794        let mut from_elsewhere = upstream_response(&query, 0, 1, b"injected");
4795        from_elsewhere[2] |= 0x02; // TC
4796        let answer = race_udp_and_tcp(
4797            upstream,
4798            &query,
4799            ClientTransport::Udp,
4800            TcpRetry::Enabled,
4801            || std::future::ready(Some((upstream_addr(9), from_elsewhere.clone()))),
4802            &mut tcp_hop,
4803        )
4804        .await
4805        .expect("the datagram is still handed on for the walk to discard");
4806        assert!(
4807            !retried.get(),
4808            "a datagram from the wrong source must not be retried"
4809        );
4810        assert_eq!(answer.via, UpstreamTransport::Udp);
4811
4812        let other_question = build_query(0x404, &["other", "example", "com"], 1, 1);
4813        let mut wrong_question = upstream_response(&other_question, 0, 1, b"injected");
4814        wrong_question[2] |= 0x02; // TC
4815        let answer = race_udp_and_tcp(
4816            upstream,
4817            &query,
4818            ClientTransport::Udp,
4819            TcpRetry::Enabled,
4820            || std::future::ready(Some((upstream, wrong_question.clone()))),
4821            &mut tcp_hop,
4822        )
4823        .await
4824        .expect("the datagram is still handed on for the walk to discard");
4825        assert!(
4826            !retried.get(),
4827            "a datagram answering another question must not be retried"
4828        );
4829        assert_eq!(answer.via, UpstreamTransport::Udp);
4830    }
4831
4832    /// Where the TCP hop is already running — a TCP client's, which starts with the UDP hop — a
4833    /// forged datagram does not end the race either: it is not an answer, so the resolver's own
4834    /// TCP answer is what comes back.
4835    #[tokio::test]
4836    async fn a_forged_datagram_does_not_cut_short_a_running_tcp_hop() {
4837        let query = build_query(0x40E, &["example", "com"], 1, 1);
4838        let upstream = upstream_addr(1);
4839        let injected = upstream_response(&query, 0, 1, b"injected");
4840        let over_tcp = upstream_response(&query, 0, 1, b"the resolver over tcp");
4841
4842        let answer = race_udp_and_tcp(
4843            upstream,
4844            &query,
4845            ClientTransport::Tcp,
4846            TcpRetry::Enabled,
4847            || std::future::ready(Some((upstream_addr(9), injected.clone()))),
4848            || std::future::ready(Some(over_tcp.clone())),
4849        )
4850        .await
4851        .expect("the TCP hop answered");
4852
4853        assert_eq!(answer.resp, over_tcp);
4854        assert_eq!(answer.via, UpstreamTransport::Tcp);
4855    }
4856
4857    /// The TCP hop gets the same scrutiny as the datagram, and for a reason the datagram check does
4858    /// not have: the hop that loses this race is **dropped**. A TCP message that does not echo the
4859    /// query is one `forward_walk` will discard, so letting it win takes the UDP answer down with
4860    /// it — the future is cancelled and the answer never arrives — and a query that resolves over
4861    /// UDP comes back SERVFAIL instead. Scored as a failed hop, the race stays with UDP.
4862    #[tokio::test(start_paused = true)]
4863    async fn a_mismatched_tcp_answer_leaves_the_race_to_the_udp_hop() {
4864        let query = build_query(0x410, &["example", "com"], 1, 1);
4865        let upstream = upstream_addr(1);
4866        let over_udp = upstream_response(&query, 0, 1, b"the resolver over udp");
4867        // A resolver answering a question we never asked, framed over the connection we opened for
4868        // this one: `response_matches_query` is what tells the two apart.
4869        let other_question = build_query(0x410, &["other", "example", "com"], 1, 1);
4870        let mismatched = upstream_response(&other_question, 0, 1, b"an answer to something else");
4871
4872        // A TCP client races both hops from the start, so the mismatched message is ready while the
4873        // UDP hop is still in flight — the case where winning would cost the answer.
4874        let answer = race_udp_and_tcp(
4875            upstream,
4876            &query,
4877            ClientTransport::Tcp,
4878            TcpRetry::Enabled,
4879            async || {
4880                tokio::time::sleep(Duration::from_millis(100)).await;
4881                Some((upstream, over_udp.clone()))
4882            },
4883            || std::future::ready(Some(mismatched.clone())),
4884        )
4885        .await
4886        .expect("the UDP hop's answer must survive a mismatched TCP message");
4887
4888        assert_eq!(
4889            answer.resp, over_udp,
4890            "the mismatched TCP message must not win a race the UDP hop was still running"
4891        );
4892        assert_eq!(answer.via, UpstreamTransport::Udp);
4893
4894        // And with nothing else running, a mismatched message is no answer at all: the walk moves
4895        // on to the next resolver rather than relaying it.
4896        let answer = race_udp_and_tcp(
4897            upstream,
4898            &query,
4899            ClientTransport::Udp,
4900            TcpRetry::Enabled,
4901            || std::future::ready(None),
4902            || std::future::ready(Some(mismatched.clone())),
4903        )
4904        .await;
4905
4906        assert!(
4907            answer.is_err(),
4908            "a failed UDP hop plus a mismatched TCP message is not an answer"
4909        );
4910    }
4911
4912    /// The truncation retry has the same hole and the worst outcome of it: a truncated answer is a
4913    /// real answer being *held*, and a mismatched TCP reply that replaced it would lose it outright
4914    /// — the same loss a failed TCP retry is already careful not to cause.
4915    #[tokio::test]
4916    async fn a_mismatched_tcp_retry_relays_the_truncated_udp_answer() {
4917        let query = build_query(0x411, &["big", "example", "com"], 16, 1);
4918        let upstream = upstream_addr(1);
4919        let mut truncated = upstream_response(&query, 0, 1, b"the part that fit");
4920        truncated[2] |= 0x02; // TC
4921        // Same question, wrong transaction id: a stale answer to the previous query on a reused
4922        // connection is the everyday way to get one of these without an attacker.
4923        let mut stale = upstream_response(&query, 0, 40, &[0xAB; 600]);
4924        stale[0] ^= 0xFF;
4925
4926        for client in BOTH_CLIENTS {
4927            let answer = race_udp_and_tcp(
4928                upstream,
4929                &query,
4930                client,
4931                TcpRetry::Enabled,
4932                || std::future::ready(Some((upstream, truncated.clone()))),
4933                || std::future::ready(Some(stale.clone())),
4934            )
4935            .await
4936            .expect("a mismatched retry must not lose the answer we already had");
4937
4938            assert_eq!(
4939                answer.resp, truncated,
4940                "{client:?}: the truncated UDP answer is relayed, not the mismatched TCP message"
4941            );
4942            assert_eq!(answer.via, UpstreamTransport::Udp, "{client:?}");
4943        }
4944    }
4945
4946    /// The other side of the fallback, in the shape of Go's `TestForwarderNetstackUpstream`, which
4947    /// bounds its elapsed time by `udpRaceTimeout`: a resolver whose UDP path works must be answered
4948    /// over UDP, inside [`UDP_RACE_TIMEOUT`], with no TCP hop started. The race would otherwise hide
4949    /// a broken UDP hop behind the right bytes arriving two seconds late over TCP — which is why the
4950    /// clock is checked, not only the bytes.
4951    #[tokio::test(start_paused = true)]
4952    async fn a_working_udp_hop_answers_inside_the_race_timeout_without_tcp() {
4953        let query = build_query(0x40F, &["example", "com"], 1, 1);
4954        let upstream = upstream_addr(1);
4955        let over_udp = upstream_response(&query, 0, 1, b"the resolver over udp");
4956        let started = tokio::time::Instant::now();
4957
4958        let tcp_started = std::cell::Cell::new(false);
4959        let answer = race_udp_and_tcp(
4960            upstream,
4961            &query,
4962            ClientTransport::Udp,
4963            TcpRetry::Enabled,
4964            async || {
4965                // A round trip to a resolver that is up.
4966                tokio::time::sleep(Duration::from_millis(50)).await;
4967                Some((upstream, over_udp.clone()))
4968            },
4969            || {
4970                tcp_started.set(true);
4971                std::future::ready(Some(b"never wanted".to_vec()))
4972            },
4973        )
4974        .await
4975        .expect("the upstream answered");
4976
4977        assert_eq!(answer.resp, over_udp);
4978        assert_eq!(answer.via, UpstreamTransport::Udp);
4979        assert!(
4980            started.elapsed() < UDP_RACE_TIMEOUT,
4981            "a working UDP path answers before TCP would ever be tried ({:?})",
4982            started.elapsed()
4983        );
4984        assert!(!tcp_started.get(), "and no TCP connection is opened");
4985    }
4986
4987    /// A SERVFAIL or REFUSED over UDP is a failed hop, not an answer: Go's `sendUDP` returns it as
4988    /// an `rcodeResponseError`, so `Race.Start` starts the TCP hop to the same resolver at once, and
4989    /// that hop's answer is the resolver's answer. Before this, the datagram won the race and the TCP
4990    /// hop was never tried, so a resolver that soft-fails over UDP but answers over TCP did not
4991    /// resolve here.
4992    #[tokio::test(start_paused = true)]
4993    async fn a_udp_soft_error_starts_the_tcp_hop_at_once_and_its_answer_wins() {
4994        let query = build_query(0x412, &["example", "com"], 1, 1);
4995        let upstream = upstream_addr(1);
4996        let over_tcp = upstream_response(&query, 0, 1, b"answered over tcp");
4997
4998        for rcode in [RCODE_SERVFAIL, RCODE_REFUSED] {
4999            let soft = upstream_response(&query, rcode, 0, b"soft over udp");
5000            for client in BOTH_CLIENTS {
5001                let started = tokio::time::Instant::now();
5002                let tcp_started_at = std::cell::Cell::new(None);
5003                let answer = race_udp_and_tcp(
5004                    upstream,
5005                    &query,
5006                    client,
5007                    TcpRetry::Enabled,
5008                    || std::future::ready(Some((upstream, soft.clone()))),
5009                    || {
5010                        tcp_started_at.set(Some(started.elapsed()));
5011                        std::future::ready(Some(over_tcp.clone()))
5012                    },
5013                )
5014                .await
5015                .expect("the TCP hop answered");
5016
5017                assert_eq!(
5018                    answer.resp, over_tcp,
5019                    "rcode {rcode}, {client:?}: the TCP answer, not the soft error"
5020                );
5021                assert_eq!(answer.via, UpstreamTransport::Tcp);
5022                assert_eq!(answer.from, upstream, "the same resolver");
5023                assert_eq!(
5024                    tcp_started_at.get(),
5025                    Some(Duration::ZERO),
5026                    "rcode {rcode}, {client:?}: no head start is waited out after a soft error"
5027                );
5028            }
5029        }
5030    }
5031
5032    /// When both hops soft-fail the resolver has failed, and the failure is Go's joined error read
5033    /// the way `forwardWithDestChan` reads it: refused if EITHER hop refused, and carrying the soft
5034    /// error of the hop that settled first.
5035    #[tokio::test]
5036    async fn both_hops_soft_failing_is_a_failure_carrying_the_first_soft_error() {
5037        let query = build_query(0x413, &["example", "com"], 1, 1);
5038        let upstream = upstream_addr(1);
5039        let servfail = upstream_response(&query, RCODE_SERVFAIL, 0, b"servfail over udp");
5040        let refused = upstream_response(&query, RCODE_REFUSED, 0, b"refused over tcp");
5041
5042        let failure = race_udp_and_tcp(
5043            upstream,
5044            &query,
5045            ClientTransport::Udp,
5046            TcpRetry::Enabled,
5047            || std::future::ready(Some((upstream, servfail.clone()))),
5048            || std::future::ready(Some(refused.clone())),
5049        )
5050        .await
5051        .expect_err("neither hop answered");
5052        assert!(
5053            failure.refused,
5054            "a REFUSED on either hop makes the resolver refused (errors.Is on the joined error)"
5055        );
5056        assert_eq!(
5057            failure.first_soft.map(|soft| soft.resp),
5058            Some(servfail.clone()),
5059            "the soft error kept is the first to settle — the UDP hop's SERVFAIL"
5060        );
5061
5062        // A soft error and a transport failure: the soft error is all there is to keep, and the
5063        // resolver is refused only if that soft error is a refusal.
5064        for (rcode, refused) in [(RCODE_SERVFAIL, false), (RCODE_REFUSED, true)] {
5065            let soft = upstream_response(&query, rcode, 0, b"soft over udp");
5066            let failure = race_udp_and_tcp(
5067                upstream,
5068                &query,
5069                ClientTransport::Udp,
5070                TcpRetry::Enabled,
5071                || std::future::ready(Some((upstream, soft.clone()))),
5072                || std::future::ready(None),
5073            )
5074            .await
5075            .expect_err("neither hop answered");
5076            assert_eq!(failure.refused, refused, "rcode {rcode}");
5077            assert_eq!(failure.first_soft.map(|soft| soft.resp), Some(soft));
5078        }
5079    }
5080
5081    /// The same rule on the other hop: a SERVFAIL or REFUSED over TCP (Go's `sendTCP` returns it as
5082    /// an `rcodeResponseError`) leaves the race to the UDP hop, which is waited for rather than
5083    /// beaten by the soft error.
5084    #[tokio::test(start_paused = true)]
5085    async fn a_tcp_soft_error_leaves_the_race_to_the_udp_hop() {
5086        let query = build_query(0x414, &["example", "com"], 1, 1);
5087        let upstream = upstream_addr(1);
5088        let over_udp = upstream_response(&query, 0, 1, b"answered over udp");
5089        let soft = upstream_response(&query, RCODE_SERVFAIL, 0, b"servfail over tcp");
5090
5091        // A TCP client races both hops from the start, so the TCP soft error is in while the UDP
5092        // hop is still in flight.
5093        let answer = race_udp_and_tcp(
5094            upstream,
5095            &query,
5096            ClientTransport::Tcp,
5097            TcpRetry::Enabled,
5098            async || {
5099                tokio::time::sleep(Duration::from_millis(100)).await;
5100                Some((upstream, over_udp.clone()))
5101            },
5102            || std::future::ready(Some(soft.clone())),
5103        )
5104        .await
5105        .expect("the UDP hop answered after the TCP hop soft-failed");
5106
5107        assert_eq!(answer.resp, over_udp);
5108        assert_eq!(answer.via, UpstreamTransport::Udp);
5109    }
5110
5111    /// A truncated answer held while TCP retries it is not given up for a soft error over TCP: Go's
5112    /// `send` finds the `truncatedResponseError` in the joined error and returns its bytes.
5113    #[tokio::test]
5114    async fn a_soft_tcp_retry_relays_the_truncated_udp_answer() {
5115        let query = build_query(0x415, &["big", "example", "com"], 16, 1);
5116        let upstream = upstream_addr(1);
5117        let mut truncated = upstream_response(&query, 0, 1, b"the part that fit");
5118        truncated[2] |= 0x02; // TC
5119        let soft = upstream_response(&query, RCODE_SERVFAIL, 0, b"servfail over tcp");
5120
5121        for client in BOTH_CLIENTS {
5122            let answer = race_udp_and_tcp(
5123                upstream,
5124                &query,
5125                client,
5126                TcpRetry::Enabled,
5127                || std::future::ready(Some((upstream, truncated.clone()))),
5128                || std::future::ready(Some(soft.clone())),
5129            )
5130            .await
5131            .expect("a soft-failed retry must not lose the answer we already had");
5132
5133            assert_eq!(answer.resp, truncated, "{client:?}");
5134            assert_eq!(answer.via, UpstreamTransport::Udp, "{client:?}");
5135        }
5136    }
5137
5138    /// With the TCP hop switched off, a soft error over UDP is still a failure and not an answer —
5139    /// and no connection is opened to find a better one.
5140    #[tokio::test]
5141    async fn with_tcp_off_a_udp_soft_error_is_a_failure_and_opens_no_connection() {
5142        let query = build_query(0x416, &["example", "com"], 1, 1);
5143        let upstream = upstream_addr(1);
5144        let refused = upstream_response(&query, RCODE_REFUSED, 0, b"refused over udp");
5145
5146        for client in BOTH_CLIENTS {
5147            let dialled = std::cell::Cell::new(false);
5148            let failure = race_udp_and_tcp(
5149                upstream,
5150                &query,
5151                client,
5152                TcpRetry::Disabled,
5153                || std::future::ready(Some((upstream, refused.clone()))),
5154                || {
5155                    dialled.set(true);
5156                    std::future::ready(None)
5157                },
5158            )
5159            .await
5160            .expect_err("a REFUSED is not an answer");
5161
5162            assert!(!dialled.get(), "{client:?}: TCP is off");
5163            assert!(failure.refused, "{client:?}");
5164            assert_eq!(
5165                failure.first_soft.map(|soft| soft.resp),
5166                Some(refused.clone())
5167            );
5168        }
5169    }
5170
5171    /// One scripted upstream for [`run_forward_walk_over_both_hops`]: its address, the datagram its
5172    /// UDP hop brings back, and the message its TCP hop brings back (`None` = nothing came back).
5173    type TwoHopUpstream = (SocketAddr, Option<Vec<u8>>, Option<Vec<u8>>);
5174
5175    /// Run the real [`forward_walk`] over the real [`race_udp_and_tcp`] for a UDP client, with both
5176    /// hops of each upstream scripted. Returns the client's bytes and the upstreams asked.
5177    async fn run_forward_walk_over_both_hops(
5178        script: &[TwoHopUpstream],
5179        query: &[u8],
5180        fallback: Vec<u8>,
5181    ) -> (Vec<u8>, Vec<SocketAddr>) {
5182        let upstreams: Vec<SocketAddr> = script.iter().map(|(upstream, ..)| *upstream).collect();
5183        let asked = std::cell::RefCell::new(Vec::new());
5184
5185        let response = forward_walk(
5186            &upstreams,
5187            query,
5188            fallback,
5189            ClientTransport::Udp,
5190            |upstream| {
5191                asked.borrow_mut().push(upstream);
5192                let (_, over_udp, over_tcp) = script
5193                    .iter()
5194                    .find(|(scripted, ..)| *scripted == upstream)
5195                    .cloned()
5196                    .expect("a scripted upstream");
5197                race_udp_and_tcp(
5198                    upstream,
5199                    query,
5200                    ClientTransport::Udp,
5201                    TcpRetry::Enabled,
5202                    move || std::future::ready(over_udp.map(|resp| (upstream, resp))),
5203                    move || std::future::ready(over_tcp),
5204                )
5205            },
5206        )
5207        .await;
5208
5209        (response, asked.into_inner())
5210    }
5211
5212    /// Consequence (1) of the audit: a resolver that soft-fails over UDP but answers over TCP
5213    /// resolves, and the walk never hands the query to a second resolver Go would not have asked.
5214    #[tokio::test]
5215    async fn a_resolver_that_soft_fails_over_udp_but_answers_over_tcp_ends_the_walk() {
5216        let query = build_query(0x417, &["example", "com"], 1, 1);
5217        let (first, second) = (upstream_addr(1), upstream_addr(2));
5218        let over_tcp = upstream_response(&query, 0, 1, b"the first resolver over tcp");
5219        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
5220
5221        for rcode in [RCODE_SERVFAIL, RCODE_REFUSED] {
5222            let (got, asked) = run_forward_walk_over_both_hops(
5223                &[
5224                    (
5225                        first,
5226                        Some(upstream_response(&query, rcode, 0, b"soft over udp")),
5227                        Some(over_tcp.clone()),
5228                    ),
5229                    (
5230                        second,
5231                        Some(upstream_response(&query, 0, 1, b"the second resolver")),
5232                        None,
5233                    ),
5234                ],
5235                &query,
5236                fallback.clone(),
5237            )
5238            .await;
5239
5240            assert_eq!(
5241                got, over_tcp,
5242                "rcode {rcode}: the first resolver's TCP answer"
5243            );
5244            assert_eq!(
5245                asked,
5246                vec![first],
5247                "rcode {rcode}: the second is never asked"
5248            );
5249        }
5250    }
5251
5252    /// Consequence (2): the refused tally counts a refusal on either hop. The second resolver's UDP
5253    /// SERVFAIL is followed by a TCP REFUSED, which Go counts as refused, so every resolver refused
5254    /// and the first refusal is relayed. Scored on the UDP datagram alone, the SERVFAIL made it a
5255    /// non-refusal and the client got the synthesized SERVFAIL instead.
5256    #[tokio::test]
5257    async fn a_refusal_on_either_hop_counts_toward_every_upstream_refusing() {
5258        let query = build_query(0x418, &["example", "com"], 1, 1);
5259        let (first, second) = (upstream_addr(1), upstream_addr(2));
5260        let first_refusal = upstream_response(&query, RCODE_REFUSED, 0, b"first refusal");
5261        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
5262
5263        let (got, asked) = run_forward_walk_over_both_hops(
5264            &[
5265                (first, Some(first_refusal.clone()), None),
5266                (
5267                    second,
5268                    Some(upstream_response(
5269                        &query,
5270                        RCODE_SERVFAIL,
5271                        0,
5272                        b"servfail over udp",
5273                    )),
5274                    Some(upstream_response(
5275                        &query,
5276                        RCODE_REFUSED,
5277                        0,
5278                        b"refused over tcp",
5279                    )),
5280                ),
5281            ],
5282            &query,
5283            fallback.clone(),
5284        )
5285        .await;
5286
5287        assert_eq!(asked, vec![first, second]);
5288        assert_eq!(got, first_refusal, "every resolver was refused on some hop");
5289        assert_ne!(got, fallback);
5290    }
5291
5292    /// And the relayed bytes are the first soft error to settle, whatever its code: a lone resolver
5293    /// that answers SERVFAIL over UDP and REFUSED over TCP is refused, and Go relays the SERVFAIL
5294    /// it found first in the joined error.
5295    #[tokio::test]
5296    async fn an_all_refused_forward_relays_the_first_soft_error_to_settle() {
5297        let query = build_query(0x419, &["example", "com"], 1, 1);
5298        let only = upstream_addr(1);
5299        let servfail = upstream_response(&query, RCODE_SERVFAIL, 0, b"servfail over udp");
5300        let fallback = upstream_response(&query, RCODE_SERVFAIL, 0, b"synthesized");
5301
5302        let (got, _asked) = run_forward_walk_over_both_hops(
5303            &[(
5304                only,
5305                Some(servfail.clone()),
5306                Some(upstream_response(
5307                    &query,
5308                    RCODE_REFUSED,
5309                    0,
5310                    b"refused over tcp",
5311                )),
5312            )],
5313            &query,
5314            fallback,
5315        )
5316        .await;
5317
5318        assert_eq!(got, servfail);
5319    }
5320
5321    /// The relay cap is a datagram bound, so the one path it must not chop is the one that never
5322    /// touches a datagram: fetched over the TCP hop, handed to a TCP client. Chopping there would
5323    /// hand the stub resolver the same truncated answer it retried over TCP to escape, and the name
5324    /// would still not resolve through this node.
5325    ///
5326    /// The same answer on its way to a **UDP** client is still cut to one datagram and marked `TC`
5327    /// — it has to fit the datagram it leaves in — which is what sends that client to
5328    /// `dns_over_tcp`, where it is served whole.
5329    #[test]
5330    fn a_tcp_fetched_answer_is_relayed_whole_to_a_tcp_client() {
5331        let query = build_edns_query(0x405, &["big", "example", "com"], 16, 1, 4096);
5332        let mut big = query.clone();
5333        big[2] |= 0x80; // QR = 1
5334        big.resize(MAX_UPSTREAM_RESPONSE + 5000, 0xAB);
5335
5336        let out = cap_response(
5337            &query,
5338            big.clone(),
5339            ClientTransport::Tcp,
5340            UpstreamTransport::Tcp,
5341        );
5342        assert_eq!(
5343            out, big,
5344            "TCP end to end: the whole answer, unchopped and unmarked"
5345        );
5346
5347        let out = cap_response(&query, big, ClientTransport::Udp, UpstreamTransport::Tcp);
5348        assert_eq!(
5349            out.len(),
5350            MAX_UPSTREAM_RESPONSE,
5351            "the same answer still has to fit the datagram a UDP client is answered in"
5352        );
5353        assert_ne!(
5354            out[2] & 0x02,
5355            0,
5356            "and is marked truncated, which is what sends that client to the TCP responder"
5357        );
5358    }
5359
5360    /// The TCP hop's framing, driven end to end over an in-memory stream: the query goes out under
5361    /// a two-byte big-endian length prefix (RFC 1035 §4.2.2) in ONE write, and the answer is read
5362    /// back out from under its own prefix. Framing is what a DNS-over-TCP resolver rejects a
5363    /// connection for, so it is checked against a reader rather than asserted about.
5364    #[tokio::test]
5365    async fn tcp_exchange_frames_the_query_and_reads_the_framed_answer() {
5366        let query = build_query(0x406, &["big", "example", "com"], 16, 1);
5367        let answer = upstream_response(&query, 0, 40, &[0xAB; 8000]);
5368
5369        let (mut client, mut server) = tokio::io::duplex(64 * 1024);
5370        let resolver = {
5371            let query = query.clone();
5372            let answer = answer.clone();
5373            tokio::spawn(async move {
5374                let mut len_buf = [0u8; 2];
5375                server.read_exact(&mut len_buf).await.unwrap();
5376                let len = usize::from(u16::from_be_bytes(len_buf));
5377                assert_eq!(len, query.len(), "the prefix declares the query's length");
5378                let mut got = vec![0u8; len];
5379                server.read_exact(&mut got).await.unwrap();
5380                assert_eq!(got, query, "and the query follows it verbatim");
5381
5382                let mut framed = u16::try_from(answer.len()).unwrap().to_be_bytes().to_vec();
5383                framed.extend_from_slice(&answer);
5384                server.write_all(&framed).await.unwrap();
5385            })
5386        };
5387
5388        let got = tcp_exchange(&mut client, &query)
5389            .await
5390            .expect("a well-framed answer is read back");
5391        resolver
5392            .await
5393            .expect("the resolver side saw a framed query");
5394
5395        assert_eq!(
5396            got, answer,
5397            "the answer comes back whole — 8000 bytes no datagram here could have carried"
5398        );
5399    }
5400
5401    /// The `TC` bit a truncated UDP answer sets is what sends a stub resolver to TCP (RFC 1035
5402    /// §4.2.1). Setting it *again* on the TCP answer sends that resolver straight back into another
5403    /// retry, so the client's advertised UDP payload size — a property of the datagram it would
5404    /// have been answered in, and one RFC 7766 §8 gives a TCP client no equivalent of — is applied
5405    /// only to a [`ClientTransport::Udp`] client. Same query, same answer, two transports.
5406    #[test]
5407    fn client_udp_limit_is_not_applied_to_a_tcp_client() {
5408        // No EDNS OPT record, so the client's limit is the classic 512 bytes.
5409        let query = build_query(0x310, &["example", "com"], 1, 1);
5410        let mut answer = query.clone();
5411        answer[2] |= 0x80; // make it a response (QR=1)
5412        answer.resize(900, 0xAB); // over 512, under MAX_UPSTREAM_RESPONSE: only the client limit bites
5413
5414        let udp = cap_response(
5415            &query,
5416            answer.clone(),
5417            ClientTransport::Udp,
5418            UpstreamTransport::Udp,
5419        );
5420        assert_ne!(
5421            udp[2] & 0x02,
5422            0,
5423            "a UDP client that advertised 512 bytes is told the 900-byte answer is truncated"
5424        );
5425        assert_eq!(udp.len(), 900, "and the body is left intact either way");
5426
5427        let tcp = cap_response(&query, answer, ClientTransport::Tcp, UpstreamTransport::Udp);
5428        assert_eq!(
5429            tcp[2] & 0x02,
5430            0,
5431            "the same answer over TCP is NOT marked: the client already did the TCP retry"
5432        );
5433        assert_eq!(tcp.len(), 900, "and is relayed whole");
5434    }
5435
5436    /// The relay cap is a different claim from the client's datagram size, and for an answer that
5437    /// crossed the UDP hop it holds on both client transports: when [`MAX_UPSTREAM_RESPONSE`] really
5438    /// did cut the message, `TC` says so. Handing a TCP client a chopped body with `TC` clear would
5439    /// be a malformed-but-"complete" answer.
5440    #[test]
5441    fn a_chopped_answer_is_marked_truncated_on_both_transports() {
5442        let query = build_edns_query(0x311, &["example", "com"], 1, 1, 4096);
5443        let mut big = query.clone();
5444        big[2] |= 0x80;
5445        big.resize(MAX_UPSTREAM_RESPONSE + 500, 0xAB);
5446
5447        let out = cap_response(&query, big, ClientTransport::Tcp, UpstreamTransport::Udp);
5448        assert_eq!(out.len(), MAX_UPSTREAM_RESPONSE, "capped to one datagram");
5449        assert_ne!(
5450            out[2] & 0x02,
5451            0,
5452            "we really did chop the body, so TC is set for a TCP client too"
5453        );
5454    }
5455
5456    #[test]
5457    fn cap_response_sets_tc_when_truncated() {
5458        // An oversize upstream answer is capped to a single datagram AND marked truncated (TC bit)
5459        // so the stub resolver retries over TCP rather than trusting a chopped message. The query
5460        // advertises a big EDNS buffer so only the relay cap can be what fires here.
5461        let query = build_edns_query(0x300, &["example", "com"], 1, 1, 4096);
5462        let mut big = query.clone();
5463        big[2] |= 0x80; // make it a response (QR=1)
5464        big.resize(MAX_UPSTREAM_RESPONSE + 500, 0xAB);
5465
5466        let out = cap_response(&query, big, ClientTransport::Udp, UpstreamTransport::Udp);
5467        assert_eq!(out.len(), MAX_UPSTREAM_RESPONSE, "capped to one datagram");
5468        assert_ne!(out[2] & 0x02, 0, "TC bit set on truncation");
5469    }
5470
5471    #[test]
5472    fn cap_response_leaves_small_response_untouched() {
5473        // A response that fits both bounds is returned verbatim with no TC bit forced on.
5474        let query = build_query(0x301, &["example", "com"], 1, 1);
5475        let mut small = query.clone();
5476        small[2] |= 0x80;
5477        let before = small.clone();
5478
5479        let out = cap_response(&query, small, ClientTransport::Udp, UpstreamTransport::Udp);
5480        assert_eq!(out, before, "small response unchanged");
5481        assert_eq!(out[2] & 0x02, 0, "TC bit not set when no truncation");
5482    }
5483
5484    #[test]
5485    fn cap_is_a_relay_bound_not_the_read_bound() {
5486        // `forward_query` reads with `recv_from_bytes`, which issues `Recv { max_len: None }`, so
5487        // the netstack has already copied the whole datagram out before `cap_response` runs: the
5488        // cap bounds what we relay, not what we read or allocate. What bounds the read is the
5489        // netstack UDP socket's receive ring (`udp_buffer_size`, which `ts_runtime` leaves at the
5490        // `netcore` default) -- smoltcp drops a datagram larger than that ring at enqueue instead
5491        // of delivering it, and hands us everything up to and including the ring whole. The ring
5492        // being *wider* than the cap is what shows the two are different bounds: the read can put
5493        // more bytes in front of `cap_response` than the cap will relay.
5494        let ring = netstack::netcore::Config::default().udp_buffer_size;
5495        assert!(
5496            ring > MAX_UPSTREAM_RESPONSE,
5497            "the netstack udp receive ring ({ring}) no longer exceeds the relay cap \
5498             ({MAX_UPSTREAM_RESPONSE}): the cap would then be unreachable through this socket, and \
5499             the doc describing it as a relay bound the read can overrun is wrong"
5500        );
5501
5502        // The largest answer the cap passes is relayed byte-for-byte. Ask with an EDNS buffer that
5503        // covers the whole datagram, so the client-limit check (the other half of `cap_response`)
5504        // is not what we are measuring.
5505        let query = build_edns_query(0x302, &["example", "com"], 1, 1, 4096);
5506        let mut largest = query.clone();
5507        largest[2] |= 0x80; // QR=1
5508        largest.resize(MAX_UPSTREAM_RESPONSE, 0xAB);
5509        let before = largest.clone();
5510
5511        let out = cap_response(
5512            &query,
5513            largest,
5514            ClientTransport::Udp,
5515            UpstreamTransport::Udp,
5516        );
5517        assert_eq!(out, before, "an answer at the cap must be relayed verbatim");
5518        assert_eq!(
5519            out[2] & 0x02,
5520            0,
5521            "TC must not be set on a datagram that was never chopped"
5522        );
5523    }
5524
5525    #[test]
5526    fn full_ring_datagram_is_chopped_and_marked_truncated() {
5527        // Upstream's bound is `const maxResponseBytes = 4095` (net/dns/resolver/tsdns.go @
5528        // 9ea7cba44591e0cd840c6c94d23274dd222059bf). `sendUDP` reads into `maxResponseBytes+1`
5529        // bytes exactly so a 4096-byte answer is detectable as "did not fit", then cuts it to 4095
5530        // and sets TC. Here the netstack's 4096-byte receive ring plays the part of Go's `+1`: a
5531        // full-ring datagram is the one deliverable size the cap does not pass, and it must come
5532        // back with the same shape a Go forwarder would have produced. With the cap at 4096 this
5533        // datagram was relayed whole with TC clear, while a Go client on the same tailnet answering
5534        // the same query returned 4095 bytes marked truncated.
5535        let ring = netstack::netcore::Config::default().udp_buffer_size;
5536        let query = build_edns_query(0x303, &["example", "com"], 1, 1, 4096);
5537        let mut full_ring = query.clone();
5538        full_ring[2] |= 0x80; // QR=1
5539        full_ring.resize(ring, 0xAB);
5540
5541        let out = cap_response(
5542            &query,
5543            full_ring,
5544            ClientTransport::Udp,
5545            UpstreamTransport::Udp,
5546        );
5547        assert_eq!(
5548            out.len(),
5549            4095,
5550            "a full-ring answer must be cut to upstream's maxResponseBytes"
5551        );
5552        assert_ne!(out[2] & 0x02, 0, "TC bit set on the chopped answer");
5553    }
5554
5555    #[test]
5556    fn forwarded_reply_over_512_sets_tc_for_a_plain_query() {
5557        // A query with no EDNS OPT record is limited to 512 bytes (RFC 1035), so a 900-byte
5558        // forwarded reply -- well under the 4095 relay cap, and therefore relayed with TC clear
5559        // before this check existed -- must come back marked truncated, body intact.
5560        let query = build_query(0x400, &["example", "com"], 1, 1);
5561        let mut reply = query.clone();
5562        reply[2] |= 0x80; // QR=1
5563        reply.resize(900, 0xAB);
5564
5565        let out = cap_response(
5566            &query,
5567            reply.clone(),
5568            ClientTransport::Udp,
5569            UpstreamTransport::Udp,
5570        );
5571
5572        assert_ne!(
5573            out[2] & 0x02,
5574            0,
5575            "a 900-byte reply to a non-EDNS query must have TC set"
5576        );
5577        assert_eq!(out.len(), 900, "the body is left intact, not chopped");
5578        assert_eq!(
5579            out[3..],
5580            reply[3..],
5581            "only the flags byte carrying TC may differ"
5582        );
5583    }
5584
5585    #[test]
5586    fn forwarded_reply_under_advertised_edns_size_leaves_tc_clear() {
5587        // The same 900-byte reply, but the client advertised a 4096-byte EDNS buffer: it fits, so
5588        // TC must stay clear and the datagram must be relayed byte-for-byte.
5589        let query = build_edns_query(0x401, &["example", "com"], 1, 1, 4096);
5590        let mut reply = query.clone();
5591        reply[2] |= 0x80; // QR=1
5592        reply.resize(900, 0xAB);
5593        let before = reply.clone();
5594
5595        let out = cap_response(&query, reply, ClientTransport::Udp, UpstreamTransport::Udp);
5596
5597        assert_eq!(
5598            out, before,
5599            "a reply within the advertised buffer is verbatim"
5600        );
5601        assert_eq!(out[2] & 0x02, 0, "TC must stay clear");
5602    }
5603
5604    /// Go's `findOPTRecord` accepts an OPT record only in the final 11 bytes of the message, with a
5605    /// root NAME, EDNS version 0 and `RDLEN == 0`; anything else is "no EDNS", i.e. the 512-byte
5606    /// RFC 1035 limit. Every rejection below is a case where a laxer reader would honour a large
5607    /// advertised buffer and leave `TC` clear on an answer a Go node marks truncated.
5608    #[test]
5609    fn client_udp_limit_reads_the_opt_record() {
5610        // No OPT record => the RFC 1035 512-byte limit.
5611        let plain = build_query(0x402, &["example", "com"], 1, 1);
5612        assert_eq!(client_udp_limit(&plain), NO_EDNS_UDP_LIMIT);
5613
5614        // An OPT record's CLASS field carries the advertised size.
5615        let edns = build_edns_query(0x403, &["example", "com"], 1, 1, 1232);
5616        assert_eq!(client_udp_limit(&edns), 1232);
5617
5618        // A value below 512 is taken verbatim. RFC 6891 6.2.3 would floor it at 512, but Go does
5619        // not (`maxSize = int(ednsSize)`), so a Rust node that did would leave `TC` clear where a
5620        // Go node on the same tailnet sets it.
5621        let tiny = build_edns_query(0x404, &["example", "com"], 1, 1, 64);
5622        assert_eq!(client_udp_limit(&tiny), 64);
5623
5624        // An OPT record that is not the last record in the message is not read at all: upstream
5625        // only ever looks at the final 11 bytes.
5626        let mut trailing_rr = build_edns_query(0x405, &["example", "com"], 1, 1, 2048);
5627        // A 1-byte-RDATA TXT (type 16) record for the root name, appended after the OPT.
5628        trailing_rr.extend_from_slice(&[0, 0, 16, 0, 1, 0, 0, 0, 0, 0, 1, 0]);
5629        trailing_rr[11] = 2; // ARCOUNT = 2
5630        assert_eq!(client_udp_limit(&trailing_rr), NO_EDNS_UDP_LIMIT);
5631
5632        // An OPT record carrying options — a DNS cookie, EDNS Client Subnet — has RDLEN != 0 and is
5633        // rejected. This is the common case, not a corner: stub resolvers send cookies routinely.
5634        let cookie =
5635            build_edns_query_with_option(0x406, &["example", "com"], 1, 1, 4096, 10, &[0; 8]);
5636        assert_eq!(client_udp_limit(&cookie), NO_EDNS_UDP_LIMIT);
5637
5638        // An unknown EDNS version is left alone rather than guessed at.
5639        let mut future_version = build_edns_query(0x407, &["example", "com"], 1, 1, 4096);
5640        let ttl_at = future_version.len() - 6; // TTL = extended RCODE (1) | VERSION (1) | flags (2)
5641        future_version[ttl_at + 1] = 1; // EDNS version 1
5642        assert_eq!(client_udp_limit(&future_version), NO_EDNS_UDP_LIMIT);
5643
5644        // A non-root OPT NAME is rejected.
5645        let mut named = build_edns_query(0x408, &["example", "com"], 1, 1, 4096);
5646        let name_at = named.len() - 11;
5647        named[name_at] = 0xC0; // a compression pointer where the root label must be
5648        assert_eq!(client_udp_limit(&named), NO_EDNS_UDP_LIMIT);
5649
5650        // ARCOUNT == 0 means there is no additional section to hold an OPT, whatever the trailing
5651        // bytes happen to look like.
5652        let mut no_ar = build_edns_query(0x409, &["example", "com"], 1, 1, 4096);
5653        no_ar[11] = 0;
5654        assert_eq!(client_udp_limit(&no_ar), NO_EDNS_UDP_LIMIT);
5655
5656        // A truncated message falls back to the conservative limit, never a larger one.
5657        let mut chopped = build_edns_query(0x40A, &["example", "com"], 1, 1, 4096);
5658        chopped.truncate(chopped.len() - 8);
5659        assert_eq!(client_udp_limit(&chopped), NO_EDNS_UDP_LIMIT);
5660    }
5661
5662    /// The whole point of the narrow OPT reader, end to end: a stub resolver that advertises 4096
5663    /// **and** sends a DNS cookie is capped at 512, so the 900-byte forwarded reply comes back with
5664    /// `TC` set. A reader that walked the additional section properly would honour the 4096 and
5665    /// leave `TC` clear — which is the answer no Go node on the tailnet would have produced.
5666    #[test]
5667    fn an_opt_record_carrying_options_is_not_honoured() {
5668        let query =
5669            build_edns_query_with_option(0x40B, &["example", "com"], 1, 1, 4096, 10, &[0; 8]);
5670        let mut reply = query.clone();
5671        reply[2] |= 0x80; // QR=1
5672        reply.resize(900, 0xAB);
5673
5674        let out = cap_response(&query, reply, ClientTransport::Udp, UpstreamTransport::Udp);
5675        assert_ne!(
5676            out[2] & 0x02,
5677            0,
5678            "an OPT record with options is no EDNS at all upstream: the 512-byte limit applies"
5679        );
5680        assert_eq!(out.len(), 900, "the body is left intact, not chopped");
5681    }
5682
5683    /// An advertised size below 512 is honoured as-is. Go floors nothing: `maxSize = int(ednsSize)`
5684    /// whenever an OPT record is present, and only a request with no OPT record falls back to 512.
5685    #[test]
5686    fn an_advertised_size_below_512_is_not_floored() {
5687        let query = build_edns_query(0x40C, &["example", "com"], 1, 1, 200);
5688        let mut reply = query.clone();
5689        reply[2] |= 0x80; // QR=1
5690        reply.resize(300, 0xAB);
5691
5692        let out = cap_response(&query, reply, ClientTransport::Udp, UpstreamTransport::Udp);
5693        assert_ne!(
5694            out[2] & 0x02,
5695            0,
5696            "300 bytes overflows the 200 the client asked for, so TC is set"
5697        );
5698        assert_eq!(out.len(), 300, "the body is left intact, not chopped");
5699    }
5700
5701    /// Upstream runs the size check on answers the resolver builds itself, not only on forwarded
5702    /// ones (`Resolver.Query` calls `checkResponseSizeAndSetTC` right after `respond` succeeds). An
5703    /// authoritative answer is capped at 512 bytes, which says nothing about a client that
5704    /// advertised less than that.
5705    #[test]
5706    fn an_authoritative_answer_over_the_advertised_size_is_marked() {
5707        let view = view_with_peer();
5708        let buf = build_edns_query(0x40D, &["host", "user", "ts", "net"], 1, 1, 20);
5709
5710        let resp = answer(&view, &buf).expect("answers");
5711        assert!(
5712            resp.len() > 20,
5713            "the fixture only works if the answer overflows the advertised 20 bytes"
5714        );
5715
5716        let marked = check_response_size_and_set_tc(&buf, resp.clone(), ClientTransport::Udp);
5717        assert_ne!(
5718            marked[2] & 0x02,
5719            0,
5720            "an answer we composed ourselves can still overflow a small advertised buffer"
5721        );
5722        assert_eq!(marked.len(), resp.len(), "the body is left intact");
5723        assert_eq!(
5724            marked[3..],
5725            resp[3..],
5726            "only the flags byte carrying TC may differ"
5727        );
5728    }
5729
5730    #[test]
5731    fn response_matches_query_rejects_mismatched_question() {
5732        // id + QR match but the echoed question differs (different QNAME) => rejected. This guards
5733        // against an off-path injector that guesses the id but answers a different question.
5734        let query = build_query(0x1234, &["a", "com"], 1, 1);
5735
5736        let mut wrong_question = build_query(0x1234, &["b", "com"], 1, 1);
5737        wrong_question[2] |= 0x80; // QR=1, same id
5738        assert!(
5739            !response_matches_query(&query, &wrong_question),
5740            "different QNAME must be rejected"
5741        );
5742
5743        // A different QTYPE with the same name is also rejected.
5744        let mut wrong_qtype = build_query(0x1234, &["a", "com"], 28, 1);
5745        wrong_qtype[2] |= 0x80;
5746        assert!(
5747            !response_matches_query(&query, &wrong_qtype),
5748            "different QTYPE must be rejected"
5749        );
5750
5751        // The exact echoed question with QR=1 is accepted.
5752        let mut good = query.clone();
5753        good[2] |= 0x80;
5754        assert!(
5755            response_matches_query(&query, &good),
5756            "matching question accepted"
5757        );
5758    }
5759
5760    #[test]
5761    fn suffix_matches_handles_boundaries_and_empty() {
5762        // Exact and label-boundary matches.
5763        assert!(suffix_matches("corp", "corp"));
5764        assert!(suffix_matches("a.corp", "corp"));
5765        assert!(suffix_matches("a.b.corp", "corp"));
5766        // Not a label boundary.
5767        assert!(!suffix_matches("acorp", "corp"));
5768        // Empty suffix never matches (defense-in-depth against `ends_with("")`).
5769        assert!(!suffix_matches("anything.example", ""));
5770        assert!(!suffix_matches("", ""));
5771    }
5772
5773    #[test]
5774    fn empty_search_domain_does_not_capture_everything() {
5775        // Defense-in-depth: an empty search domain must NOT make every name look like a tailnet
5776        // name (which would fail-close legitimate recursive queries / mis-route). With an empty
5777        // suffix present alongside a real resolver, an off-tailnet name still forwards.
5778        let mut view = view_with_routes(
5779            std::collections::BTreeMap::new(),
5780            vec![udp("8.8.8.8:53")],
5781            vec![],
5782        );
5783        view.cfg.search_domains = vec![String::new()];
5784        let buf = build_query(0x400, &["example", "com"], 1, 1);
5785
5786        match decide(&view, &buf).expect("decides") {
5787            Decision::Forward { upstreams, .. } => {
5788                assert_eq!(upstreams, vec!["8.8.8.8:53".parse().unwrap()]);
5789            }
5790            Decision::Reply(_) => {
5791                panic!("empty search domain must not treat every name as tailnet")
5792            }
5793        }
5794    }
5795
5796    #[test]
5797    fn empty_route_suffix_does_not_capture_everything() {
5798        // Defense-in-depth: an empty route suffix must not match every name (which would route all
5799        // queries to that route's upstreams). With an empty-suffix route present, an unrelated name
5800        // still falls through to the global resolver.
5801        let mut routes = std::collections::BTreeMap::new();
5802        routes.insert(String::new(), vec![udp("10.9.9.9:53")]);
5803        let view = view_with_routes(routes, vec![udp("8.8.8.8:53")], vec![]);
5804        let buf = build_query(0x401, &["example", "com"], 1, 1);
5805
5806        match decide(&view, &buf).expect("decides") {
5807            Decision::Forward { upstreams, .. } => {
5808                assert_eq!(
5809                    upstreams,
5810                    vec!["8.8.8.8:53".parse().unwrap()],
5811                    "empty route suffix must not capture; falls through to global"
5812                );
5813            }
5814            Decision::Reply(_) => panic!("expected forward to global resolver"),
5815        }
5816    }
5817
5818    fn udp_exit(addr: &str) -> DnsResolver {
5819        DnsResolver {
5820            transport: ts_control::ResolverTransport::Udp(addr.parse().unwrap()),
5821            use_with_exit_node: true,
5822        }
5823    }
5824
5825    #[test]
5826    fn recursive_forward_is_flagged_route_forward_is_not() {
5827        // A recursive (global/fallback) forward sets `recursive = true` (eligible for DoH
5828        // delegation); a deliberately-configured split-DNS route sets `recursive = false`.
5829        let mut routes = std::collections::BTreeMap::new();
5830        routes.insert("corp.example".to_string(), vec![udp("10.0.0.53:53")]);
5831        let view = view_with_routes(routes, vec![udp("8.8.8.8:53")], vec![]);
5832
5833        let routed = build_query(0x500, &["api", "corp", "example"], 1, 1);
5834        match decide(&view, &routed).expect("decides") {
5835            Decision::Forward { recursive, .. } => {
5836                assert!(!recursive, "split-DNS route is not a recursive forward")
5837            }
5838            Decision::Reply(_) => panic!("expected route forward"),
5839        }
5840
5841        let global = build_query(0x501, &["example", "com"], 1, 1);
5842        match decide(&view, &global).expect("decides") {
5843            Decision::Forward { recursive, .. } => {
5844                assert!(recursive, "unrouted name is a recursive forward")
5845            }
5846            Decision::Reply(_) => panic!("expected recursive forward"),
5847        }
5848    }
5849
5850    #[test]
5851    fn recursive_plan_keeps_udp_without_exit_node() {
5852        // No active exit node: a recursive forward stays on its default UDP upstreams.
5853        let view = view_with_routes(
5854            std::collections::BTreeMap::new(),
5855            vec![udp("8.8.8.8:53")],
5856            vec![],
5857        );
5858        let default = vec!["8.8.8.8:53".parse().unwrap()];
5859        assert_eq!(
5860            recursive_plan(&view, default.clone()),
5861            RecursivePlan::Udp(default)
5862        );
5863    }
5864
5865    #[test]
5866    fn recursive_plan_delegates_to_doh_with_exit_node() {
5867        // Exit node active, no kept-local resolvers: recursive queries delegate to the exit node's
5868        // DoH endpoint so resolution egresses from the exit node, not this host.
5869        let mut view = view_with_routes(
5870            std::collections::BTreeMap::new(),
5871            vec![udp("8.8.8.8:53")],
5872            vec![],
5873        );
5874        let doh: SocketAddr = "100.64.0.5:8080".parse().unwrap();
5875        view.exit_doh = Some(doh);
5876        assert_eq!(
5877            recursive_plan(&view, vec!["8.8.8.8:53".parse().unwrap()]),
5878            RecursivePlan::Doh(doh)
5879        );
5880    }
5881
5882    #[test]
5883    fn recursive_plan_keeps_use_with_exit_node_resolvers_local() {
5884        // Even with an exit node active, resolvers flagged `use_with_exit_node` stay local (Go keeps
5885        // UseWithExitNode resolvers). The plan forwards to those over UDP, never delegating to DoH.
5886        let mut view = view_with_routes(
5887            std::collections::BTreeMap::new(),
5888            vec![udp_exit("10.0.0.53:53"), udp("8.8.8.8:53")],
5889            vec![],
5890        );
5891        view.exit_doh = Some("100.64.0.5:8080".parse().unwrap());
5892        // The default upstreams the caller computed are irrelevant when kept-local resolvers exist;
5893        // the plan must use the kept-local ones.
5894        assert_eq!(
5895            recursive_plan(&view, vec!["8.8.8.8:53".parse().unwrap()]),
5896            RecursivePlan::Udp(vec!["10.0.0.53:53".parse().unwrap()])
5897        );
5898    }
5899
5900    // --- SOA on authoritative negative answers (RFC 2308) -----------------------------------
5901
5902    /// Read an uncompressed name at `off`, returning it dotted and the offset just past it.
5903    fn read_name(resp: &[u8], mut off: usize) -> (String, usize) {
5904        let mut labels: Vec<String> = Vec::new();
5905        loop {
5906            let len = resp[off] as usize;
5907            assert_eq!(len & 0xC0, 0, "no compression pointer expected here");
5908            off += 1;
5909            if len == 0 {
5910                break;
5911            }
5912            labels.push(String::from_utf8(resp[off..off + len].to_vec()).expect("ascii label"));
5913            off += len;
5914        }
5915        (labels.join("."), off)
5916    }
5917
5918    /// The number of records in a response's authority section (NSCOUNT).
5919    fn nscount(resp: &[u8]) -> u16 {
5920        u16::from_be_bytes([resp[8], resp[9]])
5921    }
5922
5923    /// Walk an answer-less response to its authority section and read the SOA there, returning
5924    /// `(zone, record TTL, SERIAL, MINIMUM)`. `None` when the authority section is empty.
5925    ///
5926    /// Also asserts the record's shape as it goes: TYPE=SOA, CLASS=IN, and MNAME/RNAME both equal
5927    /// the owner name (the placeholders Go writes).
5928    fn parse_soa(resp: &[u8]) -> Option<(String, u32, u32, u32)> {
5929        let (.., ancount) = parse_header(resp);
5930        assert_eq!(ancount, 0, "parse_soa only walks answer-less responses");
5931        if nscount(resp) == 0 {
5932            return None;
5933        }
5934        assert_eq!(nscount(resp), 1, "at most one SOA");
5935
5936        // Question: QNAME then QTYPE + QCLASS.
5937        let (_, off) = read_name(resp, 12);
5938        // Authority record: NAME, TYPE, CLASS, TTL, RDLENGTH, RDATA.
5939        let (zone, off) = read_name(resp, off + 4);
5940        let u16_at = |at: usize| u16::from_be_bytes([resp[at], resp[at + 1]]);
5941        let u32_at = |at: usize| u32::from_be_bytes(resp[at..at + 4].try_into().unwrap());
5942        assert_eq!(u16_at(off), 6, "TYPE = SOA");
5943        assert_eq!(u16_at(off + 2), 1, "CLASS = IN");
5944        let ttl = u32_at(off + 4);
5945        let rdlength = u16_at(off + 8) as usize;
5946
5947        // RDATA: MNAME, RNAME, SERIAL, REFRESH, RETRY, EXPIRE, MINIMUM.
5948        let rdata_start = off + 10;
5949        let (mname, off) = read_name(resp, rdata_start);
5950        let (rname, off) = read_name(resp, off);
5951        assert_eq!(mname, zone, "MNAME is the zone (placeholder)");
5952        assert_eq!(rname, zone, "RNAME is the zone (placeholder)");
5953        let serial = u32_at(off);
5954        let minimum = u32_at(off + 16);
5955        assert_eq!(
5956            off + 20 - rdata_start,
5957            rdlength,
5958            "RDLENGTH covers exactly the SOA fields"
5959        );
5960        assert_eq!(resp.len(), off + 20, "the SOA is the last record");
5961        Some((zone, ttl, serial, minimum))
5962    }
5963
5964    /// Roughly-now, for asserting the SOA SERIAL is a unix timestamp rather than a constant.
5965    fn now_unix() -> u32 {
5966        std::time::SystemTime::now()
5967            .duration_since(std::time::UNIX_EPOCH)
5968            .expect("clock after the epoch")
5969            .as_secs() as u32
5970    }
5971
5972    /// An NXDOMAIN for a name under a tailnet search domain is authoritative, so it carries that
5973    /// search domain's SOA with the 10-second negative TTL. Without it a downstream cache picks its
5974    /// own (much longer) negative lifetime and a node renamed to that name stays unresolvable.
5975    #[test]
5976    fn nxdomain_for_tailnet_name_carries_the_search_domain_soa() {
5977        let view = view_with_peer();
5978        let buf = build_query(0x1111, &["nope", "user", "ts", "net"], 1, 1);
5979
5980        let resp = answer(&view, &buf).expect("answers");
5981        let (_, rcode, ancount) = parse_header(&resp);
5982        assert_eq!(rcode, 3, "NXDOMAIN");
5983        assert_eq!(ancount, 0);
5984
5985        let (zone, ttl, serial, minimum) =
5986            parse_soa(&resp).expect("an SOA in the authority section");
5987        assert_eq!(zone, "user.ts.net", "the search domain containing the name");
5988        assert_eq!(ttl, 10, "negative TTL");
5989        assert_eq!(minimum, 10, "MINIMUM also bounds negative caching");
5990        // The serial is the response time in unix seconds, not a fixed placeholder.
5991        assert!(
5992            serial.abs_diff(now_unix()) < 60,
5993            "SERIAL should be about now, got {serial}"
5994        );
5995    }
5996
5997    /// A NODATA — the name exists but we hold no address of the queried family, which is what an
5998    /// AAAA query for a peer becomes with the IPv6 gate off — is negative too, and takes the SOA.
5999    #[test]
6000    fn nodata_aaaa_for_known_peer_carries_the_soa() {
6001        let view = view_with_peer();
6002        assert!(!view.enable_ipv6, "default gate is off");
6003        let buf = build_query(0x2222, &["host", "user", "ts", "net"], 28, 1);
6004
6005        let resp = answer(&view, &buf).expect("answers");
6006        let (_, rcode, ancount) = parse_header(&resp);
6007        assert_eq!(rcode, 0, "NoError (NODATA)");
6008        assert_eq!(ancount, 0);
6009        let (zone, ttl, _, minimum) = parse_soa(&resp).expect("an SOA in the authority section");
6010        assert_eq!(zone, "user.ts.net");
6011        assert_eq!((ttl, minimum), (10, 10));
6012    }
6013
6014    /// A reverse query for an unmatched IP in the tailnet CGNAT range is authoritatively absent, so
6015    /// it carries the SOA of the reverse zone that covers it — the same per-/16 `in-addr.arpa`
6016    /// chunk real tailscaled advertises, not the search domain.
6017    #[test]
6018    fn cgnat_reverse_miss_carries_the_reverse_zone_soa() {
6019        let view = view_with_peer();
6020        // Reverse name for an unclaimed 100.64.0.0/10 address, least-significant octet first.
6021        let buf = build_query(0x3333, &["9", "0", "64", "100", "in-addr", "arpa"], 12, 1);
6022
6023        let resp = answer(&view, &buf).expect("answers");
6024        let (_, rcode, ancount) = parse_header(&resp);
6025        assert_eq!(rcode, 3, "NXDOMAIN");
6026        assert_eq!(ancount, 0);
6027        let (zone, ttl, _, minimum) = parse_soa(&resp).expect("an SOA in the authority section");
6028        assert_eq!(zone, "64.100.in-addr.arpa", "the CGNAT reverse zone");
6029        assert_eq!((ttl, minimum), (10, 10));
6030    }
6031
6032    /// The exotic-qtype path re-applies the CGNAT reverse guard, and its NXDOMAIN is just as
6033    /// authoritative — so it carries the same reverse-zone SOA the PTR arm does.
6034    #[test]
6035    fn exotic_qtype_cgnat_reverse_nxdomain_carries_the_soa() {
6036        let view = view_with_peer();
6037        // TXT (16) for a CGNAT reverse name.
6038        let buf = build_query(0x4444, &["9", "0", "64", "100", "in-addr", "arpa"], 16, 1);
6039
6040        let resp = answer(&view, &buf).expect("answers");
6041        assert_eq!(parse_header(&resp).1, 3, "NXDOMAIN");
6042        let (zone, ..) = parse_soa(&resp).expect("an SOA in the authority section");
6043        assert_eq!(zone, "64.100.in-addr.arpa");
6044    }
6045
6046    /// A negative split-DNS route (a route with no resolvers) is Go's `localDomains` verbatim: the
6047    /// NXDOMAIN it produces is authoritative and names the route's own suffix as its zone.
6048    #[test]
6049    fn negative_route_nxdomain_carries_the_route_zone_soa() {
6050        let mut routes = std::collections::BTreeMap::new();
6051        routes.insert("corp.example".to_string(), vec![]);
6052        let view = view_with_routes(routes, vec![], vec![]);
6053        let buf = build_query(0x5555, &["intranet", "corp", "example"], 1, 1);
6054
6055        let resp = answer(&view, &buf).expect("answers");
6056        assert_eq!(parse_header(&resp).1, 3, "NXDOMAIN");
6057        let (zone, ttl, _, minimum) = parse_soa(&resp).expect("an SOA in the authority section");
6058        assert_eq!(zone, "corp.example");
6059        assert_eq!((ttl, minimum), (10, 10));
6060    }
6061
6062    /// Answers we are NOT authoritative for carry no SOA: a SERVFAIL is a soft failure with nothing
6063    /// to cache, and an `ip6.arpa` NXDOMAIN is this fork's blanket anti-leak refusal, not a claim to
6064    /// serve the IPv6 reverse tree.
6065    #[test]
6066    fn non_authoritative_negative_answers_carry_no_soa() {
6067        let view = view_with_peer();
6068
6069        // Off-tailnet name, no upstream configured => SERVFAIL.
6070        let servfail =
6071            answer(&view, &build_query(0x6, &["example", "com"], 1, 1)).expect("answers");
6072        assert_eq!(parse_header(&servfail).1, 2, "ServFail");
6073        assert_eq!(nscount(&servfail), 0, "SERVFAIL carries no SOA");
6074
6075        // An ip6.arpa reverse name. The exact nibble labels do not matter to the guard.
6076        let mut labels: Vec<&str> = vec!["1"; 32];
6077        labels.push("ip6");
6078        labels.push("arpa");
6079        let ip6 = answer(&view, &build_query(0x7, &labels, 12, 1)).expect("answers");
6080        assert_eq!(parse_header(&ip6).1, 3, "NXDOMAIN");
6081        assert_eq!(nscount(&ip6), 0, "ip6.arpa NXDOMAIN carries no SOA");
6082
6083        // MagicDNS off => REFUSED, which asserts nothing about the name.
6084        let mut off = view_with_peer();
6085        off.cfg.magic_dns = false;
6086        let refused = answer(
6087            &off,
6088            &build_query(0x8, &["host", "user", "ts", "net"], 1, 1),
6089        )
6090        .expect("answers");
6091        assert_eq!(parse_header(&refused).1, 5, "Refused");
6092        assert_eq!(nscount(&refused), 0, "REFUSED carries no SOA");
6093    }
6094
6095    /// A NODATA for a type we simply do not serve on a name we do (TXT on a tailnet name) carries
6096    /// no SOA: Go sets `SOAZone` on a no-data answer only for an A/AAAA/ALL question.
6097    #[test]
6098    fn nodata_for_an_unserved_qtype_carries_no_soa() {
6099        let view = view_with_peer();
6100        let resp = answer(
6101            &view,
6102            &build_query(0x9, &["host", "user", "ts", "net"], 16, 1),
6103        )
6104        .expect("answers");
6105        let (_, rcode, ancount) = parse_header(&resp);
6106        assert_eq!((rcode, ancount), (0, 0), "NODATA");
6107        assert_eq!(nscount(&resp), 0);
6108    }
6109
6110    /// A positive answer has an empty authority section and a 5-second TTL. The short TTL is the
6111    /// positive half of the same argument: the netmap is local and in-memory, so a re-query is
6112    /// nearly free, while a downstream cache would otherwise hide a node rename for the full TTL.
6113    #[test]
6114    fn positive_answer_has_ttl_5_and_no_authority_section() {
6115        let view = view_with_peer();
6116        let resp = answer(
6117            &view,
6118            &build_query(0xA, &["host", "user", "ts", "net"], 1, 1),
6119        )
6120        .expect("answers");
6121        let (_, rcode, ancount) = parse_header(&resp);
6122        assert_eq!((rcode, ancount), (0, 1), "one A record");
6123        assert_eq!(nscount(&resp), 0, "a positive answer claims no zone");
6124        // The single A record's tail is TTL, RDLENGTH, RDATA.
6125        let ttl_at = resp.len() - 10;
6126        let ttl = u32::from_be_bytes(resp[ttl_at..ttl_at + 4].try_into().unwrap());
6127        assert_eq!(ttl, 5, "positive TTL");
6128    }
6129
6130    /// An authoritative negative answer with its SOA attached must still fit the classic 512-byte
6131    /// UDP limit, so the client-limit check leaves TC clear on it for a client that advertised no
6132    /// EDNS buffer. (A client that advertises *less* than 512 is a different case and is marked —
6133    /// see `an_authoritative_answer_over_the_advertised_size_is_marked`.)
6134    #[test]
6135    fn nxdomain_with_soa_stays_within_the_client_udp_limit() {
6136        let view = view_with_peer();
6137        let long = "a".repeat(63);
6138        let buf = build_query(0xB, &[&long, "user", "ts", "net"], 1, 1);
6139
6140        let resp = answer(&view, &buf).expect("answers");
6141        assert_eq!(nscount(&resp), 1, "the SOA fits beside this question");
6142        assert!(resp.len() <= 512, "still one classic UDP datagram");
6143
6144        let marked = check_response_size_and_set_tc(&buf, resp.clone(), ClientTransport::Udp);
6145        assert_eq!(marked, resp, "nothing to mark: an authoritative reply fits");
6146        assert_eq!(
6147            u16::from_be_bytes([marked[2], marked[3]]) & 0x0200,
6148            0,
6149            "TC must stay clear"
6150        );
6151    }
6152
6153    /// When the zone is so long that its SOA no longer fits under the 512-byte cap, the SOA is
6154    /// dropped rather than the answer being truncated: the NXDOMAIN goes back complete, with an
6155    /// empty authority section, TC clear, and still within a client's UDP limit. Losing the SOA
6156    /// only means a resolver falls back to its own negative-cache policy.
6157    #[test]
6158    fn an_soa_that_will_not_fit_is_dropped_and_the_nxdomain_still_answers() {
6159        let long = "a".repeat(63);
6160        let zone = [long.as_str(), long.as_str(), long.as_str()].join(".");
6161        let mut view = view_with_peer();
6162        view.cfg.search_domains = vec![zone.clone()];
6163
6164        let buf = build_query(0xC, &["x", &long, &long, &long], 1, 1);
6165        let resp = answer(&view, &buf).expect("answers");
6166
6167        assert_eq!(parse_header(&resp).1, 3, "NXDOMAIN");
6168        assert_eq!(nscount(&resp), 0, "the SOA did not fit and was dropped");
6169        assert!(resp.len() <= 512, "response stays within the UDP limit");
6170        let marked = check_response_size_and_set_tc(&buf, resp.clone(), ClientTransport::Udp);
6171        assert_eq!(
6172            u16::from_be_bytes([marked[2], marked[3]]) & 0x0200,
6173            0,
6174            "a dropped SOA must not set TC: the fork cannot serve the TCP retry it would ask for"
6175        );
6176    }
6177
6178    /// The zone is the *longest* authoritative suffix containing the name, so a name under a
6179    /// sub-zone gets the sub-zone's SOA rather than the shorter search domain's.
6180    #[test]
6181    fn the_longest_authoritative_zone_wins() {
6182        let mut routes = std::collections::BTreeMap::new();
6183        routes.insert("sub.user.ts.net".to_string(), vec![]);
6184        let mut view = view_with_routes(routes, vec![], vec![]);
6185        view.cfg.search_domains = vec!["user.ts.net".to_string()];
6186
6187        let buf = build_query(0xD, &["nope", "sub", "user", "ts", "net"], 1, 1);
6188        let resp = answer(&view, &buf).expect("answers");
6189        assert_eq!(parse_header(&resp).1, 3, "NXDOMAIN");
6190        let (zone, ..) = parse_soa(&resp).expect("an SOA in the authority section");
6191        assert_eq!(zone, "sub.user.ts.net");
6192    }
6193
6194    /// A name we resolved only by search-domain qualification (a short name like `host`) is not
6195    /// itself inside a zone we serve, so its negative answer names no zone — matching Go, whose
6196    /// `authoritativeZoneFor` is given the query name as asked.
6197    #[test]
6198    fn a_short_name_outside_every_zone_gets_no_soa() {
6199        let mut view = view_with_peer();
6200        view.enable_ipv6 = false;
6201        // `host` resolves to the peer via search-domain qualification, and with IPv6 off the AAAA
6202        // is a NODATA — but `host` sits under no zone we serve.
6203        let resp = answer(&view, &build_query(0xE, &["host"], 28, 1)).expect("answers");
6204        let (_, rcode, ancount) = parse_header(&resp);
6205        assert_eq!((rcode, ancount), (0, 0), "NODATA");
6206        assert_eq!(nscount(&resp), 0, "no zone contains a single-label name");
6207    }
6208}