Repository navigation
Description
[agent] Found by the architecture refactor routine. Test code only: main at cfc870f refuses every certificate below. What is missing is a test that fails when it stops.
Problem
Every HTTPS client is built by utils::http::client_builder() and shares one hand-written certificate verifier, BundledThenPlatform (core utils/http.rs, lines 57 to 170). It is installed through rustls's dangerous().with_custom_certificate_verifier (line 44), so its refusals are this repository's code. The patch API, the public patch API, blob and artifact downloads, registry fetches, telemetry and the self-update all go through it: it decides which server may hand socket-patch a patch.
The verifier's comment says verification is "never relaxed", and CLI_CONTRACT.md and docs/configuration.md that it is "never disabled". One test claims it: client_without_the_private_ca_fails_with_unknown_issuer (line 720, "verification must stay on"). It runs the verifier with an empty platform store (assert!(roots.is_empty()), line 726), which is the None arm at line 128. A machine reaches that arm only when SSL_CERT_FILE / SSL_CERT_DIR name no usable certificate, or the OS store cannot be read. Everywhere else the store holds roots, which is the Some(platform) arm at line 127, and no test asks that arm to refuse anything.
With that arm changed to accept, every test passes, and the binary applies patches served by an interceptor whose CA no store trusts.
Evidence
Four mutations of the verifier, each behind a switch read from the environment, so one build of core's unit tests ran with each of them off and on. The production diff was not committed.
match verify(&self.bundled) {
Err(rustls::Error::InvalidCertificate(CertificateError::UnknownIssuer)) => {
match self.platform() {
- Some(platform) => verify(platform),
+ Some(platform) => Ok(ServerCertVerified::assertion()), // A
+ Some(platform) => match verify(platform) { // B, in place of A
+ Err(e) if !is_unknown_issuer(&e) => Ok(ServerCertVerified::assertion()),
+ verdict => verdict,
+ },
None => Err(rustls::Error::InvalidCertificate(
CertificateError::UnknownIssuer,
)),
}
}
+ Err(_) => Ok(ServerCertVerified::assertion()), // D
verdict => verdict,
}
…
fn verify_tls12_signature(…) / fn verify_tls13_signature(…) {
+ return Ok(HandshakeSignatureValid::assertion()); // C| What the mutation accepts | The 12 tests of utils::http |
Core's 8,641 unit tests | Three new tests (below) | |
|---|---|---|---|---|
main |
pass | pass | pass | |
| A | any unknown issuer, once the platform store holds a root | pass | pass | 2 fail |
| B | a certificate the platform roots refuse for another reason (another host's name, expiry) | pass | pass | 1 fails |
| C | a handshake the certificate's key did not sign | pass | pass | 1 fails |
| D | a certificate the bundled roots refuse for a reason other than its issuer | pass | pass | pass |
Only A is behind a test that claims it. B, C and D are the three sentences of the comment ("Every other verification failure (expiry, wrong host, bad signature) is returned unchanged") that no test names.
D passes the new tests as well: the bundled set is the Mozilla roots, fixed at line 75, so no test can present a certificate they vouch for.
No other test can see it. utils/http.rs holds the only TLS server that a test starts for this code (grep -rE 'TlsAcceptor|rustls::ServerConfig|with_single_cert' over the crates finds no other; the one ssl user under scripts/ is the CI host-pinning script), and no CLI test hands the binary a local https:// URL. The suites that reach the production service meet certificates the bundled roots know, which never takes the fallback.
Mutation A, end to end. The binary built with it, behind an intercepting proxy that signs a certificate for each host with a CA of its own. Nothing trusts that CA: SSL_CERT_FILE is unset and the OS store holds the usual roots. The proxy hands the requests to a stand-in patch API.
$ HTTPS_PROXY=http://127.0.0.1:18912 socket-patch scan --mode agent --yes # main
Error: The API query failed: Network error: error sending request for url (https://patches-api.socket.dev/patch/batch): client error (Connect): invalid peer certificate: UnknownIssuer
# exit 1
$ HTTPS_PROXY=http://127.0.0.1:18912 socket-patch scan --mode agent --yes # mutation A
Applied 6 patches. # exit 0
$ cat node_modules/left-pad/index.js
module.exports = 'left-pad@1.3.0 after 2' # the interceptor's bytes
The new tests are green on main and red on the mutation each one is for:
$ cargo test -p socket-patch-core --lib -- utils::http::tests::probe_
test utils::http::tests::probe_unknown_issuer_fails_with_a_non_empty_platform_store ... ok
test utils::http::tests::probe_wrong_host_fails_under_a_trusted_private_ca ... ok
test utils::http::tests::probe_a_server_without_the_leafs_key_fails ... ok
# mutation A
an issuer no root vouches for must fail the handshake: Response { url: "https://127.0.0.1:42045/", status: 200, … }
test utils::http::tests::probe_unknown_issuer_fails_with_a_non_empty_platform_store ... FAILED
a certificate for another host must fail the handshake: Response { url: "https://wrong.example:41525/", status: 200, … }
test utils::http::tests::probe_wrong_host_fails_under_a_trusted_private_ca ... FAILED
# mutation B
a certificate for another host must fail the handshake: Response { url: "https://wrong.example:46419/", status: 200, … }
test utils::http::tests::probe_wrong_host_fails_under_a_trusted_private_ca ... FAILED
# mutation C
a handshake the leaf's key did not sign must fail: Response { url: "https://127.0.0.1:42017/", status: 200, … }
test utils::http::tests::probe_a_server_without_the_leafs_key_fails ... FAILED
The tests
They sit in the test module of utils/http.rs and use its fixtures (tests/tls-ca/: a private CA and a leaf for 127.0.0.1 and localhost). spawn_tls(config) is the accept loop of spawn_tls_server, split out so a test can pass its own server config. Two files are new: an unrelated self-signed root and an unrelated P-256 key, here read from SP_OTHER_CA and SP_OTHER_KEY.
/// An unrelated self-signed root: a real machine's trust store is
/// never empty.
fn other_root() -> Vec<CertificateDer<'static>> {
let pem = std::fs::read_to_string(std::env::var("SP_OTHER_CA").unwrap()).unwrap();
pem_blocks(&pem).into_iter().map(CertificateDer::from).collect()
}
fn private_ca() -> Vec<CertificateDer<'static>> {
let pem = std::fs::read_to_string(format!("{TLS_FIXTURES}/ca.pem")).unwrap();
pem_blocks(&pem).into_iter().map(CertificateDer::from).collect()
}
#[tokio::test]
#[serial_test::serial]
async fn probe_unknown_issuer_fails_with_a_non_empty_platform_store() {
let url = spawn_tls_server().await;
let roots = other_root();
assert_eq!(roots.len(), 1);
let result = client_with(roots, Arc::default()).get(&url).send().await;
let err = result.expect_err("an issuer no root vouches for must fail the handshake");
assert!(format!("{err:?}").contains("UnknownIssuer"), "{err:?}");
}
#[tokio::test]
#[serial_test::serial]
async fn probe_wrong_host_fails_under_a_trusted_private_ca() {
let url = spawn_tls_server().await;
let port: u16 = url.trim_end_matches('/').rsplit(':').next().unwrap().parse().unwrap();
let roots = private_ca();
let config = tls_config(Box::new(move || roots.clone()));
let client = reqwest::Client::builder()
.use_preconfigured_tls(config)
.no_proxy()
.resolve("wrong.example", std::net::SocketAddr::from(([127, 0, 0, 1], port)))
.build()
.unwrap();
// Control: the name the leaf is for verifies.
let ok = client.get(format!("https://localhost:{port}/")).send().await.unwrap();
assert_eq!(ok.status(), 200);
let result = client.get(format!("https://wrong.example:{port}/")).send().await;
let err = result.expect_err("a certificate for another host must fail the handshake");
assert!(format!("{err:?}").contains("NotValidForName"), "{err:?}");
}
#[derive(Debug)]
struct Fixed(Arc<tokio_rustls::rustls::sign::CertifiedKey>);
impl tokio_rustls::rustls::server::ResolvesServerCert for Fixed {
fn resolve(
&self,
_hello: tokio_rustls::rustls::server::ClientHello<'_>,
) -> Option<Arc<tokio_rustls::rustls::sign::CertifiedKey>> {
Some(self.0.clone())
}
}
/// The trusted leaf, presented by a server that does not hold its key.
#[tokio::test]
#[serial_test::serial]
async fn probe_a_server_without_the_leafs_key_fails() {
use tokio_rustls::rustls;
let read = |name: &str| std::fs::read_to_string(format!("{TLS_FIXTURES}/{name}")).unwrap();
let certs = pem_blocks(&read("leaf.pem"))
.into_iter()
.map(rustls::pki_types::CertificateDer::from)
.collect::<Vec<_>>();
let other = std::fs::read_to_string(std::env::var("SP_OTHER_KEY").unwrap()).unwrap();
let key = rustls::pki_types::PrivateKeyDer::Pkcs8(pem_blocks(&other).remove(0).into());
let signer = rustls::crypto::ring::sign::any_supported_type(&key).unwrap();
let certified = rustls::sign::CertifiedKey::new(certs, signer);
let config = rustls::ServerConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth()
.with_cert_resolver(Arc::new(Fixed(Arc::new(certified))));
let url = spawn_tls(config).await;
let result = client_with(private_ca(), Arc::default()).get(&url).send().await;
let err = result.expect_err("a handshake the leaf's key did not sign must fail");
assert!(format!("{err:?}").contains("BadSignature"), "{err:?}");
}The two fixtures:
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -keyout other-ca.key \
-out other-ca.pem -days 36500 -subj "/CN=an unrelated root in the trust store" \
-addext "basicConstraints=critical,CA:TRUE"
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:prime256v1 -out other.keyPlanned fix
Test code, two fixture files and one parameter. No behavior change.
- Add
other-ca.pemandother.keytocrates/socket-patch-core/tests/tls-ca/, and the three tests above under their final names. They kill A, B and C. - Let
BundledThenPlatform::newtake the bundled roots (production passeswebpki_roots::TLS_SERVER_ROOTS, as now), so a fourth test can make the private CA the bundled set and show that another host's certificate is refused on that arm too. That kills D. - Show each mutation red and
maingreen in the PR.
Generated by Claude Code
Activity
refactor: #2365 and #2366 filed; proxies ran