cellos-supervisor 0.5.1

CellOS execution-cell runner — boots cells in Firecracker microVMs or gVisor, enforces narrow typed authority, emits signed CloudEvents.
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
//! SEC-21 Phase 3 — async DNS resolution via `hickory-resolver` that surfaces
//! real upstream TTL.
//!
//! This module exists to close the v0.4.0 honest-residual claim:
//!
//! > Phase 1 TTL is `0` because `to_socket_addrs` doesn't surface upstream TTL.
//!
//! `to_socket_addrs` is a `getaddrinfo`-class call that hides the underlying
//! DNS records — the libc resolver returns IP addresses but discards the TTL
//! the upstream nameserver returned. With no real TTL the
//! [`super::ResolverRefresh`] tick can:
//!
//! - Honour `refreshPolicy.minTtlSeconds` only as a *floor* on its own poll
//!   cadence (the prior W2 / W7 behaviour).
//! - Compute a meaningful `staleSeconds` (always 0 when TTL=0, because the
//!   answer technically expired the moment it was issued).
//!
//! Both of those become honest the moment we have a real TTL. This module is
//! the smallest piece of "ask `hickory-resolver` for A + AAAA records and tell
//! me the minimum TTL it observed" — no caching, no recursion, no auto-retry
//! beyond what the library itself does.
//!
//! ## Scope (Phase 3)
//!
//! - **Real upstream TTL.** A query for `host` resolves both A and AAAA
//!   records, the answer carries the *minimum* TTL across the records the
//!   upstream returned (per RFC 1035 §3.2.1: the cache invalidates at the
//!   minimum of the included RRs).
//! - **UDP first, TCP fallback.** Default `hickory-resolver` behaviour for
//!   the configured nameserver: try UDP, escalate to TCP when the response
//!   indicates truncation. We do not enable DoH / DoT / DoQ here — the
//!   transport choice belongs to the operator's resolver declaration in
//!   `dnsAuthority.resolvers[]`, and the do53-class endpoint is what the
//!   refresh ticker probes for drift observation.
//! - **Bounded by `tokio::time::timeout`.** The caller passes a hard ceiling;
//!   on expiry we surface a `std::io::Error { kind: TimedOut, ... }` so the
//!   ticker can treat it as a transient resolver failure.
//! - **No DNSSEC on the P3a path.** The unvalidated `resolve_with_ttl`
//!   keeps the dnssec-ring feature compiled in (the supervisor's
//!   Cargo.toml flips it on for the P3h validating sibling) but does NOT
//!   set `validate=true`; the validator stays dormant.
//! - **No network in tests.** The unit suite spins up a synthetic upstream on
//!   a localhost UDP socket and constructs DNS responses by hand.
//!
//! ## SEC-21 Phase 3h.2 — hickory 0.26.1 migration
//!
//! Two structural API changes from the 0.24 line that this module rides
//! on top of:
//!
//! 1. **Constructor pattern.** `TokioAsyncResolver::tokio(cfg, opts)` is
//!    gone. The 0.26 entry point is
//!    `Resolver::builder_with_config(cfg, TokioRuntimeProvider::default())
//!    .with_options(opts).build()` — the builder makes options/anchors
//!    explicit and lets the library auto-flip `validate=true` when
//!    `ResolverOpts.trust_anchor` is set.
//! 2. **Error type.** `ResolveError` / `ResolveErrorKind` are gone;
//!    `lookup_ip` returns `Result<LookupIp, NetError>` where
//!    `NetError::Dns(DnsError::NoRecordsFound { response_code, .. })`
//!    replaces the old `NoRecordsFound` arm and `NetError::Timeout`
//!    replaces the `Timeout` arm. The mapper below is updated to the
//!    new taxonomy.
//!
//! Plus the per-feature renames:
//!
//! - `tokio-runtime` → `tokio` (now default-on; we list it explicitly).
//! - `system-config` unchanged.
//! - `dnssec-ring` unchanged.
//! - `NameServerConfig` is now `(ip, trust_negative_responses, Vec<ConnectionConfig>)`
//!   instead of a single `socket_addr + protocol` — we build the
//!   per-protocol `ConnectionConfig`s explicitly with the upstream's port
//!   (so non-default ports keep working).
//!
//! ## Why `ResolvedAnswer` and not just `(Vec<String>, u32)`
//!
//! The ticker emits the resolver's address into the audit event payload so
//! operators can reason about *which* upstream answered the query that
//! triggered drift. We carry that through here so the call site does not have
//! to re-derive it from the original `SocketAddr` configuration.

use std::io;
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;

use hickory_proto::dnssec::Proof;
use hickory_proto::op::ResponseCode;
use hickory_resolver::config::{
    ConnectionConfig, NameServerConfig, ProtocolConfig, ResolveHosts, ResolverConfig, ResolverOpts,
};
use hickory_resolver::net::runtime::TokioRuntimeProvider;
use hickory_resolver::net::{DnsError, NetError};
use hickory_resolver::Resolver;

use crate::resolver_refresh::dnssec::TrustAnchors;

/// Resolved answer with real TTL, replacing the W2 SEC-21 `to_socket_addrs`
/// shim that always reported TTL=0.
///
/// `targets` are sorted + deduped before return; the caller can hash the
/// canonical list directly. `ttl_seconds` is the minimum TTL across the
/// records returned (per RFC 1035 §3.2.1) — `0` when no records were
/// returned (NXDOMAIN, empty answer). `resolver_addr` is the upstream that
/// actually answered, which the audit ticker stamps into the
/// `dns_authority_drift` event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedAnswer {
    /// IP address strings (v4 or v6). Sorted lexicographically and deduped.
    pub targets: Vec<String>,
    /// Minimum TTL across the records returned (in seconds). `0` if upstream
    /// returned no records. The caller is responsible for clamping to
    /// `refreshPolicy.minTtlSeconds` (the rebinding-mitigation floor).
    pub ttl_seconds: u32,
    /// Resolver address that actually answered (for audit). When the caller
    /// passed `from_system_conf` and the system resolver answered, this is
    /// the address `hickory-resolver` selected from `/etc/resolv.conf` (or
    /// the platform equivalent).
    pub resolver_addr: SocketAddr,
}

/// Build a `NameServerConfig` for the given upstream `SocketAddr` with both
/// UDP and TCP `ConnectionConfig`s wired to the upstream's port.
///
/// 0.26's `NameServerConfig::udp_and_tcp(IpAddr)` is a convenience that
/// always uses port 53; we explicitly carry the operator-provided port
/// through so non-standard upstream ports (e.g. a bind running on
/// `127.0.0.1:5353` for testing) keep working.
fn build_nameserver_config(upstream: SocketAddr) -> NameServerConfig {
    let mut udp = ConnectionConfig::new(ProtocolConfig::Udp);
    udp.port = upstream.port();
    let mut tcp = ConnectionConfig::new(ProtocolConfig::Tcp);
    tcp.port = upstream.port();
    NameServerConfig::new(upstream.ip(), true, vec![udp, tcp])
}

/// Build the shared [`ResolverOpts`] used by both [`resolve_with_ttl`] and
/// [`resolve_with_ttl_validated`]. Optionally accepts a trust-anchor path —
/// when `Some`, the returned opts have `trust_anchor` populated, which
/// causes [`hickory_resolver::ResolverBuilder::build`] to auto-flip
/// `validate = true` (see hickory 0.26 `resolver.rs::ResolverBuilder::build`).
///
/// This factoring exists for testability: the trust-anchor injection
/// regression test ([`tests::trust_anchor_path_flips_validate_on`])
/// builds opts directly via this helper and asserts `trust_anchor.is_some()`
/// without needing to round-trip a real DNS query.
pub(crate) fn build_resolver_opts(
    timeout: Duration,
    trust_anchor: Option<PathBuf>,
) -> ResolverOpts {
    let mut opts = ResolverOpts::default();
    // Disable the in-process cache. The CellOS refresh ticker is itself the
    // cache (it stamps `last_refresh_at` and honours `refreshPolicy`); a
    // second cache here would silently mask the TTL we are trying to surface.
    opts.cache_size = 0;
    // Single attempt — the ticker re-runs every interval, no need for the
    // library to retry on its own and inflate the deadline.
    opts.attempts = 1;
    opts.timeout = timeout;
    opts.use_hosts_file = ResolveHosts::Never;
    // 0.26 default `edns0 = true` would attach an OPT record to every
    // query. CellOS does not need EDNS for the do53 supervisor refresh
    // path (no large responses, no EDNS-protocol DNSSEC OK bit needed —
    // the validator chains via separate DS / DNSKEY queries), and
    // turning it off keeps the wire-format symmetric with the
    // synthetic-upstream stub used in the unit tests (the stub does
    // not synthesize an OPT record back).
    opts.edns0 = false;
    // Both A + AAAA — we fetch each explicitly below to keep the TTL math
    // honest.
    opts.ip_strategy = hickory_resolver::config::LookupIpStrategy::Ipv4AndIpv6;
    if let Some(path) = trust_anchor {
        // SEC-21 Phase 3h.2 — Q1 closure. Setting `trust_anchor` causes
        // `ResolverBuilder::build` to auto-flip `validate = true`
        // (hickory 0.26.1 `resolver.rs::ResolverBuilder::build`,
        // `if trust_anchor.is_some() || options.trust_anchor.is_some()
        // { options.validate = true; }`). The supervisor's
        // `resolver_refresh::dnssec::TrustAnchors` loader pre-validates
        // the path with `O_NOFOLLOW` + 32 KiB ceiling before handing it
        // here; hickory will re-open the file via
        // `hickory_proto::dnssec::TrustAnchors::from_file`. The
        // re-open is acceptable: we already proved the path is not a
        // symlink and is bounded.
        opts.trust_anchor = Some(path);
    }
    opts
}

/// Resolve `hostname` against `upstream` (UDP-first, TCP fallback) within
/// `timeout`. Merges A + AAAA records and returns the minimum TTL across
/// them.
///
/// ## Errors
///
/// - [`io::ErrorKind::TimedOut`] — the resolver did not respond within
///   `timeout`. The ticker treats this as a transient failure: no drift
///   event, prior state preserved.
/// - [`io::ErrorKind::Other`] — any other resolver error (servfail, refused,
///   network unreachable). Mapped to `io::Error::other` so the ticker's
///   existing `Err → continue` path handles it.
///
/// ## NXDOMAIN handling
///
/// `hickory-resolver` 0.26 surfaces NXDOMAIN as
/// `NetError::Dns(DnsError::NoRecordsFound { response_code: NXDomain, .. })`.
/// We special-case it (and `NoError`-with-empty-answer) to
/// `Ok(empty, ttl=0)` so the ticker can observe an empty target set and
/// emit a drift event when the hostname's last-known answer was non-empty
/// (i.e. the domain disappeared) — matching the W2 design where Ok([]) is
/// a real signal, not an error.
pub async fn resolve_with_ttl(
    hostname: &str,
    upstream: SocketAddr,
    timeout: Duration,
) -> io::Result<ResolvedAnswer> {
    let mut config = ResolverConfig::from_parts(None, Vec::new(), Vec::new());
    config.add_name_server(build_nameserver_config(upstream));

    let opts = build_resolver_opts(timeout, None);

    let resolver = Resolver::builder_with_config(config, TokioRuntimeProvider::default())
        .with_options(opts)
        .build()
        .map_err(|e| io::Error::other(format!("hickory-resolver build: {e}")))?;

    let work = async {
        // `lookup_ip` performs both the A and AAAA queries when the strategy
        // is Ipv4AndIpv6 and merges the results — including the underlying
        // record TTLs, which we walk explicitly below.
        let lookup_result = resolver.lookup_ip(hostname).await;
        let lookup = match lookup_result {
            Ok(l) => l,
            Err(e) => {
                // NXDOMAIN / NOERROR-empty: surface as Ok(empty, ttl=0) so the
                // ticker can treat the empty target set as a real signal
                // (the hostname disappeared) rather than a transient error.
                //
                // Other error response codes (SERVFAIL / REFUSED / etc.):
                // surface as io::Error so the ticker preserves prior state and
                // emits no drift event.
                if let Some(rc) = no_records_response_code(&e) {
                    if matches!(rc, ResponseCode::NXDomain | ResponseCode::NoError) {
                        return Ok(ResolvedAnswer {
                            targets: Vec::new(),
                            ttl_seconds: 0,
                            resolver_addr: upstream,
                        });
                    }
                }
                return Err(map_net_error(e));
            }
        };

        // Iterate the underlying records (`as_lookup().answers()` exposes the
        // per-record TTL the upstream returned). Empty answer → ttl=0.
        let (targets, min_ttl) = collect_targets_and_min_ttl(lookup.as_lookup().answers());

        Ok(ResolvedAnswer {
            targets,
            ttl_seconds: min_ttl.unwrap_or(0),
            resolver_addr: upstream,
        })
    };

    match tokio::time::timeout(timeout, work).await {
        Ok(inner) => inner,
        Err(_) => Err(io::Error::new(
            io::ErrorKind::TimedOut,
            format!("hickory-resolver timed out after {timeout:?} for {hostname}"),
        )),
    }
}

/// Walk the answer Records, collecting A/AAAA targets (sorted, deduped) and
/// the minimum TTL across all records (CNAME chase records contribute to
/// the TTL minimum but not to the target set, mirroring the P3a behaviour).
fn collect_targets_and_min_ttl(
    records: &[hickory_resolver::proto::rr::Record],
) -> (Vec<String>, Option<u32>) {
    let mut min_ttl: Option<u32> = None;
    let mut targets: Vec<String> = Vec::new();
    for record in records {
        let ttl = record.ttl;
        min_ttl = Some(match min_ttl {
            Some(prev) => prev.min(ttl),
            None => ttl,
        });
        if let Some(ip) = record_to_ip(record) {
            targets.push(ip.to_string());
        }
    }
    targets.sort();
    targets.dedup();
    (targets, min_ttl)
}

/// Project a hickory-resolver record into an `IpAddr`. Returns `None` for
/// non-A/AAAA records (CNAME chase steps, etc.) — those still contribute
/// to the TTL minimum but not to the target set.
fn record_to_ip(record: &hickory_resolver::proto::rr::Record) -> Option<IpAddr> {
    use hickory_resolver::proto::rr::RData;
    match &record.data {
        RData::A(a) => Some(IpAddr::V4(a.0)),
        RData::AAAA(aaaa) => Some(IpAddr::V6(aaaa.0)),
        _ => None,
    }
}

/// If `e` represents a `NoRecordsFound` outcome, return the embedded
/// `ResponseCode` so the caller can discriminate NXDOMAIN / NoError vs
/// SERVFAIL / etc. Returns `None` for all other error kinds.
fn no_records_response_code(e: &NetError) -> Option<ResponseCode> {
    match e {
        NetError::Dns(DnsError::NoRecordsFound(no_records)) => Some(no_records.response_code),
        _ => None,
    }
}

/// Map a `hickory_resolver::net::NetError` (the 0.26 unified error) to an
/// `io::Error` with the closest matching kind. Most resolver errors collapse
/// to `io::ErrorKind::Other` because hickory's error taxonomy is
/// finer-grained than `io::ErrorKind`'s closed enum; the ticker treats any
/// non-timeout error the same way (no drift event, prior state preserved).
fn map_net_error(e: NetError) -> io::Error {
    let kind = match &e {
        NetError::Timeout => io::ErrorKind::TimedOut,
        NetError::Io(io_err) => io_err.kind(),
        _ => io::ErrorKind::Other,
    };
    io::Error::new(kind, format!("hickory-resolver error: {e}"))
}

// ============================================================================
// SEC-21 Phase 3h — opt-in DNSSEC validation (post Phase 3h.2)
// ============================================================================
//
// `resolve_with_ttl_validated` is the Phase 3h sibling of `resolve_with_ttl`
// above. It builds the same `ResolverConfig` + `ResolverOpts` but with the
// operator-supplied `trust_anchor` path threaded into `ResolverOpts`, which
// causes hickory 0.26.1's `ResolverBuilder::build` to auto-flip
// `validate=true` and engage the validator.
//
// **Phase 3h.2 closures** (was: P3h.1 limitations):
//
// - **Q1 (custom trust-anchor injection): CLOSED.** The `TrustAnchors` loader
//   in `super::dnssec` now exposes the validated `PathBuf` via
//   `TrustAnchors::path()`; we forward it into `ResolverOpts.trust_anchor`.
//   When the loader returned the IANA-default sentinel, we leave
//   `trust_anchor = None` and hickory falls back to its bundled
//   `hickory_proto::dnssec::TrustAnchors::default()` (the IANA root KSKs).
//
// - **Q3 (typed validator outcome): CLOSED.** The four substring branches
//   (`"rrsigs are not present"` / `"no signature"` / `"bogus"` / `"verify"`)
//   are replaced by the `Proof::{Secure, Insecure, Bogus, Indeterminate}`
//   enum from `hickory_proto::dnssec`. The mapping is implemented by
//   [`proof_to_validation_result`]; the wrapper applies it to each answer
//   record's `proof` field (0.26 promotes `proof: Proof` to a public field
//   on `Record` when the `__dnssec` feature is on). When `Lookup.answers()`
//   is empty (NSEC denial), the validator's verdict comes through the error
//   path as `DnsError::Nsec { proof, .. }` — handled in the error branch.
//
// **Phase 3h.2 residual closure (T1.A / P0-1)**:
//
// - **Q2 (RRSIG algorithm + key_tag): CLOSED.** Hickory 0.26.1 with
//   `validate=true` flips `edns_set_dnssec_ok=true` on the outbound
//   request (`hickory_resolver::resolver.rs:360`) which causes
//   `Message::maybe_strip_dnssec_records` to NOT strip DNSSEC records
//   from the inbound response (`hickory_proto::op::message.rs:194`).
//   For simple A/AAAA queries (no CNAME chase) the caching client takes
//   the `needs_filtering=false` branch and returns the message
//   unchanged, so RRSIG records are present in `Lookup.answers()`
//   alongside the A/AAAA records. The [`extract_rrsig_metadata`]
//   helper walks them and pulls `RRSIG.input.algorithm` +
//   `RRSIG.input.key_tag` (both `pub` on
//   `hickory_proto::dnssec::rdata::SigInput`) for the matching
//   `type_covered`. The mapping no longer fabricates `"unknown"` / `0`
//   when real metadata is available — but it still falls back to the
//   placeholders when the resolver did not surface RRSIG records (a
//   defensive path that does not trigger for healthy A/AAAA paths
//   under `validate=true`, but is reachable on CNAME chases where
//   `caching_client.rs:429` filters the answer section by
//   `query_type == record_type`, or on the NSEC denial-of-existence
//   path with an empty answer set). The placeholder fallback is the
//   load-bearing fail-safe — we never invent algorithm names.

/// Outcome of one DNSSEC-validating resolution.
///
/// **Wire-stable** — the variant set (`Validated` / `Failed` / `Unsigned`)
/// is the contract that `dns_proxy::dnssec` (P3h.1, lands later) and
/// `resolver_refresh::ticker` consume. Internal fields may grow
/// additively (e.g. a future `algorithm: AlgorithmRfc8624` field) but the
/// variant names are frozen.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DnssecValidationResult {
    /// Validation succeeded and a chain of trust was established to the
    /// configured anchor. `algorithm` and `key_tag` are stamped into the
    /// audit log; `algorithm` is the human-readable name (e.g.
    /// `"RSASHA256"`).
    ///
    /// **T1.A / P0-1 — real RRSIG metadata (was: Q2 placeholder).**
    /// When validation succeeds and the inbound response carried RRSIG
    /// records covering the queried type (the healthy A/AAAA case under
    /// `validate=true`), `algorithm` and `key_tag` reflect the real
    /// signing parameters from the first RRSIG record covering the
    /// query type (see [`extract_rrsig_metadata`]). When the resolver
    /// did NOT surface RRSIG records (e.g. on a CNAME chase where the
    /// caching client filtered the ANSWER section by query type, or on
    /// the NSEC-denial-of-existence path where there are no answer
    /// records at all), the placeholder values (`algorithm: "unknown"`,
    /// `key_tag: 0`) are stamped as the documented fail-safe. The
    /// fallback is always honest — we never fabricate an algorithm
    /// name.
    Validated {
        /// DNSSEC algorithm name (RFC 8624 / IANA registry). Real
        /// algorithm string (e.g. `"RSASHA256"`, `"ED25519"`) when
        /// hickory surfaced an RRSIG covering the query type;
        /// `"unknown"` as the documented fallback when no RRSIG was
        /// available (CNAME chase, NSEC denial of existence).
        algorithm: String,
        /// DNSSEC key tag (RFC 4034 §5.1.1). Real key tag when an
        /// RRSIG covering the query type was present; `0` as the
        /// documented fallback otherwise.
        key_tag: u16,
    },
    /// Validation was attempted but failed; payload reason for the event.
    Failed {
        /// Stable reason code for SIEM grep. Phase 3h.2 emits two distinct
        /// codes:
        ///
        /// - `"validation_failed"` — `Proof::Bogus` outcome: the
        ///   validator believed the chain *should* exist but the
        ///   signatures don't verify (or required records are
        ///   missing). This is the "active attack OR
        ///   misconfiguration" indicator.
        /// - `"validation_indeterminate"` — `Proof::Indeterminate`
        ///   outcome: the validator could not reach any verdict (e.g.
        ///   couldn't fetch DS / DNSKEY records). Distinct from
        ///   `Bogus` because the validator itself is uncertain — an
        ///   operator may want to retry rather than treat it as
        ///   adversarial.
        ///
        /// These distinct codes let SIEM operators grep for one or the
        /// other without parsing free-form strings.
        reason: String,
    },
    /// Resolver returned answers but the zone is not signed
    /// (`Proof::Insecure`). Operator policy decides whether this is a
    /// deny (`failClosed=true`) or an allow (audit-only).
    Unsigned,
}

/// Resolved answer + DNSSEC validation outcome.
///
/// `answer` is the same `ResolvedAnswer` shape as the P3a path so the
/// downstream rebinding evaluator + drift digest pipeline does not have
/// to learn a new type. `validation` is the new Phase 3h discriminator.
///
/// When `validation` is `Failed` or `Unsigned`, the caller decides
/// whether to drop `answer.targets` based on the resolver's
/// `dnssec.failClosed` policy — this function does NOT enforce policy
/// itself, it only reports.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidatedResolvedAnswer {
    /// P3a-shape answer (targets + ttl + resolver_addr).
    pub answer: ResolvedAnswer,
    /// scope: DNSSEC validation outcome.
    pub validation: DnssecValidationResult,
}

/// SEC-21 Phase 3h.2 — map a hickory `Proof` to a stable
/// [`DnssecValidationResult`] using placeholder RRSIG metadata
/// (`algorithm: "unknown"`, `key_tag: 0`).
///
/// This is the canonical mapping table. Two policies encoded here:
///
/// - `Bogus` and `Indeterminate` BOTH map to `Failed` (they're both
///   "validator did not say Secure"), but they get distinct reason codes
///   (`"validation_failed"` vs `"validation_indeterminate"`) so a SIEM
///   operator can grep for one or the other. They ARE semantically
///   distinct: `Bogus` means the validator believed there *should* be a
///   chain and rejected it (cryptographic failure); `Indeterminate`
///   means the validator couldn't reach a verdict at all (e.g. fetch
///   failure on the DS / DNSKEY records). The SIEM treatment may
///   differ — a `Bogus` outcome is more likely to indicate an active
///   attack while `Indeterminate` is more likely to indicate
///   intermittent infrastructure failure.
///
/// - `Secure` returns the placeholder `algorithm: "unknown"` /
///   `key_tag: 0` values. **This is the fallback path** for callers
///   that have a `Proof` but no RRSIG metadata to extract (NSEC denial
///   of existence, malformed answer set). Production success paths
///   should call [`proof_to_validation_result_with_rrsig`] which
///   surfaces the real signing parameters when available.
pub(crate) fn proof_to_validation_result(proof: Proof) -> DnssecValidationResult {
    proof_to_validation_result_with_rrsig(proof, None)
}

/// Map a hickory `Proof` to a [`DnssecValidationResult`]
/// with optional real RRSIG metadata.
///
/// When `proof` is `Proof::Secure` and `rrsig_metadata` is `Some((alg,
/// key_tag))`, the returned `Validated` variant carries the real signing
/// parameters extracted from an RRSIG record covering the queried type
/// (see [`extract_rrsig_metadata`]). When metadata is `None` the
/// placeholders (`"unknown"` / `0`) are stamped — this is honest
/// degradation, not invented data.
///
/// For non-`Secure` proofs the metadata argument is ignored: `Insecure`
/// maps to `Unsigned`, `Bogus` to `Failed{validation_failed}`, and
/// `Indeterminate` to `Failed{validation_indeterminate}` regardless.
pub fn proof_to_validation_result_with_rrsig(
    proof: Proof,
    rrsig_metadata: Option<(String, u16)>,
) -> DnssecValidationResult {
    match proof {
        Proof::Secure => {
            let (algorithm, key_tag) =
                rrsig_metadata.unwrap_or_else(|| ("unknown".to_string(), 0u16));
            DnssecValidationResult::Validated { algorithm, key_tag }
        }
        Proof::Insecure => DnssecValidationResult::Unsigned,
        Proof::Bogus => DnssecValidationResult::Failed {
            reason: "validation_failed".to_string(),
        },
        Proof::Indeterminate => DnssecValidationResult::Failed {
            reason: "validation_indeterminate".to_string(),
        },
    }
}

/// Extract `(algorithm, key_tag)` from the first RRSIG
/// record in `records` whose `type_covered` is in `acceptable_types`.
///
/// Walks `records` looking for `RData::DNSSEC(DNSSECRData::RRSIG(rrsig))`
/// where `rrsig.input.type_covered` matches one of the requested types.
/// Returns the first match's algorithm name (via `Algorithm::as_str`,
/// e.g. `"RSASHA256"`, `"ED25519"`) and `key_tag`.
///
/// `resolve_with_ttl_validated` uses the `Ipv4AndIpv6` lookup strategy
/// which merges A and AAAA queries; the merged answer set carries RRSIGs
/// covering either type. Callers pass `&[RecordType::A,
/// RecordType::AAAA]` so either signature qualifies — we report the
/// first one we see, which mirrors the "first record wins" pattern
/// already used by `collect_targets_and_min_ttl`.
///
/// Returns `None` when:
/// - The records slice contains no RRSIG records (e.g. CNAME chase
///   path where `caching_client.rs:429` filtered the answer section by
///   query type, or a NSEC denial path with an empty answer set).
/// - The records contain RRSIG entries but none cover any of the
///   `acceptable_types` (defensive — RRSIGs covering a different type
///   can leak in if a future hickory change reorganizes section
///   handling).
///
/// The caller (`proof_to_validation_result_with_rrsig`) treats `None`
/// as "no metadata; stamp the documented placeholder". We never invent
/// algorithm strings.
pub fn extract_rrsig_metadata(
    records: &[hickory_resolver::proto::rr::Record],
    acceptable_types: &[hickory_resolver::proto::rr::RecordType],
) -> Option<(String, u16)> {
    use hickory_resolver::proto::rr::RData;
    for record in records {
        if let RData::DNSSEC(hickory_proto::dnssec::rdata::DNSSECRData::RRSIG(rrsig)) = &record.data
        {
            let input = rrsig.input();
            if acceptable_types.contains(&input.type_covered) {
                return Some((input.algorithm.as_str().to_string(), input.key_tag));
            }
        }
    }
    None
}

/// Combine the per-record `Proof` flags on the answer set into a single
/// outcome. Conservative ordering: a single `Bogus` poisons the whole
/// answer (cryptographic failure on any RR makes the set untrustworthy);
/// then `Indeterminate` (any record where the validator couldn't reach a
/// verdict pessimizes the set); then `Insecure` (any unsigned RR makes
/// the set unsigned overall); only when *every* record is `Secure` does
/// the set come back `Secure`. An empty record set returns
/// `Indeterminate` — a successful query with zero answers (NOERROR-empty)
/// shouldn't reach this path (we early-return above) but the defensive
/// fallback matches what the validator would conclude.
fn worst_proof(records: &[hickory_resolver::proto::rr::Record]) -> Proof {
    let mut have_any = false;
    let mut all_secure = true;
    let mut any_insecure = false;
    let mut any_indeterminate = false;
    for record in records {
        have_any = true;
        match record.proof {
            Proof::Bogus => return Proof::Bogus,
            Proof::Indeterminate => {
                any_indeterminate = true;
                all_secure = false;
            }
            Proof::Insecure => {
                any_insecure = true;
                all_secure = false;
            }
            Proof::Secure => {}
        }
    }
    if !have_any {
        return Proof::Indeterminate;
    }
    if all_secure {
        Proof::Secure
    } else if any_indeterminate {
        Proof::Indeterminate
    } else if any_insecure {
        Proof::Insecure
    } else {
        // Defensive fallback — not reachable given the branches above.
        Proof::Indeterminate
    }
}

/// SEC-21 Phase 3h.2 — DNSSEC-validating resolution.
///
/// Builds the same `ResolverConfig` as P3a's [`resolve_with_ttl`] (UDP
/// first, TCP fallback) and engages hickory 0.26.1's bundled DNSSEC
/// validator. When `trust_anchors.path()` is `Some`, the operator's
/// anchor file is parsed via `hickory_proto::dnssec::TrustAnchors::from_file`
/// and wired in via [`hickory_resolver::ResolverBuilder::with_trust_anchor`];
/// when it's `None` (the IANA-default sentinel) we set
/// `ResolverOpts.trust_anchor = None` and let hickory's
/// `Default for TrustAnchors` provide the IANA root KSKs.
///
/// ## Discrepancy from the research brief
///
/// The brief asserted that setting `ResolverOpts.trust_anchor:
/// Option<PathBuf>` causes hickory to load the file via
/// `from_file`. **In hickory 0.26.1 this is only partially true.**
///
/// The `ResolverOpts.trust_anchor` field IS public, IS forwarded into
/// the recursive resolver path (`ValidatingRecursor::new` reads
/// `config.trust_anchor`), AND its presence auto-flips
/// `options.validate = true` inside `ResolverBuilder::build`
/// (line `if trust_anchor.is_some() || options.trust_anchor.is_some()
/// { options.validate = true; }`).
///
/// **However**, the regular stub-resolver path (which is what cellos
/// uses for the supervisor refresh ticker) does NOT consume the
/// `PathBuf`. It uses `trust_anchor.unwrap_or_else(||
/// Arc::new(TrustAnchors::default()))` — which means the builder's
/// `Arc<TrustAnchors>` (set via `with_trust_anchor`) wins, and
/// `options.trust_anchor`'s only effect is the auto-flip of
/// `validate`. To get truly custom anchors on the stub-resolver path,
/// we must call `with_trust_anchor(Arc::new(loaded_anchors))`
/// ourselves.
///
/// The supervisor's loader pre-validates the path with `O_NOFOLLOW`
/// and 32 KiB ceiling, then we hand the path to
/// `hickory_proto::dnssec::TrustAnchors::from_file`. Hickory's loader
/// re-opens the file, which is acceptable: the pre-validation
/// guaranteed the path is not a symlink and is bounded.
///
/// ## Outcomes
///
/// - `Ok(ValidatedResolvedAnswer { validation: Validated, .. })` —
///   chain established. `answer.targets` is the validated set; the
///   caller may pass it to the rebinding evaluator unchanged.
/// - `Ok(ValidatedResolvedAnswer { validation: Failed, .. })` — chain
///   rejected. `answer.targets` carries the unvalidated set; the caller
///   decides whether to drop it (`failClosed=true`) or keep it
///   (audit-only).
/// - `Ok(ValidatedResolvedAnswer { validation: Unsigned, .. })` — zone
///   has no DNSSEC chain. Same allow/deny choice as `Failed`.
/// - `Err(io::Error)` — transport failure / timeout / SERVFAIL or
///   trust-anchor load failure — same semantics as the P3a path: the
///   ticker preserves prior state and emits no drift.
pub async fn resolve_with_ttl_validated(
    hostname: &str,
    upstream: SocketAddr,
    timeout: Duration,
    trust_anchors: &TrustAnchors,
) -> io::Result<ValidatedResolvedAnswer> {
    let mut config = ResolverConfig::from_parts(None, Vec::new(), Vec::new());
    config.add_name_server(build_nameserver_config(upstream));

    // Forward the operator's path into ResolverOpts.trust_anchor. This
    // does TWO things:
    //   1. It auto-flips opts.validate = true inside
    //      ResolverBuilder::build (see hickory 0.26.1 resolver.rs:518-520).
    //   2. It propagates into the recursive-resolver path if a future
    //      cellos slice opts in to recursion (we don't today).
    // The stub-resolver path also needs the loaded anchors via
    // with_trust_anchor() below — see the discrepancy note above.
    let mut opts = build_resolver_opts(timeout, trust_anchors.path().map(PathBuf::from));
    // Engage the validator unconditionally on this path. When
    // `trust_anchors.path()` was Some, hickory would have auto-flipped
    // this for us; we set it explicitly so the IANA-default sentinel
    // path also engages the validator.
    opts.validate = true;

    let mut builder =
        Resolver::builder_with_config(config, TokioRuntimeProvider::default()).with_options(opts);

    // SEC-21 Phase 3h.2 — Q1 closure for the stub-resolver path.
    // When the operator supplied a custom anchor file, parse it via
    // `hickory_proto::dnssec::TrustAnchors::from_file` and inject the
    // loaded anchors. Without this call, hickory would silently fall
    // back to the bundled IANA defaults even when the operator
    // explicitly wired a custom anchor path through the spec.
    if let Some(path) = trust_anchors.path() {
        match hickory_proto::dnssec::TrustAnchors::from_file(path) {
            Ok(anchors) => {
                builder = builder.with_trust_anchor(std::sync::Arc::new(anchors));
            }
            Err(e) => {
                return Err(io::Error::other(format!(
                    "trust anchor parse failed for {}: {e}",
                    path.display()
                )));
            }
        }
    }

    let resolver = builder
        .build()
        .map_err(|e| io::Error::other(format!("hickory-resolver build (validating): {e}")))?;

    let work = async {
        let lookup_result = resolver.lookup_ip(hostname).await;
        let lookup = match lookup_result {
            Ok(l) => l,
            Err(e) => {
                // Decision tree:
                //   - NXDOMAIN / NOERROR-empty → Ok(empty, ttl=0,
                //     validation=Validated) when the response carried a
                //     proof of nonexistence; otherwise we cannot tell the
                //     validator's verdict so we emit Indeterminate.
                //     Today's hickory 0.26.1 surfaces NSEC denials via
                //     `DnsError::Nsec { proof, .. }` — when present, we
                //     map it through `proof_to_validation_result` so an
                //     authenticated denial of existence (Proof::Secure)
                //     comes through as Validated.
                //   - All other transport-class errors (SERVFAIL /
                //     REFUSED / network unreachable / timeout) bubble up
                //     as io::Error; the ticker preserves prior state and
                //     emits no drift event.
                if let Some(rc) = no_records_response_code(&e) {
                    if matches!(rc, ResponseCode::NXDomain | ResponseCode::NoError) {
                        let validation = nsec_proof(&e).map(proof_to_validation_result).unwrap_or(
                            DnssecValidationResult::Validated {
                                algorithm: "unknown".to_string(),
                                key_tag: 0,
                            },
                        );
                        return Ok(ValidatedResolvedAnswer {
                            answer: ResolvedAnswer {
                                targets: Vec::new(),
                                ttl_seconds: 0,
                                resolver_addr: upstream,
                            },
                            validation,
                        });
                    }
                }
                if let Some(proof) = nsec_proof(&e) {
                    // NSEC-with-proof but a non-NXDOMAIN response code —
                    // surface the proof verbatim so SIEM can disambiguate.
                    return Ok(ValidatedResolvedAnswer {
                        answer: ResolvedAnswer {
                            targets: Vec::new(),
                            ttl_seconds: 0,
                            resolver_addr: upstream,
                        },
                        validation: proof_to_validation_result(proof),
                    });
                }
                return Err(map_net_error(e));
            }
        };

        let answers = lookup.as_lookup().answers();
        let (targets, min_ttl) = collect_targets_and_min_ttl(answers);

        // The lookup succeeded with `validate=true` set on
        // ResolverOpts — by hickory 0.26's contract the per-record
        // `Proof` field reflects the validator's verdict for each
        // record. Combine via `worst_proof` then map to the stable
        // `DnssecValidationResult` taxonomy.
        let proof = worst_proof(answers);

        // Extract real RRSIG `algorithm` + `key_tag`
        // when the inbound response carried RRSIG records covering A
        // or AAAA. With `validate=true` set on opts above, hickory
        // flips `edns_set_dnssec_ok=true` on the outbound query, which
        // tells `Message::maybe_strip_dnssec_records` to preserve
        // RRSIGs in the response. They land alongside the A/AAAA
        // records in `Lookup.answers()` and we walk them here. When
        // no RRSIG matches (CNAME chase that filtered the section, or
        // a synthetic upstream that didn't sign its response), the
        // helper returns None and `proof_to_validation_result_with_rrsig`
        // stamps the documented placeholders.
        let rrsig_metadata = extract_rrsig_metadata(
            answers,
            &[
                hickory_resolver::proto::rr::RecordType::A,
                hickory_resolver::proto::rr::RecordType::AAAA,
            ],
        );

        Ok(ValidatedResolvedAnswer {
            answer: ResolvedAnswer {
                targets,
                ttl_seconds: min_ttl.unwrap_or(0),
                resolver_addr: upstream,
            },
            validation: proof_to_validation_result_with_rrsig(proof, rrsig_metadata),
        })
    };

    match tokio::time::timeout(timeout, work).await {
        Ok(inner) => inner,
        Err(_) => Err(io::Error::new(
            io::ErrorKind::TimedOut,
            format!("hickory-resolver timed out after {timeout:?} for {hostname} (DNSSEC path)"),
        )),
    }
}

/// Extract the `Proof` from a `DnsError::Nsec` outcome, if present.
/// `NetError` carries this when the validator chose to encode an
/// authenticated denial of existence as a typed error rather than an
/// empty answer set.
fn nsec_proof(e: &NetError) -> Option<Proof> {
    match e {
        NetError::Dns(DnsError::Nsec { proof, .. }) => Some(*proof),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv4Addr;
    use std::sync::Arc;
    use tokio::net::UdpSocket;
    use tokio::sync::oneshot;

    /// Synthetic-upstream control. The test composes one [`StubResponse`] per
    /// expected query; the stub thread parses each incoming question and
    /// constructs a response from the recipe.
    #[derive(Clone)]
    struct StubResponse {
        /// RCODE to set in the response header (0=NOERROR, 2=SERVFAIL,
        /// 3=NXDOMAIN). A response is sent for every RCODE except via the
        /// `swallow` toggle below.
        rcode: u8,
        /// `(ipv4, ttl_seconds)` answers to embed for `A` queries.
        a_records: Vec<(Ipv4Addr, u32)>,
        /// If true, swallow the query and never reply — drives the timeout
        /// path.
        swallow: bool,
    }

    impl StubResponse {
        fn ok_a(records: Vec<(Ipv4Addr, u32)>) -> Self {
            Self {
                rcode: 0,
                a_records: records,
                swallow: false,
            }
        }
        fn empty_noerror() -> Self {
            Self {
                rcode: 0,
                a_records: Vec::new(),
                swallow: false,
            }
        }
        fn nxdomain() -> Self {
            Self {
                rcode: 3,
                a_records: Vec::new(),
                swallow: false,
            }
        }
        fn servfail() -> Self {
            Self {
                rcode: 2,
                a_records: Vec::new(),
                swallow: false,
            }
        }
        fn timeout() -> Self {
            Self {
                rcode: 0,
                a_records: Vec::new(),
                swallow: true,
            }
        }
    }

    /// Encode a wire-format DNS response from `query` (which we echo, plus
    /// QR=1, RCODE, ANCOUNT, and inline A records). We do not implement
    /// pointer compression in answers — RFC 1035 allows literal name copies,
    /// and `hickory-resolver` parses both forms.
    fn build_response(query: &[u8], spec: &StubResponse) -> Vec<u8> {
        let mut resp = query.to_vec();
        // QR=1, RA=1, plus the requested RCODE in low nibble of byte 3.
        resp[2] = 0x81;
        resp[3] = 0x80 | (spec.rcode & 0x0f);
        let ancount = if spec.rcode == 0 {
            spec.a_records.len() as u16
        } else {
            0
        };
        resp[6] = (ancount >> 8) as u8;
        resp[7] = (ancount & 0xff) as u8;
        if spec.rcode == 0 {
            let mut qend = 12;
            while qend < query.len() && query[qend] != 0 {
                let len = query[qend] as usize;
                qend += 1 + len;
            }
            qend += 1;
            let qname = &query[12..qend];
            for (ip, ttl) in &spec.a_records {
                resp.extend_from_slice(qname);
                resp.extend_from_slice(&[0x00, 0x01]); // TYPE A
                resp.extend_from_slice(&[0x00, 0x01]); // CLASS IN
                resp.extend_from_slice(&ttl.to_be_bytes()); // TTL u32
                resp.extend_from_slice(&[0x00, 0x04]); // RDLENGTH
                resp.extend_from_slice(&ip.octets());
            }
        }
        resp
    }

    /// Spawn a synthetic UDP upstream that consumes `responses` in order,
    /// answering each incoming query with the next recipe. AAAA queries are
    /// answered with a NOERROR + empty AnSection so the resolver sees
    /// "v4-only" and the test stays focused on the v4 path.
    async fn spawn_stub(responses: Vec<StubResponse>) -> (SocketAddr, oneshot::Sender<()>) {
        let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let addr = sock.local_addr().unwrap();
        let (stop_tx, mut stop_rx) = oneshot::channel::<()>();
        let responses = Arc::new(responses);
        tokio::spawn(async move {
            let mut buf = vec![0u8; 1500];
            let mut idx_a: usize = 0;
            loop {
                tokio::select! {
                    _ = &mut stop_rx => break,
                    r = sock.recv_from(&mut buf) => {
                        let (n, peer) = match r { Ok(v) => v, Err(_) => break };
                        let query = buf[..n].to_vec();
                        let mut idx = 12;
                        while idx < query.len() && query[idx] != 0 {
                            let len = query[idx] as usize;
                            idx += 1 + len;
                        }
                        idx += 1;
                        if idx + 4 > query.len() { continue; }
                        let qtype = u16::from_be_bytes([query[idx], query[idx+1]]);
                        if qtype == 1 {
                            let spec = if idx_a < responses.len() {
                                let s = responses[idx_a].clone();
                                idx_a += 1;
                                s
                            } else {
                                responses.last().cloned()
                                    .unwrap_or_else(StubResponse::empty_noerror)
                            };
                            if !spec.swallow {
                                let resp = build_response(&query, &spec);
                                let _ = sock.send_to(&resp, peer).await;
                            }
                        } else {
                            let spec = StubResponse::empty_noerror();
                            let resp = build_response(&query, &spec);
                            let _ = sock.send_to(&resp, peer).await;
                        }
                    }
                }
            }
        });
        (addr, stop_tx)
    }

    // ============================================================
    // P3a (no-DNSSEC) tests — unchanged in behaviour, exercise the
    // 0.26 constructor pattern and the new error taxonomy.
    // ============================================================

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resolve_returns_ttl_from_a_records() {
        let (addr, stop) = spawn_stub(vec![StubResponse::ok_a(vec![(
            Ipv4Addr::new(203, 0, 113, 5),
            300,
        )])])
        .await;
        let answer = resolve_with_ttl("api.example.com.", addr, Duration::from_secs(2))
            .await
            .expect("resolve ok");
        assert_eq!(answer.targets, vec!["203.0.113.5".to_string()]);
        assert_eq!(answer.ttl_seconds, 300, "TTL must be the upstream record's");
        assert_eq!(answer.resolver_addr, addr);
        let _ = stop.send(());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resolve_returns_min_ttl_across_a_aaaa() {
        let (addr, stop) = spawn_stub(vec![StubResponse::ok_a(vec![
            (Ipv4Addr::new(203, 0, 113, 1), 600),
            (Ipv4Addr::new(203, 0, 113, 2), 120),
        ])])
        .await;
        let answer = resolve_with_ttl("multi.example.com.", addr, Duration::from_secs(2))
            .await
            .expect("resolve ok");
        assert_eq!(
            answer.ttl_seconds, 120,
            "min TTL across records must be reported"
        );
        assert!(answer.targets.contains(&"203.0.113.1".to_string()));
        assert!(answer.targets.contains(&"203.0.113.2".to_string()));
        let _ = stop.send(());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resolve_handles_empty_answer() {
        let (addr, stop) = spawn_stub(vec![StubResponse::empty_noerror()]).await;
        let answer = resolve_with_ttl("nothing.example.com.", addr, Duration::from_secs(2))
            .await
            .expect("empty NOERROR is Ok(empty)");
        assert!(answer.targets.is_empty());
        assert_eq!(answer.ttl_seconds, 0);
        let _ = stop.send(());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resolve_returns_timeout_error() {
        let (addr, stop) = spawn_stub(vec![StubResponse::timeout()]).await;
        let err = resolve_with_ttl("slow.example.com.", addr, Duration::from_millis(250))
            .await
            .expect_err("timeout must error");
        assert_eq!(
            err.kind(),
            io::ErrorKind::TimedOut,
            "swallowed query must surface as TimedOut, got {err:?}"
        );
        let _ = stop.send(());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resolve_dedupes_targets() {
        let (addr, stop) = spawn_stub(vec![StubResponse::ok_a(vec![
            (Ipv4Addr::new(198, 51, 100, 7), 60),
            (Ipv4Addr::new(198, 51, 100, 7), 60),
        ])])
        .await;
        let answer = resolve_with_ttl("dup.example.com.", addr, Duration::from_secs(2))
            .await
            .expect("resolve ok");
        assert_eq!(answer.targets, vec!["198.51.100.7".to_string()]);
        let _ = stop.send(());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resolve_sorts_targets() {
        let (addr, stop) = spawn_stub(vec![StubResponse::ok_a(vec![
            (Ipv4Addr::new(203, 0, 113, 9), 60),
            (Ipv4Addr::new(203, 0, 113, 1), 60),
            (Ipv4Addr::new(203, 0, 113, 5), 60),
        ])])
        .await;
        let answer = resolve_with_ttl("sort.example.com.", addr, Duration::from_secs(2))
            .await
            .expect("resolve ok");
        assert_eq!(
            answer.targets,
            vec![
                "203.0.113.1".to_string(),
                "203.0.113.5".to_string(),
                "203.0.113.9".to_string(),
            ]
        );
        let _ = stop.send(());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resolve_handles_servfail() {
        let (addr, stop) = spawn_stub(vec![StubResponse::servfail()]).await;
        let err = resolve_with_ttl("broken.example.com.", addr, Duration::from_secs(2))
            .await
            .expect_err("SERVFAIL must error");
        assert_ne!(err.kind(), io::ErrorKind::TimedOut, "got {err:?}");
        let _ = stop.send(());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resolve_handles_nxdomain() {
        let (addr, stop) = spawn_stub(vec![StubResponse::nxdomain()]).await;
        let answer = resolve_with_ttl("gone.example.com.", addr, Duration::from_secs(2))
            .await
            .expect("NXDOMAIN must surface as Ok(empty)");
        assert!(answer.targets.is_empty(), "NXDOMAIN means no targets");
        assert_eq!(answer.ttl_seconds, 0);
        let _ = stop.send(());
    }

    // ============================================================
    // SEC-21 Phase 3h.2 — Q1 closure regression.
    // Setting `ResolverOpts.trust_anchor = Some(path)` causes
    // hickory's `ResolverBuilder::build` to auto-flip
    // `validate = true`. We assert this directly via the builder
    // shape (no network round-trip needed) so the test pins
    // the behaviour of our `build_resolver_opts` helper plus
    // the documented hickory-side auto-flip.
    // ============================================================

    #[test]
    fn trust_anchor_path_populates_resolver_opts() {
        // A path that does NOT need to exist — `build_resolver_opts`
        // doesn't open the file; it only sets the field. Hickory will
        // open it later inside `ResolverBuilder::build` and we don't
        // need that round-trip for this regression.
        let path = PathBuf::from("/etc/cellos/dnssec/operator-anchor.bin");
        let opts = build_resolver_opts(Duration::from_secs(2), Some(path.clone()));
        assert_eq!(
            opts.trust_anchor,
            Some(path),
            "operator-supplied path must reach ResolverOpts.trust_anchor verbatim"
        );
        // No path → no anchor (fall through to hickory's bundled IANA
        // defaults at validator-build time).
        let opts_default = build_resolver_opts(Duration::from_secs(2), None);
        assert_eq!(
            opts_default.trust_anchor, None,
            "no anchor path means we leave the field None for the default-anchor fallback"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn operator_anchor_path_is_actually_consulted() {
        // SEC-21 Phase 3h.2 — Q1 closure end-to-end regression.
        //
        // Hickory 0.26.1's stub-resolver path does NOT consume
        // `ResolverOpts.trust_anchor: Option<PathBuf>` directly — see
        // the discrepancy note on `resolve_with_ttl_validated`. The
        // load-bearing code path is our explicit
        // `hickory_proto::dnssec::TrustAnchors::from_file` call,
        // wired via `ResolverBuilder::with_trust_anchor`. This test
        // pins that wiring: when an operator supplies a path that
        // does NOT exist, the validator MUST surface a "trust anchor
        // parse failed" error rather than silently fall through to
        // the bundled IANA defaults. Silent fall-through would mean
        // operator-supplied anchors are unused — exactly the
        // pre-Phase-3h.2 audit-only-theatre that this upgrade
        // closes.
        //
        // We construct a TrustAnchors with `path()` pointing at a
        // nonexistent file by hand-building it. The supervisor's
        // production loader (`super::dnssec::TrustAnchors::load_from_path`)
        // would have rejected this with `O_NOFOLLOW` / metadata
        // checks before reaching here; this test bypasses that
        // pre-flight gate to drive the hickory-side wiring directly.
        struct SyntheticAnchors {
            path: PathBuf,
        }
        impl SyntheticAnchors {
            fn as_trust_anchors(&self) -> TrustAnchors {
                // Reach into the dnssec module for the test-only
                // builder. The production `TrustAnchors::load_from_path`
                // would have refused the nonexistent path; the
                // synthetic factory here is for driving the
                // hickory-side wiring only.
                let mut anchors = TrustAnchors::iana_default();
                anchors.bytes = b"unused-by-this-test".to_vec();
                anchors.source = "synthetic-nonexistent.bin".to_string();
                anchors.set_path_for_test(Some(self.path.clone()));
                anchors
            }
        }
        let synthetic = SyntheticAnchors {
            path: PathBuf::from("/nonexistent/cellos/dnssec/operator-anchor.bin"),
        };
        let anchors = synthetic.as_trust_anchors();
        // Use a guaranteed-no-route socket addr so we never accidentally
        // contact a real upstream — the trust-anchor-load failure must
        // happen BEFORE the network is touched.
        let unreachable: SocketAddr = "127.0.0.1:9".parse().unwrap();
        let err = resolve_with_ttl_validated(
            "anchor-test.example.com.",
            unreachable,
            Duration::from_millis(200),
            &anchors,
        )
        .await
        .expect_err(
            "nonexistent operator anchor path must surface as Err, not silently use IANA defaults",
        );
        let msg = format!("{err}");
        assert!(
            msg.contains("trust anchor parse failed"),
            "operator-anchor wiring must reach hickory_proto::dnssec::TrustAnchors::from_file \
             — silent IANA-default fallback would defeat Phase 3h.2 Q1 closure; got: {msg}"
        );
    }

    // ============================================================
    // SEC-21 Phase 3h.2 — Q3 closure regression.
    // The four `Proof` enum variants (`Secure` / `Insecure` /
    // `Bogus` / `Indeterminate`) map deterministically to the
    // four `DnssecValidationResult` outcomes (`Validated` /
    // `Unsigned` / `Failed{validation_failed}` /
    // `Failed{validation_indeterminate}`). The mapping is
    // implemented by `proof_to_validation_result` and exercised
    // here against each enum variant explicitly so a hickory
    // upgrade that adds a new `Proof` variant trips the
    // exhaustiveness check at compile time AND a behavioural
    // change to one of the four mappings trips an assertion at
    // test time.
    // ============================================================

    #[test]
    fn proof_secure_maps_to_validated() {
        //`proof_to_validation_result(Proof::Secure)` is the
        // documented placeholder fallback for callers that have a Proof
        // but no RRSIG metadata to extract (NSEC denial of existence,
        // or a malformed answer set). The success path now uses
        // `proof_to_validation_result_with_rrsig`, exercised by
        // `proof_secure_with_rrsig_metadata_uses_real_values` below.
        let result = proof_to_validation_result(Proof::Secure);
        match result {
            DnssecValidationResult::Validated { algorithm, key_tag } => {
                assert_eq!(
                    algorithm, "unknown",
                    "fallback path keeps the documented placeholder"
                );
                assert_eq!(key_tag, 0, "fallback path keeps the documented placeholder");
            }
            other => panic!("Proof::Secure must map to Validated; got {other:?}"),
        }
    }

    /// When real RRSIG metadata is supplied,
    /// `proof_to_validation_result_with_rrsig(Proof::Secure, Some((alg,
    /// tag)))` MUST stamp the real values, not the placeholder. This is
    /// the load-bearing assertion for the Q2 closure: a SIEM seeing
    /// `algorithm: "RSASHA256", key_tag: 12345` knows the validator
    /// actually surfaced signing metadata, not the documented fallback.
    #[test]
    fn proof_secure_with_rrsig_metadata_uses_real_values() {
        let result = proof_to_validation_result_with_rrsig(
            Proof::Secure,
            Some(("RSASHA256".to_string(), 12345)),
        );
        match result {
            DnssecValidationResult::Validated { algorithm, key_tag } => {
                assert_eq!(
                    algorithm, "RSASHA256",
                    "real RRSIG metadata MUST replace the 'unknown' placeholder \
                     when supplied — Q2 closure regression"
                );
                assert_eq!(
                    key_tag, 12345,
                    "real RRSIG key_tag MUST replace the 0 placeholder \
                     when supplied — Q2 closure regression"
                );
            }
            other => panic!("Proof::Secure must map to Validated; got {other:?}"),
        }
    }

    /// Non-Secure proofs ignore RRSIG metadata. The
    /// metadata is only meaningful when validation succeeded; a
    /// `Bogus` outcome with metadata still maps to
    /// `Failed{validation_failed}` (and `Indeterminate` to
    /// `Failed{validation_indeterminate}`).
    #[test]
    fn rrsig_metadata_ignored_for_non_secure_proofs() {
        for proof in [Proof::Insecure, Proof::Bogus, Proof::Indeterminate] {
            let result = proof_to_validation_result_with_rrsig(
                proof,
                Some(("RSASHA256".to_string(), 12345)),
            );
            match (proof, &result) {
                (Proof::Insecure, DnssecValidationResult::Unsigned) => {}
                (Proof::Bogus, DnssecValidationResult::Failed { reason })
                    if reason == "validation_failed" => {}
                (Proof::Indeterminate, DnssecValidationResult::Failed { reason })
                    if reason == "validation_indeterminate" => {}
                _ => panic!(
                    "metadata MUST be ignored for non-Secure proofs; \
                     got {proof:?} -> {result:?}"
                ),
            }
        }
    }

    ///`extract_rrsig_metadata` returns `None` for an
    /// answer set with no RRSIG records. The caller falls back to the
    /// placeholder values via `proof_to_validation_result_with_rrsig`.
    #[test]
    fn extract_rrsig_metadata_none_when_no_rrsigs() {
        let a_record = hickory_resolver::proto::rr::Record::from_rdata(
            "example.com.".parse().unwrap(),
            300,
            hickory_resolver::proto::rr::RData::A(hickory_resolver::proto::rr::rdata::A(
                Ipv4Addr::new(203, 0, 113, 1),
            )),
        );
        let metadata = extract_rrsig_metadata(
            &[a_record],
            &[
                hickory_resolver::proto::rr::RecordType::A,
                hickory_resolver::proto::rr::RecordType::AAAA,
            ],
        );
        assert!(
            metadata.is_none(),
            "answer set with no RRSIGs MUST return None so the caller \
             stamps the documented placeholder rather than fabricating values"
        );
    }

    ///`extract_rrsig_metadata` walks the answer set,
    /// finds the first RRSIG covering an acceptable type, and returns
    /// its real `(algorithm, key_tag)`. This is the synthetic
    /// counterpart to a real DNSSEC-signed upstream: we hand-build a
    /// `Record` carrying an RRSIG and assert the helper extracts the
    /// signing parameters verbatim.
    #[test]
    fn extract_rrsig_metadata_returns_real_values_for_a_query() {
        use hickory_proto::dnssec::rdata::{DNSSECRData, SigInput, RRSIG};
        use hickory_proto::dnssec::Algorithm;
        use hickory_resolver::proto::rr::{RData, Record, RecordType, SerialNumber};

        // Build a synthetic RRSIG with known signing parameters.
        let input = SigInput {
            type_covered: RecordType::A,
            algorithm: Algorithm::RSASHA256,
            num_labels: 2,
            original_ttl: 300,
            sig_expiration: SerialNumber::new(1_700_000_000),
            sig_inception: SerialNumber::new(1_690_000_000),
            key_tag: 54321,
            signer_name: "example.com.".parse().unwrap(),
        };
        let rrsig = RRSIG::from_sig(input, vec![0u8; 32]);
        let rrsig_record = Record::from_rdata(
            "example.com.".parse().unwrap(),
            300,
            RData::DNSSEC(DNSSECRData::RRSIG(rrsig)),
        );

        // Plus a sibling A record so the answer set looks like a real
        // validated response: A record + RRSIG covering A.
        let a_record = Record::from_rdata(
            "example.com.".parse().unwrap(),
            300,
            RData::A(hickory_resolver::proto::rr::rdata::A(Ipv4Addr::new(
                203, 0, 113, 1,
            ))),
        );

        let metadata = extract_rrsig_metadata(
            &[a_record, rrsig_record],
            &[RecordType::A, RecordType::AAAA],
        );
        assert_eq!(
            metadata,
            Some(("RSASHA256".to_string(), 54321)),
            "extract_rrsig_metadata MUST surface the RRSIG's algorithm + key_tag — \
             this is the load-bearing T1.A / P0-1 closure"
        );
    }

    ///`extract_rrsig_metadata` skips RRSIG records whose
    /// `type_covered` is not in the acceptable list. Defensive: if a
    /// future hickory change reorganizes section handling and a CNAME
    /// RRSIG leaks into the answers, we don't accidentally report it
    /// as the A record's signature.
    #[test]
    fn extract_rrsig_metadata_skips_rrsig_for_other_types() {
        use hickory_proto::dnssec::rdata::{DNSSECRData, SigInput, RRSIG};
        use hickory_proto::dnssec::Algorithm;
        use hickory_resolver::proto::rr::{RData, Record, RecordType, SerialNumber};

        let cname_input = SigInput {
            type_covered: RecordType::CNAME,
            algorithm: Algorithm::ED25519,
            num_labels: 2,
            original_ttl: 300,
            sig_expiration: SerialNumber::new(1_700_000_000),
            sig_inception: SerialNumber::new(1_690_000_000),
            key_tag: 60_999,
            signer_name: "example.com.".parse().unwrap(),
        };
        let cname_rrsig = RRSIG::from_sig(cname_input, vec![0u8; 32]);
        let cname_rrsig_record = Record::from_rdata(
            "example.com.".parse().unwrap(),
            300,
            RData::DNSSEC(DNSSECRData::RRSIG(cname_rrsig)),
        );

        let metadata =
            extract_rrsig_metadata(&[cname_rrsig_record], &[RecordType::A, RecordType::AAAA]);
        assert!(
            metadata.is_none(),
            "RRSIG covering CNAME MUST NOT be reported when caller asked for A/AAAA — \
             defensive type-cover discipline prevents misattributed signing parameters"
        );
    }

    #[test]
    fn proof_insecure_maps_to_unsigned() {
        let result = proof_to_validation_result(Proof::Insecure);
        assert!(
            matches!(result, DnssecValidationResult::Unsigned),
            "Proof::Insecure (zone known to be unsigned) must map to Unsigned; got {result:?}"
        );
    }

    #[test]
    fn proof_bogus_maps_to_failed_validation_failed() {
        let result = proof_to_validation_result(Proof::Bogus);
        match result {
            DnssecValidationResult::Failed { reason } => {
                assert_eq!(
                    reason, "validation_failed",
                    "Proof::Bogus → Failed must use the SIEM-stable code 'validation_failed'"
                );
            }
            other => panic!("Proof::Bogus must map to Failed; got {other:?}"),
        }
    }

    #[test]
    fn proof_indeterminate_maps_to_failed_validation_indeterminate() {
        let result = proof_to_validation_result(Proof::Indeterminate);
        match result {
            DnssecValidationResult::Failed { reason } => {
                assert_eq!(
                    reason, "validation_indeterminate",
                    "Proof::Indeterminate → Failed must use the SIEM-stable code \
                     'validation_indeterminate' (distinct from validation_failed so an operator \
                     can grep for the 'validator could not reach a verdict' case separately from \
                     the 'validator rejected the chain' case)"
                );
            }
            other => panic!("Proof::Indeterminate must map to Failed; got {other:?}"),
        }
    }

    #[test]
    fn worst_proof_demotes_on_first_bogus() {
        let mut secure_record = hickory_resolver::proto::rr::Record::from_rdata(
            "example.com.".parse().unwrap(),
            300,
            hickory_resolver::proto::rr::RData::A(hickory_resolver::proto::rr::rdata::A(
                Ipv4Addr::new(203, 0, 113, 1),
            )),
        );
        secure_record.proof = Proof::Secure;
        let mut bogus_record = hickory_resolver::proto::rr::Record::from_rdata(
            "example.com.".parse().unwrap(),
            300,
            hickory_resolver::proto::rr::RData::A(hickory_resolver::proto::rr::rdata::A(
                Ipv4Addr::new(203, 0, 113, 2),
            )),
        );
        bogus_record.proof = Proof::Bogus;
        let records = vec![secure_record, bogus_record];
        assert_eq!(
            worst_proof(&records),
            Proof::Bogus,
            "any Bogus record must poison the whole answer set"
        );
    }

    #[test]
    fn worst_proof_returns_secure_only_when_all_records_secure() {
        let mut r1 = hickory_resolver::proto::rr::Record::from_rdata(
            "example.com.".parse().unwrap(),
            300,
            hickory_resolver::proto::rr::RData::A(hickory_resolver::proto::rr::rdata::A(
                Ipv4Addr::new(203, 0, 113, 1),
            )),
        );
        r1.proof = Proof::Secure;
        let mut r2 = hickory_resolver::proto::rr::Record::from_rdata(
            "example.com.".parse().unwrap(),
            300,
            hickory_resolver::proto::rr::RData::A(hickory_resolver::proto::rr::rdata::A(
                Ipv4Addr::new(203, 0, 113, 2),
            )),
        );
        r2.proof = Proof::Secure;
        assert_eq!(
            worst_proof(&[r1, r2]),
            Proof::Secure,
            "all-Secure record set must come back Secure"
        );
    }

    #[test]
    fn worst_proof_empty_returns_indeterminate() {
        // Defensive fallback for the "no records to inspect" case —
        // shouldn't be reached in production (we early-return for
        // empty answers with the validator's NSEC proof) but the
        // contract is documented.
        assert_eq!(worst_proof(&[]), Proof::Indeterminate);
    }

    // ============================================================
    // Synthetic-upstream wrapper tests — these run the validating
    // resolver against an unsigned synthetic upstream and assert
    // that the wrapper does not crash and produces a non-Failed
    // outcome (Insecure when the validator decides the zone is
    // unsigned, or potentially Indeterminate when it can't reach a
    // verdict against an untrusted upstream). The negative
    // assertion is the load-bearing one: SERVFAIL must NOT
    // masquerade as a DNSSEC outcome.
    // ============================================================

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn validated_servfail_surfaces_as_io_error_not_dnssec_failed() {
        let (addr, _stop) = spawn_stub(vec![StubResponse::servfail()]).await;
        let anchors = TrustAnchors::iana_default();
        let err = resolve_with_ttl_validated(
            "broken.example.com.",
            addr,
            Duration::from_secs(2),
            &anchors,
        )
        .await
        .expect_err("SERVFAIL must surface as io::Error, not as DnssecValidationResult::Failed");
        assert_ne!(
            err.kind(),
            io::ErrorKind::TimedOut,
            "SERVFAIL is not a timeout: {err:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn validated_unsigned_synthetic_upstream_does_not_panic() {
        // The synthetic upstream returns NOERROR-with-A and no DNSSEC
        // chain. The validator's verdict against it depends on whether
        // it tries to fetch DS / DNSKEY records (and whether the
        // synthetic answers them) — different validators produce
        // Insecure, Indeterminate, or Bogus for this configuration. We
        // assert the WRAPPER contract:
        //   - does not panic
        //   - does not return io::Error (the upstream did respond)
        //   - the validation outcome is one of the documented variants
        let (addr, stop) = spawn_stub(vec![StubResponse::ok_a(vec![(
            Ipv4Addr::new(203, 0, 113, 5),
            300,
        )])])
        .await;
        let anchors = TrustAnchors::iana_default();
        let result =
            resolve_with_ttl_validated("api.example.com.", addr, Duration::from_secs(2), &anchors)
                .await;
        match result {
            Ok(v) => {
                // The wrapper produced a structured outcome. Any of
                // the three documented variants is acceptable here —
                // we are not testing hickory's validator behaviour,
                // we are testing that the wrapper threads it through.
                let _ = v.validation;
                assert_eq!(v.answer.resolver_addr, addr);
            }
            Err(e) => {
                // io::Error is also acceptable for this synthetic —
                // hickory may surface "could not reach a chain" as a
                // transport-class failure rather than an Indeterminate
                // proof. That's still wrapper-contract-compliant.
                assert_ne!(
                    e.kind(),
                    io::ErrorKind::TimedOut,
                    "synthetic upstream answered; should not be a timeout: {e:?}"
                );
            }
        }
        let _ = stop.send(());
    }
}