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
//! Minimal DNS message parser scoped to what the SEAM-1 / L2-04 proxy needs.
//!
//! Pure logic, no I/O. The proxy parses the wire-format query, makes an
//! allowlist decision against [`crate::dns_proxy::DnsProxyConfig::hostname_allowlist`],
//! then either forwards the bytes verbatim upstream (allow path) or builds a
//! REFUSED response from the parsed view (deny path).
//!
//! ## Phase 2 scope (multi-question)
//!
//! - **Exactly one question on the hot path.** A DNS message with `QDCOUNT == 0`
//!   is rejected as malformed (nothing to evaluate). HIGH-D1 hardened the
//!   single-question API ([`parse_query`]) further: any packet declaring
//!   `QDCOUNT != 1` is rejected at the parser layer with
//!   [`DnsParseError::QdcountUnsupported`]. RFC 1035 §4.1.2 permits
//!   `QDCOUNT > 1`, but real-world recursive resolvers (Unbound, Knot, BIND)
//!   serve at most the first question and the supervisor's threat model
//!   (hostile guests) does not justify the policy-bypass / log-evasion
//!   surface that "parse first question, forward all bytes" exposes. The
//!   typed offline API [`parse_query_multi`] still returns one
//!   [`QuestionOutcome`] per declared question for tools that legitimately
//!   need to walk multi-question packets (e.g. fixture inspection).
//! - **No pointer-compression in QNAME.** RFC 1035 §4.1.4 allows a label to be
//!   replaced by a 2-byte pointer to an earlier label. Real workload-side
//!   queries almost never use compression — the questions section is the only
//!   labels the message carries — so the parser rejects pointers as a defense
//!   against malformed/adversarial inputs that could otherwise drive the
//!   parser into a cycle. Compression in *responses* is handled by passing
//!   the wire bytes through untouched on the allow path.
//! - **IN class only.** `qclass != 1` is rejected for any question.
//! - **RFC 1035 length bounds.** Labels capped at 63 octets; total QNAME
//!   capped at 253 octets (the RFC 1035 §3.1 maximum once you remove the
//!   trailing root label and the length prefixes).
//!
//! ## What the parser surfaces
//!
//! [`DnsQueryView`] carries the transaction id (echoed back in the proxy's
//! response when denying), the flags word (so the proxy can OR in QR=1 +
//! RCODE=REFUSED for the deny path), the lowercased trailing-dot-stripped
//! query name, and the raw wire-format `qtype` / `qclass` fields. The proxy
//! maps the raw `qtype` to the bounded [`cellos_core::DnsQueryType`] enum
//! via `cellos_core::qtype_to_dns_query_type`; query types outside that set
//! produce a `denied_query_type` decision rather than a parser error.

use thiserror::Error;

/// Maximum labels per RFC 1035 §3.1 (one octet length).
pub(crate) const MAX_LABEL_LEN: usize = 63;
/// Maximum total QNAME length per RFC 1035 §3.1 (sum of label lengths + dots).
pub(crate) const MAX_QNAME_LEN: usize = 253;
/// DNS message header is fixed at 12 octets per RFC 1035 §4.1.1.
pub(crate) const DNS_HEADER_LEN: usize = 12;
/// `IN` (Internet) class. The only class the parser accepts.
pub(crate) const QCLASS_IN: u16 = 1;
/// Wire-format pointer indicator: top two bits set in a label-length octet
/// signal a 2-byte compression pointer rather than a literal label.
/// We test `(b & POINTER_MASK) == POINTER_MASK` to require BOTH bits set —
/// a length octet with only the second-highest bit set (0x40-0x7f) is
/// reserved by RFC 1035 and treated as a label-overflow when the value
/// happens to exceed [`MAX_LABEL_LEN`].
const POINTER_MASK: u8 = 0b1100_0000;

/// Errors the parser can surface. Each maps to a `reasonCode` on the emitted
/// `dns_query` event:
/// - [`DnsParseError::TooShort`], [`DnsParseError::QdcountZero`],
///   [`DnsParseError::QdcountUnsupported`],
///   [`DnsParseError::LabelOverflow`], [`DnsParseError::NameOverflow`],
///   [`DnsParseError::CompressionRejected`],
///   [`DnsParseError::UnsupportedClass`],
///   [`DnsParseError::InvalidLabelByte`] → `malformed_query`
///   (proxy drops the packet — no response — matching common resolver
///   behaviour against malformed input).
#[derive(Debug, Error, PartialEq, Eq)]
pub enum DnsParseError {
    /// Packet smaller than the 12-byte header or truncated mid-question.
    #[error("dns packet too short")]
    TooShort,
    /// Header `QDCOUNT` field was `0`. A query with no questions is malformed —
    /// there is nothing to evaluate against the allowlist. The
    /// `T2.B` multi-question expansion accepts `QDCOUNT >= 1`; only the
    /// degenerate zero case is now refused at the parser layer.
    #[error("dns QDCOUNT must be at least 1, got 0")]
    QdcountZero,
    /// Header `QDCOUNT` was greater than 1 on the hot-path single-question
    /// API. HIGH-D1 closed the policy-bypass / log-evasion gap that arose
    /// from "parse FIRST question, forward all bytes verbatim": a hostile
    /// guest could craft a `[allowed.example.com, attacker.tld]` packet,
    /// pass the allowlist on Q1, and have Q2 silently resolved by the
    /// upstream resolver. The supervisor's contract is one allow-listed
    /// query in, one logged event out — so the parser now refuses any
    /// `QDCOUNT != 1` on the proxy path. Tools that need multi-question
    /// inspection should use [`parse_query_multi`].
    #[error("dns QDCOUNT must be exactly 1 on the proxy path, got {0}")]
    QdcountUnsupported(u16),
    /// A QNAME label exceeded the RFC 1035 63-octet maximum.
    #[error("dns label exceeds 63 octets")]
    LabelOverflow,
    /// Total QNAME length exceeded the RFC 1035 253-octet maximum.
    #[error("dns QNAME exceeds 253 octets")]
    NameOverflow,
    /// Encountered a pointer-compressed label in a query QNAME — the parser
    /// rejects these as a defense against adversarial inputs.
    #[error("dns QNAME pointer-compression rejected")]
    CompressionRejected,
    /// `qclass` was not `IN` (1). The parser only forwards Internet-class queries.
    #[error("dns qclass {0} not supported (only IN/1)")]
    UnsupportedClass(u16),
    /// Label byte fell outside RFC 1035's preferred ASCII set.
    #[error("dns label contains invalid byte 0x{0:02x}")]
    InvalidLabelByte(u8),
}

/// Minimal view of a parsed single-question DNS query.
///
/// The proxy uses [`Self::txn_id`] + [`Self::flags`] to construct deny / SERVFAIL
/// responses without re-parsing the question section. [`Self::qname`] is
/// already lowercased and trailing-dot-stripped so allowlist comparison is a
/// straight `eq_ignore_ascii_case` (or wildcard suffix match).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DnsQueryView {
    /// 16-bit DNS transaction id from the message header. Echoed back to the
    /// workload in any response the proxy emits.
    pub txn_id: u16,
    /// Raw flags word from the header. The proxy uses this to derive the
    /// response flags (set QR=1, copy RD, set RA=0, write the new RCODE).
    pub flags: u16,
    /// Lowercased, trailing-dot-stripped query name.
    pub qname: String,
    /// Raw 16-bit `qtype` field. Map via
    /// [`cellos_core::qtype_to_dns_query_type`] before allowlist evaluation.
    pub qtype: u16,
    /// Raw 16-bit `qclass` field. The parser only ever surfaces `IN` (1) here —
    /// other classes return [`DnsParseError::UnsupportedClass`] before this
    /// view is built.
    pub qclass: u16,
}

/// Per-question outcome returned by [`parse_query_multi`].
///
/// Today this only carries the [`Self::Parsed`] variant; the enum exists (and
/// is `#[non_exhaustive]`) so future extensions — e.g. a per-question soft
/// failure that does not abort the whole packet — can land additively without
/// breaking call sites that pattern-match on the variant. Callers should reach
/// for [`Self::as_view`] rather than destructuring directly when they only
/// need the underlying [`DnsQueryView`].
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QuestionOutcome {
    /// The question was parsed cleanly into a [`DnsQueryView`].
    Parsed(DnsQueryView),
}

impl QuestionOutcome {
    /// Borrow the underlying [`DnsQueryView`] when the outcome is
    /// [`Self::Parsed`]. Returns `None` for any future variant that does not
    /// carry a parsed view (currently unreachable, but kept honest by the
    /// `#[non_exhaustive]` marker).
    pub fn as_view(&self) -> Option<&DnsQueryView> {
        match self {
            QuestionOutcome::Parsed(v) => Some(v),
        }
    }
}

/// Parse the question section of a workload DNS query (single-question API).
///
/// Returns a [`DnsQueryView`] over the sole question on success, or a
/// [`DnsParseError`] describing why the packet is rejected.
///
/// HIGH-D1 hardened this entry point: any packet declaring `QDCOUNT != 1`
/// is now rejected with [`DnsParseError::QdcountZero`] (for `QDCOUNT == 0`)
/// or [`DnsParseError::QdcountUnsupported`] (for `QDCOUNT > 1`). The
/// previous behaviour — "parse FIRST question, leave trailing questions
/// to be forwarded verbatim" — created a policy-bypass / log-evasion
/// vector where a hostile guest could ride one allowlisted question on the
/// front of a multi-question packet and have the upstream resolver answer
/// the rest. RFC 1035 §4.1.2 permits `QDCOUNT > 1` but every modern
/// recursive resolver (Unbound, Knot, BIND) services only the first
/// question on UDP, so refusing here costs nothing in real-world
/// compatibility while closing the bypass. Tools that legitimately need
/// to inspect every declared question (offline fixture inspection, etc.)
/// should reach for [`parse_query_multi`] instead.
///
/// On error, callers should drop the packet (no response) and emit a
/// `dns_query` event with `reasonCode: malformed_query`.
pub fn parse_query(packet: &[u8]) -> Result<DnsQueryView, DnsParseError> {
    if packet.len() < DNS_HEADER_LEN {
        return Err(DnsParseError::TooShort);
    }
    let txn_id = u16::from_be_bytes([packet[0], packet[1]]);
    let flags = u16::from_be_bytes([packet[2], packet[3]]);
    let qdcount = u16::from_be_bytes([packet[4], packet[5]]);
    if qdcount == 0 {
        return Err(DnsParseError::QdcountZero);
    }
    if qdcount != 1 {
        // HIGH-D1: refuse multi-question packets on the hot path. See the
        // `QdcountUnsupported` doc comment for the threat model.
        return Err(DnsParseError::QdcountUnsupported(qdcount));
    }

    let (view, _next) = parse_one_question(packet, DNS_HEADER_LEN, txn_id, flags)?;
    Ok(view)
}

/// Parse every question declared by `QDCOUNT` and return one
/// [`QuestionOutcome`] per question.
///
/// `QDCOUNT == 0` is rejected with [`DnsParseError::QdcountZero`]; any
/// per-question parse failure (truncation, label overflow, unsupported class,
/// etc.) aborts the whole walk and surfaces the error — partial outcomes are
/// not returned. This matches the single-question API's "drop on malformed"
/// stance: a multi-question packet with one bad question is treated as
/// malformed in its entirety.
///
/// The single-question API ([`parse_query`]) and this multi-question API are
/// equivalent on a packet with exactly one question: both surface the same
/// [`DnsQueryView`] for that question.
pub fn parse_query_multi(packet: &[u8]) -> Result<Vec<QuestionOutcome>, DnsParseError> {
    if packet.len() < DNS_HEADER_LEN {
        return Err(DnsParseError::TooShort);
    }
    let txn_id = u16::from_be_bytes([packet[0], packet[1]]);
    let flags = u16::from_be_bytes([packet[2], packet[3]]);
    let qdcount = u16::from_be_bytes([packet[4], packet[5]]);
    if qdcount == 0 {
        return Err(DnsParseError::QdcountZero);
    }

    let mut outcomes = Vec::with_capacity(qdcount as usize);
    let mut idx = DNS_HEADER_LEN;
    for _ in 0..qdcount {
        let (view, next) = parse_one_question(packet, idx, txn_id, flags)?;
        outcomes.push(QuestionOutcome::Parsed(view));
        idx = next;
    }
    Ok(outcomes)
}

/// Parse exactly one question starting at `start`.
///
/// Returns the [`DnsQueryView`] for the question and the byte offset of the
/// first byte AFTER the question's `qclass` field — i.e. the start offset of
/// the next question (or of the answer/authority/additional sections, when
/// the parser is invoked on a response packet, which the proxy never does).
///
/// `txn_id` and `flags` are header-derived and shared across all questions in
/// a single packet; the helper accepts them as parameters so it can build a
/// per-question [`DnsQueryView`] without re-reading the header on every call.
fn parse_one_question(
    packet: &[u8],
    start: usize,
    txn_id: u16,
    flags: u16,
) -> Result<(DnsQueryView, usize), DnsParseError> {
    // Walk the QNAME starting at `start`. The parser rejects pointer-compressed
    // labels — a length byte with the top two bits set is treated as a pointer
    // and refused.
    let mut idx = start;
    let mut qname = String::new();
    loop {
        if idx >= packet.len() {
            return Err(DnsParseError::TooShort);
        }
        let len_byte = packet[idx];
        if len_byte == 0 {
            // Root label terminator. Advance past it and break.
            idx += 1;
            break;
        }
        if (len_byte & POINTER_MASK) == POINTER_MASK {
            return Err(DnsParseError::CompressionRejected);
        }
        let label_len = len_byte as usize;
        if label_len > MAX_LABEL_LEN {
            return Err(DnsParseError::LabelOverflow);
        }
        idx += 1;
        if idx + label_len > packet.len() {
            return Err(DnsParseError::TooShort);
        }
        let label = &packet[idx..idx + label_len];
        for &b in label {
            // RFC 1035 preferred name syntax is letters/digits/hyphen + dot.
            // scope: accept the broader RFC 2181 set (any byte except 0
            // and the ASCII control / high-bit / unprintable ranges) and
            // lowercase ASCII A-Z so allowlist matches are case-insensitive.
            if b == 0 || !(0x20..=0x7e).contains(&b) {
                return Err(DnsParseError::InvalidLabelByte(b));
            }
        }
        if !qname.is_empty() {
            qname.push('.');
        }
        // Lowercase ASCII A-Z; non-ASCII already filtered above.
        for &b in label {
            qname.push((b as char).to_ascii_lowercase());
        }
        if qname.len() > MAX_QNAME_LEN {
            return Err(DnsParseError::NameOverflow);
        }
        idx += label_len;
    }

    // qtype + qclass: 4 octets after the QNAME.
    if idx + 4 > packet.len() {
        return Err(DnsParseError::TooShort);
    }
    let qtype = u16::from_be_bytes([packet[idx], packet[idx + 1]]);
    let qclass = u16::from_be_bytes([packet[idx + 2], packet[idx + 3]]);
    if qclass != QCLASS_IN {
        return Err(DnsParseError::UnsupportedClass(qclass));
    }
    let view = DnsQueryView {
        txn_id,
        flags,
        qname,
        qtype,
        qclass,
    };
    Ok((view, idx + 4))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Helper: build a wire-format DNS query for a single-question A record.
    fn build_query(qname: &str, qtype: u16, qclass: u16) -> Vec<u8> {
        let mut p = Vec::new();
        // header: txn_id=0x1234, flags=0x0100 (RD), QDCOUNT=1, ANCOUNT=0, NSCOUNT=0, ARCOUNT=0
        p.extend_from_slice(&[
            0x12, 0x34, 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); // root
        p.extend_from_slice(&qtype.to_be_bytes());
        p.extend_from_slice(&qclass.to_be_bytes());
        p
    }

    /// Helper: append a question (qname / qtype / qclass) to an existing packet
    /// body. Caller is responsible for fixing up `QDCOUNT` separately.
    fn append_question(p: &mut Vec<u8>, qname: &str, qtype: u16, qclass: u16) {
        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(&qclass.to_be_bytes());
    }

    /// Helper: build a wire-format DNS query containing N questions.
    fn build_multi_query(questions: &[(&str, u16, u16)]) -> Vec<u8> {
        let mut p = Vec::new();
        let qd = questions.len() as u16;
        p.extend_from_slice(&[0x12, 0x34, 0x01, 0x00]);
        p.extend_from_slice(&qd.to_be_bytes());
        p.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
        for (name, qtype, qclass) in questions {
            append_question(&mut p, name, *qtype, *qclass);
        }
        p
    }

    #[test]
    fn parses_well_formed_a_query() {
        let pkt = build_query("api.example.com", 1, 1);
        let v = parse_query(&pkt).expect("parse ok");
        assert_eq!(v.txn_id, 0x1234);
        assert_eq!(v.qname, "api.example.com");
        assert_eq!(v.qtype, 1);
        assert_eq!(v.qclass, 1);
    }

    #[test]
    fn parses_aaaa_query() {
        let pkt = build_query("ipv6.example.com", 28, 1);
        let v = parse_query(&pkt).expect("parse ok");
        assert_eq!(v.qtype, 28);
        assert_eq!(v.qname, "ipv6.example.com");
    }

    #[test]
    fn lowercases_uppercase_qname() {
        let pkt = build_query("API.Example.COM", 1, 1);
        let v = parse_query(&pkt).expect("parse ok");
        assert_eq!(v.qname, "api.example.com");
    }

    #[test]
    fn parses_https_query_type_65() {
        let pkt = build_query("svc.example.com", 65, 1);
        let v = parse_query(&pkt).expect("parse ok");
        assert_eq!(v.qtype, 65);
    }

    #[test]
    fn rejects_truncated_header() {
        let pkt = vec![0x00; 6]; // only 6 octets — half a header
        assert_eq!(parse_query(&pkt), Err(DnsParseError::TooShort));
    }

    #[test]
    fn rejects_truncated_qname() {
        // header says 1 question, but body cuts off mid-label.
        let mut pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        pkt.push(5); // claims 5-byte label
        pkt.extend_from_slice(b"abc"); // only 3 bytes provided
        assert_eq!(parse_query(&pkt), Err(DnsParseError::TooShort));
    }

    #[test]
    fn rejects_truncated_qtype_qclass() {
        // QNAME terminates but no qtype/qclass follow.
        let mut pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        pkt.push(0); // root label only
                     // missing 4 bytes of qtype+qclass
        assert_eq!(parse_query(&pkt), Err(DnsParseError::TooShort));
    }

    #[test]
    fn parse_query_rejects_qdcount_two() {
        // HIGH-D1 regression: a multi-question packet with one allowlisted
        // question (Q1) and one disallowed question (Q2) was the original
        // bypass — parse_query would surface Q1, the allowlist gate would
        // pass, and the raw bytes (Q1 + Q2) would be forwarded verbatim
        // upstream. The parser now rejects QDCOUNT != 1 outright; the hot
        // path will short-circuit on `MalformedQuery`, drop the packet,
        // and never forward it.
        let pkt = build_multi_query(&[
            ("allowed.example.com", 1, 1),
            ("attacker.tld", 1, 1), // not on any allowlist
        ]);
        assert_eq!(parse_query(&pkt), Err(DnsParseError::QdcountUnsupported(2)));
    }

    #[test]
    fn parse_query_rejects_qdcount_three() {
        // Generalisation: any QDCOUNT > 1 trips the same gate.
        let pkt = build_multi_query(&[
            ("api.example.com", 1, 1),
            ("svc.example.com", 28, 1),
            ("alt.example.com", 65, 1),
        ]);
        assert_eq!(parse_query(&pkt), Err(DnsParseError::QdcountUnsupported(3)));
    }

    #[test]
    fn parse_query_rejects_qdcount_max() {
        // u16::MAX — pathological header. The parser bails on the header
        // count before walking even the first question, so no truncation
        // error is surfaced.
        let mut pkt = vec![0x12, 0x34, 0x01, 0x00];
        pkt.extend_from_slice(&u16::MAX.to_be_bytes()); // QDCOUNT = 65535
        pkt.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
        // Append one well-formed question — irrelevant; the header gate fires first.
        append_question(&mut pkt, "api.example.com", 1, 1);
        assert_eq!(
            parse_query(&pkt),
            Err(DnsParseError::QdcountUnsupported(u16::MAX))
        );
    }

    #[test]
    fn rejects_qdcount_zero_single() {
        let pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        assert_eq!(parse_query(&pkt), Err(DnsParseError::QdcountZero));
    }

    #[test]
    fn rejects_qdcount_zero_multi() {
        // The multi-question entry point ALSO rejects QDCOUNT=0 — a packet
        // with no questions is malformed regardless of which API the caller
        // reaches for.
        let pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        assert_eq!(parse_query_multi(&pkt), Err(DnsParseError::QdcountZero));
    }

    #[test]
    fn rejects_pointer_compression() {
        // Header + label byte 0xc0 (top two bits set) → pointer.
        let mut pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        pkt.push(0xc0);
        pkt.push(0x0c); // pointer to offset 12
        pkt.extend_from_slice(&[0, 1, 0, 1]);
        assert_eq!(parse_query(&pkt), Err(DnsParseError::CompressionRejected));
    }

    #[test]
    fn rejects_oversized_label() {
        // Label length 64 — over the 63-octet RFC 1035 ceiling. The 64
        // value happens to overlap with the two top bits set in 0x40 (0b01000000)
        // so it's a length, not a pointer; we catch it via the explicit
        // `MAX_LABEL_LEN` check.
        let mut pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        pkt.push(64);
        pkt.extend(std::iter::repeat_n(b'a', 64));
        pkt.push(0);
        pkt.extend_from_slice(&[0, 1, 0, 1]);
        assert_eq!(parse_query(&pkt), Err(DnsParseError::LabelOverflow));
    }

    #[test]
    fn rejects_oversized_qname() {
        // Build a name with many 50-octet labels — once the running total
        // exceeds 253 the parser bails. Each label costs `len + 1` bytes
        // (length prefix); we stop once accumulated qname > 253.
        let mut pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        // 6 labels of 50 octets = 50*6 + 5 dots = 305 octets > 253.
        for _ in 0..6 {
            pkt.push(50);
            pkt.extend(std::iter::repeat_n(b'a', 50));
        }
        pkt.push(0);
        pkt.extend_from_slice(&[0, 1, 0, 1]);
        assert_eq!(parse_query(&pkt), Err(DnsParseError::NameOverflow));
    }

    #[test]
    fn rejects_non_in_class() {
        // qclass=3 (CHAOS) — only IN is accepted.
        let pkt = build_query("api.example.com", 1, 3);
        assert_eq!(parse_query(&pkt), Err(DnsParseError::UnsupportedClass(3)));
    }

    #[test]
    fn rejects_invalid_label_byte() {
        // Inject a 0x00 byte mid-label (0x00 must only appear as the
        // root-label terminator, never inside a label).
        let mut pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        pkt.push(3);
        pkt.extend_from_slice(&[b'a', 0x00, b'b']);
        pkt.push(0);
        pkt.extend_from_slice(&[0, 1, 0, 1]);
        assert!(matches!(
            parse_query(&pkt),
            Err(DnsParseError::InvalidLabelByte(_))
        ));
    }

    #[test]
    fn parses_root_only_query_as_empty_name() {
        // A query for "." (the root) — degenerate but well-formed. We treat
        // the empty qname as "" (lowercased, no labels). Allowlist matching
        // will not match it (empty allowlist string is not a legal entry),
        // so the proxy emits `denied_not_in_allowlist`.
        let mut pkt = vec![
            0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        pkt.push(0);
        pkt.extend_from_slice(&[0, 1, 0, 1]);
        let v = parse_query(&pkt).expect("parse ok");
        assert_eq!(v.qname, "");
    }

    // ---- T2.B / A4 multi-question parser tests ---------------------------

    #[test]
    fn parse_query_multi_returns_three_distinct_outcomes_for_qdcount_three() {
        let pkt = build_multi_query(&[
            ("api.example.com", 1, 1),
            ("svc.example.com", 28, 1),
            ("alt.example.com", 65, 1),
        ]);
        let outcomes = parse_query_multi(&pkt).expect("parse ok");
        assert_eq!(outcomes.len(), 3);

        // Pull views via the typed accessor (D9 — no string-shaped access).
        let v0 = outcomes[0].as_view().expect("variant carries view");
        let v1 = outcomes[1].as_view().expect("variant carries view");
        let v2 = outcomes[2].as_view().expect("variant carries view");

        assert_eq!(v0.qname, "api.example.com");
        assert_eq!(v0.qtype, 1);
        assert_eq!(v1.qname, "svc.example.com");
        assert_eq!(v1.qtype, 28);
        assert_eq!(v2.qname, "alt.example.com");
        assert_eq!(v2.qtype, 65);

        // Distinctness — each question yields its own view, not a shared one.
        assert_ne!(v0, v1);
        assert_ne!(v1, v2);
        assert_ne!(v0, v2);
    }

    #[test]
    fn parse_query_multi_truncation_in_second_question_returns_too_short() {
        // Build a complete first question, then a second QNAME that promises
        // a 5-byte label but only delivers 2 bytes. QDCOUNT=2.
        let mut pkt = vec![0x12, 0x34, 0x01, 0x00, 0x00, 0x02];
        pkt.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
        append_question(&mut pkt, "api.example.com", 1, 1);
        // Mid-second-question truncation: 5-byte label, only 2 bytes follow,
        // and no qtype/qclass at all.
        pkt.push(5);
        pkt.extend_from_slice(b"ab");
        assert_eq!(parse_query_multi(&pkt), Err(DnsParseError::TooShort));
    }

    #[test]
    fn parse_query_multi_unsupported_class_in_second_question() {
        // First question is fine (IN); second uses class 3 (CHAOS).
        let pkt = build_multi_query(&[("api.example.com", 1, 1), ("evil.example.com", 1, 3)]);
        assert_eq!(
            parse_query_multi(&pkt),
            Err(DnsParseError::UnsupportedClass(3))
        );
    }

    #[test]
    fn parse_query_and_parse_query_multi_agree_on_single_question_packets() {
        // For a packet declaring exactly one question, both APIs must surface
        // the same DnsQueryView — `parse_query_multi` over `[q]` and
        // `parse_query` over the same bytes are equivalent.
        let pkt = build_query("api.example.com", 28, 1);
        let single = parse_query(&pkt).expect("single ok");
        let multi = parse_query_multi(&pkt).expect("multi ok");
        assert_eq!(multi.len(), 1);
        let v_multi = multi[0].as_view().expect("variant carries view");
        assert_eq!(&single, v_multi);
    }
}