mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Add opt-in WebSocket authentication to exec-server (#47601)
## What changed Expose the shared `--ws-auth` options on `codex exec-server` for direct WebSocket listeners. Support capability tokens configured by token file or SHA-256 digest, and signed JWT bearer tokens. Validate `Authorization: Bearer TOKEN` before each WebSocket upgrade, rejecting missing or invalid credentials with HTTP 401 when authentication is enabled. Reject listener authentication with stdio, `--remote`, or `forward`. Document the options and connection-time authentication behavior. ## Testing Add CLI integration tests for all three credential configurations, unauthorized upgrade rejection, authenticated RPC initialization and reconnects, invalid configuration, and incompatible transports. GitOrigin-RevId: 941fbd3d43e732c910d29b6f8137077b7c332835
This commit is contained in:
committed by
copyberry
parent
6824dabe03
commit
2210190435
Generated
+3
@@ -2535,6 +2535,7 @@ dependencies = [
|
||||
"futures",
|
||||
"http 1.4.0",
|
||||
"insta",
|
||||
"jsonwebtoken",
|
||||
"libc",
|
||||
"os_info",
|
||||
"owo-colors",
|
||||
@@ -2543,6 +2544,7 @@ dependencies = [
|
||||
"regex-lite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"sqlx",
|
||||
"supports-color 3.0.2",
|
||||
"sys-locale",
|
||||
@@ -3161,6 +3163,7 @@ dependencies = [
|
||||
"codex-utils-path-uri",
|
||||
"codex-utils-pty",
|
||||
"codex-utils-rustls-provider",
|
||||
"codex-websocket-auth",
|
||||
"codex-websocket-client",
|
||||
"ctor 0.6.3",
|
||||
"dirs",
|
||||
|
||||
@@ -125,8 +125,10 @@ codex-utils-cargo-bin = { workspace = true }
|
||||
codex-utils-pty = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
insta = { workspace = true }
|
||||
jsonwebtoken = { workspace = true }
|
||||
predicates = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
sqlx = { workspace = true }
|
||||
tar = { workspace = true }
|
||||
tokio-tungstenite = { workspace = true }
|
||||
|
||||
@@ -23,6 +23,7 @@ use codex_login::is_workload_identity_selected;
|
||||
use codex_login::read_codex_access_token_from_env;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_websocket_auth::WebsocketAuthArgs;
|
||||
|
||||
use crate::exec_server_auth;
|
||||
use crate::exec_server_telemetry;
|
||||
@@ -58,6 +59,9 @@ pub(super) struct ExecServerCommand {
|
||||
)]
|
||||
listen: Option<String>,
|
||||
|
||||
#[command(flatten)]
|
||||
websocket_auth: WebsocketAuthArgs,
|
||||
|
||||
/// Register this exec-server as a remote environment using the given base URL.
|
||||
#[arg(
|
||||
long = "remote",
|
||||
@@ -147,6 +151,10 @@ impl ExecServerCommand {
|
||||
) -> anyhow::Result<()> {
|
||||
let strict_config = self.strict_config;
|
||||
self.validate_remote_transport()?;
|
||||
let websocket_auth = self.websocket_auth.try_into_settings()?;
|
||||
if websocket_auth.config.is_some() && (self.remote.is_some() || self.command.is_some()) {
|
||||
anyhow::bail!("WebSocket listener auth cannot be used with --remote or forward");
|
||||
}
|
||||
let codex_self_exe = arg0_paths
|
||||
.codex_self_exe
|
||||
.clone()
|
||||
@@ -279,6 +287,7 @@ impl ExecServerCommand {
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
self.request_dispatch_mode,
|
||||
websocket_auth,
|
||||
),
|
||||
exec_server_telemetry::ParentLifetime::Independent,
|
||||
exec_server_telemetry::ShutdownBehavior::Immediate,
|
||||
|
||||
+23
@@ -41,6 +41,29 @@ Options:
|
||||
Transport endpoint URL. Supported values: `ws://IP:PORT` (default),
|
||||
`stdio`, `stdio://`
|
||||
|
||||
--ws-auth <MODE>
|
||||
Authentication mode for incoming WebSocket connections
|
||||
|
||||
[possible values: capability-token, signed-bearer-token]
|
||||
|
||||
--ws-token-file <PATH>
|
||||
Absolute path to the capability-token file
|
||||
|
||||
--ws-token-sha256 <HEX>
|
||||
Hex-encoded SHA-256 digest of the capability token
|
||||
|
||||
--ws-shared-secret-file <PATH>
|
||||
Absolute path to the shared secret file for signed JWT bearer tokens
|
||||
|
||||
--ws-issuer <ISSUER>
|
||||
Expected issuer for signed JWT bearer tokens
|
||||
|
||||
--ws-audience <AUDIENCE>
|
||||
Expected audience for signed JWT bearer tokens
|
||||
|
||||
--ws-max-clock-skew-seconds <SECONDS>
|
||||
Maximum clock skew when validating signed JWT bearer tokens
|
||||
|
||||
--remote <URL>
|
||||
Register this exec-server as a remote environment using the given base
|
||||
URL
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Exercises listener authentication through the standalone executor CLI and real WebSockets.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Command;
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::Error as WebSocketError;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
|
||||
enum AuthMode {
|
||||
TokenHash,
|
||||
TokenFile,
|
||||
SignedBearer,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exec_server_websocket_auth_gates_rpc_connections() -> Result<()> {
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 60), async {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
for mode in [
|
||||
AuthMode::TokenHash,
|
||||
AuthMode::TokenFile,
|
||||
AuthMode::SignedBearer,
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
let secret = "0123456789abcdef0123456789abcdef";
|
||||
let secret_file = home.path().join("secret");
|
||||
std::fs::write(&secret_file, secret)?;
|
||||
let mut command = Command::new(&codex);
|
||||
command
|
||||
.args(["exec-server", "--listen", "ws://127.0.0.1:0", "--ws-auth"])
|
||||
.env("CODEX_HOME", home.path())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true);
|
||||
let token = match mode {
|
||||
AuthMode::TokenHash => {
|
||||
command.args([
|
||||
"capability-token",
|
||||
"--ws-token-sha256",
|
||||
&format!("{:x}", Sha256::digest(secret.as_bytes())),
|
||||
]);
|
||||
secret.to_string()
|
||||
}
|
||||
AuthMode::TokenFile => {
|
||||
command
|
||||
.args(["capability-token", "--ws-token-file"])
|
||||
.arg(&secret_file);
|
||||
secret.to_string()
|
||||
}
|
||||
AuthMode::SignedBearer => {
|
||||
command
|
||||
.args(["signed-bearer-token", "--ws-shared-secret-file"])
|
||||
.arg(&secret_file)
|
||||
.args([
|
||||
"--ws-issuer",
|
||||
"test-issuer",
|
||||
"--ws-audience",
|
||||
"test-executor",
|
||||
]);
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
|
||||
jsonwebtoken::encode(
|
||||
&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
|
||||
&json!({"exp": now + 300, "iss": "test-issuer", "aud": "test-executor"}),
|
||||
&jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
|
||||
)?
|
||||
}
|
||||
};
|
||||
let mut child = command.spawn()?;
|
||||
let mut lines = BufReader::new(child.stdout.take().context("stdout")?).lines();
|
||||
let url = loop {
|
||||
let line = lines
|
||||
.next_line()
|
||||
.await?
|
||||
.context("listener exited before startup")?;
|
||||
if line.starts_with("ws://") {
|
||||
break line;
|
||||
}
|
||||
};
|
||||
|
||||
// A missing or incorrect credential must fail before any RPC session opens.
|
||||
let digest_as_bearer = format!("Bearer {:x}", Sha256::digest(secret.as_bytes()));
|
||||
for authorization in [
|
||||
None,
|
||||
Some("Bearer incorrect"),
|
||||
Some("Basic incorrect"),
|
||||
Some(digest_as_bearer.as_str()),
|
||||
] {
|
||||
let mut request = url.as_str().into_client_request()?;
|
||||
if let Some(authorization) = authorization {
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("authorization", authorization.parse()?);
|
||||
}
|
||||
let error = connect_async(request)
|
||||
.await
|
||||
.expect_err("reject unauthorized upgrade");
|
||||
let WebSocketError::Http(response) = error else {
|
||||
anyhow::bail!("expected HTTP rejection, got {error}");
|
||||
};
|
||||
assert_eq!(response.status(), http::StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// Authentication applies to every connection, including reconnects.
|
||||
for _ in 0..2 {
|
||||
let mut request = url.as_str().into_client_request()?;
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("authorization", format!("Bearer {token}").parse()?);
|
||||
let (mut websocket, _) = connect_async(request).await?;
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {"clientName": "auth-test"}
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
let response = websocket.next().await.context("initialize response")??;
|
||||
let response: serde_json::Value = serde_json::from_str(response.to_text()?)?;
|
||||
assert_eq!(response["id"], json!(1));
|
||||
assert!(response.get("error").is_none(), "{response}");
|
||||
assert!(response["result"]["sessionId"].is_string(), "{response}");
|
||||
websocket.close(/*msg*/ None).await?;
|
||||
}
|
||||
child.kill().await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_server_websocket_auth_rejects_inapplicable_transports() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
for (transport, expected) in [
|
||||
(vec!["--listen", "stdio"], "not stdio"),
|
||||
(vec!["--listen", "stdio://"], "not stdio"),
|
||||
(
|
||||
vec![
|
||||
"--remote",
|
||||
"https://registry.example",
|
||||
"--environment-id",
|
||||
"test",
|
||||
],
|
||||
"cannot be used with --remote",
|
||||
),
|
||||
(
|
||||
vec![
|
||||
"forward",
|
||||
"--connect",
|
||||
"ws://127.0.0.1:1234",
|
||||
"--remote",
|
||||
"https://registry.example",
|
||||
"--environment-id",
|
||||
"test",
|
||||
],
|
||||
"cannot be used with --remote",
|
||||
),
|
||||
] {
|
||||
assert_cmd::Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args([
|
||||
"exec-server",
|
||||
"--ws-auth",
|
||||
"capability-token",
|
||||
"--ws-token-sha256",
|
||||
&"ab".repeat(32),
|
||||
])
|
||||
.args(transport)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains(expected));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_server_websocket_auth_rejects_invalid_configuration() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
for (args, expected) in [
|
||||
(vec!["--ws-token-sha256", "invalid"], "require `--ws-auth"),
|
||||
(
|
||||
vec![
|
||||
"--ws-auth",
|
||||
"capability-token",
|
||||
"--ws-token-sha256",
|
||||
"invalid",
|
||||
],
|
||||
"64-character hex",
|
||||
),
|
||||
(vec!["--ws-auth", "capability-token"], "is required"),
|
||||
] {
|
||||
assert_cmd::Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args(["exec-server"])
|
||||
.args(args)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains(expected));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -37,6 +37,7 @@ codex-utils-home-dir = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
codex-utils-pty = { workspace = true }
|
||||
codex-utils-rustls-provider = { workspace = true }
|
||||
codex-websocket-auth = { workspace = true }
|
||||
codex-websocket-client = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
|
||||
@@ -25,6 +25,13 @@ The CLI entrypoint supports:
|
||||
- `--remote URL --environment-id ID [--name NAME]`
|
||||
- `forward --connect ws://HOST:PORT --remote URL --environment-id ID`
|
||||
|
||||
## Authentication
|
||||
|
||||
Direct WebSocket listeners support app-server's opt-in auth flags, including `--ws-auth capability-token --ws-token-sha256 HEX`, token files, and signed bearer tokens; clients send `Authorization: Bearer TOKEN` on each connection.
|
||||
Use a protected transport or TLS proxy for remote access; authentication is checked at connection time and these flags do not apply to stdio, remote registration, or forwarding.
|
||||
|
||||
## Remote connections
|
||||
|
||||
Remote mode registers the local exec-server with the environment registry,
|
||||
then reconnects to the service-provided rendezvous websocket as the environment.
|
||||
Remote communication uses the Noise relay contract; the registry and harness
|
||||
|
||||
@@ -23,6 +23,7 @@ pub use transport::ExecServerListenUrlParseError;
|
||||
use crate::ExecServerRuntimePaths;
|
||||
use crate::ExecServerTelemetry;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_websocket_auth::WebsocketAuthSettings;
|
||||
|
||||
pub async fn run_main(
|
||||
listen_url: &str,
|
||||
@@ -35,6 +36,7 @@ pub async fn run_main(
|
||||
ExecServerTelemetry::default(),
|
||||
http_client_factory,
|
||||
RequestDispatchMode::Inline,
|
||||
WebsocketAuthSettings::default(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -50,6 +52,7 @@ pub async fn run_main_with_telemetry(
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
websocket_auth: WebsocketAuthSettings,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
std::sync::LazyLock::force(&build_identity::PROVIDER_ID);
|
||||
transport::run_transport(
|
||||
@@ -58,6 +61,7 @@ pub async fn run_main_with_telemetry(
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
websocket_auth,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -97,6 +101,7 @@ mod tests {
|
||||
ExecServerTelemetry::default(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
super::RequestDispatchMode::Inline,
|
||||
codex_websocket_auth::WebsocketAuthSettings::default(),
|
||||
)
|
||||
.await
|
||||
.expect_err("invalid listen URL should fail");
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
//! Exec-server stdio and WebSocket listeners. Configured authentication gates
|
||||
//! WebSocket upgrades; unauthenticated listeners remain supported for compatibility.
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
use axum::extract::ConnectInfo;
|
||||
use axum::extract::State;
|
||||
use axum::extract::ws::WebSocketUpgrade;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::Request;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::header::ORIGIN;
|
||||
@@ -13,6 +17,10 @@ use axum::response::Response;
|
||||
use axum::routing::any;
|
||||
use axum::routing::get;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_websocket_auth::WebsocketAuthPolicy;
|
||||
use codex_websocket_auth::WebsocketAuthSettings;
|
||||
use codex_websocket_auth::authorize_upgrade;
|
||||
use codex_websocket_auth::policy_from_settings;
|
||||
use std::io::Write as _;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::io;
|
||||
@@ -87,6 +95,7 @@ pub(crate) async fn run_transport(
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
websocket_auth: WebsocketAuthSettings,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
match parse_listen_url(listen_url)? {
|
||||
ExecServerListenTransport::WebSocket(bind_address) => {
|
||||
@@ -96,10 +105,18 @@ pub(crate) async fn run_transport(
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
policy_from_settings(&websocket_auth)?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ExecServerListenTransport::Stdio => {
|
||||
if websocket_auth.config.is_some() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"WebSocket auth requires a WebSocket listener, not stdio",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
run_stdio_connection(
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
@@ -164,6 +181,7 @@ async fn run_websocket_listener(
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
auth_policy: WebsocketAuthPolicy,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let listener = TcpListener::bind(bind_address).await?;
|
||||
let local_addr = listener.local_addr()?;
|
||||
@@ -181,7 +199,10 @@ async fn run_websocket_listener(
|
||||
.route("/", any(websocket_upgrade_handler))
|
||||
.route("/readyz", get(readiness_handler))
|
||||
.layer(middleware::from_fn(reject_requests_with_origin_header))
|
||||
.with_state(ExecServerWebSocketState { processor });
|
||||
.with_state(ExecServerWebSocketState {
|
||||
processor,
|
||||
auth_policy,
|
||||
});
|
||||
axum::serve(
|
||||
listener,
|
||||
router.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
@@ -193,6 +214,7 @@ async fn run_websocket_listener(
|
||||
#[derive(Clone)]
|
||||
struct ExecServerWebSocketState {
|
||||
processor: ConnectionProcessor,
|
||||
auth_policy: WebsocketAuthPolicy,
|
||||
}
|
||||
|
||||
async fn readiness_handler() -> StatusCode {
|
||||
@@ -219,20 +241,26 @@ async fn websocket_upgrade_handler(
|
||||
websocket: WebSocketUpgrade,
|
||||
ConnectInfo(peer_addr): ConnectInfo<SocketAddr>,
|
||||
State(state): State<ExecServerWebSocketState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(err) = authorize_upgrade(&headers, &state.auth_policy) {
|
||||
return (err.status_code(), err.message()).into_response();
|
||||
}
|
||||
info!(%peer_addr, "exec-server websocket client connected");
|
||||
websocket.on_upgrade(move |stream| async move {
|
||||
state
|
||||
.processor
|
||||
.run_connection(
|
||||
JsonRpcConnection::from_axum_websocket(
|
||||
stream,
|
||||
format!("exec-server websocket {peer_addr}"),
|
||||
),
|
||||
ConnectionTransport::WebSocket,
|
||||
)
|
||||
.await;
|
||||
})
|
||||
websocket
|
||||
.on_upgrade(move |stream| async move {
|
||||
state
|
||||
.processor
|
||||
.run_connection(
|
||||
JsonRpcConnection::from_axum_websocket(
|
||||
stream,
|
||||
format!("exec-server websocket {peer_addr}"),
|
||||
),
|
||||
ConnectionTransport::WebSocket,
|
||||
)
|
||||
.await;
|
||||
})
|
||||
.into_response()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -262,6 +262,7 @@ fn maybe_run_exec_server_from_test_binary(guard: Option<&TestBinaryDispatchGuard
|
||||
ExecServerTelemetry::default(),
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
codex_websocket_auth::WebsocketAuthSettings::default(),
|
||||
)
|
||||
.await
|
||||
}) {
|
||||
|
||||
Reference in New Issue
Block a user