Add an environment API key fallback for Guardian Decisions (#53633)

## What changed

Allow Guardian Decisions to use `OPENAI_API_KEY` when the default `openai` provider has no custom base URL and neither `CODEX_GUARDIAN_DECISIONS_API_KEY` nor a cached API key is available. Preserve cached API key precedence over the environment fallback.

Report missing credentials as `credentials_unavailable` instead of `provider_error` in Decisions failure metrics.

## Testing

Add tests for cached API key precedence and the environment fallback with ChatGPT authentication. Run each test in a child process to isolate environment changes.

GitOrigin-RevId: fbb772dcb9287d9e1be1b34292ad9bdffeb3d6b3
This commit is contained in:
swastik-oai
2026-10-13 10:43:13 +00:00
committed by copyberry
parent 6042ec37b0
commit 90f00bd89e
3 changed files with 59 additions and 1 deletions
@@ -1,9 +1,12 @@
use super::super::startup::decisions_api_key;
use super::*;
use codex_context_fragments::AnnotatedContent;
use codex_context_fragments::ContextualUserFragment;
use codex_guardian_context::TrustedTool;
use codex_guardian_context::TrustedToolSource;
use codex_http_client::HttpClientBuilder;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::models::ContentItemKind;
use pretty_assertions::assert_eq;
use wiremock::Mock;
@@ -156,6 +159,60 @@ async fn decisions_key_lookup_honors_override_or_reloaded_login() {
);
}
#[test]
fn decisions_prefers_cached_api_key_over_openai_env() -> anyhow::Result<()> {
// Bazel runs tests in a shared process. Set keys only in a child so other tests cannot see them.
if std::env::var_os("CODEX_GUARDIAN_DECISIONS_TEST_CHILD").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args(["--exact", std::thread::current().name().unwrap()])
.env("CODEX_GUARDIAN_DECISIONS_TEST_CHILD", "1")
.env_remove("CODEX_GUARDIAN_DECISIONS_API_KEY")
.env("OPENAI_API_KEY", "synthetic-env-key")
.output()?;
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"{stdout}{}",
String::from_utf8_lossy(&output.stderr)
);
return Ok(());
}
let auth_key = "synthetic-auth-key";
let cached = AuthManager::from_auth_for_testing(CodexAuth::from_api_key(auth_key));
assert!(
decisions_api_key("openai", /*base_url*/ None, &cached) == Ok(auth_key.into()),
"cached API-key auth must take priority over OPENAI_API_KEY"
);
Ok(())
}
#[test]
fn decisions_falls_back_to_openai_env_key() -> anyhow::Result<()> {
let env_key = "synthetic-env-key";
if std::env::var_os("CODEX_GUARDIAN_DECISIONS_TEST_CHILD").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args(["--exact", std::thread::current().name().unwrap()])
.env("CODEX_GUARDIAN_DECISIONS_TEST_CHILD", "1")
.env_remove("CODEX_GUARDIAN_DECISIONS_API_KEY")
.env("OPENAI_API_KEY", env_key)
.output()?;
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"{stdout}{}",
String::from_utf8_lossy(&output.stderr)
);
return Ok(());
}
let chatgpt =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
assert!(
decisions_api_key("openai", /*base_url*/ None, &chatgpt) == Ok(env_key.into()),
"use OPENAI_API_KEY when neither a Guardian key nor a cached API key is available"
);
Ok(())
}
#[tokio::test]
async fn http_contract_and_untrusted_response_validation() {
core_test_support::skip_if_no_network!();
@@ -184,7 +184,7 @@ pub(super) fn record_decisions_comparison_outcome(
// Keep all backend diagnostics bounded and free of raw transport data.
pub(super) fn decisions_failure_reason(error: DecisionsError) -> &'static str {
match error {
DecisionsError::Credentials => "provider_error",
DecisionsError::Credentials => "credentials_unavailable",
DecisionsError::ClientSetup => "request_build_error",
DecisionsError::UnsupportedEvidence => "decisions_unsupported_evidence",
DecisionsError::InputTooLarge => "input_too_large",
@@ -67,6 +67,7 @@ pub(super) fn decisions_api_key(
.as_ref()
.and_then(CodexAuth::api_key)
.map(str::to_owned)
.or_else(codex_login::read_openai_api_key_from_env)
.ok_or(DecisionsError::Credentials)
}
Err(std::env::VarError::NotPresent | std::env::VarError::NotUnicode(_)) => {