mirror of
https://github.com/openai/codex.git
synced 2026-11-29 00:00:54 +00:00
[codex] close workload identity review gaps [ci changed_files]
This commit is contained in:
Generated
+1
@@ -4493,6 +4493,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"codex-workload-identity",
|
||||
"spiffe",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
|
||||
@@ -246,16 +246,7 @@ impl CatalogRequestProcessor {
|
||||
}
|
||||
|
||||
async fn auth_for_optional_workspace_settings(&self) -> Option<CodexAuth> {
|
||||
match self.auth_manager.auth().await {
|
||||
Ok(auth) => auth,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
error = %err,
|
||||
"failed to resolve auth for optional workspace settings; using defaults"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
self.auth_manager.auth_for_optional_use().await
|
||||
}
|
||||
|
||||
async fn list_models(
|
||||
|
||||
@@ -421,6 +421,42 @@ async fn workload_identity_rejects_forced_api_key_login() -> anyhow::Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn workload_identity_rejects_external_filesystem_enforcement() -> anyhow::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let cfg = ConfigToml {
|
||||
workload_identity: Some(WorkloadIdentityConfig {
|
||||
identity_provider_id: "idp_example".to_string(),
|
||||
identity_provider_mapping_id: "idpm_example".to_string(),
|
||||
audience: "openai-audience".to_string(),
|
||||
token_url: "https://auth.openai.com/oauth/token".to_string(),
|
||||
credential_source: CredentialSourceConfig::File {
|
||||
path: codex_home.path().join("subject-token"),
|
||||
},
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let error = Config::load_from_base_config_with_overrides(
|
||||
cfg,
|
||||
ConfigOverrides {
|
||||
permission_profile: Some(PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
codex_home.abs(),
|
||||
)
|
||||
.await
|
||||
.expect_err("external filesystem enforcement must reject workload identity");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"`workload_identity` requires Codex-managed filesystem enforcement so credential paths can be denied"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn rotating_workload_credential_denies_its_secret_directory() -> anyhow::Result<()> {
|
||||
|
||||
@@ -3655,6 +3655,12 @@ impl Config {
|
||||
workload_identity.validate().map_err(|error| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidInput, error.to_string())
|
||||
})?;
|
||||
if effective_permission_profile.enforcement() == SandboxEnforcement::External {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"`workload_identity` requires Codex-managed filesystem enforcement so credential paths can be denied",
|
||||
));
|
||||
}
|
||||
let credential_deny_paths =
|
||||
workload_identity_credential_deny_paths(workload_identity);
|
||||
let enforcement_only_paths = credential_deny_paths
|
||||
|
||||
@@ -192,11 +192,12 @@ impl RequestPluginInstallHandler {
|
||||
.is_some_and(|response| response.action == ElicitationAction::Accept);
|
||||
|
||||
let completed = if user_confirmed {
|
||||
let auth = session.services.auth_manager.auth().await.map_err(|err| {
|
||||
FunctionCallError::Fatal(format!(
|
||||
"failed to resolve auth after plugin installation: {err}"
|
||||
))
|
||||
})?;
|
||||
let auth = session
|
||||
.services
|
||||
.auth_manager
|
||||
.auth()
|
||||
.await
|
||||
.map_err(model_safe_plugin_install_auth_error)?;
|
||||
verify_request_plugin_install_completed(&session, &turn, &tool, auth.as_ref()).await
|
||||
} else {
|
||||
false
|
||||
@@ -404,6 +405,14 @@ async fn refresh_missing_requested_connectors(
|
||||
}
|
||||
}
|
||||
|
||||
fn model_safe_plugin_install_auth_error(error: std::io::Error) -> FunctionCallError {
|
||||
warn!(
|
||||
error = %error,
|
||||
"failed to resolve auth after plugin installation"
|
||||
);
|
||||
FunctionCallError::Fatal("failed to resolve auth after plugin installation".to_string())
|
||||
}
|
||||
|
||||
fn verified_plugin_install_completed(
|
||||
tool_id: &str,
|
||||
config: &crate::config::Config,
|
||||
|
||||
@@ -68,6 +68,18 @@ fn remote_plugin_install_suggestions_skip_core_installed_verification() {
|
||||
assert!(!is_remote_plugin_install_suggestion("Plugin_123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_install_auth_error_redacts_credential_details() {
|
||||
let error = model_safe_plugin_install_auth_error(std::io::Error::other(
|
||||
"failed to read /run/secrets/codex-wif/subject-token",
|
||||
));
|
||||
|
||||
let FunctionCallError::Fatal(message) = error else {
|
||||
panic!("auth resolution should be a fatal tool error");
|
||||
};
|
||||
assert_eq!(message, "failed to resolve auth after plugin installation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recommended_plugin_install_args_accept_legacy_tool_id() {
|
||||
let current: RecommendedPluginInstallArgs = serde_json::from_value(json!({
|
||||
|
||||
@@ -562,6 +562,32 @@ fn external_auth_tokens_debug_redacts_access_token() {
|
||||
assert!(debug.contains("[REDACTED]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_auth_metadata_overrides_chatgpt_user_id_claim() {
|
||||
let token = fake_jwt_for_auth_file_params(&AuthFileParams {
|
||||
openai_api_key: None,
|
||||
chatgpt_plan_type: Some("enterprise".to_string()),
|
||||
chatgpt_account_id: Some(WORKSPACE_ID_ALLOWED.to_string()),
|
||||
})
|
||||
.expect("build test access token");
|
||||
let external = ExternalAuthTokens::chatgpt_with_user_id(
|
||||
token,
|
||||
"mapped-user-id",
|
||||
WORKSPACE_ID_ALLOWED,
|
||||
Some("enterprise".to_string()),
|
||||
);
|
||||
|
||||
let auth = AuthDotJson::from_external_tokens(&external).expect("build external ChatGPT auth");
|
||||
|
||||
assert_eq!(
|
||||
auth.tokens
|
||||
.expect("external auth should contain tokens")
|
||||
.id_token
|
||||
.chatgpt_user_id,
|
||||
Some("mapped-user-id".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
struct TestExternalChatgptAuth {
|
||||
initial: ExternalAuthTokens,
|
||||
refreshed: ExternalAuthTokens,
|
||||
@@ -670,6 +696,7 @@ async fn external_chatgpt_auth_resolves_and_refreshes_without_writing_auth_file(
|
||||
|
||||
assert_eq!(manager.auth_mode(), None);
|
||||
assert_eq!(manager.get_api_auth_mode(), None);
|
||||
assert!(!manager.current_auth_uses_codex_backend());
|
||||
let auth = manager
|
||||
.auth()
|
||||
.await
|
||||
@@ -687,6 +714,7 @@ async fn external_chatgpt_auth_resolves_and_refreshes_without_writing_auth_file(
|
||||
manager.get_api_auth_mode(),
|
||||
Some(AuthMode::ChatgptAuthTokens)
|
||||
);
|
||||
assert!(manager.current_auth_uses_codex_backend());
|
||||
assert_eq!(auth.get_token().unwrap(), token);
|
||||
assert_eq!(auth.get_account_id().as_deref(), Some(WORKSPACE_ID_ALLOWED));
|
||||
assert!(!get_auth_file(codex_home.path()).exists());
|
||||
@@ -795,6 +823,7 @@ async fn auth_result_preserves_external_auth_resolution_errors() {
|
||||
manager.get_api_auth_mode(),
|
||||
Some(ApiAuthMode::ChatgptAuthTokens)
|
||||
);
|
||||
assert!(!manager.current_auth_uses_codex_backend());
|
||||
let error = manager
|
||||
.auth_result()
|
||||
.await
|
||||
|
||||
@@ -215,6 +215,26 @@ pub fn build_reqwest_client() -> reqwest::Client {
|
||||
})
|
||||
}
|
||||
|
||||
/// Tries to build the default Codex HTTP client with redirects disabled.
|
||||
///
|
||||
/// Credential-bearing requests such as workload-identity token exchange must not replay their
|
||||
/// bodies to a redirect target. This keeps the normal Codex transport configuration while making
|
||||
/// any redirect visible to the caller as the original response.
|
||||
pub fn try_build_reqwest_client_without_redirects()
|
||||
-> Result<reqwest::Client, BuildCustomCaTransportError> {
|
||||
let builder = reqwest::Client::builder()
|
||||
.default_headers(default_headers())
|
||||
.redirect(reqwest::redirect::Policy::none());
|
||||
let builder = if is_sandboxed() {
|
||||
builder.no_proxy()
|
||||
} else {
|
||||
builder
|
||||
};
|
||||
let builder = with_chatgpt_cloudflare_cookie_store(builder);
|
||||
|
||||
build_reqwest_client_with_custom_ca(builder)
|
||||
}
|
||||
|
||||
/// Tries to build the default reqwest client used for ordinary Codex HTTP traffic.
|
||||
///
|
||||
/// Callers that need a structured CA-loading failure instead of the legacy logged fallback can use
|
||||
|
||||
@@ -41,6 +41,7 @@ use crate::auth::storage::create_auth_storage;
|
||||
use crate::auth::util::try_parse_error_message;
|
||||
use crate::default_client::build_reqwest_client;
|
||||
use crate::default_client::create_client;
|
||||
use crate::default_client::try_build_reqwest_client_without_redirects;
|
||||
use crate::token_data::TokenData;
|
||||
use crate::token_data::parse_chatgpt_jwt_claims;
|
||||
use crate::token_data::parse_jwt_expiration;
|
||||
@@ -141,6 +142,7 @@ impl Debug for ExternalAuthTokens {
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ExternalAuthChatgptMetadata {
|
||||
pub account_id: String,
|
||||
pub user_id: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
}
|
||||
|
||||
@@ -161,6 +163,23 @@ impl ExternalAuthTokens {
|
||||
access_token: access_token.into(),
|
||||
chatgpt_metadata: Some(ExternalAuthChatgptMetadata {
|
||||
account_id: chatgpt_account_id.into(),
|
||||
user_id: None,
|
||||
plan_type: chatgpt_plan_type,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn chatgpt_with_user_id(
|
||||
access_token: impl Into<String>,
|
||||
chatgpt_user_id: impl Into<String>,
|
||||
chatgpt_account_id: impl Into<String>,
|
||||
chatgpt_plan_type: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
access_token: access_token.into(),
|
||||
chatgpt_metadata: Some(ExternalAuthChatgptMetadata {
|
||||
account_id: chatgpt_account_id.into(),
|
||||
user_id: Some(chatgpt_user_id.into()),
|
||||
plan_type: chatgpt_plan_type,
|
||||
}),
|
||||
}
|
||||
@@ -1171,6 +1190,10 @@ impl AuthDotJson {
|
||||
let mut token_info =
|
||||
parse_chatgpt_jwt_claims(&external.access_token).map_err(std::io::Error::other)?;
|
||||
token_info.chatgpt_account_id = Some(chatgpt_metadata.account_id.clone());
|
||||
token_info.chatgpt_user_id = chatgpt_metadata
|
||||
.user_id
|
||||
.clone()
|
||||
.or(token_info.chatgpt_user_id);
|
||||
token_info.chatgpt_plan_type = chatgpt_metadata
|
||||
.plan_type
|
||||
.as_deref()
|
||||
@@ -2000,7 +2023,7 @@ impl AuthManager {
|
||||
let external_auth = shared_workload_identity_external_auth(
|
||||
workload_identity,
|
||||
oauth_client_id(),
|
||||
build_reqwest_client(),
|
||||
try_build_reqwest_client_without_redirects().map_err(std::io::Error::from),
|
||||
);
|
||||
auth_manager.set_external_auth(external_auth);
|
||||
}
|
||||
@@ -2239,6 +2262,15 @@ impl AuthManager {
|
||||
}
|
||||
|
||||
pub fn current_auth_uses_codex_backend(&self) -> bool {
|
||||
if self
|
||||
.external_auth()
|
||||
.is_some_and(|external_auth| external_auth.requires_successful_resolution())
|
||||
{
|
||||
return self
|
||||
.auth_cached()
|
||||
.as_ref()
|
||||
.is_some_and(|auth| auth.api_auth_mode().uses_codex_backend());
|
||||
}
|
||||
self.get_api_auth_mode()
|
||||
.is_some_and(AuthMode::uses_codex_backend)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ use super::ExternalAuthRefreshContext;
|
||||
use super::ExternalAuthTokens;
|
||||
|
||||
pub(super) struct WorkloadIdentityExternalAuth {
|
||||
client: ConfiguredWorkloadIdentityClient,
|
||||
client: Result<ConfiguredWorkloadIdentityClient, String>,
|
||||
process_isolation_error: Option<String>,
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ fn shared_workload_identity_auths() -> &'static Mutex<Vec<SharedWorkloadIdentity
|
||||
pub(super) fn shared_workload_identity_external_auth(
|
||||
config: WorkloadIdentityConfig,
|
||||
client_id: String,
|
||||
http: reqwest::Client,
|
||||
no_redirect_http: std::io::Result<reqwest::Client>,
|
||||
) -> Arc<dyn ExternalAuth> {
|
||||
let mut shared_auths = shared_workload_identity_auths()
|
||||
.lock()
|
||||
@@ -47,7 +47,11 @@ pub(super) fn shared_workload_identity_external_auth(
|
||||
}
|
||||
|
||||
let auth = Arc::new(WorkloadIdentityExternalAuth::new(
|
||||
build_workload_identity_client(config.clone(), client_id.clone(), http),
|
||||
no_redirect_http
|
||||
.map(|http| build_workload_identity_client(config.clone(), client_id.clone(), http))
|
||||
.map_err(|error| {
|
||||
format!("workload identity HTTP client initialization failed: {error}")
|
||||
}),
|
||||
));
|
||||
shared_auths.push(SharedWorkloadIdentityExternalAuth {
|
||||
config,
|
||||
@@ -58,7 +62,7 @@ pub(super) fn shared_workload_identity_external_auth(
|
||||
}
|
||||
|
||||
impl WorkloadIdentityExternalAuth {
|
||||
pub(super) fn new(client: ConfiguredWorkloadIdentityClient) -> Self {
|
||||
pub(super) fn new(client: Result<ConfiguredWorkloadIdentityClient, String>) -> Self {
|
||||
#[cfg(target_os = "windows")]
|
||||
// Core config forces WIF sessions onto the Windows restricted-token sandbox, which keeps
|
||||
// model-controlled child processes from opening the parent process.
|
||||
@@ -77,15 +81,20 @@ impl WorkloadIdentityExternalAuth {
|
||||
if let Some(error) = self.process_isolation_error.as_ref() {
|
||||
return Err(std::io::Error::other(error.clone()));
|
||||
}
|
||||
let client = self
|
||||
.client
|
||||
.as_ref()
|
||||
.map_err(|error| std::io::Error::other(error.clone()))?;
|
||||
let token = if force_refresh {
|
||||
self.client.refresh().await
|
||||
client.refresh().await
|
||||
} else {
|
||||
self.client.resolve().await
|
||||
client.resolve().await
|
||||
}
|
||||
.map_err(std::io::Error::other)?;
|
||||
|
||||
Ok(ExternalAuthTokens::chatgpt(
|
||||
Ok(ExternalAuthTokens::chatgpt_with_user_id(
|
||||
token.access_token,
|
||||
token.user_id,
|
||||
token.chatgpt_account_id,
|
||||
token.chatgpt_plan_type,
|
||||
))
|
||||
|
||||
@@ -21,12 +21,12 @@ fn identical_config_reuses_process_scoped_external_auth() {
|
||||
let first = shared_workload_identity_external_auth(
|
||||
config.clone(),
|
||||
"client-test".to_string(),
|
||||
reqwest::Client::new(),
|
||||
Ok(reqwest::Client::new()),
|
||||
);
|
||||
let second = shared_workload_identity_external_auth(
|
||||
config,
|
||||
"client-test".to_string(),
|
||||
reqwest::Client::new(),
|
||||
Ok(reqwest::Client::new()),
|
||||
);
|
||||
|
||||
assert!(Arc::ptr_eq(&first, &second));
|
||||
@@ -37,13 +37,32 @@ fn different_config_uses_distinct_external_auth() {
|
||||
let first = shared_workload_identity_external_auth(
|
||||
test_config("idpm_first"),
|
||||
"client-test".to_string(),
|
||||
reqwest::Client::new(),
|
||||
Ok(reqwest::Client::new()),
|
||||
);
|
||||
let second = shared_workload_identity_external_auth(
|
||||
test_config("idpm_second"),
|
||||
"client-test".to_string(),
|
||||
reqwest::Client::new(),
|
||||
Ok(reqwest::Client::new()),
|
||||
);
|
||||
|
||||
assert!(!Arc::ptr_eq(&first, &second));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_client_initialization_failure_is_preserved() {
|
||||
let auth = shared_workload_identity_external_auth(
|
||||
test_config("idpm_client_failure"),
|
||||
"client-test".to_string(),
|
||||
Err(std::io::Error::other("custom CA is invalid")),
|
||||
);
|
||||
|
||||
let error = auth
|
||||
.resolve()
|
||||
.await
|
||||
.expect_err("required WIF must fail when its HTTP client cannot be built");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"workload identity HTTP client initialization failed: custom CA is invalid"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::query_param;
|
||||
|
||||
#[tokio::test]
|
||||
async fn requests_runner_token_with_exact_audience() -> anyhow::Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(header("Authorization", "Bearer runner-request-secret"))
|
||||
.and(query_param("api-version", "2.0"))
|
||||
.and(query_param("audience", "openai-audience"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(serde_json::json!({"value": "github.actions.jwt"})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let source = GithubActionsSubjectTokenProvider {
|
||||
request_url: Some(format!("{}?api-version=2.0", server.uri())),
|
||||
request_token: Some("runner-request-secret".to_string()),
|
||||
audience: "openai-audience".to_string(),
|
||||
http: reqwest::Client::new(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
source.subject_token().await?,
|
||||
SubjectToken::jwt("github.actions.jwt", "github_actions")?
|
||||
);
|
||||
assert!(!format!("{source:?}").contains("runner-request-secret"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_runner_supplied_audience() -> anyhow::Result<()> {
|
||||
let source = GithubActionsSubjectTokenProvider {
|
||||
request_url: Some(
|
||||
"https://vstoken.actions.githubusercontent.com/token?audience=wrong&api-version=2.0"
|
||||
.to_string(),
|
||||
),
|
||||
request_token: Some("runner-request-secret".to_string()),
|
||||
audience: "openai-audience".to_string(),
|
||||
http: reqwest::Client::new(),
|
||||
};
|
||||
|
||||
let audiences = source
|
||||
.request_url()?
|
||||
.query_pairs()
|
||||
.filter(|(name, _)| name == "audience")
|
||||
.map(|(_, value)| value.into_owned())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(audiences, vec!["openai-audience"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_request_url_user_info_and_fragments() {
|
||||
for request_url in [
|
||||
"https://user@actions.githubusercontent.com/token",
|
||||
"https://actions.githubusercontent.com/token#fragment",
|
||||
] {
|
||||
let source = GithubActionsSubjectTokenProvider {
|
||||
request_url: Some(request_url.to_string()),
|
||||
request_token: Some("runner-request-secret".to_string()),
|
||||
audience: "openai-audience".to_string(),
|
||||
http: reqwest::Client::new(),
|
||||
};
|
||||
|
||||
assert!(matches!(
|
||||
source.request_url(),
|
||||
Err(SubjectTokenError::InvalidConfiguration {
|
||||
provider: "github_actions"
|
||||
})
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -139,86 +139,5 @@ struct OidcTokenResponse {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::query_param;
|
||||
|
||||
#[tokio::test]
|
||||
async fn requests_runner_token_with_exact_audience() -> anyhow::Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(header("Authorization", "Bearer runner-request-secret"))
|
||||
.and(query_param("api-version", "2.0"))
|
||||
.and(query_param("audience", "openai-audience"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(serde_json::json!({"value": "github.actions.jwt"})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let source = GithubActionsSubjectTokenProvider {
|
||||
request_url: Some(format!("{}?api-version=2.0", server.uri())),
|
||||
request_token: Some("runner-request-secret".to_string()),
|
||||
audience: "openai-audience".to_string(),
|
||||
http: reqwest::Client::new(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
source.subject_token().await?,
|
||||
SubjectToken::jwt("github.actions.jwt", "github_actions")?
|
||||
);
|
||||
assert!(!format!("{source:?}").contains("runner-request-secret"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_runner_supplied_audience() -> anyhow::Result<()> {
|
||||
let source = GithubActionsSubjectTokenProvider {
|
||||
request_url: Some(
|
||||
"https://vstoken.actions.githubusercontent.com/token?audience=wrong&api-version=2.0"
|
||||
.to_string(),
|
||||
),
|
||||
request_token: Some("runner-request-secret".to_string()),
|
||||
audience: "openai-audience".to_string(),
|
||||
http: reqwest::Client::new(),
|
||||
};
|
||||
|
||||
let audiences = source
|
||||
.request_url()?
|
||||
.query_pairs()
|
||||
.filter(|(name, _)| name == "audience")
|
||||
.map(|(_, value)| value.into_owned())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(audiences, vec!["openai-audience"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_request_url_user_info_and_fragments() {
|
||||
for request_url in [
|
||||
"https://user@actions.githubusercontent.com/token",
|
||||
"https://actions.githubusercontent.com/token#fragment",
|
||||
] {
|
||||
let source = GithubActionsSubjectTokenProvider {
|
||||
request_url: Some(request_url.to_string()),
|
||||
request_token: Some("runner-request-secret".to_string()),
|
||||
audience: "openai-audience".to_string(),
|
||||
http: reqwest::Client::new(),
|
||||
};
|
||||
|
||||
assert!(matches!(
|
||||
source.request_url(),
|
||||
Err(SubjectTokenError::InvalidConfiguration {
|
||||
provider: "github_actions"
|
||||
})
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[path = "github_actions_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -82,13 +82,13 @@ impl SubjectTokenProvider for ConfiguredSubjectTokenProvider {
|
||||
pub fn build_client(
|
||||
config: WorkloadIdentityConfig,
|
||||
client_id: impl Into<String>,
|
||||
http: reqwest::Client,
|
||||
no_redirect_http: reqwest::Client,
|
||||
) -> ConfiguredWorkloadIdentityClient {
|
||||
let source = ConfiguredSubjectTokenProvider::from_config(
|
||||
&config.credential_source,
|
||||
&config.identity_provider_id,
|
||||
&config.audience,
|
||||
http.clone(),
|
||||
no_redirect_http.clone(),
|
||||
);
|
||||
ConfiguredWorkloadIdentityClient::new(config, client_id, http, source)
|
||||
ConfiguredWorkloadIdentityClient::new(config, client_id, no_redirect_http, source)
|
||||
}
|
||||
|
||||
@@ -10,9 +10,11 @@ workspace = true
|
||||
[dependencies]
|
||||
codex-workload-identity = { workspace = true }
|
||||
spiffe = { workspace = true, features = ["workload-api-jwt"] }
|
||||
tokio = { workspace = true, features = ["time"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "time"] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_workload_identity::SubjectToken;
|
||||
use codex_workload_identity::SubjectTokenError;
|
||||
use codex_workload_identity::SubjectTokenProvider;
|
||||
use spiffe::SpiffeId;
|
||||
use spiffe::WorkloadApiClient;
|
||||
use spiffe::transport::Endpoint;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const SPIFFE_ENDPOINT_SOCKET_ENV: &str = "SPIFFE_ENDPOINT_SOCKET";
|
||||
#[cfg(not(test))]
|
||||
const WORKLOAD_API_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
#[cfg(test)]
|
||||
const WORKLOAD_API_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SpiffeSubjectTokenProvider {
|
||||
@@ -50,46 +57,21 @@ impl SubjectTokenProvider for SpiffeSubjectTokenProvider {
|
||||
.map(str::parse::<SpiffeId>)
|
||||
.transpose()
|
||||
.map_err(|_| SubjectTokenError::InvalidConfiguration { provider: "spiffe" })?;
|
||||
let client = WorkloadApiClient::connect(endpoint)
|
||||
.await
|
||||
.map_err(|_| SubjectTokenError::Unavailable { provider: "spiffe" })?;
|
||||
let jwt_svid = client
|
||||
.fetch_jwt_svid([self.audience.as_str()], spiffe_id.as_ref())
|
||||
.await
|
||||
.map_err(|_| SubjectTokenError::InvalidResponse { provider: "spiffe" })?;
|
||||
let jwt_svid = timeout(WORKLOAD_API_TIMEOUT, async {
|
||||
let client = WorkloadApiClient::connect(endpoint)
|
||||
.await
|
||||
.map_err(|_| SubjectTokenError::Unavailable { provider: "spiffe" })?;
|
||||
client
|
||||
.fetch_jwt_svid([self.audience.as_str()], spiffe_id.as_ref())
|
||||
.await
|
||||
.map_err(|_| SubjectTokenError::InvalidResponse { provider: "spiffe" })
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SubjectTokenError::Unavailable { provider: "spiffe" })??;
|
||||
SubjectToken::jwt(jwt_svid.token(), "spiffe")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_invalid_explicit_spiffe_id_before_connecting() {
|
||||
let source = SpiffeSubjectTokenProvider::new(
|
||||
Some("unix:/tmp/does-not-exist.sock".to_string()),
|
||||
Some("not-a-spiffe-id".to_string()),
|
||||
"openai-audience".to_string(),
|
||||
);
|
||||
|
||||
assert!(matches!(
|
||||
source.subject_token().await,
|
||||
Err(SubjectTokenError::InvalidConfiguration { provider: "spiffe" })
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_tcp_endpoint() {
|
||||
let source = SpiffeSubjectTokenProvider::new(
|
||||
Some("tcp://127.0.0.1:8081".to_string()),
|
||||
/*spiffe_id*/ None,
|
||||
"openai-audience".to_string(),
|
||||
);
|
||||
|
||||
assert!(matches!(
|
||||
source.subject_token().await,
|
||||
Err(SubjectTokenError::InvalidConfiguration { provider: "spiffe" })
|
||||
));
|
||||
}
|
||||
}
|
||||
#[path = "spiffe_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::future::pending;
|
||||
#[cfg(unix)]
|
||||
use tokio::net::UnixListener;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_invalid_explicit_spiffe_id_before_connecting() {
|
||||
let source = SpiffeSubjectTokenProvider::new(
|
||||
Some("unix:/tmp/does-not-exist.sock".to_string()),
|
||||
Some("not-a-spiffe-id".to_string()),
|
||||
"openai-audience".to_string(),
|
||||
);
|
||||
|
||||
assert!(matches!(
|
||||
source.subject_token().await,
|
||||
Err(SubjectTokenError::InvalidConfiguration { provider: "spiffe" })
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_tcp_endpoint() {
|
||||
let source = SpiffeSubjectTokenProvider::new(
|
||||
Some("tcp://127.0.0.1:8081".to_string()),
|
||||
/*spiffe_id*/ None,
|
||||
"openai-audience".to_string(),
|
||||
);
|
||||
|
||||
assert!(matches!(
|
||||
source.subject_token().await,
|
||||
Err(SubjectTokenError::InvalidConfiguration { provider: "spiffe" })
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn times_out_when_workload_api_stalls() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temporary SPIFFE socket directory");
|
||||
let socket_path = temp_dir.path().join("workload-api.sock");
|
||||
let listener = UnixListener::bind(&socket_path).expect("bind stalled Workload API socket");
|
||||
let stalled_server = tokio::spawn(async move {
|
||||
let _accepted = listener.accept().await.expect("accept Workload API client");
|
||||
pending::<()>().await;
|
||||
});
|
||||
let source = SpiffeSubjectTokenProvider::new(
|
||||
Some(format!("unix:{}", socket_path.display())),
|
||||
/*spiffe_id*/ None,
|
||||
"openai-audience".to_string(),
|
||||
);
|
||||
|
||||
let result = tokio::time::timeout(Duration::from_secs(2), source.subject_token())
|
||||
.await
|
||||
.expect("provider should enforce its own timeout");
|
||||
stalled_server.abort();
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(SubjectTokenError::Unavailable { provider: "spiffe" })
|
||||
));
|
||||
}
|
||||
@@ -94,7 +94,7 @@ pub struct WorkloadIdentityClient<S> {
|
||||
token_url: String,
|
||||
client_id: String,
|
||||
source: S,
|
||||
http: reqwest::Client,
|
||||
no_redirect_http: reqwest::Client,
|
||||
cache: Mutex<CacheState>,
|
||||
exchange_lock: Semaphore,
|
||||
}
|
||||
@@ -106,7 +106,7 @@ where
|
||||
pub fn new(
|
||||
config: WorkloadIdentityConfig,
|
||||
client_id: impl Into<String>,
|
||||
http: reqwest::Client,
|
||||
no_redirect_http: reqwest::Client,
|
||||
source: S,
|
||||
) -> Self {
|
||||
Self {
|
||||
@@ -115,7 +115,7 @@ where
|
||||
token_url: config.token_url,
|
||||
client_id: client_id.into(),
|
||||
source,
|
||||
http,
|
||||
no_redirect_http,
|
||||
cache: Mutex::new(CacheState::default()),
|
||||
exchange_lock: Semaphore::new(/*permits*/ 1),
|
||||
}
|
||||
@@ -221,7 +221,7 @@ where
|
||||
) -> Result<WorkloadIdentityAccessToken, WorkloadIdentityError> {
|
||||
let subject_token = self.source.subject_token().await?;
|
||||
let response = self
|
||||
.http
|
||||
.no_redirect_http
|
||||
.post(&self.token_url)
|
||||
.timeout(TOKEN_EXCHANGE_TIMEOUT)
|
||||
.json(&TokenExchangeRequest {
|
||||
|
||||
@@ -31,11 +31,43 @@ async fn test_client(
|
||||
},
|
||||
},
|
||||
"app_codex_cli",
|
||||
reqwest::Client::new(),
|
||||
reqwest::Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()?,
|
||||
FileSubjectTokenSource::new(token_file),
|
||||
))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn token_exchange_does_not_follow_redirects() -> anyhow::Result<()> {
|
||||
let redirect_target = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.respond_with(exchange_response("redirected.access.token"))
|
||||
.expect(0)
|
||||
.mount(&redirect_target)
|
||||
.await;
|
||||
let token_endpoint = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(307)
|
||||
.insert_header("Location", format!("{}/stolen", redirect_target.uri())),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&token_endpoint)
|
||||
.await;
|
||||
let client = test_client(&token_endpoint).await?;
|
||||
|
||||
assert!(matches!(
|
||||
client.resolve().await,
|
||||
Err(WorkloadIdentityError::Rejected { status, .. })
|
||||
if status == StatusCode::TEMPORARY_REDIRECT
|
||||
));
|
||||
token_endpoint.verify().await;
|
||||
redirect_target.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exchange_request() -> serde_json::Value {
|
||||
json!({
|
||||
"grant_type": TOKEN_EXCHANGE_GRANT_TYPE,
|
||||
|
||||
Reference in New Issue
Block a user