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();
@@ -1,5 +1,10 @@
load("//:defs.bzl", "codex_rust_crate")
exports_files(
["testdata/plugin_archive_signing_v1.json"],
visibility = ["//codex-rs/core-plugins:__pkg__"],
)
codex_rust_crate(
name = "plugin-archive-verification",
compile_data = ["testdata/plugin_archive_signing_v1.json"],
@@ -20,7 +20,7 @@ http = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["rt"] }
tokio = { workspace = true, features = ["rt", "sync"] }
tracing = { workspace = true }
[dev-dependencies]
@@ -1,34 +1,99 @@
//! Fetches and validates the signing keys returned by the authenticated Plugin Service endpoint.
//! Fetches authenticated Plugin Service signing keys. The bounded cache reuses keys only within the
//! same endpoint and credentials. Each lookup fetches at most once.
use crate::ArchiveVerificationFailure;
use aws_lc_rs::digest::Context;
use aws_lc_rs::digest::SHA256;
use codex_http_client::RequestBuilder;
use http::HeaderMap;
use http::header::AUTHORIZATION;
use serde::Deserialize;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::time::Duration;
use std::time::Instant;
use tokio::sync::Semaphore;
const MARKETPLACE_ARCHIVE_PURPOSE: &str = "PLUGIN_RELEASE_ARCHIVE_SIGNING";
const MAX_CACHED_SCOPES: usize = 8;
const MAX_SIGNING_KEYS: usize = 64;
const MAX_SIGNING_KEYS_RESPONSE_BYTES: usize = 128 * 1024;
const MAX_PUBLIC_KEY_BASE64_BYTES: usize = 16 * 1024;
pub(super) async fn signing_key<Fut>(
service_base_url: &str,
key_id: &str,
key_request: impl FnOnce(String) -> Fut,
) -> Result<SigningKey, ArchiveVerificationFailure>
where
Fut: Future<Output = Result<(RequestBuilder, HeaderMap), ArchiveVerificationFailure>>,
{
let endpoint = service_base_url.trim_end_matches('/');
let key_url = format!("{endpoint}/ps/plugins/signing-keys");
let (request, headers) = key_request(key_url.clone()).await?;
let keys = fetch_signing_keys(request.headers(headers), &key_url).await?;
keys.get(key_id)
.cloned()
.unwrap_or(Err(ArchiveVerificationFailure::UnknownSigningKey))
type SigningKeyCacheScope = (String, aws_lc_rs::digest::Digest);
/// Reuses Plugin Service signing keys within one owner and credential scope.
#[derive(Default)]
pub struct SigningKeyCache {
scopes: Mutex<VecDeque<(SigningKeyCacheScope, Arc<ScopedSigningKeyCache>)>>,
}
impl fmt::Debug for SigningKeyCache {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SigningKeyCache")
.finish_non_exhaustive()
}
}
impl SigningKeyCache {
fn scope(&self, endpoint: &str, headers: &HeaderMap) -> Arc<ScopedSigningKeyCache> {
if headers
.get(AUTHORIZATION)
.is_none_or(http::HeaderValue::is_empty)
{
// External providers can authenticate with custom headers. Always fetch in that case.
return Arc::default();
}
// Bind the cache entry to the exact outgoing auth,
// including account and provider-specific identity headers. A fresh runtime proof
// must select a fresh scope so the key service authorizes that request.
let mut fields: Vec<_> = headers.iter().collect();
fields.sort_by_key(|(name, _)| name.as_str());
let mut digest = Context::new(&SHA256);
for (name, value) in fields {
digest.update(name.as_str().as_bytes());
digest.update(b":");
digest.update(value.as_bytes());
digest.update(b"\n");
}
let fingerprint = digest.finish();
let mut scopes = self
.scopes
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let entry = scopes
.iter()
.position(|((url, hash), _)| url == endpoint && hash.as_ref() == fingerprint.as_ref())
.and_then(|position| scopes.remove(position))
.unwrap_or_else(|| ((endpoint.to_owned(), fingerprint), Arc::default()));
let scope = Arc::clone(&entry.1);
scopes.push_front(entry);
scopes.truncate(MAX_CACHED_SCOPES);
scope
}
pub(super) async fn key<Fut>(
&self,
service_base_url: &str,
key_id: &str,
key_request: impl FnOnce(String) -> Fut,
) -> Result<SigningKey, ArchiveVerificationFailure>
where
Fut: Future<Output = Result<(RequestBuilder, HeaderMap), ArchiveVerificationFailure>>,
{
let endpoint = service_base_url.trim_end_matches('/');
let key_url = format!("{endpoint}/ps/plugins/signing-keys");
let (request, headers) = key_request(key_url.clone()).await?;
self.scope(endpoint, &headers)
.key(request.headers(headers), &key_url, key_id)
.await
}
}
#[derive(Clone, PartialEq, Eq, Deserialize)]
@@ -59,16 +124,91 @@ struct SigningKeysResponse {
keys: Vec<SigningKey>,
#[serde(default)]
eval_keys: Vec<SigningKey>,
#[serde(rename = "cache_ttl_seconds")]
_cache_ttl_seconds: u64,
cache_ttl_seconds: u64,
}
type SigningKeys = HashMap<String, Result<SigningKey, ArchiveVerificationFailure>>;
struct CachedSigningKeys {
keys: HashMap<String, Result<SigningKey, ArchiveVerificationFailure>>,
expires_at: Instant,
}
impl CachedSigningKeys {
fn fresh_key(&self, key_id: &str) -> Option<&Result<SigningKey, ArchiveVerificationFailure>> {
if self.expires_at <= Instant::now() {
return None;
}
self.keys.get(key_id)
}
fn key(&self, key_id: &str) -> Result<SigningKey, ArchiveVerificationFailure> {
self.keys
.get(key_id)
.cloned()
.unwrap_or(Err(ArchiveVerificationFailure::UnknownSigningKey))
}
}
struct ScopedSigningKeyCache {
cached: Mutex<Option<CachedSigningKeys>>,
refresh: Semaphore,
}
impl Default for ScopedSigningKeyCache {
fn default() -> Self {
Self {
cached: Mutex::new(None),
refresh: Semaphore::new(/*permits*/ 1),
}
}
}
impl ScopedSigningKeyCache {
fn lock_cached(&self) -> MutexGuard<'_, Option<CachedSigningKeys>> {
self.cached
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
async fn key(
&self,
request: RequestBuilder,
key_url: &str,
key_id: &str,
) -> Result<SigningKey, ArchiveVerificationFailure> {
if let Some(key) = self
.lock_cached()
.as_ref()
.and_then(|keys| keys.fresh_key(key_id))
{
return key.clone();
}
// Keep refreshes ordered without locking the cached data during the request.
// Dropping the permit lets a waiter retry after a cancelled refresh.
let _permit = self
.refresh
.acquire()
.await
.map_err(|_| ArchiveVerificationFailure::SigningKeysUnavailable)?;
{
let mut cached = self.lock_cached();
if let Some(key) = cached.as_ref().and_then(|keys| keys.fresh_key(key_id)) {
return key.clone();
}
// A failed refresh can mean that this caller has lost access to the published keys.
*cached = None;
}
let keys = fetch_signing_keys(request, key_url).await?;
let key = keys.key(key_id);
*self.lock_cached() = Some(keys);
key
}
}
async fn fetch_signing_keys(
request: RequestBuilder,
key_url: &str,
) -> Result<SigningKeys, ArchiveVerificationFailure> {
) -> Result<CachedSigningKeys, ArchiveVerificationFailure> {
let started = Instant::now();
let result = async {
let mut response = request
@@ -121,7 +261,11 @@ async fn fetch_signing_keys(
.ok_or(ArchiveVerificationFailure::UnsupportedKeyPurpose),
);
}
Ok(keys)
let now = Instant::now();
let expires_at = now
.checked_add(Duration::from_secs(response.cache_ttl_seconds))
.unwrap_or(now);
Ok(CachedSigningKeys { keys, expires_at })
}
.await;
if let Some(metrics) = codex_otel::global() {
@@ -143,3 +287,7 @@ async fn fetch_signing_keys(
}
result
}
#[cfg(test)]
#[path = "archive_signing_keys_tests.rs"]
mod tests;
@@ -0,0 +1,188 @@
#![cfg(test)]
use super::*;
use crate::test_support::auth_headers;
use crate::test_support::fixture;
use crate::test_support::key_request;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::task::Context as TaskContext;
use std::task::Waker;
use tokio::sync::Notify;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn key_response() -> Value {
fixture()["signing_keys_response"].clone()
}
#[tokio::test]
async fn reuses_fresh_keys_and_refetches_after_server_ttl_expiry() {
for (ttl, expected_requests) in [(600, 1), (0, 2)] {
let server = MockServer::start().await;
let mut response = key_response();
response["cache_ttl_seconds"] = json!(ttl);
let expected: SigningKey = serde_json::from_value(response["keys"][0].clone()).unwrap();
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/signing-keys"))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.expect(expected_requests)
.mount(&server)
.await;
let base_url = format!("{}/backend-api", server.uri());
let auth = auth_headers("Access Token", "account_id");
let cache = SigningKeyCache::default();
for _ in 0..2 {
assert_eq!(
cache
.key(&base_url, &expected.key_id, key_request(auth.clone()))
.await,
Ok(expected.clone())
);
}
}
}
#[tokio::test]
async fn fetches_once_per_lookup_for_an_unknown_key() {
let server = MockServer::start().await;
let response = key_response();
let known_key: SigningKey = serde_json::from_value(response["keys"][0].clone()).unwrap();
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/signing-keys"))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.mount(&server)
.await;
let base_url = format!("{}/backend-api", server.uri());
let auth = auth_headers("Access Token", "account_id");
let cache = SigningKeyCache::default();
// The first lookup has no cache; the second has a fresh cache without the key.
for expected_requests in 1..=2 {
assert_eq!(
cache
.key(&base_url, "unknown-key", key_request(auth.clone()))
.await,
Err(ArchiveVerificationFailure::UnknownSigningKey)
);
assert_eq!(
server.received_requests().await.unwrap().len(),
expected_requests
);
}
assert_eq!(
cache
.key(&base_url, &known_key.key_id, key_request(auth.clone()))
.await,
Ok(known_key.clone())
);
server.reset().await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/signing-keys"))
.respond_with(ResponseTemplate::new(403))
.expect(2)
.mount(&server)
.await;
// The missing key forces a refresh; its denial also invalidates the previously known key.
for key_id in ["unknown-key", &known_key.key_id] {
assert_eq!(
cache
.key(&base_url, key_id, key_request(auth.clone()))
.await,
Err(ArchiveVerificationFailure::SigningKeysUnavailable)
);
}
}
#[tokio::test]
async fn canceled_refresh_leaves_waiter_free_to_fetch_new_keys() {
let server = MockServer::start().await;
let response = key_response();
let expected: SigningKey = serde_json::from_value(response["keys"][0].clone()).unwrap();
let base_url = format!("{}/backend-api", server.uri());
let keys_path = "/backend-api/ps/plugins/signing-keys";
let auth = auth_headers("Access Token", "account_id");
let cache = SigningKeyCache::default();
Mock::given(method("GET"))
.and(path(keys_path))
.respond_with(ResponseTemplate::new(200).set_body_json(&response))
.expect(1)
.mount(&server)
.await;
assert_eq!(
cache
.key(&base_url, &expected.key_id, key_request(auth.clone()))
.await,
Ok(expected.clone())
);
server.verify().await;
server.reset().await;
let started = Arc::new(Notify::new());
let request_started = Arc::clone(&started);
Mock::given(method("GET"))
.and(path(keys_path))
.respond_with(move |_: &wiremock::Request| {
request_started.notify_one();
ResponseTemplate::new(403).set_delay(Duration::from_secs(60))
})
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path(keys_path))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.expect(1)
.mount(&server)
.await;
let mut refresh = Box::pin(cache.key(&base_url, "unknown-key", key_request(auth.clone())));
tokio::select! {
() = started.notified() => {},
result = refresh.as_mut() => panic!("refresh completed before cancellation: {result:?}"),
}
let mut waiter = Box::pin(cache.key(&base_url, &expected.key_id, key_request(auth)));
assert!(
waiter
.as_mut()
.poll(&mut TaskContext::from_waker(Waker::noop()))
.is_pending()
);
drop(refresh);
assert_eq!(waiter.await, Ok(expected));
}
#[tokio::test]
async fn rejects_invalid_key_responses() {
let valid = key_response();
for response in [
json!({"keys": [], "cache_ttl_seconds": 600}),
json!({"keys": valid["keys"], "cache_ttl_seconds": -1}),
] {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/signing-keys"))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.expect(1)
.mount(&server)
.await;
let base_url = format!("{}/backend-api", server.uri());
let auth = auth_headers("Access Token", "account_id");
assert_eq!(
SigningKeyCache::default()
.key(
&base_url,
"codex-test-rsa-2048-v1",
key_request(auth.clone())
)
.await,
Err(ArchiveVerificationFailure::InvalidSigningKeysResponse)
);
}
}
@@ -2,7 +2,7 @@
//! metadata. Missing signing metadata preserves legacy behavior, while malformed metadata fails at
//! the download boundary. Diagnostics contain no signature or key material.
use crate::archive_signing_keys::signing_key;
use crate::SigningKeyCache;
use aws_lc_rs::digest::SHA256;
use aws_lc_rs::digest::digest;
use aws_lc_rs::signature::ParsedPublicKey;
@@ -197,6 +197,7 @@ impl RemotePluginArchiveDownload {
&self,
archive_bytes: Vec<u8>,
service_base_url: &str,
signing_key_cache: &SigningKeyCache,
key_request: impl FnOnce(String) -> Fut,
) -> Result<(Vec<u8>, PluginArchiveVerification), ArchiveVerificationFailure>
where
@@ -225,7 +226,9 @@ impl RemotePluginArchiveDownload {
if archive_digest.as_ref() != signature.expected_digest {
return Err(ArchiveVerificationFailure::DigestMismatch);
}
let key = signing_key(service_base_url, signature.key_id, key_request).await?;
let key = signing_key_cache
.key(service_base_url, signature.key_id, key_request)
.await?;
archive_kind = key.archive_kind();
if key.algorithm != ARCHIVE_SIGNING_ALGORITHM {
return Err(ArchiveVerificationFailure::UnsupportedKeyAlgorithm);
@@ -31,45 +31,39 @@ async fn unexpected_key_request(
panic!("unexpected signing-key request to {url}");
}
async fn server_with_keys(keys: Value, request_count: u64) -> (MockServer, String) {
async fn server_with_keys(keys: Value) -> (MockServer, String) {
let server = MockServer::start().await;
// Give each signing-key mock its own endpoint.
static NEXT_ENDPOINT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let id = NEXT_ENDPOINT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let base_path = format!("/test-{id}/backend-api");
Mock::given(method("GET"))
.and(path(format!("{base_path}/ps/plugins/signing-keys")))
.and(path("/backend-api/ps/plugins/signing-keys"))
.respond_with(ResponseTemplate::new(200).set_body_json(keys))
.expect(request_count)
.expect(1)
.mount(&server)
.await;
let base_url = format!("{}{base_path}", server.uri());
let base_url = format!("{}/backend-api", server.uri());
(server, base_url)
}
#[tokio::test]
async fn verifies_production_compatible_archive_and_rejects_tampering() {
let cache = SigningKeyCache::default();
let (archive, fixture) = signed_fixture();
let (_server, base_url) = server_with_keys(
fixture["signing_keys_response"].clone(),
/*request_count*/ 2,
)
.await;
let (_server, base_url) = server_with_keys(fixture["signing_keys_response"].clone()).await;
let auth = auth_headers("user-token", "account");
let metadata = download(&fixture["signing"]);
assert_eq!(
metadata
.verify(archive.clone(), &base_url, key_request(auth.clone()))
.verify(
archive.clone(),
&base_url,
&cache,
key_request(auth.clone())
)
.await,
Ok((archive.clone(), PluginArchiveVerification::Verified))
);
let redirector = MockServer::start().await;
let (_target, target_url) = server_with_keys(
fixture["signing_keys_response"].clone(),
/*request_count*/ 1,
)
.await;
let (_target, target_url) = server_with_keys(fixture["signing_keys_response"].clone()).await;
Mock::given(method("GET"))
.and(path("/ps/plugins/signing-keys"))
.respond_with(
@@ -85,6 +79,7 @@ async fn verifies_production_compatible_archive_and_rejects_tampering() {
.verify(
archive.clone(),
&redirector.uri(),
&cache,
key_request(auth.clone())
)
.await,
@@ -95,7 +90,12 @@ async fn verifies_production_compatible_archive_and_rejects_tampering() {
altered_archive[0] ^= 1;
assert_eq!(
metadata
.verify(altered_archive.clone(), &base_url, unexpected_key_request)
.verify(
altered_archive.clone(),
&base_url,
&cache,
unexpected_key_request
)
.await,
Err(ArchiveVerificationFailure::DigestMismatch)
);
@@ -103,7 +103,12 @@ async fn verifies_production_compatible_archive_and_rejects_tampering() {
altered_signing["sha256"] = json!(hex::encode(digest(&SHA256, &altered_archive)));
assert_eq!(
download(&altered_signing)
.verify(altered_archive, &base_url, key_request(auth.clone()))
.verify(
altered_archive,
&base_url,
&cache,
key_request(auth.clone())
)
.await,
Err(ArchiveVerificationFailure::SignatureMismatch)
);
@@ -111,6 +116,7 @@ async fn verifies_production_compatible_archive_and_rejects_tampering() {
#[tokio::test]
async fn rejects_malformed_and_unsupported_signing_metadata() {
let cache = SigningKeyCache::default();
let (archive, fixture) = signed_fixture();
for (field, value, failure) in [
(
@@ -138,7 +144,7 @@ async fn rejects_malformed_and_unsupported_signing_metadata() {
signing[field] = value;
assert_eq!(
download(&signing)
.verify(archive.clone(), "", unexpected_key_request)
.verify(archive.clone(), "", &cache, unexpected_key_request)
.await,
Err(failure)
);
@@ -147,6 +153,7 @@ async fn rejects_malformed_and_unsupported_signing_metadata() {
#[tokio::test]
async fn applies_release_signing_presence_at_download() {
let cache = SigningKeyCache::default();
let (archive, _) = signed_fixture();
for (raw, expected) in [
(
@@ -170,7 +177,7 @@ async fn applies_release_signing_presence_at_download() {
serde_json::from_str(raw).expect("verification failures are deferred until download");
assert_eq!(
download
.verify(archive.clone(), "", unexpected_key_request)
.verify(archive.clone(), "", &cache, unexpected_key_request)
.await,
expected
);
@@ -200,10 +207,16 @@ async fn rejects_keys_with_unsupported_purpose_algorithm_or_invalid_material() {
] {
let mut keys = fixture["signing_keys_response"].clone();
keys["keys"][0][field] = json!(value);
let (_server, base_url) = server_with_keys(keys, /*request_count*/ 1).await;
let (_server, base_url) = server_with_keys(keys).await;
let cache = SigningKeyCache::default();
assert_eq!(
download(&fixture["signing"])
.verify(archive.clone(), &base_url, key_request(auth.clone()))
.verify(
archive.clone(),
&base_url,
&cache,
key_request(auth.clone())
)
.await,
Err(failure)
);
@@ -4,6 +4,7 @@ mod archive_verification;
#[cfg(test)]
mod test_support;
pub use archive_signing_keys::SigningKeyCache;
pub use archive_verification::ArchiveVerificationFailure;
pub use archive_verification::PluginArchiveVerification;
pub use archive_verification::RemotePluginArchiveDownload;