1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use futures::future::join_all;
use tokio::sync::Semaphore;
use tracing::{debug, instrument, warn};
use super::analysis::{
analyze_results, build_nameserver_consensus, build_nameserver_inconsistencies, PerVantage,
};
use super::servers::default_dns_servers;
use super::types::{DnsServer, NameserverDetails, PropagationResult, ServerResult};
use crate::dns::records::{RecordData, RecordType};
use crate::dns::resolver::DnsResolver;
use crate::error::{Result, SeerError};
/// Caps concurrent A/AAAA lookups during nameserver-IP enrichment so a large
/// custom server list can't trigger an unbounded burst of DNS queries (#61).
const MAX_CONCURRENT_NS_LOOKUPS: usize = 50;
/// Checks DNS propagation across multiple global DNS servers.
#[derive(Debug, Clone)]
pub struct PropagationChecker {
resolver: DnsResolver,
servers: Vec<DnsServer>,
}
impl Default for PropagationChecker {
fn default() -> Self {
Self::new()
}
}
impl PropagationChecker {
pub fn new() -> Self {
Self {
resolver: DnsResolver::new().with_timeout(Duration::from_secs(5)),
servers: default_dns_servers().to_vec(),
}
}
pub fn with_servers(mut self, servers: Vec<DnsServer>) -> Self {
self.servers = servers;
self
}
pub fn add_server(mut self, server: DnsServer) -> Self {
self.servers.push(server);
self
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.resolver = DnsResolver::new().with_timeout(timeout);
self
}
/// Outer deadline for the entire propagation check across all servers.
/// Individual server queries have their own per-query timeout via the resolver;
/// this guards against the aggregate wall-clock time exceeding a safe limit.
const PROPAGATION_TIMEOUT: Duration = Duration::from_secs(15);
/// Hard cap on the post-check nameserver-IP enrichment step for NS lookups.
/// If it expires, propagation results are returned without IP annotations
/// rather than failing the whole call — enrichment is best-effort.
/// Bumped from the single-vantage version (5s) because per-vantage
/// resolution fans out 29 servers × N nameservers; even fully parallel,
/// the slowest single A/AAAA query gates completion and DNS-over-WAN to
/// distant resolvers can exceed the per-query timeout.
const NS_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(8);
#[instrument(skip(self), fields(domain = %domain, record_type = %record_type))]
pub async fn check(&self, domain: &str, record_type: RecordType) -> Result<PropagationResult> {
// Normalize once up front so the stored `domain` field agrees with what
// every per-server query actually resolves, instead of echoing the raw
// input and re-normalizing ~29 times lazily inside the resolver. (The
// DNSSEC checker already normalizes this way.)
let domain = crate::validation::normalize_domain(domain)?;
// An SRV query needs a `_service._proto.name` query name. A bare domain
// is a deterministic input error: without this guard it fails identically
// on every one of the ~29 servers, and the aggregate result (0% / all
// unreachable) is indistinguishable from a real network-wide outage.
// Reject it once, up front, before any fan-out.
if record_type == RecordType::SRV
&& crate::dns::resolver::parse_srv_query(&domain).is_none()
{
return Err(crate::dns::resolver::srv_format_error());
}
debug!(servers = self.servers.len(), "Starting propagation check");
let futures: Vec<_> = self
.servers
.iter()
.map(|server| self.query_server(&domain, record_type, server.clone()))
.collect();
let results = tokio::time::timeout(Self::PROPAGATION_TIMEOUT, join_all(futures))
.await
.map_err(|_| {
warn!(
domain = %domain,
timeout_secs = Self::PROPAGATION_TIMEOUT.as_secs(),
"Propagation check timed out"
);
SeerError::Timeout(format!(
"propagation check for {} timed out after {}s",
domain,
Self::PROPAGATION_TIMEOUT.as_secs()
))
})?;
let servers_checked = results.len();
let servers_responding = results.iter().filter(|r| r.success).count();
let outcome = analyze_results(&results, record_type);
// For NS lookups, ask each responding propagation server what A/AAAA
// it returns for every nameserver hostname observed in the NS answers.
// This is the per-vantage view that surfaces glue-record propagation
// lag — a regional recursor still serving the previous IP shows up as
// a `NameserverIpInconsistency`. Bounded by NS_RESOLUTION_TIMEOUT so a
// slow secondary lookup cannot extend total wall-clock beyond the
// documented bound; on timeout we surface results without IP
// annotations rather than failing the call.
let nameserver_details = if record_type == RecordType::NS {
match tokio::time::timeout(
Self::NS_RESOLUTION_TIMEOUT,
self.resolve_nameserver_details(&results),
)
.await
{
Ok(details) => details,
Err(_) => {
warn!(
domain = %domain,
timeout_secs = Self::NS_RESOLUTION_TIMEOUT.as_secs(),
"Per-vantage nameserver IP enrichment timed out; returning results without IP annotations"
);
None
}
}
} else {
None
};
Ok(PropagationResult {
domain: domain.to_string(),
record_type,
servers_checked,
servers_responding,
propagation_percentage: outcome.propagation_percentage,
results,
consensus_values: outcome.consensus_values,
inconsistencies: outcome.inconsistencies,
unreachable_servers: outcome.unreachable_servers,
// DNSSEC validation is not currently performed by the resolver.
// This field exists so callers / formatters can disclose the
// lack of authentication to users.
dnssec_validated: false,
nameserver_details,
})
}
/// Per-vantage resolution: for every unique nameserver hostname returned
/// across all NS answers, ask each successfully-responding propagation
/// server (via its own IP) for that hostname's A/AAAA addresses.
/// Returns `None` when there are no NS records to enrich; otherwise
/// returns `Some(NameserverDetails { consensus, per_vantage, inconsistencies })`.
///
/// Failed A/AAAA lookups from a given vantage produce an empty list —
/// empty matches an NXDOMAIN/NODATA response, and either way the resolver
/// couldn't provide an IP. If that empty differs from the consensus it
/// surfaces as a `NameserverIpInconsistency`.
///
/// Hostnames are lowercased for dedup so case-variant responses from
/// different upstream resolvers do not trigger redundant lookups.
/// Formatters must lowercase the record value before looking up the map.
async fn resolve_nameserver_details(
&self,
results: &[ServerResult],
) -> Option<NameserverDetails> {
let unique: HashSet<String> = results
.iter()
.flat_map(|sr| sr.records.iter())
.filter_map(|r| match &r.data {
RecordData::NS { nameserver } => Some(nameserver.to_ascii_lowercase()),
_ => None,
})
.collect();
if unique.is_empty() {
return None;
}
// Build a flat (server_ip, nameserver) work list of A+AAAA lookups
// and fan out in parallel. Only successful propagation servers — those
// that already answered the NS query — are queried; an unreachable
// server can't meaningfully report a per-vantage IP either.
let unique_vec: Vec<String> = unique.into_iter().collect();
// Bound the fan-out: this loop produces `responding_servers × unique_ns`
// tasks, each doing 2 lookups. Harmless at the built-in 29-server list,
// but a large custom `with_servers` list would otherwise spawn an
// unbounded burst of concurrent DNS queries (#61).
let sem = Arc::new(Semaphore::new(MAX_CONCURRENT_NS_LOOKUPS));
let mut tasks = Vec::new();
for sr in results.iter().filter(|sr| sr.success) {
for ns in &unique_vec {
let resolver = self.resolver.clone();
let server_ip = sr.server.ip.clone();
let ns = ns.clone();
let sem = sem.clone();
tasks.push(async move {
// Held for the task's lifetime; caps concurrent lookups.
let _permit = sem.acquire().await.ok();
let (a_res, aaaa_res) = tokio::join!(
resolver.resolve(&ns, RecordType::A, Some(&server_ip)),
resolver.resolve(&ns, RecordType::AAAA, Some(&server_ip)),
);
let mut ips: Vec<String> = Vec::new();
if let Ok(records) = a_res {
for r in &records {
if let RecordData::A { address } = &r.data {
ips.push(address.clone());
}
}
}
if let Ok(records) = aaaa_res {
for r in &records {
if let RecordData::AAAA { address } = &r.data {
ips.push(address.clone());
}
}
}
ips.sort();
ips.dedup();
(server_ip, ns, ips)
});
}
}
let outputs = join_all(tasks).await;
let mut per_vantage: PerVantage = HashMap::new();
for (server_ip, ns, ips) in outputs {
per_vantage.entry(server_ip).or_default().insert(ns, ips);
}
let consensus = build_nameserver_consensus(results, &per_vantage, &unique_vec);
let inconsistencies = build_nameserver_inconsistencies(results, &per_vantage, &consensus);
Some(NameserverDetails {
consensus,
per_vantage,
inconsistencies,
})
}
#[cfg(test)]
fn empty_for_tests() -> Self {
Self {
resolver: DnsResolver::new(),
servers: Vec::new(),
}
}
async fn query_server(
&self,
domain: &str,
record_type: RecordType,
server: DnsServer,
) -> ServerResult {
let start = Instant::now();
match self
.resolver
.resolve(domain, record_type, Some(&server.ip))
.await
{
Ok(records) => {
let response_time_ms = start.elapsed().as_millis() as u64;
debug!(
server = %server.name,
records = records.len(),
time_ms = response_time_ms,
"Server responded"
);
ServerResult {
server,
records,
response_time_ms,
success: true,
error: None,
}
}
Err(e) => {
let response_time_ms = start.elapsed().as_millis() as u64;
debug!(
server = %server.name,
error = %e,
"Server query failed"
);
ServerResult {
server,
records: vec![],
response_time_ms,
success: false,
// Sanitized for external return; full detail logged above.
error: Some(e.sanitized_message()),
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `check()` must normalize the input domain ONCE at the top and store the
/// normalized value, rather than echoing back the raw (messy) input. An
/// empty server list keeps this hermetic — no live DNS is performed.
#[tokio::test]
async fn check_stores_normalized_domain() {
let checker = PropagationChecker::empty_for_tests();
let result = checker
.check("HTTPS://WWW.Example.COM/some/path", RecordType::A)
.await
.expect("check with empty server list should succeed");
assert_eq!(
result.domain, "example.com",
"stored domain must be the normalized form, not the raw input"
);
// Sanity: with no servers, nothing was queried.
assert_eq!(result.servers_checked, 0);
assert_eq!(result.servers_responding, 0);
}
/// An SRV query against a bare domain is a deterministic input error, not a
/// network condition. `check()` must reject it up front with `InvalidInput`
/// rather than fanning out and reporting every server as failed (which is
/// indistinguishable from a real outage). Uses the empty-server seam, so the
/// rejection must happen before any server fan-out for this to pass.
#[tokio::test]
async fn check_rejects_srv_against_bare_domain() {
let checker = PropagationChecker::empty_for_tests();
let err = checker
.check("example.com", RecordType::SRV)
.await
.expect_err("bare-domain SRV must be rejected as an input error");
assert!(
matches!(err, SeerError::InvalidInput(_)),
"expected InvalidInput, got: {err:?}"
);
}
/// A properly-formed `_service._proto.name` SRV query must NOT be rejected
/// by the upfront guard (it should proceed to the normal fan-out path).
#[tokio::test]
async fn check_allows_well_formed_srv_query() {
let checker = PropagationChecker::empty_for_tests();
let result = checker
.check("_sip._tcp.example.com", RecordType::SRV)
.await
.expect("well-formed SRV query must pass the upfront guard");
assert_eq!(result.servers_checked, 0);
}
}