Files
codex/codex-rs/core/tests/common/runtime_auth.rs
T
iceweasel-oai f39c3c78d7 Initialize Statsig feature gates across Codex launch modes (#64001)
## Why

Enabling `statsig_gates` can only load evaluations if the process starts
the Statsig runtime. Several Codex entry points never started it.

## What changed

Start Statsig in standalone and embedded app servers, the TUI when it
connects to a separate app server, eligible `codex sandbox` launches, and
local and remote exec servers. This also covers `codex exec` through its
embedded app server. Use the serving or local account where applicable
and installation identity for remote execution. Share the runtime with
the embedded TUI and flush it on normal shutdown.

## Testing

Add a CLI integration test that checks which evaluation endpoint each
launch mode requests, including signed-in and signed-out sandbox launches.
Supply a bundled fixture key in Bazel and nextest CI builds so the test runs.

GitOrigin-RevId: 64df9933c1a9783a86be8712fa012b495f34b0f8
2026-11-25 22:46:26 +00:00

195 lines
8.2 KiB
Rust

//! Route isolated first-party auth tests to loopback without relaxing destination checks.
use anyhow::Result;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::process::Command;
use tokio::task::JoinSet;
use tokio_rustls::TlsAcceptor;
use tokio_rustls::rustls;
use wiremock::MockServer;
pub const PROBE_SERVER: &str = "CODEX_RUNTIME_AUTH_TEST_SERVER";
/// Run one test in an isolated subprocess with first-party HTTP routed to the mock server.
/// An optional Realtime target receives public and synthetic private observer upgrades.
pub async fn run_harness_through_proxy(
server: &MockServer,
test_name: &str,
realtime_target: Option<std::net::SocketAddr>,
) -> Result<()> {
run_harness_through_proxy_with_env(server, test_name, realtime_target, &[]).await
}
/// Adds process-local auth inputs without changing the test runner's environment.
pub async fn run_harness_through_proxy_with_env(
server: &MockServer,
test_name: &str,
realtime_target: Option<std::net::SocketAddr>,
environment: &[(&str, Option<&str>)],
) -> Result<()> {
run_harness_through_proxy_until(
server,
test_name,
realtime_target,
environment,
std::future::ready(Ok(())),
)
.await
}
/// Keeps active proxy connections alive while checking the observer after the child exits.
pub async fn run_harness_through_proxy_until(
server: &MockServer,
test_name: &str,
realtime_target: Option<std::net::SocketAddr>,
environment: &[(&str, Option<&str>)],
observer_completion: impl Future<Output = Result<()>>,
) -> Result<()> {
with_harness_proxy(server, realtime_target, async |mut command| {
command
.args(["--exact", test_name, "--nocapture"])
.kill_on_drop(true);
for (key, value) in environment {
match value {
Some(value) => command.env(key, value),
None => command.env_remove(key),
};
}
let output = tokio::time::timeout(Duration::from_secs(90), command.output()).await??;
assert!(
output.status.success(),
"harness subprocess failed\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
observer_completion.await
})
.await
}
/// Supplies a test subprocess command with HTTPS routed to the mock server.
pub async fn with_harness_proxy(
server: &MockServer,
realtime_target: Option<std::net::SocketAddr>,
run: impl AsyncFnOnce(Command) -> Result<()>,
) -> Result<()> {
// The production destination check stays intact. A test-only CA and CONNECT proxy route
// the real host names to wiremock, only inside this isolated test subprocess.
codex_utils_rustls_provider::ensure_rustls_crypto_provider();
let rcgen::CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed(vec![
"api.openai.com".into(),
"api.openai.org".into(),
"auth.openai.com".into(),
"chatgpt.com".into(),
"us.chatgpt.com".into(),
"chatgpt-staging.com".into(),
"us.chatgpt-staging.com".into(),
"auth.api.openai.org".into(),
"observer.internal.api.openai.org".into(),
"ab.chatgpt.com".into(),
])?;
let ca_dir = tempfile::tempdir()?;
let ca_path = ca_dir.path().join("ca.pem");
std::fs::write(&ca_path, cert.pem())?;
let acceptor = TlsAcceptor::from(Arc::new(
rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(vec![cert.der().clone()], signing_key.into())?,
));
let proxy = TcpListener::bind("127.0.0.1:0").await?;
let proxy_url = format!("http://{}", proxy.local_addr()?);
let target = *server.address();
// Dropping the task set also closes the proxy if the test fails or is cancelled.
let mut proxy_tasks = JoinSet::new();
proxy_tasks.spawn(async move {
let mut connections = JoinSet::new();
loop {
let (mut stream, _) = proxy.accept().await?;
let acceptor = acceptor.clone();
connections.spawn(async move {
let mut headers = Vec::new();
while !headers.ends_with(b"\r\n\r\n") && headers.len() < 8192 {
headers.push(stream.read_u8().await?);
}
let headers = std::str::from_utf8(&headers)?;
anyhow::ensure!(
matches!(
headers.lines().next(),
Some(
"CONNECT api.openai.com:443 HTTP/1.1"
| "CONNECT api.openai.org:443 HTTP/1.1"
| "CONNECT auth.openai.com:443 HTTP/1.1"
| "CONNECT chatgpt.com:443 HTTP/1.1"
| "CONNECT us.chatgpt.com:443 HTTP/1.1"
| "CONNECT chatgpt-staging.com:443 HTTP/1.1"
| "CONNECT us.chatgpt-staging.com:443 HTTP/1.1"
| "CONNECT auth.api.openai.org:443 HTTP/1.1"
| "CONNECT observer.internal.api.openai.org:443 HTTP/1.1"
| "CONNECT ab.chatgpt.com:443 HTTP/1.1"
)
),
"unexpected proxy destination"
);
stream
.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
.await?;
let realtime_host = headers.starts_with("CONNECT chatgpt.com:443 ")
|| headers.starts_with("CONNECT observer.internal.api.openai.org:443 ");
let mut stream = acceptor.accept(stream).await?;
let mut prefix = Vec::new();
let mut destination = target;
if let Some(realtime_target) = realtime_target.filter(|_| realtime_host) {
// Background HTTP requests share this host with Realtime. Only upgrades
// belong on the WebSocket fixture; ordinary HTTP still goes to wiremock.
while !prefix.ends_with(b"\r\n\r\n") && prefix.len() < 65536 {
prefix.push(stream.read_u8().await?);
}
anyhow::ensure!(
prefix.ends_with(b"\r\n\r\n"),
"oversized test request headers"
);
let request_headers = std::str::from_utf8(&prefix)?;
let realtime_path = request_headers.lines().next().is_some_and(|line| {
line.starts_with("GET /v1/realtime") || line.starts_with("GET /v1/live")
});
if realtime_path
&& request_headers.lines().any(|line| {
line.split_once(':').is_some_and(|(name, value)| {
name.eq_ignore_ascii_case("upgrade")
&& value.trim().eq_ignore_ascii_case("websocket")
})
})
{
destination = realtime_target;
}
}
let mut target = TcpStream::connect(destination).await?;
target.write_all(&prefix).await?;
tokio::io::copy_bidirectional(&mut stream, &mut target).await?;
Ok::<_, anyhow::Error>(())
});
}
#[allow(unreachable_code)]
Ok::<_, anyhow::Error>(())
});
let mut command = Command::new(std::env::current_exe()?);
// Materialize inherited variables so launchers that take an env map can use get_envs().
command.env_clear().envs(std::env::vars_os());
for &key in codex_network_proxy::PROXY_ENV_KEYS {
command.env_remove(key);
}
command
.env(PROBE_SERVER, server.uri())
.env("HTTPS_PROXY", proxy_url)
.env("NO_PROXY", codex_network_proxy::DEFAULT_NO_PROXY_VALUE)
.env("CODEX_CA_CERTIFICATE", ca_path);
let result = run(command).await;
proxy_tasks.shutdown().await;
result
}