This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-http-transport-304-content-length in repository https://gitbox.apache.org/repos/asf/opendal.git
commit df57b90a139935ed873aab117e380b29743c1674 Author: Xuanwo <[email protected]> AuthorDate: Mon Nov 23 09:49:48 2026 +0100 fix(http-transports): ignore Content-Length for bodyless responses RFC 9110 §8.6 makes responses to HEAD and 1xx, 204, and 304 responses bodyless. A 304 may still carry the selected representation's Content-Length, so it must not size the response body. Otherwise reading a 304 as an empty body fails with got too little data instead of reaching services' ConditionNotMatch handling. --- core/http-transports/cyper/src/lib.rs | 17 +++- .../http-transports/cyper/tests/bodyless_status.rs | 97 +++++++++++++++++++ core/http-transports/reqwest/src/lib.rs | 17 ++-- .../reqwest/tests/bodyless_status.rs | 104 +++++++++++++++++++++ 4 files changed, 224 insertions(+), 11 deletions(-) diff --git a/core/http-transports/cyper/src/lib.rs b/core/http-transports/cyper/src/lib.rs index 69ac51ccf5..d1331fefe2 100644 --- a/core/http-transports/cyper/src/lib.rs +++ b/core/http-transports/cyper/src/lib.rs @@ -34,6 +34,7 @@ use futures::future::Either; use futures::future::select; use http::Request; use http::Response; +use http::StatusCode; use opendal_core::Buffer; use opendal_core::Error; use opendal_core::ErrorKind; @@ -221,17 +222,23 @@ async fn fetch( .set_source(err) })?; - // HEAD responses have no body even when their headers describe the resource - // size. Encoded response bodies do not have the encoded content length after - // decoding. - let content_length = if is_head || parse_content_encoding(resp.headers())?.is_some() { + // RFC 9110 §8.6: responses to HEAD and 1xx, 204, and 304 responses never + // carry a message body. A 304 may still carry the Content-Length of the + // selected representation, so it cannot validate the body. Encoded bodies + // also do not have the encoded content length after decoding. + let status = resp.status(); + let is_bodyless = is_head + || status == StatusCode::NOT_MODIFIED + || status == StatusCode::NO_CONTENT + || status.is_informational(); + let content_length = if is_bodyless || parse_content_encoding(resp.headers())?.is_some() { None } else { parse_content_length(resp.headers())? }; let mut builder = Response::builder() - .status(resp.status()) + .status(status) .version(resp.version()) .extension(uri.clone()); *builder.headers_mut().unwrap() = std::mem::take(resp.headers_mut()); diff --git a/core/http-transports/cyper/tests/bodyless_status.rs b/core/http-transports/cyper/tests/bodyless_status.rs new file mode 100644 index 0000000000..0c5c00343b --- /dev/null +++ b/core/http-transports/cyper/tests/bodyless_status.rs @@ -0,0 +1,97 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::io::BufRead; +use std::io::BufReader; +use std::io::Write; +use std::net::TcpListener; +use std::thread; +use std::time::Duration; + +use compio::runtime::Runtime; +use http::Request; +use http::StatusCode; +use opendal_core::Buffer; +use opendal_core::ErrorKind; +use opendal_core::HttpBody; +use opendal_core::HttpTransporter; +use opendal_core::Result; +use opendal_core::raw::oio::ReadStream; +use opendal_http_transport_cyper::CyperTransport; + +const TIMEOUT: Duration = Duration::from_secs(10); + +fn fetch(raw_response: &'static [u8]) -> (StatusCode, Result<Buffer>) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let server = thread::spawn(move || { + let (mut connection, _) = listener.accept().unwrap(); + let mut lines = BufReader::new(&mut connection).lines(); + while !lines.next().unwrap().unwrap().is_empty() {} + connection.write_all(raw_response).unwrap(); + connection.flush().unwrap(); + }); + + let transport = HttpTransporter::new(CyperTransport::new()); + let request = Request::get(format!("{endpoint}/object")) + .body(Buffer::new()) + .unwrap(); + let runtime = Runtime::new().unwrap(); + let (status, data) = runtime + .block_on(compio::time::timeout(TIMEOUT, async { + let response = transport.fetch(request).await.unwrap(); + let status = response.status(); + let mut body: HttpBody = response.into_body(); + (status, body.read_all().await) + })) + .expect("transport timed out"); + server.join().unwrap(); + (status, data) +} + +#[test] +fn not_modified_ignores_content_length() { + let (status, data) = fetch(b"HTTP/1.1 304 Not Modified\r\nContent-Length: 5\r\n\r\n"); + + assert_eq!(status, StatusCode::NOT_MODIFIED); + assert!(data.unwrap().is_empty()); +} + +#[test] +fn no_content_ignores_content_length() { + let (status, data) = fetch(b"HTTP/1.1 204 No Content\r\nContent-Length: 5\r\n\r\n"); + + assert_eq!(status, StatusCode::NO_CONTENT); + assert!(data.unwrap().is_empty()); +} + +#[test] +fn ok_validates_content_length() { + let (status, data) = fetch(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\na"); + + assert_eq!(status, StatusCode::OK); + // The HTTP client rejects the incomplete message before `HttpBody` reaches + // the end of the stream, so the response must fail instead of being read + // as an empty body. + let error = data.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Unexpected); + assert!(error.is_temporary()); + assert!( + error.message().contains("read data from http response"), + "unexpected error: {error}" + ); +} diff --git a/core/http-transports/reqwest/src/lib.rs b/core/http-transports/reqwest/src/lib.rs index 9c706bf033..4b94228f50 100644 --- a/core/http-transports/reqwest/src/lib.rs +++ b/core/http-transports/reqwest/src/lib.rs @@ -28,6 +28,7 @@ use std::sync::LazyLock; use futures::TryStreamExt; use http::Request; use http::Response; +use http::StatusCode; use opendal_core::Buffer; use opendal_core::Error; use opendal_core::ErrorKind; @@ -149,18 +150,22 @@ impl HttpTransport for ReqwestTransport { .set_source(err.without_url()) })?; - // Get content length from header so that we can check it. - // - // - If the request method is HEAD, we will ignore content length. - // - If response contains content_encoding, we should omit its content length. - let content_length = if is_head || parse_content_encoding(resp.headers())?.is_some() { + // RFC 9110 §8.6: responses to HEAD and 1xx, 204, and 304 responses + // never carry a message body. A 304 may still carry the Content-Length + // of the selected representation, so it cannot validate the body. + let status = resp.status(); + let is_bodyless = is_head + || status == StatusCode::NOT_MODIFIED + || status == StatusCode::NO_CONTENT + || status.is_informational(); + let content_length = if is_bodyless || parse_content_encoding(resp.headers())?.is_some() { None } else { parse_content_length(resp.headers())? }; let mut hr = Response::builder() - .status(resp.status()) + .status(status) // Insert uri into response extension so that we can fetch // it later. .extension(uri.clone()); diff --git a/core/http-transports/reqwest/tests/bodyless_status.rs b/core/http-transports/reqwest/tests/bodyless_status.rs new file mode 100644 index 0000000000..53fd5fd639 --- /dev/null +++ b/core/http-transports/reqwest/tests/bodyless_status.rs @@ -0,0 +1,104 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +#![cfg(not(target_arch = "wasm32"))] + +use std::time::Duration; + +use http::Request; +use http::StatusCode; +use opendal_core::Buffer; +use opendal_core::ErrorKind; +use opendal_core::HttpBody; +use opendal_core::HttpTransporter; +use opendal_core::Result; +use opendal_core::raw::oio::ReadStream; +use opendal_http_transport_reqwest::ReqwestTransport; +use tokio::io::AsyncBufReadExt; +use tokio::io::AsyncWriteExt; +use tokio::io::BufReader; +use tokio::net::TcpListener; + +const TIMEOUT: Duration = Duration::from_secs(10); + +async fn fetch(raw_response: &'static [u8]) -> (StatusCode, Result<Buffer>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (connection, _) = listener.accept().await.unwrap(); + let mut lines = BufReader::new(connection).lines(); + while !lines.next_line().await.unwrap().unwrap().is_empty() {} + let mut connection = lines.into_inner().into_inner(); + connection.write_all(raw_response).await.unwrap(); + connection.flush().await.unwrap(); + }); + + let client = reqwest::Client::builder() + .no_proxy() + .timeout(TIMEOUT) + .build() + .unwrap(); + let transport = HttpTransporter::new(ReqwestTransport::new(client)); + let request = Request::get(&endpoint).body(Buffer::new()).unwrap(); + let response = tokio::time::timeout(TIMEOUT, transport.fetch(request)) + .await + .expect("transport fetch timed out") + .unwrap(); + let status = response.status(); + let mut body: HttpBody = response.into_body(); + let data = tokio::time::timeout(TIMEOUT, body.read_all()) + .await + .expect("transport body read timed out"); + tokio::time::timeout(TIMEOUT, server) + .await + .expect("test server timed out") + .unwrap(); + (status, data) +} + +#[tokio::test] +async fn not_modified_ignores_content_length() { + let (status, data) = fetch(b"HTTP/1.1 304 Not Modified\r\nContent-Length: 5\r\n\r\n").await; + + assert_eq!(status, StatusCode::NOT_MODIFIED); + assert!(data.unwrap().is_empty()); +} + +#[tokio::test] +async fn no_content_ignores_content_length() { + let (status, data) = fetch(b"HTTP/1.1 204 No Content\r\nContent-Length: 5\r\n\r\n").await; + + assert_eq!(status, StatusCode::NO_CONTENT); + assert!(data.unwrap().is_empty()); +} + +#[tokio::test] +async fn ok_validates_content_length() { + let (status, data) = fetch(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\na").await; + + assert_eq!(status, StatusCode::OK); + // The HTTP client rejects the incomplete message before `HttpBody` reaches + // the end of the stream, so the response must fail instead of being read + // as an empty body. + let error = data.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Unexpected); + assert!(error.is_temporary()); + assert!( + error.message().contains("read data from http response"), + "unexpected error: {error}" + ); +}
