mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Reuse configuration server OAuth discovery across startup reads (#63781)
## Why The one-shot startup flow uses separate invocations to check requirements, sign in, and reload policy. Each invocation can repeat OAuth discovery. ## What changed Accept `configRequirements/read` in `codex app-server --startup-oauth` with the same validation and errors as `--print-startup-config`. Successful responses include `appServerVersion`. When the read reports `configServerLogin`, clients can sign in and retry the read over the same stdio connection. The retry reloads policy with the saved credentials and reuses OAuth discovery while the configuration server and proxy settings still match. GitOrigin-RevId: b5342cead5ebb9f2e0692061bf4b6ef933dc8cdd
This commit is contained in:
committed by
copyberry
parent
a5815ebe65
commit
b8e2d0cdef
@@ -854,9 +854,16 @@ the app server. If a required configuration server uses OAuth and needs a new
|
||||
grant, the command exits with an error whose `data` contains
|
||||
`"reason": "configServer"` and `"action": "configServerLogin"`.
|
||||
|
||||
When the action is `configServerLogin`, start `codex app-server --startup-oauth`.
|
||||
To share OAuth discovery across startup and sign-in, start
|
||||
`codex app-server --startup-oauth` and send
|
||||
`{"id":0,"method":"configRequirements/read"}`. The result is the usual
|
||||
requirements response with an additional `appServerVersion` field. The helper
|
||||
performs the same validation and reports the same errors as
|
||||
`--print-startup-config`.
|
||||
|
||||
This dedicated stdio connection accepts one JSON request per line without an
|
||||
initialize handshake. Each reply echoes the string or integer request ID.
|
||||
If the read reports `configServerLogin`, keep the connection open.
|
||||
|
||||
1. After the user chooses Sign in, send
|
||||
`{"id":1,"method":"account/gatewayOAuth/login","params":{"target":{"kind":"configServer"}}}`.
|
||||
@@ -869,8 +876,11 @@ initialize handshake. Each reply echoes the string or integer request ID.
|
||||
success, or an error on failure. To cancel, send
|
||||
`{"id":2,"method":"account/gatewayOAuth/cancel"}`. Closing stdin also ends the
|
||||
pending attempt.
|
||||
4. On success, close the pipe and rerun `--print-startup-config`. Continue startup
|
||||
only with the validated requirements.
|
||||
4. On success, send `configRequirements/read` again on the same pipe. The
|
||||
helper reloads policy with the saved credentials and reuses OAuth discovery
|
||||
if the server and proxy settings still match. Close the pipe and continue
|
||||
only after validating the requirements. Older clients can still use the
|
||||
one-shot command before and after sign-in.
|
||||
|
||||
# Item history anchors
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_cloud_config::managed_config_bundle_loader;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::ConfigServerResolution;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::ThreadConfigLoader;
|
||||
use codex_config::apply_default_gcp_auth;
|
||||
@@ -122,6 +123,19 @@ impl ConfigManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Isolate each startup read from the previous loader's cached auth error and network policy.
|
||||
pub(crate) fn startup_probe(&self) -> Self {
|
||||
Self::new(
|
||||
self.codex_home.clone(),
|
||||
self.current_cli_overrides(),
|
||||
self.loader_overrides.clone(),
|
||||
self.strict_config,
|
||||
CloudConfigBundleLoader::default(),
|
||||
self.arg0_paths.clone(),
|
||||
self.thread_config_loader.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn with_mcp_launch_cwds(mut self, cwds: McpLaunchCwds) -> Self {
|
||||
self.mcp_launch_cwds = Arc::new(cwds);
|
||||
self
|
||||
@@ -205,6 +219,20 @@ impl ConfigManager {
|
||||
&self,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
config: &Config,
|
||||
) {
|
||||
self.update_managed_config_loader_with_resolution(
|
||||
auth_manager,
|
||||
config,
|
||||
/*previous*/ None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn update_managed_config_loader_with_resolution(
|
||||
&self,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
config: &Config,
|
||||
previous: Option<&ConfigServerResolution>,
|
||||
) {
|
||||
// Keep config-server settings and their refresh worker when only
|
||||
// ChatGPT/API-key credentials change.
|
||||
@@ -224,6 +252,7 @@ impl ConfigManager {
|
||||
.http_client_factory()
|
||||
.with_network_policy(self.local_network_policy.policy()),
|
||||
config.config_layer_stack.requirements_toml(),
|
||||
previous,
|
||||
)
|
||||
.await;
|
||||
if let Ok(mut guard) = self.cloud_config_bundle.write() {
|
||||
@@ -434,13 +463,15 @@ impl ConfigManager {
|
||||
pub(crate) async fn load_managed_startup_config(
|
||||
&self,
|
||||
cwd: Option<PathBuf>,
|
||||
previous: Option<&ConfigServerResolution>,
|
||||
) -> std::io::Result<CloudStartupConfig> {
|
||||
let bootstrap = self.load_startup_config(cwd.clone()).await?.config;
|
||||
let auth =
|
||||
AuthManager::shared_from_config(&bootstrap, /*enable_codex_api_key_env*/ false)
|
||||
.await
|
||||
.map_err(std::io::Error::other)?;
|
||||
self.update_managed_config_loader(auth, &bootstrap).await;
|
||||
self.update_managed_config_loader_with_resolution(auth, &bootstrap, previous)
|
||||
.await;
|
||||
let config = self.load_latest_config(cwd).await;
|
||||
Ok(CloudStartupConfig { bootstrap, config })
|
||||
}
|
||||
|
||||
@@ -578,7 +578,7 @@ pub async fn run_main_with_transport_options(
|
||||
)
|
||||
.with_mcp_launch_cwds(runtime_options.plugin_mcp_launch.into_cwds()?);
|
||||
let startup = config_manager
|
||||
.load_managed_startup_config(startup_cwd.clone())
|
||||
.load_managed_startup_config(startup_cwd.clone(), /*previous*/ None)
|
||||
.await?;
|
||||
let mut config_warnings = Vec::new();
|
||||
let mut plugin_startup_config = PluginStartupConfig::Current;
|
||||
|
||||
@@ -41,7 +41,7 @@ pub struct StartupConfigArgs {
|
||||
)]
|
||||
pub startup_sign_out: bool,
|
||||
|
||||
/// Serve only configuration-server OAuth requests over standard input and output.
|
||||
/// Serve startup requirements and configuration-server OAuth requests over standard input and output.
|
||||
#[arg(long, group = "startup_mode", conflicts_with_all = ["listen", "stdio", "remote_control", "managed_daemon"])]
|
||||
pub startup_oauth: bool,
|
||||
|
||||
@@ -81,7 +81,9 @@ pub async fn print_startup_config(
|
||||
return oauth::serve(manager, tokio::io::stdin(), tokio::io::stdout()).await;
|
||||
}
|
||||
let result = match manager {
|
||||
Ok(manager) => read_startup_config(manager, startup.startup_sign_out).await,
|
||||
Ok(manager) => {
|
||||
read_startup_config(&manager, startup.startup_sign_out, /*previous*/ None).await
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let output = match &result {
|
||||
@@ -98,8 +100,9 @@ pub async fn print_startup_config(
|
||||
}
|
||||
|
||||
async fn read_startup_config(
|
||||
manager: ConfigManager,
|
||||
manager: &ConfigManager,
|
||||
sign_out: bool,
|
||||
previous: Option<&codex_config::ConfigServerResolution>,
|
||||
) -> Result<StartupConfig, JSONRPCErrorError> {
|
||||
if sign_out && (is_workload_identity_selected() || read_codex_access_token_from_env().is_some())
|
||||
{
|
||||
@@ -109,7 +112,7 @@ async fn read_startup_config(
|
||||
}
|
||||
let cwd = std::env::current_dir().ok();
|
||||
let loaded = manager
|
||||
.load_managed_startup_config(cwd.clone())
|
||||
.load_managed_startup_config(cwd.clone(), previous)
|
||||
.await
|
||||
.map_err(startup_error)?;
|
||||
let config = match loaded.config {
|
||||
@@ -141,8 +144,8 @@ async fn read_startup_config(
|
||||
.await
|
||||
.map_err(|error| startup_error(io::Error::other(error)))?;
|
||||
set_default_client_residency_requirement(config.enforce_residency.value());
|
||||
let config = logout_configured_account(&manager, &auth, &config).await?;
|
||||
clear_account_configuration(&manager, &config).await?;
|
||||
let config = logout_configured_account(manager, &auth, &config).await?;
|
||||
clear_account_configuration(manager, &config).await?;
|
||||
manager
|
||||
.update_managed_config_loader(Arc::clone(&auth), &config)
|
||||
.await;
|
||||
|
||||
@@ -18,6 +18,7 @@ use codex_app_server_protocol::JSONRPCRequest;
|
||||
use codex_app_server_protocol::JSONRPCResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::StartupGatewayOAuthChangedNotification;
|
||||
use codex_config::ConfigServerResolution;
|
||||
use codex_login::OAuthSessionManager;
|
||||
use futures::FutureExt;
|
||||
use futures::future::BoxFuture;
|
||||
@@ -36,19 +37,32 @@ use tokio_util::sync::CancellationToken;
|
||||
// bootstrap settings to resolve the grant without fetching policy again.
|
||||
async fn discover_session(
|
||||
manager: &ConfigManager,
|
||||
resolution: &mut Option<ConfigServerResolution>,
|
||||
) -> Result<Option<OAuthSessionManager>, JSONRPCErrorError> {
|
||||
let bootstrap = manager
|
||||
.load_startup_config(std::env::current_dir().ok())
|
||||
.await
|
||||
.map_err(startup_error)?
|
||||
.config;
|
||||
codex_cloud_config::managed_config_auth_manager(
|
||||
bootstrap.auth_config(),
|
||||
bootstrap.config_layer_stack.requirements_toml(),
|
||||
let previous = resolution.take();
|
||||
let Some(server) = &bootstrap
|
||||
.config_layer_stack
|
||||
.requirements_toml()
|
||||
.config_server
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let auth = bootstrap.auth_config();
|
||||
let (resolved, session) = codex_cloud_config::config_server_auth_manager(
|
||||
server,
|
||||
auth.codex_home,
|
||||
&auth.auth_route_config,
|
||||
previous.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map(|session| session.and_then(|(_, manager)| manager))
|
||||
.map_err(|_| config_server_login_failed("Could not initialize configuration server sign-in"))
|
||||
.map_err(|_| config_server_login_failed("Could not initialize configuration server sign-in"))?;
|
||||
*resolution = Some(resolved);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
struct Attempt {
|
||||
@@ -117,6 +131,7 @@ async fn start_login(
|
||||
id: RequestId,
|
||||
params: GatewayOAuthLoginParams,
|
||||
manager: &ConfigManager,
|
||||
resolution: &mut Option<ConfigServerResolution>,
|
||||
active: &mut Option<Attempt>,
|
||||
) -> Result<StartupGatewayOAuthChangedNotification, JSONRPCErrorError> {
|
||||
if params.target != Some(GatewayOAuthTarget::ConfigServer) || params.model_provider.is_some() {
|
||||
@@ -132,9 +147,11 @@ async fn start_login(
|
||||
if active.is_some() {
|
||||
return Err(invalid_request("Sign-in already in progress"));
|
||||
}
|
||||
let session = discover_session(manager).await?.ok_or_else(|| {
|
||||
config_server_login_failed("Configuration server OAuth is not configured")
|
||||
})?;
|
||||
let session = discover_session(manager, resolution)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
config_server_login_failed("Configuration server OAuth is not configured")
|
||||
})?;
|
||||
let (attempt, handoff) = Attempt::start(id, session).await?;
|
||||
*active = Some(attempt);
|
||||
Ok(handoff)
|
||||
@@ -143,6 +160,7 @@ async fn start_login(
|
||||
async fn handle_request(
|
||||
line: &str,
|
||||
manager: &ConfigManager,
|
||||
resolution: &mut Option<ConfigServerResolution>,
|
||||
active: &mut Option<Attempt>,
|
||||
output: &mut (impl AsyncWrite + Unpin),
|
||||
) -> io::Result<()> {
|
||||
@@ -150,7 +168,7 @@ async fn handle_request(
|
||||
let id = raw.id.clone();
|
||||
if !matches!(
|
||||
raw.method.as_str(),
|
||||
"account/gatewayOAuth/login" | "account/gatewayOAuth/cancel"
|
||||
"configRequirements/read" | "account/gatewayOAuth/login" | "account/gatewayOAuth/cancel"
|
||||
) {
|
||||
return write(
|
||||
output,
|
||||
@@ -159,8 +177,34 @@ async fn handle_request(
|
||||
.await;
|
||||
}
|
||||
let result = match ClientRequest::try_from(raw) {
|
||||
Ok(ClientRequest::ConfigRequirementsRead { .. }) if active.is_some() => {
|
||||
Err(invalid_request("Sign-in already in progress"))
|
||||
}
|
||||
Ok(ClientRequest::ConfigRequirementsRead { .. }) => {
|
||||
let probe = manager.startup_probe();
|
||||
let result =
|
||||
super::read_startup_config(&probe, /*sign_out*/ false, resolution.as_ref()).await;
|
||||
// Keep successful discovery even when the policy read requires sign-in.
|
||||
*resolution = probe
|
||||
.current_managed_config_loader()
|
||||
.config_server_resolution()
|
||||
.cloned();
|
||||
result.map(|config| {
|
||||
let mut response = json!(config.config_requirements);
|
||||
response["appServerVersion"] = json!(config.app_server_version);
|
||||
response
|
||||
})
|
||||
}
|
||||
Ok(ClientRequest::GatewayOAuthLogin { params, .. }) => {
|
||||
match start_login(id.clone(), params.unwrap_or_default(), manager, active).await {
|
||||
match start_login(
|
||||
id.clone(),
|
||||
params.unwrap_or_default(),
|
||||
manager,
|
||||
resolution,
|
||||
active,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(handoff) => {
|
||||
return write(
|
||||
output,
|
||||
@@ -191,6 +235,7 @@ pub(super) async fn serve(
|
||||
) -> io::Result<()> {
|
||||
let mut requests = BufReader::new(input).lines();
|
||||
let mut active: Option<Attempt> = None;
|
||||
let mut resolution = None;
|
||||
loop {
|
||||
let line = if let Some(attempt) = active.as_mut() {
|
||||
tokio::select! {
|
||||
@@ -207,6 +252,6 @@ pub(super) async fn serve(
|
||||
requests.next_line().await
|
||||
}?;
|
||||
let Some(line) = line else { return Ok(()) };
|
||||
handle_request(&line, &manager, &mut active, &mut output).await?;
|
||||
handle_request(&line, &manager, &mut resolution, &mut active, &mut output).await?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,9 +29,14 @@ pub async fn managed_config_auth_manager(
|
||||
let Some(service_config) = requirements.config_server.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
crate::config_server_auth_manager(service_config, auth.codex_home, &auth.auth_route_config)
|
||||
.await
|
||||
.map(Some)
|
||||
crate::config_server_auth_manager(
|
||||
service_config,
|
||||
auth.codex_home,
|
||||
&auth.auth_route_config,
|
||||
/*previous*/ None,
|
||||
)
|
||||
.await
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// How to sign in when the config server has no saved OAuth grant.
|
||||
@@ -87,13 +92,14 @@ pub async fn managed_config_bundle_loader(
|
||||
codex_home: PathBuf,
|
||||
factory: HttpClientFactory,
|
||||
requirements: &ConfigRequirementsToml,
|
||||
previous: Option<&ConfigServerResolution>,
|
||||
) -> CloudConfigBundleLoader {
|
||||
if let Some(service_config) = requirements.config_server.as_ref() {
|
||||
return crate::config_server_bundle_loader(
|
||||
service_config.clone(),
|
||||
codex_home,
|
||||
&codex_login::AuthRouteConfig::from_http_client_factory(factory),
|
||||
/*previous*/ None,
|
||||
previous,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
@@ -181,8 +181,9 @@ pub async fn config_server_auth_manager(
|
||||
service_config: &ConfigServer,
|
||||
codex_home: PathBuf,
|
||||
routes: &AuthRouteConfig,
|
||||
previous: Option<&ConfigServerResolution>,
|
||||
) -> std::io::Result<(ConfigServerResolution, Option<OAuthSessionManager>)> {
|
||||
let resolution = resolve_config_server(service_config, routes, /*previous*/ None).await?;
|
||||
let resolution = resolve_config_server(service_config, routes, previous).await?;
|
||||
let factory = config_server_http_client_factory(&resolution.resolved, routes);
|
||||
let manager =
|
||||
oauth_session_manager(resolution.resolved.oauth.as_deref(), codex_home, &factory)?;
|
||||
|
||||
Reference in New Issue
Block a user