aKode fase 2a: rimossi cloud tasks, chatgpt apply, responses-api-proxy, codex app, remote control, guardian decisions; realtime senza fallback OpenAI; doctor senza sonde OpenAI

This commit is contained in:
Andrea
2026-11-09 13:15:08 +01:00
parent 39a103d16f
commit 137106bf17
172 changed files with 485 additions and 42398 deletions

View File

@@ -72,7 +72,6 @@ codex-user-verification = { workspace = true }
codex-utils-pty = { workspace = true }
codex-backend-client = { workspace = true }
codex-file-search = { workspace = true }
codex-chatgpt = { workspace = true }
codex-login = { workspace = true }
codex-runtime-agent-instance = { workspace = true }
codex-image-generation-extension = { workspace = true }

View File

@@ -0,0 +1,243 @@
use codex_core::config::Config;
use codex_features::Feature;
use codex_features::RuntimeAuthMode;
use codex_http_client::HttpClient;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::default_client::RESIDENCY_HEADER_NAME;
use codex_login::default_client::create_client_with_chatgpt_cookies;
use codex_login::default_client::default_headers;
use codex_runtime_agent_instance::RuntimeAuthManager;
use std::sync::Arc;
use anyhow::Context;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::time::Duration;
const OAI_PRODUCT_SKU_HEADER: &str = "OAI-Product-Sku";
const CODEX_PRODUCT_SKU: &str = "codex";
struct CachedChatGptClient {
factory: HttpClientFactory,
residency: Option<Vec<u8>>,
client: HttpClient,
}
static CHATGPT_CLIENT: LazyLock<Mutex<Option<CachedChatGptClient>>> =
LazyLock::new(|| Mutex::new(None));
/// Reuse the client and cookies without changing the caller's captured account policy.
fn chatgpt_client(factory: HttpClientFactory) -> HttpClient {
let residency = default_headers()
.get(RESIDENCY_HEADER_NAME)
.map(|value| value.as_bytes().to_vec());
let mut cached = CHATGPT_CLIENT
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(cached_client) = cached.as_ref()
&& cached_client.factory == factory
&& cached_client.residency == residency
{
return cached_client.client.clone();
}
let client = create_client_with_chatgpt_cookies(&factory);
*cached = Some(CachedChatGptClient {
factory,
residency,
client: client.clone(),
});
client
}
/// Make a GET request to the ChatGPT backend API.
#[cfg(test)]
pub(crate) async fn chatgpt_get_request<T: DeserializeOwned>(
config: &Config,
path: String,
) -> anyhow::Result<T> {
let mut config = config.clone();
let (auth, runtime) = standalone_auth(&mut config).await?;
chatgpt_get_request_with_timeout(
&config,
&auth,
runtime.as_ref(),
path,
/*timeout*/ None,
)
.await
}
pub(crate) async fn standalone_auth(
config: &mut Config,
) -> anyhow::Result<(
CodexAuth,
Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
)> {
// Standalone commands create one owner. Freeze the caller's account policy before loading
// credentials; this temporary manager does not own later account changes.
config.application_network_policy = config
.application_network_policy
.clone()
.for_current_account();
if config.features.enabled(Feature::RuntimeAgentInstances) {
codex_model_provider::validate_runtime_destination(Some(&config.chatgpt_base_url))?;
}
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?;
let runtime = if config.features.enabled(Feature::RuntimeAgentInstances)
&& codex_runtime_agent_instance::is_openai_api_url(&config.chatgpt_base_url)
{
let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?;
codex_core::build_runtime_auth_manager(config, auth_manager.clone(), &installation_id)
.map(|runtime| (runtime, config.runtime_auth_mode))
} else {
None
};
let auth = auth_manager
.auth()
.await
.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?;
Ok((auth, runtime))
}
pub(crate) async fn chatgpt_get_request_with_timeout<T: DeserializeOwned>(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
path: String,
timeout: Option<Duration>,
) -> anyhow::Result<T> {
let chatgpt_base_url = &config.chatgpt_base_url;
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run `codex login`"
);
let url = format!(
"{}/{}",
chatgpt_base_url.trim_end_matches('/'),
path.trim_start_matches('/')
);
let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?;
let mut request = client
.get(&url)
.headers(default_headers())
.headers(
request_auth
.auth
.apply_auth_headers(Default::default())
.await?,
)
.header(OAI_PRODUCT_SKU_HEADER, CODEX_PRODUCT_SKU)
.header("Content-Type", "application/json");
if let Some(timeout) = timeout {
request = request.timeout(timeout);
}
let response = request.send().await.context("Failed to send request")?;
if response.status().is_success() {
let result: T = response
.json()
.await
.context("Failed to parse JSON response")?;
Ok(result)
} else {
let status = response.status();
let body = response.text().await.unwrap_or_default();
anyhow::bail!("Request failed with status {status}: {body}")
}
}
/// Make a POST request to the ChatGPT backend API with an already-captured auth identity.
///
/// Callers must capture `auth` and `config.application_network_policy` together and preserve
/// that snapshot rather than reacquiring either while the request is in flight.
pub(crate) async fn chatgpt_post_request_with_timeout<
TResponse: DeserializeOwned,
TRequest: Serialize + ?Sized,
>(
config: &Config,
auth: &CodexAuth,
path: String,
body: &TRequest,
timeout: Duration,
product_sku: &str,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
) -> anyhow::Result<TResponse> {
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run codex login"
);
let url = format!(
"{}/{}",
config.chatgpt_base_url.trim_end_matches('/'),
path.trim_start_matches('/')
);
let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?;
let response = client
.post(&url)
.headers(default_headers())
.headers(
request_auth
.auth
.apply_auth_headers(Default::default())
.await?,
)
.header(OAI_PRODUCT_SKU_HEADER, product_sku)
.header("Content-Type", "application/json")
.timeout(timeout)
.json(body)
.send()
.await
.context("Failed to send request")?;
if response.status().is_success() {
response
.json()
.await
.context("Failed to parse JSON response")
} else {
let status = response.status();
let body = response.text().await.unwrap_or_default();
anyhow::bail!("Request failed with status {status}: {body}")
}
}
/// Keep request credentials and the transport bound to the same account snapshot.
async fn prepare_client_auth(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
url: &str,
) -> anyhow::Result<(HttpClient, codex_model_provider::ResolvedProviderAuth)> {
if runtime.is_some() {
codex_model_provider::validate_runtime_destination(Some(url))?;
}
let resolved = codex_model_provider::auth_provider_for_request(
auth,
runtime,
/*headers*/ &Default::default(),
)
.await?;
let factory = resolved.bind_http_client_factory(config.http_client_factory())?;
let client = chatgpt_client(factory);
Ok((client, resolved))
}
#[cfg(test)]
#[path = "chatgpt_client_runtime_auth_tests.rs"]
mod runtime_auth_tests;

View File

@@ -0,0 +1,321 @@
//! Test captured ChatGPT credentials and runtime proofs on helper requests.
use super::*;
use base64::Engine;
use codex_features::RuntimeAuthMode;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::HashSet;
use std::sync::Arc;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::path;
#[tokio::test]
async fn helpers_use_captured_auth_and_strip_cross_origin_proofs() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let redirected = MockServer::start().await;
Mock::given(path("/"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(1)
.mount(&redirected)
.await;
Mock::given(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-chatgpt", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/data"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(2)
.mount(&server)
.await;
Mock::given(path("/redirect"))
.respond_with(ResponseTemplate::new(307).insert_header("location", redirected.uri()))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/ps/apps/batch"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"apps": [{"id": "calendar", "name": "Calendar", "description": "Calendar metadata"}],
})))
.expect(1).mount(&server).await;
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = server.uri();
let token = actor_token();
let auth = CodexAuth::from_external_chatgpt_tokens(
&token,
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let runtime = (
Arc::new(RuntimeAuthManager::new(
AuthManager::from_auth_for_testing(auth.clone()),
AgentHostAuthorization::InstallationId {
installation_id: uuid::Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/agent/register", server.uri()).parse().unwrap(),
)),
mode,
);
// No saved auth exists: these helpers must use the supplied snapshot, not reload auth.
let get: serde_json::Value = chatgpt_get_request_with_timeout(
&config,
&auth,
Some(&runtime),
"data".into(),
/*timeout*/ None,
)
.await
.unwrap();
let post: serde_json::Value = chatgpt_post_request_with_timeout(
&config,
&auth,
"data".into(),
&json!({}),
Duration::from_secs(10),
"codex",
Some(&runtime),
)
.await
.unwrap();
let metadata = crate::chatgpt_connectors::read_connector_metadata(
&config,
&auth,
Some(&runtime),
&["calendar".into()],
/*include_tools*/ false,
)
.await
.unwrap();
assert_eq!(metadata.apps.len(), 1);
assert_eq!(metadata.apps[0].name, "Calendar");
assert!(metadata.missing_app_ids.is_empty());
assert_eq!(get, json!({"ok": true}));
assert_eq!(post, get);
let redirected_result = chatgpt_get_request_with_timeout::<serde_json::Value>(
&config,
&auth,
Some(&runtime),
"redirect".into(),
/*timeout*/ None,
)
.await
.unwrap();
assert_eq!(redirected_result, get);
let forwarded = redirected.received_requests().await.unwrap();
assert_eq!(forwarded.len(), 1);
assert!(!forwarded[0].headers.contains_key("authorization"));
assert!(
!forwarded[0]
.headers
.contains_key("x-openai-agent-assertion")
);
redirected.verify().await;
let requests = server.received_requests().await.unwrap();
let metadata_request = requests
.iter()
.find(|request| request.url.path() == "/ps/apps/batch")
.unwrap();
assert_eq!(
metadata_request.headers["authorization"],
format!("Bearer {token}")
);
assert!(
!metadata_request
.headers
.contains_key("x-openai-agent-assertion")
);
let proofs: HashSet<_> = requests
.iter()
.filter(|r| !matches!(r.url.path(), "/agent/register" | "/ps/apps/batch"))
.map(|r| {
assert_eq!(r.headers["chatgpt-account-id"], "workspace-a");
let authorization = r.headers["authorization"].to_str().unwrap();
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(authorization, format!("Bearer {token}"));
r.headers["x-openai-agent-assertion"].to_str().unwrap()
}
RuntimeAuthMode::AssertionOnly => {
assert!(!r.headers.contains_key("x-openai-agent-assertion"));
authorization.strip_prefix("AgentAssertion ").unwrap()
}
}
})
.collect();
assert_eq!(proofs.len(), 3);
server.verify().await;
}
}
fn actor_token() -> String {
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json!({
"iss": "https://auth.openai.com/", "session_id": "login-a",
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"},
}).to_string());
format!("header.{claims}.signature")
}
#[tokio::test]
async fn standalone_apply_keeps_custom_backend_auth_when_runtime_feature_is_enabled() {
let server = MockServer::start().await;
let token = actor_token();
Mock::given(path("/task"))
.and(wiremock::matchers::header(
"authorization",
format!("Bearer {token}"),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(1)
.mount(&server)
.await;
let home = tempfile::TempDir::new().unwrap();
codex_login::auth::login_with_chatgpt_auth_tokens(
home.path(),
&token,
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = server.uri();
config
.features
.enable(Feature::RuntimeAgentInstances)
.unwrap();
let response: serde_json::Value = chatgpt_get_request(&config, "task".into()).await.unwrap();
assert_eq!(response, json!({"ok": true}));
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 1);
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
server.verify().await;
}
#[tokio::test]
async fn connector_requests_reject_unsupported_openai_destinations() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
for base_url in [
"http://chatgpt.com",
"https://future.openai.com/backend-api",
] {
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = base_url.to_string();
config.features.enable(Feature::Apps).unwrap();
let auth = CodexAuth::from_external_chatgpt_tokens(
&actor_token(),
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let runtime = (
Arc::new(RuntimeAuthManager::for_chatgpt(
AuthManager::from_auth_for_testing(auth.clone()),
uuid::Uuid::nil().to_string(),
base_url.to_string(),
RuntimeRegistrationMetadata {
harness: Some("codex".to_string()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
)),
mode,
);
// Keep a broken validation path from sending the test credential to the network.
let controller = codex_http_client::NetworkPolicyController::default();
config.application_network_policy = controller.policy();
assert!(controller.publish(
config.application_network_policy.revision(),
codex_http_client::DestinationPolicy::Restricted {
allowed_hosts: Default::default(),
},
));
let directory_error = crate::chatgpt_connectors::list_all_connectors_with_options(
&config,
Some(&auth),
Some(&runtime),
/*force_refetch*/ true,
&[],
)
.await
.expect_err("reject unsupported directory destination");
let metadata_error = crate::chatgpt_connectors::read_connector_metadata(
&config,
&auth,
Some(&runtime),
&["calendar".to_string()],
/*include_tools*/ false,
)
.await
.err()
.expect("reject unsupported metadata destination");
for error in [directory_error, metadata_error] {
assert!(
matches!(
error
.downcast_ref::<codex_protocol::error::CodexErr>()
.map(codex_protocol::error::CodexErr::details),
Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_))
),
"{base_url} ({mode:?}): {error:#}",
);
}
}
}
}
#[tokio::test]
async fn standalone_apply_rejects_unsupported_openai_destination() {
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = "https://future.openai.com/backend-api".into();
config
.features
.enable(Feature::RuntimeAgentInstances)
.unwrap();
let error = chatgpt_get_request::<serde_json::Value>(&config, "task".into())
.await
.unwrap_err();
assert!(matches!(
error
.downcast_ref::<codex_protocol::error::CodexErr>()
.map(codex_protocol::error::CodexErr::details),
Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_))
));
}

View File

@@ -0,0 +1,525 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::time::Duration;
mod chatgpt_client;
use self::chatgpt_client::chatgpt_get_request_with_timeout;
use self::chatgpt_client::chatgpt_post_request_with_timeout;
use codex_connectors::AppInfo;
use codex_connectors::AppToolPolicyEvaluator;
use codex_connectors::ConnectorDirectoryCacheContext;
use codex_connectors::ConnectorDirectoryCacheKey;
use codex_connectors::ConnectorMetadata;
use codex_connectors::ConnectorMetadataStore;
use codex_connectors::ConnectorToolSummary;
use codex_connectors::DirectoryListResponse;
use codex_connectors::merge::merge_connectors;
use codex_connectors::merge::merge_plugin_connectors;
use codex_core::config::Config;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status;
pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools;
use codex_features::RuntimeAuthMode;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_plugin::AppConnectorId;
use codex_runtime_agent_instance::RuntimeAuthManager;
use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;
const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60);
const CONNECTOR_METADATA_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_APPS_PRODUCT_SKU: &str = "codex";
async fn apps_enabled(config: &Config) -> anyhow::Result<bool> {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?;
let auth = auth_manager.auth().await;
Ok(config
.features
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)))
}
pub async fn list_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
if !apps_enabled(config).await? {
return Ok(Vec::new());
}
let (connectors_result, accessible_result) = tokio::join!(
list_all_connectors(config),
list_accessible_connectors_from_mcp_tools(config),
);
let connectors = connectors_result?;
let accessible = accessible_result?;
Ok(
AppToolPolicyEvaluator::new(&config.config_layer_stack).apply_app_enabled_state(
merge_connectors_with_accessible(
connectors, accessible, /*all_connectors_loaded*/ true,
),
),
)
}
pub async fn list_all_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
if !apps_enabled(config).await? {
return Ok(Vec::new());
}
let mut config = config.clone();
let (auth, runtime) = self::chatgpt_client::standalone_auth(&mut config).await?;
list_all_connectors_with_options(
&config,
Some(&auth),
runtime.as_ref(),
/*force_refetch*/ false,
&[],
)
.await
}
pub fn list_cached_all_connectors(
config: &Config,
auth: Option<&CodexAuth>,
plugin_apps: &[AppConnectorId],
) -> Option<Vec<AppInfo>> {
if !config
.features
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend))
{
return Some(Vec::new());
}
let auth = auth?;
let cache_context = connector_directory_cache_context(config, auth);
let connectors = codex_connectors::cached_directory_connectors(&cache_context)?;
Some(merge_directory_and_plugin_connectors(
connectors.to_vec(),
plugin_apps,
))
}
pub async fn list_all_connectors_with_options(
config: &Config,
auth: Option<&CodexAuth>,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
force_refetch: bool,
plugin_apps: &[AppConnectorId],
) -> anyhow::Result<Vec<AppInfo>> {
if !config
.features
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend))
{
return Ok(Vec::new());
}
let auth = auth.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?;
let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?;
let cache_context = connector_directory_cache_context(config, auth);
let connectors = codex_connectors::list_all_connectors_with_options(
cache_context,
auth.is_workspace_account(),
force_refetch,
|path| async move {
chatgpt_get_request_with_timeout::<DirectoryListResponse>(
config,
auth,
runtime,
path,
Some(DIRECTORY_CONNECTORS_TIMEOUT),
)
.await
},
)
.await?;
Ok(merge_directory_and_plugin_connectors(
connectors,
plugin_apps,
))
}
pub struct ConnectorMetadataReadResult {
pub apps: Vec<ConnectorMetadata>,
pub missing_app_ids: Vec<String>,
}
/// Reads display metadata without loading MCP connector tools or runtime state.
///
/// The store is created before awaiting the backend request, so a response that arrives after an
/// account or backend change can only commit to the scope under which it was requested.
/// Capture `auth` and `config.application_network_policy` together using
/// `AuthManager::auth_with_http_client_factory` so the request retains that account's policy.
pub async fn read_connector_metadata(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
app_ids: &[String],
include_tools: bool,
) -> anyhow::Result<ConnectorMetadataReadResult> {
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run codex login"
);
let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?;
let store = ConnectorMetadataStore::new(
config.chatgpt_base_url.clone(),
auth.get_account_id(),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
);
let mut metadata_by_id = store.fresh_records(app_ids, include_tools);
let missing_ids = app_ids
.iter()
.filter(|app_id| !metadata_by_id.contains_key(app_id.as_str()))
.cloned()
.collect::<Vec<_>>();
if !missing_ids.is_empty() {
let product_sku = config
.apps_mcp_product_sku
.as_deref()
.unwrap_or(DEFAULT_APPS_PRODUCT_SKU);
let response: GetAppsResponse = chatgpt_post_request_with_timeout(
config,
auth,
"/ps/apps/batch".to_string(),
&GetAppsRequest {
app_ids: &missing_ids,
include_tools,
},
CONNECTOR_METADATA_TIMEOUT,
product_sku,
runtime,
)
.await?;
let mut requested_ids = missing_ids.iter().cloned().collect::<HashSet<_>>();
let fetched = response
.apps
.into_iter()
.map(batch_app_to_metadata)
.filter(|metadata| requested_ids.remove(&metadata.id))
.collect::<Vec<_>>();
store.commit(&fetched);
metadata_by_id.extend(
fetched
.into_iter()
.map(|metadata| (metadata.id.clone(), metadata)),
);
}
let mut apps = Vec::new();
let mut missing_app_ids = Vec::new();
for app_id in app_ids {
if let Some(mut metadata) = metadata_by_id.remove(app_id) {
if !include_tools {
metadata.tool_summaries = None;
}
apps.push(metadata);
} else {
missing_app_ids.push(app_id.clone());
}
}
Ok(ConnectorMetadataReadResult {
apps,
missing_app_ids,
})
}
#[derive(Serialize)]
struct GetAppsRequest<'a> {
app_ids: &'a [String],
include_tools: bool,
}
#[derive(Deserialize)]
struct GetAppsResponse {
apps: Vec<BatchApp>,
}
/// The explicit metadata-only projection of Plugin Service's public app response.
///
/// Serde ignores all other backend fields, including full actions, model descriptions, and
/// runtime state.
#[derive(Deserialize)]
struct BatchApp {
id: String,
name: String,
description: Option<String>,
icon_url: Option<String>,
#[serde(default, rename = "icon_dark_url", alias = "icon_url_dark")]
icon_url_dark: Option<String>,
#[serde(default)]
distribution_channel: Option<String>,
#[serde(default)]
tools: Option<Vec<BatchAppToolSummary>>,
}
#[derive(Deserialize)]
struct BatchAppToolSummary {
name: String,
title: Option<String>,
description: String,
#[serde(default)]
is_enabled: Option<bool>,
#[serde(default)]
disabled_reason: Option<String>,
#[serde(default)]
is_read_only: bool,
}
fn batch_app_to_metadata(app: BatchApp) -> ConnectorMetadata {
let BatchApp {
id,
name,
description,
icon_url,
icon_url_dark,
distribution_channel,
tools,
} = app;
ConnectorMetadata {
id,
name,
description,
icon_url,
icon_url_dark,
distribution_channel,
tool_summaries: tools.map(|tools| {
tools
.into_iter()
.map(|tool| {
let BatchAppToolSummary {
name,
title,
description,
is_enabled,
disabled_reason,
is_read_only,
} = tool;
ConnectorToolSummary {
name,
title,
description,
is_enabled: is_enabled.unwrap_or(true),
disabled_reason,
is_read_only,
}
})
.collect()
}),
}
}
fn connector_directory_cache_context(
config: &Config,
auth: &CodexAuth,
) -> ConnectorDirectoryCacheContext {
ConnectorDirectoryCacheContext::new(
config.codex_home.to_path_buf(),
ConnectorDirectoryCacheKey::new(
config.chatgpt_base_url.clone(),
auth.get_account_id(),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
),
)
}
fn merge_directory_and_plugin_connectors(
connectors: Vec<AppInfo>,
plugin_apps: &[AppConnectorId],
) -> Vec<AppInfo> {
merge_plugin_connectors(
connectors,
plugin_apps
.iter()
.map(|connector_id| connector_id.0.clone()),
)
}
pub fn connectors_for_plugin_apps(
connectors: Vec<AppInfo>,
plugin_apps: &[AppConnectorId],
) -> Vec<AppInfo> {
let connectors = merge_plugin_connectors(
connectors,
plugin_apps
.iter()
.map(|connector_id| connector_id.0.clone()),
);
let mut connectors_by_id = connectors
.into_iter()
.map(|connector| (connector.id.clone(), connector))
.collect::<HashMap<_, _>>();
plugin_apps
.iter()
.filter_map(|connector_id| connectors_by_id.remove(connector_id.0.as_str()))
.collect()
}
pub fn merge_connectors_with_accessible(
connectors: Vec<AppInfo>,
accessible_connectors: Vec<AppInfo>,
all_connectors_loaded: bool,
) -> Vec<AppInfo> {
let accessible_connectors = if all_connectors_loaded {
let connector_ids: HashSet<&str> = connectors
.iter()
.map(|connector| connector.id.as_str())
.collect();
accessible_connectors
.into_iter()
.filter(|connector| connector_ids.contains(connector.id.as_str()))
.collect()
} else {
accessible_connectors
};
merge_connectors(connectors, accessible_connectors)
}
#[cfg(test)]
mod tests {
use super::*;
use codex_connectors::metadata::connector_install_url;
use codex_plugin::AppConnectorId;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn batch_app_accepts_missing_optional_metadata() {
let app = serde_json::from_value::<BatchApp>(json!({
"id": "alpha",
"name": "Alpha",
"description": "Alpha description",
"icon_url": null,
"tools": [{
"name": "search",
"title": "Search",
"description": "Search Alpha",
}],
}))
.expect("valid legacy batch app");
assert_eq!(
batch_app_to_metadata(app),
ConnectorMetadata {
id: "alpha".to_string(),
name: "Alpha".to_string(),
description: Some("Alpha description".to_string()),
icon_url: None,
icon_url_dark: None,
distribution_channel: None,
tool_summaries: Some(vec![ConnectorToolSummary {
name: "search".to_string(),
title: Some("Search".to_string()),
description: "Search Alpha".to_string(),
is_enabled: true,
disabled_reason: None,
is_read_only: false,
}]),
}
);
}
fn app(id: &str) -> AppInfo {
AppInfo {
id: id.to_string(),
name: id.to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: None,
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
}
}
fn merged_app(id: &str, is_accessible: bool) -> AppInfo {
AppInfo {
id: id.to_string(),
name: id.to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: Some(connector_install_url(id, id)),
is_accessible,
is_enabled: true,
plugin_display_names: Vec::new(),
}
}
#[test]
fn excludes_accessible_connectors_not_in_all_when_all_loaded() {
let merged = merge_connectors_with_accessible(
vec![app("alpha")],
vec![app("alpha"), app("beta")],
/*all_connectors_loaded*/ true,
);
assert_eq!(merged, vec![merged_app("alpha", /*is_accessible*/ true)]);
}
#[test]
fn keeps_accessible_connectors_not_in_all_while_all_loading() {
let merged = merge_connectors_with_accessible(
vec![app("alpha")],
vec![app("alpha"), app("beta")],
/*all_connectors_loaded*/ false,
);
assert_eq!(
merged,
vec![
merged_app("alpha", /*is_accessible*/ true),
merged_app("beta", /*is_accessible*/ true)
]
);
}
#[test]
fn connectors_for_plugin_apps_returns_only_requested_plugin_apps() {
let connectors = connectors_for_plugin_apps(
vec![app("alpha"), app("beta")],
&[
AppConnectorId("gmail".to_string()),
AppConnectorId("alpha".to_string()),
AppConnectorId("gmail".to_string()),
],
);
assert_eq!(
connectors,
vec![merged_app("gmail", /*is_accessible*/ false), app("alpha")]
);
}
#[test]
fn connectors_for_plugin_apps_preserves_formerly_disallowed_plugin_apps() {
let connector_id = "asdk_app_6938a94a61d881918ef32cb999ff937c";
let connectors =
connectors_for_plugin_apps(Vec::new(), &[AppConnectorId(connector_id.to_string())]);
assert_eq!(
connectors,
vec![merged_app(connector_id, /*is_accessible*/ false)]
);
}
}

View File

@@ -104,7 +104,7 @@ pub(crate) fn thread_extensions(
git_attribution_base_url,
http_client_factory,
);
codex_guardian_v2::install(&mut builder, auth_manager.clone(), thread_manager);
codex_guardian_v2::install(&mut builder, thread_manager);
codex_memories_extension::install(&mut builder, codex_otel::global());
codex_mcp_extension::install(&mut builder);
codex_mcp_extension::install_plugins(&mut builder, environment_manager);

View File

@@ -104,6 +104,8 @@ mod app_server_tracing;
mod attestation;
mod auth_mode;
mod bespoke_event_handling;
#[doc(hidden)]
pub mod chatgpt_connectors;
mod code_mode_host;
mod codex_home_metrics;
mod command_exec;

View File

@@ -70,17 +70,14 @@ struct AppServerArgs {
#[arg(long = "disable-plugin-startup-tasks-for-tests", hide = true)]
disable_plugin_startup_tasks_for_tests: bool,
/// Enable remote control for this app-server process without changing persistence.
#[arg(long = "remote-control", hide = true)]
remote_control: bool,
/// Save loaded threads during managed daemon shutdown.
#[arg(long, hide = true)]
managed_daemon: bool,
}
fn main() -> anyhow::Result<()> {
let remote_control_disabled = codex_app_server::take_remote_control_disabled_env();
// aKode: remote control is not available; still consume the daemon's internal marker.
let _ = codex_app_server::take_remote_control_disabled_env();
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
let AppServerArgs {
cloud_skills_snapshot,
@@ -92,7 +89,6 @@ fn main() -> anyhow::Result<()> {
strict_config,
#[cfg(debug_assertions)]
disable_plugin_startup_tasks_for_tests,
remote_control,
managed_daemon,
} = AppServerArgs::parse();
let loader_overrides = if disable_managed_config_from_debug_env() {
@@ -115,11 +111,7 @@ fn main() -> anyhow::Result<()> {
runtime_options.plugin_startup_tasks = PluginStartupTasks::Skip;
}
runtime_options.remote_control_startup_mode =
match (remote_control, remote_control_disabled) {
(true, _) => codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
(false, true) => codex_app_server::RemoteControlStartupMode::DisabledEphemeral,
(false, false) => codex_app_server::RemoteControlStartupMode::ResolvePersisted,
};
codex_app_server::RemoteControlStartupMode::DisabledEphemeral;
let exit = run_main_with_transport_options(
arg0_paths,

View File

@@ -1,4 +1,5 @@
use crate::bespoke_event_handling::apply_bespoke_event_handling;
use crate::chatgpt_connectors as connectors;
use crate::command_exec::CommandExecManager;
use crate::command_exec::StartCommandExecParams;
use crate::config_manager::ConfigManager;
@@ -328,7 +329,6 @@ use codex_backend_client::RateLimitResetCreditDetails as BackendRateLimitResetCr
use codex_backend_client::RateLimitResetCreditsDetails as BackendRateLimitResetCreditsDetails;
use codex_backend_client::RequestError as BackendRequestError;
use codex_backend_client::TokenUsageProfile;
use codex_chatgpt::connectors;
use codex_config::CloudConfigBundleLoadError;
use codex_config::CloudConfigBundleLoadErrorCode;
use codex_config::ConfigLayerStack;

View File

@@ -32,7 +32,7 @@ pub struct StartupConfigArgs {
pub startup_sign_out: bool,
/// Validate configuration and print requirements as JSON without starting the app server.
#[arg(long, conflicts_with_all = ["listen", "stdio", "remote_control", "managed_daemon"])]
#[arg(long, conflicts_with_all = ["listen", "stdio", "managed_daemon"])]
pub print_startup_config: bool,
/// ClientInfo JSON used for configuration/auth request identity.

View File

@@ -18,6 +18,7 @@ use axum::http::StatusCode;
use axum::http::header::AUTHORIZATION;
use axum::routing::any;
use axum::routing::post;
use codex_app_server::chatgpt_connectors as connectors;
use codex_app_server_protocol::AppsReadParams;
use codex_app_server_protocol::AppsReadResponse;
use codex_app_server_protocol::ConnectorMetadata;
@@ -26,7 +27,6 @@ use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_chatgpt::connectors;
use codex_config::LoaderOverrides;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::ConfigBuilder;

View File

@@ -130,7 +130,6 @@ mod rate_limits;
mod rate_limits_identity;
mod realtime_conversation;
mod recommended_plugins;
mod remote_control;
#[cfg(debug_assertions)]
mod remote_thread_store;
mod request_permissions;

File diff suppressed because it is too large Load Diff

View File

@@ -1,631 +0,0 @@
//! Exercises login lifetime boundaries through public RPCs and a real relay websocket.
use super::*;
use app_test_support::ChatGptIdTokenClaims;
use app_test_support::encode_id_token;
use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse;
use codex_app_server_protocol::ServerRequest;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tokio_tungstenite::WebSocketStream;
struct RelayClient {
socket: WebSocketStream<TcpStream>,
next_seq: u64,
}
impl RelayClient {
async fn send(&mut self, message: Value) -> Result<()> {
self.socket
.send(Message::Text(
json!({
"type": "client_message", "client_id": "client-a", "stream_id": "stream-a",
"seq_id": self.next_seq, "cursor": format!("cursor-{}", self.next_seq),
"message": message,
})
.to_string()
.into(),
))
.await?;
self.next_seq += 1;
Ok(())
}
async fn response(&mut self, id: i64) -> Result<Value> {
timeout(DEFAULT_TIMEOUT, async {
loop {
let message = self.socket.next().await.context("relay disconnected")??;
if let Message::Text(text) = message {
let envelope: Value = serde_json::from_str(&text)?;
if envelope["type"] == "server_message" && envelope["message"]["id"] == id {
return Ok(envelope["message"].clone());
}
}
}
})
.await?
}
async fn closed(&mut self) -> Result<()> {
timeout(DEFAULT_TIMEOUT, async {
loop {
match self.socket.next().await {
None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return,
Some(Ok(_)) => {}
}
}
})
.await?;
Ok(())
}
async fn assert_account(&mut self, app: &mut TestAppServer) -> Result<()> {
let local = app.send_request("account/read", Some(json!({}))).await?;
let expected: Value = timeout(DEFAULT_TIMEOUT, app.read_response(local)).await??;
self.send(json!({"id": 2, "method": "account/read", "params": {}}))
.await?;
assert_eq!(
self.response(/*id*/ 2).await?.get("result"),
Some(&expected)
);
Ok(())
}
}
fn external_token(user: &str, account: &str, revision: &str) -> Result<String> {
encode_id_token(
&ChatGptIdTokenClaims::new()
.chatgpt_account_id(account)
.chatgpt_user_id(user)
.plan_type("pro")
.email(format!("{revision}@example.com")),
)
}
async fn login(app: &mut TestAppServer, user: &str, account: &str, revision: &str) -> Result<()> {
let id = app
.send_chatgpt_auth_tokens_login_request(
external_token(user, account, revision)?,
account.to_string(),
Some("pro".to_string()),
)
.await?;
wait_for_response(app, id).await
}
async fn open_relay(app: &mut TestAppServer, listener: &TcpListener) -> Result<RelayClient> {
let id = app.send_remote_control_ephemeral_enable_request().await?;
wait_for_response(app, id).await?;
let request = timeout(DEFAULT_TIMEOUT, read_http_request(listener)).await??;
assert!(
request.request_line.contains("/server/enroll ")
|| request.request_line.contains("/server/refresh "),
"{}",
request.request_line
);
respond_with_json(
request.reader.into_inner(),
json!({
"server_id": "server-id", "environment_id": "environment-id",
"remote_control_token": "remote-control-token", "expires_at": "3026-05-22T12:34:56Z",
}),
)
.await?;
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
let socket = timeout(
DEFAULT_TIMEOUT,
tokio_tungstenite::accept_hdr_async(
stream,
|request: &tokio_tungstenite::tungstenite::handshake::server::Request, response| {
assert!(!request.headers().contains_key("x-codex-subscribe-cursor"));
Ok(response)
},
),
)
.await??;
let mut relay = RelayClient {
socket,
next_seq: 0,
};
// A replacement must not retain the old logical client or replay its unacknowledged results.
relay
.socket
.send(Message::Text(
json!({
"type": "ping", "client_id": "client-a", "stream_id": "stream-a",
})
.to_string()
.into(),
))
.await?;
timeout(DEFAULT_TIMEOUT, async {
loop {
let message = relay
.socket
.next()
.await
.context("relay disconnected before pong")??;
if let Message::Text(text) = message {
let envelope: Value = serde_json::from_str(&text)?;
assert_ne!(envelope["type"], "server_message");
if envelope["type"] == "pong" {
assert_eq!(envelope["status"], "unknown");
return Ok::<(), anyhow::Error>(());
}
}
}
})
.await??;
relay
.send(json!({"id": 1, "method": "initialize", "params": {
"clientInfo": {"name": "remote-auth-test", "version": "0.1.0"},
"capabilities": {"experimentalApi": true},
}}))
.await?;
assert!(relay.response(/*id*/ 1).await?.get("result").is_some());
relay.send(json!({"method": "initialized"})).await?;
Ok(relay)
}
#[tokio::test]
async fn same_owner_refresh_preserves_live_relay() -> Result<()> {
let home = TempDir::new()?;
let listener = configured_remote_control_listener(home.path()).await?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.build_initialized()
.await?;
login(&mut app, "user-a", "account-a", "initial").await?;
let mut relay = open_relay(&mut app, &listener).await?;
login(&mut app, "user-a", "account-a", "refreshed").await?;
relay.assert_account(&mut app).await
}
#[tokio::test]
async fn owner_change_retires_live_relay() -> Result<()> {
for (user, account) in [("user-b", "account-a"), ("user-a", "account-b")] {
let home = TempDir::new()?;
let listener = configured_remote_control_listener(home.path()).await?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.build_initialized()
.await?;
login(&mut app, "user-a", "account-a", "initial").await?;
let mut old = open_relay(&mut app, &listener).await?;
old.assert_account(&mut app).await?;
login(&mut app, user, account, "replacement").await?;
old.closed().await?;
let id = app.send_remote_control_status_read_request().await?;
let status: RemoteControlStatusReadResponse =
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
assert_eq!(status.status, RemoteControlConnectionStatus::Disabled);
let mut fresh = open_relay(&mut app, &listener).await?;
fresh.assert_account(&mut app).await?;
}
Ok(())
}
#[tokio::test]
async fn owner_change_discards_pending_and_queued_pairing() -> Result<()> {
let home = TempDir::new()?;
let listener = configured_remote_control_listener(home.path()).await?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.build_initialized()
.await?;
login(&mut app, "user-a", "account-a", "initial").await?;
let mut old = open_relay(&mut app, &listener).await?;
let pending = app
.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
manual_code: false,
})
.await?;
let held = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
assert!(held.request_line.contains("/server/pair "));
old.send(
json!({"id": 3, "method": "remoteControl/pairing/start", "params": {"manualCode": false}}),
)
.await?;
// account/read uses another queue. Its response proves the prior pairing RPC was received.
old.assert_account(&mut app).await?;
login(&mut app, "user-b", "account-a", "replacement").await?;
let mut fresh = open_relay(&mut app, &listener).await?;
let sentinel = app
.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
manual_code: true,
})
.await?;
// The old socket can already be cancelled, so delivery of this obsolete response is optional.
let _ = respond_with_json(held.reader.into_inner(), json!({
"pairing_code": "obsolete", "server_id": "server-id", "environment_id": "environment-id",
"expires_at": "3026-05-22T12:34:56Z",
})).await;
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
assert!(next.request_line.contains("/server/pair "));
assert_eq!(
serde_json::from_str::<Value>(&next.body)?,
json!({"manual_code": true})
);
respond_with_json(
next.reader.into_inner(),
json!({
"pairing_code": "current", "server_id": "server-id", "manual_pairing_code": "ABCD-EFGH",
"environment_id": "environment-id", "expires_at": "3026-05-22T12:34:56Z",
}),
)
.await?;
timeout(
DEFAULT_TIMEOUT,
app.read_stream_until_error_message(RequestId::Integer(pending)),
)
.await??;
wait_for_response(&mut app, sentinel).await?;
old.closed().await?;
fresh.assert_account(&mut app).await
}
#[tokio::test]
async fn client_revoke_retry_stays_with_original_owner() -> Result<()> {
for refreshed_user in ["user-a", "user-b"] {
let home = TempDir::new()?;
let listener = configured_remote_control_listener(home.path()).await?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.build_initialized()
.await?;
login(&mut app, "user-a", "account-a", "initial").await?;
let old = app
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
environment_id: "environment-id".to_string(),
client_id: "old-client".to_string(),
})
.await?;
let first = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
assert_eq!(
first.request_line,
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/old-client HTTP/1.1"
);
respond_with_status(first.reader.into_inner(), "401 Unauthorized", "expired").await?;
let request = timeout(DEFAULT_TIMEOUT, app.read_stream_until_request_message()).await??;
let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = request else {
anyhow::bail!("expected external authentication refresh");
};
app.send_response(
request_id,
serde_json::to_value(ChatgptAuthTokensRefreshResponse {
access_token: external_token(refreshed_user, "account-a", "refreshed")?,
chatgpt_account_id: "account-a".to_string(),
chatgpt_plan_type: Some("pro".to_string()),
})?,
)
.await?;
let (next_id, client) = if refreshed_user == "user-a" {
(old, "old-client")
} else {
timeout(
DEFAULT_TIMEOUT,
app.read_stream_until_error_message(RequestId::Integer(old)),
)
.await??;
login(&mut app, refreshed_user, "account-a", "refreshed").await?;
let id = app
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
environment_id: "environment-id".to_string(),
client_id: "new-client".to_string(),
})
.await?;
(id, "new-client")
};
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
assert_eq!(
next.request_line,
format!(
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/{client} HTTP/1.1"
)
);
respond_with_json(next.reader.into_inner(), json!({})).await?;
let result: RemoteControlClientsRevokeResponse =
timeout(DEFAULT_TIMEOUT, app.read_response(next_id)).await??;
assert_eq!(result, RemoteControlClientsRevokeResponse {});
}
Ok(())
}
#[tokio::test]
async fn owner_change_rejects_queued_client_revoke() -> Result<()> {
let home = TempDir::new()?;
let listener = configured_remote_control_listener(home.path()).await?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.build_initialized()
.await?;
login(&mut app, "user-a", "account-a", "initial").await?;
let mut relay = open_relay(&mut app, &listener).await?;
let pending = app
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
environment_id: "environment-id".to_string(),
client_id: "pending".to_string(),
})
.await?;
let held = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
relay
.send(
json!({"id": 3, "method": "remoteControl/client/revoke", "params": {
"environmentId": "environment-id", "clientId": "obsolete",
}}),
)
.await?;
relay.assert_account(&mut app).await?;
login(&mut app, "user-b", "account-a", "replacement").await?;
let sentinel = app
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
environment_id: "environment-id".to_string(),
client_id: "current".to_string(),
})
.await?;
let _ = respond_with_json(held.reader.into_inner(), json!({})).await;
// Client management works even while disabled, so disablement cannot mask a missing gate.
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
assert_eq!(
next.request_line,
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/current HTTP/1.1"
);
respond_with_json(next.reader.into_inner(), json!({})).await?;
timeout(
DEFAULT_TIMEOUT,
app.read_stream_until_error_message(RequestId::Integer(pending)),
)
.await??;
wait_for_response(&mut app, sentinel).await?;
relay.closed().await
}
#[tokio::test]
async fn logout_login_enable_recovers_first_unauthorized_enrollment() -> Result<()> {
let home = TempDir::new()?;
let listener = configured_remote_control_listener(home.path()).await?;
let oauth = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::path("/oauth/revoke"))
.respond_with(wiremock::ResponseTemplate::new(/*s*/ 200))
.expect(1)
.mount(&oauth)
.await;
let revoke_url = format!("{}/oauth/revoke", oauth.uri());
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.with_env_overrides(&[("CODEX_REVOKE_TOKEN_URL_OVERRIDE", Some(revoke_url.as_str()))])
.without_auto_env()
.build_initialized()
.await?;
let enabled = app.send_remote_control_ephemeral_enable_request().await?;
wait_for_response(&mut app, enabled).await?;
let (_, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
respond_with_json(
reader.into_inner(),
serde_json::json!({
"server_id": "server-a", "environment_id": "environment-a",
"remote_control_token": "token-a", "expires_at": "3026-05-22T12:34:56Z",
}),
)
.await?;
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
let mut websocket = timeout(DEFAULT_TIMEOUT, accept_async(stream)).await??;
let logout = app.send_logout_account_request().await?;
wait_for_response(&mut app, logout).await?;
timeout(DEFAULT_TIMEOUT, async {
loop {
let notification = app
.read_stream_until_notification_message("remoteControl/status/changed")
.await?;
let status: RemoteControlStatusChangedNotification =
serde_json::from_value(notification.params.context("status params")?)?;
if status.status == RemoteControlConnectionStatus::Disabled {
return Ok::<(), anyhow::Error>(());
}
}
})
.await??;
assert!(matches!(
timeout(DEFAULT_TIMEOUT, websocket.next()).await?,
None | Some(Err(_)) | Some(Ok(Message::Close(_)))
));
let token = encode_id_token(
&ChatGptIdTokenClaims::new()
.chatgpt_account_id("account_b")
.chatgpt_user_id("user_b")
.plan_type("pro"),
)?;
let login = app
.send_chatgpt_auth_tokens_login_request(
token.clone(),
"account_b".to_string(),
Some("pro".to_string()),
)
.await?;
wait_for_response(&mut app, login).await?;
let enabled = app.send_remote_control_ephemeral_enable_request().await?;
wait_for_response(&mut app, enabled).await?;
let (line, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
assert_eq!(
line,
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
);
respond_with_status(reader.into_inner(), "401 Unauthorized", "expired token").await?;
let request = timeout(DEFAULT_TIMEOUT, app.read_stream_until_request_message()).await??;
let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = request else {
anyhow::bail!("expected token refresh after the new owner's 401");
};
let refreshed_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.chatgpt_account_id("account_b")
.chatgpt_user_id("user_b")
.plan_type("pro")
.email("refreshed@example.com"),
)?;
app.send_response(
request_id,
serde_json::to_value(ChatgptAuthTokensRefreshResponse {
access_token: refreshed_token,
chatgpt_account_id: "account_b".to_string(),
chatgpt_plan_type: Some("pro".to_string()),
})?,
)
.await?;
let (_, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
respond_with_json(
reader.into_inner(),
serde_json::json!({
"server_id": "server-b", "environment_id": "environment-b",
"remote_control_token": "token-b", "expires_at": "3026-05-22T12:34:56Z",
}),
)
.await?;
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
let _websocket = timeout(DEFAULT_TIMEOUT, accept_async(stream)).await??;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn public_client_management_uses_runtime_auth() -> Result<()> {
use base64::Engine;
use core_test_support::runtime_auth::PROBE_SERVER;
use core_test_support::runtime_auth::run_harness_through_proxy;
use std::collections::BTreeSet;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
core_test_support::skip_if_no_network!(Ok(()));
let claims =
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({
"exp": 4102444800_i64, "session_id": "remote-public",
"iss": "https://auth.openai.com",
"https://api.openai.com/auth": {
"chatgpt_user_id": "user-123", "chatgpt_account_id": "account-123"
},
}))?);
let token = format!("e30.{claims}.c2ln");
if std::env::var(PROBE_SERVER).is_ok() {
for mode in ["dual_header", "assertion_only"] {
let home = TempDir::new()?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new(&token)
.account_id("account-123")
.chatgpt_user_id("user-123")
.plan_type("pro"),
AuthCredentialsStoreMode::File,
)?;
std::fs::write(
home.path().join("config.toml"),
format!(
"chatgpt_base_url = \"https://chatgpt.com/backend-api\"\n[features.runtime_agent_instances]\nenabled = true\nmode = {mode:?}\n"
),
)?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
for _ in 0..2 {
let id = app
.send_remote_control_clients_list_request(RemoteControlClientsListParams {
environment_id: "environment".into(),
cursor: None,
limit: None,
order: None,
})
.await?;
let response: RemoteControlClientsListResponse =
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
assert!(response.data.is_empty());
}
let id = app
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
environment_id: "environment".into(),
client_id: "client".into(),
})
.await?;
let _: RemoteControlClientsRevokeResponse =
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
}
return Ok(());
}
let server = MockServer::start().await;
app_test_support::mount_workspace_routing(&server).await;
Mock::given(method("POST"))
.and(path("/agent/register"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-remote-public", "agent_host_id": "host",
"actor": {"kind": "chatgpt", "user_id": "user-123", "account_id": "account-123"}
})))
.expect(/*r*/ 2)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path(
"/backend-api/wham/remote/control/environments/environment/clients",
))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"items": [], "cursor": null
})))
.expect(/*r*/ 4)
.mount(&server)
.await;
Mock::given(method("DELETE"))
.and(path(
"/backend-api/wham/remote/control/environments/environment/clients/client",
))
.respond_with(ResponseTemplate::new(/*s*/ 204))
.expect(/*r*/ 2)
.mount(&server)
.await;
run_harness_through_proxy(
&server,
"suite::v2::remote_control::auth_tests::public_client_management_uses_runtime_auth",
/*realtime_target*/ None,
)
.await?;
let requests = server.received_requests().await.unwrap();
let mut proofs = BTreeSet::new();
let mut dual = 0;
for request in requests
.iter()
.filter(|r| r.url.path().contains("/wham/remote/control/"))
{
assert_eq!(request.headers["host"], "chatgpt.com");
assert_eq!(request.headers["chatgpt-account-id"], "account-123");
let authorization = request.headers["authorization"].to_str()?;
let proof = if let Some(proof) = request.headers.get("x-openai-agent-assertion") {
dual += 1;
assert_eq!(authorization, format!("Bearer {token}"));
proof.to_str()?
} else {
authorization
.strip_prefix("AgentAssertion ")
.expect("assertion-only auth")
};
let payload: Value = serde_json::from_slice(
&base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(proof.split('.').nth(/*n*/ 2).unwrap())?,
)?;
assert_eq!(payload["runtime_agent_instance"], "runtime-remote-public");
assert!(
proofs.insert(proof.to_owned()),
"each request gets a fresh assertion"
);
}
assert_eq!((dual, proofs.len()), (3, 6));
server.verify().await;
Ok(())
}