Cache Plugin Service signing keys for archive verification (#63490)

## Why

Verifying each signed plugin archive fetched the signing keys again, even
when the same Plugin Service credentials and key ID were used.

## What changed

Reuse signing keys within a plugin manager for the same Plugin Service
endpoint and request headers until the server-provided
`cache_ttl_seconds` expires. Requests without a non-empty
`Authorization` header fetch keys every time.

Fetch keys when the requested key ID is missing or the cache expires.
Serialize refreshes within each scope and clear the previous keys before
fetching so a failed refresh leaves no cached keys to reuse.

## Testing

Add coverage for cache reuse and expiry, missing key IDs, invalidation
after a denied refresh, and recovery after a canceled refresh. Exercise
reuse and isolation across plugin managers through signed bundle downloads.

GitOrigin-RevId: cc1171d7914b904f6895a179cbb0cf55ffa537d3
This commit is contained in:
Alex Ionescu
2026-11-24 01:30:26 +00:00
committed by copyberry
parent e173e7b9b2
commit 9340f3c232
15 changed files with 552 additions and 76 deletions
+1 -1
View File
@@ -10,6 +10,6 @@ codex_rust_crate(
"BUILD.bazel",
"Cargo.toml",
],
),
) + ["//codex-rs/plugin-archive-verification:testdata/plugin_archive_signing_v1.json"],
crate_name = "codex_core_plugins",
)
+14 -1
View File
@@ -123,6 +123,7 @@ use codex_plugin::PluginIdError;
use codex_plugin::PluginTelemetryMetadata;
use codex_plugin::app_connector_ids_from_declarations;
use codex_plugin::prompt_safe_plugin_description;
use codex_plugin_archive_verification::SigningKeyCache;
use codex_protocol::auth::AuthMode;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::Product;
@@ -241,6 +242,14 @@ impl PluginsConfigInput {
pub fn remote_plugin_service_config(
&self,
runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
) -> RemotePluginServiceConfig {
self.remote_plugin_service_config_with_signing_key_cache(runtime_auth, Arc::default())
}
pub(crate) fn remote_plugin_service_config_with_signing_key_cache(
&self,
runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
signing_key_cache: Arc<SigningKeyCache>,
) -> RemotePluginServiceConfig {
let runtime_auth = runtime_auth.filter(|_| {
codex_http_client::classify_openai_api_url(&self.chatgpt_base_url)
@@ -272,6 +281,7 @@ impl PluginsConfigInput {
.unwrap_or_else(|| CODEX_PRODUCT_SKU.to_string()),
http_clients: Arc::clone(http_clients),
runtime_auth,
signing_key_cache,
}
}
}
@@ -712,6 +722,7 @@ pub struct PluginsManager {
remote_installed_plugin_bundle_sync_gate: Arc<Semaphore>,
remote_installed_plugins_cache_refresh_state: RwLock<RemoteInstalledPluginsCacheRefreshState>,
remote_catalog_cache_refresh_state: RwLock<RemoteCatalogCacheRefreshState>,
signing_key_cache: Arc<SigningKeyCache>,
restriction_product: Option<Product>,
auth_manager: Arc<AuthManager>,
runtime_auth: RuntimeAuthSlot,
@@ -829,10 +840,11 @@ impl PluginsManager {
&self,
config: &PluginsConfigInput,
) -> RemotePluginServiceConfig {
config.remote_plugin_service_config(
config.remote_plugin_service_config_with_signing_key_cache(
config
.runtime_auth_mode
.map(|mode| (Arc::clone(&self.runtime_auth), mode)),
Arc::clone(&self.signing_key_cache),
)
}
@@ -939,6 +951,7 @@ impl PluginsManager {
remote_catalog_cache_refresh_state: RwLock::new(
RemoteCatalogCacheRefreshState::default(),
),
signing_key_cache: Arc::default(),
restriction_product,
auth_manager,
runtime_auth,
@@ -10,6 +10,7 @@ use crate::script_attribution::PluginMeasurementTarget;
use codex_features::RuntimeAuthMode;
use codex_login::CodexAuth;
use codex_plugin::PluginId;
use codex_plugin_archive_verification::SigningKeyCache;
use codex_runtime_agent_instance::RuntimeAuthSlot;
use codex_utils_path_uri::PathConvention;
use std::sync::Arc;
@@ -67,6 +68,7 @@ fn is_preparing(cell: &ReferenceCell) -> bool {
#[derive(Default)]
pub struct RemotePluginMeasurementCache {
references: Mutex<Vec<(ReferenceKey, ReferenceCell)>>,
signing_key_cache: Arc<SigningKeyCache>,
}
impl RemotePluginMeasurementCache {
@@ -96,7 +98,10 @@ impl RemotePluginMeasurementCache {
// GLOBAL plugins have already passed server-side admission; local
// marketplace product policy and skill capability loading are separate.
let service = config
.remote_plugin_service_config(runtime_auth)
.remote_plugin_service_config_with_signing_key_cache(
runtime_auth,
Arc::clone(&self.signing_key_cache),
)
.for_current_account();
let Some((remote_id, bundle)) = fetch_measurement_reference_bundle(&service, auth, target)
.await
@@ -1,6 +1,7 @@
//! Real bundle preparation tests without mutating the parent test environment.
use super::*;
use crate::test_support::isolated_loopback_bundle_test;
use crate::test_support::load_plugins_config;
use crate::test_support::write_file;
use anyhow::Context;
@@ -14,7 +15,6 @@ use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncReadExt;
@@ -32,26 +32,7 @@ const SCRIPT: &str = "console.log('installed');\n";
const ANALYTICS: &str = "version: 1\noperations:\n install:\n path: scripts/install.mjs\n measurements:\n duration_ms:\n dimensions:\n outcome: [success, error]\n";
fn isolated_bundle_test(name: &str) -> Result<bool> {
const CHILD: &str = "CODEX_MEASUREMENT_REFERENCE_TEST";
if std::env::var(CHILD).as_deref() == Ok(name) {
return Ok(true);
}
let output = Command::new(std::env::current_exe()?)
.args([
"--exact",
&format!("plugin_measurement_references::tests::{name}"),
"--nocapture",
])
.env(CHILD, name)
.env("CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", "1")
.output()?;
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Ok(false)
isolated_loopback_bundle_test(&format!("plugin_measurement_references::tests::{name}"))
}
fn installed(server: &MockServer, version: &str) -> Value {
+3
View File
@@ -35,6 +35,7 @@ use codex_plugin::app_connector_ids_from_declarations;
use codex_plugin::prompt_safe_plugin_description;
use codex_plugin_archive_verification::ArchiveVerificationFailure;
use codex_plugin_archive_verification::RemotePluginArchiveDownload;
use codex_plugin_archive_verification::SigningKeyCache;
use codex_runtime_agent_instance::RuntimeAuthSlot;
use codex_utils_absolute_path::AbsolutePathBuf;
use futures::future::BoxFuture;
@@ -160,6 +161,7 @@ pub struct RemotePluginServiceConfig {
pub(crate) product_sku: String,
pub(crate) http_clients: Arc<dyn HttpClientSelector>,
pub(crate) runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
pub(crate) signing_key_cache: Arc<SigningKeyCache>,
}
impl RemotePluginServiceConfig {
@@ -189,6 +191,7 @@ impl RemotePluginServiceConfig {
product_sku: product_sku.unwrap_or_else(|| CODEX_PRODUCT_SKU.to_string()),
http_clients,
runtime_auth: None,
signing_key_cache: Arc::default(),
}
}
+10 -3
View File
@@ -334,9 +334,12 @@ pub(crate) async fn download_remote_plugin_bundle(
.await?;
bundle
.archive_download
.verify(bytes, &config.chatgpt_base_url, |url| {
prepare_signing_key_request(config, url, auth)
})
.verify(
bytes,
&config.chatgpt_base_url,
&config.signing_key_cache,
|url| prepare_signing_key_request(config, url, auth),
)
.await
.map(|(bytes, _)| bytes)
.map_err(
@@ -1193,3 +1196,7 @@ mod tests {
#[cfg(test)]
#[path = "remote_bundle_runtime_auth_tests.rs"]
mod runtime_auth_tests;
#[cfg(test)]
#[path = "remote_bundle_signing_key_cache_tests.rs"]
mod signing_key_cache_tests;
@@ -0,0 +1,89 @@
#![cfg(test)]
//! Exercises cache reuse and isolation through the signed bundle download path.
use super::*;
use crate::test_support::isolated_loopback_bundle_test;
use crate::test_support::load_plugins_config;
use crate::test_support::test_auth_manager;
use crate::test_support::test_plugins_manager_with_auth_manager;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use codex_protocol::auth::AuthMode;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn signed_downloads_reuse_keys_only_within_the_same_plugin_manager() -> anyhow::Result<()> {
if !isolated_loopback_bundle_test(
"remote_bundle::signing_key_cache_tests::signed_downloads_reuse_keys_only_within_the_same_plugin_manager",
)? {
return Ok(());
}
let fixture: JsonValue = serde_json::from_str(include_str!(
"../../plugin-archive-verification/testdata/plugin_archive_signing_v1.json"
))?;
let archive = STANDARD.decode(fixture["archive_base64"].as_str().unwrap())?;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive.clone()))
.expect(3)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/signing-keys"))
.respond_with(ResponseTemplate::new(200).set_body_json(&fixture["signing_keys_response"]))
.expect(2)
.mount(&server)
.await;
let home = TempDir::new()?;
let mut config = load_plugins_config(home.path(), home.path()).await;
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt));
let auth = auth_manager.auth().await.unwrap();
let manager = test_plugins_manager_with_auth_manager(
home.path().to_path_buf(),
/*restriction_product*/ None,
Arc::clone(&auth_manager),
);
let other_manager = manager.for_auth_context(auth_manager, manager.runtime_auth_slot());
let download = serde_json::from_value(json!({
"bundle_download_url": format!("{}/bundle", server.uri()),
"signing": fixture["signing"],
}))?;
let bundle = validate_remote_plugin_bundle(
"plugins~Plugin_00000000000000000000000000000000",
REMOTE_GLOBAL_MARKETPLACE_NAME,
"sample",
Some("1.0.0"),
&download,
/*app_manifest*/ None,
)?;
for (manager, expected_key_requests) in [(&manager, 1), (&manager, 1), (&other_manager, 2)] {
let service = manager
.remote_plugin_service_config(&config)
.for_current_account();
assert_eq!(
download_remote_plugin_bundle(&service, Some(&auth), &bundle).await?,
archive
);
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests
.iter()
.filter(|request| request.url.path().ends_with("/signing-keys"))
.count(),
expected_key_requests,
);
}
Ok(())
}
+20
View File
@@ -387,6 +387,7 @@ pub(crate) fn recording_remote_plugin_service_config(
(
RemotePluginServiceConfig {
runtime_auth: None,
signing_key_cache: Arc::default(),
chatgpt_base_url,
product_sku: crate::remote::CODEX_PRODUCT_SKU.to_string(),
http_clients,
@@ -402,6 +403,25 @@ pub(crate) fn recorded_http_client_urls(selected_urls: &Mutex<Vec<String>>) -> V
}
}
pub(crate) fn isolated_loopback_bundle_test(test_name: &str) -> anyhow::Result<bool> {
const CHILD: &str = "CODEX_LOOPBACK_BUNDLE_TEST";
if std::env::var(CHILD).as_deref() == Ok(test_name) {
return Ok(true);
}
let output = std::process::Command::new(std::env::current_exe()?)
.args(["--exact", test_name, "--nocapture"])
.env(CHILD, test_name)
.env("CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", "1")
.output()?;
assert!(
output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Ok(false)
}
pub(crate) fn write_file(path: &Path, contents: &str) {
fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap();
fs::write(path, contents).unwrap();