zond-engine 0.14.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Resolving a whole target list
//!
//! The two-pass bridge between synchronous parsing and asynchronous resolution.
//! [`collect_names`] finds the names in a list of target expressions by asking
//! the address grammar which halves it cannot make an address of; those are
//! resolved concurrently, and the answers feed the
//! [`HostLookup`](crate::model::parse::target::HostLookup) the second pass reads.
//!
//! Nothing here re-implements the grammar. A name is what [`insert_expression`]
//! rejects as [`IpParseError::Malformed`], the same signal
//! [`TargetMapBuilder`](crate::model::parse::target::TargetMapBuilder) uses to
//! decide a token is worth resolving, so the classification cannot drift
//! from the one the builder applies when it later consumes the same input.

use std::collections::{HashMap, HashSet};
use std::net::IpAddr;

use tokio::task::JoinSet;

use crate::config::ZondConfig;
use crate::model::exclusion::Exclusions;
use crate::model::ip::set::IpSet;
use crate::model::parse::ip::{
    IpParseError, Keyword, ResolverFn, ZoneResolverFn, insert_expression, names_keyword,
};
use crate::model::parse::target::{self, TargetContext, TargetExpr, TargetParseError};
use crate::model::port::PortSet;
use crate::model::target::TargetMap;
use crate::system::interface;
use crate::warn;

use super::Resolver;

/// How many names are resolved at once.
///
/// An mDNS lookup holds a socket open for the length of its reply window, so the
/// ceiling bounds how many sockets a list of `.local` names opens at a time
/// rather than letting a large file open one per name. Unicast lookups are far
/// cheaper, but sharing one ceiling keeps the pass simple, and the network, not
/// this number, is the limit that matters for them.
const MAX_CONCURRENT_LOOKUPS: usize = 16;

/// Resolves every name in `exprs` concurrently, returning a map from each name
/// to the addresses it stands for.
///
/// A name nothing answered for is absent from the map rather than present with
/// an empty list, so a caller can tell "resolved to nothing" from "resolved" by
/// membership alone. This is the pass to run when a caller wants to build the
/// [`TargetMap`] itself, or to move the work across threads: the returned map is
/// owned, where the [`TargetContext`] this reads borrows the caller's keyword
/// and zone resolvers and so cannot cross a thread boundary.
pub async fn resolve_names<S: AsRef<str>>(
    exprs: &[S],
    ctx: &TargetContext<'_>,
    resolver: &Resolver,
) -> HashMap<String, Vec<IpAddr>> {
    let names = collect_names(exprs, ctx);
    resolve_all(names, resolver).await
}

/// Parses `exprs` into a [`TargetMap`], resolving any hostnames along the way.
///
/// The asynchronous counterpart to
/// [`target::to_target_map`](crate::model::parse::target::to_target_map): it
/// resolves first, then builds with a lookup that reads the results, so a name
/// becomes the addresses it stands for instead of the error an unresolved one
/// would raise.
///
/// The returned future borrows `ctx`, and so is only as `Send` as the keyword and
/// zone resolvers `ctx` holds, which are `&dyn Fn` and need not be. A caller that
/// has to move the work across threads resolves with [`resolve_names`] and builds
/// synchronously from the owned map it returns.
pub async fn to_target_map<S: AsRef<str>>(
    exprs: &[S],
    default_ports: PortSet,
    ctx: &TargetContext<'_>,
    resolver: &Resolver,
) -> Result<TargetMap, TargetParseError> {
    let resolved = resolve_names(exprs, ctx, resolver).await;

    // Read by the builder's second pass; owns its addresses so it outlives no
    // borrow of the map.
    let lookup = |name: &str| resolved.get(name).cloned();
    let ctx = TargetContext {
        keywords: ctx.keywords,
        zones: ctx.zones,
        hosts: Some(&lookup),
    };

    target::to_target_map(exprs, default_ports, &ctx)
}

/// Resolves `exprs` into a single [`IpSet`], for the discovery phase, which asks
/// only whether a host is there and has no use for ports.
///
/// The convenience over [`to_target_map`] for a caller feeding
/// [`discover`](crate::scanner::discover): a name resolves the same way, and the
/// ports every expression is grouped by are discarded rather than carried.
/// Reports a [`TargetParseError`], which is richer than the address grammar's own
/// error since it can name a host that would not resolve.
pub async fn to_set<S: AsRef<str>>(
    exprs: &[S],
    keywords: Option<ResolverFn<'_>>,
    zones: Option<ZoneResolverFn<'_>>,
    resolver: &Resolver,
) -> Result<IpSet, TargetParseError> {
    let ctx = TargetContext {
        keywords,
        zones,
        hosts: None,
    };

    // The port specification is immaterial here: it only groups addresses, and
    // they are unioned back together below regardless of which group they fell
    // into.
    let map = to_target_map(exprs, PortSet::default(), &ctx, resolver).await?;

    Ok(ips_of(&map))
}

/// The addresses `exprs` names, under the caller's DNS policy.
///
/// The one decision [`for_discovery_with`] and [`for_exclusion_with`] both make,
/// and they used to make it in identical blocks a dozen lines apart. `Some`
/// resolves hostnames; `None` refuses them, which is what a scan running under
/// [`ZondConfig::no_dns`](crate::config::ZondConfig::no_dns) needs, since looking
/// a target up emits a query to a resolver somebody else operates. Either way a
/// name that cannot be turned into addresses is reported rather than dropped.
///
/// An empty list of expressions is an empty set of addresses through the
/// ordinary path. `for_exclusion_with` used to answer that case first and by
/// hand, which read as a difference between the two callers and was not one.
async fn addresses_of<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
    keywords: Option<ResolverFn<'_>>,
    zones: Option<ZoneResolverFn<'_>>,
) -> Result<IpSet, TargetParseError> {
    match names {
        Some(resolver) => to_set(exprs, keywords, zones, resolver).await,
        None => {
            let ctx = TargetContext {
                keywords,
                zones,
                hosts: None,
            };
            Ok(ips_of(&target::to_target_map(
                exprs,
                PortSet::default(),
                &ctx,
            )?))
        }
    }
}

/// Every address a target map covers, with the port groupings discarded.
///
/// The groups only ever decided which ports went with which addresses, so a
/// caller that has no use for ports is left with their union.
fn ips_of(map: &TargetMap) -> IpSet {
    let mut set = IpSet::new();
    for unit in &map.units {
        for range in unit.ips().v4() {
            set.push_v4_range(*range);
        }
        for range in unit.ips().v6() {
            set.push_v6_range(*range);
        }
    }
    set.canonicalize();
    set
}

/// What a discovery sweep was asked to cover.
///
/// The addresses, and the one thing about the request that the addresses no
/// longer say: whether a *network* was named.
///
/// Those two travel together because separating them is a mistake nobody
/// notices. `lan` and the range it expands to produce the same [`IpSet`], and by
/// the time [`discover`](crate::scanner::discover) has one it cannot tell which
/// was written, so a caller that resolves the addresses and forgets the flag gets
/// a targeted run where a sweep was asked for, no all-nodes echo, no
/// neighbour-table leads, and an IPv6 half that reports a network as empty. It
/// looks exactly like a working scan.
#[derive(Debug, Clone)]
pub struct DiscoveryTargets {
    ips: IpSet,
    segment_sweep: bool,
}

impl DiscoveryTargets {
    /// The addresses to probe.
    pub fn ips(&self) -> &IpSet {
        &self.ips
    }

    /// Takes the addresses, for handing to [`discover`](crate::scanner::discover).
    pub fn into_ips(self) -> IpSet {
        self.ips
    }

    /// Whether a network was named, rather than a set of addresses.
    ///
    /// What [`ZondConfig::segment_sweep`] wants. Prefer
    /// [`apply_to`](Self::apply_to), which puts it there without the caller
    /// having to remember that it is what the field is for.
    pub fn segment_sweep(&self) -> bool {
        self.segment_sweep
    }

    /// Writes what these targets imply into `cfg`.
    ///
    /// Only [`segment_sweep`](ZondConfig::segment_sweep) today. It is a method
    /// rather than a field the caller copies across because the copying is the
    /// step that gets skipped, and the same shape already exists on
    /// `import::settings::Settings::apply_to`.
    pub fn apply_to(&self, cfg: &mut ZondConfig) {
        cfg.segment_sweep = self.segment_sweep;
    }
}

/// Resolves target expressions into everything a discovery sweep needs.
///
/// The one call a front end makes. It wires this host's own interface table for
/// `lan` and for the `%interface` suffix, resolves any hostnames, and works out
/// whether a segment sweep was asked for: three steps that were once three
/// separate things for every consumer to remember, and that every consumer
/// remembered differently.
///
/// `names` is the DNS policy, and it is the caller's because only they know it.
/// `Some` resolves hostnames; `None` refuses them, which is what a scan running
/// under [`ZondConfig::no_dns`] needs, since looking a target up emits a query
/// to a resolver somebody else operates. A name given to a `None` is reported as
/// an unusable expression rather than quietly dropped.
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use zond_engine::{Resolver, ZondConfig, discover, resolve};
///
/// let resolver = Resolver::from_system();
/// let targets = resolve::for_discovery(&["lan"], Some(&resolver)).await?;
///
/// let mut cfg = ZondConfig::default();
/// targets.apply_to(&mut cfg);
///
/// let (_session, task) = discover(targets.into_ips(), &cfg).await?;
/// let report = task.join().await?;
/// # Ok(())
/// # }
/// ```
pub async fn for_discovery<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
) -> Result<DiscoveryTargets, TargetParseError> {
    for_discovery_with(
        exprs,
        names,
        Some(&interface::resolve_keyword),
        Some(&interface::resolve_zone),
    )
    .await
}

/// [`for_discovery`], with the host lookups supplied rather than assumed.
///
/// The same call with its two reads of the local machine handed in. That is what
/// makes the behaviour around `lan` and `%en0` testable somewhere that has
/// neither, and what lets a caller who means something else by `lan`, such as a
/// management network or a lab segment, say so.
pub async fn for_discovery_with<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
    keywords: Option<ResolverFn<'_>>,
    zones: Option<ZoneResolverFn<'_>>,
) -> Result<DiscoveryTargets, TargetParseError> {
    let ips = addresses_of(exprs, names, keywords, zones).await?;

    // Asked of what was written, not of what it expanded to. This is the whole
    // reason the flag has to be worked out here: the addresses cannot answer it.
    let segment_sweep = names_keyword(exprs, Keyword::Lan);

    Ok(DiscoveryTargets { ips, segment_sweep })
}

/// Resolves exclusion expressions into a policy [`scan`](crate::scanner::scan)
/// and [`discover`](crate::scanner::discover) will honour.
///
/// The counterpart of [`for_discovery`], and the same grammar. An exclusion is
/// written the way a target is, so `10.0.5.0/24`, `192.168.1.10-20`,
/// `db.internal`, `lan` and `fe80::1%en0` all work, because a person reading a
/// scope document transcribes both halves of it and a scanner that accepted CIDR
/// for
/// what it must scan and something narrower for what it must not would be asking
/// them to translate the half that matters more.
///
/// `names` is the DNS policy, exactly as on [`for_discovery`]. A name given to a
/// `None` is reported rather than dropped, which for this input is the whole
/// point: an exclusion that quietly failed to parse is an exclusion that quietly
/// does not apply.
///
/// A name is resolved once, here. What comes back is the addresses it stood for
/// at that moment, and the policy holds those rather than the name, so a host
/// that moves during the scan is no longer excluded and one whose record lists
/// two addresses is excluded at both. Write the addresses where that
/// matters, which is most of the time it matters at all.
///
/// # Combining with a settings document
///
/// Layer with [`Exclusions::extend`], never by assigning over
/// [`ZondConfig::exclusions`](crate::config::ZondConfig::exclusions):
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use zond_engine::{Resolver, ZondConfig, resolve};
///
/// let mut cfg = ZondConfig::default();
/// // ... a settings document has already contributed its own ...
///
/// let resolver = Resolver::from_system();
/// let from_arguments = resolve::for_exclusion(&["10.0.5.0/24"], Some(&resolver)).await?;
/// cfg.exclusions.extend(&from_arguments);
/// # Ok(())
/// # }
/// ```
///
/// Assigning would drop whatever an administrator put in a system-wide file, and
/// the resulting scan would look exactly like a correct one. See
/// [`Exclusions::extend`] for why this is the one setting that unions.
pub async fn for_exclusion<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
) -> Result<Exclusions, TargetParseError> {
    for_exclusion_with(
        exprs,
        names,
        Some(&interface::resolve_keyword),
        Some(&interface::resolve_zone),
    )
    .await
}

/// [`for_exclusion`], with the host lookups supplied rather than assumed.
///
/// The same relationship [`for_discovery_with`] has to [`for_discovery`], and it
/// exists for the same reason: what `lan` and `%en0` mean is a fact about this
/// machine, and a test asserting that an exclusion covers a segment should not
/// need the machine to have one.
pub async fn for_exclusion_with<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
    keywords: Option<ResolverFn<'_>>,
    zones: Option<ZoneResolverFn<'_>>,
) -> Result<Exclusions, TargetParseError> {
    Ok(Exclusions::new(
        addresses_of(exprs, names, keywords, zones).await?,
    ))
}

/// Every distinct hostname named across `exprs`, in first-seen order.
///
/// A name is an address half the grammar rejects as
/// [`IpParseError::Malformed`] **and** that
/// [`host_name`](target::host_name) then agrees is a name. Every other rejection,
/// whether a wrong address or a keyword with no resolver or a zone on a global
/// address, is an error about something meant to be an address, and is left for
/// the build pass to report against the expression it belongs to. A token that
/// will not even split is skipped for the same reason: the builder will raise it
/// verbatim.
///
/// The second half used to be missing, and `Malformed` alone is not the
/// builder's rule: it applies two more tests before it consults the lookup, so
/// `192.168.0.300` was sent to a resolver here and refused as a mistyped address
/// there. Asking the same function is what makes the two passes agree, rather
/// than a comment saying they do.
fn collect_names<S: AsRef<str>>(exprs: &[S], ctx: &TargetContext<'_>) -> Vec<String> {
    let mut names = Vec::new();
    let mut seen = HashSet::new();

    for token in exprs {
        let Ok(expr) = TargetExpr::parse(token.as_ref()) else {
            continue;
        };

        for address in expr.addresses() {
            let mut throwaway = IpSet::new();
            if let Err(IpParseError::Malformed(_)) =
                insert_expression(address, &mut throwaway, ctx.keywords, ctx.zones)
                && target::host_name(address) == target::HostName::Yes
                && seen.insert(address.to_string())
            {
                names.push(address.to_string());
            }
        }
    }

    names
}

/// Resolves a list of names concurrently, at most [`MAX_CONCURRENT_LOOKUPS`] in
/// flight, keeping only those that resolved to something.
///
/// One lookup per name rather than per spelling. DNS is case-insensitive, so
/// `NAS` and `nas` are one host and were once two round trips and two map
/// entries.
/// They are resolved once and the answer is recorded under every spelling that
/// asked for it, which leaves the returned map keyed as the caller wrote things:
/// the build pass looks a name up by the token in the expression, and lowering
/// the keys here would simply move the mismatch.
async fn resolve_all(names: Vec<String>, resolver: &Resolver) -> HashMap<String, Vec<IpAddr>> {
    let mut resolved = HashMap::new();
    if names.is_empty() {
        return resolved;
    }

    // Every spelling that asked for one host, under the one name to look up.
    let mut spellings: HashMap<String, Vec<String>> = HashMap::new();
    let mut order = Vec::new();
    for name in names {
        let folded = name.to_ascii_lowercase();
        let written = spellings.entry(folded.clone()).or_default();
        if written.is_empty() {
            order.push(folded);
        }
        written.push(name);
    }

    let mut set: JoinSet<(String, Vec<IpAddr>)> = JoinSet::new();
    let mut pending = order.into_iter();

    for name in pending.by_ref().take(MAX_CONCURRENT_LOOKUPS) {
        spawn_lookup(&mut set, resolver, name);
    }

    while let Some(joined) = set.join_next().await {
        match joined {
            Ok((folded, addresses)) if !addresses.is_empty() => {
                for spelling in spellings.remove(&folded).unwrap_or_default() {
                    resolved.insert(spelling, addresses.clone());
                }
            }
            Ok(_) => {}
            // A lookup that did not finish is a name that resolves to nothing,
            // which is what an absent entry says. Logged rather than swallowed,
            // because every other failure on this path is.
            Err(e) => warn!("a name lookup did not finish: {e}"),
        }

        if let Some(name) = pending.next() {
            spawn_lookup(&mut set, resolver, name);
        }
    }

    resolved
}

/// Spawns one lookup, cloning the resolver into the task so the set owns it.
fn spawn_lookup(set: &mut JoinSet<(String, Vec<IpAddr>)>, resolver: &Resolver, name: String) {
    let resolver = resolver.clone();
    set.spawn(async move {
        let addresses = resolver.resolve(&name).await;
        (name, addresses)
    });
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::parse::ip::Keyword;

    /// The two passes agree about what a name is, because they ask the same
    /// function.
    ///
    /// They once did not. The collector took [`IpParseError::Malformed`] as the
    /// whole answer while the builder applies two more tests before consulting
    /// the lookup, so a mistyped address was sent to a resolver somebody else
    /// operates and then refused here without ever being looked up. A typo in a
    /// target file became a DNS query, which is what `no_dns` exists to
    /// prevent.
    #[test]
    fn a_token_the_builder_will_refuse_is_never_put_on_the_network() {
        let ctx = TargetContext {
            keywords: None,
            zones: None,
            hosts: None,
        };

        let refused = [
            "192.168.0.300",   // an octet out of range
            "999.999.999.999", // every octet out of range
            "10.0.0",          // too few octets
        ];
        assert_eq!(
            collect_names(&refused, &ctx),
            Vec::<String>::new(),
            "a mistyped address was collected as a name to look up"
        );

        // The builder's own verdict on the same tokens, which is what makes the
        // two agree rather than merely both refuse.
        for token in refused {
            assert_eq!(target::host_name(token), target::HostName::Mistyped);
        }

        // A real name is still collected, or the check above proves nothing.
        assert_eq!(
            collect_names(&["nas.local", "example.com"], &ctx),
            vec!["nas.local".to_string(), "example.com".to_string()]
        );
    }

    /// One host is one lookup, however many ways it is spelled.
    ///
    /// DNS is case-insensitive, so `NAS` and `nas` name one host. They used to
    /// be two entries and two round trips.
    #[test]
    fn a_name_written_two_ways_is_looked_up_once() {
        let ctx = TargetContext {
            keywords: None,
            zones: None,
            hosts: None,
        };

        // Collection keeps every spelling, since the build pass looks a name up
        // by the token the expression carried.
        let collected = collect_names(&["NAS", "nas", "Nas"], &ctx);
        assert_eq!(collected.len(), 3);

        // What must not be three is the number of names resolution asks for.
        let folded: std::collections::HashSet<String> = collected
            .iter()
            .map(|name| name.to_ascii_lowercase())
            .collect();
        assert_eq!(folded.len(), 1, "three spellings of one host");
    }

    /// A keyword resolver that expands `lan` to one address, so a list mixing a
    /// keyword, literals and names can be classified the way the builder would.
    fn keywords(keyword: Keyword, set: &mut IpSet) -> Result<(), IpParseError> {
        match keyword {
            Keyword::Lan => {
                set.insert("192.168.1.1".parse().expect("a valid address"));
                Ok(())
            }
        }
    }

    /// The distinction the addresses cannot carry. Both of these resolve to the
    /// same single address and only one is a request to sweep a segment, so a
    /// caller reading only the `IpSet` has already lost it.
    #[tokio::test]
    async fn only_the_keyword_asks_for_a_segment_sweep() {
        let keyword = for_discovery_with(&["lan"], None, Some(&keywords), None)
            .await
            .expect("the keyword resolver answers");
        assert!(keyword.segment_sweep());
        assert_eq!(keyword.ips().len(), 1);

        let spelled_out = for_discovery_with(&["192.168.1.1"], None, Some(&keywords), None)
            .await
            .expect("a literal address");
        assert!(!spelled_out.segment_sweep());
        assert_eq!(spelled_out.ips().len(), 1);
    }

    /// Found wherever it appears, including inside a comma-separated list, since
    /// that is where a person writes it when mixing it with something else.
    #[tokio::test]
    async fn the_keyword_is_found_alongside_other_targets() {
        let mixed = for_discovery_with(&["lan,10.1.0.0/30"], None, Some(&keywords), None)
            .await
            .expect("the keyword resolver answers");
        assert!(mixed.segment_sweep());
    }

    /// The step this type exists to stop anyone skipping.
    #[tokio::test]
    async fn applying_targets_to_a_config_sets_the_sweep() {
        let targets = for_discovery_with(&["lan"], None, Some(&keywords), None)
            .await
            .expect("the keyword resolver answers");

        let mut cfg = ZondConfig::default();
        assert!(!cfg.segment_sweep, "off until something asks for it");
        targets.apply_to(&mut cfg);
        assert!(cfg.segment_sweep);
    }

    /// A scan told to emit no DNS may not look a target name up either: the
    /// query would go to a resolver somebody else operates and announce the
    /// scan. Refused against the expression that caused it, rather than dropped.
    #[tokio::test]
    async fn a_name_is_refused_when_no_resolver_is_offered() {
        let refused = for_discovery_with(&["one.one.one.one"], None, Some(&keywords), None).await;

        let Err(TargetParseError::NoHostLookup(expression)) = refused else {
            panic!("a name with nothing to resolve it is not a target");
        };
        assert_eq!(expression, "one.one.one.one");
    }

    /// Literal addresses need no resolver at all, so refusing names does not
    /// cost a caller the rest of their target list.
    #[tokio::test]
    async fn addresses_still_resolve_with_no_name_resolver() {
        let targets = for_discovery_with(&["10.0.0.0/30", "2001:db8::1"], None, None, None)
            .await
            .expect("literals need nothing looked up");
        assert_eq!(targets.ips().len(), 5);
    }

    /// The whole point of the classification: names are picked out and nothing
    /// else is. A literal, a range, a CIDR block and a resolvable keyword are all
    /// addresses the grammar handles, and only the two hostnames are left for
    /// resolution, carrying their ports stripped since a name is the address half
    /// alone.
    #[test]
    fn only_the_hostnames_in_a_mixed_list_are_collected() {
        let ctx = TargetContext::new().with_keywords(&keywords);

        let exprs = [
            "192.168.1.10",
            "example.com:443",
            "10.0.0.0/24",
            "raspberrypi.local",
            "10.0.0.1-10",
            "lan",
        ];

        assert_eq!(
            collect_names(&exprs, &ctx),
            vec!["example.com".to_string(), "raspberrypi.local".to_string()]
        );
    }

    /// A name written twice, or on two ports, is one name to resolve. Order is
    /// first-seen so a run over the same input resolves in the same order.
    #[test]
    fn a_repeated_name_is_collected_once() {
        let ctx = TargetContext::new();

        let exprs = ["host.example:80", "host.example:443", "host.example"];

        assert_eq!(
            collect_names(&exprs, &ctx),
            vec!["host.example".to_string()]
        );
    }

    /// The comma-separated address half is split before classification, so a
    /// single token naming a literal and a name yields just the name.
    #[test]
    fn names_are_found_inside_a_comma_list() {
        let ctx = TargetContext::new();

        assert_eq!(
            collect_names(&["10.0.0.1,db.internal:5432"], &ctx),
            vec!["db.internal".to_string()]
        );
    }

    /// A keyword with no resolver is rejected by the grammar, but not as
    /// `Malformed`, so it is never mistaken for a hostname and sent to a
    /// resolver that would report "no such host" for it.
    #[test]
    fn a_keyword_without_a_resolver_is_not_taken_for_a_name() {
        let ctx = TargetContext::new();
        assert!(collect_names(&["lan"], &ctx).is_empty());
    }

    /// An empty list resolves to an empty map with no tasks spawned, so the
    /// common case of a list with no names at all costs nothing.
    #[tokio::test]
    async fn resolving_no_names_yields_an_empty_map() {
        let resolver = Resolver::from_system();
        assert!(resolve_all(Vec::new(), &resolver).await.is_empty());
    }

    /// A list of literals reaches `to_set` without a name to resolve, so it
    /// touches no network, which is what makes this seam testable offline. What
    /// it pins is the union: expressions land in separate port groups, and
    /// `to_set` has to fold every group's addresses back into one set across
    /// both families rather than returning only the last group's.
    #[tokio::test]
    async fn to_set_unions_every_group_across_both_families() {
        let resolver = Resolver::from_system();

        let set = to_set(
            &["10.0.0.1:80", "10.0.0.2:443", "2001:db8::1"],
            None,
            None,
            &resolver,
        )
        .await
        .expect("literals resolve without a lookup");

        assert_eq!(set.len(), 3);
        assert!(set.contains(&"10.0.0.1".parse().unwrap()));
        assert!(set.contains(&"10.0.0.2".parse().unwrap()));
        assert!(set.contains(&"2001:db8::1".parse().unwrap()));
    }
}