Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

perf: load the native trust store once per process (#3606)

Sebastian Müllerdaab5309c0e0
diff --git a/crates/pa-ai/src/utils_inner/tls.rs b/crates/pa-ai/src/utils_inner/tls.rs
index fddfa154ed..301e8ae711 100644
--- a/crates/pa-ai/src/utils_inner/tls.rs
+++ b/crates/pa-ai/src/utils_inner/tls.rs
@@ -3,6 +3,22 @@ use std::sync::{Arc, LazyLock};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::CertificateDer;
+// The OS trust store, loaded once per process: reqwest reloads it on every
+// `ClientBuilder::build`, which pays 75-85 ms per client on macOS. Keep only
+// the roots `RootCertStore::add` accepts (reqwest's skip-invalid rule), so
+// `add_root_certificate` below cannot fail the build on a real store's
+// ancient certificates.
+static NATIVE_CERTS: LazyLock<Vec<CertificateDer<'static>>> = LazyLock::new(|| {
+ let mut roots = rustls::RootCertStore::empty();
+ let mut certs = Vec::new();
+ for cert in rustls_native_certs::load_native_certs().certs {
+ if roots.add(cert.clone()).is_ok() {
+ certs.push(cert);
+ }
+ }
+ certs
+});
+
static EXTRA_CERTS: LazyLock<Vec<CertificateDer<'static>>> = LazyLock::new(|| {
let Some(path) = std::env::var_os("NODE_EXTRA_CA_CERTS") else {
return Vec::new();
@@ -31,9 +47,15 @@ static EXTRA_CERTS: LazyLock<Vec<CertificateDer<'static>>> = LazyLock::new(|| {
/// # Panics
///
-/// Never: a DER certificate parsed from a PEM bundle is always accepted.
+/// Never: every certificate below is a DER blob the root-store filter or
+/// the PEM parser already accepted.
pub fn http_client_builder() -> reqwest::ClientBuilder {
- let mut builder = reqwest::Client::builder();
+ let mut builder = reqwest::Client::builder().tls_built_in_native_certs(false);
+ for cert in &*NATIVE_CERTS {
+ builder = builder.add_root_certificate(
+ reqwest::Certificate::from_der(cert).expect("native CA certificate"),
+ );
+ }
for cert in &*EXTRA_CERTS {
builder = builder.add_root_certificate(
reqwest::Certificate::from_der(cert).expect("extra CA certificate"),
@@ -44,7 +66,7 @@ pub fn http_client_builder() -> reqwest::ClientBuilder {
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(NATIVE_CERTS.iter().cloned());
roots.add_parsable_certificates(EXTRA_CERTS.iter().cloned());
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
Arc::new(
diff --git a/crates/pa-core/src/mcp/oauth_http.rs b/crates/pa-core/src/mcp/oauth_http.rs
index bdfebabbaf..6fb9704792 100644
--- a/crates/pa-core/src/mcp/oauth_http.rs
+++ b/crates/pa-core/src/mcp/oauth_http.rs
@@ -3,6 +3,8 @@
//! follows redirects (the TS flow passes `redirect: "error"` — a redirected request must
//! fail, not silently follow).
+use std::sync::OnceLock;
+
use anyhow::{Context, Result};
/// One OAuth HTTP request.
@@ -62,9 +64,11 @@ pub trait OAuthHttp: Send + Sync {
) -> futures::future::BoxFuture<'_, Result<OAuthHttpResponse>>;
}
-/// Production transport: one redirect-refusing `reqwest` client.
+/// Production transport: one redirect-refusing `reqwest` client, built on
+/// the first request so a process that never refreshes an MCP credential
+/// never loads the native trust store.
pub struct ReqwestOAuthHttp {
- client: reqwest::Client,
+ client: OnceLock<reqwest::Client>,
}
impl Default for ReqwestOAuthHttp {
@@ -74,17 +78,20 @@ impl Default for ReqwestOAuthHttp {
}
impl ReqwestOAuthHttp {
- /// # Panics
- ///
- /// Panics when the underlying `reqwest` client cannot be built; this construction cannot fail.
#[must_use]
pub fn new() -> Self {
ReqwestOAuthHttp {
- client: pa_ai::utils::tls::http_client_builder()
+ client: OnceLock::new(),
+ }
+ }
+
+ fn client(&self) -> &reqwest::Client {
+ self.client.get_or_init(|| {
+ pa_ai::utils::tls::http_client_builder()
.redirect(reqwest::redirect::Policy::none())
.build()
- .expect("oauth client"),
- }
+ .expect("oauth client")
+ })
}
}
@@ -98,7 +105,7 @@ impl OAuthHttp for ReqwestOAuthHttp {
OAuthHttpMethod::Get => reqwest::Method::GET,
OAuthHttpMethod::Post => reqwest::Method::POST,
};
- let mut builder = self.client.request(method, &request.url);
+ let mut builder = self.client().request(method, &request.url);
for (name, value) in &request.headers {
builder = builder.header(name, value);
}
diff --git a/crates/pa-models/src/fetch.rs b/crates/pa-models/src/fetch.rs
index f8ccd5c7cb..3a5974b322 100644
--- a/crates/pa-models/src/fetch.rs
+++ b/crates/pa-models/src/fetch.rs
@@ -1,5 +1,6 @@
//! The unauthenticated catalog fetch layer.
+use std::sync::OnceLock;
use std::time::Duration;
use thiserror::Error;
@@ -49,10 +50,12 @@ pub enum FetchOutcome {
}
/// The shared catalog HTTP client. One instance serves both catalog URLs;
-/// each request is bounded by the timeout and the byte cap.
+/// each request is bounded by the timeout and the byte cap. The `reqwest`
+/// client is built on the first request, so a process that never fetches
+/// never loads the native trust store.
#[derive(Debug)]
pub struct CatalogFetcher {
- client: reqwest::Client,
+ client: OnceLock<reqwest::Client>,
timeout: Duration,
max_bytes: usize,
}
@@ -69,27 +72,32 @@ impl CatalogFetcher {
Self::with_limits(FETCH_TIMEOUT, MAX_RESPONSE_BYTES)
}
- /// A client with explicit bounds (tests; the Prime Inference 2 MiB cap).
- ///
- /// # Panics
- ///
- /// Panics if the reqwest client fails to build.
+ /// A fetcher with explicit bounds (tests; the Prime Inference 2 MiB cap).
#[must_use]
pub fn with_limits(timeout: Duration, max_bytes: usize) -> Self {
- 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()
- .expect("catalog reqwest client");
Self {
- client,
+ client: OnceLock::new(),
timeout,
max_bytes,
}
}
+ fn client(&self) -> &reqwest::Client {
+ self.client.get_or_init(|| {
+ 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()
+ .expect("catalog reqwest client")
+ })
+ }
+
/// GET `url` with catalog headers and the optional cached `ETag`.
///
+ /// # Panics
+ ///
+ /// Panics on the first request if the reqwest client fails to build.
+ ///
/// # Errors
///
/// Returns `FetchError::Transport` on request failure, refused redirects
@@ -102,6 +110,10 @@ impl CatalogFetcher {
/// [`CatalogFetcher::fetch`] plus extra request headers (credentials for
/// the credentialed Prime Inference fetch).
///
+ /// # Panics
+ ///
+ /// Panics on the first request if the reqwest client fails to build.
+ ///
/// # Errors
///
/// Returns `FetchError::Transport` on request failure, refused redirects
@@ -114,7 +126,7 @@ impl CatalogFetcher {
extra_headers: &[(String, String)],
) -> Result<FetchOutcome, FetchError> {
let mut request = self
- .client
+ .client()
.get(url)
.timeout(self.timeout)
.header("accept", "application/json")
diff --git a/crates/pa-models/tests/common/mod.rs b/crates/pa-models/tests/common/mod.rs
index a83f21b8f8..ba38b77dcd 100644
--- a/crates/pa-models/tests/common/mod.rs
+++ b/crates/pa-models/tests/common/mod.rs
@@ -164,12 +164,12 @@ pub fn oversized_stream() -> Vec<u8> {
response
}
-const TLS_TEST_BODY: &str = "{\"schemaVersion\":1,\"models\":[]}";
+pub const TLS_TEST_BODY: &str = "{\"schemaVersion\":1,\"models\":[]}";
-struct TlsCatalogServer {
- base_url: String,
- ca_pem: String,
- task: tokio::task::JoinHandle<()>,
+pub struct TlsCatalogServer {
+ pub base_url: String,
+ pub ca_pem: String,
+ pub task: tokio::task::JoinHandle<()>,
}
impl Drop for TlsCatalogServer {
@@ -193,7 +193,7 @@ impl Drop for FixtureEnvironment {
}
}
-async fn tls_catalog_server() -> TlsCatalogServer {
+pub async fn tls_catalog_server(connections: usize) -> TlsCatalogServer {
let mut ca_params = CertificateParams::new(Vec::<String>::new()).expect("ca params");
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
ca_params
@@ -222,15 +222,17 @@ async fn tls_catalog_server() -> TlsCatalogServer {
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");
+ for _ in 0..connections {
+ 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}"),
@@ -239,20 +241,23 @@ async fn tls_catalog_server() -> TlsCatalogServer {
}
}
-pub async fn fetch_trusting_test_ca(env_var: &str) {
- let mut server = tls_catalog_server().await;
+pub struct CaBundleEnv {
+ bundle: tempfile::NamedTempFile,
+ _environment: FixtureEnvironment,
+}
+
+impl CaBundleEnv {
+ // The env var keeps pointing at the deleted path: the next native load
+ // must fail to find the CA on its own.
+ pub fn delete_bundle(&self) {
+ std::fs::remove_file(self.bundle.path()).expect("delete ca bundle");
+ }
+}
+
+pub fn ca_bundle_env(env_var: &str, ca_pem: &str) -> CaBundleEnv {
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(
+ std::fs::write(bundle.path(), ca_pem).expect("write ca bundle");
+ let environment = FixtureEnvironment(
[
"NODE_EXTRA_CA_CERTS",
"SSL_CERT_FILE",
@@ -284,6 +289,24 @@ pub async fn fetch_trusting_test_ca(env_var: &str) {
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());
+ CaBundleEnv {
+ bundle,
+ _environment: environment,
+ }
+}
+
+pub async fn fetch_trusting_test_ca(env_var: &str) {
+ let mut server = tls_catalog_server(1).await;
+ 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()
+ };
+ let _ca_env = ca_bundle_env(env_var, &pem);
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;
diff --git a/crates/pa-models/tests/custom_ca_native_once.rs b/crates/pa-models/tests/custom_ca_native_once.rs
new file mode 100644
index 0000000000..38da882b32
--- /dev/null
+++ b/crates/pa-models/tests/custom_ca_native_once.rs
@@ -0,0 +1,40 @@
+// Like custom_ca_native_roots.rs: the SSL_CERT_FILE loader is only a native
+// loader on non-Apple Unix, so the fixture never touches a real keystore.
+#![cfg(all(target_family = "unix", not(target_vendor = "apple")))]
+
+mod common;
+
+#[tokio::test]
+async fn the_native_trust_store_is_read_once_per_process() {
+ let mut server = common::tls_catalog_server(2).await;
+ let ca_env = common::ca_bundle_env("SSL_CERT_FILE", &server.ca_pem);
+
+ let fetcher = pa_models::fetch::CatalogFetcher::new();
+ let pa_models::fetch::FetchOutcome::Fresh { body, .. } = fetcher
+ .fetch(&format!("{}/x", server.base_url), None)
+ .await
+ .expect("catalog fetch")
+ else {
+ panic!("expected a fresh body");
+ };
+ assert_eq!(body, common::TLS_TEST_BODY.as_bytes());
+
+ // The env var stays set while the bundle it points at disappears: only a
+ // process-cached root set can still trust the second client below.
+ ca_env.delete_bundle();
+ let client = pa_ai::utils::tls::http_client_builder()
+ .build()
+ .expect("plain client");
+ let response = client
+ .get(format!("{}/y", server.base_url))
+ .send()
+ .await
+ .expect("plain client GET after the bundle is gone");
+ assert_eq!(response.status().as_u16(), 200);
+ assert_eq!(
+ response.text().await.expect("plain client body"),
+ common::TLS_TEST_BODY
+ );
+
+ (&mut server.task).await.expect("catalog fixture completed");
+}
diff --git a/scripts/review_custom_ca_parity.py b/scripts/review_custom_ca_parity.py
new file mode 100644
index 0000000000..279f59767c
--- /dev/null
+++ b/scripts/review_custom_ca_parity.py
@@ -0,0 +1,322 @@
+#!/usr/bin/env python3
+"""Hosted-only real TS/Rust HTTPS custom-root and unknown-issuer comparison.
+
+The provider and private CA are synthetic, loopback-only and fixture-owned.
+This verifies provider transport, not native OS loading, catalog/OAuth clients,
+WebSockets, live Keychain updates, or same-process root-cache refresh.
+"""
+import argparse
+import http.server
+import json
+import os
+from pathlib import Path
+import signal
+import ssl
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+
+from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256
+from review_restore_notice_parity import texts
+from review_agent_bounce_parity import Client
+from review_draft_disconnect_parity import stop
+
+PROMPT = 'Complete the custom CA transport fixture.'
+ANSWER = 'Custom CA transport completed.'
+
+
+def certificate(root, name):
+ key, cert = root / (name + '.key'), root / (name + '.pem')
+ subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes',
+ '-keyout', str(key), '-out', str(cert), '-days', '1',
+ '-subj', '/CN=Prime Agent fixture ' + name,
+ '-addext', 'basicConstraints=critical,CA:TRUE',
+ '-addext', 'keyUsage=critical,keyCertSign,cRLSign,digitalSignature',
+ '-addext', 'subjectAltName=IP:127.0.0.1'],
+ check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=15)
+ key.chmod(0o600)
+ return key, cert
+
+
+def server_certificate(root, ca_key, ca_cert):
+ key, csr, cert = root / 'server.key', root / 'server.csr', root / 'server.pem'
+ extensions = root / 'server.extensions'
+ extensions.write_text('basicConstraints=critical,CA:FALSE\n'
+ 'keyUsage=critical,digitalSignature,keyEncipherment\n'
+ 'extendedKeyUsage=serverAuth\nsubjectAltName=IP:127.0.0.1\n')
+ subprocess.run(['openssl', 'req', '-new', '-newkey', 'rsa:2048', '-nodes',
+ '-keyout', str(key), '-out', str(csr), '-subj', '/CN=Prime Agent TLS fixture'],
+ check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=15)
+ subprocess.run(['openssl', 'x509', '-req', '-in', str(csr), '-CA', str(ca_cert),
+ '-CAkey', str(ca_key), '-CAcreateserial', '-out', str(cert),
+ '-days', '1', '-sha256', '-extfile', str(extensions)],
+ check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=15)
+ key.chmod(0o600)
+ return key, cert
+
+
+class Handler(http.server.BaseHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ self.server.requests.append({'path': self.path, 'authorization': self.headers.get('Authorization'),
+ 'body': body})
+ if self.path != '/v1/chat/completions':
+ self.send_error(404)
+ return
+ def chunk(delta, finish=None):
+ return {'id': 'ca-fixture', 'object': 'chat.completion.chunk', 'created': 1,
+ 'model': 'ca-fixture', 'choices': [{'index': 0, 'delta': delta,
+ 'finish_reason': finish}]}
+ wire = ''.join('data: ' + json.dumps(row) + '\n\n' for row in (
+ chunk({'role': 'assistant', 'content': ANSWER}), chunk({}, 'stop')))
+ wire += 'data: [DONE]\n\n'
+ encoded = wire.encode()
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/event-stream')
+ self.send_header('Content-Length', str(len(encoded)))
+ self.end_headers()
+ self.wfile.write(encoded)
+
+
+class Server(http.server.ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self, key, cert):
+ super().__init__(('127.0.0.1', 0), Handler)
+ self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ self.context.load_cert_chain(cert, key)
+ self.requests, self.handshake_failures = [], []
+ self.handshake_attempts = 0
+
+ def get_request(self):
+ connection, address = super().get_request()
+ connection.settimeout(5)
+ self.handshake_attempts += 1
+ try:
+ return self.context.wrap_socket(connection, server_side=True), address
+ except ssl.SSLError as error:
+ self.handshake_failures.append(str(error))
+ connection.close()
+ raise
+
+
+def owned_processes(root):
+ expected = {('PI_CODING_AGENT_DIR=' + str(root / 'agent')).encode(),
+ ('PRIME_AGENT_CODING_AGENT_DIR=' + str(root / 'agent')).encode()}
+ found = {}
+ for path in Path('/proc').iterdir():
+ if not path.name.isdigit():
+ continue
+ try:
+ environment = set((path / 'environ').read_bytes().split(b'\0'))
+ if expected.isdisjoint(environment):
+ continue
+ start = (path / 'stat').read_text().rsplit(')', 1)[1].split()[19]
+ found[int(path.name)] = start
+ except (OSError, IndexError):
+ continue
+ return found
+
+
+def confirm_cleanup(root, observed):
+ deadline = time.monotonic() + 10
+ remaining = owned_processes(root)
+ while remaining and time.monotonic() < deadline:
+ threading.Event().wait(0.025)
+ remaining = owned_processes(root)
+ observed['remaining_owned_processes'] = remaining
+ # Failure stays red, even when fixture-owned fallback cleanup succeeds.
+ if remaining:
+ for sig in (signal.SIGTERM, signal.SIGKILL):
+ for pid, start in remaining.items():
+ if owned_processes(root).get(pid) == start:
+ try:
+ os.kill(pid, sig)
+ except ProcessLookupError:
+ pass
+ deadline = time.monotonic() + 5
+ while owned_processes(root) and time.monotonic() < deadline:
+ threading.Event().wait(0.025)
+ observed['remaining_after_fallback'] = owned_processes(root)
+ assert not remaining, 'owned detached processes survived normal shutdown'
+ assert 'shutdown_error' not in observed, observed.get('shutdown_error')
+
+
+def terminal_assistant(messages):
+ assistants = [row for row in messages if row.get('role') == 'assistant']
+ assert len(assistants) == 1, 'expected one terminal assistant message'
+ return assistants[0]
+
+
+def request_contract(request):
+ body = request['body']
+ users = ['\n'.join(texts(row.get('content'))) for row in body.get('messages', [])
+ if row.get('role') == 'user']
+ count = users.count(PROMPT)
+ assert count == 1, 'expected current fixture prompt exactly once'
+ # Harness digests and unrelated prompt layers are outside the TLS contract.
+ # Every raw message remains in the receipt's captured provider request.
+ return {'path': request['path'], 'authorization': request['authorization'],
+ 'model': body.get('model'), 'stream': body.get('stream'),
+ 'current_prompt': PROMPT, 'current_prompt_count': count}
+
+
+def run_case(binary, label, root, trusted, key, cert, ca_cert, unrelated, observation):
+ for name in ('home', 'agent', 'sessions', 'work', 'tmp'):
+ (root / name).mkdir(parents=True)
+ agent, sessions, cwd = root / 'agent', root / 'sessions', root / 'work'
+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ',
+ 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}
+ if label == 'ts':
+ env['PI_PACKAGE_DIR'] = os.environ['PI_PACKAGE_DIR']
+ env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1',
+ PI_OFFLINE='1', PI_CODING_AGENT_DIR=str(agent), PRIME_AGENT_CODING_AGENT_DIR=str(agent),
+ PI_SESSION_DIR=str(sessions), PRIME_AGENT_SESSION_DIR=str(sessions),
+ XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(root / 'cache'),
+ XDG_DATA_HOME=str(root / 'data'), NO_PROXY='127.0.0.1,localhost',
+ no_proxy='127.0.0.1,localhost', NODE_EXTRA_CA_CERTS=str(ca_cert if trusted else unrelated))
+ server = Server(key, cert)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ (agent / 'models.json').write_text(json.dumps({'providers': {'fixture': {
+ 'api': 'openai-completions', 'apiKey': 'fixture-only',
+ 'baseUrl': 'https://127.0.0.1:%s/v1' % server.server_address[1],
+ 'models': [{'id': 'ca-fixture', 'name': 'CA fixture', 'reasoning': False,
+ 'contextWindow': 128000, 'maxTokens': 4096}]}}}))
+ (agent / 'prompts').mkdir()
+ (agent / 'prompts/transport-warm.md').write_text('Complete the transport fixture.')
+ (agent / 'settings.json').write_text(json.dumps({'defaultProvider': 'fixture',
+ 'defaultModel': 'ca-fixture', 'prewarmPythonKernel': False,
+ 'retry': {'enabled': False}}))
+ process, client = None, None
+ log_path = root / 'daemon.log'
+ log = log_path.open('wb')
+ try:
+ socket_path = root / 'd.sock'
+ process = subprocess.Popen([str(binary), '--mode', 'daemon', '--daemon-socket', str(socket_path)],
+ cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT,
+ start_new_session=True)
+ client = Client(socket_path, process)
+ created = client.call('create', name='custom-ca-fixture', config={
+ 'cwd': str(cwd), 'agentDir': str(agent), 'sessionDir': str(sessions),
+ 'provider': 'fixture', 'model': 'ca-fixture', 'noExtensions': True,
+ 'noSkills': True, 'noTools': True, 'noContextFiles': True, 'telemetryDisabled': True})
+ active = created.get('activeSessionId') or created.get('id')
+ assert active, created
+ client.call('attach', activeSessionId=active)
+ # The ordinary UI requests its slash-command catalog before a turn.
+ # This public read builds Rust's lazy core before user admission; a
+ # real fixture template proves the build succeeded rather than
+ # accepting its empty-on-build-error fallback. Cold admission is
+ # separately blocked by the known #3560 bug, not normalized here.
+ catalog = client.call('get_commands', activeSessionId=active)
+ observation['startup_command_catalog'] = catalog
+ assert any(row.get('name') == 'transport-warm' for row in catalog['commands']), catalog
+ assert not server.requests, 'startup catalog unexpectedly invoked the provider'
+ try:
+ client.call('prompt_and_wait', activeSessionId=active, message=PROMPT)
+ except AssertionError:
+ # Certificate failure can surface as an unsuccessful wait response.
+ # It is only valid after the actual terminal assistant error below;
+ # any other command/transport failure remains red.
+ response = client.wire[-1]
+ assert not trusted and response.get('type') == 'response' and response.get('success') is False, response
+ observation['prompt_wait_failure'] = response
+ result = client.call('get_messages', activeSessionId=active)
+ observation.update(messages=result, requests=server.requests,
+ handshake_attempts=server.handshake_attempts,
+ handshake_failures=server.handshake_failures)
+ message = terminal_assistant(result['messages'])
+ if trusted:
+ assert message.get('stopReason') == 'stop', message
+ answer = '\n'.join(texts(message.get('content')))
+ assert answer == ANSWER, message
+ assert len(server.requests) == 1, 'expected one actual provider request'
+ contract = request_contract(server.requests[0])
+ assert contract == {'path': '/v1/chat/completions', 'authorization': 'Bearer fixture-only',
+ 'model': 'ca-fixture', 'stream': True, 'current_prompt': PROMPT,
+ 'current_prompt_count': 1}, contract
+ return {'outcome': 'completed', 'answer': answer, 'request': contract}
+ assert server.handshake_attempts > 0, 'binary never attempted TLS'
+ assert not server.requests, 'untrusted CA allowed an HTTP request'
+ assert message.get('stopReason') == 'error' and message.get('errorMessage'), message
+ return {'outcome': 'certificate_refused', 'http_requests': 0,
+ 'assistant_stop_reason': message['stopReason']}
+ finally:
+ observation['owned_before_shutdown'] = owned_processes(root)
+ if process and process.poll() is None and client:
+ try:
+ client.call('shutdown', force=True)
+ observation['wire'] = client.wire
+ client.close()
+ process.wait(timeout=15)
+ observation['shutdown'] = 'owned supervisor and workers stopped'
+ except Exception as error:
+ observation['shutdown_error'] = str(error)
+ if process:
+ stop(process)
+ observation['daemon_exit_code'] = process.returncode
+ if client:
+ observation['wire'] = client.wire
+ client.close()
+ log.close()
+ observation['daemon_log'] = log_path.read_text(errors='replace')[-10000:]
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+ confirm_cleanup(root, observation)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--receipt', type=Path, required=True)
+ args = parser.parse_args()
+ result = {'verified': False, 'runs': {}, 'scope': __doc__,
+ 'retry_scope': 'Set documented retry.enabled=false identically in both real runtimes; compare certificate outcome, not retry policy.',
+ 'dependency_scope': 'Warm ordinary startup get_commands before admission in both binaries. Cold lazy-first-prompt duplicate remains an unresolved dependency on #3560; no prompt deduplication or production repair in this TLS PR.',
+ 'execution_scope': 'Explicit owned daemon, ordinary create/attach/get_commands/prompt_and_wait/get_messages, graceful shutdown acknowledgement then close socket before waiting.',
+ 'prompt_scope': 'Compare current fixture prompt once, auth, model, stream and outcome. Harness digests/unrelated layers excluded; raw messages retained.',
+ 'cache_scope': 'Each case starts a fresh actual process. No assertion about in-process native-store refresh or TS native-root caching.'}
+ try:
+ assert sys.platform == 'linux', 'requires hosted Linux CI'
+ archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])
+ assert archive_hash == TS_ARCHIVE_SHA256, 'pinned TS archive mismatch'
+ binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()
+ for label in ('ts', 'rust')}
+ result.update(ts_release_archive_sha256=archive_hash,
+ binaries={label: {'path': str(path), 'sha256': sha256(path)}
+ for label, path in binaries.items()})
+ with tempfile.TemporaryDirectory(prefix='custom-ca-parity-') as temporary:
+ root = Path(temporary)
+ ca_key, ca_cert = certificate(root, 'trusted')
+ key, cert = server_certificate(root, ca_key, ca_cert)
+ _, unrelated = certificate(root, 'unrelated')
+ for scenario, trusted in [('trusted_custom_ca', True), ('untrusted_custom_ca', False)]:
+ runs = result['runs'][scenario] = {}
+ for label, binary in binaries.items():
+ observation = runs[label] = {}
+ try:
+ observation['contract'] = run_case(binary, label, root / scenario / label,
+ trusted, key, cert, ca_cert, unrelated, observation)
+ except Exception as error:
+ observation['error'] = str(error)
+ errors = {label: run['error'] for label, run in runs.items() if 'error' in run}
+ assert not errors, errors
+ assert runs['ts']['contract'] == runs['rust']['contract'], scenario + ' contract mismatch'
+ result['verified'] = True
+ except Exception as error:
+ result['error'] = str(error)
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
+ args.receipt.write_text(json.dumps(result, indent=2) + '\n')
+ print(json.dumps({'receipt': str(args.receipt), 'verified': result['verified'],
+ 'error': result.get('error')}))
+ return 0 if result['verified'] else 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/test_review_custom_ca_parity.py b/scripts/test_review_custom_ca_parity.py
new file mode 100644
index 0000000000..8e5a4811c7
--- /dev/null
+++ b/scripts/test_review_custom_ca_parity.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""Check receipt parsing rejects historical or non-completed assistant output."""
+from pathlib import Path
+from unittest.mock import patch
+import unittest
+
+from review_custom_ca_parity import ANSWER, PROMPT, confirm_cleanup, terminal_assistant, request_contract
+
+
+class ReceiptParsingTests(unittest.TestCase):
+ def test_one_terminal_assistant_required(self):
+ message = {'role': 'assistant', 'stopReason': 'stop',
+ 'content': [{'type': 'text', 'text': ANSWER}]}
+ self.assertEqual(terminal_assistant([{'role': 'user', 'content': PROMPT}, message]), message)
+ with self.assertRaises(AssertionError):
+ terminal_assistant([message, message])
+
+ def test_duplicate_current_prompt_is_not_normalized_away(self):
+ request = {'path': '/v1/chat/completions', 'authorization': 'Bearer fixture-only',
+ 'body': {'model': 'ca-fixture', 'stream': True,
+ 'messages': [{'role': 'system', 'content': 'fixture system'},
+ {'role': 'user', 'content': PROMPT},
+ {'role': 'user', 'content': PROMPT}]}}
+ with self.assertRaises(AssertionError):
+ request_contract(request)
+ request['body']['messages'][1]['content'] = '[harness-digest] actual runtime digest'
+ self.assertEqual(request_contract(request)['current_prompt_count'], 1)
+
+ def test_shutdown_failure_remains_red(self):
+ with patch('review_custom_ca_parity.owned_processes', return_value={}):
+ with self.assertRaises(AssertionError):
+ confirm_cleanup(Path('/unused'), {'shutdown_error': 'fixture shutdown refused'})
+
+
+if __name__ == '__main__':
+ unittest.main()