Support device-code login for config servers (#62079)

## Why

`codex login --device-auth` still used browser authorization when config server sign-in was required, preventing the selected device-code flow from being used there.

## What changed

- Use device authorization for config server sign-in when `--device-auth` is selected, display the verification URL and code, and report a missing `config_server.oauth.device_authorization_url` explicitly.
- Include the configured OAuth `resource` in device authorization and token polling requests.
- Reserve sign-in per credential across Codex processes, reuse saved grants, and release the reservation when sign-in completes or is canceled.
- Report config server sign-in failures with guidance specific to `config_server.oauth` and the credential store.

## Testing

Add or extend tests for the device-code prompt, config server failure messages, OAuth resource parameters, policy reload after credential replacement, and rejection of concurrent sign-in with retry after cancellation.

GitOrigin-RevId: 013176d0e10128c347dd072b818e22b5038a2791
This commit is contained in:
vishnu-oai
2026-11-17 16:42:48 +00:00
committed by copyberry
parent 378364e784
commit 2df29476ae
11 changed files with 310 additions and 69 deletions
+54 -9
View File
@@ -7,6 +7,7 @@
//! into a one-shot CLI command while still producing a durable `codex-login.log` artifact that
//! support can request from users.
use codex_cloud_config::ConfigServerLoginMethod;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::Config;
use codex_core::config::edit::ConfigEdit;
@@ -15,6 +16,7 @@ use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use codex_login::AuthRouteConfig;
use codex_login::CLIENT_ID;
use codex_login::OAuthDeviceCodePrompt;
use codex_login::ServerOptions;
use codex_login::is_workload_identity_selected;
use codex_login::login_with_access_token;
@@ -176,6 +178,7 @@ pub async fn login_with_chatgpt(
async fn sign_in_to_config_server_and_reload_config(
config: &mut Config,
cli_config_overrides: &CliConfigOverrides,
method: ConfigServerLoginMethod,
) -> std::io::Result<()> {
let requirements = config.config_layer_stack.requirements_toml();
let network = codex_app_server::in_process::EmbeddedNetworkPolicy::load(
@@ -184,7 +187,7 @@ async fn sign_in_to_config_server_and_reload_config(
.await;
let bootstrap_auth = network.bind_bootstrap_auth(config.auth_config());
let auth_route_config = bootstrap_auth.auth_route_config.clone();
codex_cloud_config::ensure_config_server_login(bootstrap_auth, requirements).await?;
codex_cloud_config::ensure_config_server_login(bootstrap_auth, requirements, method).await?;
*config = crate::cloud_config::load_config(cli_config_overrides, Default::default())
.await
.map_err(|error| std::io::Error::other(format!("{error:#}")))?;
@@ -208,6 +211,7 @@ fn finish_login(result: std::io::Result<()>) -> ! {
async fn run_interactive_login<F>(
cli_config_overrides: CliConfigOverrides,
config_server_login_method: ConfigServerLoginMethod,
chatgpt_login: impl FnOnce(Config) -> F,
) -> !
where
@@ -223,14 +227,18 @@ where
finish_login(chatgpt_login(config).await);
}
let result =
sign_in_to_config_server_and_reload_config(&mut config, &cli_config_overrides).await;
let result = sign_in_to_config_server_and_reload_config(
&mut config,
&cli_config_overrides,
config_server_login_method,
)
.await;
let _login_log_guard = init_login_file_logging(&config);
finish_login(result)
}
pub async fn run_login_with_browser(cli_config_overrides: CliConfigOverrides) -> ! {
run_interactive_login(cli_config_overrides, |config| async move {
let chatgpt_login = |config: Config| async move {
tracing::info!("starting browser login flow");
if !config
@@ -250,7 +258,12 @@ pub async fn run_login_with_browser(cli_config_overrides: CliConfigOverrides) ->
config.auth_route_config(),
)
.await
})
};
run_interactive_login(
cli_config_overrides,
ConfigServerLoginMethod::Browser,
chatgpt_login,
)
.await
}
@@ -374,7 +387,7 @@ pub async fn run_login_with_device_code(
issuer_base_url: Option<String>,
client_id: Option<String>,
) -> ! {
run_interactive_login(cli_config_overrides, |config| async move {
let chatgpt_login = |config: Config| async move {
tracing::info!("starting device code login flow");
if !config
.auth_config()
@@ -404,10 +417,25 @@ pub async fn run_login_with_device_code(
opts.issuer = iss;
}
run_device_code_login(opts).await
})
};
run_interactive_login(
cli_config_overrides,
ConfigServerLoginMethod::DeviceCode {
present: |prompt| eprintln!("{}", config_server_device_code_message(prompt)),
},
chatgpt_login,
)
.await
}
fn config_server_device_code_message(prompt: &OAuthDeviceCodePrompt) -> String {
let OAuthDeviceCodePrompt {
verification_uri,
user_code,
} = prompt;
format!("To sign in to the config server, open {verification_uri} and enter code {user_code}.")
}
/// Prefers device-code login (with `open_browser = false`) when headless environment is detected, but keeps
/// `codex login` working in environments where device-code may be disabled/feature-gated.
/// If `run_device_code_login` returns `ErrorKind::NotFound` ("device-code unsupported"), this
@@ -662,8 +690,12 @@ async fn load_managed_login_config_or_exit(cli_config_overrides: CliConfigOverri
.config_layer_stack
.requirements_toml()
.requires_remote_config()
&& let Err(error) =
sign_in_to_config_server_and_reload_config(&mut config, &cli_config_overrides).await
&& let Err(error) = sign_in_to_config_server_and_reload_config(
&mut config,
&cli_config_overrides,
ConfigServerLoginMethod::Browser,
)
.await
{
finish_login(Err(error));
}
@@ -711,14 +743,27 @@ mod storage_tests;
mod tests {
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::OAuthDeviceCodePrompt;
use codex_login::load_auth_dot_json;
use codex_login::login_with_api_key;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use super::clear_existing_auth_before_login;
use super::config_server_device_code_message;
use super::safe_format_key;
#[test]
fn config_server_device_code_prompt_shows_verification_url_and_code() {
let prompt = OAuthDeviceCodePrompt {
verification_uri: "https://login.example/device"
.parse()
.expect("valid verification URL"),
user_code: "ABCD-EFGH".into(),
};
insta::assert_snapshot!(config_server_device_code_message(&prompt), @"To sign in to the config server, open https://login.example/device and enter code ABCD-EFGH.");
}
#[tokio::test]
async fn clears_existing_auth_before_login() {
let codex_home = tempdir().expect("create temporary Codex home");
+38 -10
View File
@@ -11,16 +11,21 @@ use codex_http_client::HttpClientFactory;
use codex_login::AuthConfig;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::OAuthDeviceCodePrompt;
use codex_login::OAuthSessionManager;
use codex_protocol::account::PlanType;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::task::AbortHandle;
use tokio::task::JoinHandle;
const CONFIG_SERVER_LOGIN_FAILURE: &str =
"Config server sign-in failed. Check config_server.oauth and the credential store.";
pub fn managed_config_auth_manager(
auth: AuthConfig,
requirements: &ConfigRequirementsToml,
) -> std::io::Result<Option<codex_login::OAuthSessionManager>> {
) -> std::io::Result<Option<OAuthSessionManager>> {
let Some(service_config) = requirements.config_server.as_ref() else {
return Ok(None);
};
@@ -28,25 +33,48 @@ pub fn managed_config_auth_manager(
crate::config_server_auth_manager(service_config, auth.codex_home, &factory)
}
/// How to sign in when the config server has no saved OAuth grant.
pub enum ConfigServerLoginMethod {
Browser,
DeviceCode { present: fn(&OAuthDeviceCodePrompt) },
}
/// Existing grants are left to the loader's normal cache and refresh handling.
pub async fn ensure_config_server_login(
auth: AuthConfig,
requirements: &ConfigRequirementsToml,
method: ConfigServerLoginMethod,
) -> std::io::Result<()> {
let Some(manager) = managed_config_auth_manager(auth, requirements)? else {
return Ok(());
};
if let Err(error) = manager.authorization_id().await {
if error
.get_ref()
.and_then(|source| source.downcast_ref::<codex_login::OAuthSessionError>())
!= Some(&codex_login::OAuthSessionError::LoginRequired)
{
return Err(error);
ensure_config_server_login_with_manager(&manager, method).await
}
pub(crate) async fn ensure_config_server_login_with_manager(
manager: &OAuthSessionManager,
method: ConfigServerLoginMethod,
) -> std::io::Result<()> {
let Some(attempt) = manager.start_login_if_required().await? else {
return Ok(());
};
match method {
ConfigServerLoginMethod::Browser => attempt.login(CONFIG_SERVER_LOGIN_FAILURE).await,
ConfigServerLoginMethod::DeviceCode { present } => {
if manager.config().device_authorization_url.is_none() {
return Err(std::io::Error::other(
"Device sign-in requires config_server.oauth.device_authorization_url",
));
}
attempt
.login_with_device_code(
std::future::pending(),
present,
CONFIG_SERVER_LOGIN_FAILURE,
)
.await
}
manager.login().await?;
}
Ok(())
}
pub fn managed_config_bundle_loader(
@@ -1,6 +1,8 @@
#![cfg(test)]
use super::*;
use crate::ConfigServerLoginMethod;
use crate::bundle_loader::ensure_config_server_login_with_manager;
use crate::bundle_loader::managed_config_bundle_loader_for_service;
use crate::service::CLOUD_CONFIG_BUNDLE_TIMEOUT;
use crate::service::CloudConfigBundleService;
@@ -13,6 +15,7 @@ use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tempfile::tempdir;
use wiremock::Mock;
use wiremock::MockServer;
@@ -86,17 +89,64 @@ async fn a_supplied_chatgpt_token_does_not_replace_config_server_sign_in() {
assert!(server.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn device_endpoint_failure_points_to_config_server_oauth() {
let server = MockServer::start().await;
let home = tempdir().unwrap();
let oauth = OAuthSessionConfig {
device_authorization_url: Some(format!("{}/missing", server.uri())),
..oauth_config(&server.uri())
};
let manager = OAuthSessionManager::new(
oauth,
home.path().to_path_buf(),
transport_default_auth_route_config().http_client_factory(),
Arc::new(MockKeyringStore::default()),
)
.unwrap();
let error = ensure_config_server_login_with_manager(
&manager,
ConfigServerLoginMethod::DeviceCode {
present: |_| panic!("unexpected device code"),
},
)
.await
.unwrap_err();
assert_eq!(
error.to_string(),
"Config server sign-in failed. Check config_server.oauth and the credential store."
);
}
#[tokio::test]
async fn policy_fetch_uses_replacement_config_server_credentials() {
let server = MockServer::start().await;
let resource = "https://config.example/audience";
let resource_field = b"resource=https%3A%2F%2Fconfig.example%2Faudience";
Mock::given(method("POST"))
.and(path("/oauth/device"))
.and(form_has_field(resource_field))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"device_code": "device-code",
"user_code": "ABCD-EFGH",
"verification_uri": "https://login.example/device",
"expires_in": 60,
"interval": 1,
})))
.expect(1)
.mount(&server)
.await;
let sign_in = AtomicUsize::new(0);
Mock::given(path("/token"))
Mock::given(method("POST"))
.and(path("/token"))
.and(form_has_field(resource_field))
.respond_with(move |_: &wiremock::Request| {
ResponseTemplate::new(200).set_body_json(json!({
"access_token": format!("account-{}", sign_in.fetch_add(1, Ordering::Relaxed)),
"token_type": "Bearer", "expires_in": 3600,
}))
})
.expect(2)
.mount(&server)
.await;
let policies = ["never", "on-request"].map(|approval| {
@@ -116,7 +166,11 @@ async fn policy_fetch_uses_replacement_config_server_credentials() {
let factory = transport_default_auth_route_config()
.http_client_factory()
.clone();
let oauth = oauth_config(&server.uri());
let oauth = OAuthSessionConfig {
device_authorization_url: Some(format!("{}/oauth/device", server.uri())),
resource: Some(resource.into()),
..oauth_config(&server.uri())
};
let keyring = Arc::new(MockKeyringStore::default());
let manager = || {
OAuthSessionManager::new(
@@ -127,11 +181,17 @@ async fn policy_fetch_uses_replacement_config_server_credentials() {
)
.unwrap()
};
let gateway = manager();
gateway
.login_with_browser(std::future::pending(), complete_browser_authorization)
.await
.unwrap();
let auth = manager().without_interactive_login();
tokio::time::timeout(
Duration::from_secs(20),
ensure_config_server_login_with_manager(
&auth,
ConfigServerLoginMethod::DeviceCode { present: |_| {} },
),
)
.await
.expect("device sign-in should complete")
.unwrap();
let source = ConfigServerSource {
cache_namespace: "test".into(),
client: BackendClient::for_config_endpoint(
@@ -150,8 +210,7 @@ async fn policy_fetch_uses_replacement_config_server_credentials() {
Some(policies[0].clone())
);
gateway
.login_with_browser(std::future::pending(), complete_browser_authorization)
auth.login_with_browser(std::future::pending(), complete_browser_authorization)
.await
.unwrap();
// The old access token is still valid, so this must detect the changed grant.
@@ -159,6 +218,16 @@ async fn policy_fetch_uses_replacement_config_server_credentials() {
service.load_startup_bundle_with_timeout().await.unwrap(),
Some(policies[1].clone())
);
server.verify().await;
}
fn form_has_field(field: &'static [u8]) -> impl wiremock::Match {
move |request: &wiremock::Request| {
request
.body
.split(|byte| *byte == b'&')
.any(|pair| pair == field)
}
}
fn complete_browser_authorization(url: &wiremock::http::Url) {
+1
View File
@@ -13,6 +13,7 @@ mod metrics;
mod service;
mod validation;
pub use bundle_loader::ConfigServerLoginMethod;
pub use bundle_loader::chatgpt_config_bundle_loader;
pub use bundle_loader::chatgpt_config_bundle_loader_for_storage;
pub use bundle_loader::chatgpt_config_bundle_loader_for_storage_without_cache;
+1
View File
@@ -91,6 +91,7 @@ pub use oauth_session::OAuthSessionStatus as GatewayAuthStatus;
pub use oauth_session::OAuthSessionStatusChange as GatewayAuthStatusChange;
pub use oauth_session::subscribe_oauth_session_status as subscribe_gateway_auth_status;
pub use oauth_session::OAuthLoginAttempt;
pub use oauth_session::OAuthLoginControl;
pub use oauth_session::OAuthRequestCredentials;
pub use oauth_session::OAuthSessionConfig;
+10 -3
View File
@@ -46,6 +46,7 @@ pub(crate) struct DeviceAuthorizationOptions<'a> {
pub token_url: &'a str,
pub client_id: &'a str,
pub scopes: &'a [String],
pub resource: Option<&'a str>,
pub request_timeout: Duration,
}
@@ -55,7 +56,7 @@ pub(crate) enum DeviceAuthorizationError {
Expired,
#[error("Device authorization was denied; start sign-in again when ready")]
Denied,
#[error("The gateway returned an invalid device verification URL")]
#[error("The authorization server returned an invalid device verification URL")]
InvalidVerificationUrl,
#[error(transparent)]
Policy(NetworkPolicyDenied),
@@ -134,9 +135,12 @@ pub(crate) async fn authorize_device(
.map_err(network_policy_denial)
};
let device_permit = permit_for(oauth.device_authorization_url().url())?;
let request = oauth
let mut request = oauth
.exchange_device_code()
.add_scopes(options.scopes.iter().cloned().map(Scope::new));
if let Some(resource) = options.resource {
request = request.add_extra_param("resource", resource);
}
let authorization: StandardDeviceAuthorizationResponse = device_permit
.run(request.request_async(&http))
.await
@@ -157,7 +161,10 @@ pub(crate) async fn authorize_device(
verification_uri,
user_code: authorization.user_code().secret().clone(),
});
let poll = oauth.exchange_device_access_token(&authorization);
let mut poll = oauth.exchange_device_access_token(&authorization);
if let Some(resource) = options.resource {
poll = poll.add_extra_param("resource", resource);
}
token_permit
.run(poll.request_async(&http, tokio::time::sleep, /*timeout*/ None))
.await
+4 -4
View File
@@ -44,6 +44,7 @@ mod token;
pub use crate::oauth::OAuthDeviceCodePrompt;
pub use codex_model_provider_info::OAuthSessionConfig;
pub use login::OAuthLoginAttempt;
pub use login::OAuthLoginControl;
pub use login::OAuthSessionStatus;
pub use login::OAuthSessionStatusChange;
@@ -64,7 +65,7 @@ const HTTP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 20);
pub enum OAuthSessionError {
#[error("Gateway sign-in required. Choose Sign in or Reconnect, then retry your request")]
LoginRequired,
#[error("Gateway authentication is in progress; retry after sign-in")]
#[error("Another sign-in for this credential is in progress. Finish or cancel it, then retry.")]
LoginInProgress,
}
@@ -110,8 +111,6 @@ struct OAuthSessionState {
http_client: HttpClient,
http_client_factory: HttpClientFactory,
cached_token: Arc<Mutex<OAuthSessionCache>>,
// Reserve explicit login independently of background credential reads and refreshes.
login_attempt: Arc<Mutex<()>>,
status: tokio::sync::watch::Sender<Option<login::OAuthSessionStatusSnapshot>>,
status_tx: tokio::sync::broadcast::Sender<OAuthSessionStatusChange>,
}
@@ -159,7 +158,6 @@ impl OAuthSessionManager {
http_client,
http_client_factory: http_client_factory.clone(),
cached_token: Arc::new(Mutex::new(OAuthSessionCache::default())),
login_attempt: Arc::new(Mutex::new(())),
status: tokio::sync::watch::channel(/*init*/ None).0,
}),
})
@@ -238,6 +236,7 @@ impl OAuthSessionManager {
&& cached.token == cached.login_required
{
if self.interactive_login_allowed() {
let _attempt = self.try_start_login()?;
return self.authorize_with_browser(&mut cached, open_browser).await;
}
return Err(self.login_required_error(cached.token.as_ref()));
@@ -287,6 +286,7 @@ impl OAuthSessionManager {
== Some(&OAuthSessionError::LoginRequired)
}) && self.interactive_login_allowed()
{
let _attempt = self.try_start_login()?;
return self.authorize_with_browser(&mut cached, open_browser).await;
}
result
@@ -72,7 +72,7 @@ async fn device_login_rejects_an_insecure_verification_link_before_showing_the_c
.unwrap_err();
assert_eq!(
error.to_string(),
"The gateway returned an invalid device verification URL"
"The authorization server returned an invalid device verification URL"
);
}
@@ -137,10 +137,28 @@ async fn device_login_can_be_canceled_while_waiting_for_approval() {
.set_body_json(json!({"error": "authorization_pending"}))
.set_delay(Duration::from_secs(30));
let token_request = mount_device_code_grant(&server, pending).await;
let (client, home) = client(device_config(&server), Default::default());
let keyring = Arc::new(MockKeyringStore::default());
let (device, home) = client(device_config(&server), keyring.clone());
let browser = OAuthSessionManager::new(
config(&server),
home.path().to_path_buf(),
transport_default_auth_route_config().http_client_factory(),
keyring,
)
.unwrap();
let cancel = async {
token_request.wait_until_satisfied().await;
let error = browser
.login_with_browser(std::future::pending(), |_| {
panic!("unexpected browser prompt")
})
.await
.unwrap_err();
assert_eq!(
error.get_ref().and_then(|error| error.downcast_ref()),
Some(&crate::OAuthSessionError::LoginInProgress),
);
// Another Codex process can use the credential store while the user decides.
let _store = super::super::storage::lock_credentials(home.path())
.await
@@ -148,9 +166,15 @@ async fn device_login_can_be_canceled_while_waiting_for_approval() {
};
let result = tokio::time::timeout(
Duration::from_secs(15),
client.login_with_device_code(cancel, |_| {}),
device.login_with_device_code(cancel, |_| {}),
)
.await
.expect("cancel should finish while the issuer is still waiting");
assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Interrupted);
let cancel = tokio::sync::Notify::new();
let retry = browser
.login_with_browser(cancel.notified(), |_| cancel.notify_one())
.await;
assert_eq!(retry.unwrap_err().kind(), std::io::ErrorKind::Interrupted);
}
+74 -25
View File
@@ -12,11 +12,20 @@ use std::sync::atomic::Ordering;
use tokio::sync::OwnedMutexGuard;
use tokio::sync::broadcast;
const GATEWAY_LOGIN_FAILURE: &str =
"Gateway sign-in failed; check the gateway configuration and credential store.";
enum LoginMethod<B, D> {
Browser(B),
DeviceCode { endpoint: String, present: D },
}
/// Exclusive permission to start a sign-in for this credential across Codex processes.
pub struct OAuthLoginAttempt<'a> {
manager: &'a OAuthSessionManager,
_lock: std::fs::File,
}
/// Readiness and browser authorization progress for a gateway credential.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OAuthSessionStatus {
@@ -119,6 +128,26 @@ pub(super) fn status_sender_for_host(
}
impl OAuthSessionManager {
pub(super) fn try_start_login(&self) -> io::Result<OAuthLoginAttempt<'_>> {
Ok(OAuthLoginAttempt {
manager: self,
_lock: storage::try_lock_login(&self.state.codex_home, &self.credential_id())?,
})
}
/// Reuse a saved sign-in, or reserve a new one before releasing the store lock.
pub async fn start_login_if_required(&self) -> io::Result<Option<OAuthLoginAttempt<'_>>> {
let _store_lock = storage::lock_credentials(&self.state.codex_home).await?;
if self
.load_token_async()
.await?
.is_some_and(|token| token.authorization_id.is_some())
{
return Ok(None);
}
self.try_start_login().map(Some)
}
/// Identifies the persisted sign-in without refreshing an expired access token.
/// Refresh preserves this ID; explicit login creates a new one.
pub async fn authorization_id(&self) -> io::Result<String> {
@@ -135,8 +164,7 @@ impl OAuthSessionManager {
}
pub async fn login(&self) -> io::Result<()> {
self.login_with_browser(std::future::pending(), open_browser)
.await
self.try_start_login()?.login(GATEWAY_LOGIN_FAILURE).await
}
/// Removes the persisted grant and its in-memory copy without contacting the issuer.
@@ -328,9 +356,11 @@ impl OAuthSessionManager {
cancel: impl Future<Output = ()>,
open_browser: impl FnOnce(&Url),
) -> io::Result<()> {
let _attempt = self.try_start_login()?;
self.login_with_method(
cancel,
LoginMethod::<_, fn(&OAuthDeviceCodePrompt)>::Browser(open_browser),
GATEWAY_LOGIN_FAILURE,
)
.await
}
@@ -341,20 +371,9 @@ impl OAuthSessionManager {
cancel: impl Future<Output = ()>,
present: impl FnOnce(&OAuthDeviceCodePrompt),
) -> io::Result<()> {
let device_authorization_url = self.state.config.device_authorization_url.as_deref()
.ok_or_else(|| io::Error::other("The configured gateway does not specify gateway_oauth.device_authorization_url"))?;
validate_oauth_url(
device_authorization_url,
"provider OAuth device authorization endpoint",
)?;
self.login_with_method(
cancel,
LoginMethod::<fn(&Url), _>::DeviceCode {
endpoint: device_authorization_url.to_owned(),
present,
},
)
.await
self.try_start_login()?
.login_with_device_code(cancel, present, GATEWAY_LOGIN_FAILURE)
.await
}
async fn authorize_with_device_code(
@@ -372,6 +391,7 @@ impl OAuthSessionManager {
token_url: &config.token_url,
client_id: &config.client_id,
scopes: &config.scopes,
resource: config.resource.as_deref(),
request_timeout: HTTP_TIMEOUT,
},
present,
@@ -391,16 +411,9 @@ impl OAuthSessionManager {
&self,
cancel: impl Future<Output = ()>,
method: LoginMethod<impl FnOnce(&Url), impl FnOnce(&OAuthDeviceCodePrompt)>,
failure_message: &'static str,
) -> io::Result<()> {
validate_config(&self.state.config)?;
let _login_attempt = Arc::clone(&self.state.login_attempt)
.try_lock_owned()
.map_err(|_| {
io::Error::new(
io::ErrorKind::WouldBlock,
OAuthSessionError::LoginInProgress,
)
})?;
tokio::pin!(cancel);
let mut cached = tokio::select! {
biased;
@@ -437,7 +450,7 @@ impl OAuthSessionManager {
let message = if error.kind() == io::ErrorKind::Interrupted {
"Gateway sign-in was canceled"
} else {
"Gateway sign-in failed; check the gateway configuration and credential store."
failure_message
};
io::Error::new(error.kind(), message)
});
@@ -450,6 +463,42 @@ impl OAuthSessionManager {
}
}
impl OAuthLoginAttempt<'_> {
pub async fn login(self, failure_message: &'static str) -> io::Result<()> {
self.manager
.login_with_method(
std::future::pending(),
LoginMethod::<_, fn(&OAuthDeviceCodePrompt)>::Browser(open_browser),
failure_message,
)
.await
}
pub async fn login_with_device_code(
self,
cancel: impl Future<Output = ()>,
present: impl FnOnce(&OAuthDeviceCodePrompt),
failure_message: &'static str,
) -> io::Result<()> {
let device_authorization_url = self.manager.config().device_authorization_url.as_deref()
.ok_or_else(|| io::Error::other("The configured gateway does not specify gateway_oauth.device_authorization_url"))?;
validate_oauth_url(
device_authorization_url,
"provider OAuth device authorization endpoint",
)?;
self.manager
.login_with_method(
cancel,
LoginMethod::<fn(&Url), _>::DeviceCode {
endpoint: device_authorization_url.to_owned(),
present,
},
failure_message,
)
.await
}
}
struct LoginStatusGuard<'a> {
manager: &'a OAuthSessionManager,
credential: Option<StoredToken>,
+22 -6
View File
@@ -22,18 +22,34 @@ use codex_utils_path::write_atomically;
use super::StoredToken;
pub(super) async fn lock_credentials(codex_home: &Path) -> io::Result<File> {
fn open_lock_file(codex_home: &Path, name: &str) -> io::Result<File> {
let directory = codex_home.join("secrets");
std::fs::create_dir_all(&directory)?;
// Configurations have separate credential entries but rewrite the same store file.
// Keep one stable sidecar locked from the initial read through token exchange and save.
let path = directory.join("gateway_oauth.lock");
let file = OpenOptions::new()
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)?;
.open(directory.join(name))
}
// Hold this lock across user approval. Other credentials have independent sign-ins.
pub(super) fn try_lock_login(codex_home: &Path, credential_id: &str) -> io::Result<File> {
let name = secret_name(credential_id)?;
let file = open_lock_file(codex_home, &format!("{name}.login.lock"))?;
match file.try_lock() {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(io::Error::new(
io::ErrorKind::WouldBlock,
super::OAuthSessionError::LoginInProgress,
)),
Err(error) => Err(error.into()),
}
}
pub(super) async fn lock_credentials(codex_home: &Path) -> io::Result<File> {
// Configurations have separate credential entries but rewrite the same store file.
let file = open_lock_file(codex_home, "gateway_oauth.lock")?;
tokio::time::timeout(Duration::from_secs(/*secs*/ 60), async {
loop {
match file.try_lock() {
@@ -323,6 +323,7 @@ pub(super) async fn run_main_inner(
.bootstrap_config
.config_layer_stack
.requirements_toml(),
codex_cloud_config::ConfigServerLoginMethod::Browser,
)
.await?;
}