Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Add an advisory Bedrock GovCloud requirements check (#49817)

alexsong-oaia5eac80150fb
diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst
index b7a833ce65..4a62d11ee9 100644
Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst differ
diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs
index 1aec8bbd45..e4a3e80366 100644
--- a/codex-rs/app-server-protocol/src/protocol/common.rs
+++ b/codex-rs/app-server-protocol/src/protocol/common.rs
@@ -1300,6 +1300,13 @@ client_request_definitions! {
response: v2::BedrockSetupResponse,
},
+ #[experimental("account/bedrock/checkGovCloudRequirements")]
+ BedrockCheckGovCloudRequirements => "account/bedrock/checkGovCloudRequirements" {
+ params: v2::BedrockCheckGovCloudRequirementsParams,
+ serialization: global("account-auth"),
+ response: v2::BedrockCheckGovCloudRequirementsResponse,
+ },
+
CancelLoginAccount => "account/login/cancel" {
params: v2::CancelLoginAccountParams,
serialization: global("account-auth"),
diff --git a/codex-rs/app-server-protocol/src/protocol/v2/bedrock.rs b/codex-rs/app-server-protocol/src/protocol/v2/bedrock.rs
index effd6f906a..c59dd2b18e 100644
--- a/codex-rs/app-server-protocol/src/protocol/v2/bedrock.rs
+++ b/codex-rs/app-server-protocol/src/protocol/v2/bedrock.rs
@@ -60,3 +60,20 @@ pub enum BedrockSetupParams {
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct BedrockSetupResponse {}
+
+#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, JsonSchema, TS)]
+#[serde(rename_all = "camelCase")]
+#[ts(export_to = "v2/")]
+pub struct BedrockCheckGovCloudRequirementsParams {}
+
+/// Advisory check of the current Bedrock configuration after login or setup.
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
+#[serde(rename_all = "camelCase")]
+#[ts(export_to = "v2/")]
+pub struct BedrockCheckGovCloudRequirementsResponse {
+ /// Whether the active Bedrock authentication resolves to a GovCloud region.
+ pub is_gov_cloud: bool,
+ /// Whether GovCloud is selected and the managed requirements miss the baseline.
+ /// A false value is not a general certification of the network configuration.
+ pub should_warn: bool,
+}
diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md
index 64aef0e2de..6607c97ca4 100644
--- a/codex-rs/app-server/README.md
+++ b/codex-rs/app-server/README.md
@@ -231,6 +231,18 @@ AWS profile `credential_process` commands are run by the AWS SDK; their network
the application's HTTP policy. Configured credential exporters and AWS reauthentication commands
require unrestricted application policy; policy revocation cancels their active work.
+After Bedrock login or setup, clients can call the experimental
+`account/bedrock/checkGovCloudRequirements` with `{}`. The server reloads configuration and
+requirements and returns `{ isGovCloud, shouldWarn }`. An explicitly configured official
+Bedrock endpoint hostname determines the region; with no URL or a custom proxy URL, the check
+resolves the AWS region using the current authentication state. It does not reload saved
+credentials or change login policy.
+For GovCloud, the advisory check requires API-only login and enabled managed application
+network restrictions with an explicit allow entry for the active Bedrock endpoint's domain.
+Non-Bedrock providers and commercial regions return both fields as `false`. Configuration or
+region resolution failures return an RPC error. This check does not block login or certify
+the entire network configuration.
+
## Stored thread attachments
- `thread/attachment/add` — add a durable resource reference to a stored thread without loading it. Repeated writes with the same attachment type and identity key return the existing attachment.
diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs
index 796ecf2fc8..8c883373be 100644
--- a/codex-rs/app-server/src/message_processor.rs
+++ b/codex-rs/app-server/src/message_processor.rs
@@ -1751,6 +1751,11 @@ impl MessageProcessor {
ClientRequest::BedrockSetup { params, .. } => {
self.account_processor.bedrock_setup(params).await
}
+ ClientRequest::BedrockCheckGovCloudRequirements { .. } => {
+ self.account_processor
+ .bedrock_check_gov_cloud_requirements()
+ .await
+ }
ClientRequest::GatewayOAuthRead { .. } => {
Box::pin(self.account_processor.gateway_oauth_read())
.await
diff --git a/codex-rs/app-server/src/request_processors/account_processor.rs b/codex-rs/app-server/src/request_processors/account_processor.rs
index 401b4cc584..eeaba7882e 100644
--- a/codex-rs/app-server/src/request_processors/account_processor.rs
+++ b/codex-rs/app-server/src/request_processors/account_processor.rs
@@ -16,6 +16,7 @@ use codex_model_provider::is_supported_amazon_bedrock_region;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
+mod bedrock_gov_cloud;
mod bedrock_setup;
mod enterprise_login;
mod gateway_oauth;
diff --git a/codex-rs/app-server/src/request_processors/account_processor/bedrock_gov_cloud.rs b/codex-rs/app-server/src/request_processors/account_processor/bedrock_gov_cloud.rs
new file mode 100644
index 0000000000..77fcae530d
--- /dev/null
+++ b/codex-rs/app-server/src/request_processors/account_processor/bedrock_gov_cloud.rs
@@ -0,0 +1,107 @@
+//! Post-login GovCloud checks use current authentication and freshly loaded configuration.
+//! Official endpoint hostnames take precedence over credential and configured AWS regions.
+//! Results are advisory; configuration and region resolution failures remain RPC errors.
+
+use super::AccountRequestProcessor;
+use crate::error_code::internal_error;
+use codex_app_server_protocol::BedrockCheckGovCloudRequirementsResponse;
+use codex_app_server_protocol::ClientResponsePayload;
+use codex_app_server_protocol::JSONRPCErrorError;
+use codex_config::NetworkDomainPermissionToml;
+use codex_model_provider::is_amazon_bedrock_gov_cloud_region;
+use codex_model_provider::resolve_amazon_bedrock_region;
+use codex_protocol::config_types::ForcedLoginMethod;
+
+impl AccountRequestProcessor {
+ pub(crate) async fn bedrock_check_gov_cloud_requirements(
+ &self,
+ ) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
+ let config = self
+ .config_manager
+ .load_latest_config(/*fallback_cwd*/ None)
+ .await
+ .map_err(|err| internal_error(format!("failed to load configuration: {err}")))?;
+ let provider = &config.model_provider;
+ if !provider.is_amazon_bedrock() {
+ return Ok(Some(
+ BedrockCheckGovCloudRequirementsResponse {
+ is_gov_cloud: false,
+ should_warn: false,
+ }
+ .into(),
+ ));
+ }
+
+ let endpoint_domain = provider
+ .base_url
+ .as_deref()
+ .map(|base_url| {
+ url::Url::parse(base_url)
+ .ok()
+ .and_then(|url| {
+ url.host_str()
+ .map(|host| host.trim_end_matches('.').to_string())
+ })
+ .ok_or_else(|| internal_error("Amazon Bedrock endpoint has no valid hostname"))
+ })
+ .transpose()?;
+ let endpoint_region = endpoint_domain.as_deref().and_then(|domain| {
+ let (service, rest) = domain.split_once('.')?;
+ let region = match service {
+ "bedrock-mantle" => rest.strip_suffix(".api.aws"),
+ "bedrock-runtime" | "bedrock-runtime-fips" => rest.strip_suffix(".amazonaws.com"),
+ _ => None,
+ }?;
+ // Require a single region label, not a substring in a proxy hostname.
+ (!region.is_empty() && !region.contains('.')).then_some(region)
+ });
+ let region = match endpoint_region {
+ Some(region) => region.to_string(),
+ None => {
+ resolve_amazon_bedrock_region(provider.clone(), Some(self.auth_manager.clone()))
+ .await
+ .map_err(|err| {
+ internal_error(format!("failed to resolve Amazon Bedrock region: {err}"))
+ })?
+ }
+ };
+ let is_gov_cloud = is_amazon_bedrock_gov_cloud_region(&region);
+ let mut should_warn = false;
+ if is_gov_cloud {
+ let domain = if let Some(domain) = endpoint_domain {
+ domain
+ } else if provider.is_amazon_bedrock_runtime() {
+ format!("bedrock-runtime.{region}.amazonaws.com")
+ } else {
+ format!("bedrock-mantle.{region}.api.aws")
+ };
+ let requirements = config.config_layer_stack.requirements_toml();
+ let api_only = requirements
+ .allowed_login_methods
+ .as_ref()
+ .is_some_and(|methods| {
+ !methods.is_empty()
+ && methods
+ .iter()
+ .all(|method| *method == ForcedLoginMethod::Api)
+ });
+ let network_allowed = requirements
+ .application
+ .as_ref()
+ .and_then(|application| application.network.as_ref())
+ .is_some_and(|network| {
+ network.enabled
+ && network.domains.get(&domain) == Some(&NetworkDomainPermissionToml::Allow)
+ });
+ should_warn = !api_only || !network_allowed;
+ }
+
+ Ok(Some(
+ BedrockCheckGovCloudRequirementsResponse {
+ is_gov_cloud,
+ should_warn,
+ }
+ .into(),
+ ))
+ }
+}
diff --git a/codex-rs/app-server/tests/suite/v2/bedrock_gov_cloud_tests.rs b/codex-rs/app-server/tests/suite/v2/bedrock_gov_cloud_tests.rs
new file mode 100644
index 0000000000..e4a4d53a36
--- /dev/null
+++ b/codex-rs/app-server/tests/suite/v2/bedrock_gov_cloud_tests.rs
@@ -0,0 +1,223 @@
+//! GovCloud checks use current login state and refresh managed requirements without a restart.
+
+use anyhow::Result;
+use app_test_support::TestAppServer;
+use codex_app_server_protocol::BedrockCheckGovCloudRequirementsParams;
+use codex_app_server_protocol::ClientRequest;
+use codex_app_server_protocol::LoginAccountParams;
+use codex_app_server_protocol::LoginAccountResponse;
+use codex_app_server_protocol::RequestId;
+use codex_config::types::AuthCredentialsStoreMode;
+use codex_login::AuthKeyringBackendKind;
+use codex_login::login_with_bedrock_api_key;
+use pretty_assertions::assert_eq;
+use serde_json::Value;
+use serde_json::json;
+use tempfile::TempDir;
+use test_case::test_case;
+
+const BASELINE: &str = r#"
+allowed_login_methods = ["api"]
+[application.network]
+enabled = true
+[application.network.domains]
+"bedrock-mantle.us-gov-west-1.api.aws" = "allow"
+"#;
+
+async fn check(server: &mut TestAppServer) -> Result<Value> {
+ server
+ .request(
+ |request_id| ClientRequest::BedrockCheckGovCloudRequirements {
+ request_id,
+ params: BedrockCheckGovCloudRequirementsParams {},
+ },
+ )
+ .await
+}
+
+#[tokio::test]
+async fn checks_current_provider_after_login_without_restart() -> Result<()> {
+ let home = TempDir::new()?;
+ std::fs::write(home.path().join("config.toml"), "")?;
+ login_with_bedrock_api_key(
+ home.path(),
+ "test-key",
+ "us-gov-west-1",
+ AuthCredentialsStoreMode::File,
+ AuthKeyringBackendKind::default(),
+ )?;
+ let mut server = TestAppServer::builder()
+ .with_codex_home(home.path())
+ .build_initialized()
+ .await?;
+ assert_eq!(
+ check(&mut server).await?,
+ json!({"isGovCloud": false, "shouldWarn": false})
+ );
+ // GovCloud onboarding is enabled separately. Select the provider using the
+ // existing login so stale startup configuration produces a different result.
+ std::fs::write(
+ home.path().join("config.toml"),
+ "model_provider = 'amazon-bedrock'\n",
+ )?;
+ assert_eq!(
+ check(&mut server).await?,
+ json!({"isGovCloud": true, "shouldWarn": true})
+ );
+ let _: LoginAccountResponse = server
+ .request(|request_id| ClientRequest::LoginAccount {
+ request_id,
+ params: LoginAccountParams::AmazonBedrock {
+ api_key: "test-key".to_string(),
+ region: "us-west-2".to_string(),
+ },
+ })
+ .await?;
+ assert_eq!(
+ check(&mut server).await?,
+ json!({"isGovCloud": false, "shouldWarn": false})
+ );
+
+ Ok(())
+}
+
+#[test_case("amazon-bedrock", "", "bedrock-mantle.us-gov-west-1.api.aws"; "mantle")]
+#[test_case("amazon-bedrock-runtime", "", "bedrock-runtime.us-gov-west-1.amazonaws.com"; "runtime")]
+#[test_case("amazon-bedrock", "[model_providers.amazon-bedrock]\nbase_url = 'https://bedrock.example.com/openai/v1'", "bedrock.example.com"; "custom_endpoint")]
+#[tokio::test]
+async fn checks_required_policy_fields_and_endpoint(
+ provider: &str,
+ provider_config: &str,
+ domain: &str,
+) -> Result<()> {
+ let home = TempDir::new()?;
+ std::fs::write(
+ home.path().join("config.toml"),
+ format!("model_provider = '{provider}'\n{provider_config}\n"),
+ )?;
+ login_with_bedrock_api_key(
+ home.path(),
+ "test-key",
+ "us-gov-west-1",
+ AuthCredentialsStoreMode::File,
+ AuthKeyringBackendKind::default(),
+ )?;
+ let mut server = TestAppServer::builder()
+ .with_codex_home(home.path())
+ .build_initialized()
+ .await?;
+ let baseline = BASELINE.replace("bedrock-mantle.us-gov-west-1.api.aws", domain);
+ for (requirements, should_warn) in [
+ (
+ baseline.replace("[\"api\"]", "[\"api\", \"chatgpt\"]"),
+ true,
+ ),
+ (baseline.replace("enabled = true", "enabled = false"), true),
+ (baseline.replace("\"allow\"", "\"deny\""), true),
+ (baseline, false),
+ ] {
+ std::fs::write(home.path().join("requirements.toml"), &requirements)?;
+ assert_eq!(
+ check(&mut server).await?,
+ json!({"isGovCloud": true, "shouldWarn": should_warn}),
+ "{requirements}"
+ );
+ }
+ std::fs::write(home.path().join("requirements.toml"), "[invalid toml")?;
+ let request_id = server
+ .send_request("account/bedrock/checkGovCloudRequirements", Some(json!({})))
+ .await?;
+ let error = tokio::time::timeout(
+ std::time::Duration::from_secs(/*secs*/ 10),
+ server.read_stream_until_error_message(RequestId::Integer(request_id)),
+ )
+ .await??;
+ assert_eq!((error.error.code, error.error.data), (-32603, None));
+ assert!(
+ error
+ .error
+ .message
+ .starts_with("failed to load configuration:")
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn check_preserves_current_login_when_saved_credentials_are_unreadable() -> Result<()> {
+ let home = TempDir::new()?;
+ std::fs::write(
+ home.path().join("config.toml"),
+ "model_provider = 'amazon-bedrock'\ncli_auth_credentials_store = 'file'\n",
+ )?;
+ login_with_bedrock_api_key(
+ home.path(),
+ "test-key",
+ "us-gov-west-1",
+ AuthCredentialsStoreMode::File,
+ AuthKeyringBackendKind::default(),
+ )?;
+ let mut server = TestAppServer::builder()
+ .with_codex_home(home.path())
+ .build_initialized()
+ .await?;
+
+ // The advisory must keep using the running session's credentials even when
+ // its persistent credential store becomes unreadable.
+ std::fs::write(home.path().join("auth.json"), "invalid json")?;
+ assert_eq!(
+ check(&mut server).await?,
+ json!({"isGovCloud": true, "shouldWarn": true})
+ );
+ std::fs::write(home.path().join("requirements.toml"), BASELINE)?;
+ assert_eq!(
+ check(&mut server).await?,
+ json!({"isGovCloud": true, "shouldWarn": false})
+ );
+ Ok(())
+}
+
+#[test_case("bedrock-mantle.us-gov-west-1.api.aws", "us-west-2", true; "mantle_url_overrides_commercial_region")]
+#[test_case("bedrock-runtime.us-gov-east-1.amazonaws.com", "us-west-2", true; "runtime_url_overrides_commercial_region")]
+#[test_case("bedrock-runtime-fips.us-gov-west-1.amazonaws.com", "us-west-2", true; "fips_url_overrides_commercial_region")]
+#[test_case("bedrock-mantle.us-west-2.api.aws", "us-gov-west-1", false; "commercial_url_overrides_govcloud_region")]
+#[test_case("bedrock-mantle.us-gov-west-1.api.aws.example.com", "us-west-2", false; "lookalike_proxy_uses_region")]
+#[tokio::test]
+async fn official_endpoint_takes_precedence_over_auth_region(
+ domain: &str,
+ auth_region: &str,
+ is_gov_cloud: bool,
+) -> Result<()> {
+ let home = TempDir::new()?;
+ std::fs::write(
+ home.path().join("config.toml"),
+ format!(
+ "model_provider = 'amazon-bedrock'\n\
+ [model_providers.amazon-bedrock]\n\
+ base_url = 'https://{domain}/openai/v1'\n"
+ ),
+ )?;
+ login_with_bedrock_api_key(
+ home.path(),
+ "test-key",
+ auth_region,
+ AuthCredentialsStoreMode::File,
+ AuthKeyringBackendKind::default(),
+ )?;
+ let mut server = TestAppServer::builder()
+ .with_codex_home(home.path())
+ .build_initialized()
+ .await?;
+ assert_eq!(
+ check(&mut server).await?,
+ json!({"isGovCloud": is_gov_cloud, "shouldWarn": is_gov_cloud})
+ );
+ std::fs::write(
+ home.path().join("requirements.toml"),
+ BASELINE.replace("bedrock-mantle.us-gov-west-1.api.aws", domain),
+ )?;
+ assert_eq!(
+ check(&mut server).await?,
+ json!({"isGovCloud": is_gov_cloud, "shouldWarn": false})
+ );
+ Ok(())
+}
diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs
index 804987396f..f52cdac971 100644
--- a/codex-rs/app-server/tests/suite/v2/mod.rs
+++ b/codex-rs/app-server/tests/suite/v2/mod.rs
@@ -12,6 +12,8 @@ mod attestation;
#[path = "auth_storage_originator_tests.rs"]
mod auth_storage_originator;
mod auto_env;
+#[path = "bedrock_gov_cloud_tests.rs"]
+mod bedrock_gov_cloud;
mod bedrock_setup;
mod client_metadata;
mod code_mode_host;
diff --git a/codex-rs/model-provider/src/amazon_bedrock/mantle.rs b/codex-rs/model-provider/src/amazon_bedrock/mantle.rs
index 9406c6b7ea..28fa1660f9 100644
--- a/codex-rs/model-provider/src/amazon_bedrock/mantle.rs
+++ b/codex-rs/model-provider/src/amazon_bedrock/mantle.rs
@@ -43,8 +43,12 @@ pub(super) fn region_from_config(aws: &ModelProviderAwsAuthInfo) -> Option<Strin
/// Returns whether Amazon Bedrock Mantle is available in `region`.
pub fn is_supported_amazon_bedrock_region(region: &str) -> bool {
- BEDROCK_MANTLE_SUPPORTED_REGIONS.contains(&region)
- || BEDROCK_GOV_CLOUD_SUPPORTED_REGIONS.contains(&region)
+ BEDROCK_MANTLE_SUPPORTED_REGIONS.contains(&region) || is_amazon_bedrock_gov_cloud_region(region)
+}
+
+/// Returns whether `region` is a supported Amazon Bedrock GovCloud region.
+pub fn is_amazon_bedrock_gov_cloud_region(region: &str) -> bool {
+ BEDROCK_GOV_CLOUD_SUPPORTED_REGIONS.contains(&region)
}
pub(super) fn base_url(region: &str) -> Result<String> {
diff --git a/codex-rs/model-provider/src/amazon_bedrock/mod.rs b/codex-rs/model-provider/src/amazon_bedrock/mod.rs
index 84c1d05a25..3f7131f577 100644
--- a/codex-rs/model-provider/src/amazon_bedrock/mod.rs
+++ b/codex-rs/model-provider/src/amazon_bedrock/mod.rs
@@ -4,6 +4,7 @@ mod catalog;
mod credential_export;
mod error;
mod mantle;
+mod region;
mod runtime;
mod runtime_catalog;
@@ -47,7 +48,9 @@ use catalog::static_gov_model_catalog;
pub(crate) use catalog::static_model_catalog;
pub(crate) use credential_export::AwsCredentialExport;
use mantle::bedrock_mantle_runtime_base_url;
+pub use mantle::is_amazon_bedrock_gov_cloud_region;
pub use mantle::is_supported_amazon_bedrock_region;
+pub use region::resolve_amazon_bedrock_region;
use runtime::bedrock_runtime_base_url;
use runtime_catalog::static_runtime_model_catalog;
diff --git a/codex-rs/model-provider/src/amazon_bedrock/region.rs b/codex-rs/model-provider/src/amazon_bedrock/region.rs
new file mode 100644
index 0000000000..d1791ae299
--- /dev/null
+++ b/codex-rs/model-provider/src/amazon_bedrock/region.rs
@@ -0,0 +1,35 @@
+//! Resolves the active Bedrock region using the same authentication precedence as requests.
+//! This does not validate model availability or issue an inference request.
+
+use std::sync::Arc;
+
+use codex_login::AuthManager;
+use codex_model_provider_info::ModelProviderInfo;
+use codex_protocol::error::Result;
+
+use super::AmazonBedrockModelProvider;
+use super::auth::resolve_region;
+
+/// Resolves a Bedrock provider's region independently of endpoint availability.
+pub async fn resolve_amazon_bedrock_region(
+ provider_info: ModelProviderInfo,
+ auth_manager: Option<Arc<AuthManager>>,
+) -> Result<String> {
+ let provider = AmazonBedrockModelProvider::new(provider_info, auth_manager);
+ let managed_auth = provider.managed_auth();
+ let factory = provider.http_client_factory.clone().with_network_policy(
+ provider
+ .http_client_factory
+ .network_policy()
+ .clone()
+ .for_current_account(),
+ );
+ resolve_region(
+ provider.auth_source(),
+ managed_auth.as_ref(),
+ &provider.aws,
+ provider.endpoint,
+ &factory,
+ )
+ .await
+}
diff --git a/codex-rs/model-provider/src/lib.rs b/codex-rs/model-provider/src/lib.rs
index 2eefe68bb7..825bd669b0 100644
--- a/codex-rs/model-provider/src/lib.rs
+++ b/codex-rs/model-provider/src/lib.rs
@@ -13,7 +13,9 @@ pub use workspace_routing::ResolvedResponsesProvider;
pub use workspace_routing::ResponsesConnectionKey;
pub use workspace_routing::WorkspaceRoutingContext;
+pub use amazon_bedrock::is_amazon_bedrock_gov_cloud_region;
pub use amazon_bedrock::is_supported_amazon_bedrock_region;
+pub use amazon_bedrock::resolve_amazon_bedrock_region;
pub use auth::AgentIdentitySessionFallback;
pub use auth::ProviderAuthScope;
pub use auth::ResolvedProviderAuth;