pingora-core 0.9.1

Pingora's APIs and traits for the core network protocols.
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
// Copyright 2026 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! HTTP authority consistency checks shared by protocol versions and proxy egress.
//!
//! The boundary classification these checks act on lives in [`pingora_http::authority`] and
//! is re-exported here.

use http::{header, HeaderValue};
use pingora_error::{Error, ErrorType::InvalidHTTPHeader, Result};
use pingora_http::RequestHeader;

pub use pingora_http::authority::{
    is_http_family_scheme, raw_target_authority, RawTargetAuthority,
};

/// Validate that a request has one unambiguous authority.
///
/// CONNECT handling:
///
/// - A valid authority with a port may omit `Host`; a present `Host` must match.
/// - Malformed authority prefixes require a byte-exact `Host` match.
/// - Other nonstandard forms remain application-defined.
/// - Userinfo and ambiguous bracket or port forms are rejected.
///
/// Other requests reject duplicate `Host` ([RFC 9112 section 3.2]), userinfo
/// ([RFC 9110 section 4.2.4]), inconsistent absolute-form authority, and targets whose authority
/// changes under slash or backslash normalization. This is stricter than
/// [RFC 9112 section 3.2.2], which replaces conflicting `Host`. Userinfo is unsafe because
/// [`http::Uri::host`] strips it.
///
/// Authority bytes otherwise remain opaque. HTTP/1 ingress and standard proxy egress call this;
/// HTTP/2 performs equivalent stream-local checks.
///
/// [RFC 9110 section 4.2.4]: https://www.rfc-editor.org/rfc/rfc9110.html#section-4.2.4
/// [RFC 9112 section 3.2]: https://www.rfc-editor.org/rfc/rfc9112.html#section-3.2
/// [RFC 9112 section 3.2.2]: https://www.rfc-editor.org/rfc/rfc9112.html#section-3.2.2
pub fn validate_request_authority(req: &RequestHeader) -> Result<()> {
    validate_request_authority_fields(req)?;

    let host = req.headers.get(header::HOST);

    if req.method == http::Method::CONNECT {
        return validate_connect_authority(req.raw_path(), host);
    }

    match raw_target_authority(req.raw_path()) {
        RawTargetAuthority::None => {}
        RawTargetAuthority::AmbiguousAuthority => {
            return Error::e_explain(
                InvalidHTTPHeader,
                "ambiguous HTTP absolute-form request target",
            );
        }
        RawTargetAuthority::Absolute {
            scheme, authority, ..
        } => {
            if is_http_family_scheme(scheme) {
                http::uri::Authority::try_from(authority).map_err(|cause| {
                    Error::because(
                        InvalidHTTPHeader,
                        "unparseable absolute-form authority",
                        cause,
                    )
                })?;
            }
            if authority.contains(&b'@') {
                return Error::e_explain(InvalidHTTPHeader, "userinfo in request target");
            }
            if host.is_some_and(|host| host.as_bytes() != authority) {
                return Error::e_explain(
                    InvalidHTTPHeader,
                    "Host header differs from request-target authority",
                );
            }
        }
    }

    Ok(())
}

/// Validate authority fields shared by H1 and H2 ingress.
pub(super) fn validate_request_authority_fields(req: &RequestHeader) -> Result<()> {
    let mut hosts = req.headers.get_all(header::HOST).iter();
    let (host, duplicate_host) = (hosts.next(), hosts.next());

    if duplicate_host.is_some() {
        return Error::e_explain(InvalidHTTPHeader, "multiple Host header fields");
    }

    if host.is_some_and(|host| host.as_bytes().contains(&b'@')) {
        return Error::e_explain(InvalidHTTPHeader, "userinfo in Host header");
    }

    let uri_authority = req.uri.authority().map(|authority| authority.as_str());
    if uri_authority.is_some_and(|authority| authority.contains('@')) {
        return Error::e_explain(InvalidHTTPHeader, "userinfo in URI authority");
    }

    if host
        .zip(uri_authority)
        .is_some_and(|(host, authority)| host.as_bytes() != authority.as_bytes())
    {
        return Error::e_explain(InvalidHTTPHeader, "Host header differs from URI authority");
    }

    Ok(())
}

/// Reconcile authority-like CONNECT targets with `Host` while preserving custom target forms.
fn validate_connect_authority(target: &[u8], host: Option<&HeaderValue>) -> Result<()> {
    let authority_end = target
        .iter()
        .position(|byte| matches!(byte, b'/' | b'?' | b'#'))
        .unwrap_or(target.len());
    let authority_target = &target[..authority_end];

    // For ordinary CONNECT this is `host:port`; for absolute-form it is only the scheme (`http:`),
    // so the fallback classifier below must extract and validate the actual authority separately.
    if authority_target.contains(&b'@') {
        return Error::e_explain(InvalidHTTPHeader, "userinfo in request target");
    }

    if has_ambiguous_port_suffix(authority_target) {
        return Error::e_explain(InvalidHTTPHeader, "ambiguous CONNECT request target");
    }

    // Parse ordinary authority-form (`host:port`) and reconcile by components.
    let parsed_authority = http::uri::Authority::try_from(authority_target);
    if let Ok(authority) = &parsed_authority {
        if authority.port().is_some() {
            let Some(host) = host else {
                return Ok(());
            };
            return reconcile_connect_host(authority_target, authority.host().as_bytes(), host);
        }
    }

    // Handle absolute (`http://host/path`), ambiguous (`http:/\host`), and custom (`unix:/path`)
    // forms when ordinary parsing did not return above.
    match raw_target_authority(target) {
        RawTargetAuthority::Absolute { authority, .. } => {
            if authority.contains(&b'@') {
                return Error::e_explain(InvalidHTTPHeader, "userinfo in request target");
            }
            if has_ambiguous_port_suffix(authority) {
                return Error::e_explain(InvalidHTTPHeader, "ambiguous CONNECT request target");
            }
            let Some(host) = host else {
                return Error::e_explain(
                    InvalidHTTPHeader,
                    "missing Host header for absolute-form CONNECT request target",
                );
            };
            // Reparse the authority extracted from the absolute-form target.
            match http::uri::Authority::try_from(authority) {
                Ok(parsed) => reconcile_connect_host(authority, parsed.host().as_bytes(), host),
                Err(_) => reconcile_connect_host(authority, authority, host),
            }
        }
        RawTargetAuthority::AmbiguousAuthority => {
            Error::e_explain(InvalidHTTPHeader, "ambiguous CONNECT request target")
        }
        // An authority prefix that does not parse cannot be reconciled by component, so require it
        // to match `Host` byte-for-byte: otherwise one malformed byte would escape the reconciliation
        // the same target is subject to without it. An empty prefix carries no authority to disagree
        // about.
        RawTargetAuthority::None if !authority_target.is_empty() && parsed_authority.is_err() => {
            let Some(host) = host else {
                return Error::e_explain(
                    InvalidHTTPHeader,
                    "missing Host header for malformed CONNECT request target",
                );
            };
            reconcile_connect_host(authority_target, authority_target, host)
        }
        RawTargetAuthority::None => Ok(()),
    }
}

/// Accept `Host` only when it names the complete CONNECT authority or its host component.
///
/// The host-only form follows the [RFC 9112 section 3.2.3] example:
/// `CONNECT example.com:80` with `Host: example.com`.
///
/// [RFC 9112 section 3.2.3]: https://www.rfc-editor.org/rfc/rfc9112.html#section-3.2.3
fn reconcile_connect_host(
    authority: &[u8],
    authority_host: &[u8],
    host: &HeaderValue,
) -> Result<()> {
    if host.as_bytes() == authority || host.as_bytes() == authority_host {
        Ok(())
    } else {
        Error::e_explain(
            InvalidHTTPHeader,
            "Host header differs from CONNECT request target",
        )
    }
}

/// Detect multiple unbracketed port separators, whose interpretation differs between parsers.
pub(super) fn has_ambiguous_port_suffix(authority: &[u8]) -> bool {
    let mut inside_brackets = authority.first() == Some(&b'[');
    let mut suffix_colon_seen = false;

    for (index, &byte) in authority.iter().enumerate() {
        if inside_brackets {
            if index == 0 {
                continue;
            }
            match byte {
                b'[' => return true,
                b']' => inside_brackets = false,
                _ => {}
            }
            continue;
        }

        match byte {
            b'[' | b']' => return true,
            b':' if suffix_colon_seen => return true,
            b':' => suffix_colon_seen = true,
            _ => {}
        }
    }

    inside_brackets
}

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

    fn request(method: &str, target: &str, hosts: &[&str]) -> RequestHeader {
        let mut request = RequestHeader::build(method, target.as_bytes(), None).unwrap();
        for host in hosts {
            request.append_header(header::HOST, *host).unwrap();
        }
        request
    }

    #[test]
    fn validate_authority_sources() {
        assert!(validate_request_authority(&request("GET", "/test", &[])).is_ok());
        assert!(
            validate_request_authority(&request("GET", "/test", &["authority.example:8443"]))
                .is_ok()
        );
        assert!(validate_request_authority(&request(
            "GET",
            "/test",
            &["authority.example", "other.example"]
        ))
        .is_err());
        assert!(validate_request_authority(&request(
            "GET",
            "/test",
            &["authority.example", "authority.example"]
        ))
        .is_err());
        assert!(
            validate_request_authority(&request("GET", "/test", &["user@authority.example"]))
                .is_err()
        );
        assert!(validate_request_authority(&request(
            "GET",
            "/test",
            &["user:pass@authority.example"]
        ))
        .is_err());
        assert!(validate_request_authority(&request(
            "GET",
            "/test",
            &["user%40authority.example"]
        ))
        .is_ok());

        let uri_request = |uri: &str, host: Option<&str>| {
            let mut request = http::Request::builder().uri(uri).body(()).unwrap();
            if let Some(host) = host {
                request
                    .headers_mut()
                    .insert(header::HOST, HeaderValue::from_str(host).unwrap());
            }
            RequestHeader::from(request.into_parts().0)
        };
        assert!(validate_request_authority(&uri_request(
            "https://user@authority.example/test",
            None
        ))
        .is_err());
        assert!(validate_request_authority(&uri_request(
            "https://authority.example/test",
            Some("other.example")
        ))
        .is_err());
    }

    #[test]
    fn validate_absolute_form() {
        assert!(validate_request_authority(&request(
            "GET",
            "http://authority.example/test",
            &["authority.example"]
        ))
        .is_ok());
        assert!(validate_request_authority(&request(
            "GET",
            "http://user@authority.example/test",
            &["authority.example"]
        ))
        .is_err());
        for authority in [
            "good.example%5Cevil.example",
            "user%40good.example",
            "a%2f.example",
            "good.example:443:8080",
            "[good.example",
        ] {
            let target = format!("http://{authority}/test");
            let err =
                validate_request_authority(&request("GET", &target, &[authority])).unwrap_err();
            assert_eq!(
                err.context.as_ref().map(|context| context.as_str()),
                Some("unparseable absolute-form authority"),
                "{target}"
            );
        }
        for target in ["http:///path", "https://?query"] {
            let err = validate_request_authority(&request("GET", target, &[""])).unwrap_err();
            assert_eq!(
                err.context.as_ref().map(|context| context.as_str()),
                Some("ambiguous HTTP absolute-form request target"),
                "{target}"
            );
        }
        for target in ["ht_tp://other.example/admin", "9x://other.example/admin"] {
            assert!(
                validate_request_authority(&request("GET", target, &["other.example"])).is_err(),
                "{target}"
            );
        }
        let mut hostless = request("GET", "http://authority.example/test", &[]);
        assert!(validate_request_authority(&hostless).is_ok());
        hostless.set_version(http::Version::HTTP_10);
        assert!(validate_request_authority(&hostless).is_ok());
        let err = validate_request_authority(&request(
            "GET",
            "http://authority.example/test",
            &["other.example"],
        ))
        .unwrap_err();
        assert_eq!(
            err.context.as_ref().map(|context| context.as_str()),
            Some("Host header differs from request-target authority")
        );
        let err = validate_request_authority(&request(
            "GET",
            "http:/\\/\\other.example/admin",
            &["authority.example"],
        ))
        .unwrap_err();
        assert_eq!(
            err.context.as_ref().map(|context| context.as_str()),
            Some("ambiguous HTTP absolute-form request target")
        );
        let err = validate_request_authority(&request(
            "GET",
            "http://good.example\\evil.example/",
            &["good.example\\evil.example"],
        ))
        .unwrap_err();
        assert_eq!(
            err.context.as_ref().map(|context| context.as_str()),
            Some("ambiguous HTTP absolute-form request target")
        );
        assert!(validate_request_authority(&request("GET", "/users/foo@bar.example", &[])).is_ok());
        assert!(
            validate_request_authority(&request("GET", "/test?email=foo@bar.example", &[])).is_ok()
        );
        assert!(validate_request_authority(&request(
            "GET",
            "/redirect?next=http://other.example/admin",
            &["authority.example"]
        ))
        .is_ok());
        assert!(validate_request_authority(&request(
            "GET",
            "/test#http://user@evil.example/",
            &["authority.example"]
        ))
        .is_ok());
    }

    #[test]
    fn validate_connect() {
        // Empty authority prefixes carry no authority to reconcile with Host.
        for target in [
            "/",
            "/foo",
            "/ws?arr[]=1",
            "/ws?token=a@b.com",
            "?query",
            "?a=:1:2",
            "#frag",
        ] {
            assert!(
                validate_request_authority(&request("CONNECT", target, &["other.example"])).is_ok(),
                "{target} should remain application-defined"
            );
        }
        assert!(validate_request_authority(&request("CONNECT", "http:443", &["http"])).is_ok());
        assert!(
            validate_request_authority(&request("CONNECT", "[::1]", &["other.example"])).is_ok()
        );
        assert!(validate_request_authority(&request("CONNECT", "[::1]:443", &["[::1]"])).is_ok());
        assert!(
            validate_request_authority(&request("CONNECT", "authority.example:443", &[])).is_ok()
        );
        assert!(validate_request_authority(&request(
            "CONNECT",
            "authority.example:443",
            &["authority.example:443"]
        ))
        .is_ok());
        assert!(validate_request_authority(&request(
            "CONNECT",
            "authority.example:443/path?arr[]=1&port=:1:2",
            &["authority.example:443"]
        ))
        .is_ok());
        assert!(validate_request_authority(&request(
            "CONNECT",
            "unix:/var/run/x.sock",
            &["other.example"]
        ))
        .is_ok());
        for target in [
            "a.example",
            "a.example:",
            "a.example:443x",
            "a.example:65536",
            "myproto:opaque",
        ] {
            assert!(
                validate_request_authority(&request("CONNECT", target, &["other.example"])).is_ok(),
                "{target} should remain application-defined"
            );
        }
        for target in ["a%2f.example:443", "[0:1:2:3:4:5:6:7:8:9]:443"] {
            assert!(
                validate_request_authority(&request("CONNECT", target, &[target])).is_ok(),
                "{target} should be accepted when Host is byte-identical"
            );
        }
        assert!(validate_request_authority(&request(
            "CONNECT",
            "http://a%2f.example:443/",
            &["a%2f.example:443"]
        ))
        .is_ok());
        for target in [
            "authority.example:443",
            "authority.example:443/path",
            "authority.example:443?query",
            "authority.example:443:80",
            "[::1]:443:80",
            "a.example:80x:443",
            "[a.example:443:80",
            "a.example:443[:80]",
            "[::1]:443",
            "::1",
            "a%2f.example:443",
            "[a[b]:443",
            "[0:1:2:3:4:5:6:7:8:9]:443",
            "http://a%2f.example:443/",
            "https://authority.example/",
        ] {
            assert!(
                validate_request_authority(&request("CONNECT", target, &["other.example"]))
                    .is_err(),
                "{target} should be rejected"
            );
        }

        assert!(validate_request_authority(&request(
            "CONNECT",
            "a.example:443:80",
            &["a.example:443:80"]
        ))
        .is_err());
        assert!(
            validate_request_authority(&request("CONNECT", "a[b]:443", &["a[b]:443"])).is_err()
        );
        assert!(
            validate_request_authority(&request("CONNECT", "[a[b]:443", &["[a[b]:443"])).is_err()
        );
        assert!(
            validate_request_authority(&request("CONNECT", "http://a[b]:443/", &["a[b]:443"]))
                .is_err()
        );
        assert!(validate_request_authority(&request(
            "CONNECT",
            "http://user@authority.example:443/",
            &["user@authority.example:443"]
        ))
        .is_err());

        let mut non_utf8 = RequestHeader::build("CONNECT", b"a.example:443\xff#:80", None).unwrap();
        non_utf8.append_header(header::HOST, "a.example").unwrap();
        assert!(validate_request_authority(&non_utf8).is_err());

        let mut non_utf8 = RequestHeader::build("CONNECT", b"a\xff.example:443", None).unwrap();
        non_utf8
            .append_header(header::HOST, "other.example")
            .unwrap();
        assert!(validate_request_authority(&non_utf8).is_err());
    }
}