A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Trust system and custom certificate authorities (#3477)
Sebastian Müller8fd44c25b31b
diff --git a/.changes/fix-custom-ca-trust.md b/.changes/fix-custom-ca-trust.mdnew file mode 100644index 0000000000..25f7ae2ea5--- /dev/null+++ b/.changes/fix-custom-ca-trust.md@@ -0,0 +1 @@+- HTTPS clients and Codex WebSockets now trust operating system certificate authorities alongside bundled roots, and honor custom CA bundles supplied through `NODE_EXTRA_CA_CERTS`, including the default proxy streaming path.diff --git a/Cargo.lock b/Cargo.lockindex efe71a6b05..48245f29a6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -79,6 +79,45 @@ version = "1.0.104"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"+[[package]]+name = "asn1-rs"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"+dependencies = [+ "asn1-rs-derive",+ "asn1-rs-impl",+ "displaydoc",+ "nom",+ "num-traits",+ "rusticata-macros",+ "thiserror",+ "time",+]++[[package]]+name = "asn1-rs-derive"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "synstructure 0.13.2",+]++[[package]]+name = "asn1-rs-impl"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "async-compression"version = "0.4.47"@@ -109,6 +148,12 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"+[[package]]name = "base64ct"version = "1.8.3"@@ -121,7 +166,7 @@ version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"dependencies = [- "bit-vec",+ "bit-vec 0.8.0",][[package]]@@ -130,6 +175,15 @@ version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"+[[package]]+name = "bit-vec"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"+dependencies = [+ "serde",+]+[[package]]name = "bitflags"version = "2.13.2"@@ -298,6 +352,22 @@ version = "0.9.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"+[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"+[[package]]name = "cpufeatures"version = "0.2.17"@@ -435,6 +505,26 @@ dependencies = ["zeroize",]+[[package]]+name = "der-parser"+version = "10.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"+dependencies = [+ "asn1-rs",+ "displaydoc",+ "nom",+ "num-bigint",+ "num-traits",+ "rusticata-macros",+]++[[package]]+name = "deranged"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"+[[package]]name = "digest"version = "0.10.7"@@ -831,6 +921,7 @@ dependencies = ["hyper","hyper-util","rustls",+ "rustls-native-certs","tokio","tokio-rustls","tower-service",@@ -843,7 +934,7 @@ version = "0.1.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"dependencies = [- "base64",+ "base64 0.22.1","bytes","futures-channel","futures-util",@@ -1177,6 +1268,12 @@ version = "2.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"+[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"+[[package]]name = "miniz_oxide"version = "0.9.1"@@ -1211,6 +1308,16 @@ dependencies = ["libc",]+[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]+[[package]]name = "notify"version = "8.2.0"@@ -1238,6 +1345,16 @@ dependencies = ["bitflags",]+[[package]]+name = "num-bigint"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"+dependencies = [+ "num-integer",+ "num-traits",+]+[[package]]name = "num-bigint-dig"version = "0.8.6"@@ -1254,6 +1371,12 @@ dependencies = ["zeroize",]+[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"+[[package]]name = "num-integer"version = "0.1.47"@@ -1283,6 +1406,15 @@ dependencies = ["libm",]+[[package]]+name = "oid-registry"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"+dependencies = [+ "asn1-rs",+]+[[package]]name = "once_cell"version = "1.21.4"@@ -1295,17 +1427,27 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]+name = "openssl-probe"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"+[[package]]name = "pa-agent"version = "0.10.0"dependencies = ["anyhow","futures",+ "rcgen","reqwest",+ "rustls","serde","serde_json",+ "tempfile","thiserror","tokio",+ "tokio-rustls",][[package]]@@ -1313,7 +1455,7 @@ name = "pa-ai"version = "0.10.0"dependencies = ["anyhow",- "base64",+ "base64 0.22.1","bytes","futures","h2",@@ -1323,17 +1465,24 @@ dependencies = ["pa-types","rand 0.8.8","regex",+ "rcgen","reqwest","rsa",+ "rustls",+ "rustls-native-certs","serde","serde_json","sha1","sha2",+ "tempfile","thiserror","tokio",+ "tokio-rustls","tokio-tungstenite","tokio-util",+ "tracing","url",+ "webpki-roots 1.0.9",][[package]]@@ -1341,7 +1490,7 @@ name = "pa-cli"version = "0.10.0"dependencies = ["anyhow",- "base64",+ "base64 0.22.1","crossterm","flate2","futures",@@ -1371,7 +1520,7 @@ name = "pa-core"version = "0.10.0"dependencies = ["anyhow",- "base64",+ "base64 0.22.1","fancy-regex","flate2","futures",@@ -1440,6 +1589,7 @@ dependencies = ["hmac","pa-ai","pa-types",+ "rcgen","reqwest","serde","serde_json",@@ -1447,6 +1597,7 @@ dependencies = ["tempfile","thiserror","tokio",+ "tokio-rustls","tracing",]@@ -1470,7 +1621,7 @@ name = "pa-tui"version = "0.10.0"dependencies = ["anyhow",- "base64",+ "base64 0.22.1","clap","crossterm","fancy-regex",@@ -1535,6 +1686,16 @@ version = "1.0.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"+[[package]]+name = "pem"+version = "4.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"+dependencies = [+ "base64 0.23.1",+ "serde_core",+]+[[package]]name = "pem-rfc7468"version = "0.7.0"@@ -1586,6 +1747,12 @@ dependencies = ["zerovec",]+[[package]]+name = "powerfmt"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"+[[package]]name = "ppv-lite86"version = "0.2.21"@@ -1811,6 +1978,20 @@ dependencies = ["unicode-width 0.2.0",]+[[package]]+name = "rcgen"+version = "0.14.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"+dependencies = [+ "pem",+ "ring",+ "rustls-pki-types",+ "time",+ "x509-parser",+ "yasna",+]+[[package]]name = "redox_syscall"version = "0.5.18"@@ -1855,7 +2036,7 @@ version = "0.12.28"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"dependencies = [- "base64",+ "base64 0.22.1","bytes","futures-core","futures-util",@@ -1872,6 +2053,7 @@ dependencies = ["pin-project-lite","quinn","rustls",+ "rustls-native-certs","rustls-pki-types","serde","serde_json",@@ -1932,6 +2114,15 @@ version = "2.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"+[[package]]+name = "rusticata-macros"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"+dependencies = [+ "nom",+]+[[package]]name = "rustix"version = "0.38.44"@@ -1972,6 +2163,18 @@ dependencies = ["zeroize",]+[[package]]+name = "rustls-native-certs"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"+dependencies = [+ "openssl-probe",+ "rustls-pki-types",+ "schannel",+ "security-framework",+]+[[package]]name = "rustls-pki-types"version = "1.15.1"@@ -2014,12 +2217,44 @@ dependencies = ["winapi-util",]+[[package]]+name = "schannel"+version = "0.1.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"+dependencies = [+ "windows-sys 0.61.2",+]+[[package]]name = "scopeguard"version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags",+ "core-foundation",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "serde"version = "1.0.229"@@ -2275,6 +2510,17 @@ dependencies = ["futures-core",]+[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "synstructure"version = "0.14.0"@@ -2330,6 +2576,36 @@ dependencies = ["syn 3.0.5",]+[[package]]+name = "time"+version = "0.3.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"+dependencies = [+ "deranged",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"++[[package]]+name = "time-macros"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"+dependencies = [+ "num-conv",+ "time-core",+]+[[package]]name = "tinystr"version = "0.8.4"@@ -2393,6 +2669,7 @@ dependencies = ["futures-util","log","rustls",+ "rustls-native-certs","rustls-pki-types","tokio","tokio-rustls",@@ -3032,6 +3309,24 @@ version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"+[[package]]+name = "x509-parser"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"+dependencies = [+ "asn1-rs",+ "data-encoding",+ "der-parser",+ "lazy_static",+ "nom",+ "oid-registry",+ "ring",+ "rusticata-macros",+ "thiserror",+ "time",+]+[[package]]name = "xattr"version = "1.6.1"@@ -3055,6 +3350,16 @@ dependencies = ["serde",]+[[package]]+name = "yasna"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"+dependencies = [+ "bit-vec 0.9.1",+ "time",+]+[[package]]name = "yoke"version = "0.8.3"@@ -3075,7 +3380,7 @@ dependencies = ["proc-macro2","quote","syn 3.0.5",- "synstructure",+ "synstructure 0.14.0",][[package]]@@ -3116,7 +3421,7 @@ dependencies = ["proc-macro2","quote","syn 3.0.5",- "synstructure",+ "synstructure 0.14.0",][[package]]diff --git a/README.md b/README.mdindex 7f306dbcae..112c8cc9fa 100644--- a/README.md+++ b/README.md@@ -72,6 +72,16 @@ Prime Agent uses the local clipboard tool (such as `pbcopy`) when available. InNested tmux servers and terminals may still block delivery. An outer tmux with `set-clipboard external` can reject the inner server's OSC 52. In that case, run `tmux set -s set-clipboard on` on the outer server, or use native terminal selection (Shift-drag in most terminals; Option-drag in iTerm2) followed by Cmd-C. macOS Terminal.app does not support OSC 52; iTerm2 requires its “Applications in terminal may access clipboard” setting.+## Custom certificate authorities++HTTPS requests trust your operating system's trust store together with the bundled Mozilla roots. For servers behind a custom CA, point `NODE_EXTRA_CA_CERTS` at a PEM bundle of your CA certificates — the same variable the Node/TypeScript build honors:++```bash+export NODE_EXTRA_CA_CERTS=/path/to/your-ca.pem+```++Each transport reads the variable once when its first client is initialized. The background daemon keeps the environment it started with, so run `prime-agent shutdown` after changing it.+## Getting StartedStart Prime Agent from the repository or directory you want it to work in:diff --git a/crates/pa-agent/Cargo.toml b/crates/pa-agent/Cargo.tomlindex 02bce888e9..f9b5fc1a8f 100644--- a/crates/pa-agent/Cargo.toml+++ b/crates/pa-agent/Cargo.toml@@ -12,9 +12,13 @@ serde.workspace = trueserde_json.workspace = truethiserror.workspace = truetokio.workspace = true-reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }+reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls-native-roots", "rustls-tls-webpki-roots"] }+rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }[dev-dependencies]+tempfile = "3"+rcgen = { version = "0.14", default-features = false, features = ["pem", "ring"] }+tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }[lints]workspace = truediff --git a/crates/pa-agent/README.md b/crates/pa-agent/README.mdindex 25c5f09605..ed27ecb1c3 100644--- a/crates/pa-agent/README.md+++ b/crates/pa-agent/README.md@@ -12,4 +12,9 @@ No tool implementations (pa-core), no providers (pa-ai), no session persistence,`run_loop` (session inputs -> stream of loop events), `ToolDispatcher` trait. Loop internals `pub(crate)`.## Depends on-pa-types, pa-ai (one-way).+No workspace dependencies. The proxy transport uses the already-resolved+`rustls` PEM iterator and DER validation to retain the valid prefix of+`NODE_EXTRA_CA_CERTS` when a later certificate is malformed, matching Node.+reqwest's whole-bundle parser discards that prefix on error; directly using+the existing transport dependency avoids a peer dependency on pa-ai and adds+no package version or public API.diff --git a/crates/pa-agent/src/proxy.rs b/crates/pa-agent/src/proxy.rsindex d43e9cf522..b9e76789df 100644--- a/crates/pa-agent/src/proxy.rs+++ b/crates/pa-agent/src/proxy.rs@@ -5,8 +5,11 @@use std::collections::HashMap;use std::fmt::Write;+use std::sync::LazyLock;use futures::StreamExt;+use rustls::pki_types::pem::PemObject;+use rustls::pki_types::CertificateDer;use serde::Deserialize;use crate::abort::AbortSignal;@@ -19,6 +22,35 @@ use crate::types::{Usage,};+// pa-agent is a leaf crate: use the already-resolved rustls PEM/DER parser+// instead of a peer provider dependency. Cache once, retaining Node's valid+// prefix if a later certificate is malformed.+static PROXY_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {+ let mut certs = Vec::new();+ if let Some(path) = std::env::var_os("NODE_EXTRA_CA_CERTS") {+ let loaded = (|| -> anyhow::Result<()> {+ let mut roots = rustls::RootCertStore::empty();+ for cert in CertificateDer::pem_file_iter(&path)? {+ let cert = cert?;+ roots.add(cert.clone())?;+ certs.push(reqwest::Certificate::from_der(&cert)?);+ }+ anyhow::ensure!(!certs.is_empty(), "empty CA bundle");+ Ok(())+ })();+ if let Err(error) = loaded {+ eprintln!(+ "NODE_EXTRA_CA_CERTS could not be fully loaded for the proxy; keeping certificates loaded before the error: {error}"+ );+ }+ }+ let mut builder = reqwest::Client::builder();+ for cert in certs {+ builder = builder.add_root_certificate(cert);+ }+ builder.build().expect("proxy HTTP client")+});+#[derive(Debug, Clone, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum ProxyAssistantMessageEvent {@@ -262,7 +294,7 @@ async fn proxy_run("options": request_options,});- let client = reqwest::Client::new();+ let client = &*PROXY_CLIENT;let send = async {client.post(format!("{}/api/stream", proxy_options.proxy_url))diff --git a/crates/pa-agent/tests/proxy_extra_ca.rs b/crates/pa-agent/tests/proxy_extra_ca.rsnew file mode 100644index 0000000000..c94a55ea0a--- /dev/null+++ b/crates/pa-agent/tests/proxy_extra_ca.rs@@ -0,0 +1,169 @@+//! A dedicated binary keeps the proxy's once-only CA cache isolated from other tests.++use std::sync::Arc;+use std::time::Duration;++use pa_agent::abort::AbortSignal;+use pa_agent::proxy::{stream_proxy, ProxyStreamOptions};+use pa_agent::stream::{LlmContext, ModelStream, StreamRequestOptions};+use pa_agent::types::{Model, StopReason};+use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::TcpListener;+use tokio_rustls::rustls::pki_types::PrivateKeyDer;+use tokio_rustls::rustls::ServerConfig;+use tokio_rustls::TlsAcceptor;++struct FixtureEnvironment(Vec<(&'static str, Option<std::ffi::OsString>)>);++impl Drop for FixtureEnvironment {+ fn drop(&mut self) {+ for (name, previous) in self.0.drain(..) {+ match previous {+ Some(value) => std::env::set_var(name, value),+ None => std::env::remove_var(name),+ }+ }+ }+}++#[tokio::test]+// Keep setup, the untrusted control, and the public-path assertion together so+// the single test binary owns every socket and environment mutation it creates.+#[allow(clippy::too_many_lines)]+async fn the_default_proxy_stream_honors_node_extra_ca_certs() {+ let mut ca_params = CertificateParams::new(Vec::<String>::new()).expect("CA params");+ ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);+ let ca_key = KeyPair::generate().expect("CA key");+ let ca_cert = ca_params.self_signed(&ca_key).expect("CA cert");+ let leaf_params = CertificateParams::new(vec!["127.0.0.1".to_string()]).expect("leaf params");+ let leaf_key = KeyPair::generate().expect("leaf key");+ let leaf_cert = leaf_params+ .signed_by(&leaf_key, &Issuer::from_params(&ca_params, &ca_key))+ .expect("leaf cert");+ let config = ServerConfig::builder()+ .with_no_client_auth()+ .with_single_cert(+ vec![leaf_cert.der().clone()],+ PrivateKeyDer::Pkcs8(leaf_key.serialize_der().into()),+ )+ .expect("TLS config");+ let acceptor = TlsAcceptor::from(Arc::new(config));+ let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");+ let proxy_url = format!("https://{}", listener.local_addr().expect("address"));++ let server = tokio::spawn(async move {+ // The plain-client control must reject this CA, which is absent from+ // both the OS store and the bundled public roots.+ let (socket, _) = listener.accept().await.expect("control connection");+ assert!(acceptor.accept(socket).await.is_err());+ let (socket, _) = listener.accept().await.expect("proxy connection");+ let mut stream = acceptor.accept(socket).await.expect("proxy TLS handshake");+ let mut request = Vec::new();+ let mut buffer = [0; 4096];+ loop {+ let count = stream.read(&mut buffer).await.expect("request read");+ assert!(count > 0, "proxy closed before sending its request");+ request.extend_from_slice(&buffer[..count]);+ if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {+ let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();+ let length: usize = headers+ .lines()+ .find_map(|line| line.strip_prefix("content-length: "))+ .expect("content length")+ .parse()+ .expect("numeric content length");+ if request.len() >= end + 4 + length {+ assert!(headers.starts_with("post /api/stream http/1.1\r\n"));+ assert!(headers+ .lines()+ .any(|line| line == "authorization: bearer fixture-token"));+ break;+ }+ }+ }+ let sse = "data: {\"type\":\"start\"}\n\ndata: {\"type\":\"done\",\"reason\":\"stop\",\"usage\":{}}\n\n";+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{sse}",+ sse.len()+ );+ stream+ .write_all(response.as_bytes())+ .await+ .expect("response");+ stream.flush().await.expect("flush");+ });++ let bundle = tempfile::NamedTempFile::new().expect("CA bundle");+ // Node retains the trusted prefix when a later PEM certificate has invalid DER.+ let pem = format!(+ "{}-----BEGIN CERTIFICATE-----\nAQID\n-----END CERTIFICATE-----\n",+ ca_cert.pem()+ );+ std::fs::write(bundle.path(), pem).expect("write CA");+ let _environment = FixtureEnvironment(+ [+ "NODE_EXTRA_CA_CERTS",+ "HTTP_PROXY",+ "http_proxy",+ "HTTPS_PROXY",+ "https_proxy",+ "ALL_PROXY",+ "all_proxy",+ "NO_PROXY",+ "no_proxy",+ ]+ .into_iter()+ .map(|name| (name, std::env::var_os(name)))+ .collect(),+ );+ std::env::set_var("NODE_EXTRA_CA_CERTS", bundle.path());+ // Exercise the real default client while keeping inherited corporate+ // proxies from sending this fixture's requests outside the loopback server.+ std::env::set_var("NO_PROXY", "127.0.0.1,localhost");+ std::env::set_var("no_proxy", "127.0.0.1,localhost");+ for name in [+ "HTTP_PROXY",+ "http_proxy",+ "HTTPS_PROXY",+ "https_proxy",+ "ALL_PROXY",+ "all_proxy",+ ] {+ std::env::remove_var(name);+ }++ tokio::time::timeout(Duration::from_secs(10), async {+ let error = reqwest::Client::builder()+ .no_proxy()+ .build()+ .expect("plain client")+ .get(&proxy_url)+ .send()+ .await+ .expect_err("plain reqwest must reject the fixture CA");+ assert!(error.is_connect(), "control must fail during TLS: {error}");+ let model: Model = serde_json::from_value(serde_json::json!({+ "id": "fixture", "name": "Fixture", "api": "proxy", "provider": "proxy",+ "baseUrl": proxy_url, "reasoning": false, "contextWindow": 1000, "maxTokens": 100,+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}+ }))+ .expect("model");+ let (_handle, mut events) = stream_proxy(+ model,+ LlmContext::default(),+ StreamRequestOptions::default(),+ ProxyStreamOptions {+ auth_token: "fixture-token".to_string(),+ proxy_url,+ signal: AbortSignal::never(),+ },+ );+ let result = events.result().await.expect("terminal event");+ assert_eq!(result.stop_reason, StopReason::Stop, "{result:?}");+ assert_eq!(result.error_message, None);+ server.await.expect("TLS fixture completed");+ })+ .await+ .expect("TLS proxy completes within the timeout");+}diff --git a/crates/pa-ai/Cargo.toml b/crates/pa-ai/Cargo.tomlindex 8eebd0434a..3af2fb629b 100644--- a/crates/pa-ai/Cargo.toml+++ b/crates/pa-ai/Cargo.toml@@ -12,6 +12,7 @@ serde_json = { workspace = true }anyhow = { workspace = true }thiserror = { workspace = true }futures = { workspace = true }+tracing = { workspace = true }tokio = { workspace = true }tokio-util = { version = "0.7", default-features = false, features = ["rt"] }# `http2` enables ALPN-negotiated HTTP/2 for providers whose TS transport@@ -19,7 +20,8 @@ tokio-util = { version = "0.7", default-features = false, features = ["rt"] }# shared client's `http1_only()`.reqwest = { version = "0.12", default-features = false, features = ["json",- "rustls-tls",+ "rustls-tls-native-roots",+ "rustls-tls-webpki-roots","gzip","http2",] }@@ -36,7 +38,14 @@ hmac = "0.12"hex = "0.4"rsa = { version = "0.9", features = ["sha2"] }url = "2"-tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake", "rustls-tls-webpki-roots"] }+rustls = { version = "0.23", default-features = false, features = [+ "ring",+ "std",+ "tls12",+] }+rustls-native-certs = "0.8"+webpki-roots = "1"+tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake", "rustls-tls-native-roots", "rustls-tls-webpki-roots"] }http = "1"[dev-dependencies]@@ -44,6 +53,9 @@ tokio = { workspace = true, features = ["test-util", "macros"] }# Wire tests only: the WS handshake accept key (SHA-1 of key + GUID); the# same version the graph resolves for tokio-tungstenite's rustls chain.sha1 = "0.10"+tempfile = "3"+rcgen = { version = "0.14", default-features = false, features = ["pem", "ring"] }+tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }[lints]workspace = truediff --git a/crates/pa-ai/README.md b/crates/pa-ai/README.mdindex d16a1ff9f8..635a0b4154 100644--- a/crates/pa-ai/README.md+++ b/crates/pa-ai/README.md@@ -9,7 +9,7 @@ Provider trait + per-provider streaming clients (anthropic, openai-completions/rNo agent loop, no tool execution, no session state, no UI. Receives/returns `pa-types` messages.## Public API-`Provider` trait, `ProviderRegistry`, model lookup/resolution, faux provider. Per-provider internals are `pub(crate)`.+`Provider` trait, `ProviderRegistry`, model lookup/resolution, faux provider. `utils::tls::http_client_builder` lets caller-owned HTTP transports apply the shared extra-CA trust configuration. Per-provider internals are `pub(crate)`.## Depends onpa-types (one-way).diff --git a/crates/pa-ai/src/lib.rs b/crates/pa-ai/src/lib.rsindex 18d4cc71b2..e9151481b2 100644--- a/crates/pa-ai/src/lib.rs+++ b/crates/pa-ai/src/lib.rs@@ -39,12 +39,14 @@ pub use stream::{complete, complete_simple, stream, stream_simple};// Cross-crate surface consumed by the agent layer (pa-ai owned).pub mod utils {//! Overflow detection, stream-failure classification, JSON repair- //! parsing, and structured diagnostics. SSE decoding, HTTP plumbing,- //! hashing, and logging are crate-internal.+ //! parsing, structured diagnostics, and the caller-facing TLS client+ //! builder. SSE decoding, request plumbing, hashing, and logging are+ //! crate-internal.pub use crate::utils_inner::diagnostics;pub use crate::utils_inner::json_parse;pub use crate::utils_inner::overflow;pub use crate::utils_inner::stream_failure;+ pub use crate::utils_inner::tls;}mod utils_inner;diff --git a/crates/pa-ai/src/oauth/mod.rs b/crates/pa-ai/src/oauth/mod.rsindex fbb99afbe3..1b9a876ca4 100644--- a/crates/pa-ai/src/oauth/mod.rs+++ b/crates/pa-ai/src/oauth/mod.rs@@ -88,7 +88,7 @@ impl CodexHttp for ReqwestCodexHttp {) -> std::pin::Pin<Box<dyn Future<Output = Result<CodexHttpResponse, String>> + Send + 'a>>{Box::pin(async move {- let client = reqwest::Client::builder()+ let client = crate::utils_inner::tls::http_client_builder().timeout(Duration::from_millis(timeout_ms)).build().map_err(|error| error.to_string())?;diff --git a/crates/pa-ai/src/oauth/provider_http.rs b/crates/pa-ai/src/oauth/provider_http.rsindex bc74ba9920..406b365a55 100644--- a/crates/pa-ai/src/oauth/provider_http.rs+++ b/crates/pa-ai/src/oauth/provider_http.rs@@ -76,7 +76,7 @@ impl ProviderHttp for ReqwestProviderHttp {ProviderHttpMethod::Get => reqwest::Method::GET,ProviderHttpMethod::Post => reqwest::Method::POST,};- let client = reqwest::Client::builder()+ let client = crate::utils_inner::tls::http_client_builder().timeout(Duration::from_millis(timeout_ms)).redirect(reqwest::redirect::Policy::custom(move |attempt| {// TS `redirect: "error"`: a redirected requestdiff --git a/crates/pa-ai/src/providers/openai_codex_responses/websocket.rs b/crates/pa-ai/src/providers/openai_codex_responses/websocket.rsindex 238ae76b2d..a1b8ff2937 100644--- a/crates/pa-ai/src/providers/openai_codex_responses/websocket.rs+++ b/crates/pa-ai/src/providers/openai_codex_responses/websocket.rs@@ -199,7 +199,12 @@ async fn spawn_connection_worker(return Err(CodexStreamError::Aborted);}- let connect = tokio_tungstenite::connect_async(request);+ let connect = tokio_tungstenite::connect_async_tls_with_config(+ request,+ None,+ false,+ Some(crate::utils_inner::tls::websocket_connector()),+ );let (stream, _response) = match signal.as_ref() {Some(signal) => {tokio::select! {diff --git a/crates/pa-ai/src/utils_inner/http.rs b/crates/pa-ai/src/utils_inner/http.rsindex bf81dc2bbf..a406249081 100644--- a/crates/pa-ai/src/utils_inner/http.rs+++ b/crates/pa-ai/src/utils_inner/http.rs@@ -19,7 +19,7 @@ static H2_ALPN_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();/// reqwest `http2` feature (bedrock) cannot change the transport of any other provider.fn client() -> &'static reqwest::Client {CLIENT.get_or_init(|| {- reqwest::Client::builder()+ crate::utils_inner::tls::http_client_builder().http1_only().pool_idle_timeout(std::time::Duration::from_secs(90)).build()@@ -31,7 +31,7 @@ fn client() -> &'static reqwest::Client {/// default transport; cleartext bedrock endpoints go through `providers/bedrock/h2.rs` instead.fn h2_alpn_client() -> &'static reqwest::Client {H2_ALPN_CLIENT.get_or_init(|| {- reqwest::Client::builder()+ crate::utils_inner::tls::http_client_builder().pool_idle_timeout(std::time::Duration::from_secs(90)).build().expect("reqwest h2 client")diff --git a/crates/pa-ai/src/utils_inner/mod.rs b/crates/pa-ai/src/utils_inner/mod.rsindex ce3950a6d6..4d446218c9 100644--- a/crates/pa-ai/src/utils_inner/mod.rs+++ b/crates/pa-ai/src/utils_inner/mod.rs@@ -12,5 +12,6 @@ pub mod overflow;pub mod sanitize_unicode;pub mod sse;pub mod stream_failure;+pub mod tls;pub use stream_failure::ProviderError;diff --git a/crates/pa-ai/src/utils_inner/tls.rs b/crates/pa-ai/src/utils_inner/tls.rsnew file mode 100644index 0000000000..fddfa154ed--- /dev/null+++ b/crates/pa-ai/src/utils_inner/tls.rs@@ -0,0 +1,59 @@+use std::sync::{Arc, LazyLock};++use rustls::pki_types::pem::PemObject;+use rustls::pki_types::CertificateDer;++static EXTRA_CERTS: LazyLock<Vec<CertificateDer<'static>>> = LazyLock::new(|| {+ let Some(path) = std::env::var_os("NODE_EXTRA_CA_CERTS") else {+ return Vec::new();+ };+ let mut certs = Vec::new();+ let loaded = (|| -> anyhow::Result<()> {+ let mut roots = rustls::RootCertStore::empty();+ for cert in CertificateDer::pem_file_iter(&path)? {+ let cert = cert?;+ roots.add(cert.clone())?;+ certs.push(cert);+ }+ anyhow::ensure!(!certs.is_empty(), "empty CA bundle");+ Ok(())+ })();+ if let Err(error) = loaded {+ tracing::warn!(+ path = %path.display(),+ error = %error,+ "NODE_EXTRA_CA_CERTS could not be fully loaded; keeping certificates loaded before the error"+ );+ }+ // Node keeps the valid prefix and stops at the first PEM or DER error.+ certs+});++/// # Panics+///+/// Never: a DER certificate parsed from a PEM bundle is always accepted.+pub fn http_client_builder() -> reqwest::ClientBuilder {+ let mut builder = reqwest::Client::builder();+ for cert in &*EXTRA_CERTS {+ builder = builder.add_root_certificate(+ reqwest::Certificate::from_der(cert).expect("extra CA certificate"),+ );+ }+ builder+}++static WS_CONFIG: LazyLock<Arc<rustls::ClientConfig>> = LazyLock::new(|| {+ let mut roots = rustls::RootCertStore::empty();+ roots.add_parsable_certificates(rustls_native_certs::load_native_certs().certs);+ roots.add_parsable_certificates(EXTRA_CERTS.iter().cloned());+ roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());+ Arc::new(+ rustls::ClientConfig::builder()+ .with_root_certificates(roots)+ .with_no_client_auth(),+ )+});++pub(crate) fn websocket_connector() -> tokio_tungstenite::Connector {+ tokio_tungstenite::Connector::Rustls(Arc::clone(&WS_CONFIG))+}diff --git a/crates/pa-ai/tests/codex_extra_ca.rs b/crates/pa-ai/tests/codex_extra_ca.rsnew file mode 100644index 0000000000..71ca4a5385--- /dev/null+++ b/crates/pa-ai/tests/codex_extra_ca.rs@@ -0,0 +1,191 @@+//! Dedicated binary: Codex WSS is the first process-default TLS client.++use std::sync::Arc;+use std::time::Duration;++use base64::Engine as _;+use futures::{SinkExt, StreamExt};+use pa_ai::types::{Context, Model, StopReason, StreamOptions, Transport};+use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair};+use serde_json::json;+use tokio::net::TcpListener;+use tokio_rustls::rustls::pki_types::PrivateKeyDer;+use tokio_rustls::rustls::{crypto::CryptoProvider, ServerConfig};+use tokio_rustls::TlsAcceptor;+use tokio_tungstenite::tungstenite::Message;++struct FixtureEnvironment(Vec<(&'static str, Option<std::ffi::OsString>)>);++impl Drop for FixtureEnvironment {+ fn drop(&mut self) {+ for (name, previous) in self.0.drain(..) {+ match previous {+ Some(value) => std::env::set_var(name, value),+ None => std::env::remove_var(name),+ }+ }+ }+}++#[tokio::test]+// Keep the fixture, first-use precondition and public-path assertions in one+// test so no other test/client can initialize the process-default TLS provider.+// tungstenite dictates the upgrade callback's Response-sized error type.+#[allow(clippy::too_many_lines, clippy::result_large_err)]+async fn the_first_codex_websocket_trusts_node_extra_ca_certs() {+ let mut ca_params = CertificateParams::new(Vec::<String>::new()).expect("CA params");+ ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);+ let ca_key = KeyPair::generate().expect("CA key");+ let ca_cert = ca_params.self_signed(&ca_key).expect("CA cert");+ let leaf_params = CertificateParams::new(vec!["127.0.0.1".to_string()]).expect("leaf params");+ let leaf_key = KeyPair::generate().expect("leaf key");+ let leaf_cert = leaf_params+ .signed_by(&leaf_key, &Issuer::from_params(&ca_params, &ca_key))+ .expect("leaf cert");+ // Explicit provider only for the server: do not install a process default+ // before the production client's first call to ClientConfig::builder().+ let mut config = ServerConfig::builder_with_provider(Arc::new(+ tokio_rustls::rustls::crypto::ring::default_provider(),+ ))+ .with_safe_default_protocol_versions()+ .expect("server protocol versions")+ .with_no_client_auth()+ .with_single_cert(+ vec![leaf_cert.der().clone()],+ PrivateKeyDer::Pkcs8(leaf_key.serialize_der().into()),+ )+ .expect("TLS config");+ config.alpn_protocols = vec![b"http/1.1".to_vec()];+ let acceptor = TlsAcceptor::from(Arc::new(config));+ let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");+ let base_url = format!("https://{}", listener.local_addr().expect("address"));+ let server = tokio::spawn(async move {+ let (socket, _) = listener.accept().await.expect("Codex connection");+ let tls = acceptor+ .accept(socket)+ .await+ .expect("custom-CA TLS handshake");+ // The old default tungstenite connector also advertises no ALPN.+ assert_eq!(tls.get_ref().1.alpn_protocol(), None);+ let mut websocket = tokio_tungstenite::accept_hdr_async(+ tls,+ |request: &tokio_tungstenite::tungstenite::handshake::server::Request, response| {+ assert_eq!(request.uri().path(), "/codex/responses");+ assert_eq!(request.headers()["chatgpt-account-id"], "fixture-account");+ Ok(response)+ },+ )+ .await+ .expect("WebSocket upgrade");+ let request = websocket+ .next()+ .await+ .expect("request frame")+ .expect("request");+ let request: serde_json::Value =+ serde_json::from_str(request.to_text().expect("text request")).expect("request JSON");+ assert_eq!(request["type"], "response.create");+ for event in [+ json!({"type": "response.created", "response": {"id": "fixture-response"}}),+ json!({"type": "response.output_item.added", "output_index": 0,+ "item": {"type": "message", "id": "fixture-message", "role": "assistant", "status": "in_progress", "content": []}}),+ json!({"type": "response.content_part.added", "output_index": 0, "content_index": 0,+ "part": {"type": "output_text", "text": ""}}),+ json!({"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "Trusted"}),+ json!({"type": "response.output_item.done", "item": {"type": "message", "id": "fixture-message",+ "role": "assistant", "status": "completed", "content": [{"type": "output_text", "text": "Trusted"}]}}),+ json!({"type": "response.completed", "response": {"id": "fixture-response", "status": "completed",+ "usage": {"input_tokens": 5, "output_tokens": 3, "total_tokens": 8}}}),+ ] {+ websocket+ .send(Message::Text(event.to_string().into()))+ .await+ .expect("response frame");+ }+ });++ let bundle = tempfile::NamedTempFile::new().expect("CA bundle");+ // Node retains the trusted prefix when a later PEM certificate has invalid DER.+ let pem = format!(+ "{}-----BEGIN CERTIFICATE-----\nAQID\n-----END CERTIFICATE-----\n",+ ca_cert.pem()+ );+ std::fs::write(bundle.path(), pem).expect("write CA");+ let _environment = FixtureEnvironment(+ [+ "NODE_EXTRA_CA_CERTS",+ "HTTP_PROXY",+ "http_proxy",+ "HTTPS_PROXY",+ "https_proxy",+ "ALL_PROXY",+ "all_proxy",+ "NO_PROXY",+ "no_proxy",+ ]+ .into_iter()+ .map(|name| (name, std::env::var_os(name)))+ .collect(),+ );+ std::env::set_var("NODE_EXTRA_CA_CERTS", bundle.path());+ // Even an unexpected HTTP fallback must remain local to this fixture.+ for name in [+ "HTTP_PROXY",+ "http_proxy",+ "HTTPS_PROXY",+ "https_proxy",+ "ALL_PROXY",+ "all_proxy",+ ] {+ std::env::remove_var(name);+ }+ std::env::set_var("NO_PROXY", "127.0.0.1,localhost");+ std::env::set_var("no_proxy", "127.0.0.1,localhost");+ assert!(+ CryptoProvider::get_default().is_none(),+ "fixture must not initialize the default TLS provider"+ );+ let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(+ json!({"https://api.openai.com/auth": {"chatgpt_account_id": "fixture-account"}})+ .to_string(),+ );+ let model: Model = serde_json::from_value(json!({+ "id": "gpt-5.1-codex", "name": "Fixture Codex", "api": "openai-codex-responses", "provider": "openai-codex",+ "baseUrl": base_url, "reasoning": false, "input": ["text"], "contextWindow": 1000, "maxTokens": 100,+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}+ })).expect("model");+ tokio::time::timeout(Duration::from_secs(10), async {+ let events = pa_ai::stream(+ &model,+ &Context::default(),+ Some(StreamOptions {+ api_key: Some(format!("fixture.{payload}.signature")),+ transport: Some(Transport::Websocket),+ session_id: Some("fixture-first-wss".to_string()),+ ..Default::default()+ }),+ )+ .expect("Codex provider");+ let result = events.result().await;+ assert_eq!(+ (result.stop_reason, result.response_id.as_deref()),+ (StopReason::Stop, Some("fixture-response")),+ "{result:?}"+ );+ assert_eq!(result.error_message, None);+ let content = result+ .content+ .iter()+ .filter_map(|part| match part {+ pa_ai::types::AssistantContent::Text(text) => Some(text.text.as_str()),+ pa_ai::types::AssistantContent::Thinking(_)+ | pa_ai::types::AssistantContent::ToolCall(_) => None,+ })+ .collect::<Vec<_>>();+ assert_eq!(content, vec!["Trusted"]);+ server.await.expect("TLS fixture completed");+ pa_ai::codex_debug::close_websocket_sessions(Some("fixture-first-wss"));+ })+ .await+ .expect("Codex WSS completes within the timeout");+}diff --git a/crates/pa-core/Cargo.toml b/crates/pa-core/Cargo.tomlindex a6b3722d05..1bba504158 100644--- a/crates/pa-core/Cargo.toml+++ b/crates/pa-core/Cargo.toml@@ -35,7 +35,7 @@ url = "2"hmac = "0.12"globset = "0.4"toml.workspace = true-reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "stream"] }+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots", "rustls-tls-webpki-roots", "json", "stream"] }tar = "0.4"flate2 = "1"unicode-normalization = "0.1"diff --git a/crates/pa-core/src/agent_traces/http.rs b/crates/pa-core/src/agent_traces/http.rsindex 8e9aaacc1a..66b6e2a031 100644--- a/crates/pa-core/src/agent_traces/http.rs+++ b/crates/pa-core/src/agent_traces/http.rs@@ -58,7 +58,7 @@ impl TraceHttp for ReqwestTraceHttp {cancel: Option<&'a TraceUploadCancel>,) -> Pin<Box<dyn Future<Output = Result<TraceHttpResponse, TraceHttpError>> + Send + 'a>> {Box::pin(async move {- let client = reqwest::Client::builder()+ let client = pa_ai::utils::tls::http_client_builder().timeout(std::time::Duration::from_millis(timeout_ms)).build().map_err(|error| TraceHttpError::Transport(error.to_string()))?;diff --git a/crates/pa-core/src/auth/prime_inference.rs b/crates/pa-core/src/auth/prime_inference.rsindex 7d22824448..6d9a86a39e 100644--- a/crates/pa-core/src/auth/prime_inference.rs+++ b/crates/pa-core/src/auth/prime_inference.rs@@ -115,7 +115,7 @@ impl PrimeHttp for ReqwestPrimeHttp {let url = url.to_string();let api_key = api_key.to_string();Box::pin(async move {- let client = reqwest::Client::builder()+ let client = pa_ai::utils::tls::http_client_builder().timeout(Duration::from_millis(timeout_ms)).build().map_err(|error| error.to_string())?;@@ -146,7 +146,7 @@ impl PrimeHttp for ReqwestPrimeHttp {timeout_ms: u64,) -> Pin<Box<dyn Future<Output = Result<PrimeHttpResponse, String>> + Send + 'a>> {Box::pin(async move {- let client = reqwest::Client::builder()+ let client = pa_ai::utils::tls::http_client_builder().timeout(Duration::from_millis(timeout_ms)).build().map_err(|error| error.to_string())?;diff --git a/crates/pa-core/src/mcp/oauth_http.rs b/crates/pa-core/src/mcp/oauth_http.rsindex d622b95cb8..bdfebabbaf 100644--- a/crates/pa-core/src/mcp/oauth_http.rs+++ b/crates/pa-core/src/mcp/oauth_http.rs@@ -80,10 +80,10 @@ impl ReqwestOAuthHttp {#[must_use]pub fn new() -> Self {ReqwestOAuthHttp {- client: reqwest::Client::builder()+ client: pa_ai::utils::tls::http_client_builder().redirect(reqwest::redirect::Policy::none()).build()- .expect("reqwest client construction cannot fail with no TLS config"),+ .expect("oauth client"),}}}diff --git a/crates/pa-core/src/mcp/probe.rs b/crates/pa-core/src/mcp/probe.rsindex df37774f79..9a661cea2c 100644--- a/crates/pa-core/src/mcp/probe.rs+++ b/crates/pa-core/src/mcp/probe.rs@@ -61,7 +61,7 @@ pub struct ReqwestMcpProbe {impl Default for ReqwestMcpProbe {fn default() -> Self {Self {- client: reqwest::Client::builder()+ client: pa_ai::utils::tls::http_client_builder()// No redirects: a redirecting endpoint must not receive the token..redirect(reqwest::redirect::Policy::none()).build()diff --git a/crates/pa-core/src/models/prime_inference_catalog.rs b/crates/pa-core/src/models/prime_inference_catalog.rsindex 87817f9105..ef5cb5945b 100644--- a/crates/pa-core/src/models/prime_inference_catalog.rs+++ b/crates/pa-core/src/models/prime_inference_catalog.rs@@ -322,7 +322,7 @@ pub(crate) async fn fetch_prime_inference_model_catalog(timeout_ms: u64,allow_empty: bool,) -> Result<(serde_json::Value, Vec<PrimeInferenceCatalogEntry>), String> {- let client = reqwest::Client::builder()+ let client = pa_ai::utils::tls::http_client_builder().timeout(std::time::Duration::from_millis(timeout_ms)).build().map_err(|error| error.to_string())?;diff --git a/crates/pa-core/src/session_engine/telemetry.rs b/crates/pa-core/src/session_engine/telemetry.rsindex 38a432094a..dee853548e 100644--- a/crates/pa-core/src/session_engine/telemetry.rs+++ b/crates/pa-core/src/session_engine/telemetry.rs@@ -1139,7 +1139,10 @@ pub fn build_client(config.install_id = id;let mut sinks: Vec<Arc<dyn pa_telemetry::TelemetrySink>> = Vec::new();if let Some(endpoint) = telemetry_endpoint() {- sinks.push(Arc::new(pa_telemetry::AnalyticsSink::new(endpoint)));+ sinks.push(Arc::new(pa_telemetry::AnalyticsSink::with_http_builder(+ endpoint,+ pa_ai::utils::tls::http_client_builder(),+ )));}let local_mirror = settings.settings()diff --git a/crates/pa-core/src/update/download.rs b/crates/pa-core/src/update/download.rsindex 41a05c96ce..9921e4d0f7 100644--- a/crates/pa-core/src/update/download.rs+++ b/crates/pa-core/src/update/download.rs@@ -58,7 +58,9 @@ async fn download_once(user_agent: &str,) -> Result<()> {use futures::StreamExt;- let response = reqwest::Client::new()+ let response = pa_ai::utils::tls::http_client_builder()+ .build()+ .expect("download client").get(url).header("User-Agent", user_agent).timeout(timeout)diff --git a/crates/pa-core/src/update/installer.rs b/crates/pa-core/src/update/installer.rsindex e32f3d1163..27ee42df74 100644--- a/crates/pa-core/src/update/installer.rs+++ b/crates/pa-core/src/update/installer.rs@@ -510,7 +510,9 @@ pub fn installed_channel(prefix: &Path) -> Option<&'static str> {/// Returns an error when the request fails, answers a non-success status,/// or the body cannot be read or written.async fn fetch_script(url: &str) -> Result<(PathBuf, std::fs::File)> {- let response = reqwest::Client::new()+ let response = pa_ai::utils::tls::http_client_builder()+ .build()+ .expect("installer client").get(url).header("User-Agent", update_user_agent(env!("CARGO_PKG_VERSION"))).timeout(SCRIPT_FETCH_TIMEOUT)diff --git a/crates/pa-core/src/update/release.rs b/crates/pa-core/src/update/release.rsindex d77931bda7..3f02089a04 100644--- a/crates/pa-core/src/update/release.rs+++ b/crates/pa-core/src/update/release.rs@@ -64,6 +64,10 @@ pub fn update_user_agent(version: &str) -> String {/// # Errors////// Returns an error only when the manifest body cannot be read after a successful fetch.+///+/// # Panics+///+/// Panics if the HTTP client cannot be built.pub async fn latest_release(current_version: &str,channel: Option<UpdateChannel>,@@ -76,7 +80,9 @@ pub async fn latest_release(let manifest_path =super::version::resolve_update_channel(current_version, channel).manifest_path();let url = format!("{}/{manifest_path}", base_url.trim_end_matches('/'));- let response = reqwest::Client::new()+ let response = pa_ai::utils::tls::http_client_builder()+ .build()+ .expect("release client").get(&url).header("User-Agent", update_user_agent(current_version)).header("accept", "application/json")diff --git a/crates/pa-models/Cargo.toml b/crates/pa-models/Cargo.tomlindex eb1962f9e4..3f664957ff 100644--- a/crates/pa-models/Cargo.toml+++ b/crates/pa-models/Cargo.toml@@ -14,7 +14,8 @@ thiserror = { workspace = true }tokio = { workspace = true }tracing = { version = "0.1", features = ["attributes"] }reqwest = { version = "0.12", default-features = false, features = [- "rustls-tls",+ "rustls-tls-native-roots",+ "rustls-tls-webpki-roots",] }hmac = "0.12"sha2 = "0.10"@@ -22,6 +23,8 @@ hex = "0.4"[dev-dependencies]tempfile = "3"+rcgen = { version = "0.14", default-features = false, features = ["pem", "ring"] }+tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }[lints]workspace = truediff --git a/crates/pa-models/src/fetch.rs b/crates/pa-models/src/fetch.rsindex 0da4b807a4..f8ccd5c7cb 100644--- a/crates/pa-models/src/fetch.rs+++ b/crates/pa-models/src/fetch.rs@@ -76,7 +76,7 @@ impl CatalogFetcher {/// Panics if the reqwest client fails to build.#[must_use]pub fn with_limits(timeout: Duration, max_bytes: usize) -> Self {- let client = reqwest::Client::builder()+ let client = pa_ai::utils::tls::http_client_builder()// A moved catalog must be a client change, never a silent hop..redirect(reqwest::redirect::Policy::none()).build()diff --git a/crates/pa-models/tests/common/mod.rs b/crates/pa-models/tests/common/mod.rsindex 6eb472c0d2..a83f21b8f8 100644--- a/crates/pa-models/tests/common/mod.rs+++ b/crates/pa-models/tests/common/mod.rs@@ -8,8 +8,13 @@use std::collections::VecDeque;use std::sync::{Arc, Mutex};+use pa_models::fetch::{CatalogFetcher, FetchOutcome};+use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair};use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::TcpListener;+use tokio_rustls::rustls::pki_types::PrivateKeyDer;+use tokio_rustls::rustls::ServerConfig;+use tokio_rustls::TlsAcceptor;type RequestLog = Arc<Mutex<Vec<String>>>;@@ -158,3 +163,136 @@ pub fn oversized_stream() -> Vec<u8> {response.extend_from_slice(b"\r\n");response}++const TLS_TEST_BODY: &str = "{\"schemaVersion\":1,\"models\":[]}";++struct TlsCatalogServer {+ base_url: String,+ ca_pem: String,+ task: tokio::task::JoinHandle<()>,+}++impl Drop for TlsCatalogServer {+ fn drop(&mut self) {+ // Also cancel the owned listener/socket if a client assertion panics+ // or the bounded fixture run times out.+ self.task.abort();+ }+}++struct FixtureEnvironment(Vec<(&'static str, Option<std::ffi::OsString>)>);++impl Drop for FixtureEnvironment {+ fn drop(&mut self) {+ for (name, previous) in self.0.drain(..) {+ match previous {+ Some(value) => std::env::set_var(name, value),+ None => std::env::remove_var(name),+ }+ }+ }+}++async fn tls_catalog_server() -> TlsCatalogServer {+ let mut ca_params = CertificateParams::new(Vec::<String>::new()).expect("ca params");+ ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);+ ca_params+ .distinguished_name+ .push(DnType::CommonName, "catalog test ca");+ let ca_key = KeyPair::generate().expect("ca key");+ let ca_cert = ca_params.self_signed(&ca_key).expect("ca cert");++ let leaf_params = CertificateParams::new(vec!["127.0.0.1".to_string()]).expect("leaf params");+ let leaf_key = KeyPair::generate().expect("leaf key");+ let leaf_cert = leaf_params+ .signed_by(&leaf_key, &Issuer::from_params(&ca_params, &ca_key))+ .expect("leaf cert");++ let config = ServerConfig::builder()+ .with_no_client_auth()+ .with_single_cert(+ vec![leaf_cert.der().clone()],+ PrivateKeyDer::Pkcs8(leaf_key.serialize_der().into()),+ )+ .expect("tls config");+ let acceptor = TlsAcceptor::from(Arc::new(config));+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind tls server");+ let port = listener.local_addr().expect("tls addr").port();+ let response = ok_json(TLS_TEST_BODY, None);+ let task = tokio::spawn(async move {+ let (socket, _) = listener.accept().await.expect("catalog connection");+ let mut stream = acceptor+ .accept(socket)+ .await+ .expect("catalog TLS handshake");+ let mut buffer = [0u8; 8_192];+ assert!(stream.read(&mut buffer).await.expect("catalog request") > 0);+ stream.write_all(&response).await.expect("catalog response");+ stream.flush().await.expect("catalog flush");+ });+ TlsCatalogServer {+ base_url: format!("https://127.0.0.1:{port}"),+ ca_pem: ca_cert.pem(),+ task,+ }+}++pub async fn fetch_trusting_test_ca(env_var: &str) {+ let mut server = tls_catalog_server().await;+ let bundle = tempfile::NamedTempFile::new().expect("ca bundle");+ let pem = if env_var == "NODE_EXTRA_CA_CERTS" {+ // Keep native-loader input pure; only Node extra-cert parsing retains a prefix.+ format!(+ "{}-----BEGIN CERTIFICATE-----\nAQID\n-----END CERTIFICATE-----\n",+ server.ca_pem+ )+ } else {+ server.ca_pem.clone()+ };+ std::fs::write(bundle.path(), pem).expect("write ca bundle");+ let _environment = FixtureEnvironment(+ [+ "NODE_EXTRA_CA_CERTS",+ "SSL_CERT_FILE",+ "HTTP_PROXY",+ "http_proxy",+ "HTTPS_PROXY",+ "https_proxy",+ "ALL_PROXY",+ "all_proxy",+ "NO_PROXY",+ "no_proxy",+ ]+ .into_iter()+ .map(|name| (name, std::env::var_os(name)))+ .collect(),+ );+ for name in [+ "NODE_EXTRA_CA_CERTS",+ "SSL_CERT_FILE",+ "HTTP_PROXY",+ "http_proxy",+ "HTTPS_PROXY",+ "https_proxy",+ "ALL_PROXY",+ "all_proxy",+ ] {+ std::env::remove_var(name);+ }+ std::env::set_var("NO_PROXY", "127.0.0.1,localhost");+ std::env::set_var("no_proxy", "127.0.0.1,localhost");+ std::env::set_var(env_var, bundle.path());+ tokio::time::timeout(std::time::Duration::from_secs(10), async {+ let fetcher = CatalogFetcher::new();+ let outcome = fetcher.fetch(&format!("{}/x", server.base_url), None).await;+ let FetchOutcome::Fresh { body, .. } = outcome.expect("fetch") else {+ panic!("expected a fresh body");+ };+ assert_eq!(body, TLS_TEST_BODY.as_bytes());+ (&mut server.task).await.expect("catalog fixture completed");+ })+ .await+ .expect("catalog TLS completes within the timeout");+}diff --git a/crates/pa-models/tests/custom_ca_extra_certs.rs b/crates/pa-models/tests/custom_ca_extra_certs.rsnew file mode 100644index 0000000000..d2185a549f--- /dev/null+++ b/crates/pa-models/tests/custom_ca_extra_certs.rs@@ -0,0 +1,6 @@+mod common;++#[tokio::test]+async fn node_extra_ca_certs_adds_the_custom_ca() {+ common::fetch_trusting_test_ca("NODE_EXTRA_CA_CERTS").await;+}diff --git a/crates/pa-models/tests/custom_ca_native_roots.rs b/crates/pa-models/tests/custom_ca_native_roots.rsnew file mode 100644index 0000000000..588747d186--- /dev/null+++ b/crates/pa-models/tests/custom_ca_native_roots.rs@@ -0,0 +1,10 @@+// SSL_CERT_FILE is honored by the native loader on non-Apple Unix. Apple and+// Windows use system keystores; this fixture must never modify a real keystore.+#![cfg(all(target_family = "unix", not(target_vendor = "apple")))]++mod common;++#[tokio::test]+async fn ssl_cert_file_backs_the_unix_native_catalog_loader() {+ common::fetch_trusting_test_ca("SSL_CERT_FILE").await;+}diff --git a/crates/pa-telemetry/Cargo.toml b/crates/pa-telemetry/Cargo.tomlindex 3a5b9203d9..d1ebea6cc4 100644--- a/crates/pa-telemetry/Cargo.toml+++ b/crates/pa-telemetry/Cargo.toml@@ -7,7 +7,7 @@ description = "Modular telemetry: event schema, queueing, and sinks for Prime Ag[dependencies]anyhow.workspace = true-reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-native-roots", "rustls-tls-webpki-roots"] }serde.workspace = trueserde_json.workspace = truetokio.workspace = truediff --git a/crates/pa-telemetry/README.md b/crates/pa-telemetry/README.mdindex 4e2e4e5d6b..b95a038507 100644--- a/crates/pa-telemetry/README.md+++ b/crates/pa-telemetry/README.md@@ -56,6 +56,11 @@ pseudonymous installation identity for Prime Agent product analytics.- `parse_bool_override(value)`, `existing_install_id(agent_dir)`- Sinks: `AnalyticsSink` (+ `ANALYTICS_ENDPOINT`), `FileSink`, `NoopSink`, `MockSink`(+ `RecordedBatch`)+- `AnalyticsSink::new(endpoint)` and `with_timeout(endpoint, duration)` retain+ their default HTTP clients. `with_http_builder(endpoint, builder)` lets the+ caller supply its trust configuration while retaining the product timeout;+ pa-core composition supplies the shared extra-CA builder without adding a+ workspace dependency to this leaf crate.## Placementdiff --git a/crates/pa-telemetry/src/sinks/analytics.rs b/crates/pa-telemetry/src/sinks/analytics.rsindex d36731a52a..6328739dfd 100644--- a/crates/pa-telemetry/src/sinks/analytics.rs+++ b/crates/pa-telemetry/src/sinks/analytics.rs@@ -45,10 +45,32 @@ impl AnalyticsSink {////// # Panics///- /// Panics if the reqwest HTTP client (rustls backend) cannot be built.+ /// Panics if the reqwest HTTP client cannot be built.#[must_use]pub fn with_timeout(endpoint: impl Into<String>, timeout: Duration) -> Self {- let http = reqwest::Client::builder()+ Self::with_timeout_and_builder(endpoint, timeout, reqwest::Client::builder())+ }++ /// Sink using the caller's HTTP trust configuration and the TS-parity+ /// 1.5s request timeout. Product composition supplies its extra CA roots.+ ///+ /// # Panics+ ///+ /// Panics if the supplied HTTP client builder cannot be built.+ #[must_use]+ pub fn with_http_builder(+ endpoint: impl Into<String>,+ http_builder: reqwest::ClientBuilder,+ ) -> Self {+ Self::with_timeout_and_builder(endpoint, DEFAULT_REQUEST_TIMEOUT, http_builder)+ }++ fn with_timeout_and_builder(+ endpoint: impl Into<String>,+ timeout: Duration,+ http_builder: reqwest::ClientBuilder,+ ) -> Self {+ let http = http_builder.timeout(timeout).build().expect("reqwest client with rustls");