mirror of
https://github.com/openai/codex.git
synced 2026-11-17 22:10:37 +00:00
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:
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user