mirror of
https://github.com/openai/codex.git
synced 2026-11-17 22:10:37 +00:00
Add external header auth for existing realtime calls (#62114)
## What changed Add `RealtimeExistingCallAuth` to `RealtimeAttachmentOptions`, with model-provider authentication as the default. Embedding hosts can explicitly select `ExternalHeaders` for existing calls to use header-based credentials and the host's transport without adding model-provider headers or performing runtime agent registration. Require an explicit, nonempty sideband URL and header-based authentication for this mode. Destination authorization remains the trusted host's responsibility, and application network policy still applies. ## Testing Add integration coverage for external-header and model-provider authentication through event delivery, reconnect, and detach. Verify that model-provider credentials are excluded in external-header mode and that invalid authentication, missing URLs, and network policy denials reject the attachment before a WebSocket handshake. GitOrigin-RevId: 2c915e1cf76a3563f58f751272db1ec50718d925
This commit is contained in:
@@ -59,6 +59,7 @@ use codex_protocol::protocol::RealtimeConversationClosedEvent;
|
||||
use codex_protocol::protocol::RealtimeConversationRealtimeEvent;
|
||||
use codex_protocol::protocol::RealtimeConversationSdpEvent;
|
||||
use codex_protocol::protocol::RealtimeConversationStartedEvent;
|
||||
use codex_protocol::protocol::RealtimeExistingCallAuth;
|
||||
use codex_protocol::protocol::RealtimeHandoffRequested;
|
||||
use codex_protocol::protocol::RealtimeOutputModality;
|
||||
use codex_protocol::protocol::RealtimeTranscriptEntry;
|
||||
@@ -695,7 +696,7 @@ impl RealtimeConversationManager {
|
||||
attachment_control,
|
||||
sideband,
|
||||
auth_context,
|
||||
api_provider,
|
||||
mut api_provider,
|
||||
http_client_factory,
|
||||
realtime_sideband_base_url,
|
||||
extra_headers,
|
||||
@@ -758,6 +759,13 @@ impl RealtimeConversationManager {
|
||||
|
||||
let sideband_base_url =
|
||||
realtime_sideband_base_url.unwrap_or_else(|| "https://api.openai.com/v1".to_string());
|
||||
if attachment_control.options.existing_call_auth
|
||||
== RealtimeExistingCallAuth::ExternalHeaders
|
||||
{
|
||||
// Model-provider headers may contain inference authentication. The
|
||||
// host-selected observer uses only its external auth and session headers.
|
||||
api_provider.headers.clear();
|
||||
}
|
||||
let client = RealtimeWebsocketClient::new(api_provider, http_client_factory.clone())
|
||||
.with_webrtc_sideband_base_url(sideband_base_url.clone());
|
||||
let transcript_tail_flush = RealtimeTranscriptTailFlush {
|
||||
@@ -821,6 +829,7 @@ impl RealtimeConversationManager {
|
||||
} else if let Some(call_id) = existing_call_id {
|
||||
let task = existing_call::attach(existing_call::ExistingCallAttachment {
|
||||
attachment_cancellation: attachment_control.token.clone(),
|
||||
existing_call_auth: attachment_control.options.existing_call_auth,
|
||||
client,
|
||||
model_client,
|
||||
auth_context,
|
||||
@@ -2244,6 +2253,20 @@ pub(crate) async fn handle_attach(
|
||||
params: ConversationStartParams,
|
||||
options: RealtimeAttachmentOptions,
|
||||
) -> CodexResult<()> {
|
||||
if options.existing_call_auth == RealtimeExistingCallAuth::ExternalHeaders
|
||||
&& !matches!(
|
||||
¶ms.transport,
|
||||
Some(ConversationStartTransport::ExistingCall {
|
||||
sideband_base_url: Some(base_url),
|
||||
..
|
||||
}) if !base_url.trim().is_empty()
|
||||
)
|
||||
{
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"external header authentication requires an existing call with an explicit sideband URL"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let attachment_control = RealtimeAttachmentControl {
|
||||
token: CancellationToken::new(),
|
||||
options,
|
||||
|
||||
@@ -15,8 +15,11 @@ use codex_api::RealtimeWebsocketClient;
|
||||
use codex_api::map_api_error;
|
||||
use codex_async_utils::OrCancelExt;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::default_headers;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_protocol::protocol::RealtimeExistingCallAuth;
|
||||
use http::HeaderMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
@@ -25,6 +28,7 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(super) struct ExistingCallAttachment {
|
||||
pub(super) attachment_cancellation: CancellationToken,
|
||||
pub(super) existing_call_auth: RealtimeExistingCallAuth,
|
||||
pub(super) client: RealtimeWebsocketClient,
|
||||
pub(super) model_client: ModelClient,
|
||||
pub(super) auth_context: codex_model_provider::ProviderAuthContext,
|
||||
@@ -46,6 +50,7 @@ pub(super) struct ExistingCallAttachment {
|
||||
pub(super) async fn attach(attachment: ExistingCallAttachment) -> CodexResult<JoinHandle<()>> {
|
||||
let ExistingCallAttachment {
|
||||
attachment_cancellation,
|
||||
existing_call_auth,
|
||||
client,
|
||||
model_client,
|
||||
auth_context,
|
||||
@@ -63,15 +68,36 @@ pub(super) async fn attach(attachment: ExistingCallAttachment) -> CodexResult<Jo
|
||||
transcript_tail_flush,
|
||||
stop_token,
|
||||
} = attachment;
|
||||
let (auth, sideband_headers, factory) = model_client
|
||||
.realtime_sideband_auth(
|
||||
extra_headers,
|
||||
&sideband_base_url,
|
||||
&auth_context,
|
||||
http_client_factory,
|
||||
)
|
||||
.or_cancel(&attachment_cancellation)
|
||||
.await??;
|
||||
let (auth, sideband_headers, factory) = match existing_call_auth {
|
||||
RealtimeExistingCallAuth::ModelProvider => {
|
||||
model_client
|
||||
.realtime_sideband_auth(
|
||||
extra_headers,
|
||||
&sideband_base_url,
|
||||
&auth_context,
|
||||
http_client_factory,
|
||||
)
|
||||
.or_cancel(&attachment_cancellation)
|
||||
.await??
|
||||
}
|
||||
RealtimeExistingCallAuth::ExternalHeaders => {
|
||||
let Some(auth @ CodexAuth::Headers(_)) = auth_context
|
||||
.credentials
|
||||
.auth()
|
||||
.or_cancel(&attachment_cancellation)
|
||||
.await?
|
||||
else {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"external header authentication requires header-based authentication".into(),
|
||||
));
|
||||
};
|
||||
(
|
||||
codex_model_provider::auth_provider_from_auth(&auth),
|
||||
extra_headers,
|
||||
http_client_factory,
|
||||
)
|
||||
}
|
||||
};
|
||||
let client = client.with_http_client_factory(factory).with_auth(auth);
|
||||
let transcript_state = RealtimeTranscriptState::default();
|
||||
let connection = client
|
||||
|
||||
@@ -16,7 +16,7 @@ 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 chatgpt.com Realtime WebSocket upgrades.
|
||||
/// An optional Realtime target receives public and synthetic private observer upgrades.
|
||||
pub async fn run_harness_through_proxy(
|
||||
server: &MockServer,
|
||||
test_name: &str,
|
||||
@@ -31,6 +31,24 @@ pub async fn run_harness_through_proxy_with_env(
|
||||
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<()> {
|
||||
// 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.
|
||||
@@ -44,6 +62,7 @@ pub async fn run_harness_through_proxy_with_env(
|
||||
"chatgpt-staging.com".into(),
|
||||
"us.chatgpt-staging.com".into(),
|
||||
"auth.api.openai.org".into(),
|
||||
"observer.internal.api.openai.org".into(),
|
||||
])?;
|
||||
let ca_dir = tempfile::tempdir()?;
|
||||
let ca_path = ca_dir.path().join("ca.pem");
|
||||
@@ -56,7 +75,9 @@ pub async fn run_harness_through_proxy_with_env(
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let proxy_url = format!("http://{}", proxy.local_addr()?);
|
||||
let target = *server.address();
|
||||
let proxy_task = tokio::spawn(async move {
|
||||
// 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?;
|
||||
@@ -79,6 +100,7 @@ pub async fn run_harness_through_proxy_with_env(
|
||||
| "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"
|
||||
)
|
||||
),
|
||||
"unexpected proxy destination"
|
||||
@@ -86,7 +108,8 @@ pub async fn run_harness_through_proxy_with_env(
|
||||
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 ");
|
||||
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;
|
||||
@@ -142,9 +165,7 @@ pub async fn run_harness_through_proxy_with_env(
|
||||
None => command.env_remove(key),
|
||||
};
|
||||
}
|
||||
let output = tokio::time::timeout(Duration::from_secs(90), command.output()).await;
|
||||
proxy_task.abort();
|
||||
let output = output??;
|
||||
let output = tokio::time::timeout(Duration::from_secs(90), command.output()).await??;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"harness subprocess failed\n{}\n{}",
|
||||
@@ -152,5 +173,7 @@ pub async fn run_harness_through_proxy_with_env(
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
let result = observer_completion.await;
|
||||
proxy_tasks.shutdown().await;
|
||||
result
|
||||
}
|
||||
|
||||
@@ -443,6 +443,7 @@ async fn cancelled_attachments_release_the_queue_and_preserve_the_next_call() ->
|
||||
options: RealtimeAttachmentOptions {
|
||||
cancel: Some(cancellation),
|
||||
start_before: None,
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
@@ -459,6 +460,7 @@ async fn cancelled_attachments_release_the_queue_and_preserve_the_next_call() ->
|
||||
options: RealtimeAttachmentOptions {
|
||||
cancel: Some(cancellation),
|
||||
start_before: None,
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
@@ -471,6 +473,7 @@ async fn cancelled_attachments_release_the_queue_and_preserve_the_next_call() ->
|
||||
options: RealtimeAttachmentOptions {
|
||||
cancel: Some(cancellation),
|
||||
start_before: Some(SystemTime::now() - Duration::from_secs(1)),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
@@ -483,6 +486,7 @@ async fn cancelled_attachments_release_the_queue_and_preserve_the_next_call() ->
|
||||
options: RealtimeAttachmentOptions {
|
||||
cancel: Some(cancellation),
|
||||
start_before: None,
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
@@ -561,6 +565,7 @@ async fn attachment_deadline_releases_a_pending_handshake() -> Result<()> {
|
||||
options: RealtimeAttachmentOptions {
|
||||
cancel: None,
|
||||
start_before: Some(SystemTime::now() + Duration::from_secs(60)),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -1,28 +1,387 @@
|
||||
//! Verifies that existing-call sidebands honor trusted per-call endpoint overrides,
|
||||
//! fall back to the configured endpoint, and preserve runtime authentication without
|
||||
//! adding bearer credentials.
|
||||
//! fall back to the configured endpoint, and keep host header authentication separate
|
||||
//! from public runtime authentication.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_features::Feature;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::protocol::CodexResponseHandoffMode;
|
||||
use codex_protocol::protocol::ConversationStartParams;
|
||||
use codex_protocol::protocol::ConversationStartTransport;
|
||||
use codex_protocol::protocol::ConversationTextParams;
|
||||
use codex_protocol::protocol::ConversationTextRole;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::RealtimeAttachmentOptions;
|
||||
use codex_protocol::protocol::RealtimeConversationVersion;
|
||||
use codex_protocol::protocol::RealtimeEvent;
|
||||
use codex_protocol::protocol::RealtimeExistingCallAuth;
|
||||
use codex_protocol::protocol::RealtimeOutputModality;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::responses::start_websocket_server;
|
||||
use core_test_support::runtime_auth::PROBE_SERVER;
|
||||
use core_test_support::runtime_auth::run_harness_through_proxy_until;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use core_test_support::wait_for_event;
|
||||
use core_test_support::wait_for_event_match;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderName;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
use test_case::test_case;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::timeout;
|
||||
use tokio_tungstenite::accept_hdr_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::Request;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::Response;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use wiremock::Mock;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const OBSERVER_URL: &str = "https://observer.internal.api.openai.org/v1";
|
||||
|
||||
fn observer_params(sideband_base_url: Option<String>) -> ConversationStartParams {
|
||||
ConversationStartParams {
|
||||
client_managed_handoffs: false,
|
||||
delegation_ack_filler: None,
|
||||
flush_transcript_tail_on_session_end: false,
|
||||
codex_responses_as_items: false,
|
||||
codex_response_item_prefix: None,
|
||||
codex_response_handoff_mode: CodexResponseHandoffMode::Thinking,
|
||||
backend_reasoning_status: false,
|
||||
codex_response_handoff_channel_prefixes: None,
|
||||
model: None,
|
||||
output_modality: RealtimeOutputModality::Audio,
|
||||
include_startup_context: false,
|
||||
initial_items: Vec::new(),
|
||||
realtime_start_instructions: None,
|
||||
realtime_end_instructions: None,
|
||||
prompt: None,
|
||||
realtime_session_id: Some("observer-session".into()),
|
||||
voice_session_id: None,
|
||||
transport: Some(ConversationStartTransport::ExistingCall {
|
||||
call_id: "rtc_existing".into(),
|
||||
sideband_base_url,
|
||||
}),
|
||||
version: Some(RealtimeConversationVersion::V3),
|
||||
voice: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn observer_auth() -> CodexAuth {
|
||||
CodexAuth::Headers(AuthHeaders::new(HeaderMap::from_iter([(
|
||||
HeaderName::from_static("x-openai-actor-authorization"),
|
||||
HeaderValue::from_static("Bearer synthetic-owner-biscuit"),
|
||||
)])))
|
||||
}
|
||||
|
||||
/// Private observers and public Realtime retain distinct auth through events, reconnect, and stop.
|
||||
#[test_case(true; "private observer")]
|
||||
#[test_case(false; "public realtime")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn existing_call_runtime_auth_reconnects_and_stops(external_headers: bool) -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
let server = start_mock_server().await;
|
||||
if std::env::var(PROBE_SERVER).is_ok() {
|
||||
let test = test_codex()
|
||||
.with_auth(if external_headers {
|
||||
observer_auth()
|
||||
} else {
|
||||
CodexAuth::from_api_key("public-key")
|
||||
})
|
||||
.with_config(move |config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::RuntimeAgentInstances)
|
||||
.expect("enable runtime authentication");
|
||||
config.runtime_auth_mode = RuntimeAuthMode::DualHeader;
|
||||
if external_headers {
|
||||
config.model_provider.experimental_bearer_token =
|
||||
Some("inference-only-key".into());
|
||||
config.model_provider.http_headers = Some(
|
||||
[
|
||||
("authorization".into(), "Bearer configured-model-key".into()),
|
||||
(
|
||||
"x-openai-agent-assertion".into(),
|
||||
"configured-model-assertion".into(),
|
||||
),
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
let (reply, result) = oneshot::channel();
|
||||
test.codex
|
||||
.submit(Op::RealtimeConversationAttach {
|
||||
params: observer_params(Some(if external_headers {
|
||||
OBSERVER_URL.into()
|
||||
} else {
|
||||
"https://chatgpt.com/v1".into()
|
||||
})),
|
||||
options: RealtimeAttachmentOptions {
|
||||
existing_call_auth: if external_headers {
|
||||
RealtimeExistingCallAuth::ExternalHeaders
|
||||
} else {
|
||||
RealtimeExistingCallAuth::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
reply,
|
||||
})
|
||||
.await?;
|
||||
timeout(Duration::from_secs(10), result).await???;
|
||||
for text in ["first connection", "reconnected"] {
|
||||
wait_for_event_match(&test.codex, |event| match event {
|
||||
EventMsg::RealtimeConversationRealtime(event) => match &event.payload {
|
||||
RealtimeEvent::OutputTranscriptDelta(delta) if delta.delta == text => {
|
||||
Some(Ok(()))
|
||||
}
|
||||
RealtimeEvent::Error(message) => Some(Err(anyhow::anyhow!("{message}"))),
|
||||
_ => None,
|
||||
},
|
||||
EventMsg::RealtimeConversationClosed(event) => {
|
||||
Some(Err(anyhow::anyhow!("unexpected close: {event:?}")))
|
||||
}
|
||||
EventMsg::Error(error) => Some(Err(anyhow::anyhow!("{error:?}"))),
|
||||
_ => None,
|
||||
})
|
||||
.await?;
|
||||
test.codex
|
||||
.submit(Op::RealtimeConversationText(ConversationTextParams {
|
||||
text: text.into(),
|
||||
role: ConversationTextRole::User,
|
||||
}))
|
||||
.await?;
|
||||
}
|
||||
wait_for_event(&test.codex, |event| matches!(event,
|
||||
EventMsg::RealtimeConversationRealtime(event)
|
||||
if matches!(&event.payload, RealtimeEvent::OutputTranscriptDelta(delta) if delta.delta == "stop ready")
|
||||
)).await;
|
||||
let (reply, result) = oneshot::channel();
|
||||
test.codex
|
||||
.submit(Op::RealtimeConversationDetach {
|
||||
realtime_session_id: "observer-session".into(),
|
||||
reply,
|
||||
})
|
||||
.await?;
|
||||
timeout(Duration::from_secs(10), result).await???;
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !external_headers {
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/agent/register"))
|
||||
.respond_with(|request: &wiremock::Request| {
|
||||
let body: serde_json::Value = request.body_json().expect("parse registration body");
|
||||
assert_eq!(body["actor_auth"]["credential"], "public-key");
|
||||
ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": request.headers["idempotency-key"].to_str().expect("registration idempotency key is text"),
|
||||
"agent_host_id": "host-a",
|
||||
"actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null},
|
||||
}))
|
||||
})
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let observer = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
for (index, text) in ["first connection", "reconnected"].into_iter().enumerate() {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let mut websocket =
|
||||
accept_hdr_async(stream, |request: &Request, response: Response| {
|
||||
assert_eq!(request.uri().to_string(), "/v1/live/rtc_existing");
|
||||
if external_headers {
|
||||
assert_eq!(
|
||||
request.headers().get("x-openai-actor-authorization"),
|
||||
Some(&HeaderValue::from_static("Bearer synthetic-owner-biscuit"))
|
||||
);
|
||||
assert_eq!(request.headers().get("authorization"), None);
|
||||
assert_eq!(request.headers().get("x-openai-agent-assertion"), None);
|
||||
} else {
|
||||
assert_eq!(request.headers().get("x-openai-actor-authorization"), None);
|
||||
assert_eq!(request.headers()["authorization"], "Bearer public-key");
|
||||
assert!(request.headers().contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
Ok(response)
|
||||
})
|
||||
.await?;
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"type": "output_transcript.added", "item": { "text": text }
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
loop {
|
||||
let message = websocket
|
||||
.next()
|
||||
.await
|
||||
.context("observer disconnected before text")??;
|
||||
if message.is_text() && message.to_text()?.contains(text) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if index == 1 {
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"type": "output_transcript.added", "item": { "text": "stop ready" }
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
assert!(matches!(
|
||||
websocket.next().await,
|
||||
Some(Ok(Message::Close(_)))
|
||||
));
|
||||
}
|
||||
// Dropping the first socket without a close frame exercises Core's reconnect path.
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}));
|
||||
let case = if external_headers {
|
||||
"private_observer"
|
||||
} else {
|
||||
"public_realtime"
|
||||
};
|
||||
run_harness_through_proxy_until(
|
||||
&server,
|
||||
&format!("suite::realtime_sideband_endpoint::existing_call_runtime_auth_reconnects_and_stops::{case}"),
|
||||
Some(address),
|
||||
&[],
|
||||
async move {
|
||||
timeout(Duration::from_secs(10), observer)
|
||||
.await
|
||||
.context("observer did not receive the WebSocket close frame")???;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("request recording is enabled")
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/agent/register")
|
||||
.count(),
|
||||
usize::from(!external_headers),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum RejectedObserver {
|
||||
ModelProvider,
|
||||
ApiKey,
|
||||
MissingUrl,
|
||||
NetworkPolicy,
|
||||
}
|
||||
|
||||
/// External header admission cannot be inferred from a URL or bypass auth-kind and network policy checks.
|
||||
#[test_case(RejectedObserver::ModelProvider; "untrusted destination")]
|
||||
#[test_case(RejectedObserver::ApiKey; "wrong authentication kind")]
|
||||
#[test_case(RejectedObserver::MissingUrl; "missing explicit route")]
|
||||
#[test_case(RejectedObserver::NetworkPolicy; "destination policy denial")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn observer_authentication_fails_closed(case: RejectedObserver) -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
let server = start_mock_server().await;
|
||||
let observer = start_websocket_server(vec![vec![]]).await;
|
||||
let controller = codex_http_client::NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
controller.publish(
|
||||
policy.revision(),
|
||||
codex_http_client::DestinationPolicy::Unrestricted,
|
||||
);
|
||||
let auth = match case {
|
||||
RejectedObserver::ApiKey => CodexAuth::from_api_key("not-host-headers"),
|
||||
_ => observer_auth(),
|
||||
};
|
||||
let test = test_codex()
|
||||
.with_auth(auth)
|
||||
.with_config(move |config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::RuntimeAgentInstances)
|
||||
.expect("enable runtime authentication");
|
||||
config.runtime_auth_mode = RuntimeAuthMode::DualHeader;
|
||||
if matches!(case, RejectedObserver::NetworkPolicy) {
|
||||
config.application_network_policy = policy;
|
||||
}
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
if matches!(case, RejectedObserver::NetworkPolicy) {
|
||||
controller.publish(
|
||||
controller.policy().revision(),
|
||||
codex_http_client::DestinationPolicy::Restricted {
|
||||
allowed_hosts: Default::default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let (url, auth, expected) = match case {
|
||||
RejectedObserver::ModelProvider => (
|
||||
Some(OBSERVER_URL.into()),
|
||||
RealtimeExistingCallAuth::ModelProvider,
|
||||
"runtime auth does not support this OpenAI endpoint",
|
||||
),
|
||||
RejectedObserver::ApiKey => (
|
||||
Some(observer.uri().into()),
|
||||
RealtimeExistingCallAuth::ExternalHeaders,
|
||||
"external header authentication requires header-based authentication",
|
||||
),
|
||||
RejectedObserver::MissingUrl => (
|
||||
None,
|
||||
RealtimeExistingCallAuth::ExternalHeaders,
|
||||
"external header authentication requires an existing call with an explicit sideband URL",
|
||||
),
|
||||
RejectedObserver::NetworkPolicy => (
|
||||
Some(observer.uri().into()),
|
||||
RealtimeExistingCallAuth::ExternalHeaders,
|
||||
"policy",
|
||||
),
|
||||
};
|
||||
let (reply, result) = oneshot::channel();
|
||||
test.codex
|
||||
.submit(Op::RealtimeConversationAttach {
|
||||
params: observer_params(url),
|
||||
options: RealtimeAttachmentOptions {
|
||||
existing_call_auth: auth,
|
||||
..Default::default()
|
||||
},
|
||||
reply,
|
||||
})
|
||||
.await?;
|
||||
let error = timeout(Duration::from_secs(10), result)
|
||||
.await??
|
||||
.expect_err("invalid observer authentication must fail")
|
||||
.to_string();
|
||||
assert!(error.contains(expected), "{error}");
|
||||
assert!(observer.handshakes().is_empty());
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
observer.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum EndpointSelection {
|
||||
|
||||
@@ -226,7 +226,19 @@ pub struct ConversationStartParams {
|
||||
pub voice: Option<Option<RealtimeVoice>>,
|
||||
}
|
||||
|
||||
/// Controls when an in-process realtime attachment may establish a connection.
|
||||
/// Authentication selected by the embedding host for an existing call.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum RealtimeExistingCallAuth {
|
||||
/// Use the model provider's authentication and runtime destination checks.
|
||||
#[default]
|
||||
ModelProvider,
|
||||
/// Use the selected auth manager's external headers and the host's transport.
|
||||
/// The trusted host must authorize the destination, call owner, and calling
|
||||
/// workload before selecting this mode. Never derive it from a client URL.
|
||||
ExternalHeaders,
|
||||
}
|
||||
|
||||
/// Controls connection admission and authentication for an in-process attachment.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct RealtimeAttachmentOptions {
|
||||
/// Set the watch to `true` to cancel a pending connection.
|
||||
@@ -234,6 +246,8 @@ pub struct RealtimeAttachmentOptions {
|
||||
pub cancel: Option<watch::Receiver<bool>>,
|
||||
/// Optional caller deadline for publishing the connection. Cleanup can finish later.
|
||||
pub start_before: Option<SystemTime>,
|
||||
/// Applies only to existing calls; external headers require an explicit host-selected URL.
|
||||
pub existing_call_auth: RealtimeExistingCallAuth,
|
||||
}
|
||||
|
||||
/// A caller-owned realtime sideband. Dropping either direction seals input and ends
|
||||
|
||||
Reference in New Issue
Block a user