let codex force ChatGPT login by org too

Add forced_chatgpt_org_id config parsing, runtime validation, and mutual exclusion with forced_chatgpt_workspace_id.\n\nThread org restrictions through browser and device-code login flows, auth enforcement, local auth loading, and app-server config schemas, with focused regression coverage for org restriction handling.
This commit is contained in:
rreichel3-oai
2026-04-17 16:19:48 -04:00
parent 9545da13a7
commit 4a144dae80
24 changed files with 366 additions and 29 deletions
@@ -6430,6 +6430,15 @@
"null"
]
},
"forced_chatgpt_org_id": {
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
},
"forced_chatgpt_workspace_id": {
"items": {
"type": "string"
@@ -3047,6 +3047,15 @@
"null"
]
},
"forced_chatgpt_org_id": {
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
},
"forced_chatgpt_workspace_id": {
"items": {
"type": "string"
@@ -233,6 +233,15 @@
"null"
]
},
"forced_chatgpt_org_id": {
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
},
"forced_chatgpt_workspace_id": {
"items": {
"type": "string"
@@ -20,4 +20,4 @@ export type Config = {model: string | null, review_model: string | null, model_c
* [UNSTABLE] Optional default for where approval requests are routed for
* review.
*/
approvals_reviewer: ApprovalsReviewer | null, sandbox_mode: SandboxMode | null, sandbox_workspace_write: SandboxWorkspaceWrite | null, forced_chatgpt_workspace_id: Array<string> | null, forced_login_method: ForcedLoginMethod | null, web_search: WebSearchMode | null, tools: ToolsV2 | null, profile: string | null, profiles: { [key in string]?: ProfileV2 }, instructions: string | null, developer_instructions: string | null, compact_prompt: string | null, model_reasoning_effort: ReasoningEffort | null, model_reasoning_summary: ReasoningSummary | null, model_verbosity: Verbosity | null, service_tier: ServiceTier | null, analytics: AnalyticsConfig | null} & ({ [key in string]?: number | string | boolean | Array<JsonValue> | { [key in string]?: JsonValue } | null });
approvals_reviewer: ApprovalsReviewer | null, sandbox_mode: SandboxMode | null, sandbox_workspace_write: SandboxWorkspaceWrite | null, forced_chatgpt_workspace_id: Array<string> | null, forced_chatgpt_org_id: Array<string> | null, forced_login_method: ForcedLoginMethod | null, web_search: WebSearchMode | null, tools: ToolsV2 | null, profile: string | null, profiles: { [key in string]?: ProfileV2 }, instructions: string | null, developer_instructions: string | null, compact_prompt: string | null, model_reasoning_effort: ReasoningEffort | null, model_reasoning_summary: ReasoningSummary | null, model_verbosity: Verbosity | null, service_tier: ServiceTier | null, analytics: AnalyticsConfig | null} & ({ [key in string]?: number | string | boolean | Array<JsonValue> | { [key in string]?: JsonValue } | null });
@@ -199,6 +199,7 @@ pub struct UserSavedConfig {
pub sandbox_mode: Option<SandboxMode>,
pub sandbox_settings: Option<SandboxSettings>,
pub forced_chatgpt_workspace_id: Option<Vec<String>>,
pub forced_chatgpt_org_id: Option<Vec<String>>,
pub forced_login_method: Option<ForcedLoginMethod>,
pub model: Option<String>,
pub model_reasoning_effort: Option<ReasoningEffort>,
@@ -766,6 +766,7 @@ pub struct Config {
pub sandbox_mode: Option<SandboxMode>,
pub sandbox_workspace_write: Option<SandboxWorkspaceWrite>,
pub forced_chatgpt_workspace_id: Option<Vec<String>>,
pub forced_chatgpt_org_id: Option<Vec<String>>,
pub forced_login_method: Option<ForcedLoginMethod>,
pub web_search: Option<WebSearchMode>,
pub tools: Option<ToolsV2>,
@@ -7549,6 +7550,7 @@ mod tests {
sandbox_mode: None,
sandbox_workspace_write: None,
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
forced_login_method: None,
web_search: None,
tools: None,
@@ -7582,6 +7584,7 @@ mod tests {
sandbox_mode: None,
sandbox_workspace_write: None,
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
forced_login_method: None,
web_search: None,
tools: None,
@@ -7615,6 +7618,7 @@ mod tests {
sandbox_mode: None,
sandbox_workspace_write: None,
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
forced_login_method: None,
web_search: None,
tools: None,
@@ -7670,6 +7674,7 @@ mod tests {
sandbox_mode: None,
sandbox_workspace_write: None,
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
forced_login_method: None,
web_search: None,
tools: None,
@@ -1312,6 +1312,7 @@ impl CodexMessageProcessor {
config.codex_home.to_path_buf(),
CLIENT_ID.to_string(),
config.forced_chatgpt_workspace_id.clone(),
config.forced_chatgpt_org_id.clone(),
config.cli_auth_credentials_store_mode,
)
};
+8
View File
@@ -113,12 +113,14 @@ fn print_login_server_start(actual_port: u16, auth_url: &str) {
pub async fn login_with_chatgpt(
codex_home: PathBuf,
forced_chatgpt_workspace_id: Option<Vec<String>>,
forced_chatgpt_org_id: Option<Vec<String>>,
cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
) -> std::io::Result<()> {
let opts = ServerOptions::new(
codex_home,
CLIENT_ID.to_string(),
forced_chatgpt_workspace_id,
forced_chatgpt_org_id,
cli_auth_credentials_store_mode,
);
let server = run_login_server(opts)?;
@@ -139,10 +141,12 @@ pub async fn run_login_with_chatgpt(cli_config_overrides: CliConfigOverrides) ->
}
let forced_chatgpt_workspace_id = config.forced_chatgpt_workspace_id.clone();
let forced_chatgpt_org_id = config.forced_chatgpt_org_id.clone();
match login_with_chatgpt(
config.codex_home.to_path_buf(),
forced_chatgpt_workspace_id,
forced_chatgpt_org_id,
config.cli_auth_credentials_store_mode,
)
.await
@@ -228,10 +232,12 @@ pub async fn run_login_with_device_code(
std::process::exit(1);
}
let forced_chatgpt_workspace_id = config.forced_chatgpt_workspace_id.clone();
let forced_chatgpt_org_id = config.forced_chatgpt_org_id.clone();
let mut opts = ServerOptions::new(
config.codex_home.to_path_buf(),
client_id.unwrap_or(CLIENT_ID.to_string()),
forced_chatgpt_workspace_id,
forced_chatgpt_org_id,
config.cli_auth_credentials_store_mode,
);
if let Some(iss) = issuer_base_url {
@@ -267,10 +273,12 @@ pub async fn run_login_with_device_code_fallback_to_browser(
}
let forced_chatgpt_workspace_id = config.forced_chatgpt_workspace_id.clone();
let forced_chatgpt_org_id = config.forced_chatgpt_org_id.clone();
let mut opts = ServerOptions::new(
config.codex_home.to_path_buf(),
client_id.unwrap_or(CLIENT_ID.to_string()),
forced_chatgpt_workspace_id,
forced_chatgpt_org_id,
config.cli_auth_credentials_store_mode,
);
if let Some(iss) = issuer_base_url {
+12 -5
View File
@@ -62,15 +62,15 @@ const RESERVED_MODEL_PROVIDER_IDS: [&str; 3] = [
LMSTUDIO_OSS_PROVIDER_ID,
];
/// Backward-compatible shape for workspace restrictions in config.toml.
/// Backward-compatible shape for ChatGPT restriction lists in config.toml.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]
#[serde(untagged)]
pub enum ForcedChatgptWorkspaceIds {
pub enum ForcedChatgptIds {
Single(String),
Multiple(Vec<String>),
}
impl ForcedChatgptWorkspaceIds {
impl ForcedChatgptIds {
pub fn into_vec(self) -> Vec<String> {
match self {
Self::Single(value) => vec![value],
@@ -168,7 +168,11 @@ pub struct ConfigToml {
/// When set, restricts ChatGPT login to one or more workspace identifiers.
#[serde(default)]
pub forced_chatgpt_workspace_id: Option<ForcedChatgptWorkspaceIds>,
pub forced_chatgpt_workspace_id: Option<ForcedChatgptIds>,
/// When set, restricts ChatGPT login to one or more organization identifiers.
#[serde(default)]
pub forced_chatgpt_org_id: Option<ForcedChatgptIds>,
/// When set, restricts the login mechanism users may use.
#[serde(default)]
@@ -426,7 +430,10 @@ impl From<ConfigToml> for UserSavedConfig {
sandbox_settings: config_toml.sandbox_workspace_write.map(From::from),
forced_chatgpt_workspace_id: config_toml
.forced_chatgpt_workspace_id
.map(ForcedChatgptWorkspaceIds::into_vec),
.map(ForcedChatgptIds::into_vec),
forced_chatgpt_org_id: config_toml
.forced_chatgpt_org_id
.map(ForcedChatgptIds::into_vec),
forced_login_method: config_toml.forced_login_method,
model: config_toml.model,
model_reasoning_effort: config_toml.model_reasoning_effort,
+12 -3
View File
@@ -675,7 +675,7 @@
"FilesystemPermissionsToml": {
"type": "object"
},
"ForcedChatgptWorkspaceIds": {
"ForcedChatgptIds": {
"anyOf": [
{
"type": "string"
@@ -687,7 +687,7 @@
"type": "array"
}
],
"description": "Backward-compatible shape for workspace restrictions in config.toml."
"description": "Backward-compatible shape for ChatGPT restriction lists in config.toml."
},
"ForcedLoginMethod": {
"enum": [
@@ -2445,10 +2445,19 @@
],
"description": "Optional URI-based file opener. If set, citations to files in the model output will be hyperlinked using the specified URI scheme."
},
"forced_chatgpt_org_id": {
"allOf": [
{
"$ref": "#/definitions/ForcedChatgptIds"
}
],
"default": null,
"description": "When set, restricts ChatGPT login to one or more organization identifiers."
},
"forced_chatgpt_workspace_id": {
"allOf": [
{
"$ref": "#/definitions/ForcedChatgptWorkspaceIds"
"$ref": "#/definitions/ForcedChatgptIds"
}
],
"default": null,
+1
View File
@@ -785,6 +785,7 @@ mod tests {
chatgpt_plan_type: None,
chatgpt_user_id: user_id.map(ToOwned::to_owned),
chatgpt_account_id: Some(account_id.to_string()),
organization_id: None,
chatgpt_account_is_fedramp: false,
raw_jwt: fake_id_token(account_id, user_id),
},
@@ -440,6 +440,7 @@ mod tests {
chatgpt_plan_type: None,
chatgpt_user_id: user_id.map(ToOwned::to_owned),
chatgpt_account_id: Some(account_id.to_string()),
organization_id: None,
chatgpt_account_is_fedramp: false,
raw_jwt: fake_id_token(account_id, user_id),
},
+35
View File
@@ -4797,6 +4797,7 @@ async fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> {
compact_prompt: None,
commit_attribution: None,
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
forced_login_method: None,
include_apply_patch_tool: false,
web_search_mode: Constrained::allow_any(WebSearchMode::Cached),
@@ -4947,6 +4948,7 @@ async fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> {
compact_prompt: None,
commit_attribution: None,
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
forced_login_method: None,
include_apply_patch_tool: false,
web_search_mode: Constrained::allow_any(WebSearchMode::Cached),
@@ -5095,6 +5097,7 @@ async fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> {
compact_prompt: None,
commit_attribution: None,
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
forced_login_method: None,
include_apply_patch_tool: false,
web_search_mode: Constrained::allow_any(WebSearchMode::Cached),
@@ -5228,6 +5231,7 @@ async fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> {
compact_prompt: None,
commit_attribution: None,
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
forced_login_method: None,
include_apply_patch_tool: false,
web_search_mode: Constrained::allow_any(WebSearchMode::Cached),
@@ -5508,6 +5512,37 @@ async fn test_load_config_rejects_legacy_ollama_chat_provider_with_helpful_error
Ok(())
}
#[tokio::test]
async fn load_config_rejects_mixing_forced_chatgpt_workspace_and_org_ids() -> std::io::Result<()> {
let codex_home = TempDir::new()?;
let cfg = ConfigToml {
forced_chatgpt_workspace_id: Some(codex_config::config_toml::ForcedChatgptIds::Single(
"workspace-123".to_string(),
)),
forced_chatgpt_org_id: Some(codex_config::config_toml::ForcedChatgptIds::Single(
"org-123".to_string(),
)),
..Default::default()
};
let result = Config::load_from_base_config_with_overrides(
cfg,
ConfigOverrides::default(),
codex_home.abs(),
)
.await;
assert!(result.is_err());
let error = result.unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
assert!(
error.to_string().contains(
"Only one of forced_chatgpt_workspace_id or forced_chatgpt_org_id may be set."
)
);
Ok(())
}
#[tokio::test]
async fn test_untrusted_project_gets_workspace_write_sandbox() -> anyhow::Result<()> {
let config_with_untrusted = r#"
+26 -1
View File
@@ -524,6 +524,8 @@ pub struct Config {
pub experimental_realtime_start_instructions: Option<String>,
/// When set, restricts ChatGPT login to one or more workspace identifiers.
pub forced_chatgpt_workspace_id: Option<Vec<String>>,
/// When set, restricts ChatGPT login to one or more organization identifiers.
pub forced_chatgpt_org_id: Option<Vec<String>>,
/// When set, restricts the login mechanism users may use.
pub forced_login_method: Option<ForcedLoginMethod>,
@@ -625,6 +627,10 @@ impl AuthManagerConfig for Config {
fn forced_chatgpt_workspace_id(&self) -> Option<Vec<String>> {
self.forced_chatgpt_workspace_id.clone()
}
fn forced_chatgpt_org_id(&self) -> Option<Vec<String>> {
self.forced_chatgpt_org_id.clone()
}
}
#[derive(Debug, Clone, Default)]
@@ -1863,7 +1869,7 @@ impl Config {
let forced_chatgpt_workspace_id = cfg
.forced_chatgpt_workspace_id
.clone()
.map(codex_config::config_toml::ForcedChatgptWorkspaceIds::into_vec)
.map(codex_config::config_toml::ForcedChatgptIds::into_vec)
.map(|values| {
values
.into_iter()
@@ -1872,6 +1878,24 @@ impl Config {
.collect::<Vec<_>>()
})
.filter(|values| !values.is_empty());
let forced_chatgpt_org_id = cfg
.forced_chatgpt_org_id
.clone()
.map(codex_config::config_toml::ForcedChatgptIds::into_vec)
.map(|values| {
values
.into_iter()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.collect::<Vec<_>>()
})
.filter(|values| !values.is_empty());
if forced_chatgpt_workspace_id.is_some() && forced_chatgpt_org_id.is_some() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Only one of forced_chatgpt_workspace_id or forced_chatgpt_org_id may be set.",
));
}
let forced_login_method = cfg.forced_login_method;
@@ -2186,6 +2210,7 @@ impl Config {
experimental_realtime_ws_startup_context: cfg.experimental_realtime_ws_startup_context,
experimental_realtime_start_instructions: cfg.experimental_realtime_start_instructions,
forced_chatgpt_workspace_id,
forced_chatgpt_org_id,
forced_login_method,
include_apply_patch_tool: include_apply_patch_tool_flag,
web_search_mode: constrained_web_search_mode.value,
+1
View File
@@ -422,6 +422,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
auth_credentials_store_mode: config.cli_auth_credentials_store_mode,
forced_login_method: config.forced_login_method,
forced_chatgpt_workspace_id: config.forced_chatgpt_workspace_id.clone(),
forced_chatgpt_org_id: config.forced_chatgpt_org_id.clone(),
}) {
eprintln!("{err}");
std::process::exit(1);
+87
View File
@@ -27,6 +27,7 @@ async fn refresh_without_id_token() {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: None,
organization_id: None,
},
codex_home.path(),
)
@@ -97,6 +98,7 @@ async fn pro_account_with_no_api_key_uses_chatgpt_auth() {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: None,
organization_id: None,
},
codex_home.path(),
)
@@ -130,6 +132,7 @@ async fn pro_account_with_no_api_key_uses_chatgpt_auth() {
chatgpt_plan_type: Some(InternalPlanType::Known(InternalKnownPlan::Pro)),
chatgpt_user_id: Some("user-12345".to_string()),
chatgpt_account_id: None,
organization_id: None,
chatgpt_account_is_fedramp: false,
raw_jwt: fake_jwt,
},
@@ -194,6 +197,7 @@ fn chatgpt_auth_persists_agent_identity_for_workspace() {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: Some("account-123".to_string()),
organization_id: None,
},
codex_home.path(),
)
@@ -264,6 +268,7 @@ fn refresh_failure_is_scoped_to_the_matching_auth_snapshot() {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: Some("org_mine".to_string()),
organization_id: None,
},
codex_home.path(),
)
@@ -587,6 +592,7 @@ struct AuthFileParams {
openai_api_key: Option<String>,
chatgpt_plan_type: Option<String>,
chatgpt_account_id: Option<String>,
organization_id: Option<String>,
}
fn write_auth_file(params: AuthFileParams, codex_home: &Path) -> std::io::Result<String> {
@@ -629,6 +635,9 @@ fn fake_jwt_for_auth_file_params(params: &AuthFileParams) -> std::io::Result<Str
if let Some(chatgpt_account_id) = params.chatgpt_account_id.as_ref() {
auth_payload["chatgpt_account_id"] = serde_json::Value::String(chatgpt_account_id.clone());
}
if let Some(organization_id) = params.organization_id.as_ref() {
auth_payload["organization_id"] = serde_json::Value::String(organization_id.clone());
}
let payload = serde_json::json!({
"email": "user@example.com",
@@ -646,12 +655,14 @@ async fn build_config(
codex_home: &Path,
forced_login_method: Option<ForcedLoginMethod>,
forced_chatgpt_workspace_id: Option<Vec<String>>,
forced_chatgpt_org_id: Option<Vec<String>>,
) -> AuthConfig {
AuthConfig {
codex_home: codex_home.to_path_buf(),
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
forced_login_method,
forced_chatgpt_workspace_id,
forced_chatgpt_org_id,
}
}
@@ -696,6 +707,7 @@ async fn enforce_login_restrictions_logs_out_for_method_mismatch() {
codex_home.path(),
Some(ForcedLoginMethod::Chatgpt),
/*forced_chatgpt_workspace_id*/ None,
/*forced_chatgpt_org_id*/ None,
)
.await;
@@ -717,6 +729,7 @@ async fn enforce_login_restrictions_logs_out_for_workspace_mismatch() {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: Some("org_another_org".to_string()),
organization_id: None,
},
codex_home.path(),
)
@@ -726,6 +739,7 @@ async fn enforce_login_restrictions_logs_out_for_workspace_mismatch() {
codex_home.path(),
/*forced_login_method*/ None,
Some(vec!["org_mine".to_string()]),
/*forced_chatgpt_org_id*/ None,
)
.await;
@@ -747,6 +761,7 @@ async fn enforce_login_restrictions_allows_matching_workspace() {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: Some("org_mine".to_string()),
organization_id: None,
},
codex_home.path(),
)
@@ -756,6 +771,7 @@ async fn enforce_login_restrictions_allows_matching_workspace() {
codex_home.path(),
/*forced_login_method*/ None,
Some(vec!["org_mine".to_string()]),
/*forced_chatgpt_org_id*/ None,
)
.await;
@@ -766,6 +782,68 @@ async fn enforce_login_restrictions_allows_matching_workspace() {
);
}
#[tokio::test]
#[serial(codex_api_key)]
async fn enforce_login_restrictions_logs_out_for_org_mismatch() {
let codex_home = tempdir().unwrap();
let _jwt = write_auth_file(
AuthFileParams {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: Some("workspace_mine".to_string()),
organization_id: Some("org_other".to_string()),
},
codex_home.path(),
)
.expect("failed to write auth file");
let config = build_config(
codex_home.path(),
/*forced_login_method*/ None,
/*forced_chatgpt_workspace_id*/ None,
Some(vec!["org_mine".to_string()]),
)
.await;
let err =
super::enforce_login_restrictions(&config).expect_err("expected org mismatch to error");
assert!(err.to_string().contains("org(s) org_mine"));
assert!(
!codex_home.path().join("auth.json").exists(),
"auth.json should be removed on mismatch"
);
}
#[tokio::test]
#[serial(codex_api_key)]
async fn enforce_login_restrictions_allows_matching_org() {
let codex_home = tempdir().unwrap();
let _jwt = write_auth_file(
AuthFileParams {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: Some("workspace_mine".to_string()),
organization_id: Some("org_mine".to_string()),
},
codex_home.path(),
)
.expect("failed to write auth file");
let config = build_config(
codex_home.path(),
/*forced_login_method*/ None,
/*forced_chatgpt_workspace_id*/ None,
Some(vec!["org_mine".to_string()]),
)
.await;
super::enforce_login_restrictions(&config).expect("matching org should succeed");
assert!(
codex_home.path().join("auth.json").exists(),
"auth.json should remain when restrictions pass"
);
}
#[tokio::test]
#[serial(codex_api_key)]
async fn enforce_login_restrictions_allows_any_matching_workspace_in_list() {
@@ -775,6 +853,7 @@ async fn enforce_login_restrictions_allows_any_matching_workspace_in_list() {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: Some("org_mine".to_string()),
organization_id: None,
},
codex_home.path(),
)
@@ -784,6 +863,7 @@ async fn enforce_login_restrictions_allows_any_matching_workspace_in_list() {
codex_home.path(),
/*forced_login_method*/ None,
Some(vec!["org_other".to_string(), "org_mine".to_string()]),
/*forced_chatgpt_org_id*/ None,
)
.await;
@@ -802,6 +882,7 @@ async fn enforce_login_restrictions_allows_api_key_if_login_method_not_set_but_f
codex_home.path(),
/*forced_login_method*/ None,
Some(vec!["org_mine".to_string()]),
/*forced_chatgpt_org_id*/ None,
)
.await;
@@ -822,6 +903,7 @@ async fn enforce_login_restrictions_blocks_env_api_key_when_chatgpt_required() {
codex_home.path(),
Some(ForcedLoginMethod::Chatgpt),
/*forced_chatgpt_workspace_id*/ None,
/*forced_chatgpt_org_id*/ None,
)
.await;
@@ -841,6 +923,7 @@ fn plan_type_maps_known_plan() {
openai_api_key: None,
chatgpt_plan_type: Some("pro".to_string()),
chatgpt_account_id: None,
organization_id: None,
},
codex_home.path(),
)
@@ -865,6 +948,7 @@ fn plan_type_maps_self_serve_business_usage_based_plan() {
openai_api_key: None,
chatgpt_plan_type: Some("self_serve_business_usage_based".to_string()),
chatgpt_account_id: None,
organization_id: None,
},
codex_home.path(),
)
@@ -892,6 +976,7 @@ fn plan_type_maps_enterprise_cbp_usage_based_plan() {
openai_api_key: None,
chatgpt_plan_type: Some("enterprise_cbp_usage_based".to_string()),
chatgpt_account_id: None,
organization_id: None,
},
codex_home.path(),
)
@@ -919,6 +1004,7 @@ fn plan_type_maps_unknown_to_unknown() {
openai_api_key: None,
chatgpt_plan_type: Some("mystery-tier".to_string()),
chatgpt_account_id: None,
organization_id: None,
},
codex_home.path(),
)
@@ -943,6 +1029,7 @@ fn missing_plan_type_maps_to_unknown() {
openai_api_key: None,
chatgpt_plan_type: None,
chatgpt_account_id: None,
organization_id: None,
},
codex_home.path(),
)
+66
View File
@@ -547,6 +547,7 @@ pub struct AuthConfig {
pub auth_credentials_store_mode: AuthCredentialsStoreMode,
pub forced_login_method: Option<ForcedLoginMethod>,
pub forced_chatgpt_workspace_id: Option<Vec<String>>,
pub forced_chatgpt_org_id: Option<Vec<String>>,
}
pub fn enforce_login_restrictions(config: &AuthConfig) -> std::io::Result<()> {
@@ -626,6 +627,45 @@ pub fn enforce_login_restrictions(config: &AuthConfig) -> std::io::Result<()> {
}
}
if let Some(expected_org_ids) = config.forced_chatgpt_org_id.as_deref() {
if !auth.is_chatgpt_auth() {
return Ok(());
}
let token_data = match auth.get_token_data() {
Ok(data) => data,
Err(err) => {
return logout_with_message(
&config.codex_home,
format!(
"Failed to load ChatGPT credentials while enforcing org restrictions: {err}. Logging out."
),
config.auth_credentials_store_mode,
);
}
};
let organization_id = token_data.id_token.organization_id.as_deref();
if !organization_id
.is_some_and(|actual| expected_org_ids.iter().any(|expected| expected == actual))
{
let expected_orgs = expected_org_ids.join(", ");
let message = match organization_id {
Some(actual) => format!(
"Login is restricted to org(s) {expected_orgs}, but current credentials belong to {actual}. Logging out."
),
None => format!(
"Login is restricted to org(s) {expected_orgs}, but current credentials lack an organization identifier. Logging out."
),
};
return logout_with_message(
&config.codex_home,
message,
config.auth_credentials_store_mode,
);
}
}
Ok(())
}
@@ -1167,6 +1207,7 @@ pub struct AuthManager {
enable_codex_api_key_env: bool,
auth_credentials_store_mode: AuthCredentialsStoreMode,
forced_chatgpt_workspace_id: RwLock<Option<Vec<String>>>,
forced_chatgpt_org_id: RwLock<Option<Vec<String>>>,
refresh_lock: AsyncMutex<()>,
external_auth: RwLock<Option<Arc<dyn ExternalAuth>>>,
auth_state_tx: watch::Sender<()>,
@@ -1187,6 +1228,9 @@ pub trait AuthManagerConfig {
/// Returns the workspace IDs that ChatGPT auth should be restricted to, if any.
fn forced_chatgpt_workspace_id(&self) -> Option<Vec<String>>;
/// Returns the org IDs that ChatGPT auth should be restricted to, if any.
fn forced_chatgpt_org_id(&self) -> Option<Vec<String>>;
}
impl Debug for AuthManager {
@@ -1203,6 +1247,7 @@ impl Debug for AuthManager {
"forced_chatgpt_workspace_id",
&self.forced_chatgpt_workspace_id,
)
.field("forced_chatgpt_org_id", &self.forced_chatgpt_org_id)
.field("has_external_auth", &self.has_external_auth())
.finish_non_exhaustive()
}
@@ -1235,6 +1280,7 @@ impl AuthManager {
enable_codex_api_key_env,
auth_credentials_store_mode,
forced_chatgpt_workspace_id: RwLock::new(None),
forced_chatgpt_org_id: RwLock::new(None),
refresh_lock: AsyncMutex::new(()),
external_auth: RwLock::new(None),
auth_state_tx,
@@ -1255,6 +1301,7 @@ impl AuthManager {
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
forced_chatgpt_workspace_id: RwLock::new(None),
forced_chatgpt_org_id: RwLock::new(None),
refresh_lock: AsyncMutex::new(()),
external_auth: RwLock::new(None),
auth_state_tx,
@@ -1274,6 +1321,7 @@ impl AuthManager {
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
forced_chatgpt_workspace_id: RwLock::new(None),
forced_chatgpt_org_id: RwLock::new(None),
refresh_lock: AsyncMutex::new(()),
external_auth: RwLock::new(None),
auth_state_tx,
@@ -1291,6 +1339,7 @@ impl AuthManager {
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
forced_chatgpt_workspace_id: RwLock::new(None),
forced_chatgpt_org_id: RwLock::new(None),
refresh_lock: AsyncMutex::new(()),
external_auth: RwLock::new(Some(
Arc::new(BearerTokenRefresher::new(config)) as Arc<dyn ExternalAuth>
@@ -1472,6 +1521,22 @@ impl AuthManager {
.and_then(|guard| guard.clone())
}
pub fn set_forced_chatgpt_org_id(&self, org_id: Option<Vec<String>>) {
if let Ok(mut guard) = self.forced_chatgpt_org_id.write()
&& *guard != org_id
{
*guard = org_id;
self.auth_state_tx.send_replace(());
}
}
pub fn forced_chatgpt_org_id(&self) -> Option<Vec<String>> {
self.forced_chatgpt_org_id
.read()
.ok()
.and_then(|guard| guard.clone())
}
pub fn subscribe_auth_state(&self) -> watch::Receiver<()> {
self.auth_state_tx.subscribe()
}
@@ -1514,6 +1579,7 @@ impl AuthManager {
config.cli_auth_credentials_store_mode(),
);
auth_manager.set_forced_chatgpt_workspace_id(config.forced_chatgpt_workspace_id());
auth_manager.set_forced_chatgpt_org_id(config.forced_chatgpt_org_id());
auth_manager
}
+2 -1
View File
@@ -203,8 +203,9 @@ pub async fn complete_device_code_login(
.await
.map_err(|err| std::io::Error::other(format!("device code exchange failed: {err}")))?;
if let Err(message) = crate::server::ensure_workspace_allowed(
if let Err(message) = crate::server::ensure_chatgpt_restrictions_allowed(
opts.forced_chatgpt_workspace_id.as_deref(),
opts.forced_chatgpt_org_id.as_deref(),
&tokens.id_token,
) {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, message));
+44 -18
View File
@@ -65,6 +65,7 @@ pub struct ServerOptions {
pub open_browser: bool,
pub force_state: Option<String>,
pub forced_chatgpt_workspace_id: Option<Vec<String>>,
pub forced_chatgpt_org_id: Option<Vec<String>>,
pub cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
}
@@ -74,6 +75,7 @@ impl ServerOptions {
codex_home: PathBuf,
client_id: String,
forced_chatgpt_workspace_id: Option<Vec<String>>,
forced_chatgpt_org_id: Option<Vec<String>>,
cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
) -> Self {
Self {
@@ -84,6 +86,7 @@ impl ServerOptions {
open_browser: true,
force_state: None,
forced_chatgpt_workspace_id,
forced_chatgpt_org_id,
cli_auth_credentials_store_mode,
}
}
@@ -154,6 +157,7 @@ pub fn run_login_server(opts: ServerOptions) -> io::Result<LoginServer> {
&pkce,
&state,
opts.forced_chatgpt_workspace_id.as_deref(),
opts.forced_chatgpt_org_id.as_deref(),
);
if opts.open_browser {
@@ -332,8 +336,9 @@ async fn process_request(
.await
{
Ok(tokens) => {
if let Err(message) = ensure_workspace_allowed(
if let Err(message) = ensure_chatgpt_restrictions_allowed(
opts.forced_chatgpt_workspace_id.as_deref(),
opts.forced_chatgpt_org_id.as_deref(),
&tokens.id_token,
) {
eprintln!("Workspace restriction error: {message}");
@@ -472,6 +477,7 @@ fn build_authorize_url(
pkce: &PkceCodes,
state: &str,
forced_chatgpt_workspace_ids: Option<&[String]>,
forced_chatgpt_org_ids: Option<&[String]>,
) -> String {
let mut query = vec![
("response_type".to_string(), "code".to_string()),
@@ -500,6 +506,14 @@ fn build_authorize_url(
.map(|workspace_id| ("allowed_workspace_id".to_string(), workspace_id)),
);
}
if let Some(org_ids) = forced_chatgpt_org_ids {
query.extend(
org_ids
.iter()
.cloned()
.map(|org_id| ("allowed_org_id".to_string(), org_id)),
);
}
let qs = query
.into_iter()
.map(|(k, v)| format!("{k}={}", urlencoding::encode(&v)))
@@ -873,28 +887,40 @@ fn jwt_auth_claims(jwt: &str) -> serde_json::Map<String, serde_json::Value> {
serde_json::Map::new()
}
/// Validates the ID token against an optional workspace restriction.
pub(crate) fn ensure_workspace_allowed(
expected: Option<&[String]>,
/// Validates the ID token against optional workspace or organization restrictions.
pub(crate) fn ensure_chatgpt_restrictions_allowed(
expected_workspace_ids: Option<&[String]>,
expected_org_ids: Option<&[String]>,
id_token: &str,
) -> Result<(), String> {
let Some(expected) = expected else {
return Ok(());
};
let claims = jwt_auth_claims(id_token);
let Some(actual) = claims.get("chatgpt_account_id").and_then(JsonValue::as_str) else {
return Err("Login is restricted to a specific workspace, but the token did not include an chatgpt_account_id claim.".to_string());
};
if let Some(expected) = expected_workspace_ids {
let Some(actual) = claims.get("chatgpt_account_id").and_then(JsonValue::as_str) else {
return Err("Login is restricted to a specific workspace, but the token did not include an chatgpt_account_id claim.".to_string());
};
if expected.iter().any(|workspace_id| workspace_id == actual) {
Ok(())
} else {
Err(format!(
"Login is restricted to workspace id(s) {}.",
expected.join(", ")
))
if !expected.iter().any(|workspace_id| workspace_id == actual) {
return Err(format!(
"Login is restricted to workspace id(s) {}.",
expected.join(", ")
));
}
}
if let Some(expected) = expected_org_ids {
let Some(actual) = claims.get("organization_id").and_then(JsonValue::as_str) else {
return Err("Login is restricted to a specific org, but the token did not include an organization_id claim.".to_string());
};
if !expected.iter().any(|org_id| org_id == actual) {
return Err(format!(
"Login is restricted to org id(s) {}.",
expected.join(", ")
));
}
}
Ok(())
}
/// Builds a terminal callback response for login failures.
+6
View File
@@ -36,6 +36,8 @@ pub struct IdTokenInfo {
pub chatgpt_user_id: Option<String>,
/// Organization/workspace identifier associated with the token, if present.
pub chatgpt_account_id: Option<String>,
/// Organization identifier associated with the token, if present.
pub organization_id: Option<String>,
/// Whether the selected ChatGPT workspace must route through the FedRAMP edge.
pub chatgpt_account_is_fedramp: bool,
pub raw_jwt: String,
@@ -95,6 +97,8 @@ struct AuthClaims {
#[serde(default)]
chatgpt_account_id: Option<String>,
#[serde(default)]
organization_id: Option<String>,
#[serde(default)]
chatgpt_account_is_fedramp: bool,
}
@@ -147,6 +151,7 @@ pub fn parse_chatgpt_jwt_claims(jwt: &str) -> Result<IdTokenInfo, IdTokenInfoErr
chatgpt_plan_type: auth.chatgpt_plan_type,
chatgpt_user_id: auth.chatgpt_user_id.or(auth.user_id),
chatgpt_account_id: auth.chatgpt_account_id,
organization_id: auth.organization_id,
chatgpt_account_is_fedramp: auth.chatgpt_account_is_fedramp,
}),
None => Ok(IdTokenInfo {
@@ -155,6 +160,7 @@ pub fn parse_chatgpt_jwt_claims(jwt: &str) -> Result<IdTokenInfo, IdTokenInfoErr
chatgpt_plan_type: None,
chatgpt_user_id: None,
chatgpt_account_id: None,
organization_id: None,
chatgpt_account_is_fedramp: false,
}),
}
@@ -106,6 +106,7 @@ fn server_opts(
codex_home.path().to_path_buf(),
"client-id".to_string(),
/*forced_chatgpt_workspace_id*/ None,
/*forced_chatgpt_org_id*/ None,
cli_auth_credentials_store_mode,
);
opts.issuer = issuer;
@@ -258,6 +259,7 @@ async fn device_code_login_integration_persists_without_api_key_on_exchange_fail
codex_home.path().to_path_buf(),
"client-id".to_string(),
/*forced_chatgpt_workspace_id*/ None,
/*forced_chatgpt_org_id*/ None,
AuthCredentialsStoreMode::File,
);
opts.issuer = issuer;
@@ -308,6 +310,7 @@ async fn device_code_login_integration_handles_error_payload() -> anyhow::Result
codex_home.path().to_path_buf(),
"client-id".to_string(),
/*forced_chatgpt_workspace_id*/ None,
/*forced_chatgpt_org_id*/ None,
AuthCredentialsStoreMode::File,
);
opts.issuer = issuer;
@@ -118,6 +118,7 @@ async fn end_to_end_login_flow_persists_auth_json() -> Result<()> {
open_browser: false,
force_state: Some(state),
forced_chatgpt_workspace_id: Some(vec![chatgpt_account_id.to_string()]),
forced_chatgpt_org_id: None,
};
let server = run_login_server(opts)?;
assert!(
@@ -179,6 +180,7 @@ async fn creates_missing_codex_home_dir() -> Result<()> {
open_browser: false,
force_state: Some(state),
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
};
let server = run_login_server(opts)?;
let login_port = server.actual_port;
@@ -221,6 +223,7 @@ async fn login_server_includes_all_forced_workspace_query_params() -> Result<()>
"org-required-a".to_string(),
"org-required-b".to_string(),
]),
forced_chatgpt_org_id: None,
};
let server = run_login_server(opts)?;
assert!(
@@ -257,6 +260,7 @@ async fn forced_chatgpt_workspace_id_mismatch_blocks_login() -> Result<()> {
open_browser: false,
force_state: Some(state.clone()),
forced_chatgpt_workspace_id: Some(vec!["org-required".to_string()]),
forced_chatgpt_org_id: None,
};
let server = run_login_server(opts)?;
assert!(
@@ -314,6 +318,7 @@ async fn oauth_access_denied_missing_entitlement_blocks_login_with_clear_error()
open_browser: false,
force_state: Some(state.clone()),
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
};
let server = run_login_server(opts)?;
let login_port = server.actual_port;
@@ -381,6 +386,7 @@ async fn oauth_access_denied_unknown_reason_uses_generic_error_page() -> Result<
open_browser: false,
force_state: Some(state.clone()),
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
};
let server = run_login_server(opts)?;
let login_port = server.actual_port;
@@ -459,6 +465,7 @@ async fn cancels_previous_login_server_when_port_is_in_use() -> Result<()> {
open_browser: false,
force_state: Some("cancel_state".to_string()),
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
};
let first_server = run_login_server(first_opts)?;
@@ -479,6 +486,7 @@ async fn cancels_previous_login_server_when_port_is_in_use() -> Result<()> {
open_browser: false,
force_state: Some("cancel_state_2".to_string()),
forced_chatgpt_workspace_id: None,
forced_chatgpt_org_id: None,
};
let second_server = run_login_server(second_opts)?;
+1
View File
@@ -884,6 +884,7 @@ pub async fn run_main(
auth_credentials_store_mode: config.cli_auth_credentials_store_mode,
forced_login_method: config.forced_login_method,
forced_chatgpt_workspace_id: config.forced_chatgpt_workspace_id.clone(),
forced_chatgpt_org_id: config.forced_chatgpt_org_id.clone(),
}) {
eprintln!("{err}");
std::process::exit(1);
+18
View File
@@ -17,6 +17,7 @@ pub(crate) fn load_local_chatgpt_auth(
codex_home: &Path,
auth_credentials_store_mode: AuthCredentialsStoreMode,
forced_chatgpt_workspace_id: Option<&[String]>,
forced_chatgpt_org_id: Option<&[String]>,
) -> Result<LocalChatgptAuth, String> {
let auth = load_auth_dot_json(codex_home, auth_credentials_store_mode)
.map_err(|err| format!("failed to load local auth: {err}"))?
@@ -40,6 +41,18 @@ pub(crate) fn load_local_chatgpt_auth(
"local ChatGPT auth must use one of workspace(s) {expected_workspaces:?}, but found {chatgpt_account_id:?}",
));
}
if let Some(expected_orgs) = forced_chatgpt_org_id {
let organization_id = tokens
.id_token
.organization_id
.as_ref()
.ok_or_else(|| "local ChatGPT auth is missing organization id".to_string())?;
if !expected_orgs.contains(organization_id) {
return Err(format!(
"local ChatGPT auth must use one of org(s) {expected_orgs:?}, but found {organization_id:?}",
));
}
}
let chatgpt_plan_type = tokens
.id_token
@@ -123,6 +136,7 @@ mod tests {
codex_home.path(),
AuthCredentialsStoreMode::File,
Some(&["workspace-1".to_string()]),
/*forced_chatgpt_org_id*/ None,
)
.expect("chatgpt auth should load");
@@ -139,6 +153,7 @@ mod tests {
codex_home.path(),
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
/*forced_chatgpt_org_id*/ None,
)
.expect_err("missing auth should fail");
@@ -165,6 +180,7 @@ mod tests {
codex_home.path(),
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
/*forced_chatgpt_org_id*/ None,
)
.expect_err("api key auth should fail");
@@ -187,6 +203,7 @@ mod tests {
codex_home.path(),
AuthCredentialsStoreMode::File,
Some(&["workspace-1".to_string(), "workspace-2".to_string()]),
/*forced_chatgpt_org_id*/ None,
)
.expect("managed auth should win");
@@ -203,6 +220,7 @@ mod tests {
codex_home.path(),
AuthCredentialsStoreMode::File,
Some(&["workspace-1".to_string()]),
/*forced_chatgpt_org_id*/ None,
)
.expect("chatgpt auth should load");