diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index d01166ff5d..a76090def0 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -6430,6 +6430,15 @@ "null" ] }, + "forced_chatgpt_org_id": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "forced_chatgpt_workspace_id": { "items": { "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 6e658c8916..7298583694 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -3047,6 +3047,15 @@ "null" ] }, + "forced_chatgpt_org_id": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "forced_chatgpt_workspace_id": { "items": { "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json index 0047d78680..fa9c1177b0 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json @@ -233,6 +233,15 @@ "null" ] }, + "forced_chatgpt_org_id": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "forced_chatgpt_workspace_id": { "items": { "type": "string" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts index 1b04d60d28..ce745d4d8a 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts @@ -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 | 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 | { [key in string]?: JsonValue } | null }); +approvals_reviewer: ApprovalsReviewer | null, sandbox_mode: SandboxMode | null, sandbox_workspace_write: SandboxWorkspaceWrite | null, forced_chatgpt_workspace_id: Array | null, forced_chatgpt_org_id: Array | 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 | { [key in string]?: JsonValue } | null }); diff --git a/codex-rs/app-server-protocol/src/protocol/v1.rs b/codex-rs/app-server-protocol/src/protocol/v1.rs index 64f82789b1..feba023f89 100644 --- a/codex-rs/app-server-protocol/src/protocol/v1.rs +++ b/codex-rs/app-server-protocol/src/protocol/v1.rs @@ -199,6 +199,7 @@ pub struct UserSavedConfig { pub sandbox_mode: Option, pub sandbox_settings: Option, pub forced_chatgpt_workspace_id: Option>, + pub forced_chatgpt_org_id: Option>, pub forced_login_method: Option, pub model: Option, pub model_reasoning_effort: Option, diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 11aac8cd1e..6ae3f974ba 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -766,6 +766,7 @@ pub struct Config { pub sandbox_mode: Option, pub sandbox_workspace_write: Option, pub forced_chatgpt_workspace_id: Option>, + pub forced_chatgpt_org_id: Option>, pub forced_login_method: Option, pub web_search: Option, pub tools: Option, @@ -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, diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 2769974ed8..2cf1247bf8 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -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, ) }; diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index dba7103840..50c87ba50e 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -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>, + forced_chatgpt_org_id: Option>, 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 { diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rs index 4ce934f5d2..81435eafde 100644 --- a/codex-rs/config/src/config_toml.rs +++ b/codex-rs/config/src/config_toml.rs @@ -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), } -impl ForcedChatgptWorkspaceIds { +impl ForcedChatgptIds { pub fn into_vec(self) -> Vec { 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, + pub forced_chatgpt_workspace_id: Option, + + /// When set, restricts ChatGPT login to one or more organization identifiers. + #[serde(default)] + pub forced_chatgpt_org_id: Option, /// When set, restricts the login mechanism users may use. #[serde(default)] @@ -426,7 +430,10 @@ impl From 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, diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index a45234ab1d..f8beb191ad 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -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, diff --git a/codex-rs/core/src/agent_identity.rs b/codex-rs/core/src/agent_identity.rs index dac628dae1..44717efb9d 100644 --- a/codex-rs/core/src/agent_identity.rs +++ b/codex-rs/core/src/agent_identity.rs @@ -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), }, diff --git a/codex-rs/core/src/agent_identity/task_registration.rs b/codex-rs/core/src/agent_identity/task_registration.rs index 4fc5d51282..5bcf15269f 100644 --- a/codex-rs/core/src/agent_identity/task_registration.rs +++ b/codex-rs/core/src/agent_identity/task_registration.rs @@ -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), }, diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 34002b129a..94268264dc 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -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#" diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index fbab2dd850..90e6334746 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -524,6 +524,8 @@ pub struct Config { pub experimental_realtime_start_instructions: Option, /// When set, restricts ChatGPT login to one or more workspace identifiers. pub forced_chatgpt_workspace_id: Option>, + /// When set, restricts ChatGPT login to one or more organization identifiers. + pub forced_chatgpt_org_id: Option>, /// When set, restricts the login mechanism users may use. pub forced_login_method: Option, @@ -625,6 +627,10 @@ impl AuthManagerConfig for Config { fn forced_chatgpt_workspace_id(&self) -> Option> { self.forced_chatgpt_workspace_id.clone() } + + fn forced_chatgpt_org_id(&self) -> Option> { + 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::>() }) .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::>() + }) + .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, diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 123038ffaa..d6e9482669 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -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); diff --git a/codex-rs/login/src/auth/auth_tests.rs b/codex-rs/login/src/auth/auth_tests.rs index 0503256b60..08bbdd998a 100644 --- a/codex-rs/login/src/auth/auth_tests.rs +++ b/codex-rs/login/src/auth/auth_tests.rs @@ -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, chatgpt_plan_type: Option, chatgpt_account_id: Option, + organization_id: Option, } fn write_auth_file(params: AuthFileParams, codex_home: &Path) -> std::io::Result { @@ -629,6 +635,9 @@ fn fake_jwt_for_auth_file_params(params: &AuthFileParams) -> std::io::Result, forced_chatgpt_workspace_id: Option>, + forced_chatgpt_org_id: Option>, ) -> 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(), ) diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index 3f7d5f4236..f7f48e137f 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -547,6 +547,7 @@ pub struct AuthConfig { pub auth_credentials_store_mode: AuthCredentialsStoreMode, pub forced_login_method: Option, pub forced_chatgpt_workspace_id: Option>, + pub forced_chatgpt_org_id: Option>, } 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>>, + forced_chatgpt_org_id: RwLock>>, refresh_lock: AsyncMutex<()>, external_auth: RwLock>>, 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>; + + /// Returns the org IDs that ChatGPT auth should be restricted to, if any. + fn forced_chatgpt_org_id(&self) -> Option>; } 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 @@ -1472,6 +1521,22 @@ impl AuthManager { .and_then(|guard| guard.clone()) } + pub fn set_forced_chatgpt_org_id(&self, org_id: Option>) { + 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> { + 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 } diff --git a/codex-rs/login/src/device_code_auth.rs b/codex-rs/login/src/device_code_auth.rs index 4b9cb7c321..9f13f7a565 100644 --- a/codex-rs/login/src/device_code_auth.rs +++ b/codex-rs/login/src/device_code_auth.rs @@ -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)); diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index 0947340e59..bc240121fc 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -65,6 +65,7 @@ pub struct ServerOptions { pub open_browser: bool, pub force_state: Option, pub forced_chatgpt_workspace_id: Option>, + pub forced_chatgpt_org_id: Option>, pub cli_auth_credentials_store_mode: AuthCredentialsStoreMode, } @@ -74,6 +75,7 @@ impl ServerOptions { codex_home: PathBuf, client_id: String, forced_chatgpt_workspace_id: Option>, + forced_chatgpt_org_id: Option>, 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 { &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 { 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. diff --git a/codex-rs/login/src/token_data.rs b/codex-rs/login/src/token_data.rs index 2952ecb2a7..ccfa17294c 100644 --- a/codex-rs/login/src/token_data.rs +++ b/codex-rs/login/src/token_data.rs @@ -36,6 +36,8 @@ pub struct IdTokenInfo { pub chatgpt_user_id: Option, /// Organization/workspace identifier associated with the token, if present. pub chatgpt_account_id: Option, + /// Organization identifier associated with the token, if present. + pub organization_id: Option, /// 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, #[serde(default)] + organization_id: Option, + #[serde(default)] chatgpt_account_is_fedramp: bool, } @@ -147,6 +151,7 @@ pub fn parse_chatgpt_jwt_claims(jwt: &str) -> Result Ok(IdTokenInfo { @@ -155,6 +160,7 @@ pub fn parse_chatgpt_jwt_claims(jwt: &str) -> Result 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; diff --git a/codex-rs/login/tests/suite/login_server_e2e.rs b/codex-rs/login/tests/suite/login_server_e2e.rs index cc203601cc..12ed67b871 100644 --- a/codex-rs/login/tests/suite/login_server_e2e.rs +++ b/codex-rs/login/tests/suite/login_server_e2e.rs @@ -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)?; diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index a5efcd1ea2..7f8908376f 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -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); diff --git a/codex-rs/tui/src/local_chatgpt_auth.rs b/codex-rs/tui/src/local_chatgpt_auth.rs index 270d64f5f7..8d50cf133b 100644 --- a/codex-rs/tui/src/local_chatgpt_auth.rs +++ b/codex-rs/tui/src/local_chatgpt_auth.rs @@ -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 { 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");