Base: codex-main originale (prima del fork aKode)
This commit is contained in:
420
codex-rs/exec-server/tests/common/exec_server.rs
Normal file
420
codex-rs/exec-server/tests/common/exec_server.rs
Normal file
@@ -0,0 +1,420 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use codex_exec_server_protocol::JSONRPCMessage;
|
||||
use codex_exec_server_protocol::JSONRPCNotification;
|
||||
use codex_exec_server_protocol::JSONRPCRequest;
|
||||
use codex_exec_server_protocol::RequestId;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::io::copy_bidirectional;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::sleep;
|
||||
use tokio::time::timeout;
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CONNECT_RETRY_INTERVAL: Duration = Duration::from_millis(25);
|
||||
const EVENT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub(crate) struct ExecServerHarness {
|
||||
codex_home: TempDir,
|
||||
child: Child,
|
||||
websocket_url: String,
|
||||
websocket: tokio_tungstenite::WebSocketStream<
|
||||
tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
|
||||
>,
|
||||
next_request_id: i64,
|
||||
}
|
||||
|
||||
impl Drop for ExecServerHarness {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.start_kill();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct TestCodexHelperPaths {
|
||||
pub(crate) codex_exe: PathBuf,
|
||||
pub(crate) codex_linux_sandbox_exe: Option<PathBuf>,
|
||||
}
|
||||
|
||||
pub(crate) struct DisconnectableWebSocketProxy {
|
||||
websocket_url: String,
|
||||
pause_tx: Option<oneshot::Sender<()>>,
|
||||
blocked_connection_rx: Option<oneshot::Receiver<()>>,
|
||||
resume_tx: Option<oneshot::Sender<()>>,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Drop for DisconnectableWebSocketProxy {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn test_codex_helper_paths() -> anyhow::Result<TestCodexHelperPaths> {
|
||||
let (helper_binary, codex_linux_sandbox_exe) = super::current_test_binary_helper_paths()?;
|
||||
Ok(TestCodexHelperPaths {
|
||||
codex_exe: helper_binary,
|
||||
codex_linux_sandbox_exe,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn exec_server() -> anyhow::Result<ExecServerHarness> {
|
||||
exec_server_with_env(std::iter::empty::<(&str, &str)>(), &[]).await
|
||||
}
|
||||
|
||||
pub(crate) async fn exec_server_with_env<I, K, V>(
|
||||
env: I,
|
||||
args: &[&str],
|
||||
) -> anyhow::Result<ExecServerHarness>
|
||||
where
|
||||
I: IntoIterator<Item = (K, V)>,
|
||||
K: AsRef<std::ffi::OsStr>,
|
||||
V: AsRef<std::ffi::OsStr>,
|
||||
{
|
||||
let helper_paths = test_codex_helper_paths()?;
|
||||
let mut child = Command::new(&helper_paths.codex_exe);
|
||||
child.args(["exec-server", "--listen", "ws://127.0.0.1:0"]);
|
||||
child.args(args);
|
||||
child.envs(env);
|
||||
ExecServerHarness::start(child).await
|
||||
}
|
||||
|
||||
impl ExecServerHarness {
|
||||
pub(crate) async fn start(command: Command) -> anyhow::Result<Self> {
|
||||
Self::start_with_stderr(command, Stdio::inherit()).await
|
||||
}
|
||||
|
||||
pub(crate) async fn start_with_stderr(
|
||||
mut command: Command,
|
||||
stderr: Stdio,
|
||||
) -> anyhow::Result<Self> {
|
||||
let codex_home = TempDir::new()?;
|
||||
command.stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped());
|
||||
command.stderr(stderr);
|
||||
command.kill_on_drop(true);
|
||||
if !command
|
||||
.as_std()
|
||||
.get_envs()
|
||||
.any(|(key, value)| key == "CODEX_HOME" && value.is_some())
|
||||
{
|
||||
command.env("CODEX_HOME", codex_home.path());
|
||||
}
|
||||
let mut child = command.spawn()?;
|
||||
|
||||
let websocket_url = read_listen_url_from_stdout(&mut child).await?;
|
||||
let (websocket, _) = connect_websocket_when_ready(&websocket_url).await?;
|
||||
Ok(Self {
|
||||
codex_home,
|
||||
child,
|
||||
websocket_url,
|
||||
websocket,
|
||||
next_request_id: 1,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn codex_home(&self) -> &std::path::Path {
|
||||
self.codex_home.path()
|
||||
}
|
||||
|
||||
pub(crate) fn websocket_url(&self) -> &str {
|
||||
&self.websocket_url
|
||||
}
|
||||
|
||||
pub(crate) async fn disconnect_websocket(&mut self) -> anyhow::Result<()> {
|
||||
self.websocket.close(None).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn reconnect_websocket(&mut self) -> anyhow::Result<()> {
|
||||
let (websocket, _) = connect_websocket_when_ready(&self.websocket_url).await?;
|
||||
self.websocket = websocket;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn disconnectable_websocket_proxy(
|
||||
&self,
|
||||
) -> anyhow::Result<DisconnectableWebSocketProxy> {
|
||||
DisconnectableWebSocketProxy::new(&self.websocket_url).await
|
||||
}
|
||||
|
||||
pub(crate) async fn send_request(
|
||||
&mut self,
|
||||
method: &str,
|
||||
params: serde_json::Value,
|
||||
) -> anyhow::Result<RequestId> {
|
||||
let id = RequestId::Integer(self.next_request_id);
|
||||
self.next_request_id += 1;
|
||||
self.send_message(JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: id.clone(),
|
||||
method: method.to_string(),
|
||||
params: Some(params),
|
||||
trace: None,
|
||||
}))
|
||||
.await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub(crate) async fn send_notification(
|
||||
&mut self,
|
||||
method: &str,
|
||||
params: serde_json::Value,
|
||||
) -> anyhow::Result<()> {
|
||||
self.send_message(JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: method.to_string(),
|
||||
params: Some(params),
|
||||
}))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn send_raw_text(&mut self, text: &str) -> anyhow::Result<()> {
|
||||
self.websocket
|
||||
.send(Message::Text(text.to_string().into()))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn send_raw_binary(&mut self, bytes: Vec<u8>) -> anyhow::Result<()> {
|
||||
self.websocket.send(Message::Binary(bytes.into())).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn next_event(&mut self) -> anyhow::Result<JSONRPCMessage> {
|
||||
self.next_event_with_timeout(EVENT_TIMEOUT).await
|
||||
}
|
||||
|
||||
pub(crate) async fn wait_for_event<F>(
|
||||
&mut self,
|
||||
mut predicate: F,
|
||||
) -> anyhow::Result<JSONRPCMessage>
|
||||
where
|
||||
F: FnMut(&JSONRPCMessage) -> bool,
|
||||
{
|
||||
let deadline = Instant::now() + EVENT_TIMEOUT;
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return Err(anyhow!(
|
||||
"timed out waiting for matching exec-server event after {EVENT_TIMEOUT:?}"
|
||||
));
|
||||
}
|
||||
let remaining = deadline.duration_since(now);
|
||||
let event = self.next_event_with_timeout(remaining).await?;
|
||||
if predicate(&event) {
|
||||
return Ok(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&mut self) -> anyhow::Result<()> {
|
||||
self.child.start_kill()?;
|
||||
timeout(CONNECT_TIMEOUT, self.child.wait())
|
||||
.await
|
||||
.map_err(|_| anyhow!("timed out waiting for exec-server shutdown"))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_message(&mut self, message: JSONRPCMessage) -> anyhow::Result<()> {
|
||||
let encoded = serde_json::to_string(&message)?;
|
||||
self.websocket.send(Message::Text(encoded.into())).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn next_event_with_timeout(
|
||||
&mut self,
|
||||
timeout_duration: Duration,
|
||||
) -> anyhow::Result<JSONRPCMessage> {
|
||||
loop {
|
||||
let frame = timeout(timeout_duration, self.websocket.next())
|
||||
.await
|
||||
.map_err(|_| anyhow!("timed out waiting for exec-server websocket event"))?
|
||||
.ok_or_else(|| anyhow!("exec-server websocket closed"))??;
|
||||
|
||||
match frame {
|
||||
Message::Text(text) => {
|
||||
return Ok(serde_json::from_str(text.as_ref())?);
|
||||
}
|
||||
Message::Binary(bytes) => {
|
||||
return Ok(serde_json::from_slice(bytes.as_ref())?);
|
||||
}
|
||||
Message::Close(_) => return Err(anyhow!("exec-server websocket closed")),
|
||||
Message::Ping(_) | Message::Pong(_) => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DisconnectableWebSocketProxy {
|
||||
pub(crate) async fn new(websocket_url: &str) -> anyhow::Result<Self> {
|
||||
let upstream = websocket_url
|
||||
.strip_prefix("ws://")
|
||||
.ok_or_else(|| anyhow!("exec-server websocket URL must use ws://"))?
|
||||
.trim_end_matches('/')
|
||||
.to_string();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let websocket_url = format!("ws://{}", listener.local_addr()?);
|
||||
let (pause_tx, pause_rx) = oneshot::channel();
|
||||
let (blocked_connection_tx, blocked_connection_rx) = oneshot::channel();
|
||||
let (resume_tx, resume_rx) = oneshot::channel();
|
||||
let task = tokio::spawn(run_disconnectable_proxy(
|
||||
listener,
|
||||
upstream,
|
||||
pause_rx,
|
||||
blocked_connection_tx,
|
||||
resume_rx,
|
||||
));
|
||||
Ok(DisconnectableWebSocketProxy {
|
||||
websocket_url,
|
||||
pause_tx: Some(pause_tx),
|
||||
blocked_connection_rx: Some(blocked_connection_rx),
|
||||
resume_tx: Some(resume_tx),
|
||||
task,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn websocket_url(&self) -> &str {
|
||||
&self.websocket_url
|
||||
}
|
||||
|
||||
pub(crate) async fn pause_and_disconnect(&mut self) -> anyhow::Result<()> {
|
||||
self.pause_tx
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("disconnectable websocket proxy is already paused"))?
|
||||
.send(())
|
||||
.map_err(|_| anyhow!("disconnectable websocket proxy stopped"))?;
|
||||
let blocked_connection_rx = self
|
||||
.blocked_connection_rx
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("disconnectable websocket proxy is already paused"))?;
|
||||
timeout(CONNECT_TIMEOUT, blocked_connection_rx)
|
||||
.await
|
||||
.map_err(|_| anyhow!("timed out waiting for client reconnect attempt"))?
|
||||
.map_err(|_| anyhow!("disconnectable websocket proxy stopped"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn resume(&mut self) -> anyhow::Result<()> {
|
||||
self.resume_tx
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("disconnectable websocket proxy is already resumed"))?
|
||||
.send(())
|
||||
.map_err(|_| anyhow!("disconnectable websocket proxy stopped"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_disconnectable_proxy(
|
||||
listener: TcpListener,
|
||||
upstream: String,
|
||||
pause_rx: oneshot::Receiver<()>,
|
||||
blocked_connection_tx: oneshot::Sender<()>,
|
||||
mut resume_rx: oneshot::Receiver<()>,
|
||||
) {
|
||||
let Ok((mut downstream, _)) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
let Ok(mut upstream_stream) = TcpStream::connect(&upstream).await else {
|
||||
return;
|
||||
};
|
||||
tokio::select! {
|
||||
_ = copy_bidirectional(&mut downstream, &mut upstream_stream) => return,
|
||||
_ = pause_rx => {}
|
||||
}
|
||||
drop(downstream);
|
||||
drop(upstream_stream);
|
||||
|
||||
let mut blocked_connection_tx = Some(blocked_connection_tx);
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = &mut resume_rx => break,
|
||||
accepted = listener.accept() => {
|
||||
let Ok((blocked, _)) = accepted else {
|
||||
break;
|
||||
};
|
||||
drop(blocked);
|
||||
if let Some(blocked_connection_tx) = blocked_connection_tx.take() {
|
||||
let _ = blocked_connection_tx.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
let Ok((mut downstream, _)) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
let Ok(mut upstream_stream) = TcpStream::connect(&upstream).await else {
|
||||
continue;
|
||||
};
|
||||
let _ = copy_bidirectional(&mut downstream, &mut upstream_stream).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_websocket_when_ready(
|
||||
websocket_url: &str,
|
||||
) -> anyhow::Result<(
|
||||
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
|
||||
tokio_tungstenite::tungstenite::handshake::client::Response,
|
||||
)> {
|
||||
let deadline = Instant::now() + CONNECT_TIMEOUT;
|
||||
loop {
|
||||
match connect_async(websocket_url).await {
|
||||
Ok(websocket) => return Ok(websocket),
|
||||
Err(err)
|
||||
if Instant::now() < deadline
|
||||
&& matches!(
|
||||
err,
|
||||
tokio_tungstenite::tungstenite::Error::Io(ref io_err)
|
||||
if io_err.kind() == std::io::ErrorKind::ConnectionRefused
|
||||
) =>
|
||||
{
|
||||
sleep(CONNECT_RETRY_INTERVAL).await;
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_listen_url_from_stdout(child: &mut Child) -> anyhow::Result<String> {
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("failed to capture exec-server stdout"))?;
|
||||
let mut lines = BufReader::new(stdout).lines();
|
||||
let deadline = Instant::now() + CONNECT_TIMEOUT;
|
||||
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return Err(anyhow!(
|
||||
"timed out waiting for exec-server listen URL on stdout after {CONNECT_TIMEOUT:?}"
|
||||
));
|
||||
}
|
||||
let remaining = deadline.duration_since(now);
|
||||
let line = timeout(remaining, lines.next_line())
|
||||
.await
|
||||
.map_err(|_| anyhow!("timed out waiting for exec-server stdout"))??
|
||||
.ok_or_else(|| anyhow!("exec-server stdout closed before emitting listen URL"))?;
|
||||
let listen_url = line.trim();
|
||||
if listen_url.starts_with("ws://") {
|
||||
return Ok(listen_url.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
58
codex-rs/exec-server/tests/common/fake_bwrap.rs
Normal file
58
codex-rs/exec-server/tests/common/fake_bwrap.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(crate) fn write_fake_bwrap(bin_dir: &Path) -> anyhow::Result<PathBuf> {
|
||||
std::fs::create_dir_all(bin_dir)?;
|
||||
let fake_bwrap = bin_dir.join("bwrap");
|
||||
codex_utils_cargo_bin::write_executable(
|
||||
&fake_bwrap,
|
||||
r#"#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
for arg in "$@"; do
|
||||
if [[ "${arg}" == "--help" ]]; then
|
||||
echo "Usage: bwrap --argv0 --perms --as-pid-1"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
args=("$@")
|
||||
argv0=""
|
||||
command_start=-1
|
||||
for i in "${!args[@]}"; do
|
||||
if [[ "${args[$i]}" == "--argv0" && $((i + 1)) -lt ${#args[@]} ]]; then
|
||||
argv0="${args[$((i + 1))]}"
|
||||
fi
|
||||
if [[ "${args[$i]}" == "--" ]]; then
|
||||
command_start=$((i + 1))
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ "${command_start}" -lt 0 || "${command_start}" -ge "${#args[@]}" ]]; then
|
||||
echo "fake bwrap did not find an inner command" >&2
|
||||
exit 125
|
||||
fi
|
||||
|
||||
cmd=("${args[@]:$command_start}")
|
||||
case "${cmd[0]}" in
|
||||
/usr/bin/true|/bin/true|true)
|
||||
exec "${cmd[@]}"
|
||||
;;
|
||||
esac
|
||||
|
||||
printf '%s\n' "$*" >> "${0}.log"
|
||||
if [[ -f "${0}.fail-once" ]]; then
|
||||
rm -f "${0}.fail-once"
|
||||
echo "forced fake bwrap failure" >&2
|
||||
exit 125
|
||||
fi
|
||||
|
||||
if [[ -n "${argv0}" ]]; then
|
||||
exec -a "${argv0}" "${cmd[@]}"
|
||||
fi
|
||||
exec "${cmd[@]}"
|
||||
"#,
|
||||
)?;
|
||||
Ok(fake_bwrap)
|
||||
}
|
||||
313
codex-rs/exec-server/tests/common/mod.rs
Normal file
313
codex-rs/exec-server/tests/common/mod.rs
Normal file
@@ -0,0 +1,313 @@
|
||||
use std::env;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_exec_server::CODEX_ARG0_EXEC_HELPER_ARG1;
|
||||
use codex_exec_server::CODEX_FS_HELPER_ARG1;
|
||||
use codex_exec_server::ExecServerRuntimeOptions;
|
||||
use codex_exec_server::ExecServerTelemetry;
|
||||
use codex_exec_server::RequestDispatchMode;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
|
||||
use codex_test_binary_support::TestBinaryDispatchGuard;
|
||||
use codex_test_binary_support::TestBinaryDispatchMode;
|
||||
use codex_test_binary_support::configure_test_binary_dispatch;
|
||||
use ctor::ctor;
|
||||
|
||||
pub(crate) mod exec_server;
|
||||
|
||||
pub(crate) const TEST_BUILD_COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
|
||||
pub(crate) const DELAYED_OUTPUT_AFTER_EXIT_PARENT_ARG: &str =
|
||||
"--codex-test-delayed-output-after-exit-parent";
|
||||
pub(crate) const SYSTEM_PROXY_REQUEST_URL_ENV: &str =
|
||||
"CODEX_EXEC_SERVER_TEST_SYSTEM_PROXY_REQUEST_URL";
|
||||
pub(crate) const SYSTEM_PROXY_URL_ENV: &str = "CODEX_EXEC_SERVER_TEST_SYSTEM_PROXY_URL";
|
||||
|
||||
const CODEX_WINDOWS_SANDBOX_ARG1: &str = "--run-as-windows-sandbox";
|
||||
const DELAYED_OUTPUT_AFTER_EXIT_CHILD_ARG: &str = "--codex-test-delayed-output-after-exit-child";
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! skip_if_mxc_unavailable {
|
||||
($return_value:expr $(,)?) => {{
|
||||
if !codex_sandboxing::windows_mxc_available() {
|
||||
eprintln!("skipping test: native MXC is unavailable on this host");
|
||||
return $return_value;
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
#[ctor]
|
||||
pub static TEST_BINARY_DISPATCH_GUARD: Option<TestBinaryDispatchGuard> = {
|
||||
let guard = configure_test_binary_dispatch("codex-exec-server-tests", |exe_name, argv1| {
|
||||
if argv1 == Some(CODEX_ARG0_EXEC_HELPER_ARG1) {
|
||||
return TestBinaryDispatchMode::DispatchArg0Only;
|
||||
}
|
||||
if argv1 == Some(CODEX_FS_HELPER_ARG1) {
|
||||
return TestBinaryDispatchMode::DispatchArg0Only;
|
||||
}
|
||||
if argv1 == Some(CODEX_WINDOWS_SANDBOX_ARG1) {
|
||||
return TestBinaryDispatchMode::DispatchArg0Only;
|
||||
}
|
||||
if argv1 == Some(codex_sandboxing::CODEX_WINDOWS_MXC_ARG1) {
|
||||
return TestBinaryDispatchMode::DispatchArg0Only;
|
||||
}
|
||||
if exe_name == CODEX_LINUX_SANDBOX_ARG0 {
|
||||
return TestBinaryDispatchMode::DispatchArg0Only;
|
||||
}
|
||||
TestBinaryDispatchMode::InstallAliases
|
||||
});
|
||||
maybe_run_delayed_output_after_exit_from_test_binary();
|
||||
maybe_run_exec_server_from_test_binary(guard.as_ref());
|
||||
guard
|
||||
};
|
||||
|
||||
pub(crate) fn current_test_binary_helper_paths() -> anyhow::Result<(PathBuf, Option<PathBuf>)> {
|
||||
let current_exe = env::current_exe()?;
|
||||
let codex_linux_sandbox_exe = if cfg!(target_os = "linux") {
|
||||
TEST_BINARY_DISPATCH_GUARD
|
||||
.as_ref()
|
||||
.and_then(|guard| guard.paths().codex_linux_sandbox_exe.clone())
|
||||
.or_else(|| Some(current_exe.clone()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((current_exe, codex_linux_sandbox_exe))
|
||||
}
|
||||
|
||||
fn maybe_run_delayed_output_after_exit_from_test_binary() {
|
||||
let mut args = env::args();
|
||||
let _program = args.next();
|
||||
let Some(command) = args.next() else {
|
||||
return;
|
||||
};
|
||||
match command.as_str() {
|
||||
DELAYED_OUTPUT_AFTER_EXIT_PARENT_ARG => {
|
||||
let release_path = next_release_path_arg(args);
|
||||
run_delayed_output_after_exit_parent(&release_path);
|
||||
}
|
||||
DELAYED_OUTPUT_AFTER_EXIT_CHILD_ARG => {
|
||||
let release_path = next_release_path_arg(args);
|
||||
run_delayed_output_after_exit_child(&release_path);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn next_release_path_arg(mut args: impl Iterator<Item = String>) -> PathBuf {
|
||||
let Some(release_path) = args.next() else {
|
||||
eprintln!("expected release path");
|
||||
std::process::exit(1);
|
||||
};
|
||||
if args.next().is_some() {
|
||||
eprintln!("unexpected extra arguments");
|
||||
std::process::exit(1);
|
||||
}
|
||||
PathBuf::from(release_path)
|
||||
}
|
||||
|
||||
fn run_delayed_output_after_exit_parent(release_path: &Path) {
|
||||
let current_exe = match env::current_exe() {
|
||||
Ok(current_exe) => current_exe,
|
||||
Err(error) => {
|
||||
eprintln!("failed to resolve current test binary: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
match Command::new(current_exe)
|
||||
.arg(DELAYED_OUTPUT_AFTER_EXIT_CHILD_ARG)
|
||||
.arg(release_path)
|
||||
.stdin(Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
Ok(_) => std::process::exit(0),
|
||||
Err(error) => {
|
||||
eprintln!("failed to spawn delayed output child: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_delayed_output_after_exit_child(release_path: &Path) {
|
||||
for _ in 0..1_000 {
|
||||
if release_path.exists() {
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
if let Err(error) = writeln!(stdout, "late output after exit") {
|
||||
eprintln!("failed to write delayed output: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
if let Err(error) = stdout.flush() {
|
||||
eprintln!("failed to flush delayed output: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
std::process::exit(0);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
eprintln!(
|
||||
"timed out waiting for release path {}",
|
||||
release_path.display()
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
fn maybe_run_exec_server_from_test_binary(guard: Option<&TestBinaryDispatchGuard>) {
|
||||
let mut args = env::args();
|
||||
let _program = args.next();
|
||||
let Some(command) = args.next() else {
|
||||
return;
|
||||
};
|
||||
if command != "exec-server" {
|
||||
return;
|
||||
}
|
||||
// Enable requested child diagnostics so integration tests can observe background failures.
|
||||
if env::var_os("RUST_LOG").is_some()
|
||||
&& let Err(error) = tracing_subscriber::fmt()
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
|
||||
.with_writer(std::io::stderr)
|
||||
.with_ansi(false)
|
||||
.try_init()
|
||||
{
|
||||
eprintln!("failed to initialize executor test logging: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
// Initialize in the executor child, just as the real CLI does at startup.
|
||||
codex_build_info::BuildInfo::initialize(TEST_BUILD_COMMIT);
|
||||
|
||||
let Some(flag) = args.next() else {
|
||||
eprintln!("expected --listen");
|
||||
std::process::exit(1);
|
||||
};
|
||||
if flag != "--listen" {
|
||||
eprintln!("expected --listen, got `{flag}`");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let Some(listen_url) = args.next() else {
|
||||
eprintln!("expected listen URL");
|
||||
std::process::exit(1);
|
||||
};
|
||||
let remaining_args = args.collect::<Vec<_>>();
|
||||
let request_dispatch_mode = match remaining_args.as_slice() {
|
||||
[] => RequestDispatchMode::Inline,
|
||||
[flag, value] if flag == "--concurrent-requests" => match value.parse() {
|
||||
Ok(mode) => mode,
|
||||
Err(error) => {
|
||||
eprintln!("invalid concurrent request count: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
},
|
||||
args => {
|
||||
eprintln!("unexpected exec-server arguments: {args:?}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let current_exe = match env::current_exe() {
|
||||
Ok(current_exe) => current_exe,
|
||||
Err(error) => {
|
||||
eprintln!("failed to resolve current test binary: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let mut runtime_paths = match ExecServerRuntimeOptions::new(
|
||||
current_exe.clone(),
|
||||
linux_sandbox_exe(guard, ¤t_exe),
|
||||
) {
|
||||
Ok(runtime_paths) => runtime_paths,
|
||||
Err(error) => {
|
||||
eprintln!("failed to configure exec-server runtime paths: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
runtime_paths.prefer_mxc = env::var("CODEX_EXEC_SERVER_TEST_PREFER_MXC")
|
||||
.ok()
|
||||
.map(|value| {
|
||||
value.parse().unwrap_or_else(|error| {
|
||||
eprintln!("invalid test MXC preference: {error}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
});
|
||||
let runtime = match tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(runtime) => runtime,
|
||||
Err(error) => {
|
||||
eprintln!("failed to build Tokio runtime: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let http_client_factory = match (
|
||||
env::var(SYSTEM_PROXY_REQUEST_URL_ENV),
|
||||
env::var(SYSTEM_PROXY_URL_ENV),
|
||||
) {
|
||||
(Ok(request_url), Ok(proxy_url)) => {
|
||||
codex_http_client::cache_system_proxy_route_for_test(&request_url, proxy_url);
|
||||
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy)
|
||||
}
|
||||
(Err(env::VarError::NotPresent), Err(env::VarError::NotPresent)) => {
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
}
|
||||
_ => {
|
||||
eprintln!("system proxy test configuration requires both request and proxy URLs");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let exit_code = match runtime.block_on(async {
|
||||
#[cfg(target_os = "macos")]
|
||||
let runtime_paths = {
|
||||
let home = codex_utils_home_dir::find_codex_home()?;
|
||||
let config = codex_config::loader::load_config_layers_state(
|
||||
&codex_exec_server::LocalFileSystem::unsandboxed(),
|
||||
home.as_path(),
|
||||
/*cwd*/ None,
|
||||
&[],
|
||||
codex_config::LoaderOverrides::default(),
|
||||
&codex_config::NoopThreadConfigLoader,
|
||||
)
|
||||
.await?;
|
||||
runtime_paths.with_allowed_symlinked_codex_home(
|
||||
codex_config::allowed_symlinked_codex_home(&config, &home),
|
||||
)
|
||||
};
|
||||
codex_exec_server::run_main_with_telemetry(
|
||||
&listen_url,
|
||||
runtime_paths,
|
||||
ExecServerTelemetry::default(),
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
codex_websocket_auth::WebsocketAuthSettings::default(),
|
||||
)
|
||||
.await
|
||||
}) {
|
||||
Ok(()) => 0,
|
||||
Err(error) => {
|
||||
eprintln!("exec-server failed: {error}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
fn linux_sandbox_exe(
|
||||
guard: Option<&TestBinaryDispatchGuard>,
|
||||
current_exe: &std::path::Path,
|
||||
) -> Option<PathBuf> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
guard
|
||||
.and_then(|guard| guard.paths().codex_linux_sandbox_exe.clone())
|
||||
.or_else(|| Some(current_exe.to_path_buf()))
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = guard;
|
||||
let _ = current_exe;
|
||||
None
|
||||
}
|
||||
}
|
||||
157
codex-rs/exec-server/tests/common/relay.rs
Normal file
157
codex-rs/exec-server/tests/common/relay.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_api::AuthProvider;
|
||||
use codex_exec_server::ExecServerClient;
|
||||
use codex_exec_server::NoiseChannelIdentity;
|
||||
use codex_exec_server::NoiseRendezvousConnectArgs;
|
||||
use codex_exec_server::NoiseRendezvousConnectBundle;
|
||||
use codex_exec_server::RemoteEnvironmentConfig;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
pub(crate) use codex_exec_server_test_support::relay::TEST_TIMEOUT;
|
||||
pub(crate) use codex_exec_server_test_support::relay::accept_websocket;
|
||||
pub(crate) use codex_exec_server_test_support::relay::assert_relay_data_is_encrypted;
|
||||
pub(crate) use codex_exec_server_test_support::relay::proxy_relay_frames;
|
||||
pub(crate) use codex_exec_server_test_support::relay::registered_executor_public_key;
|
||||
|
||||
pub(crate) const ENVIRONMENT_ID: &str = "env-noise-relay-test";
|
||||
pub(crate) const EXECUTOR_REGISTRATION_ID: &str = "registration-1";
|
||||
pub(crate) const HARNESS_KEY_AUTHORIZATION: &str = "harness-key-authorization";
|
||||
pub(crate) const REGISTRY_TOKEN: &str = "registry-token";
|
||||
|
||||
#[derive(Debug)]
|
||||
struct StaticRegistryAuthProvider;
|
||||
|
||||
impl AuthProvider for StaticRegistryAuthProvider {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
|
||||
let _ = headers.insert(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer registry-token"),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn static_registry_auth_provider() -> codex_api::SharedAuthProvider {
|
||||
Arc::new(StaticRegistryAuthProvider)
|
||||
}
|
||||
|
||||
pub(crate) struct RelayTest {
|
||||
registry: MockServer,
|
||||
listener: TcpListener,
|
||||
}
|
||||
|
||||
pub(crate) struct RelayConnection {
|
||||
pub(crate) client: ExecServerClient,
|
||||
captured_frames: Arc<Mutex<Vec<Vec<u8>>>>,
|
||||
relay_task: AbortOnDropHandle<Result<()>>,
|
||||
}
|
||||
|
||||
impl RelayTest {
|
||||
pub(crate) async fn new() -> Result<Self> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let rendezvous_url = format!("ws://{}", listener.local_addr()?);
|
||||
let registry = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!(
|
||||
"/cloud/environment/{ENVIRONMENT_ID}/register"
|
||||
)))
|
||||
.and(header("authorization", format!("Bearer {REGISTRY_TOKEN}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"environment_id": ENVIRONMENT_ID,
|
||||
"url": format!("{rendezvous_url}/relay?role=environment"),
|
||||
"security_profile": "noise_hybrid_ik_v1",
|
||||
"executor_registration_id": EXECUTOR_REGISTRATION_ID,
|
||||
})))
|
||||
.mount(®istry)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!(
|
||||
"/cloud/environment/{ENVIRONMENT_ID}/validate"
|
||||
)))
|
||||
.and(header("authorization", format!("Bearer {REGISTRY_TOKEN}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"valid": true,
|
||||
})))
|
||||
.mount(®istry)
|
||||
.await;
|
||||
Ok(Self { registry, listener })
|
||||
}
|
||||
|
||||
pub(crate) fn config(&self) -> Result<RemoteEnvironmentConfig> {
|
||||
Ok(RemoteEnvironmentConfig::new(
|
||||
self.registry.uri(),
|
||||
ENVIRONMENT_ID.to_string(),
|
||||
static_registry_auth_provider(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub(crate) async fn connect(&self) -> Result<RelayConnection> {
|
||||
let rendezvous_url = format!("ws://{}", self.listener.local_addr()?);
|
||||
let environment_websocket = accept_websocket(&self.listener, "environment").await?;
|
||||
let executor_public_key = registered_executor_public_key(&self.registry).await?;
|
||||
let harness_identity = NoiseChannelIdentity::generate()?;
|
||||
let client_args = NoiseRendezvousConnectArgs {
|
||||
bundle: NoiseRendezvousConnectBundle {
|
||||
websocket_url: format!("{rendezvous_url}/relay?role=harness"),
|
||||
environment_id: ENVIRONMENT_ID.to_string(),
|
||||
executor_registration_id: EXECUTOR_REGISTRATION_ID.to_string(),
|
||||
executor_public_key,
|
||||
harness_key_authorization: HARNESS_KEY_AUTHORIZATION.to_string(),
|
||||
},
|
||||
harness_identity,
|
||||
client_name: "noise-relay-test".to_string(),
|
||||
connect_timeout: TEST_TIMEOUT,
|
||||
initialize_timeout: TEST_TIMEOUT,
|
||||
resume_session_id: None,
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
};
|
||||
let client_task =
|
||||
tokio::spawn(
|
||||
async move { ExecServerClient::connect_noise_rendezvous(client_args).await },
|
||||
);
|
||||
let harness_websocket = accept_websocket(&self.listener, "harness").await?;
|
||||
let captured_frames = Arc::new(Mutex::new(Vec::new()));
|
||||
let relay_task = AbortOnDropHandle::new(tokio::spawn(proxy_relay_frames(
|
||||
environment_websocket,
|
||||
harness_websocket,
|
||||
Arc::clone(&captured_frames),
|
||||
)));
|
||||
let client = timeout(TEST_TIMEOUT, client_task)
|
||||
.await
|
||||
.context("Noise harness client should connect")???;
|
||||
Ok(RelayConnection {
|
||||
client,
|
||||
captured_frames,
|
||||
relay_task,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl RelayConnection {
|
||||
pub(crate) fn assert_encrypted(&self) -> Result<()> {
|
||||
assert_relay_data_is_encrypted(&self.captured_frames)
|
||||
}
|
||||
|
||||
pub(crate) async fn close(self) {
|
||||
drop(self.client);
|
||||
self.relay_task.abort();
|
||||
let _ = self.relay_task.await;
|
||||
}
|
||||
}
|
||||
227
codex-rs/exec-server/tests/common/tls_proxy.rs
Normal file
227
codex-rs/exec-server/tests/common/tls_proxy.rs
Normal file
@@ -0,0 +1,227 @@
|
||||
//! Local TLS CONNECT proxy shared by executor integration tests.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::net::TcpListener;
|
||||
use std::net::TcpStream;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use rcgen::BasicConstraints;
|
||||
use rcgen::CertificateParams;
|
||||
use rcgen::CertifiedIssuer;
|
||||
use rcgen::DistinguishedName;
|
||||
use rcgen::DnType;
|
||||
use rcgen::ExtendedKeyUsagePurpose;
|
||||
use rcgen::IsCa;
|
||||
use rcgen::KeyPair;
|
||||
use rcgen::KeyUsagePurpose;
|
||||
use rcgen::PKCS_ECDSA_P256_SHA256;
|
||||
use rustls::pki_types::CertificateDer;
|
||||
use rustls::pki_types::PrivateKeyDer;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CapturedRequest {
|
||||
pub(crate) connect_authority: String,
|
||||
pub(crate) request_line: String,
|
||||
pub(crate) headers: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
struct TlsMaterial {
|
||||
ca_cert_pem: String,
|
||||
server_cert: CertificateDer<'static>,
|
||||
server_key: PrivateKeyDer<'static>,
|
||||
}
|
||||
|
||||
pub(crate) struct TlsInterceptingProxy {
|
||||
pub(crate) ca_cert_pem: String,
|
||||
request_rx: mpsc::Receiver<Result<CapturedRequest, String>>,
|
||||
thread: thread::JoinHandle<Result<(), String>>,
|
||||
pub(crate) url: String,
|
||||
}
|
||||
|
||||
impl TlsInterceptingProxy {
|
||||
pub(crate) fn start(expected_requests: usize) -> anyhow::Result<Self> {
|
||||
codex_utils_rustls_provider::ensure_rustls_crypto_provider();
|
||||
let material = generate_tls_material()?;
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0))?;
|
||||
let address = listener.local_addr()?;
|
||||
let config = Arc::new(
|
||||
rustls::ServerConfig::builder_with_protocol_versions(&[&rustls::version::TLS13])
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![material.server_cert], material.server_key)?,
|
||||
);
|
||||
let (request_tx, request_rx) = mpsc::channel();
|
||||
let thread = thread::spawn(move || {
|
||||
run_tls_intercepting_proxy(listener, config, request_tx, expected_requests)
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
ca_cert_pem: material.ca_cert_pem,
|
||||
request_rx,
|
||||
thread,
|
||||
url: format!("http://{address}"),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn next_request(&self) -> anyhow::Result<CapturedRequest> {
|
||||
self.request_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.map_err(anyhow::Error::from)?
|
||||
.map_err(anyhow::Error::msg)
|
||||
}
|
||||
|
||||
pub(crate) fn finish(self) -> anyhow::Result<()> {
|
||||
self.thread
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("TLS proxy thread panicked"))?
|
||||
.map_err(anyhow::Error::msg)
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_tls_material() -> anyhow::Result<TlsMaterial> {
|
||||
let mut ca_params = CertificateParams::default();
|
||||
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
|
||||
ca_params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
|
||||
let mut ca_distinguished_name = DistinguishedName::new();
|
||||
ca_distinguished_name.push(DnType::CommonName, "Codex affinity test CA");
|
||||
ca_params.distinguished_name = ca_distinguished_name;
|
||||
let ca_key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?;
|
||||
let ca = CertifiedIssuer::self_signed(ca_params, ca_key_pair)?;
|
||||
|
||||
let mut server_params = CertificateParams::new(vec![
|
||||
"chatgpt.com".to_string(),
|
||||
"api.openai.com".to_string(),
|
||||
])?;
|
||||
server_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
|
||||
server_params.key_usages = vec![
|
||||
KeyUsagePurpose::DigitalSignature,
|
||||
KeyUsagePurpose::KeyEncipherment,
|
||||
];
|
||||
let server_key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?;
|
||||
let server_cert = server_params.signed_by(&server_key_pair, &ca)?;
|
||||
|
||||
Ok(TlsMaterial {
|
||||
ca_cert_pem: ca.pem(),
|
||||
server_cert: server_cert.der().clone(),
|
||||
server_key: PrivateKeyDer::from(server_key_pair),
|
||||
})
|
||||
}
|
||||
|
||||
fn run_tls_intercepting_proxy(
|
||||
listener: TcpListener,
|
||||
config: Arc<rustls::ServerConfig>,
|
||||
request_tx: mpsc::Sender<Result<CapturedRequest, String>>,
|
||||
expected_requests: usize,
|
||||
) -> io::Result<()> {
|
||||
for request_index in 0..expected_requests {
|
||||
let (mut stream, _) = listener.accept()?;
|
||||
configure_stream(&stream)?;
|
||||
let connect_head = read_http_head(&mut stream)?;
|
||||
let connect_authority = connect_head
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.ok_or_else(|| io::Error::other("CONNECT request line should include an authority"))?
|
||||
.to_string();
|
||||
stream.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")?;
|
||||
stream.flush()?;
|
||||
|
||||
let connection =
|
||||
rustls::ServerConnection::new(Arc::clone(&config)).map_err(io::Error::other)?;
|
||||
let mut tls = rustls::StreamOwned::new(connection, stream);
|
||||
let request = capture_http_request(&mut tls, connect_authority);
|
||||
match request {
|
||||
Ok(request) => request_tx
|
||||
.send(Ok(request))
|
||||
.map_err(|_| io::Error::other("request receiver was dropped"))?,
|
||||
Err(error) => {
|
||||
let message = error.to_string();
|
||||
let _ = request_tx.send(Err(message));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
let response = match request_index {
|
||||
0 => concat!(
|
||||
"HTTP/1.1 200 OK\r\n",
|
||||
"content-length: 2\r\n",
|
||||
"connection: close\r\n",
|
||||
"set-cookie: __cflb=west; Path=/; Secure; HttpOnly\r\n",
|
||||
"set-cookie: chatgpt_session=secret; Path=/; Secure; HttpOnly\r\n",
|
||||
"\r\n",
|
||||
"ok",
|
||||
),
|
||||
1 => concat!(
|
||||
"HTTP/1.1 200 OK\r\n",
|
||||
"content-length: 2\r\n",
|
||||
"connection: close\r\n",
|
||||
"set-cookie: __cflb=central; Path=/; Secure; HttpOnly\r\n",
|
||||
"set-cookie: chatgpt_session=still-secret; Path=/; Secure; HttpOnly\r\n",
|
||||
"\r\n",
|
||||
"ok",
|
||||
),
|
||||
_ => concat!(
|
||||
"HTTP/1.1 200 OK\r\n",
|
||||
"content-length: 2\r\n",
|
||||
"connection: close\r\n",
|
||||
"\r\n",
|
||||
"ok",
|
||||
),
|
||||
};
|
||||
tls.write_all(response.as_bytes())?;
|
||||
tls.flush()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_stream(stream: &TcpStream) -> io::Result<()> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5)))
|
||||
}
|
||||
|
||||
fn capture_http_request(
|
||||
stream: &mut impl Read,
|
||||
connect_authority: String,
|
||||
) -> io::Result<CapturedRequest> {
|
||||
let request_head = read_http_head(stream)?;
|
||||
let mut lines = request_head.lines();
|
||||
let request_line = lines
|
||||
.next()
|
||||
.ok_or_else(|| io::Error::other("HTTP request should include a request line"))?
|
||||
.to_string();
|
||||
let mut headers: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
for line in lines.filter(|line| !line.is_empty()) {
|
||||
let (name, value) = line
|
||||
.split_once(':')
|
||||
.ok_or_else(|| io::Error::other(format!("invalid HTTP header: {line}")))?;
|
||||
headers
|
||||
.entry(name.to_ascii_lowercase())
|
||||
.or_default()
|
||||
.push(value.trim().to_string());
|
||||
}
|
||||
Ok(CapturedRequest {
|
||||
connect_authority,
|
||||
request_line,
|
||||
headers,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_http_head(stream: &mut impl Read) -> io::Result<String> {
|
||||
const MAX_HEADER_BYTES: usize = 64 * 1024;
|
||||
let mut bytes = Vec::new();
|
||||
while !bytes.ends_with(b"\r\n\r\n") {
|
||||
if bytes.len() == MAX_HEADER_BYTES {
|
||||
return Err(io::Error::other("HTTP headers exceeded test limit"));
|
||||
}
|
||||
let mut byte = [0];
|
||||
stream.read_exact(&mut byte)?;
|
||||
bytes.push(byte[0]);
|
||||
}
|
||||
String::from_utf8(bytes).map_err(io::Error::other)
|
||||
}
|
||||
Reference in New Issue
Block a user