diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index bf1e7ca9e1..e115e833d6 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -4715,6 +4715,21 @@ dependencies = [ [[package]] name = "codex-plugin-archive-verification" version = "0.0.0" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "codex-http-client", + "codex-otel", + "hex", + "http 1.4.0", + "pretty_assertions", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tracing", + "wiremock", +] [[package]] name = "codex-plugin-host" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index e9f373ac61..ca91641d83 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -370,6 +370,7 @@ async-io = "2.6.0" async-stream = "0.3.6" aws-config = "1" aws-credential-types = "1" +aws-lc-rs = "1.18.1" aws-sigv4 = "1" aws-smithy-runtime-api = { version = "1", features = ["client", "http-1x"] } aws-smithy-types = { version = "1", features = ["http-body-1-x"] } @@ -418,6 +419,7 @@ gix = { version = "0.89.0", default-features = false, features = ["sha1"] } gix-url = "0.40.0" glob = "0.3" globset = "0.4" +hex = "0.4.3" hmac = "0.12.1" http = "1.3.1" httpdate = "1.0.3" diff --git a/codex-rs/plugin-archive-verification/BUILD.bazel b/codex-rs/plugin-archive-verification/BUILD.bazel index e845f4c659..8145d418f3 100644 --- a/codex-rs/plugin-archive-verification/BUILD.bazel +++ b/codex-rs/plugin-archive-verification/BUILD.bazel @@ -2,5 +2,6 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "plugin-archive-verification", + compile_data = ["testdata/plugin_archive_signing_v1.json"], crate_name = "codex_plugin_archive_verification", ) diff --git a/codex-rs/plugin-archive-verification/Cargo.toml b/codex-rs/plugin-archive-verification/Cargo.toml index d5874dfb7e..a4ef59241a 100644 --- a/codex-rs/plugin-archive-verification/Cargo.toml +++ b/codex-rs/plugin-archive-verification/Cargo.toml @@ -6,7 +6,24 @@ license.workspace = true [lib] doctest = false -test = false [lints] workspace = true + +[dependencies] +aws-lc-rs = { workspace = true } +base64 = { workspace = true } +codex-http-client = { workspace = true } +codex-otel = { workspace = true } +hex = { workspace = true } +http = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true, features = ["rt"] } +tracing = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] } +wiremock = { workspace = true } diff --git a/codex-rs/plugin-archive-verification/src/archive_signing_keys.rs b/codex-rs/plugin-archive-verification/src/archive_signing_keys.rs new file mode 100644 index 0000000000..97ca4fe313 --- /dev/null +++ b/codex-rs/plugin-archive-verification/src/archive_signing_keys.rs @@ -0,0 +1,145 @@ +//! Fetches and validates the signing keys returned by the authenticated Plugin Service endpoint. + +use crate::ArchiveVerificationFailure; +use codex_http_client::RequestBuilder; +use http::HeaderMap; +use serde::Deserialize; +use std::collections::HashMap; +use std::fmt; +use std::future::Future; +use std::time::Instant; + +const MARKETPLACE_ARCHIVE_PURPOSE: &str = "PLUGIN_RELEASE_ARCHIVE_SIGNING"; +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( + service_base_url: &str, + key_id: &str, + key_request: impl FnOnce(String) -> Fut, +) -> Result +where + Fut: Future>, +{ + 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)) +} + +#[derive(Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct SigningKey { + key_id: String, + purpose: String, + pub(crate) algorithm: String, + pub(crate) public_key_spki_der_base64: String, +} + +impl SigningKey { + pub(crate) fn archive_kind(&self) -> &'static str { + match self.purpose.as_str() { + MARKETPLACE_ARCHIVE_PURPOSE => "release", + _ => "unknown", + } + } +} + +impl fmt::Debug for SigningKey { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("SigningKey { material: redacted }") + } +} + +#[derive(Deserialize)] +struct SigningKeysResponse { + keys: Vec, + #[serde(default)] + eval_keys: Vec, + #[serde(rename = "cache_ttl_seconds")] + _cache_ttl_seconds: u64, +} + +type SigningKeys = HashMap>; + +async fn fetch_signing_keys( + request: RequestBuilder, + key_url: &str, +) -> Result { + let started = Instant::now(); + let result = async { + let mut response = request + .send() + .await + .map_err(|_| ArchiveVerificationFailure::SigningKeysUnavailable)?; + // The HTTP client can follow a redirect after dropping the original credentials. + let expected_url = key_url + .parse() + .map_err(|_| ArchiveVerificationFailure::SigningKeysUnavailable)?; + if !response.status().is_success() || response.url() != &expected_url { + return Err(ArchiveVerificationFailure::SigningKeysUnavailable); + } + if response + .content_length() + .is_some_and(|length| length > MAX_SIGNING_KEYS_RESPONSE_BYTES as u64) + { + return Err(ArchiveVerificationFailure::InvalidSigningKeysResponse); + } + let mut body = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|_| ArchiveVerificationFailure::SigningKeysUnavailable)? + { + if body.len().saturating_add(chunk.len()) > MAX_SIGNING_KEYS_RESPONSE_BYTES { + return Err(ArchiveVerificationFailure::InvalidSigningKeysResponse); + } + body.extend_from_slice(&chunk); + } + let response: SigningKeysResponse = serde_json::from_slice(&body) + .map_err(|_| ArchiveVerificationFailure::InvalidSigningKeysResponse)?; + let key_count = response.keys.len() + response.eval_keys.len(); + if key_count == 0 || key_count > MAX_SIGNING_KEYS { + return Err(ArchiveVerificationFailure::InvalidSigningKeysResponse); + } + let mut keys = HashMap::with_capacity(key_count); + // Older servers published eval keys to all callers in `keys`. + for key in response.keys { + if key.key_id.is_empty() + || key.public_key_spki_der_base64.len() > MAX_PUBLIC_KEY_BASE64_BYTES + || keys.contains_key(&key.key_id) + { + return Err(ArchiveVerificationFailure::InvalidSigningKeysResponse); + } + keys.insert( + key.key_id.clone(), + (key.purpose == MARKETPLACE_ARCHIVE_PURPOSE) + .then_some(key) + .ok_or(ArchiveVerificationFailure::UnsupportedKeyPurpose), + ); + } + Ok(keys) + } + .await; + if let Some(metrics) = codex_otel::global() { + let outcome = match &result { + Ok(_) => "success", + Err(failure) => failure.as_str(), + }; + let tags = [("outcome", outcome)]; + let _ = metrics.counter( + "codex.plugins.archive_signing_keys.fetch", + /*inc*/ 1, + &tags, + ); + let _ = metrics.record_duration( + "codex.plugins.archive_signing_keys.fetch.duration_ms", + started.elapsed(), + &tags, + ); + } + result +} diff --git a/codex-rs/plugin-archive-verification/src/archive_verification.rs b/codex-rs/plugin-archive-verification/src/archive_verification.rs new file mode 100644 index 0000000000..66ea2aa36c --- /dev/null +++ b/codex-rs/plugin-archive-verification/src/archive_verification.rs @@ -0,0 +1,267 @@ +//! Verifies Plugin Service archive bytes before extraction when the release includes signing +//! 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 aws_lc_rs::digest::SHA256; +use aws_lc_rs::digest::digest; +use aws_lc_rs::signature::ParsedPublicKey; +use aws_lc_rs::signature::RSA_PKCS1_2048_8192_SHA256; +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use serde_json::Value; +use std::fmt; +use std::time::Instant; + +use codex_http_client::RequestBuilder; +use http::HeaderMap; +use std::future::Future; + +const ARCHIVE_SIGNING_ALGORITHM: &str = "RSA_PKCS1_SHA256"; +const MAX_SIGNATURE_BASE64_BYTES: usize = 2048; +const MAX_KEY_ID_BYTES: usize = 512; +pub(super) const ARCHIVE_VERIFICATION_EVENT: &str = "codex.plugins.archive_verification"; + +/// Download metadata supplied with an authorized Plugin Service archive URL. +/// Signing metadata is deliberately omitted when catalog responses are persisted. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] +pub struct RemotePluginArchiveDownload { + #[serde(default)] + pub bundle_download_url: Option, + #[serde(default, skip_serializing)] + signing: ArchiveVerification, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +enum ArchiveVerification { + #[default] + Absent, + Present(SigningMetadata), + Malformed, +} + +#[derive(Clone, PartialEq, Eq, Deserialize)] +struct SigningMetadata { + sha256: String, + signature: String, + key_id: String, + algorithm: String, +} + +impl fmt::Debug for SigningMetadata { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("SigningMetadata { .. }") + } +} + +// Defer malformed signing metadata until download so unchanged cached versions remain reusable. +impl<'de> Deserialize<'de> for ArchiveVerification { + fn deserialize>(deserializer: D) -> Result { + let value = Value::deserialize(deserializer)?; + let verification = match value { + Value::Null => Self::Absent, + value @ Value::Object(_) => match serde_json::from_value::(value) { + Ok(metadata) => Self::Present(metadata), + Err(_) => Self::Malformed, + }, + Value::Bool(_) | Value::Number(_) | Value::String(_) | Value::Array(_) => { + Self::Malformed + } + }; + Ok(verification) + } +} + +/// Result of checking a downloaded remote plugin archive before it can be installed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PluginArchiveVerification { + Verified, + NotRequired, +} + +impl PluginArchiveVerification { + pub fn as_str(self) -> &'static str { + match self { + Self::Verified => "verified", + Self::NotRequired => "not_required", + } + } +} + +/// Bounded failure categories safe for install diagnostics and metrics. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum ArchiveVerificationFailure { + #[error("archive signature metadata is malformed")] + MalformedMetadata, + #[error("archive signature algorithm is unsupported")] + UnsupportedArchiveAlgorithm, + #[error("archive digest does not match its signed metadata")] + DigestMismatch, + #[error("archive digest computation failed")] + DigestComputationFailed, + #[error("authentication is required to fetch archive signing keys")] + AuthenticationRequired, + #[error("archive signing keys are unavailable")] + SigningKeysUnavailable, + #[error("archive signing-key response is invalid")] + InvalidSigningKeysResponse, + #[error("archive signing key is unknown")] + UnknownSigningKey, + #[error("archive signing key has an unsupported purpose")] + UnsupportedKeyPurpose, + #[error("archive signing key has an unsupported algorithm")] + UnsupportedKeyAlgorithm, + #[error("archive signing public key is invalid")] + InvalidPublicKey, + #[error("archive signature does not verify")] + SignatureMismatch, +} + +impl ArchiveVerificationFailure { + pub fn as_str(self) -> &'static str { + match self { + Self::MalformedMetadata => "malformed_metadata", + Self::UnsupportedArchiveAlgorithm => "unsupported_archive_algorithm", + Self::DigestMismatch => "digest_mismatch", + Self::DigestComputationFailed => "digest_computation_failed", + Self::AuthenticationRequired => "authentication_required", + Self::SigningKeysUnavailable => "signing_keys_unavailable", + Self::InvalidSigningKeysResponse => "invalid_signing_keys_response", + Self::UnknownSigningKey => "unknown_signing_key", + Self::UnsupportedKeyPurpose => "unsupported_key_purpose", + Self::UnsupportedKeyAlgorithm => "unsupported_key_algorithm", + Self::InvalidPublicKey => "invalid_public_key", + Self::SignatureMismatch => "signature_mismatch", + } + } +} + +struct DetachedSignature<'a> { + expected_digest: [u8; 32], + bytes: Vec, + key_id: &'a str, +} + +impl<'a> TryFrom<&'a SigningMetadata> for DetachedSignature<'a> { + type Error = ArchiveVerificationFailure; + + fn try_from(value: &'a SigningMetadata) -> Result { + let SigningMetadata { + sha256, + signature, + key_id, + algorithm, + } = value; + if algorithm != ARCHIVE_SIGNING_ALGORITHM { + return Err(ArchiveVerificationFailure::UnsupportedArchiveAlgorithm); + } + let mut expected_digest = [0; 32]; + hex::decode_to_slice(sha256, &mut expected_digest) + .map_err(|_| ArchiveVerificationFailure::MalformedMetadata)?; + // The decoder accepts uppercase hex; release digests must be lowercase. + if hex::encode(expected_digest) != *sha256 + || signature.len() > MAX_SIGNATURE_BASE64_BYTES + || key_id.is_empty() + || key_id.len() > MAX_KEY_ID_BYTES + { + return Err(ArchiveVerificationFailure::MalformedMetadata); + } + let signature_bytes = STANDARD + .decode(signature) + .map_err(|_| ArchiveVerificationFailure::MalformedMetadata)?; + if signature_bytes.is_empty() { + return Err(ArchiveVerificationFailure::MalformedMetadata); + } + Ok(Self { + expected_digest, + bytes: signature_bytes, + key_id, + }) + } +} + +impl RemotePluginArchiveDownload { + pub fn new(bundle_download_url: Option) -> Self { + Self { + bundle_download_url, + signing: ArchiveVerification::Absent, + } + } + + /// Checks the downloaded bytes before they can be extracted. The key request must + /// use the authorized Plugin Service route and return its resolved authentication headers. + pub async fn verify( + &self, + archive_bytes: Vec, + service_base_url: &str, + key_request: impl FnOnce(String) -> Fut, + ) -> Result<(Vec, PluginArchiveVerification), ArchiveVerificationFailure> + where + Fut: Future>, + { + let started = Instant::now(); + // The authenticated key list determines the kind. Digest and key lookup failures precede it. + let mut archive_kind = "unknown"; + let result = async { + let signing = match &self.signing { + ArchiveVerification::Absent => { + return Ok((archive_bytes, PluginArchiveVerification::NotRequired)); + } + ArchiveVerification::Present(signing) => signing, + ArchiveVerification::Malformed => { + return Err(ArchiveVerificationFailure::MalformedMetadata); + } + }; + let signature = DetachedSignature::try_from(signing)?; + let (archive_bytes, archive_digest) = tokio::task::spawn_blocking(move || { + let archive_digest = digest(&SHA256, &archive_bytes); + (archive_bytes, archive_digest) + }) + .await + .map_err(|_| ArchiveVerificationFailure::DigestComputationFailed)?; + 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?; + archive_kind = key.archive_kind(); + if key.algorithm != ARCHIVE_SIGNING_ALGORITHM { + return Err(ArchiveVerificationFailure::UnsupportedKeyAlgorithm); + } + let key_bytes = STANDARD + .decode(&key.public_key_spki_der_base64) + .map_err(|_| ArchiveVerificationFailure::InvalidPublicKey)?; + let public_key = ParsedPublicKey::new(&RSA_PKCS1_2048_8192_SHA256, key_bytes) + .map_err(|_| ArchiveVerificationFailure::InvalidPublicKey)?; + public_key + .verify_digest_sig(&archive_digest, &signature.bytes) + .map_err(|_| ArchiveVerificationFailure::SignatureMismatch)?; + Ok((archive_bytes, PluginArchiveVerification::Verified)) + } + .await; + let outcome = match &result { + Ok((_, outcome)) => outcome.as_str(), + Err(failure) => { + let reason = failure.as_str(); + tracing::warn!(reason, "plugin archive verification failed"); + reason + } + }; + if let Some(metrics) = codex_otel::global() { + let tags = [("outcome", outcome), ("archive_kind", archive_kind)]; + let _ = metrics.counter(ARCHIVE_VERIFICATION_EVENT, /*inc*/ 1, &tags); + let _ = metrics.record_duration( + "codex.plugins.archive_verification.duration_ms", + started.elapsed(), + &tags, + ); + } + result + } +} + +#[cfg(test)] +#[path = "archive_verification_tests.rs"] +mod tests; diff --git a/codex-rs/plugin-archive-verification/src/archive_verification_tests.rs b/codex-rs/plugin-archive-verification/src/archive_verification_tests.rs new file mode 100644 index 0000000000..bde4b70d01 --- /dev/null +++ b/codex-rs/plugin-archive-verification/src/archive_verification_tests.rs @@ -0,0 +1,229 @@ +#![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 wiremock::Mock; +use wiremock::MockServer; +use wiremock::ResponseTemplate; +use wiremock::matchers::method; +use wiremock::matchers::path; + +fn signed_fixture() -> (Vec, Value) { + let fixture = fixture(); + let archive = STANDARD + .decode(fixture["archive_base64"].as_str().expect("archive base64")) + .expect("valid archive base64"); + (archive, fixture) +} + +fn download(signing: &Value) -> RemotePluginArchiveDownload { + serde_json::from_value(json!({"signing": signing})).unwrap() +} + +async fn unexpected_key_request( + url: String, +) -> Result<(RequestBuilder, HeaderMap), ArchiveVerificationFailure> { + panic!("unexpected signing-key request to {url}"); +} + +async fn server_with_keys(keys: Value, request_count: u64) -> (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"))) + .respond_with(ResponseTemplate::new(200).set_body_json(keys)) + .expect(request_count) + .mount(&server) + .await; + let base_url = format!("{}{base_path}", server.uri()); + (server, base_url) +} + +#[tokio::test] +async fn verifies_production_compatible_archive_and_rejects_tampering() { + let (archive, fixture) = signed_fixture(); + let (_server, base_url) = server_with_keys( + fixture["signing_keys_response"].clone(), + /*request_count*/ 2, + ) + .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())) + .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; + Mock::given(method("GET")) + .and(path("/ps/plugins/signing-keys")) + .respond_with( + ResponseTemplate::new(307) + .insert_header("location", format!("{target_url}/ps/plugins/signing-keys")), + ) + .expect(1) + .mount(&redirector) + .await; + // The redirected server returns the exact key that verifies this archive. + assert_eq!( + metadata + .verify( + archive.clone(), + &redirector.uri(), + key_request(auth.clone()) + ) + .await, + Err(ArchiveVerificationFailure::SigningKeysUnavailable) + ); + + let mut altered_archive = archive.clone(); + altered_archive[0] ^= 1; + assert_eq!( + metadata + .verify(altered_archive.clone(), &base_url, unexpected_key_request) + .await, + Err(ArchiveVerificationFailure::DigestMismatch) + ); + let mut altered_signing = fixture["signing"].clone(); + altered_signing["sha256"] = json!(hex::encode(digest(&SHA256, &altered_archive))); + assert_eq!( + download(&altered_signing) + .verify(altered_archive, &base_url, key_request(auth.clone())) + .await, + Err(ArchiveVerificationFailure::SignatureMismatch) + ); +} + +#[tokio::test] +async fn rejects_malformed_and_unsupported_signing_metadata() { + let (archive, fixture) = signed_fixture(); + for (field, value, failure) in [ + ( + "sha256", + json!("A".repeat(64)), + ArchiveVerificationFailure::MalformedMetadata, + ), + ( + "signature", + json!("not base64"), + ArchiveVerificationFailure::MalformedMetadata, + ), + ( + "key_id", + json!(""), + ArchiveVerificationFailure::MalformedMetadata, + ), + ( + "algorithm", + json!("RSA_PSS_SHA256"), + ArchiveVerificationFailure::UnsupportedArchiveAlgorithm, + ), + ] { + let mut signing = fixture["signing"].clone(); + signing[field] = value; + assert_eq!( + download(&signing) + .verify(archive.clone(), "", unexpected_key_request) + .await, + Err(failure) + ); + } +} + +#[tokio::test] +async fn applies_release_signing_presence_at_download() { + let (archive, _) = signed_fixture(); + for (raw, expected) in [ + ( + r#"{}"#, + Ok((archive.clone(), PluginArchiveVerification::NotRequired)), + ), + ( + r#"{"signing":null}"#, + Ok((archive.clone(), PluginArchiveVerification::NotRequired)), + ), + ( + r#"{"signing":{}}"#, + Err(ArchiveVerificationFailure::MalformedMetadata), + ), + ( + r#"{"signing":true}"#, + Err(ArchiveVerificationFailure::MalformedMetadata), + ), + ] { + let download: RemotePluginArchiveDownload = + serde_json::from_str(raw).expect("verification failures are deferred until download"); + assert_eq!( + download + .verify(archive.clone(), "", unexpected_key_request) + .await, + expected + ); + } +} + +#[tokio::test] +async fn rejects_keys_with_unsupported_purpose_algorithm_or_invalid_material() { + let (archive, fixture) = signed_fixture(); + let auth = auth_headers("user-token", "account"); + for (field, value, failure) in [ + ( + "purpose", + "OTHER_PURPOSE", + ArchiveVerificationFailure::UnsupportedKeyPurpose, + ), + ( + "algorithm", + "RSA_PSS_SHA256", + ArchiveVerificationFailure::UnsupportedKeyAlgorithm, + ), + ( + "public_key_spki_der_base64", + "invalid", + ArchiveVerificationFailure::InvalidPublicKey, + ), + ] { + 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; + assert_eq!( + download(&fixture["signing"]) + .verify(archive.clone(), &base_url, key_request(auth.clone())) + .await, + Err(failure) + ); + } +} + +#[test] +fn retains_signing_metadata_only_for_download() { + let url = "https://example.com/archive"; + let signing = json!({"sha256": "digest", "key_id": "key", "signature": "signature", "algorithm": "algorithm"}); + let release = json!({"bundle_download_url": url, "signing": signing}); + let download: RemotePluginArchiveDownload = serde_json::from_value(release).unwrap(); + assert!(matches!(download.signing, ArchiveVerification::Present(_))); + assert_eq!( + serde_json::to_value(&download).unwrap(), + json!({"bundle_download_url": url}) + ); + let malformed: RemotePluginArchiveDownload = + serde_json::from_value(json!({"signing": {}})).unwrap(); + assert_eq!(malformed.signing, ArchiveVerification::Malformed); + let unsigned: RemotePluginArchiveDownload = serde_json::from_value(json!({})).unwrap(); + assert_eq!(unsigned.signing, ArchiveVerification::Absent); +} diff --git a/codex-rs/plugin-archive-verification/src/lib.rs b/codex-rs/plugin-archive-verification/src/lib.rs index d6e2394aff..36d222a865 100644 --- a/codex-rs/plugin-archive-verification/src/lib.rs +++ b/codex-rs/plugin-archive-verification/src/lib.rs @@ -1 +1,9 @@ -//! Verifies signatures on Plugin Service archives. +mod archive_signing_keys; +mod archive_verification; + +#[cfg(test)] +mod test_support; + +pub use archive_verification::ArchiveVerificationFailure; +pub use archive_verification::PluginArchiveVerification; +pub use archive_verification::RemotePluginArchiveDownload; diff --git a/codex-rs/plugin-archive-verification/src/test_support.rs b/codex-rs/plugin-archive-verification/src/test_support.rs new file mode 100644 index 0000000000..1c4fe69187 --- /dev/null +++ b/codex-rs/plugin-archive-verification/src/test_support.rs @@ -0,0 +1,31 @@ +//! Builds key requests for the hermetic Plugin Service fixtures. + +use crate::ArchiveVerificationFailure; +use codex_http_client::HttpClientBuilder; +use codex_http_client::RequestBuilder; +use http::HeaderMap; +use http::header::AUTHORIZATION; +use serde_json::Value; +use std::future::Ready; +use std::future::ready; + +pub(super) fn fixture() -> Value { + serde_json::from_str(include_str!("../testdata/plugin_archive_signing_v1.json")) + .expect("valid signing vector") +} + +pub(super) fn auth_headers(token: &str, account: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, format!("Bearer {token}").parse().unwrap()); + headers.insert("chatgpt-account-id", account.parse().unwrap()); + headers +} + +pub(super) fn key_request( + headers: HeaderMap, +) -> impl FnOnce(String) -> Ready> { + move |url| { + let client = HttpClientBuilder::new().build_direct().unwrap(); + ready(Ok((client.get(url), headers))) + } +} diff --git a/codex-rs/plugin-archive-verification/testdata/plugin_archive_signing_v1.json b/codex-rs/plugin-archive-verification/testdata/plugin_archive_signing_v1.json new file mode 100644 index 0000000000..975a9acad9 --- /dev/null +++ b/codex-rs/plugin-archive-verification/testdata/plugin_archive_signing_v1.json @@ -0,0 +1,21 @@ +{ + "description": "RSA-2048 PKCS#1 v1.5 SHA-256 test vector generated with OpenSSL 3.0.13. The private test key was discarded. The signature signs the SHA-256 digest of the decoded deterministic plugin.tar.gz bytes.", + "archive_base64": "H4sIAAAAAAAC/+3Wy4rbMBQGYK/zFEbrxNHVivMGpbMbuipl0OUoVus4wXKGKUPevUo8hGHaLgqDocz5NjLy5YDRf6TKHTw8rY7daRf79TRU39OhL94PzWopr2P2dqSMidv1dZ7xmqqipMUMTmk0Qy5ffEzPpDd7IFvSxR7MQJbkEYYUD32eYhWvRJ7xkNwQj+M0ex93PfjSDK6Nj1CG+DSeBiDnRYH+P7EfYTfE8ed7h/4f8i8FfZN/WiuB+Z8n/yF2kMj26zM5mrHNAa/+tiXkVpBaw1WdH1LMq9oFwbWwxnLDBZeNdV4bYE2gXsh811lqNTPebpiTuhabRtmgN7rhnJyXt4LpR+y6tJ460Pr+86e7u2rvX1czxknHgXmtNHjlvFVAg3TGbhojLZOcMmFcCAChdpqxhjaWmsCcrymAIudvS9Ka1D6YbnfIy73dX+pOn891XAt783DrfOzjNLM///t5889+yz/TjGP+57BarRaXE8C2nJbA4tVmvy1f9vqpB5QjpLG8LpjF5bUvCcqxhTJND13vvpwGKjwMIIQQQgghhBBCCCGEEEIIIYTQzH4BZxmiTgAoAAA=", + "signing": { + "sha256": "3f0d376e6758f2379ed5696596b59e4fa3957f25d2015cffa44401fada829590", + "signature": "P1LLi/22J5NqCDXKJPiARSfCLHmzkyWCdT065UxE3yiojn9U1bbO1BN6KU5bk3/5/xGttr1n0kFwxeH7gW7jak1UZ5r0vDkFgA78c8QJ5ErAIKa1w9pTZ7rSFV4pnl1+ZMlew4BYAdZnuEhZNccDDrMG9Bb6USAjTs4+TDs/dyLvl9gdEFT0Bo04M9yHbp1t64VwxXjKrbB6hMpqZma2kFoM6UEG1W6jGo7ZCbvM2IDsVZM/ZNrPX28kKgnLGDDO3xnIDonp+hhkudA+KfSjKMWsQI1fU9gClCTR7bTx1mKL5PCImTfpG0a0pS+PNyZGh1JzBkdUGB6ZsdB/RfgGbQ==", + "key_id": "codex-test-rsa-2048-v1", + "algorithm": "RSA_PKCS1_SHA256" + }, + "signing_keys_response": { + "keys": [ + { + "key_id": "codex-test-rsa-2048-v1", + "purpose": "PLUGIN_RELEASE_ARCHIVE_SIGNING", + "algorithm": "RSA_PKCS1_SHA256", + "public_key_spki_der_base64": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzg1qvekIGyZ4p23hH9TmW/SkfkkKNxZZuhcbIbDz/TUa0NmrGGSZgVqEnzGAlX/x1gFTNwbM+jEgzyRrE/XSu7WdCuLKqAXz8PGKoIszJoaCjXj4EHLWG2w5YNdG+L+wo9/1Rw+gmg3rcQZR7V0SQw1i710CF9B5e8LpLEISSzZ9sMk3iUEj7XJbmWJyBrL4ZCePT9sYXKUU4OLKOWl2DPKyB1qzbrvN7cIG+hd+MFaqyeChPfLHWat9G7SoVYHkPQJPoay7IfWRe6OqJg8bBoobNefl0Exy4upT+0MQvRiinqV6dvjB1+YfUp31ThoDN2xqxWSIsYAUw10RCQ7G0QIDAQAB" + } + ], + "cache_ttl_seconds": 600 + } +}