base-http1 0.3.0

Native HTTP/1 framing over Base scheduler stream capabilities
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
// Released under the MIT License.
// Copyright, 2026, by Samuel Williams.

use crate::support::{exchange, failing_output, is_invalid, is_io, output, unflushable_output};
use base_http::{
    Fields, InterimHandler, Protocol, Response, ResponseMetadata, Status, Version,
    body::{BodyFrame, BufferedBody, ReadableBody},
};
use base_http1::Error;
use base_scheduler::Cancellation;
use futures_lite::future::{block_on, yield_now};
use std::{collections::VecDeque, io};

const GET: &[u8] = b"GET / HTTP/1.1\r\nHost: x\r\n\r\n";
const GET_10: &[u8] = b"GET / HTTP/1.0\r\n\r\n";
const UPGRADE: &[u8] = b"GET / HTTP/1.1\r\nHost: x\r\nConnection: upgrade\r\nUpgrade: echo\r\n\r\n";

/// A scripted body. `length` and `trailers` are its hints, and `suspend` makes its first read wait once.
struct Script {
    frames: VecDeque<Result<BodyFrame<Vec<u8>>, io::Error>>,
    length: Option<u64>,
    trailers: bool,
    ready: bool,
    suspend: bool,
    cancel: Option<Cancellation>,
}

impl Script {
    fn new(frames: impl IntoIterator<Item = Result<BodyFrame<Vec<u8>>, io::Error>>) -> Self {
        Self {
            frames: frames.into_iter().collect(),
            length: None,
            trailers: true,
            ready: true,
            suspend: false,
            cancel: None,
        }
    }
}

impl ReadableBody for Script {
    type Data = Vec<u8>;
    type Error = io::Error;
    fn may_have_trailers(&self) -> bool {
        self.trailers
    }
    fn is_ready(&self) -> bool {
        self.ready
    }
    fn length(&self) -> Option<u64> {
        self.length
    }
    fn close(&mut self, _: Option<io::Error>) {}
    async fn read(&mut self, _: &Cancellation) -> Result<BodyFrame<Vec<u8>>, io::Error> {
        if std::mem::take(&mut self.suspend) {
            yield_now().await;
        }
        // Cancellation can arrive while the body is producing a frame.
        if let Some(cancellation) = &self.cancel {
            cancellation.cancel();
        }
        self.frames.pop_front().unwrap_or(Ok(BodyFrame::End))
    }
}

fn data(bytes: &[u8]) -> Result<BodyFrame<Vec<u8>>, io::Error> {
    Ok(BodyFrame::Data {
        data: bytes.to_vec(),
        end: false,
    })
}

fn write<B: ReadableBody>(
    request: &'static [u8],
    response: &mut Response<B>,
) -> Result<String, Error> {
    let (mut output, bytes) = output();
    block_on(output.write_response(&exchange(request), response, &Cancellation::never()))?;
    Ok(String::from_utf8(bytes.lock().unwrap().clone()).unwrap())
}

#[test]
fn rejection_closes_output_once() {
    let (mut output, bytes) = output();
    let never = Cancellation::never();
    let cancelled = Cancellation::new();
    cancelled.cancel();
    assert!(matches!(
        block_on(output.reject(Status::BAD_REQUEST, &cancelled)),
        Err(Error::Cancelled)
    ));
    assert!(output.is_usable());
    block_on(output.reject(Status::BAD_REQUEST, &never)).unwrap();
    assert_eq!(
        *bytes.lock().unwrap(),
        b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
    );
    assert!(!output.is_usable());
    assert!(is_invalid(
        block_on(output.reject(Status::BAD_REQUEST, &never)),
        "response output is not reusable"
    ));

    let mut output = failing_output();
    let result = block_on(output.reject(Status::BAD_REQUEST, &never));
    assert!(is_io(result, io::ErrorKind::BrokenPipe));
    assert!(!output.is_usable());

    // Bytes accepted by the transport are not delivered until it flushes.
    let (mut output, bytes) = unflushable_output();
    let result = block_on(output.reject(Status::BAD_REQUEST, &never));
    assert!(is_io(result, io::ErrorKind::TimedOut));
    assert!(
        bytes
            .lock()
            .unwrap()
            .starts_with(b"HTTP/1.1 400 Bad Request\r\n")
    );
    assert!(!output.is_usable());
}

#[test]
fn a_cancelled_response_writes_nothing() {
    let (mut output, bytes) = output();
    let cancelled = Cancellation::new();
    cancelled.cancel();
    let mut response = Response::empty(Status::OK);
    let result = block_on(output.write_response(&exchange(GET), &mut response, &cancelled));
    assert!(matches!(result, Err(Error::Cancelled)));
    assert!(bytes.lock().unwrap().is_empty());
    assert!(output.is_usable());
}

#[test]
fn invalid_responses_are_rejected_before_any_output() {
    type Case = (&'static [u8], Response<Script>, &'static str);
    let response = |status: u16| Response::new(Status::new(status).unwrap(), Script::new([]));
    let with = |status: u16, fields: &[(&str, &str)]| {
        let mut response = response(status);
        for (name, value) in fields {
            response.fields.add(name, value).unwrap();
        }
        response
    };
    let with_protocol = |status: u16| {
        let mut response = response(status);
        response.protocol = Some(Protocol::new("echo").unwrap());
        response
    };
    let mut cases: Vec<Case> = vec![
        (GET, response(103), "final response required"),
        (
            GET,
            with(200, &[("Content-Length", "0"), ("Content-Length", "0")]),
            "duplicate singleton field",
        ),
        (
            GET,
            with(200, &[("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "chunked")]),
            "duplicate singleton field",
        ),
        (GET, with(200, &[("Content-Length", "x")]), "invalid content-length"),
        (
            b"POST / HTTP/1.1\r\nHost: x\r\nConnection: upgrade\r\nUpgrade: echo\r\nContent-Length: 1\r\n\r\n",
            with_protocol(101),
            "switch with unread request body",
        ),
        (UPGRADE, with(101, &[("Upgrade", "echo"), ("Content-Length", "0")]), "framing fields on tunnel response"),
        (GET, with_protocol(101), "unsolicited upgrade"),
        (UPGRADE, response(101), "missing selected protocol"),
        (
            b"CONNECT example:443 HTTP/1.1\r\nHost: example:443\r\n\r\n",
            with_protocol(200),
            "protocol on traditional CONNECT",
        ),
        (GET, with_protocol(200), "protocol without upgrade status"),
        (GET_10, with(200, &[("Transfer-Encoding", "chunked")]), "HTTP/1.0 transfer-encoding"),
        (
            b"HEAD / HTTP/1.1\r\nHost: x\r\n\r\n",
            with(200, &[("Transfer-Encoding", "chunked")]),
            "trailers or transfer-encoding on bodyless response",
        ),
        (GET, with(204, &[("Content-Length", "0")]), "content-length on 204"),
        (GET, with(205, &[("Content-Length", "1")]), "content on 205"),
    ];
    let mut versioned = response(200);
    versioned.version = Some(Version::Http10);
    cases.push((GET, versioned, "response version differs from request"));
    let mut declared = with(200, &[("Transfer-Encoding", "chunked")]);
    declared.content_length = Some(0);
    cases.push((GET, declared, "content-length with transfer-encoding"));
    let mut known = response(205);
    known.body.length = Some(1);
    cases.push((GET, known, "content on 205"));

    for (request, mut response, reason) in cases {
        let (mut output, bytes) = output();
        let result = block_on(output.write_response(
            &exchange(request),
            &mut response,
            &Cancellation::never(),
        ));
        assert!(is_invalid(result, reason), "{reason}");
        assert!(bytes.lock().unwrap().is_empty(), "{reason}");
    }
}

#[test]
fn reset_content_and_transfer_encoding_select_their_framing() {
    let mut empty = Response::new(Status::RESET_CONTENT, BufferedBody::<Vec<u8>>::default());
    assert_eq!(
        write(GET, &mut empty).unwrap(),
        "HTTP/1.1 205 Reset Content\r\nContent-Length: 0\r\n\r\n"
    );

    // A Trailer field is only a hint, so a body without trailers keeps fixed-length framing.
    let mut announced = Response::new(Status::RESET_CONTENT, BufferedBody::<Vec<u8>>::default());
    announced.fields.add("Trailer", "x-digest").unwrap();
    assert_eq!(
        write(GET, &mut announced).unwrap(),
        "HTTP/1.1 205 Reset Content\r\nTrailer: x-digest\r\nContent-Length: 0\r\n\r\n"
    );
    let mut announced = Response::new(Status::OK, BufferedBody::from(b"hi".to_vec()));
    announced.fields.add("Trailer", "x-digest").unwrap();
    assert_eq!(
        write(GET, &mut announced).unwrap(),
        "HTTP/1.1 200 OK\r\nTrailer: x-digest\r\nContent-Length: 2\r\n\r\nhi"
    );

    let mut chunked = Response::new(Status::OK, BufferedBody::from(b"hi".to_vec()));
    chunked.fields.add("Transfer-Encoding", "chunked").unwrap();
    assert_eq!(
        write(GET, &mut chunked).unwrap(),
        "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nhi\r\n0\r\n\r\n"
    );
}

#[test]
fn an_upgrade_replaces_the_application_upgrade_field_with_the_selected_protocol() {
    let mut response = Response::new(
        Status::SWITCHING_PROTOCOLS,
        BufferedBody::<Vec<u8>>::default(),
    );
    response.fields.add("Server", "example").unwrap();
    response.fields.add("upgrade", "ECHO").unwrap();
    assert_eq!(
        write(UPGRADE, &mut response).unwrap(),
        "HTTP/1.1 101 Switching Protocols\r\nServer: example\r\nUpgrade: ECHO\r\nConnection: upgrade\r\n\r\n"
    );
}

// HTTP/1.0 has no chunked framing, so trailers are validated and dropped, from fixed-length and close-delimited bodies alike.
#[test]
fn trailers_on_an_http_10_body_are_dropped_after_its_data() {
    let trailed = |length| {
        let mut trailers = Fields::new();
        trailers.add("x-digest", "1").unwrap();
        let mut body = Script::new([
            data(b"hi"),
            Ok(BodyFrame::Headers {
                fields: trailers,
                end: true,
            }),
        ]);
        body.length = length;
        Response::new(Status::OK, body)
    };
    assert_eq!(
        write(GET_10, &mut trailed(Some(2))).unwrap(),
        "HTTP/1.0 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nhi"
    );
    assert_eq!(
        write(GET_10, &mut trailed(None)).unwrap(),
        "HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nhi"
    );

    // A Trailer field is only a hint, so it neither selects framing nor is refused.
    let mut announced = trailed(Some(2));
    announced.fields.add("Trailer", "x-digest").unwrap();
    assert_eq!(
        write(GET_10, &mut announced).unwrap(),
        "HTTP/1.0 200 OK\r\nTrailer: x-digest\r\nContent-Length: 2\r\nConnection: close\r\n\r\nhi"
    );

    // A 205 whose body may have trailers still declares that it is empty.
    let mut reset = Response::new(Status::RESET_CONTENT, Script::new([]));
    reset.fields.add("Trailer", "x-digest").unwrap();
    assert_eq!(
        write(GET_10, &mut reset).unwrap(),
        "HTTP/1.0 205 Reset Content\r\nTrailer: x-digest\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
    );

    // Dropped trailers are still validated, as chunked framing would.
    let mut trailers = Fields::new();
    trailers.add("content-length", "2").unwrap();
    let mut body = Script::new([
        data(b"hi"),
        Ok(BodyFrame::Headers {
            fields: trailers,
            end: true,
        }),
    ]);
    body.length = Some(2);
    let mut response = Response::new(Status::OK, body);
    let error = write(GET_10, &mut response).expect_err("an invalid trailer");
    assert!(
        matches!(&error, Error::Body(source) if source.to_string().contains("content-length")),
        "{error:?}"
    );
}

// A body that disclaims trailers gets fixed-length framing on HTTP/1.1, which cannot carry the trailers it then produces.
#[test]
fn unannounced_trailers_on_an_http_11_fixed_body_are_rejected() {
    let mut trailers = Fields::new();
    trailers.add("x-digest", "1").unwrap();
    let mut body = Script::new([
        data(b"hi"),
        Ok(BodyFrame::Headers {
            fields: trailers,
            end: true,
        }),
    ]);
    body.length = Some(2);
    body.trailers = false;
    let mut response = Response::new(Status::OK, body);
    assert!(is_invalid(
        write(GET, &mut response),
        "trailers require chunked framing"
    ));
}

#[test]
fn output_failures_at_each_flush_point_are_reported() {
    const EXPECT: &[u8] = b"GET / HTTP/1.1\r\nHost: x\r\nConnection: upgrade\r\nUpgrade: echo\r\nExpect: 100-continue\r\n\r\n";
    let switching = || {
        let mut response = Response::new(Status::SWITCHING_PROTOCOLS, Script::new([]));
        response.protocol = Some(Protocol::new("echo").unwrap());
        response
    };
    let mut not_ready = Script::new([]);
    not_ready.ready = false;
    let mut suspending = Script::new([]);
    suspending.suspend = true;
    for (request, mut response) in [
        (EXPECT, switching()),
        (UPGRADE, switching()),
        (GET, Response::new(Status::OK, not_ready)),
        (GET, Response::new(Status::OK, suspending)),
    ] {
        let mut output = failing_output();
        let result = block_on(output.write_response(
            &exchange(request),
            &mut response,
            &Cancellation::never(),
        ));
        assert!(is_io(result, io::ErrorKind::BrokenPipe));
        assert!(!output.is_usable());
    }
}

#[test]
fn cancellation_during_a_body_read_is_reported_as_cancellation() {
    for frame in [data(b"late"), Err(io::Error::other("stopped"))] {
        let cancellation = Cancellation::new();
        let mut body = Script::new([frame]);
        body.cancel = Some(cancellation.clone());
        let mut response = Response::new(Status::OK, body);
        let (mut output, _) = output();
        let result = block_on(output.write_response(&exchange(GET), &mut response, &cancellation));
        assert!(matches!(result, Err(Error::Cancelled)));
        assert!(!output.is_usable());
    }
}

#[test]
fn invalid_interim_responses_are_rejected_before_any_output() {
    let never = Cancellation::never();
    let cancelled = Cancellation::new();
    cancelled.cancel();
    let early_hints = || ResponseMetadata::new(Status::new(103).unwrap());
    let with_field = |name: &str| {
        let mut response = early_hints();
        response.fields.add(name, "0").unwrap();
        response
    };
    let mut length = early_hints();
    length.content_length = Some(0);
    let mut protocol = early_hints();
    protocol.protocol = Some(Protocol::new("echo").unwrap());
    for (version, response, cancellation, reason) in [
        (
            Version::Http11,
            ResponseMetadata::new(Status::OK),
            &never,
            Some("invalid interim status"),
        ),
        (
            Version::Http11,
            ResponseMetadata::new(Status::SWITCHING_PROTOCOLS),
            &never,
            Some("invalid interim status"),
        ),
        (
            Version::Http10,
            early_hints(),
            &never,
            Some("HTTP/1.0 interim response"),
        ),
        (
            Version::Http11,
            with_field("Content-Length"),
            &never,
            Some("invalid interim framing"),
        ),
        (
            Version::Http11,
            with_field("Transfer-Encoding"),
            &never,
            Some("invalid interim framing"),
        ),
        (
            Version::Http11,
            length,
            &never,
            Some("invalid interim framing"),
        ),
        (
            Version::Http11,
            protocol,
            &never,
            Some("invalid interim framing"),
        ),
        (Version::Http11, early_hints(), &cancelled, None),
    ] {
        let (mut output, bytes) = output();
        let result = block_on(
            output
                .interim(version)
                .on_interim_response(response, cancellation),
        );
        match reason {
            Some(reason) => assert!(is_invalid(result, reason), "{reason}"),
            None => assert!(matches!(result, Err(Error::Cancelled))),
        }
        assert!(bytes.lock().unwrap().is_empty());
        assert!(output.is_usable());
    }

    let (mut output, _) = output();
    block_on(output.reject(Status::BAD_REQUEST, &never)).unwrap();
    let result = block_on(
        output
            .interim(Version::Http11)
            .on_interim_response(early_hints(), &never),
    );
    assert!(is_invalid(result, "response output is not reusable"));
}

// HEAD, 204 and 304 responses never carry a body, so a body that may have trailers leaves them without framing.
#[test]
fn bodyless_responses_skip_the_trailer_rule() {
    const HEAD: &[u8] = b"HEAD / HTTP/1.1\r\nHost: x\r\n\r\n";
    for (request, status, expected) in [
        (HEAD, Status::OK, "HTTP/1.1 200 OK\r\n\r\n"),
        (GET, Status::NO_CONTENT, "HTTP/1.1 204 No Content\r\n\r\n"),
        (
            GET,
            Status::NOT_MODIFIED,
            "HTTP/1.1 304 Not Modified\r\n\r\n",
        ),
    ] {
        let mut response = Response::new(status, Script::new([]));
        assert!(response.body.may_have_trailers());
        assert_eq!(write(request, &mut response).unwrap(), expected);
    }
}

// Tunnel output after a successful CONNECT is raw bytes, not an HTTP/1.0 body, so a trailer frame is refused rather than dropped.
#[test]
fn http_10_tunnels_refuse_trailers() {
    let mut response = Response::new(
        Status::OK,
        Script::new([
            data(b"raw"),
            Ok(BodyFrame::Headers {
                fields: Fields::try_from_pairs([("x-digest", "1")]).unwrap(),
                end: true,
            }),
        ]),
    );
    let result = write(b"CONNECT example:443 HTTP/1.0\r\n\r\n", &mut response);
    assert!(is_invalid(result, "trailers require chunked framing"));
}