Skip to content

Commit a7e7bb9

Browse files
test(testkit): serve TLS from host servers with a test or environment CA
Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
1 parent d90a519 commit a7e7bb9

9 files changed

Lines changed: 391 additions & 15 deletions

File tree

‎tests/suites/conformance/Cargo.lock‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎tests/suites/features/Cargo.lock‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎tests/support/Cargo.lock‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎tests/support/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ never skips it. Add a row when you add a variable.
2323
| `OPENSHELL_TEST_KEYCLOAK_CLIENT_ID` | `<base>-keycloak` | `keycloak-support` | A client in that realm that allows password grants. |
2424
| `OPENSHELL_TEST_KEYCLOAK_USERNAME` | `<base>-keycloak` | `keycloak-support` | The realm user that tests sign in as. |
2525
| `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `<base>-keycloak` | `keycloak-support` | That user's password. |
26+
| `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | The additional-CA environment, which configures the gateway's `additional_ca_bundle` (added by #5729) | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the gateway trusts. |
27+
| `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | The additional-CA environment | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. |
2628
| `OPENSHELL_TEST_BASE_IMAGE` | Optional; you, for example to use a mirror | `testkit::base_image()` | The default sandbox image. Unset, it is `nvcr.io/nvidia/base/ubuntu:24.04`. |
2729
| `OPENSHELL_TEST_PYTHON_IMAGE` | Optional; `e2e/rust/e2e-kubernetes.sh` and `e2e-vm.sh` set a pullable image | `testkit::python_image()` | The workload image for tests that run `python3`, curl, git or openssl. Unset, it is `openshell/e2e-python:dev`, which the tmachine installers load. |
2830
| `OPENSHELL_TEST_UNSUPPORTED` | CI, from `tests/suites/conformance/unsupported.yaml` (`tasks/scripts/conformance-unsupported.sh`), and `e2e/support/conformance.sh` for the host lanes; the runner passes it to the tests | testkit programs | Tests the environment can't pass yet, as `<test>=<issue>` entries. See [Unsupported tests](../testkit/README.md#unsupported-tests). |

‎tests/support/host-server/Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,13 @@ repository = "https://github.com/NVIDIA/OpenShell"
1212
publish = false
1313

1414
[dependencies]
15+
openshell-crypto = { path = "../../../crates/openshell-crypto" }
1516
openshell-testkit = { path = "../../testkit/testkit" }
17+
rcgen = { version = "0.14.10", default-features = false, features = ["pem"] }
18+
rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] }
1619
serde_json = "1"
1720
tokio = { version = "1.43", features = ["io-util", "net", "rt", "time"] }
21+
tokio-rustls = { version = "0.26", default-features = false, features = ["tls12"] }
1822
tungstenite = "0.26"
1923

2024
[dev-dependencies]

‎tests/support/host-server/src/http.rs‎

Lines changed: 59 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ use std::sync::atomic::{AtomicUsize, Ordering};
77
use std::sync::{Arc, Mutex, PoisonError};
88

99
use testkit::{Poll, Result};
10-
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11-
use tokio::net::TcpStream;
10+
use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _};
1211
use tokio::task::JoinHandle;
12+
use tokio_rustls::TlsAcceptor;
1313

14+
use crate::tls::Identity;
1415
use crate::{MAX_REQUEST, READ_TIMEOUT, WAIT_INTERVAL, WAIT_TIMEOUT, bind, find, header};
1516

1617
/// A request an [`HttpRecorder`] read. A chunked body arrives decoded.
@@ -171,6 +172,30 @@ impl HttpRecorder {
171172
/// Answer every request with `handler`'s response.
172173
pub async fn serve(
173174
handler: impl Fn(&Request) -> Response + Send + Sync + 'static,
175+
) -> Result<Self> {
176+
Self::listen(None, handler).await
177+
}
178+
179+
/// Answer every request over TLS with `200` and `body`, presenting
180+
/// `identity`'s certificate.
181+
pub async fn start_tls(identity: &Identity, body: impl Into<String>) -> Result<Self> {
182+
let body = body.into();
183+
Self::serve_tls(identity, move |_| Response::text(body.clone())).await
184+
}
185+
186+
/// Answer every request over TLS with `handler`'s response, presenting
187+
/// `identity`'s certificate. A connection that fails the TLS handshake
188+
/// counts in [`connections`](Self::connections) but records no request.
189+
pub async fn serve_tls(
190+
identity: &Identity,
191+
handler: impl Fn(&Request) -> Response + Send + Sync + 'static,
192+
) -> Result<Self> {
193+
Self::listen(Some(identity.acceptor()?), handler).await
194+
}
195+
196+
async fn listen(
197+
tls: Option<TlsAcceptor>,
198+
handler: impl Fn(&Request) -> Response + Send + Sync + 'static,
174199
) -> Result<Self> {
175200
let (listener, port) = bind().await?;
176201
let handler: Arc<Handler> = Arc::new(handler);
@@ -181,11 +206,21 @@ impl HttpRecorder {
181206
let task = tokio::spawn(async move {
182207
while let Ok((stream, _)) = listener.accept().await {
183208
task_connections.fetch_add(1, Ordering::AcqRel);
184-
tokio::spawn(respond(
185-
stream,
186-
Arc::clone(&handler),
187-
Arc::clone(&task_requests),
188-
));
209+
let _ = stream.set_nodelay(true);
210+
let local_addr = stream.local_addr().ok();
211+
let handler = Arc::clone(&handler);
212+
let requests = Arc::clone(&task_requests);
213+
let tls = tls.clone();
214+
tokio::spawn(async move {
215+
match tls {
216+
None => respond(stream, local_addr, handler, requests).await,
217+
Some(tls) => {
218+
if let Ok(stream) = tls.accept(stream).await {
219+
respond(stream, local_addr, handler, requests).await;
220+
}
221+
}
222+
}
223+
});
189224
}
190225
});
191226
Ok(Self {
@@ -239,10 +274,14 @@ impl Drop for HttpRecorder {
239274

240275
/// Read requests, record each, and answer with `handler` until a response
241276
/// or request closes the connection.
242-
async fn respond(mut stream: TcpStream, handler: Arc<Handler>, requests: Arc<Mutex<Vec<Request>>>) {
243-
let _ = stream.set_nodelay(true);
277+
async fn respond(
278+
mut stream: impl AsyncRead + AsyncWrite + Unpin,
279+
local_addr: Option<SocketAddr>,
280+
handler: Arc<Handler>,
281+
requests: Arc<Mutex<Vec<Request>>>,
282+
) {
244283
let mut buffer = Vec::new();
245-
while let Some(request) = read_request(&mut stream, &mut buffer).await {
284+
while let Some(request) = read_request(&mut stream, local_addr, &mut buffer).await {
246285
let response = handler(&request);
247286
let close = !response.keep_alive
248287
|| request
@@ -260,13 +299,18 @@ async fn respond(mut stream: TcpStream, handler: Arc<Handler>, requests: Arc<Mut
260299
}
261300

262301
/// Read one request from `stream`, starting with the bytes already in
263-
/// `buffer`, and leave any bytes after it in `buffer`.
264-
pub(crate) async fn read_request(stream: &mut TcpStream, buffer: &mut Vec<u8>) -> Option<Request> {
302+
/// `buffer`, and leave any bytes after it in `buffer`. `local_addr` is the
303+
/// address the connection arrived on.
304+
pub(crate) async fn read_request(
305+
stream: &mut (impl AsyncRead + Unpin),
306+
local_addr: Option<SocketAddr>,
307+
buffer: &mut Vec<u8>,
308+
) -> Option<Request> {
265309
let mut chunk = [0_u8; 4096];
266310
loop {
267311
if let Some((mut request, length)) = parse_request(buffer) {
268312
buffer.drain(..length);
269-
request.local_addr = stream.local_addr().ok();
313+
request.local_addr = local_addr;
270314
return Some(request);
271315
}
272316
match tokio::time::timeout(READ_TIMEOUT, stream.read(&mut chunk)).await {
@@ -337,6 +381,8 @@ fn decode_chunked(bytes: &[u8]) -> Option<(Vec<u8>, usize)> {
337381

338382
#[cfg(test)]
339383
mod tests {
384+
use tokio::net::TcpStream;
385+
340386
use super::*;
341387

342388
async fn connect(port: u16) -> TcpStream {

‎tests/support/host-server/src/lib.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
//! host, such as one on a remote cluster, can't run tests that use them.
1212
//!
1313
//! - [`HttpRecorder`] answers HTTP requests with a fixed body or a handler's
14-
//! [`Response`], and records each parsed [`Request`].
14+
//! [`Response`], and records each parsed [`Request`]. It serves HTTPS with
15+
//! a certificate from a [`TestCa`].
1516
//! - [`WebSocketRecorder`] completes the WebSocket handshake and records the
1617
//! frames that arrive.
1718
//! - [`TcpServer`] records raw bytes, and echoes them or answers once the
@@ -21,6 +22,7 @@
2122
2223
mod http;
2324
mod tcp;
25+
mod tls;
2426
mod websocket;
2527

2628
use std::time::Duration;
@@ -30,6 +32,7 @@ use tokio::net::TcpListener;
3032

3133
pub use http::{HttpRecorder, Request, Response};
3234
pub use tcp::{TcpServer, exchange};
35+
pub use tls::{ADDITIONAL_CA_CERT_ENV, ADDITIONAL_CA_KEY_ENV, Identity, TestCa};
3336
pub use websocket::{TEXT_REPLY, WebSocketRecorder};
3437

3538
/// The name a sandbox reaches these servers by.

0 commit comments

Comments
 (0)