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
//! SEC-21 Phase 3h.1 — SEAM-1 in-netns DNS proxy DNSSEC validation.
//!
//! Closes the dataplane gap left by Phase 3h. The supervisor-side
//! resolver-refresh path (P3h, see [`crate::resolver_refresh::dnssec`])
//! validates DNSSEC for the *observability* signal (drift events). The
//! workload-facing in-netns DNS proxy ([`super`]) — which the workload
//! actually queries — did not validate at all before P3h.1: a workload
//! asking for an allowlisted hostname would receive whatever the upstream
//! returned, including potentially-spoofed unsigned/bogus records.
//!
//! This module adds enforcement on the dataplane.
//!
//! ## Mode mapping
//!
//! The Phase 3h.1 spec uses three logical modes — `require | best_effort
//! | off`. We map onto the existing P3h two-boolean
//! [`cellos_core::DnsResolverDnssecPolicy`] (`validate`, `fail_closed`)
//! without inventing a new spec field:
//!
//! | Logical mode  | `validate` | `fail_closed` | Behaviour                              |
//! |---------------|------------|---------------|----------------------------------------|
//! | `off`         | n/a        | n/a           | `dnssec` block is `None`, OR `validate=false` — validator not constructed at all (`from_authority` returns `Ok(None)`). |
//! | `best_effort` | `true`     | `false`       | Validator runs; bogus → SERVFAIL+event; unsigned → forward (no event). |
//! | `require`     | `true`     | `true`        | Validator runs; bogus → SERVFAIL+event; unsigned → SERVFAIL+event.     |
//!
//! ## Behaviour matrix (load-bearing)
//!
//! For every workload query that passes the proxy's allowlist gate AND has
//! a validator configured:
//!
//! | Mode          | Outcome  | Workload sees     | Event emitted?                                          |
//! |---------------|----------|-------------------|---------------------------------------------------------|
//! | `require`     | Validated| Forwarded answer  | No                                                      |
//! | `require`     | Unsigned | SERVFAIL          | Yes — `reason: "unsigned_in_require_mode"`              |
//! | `require`     | Failed   | SERVFAIL          | Yes — `reason: "validation_failed"`                     |
//! | `best_effort` | Validated| Forwarded answer  | No                                                      |
//! | `best_effort` | Unsigned | Forwarded answer  | No (explicit "tolerate unsigned zones")                  |
//! | `best_effort` | Failed   | SERVFAIL          | Yes — `reason: "validation_failed"` (bogus always rejected)|
//! | (any)         | Skip     | (see Skip below)  | (see Skip below)                                        |
//!
//! ### `Skip` outcome (post-A2: residual non-validating types)
//!
//! `validate()` returns `Skip` ONLY for query types this validator cannot
//! evaluate via either backend (A/AAAA via
//! [`crate::resolver_refresh::hickory_resolve::resolve_with_ttl_validated`]
//! or CNAME/HTTPS/SVCB/MX/TXT via the typed-record backend introduced in
//! the A2 slot). After A2 the validator covers seven query types
//! end-to-end; `Skip` is now the residual fallback for types like
//! `NS`, `PTR`, `SRV`, `SOA`, etc., that the proxy's
//! [`super::DEFAULT_QUERY_TYPES`] does NOT admit by default. Operators
//! who widen `allowed_query_types` to include such residuals get the
//! same call-site policy as before:
//!
//! - `require` + `Skip` → SERVFAIL + event
//!   `reason: "unsupported_query_type_in_require_mode"`. Strict reading:
//!   if the operator asked for require, an unvalidatable response is not
//!   acceptable.
//! - `best_effort` + `Skip` → forward unvalidated. Documented honestly as
//!   a known gap — the seven first-class types (A/AAAA/CNAME/HTTPS/SVCB/MX/TXT)
//!   are validated; the residuals pass through.
//!
//! Off-mode cells never construct a validator; the proxy's hot path stays
//! byte-identical to pre-P3h.1.
//!
//! ## Validation strategy — Option B (post-validate after raw forward)
//!
//! The Phase 3h.1 spec offers two implementation options:
//!
//! - **Option A**: hand the workload's query off to a validating hickory
//!   resolver and synthesize the response back to the workload from the
//!   resolver's `Vec<IpAddr>` output.
//! - **Option B**: keep the existing raw forward, then re-resolve the same
//!   `(qname, qtype)` through a validating hickory resolver to produce an
//!   independent verdict, and dispatch on the verdict.
//!
//! **We chose B.** Reasoning:
//!
//! - [`crate::resolver_refresh::hickory_resolve::resolve_with_ttl_validated`]
//!   returns `Vec<String>` IP targets — it discards CNAME chains and any
//!   additional records (HTTPS/SVCB/EDNS) the upstream may have included.
//!   Synthesizing the workload-facing wire response from just IPs would
//!   silently lose information the workload may have asked for.
//! - Option B preserves whatever the upstream actually said (CNAME chain,
//!   answer additionals, the exact RCODE) when the verdict says "allow",
//!   which is the contract the workload had before P3h.1.
//!
//! Cost: each workload query that has a validator triggers two upstream
//! roundtrips (original raw forward + hickory's validation lookup).
//! Acceptable — DNS volume per cell is low and the validator is per-cell.
//! A future hickory release that exposes a public knob to inject the raw
//! upstream answer into the validator (avoiding the second roundtrip) is
//! a clean Option-A migration target.
//!
//! ## Trust anchors — reuse, not copy
//!
//! Trust-anchor loading reuses [`crate::resolver_refresh::dnssec::TrustAnchors`]
//! verbatim — same `O_NOFOLLOW`, same 32 KiB ceiling, same env-var
//! precedence (`CELLOS_DNSSEC_TRUST_ANCHORS_PATH`). The Hickory 0.24
//! limitation persists at this surface too: operator-supplied anchors are
//! observable via `trustAnchorSource` in events but the validator
//! internally uses hickory's bundled IANA defaults (19036 + 20326). When
//! hickory exposes a public anchor-injection knob, both validation
//! surfaces (resolver-refresh and dataplane) gain it together.
//!
//! ## Event emission — additive `source` field
//!
//! Both surfaces emit the same CloudEvent type
//! (`dev.cellos.events.cell.observability.v1.dns_authority_dnssec_failed`)
//! and now stamp an additive `source` field discriminating which surface
//! produced the event:
//!
//! - `source = "resolver_refresh"` — supervisor-side resolver-refresh.
//! - `source = "dataplane"` — in-netns DNS proxy (this module).
//!
//! The field is **optional** in the v1 schema for one cycle so existing
//! emitters that pre-date Phase 3h.1 still validate. The next major
//! schema bump should make this required.

use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use cellos_core::{CellosError, DnsAuthority, DnsQueryType};
use hickory_proto::dnssec::Proof;
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::proto::op::ResponseCode;
use hickory_resolver::proto::rr::RecordType;
use hickory_resolver::Resolver;

use super::parser::parse_query;
use crate::resolver_refresh::hickory_resolve::{
    extract_rrsig_metadata, proof_to_validation_result_with_rrsig,
};
use crate::resolver_refresh::DnssecValidationResult;

// Re-export TrustAnchors so callers in this module's neighborhood can
// reach it without naming the resolver_refresh path. This is a re-export
// (not a copy) — there is exactly one TrustAnchors definition in the
// supervisor crate.
pub use crate::resolver_refresh::dnssec::TrustAnchors;

/// Default upstream-validation timeout when [`from_authority`] does not
/// have an operator-configured budget. Matches the
/// [`super::DnsProxyConfig::upstream_timeout`] production default (400ms)
/// so the validator's roundtrip budget aligns with the proxy's own
/// upstream budget — avoids "validator timed out before upstream did"
/// confusion in operator triage.
const DEFAULT_VALIDATION_TIMEOUT: Duration = Duration::from_millis(400);

/// Outcome of one dataplane DNSSEC validation attempt.
///
/// Matches the P3h vocabulary [`DnssecValidationResult`] one-for-one
/// (`Validated` / `Unsigned` / `Failed`) plus a fourth `Skip` variant for
/// query types this validator cannot evaluate (see module docs).
///
/// Post-A2: `Skip` is returned by [`DataplaneDnssecValidator::validate`]
/// for query types outside the validator's first-class set
/// `{A, AAAA, CNAME, HTTPS, SVCB, MX, TXT}`. The proxy call site decides
/// what to do with it based on `fail_closed` (require vs best_effort) —
/// see the behaviour matrix in module docs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DataplaneDnssecOutcome {
    /// Backend was not dispatched because the query type is outside the
    /// validator's first-class set (post-A2: A/AAAA/CNAME/HTTPS/SVCB/MX/TXT).
    /// Caller dispatches based on policy: in `require` mode this
    /// SERVFAILs with `unsupported_query_type_in_require_mode`; in
    /// `best_effort` it forwards unvalidated.
    Skip,
    /// Chain of trust established back to the configured anchor set.
    Validated,
    /// Resolver returned answers but the zone is not signed. Operator
    /// policy (`fail_closed`) decides allow/deny.
    Unsigned,
    /// Validator rejected the chain — RRSIG missing, signature bogus, or
    /// chained to a key not in the configured trust anchors. `reason` is
    /// a stable static string suitable for the
    /// `dns_authority_dnssec_failed` event's `reason` field.
    Failed {
        /// Stable static reason string. Always one of the schema enum
        /// values: `"validation_failed"`, `"unsigned_in_require_mode"`,
        /// `"unsupported_query_type_in_require_mode"`, or
        /// `"trust_anchor_missing"`.
        reason: &'static str,
    },
}

/// Pluggable A/AAAA backend used by [`DataplaneDnssecValidator`].
///
/// Production wiring constructs a backend that calls
/// [`crate::resolver_refresh::resolve_with_ttl_validated`] inside a
/// captured tokio runtime handle. Unit tests construct synthetic
/// backends that return canned outcomes — this is what makes
/// `validate()` testable without standing up a real DNSSEC upstream.
///
/// The backend receives `(qname, qtype)` and returns a
/// [`DnssecValidationResult`] (the P3h vocabulary). The validator maps
/// that to a [`DataplaneDnssecOutcome`].
///
/// `Send + Sync` because the validator is held behind an `Arc` and
/// shared between the supervisor task and the proxy thread.
pub type DataplaneDnssecBackend =
    dyn Fn(&str, u16) -> std::io::Result<DnssecValidationResult> + Send + Sync;

/// A2 — pluggable typed-record backend used by
/// [`DataplaneDnssecValidator`] for the non-A/AAAA first-class types
/// (CNAME / HTTPS / SVCB / MX / TXT).
///
/// Distinct from [`DataplaneDnssecBackend`] because it dispatches the
/// hickory generic `Resolver::lookup(name, RecordType)` API rather than
/// the `lookup_ip` strategy `resolve_with_ttl_validated` rides on; it
/// does not need to merge A+AAAA answer sets, and the answer records
/// inspected for `Proof` are the per-type set hickory returns rather
/// than the IPv4+IPv6 union.
///
/// Production wiring builds this on top of an internal helper that
/// constructs a fresh validating resolver per call (mirroring
/// `resolve_with_ttl_validated`'s build pattern) and walks the answer
/// records to produce the `DnssecValidationResult` verdict. Tests
/// supply canned outcomes via [`DataplaneDnssecValidator::with_backends`].
///
/// Returns the same [`DnssecValidationResult`] taxonomy as the A/AAAA
/// path so the existing `Validated → Validated`, `Unsigned → Unsigned`,
/// `Failed → Failed{validation_failed}` mapping inside `validate()`
/// applies uniformly. An I/O error from the resolver fail-safes to
/// `Failed{validation_failed}` (require-mode contract: no answer unless
/// the validator could establish a chain — extending to "or unless we
/// couldn't even ask").
pub type DataplaneTypedDnssecBackend =
    dyn Fn(&str, RecordType) -> std::io::Result<DnssecValidationResult> + Send + Sync;

/// Dataplane DNSSEC validator handed to the proxy via
/// [`super::DnsProxyConfig::dnssec_validator`].
///
/// Construct via [`DataplaneDnssecValidator::from_authority`] in
/// production (returns `Ok(None)` for `mode = off` so the proxy hot
/// path is unchanged), or via the test-only
/// [`DataplaneDnssecValidator::with_backend`] for unit tests.
pub struct DataplaneDnssecValidator {
    /// `true` when the cell's DnsAuthority requested `require` mode
    /// (validate=true, fail_closed=true). Drives the SERVFAIL decision
    /// for `Unsigned` and `Skip` outcomes.
    fail_closed: bool,
    /// Source descriptor for trust anchors stamped into events
    /// (`"iana-default"` or the basename of an operator-supplied file).
    trust_anchor_source: String,
    /// A/AAAA backend callable. In production this captures a tokio
    /// runtime handle and calls
    /// [`crate::resolver_refresh::resolve_with_ttl_validated`]. In tests
    /// this is a closure returning a canned [`DnssecValidationResult`].
    backend: Arc<DataplaneDnssecBackend>,
    /// A2 — typed-record backend for CNAME / HTTPS / SVCB / MX / TXT.
    /// `None` preserves the pre-A2 behaviour (these types Skip; the
    /// proxy call site dispatches based on require vs best_effort).
    /// `Some(_)` engages per-type validation: CNAME/HTTPS/SVCB/MX/TXT
    /// queries get a real Validated/Unsigned/Failed verdict instead of
    /// the placeholder `unsupported_query_type_in_require_mode`
    /// rejection. Production [`Self::from_authority`] populates this
    /// for every `validate=true` policy; tests can supply a synthetic
    /// implementation via [`Self::with_backends`].
    typed_backend: Option<Arc<DataplaneTypedDnssecBackend>>,
}

impl std::fmt::Debug for DataplaneDnssecValidator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DataplaneDnssecValidator")
            .field("fail_closed", &self.fail_closed)
            .field("trust_anchor_source", &self.trust_anchor_source)
            .field("backend", &"<Arc<dyn Fn>>")
            .field(
                "typed_backend",
                &self.typed_backend.as_ref().map(|_| "<Arc<dyn Fn>>"),
            )
            .finish()
    }
}

impl DataplaneDnssecValidator {
    /// SEC-21 Phase 3h.1 — construct a validator from a parsed
    /// [`DnsAuthority`].
    ///
    /// Returns:
    /// - `Ok(None)` when the first declared resolver has no `dnssec`
    ///   block or has `dnssec.validate = false` — i.e. the cell opted
    ///   out (`mode = off`). The proxy hot path stays byte-identical
    ///   to today.
    /// - `Ok(Some(..))` when `dnssec.validate = true`. The validator is
    ///   ready to evaluate workload queries. `fail_closed` is taken
    ///   from `dnssec.fail_closed` (true → require, false → best_effort).
    /// - `Err(CellosError::InvalidSpec)` when `dnssec.trust_anchors_path`
    ///   is set but the file is missing, symlinked, or oversized — the
    ///   trust-anchor loader (reused from
    ///   [`crate::resolver_refresh::dnssec::TrustAnchors`]) refuses to
    ///   construct the validator silently. Surfacing this at activation
    ///   time prevents a cell from running with a broken validator and
    ///   a half-enforced policy.
    ///
    /// **Resolver selection**: the first entry of `auth.resolvers` is
    /// consulted; this matches the proxy's existing
    /// [`super::DnsProxyConfig::upstream_resolver_id`] convention (the
    /// proxy talks to one upstream resolver per cell). Cells with multiple
    /// resolvers and per-resolver DNSSEC policies are out of scope for
    /// P3h.1.
    ///
    /// **Tokio context**: this constructor does NOT call `Handle::current()`
    /// — the production backend captures the handle lazily on the first
    /// `validate()` call. This keeps `from_authority` callable from unit
    /// tests that don't have a runtime, while still letting production
    /// (which always has a runtime) drive hickory.
    pub fn from_authority(auth: &DnsAuthority) -> Result<Option<Self>, CellosError> {
        let Some(resolver) = auth.resolvers.first() else {
            return Ok(None);
        };
        let Some(policy) = resolver.dnssec.as_ref() else {
            return Ok(None);
        };
        if !policy.validate {
            return Ok(None);
        }

        // Trust-anchor loading — surfaces operator-misconfiguration as
        // an InvalidSpec error rather than a silent degrade. Reuses the
        // P3h loader (O_NOFOLLOW + 32 KiB ceiling) verbatim.
        let anchors = TrustAnchors::load(policy.trust_anchors_path.as_deref())?;
        let trust_anchor_source = anchors.source.clone();

        // Parse the upstream resolver's endpoint into a SocketAddr for
        // hickory. Phase 3h.1 only supports do53-udp/tcp resolvers (the
        // dataplane proxy itself only does do53). Other protocols would
        // require additional hickory configuration and are out of scope.
        let upstream_addr: SocketAddr = resolver.endpoint.parse().map_err(|e| {
            CellosError::InvalidSpec(format!(
                "dns_proxy::dnssec: cannot parse resolver.endpoint '{}' as SocketAddr: {e}",
                resolver.endpoint
            ))
        })?;

        let anchors = Arc::new(anchors);
        let backend =
            build_hickory_backend(upstream_addr, DEFAULT_VALIDATION_TIMEOUT, anchors.clone());
        let typed_backend =
            build_hickory_typed_backend(upstream_addr, DEFAULT_VALIDATION_TIMEOUT, anchors);

        Ok(Some(Self {
            fail_closed: policy.fail_closed,
            trust_anchor_source,
            backend,
            typed_backend: Some(typed_backend),
        }))
    }

    /// Test-only constructor — builds a validator with a synthetic
    /// A/AAAA backend ONLY. Used by integration tests in
    /// `tests/dataplane_dnssec_validation.rs` to drive the
    /// `Validated/Unsigned/Failed` matrix without standing up a real
    /// DNSSEC-signed upstream.
    ///
    /// Validators built via this constructor have NO typed-record backend
    /// (`typed_backend: None`), preserving pre-A2 Skip behaviour for
    /// CNAME/HTTPS/SVCB/MX/TXT — the existing P3h.1 test matrix that
    /// asserts `Skip + require → SERVFAIL` against a TXT query continues
    /// to fire the same code path it always has.
    ///
    /// For tests that need to exercise the typed-record validator path,
    /// use [`Self::with_backends`].
    ///
    /// Production callers MUST go through [`Self::from_authority`].
    #[doc(hidden)]
    pub fn with_backend(
        fail_closed: bool,
        trust_anchor_source: String,
        backend: Arc<DataplaneDnssecBackend>,
    ) -> Self {
        Self {
            fail_closed,
            trust_anchor_source,
            backend,
            typed_backend: None,
        }
    }

    /// A2 test-only constructor — builds a validator with both an A/AAAA
    /// backend AND a typed-record backend. The typed backend is invoked
    /// for CNAME / HTTPS / SVCB / MX / TXT queries; the A/AAAA backend
    /// for A and AAAA. All other query types still Skip.
    ///
    /// This shape is what the per-type integration tests at
    /// `tests/dataplane_dnssec_per_type_validation.rs` use to drive the
    /// post-A2 `Validated/Unsigned/Failed` matrix per type without
    /// standing up five real DNSSEC-signed zones.
    ///
    /// Production callers MUST go through [`Self::from_authority`].
    #[doc(hidden)]
    pub fn with_backends(
        fail_closed: bool,
        trust_anchor_source: String,
        backend: Arc<DataplaneDnssecBackend>,
        typed_backend: Arc<DataplaneTypedDnssecBackend>,
    ) -> Self {
        Self {
            fail_closed,
            trust_anchor_source,
            backend,
            typed_backend: Some(typed_backend),
        }
    }

    /// `true` when the validator was constructed in `require` mode
    /// (cell's DnsAuthority set `dnssec.fail_closed = true`). Drives the
    /// proxy's SERVFAIL decision for `Unsigned` and `Skip` outcomes.
    #[must_use]
    pub fn is_require_mode(&self) -> bool {
        self.fail_closed
    }

    /// Trust-anchor source descriptor stamped into emitted events
    /// (`"iana-default"` or the basename of an operator-supplied file).
    #[must_use]
    pub fn trust_anchor_source(&self) -> &str {
        &self.trust_anchor_source
    }

    /// Validate a single workload query.
    ///
    /// `query` is the raw UDP payload the workload sent. `_upstream_answer`
    /// is the raw upstream response — **ignored under Option B**: the
    /// validator re-resolves the same `(qname, qtype)` through hickory
    /// to produce an independent verdict (see module docs for why we
    /// chose Option B over Option A).
    ///
    /// The parameter is plumbed for forward-compat to a future Option-A
    /// migration that injects the raw answer into hickory's validator
    /// (when hickory exposes such a knob).
    ///
    /// ## Type dispatch (post-A2)
    ///
    /// `validate()` switches over the parsed `qtype`:
    ///
    /// | Query type             | Backend dispatched                                    |
    /// |------------------------|-------------------------------------------------------|
    /// | A, AAAA                | `self.backend` (hickory `lookup_ip` strategy)         |
    /// | CNAME, HTTPS, SVCB, MX, TXT | `self.typed_backend` (hickory generic `lookup`)   |
    /// | All others             | `Skip` (call site policy: SERVFAIL in require, forward in best_effort) |
    ///
    /// When `self.typed_backend` is `None` (validators built via the
    /// pre-A2 [`Self::with_backend`] test constructor), CNAME/HTTPS/SVCB/MX/TXT
    /// also Skip — preserving backward compatibility with the existing
    /// P3h.1 test surface that asserts `TXT + require → SERVFAIL`.
    ///
    /// ## Outcomes
    ///
    /// - [`DataplaneDnssecOutcome::Skip`] for query types outside the
    ///   first-class set, or for first-class types when the
    ///   typed-record backend is absent. Caller policy decides what to
    ///   do (see module docs).
    /// - [`DataplaneDnssecOutcome::Validated`] when hickory's bundled
    ///   validator chained the response back to the configured anchors.
    /// - [`DataplaneDnssecOutcome::Unsigned`] when the zone has no
    ///   DNSSEC chain.
    /// - [`DataplaneDnssecOutcome::Failed`] when the validator rejected
    ///   the chain (RRSIG missing, signature bogus, or chained to a
    ///   non-anchor key) OR the backend returned an I/O error (network
    ///   timeout / SERVFAIL from upstream — fail-safe to Failed).
    pub fn validate(&self, query: &[u8], _upstream_answer: &[u8]) -> DataplaneDnssecOutcome {
        // Parse just enough to extract qname + qtype. If the query is
        // malformed, the proxy already dropped it before calling us;
        // defensive `Skip` if we somehow get here with garbage.
        let view = match parse_query(query) {
            Ok(v) => v,
            Err(_) => return DataplaneDnssecOutcome::Skip,
        };

        // Switch over the typed query enum. A/AAAA dispatch onto the
        // legacy `lookup_ip`-based backend; CNAME/HTTPS/SVCB/MX/TXT
        // dispatch onto the typed-record backend (post-A2). Everything
        // else Skips — call site policy decides.
        let typed = cellos_core::qtype_to_dns_query_type(view.qtype);
        let dispatch = match typed {
            Some(DnsQueryType::A) | Some(DnsQueryType::AAAA) => Dispatch::Legacy,
            Some(DnsQueryType::CNAME) => Dispatch::Typed(RecordType::CNAME),
            Some(DnsQueryType::HTTPS) => Dispatch::Typed(RecordType::HTTPS),
            Some(DnsQueryType::SVCB) => Dispatch::Typed(RecordType::SVCB),
            Some(DnsQueryType::MX) => Dispatch::Typed(RecordType::MX),
            Some(DnsQueryType::TXT) => Dispatch::Typed(RecordType::TXT),
            _ => return DataplaneDnssecOutcome::Skip,
        };

        let result = match dispatch {
            Dispatch::Legacy => (self.backend)(&view.qname, view.qtype),
            Dispatch::Typed(rtype) => match self.typed_backend.as_ref() {
                Some(typed_backend) => (typed_backend)(&view.qname, rtype),
                // Pre-A2 shape: no typed backend wired (test constructor
                // `with_backend` or future operator-toggle). Preserve
                // legacy Skip behaviour so the call site policy still
                // decides SERVFAIL vs forward.
                None => return DataplaneDnssecOutcome::Skip,
            },
        };

        match result {
            Ok(DnssecValidationResult::Validated { .. }) => DataplaneDnssecOutcome::Validated,
            Ok(DnssecValidationResult::Unsigned) => DataplaneDnssecOutcome::Unsigned,
            Ok(DnssecValidationResult::Failed { .. }) => DataplaneDnssecOutcome::Failed {
                reason: "validation_failed",
            },
            // Fail-safe: any I/O error from the validating resolver
            // (timeout, transport, refused) is treated as a validation
            // failure rather than passing through the unvalidated
            // upstream answer. The require-mode contract is "no answer
            // unless validated" — extending that to "or unless we
            // couldn't even ask" is the only safe choice. best_effort
            // gets the same SERVFAIL because the validator's verdict
            // is "couldn't establish chain".
            Err(_) => DataplaneDnssecOutcome::Failed {
                reason: "validation_failed",
            },
        }
    }
}

/// Internal dispatch tag — which backend `validate()` should call.
/// Doesn't escape this module.
enum Dispatch {
    /// A/AAAA — hickory `lookup_ip` strategy via `self.backend`.
    Legacy,
    /// Typed record (CNAME/HTTPS/SVCB/MX/TXT) — hickory generic
    /// `lookup(name, RecordType)` via `self.typed_backend`.
    Typed(RecordType),
}

/// Build the production A/AAAA backend — captures the upstream addr,
/// timeout, and trust anchors and dispatches each call onto the current
/// tokio runtime via `Handle::block_on`.
///
/// On the first invocation, captures `tokio::runtime::Handle::current()`.
/// Production call sites are inside the proxy thread which runs after
/// the supervisor's tokio runtime is alive; the handle resolution
/// succeeds. If somehow called outside a runtime (programming error),
/// the backend returns an `io::Error` — the validator maps that to
/// `Failed { reason: "validation_failed" }`, fail-closed.
fn build_hickory_backend(
    upstream: SocketAddr,
    timeout: Duration,
    anchors: Arc<TrustAnchors>,
) -> Arc<DataplaneDnssecBackend> {
    Arc::new(move |hostname: &str, _qtype: u16| {
        let handle = tokio::runtime::Handle::try_current().map_err(|e| {
            std::io::Error::other(format!(
                "dns_proxy::dnssec backend: no tokio runtime in scope: {e}"
            ))
        })?;
        let anchors = anchors.clone();
        let hostname = hostname.to_string();
        let result = handle.block_on(async move {
            crate::resolver_refresh::resolve_with_ttl_validated(
                &hostname, upstream, timeout, &anchors,
            )
            .await
        })?;
        Ok(result.validation)
    })
}

/// A2 — build the production typed-record backend for
/// CNAME / HTTPS / SVCB / MX / TXT validation.
///
/// Mirrors [`build_hickory_backend`]'s shape (capture addr/timeout/anchors,
/// dispatch onto current tokio runtime) but uses hickory's generic
/// `Resolver::lookup(name, RecordType)` API rather than `lookup_ip`.
fn build_hickory_typed_backend(
    upstream: SocketAddr,
    timeout: Duration,
    anchors: Arc<TrustAnchors>,
) -> Arc<DataplaneTypedDnssecBackend> {
    Arc::new(move |hostname: &str, record_type: RecordType| {
        let handle = tokio::runtime::Handle::try_current().map_err(|e| {
            std::io::Error::other(format!(
                "dns_proxy::dnssec typed_backend: no tokio runtime in scope: {e}"
            ))
        })?;
        let anchors = anchors.clone();
        let hostname = hostname.to_string();
        handle.block_on(async move {
            resolve_typed_validated(&hostname, record_type, upstream, timeout, &anchors).await
        })
    })
}

/// A2 — async typed-record validating resolution helper.
///
/// Builds a fresh validating resolver per call (the same pattern
/// [`crate::resolver_refresh::resolve_with_ttl_validated`] uses for
/// A/AAAA) and issues a generic `lookup(name, record_type)`. Walks the
/// answer records' per-record [`Proof`] to derive the worst-case
/// verdict, then maps to [`DnssecValidationResult`] via the same
/// [`proof_to_validation_result_with_rrsig`] mapper.
///
/// Returns:
/// - `Ok(DnssecValidationResult::Validated { .. })` when every record
///   in the answer set proved Secure. RRSIG metadata is extracted via
///   [`extract_rrsig_metadata`] when present; the documented placeholder
///   (`algorithm: "unknown"`, `key_tag: 0`) is stamped otherwise.
/// - `Ok(DnssecValidationResult::Unsigned)` when at least one record
///   was Insecure (and none Bogus or Indeterminate).
/// - `Ok(DnssecValidationResult::Failed { reason })` when any record
///   was Bogus or Indeterminate (the "validator did not say Secure"
///   axis). Maps Bogus → `validation_failed`, Indeterminate →
///   `validation_indeterminate` per the canonical mapper.
/// - `Err(io::Error)` for transport-class failures (timeout, SERVFAIL,
///   network unreachable). The validator's call-site fail-safes any
///   I/O error to `Failed { reason: "validation_failed" }`.
///
/// NXDOMAIN / NOERROR-empty: a query with no answers comes back as
/// `Failed { reason: "validation_indeterminate" }` because
/// [`worst_proof_local`] returns `Indeterminate` for an empty record
/// set. Fail-safe per the require-mode contract — an unanswerable
/// query is not a chain-of-trust establishment.
async fn resolve_typed_validated(
    hostname: &str,
    record_type: RecordType,
    upstream: SocketAddr,
    timeout: Duration,
    trust_anchors: &TrustAnchors,
) -> std::io::Result<DnssecValidationResult> {
    let mut config = ResolverConfig::from_parts(None, Vec::new(), Vec::new());
    config.add_name_server(build_typed_nameserver_config(upstream));

    let mut opts = ResolverOpts::default();
    opts.cache_size = 0;
    opts.attempts = 1;
    opts.timeout = timeout;
    opts.use_hosts_file = ResolveHosts::Never;
    opts.edns0 = false;
    opts.validate = true;

    if let Some(path) = trust_anchors.path() {
        opts.trust_anchor = Some(PathBuf::from(path));
    }

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

    if let Some(path) = trust_anchors.path() {
        match hickory_proto::dnssec::TrustAnchors::from_file(path) {
            Ok(loaded) => {
                builder = builder.with_trust_anchor(std::sync::Arc::new(loaded));
            }
            Err(e) => {
                return Err(std::io::Error::other(format!(
                    "dns_proxy::dnssec typed_backend: trust anchor parse failed for {}: {e}",
                    path.display()
                )));
            }
        }
    }

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

    let work = async {
        let lookup_result = resolver.lookup(hostname, record_type).await;
        let lookup = match lookup_result {
            Ok(l) => l,
            Err(e) => {
                if let Some(rc) = no_records_response_code(&e) {
                    if matches!(rc, ResponseCode::NXDomain | ResponseCode::NoError) {
                        return Ok(DnssecValidationResult::Failed {
                            reason: "validation_indeterminate".to_string(),
                        });
                    }
                }
                return Err(map_typed_net_error(e));
            }
        };

        let answers = lookup.answers();
        let proof = worst_proof_local(answers);
        let rrsig_metadata = extract_rrsig_metadata(answers, &[record_type]);
        Ok(proof_to_validation_result_with_rrsig(proof, rrsig_metadata))
    };

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

/// A2 — build a `NameServerConfig` for the typed-record validating
/// resolver. Local copy because the helper in `hickory_resolve.rs` is
/// private to the resolver_refresh module.
fn build_typed_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])
}

/// A2 — local copy of `worst_proof` from `hickory_resolve.rs` (private
/// there). Combines per-record `Proof` flags into a single outcome
/// using the same conservative ordering: any `Bogus` poisons the set,
/// then `Indeterminate`, then `Insecure`; only when every record is
/// `Secure` does the set come back `Secure`. An empty answer set
/// returns `Indeterminate`.
fn worst_proof_local(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 {
        Proof::Indeterminate
    }
}

/// A2 — local copy of `no_records_response_code` from `hickory_resolve.rs`.
fn no_records_response_code(e: &NetError) -> Option<ResponseCode> {
    match e {
        NetError::Dns(DnsError::NoRecordsFound(no_records)) => Some(no_records.response_code),
        _ => None,
    }
}

/// A2 — local copy of `map_net_error` from `hickory_resolve.rs`.
fn map_typed_net_error(e: NetError) -> std::io::Error {
    let kind = match &e {
        NetError::Timeout => std::io::ErrorKind::TimedOut,
        NetError::Io(io_err) => io_err.kind(),
        _ => std::io::ErrorKind::Other,
    };
    std::io::Error::new(
        kind,
        format!("dns_proxy::dnssec typed_backend: hickory-resolver error: {e}"),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resolver_refresh::ENV_TRUST_ANCHORS_PATH;
    use cellos_core::{DnsResolver, DnsResolverDnssecPolicy, DnsResolverProtocol};
    use tempfile::tempdir;

    /// T2-5 — Per-test env-var guard.
    ///
    /// `TrustAnchors::load` (the loader behind `from_authority` below)
    /// gives `CELLOS_DNSSEC_TRUST_ANCHORS_PATH` precedence over the spec
    /// path. Under `cargo test` with `--test-threads >= 2`, a *different*
    /// test in the same process — e.g.
    /// `resolver_refresh::dnssec::tests::loads_path_with_o_nofollow_unix`
    /// — can `set_var` the env var while one of these path-rejection
    /// tests is mid-flight. `std::env::set_var` is process-global, so
    /// the dns_proxy test then sees a *valid* env-supplied trust-anchor
    /// path, `from_authority` succeeds, and the rejection assertion
    /// fails. That is the race the cleanup-bundle-v1 / T2-5 entry calls
    /// out as the "shared-tempdir" symptom.
    ///
    /// Mirrors the `EnvGuard` pattern in
    /// `crate::resolver_refresh::dnssec::tests`: clear on construction,
    /// restore on drop. Tests that route through `from_authority` MUST
    /// hold one of these for the duration of the assertion.
    struct EnvGuard {
        prior: Option<String>,
    }
    impl EnvGuard {
        fn new() -> Self {
            let prior = std::env::var(ENV_TRUST_ANCHORS_PATH).ok();
            std::env::remove_var(ENV_TRUST_ANCHORS_PATH);
            Self { prior }
        }
    }
    impl Drop for EnvGuard {
        fn drop(&mut self) {
            match self.prior.take() {
                Some(v) => std::env::set_var(ENV_TRUST_ANCHORS_PATH, v),
                None => std::env::remove_var(ENV_TRUST_ANCHORS_PATH),
            }
        }
    }

    fn authority_with_resolver(resolver: DnsResolver) -> DnsAuthority {
        DnsAuthority {
            resolvers: vec![resolver],
            ..Default::default()
        }
    }

    fn make_resolver(dnssec: Option<DnsResolverDnssecPolicy>) -> DnsResolver {
        DnsResolver {
            resolver_id: "test-resolver".into(),
            endpoint: "127.0.0.1:53".into(),
            protocol: DnsResolverProtocol::Do53Udp,
            trust_kid: None,
            dnssec,
        }
    }

    /// ISC-21 / ISC-40 — `from_authority` returns `Ok(None)` when the
    /// authority has no DNSSEC block on the first resolver (mode = off).
    /// The proxy's hot path must remain byte-identical to pre-P3h.1 in
    /// this case.
    #[test]
    fn from_authority_returns_none_when_dnssec_block_absent() {
        let auth = authority_with_resolver(make_resolver(None));
        let v = DataplaneDnssecValidator::from_authority(&auth).expect("ok");
        assert!(
            v.is_none(),
            "mode=off (no dnssec block) MUST yield None so proxy hot path is unchanged"
        );
    }

    /// ISC-22 — `from_authority` returns `Ok(None)` when `validate=false`
    /// even if the dnssec block is present. The block is informational
    /// only in that case.
    #[test]
    fn from_authority_returns_none_when_validate_false() {
        let auth = authority_with_resolver(make_resolver(Some(DnsResolverDnssecPolicy {
            validate: false,
            fail_closed: false,
            trust_anchors_path: None,
        })));
        let v = DataplaneDnssecValidator::from_authority(&auth).expect("ok");
        assert!(
            v.is_none(),
            "validate=false MUST yield None — the block is observational only"
        );
    }

    /// `from_authority` returns `Ok(None)` when the authority has zero
    /// resolvers. Defensive — the supervisor production path always has
    /// at least one resolver, but the validator must not panic on the
    /// empty-resolvers shape.
    #[test]
    fn from_authority_returns_none_when_no_resolvers() {
        let auth = DnsAuthority::default();
        let v = DataplaneDnssecValidator::from_authority(&auth).expect("ok");
        assert!(v.is_none(), "no resolvers MUST yield None");
    }

    /// ISC-23 / ISC-41 — `from_authority` returns `Ok(Some)` when the
    /// first resolver requests require mode (validate=true,
    /// fail_closed=true) with bundled IANA anchors (no
    /// trust_anchors_path override).
    #[test]
    fn from_authority_returns_some_for_require_with_iana_defaults() {
        // T2-5: assertion depends on the env var being unset (env path
        // would supersede the `trust_anchors_path: None` spec and yield
        // a non-IANA source).
        let _guard = EnvGuard::new();
        let auth = authority_with_resolver(make_resolver(Some(DnsResolverDnssecPolicy {
            validate: true,
            fail_closed: true,
            trust_anchors_path: None,
        })));
        let v = DataplaneDnssecValidator::from_authority(&auth)
            .expect("ok")
            .expect("Some");
        assert!(v.is_require_mode(), "fail_closed=true → require");
        assert_eq!(
            v.trust_anchor_source(),
            "iana-default",
            "no path override → bundled IANA defaults"
        );
    }

    /// ISC-24 — `from_authority` returns `Ok(Some)` for best_effort
    /// (validate=true, fail_closed=false). `is_require_mode` returns
    /// false.
    #[test]
    fn from_authority_returns_some_for_best_effort() {
        let auth = authority_with_resolver(make_resolver(Some(DnsResolverDnssecPolicy {
            validate: true,
            fail_closed: false,
            trust_anchors_path: None,
        })));
        let v = DataplaneDnssecValidator::from_authority(&auth)
            .expect("ok")
            .expect("Some");
        assert!(!v.is_require_mode(), "fail_closed=false → best_effort");
    }

    /// ISC-25 / ISC-42 — `from_authority` rejects an unreadable
    /// trust-anchor path. The validator MUST surface
    /// CellosError::InvalidSpec rather than constructing a
    /// half-broken validator that would silently fail every query.
    #[test]
    fn from_authority_rejects_missing_trust_anchor_path() {
        // T2-5: this test was flaking under `cargo test --test-threads >=2`.
        // Root cause: `TrustAnchors::load` gives the
        // `CELLOS_DNSSEC_TRUST_ANCHORS_PATH` env var precedence over the
        // spec path; a sibling test in `resolver_refresh::dnssec::tests`
        // (`loads_path_with_o_nofollow_unix`) sets that env var to point
        // at *its own* tempdir, and if it ran between this test's
        // `tempdir()` and the `from_authority` call the bogus spec was
        // silently superseded by the sibling's valid path → assertion
        // failed. The `EnvGuard` clears + restores the env var so this
        // test's spec is the only signal that reaches the loader.
        // tempdirs themselves are already per-test (`tempfile::tempdir`
        // hands each caller a uniquely-named directory).
        let _guard = EnvGuard::new();
        let dir = tempdir().expect("tempdir");
        let bogus = dir.path().join("does-not-exist.bin");
        let auth = authority_with_resolver(make_resolver(Some(DnsResolverDnssecPolicy {
            validate: true,
            fail_closed: true,
            trust_anchors_path: Some(bogus.to_string_lossy().into_owned()),
        })));
        let err = DataplaneDnssecValidator::from_authority(&auth)
            .expect_err("missing trust-anchor path MUST be rejected at activation");
        let msg = format!("{err}");
        assert!(
            msg.contains("trust anchors") && msg.contains("does-not-exist.bin"),
            "rejection must mention the path for operator triage; got {msg}"
        );
    }

    /// ISC-26 / ISC-43 — `from_authority` rejects a symlinked
    /// trust-anchor path (mirrors the W6 SEC-25 / P3h discipline —
    /// O_NOFOLLOW refuses to follow a swapped-in symlink at the final
    /// path component).
    #[cfg(unix)]
    #[test]
    fn from_authority_rejects_symlinked_trust_anchor_path() {
        // T2-5: same env-var race as
        // `from_authority_rejects_missing_trust_anchor_path` above —
        // see that test's comment for the full root-cause writeup.
        let _guard = EnvGuard::new();
        let dir = tempdir().expect("tempdir");
        let real = dir.path().join("real-anchor.bin");
        let link = dir.path().join("symlinked-anchor.bin");
        std::fs::write(&real, b"REAL-KEY-BYTES").expect("write real anchor");
        std::os::unix::fs::symlink(&real, &link).expect("create symlink");

        let auth = authority_with_resolver(make_resolver(Some(DnsResolverDnssecPolicy {
            validate: true,
            fail_closed: true,
            trust_anchors_path: Some(link.to_string_lossy().into_owned()),
        })));
        let err = DataplaneDnssecValidator::from_authority(&auth)
            .expect_err("symlinked trust-anchor path MUST be rejected by O_NOFOLLOW");
        let msg = format!("{err}");
        assert!(
            msg.contains(link.to_str().unwrap()),
            "rejection must include the symlinked path; got {msg}"
        );
    }

    /// `from_authority` rejects an unparseable resolver endpoint. The
    /// supervisor production path puts a valid `host:port` in the
    /// endpoint, but the validator must not panic on garbage input.
    #[test]
    fn from_authority_rejects_unparseable_endpoint() {
        let mut resolver = make_resolver(Some(DnsResolverDnssecPolicy {
            validate: true,
            fail_closed: true,
            trust_anchors_path: None,
        }));
        resolver.endpoint = "not-a-socket-addr".into();
        let auth = authority_with_resolver(resolver);
        let err = DataplaneDnssecValidator::from_authority(&auth)
            .expect_err("unparseable endpoint MUST be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("resolver.endpoint"),
            "rejection must reference the field for operator triage; got {msg}"
        );
    }

    /// `validate()` returns `Skip` for a TXT query (qtype=16) — the
    /// validator only handles A/AAAA today. The proxy's call-site
    /// policy decides what to do (forward in best_effort, SERVFAIL in
    /// require).
    #[test]
    fn validate_returns_skip_for_non_a_aaaa_qtype() {
        let backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| panic!("backend MUST NOT be called for non-A/AAAA"));
        let v = DataplaneDnssecValidator::with_backend(true, "iana-default".into(), backend);
        let q = build_query("api.example.com", 16); // TXT
        let outcome = v.validate(&q, &[]);
        assert!(
            matches!(outcome, DataplaneDnssecOutcome::Skip),
            "TXT must Skip; got {outcome:?}"
        );
    }

    /// `validate()` maps `Validated` → `Validated`.
    #[test]
    fn validate_maps_validated_outcome() {
        let backend: Arc<DataplaneDnssecBackend> = Arc::new(|_h, _t| {
            Ok(DnssecValidationResult::Validated {
                algorithm: "RSASHA256".into(),
                key_tag: 12345,
            })
        });
        let v = DataplaneDnssecValidator::with_backend(false, "iana-default".into(), backend);
        let q = build_query("api.example.com", 1); // A
        assert!(matches!(
            v.validate(&q, &[]),
            DataplaneDnssecOutcome::Validated
        ));
    }

    /// `validate()` maps `Unsigned` → `Unsigned`.
    #[test]
    fn validate_maps_unsigned_outcome() {
        let backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| Ok(DnssecValidationResult::Unsigned));
        let v = DataplaneDnssecValidator::with_backend(false, "iana-default".into(), backend);
        let q = build_query("api.example.com", 1);
        assert!(matches!(
            v.validate(&q, &[]),
            DataplaneDnssecOutcome::Unsigned
        ));
    }

    /// `validate()` maps `Failed{..}` → `Failed{reason:"validation_failed"}`.
    #[test]
    fn validate_maps_failed_outcome() {
        let backend: Arc<DataplaneDnssecBackend> = Arc::new(|_h, _t| {
            Ok(DnssecValidationResult::Failed {
                reason: "synthetic".into(),
            })
        });
        let v = DataplaneDnssecValidator::with_backend(true, "iana-default".into(), backend);
        let q = build_query("api.example.com", 1);
        let outcome = v.validate(&q, &[]);
        assert!(
            matches!(outcome, DataplaneDnssecOutcome::Failed { reason } if reason == "validation_failed"),
            "Failed must map to validation_failed; got {outcome:?}"
        );
    }

    /// `validate()` fails closed when the backend returns an I/O error
    /// (timeout, transport). The require-mode contract demands no
    /// unvalidated answer ever reaches the workload.
    #[test]
    fn validate_fails_closed_on_backend_io_error() {
        let backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| Err(std::io::Error::other("synthetic-transport-failure")));
        let v = DataplaneDnssecValidator::with_backend(true, "iana-default".into(), backend);
        let q = build_query("api.example.com", 1);
        let outcome = v.validate(&q, &[]);
        assert!(
            matches!(outcome, DataplaneDnssecOutcome::Failed { .. }),
            "I/O error MUST fail closed; got {outcome:?}"
        );
    }

    /// `validate()` returns `Skip` for a malformed query. Defensive —
    /// the proxy already drops malformed packets before calling us, but
    /// the validator must not panic.
    #[test]
    fn validate_returns_skip_for_malformed_query() {
        let backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| panic!("backend MUST NOT be called for malformed query"));
        let v = DataplaneDnssecValidator::with_backend(false, "iana-default".into(), backend);
        let outcome = v.validate(&[0u8; 4], &[]); // < 12-byte header
        assert!(matches!(outcome, DataplaneDnssecOutcome::Skip));
    }

    /// Builds a minimal DNS query packet for tests — same shape as the
    /// proxy module's existing `build_query_packet` helper but local
    /// here so the validator's tests are self-contained.
    fn build_query(qname: &str, qtype: u16) -> Vec<u8> {
        let mut p = Vec::new();
        p.extend_from_slice(&[
            0xab, 0xcd, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ]);
        for label in qname.split('.') {
            p.push(label.len() as u8);
            p.extend_from_slice(label.as_bytes());
        }
        p.push(0);
        p.extend_from_slice(&qtype.to_be_bytes());
        p.extend_from_slice(&[0x00, 0x01]);
        p
    }

    // ========================================================================
    // A2 — typed-record validation unit tests
    // ========================================================================
    //
    // These tests exercise `validate()`'s post-A2 dispatch shape: when the
    // validator was built via `with_backends(_, _, backend, typed_backend)`,
    // queries for CNAME/HTTPS/SVCB/MX/TXT route to `typed_backend` and
    // produce typed `Validated/Unsigned/Failed` outcomes instead of `Skip`.
    //
    // The legacy `with_backend` (no typed backend) shape is exercised by
    // `validate_returns_skip_for_non_a_aaaa_qtype` above — TXT continues
    // to Skip when no typed backend is wired, preserving backward
    // compatibility for tests/operators who only configured A/AAAA.

    /// A2 — `validate()` dispatches CNAME (qtype=5) to the typed backend
    /// and maps `Validated → Validated`. The legacy A/AAAA backend MUST
    /// NOT be called.
    #[test]
    fn validate_routes_cname_to_typed_backend() {
        let aaaa_backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| panic!("A/AAAA backend MUST NOT be called for CNAME"));
        let typed_backend: Arc<DataplaneTypedDnssecBackend> = Arc::new(|_h, rt| {
            assert_eq!(rt, RecordType::CNAME, "typed backend MUST receive CNAME");
            Ok(DnssecValidationResult::Validated {
                algorithm: "RSASHA256".into(),
                key_tag: 12345,
            })
        });
        let v = DataplaneDnssecValidator::with_backends(
            true,
            "iana-default".into(),
            aaaa_backend,
            typed_backend,
        );
        let q = build_query("api.example.com", 5); // CNAME
        assert!(matches!(
            v.validate(&q, &[]),
            DataplaneDnssecOutcome::Validated
        ));
    }

    /// A2 — `validate()` dispatches HTTPS (qtype=65) to the typed backend
    /// and maps `Unsigned → Unsigned`.
    #[test]
    fn validate_routes_https_to_typed_backend_unsigned() {
        let aaaa_backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| panic!("A/AAAA backend MUST NOT be called for HTTPS"));
        let typed_backend: Arc<DataplaneTypedDnssecBackend> = Arc::new(|_h, rt| {
            assert_eq!(rt, RecordType::HTTPS, "typed backend MUST receive HTTPS");
            Ok(DnssecValidationResult::Unsigned)
        });
        let v = DataplaneDnssecValidator::with_backends(
            false,
            "iana-default".into(),
            aaaa_backend,
            typed_backend,
        );
        let q = build_query("api.example.com", 65); // HTTPS
        assert!(matches!(
            v.validate(&q, &[]),
            DataplaneDnssecOutcome::Unsigned
        ));
    }

    /// A2 — `validate()` dispatches SVCB (qtype=64) to the typed backend
    /// and maps `Failed → Failed{validation_failed}`.
    #[test]
    fn validate_routes_svcb_to_typed_backend_failed() {
        let aaaa_backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| panic!("A/AAAA backend MUST NOT be called for SVCB"));
        let typed_backend: Arc<DataplaneTypedDnssecBackend> = Arc::new(|_h, rt| {
            assert_eq!(rt, RecordType::SVCB, "typed backend MUST receive SVCB");
            Ok(DnssecValidationResult::Failed {
                reason: "synthetic-bogus".into(),
            })
        });
        let v = DataplaneDnssecValidator::with_backends(
            true,
            "iana-default".into(),
            aaaa_backend,
            typed_backend,
        );
        let q = build_query("api.example.com", 64); // SVCB
        let outcome = v.validate(&q, &[]);
        assert!(
            matches!(outcome, DataplaneDnssecOutcome::Failed { reason } if reason == "validation_failed"),
            "SVCB Failed → validation_failed; got {outcome:?}"
        );
    }

    /// A2 — `validate()` dispatches MX (qtype=15) to the typed backend
    /// and fails closed when the backend returns an I/O error. Mirrors
    /// the existing A/AAAA fail-closed contract.
    #[test]
    fn validate_routes_mx_to_typed_backend_io_error_fails_closed() {
        let aaaa_backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| panic!("A/AAAA backend MUST NOT be called for MX"));
        let typed_backend: Arc<DataplaneTypedDnssecBackend> = Arc::new(|_h, rt| {
            assert_eq!(rt, RecordType::MX, "typed backend MUST receive MX");
            Err(std::io::Error::other("synthetic-transport-failure"))
        });
        let v = DataplaneDnssecValidator::with_backends(
            true,
            "iana-default".into(),
            aaaa_backend,
            typed_backend,
        );
        let q = build_query("mail.example.com", 15); // MX
        let outcome = v.validate(&q, &[]);
        assert!(
            matches!(outcome, DataplaneDnssecOutcome::Failed { reason } if reason == "validation_failed"),
            "MX I/O error MUST fail closed; got {outcome:?}"
        );
    }

    /// A2 — `validate()` dispatches TXT (qtype=16) to the typed backend
    /// when one is wired. Confirms that the legacy
    /// `validate_returns_skip_for_non_a_aaaa_qtype` Skip behaviour was
    /// the consequence of the test using the no-typed-backend constructor,
    /// not a hardcoded TXT skip.
    #[test]
    fn validate_routes_txt_to_typed_backend_validated() {
        let aaaa_backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| panic!("A/AAAA backend MUST NOT be called for TXT"));
        let typed_backend: Arc<DataplaneTypedDnssecBackend> = Arc::new(|_h, rt| {
            assert_eq!(rt, RecordType::TXT, "typed backend MUST receive TXT");
            Ok(DnssecValidationResult::Validated {
                algorithm: "ED25519".into(),
                key_tag: 60_999,
            })
        });
        let v = DataplaneDnssecValidator::with_backends(
            true,
            "iana-default".into(),
            aaaa_backend,
            typed_backend,
        );
        let q = build_query("api.example.com", 16); // TXT
        assert!(matches!(
            v.validate(&q, &[]),
            DataplaneDnssecOutcome::Validated
        ));
    }

    /// A2 — `validate()` continues to `Skip` for query types outside the
    /// first-class set (NS, PTR, SRV, etc.) even when both backends are
    /// wired. The first-class set is bounded; residuals stay on the
    /// pre-A2 Skip path.
    #[test]
    fn validate_skips_residual_types_even_with_typed_backend() {
        let aaaa_backend: Arc<DataplaneDnssecBackend> =
            Arc::new(|_h, _t| panic!("A/AAAA backend MUST NOT be called for NS"));
        let typed_backend: Arc<DataplaneTypedDnssecBackend> =
            Arc::new(|_h, _rt| panic!("typed backend MUST NOT be called for NS"));
        let v = DataplaneDnssecValidator::with_backends(
            true,
            "iana-default".into(),
            aaaa_backend,
            typed_backend,
        );
        let q = build_query("ns1.example.com", 2); // NS — outside first-class set
        assert!(
            matches!(v.validate(&q, &[]), DataplaneDnssecOutcome::Skip),
            "NS (qtype=2) MUST Skip even when typed backend is wired"
        );
    }

    /// A2 — `from_authority` populates BOTH backends so the production
    /// validator covers all seven first-class types end-to-end. We can't
    /// observe the backend Arc directly through the public API, but the
    /// debug impl exposes whether `typed_backend` is `Some` — assert the
    /// shape via the rendered debug string.
    #[test]
    fn from_authority_populates_typed_backend_in_require_mode() {
        let auth = authority_with_resolver(make_resolver(Some(DnsResolverDnssecPolicy {
            validate: true,
            fail_closed: true,
            trust_anchors_path: None,
        })));
        let v = DataplaneDnssecValidator::from_authority(&auth)
            .expect("ok")
            .expect("Some");
        let dbg = format!("{v:?}");
        assert!(
            dbg.contains("typed_backend: Some"),
            "from_authority MUST populate typed_backend so post-A2 validators \
             validate CNAME/HTTPS/SVCB/MX/TXT end-to-end; got {dbg}"
        );
    }
}