praxis-proxy-protocol 0.7.4

HTTP, TCP, and protocol adapters for Praxis
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024 Praxis Contributors

//! Pre-pipeline inbound HTTP admission per [RFC 9110] and [RFC 9112].
//!
//! Rejects or canonicalizes malformed requests before filter execution:
//! transfer codings, `Host`, path traversal, header normalization, and
//! reserved internal header names.
//!
//! [RFC 9110]: https://datatracker.ietf.org/doc/html/rfc9110
//! [RFC 9112]: https://datatracker.ietf.org/doc/html/rfc9112

use pingora_proxy::Session;
use praxis_filter::Rejection;
use tracing::{debug, warn};

use super::path_traversal::has_dot_dot_traversal;

/// Headers that MUST NOT appear with conflicting duplicate values.
const SINGLE_VALUE_HEADERS: &[http::header::HeaderName] = &[http::header::CONTENT_LENGTH, http::header::CONTENT_TYPE];

/// Headers where obs-fold is a security risk and must be rejected.
const OBS_FOLD_REJECT_HEADERS: &[http::header::HeaderName] = &[http::header::HOST, http::header::CONTENT_LENGTH];

/// Mutable request surface used for admission (Pingora session or plain [`HeaderMap`]).
///
/// [`HeaderMap`]: http::HeaderMap
trait AdmissionRequest {
    /// Downstream HTTP version.
    fn version(&self) -> http::Version;

    /// Request path (no dot-segment resolution).
    fn path(&self) -> &str;

    /// Request headers (read-only view).
    fn headers(&self) -> &http::HeaderMap;

    /// Replace all values of a header with a single field value.
    fn set_header(&mut self, name: http::header::HeaderName, value: http::HeaderValue);
}

/// Admission over a Pingora [`Session`] (production path).
struct SessionAdmission<'a> {
    /// Downstream session whose request header is admitted.
    session: &'a mut Session,
}

impl AdmissionRequest for SessionAdmission<'_> {
    fn version(&self) -> http::Version {
        self.session.req_header().version
    }

    fn path(&self) -> &str {
        self.session.req_header().uri.path()
    }

    fn headers(&self) -> &http::HeaderMap {
        &self.session.req_header().headers
    }

    fn set_header(&mut self, name: http::header::HeaderName, value: http::HeaderValue) {
        let _remove = self.session.req_header_mut().remove_header(name.as_str());
        let _insert = self.session.req_header_mut().insert_header(name, value);
    }
}

/// Run admission on a Pingora session before the request-phase pipeline.
pub(in crate::http) fn admit_inbound_session(session: &mut Session) -> Option<Rejection> {
    admit_inbound(&mut SessionAdmission { session })
}

/// Admit an inbound request, or return the first rejection.
///
/// `None` means the request may enter the filter pipeline (headers may have
/// been mutated in place).
fn admit_inbound(request: &mut impl AdmissionRequest) -> Option<Rejection> {
    reject_unsupported_transfer_coding(request.headers())
        .or_else(|| validate_host_header(request))
        .or_else(|| reject_dot_dot_path(request.path()))
        .or_else(|| normalize_request_headers(request))
        .or_else(|| reject_reserved_client_headers(request.headers()))
}

// -----------------------------------------------------------------------------
// Transfer-Encoding
// -----------------------------------------------------------------------------

/// Reject requests whose `Transfer-Encoding` names any coding other than `chunked`.
fn reject_unsupported_transfer_coding(headers: &http::HeaderMap) -> Option<Rejection> {
    if !has_unsupported_transfer_coding(headers) {
        return None;
    }

    debug!("rejecting request with unsupported transfer coding");
    Some(Rejection::status(501))
}

/// Whether any `Transfer-Encoding` value names a coding other than `chunked`.
fn has_unsupported_transfer_coding(headers: &http::HeaderMap) -> bool {
    headers.get_all(http::header::TRANSFER_ENCODING).iter().any(|value| {
        value
            .as_bytes()
            .split(|byte| *byte == b',')
            .map(<[u8]>::trim_ascii)
            .filter(|token| !token.is_empty())
            .any(|token| !token.eq_ignore_ascii_case(b"chunked"))
    })
}

// -----------------------------------------------------------------------------
// Host
// -----------------------------------------------------------------------------

/// Validate and canonicalize the `Host` header.
fn validate_host_header(request: &mut impl AdmissionRequest) -> Option<Rejection> {
    let version = request.version();
    let hosts = request.headers().get_all(http::header::HOST);
    apply_host_check(request, check_host_values(version, &hosts))
}

/// Apply a [`HostCheck`] outcome.
fn apply_host_check(request: &mut impl AdmissionRequest, check: HostCheck) -> Option<Rejection> {
    match check {
        HostCheck::Valid => None,
        HostCheck::Reject(rejection) => Some(rejection),
        HostCheck::Canonicalize(canonical) => {
            debug!("canonicalizing duplicate identical Host headers");
            request.set_header(http::header::HOST, canonical);
            None
        },
    }
}

/// Result of pure host header validation.
enum HostCheck {
    /// Single valid host header present (or absent on HTTP/1.0).
    Valid,
    /// Duplicate identical hosts; caller should collapse to one.
    Canonicalize(http::HeaderValue),
    /// Reject with the given status.
    Reject(Rejection),
}

/// Pure validation of `Host` header values.
fn check_host_values(version: http::Version, hosts: &http::header::GetAll<'_, http::HeaderValue>) -> HostCheck {
    let mut iter = hosts.iter();

    let Some(first) = iter.next() else {
        if version == http::Version::HTTP_11 {
            debug!("rejecting HTTP/1.1 request with missing Host header");
            return HostCheck::Reject(Rejection::status(400));
        }
        return HostCheck::Valid;
    };

    if first.as_bytes().iter().all(u8::is_ascii_whitespace) {
        debug!("rejecting request with empty or whitespace-only Host header");
        return HostCheck::Reject(Rejection::status(400));
    }

    if !is_valid_host_grammar(first) {
        debug!("rejecting request with malformed Host header");
        return HostCheck::Reject(Rejection::status(400));
    }

    let Some(second) = iter.next() else {
        return HostCheck::Valid;
    };

    if second.as_bytes() != first.as_bytes() {
        debug!("rejecting request with conflicting Host headers");
        return HostCheck::Reject(Rejection::status(400));
    }

    for value in iter {
        if value.as_bytes() != first.as_bytes() {
            debug!("rejecting request with conflicting Host headers");
            return HostCheck::Reject(Rejection::status(400));
        }
    }

    HostCheck::Canonicalize(first.clone())
}

/// Whether a `Host` value matches `uri-host [ ":" port ]` per [RFC 9110 Section 7.2].
fn is_valid_host_grammar(value: &http::HeaderValue) -> bool {
    let Ok(authority) = http::uri::Authority::try_from(value.as_bytes()) else {
        return false;
    };
    let text = authority.as_str();
    if text.contains('@') {
        return false;
    }

    let port = if text.starts_with('[') {
        let Some((_, rest)) = text.split_once(']') else {
            return false;
        };
        if rest.is_empty() {
            return true;
        }
        let Some(port) = rest.strip_prefix(':') else {
            return false;
        };
        port
    } else if text.contains(['[', ']']) {
        return false;
    } else {
        let Some((_, port)) = text.split_once(':') else {
            return true;
        };
        port
    };

    port.is_empty() || (port.bytes().all(|byte| byte.is_ascii_digit()) && port.parse::<u16>().is_ok())
}

// -----------------------------------------------------------------------------
// Path
// -----------------------------------------------------------------------------

/// Reject request paths containing `..` traversal segments.
fn reject_dot_dot_path(path: &str) -> Option<Rejection> {
    has_dot_dot_traversal(path).then(|| {
        debug!("rejecting request path with dot-dot segment");
        Rejection::status(400)
    })
}

// -----------------------------------------------------------------------------
// Header normalization
// -----------------------------------------------------------------------------

/// Normalize request headers before the filter pipeline.
fn normalize_request_headers(request: &mut impl AdmissionRequest) -> Option<Rejection> {
    if let Some(r) = reject_conflicting_single_value_headers(request) {
        return Some(r);
    }
    if let Some(r) = reject_dual_content_length_transfer_encoding(request.headers()) {
        return Some(r);
    }
    handle_obs_fold(request)
}

/// Collapse identical duplicate single-value headers or reject conflicting values.
fn reject_conflicting_single_value_headers(request: &mut impl AdmissionRequest) -> Option<Rejection> {
    for header_name in SINGLE_VALUE_HEADERS {
        let mut values = request.headers().get_all(header_name).iter();
        let Some(first) = values.next() else {
            continue;
        };
        let first_bytes = first.as_bytes();
        let mut saw_duplicate = false;
        for value in values {
            saw_duplicate = true;
            if value.as_bytes() != first_bytes {
                debug!(header = %header_name, "rejecting request with conflicting duplicate header");
                return Some(Rejection::status(400));
            }
        }
        if !saw_duplicate {
            continue;
        }

        debug!(header = %header_name, "canonicalizing duplicate identical header");
        request.set_header(header_name.clone(), first.clone());
    }

    None
}

/// Reject requests that carry both `Content-Length` and `Transfer-Encoding`.
fn reject_dual_content_length_transfer_encoding(headers: &http::HeaderMap) -> Option<Rejection> {
    if headers.contains_key(http::header::CONTENT_LENGTH) && headers.contains_key(http::header::TRANSFER_ENCODING) {
        debug!("rejecting request with both Content-Length and Transfer-Encoding");
        return Some(Rejection::status(400));
    }
    None
}

/// Returns `true` if the byte sequence contains obs-fold (`\r\n` followed by SP/HTAB).
fn contains_obs_fold(value: &[u8]) -> bool {
    value.windows(3).any(|w| matches!(w, [b'\r', b'\n', b' ' | b'\t']))
}

/// Replace obs-fold sequences with a single SP.
fn unfold_obs_fold(value: &[u8]) -> Vec<u8> {
    let mut result = Vec::with_capacity(value.len());
    let mut i = 0;
    while i < value.len() {
        let is_obs_fold = value.get(i) == Some(&b'\r')
            && value.get(i + 1) == Some(&b'\n')
            && matches!(value.get(i + 2), Some(b' ' | b'\t'));

        if is_obs_fold {
            result.push(b' ');
            i += 3;
            while matches!(value.get(i), Some(b' ' | b'\t')) {
                i += 1;
            }
        } else {
            if let Some(&b) = value.get(i) {
                result.push(b);
            }
            i += 1;
        }
    }
    result
}

/// Reject or unfold obsolete line folding in HTTP/1.x request headers.
fn handle_obs_fold(request: &mut impl AdmissionRequest) -> Option<Rejection> {
    if !matches!(
        request.version(),
        http::Version::HTTP_09 | http::Version::HTTP_10 | http::Version::HTTP_11
    ) {
        return None;
    }

    for name in OBS_FOLD_REJECT_HEADERS {
        if let Some(value) = request.headers().get(name)
            && contains_obs_fold(value.as_bytes())
        {
            debug!(header = %name, "rejecting request with obs-fold in security-sensitive header");
            return Some(Rejection::status(400));
        }
    }

    let headers_snapshot: Vec<(http::header::HeaderName, http::header::HeaderValue)> = request
        .headers()
        .iter()
        .filter(|(name, value)| !OBS_FOLD_REJECT_HEADERS.contains(name) && contains_obs_fold(value.as_bytes()))
        .map(|(name, value)| (name.clone(), value.clone()))
        .collect();

    for (name, value) in headers_snapshot {
        let unfolded = unfold_obs_fold(value.as_bytes());
        if let Ok(new_value) = http::header::HeaderValue::from_bytes(&unfolded) {
            debug!(header = %name, "replacing obs-fold with single SP");
            request.set_header(name, new_value);
        }
    }

    None
}

// -----------------------------------------------------------------------------
// Reserved headers
// -----------------------------------------------------------------------------

/// Reject client-supplied reserved internal headers before filter execution.
fn reject_reserved_client_headers(headers: &http::HeaderMap) -> Option<Rejection> {
    let reserved_count = headers
        .keys()
        .filter(|name| praxis_core::reserved_headers::is_reserved(name.as_str()))
        .count();

    if reserved_count == 0 {
        return None;
    }

    warn!(
        count = reserved_count,
        "rejecting request with client-supplied reserved internal headers"
    );
    Some(Rejection::status(400))
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg(test)]
#[expect(clippy::allow_attributes, reason = "blanket test suppressions")]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing, reason = "tests")]
mod tests {
    use super::*;

    /// Admission over a [`HeaderMap`] for unit tests.
    ///
    /// [`HeaderMap`]: http::HeaderMap
    struct HeaderMapAdmission<'a> {
        /// Downstream HTTP version.
        version: http::Version,

        /// Request path under test.
        path: &'a str,

        /// Request headers to validate and canonicalize.
        headers: &'a mut http::HeaderMap,
    }

    impl AdmissionRequest for HeaderMapAdmission<'_> {
        fn version(&self) -> http::Version {
            self.version
        }

        fn path(&self) -> &str {
            self.path
        }

        fn headers(&self) -> &http::HeaderMap {
            self.headers
        }

        fn set_header(&mut self, name: http::header::HeaderName, value: http::HeaderValue) {
            self.headers.remove(&name);
            self.headers.insert(name, value);
        }
    }

    fn admit(version: http::Version, path: &str, headers: &mut http::HeaderMap) -> Option<Rejection> {
        admit_inbound(&mut HeaderMapAdmission { version, path, headers })
    }

    fn te_headers(values: &[&'static str]) -> http::HeaderMap {
        let mut headers = http::HeaderMap::new();
        for value in values {
            headers.append(http::header::TRANSFER_ENCODING, http::HeaderValue::from_static(value));
        }
        headers
    }

    async fn session_for(raw: &str) -> Session {
        use tokio::io::AsyncWriteExt as _;

        let (mut client, server) = tokio::io::duplex(1_048_576);
        client.write_all(raw.as_bytes()).await.unwrap();
        let mut session = Session::new_h1(Box::new(server));
        let read = session.read_request().await.unwrap();
        assert!(read, "the session must parse the request header");
        session
    }

    fn admit_session(session: &mut Session) -> Option<Rejection> {
        admit_inbound_session(session)
    }

    // -------------------------------------------------------------------------
    // Transfer-Encoding
    // -------------------------------------------------------------------------

    #[test]
    fn transfer_coding_chunked_is_supported() {
        assert!(
            !has_unsupported_transfer_coding(&te_headers(&["chunked"])),
            "plain chunked must be accepted"
        );
    }

    #[test]
    fn transfer_coding_chunked_is_case_insensitive() {
        assert!(
            !has_unsupported_transfer_coding(&te_headers(&["Chunked"])),
            "transfer coding names are case-insensitive"
        );
    }

    #[test]
    fn transfer_coding_compound_value_is_unsupported() {
        assert!(
            has_unsupported_transfer_coding(&te_headers(&["gzip, chunked"])),
            "gzip in a compound value must be rejected"
        );
    }

    #[test]
    fn transfer_coding_split_across_fields_is_unsupported() {
        assert!(
            has_unsupported_transfer_coding(&te_headers(&["gzip", "chunked"])),
            "gzip in a separate field line must be rejected"
        );
    }

    #[test]
    fn transfer_coding_repeated_chunked_is_supported() {
        assert!(
            !has_unsupported_transfer_coding(&te_headers(&["chunked, chunked"])),
            "repeated chunked is left to Pingora framing checks"
        );
    }

    #[test]
    fn transfer_coding_absent_is_supported() {
        assert!(
            !has_unsupported_transfer_coding(&http::HeaderMap::new()),
            "no Transfer-Encoding must be accepted"
        );
    }

    // -------------------------------------------------------------------------
    // Host header validation
    // -------------------------------------------------------------------------

    fn single_host_check(value: &'static str) -> HostCheck {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, http::HeaderValue::from_static(value));
        check_host_values(http::Version::HTTP_11, &headers.get_all(http::header::HOST))
    }

    #[test]
    fn missing_host_http11_rejected() {
        let headers = http::HeaderMap::new();
        let result = check_host_values(http::Version::HTTP_11, &headers.get_all(http::header::HOST));
        assert!(
            matches!(result, HostCheck::Reject(_)),
            "HTTP/1.1 without Host must be rejected"
        );
    }

    #[test]
    fn missing_host_http10_allowed() {
        let headers = http::HeaderMap::new();
        let result = check_host_values(http::Version::HTTP_10, &headers.get_all(http::header::HOST));
        assert!(
            matches!(result, HostCheck::Valid),
            "HTTP/1.0 without Host should be allowed"
        );
    }

    #[test]
    fn missing_host_http2_allowed() {
        let headers = http::HeaderMap::new();
        let result = check_host_values(http::Version::HTTP_2, &headers.get_all(http::header::HOST));
        assert!(
            matches!(result, HostCheck::Valid),
            "HTTP/2 without Host should be allowed"
        );
    }

    #[test]
    fn single_valid_host_accepted() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "example.com".parse().unwrap());
        let result = check_host_values(http::Version::HTTP_11, &headers.get_all(http::header::HOST));
        assert!(
            matches!(result, HostCheck::Valid),
            "single valid Host should be accepted"
        );
    }

    #[test]
    fn whitespace_only_host_rejected() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "   ".parse().unwrap());
        let result = check_host_values(http::Version::HTTP_11, &headers.get_all(http::header::HOST));
        assert!(
            matches!(result, HostCheck::Reject(_)),
            "whitespace-only Host must be rejected"
        );
    }

    #[test]
    fn empty_host_rejected() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "".parse().unwrap());
        let result = check_host_values(http::Version::HTTP_11, &headers.get_all(http::header::HOST));
        assert!(matches!(result, HostCheck::Reject(_)), "empty Host must be rejected");
    }

    #[test]
    fn conflicting_duplicate_hosts_rejected() {
        let mut headers = http::HeaderMap::new();
        headers.append(http::header::HOST, "a.example.com".parse().unwrap());
        headers.append(http::header::HOST, "b.example.com".parse().unwrap());
        let result = check_host_values(http::Version::HTTP_11, &headers.get_all(http::header::HOST));
        assert!(
            matches!(result, HostCheck::Reject(_)),
            "conflicting Host headers must be rejected"
        );
    }

    #[test]
    fn three_hosts_third_conflicts_rejected() {
        let mut headers = http::HeaderMap::new();
        headers.append(http::header::HOST, "same.com".parse().unwrap());
        headers.append(http::header::HOST, "same.com".parse().unwrap());
        headers.append(http::header::HOST, "different.com".parse().unwrap());
        let result = check_host_values(http::Version::HTTP_11, &headers.get_all(http::header::HOST));
        assert!(
            matches!(result, HostCheck::Reject(_)),
            "third conflicting Host must be rejected"
        );
    }

    #[test]
    fn identical_duplicate_hosts_canonicalized() {
        let mut headers = http::HeaderMap::new();
        headers.append(http::header::HOST, "example.com".parse().unwrap());
        headers.append(http::header::HOST, "example.com".parse().unwrap());
        let result = check_host_values(http::Version::HTTP_11, &headers.get_all(http::header::HOST));
        assert!(
            matches!(&result, HostCheck::Canonicalize(v) if v.as_bytes() == b"example.com"),
            "identical duplicate Hosts should be canonicalized"
        );
    }

    #[test]
    fn malformed_host_grammar_rejected() {
        for value in ["a b", "h/p", "h:abc", "h:99999", "h:+80", "user@h", "[::1]x", "a[::1]"] {
            assert!(
                matches!(single_host_check(value), HostCheck::Reject(_)),
                "malformed Host {value:?} must be rejected"
            );
        }
    }

    #[test]
    fn well_formed_host_grammar_accepted() {
        for value in [
            "example.com",
            "example.com.",
            "example.com:443",
            "example.com:",
            "[::1]",
            "[::1]:8080",
            "localhost",
        ] {
            assert!(
                matches!(single_host_check(value), HostCheck::Valid),
                "well-formed Host {value:?} must be accepted"
            );
        }
    }

    // -------------------------------------------------------------------------
    // Request path validation
    // -------------------------------------------------------------------------

    #[test]
    fn dot_dot_path_rejected() {
        assert!(
            reject_dot_dot_path("/a/../b").is_some_and(|r| r.status == 400),
            "dot-dot segment should be rejected with 400"
        );
    }

    #[test]
    fn encoded_dot_dot_path_rejected() {
        assert!(
            reject_dot_dot_path("/a/%2e%2e/b").is_some_and(|r| r.status == 400),
            "percent-encoded dot-dot segment should be rejected with 400"
        );
    }

    #[test]
    fn route_escape_path_rejected() {
        assert!(
            reject_dot_dot_path("/public/../admin").is_some(),
            "path escaping a prefix route should be rejected"
        );
    }

    #[test]
    fn plain_and_double_slash_paths_accepted() {
        assert!(
            reject_dot_dot_path("/a/b..c/d").is_none(),
            "dots inside a segment are allowed"
        );
        assert!(
            reject_dot_dot_path("//etc/passwd").is_none(),
            "double slash is left to routing"
        );
        assert!(reject_dot_dot_path("/a/./b").is_none(), "single-dot segment is allowed");
    }

    // -------------------------------------------------------------------------
    // Admission (end-to-end on HeaderMap)
    // -------------------------------------------------------------------------

    #[test]
    fn missing_host_http11_rejected_via_admit() {
        let mut headers = http::HeaderMap::new();
        assert!(matches!(
            admit(http::Version::HTTP_11, "/", &mut headers),
            Some(r) if r.status == 400
        ));
    }

    #[test]
    fn identical_duplicate_hosts_canonicalized_then_conflicting_cl_rejected() {
        let mut headers = http::HeaderMap::new();
        headers.append(http::header::HOST, "example.com".parse().unwrap());
        headers.append(http::header::HOST, "example.com".parse().unwrap());
        headers.append(http::header::CONTENT_LENGTH, "5".parse().unwrap());
        headers.append(http::header::CONTENT_LENGTH, "6".parse().unwrap());

        let rejection = admit(http::Version::HTTP_11, "/", &mut headers);
        assert!(
            rejection.is_some_and(|r| r.status == 400),
            "conflicting Content-Length must reject after Host canonicalization"
        );
        assert_eq!(
            headers.get_all(http::header::HOST).iter().count(),
            1,
            "duplicate Host must be collapsed before normalization runs"
        );
    }

    #[test]
    fn conflicting_duplicate_content_type_is_rejected() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "x".parse().unwrap());
        headers.append(http::header::CONTENT_TYPE, "text/plain".parse().unwrap());
        headers.append(http::header::CONTENT_TYPE, "application/json".parse().unwrap());

        assert!(
            admit(http::Version::HTTP_11, "/", &mut headers).is_some_and(|r| r.status == 400),
            "conflicting Content-Type duplicates must reject"
        );
    }

    #[test]
    fn reserved_client_header_rejected() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "x".parse().unwrap());
        headers.insert("x-praxis-test", "1".parse().unwrap());

        assert!(
            admit(http::Version::HTTP_11, "/", &mut headers).is_some_and(|r| r.status == 400),
            "client reserved header must reject"
        );
    }

    // -------------------------------------------------------------------------
    // obs-fold (RFC 9112 Section 5.2)
    // -------------------------------------------------------------------------

    #[test]
    fn contains_obs_fold_detects_crlf_sp() {
        assert!(
            contains_obs_fold(b"value\r\n continuation"),
            "CRLF followed by SP is obs-fold"
        );
    }

    #[test]
    fn contains_obs_fold_detects_crlf_htab() {
        assert!(
            contains_obs_fold(b"value\r\n\tcontinuation"),
            "CRLF followed by HTAB is obs-fold"
        );
    }

    #[test]
    fn contains_obs_fold_ignores_bare_crlf() {
        assert!(
            !contains_obs_fold(b"value\r\nno-fold"),
            "CRLF without following whitespace is not obs-fold"
        );
    }

    #[test]
    fn contains_obs_fold_false_for_normal_value() {
        assert!(
            !contains_obs_fold(b"plain header value"),
            "normal value has no obs-fold"
        );
    }

    #[test]
    fn contains_obs_fold_false_for_empty() {
        assert!(!contains_obs_fold(b""), "empty value has no obs-fold");
    }

    #[test]
    fn contains_obs_fold_false_for_trailing_crlf() {
        assert!(
            !contains_obs_fold(b"value\r\n"),
            "trailing CRLF without whitespace is not obs-fold"
        );
    }

    #[test]
    fn unfold_replaces_crlf_sp_with_single_sp() {
        let input = b"value\r\n continuation";
        let result = unfold_obs_fold(input);
        assert_eq!(result, b"value continuation", "obs-fold should become single SP");
    }

    #[test]
    fn unfold_replaces_crlf_htab_with_single_sp() {
        let input = b"value\r\n\tcontinuation";
        let result = unfold_obs_fold(input);
        assert_eq!(result, b"value continuation", "CRLF+HTAB should become single SP");
    }

    #[test]
    fn unfold_collapses_multiple_whitespace_after_fold() {
        let input = b"value\r\n   continuation";
        let result = unfold_obs_fold(input);
        assert_eq!(
            result, b"value continuation",
            "obs-fold with extra whitespace should collapse to single SP"
        );
    }

    #[test]
    fn unfold_handles_multiple_folds() {
        let input = b"a\r\n b\r\n c";
        let result = unfold_obs_fold(input);
        assert_eq!(result, b"a b c", "multiple obs-folds should each become single SP");
    }

    #[test]
    fn unfold_preserves_normal_value() {
        let input = b"plain value";
        let result = unfold_obs_fold(input);
        assert_eq!(result, b"plain value", "value without obs-fold should be unchanged");
    }

    #[test]
    fn unfold_preserves_empty() {
        let result = unfold_obs_fold(b"");
        assert!(result.is_empty(), "empty input should produce empty output");
    }

    #[test]
    fn contains_obs_fold_single_crlf_sp() {
        assert!(
            contains_obs_fold(b"\r\n value"),
            "CRLF+SP at the very start of the value is obs-fold"
        );
    }

    #[test]
    fn contains_obs_fold_multiple_folds() {
        assert!(
            contains_obs_fold(b"a\r\n b\r\n c"),
            "value with multiple obs-fold sequences should be detected"
        );
    }

    #[test]
    fn contains_obs_fold_only_cr_no_lf() {
        assert!(
            !contains_obs_fold(b"value\r continuation"),
            "bare CR followed by space is not obs-fold"
        );
    }

    #[test]
    fn contains_obs_fold_only_lf_sp() {
        assert!(
            !contains_obs_fold(b"value\n continuation"),
            "bare LF followed by space is not obs-fold"
        );
    }

    #[test]
    fn unfold_at_start_of_value() {
        let result = unfold_obs_fold(b"\r\n continuation");
        assert_eq!(
            result, b" continuation",
            "obs-fold at the very start should become single SP"
        );
    }

    #[test]
    fn unfold_consecutive_folds() {
        let result = unfold_obs_fold(b"a\r\n \r\n b");
        assert_eq!(
            result, b"a  b",
            "two back-to-back obs-folds should each become single SP"
        );
    }

    #[test]
    fn unfold_mixed_whitespace_after_fold() {
        let result = unfold_obs_fold(b"val\r\n\t  rest");
        assert_eq!(
            result, b"val rest",
            "CRLF followed by tab then spaces should collapse to single SP"
        );
    }

    #[test]
    fn unfold_preserves_internal_crlf_without_continuation() {
        let result = unfold_obs_fold(b"before\r\nafter");
        assert_eq!(
            result, b"before\r\nafter",
            "bare CRLF without following whitespace should be kept as-is"
        );
    }

    #[test]
    fn unfold_single_byte_values() {
        assert_eq!(unfold_obs_fold(b"x"), b"x", "single byte input unchanged");
        assert_eq!(unfold_obs_fold(b"ab"), b"ab", "two byte input unchanged");
    }

    #[test]
    fn identical_duplicate_content_type_is_canonicalized() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "x".parse().unwrap());
        headers.append(http::header::CONTENT_TYPE, "text/plain".parse().unwrap());
        headers.append(http::header::CONTENT_TYPE, "text/plain".parse().unwrap());

        let rejection = admit(http::Version::HTTP_11, "/", &mut headers);
        assert!(rejection.is_none(), "identical duplicates must not reject");
        let count = headers.get_all(http::header::CONTENT_TYPE).iter().count();
        assert_eq!(count, 1, "identical duplicates must collapse to one value");
    }

    #[test]
    fn content_length_alone_passes_normalization() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "x".parse().unwrap());
        headers.insert(http::header::CONTENT_LENGTH, "5".parse().unwrap());

        let rejection = admit(http::Version::HTTP_11, "/", &mut headers);
        assert!(rejection.is_none(), "Content-Length alone must pass");
    }

    #[test]
    fn clean_requests_pass_normalization() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "x".parse().unwrap());
        headers.insert(http::header::CONTENT_TYPE, "text/plain".parse().unwrap());

        let rejection = admit(http::Version::HTTP_11, "/", &mut headers);
        assert!(rejection.is_none(), "well-formed requests must pass");
    }

    #[test]
    fn dual_content_length_and_transfer_encoding_is_rejected() {
        let mut headers = http::HeaderMap::new();
        headers.insert(http::header::HOST, "x".parse().unwrap());
        headers.insert(http::header::CONTENT_LENGTH, "5".parse().unwrap());
        headers.insert(http::header::TRANSFER_ENCODING, "chunked".parse().unwrap());

        assert!(
            admit(http::Version::HTTP_11, "/", &mut headers).is_some_and(|r| r.status == 400),
            "CL and TE together must reject"
        );
    }

    #[tokio::test]
    async fn conflicting_third_host_value_rejected() {
        let mut session = session_for("GET / HTTP/1.1\r\nHost: one.example\r\n\r\n").await;
        session.req_header_mut().append_header("host", "one.example").unwrap();
        session.req_header_mut().append_header("host", "two.example").unwrap();

        let rejection = admit_session(&mut session);
        assert!(
            rejection.is_some_and(|r| r.status == 400),
            "a conflicting third Host value must reject with 400"
        );
    }

    #[tokio::test]
    async fn session_unsupported_transfer_coding_before_host() {
        let mut session = session_for("GET / HTTP/1.1\r\nTransfer-Encoding: gzip, chunked\r\n\r\n").await;

        assert_eq!(
            admit_session(&mut session).map(|r| r.status),
            Some(501),
            "unsupported transfer coding must reject before missing Host is checked"
        );
    }

    #[tokio::test]
    async fn session_host_canonicalized_before_conflicting_content_length() {
        let mut session = session_for("GET / HTTP/1.1\r\nHost: example.com\r\nContent-Length: 5\r\n\r\n").await;
        let req = session.req_header_mut();
        let _duplicate_host = req.append_header("host".to_owned(), "example.com".to_owned());
        let _conflicting_cl = req.append_header("content-length".to_owned(), "6".to_owned());

        assert_eq!(
            admit_session(&mut session).map(|r| r.status),
            Some(400),
            "conflicting Content-Length must reject after Host canonicalization"
        );
        assert_eq!(
            session.req_header().headers.get_all(http::header::HOST).iter().count(),
            1,
            "duplicate Host must be collapsed on the session path"
        );
    }

    #[tokio::test]
    async fn session_reserved_headers_checked_last() {
        let mut session =
            session_for("GET / HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: gzip, chunked\r\nx-praxis-test: 1\r\n\r\n")
                .await;

        assert_eq!(
            admit_session(&mut session).map(|r| r.status),
            Some(501),
            "transfer coding must win over reserved header when both are present"
        );

        let mut session = session_for("GET / HTTP/1.1\r\nHost: x\r\nx-praxis-test: 1\r\n\r\n").await;

        assert_eq!(
            admit_session(&mut session).map(|r| r.status),
            Some(400),
            "reserved header rejects only after earlier checks pass"
        );
    }
}