[codex][device-stable-id][12/n] Send source stable ID with managed auth requests

This commit is contained in:
Riley Pinkerton
2026-06-18 07:04:07 +00:00
parent e7b6e0d859
commit 82008057b1
36 changed files with 358 additions and 40 deletions
+5
View File
@@ -1465,6 +1465,7 @@ mod tests {
request_id: RequestId::Integer(1),
params: codex_app_server_protocol::GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
},
})
.await
@@ -1523,6 +1524,7 @@ mod tests {
request_id: RequestId::Integer(1),
params: codex_app_server_protocol::GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
},
})
.await
@@ -1566,6 +1568,7 @@ mod tests {
request_id: RequestId::Integer(1),
params: codex_app_server_protocol::GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
},
})
.await
@@ -1696,6 +1699,7 @@ mod tests {
request_id: RequestId::Integer(1),
params: codex_app_server_protocol::GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
},
})
.await
@@ -1711,6 +1715,7 @@ mod tests {
request_id: RequestId::Integer(1),
params: codex_app_server_protocol::GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
},
})
.await
@@ -1227,6 +1227,13 @@
"refreshToken": {
"description": "When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.",
"type": "boolean"
},
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
}
},
"type": "object"
@@ -1442,6 +1449,13 @@
"codexStreamlinedLogin": {
"type": "boolean"
},
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"chatgpt"
@@ -1458,6 +1472,13 @@
},
{
"properties": {
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"chatgptDeviceCode"
@@ -10220,6 +10220,13 @@
"refreshToken": {
"description": "When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.",
"type": "boolean"
},
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
}
},
"title": "GetAccountParams",
@@ -11364,6 +11371,13 @@
"codexStreamlinedLogin": {
"type": "boolean"
},
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"chatgpt"
@@ -11380,6 +11394,13 @@
},
{
"properties": {
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"chatgptDeviceCode"
@@ -6616,6 +6616,13 @@
"refreshToken": {
"description": "When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.",
"type": "boolean"
},
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
}
},
"title": "GetAccountParams",
@@ -7809,6 +7816,13 @@
"codexStreamlinedLogin": {
"type": "boolean"
},
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"chatgpt"
@@ -7825,6 +7839,13 @@
},
{
"properties": {
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"chatgptDeviceCode"
@@ -4,6 +4,13 @@
"refreshToken": {
"description": "When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.",
"type": "boolean"
},
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
}
},
"title": "GetAccountParams",
@@ -26,6 +26,13 @@
"codexStreamlinedLogin": {
"type": "boolean"
},
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"chatgpt"
@@ -42,6 +49,13 @@
},
{
"properties": {
"sourceSurfaceStableId": {
"default": null,
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"chatgptDeviceCode"
@@ -10,4 +10,4 @@ export type GetAccountParams = {
* external auth mode this flag is ignored. Clients should refresh tokens
* themselves and call `account/login/start` with `chatgptAuthTokens`.
*/
refreshToken?: boolean, };
refreshToken?: boolean, sourceSurfaceStableId?: string | null, };
@@ -2,7 +2,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type LoginAccountParams = { "type": "apiKey", apiKey: string, } | { "type": "chatgpt", codexStreamlinedLogin?: boolean, } | { "type": "chatgptDeviceCode" } | { "type": "chatgptAuthTokens",
export type LoginAccountParams = { "type": "apiKey", apiKey: string, } | { "type": "chatgpt", codexStreamlinedLogin?: boolean, sourceSurfaceStableId?: string | null, } | { "type": "chatgptDeviceCode", sourceSurfaceStableId?: string | null, } | { "type": "chatgptAuthTokens",
/**
* Access token (JWT) supplied by the client.
* This token is used for backend API requests and email extraction.
@@ -1924,6 +1924,7 @@ mod tests {
request_id: request_id(),
params: v2::GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
},
};
assert_eq!(
@@ -2624,6 +2625,7 @@ mod tests {
request_id: RequestId::Integer(3),
params: v2::LoginAccountParams::Chatgpt {
codex_streamlined_login: false,
source_surface_stable_id: None,
},
};
assert_eq!(
@@ -2631,7 +2633,8 @@ mod tests {
"method": "account/login/start",
"id": 3,
"params": {
"type": "chatgpt"
"type": "chatgpt",
"sourceSurfaceStableId": null
}
}),
serde_json::to_value(&request)?,
@@ -2645,6 +2648,7 @@ mod tests {
request_id: RequestId::Integer(3),
params: v2::LoginAccountParams::Chatgpt {
codex_streamlined_login: true,
source_surface_stable_id: None,
},
};
assert_eq!(
@@ -2653,7 +2657,8 @@ mod tests {
"id": 3,
"params": {
"type": "chatgpt",
"codexStreamlinedLogin": true
"codexStreamlinedLogin": true,
"sourceSurfaceStableId": null
}
}),
serde_json::to_value(&request)?,
@@ -2665,14 +2670,17 @@ mod tests {
fn serialize_account_login_chatgpt_device_code() -> Result<()> {
let request = ClientRequest::LoginAccount {
request_id: RequestId::Integer(4),
params: v2::LoginAccountParams::ChatgptDeviceCode,
params: v2::LoginAccountParams::ChatgptDeviceCode {
source_surface_stable_id: None,
},
};
assert_eq!(
json!({
"method": "account/login/start",
"id": 4,
"params": {
"type": "chatgptDeviceCode"
"type": "chatgptDeviceCode",
"sourceSurfaceStableId": null
}
}),
serde_json::to_value(&request)?,
@@ -2728,13 +2736,16 @@ mod tests {
request_id: RequestId::Integer(6),
params: v2::GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
},
};
assert_eq!(
json!({
"method": "account/read",
"id": 6,
"params": {}
"params": {
"sourceSurfaceStableId": null
}
}),
serde_json::to_value(&request)?,
);
@@ -2742,6 +2753,7 @@ mod tests {
request_id: RequestId::Integer(7),
params: v2::GetAccountParams {
refresh_token: true,
source_surface_stable_id: None,
},
};
assert_eq!(
@@ -2749,7 +2761,8 @@ mod tests {
"method": "account/read",
"id": 7,
"params": {
"refreshToken": true
"refreshToken": true,
"sourceSurfaceStableId": null
}
}),
serde_json::to_value(&request)?,
@@ -68,10 +68,17 @@ pub enum LoginAccountParams {
Chatgpt {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
codex_streamlined_login: bool,
#[serde(default)]
#[ts(optional = nullable)]
source_surface_stable_id: Option<String>,
},
#[serde(rename = "chatgptDeviceCode", rename_all = "camelCase")]
#[ts(rename = "chatgptDeviceCode", rename_all = "camelCase")]
ChatgptDeviceCode {
#[serde(default)]
#[ts(optional = nullable)]
source_surface_stable_id: Option<String>,
},
#[serde(rename = "chatgptDeviceCode")]
#[ts(rename = "chatgptDeviceCode")]
ChatgptDeviceCode,
/// [UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE.
/// The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.
#[experimental("account/login/start.chatgptAuthTokens")]
@@ -374,6 +381,9 @@ pub struct GetAccountParams {
/// themselves and call `account/login/start` with `chatgptAuthTokens`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub refresh_token: bool,
#[serde(default)]
#[ts(optional = nullable)]
pub source_surface_stable_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
+4 -1
View File
@@ -1720,6 +1720,7 @@ impl CodexClient {
request_id: request_id.clone(),
params: codex_app_server_protocol::LoginAccountParams::Chatgpt {
codex_streamlined_login: false,
source_surface_stable_id: None,
},
};
@@ -1730,7 +1731,9 @@ impl CodexClient {
let request_id = self.request_id();
let request = ClientRequest::LoginAccount {
request_id: request_id.clone(),
params: codex_app_server_protocol::LoginAccountParams::ChatgptDeviceCode,
params: codex_app_server_protocol::LoginAccountParams::ChatgptDeviceCode {
source_surface_stable_id: None,
},
};
self.send_request(request, request_id, "account/login/start")
+3
View File
@@ -1881,6 +1881,8 @@ Codex supports these authentication modes. The current mode is surfaced in `acco
- **ChatGPT managed (`chatgpt`)** (recommended): Codex owns the ChatGPT OAuth flow and refresh tokens. Start via `account/login/start` with `type: "chatgpt"` for the browser flow or `type: "chatgptDeviceCode"` for device code; Codex persists tokens to disk and refreshes them automatically.
- **Personal access token (`personalAccessToken`)**: Codex uses a ChatGPT-backed personal access token loaded outside the app-server login RPCs, such as with `codex login --with-access-token` or `CODEX_ACCESS_TOKEN`.
Single-client stdio clients may include `sourceSurfaceStableId` on `account/login/start` and `account/read`. Codex forwards the current value on authorize, code-exchange, and refresh requests. Remote-control connections to that process inherit the value but cannot replace it; standalone shared and in-process transports use Codex's installation ID instead. The value is optional experiment-analysis context and does not affect authentication decisions.
### API Overview
- `account/read` — fetch current account info; optionally refresh tokens.
@@ -1919,6 +1921,7 @@ Response examples:
Field notes:
- `refreshToken` (bool): set `true` to force a token refresh.
- `sourceSurfaceStableId` (string, optional): updates the value Codex forwards on later managed-auth requests. Send the same value on `account/login/start` so the authorize and code-exchange requests match.
- `requiresOpenaiAuth` reflects the active provider; when `false`, Codex can run without OpenAI credentials.
- Amazon Bedrock reports `credentialSource: "codexManaged"` when it uses a Bedrock API key managed by Codex. Otherwise it reports `credentialSource: "awsManaged"` for the external AWS credential path. This identifies the selected credential source; it does not validate that the AWS credential chain can resolve credentials.
+3 -1
View File
@@ -64,6 +64,7 @@ use crate::outgoing_message::OutgoingMessage;
use crate::outgoing_message::OutgoingMessageSender;
use crate::outgoing_message::QueuedOutgoingMessage;
use crate::transport::CHANNEL_CAPACITY;
use crate::transport::ConnectionOrigin;
use crate::transport::OutboundConnectionState;
use crate::transport::route_outgoing_envelope;
use codex_analytics::AppServerRpcTransport;
@@ -382,6 +383,7 @@ async fn start_uninitialized(args: InProcessStartArgs) -> IoResult<InProcessClie
let auth_manager =
AuthManager::shared_from_config(args.config.as_ref(), args.enable_codex_api_key_env)
.await;
auth_manager.set_source_surface_stable_id(Some(installation_id.clone()));
let analytics_events_client =
analytics_events_client_from_config(Arc::clone(&auth_manager), args.config.as_ref());
let outgoing_message_sender = Arc::new(OutgoingMessageSender::new(
@@ -442,7 +444,7 @@ async fn start_uninitialized(args: InProcessStartArgs) -> IoResult<InProcessClie
plugin_startup_tasks: crate::PluginStartupTasks::Start,
}));
let mut thread_created_rx = processor.thread_created_receiver();
let session = Arc::new(ConnectionSessionState::new());
let session = Arc::new(ConnectionSessionState::new(ConnectionOrigin::InProcess));
let mut listen_for_threads = true;
loop {
+3
View File
@@ -750,6 +750,9 @@ pub async fn run_main_with_transport_options(
let auth_manager =
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await;
if !single_client_mode {
auth_manager.set_source_surface_stable_id(Some(installation_id.clone()));
}
let remote_control_enabled = remote_control_policy == RemoteControlPolicy::Allowed
&& remote_control_explicitly_requested
+15 -9
View File
@@ -46,6 +46,7 @@ use crate::skills_watcher::SkillsWatcher;
use crate::thread_state::ConnectionCapabilities;
use crate::thread_state::ThreadStateManager;
use crate::transport::AppServerTransport;
use crate::transport::ConnectionOrigin;
use crate::transport::RemoteControlHandle;
use codex_analytics::AnalyticsEventsClient;
use codex_analytics::AppServerRpcTransport;
@@ -213,6 +214,7 @@ pub(crate) struct MessageProcessor {
#[derive(Debug)]
pub(crate) struct ConnectionSessionState {
pub(crate) rpc_gate: Arc<ConnectionRpcGate>,
origin: ConnectionOrigin,
initialized: OnceLock<InitializedConnectionSessionState>,
}
@@ -225,16 +227,11 @@ pub(crate) struct InitializedConnectionSessionState {
pub(crate) request_attestation: bool,
}
impl Default for ConnectionSessionState {
fn default() -> Self {
Self::new()
}
}
impl ConnectionSessionState {
pub(crate) fn new() -> Self {
pub(crate) fn new(origin: ConnectionOrigin) -> Self {
Self {
rpc_gate: Arc::new(ConnectionRpcGate::new()),
origin,
initialized: OnceLock::new(),
}
}
@@ -884,6 +881,7 @@ impl MessageProcessor {
let serialization_scope = codex_request.serialization_scope();
let app_server_client_name = session.app_server_client_name().map(str::to_string);
let client_version = session.client_version().map(str::to_string);
let accepts_client_source_surface_stable_id = session.origin == ConnectionOrigin::Stdio;
let error_request_id = connection_request_id.clone();
let rpc_gate = Arc::clone(&session.rpc_gate);
let processor = Arc::clone(self);
@@ -899,6 +897,7 @@ impl MessageProcessor {
request_context,
app_server_client_name,
client_version,
accepts_client_source_surface_stable_id,
)
.await;
if let Err(error) = result {
@@ -928,6 +927,7 @@ impl MessageProcessor {
request_context: RequestContext,
app_server_client_name: Option<String>,
client_version: Option<String>,
accepts_client_source_surface_stable_id: bool,
) -> Result<(), JSONRPCErrorError> {
let connection_id = connection_request_id.connection_id;
let request_id = ConnectionRequestId {
@@ -1378,7 +1378,11 @@ impl MessageProcessor {
}
ClientRequest::LoginAccount { params, .. } => {
self.account_processor
.login_account(request_id.clone(), params)
.login_account(
request_id.clone(),
params,
accepts_client_source_surface_stable_id,
)
.await
}
ClientRequest::LogoutAccount { .. } => {
@@ -1390,7 +1394,9 @@ impl MessageProcessor {
self.account_processor.cancel_login_account(params).await
}
ClientRequest::GetAccount { params, .. } => {
self.account_processor.get_account(params).await
self.account_processor
.get_account(params, accepts_client_source_surface_stable_id)
.await
}
ClientRequest::GetAuthStatus { params, .. } => {
self.account_processor.get_auth_status(params).await
@@ -6,6 +6,7 @@ use crate::config_manager::ConfigManager;
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::OutgoingMessageSender;
use crate::transport::AppServerTransport;
use crate::transport::ConnectionOrigin;
use anyhow::Result;
use app_test_support::create_mock_responses_server_repeating_assistant;
use app_test_support::write_mock_responses_config_toml;
@@ -128,7 +129,7 @@ impl TracingHarness {
_codex_home: codex_home,
processor,
outgoing_rx,
session: Arc::new(ConnectionSessionState::new()),
session: Arc::new(ConnectionSessionState::new(ConnectionOrigin::WebSocket)),
tracing,
};
@@ -88,7 +88,23 @@ impl AccountRequestProcessor {
&self,
request_id: ConnectionRequestId,
params: LoginAccountParams,
accepts_client_source_surface_stable_id: bool,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let source_surface_stable_id = match &params {
LoginAccountParams::Chatgpt {
source_surface_stable_id,
..
}
| LoginAccountParams::ChatgptDeviceCode {
source_surface_stable_id,
} => source_surface_stable_id.clone(),
_ => None,
};
self.set_client_source_surface_stable_id(
accepts_client_source_surface_stable_id,
source_surface_stable_id,
);
self.login_v2(request_id, params).await.map(|()| None)
}
@@ -111,7 +127,13 @@ impl AccountRequestProcessor {
pub(crate) async fn get_account(
&self,
params: GetAccountParams,
accepts_client_source_surface_stable_id: bool,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.set_client_source_surface_stable_id(
accepts_client_source_surface_stable_id,
params.source_surface_stable_id.clone(),
);
self.get_account_response(params)
.await
.map(|response| Some(response.into()))
@@ -239,11 +261,12 @@ impl AccountRequestProcessor {
}
LoginAccountParams::Chatgpt {
codex_streamlined_login,
..
} => {
self.login_chatgpt_v2(request_id, codex_streamlined_login)
.await;
}
LoginAccountParams::ChatgptDeviceCode => {
LoginAccountParams::ChatgptDeviceCode { .. } => {
self.login_chatgpt_device_code_v2(request_id).await;
}
LoginAccountParams::ChatgptAuthTokens {
@@ -342,6 +365,7 @@ impl AccountRequestProcessor {
let opts = LoginServerOptions {
open_browser: false,
codex_streamlined_login,
source_surface_stable_id: self.auth_manager.source_surface_stable_id(),
..LoginServerOptions::new(
config.codex_home.to_path_buf(),
oauth_client_id(),
@@ -364,6 +388,16 @@ impl AccountRequestProcessor {
Ok(opts)
}
fn set_client_source_surface_stable_id(
&self,
accepts_client_source_surface_stable_id: bool,
value: Option<String>,
) {
if accepts_client_source_surface_stable_id && let Some(value) = value {
self.auth_manager.set_source_surface_stable_id(Some(value));
}
}
fn login_chatgpt_device_code_start_error(err: IoError) -> JSONRPCErrorError {
let is_not_found = err.kind() == std::io::ErrorKind::NotFound;
if is_not_found {
+2 -2
View File
@@ -45,7 +45,7 @@ pub(crate) struct ConnectionState {
impl ConnectionState {
pub(crate) fn new(
_origin: ConnectionOrigin,
origin: ConnectionOrigin,
outbound_initialized: Arc<AtomicBool>,
outbound_experimental_api_enabled: Arc<AtomicBool>,
outbound_opted_out_notification_methods: Arc<RwLock<HashSet<String>>>,
@@ -54,7 +54,7 @@ impl ConnectionState {
outbound_initialized,
outbound_experimental_api_enabled,
outbound_opted_out_notification_methods,
session: Arc::new(ConnectionSessionState::new()),
session: Arc::new(ConnectionSessionState::new(origin)),
}
}
}
@@ -1260,8 +1260,19 @@ impl TestAppServer {
/// Send an `account/login/start` JSON-RPC request for ChatGPT login.
pub async fn send_login_account_chatgpt_request(&mut self) -> anyhow::Result<i64> {
self.send_login_account_chatgpt_request_with_source_surface_stable_id(
/*source_surface_stable_id*/ None,
)
.await
}
pub async fn send_login_account_chatgpt_request_with_source_surface_stable_id(
&mut self,
source_surface_stable_id: Option<&str>,
) -> anyhow::Result<i64> {
let params = serde_json::json!({
"type": "chatgpt"
"type": "chatgpt",
"sourceSurfaceStableId": source_surface_stable_id,
});
self.send_request("account/login/start", Some(params)).await
}
+26 -1
View File
@@ -241,6 +241,7 @@ async fn logout_account_removes_auth_and_notifies() -> Result<()> {
let get_id = mcp
.send_get_account_request(GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
})
.await?;
let get_resp: JSONRPCResponse = timeout(
@@ -308,6 +309,7 @@ async fn set_auth_token_updates_account_and_notifies() -> Result<()> {
let get_id = mcp
.send_get_account_request(GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
})
.await?;
let get_resp: JSONRPCResponse = timeout(
@@ -376,6 +378,7 @@ async fn account_read_refresh_token_is_noop_in_external_mode() -> Result<()> {
let get_id = mcp
.send_get_account_request(GetAccountParams {
refresh_token: true,
source_surface_stable_id: None,
})
.await?;
let get_resp: JSONRPCResponse = timeout(
@@ -1521,7 +1524,11 @@ async fn login_account_chatgpt_includes_forced_workspace_query_param() -> Result
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp.send_login_account_chatgpt_request().await?;
let request_id = mcp
.send_login_account_chatgpt_request_with_source_surface_stable_id(Some(
"codex-source-stable-id",
))
.await?;
let resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
@@ -1536,6 +1543,16 @@ async fn login_account_chatgpt_includes_forced_workspace_query_param() -> Result
auth_url.contains(&format!("allowed_workspace_id={WORKSPACE_ID_ALLOWED}")),
"auth URL should include forced workspace"
);
let auth_url = Url::parse(&auth_url)?;
let query = auth_url
.query_pairs()
.collect::<std::collections::HashMap<_, _>>();
assert_eq!(
query
.get("source_surface_stable_id")
.map(std::convert::AsRef::as_ref),
Some("codex-source-stable-id")
);
Ok(())
}
@@ -1600,6 +1617,7 @@ async fn get_account_no_auth() -> Result<()> {
let params = GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
};
let request_id = mcp.send_get_account_request(params).await?;
@@ -1641,6 +1659,7 @@ async fn get_account_with_api_key() -> Result<()> {
let params = GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
};
let request_id = mcp.send_get_account_request(params).await?;
@@ -1675,6 +1694,7 @@ async fn get_account_when_auth_not_required() -> Result<()> {
let params = GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
};
let request_id = mcp.send_get_account_request(params).await?;
@@ -1716,6 +1736,7 @@ region = "us-west-2"
let params = GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
};
let request_id = mcp.send_get_account_request(params).await?;
@@ -1760,6 +1781,7 @@ async fn get_account_with_managed_bedrock_provider() -> Result<()> {
let request_id = mcp
.send_get_account_request(GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
})
.await?;
let resp: JSONRPCResponse = timeout(
@@ -1805,6 +1827,7 @@ async fn get_account_with_chatgpt() -> Result<()> {
let params = GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
};
let request_id = mcp.send_get_account_request(params).await?;
@@ -1889,6 +1912,7 @@ async fn get_account_omits_chatgpt_after_permanent_refresh_failure() -> Result<(
let request_id = mcp
.send_get_account_request(GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
})
.await?;
@@ -1932,6 +1956,7 @@ async fn get_account_with_chatgpt_missing_plan_claim_returns_unknown() -> Result
let params = GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
};
let request_id = mcp.send_get_account_request(params).await?;
@@ -190,6 +190,7 @@ async fn consume_timeout_releases_account_auth_queue() -> Result<()> {
let account_id = mcp
.send_get_account_request(GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
})
.await?;
+1
View File
@@ -13,6 +13,7 @@ pub use debug_sandbox::run_command_under_seatbelt;
pub use debug_sandbox::run_command_under_windows_sandbox;
pub use login::read_access_token_from_stdin;
pub use login::read_api_key_from_stdin;
pub use login::resolve_cli_source_surface_stable_id;
pub use login::run_login_status;
pub use login::run_login_with_access_token;
pub use login::run_login_with_api_key;
+20 -1
View File
@@ -10,6 +10,7 @@
use codex_app_server_protocol::AuthMode;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::Config;
use codex_core::resolve_installation_id;
use codex_login::AuthKeyringBackendKind;
use codex_login::CLIENT_ID;
use codex_login::CodexAuth;
@@ -136,6 +137,7 @@ pub async fn login_with_chatgpt(
forced_chatgpt_workspace_id: Option<Vec<String>>,
cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
auth_keyring_backend_kind: AuthKeyringBackendKind,
source_surface_stable_id: Option<String>,
) -> std::io::Result<()> {
clear_existing_auth_before_login(
&codex_home,
@@ -144,13 +146,14 @@ pub async fn login_with_chatgpt(
)
.await;
let opts = ServerOptions::new(
let mut opts = ServerOptions::new(
codex_home,
CLIENT_ID.to_string(),
forced_chatgpt_workspace_id,
cli_auth_credentials_store_mode,
auth_keyring_backend_kind,
);
opts.source_surface_stable_id = source_surface_stable_id;
let server = run_login_server(opts)?;
print_login_server_start(server.actual_port, &server.auth_url);
@@ -169,12 +172,14 @@ pub async fn run_login_with_chatgpt(cli_config_overrides: CliConfigOverrides) ->
}
let forced_chatgpt_workspace_id = config.forced_chatgpt_workspace_id.clone();
let source_surface_stable_id = resolve_cli_source_surface_stable_id(&config).await;
match login_with_chatgpt(
config.codex_home.to_path_buf(),
forced_chatgpt_workspace_id,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
source_surface_stable_id,
)
.await
{
@@ -307,6 +312,7 @@ pub async fn run_login_with_device_code(
eprintln!("{CHATGPT_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let source_surface_stable_id = resolve_cli_source_surface_stable_id(&config).await;
clear_existing_auth_before_login(
&config.codex_home,
config.cli_auth_credentials_store_mode,
@@ -321,6 +327,7 @@ pub async fn run_login_with_device_code(
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
);
opts.source_surface_stable_id = source_surface_stable_id;
if let Some(iss) = issuer_base_url {
opts.issuer = iss;
}
@@ -352,6 +359,7 @@ pub async fn run_login_with_device_code_fallback_to_browser(
eprintln!("{CHATGPT_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let source_surface_stable_id = resolve_cli_source_surface_stable_id(&config).await;
clear_existing_auth_before_login(
&config.codex_home,
config.cli_auth_credentials_store_mode,
@@ -367,6 +375,7 @@ pub async fn run_login_with_device_code_fallback_to_browser(
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
);
opts.source_surface_stable_id = source_surface_stable_id;
if let Some(iss) = issuer_base_url {
opts.issuer = iss;
}
@@ -482,6 +491,16 @@ pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
}
}
pub async fn resolve_cli_source_surface_stable_id(config: &Config) -> Option<String> {
match resolve_installation_id(&config.codex_home).await {
Ok(installation_id) => Some(installation_id),
Err(err) => {
tracing::warn!("failed to resolve installation ID for auth request: {err}");
None
}
}
}
async fn load_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
let cli_overrides = match cli_config_overrides.parse_overrides() {
Ok(v) => v,
+2
View File
@@ -12,6 +12,7 @@ use codex_chatgpt::apply_command::ApplyCommand;
use codex_chatgpt::apply_command::run_apply_command;
use codex_cli::read_access_token_from_stdin;
use codex_cli::read_api_key_from_stdin;
use codex_cli::resolve_cli_source_surface_stable_id;
use codex_cli::run_login_status;
use codex_cli::run_login_with_access_token;
use codex_cli::run_login_with_api_key;
@@ -1817,6 +1818,7 @@ async fn load_exec_server_remote_auth(
) -> anyhow::Result<codex_login::CodexAuth> {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ true).await;
auth_manager.set_source_surface_stable_id(resolve_cli_source_surface_stable_id(config).await);
let auth = match auth_manager.auth().await {
Some(auth) => auth,
+9
View File
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::path::Path;
use anyhow::Context;
@@ -169,6 +170,14 @@ async fn device_login_revokes_existing_auth_before_requesting_new_tokens() -> Re
"client_id": CLIENT_ID,
})
);
let token_exchange = url::form_urlencoded::parse(&requests[3].body).collect::<HashMap<_, _>>();
let installation_id = std::fs::read_to_string(codex_home.path().join("installation_id"))?;
assert_eq!(
token_exchange
.get("source_surface_stable_id")
.map(std::convert::AsRef::as_ref),
Some(installation_id.trim())
);
let auth = read_auth_json(codex_home.path())?;
assert_eq!(auth["tokens"]["refresh_token"], "new-refresh");
@@ -5,6 +5,7 @@ use codex_config::CloudConfigBundleLoadError;
use codex_config::CloudConfigBundleLoadErrorCode;
use codex_config::CloudConfigBundleLoader;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::resolve_installation_id;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use std::path::PathBuf;
@@ -67,5 +68,10 @@ pub async fn cloud_config_bundle_loader_for_storage(
keyring_backend_kind,
)
.await;
if let Ok(codex_home) = codex_home.clone().try_into()
&& let Ok(installation_id) = resolve_installation_id(&codex_home).await
{
auth_manager.set_source_surface_stable_id(Some(installation_id));
}
cloud_config_bundle_loader(auth_manager, chatgpt_base_url, codex_home)
}
+29 -1
View File
@@ -1057,11 +1057,13 @@ fn persist_tokens(
async fn request_chatgpt_token_refresh(
refresh_token: String,
client: &CodexHttpClient,
source_surface_stable_id: Option<String>,
) -> Result<RefreshResponse, RefreshTokenError> {
let refresh_request = RefreshRequest {
client_id: oauth_client_id(),
grant_type: "refresh_token",
refresh_token,
source_surface_stable_id,
};
let endpoint = refresh_token_endpoint();
@@ -1157,6 +1159,8 @@ struct RefreshRequest {
client_id: String,
grant_type: &'static str,
refresh_token: String,
#[serde(skip_serializing_if = "Option::is_none")]
source_surface_stable_id: Option<String>,
}
#[derive(Deserialize, Clone)]
@@ -1526,6 +1530,7 @@ pub struct AuthManager {
chatgpt_base_url: Option<String>,
refresh_lock: Semaphore,
external_auth: RwLock<Option<Arc<dyn ExternalAuth>>>,
source_surface_stable_id: RwLock<Option<String>>,
}
/// Configuration view required to construct a shared [`AuthManager`].
@@ -1630,6 +1635,7 @@ impl AuthManager {
chatgpt_base_url,
refresh_lock: Semaphore::new(/*permits*/ 1),
external_auth: RwLock::new(None),
source_surface_stable_id: RwLock::new(None),
}
}
@@ -1652,6 +1658,7 @@ impl AuthManager {
chatgpt_base_url: None,
refresh_lock: Semaphore::new(/*permits*/ 1),
external_auth: RwLock::new(None),
source_surface_stable_id: RwLock::new(None),
})
}
@@ -1673,6 +1680,7 @@ impl AuthManager {
chatgpt_base_url: None,
refresh_lock: Semaphore::new(/*permits*/ 1),
external_auth: RwLock::new(None),
source_surface_stable_id: RwLock::new(None),
})
}
@@ -1694,6 +1702,7 @@ impl AuthManager {
external_auth: RwLock::new(Some(
Arc::new(BearerTokenRefresher::new(config)) as Arc<dyn ExternalAuth>
)),
source_surface_stable_id: RwLock::new(None),
})
}
@@ -1906,6 +1915,20 @@ impl AuthManager {
self.enable_codex_api_key_env
}
pub fn source_surface_stable_id(&self) -> Option<String> {
self.source_surface_stable_id
.read()
.map(|value| value.clone())
.unwrap_or_default()
}
pub fn set_source_surface_stable_id(&self, value: Option<String>) {
let value = crate::valid_source_surface_stable_id(value.as_deref()).map(str::to_owned);
if let Ok(mut current) = self.source_surface_stable_id.write() {
*current = value;
}
}
/// Convenience constructor returning an `Arc` wrapper.
pub async fn shared(
codex_home: PathBuf,
@@ -2210,7 +2233,12 @@ impl AuthManager {
auth: &ChatgptAuth,
refresh_token: String,
) -> Result<(), RefreshTokenError> {
let refresh_response = request_chatgpt_token_refresh(refresh_token, auth.client()).await?;
let refresh_response = request_chatgpt_token_refresh(
refresh_token,
auth.client(),
self.source_surface_stable_id(),
)
.await?;
persist_tokens(
auth.storage(),
+1
View File
@@ -199,6 +199,7 @@ pub async fn complete_device_code_login(
&redirect_uri,
&pkce,
&code_resp.authorization_code,
opts.source_surface_stable_id.as_deref(),
)
.await
.map_err(|err| std::io::Error::other(format!("device code exchange failed: {err}")))?;
+8
View File
@@ -6,6 +6,14 @@ mod device_code_auth;
mod pkce;
mod server;
const SOURCE_SURFACE_STABLE_ID_MAX_LENGTH: usize = 128;
fn valid_source_surface_stable_id(value: Option<&str>) -> Option<&str> {
value.filter(|value| {
!value.trim().is_empty() && value.len() <= SOURCE_SURFACE_STABLE_ID_MAX_LENGTH
})
}
pub use codex_client::BuildCustomCaTransportError as BuildLoginHttpClientError;
pub use codex_config::types::AuthCredentialsStoreMode;
pub use device_code_auth::DeviceCode;
+36 -9
View File
@@ -71,6 +71,7 @@ pub struct ServerOptions {
pub codex_streamlined_login: bool,
pub cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
pub auth_keyring_backend_kind: AuthKeyringBackendKind,
pub source_surface_stable_id: Option<String>,
}
impl ServerOptions {
@@ -93,6 +94,7 @@ impl ServerOptions {
codex_streamlined_login: false,
cli_auth_credentials_store_mode,
auth_keyring_backend_kind,
source_surface_stable_id: None,
}
}
}
@@ -162,6 +164,7 @@ pub fn run_login_server(opts: ServerOptions) -> io::Result<LoginServer> {
&pkce,
&state,
opts.forced_chatgpt_workspace_id.as_deref(),
opts.source_surface_stable_id.as_deref(),
);
if opts.open_browser {
@@ -336,8 +339,15 @@ async fn process_request(
}
};
match exchange_code_for_tokens(&opts.issuer, &opts.client_id, redirect_uri, pkce, &code)
.await
match exchange_code_for_tokens(
&opts.issuer,
&opts.client_id,
redirect_uri,
pkce,
&code,
opts.source_surface_stable_id.as_deref(),
)
.await
{
Ok(tokens) => {
if let Err(message) = ensure_workspace_allowed(
@@ -489,6 +499,7 @@ fn build_authorize_url(
pkce: &PkceCodes,
state: &str,
forced_chatgpt_workspace_ids: Option<&[String]>,
source_surface_stable_id: Option<&str>,
) -> String {
let mut query = vec![
("response_type".to_string(), "code".to_string()),
@@ -512,6 +523,14 @@ fn build_authorize_url(
if let Some(workspace_ids) = forced_chatgpt_workspace_ids {
query.push(("allowed_workspace_id".to_string(), workspace_ids.join(",")));
}
if let Some(source_surface_stable_id) =
crate::valid_source_surface_stable_id(source_surface_stable_id)
{
query.push((
"source_surface_stable_id".to_string(),
source_surface_stable_id.to_string(),
));
}
let qs = query
.into_iter()
.map(|(k, v)| format!("{k}={}", urlencoding::encode(&v)))
@@ -719,6 +738,7 @@ pub(crate) async fn exchange_code_for_tokens(
redirect_uri: &str,
pkce: &PkceCodes,
code: &str,
source_surface_stable_id: Option<&str>,
) -> io::Result<ExchangedTokens> {
#[derive(serde::Deserialize)]
struct TokenResponse {
@@ -735,16 +755,23 @@ pub(crate) async fn exchange_code_for_tokens(
redirect_uri = %redirect_uri,
"starting oauth token exchange"
);
let mut body = format!(
"grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&code_verifier={}",
urlencoding::encode(code),
urlencoding::encode(redirect_uri),
urlencoding::encode(client_id),
urlencoding::encode(&pkce.code_verifier)
);
if let Some(source_surface_stable_id) =
crate::valid_source_surface_stable_id(source_surface_stable_id)
{
body.push_str("&source_surface_stable_id=");
body.push_str(&urlencoding::encode(source_surface_stable_id));
}
let resp = client
.post(token_endpoint)
.header("Content-Type", "application/x-www-form-urlencoded")
.body(format!(
"grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&code_verifier={}",
urlencoding::encode(code),
urlencoding::encode(redirect_uri),
urlencoding::encode(client_id),
urlencoding::encode(&pkce.code_verifier)
))
.body(body)
.send()
.await;
let resp = match resp {
@@ -62,6 +62,8 @@ async fn refresh_token_succeeds_updates_storage() -> Result<()> {
bedrock_api_key: None,
};
ctx.write_auth(&initial_auth).await?;
ctx.auth_manager
.set_source_surface_stable_id(Some("codex-source-stable-id".to_string()));
ctx.auth_manager
.refresh_token_from_authority()
@@ -75,6 +77,7 @@ async fn refresh_token_succeeds_updates_storage() -> Result<()> {
"client_id": "staging-client",
"grant_type": "refresh_token",
"refresh_token": INITIAL_REFRESH_TOKEN,
"source_surface_stable_id": "codex-source-stable-id",
})
);
@@ -130,6 +130,7 @@ async fn end_to_end_login_flow_persists_auth_json() -> Result<()> {
forced_chatgpt_workspace_id: Some(vec![chatgpt_account_id.to_string()]),
codex_streamlined_login: false,
auth_keyring_backend_kind: AuthKeyringBackendKind::Direct,
source_surface_stable_id: None,
};
let server = run_login_server(opts)?;
assert!(
@@ -193,6 +194,7 @@ async fn creates_missing_codex_home_dir() -> Result<()> {
forced_chatgpt_workspace_id: None,
codex_streamlined_login: false,
auth_keyring_backend_kind: AuthKeyringBackendKind::Direct,
source_surface_stable_id: None,
};
let server = run_login_server(opts)?;
let login_port = server.actual_port;
@@ -237,6 +239,7 @@ async fn login_server_includes_forced_workspaces_as_one_query_param() -> Result<
]),
codex_streamlined_login: false,
auth_keyring_backend_kind: AuthKeyringBackendKind::Direct,
source_surface_stable_id: None,
};
let server = run_login_server(opts)?;
let auth_url = Url::parse(&server.auth_url)?;
@@ -276,6 +279,7 @@ async fn forced_chatgpt_workspace_id_mismatch_blocks_login() -> Result<()> {
forced_chatgpt_workspace_id: Some(vec![WORKSPACE_ID_ALLOWED.to_string()]),
codex_streamlined_login: false,
auth_keyring_backend_kind: AuthKeyringBackendKind::Direct,
source_surface_stable_id: None,
};
let server = run_login_server(opts)?;
assert!(
@@ -337,6 +341,7 @@ async fn oauth_access_denied_missing_entitlement_blocks_login_with_clear_error()
forced_chatgpt_workspace_id: None,
codex_streamlined_login: false,
auth_keyring_backend_kind: AuthKeyringBackendKind::Direct,
source_surface_stable_id: None,
};
let server = run_login_server(opts)?;
let login_port = server.actual_port;
@@ -406,6 +411,7 @@ async fn oauth_access_denied_unknown_reason_uses_generic_error_page() -> Result<
forced_chatgpt_workspace_id: None,
codex_streamlined_login: false,
auth_keyring_backend_kind: AuthKeyringBackendKind::Direct,
source_surface_stable_id: None,
};
let server = run_login_server(opts)?;
let login_port = server.actual_port;
@@ -553,6 +559,7 @@ async fn cancels_previous_login_server_when_port_is_in_use() -> Result<()> {
forced_chatgpt_workspace_id: None,
codex_streamlined_login: false,
auth_keyring_backend_kind: AuthKeyringBackendKind::Direct,
source_surface_stable_id: None,
};
let first_server = run_login_server(first_opts)?;
@@ -575,6 +582,7 @@ async fn cancels_previous_login_server_when_port_is_in_use() -> Result<()> {
forced_chatgpt_workspace_id: None,
codex_streamlined_login: false,
auth_keyring_backend_kind: AuthKeyringBackendKind::Direct,
source_surface_stable_id: None,
};
let second_server = run_login_server(second_opts)?;
@@ -63,6 +63,7 @@ impl MessageProcessor {
/*enable_codex_api_key_env*/ false,
)
.await;
auth_manager.set_source_surface_stable_id(Some(installation_id.clone()));
let user_instructions_provider = Arc::new(CodexHomeUserInstructionsProvider::new(
config.codex_home.clone(),
));
+1
View File
@@ -357,6 +357,7 @@ impl AppServerSession {
request_id: account_request_id,
params: GetAccountParams {
refresh_token: false,
source_surface_stable_id: None,
},
})
.await
+1
View File
@@ -875,6 +875,7 @@ impl AuthModeWidget {
request_id: onboarding_request_id(),
params: LoginAccountParams::Chatgpt {
codex_streamlined_login: false,
source_surface_stable_id: None,
},
})
.await
@@ -34,7 +34,9 @@ pub(super) fn start_headless_chatgpt_login(widget: &mut AuthModeWidget) {
match request_handle
.request_typed::<LoginAccountResponse>(ClientRequest::LoginAccount {
request_id: onboarding_request_id(),
params: LoginAccountParams::ChatgptDeviceCode,
params: LoginAccountParams::ChatgptDeviceCode {
source_surface_stable_id: None,
},
})
.await
{