http-net 0.9.2

Sans-IO HTTP/1.1 server and client: strict RFC 9112 parsing, smuggling defences, bounded buffers, keep-alive, chunked bodies, upgrades, a blocking std adapter, no third-party dependencies.
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
//! Request smuggling vectors. Each one is a message that two HTTP
//! implementations have been known to frame differently (CL.TE, TE.CL,
//! TE.TE obfuscation, line-ending confusion). Every vector must be refused
//! with its specific error, whole or split, and the connection must not
//! produce a second request from the leftover bytes.

mod common;

use common::{Ev, drive_server};
use http_net::{ClientConn, HttpError, Limits, Request, Response, ServerConn, ServerEvent};

const VECTORS: &[(&str, &[u8], HttpError)] = &[
    (
        "CL.TE: both framings present",
        b"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 6\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\nGPOST / HTTP/1.1\r\n\r\n",
        HttpError::ConflictingFraming,
    ),
    (
        "TE.CL: both framings present, other order",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\n8\r\nSMUGGLED\r\n0\r\n\r\n",
        HttpError::ConflictingFraming,
    ),
    (
        "TE.TE: space before colon",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding : chunked\r\n\r\n",
        HttpError::WhitespaceBeforeColon,
    ),
    (
        "TE.TE: obfuscated coding name",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: xchunked\r\n\r\n",
        HttpError::InvalidTransferEncoding,
    ),
    (
        "TE.TE: second header hides chunked",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\nTransfer-encoding: cow\r\n\r\n",
        HttpError::InvalidTransferEncoding,
    ),
    (
        "TE.TE: identity after chunked",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked, identity\r\n\r\n",
        HttpError::InvalidTransferEncoding,
    ),
    (
        "TE.TE: folded continuation",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding:\r\n chunked\r\n\r\n",
        HttpError::ObsFold,
    ),
    (
        "TE.TE: leading space makes it a fold of the request line",
        b"POST / HTTP/1.1\r\n Transfer-Encoding: chunked\r\nHost: a\r\n\r\n",
        HttpError::ObsFold,
    ),
    (
        "TE.TE: vertical tab before the value",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: \x0bchunked\r\n\r\n",
        HttpError::InvalidHeaderValue,
    ),
    (
        "TE.TE: form feed after the value",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\x0c\r\n\r\n",
        HttpError::InvalidHeaderValue,
    ),
    (
        "TE.TE: NUL inside the field name",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer\x00-Encoding: chunked\r\n\r\n",
        HttpError::InvalidHeaderName,
    ),
    (
        "TE.TE: bare CR inside the value",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chun\rked\r\n\r\n",
        HttpError::BareCr,
    ),
    (
        "bare LF splits a header in two for lenient parsers",
        b"POST / HTTP/1.1\r\nHost: a\r\nX: y\nTransfer-Encoding: chunked\r\n\r\n",
        HttpError::BareLf,
    ),
    (
        "bare CR as a line ending",
        b"POST / HTTP/1.1\r\nHost: a\rContent-Length: 5\r\n\r\n",
        HttpError::BareCr,
    ),
    (
        "duplicate Content-Length with different values",
        b"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 5\r\nContent-Length: 6\r\n\r\nhello!",
        HttpError::DuplicateContentLength,
    ),
    (
        "duplicate Content-Length with equal values",
        b"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 5\r\nContent-Length: 5\r\n\r\nhello",
        HttpError::DuplicateContentLength,
    ),
    (
        "Content-Length as a list",
        b"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 5, 5\r\n\r\nhello",
        HttpError::InvalidContentLength,
    ),
    (
        "hexadecimal Content-Length",
        b"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 0x5\r\n\r\nhello",
        HttpError::InvalidContentLength,
    ),
    (
        "Transfer-Encoding in HTTP/1.0",
        b"POST / HTTP/1.0\r\nTransfer-Encoding: chunked\r\nContent-Length: 4\r\n\r\n",
        HttpError::TransferEncodingInHttp10,
    ),
    (
        "chunk size with a sign",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\n+5\r\nhello\r\n0\r\n\r\n",
        HttpError::InvalidChunkSize,
    ),
    (
        "chunk size wrapping past 64 bits",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\nffffffffffffffff1\r\n",
        HttpError::InvalidChunkSize,
    ),
    (
        "chunk size followed by junk instead of an extension",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\n5 x\r\nhello\r\n0\r\n\r\n",
        HttpError::InvalidChunkExtension,
    ),
    (
        "chunk data longer than declared",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nhello\r\n0\r\n\r\n",
        HttpError::InvalidChunkTerminator,
    ),
    (
        "chunk extension with an unterminated quote swallowing the next chunk",
        b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\n5;a=\"x\r\nhello\r\n0\r\n\r\n",
        HttpError::InvalidChunkExtension,
    ),
    (
        "two Host fields",
        b"GET / HTTP/1.1\r\nHost: good.example\r\nHost: evil.example\r\n\r\n",
        HttpError::InvalidHost,
    ),
];

#[test]
fn test_smuggling_vectors_are_refused() {
    for (name, input, expected) in VECTORS {
        let whole = drive_server(&[input], Limits::new());
        assert_eq!(whole.last(), Some(&Ev::Err(*expected)), "{name}: {whole:?}");
        // No request is ever reported from a refused message's bytes.
        let heads = whole
            .iter()
            .filter(|e| matches!(e, Ev::Head { .. }))
            .count();
        assert!(heads <= 1, "{name}: {whole:?}");
        for cut in 1..input.len() {
            let split = drive_server(&[&input[..cut], &input[cut..]], Limits::new());
            assert_eq!(whole, split, "{name}: split at {cut} changed the result");
        }
    }
}

#[test]
fn test_connection_is_dead_after_an_error() {
    let mut conn = ServerConn::new();
    let _ = conn.feed(
        b"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 1\r\nContent-Length: 1\r\n\r\nx\
          GET /next HTTP/1.1\r\nHost: a\r\n\r\n",
    );
    assert_eq!(conn.poll().unwrap_err(), HttpError::DuplicateContentLength);
    // The pipelined request after the bad one is never parsed.
    assert!(matches!(conn.poll(), Ok(ServerEvent::Closed)));
    assert!(matches!(conn.poll(), Ok(ServerEvent::Closed)));
    let mut out = Vec::new();
    conn.respond(&Response::new(400), &mut out).unwrap();
    assert!(out.windows(17).any(|w| w == b"connection: close"));
    assert!(matches!(conn.poll(), Ok(ServerEvent::Closed)));
}

#[test]
fn test_pipelined_requests_are_framed_by_their_own_lengths() {
    // The body of the first request looks like a request; it must stay body.
    let input = b"POST /a HTTP/1.1\r\nHost: a\r\nContent-Length: 30\r\n\r\n\
                  GET /smuggled HTTP/1.1\r\nX: y\r\n\
                  GET /b HTTP/1.1\r\nHost: a\r\n\r\n";
    let events = drive_server(&[input], Limits::new());
    let targets: Vec<&str> = events
        .iter()
        .filter_map(|e| match e {
            Ev::Head { target, .. } => Some(target.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(targets, ["/a", "/b"]);
    assert!(events.contains(&Ev::Body(b"GET /smuggled HTTP/1.1\r\nX: y\r\n".to_vec())));
}

#[test]
fn test_outgoing_messages_cannot_inject_framing() {
    let mut conn = ServerConn::new();
    let _ = conn.feed(b"GET / HTTP/1.1\r\nHost: a\r\n\r\n");
    while !matches!(conn.poll().unwrap(), ServerEvent::RequestEnd) {}
    let mut out = Vec::new();
    for (bad, expected) in [
        (
            Response::new(200).header("x", "a\r\nContent-Length: 0"),
            HttpError::BareCr,
        ),
        (
            Response::new(200).header("x", "a\nb"),
            HttpError::InvalidHeaderValue,
        ),
        (
            Response::new(200).header("Transfer-Encoding", "chunked"),
            HttpError::ReservedHeader,
        ),
        (
            Response::new(200).header("Content-Length", "1"),
            HttpError::ReservedHeader,
        ),
        (
            Response::new(200).header("Connection", "keep-alive"),
            HttpError::ReservedHeader,
        ),
        (
            Response::new(200).header("Upgrade", "x"),
            HttpError::ReservedHeader,
        ),
        (
            Response::new(200).header("x\r\ny", "1"),
            HttpError::InvalidHeaderName,
        ),
    ] {
        assert_eq!(conn.respond(&bad, &mut out), Err(expected), "{bad:?}");
        assert!(out.is_empty(), "nothing is written for a refused response");
    }
    conn.respond(&Response::new(200), &mut out).unwrap();
}

/// T-22, response splitting and CRLF injection through the builders: a CR,
/// LF, or space in a request target or method, and a NUL, VT, CR, bare LF,
/// or surrounding space in a field value, is refused with its documented
/// error when the message is written (`send_request` / `respond`). Nothing
/// is written, and the connection stays usable for a valid message.
#[test]
fn test_builder_injection_is_refused_and_writes_nothing() {
    let mut client = ClientConn::new();
    let mut out = Vec::new();
    for (request, expected) in [
        (
            Request::get("/a HTTP/1.1\r\nX: y"),
            HttpError::InvalidTarget,
        ),
        (Request::get("/a\r\nX: y"), HttpError::InvalidTarget),
        (Request::get("/a\nX: y"), HttpError::InvalidTarget),
        (Request::get("/a b"), HttpError::InvalidTarget),
        (Request::new("GET\r\n", "/"), HttpError::InvalidMethod),
        (Request::new("GET /x", "/"), HttpError::InvalidMethod),
        (Request::new("G\nET", "/"), HttpError::InvalidMethod),
        (
            Request::get("/").header("x", "a\r\nX-Injected: 1"),
            HttpError::BareCr,
        ),
        (
            Request::get("/").header("x", "a\nX-Injected: 1"),
            HttpError::InvalidHeaderValue,
        ),
        (
            Request::get("/").header("x", "a\0b"),
            HttpError::InvalidHeaderValue,
        ),
    ] {
        let request = request.header("host", "a");
        assert_eq!(
            client.send_request(&request, &mut out),
            Err(expected),
            "{request:?}"
        );
        assert!(out.is_empty(), "{}", String::from_utf8_lossy(&out));
    }
    client
        .send_request(&Request::get("/").header("host", "a"), &mut out)
        .unwrap();
    assert!(out.starts_with(b"GET / HTTP/1.1\r\n"));

    let mut conn = ServerConn::new();
    let _ = conn.feed(b"GET / HTTP/1.1\r\nHost: a\r\n\r\n");
    while !matches!(conn.poll().unwrap(), ServerEvent::RequestEnd) {}
    let mut out = Vec::new();
    for (value, expected) in [
        (&b"a\0b"[..], HttpError::InvalidHeaderValue),
        (b"a\x0bb", HttpError::InvalidHeaderValue),
        (b"a ", HttpError::InvalidHeaderValue),
        (b" a", HttpError::InvalidHeaderValue),
        (b"a\t", HttpError::InvalidHeaderValue),
        (b"a\nX-Injected: 1", HttpError::InvalidHeaderValue),
        (b"a\r\nX-Injected: 1", HttpError::BareCr),
    ] {
        let response = Response::new(200).header("x-value", value);
        assert_eq!(
            conn.respond(&response, &mut out),
            Err(expected),
            "{:?}",
            String::from_utf8_lossy(value)
        );
        assert!(out.is_empty(), "{}", String::from_utf8_lossy(&out));
    }
    conn.respond(&Response::new(200), &mut out).unwrap();
    assert!(out.starts_with(b"HTTP/1.1 200 OK\r\n"));
}

/// T-23, caller-set framing fields on the request side: `content-length`,
/// `transfer-encoding`, `connection`, and `upgrade`, in any case, are owned
/// by the connection. Setting one by hand is `ReservedHeader` at
/// `send_request`, nothing is written, and the connection stays usable.
#[test]
fn test_request_builder_refuses_framing_fields_in_any_case() {
    let mut conn = ClientConn::new();
    let mut out = Vec::new();
    for name in [
        "content-length",
        "transfer-encoding",
        "connection",
        "upgrade",
    ] {
        let mixed: String = name
            .chars()
            .enumerate()
            .map(|(i, c)| {
                if i % 2 == 0 {
                    c.to_ascii_uppercase()
                } else {
                    c
                }
            })
            .collect();
        for spelled in [name.to_string(), name.to_ascii_uppercase(), mixed] {
            let request = Request::get("/").header("host", "a").header(&spelled, "x");
            assert_eq!(
                conn.send_request(&request, &mut out),
                Err(HttpError::ReservedHeader),
                "{spelled}"
            );
            assert!(
                out.is_empty(),
                "{spelled}: {}",
                String::from_utf8_lossy(&out)
            );
        }
    }
    conn.send_request(&Request::get("/").header("host", "a"), &mut out)
        .unwrap();
}

/// T-3, TE.TE across fields: the coding list is every `Transfer-Encoding`
/// field joined in order, so `chunked` in two fields repeats it
/// (`InvalidTransferEncoding`), and `gzip` then `chunked` in two fields
/// asks for a coding other than chunked (`UnsupportedTransferEncoding`,
/// answered 501). Whole and at every split, with no body delivered.
#[test]
fn test_transfer_encoding_split_across_fields_is_refused() {
    for (input, expected) in [
        (
            &b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n"[..],
            HttpError::InvalidTransferEncoding,
        ),
        (
            b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n",
            HttpError::UnsupportedTransferEncoding,
        ),
    ] {
        let name = String::from_utf8_lossy(input);
        let whole = drive_server(&[input], Limits::new());
        assert_eq!(whole, [Ev::Err(expected)], "{name}");
        for cut in 1..input.len() {
            let split = drive_server(&[&input[..cut], &input[cut..]], Limits::new());
            assert_eq!(whole, split, "{name}: split at {cut} changed the result");
        }
    }
    assert_eq!(HttpError::InvalidTransferEncoding.status(), Some(400));
    assert_eq!(HttpError::UnsupportedTransferEncoding.status(), Some(501));
}

/// T-9, Funky Chunks (TERM.EXT and EXT.TERM): a CR or LF inside a chunk
/// extension that one hop reads as a line end and another as extension
/// bytes (Netty CVE-2025-58056 and CVE-2026-33870, Jetty CVE-2026-2332,
/// ASP.NET Core CVE-2025-55315). Chunk lines end only at CRLF: a lone LF is
/// `BareLf`, and a CR inside an extension or a quoted value fails the
/// extension grammar. Nothing after the bad chunk line is parsed, whole or
/// split at any byte.
const FUNKY_CHUNKS: &[(&str, &[u8], HttpError)] = &[
    (
        "TERM.EXT: LF ends the extension for a lenient hop",
        b"5;a=b\nX\r\nhello\r\n0\r\n\r\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n",
        HttpError::BareLf,
    ),
    (
        "EXT.TERM: CR inside an extension name",
        b"5;a\rb\r\nhello\r\n0\r\n\r\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n",
        HttpError::InvalidChunkExtension,
    ),
    (
        "CR inside a quoted extension value",
        b"5;a=\"x\ry\"\r\nhello\r\n0\r\n\r\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n",
        HttpError::InvalidChunkExtension,
    ),
    (
        "LF inside a quoted extension",
        b"5;\"\n\"\r\nhello\r\n0\r\n\r\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n",
        HttpError::BareLf,
    ),
    (
        "CR after an extension value",
        b"5;a=b\rX\r\nhello\r\n0\r\n\r\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n",
        HttpError::InvalidChunkExtension,
    ),
    (
        "LF straight after the chunk size",
        b"5\nhello\r\n0\r\n\r\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n",
        HttpError::BareLf,
    ),
    (
        "LF after the last chunk's extension",
        b"0;a=b\n\r\n\r\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n",
        HttpError::BareLf,
    ),
];

/// T-9: every Funky Chunks vector is refused with its exact error, whole and
/// at every split, and the request smuggled after it is never parsed.
#[test]
fn test_funky_chunks_vectors_split_anywhere_are_refused() {
    let head: &[u8] = b"POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\n";
    for (name, chunks, expected) in FUNKY_CHUNKS {
        let input = [head, chunks].concat();
        let whole = drive_server(&[&input], Limits::new());
        assert_eq!(whole.last(), Some(&Ev::Err(*expected)), "{name}: {whole:?}");
        let targets: Vec<&str> = whole
            .iter()
            .filter_map(|e| match e {
                Ev::Head { target, .. } => Some(target.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(targets, ["/"], "{name}: {whole:?}");
        assert!(
            !whole.iter().any(|e| matches!(e, Ev::Body(_))),
            "{name}: data of the bad chunk was delivered: {whole:?}"
        );
        for cut in 1..input.len() {
            let split = drive_server(&[&input[..cut], &input[cut..]], Limits::new());
            assert_eq!(whole, split, "{name}: split at {cut} changed the result");
        }
    }
}