mirror of
https://github.com/pchuan98/codex.git
synced 2026-07-01 00:31:56 +08:00
df7818c7d1
## Summary - add v2 personal access token support for `codex login --with-access-token` and `CODEX_ACCESS_TOKEN` - classify opaque `at-` tokens separately from legacy Agent Identity JWTs - hydrate required ChatGPT account metadata through AuthAPI `/v1/user-auth-credential/whoami` - use PATs directly as bearer tokens while preserving existing ChatGPT account surfaces - expose PAT-backed auth as the explicit `personalAccessToken` app-server auth mode ## Implementation PAT auth is intentionally small and stateless. Loading a PAT performs one AuthAPI metadata request, stores the hydrated metadata in the in-memory auth object, and redacts the secret from debug output. Legacy Agent Identity JWT handling remains unchanged. The shared access-token classifier lives in a private neutral module because it dispatches between both credential types. PAT hydration fails closed when AuthAPI omits any required metadata, including email. Hydrated metadata is intentionally not persisted: startup performs a live `whoami` preflight so revoked tokens or changed account metadata are not accepted from a stale cache. ## Workspace restriction scope This change intentionally does **not** apply `forced_chatgpt_workspace_id` to PAT authentication. The setting is a client-side config guardrail, not an authorization boundary, and PAT does not currently require workspace-ID parity. The PAT login and `CODEX_ACCESS_TOKEN` paths therefore validate through AuthAPI without threading workspace-restriction state through access-token loading. Existing workspace checks for non-PAT auth remain on their established paths. ## App-server compatibility The public app-server `AuthMode` is shared across v1 and v2, and PAT-backed auth reports `personalAccessToken` through both APIs. Following human review, this intentionally removes the temporary v1 compatibility mapping that reported PATs as `chatgpt`; the deprecated v1 API is kept in parity with v2 rather than maintaining a separate closed enum. Clients with exhaustive auth-mode handling in either API version must add the new case and should generally treat it as ChatGPT-backed unless they need PAT-specific behavior. The v1 auth-status response still omits the raw PAT when `includeToken` is requested because that response cannot carry the account metadata needed to reuse the credential safely. Persisted PAT auth also omits the new enum value so older Codex builds can deserialize `auth.json` and infer PAT auth from the credential field after a rollback. ## Validation Latest review-fix validation: - `CARGO_INCREMENTAL=0 just test -p codex-login` (126 passed) - `CARGO_INCREMENTAL=0 just test -p codex-cli` (263 passed) - `CARGO_INCREMENTAL=0 just test -p codex-cli stored_auth_validation_handles_personal_access_token` - `CARGO_INCREMENTAL=0 just test -p codex-app-server-protocol` (226 passed) - `CARGO_INCREMENTAL=0 just test -p codex-models-manager refresh_available_models_uses_remote_only_catalog_for_chatgpt_auth` - `CARGO_INCREMENTAL=0 just test -p codex-tui existing_non_oauth_chatgpt_login_counts_as_signed_in` - `CARGO_INCREMENTAL=0 just fix -p codex-login -p codex-app-server-protocol -p codex-models-manager -p codex-tui -p codex-cli` - `just fmt` - `git diff --check` The broader `codex-tui` suite previously compiled and ran 2,834 tests. Three unrelated environment-sensitive guardian/IDE-socket tests failed after retries; the PAT-relevant TUI coverage passed.
139 lines
4.4 KiB
Rust
139 lines
4.4 KiB
Rust
use std::sync::Arc;
|
|
|
|
use codex_agent_identity::AgentIdentityKey;
|
|
use codex_agent_identity::AgentTaskAuthorizationTarget;
|
|
use codex_agent_identity::authorization_header_for_agent_task;
|
|
use codex_api::AuthProvider;
|
|
use codex_api::SharedAuthProvider;
|
|
use codex_login::AuthManager;
|
|
use codex_login::CodexAuth;
|
|
use codex_model_provider_info::ModelProviderInfo;
|
|
use http::HeaderMap;
|
|
use http::HeaderValue;
|
|
|
|
use crate::bearer_auth_provider::BearerAuthProvider;
|
|
|
|
#[derive(Clone, Debug)]
|
|
struct AgentIdentityAuthProvider {
|
|
auth: codex_login::auth::AgentIdentityAuth,
|
|
}
|
|
|
|
impl AuthProvider for AgentIdentityAuthProvider {
|
|
fn add_auth_headers(&self, headers: &mut HeaderMap) {
|
|
let record = self.auth.record();
|
|
let header_value = authorization_header_for_agent_task(
|
|
AgentIdentityKey {
|
|
agent_runtime_id: &record.agent_runtime_id,
|
|
private_key_pkcs8_base64: &record.agent_private_key,
|
|
},
|
|
AgentTaskAuthorizationTarget {
|
|
agent_runtime_id: &record.agent_runtime_id,
|
|
task_id: self.auth.process_task_id(),
|
|
},
|
|
)
|
|
.map_err(std::io::Error::other);
|
|
|
|
if let Ok(header_value) = header_value
|
|
&& let Ok(header) = HeaderValue::from_str(&header_value)
|
|
{
|
|
let _ = headers.insert(http::header::AUTHORIZATION, header);
|
|
}
|
|
|
|
if let Ok(header) = HeaderValue::from_str(self.auth.account_id()) {
|
|
let _ = headers.insert("ChatGPT-Account-ID", header);
|
|
}
|
|
|
|
if self.auth.is_fedramp_account() {
|
|
let _ = headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
|
|
}
|
|
}
|
|
}
|
|
|
|
// Some providers are meant to send no auth headers. Examples include local OSS
|
|
// providers and custom test providers with `requires_openai_auth = false`.
|
|
#[derive(Clone, Debug)]
|
|
struct UnauthenticatedAuthProvider;
|
|
|
|
impl AuthProvider for UnauthenticatedAuthProvider {
|
|
fn add_auth_headers(&self, _headers: &mut HeaderMap) {}
|
|
}
|
|
|
|
pub fn unauthenticated_auth_provider() -> SharedAuthProvider {
|
|
Arc::new(UnauthenticatedAuthProvider)
|
|
}
|
|
|
|
/// Returns the provider-scoped auth manager when this provider uses command-backed auth.
|
|
///
|
|
/// Providers without custom auth continue using the caller-supplied base manager, when present.
|
|
pub(crate) fn auth_manager_for_provider(
|
|
auth_manager: Option<Arc<AuthManager>>,
|
|
provider: &ModelProviderInfo,
|
|
) -> Option<Arc<AuthManager>> {
|
|
match provider.auth.clone() {
|
|
Some(config) => Some(AuthManager::external_bearer_only(config)),
|
|
None => auth_manager,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn resolve_provider_auth(
|
|
auth: Option<&CodexAuth>,
|
|
provider: &ModelProviderInfo,
|
|
) -> codex_protocol::error::Result<SharedAuthProvider> {
|
|
if let Some(auth) = bearer_auth_for_provider(provider)? {
|
|
return Ok(Arc::new(auth));
|
|
}
|
|
|
|
Ok(match auth {
|
|
Some(auth) => auth_provider_from_auth(auth),
|
|
None => unauthenticated_auth_provider(),
|
|
})
|
|
}
|
|
|
|
fn bearer_auth_for_provider(
|
|
provider: &ModelProviderInfo,
|
|
) -> codex_protocol::error::Result<Option<BearerAuthProvider>> {
|
|
if let Some(api_key) = provider.api_key()? {
|
|
return Ok(Some(BearerAuthProvider::new(api_key)));
|
|
}
|
|
|
|
if let Some(token) = provider.experimental_bearer_token.clone() {
|
|
return Ok(Some(BearerAuthProvider::new(token)));
|
|
}
|
|
|
|
Ok(None)
|
|
}
|
|
|
|
/// Builds request-header auth for a first-party Codex auth snapshot.
|
|
pub fn auth_provider_from_auth(auth: &CodexAuth) -> SharedAuthProvider {
|
|
match auth {
|
|
CodexAuth::AgentIdentity(auth) => {
|
|
Arc::new(AgentIdentityAuthProvider { auth: auth.clone() })
|
|
}
|
|
CodexAuth::ApiKey(_)
|
|
| CodexAuth::Chatgpt(_)
|
|
| CodexAuth::ChatgptAuthTokens(_)
|
|
| CodexAuth::PersonalAccessToken(_) => Arc::new(BearerAuthProvider {
|
|
token: auth.get_token().ok(),
|
|
account_id: auth.get_account_id(),
|
|
is_fedramp_account: auth.is_fedramp_account(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use codex_model_provider_info::WireApi;
|
|
use codex_model_provider_info::create_oss_provider_with_base_url;
|
|
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn unauthenticated_auth_provider_adds_no_headers() {
|
|
let provider =
|
|
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses);
|
|
let auth = resolve_provider_auth(/*auth*/ None, &provider).expect("auth should resolve");
|
|
|
|
assert!(auth.to_auth_headers().is_empty());
|
|
}
|
|
}
|