Files
2026-11-27 06:03:56 +00:00

455 lines
16 KiB
Rust

use super::{
tests::{limits, request},
*,
};
use crate::{net, task, tls};
use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
};
fn echo(request: Request) -> Response {
Response {
status: 202,
headers: vec![Header {
name: "x-test".into(),
value: Bytes::from_static(b"yes"),
}],
body: request.body,
}
}
#[test]
fn server_round_trip_tls_and_plain_both_protocols() {
task::run(true, 32, async |scope| {
for encrypted in [false, true] {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let server = scope
.spawn(move |child| async move {
let tls = encrypted.then(|| {
tls::server(
include_bytes!("../../../fixtures/tls/server.pem"),
include_bytes!("../../../fixtures/tls/server-key.pem"),
)
.unwrap()
});
serve::<false, _, _>(
&child,
|request, _| async move { Ok(echo(request)) },
&listening,
&limits(http2),
tls.as_ref(),
)
.await
})
.unwrap();
let response = if encrypted {
let stream = TcpStream::connect(("127.0.0.1", port as u16))
.await
.unwrap();
let client =
tls::client(include_bytes!("../../../fixtures/tls/root.pem")).unwrap();
let stream =
TokioIo::new(client.connect("localhost", stream, http2).await.unwrap());
let input =
wire::request(request(), &limits(http2).check().unwrap(), None).unwrap();
if http2 {
let (mut sender, connection) =
hyper::client::conn::http2::handshake(TokioExecutor::new(), stream)
.await
.unwrap();
drive(connection, async {
receive(
sender.send_request(input).await.unwrap(),
&limits(true).check().unwrap(),
)
.await
})
.await
.unwrap()
} else {
let (mut sender, connection) =
hyper::client::conn::http1::handshake(stream).await.unwrap();
drive(connection, async {
receive(
sender.send_request(input).await.unwrap(),
&limits(false).check().unwrap(),
)
.await
})
.await
.unwrap()
}
} else {
send("127.0.0.1", port, request(), &limits(http2))
.await
.unwrap()
};
assert_eq!(response.status, 202);
assert_eq!(response.body, b"hello"[..]);
assert!(
response
.headers
.iter()
.any(|header| header.name == "x-test" && header.value == b"yes"[..])
);
listener.close().unwrap();
tokio::time::timeout(Duration::from_secs(2), server)
.await
.unwrap()
.unwrap()
.unwrap();
}
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn server_isolates_failures_panics_timeouts_and_invalid_responses() {
task::run(true, 32, async |scope| {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
|request, _| async move {
match request.target.as_str() {
"/fail" => Err("private failure".into()),
"/panic" => panic!("original panic"),
"/timeout" => std::future::pending().await,
"/invalid" => Ok(Response {
status: 700,
..echo(request)
}),
_ => Ok(echo(request)),
}
},
&listening,
&Limits {
timeout_ms: 30,
..limits(http2)
},
None,
)
.await
})
.unwrap();
for (target, status) in [
("/fail", 500),
("/panic", 500),
("/timeout", 504),
("/invalid", 500),
("/ok", 202),
] {
let response = send(
"127.0.0.1",
port,
Request {
target: target.into(),
..request()
},
&limits(http2),
)
.await
.unwrap();
assert_eq!(response.status, status, "{target}");
if status != 202 {
assert!(response.body.is_empty());
}
}
listener.close().unwrap();
server.await.unwrap().unwrap();
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
struct Active(Arc<AtomicUsize>);
impl Drop for Active {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
#[test]
fn server_scheduled_timeout_and_cancellation_drain_descendants() {
task::run(true, 32, async |scope| {
for http2 in [false, true] {
for cancel_server in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let active = Arc::new(AtomicUsize::new(0));
let counter = active.clone();
let server = scope
.spawn(move |child| async move {
serve::<true, _, _>(
&child,
move |_, child| {
let active = counter.clone();
async move {
active.fetch_add(1, Ordering::SeqCst);
let guard = Active(active);
let task = child
.spawn_leaf(async move {
let _guard = guard;
std::future::pending::<()>().await;
})
.unwrap();
task.await.unwrap();
unreachable!()
}
},
&listening,
&Limits {
timeout_ms: if cancel_server { 1000 } else { 30 },
..limits(http2)
},
None,
)
.await
})
.unwrap();
let client = tokio::spawn(async move {
send("127.0.0.1", port, request(), &limits(http2)).await
});
tokio::time::timeout(Duration::from_secs(1), async {
while active.load(Ordering::SeqCst) == 0 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
if cancel_server {
server.stop().await.unwrap();
assert!(client.await.unwrap().is_err());
} else {
assert_eq!(client.await.unwrap().unwrap().status, 504);
assert_eq!(active.load(Ordering::SeqCst), 0);
listener.close().unwrap();
server.await.unwrap().unwrap();
}
assert_eq!(active.load(Ordering::SeqCst), 0);
}
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn server_listener_close_finishes_inflight_and_rejects_new_connections() {
task::run(true, 16, async |scope| {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let closing = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
move |request, _| {
let closing = closing.clone();
async move {
closing.close().unwrap();
tokio::time::sleep(Duration::from_millis(10)).await;
Ok(echo(request))
}
},
&listening,
&limits(http2),
None,
)
.await
})
.unwrap();
assert_eq!(
send("127.0.0.1", port, request(), &limits(http2))
.await
.unwrap()
.body,
b"hello"[..]
);
tokio::time::timeout(Duration::from_secs(1), server)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(
TcpStream::connect(("127.0.0.1", port as u16))
.await
.is_err()
);
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn server_validates_real_request_headers_body_and_deadlines() {
task::run(true, 16, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
|request, _| async move { Ok(echo(request)) },
&listening,
&Limits {
body_bytes: 4,
timeout_ms: 30,
..limits(false)
},
None,
)
.await
})
.unwrap();
for (request, expected) in [
("GET / HTTP/1.1\r\nConnection: close\r\n\r\n", 400),
(
"GET / HTTP/1.1\r\nHost: a\r\nHost: b\r\nConnection: close\r\n\r\n",
400,
),
(
"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 5\r\nConnection: close\r\n\r\n12345",
413,
),
(
"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 4\r\nConnection: close\r\n\r\n12",
408,
),
] {
let mut stream = TcpStream::connect(("127.0.0.1", port as u16))
.await
.unwrap();
stream.write_all(request.as_bytes()).await.unwrap();
let mut response = String::new();
tokio::time::timeout(Duration::from_secs(1), stream.read_to_string(&mut response))
.await
.unwrap()
.unwrap();
assert!(
response.starts_with(&format!("HTTP/1.1 {expected}")),
"{response}"
);
}
listener.close().unwrap();
server.await.unwrap().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn server_task_capacity_is_503_and_connection_limit_applies_before_accept() {
task::run(true, 2, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<true, _, _>(
&child,
|_, _| async { panic!("capacity must reject before calling handler") },
&active,
&limits(true),
None,
)
.await
})
.unwrap();
assert_eq!(
send("127.0.0.1", port, request(), &limits(true))
.await
.unwrap()
.status,
503
);
listener.close().unwrap();
server.await.unwrap().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
task::run(true, 16, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let calls = Arc::new(AtomicUsize::new(0));
let counter = calls.clone();
let gate = Arc::new(tokio::sync::Notify::new());
let release = gate.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
move |request, _| {
let (counter, gate) = (counter.clone(), gate.clone());
async move {
if counter.fetch_add(1, Ordering::SeqCst) == 0 {
gate.notified().await;
}
Ok(echo(request))
}
},
&active,
&Limits {
connections: 1,
..limits(false)
},
None,
)
.await
})
.unwrap();
let first =
tokio::spawn(async move { send("127.0.0.1", port, request(), &limits(false)).await });
tokio::time::timeout(Duration::from_secs(1), async {
while calls.load(Ordering::SeqCst) == 0 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let second =
tokio::spawn(async move { send("127.0.0.1", port, request(), &limits(false)).await });
tokio::time::sleep(Duration::from_millis(20)).await;
assert_eq!(calls.load(Ordering::SeqCst), 1);
release.notify_one();
assert_eq!(first.await.unwrap().unwrap().status, 202);
assert_eq!(second.await.unwrap().unwrap().status, 202);
assert_eq!(calls.load(Ordering::SeqCst), 2);
listener.close().unwrap();
server.await.unwrap().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}