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
+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() {