Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-spacesd): drain refused /files upload bodies so the reply is not reset (#6464)

injaneity5e3c9612a1c4
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/http/files.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/http/files.rs
index 683fd886ad..2a99797ece 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/http/files.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/http/files.rs
@@ -21,7 +21,7 @@ use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
-use axum::body::Body;
+use axum::body::{Body, BodyDataStream};
use axum::extract::State;
use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
@@ -270,6 +270,15 @@ pub struct FilesState {
pub fs: Arc<FsState>,
}
+/// Most of a refused or partly read request body that is read and dropped
+/// before answering, and for how long. Closing with unread bytes in the
+/// socket makes the kernel reset the connection, which can destroy the
+/// response before the client reads it. A longer or slower body can still
+/// be reset. A client waiting on `Expect: 100-continue` has sent no body,
+/// and reading would invite it to, so it is not drained.
+const UNREAD_BODY_DRAIN_BYTES: usize = 8 << 20;
+const UNREAD_BODY_DRAIN_TIME: Duration = Duration::from_secs(5);
+
/// The `/files` handler (any method).
pub async fn handle(
State(state): State<FilesState>,
@@ -278,7 +287,32 @@ pub async fn handle(
headers: HeaderMap,
body: Body,
) -> Response {
- let verified = match verify(&state.ctx, &method, &uri) {
+ let mut body = body.into_data_stream();
+ let response = serve(&state, &method, &uri, &headers, &mut body).await;
+ if headers.contains_key(header::EXPECT) {
+ return response;
+ }
+ let drain = async {
+ let mut drained = 0;
+ while drained <= UNREAD_BODY_DRAIN_BYTES {
+ match body.next().await {
+ Some(Ok(chunk)) => drained += chunk.len(),
+ _ => break,
+ }
+ }
+ };
+ let _ = tokio::time::timeout(UNREAD_BODY_DRAIN_TIME, drain).await;
+ response
+}
+
+async fn serve(
+ state: &FilesState,
+ method: &Method,
+ uri: &Uri,
+ headers: &HeaderMap,
+ body: &mut BodyDataStream,
+) -> Response {
+ let verified = match verify(&state.ctx, method, uri) {
Ok(v) => v,
Err(Refusal::BadRequest(m)) => return text(StatusCode::BAD_REQUEST, m),
Err(Refusal::Expired) => return text(StatusCode::FORBIDDEN, "signed URL expired"),
@@ -291,13 +325,13 @@ pub async fn handle(
// `~` and relative paths cannot reach here: the path was resolved when
// the URL was minted.
let path = std::path::PathBuf::from(&verified.path);
- if method == Method::PUT {
+ if *method == Method::PUT {
return put(acting, path, &verified, body).await;
}
- if method == Method::POST {
- return post_multipart(acting, path, &verified, &headers, body).await;
+ if *method == Method::POST {
+ return post_multipart(acting, path, &verified, headers, body).await;
}
- get(acting, path, &verified, &headers, method == Method::HEAD).await
+ get(acting, path, &verified, headers, *method == Method::HEAD).await
}
/// Where an upload's bytes go: an atomic writer in this process, or a
@@ -430,13 +464,12 @@ async fn put(
acting: Acting,
path: std::path::PathBuf,
verified: &Verified,
- body: Body,
+ stream: &mut BodyDataStream,
) -> Response {
let mut sink = match Sink::open(acting, path, verified).await {
Ok(sink) => sink,
Err(response) => return *response,
};
- let mut stream = body.into_data_stream();
while let Some(chunk) = stream.next().await {
let chunk = match chunk {
Ok(c) => c,
@@ -468,7 +501,7 @@ async fn post_multipart(
path: std::path::PathBuf,
verified: &Verified,
headers: &HeaderMap,
- body: Body,
+ stream: &mut BodyDataStream,
) -> Response {
let content_type = headers
.get(header::CONTENT_TYPE)
@@ -488,7 +521,6 @@ async fn post_multipart(
let mut reader = multipart::FirstFile::new(&boundary);
let mut sink: Option<Sink> = None;
let mut acting = Some(acting);
- let mut stream = body.into_data_stream();
let mut out = Vec::new();
let mut done = false;
while !done {
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/files_extended.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/files_extended.rs
index c11fa3d553..fa1951a38b 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/files_extended.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/files_extended.rs
@@ -547,3 +547,51 @@ async fn metadata_limits_and_namespaces_are_validated() {
assert!(read_all(&t, &path).await.is_err());
t.cleanup().await;
}
+
+#[tokio::test]
+async fn a_refused_upload_is_answered_without_resetting_the_connection() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let t = target().await;
+ let Some(authority) = t.url.strip_prefix("http://") else {
+ return;
+ };
+ let authority = authority.trim_end_matches('/');
+ let tampered = signed_put(&t, &t.path("refused.bin"), false)
+ .await
+ .replace("sig=", "sig=AA");
+ let body = vec![7u8; 1 << 20];
+ // A request whose body the server never reads: the refusal must still
+ // reach the client instead of a connection reset.
+ for _ in 0..5 {
+ let mut stream = tokio::net::TcpStream::connect(authority).await.unwrap();
+ let head = format!(
+ "PUT {tampered} HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\nContent-Length: {}\r\n\r\n",
+ body.len()
+ );
+ stream.write_all(head.as_bytes()).await.unwrap();
+ stream.write_all(&body).await.unwrap();
+ let mut response = Vec::new();
+ stream.read_to_end(&mut response).await.unwrap();
+ assert!(
+ response.starts_with(b"HTTP/1.1 403"),
+ "{}",
+ String::from_utf8_lossy(&response)
+ );
+ }
+ // A client that waits for `100 Continue` is refused without being asked
+ // for its body.
+ let mut stream = tokio::net::TcpStream::connect(authority).await.unwrap();
+ let head = format!(
+ "PUT {tampered} HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\nExpect: 100-continue\r\nContent-Length: {}\r\n\r\n",
+ body.len()
+ );
+ stream.write_all(head.as_bytes()).await.unwrap();
+ let mut response = Vec::new();
+ stream.read_to_end(&mut response).await.unwrap();
+ assert!(
+ response.starts_with(b"HTTP/1.1 403"),
+ "{}",
+ String::from_utf8_lossy(&response)
+ );
+ t.cleanup().await;
+}