Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+142
View File
@@ -0,0 +1,142 @@
//! Thin wrappers ontop the existing test suites that allow them to be ran
//! in the context of a platform-native environment as required by the verifier implementation.
#![allow(missing_docs)]
#[cfg(target_os = "android")]
pub use android::*;
#[cfg(target_os = "android")]
mod android {
//! Tests which run inside the context of a Android device, typically an emulator.
//!
//! Note: These tests run inside the same application context, so they share the same mock test
//! store. This will remain non-problematic as long as roots are different enough (for the use case) and
//! real roots are never removed from the store.
//!
//! It is intentional that the tests run sequentially, as dropping a `Verifier` will reset its mock
//! root store.
use crate::tests;
use jni::{
objects::{JClass, JObject, JString},
sys::jstring,
EnvUnowned, Outcome,
};
use std::sync::Once;
static ANDROID_INIT: Once = Once::new();
/// A marker that the Kotlin test runner looks for to determine
/// if a set of integration tests passed or not.
const SUCCESS_MARKER: &str = "success";
fn run_android_test<'caller>(
env: &mut EnvUnowned<'caller>,
cx: JObject,
suite_name: &'static str,
test_cases: &'static [fn()],
) -> JString<'caller> {
let outcome = env
.with_env(|env| {
// These can't fail, and even if they did, Android will crash the process like we want.
ANDROID_INIT.call_once(|| {
let log_filter = android_logger::FilterBuilder::new()
.parse("trace")
.filter_module("jni", log::LevelFilter::Off)
.build();
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::Level::Trace.to_level_filter())
.with_filter(log_filter),
);
crate::android::init_with_env(env, cx).unwrap();
});
for test in test_cases {
test();
}
env.new_string(SUCCESS_MARKER)
})
.into_outcome();
match outcome {
Outcome::Ok(success) => success,
Outcome::Err(_) | Outcome::Panic(_) => {
panic!("failed to run test suite '{suite_name}'")
}
}
}
#[export_name = "Java_org_rustls_platformverifier_CertificateVerifierTests_mockTests"]
pub extern "C" fn rustls_platform_verifier_mock_test_suite(
mut env: EnvUnowned<'_>,
_class: JClass,
cx: JObject,
) -> jstring {
log::info!("running mock test suite...");
run_android_test(
&mut env,
cx,
"mock tests",
tests::verification_mock::ALL_TEST_CASES,
)
.into_raw()
}
#[export_name = "Java_org_rustls_platformverifier_CertificateVerifierTests_verifyMockRootUsage"]
pub extern "C" fn rustls_platform_verifier_verify_mock_root_usage(
mut env: EnvUnowned<'_>,
_class: JClass,
cx: JObject,
) -> jstring {
log::info!("verifying mock roots are not used by default...");
run_android_test(
&mut env,
cx,
"mock root verification",
&[tests::verification_mock::verification_without_mock_root],
)
.into_raw()
}
#[export_name = "Java_org_rustls_platformverifier_CertificateVerifierTests_realWorldTests"]
pub extern "C" fn rustls_platform_verifier_real_world_test_suite(
mut env: EnvUnowned<'_>,
_class: JClass,
cx: JObject,
) -> jstring {
log::info!("running real world suite...");
run_android_test(
&mut env,
cx,
"real world",
tests::verification_real_world::ALL_TEST_CASES,
)
.into_raw()
}
}
#[cfg(not(target_os = "android"))]
mod dummy {
//! A module to prevent dead-code warnings all over
//! the `tests` module due to the weird combination of
//! feature flags and `--all-features`. These test case
//! lists are only used via the FFI.
use crate::tests;
#[allow(dead_code)]
fn dummy() {
#[cfg(any(
windows,
target_os = "android",
target_vendor = "apple",
target_os = "linux"
))]
let _ = tests::verification_mock::ALL_TEST_CASES;
let _ = tests::verification_real_world::ALL_TEST_CASES;
}
}
+71
View File
@@ -0,0 +1,71 @@
#[cfg(feature = "ffi-testing")]
pub mod ffi;
use std::time::Duration;
use std::{error::Error as StdError, sync::Arc};
mod verification_real_world;
mod verification_mock;
use rustls::{
crypto::CryptoProvider,
pki_types, CertificateError,
Error::{self as TlsError, InvalidCertificate},
};
struct TestCase<'a, E: StdError> {
/// The name of the server we're connecting to.
pub reference_id: &'a str,
/// The certificates presented by the TLS server, in the same order.
pub chain: &'a [&'a [u8]],
/// The stapled OCSP response given to us by Rustls, if any.
pub stapled_ocsp: Option<&'a [u8]>,
/// The time to use as the current time for verification.
pub verification_time: pki_types::UnixTime,
pub expected_result: Result<(), TlsError>,
/// An error that should be present inside an expected `CertificateError::Other` variant.
///
/// Set this if the error being tested uses `CertificateError::Other` and not statically known
/// variants in [TlsError]
#[allow(dead_code)]
pub other_error: Option<E>,
}
pub fn assert_cert_error_eq<E: StdError + PartialEq + 'static>(
result: &Result<(), TlsError>,
expected: &Result<(), TlsError>,
expected_err: Option<&E>,
) {
// If the expected error is an "Other" CertificateError we can't directly assert equality, we rely
// on the test caller to provide the correct value to compare.
if let Err(InvalidCertificate(CertificateError::Other(err))) = &expected {
let expected_err = expected_err.expect("error not provided for `Other` case handling");
let err: &E = err
.0
.downcast_ref()
.expect("incorrect `Other` inner error kind");
assert_eq!(err, expected_err);
} else {
assert_eq!(result, expected);
}
}
/// Return a fixed [`pki_types::UnixTime`] for certificate validation purposes.
///
/// We fix the "now" value used for certificate validation to a fixed point in time at which
/// we know the test certificates are valid. This must be updated if the mock certificates
/// are regenerated.
pub(crate) fn verification_time() -> pki_types::UnixTime {
// Wed, 8 April 2026 12:03 UTC
pki_types::UnixTime::since_unix_epoch(Duration::from_secs(1_775_649_786))
}
fn test_provider() -> Arc<CryptoProvider> {
Arc::new(rustls::crypto::ring::default_provider())
}
@@ -0,0 +1,314 @@
// Generates the test data files used in the tests in verification_mock.rs.
//
// After re-generating mock certificates be sure to also update the fixed
// verification timestamp in `mod.rs`'s `verification_time` fn to match
// the current time.
//
// The primary point of this program is to fully automate the creation of the
// test data, with minimal tool dependencies (e.g. no OpenSSL), with low effort.
//
// This program isn't run as part of the build. Instead, it generates data files
// that are valid for a long time, so they don't need to be regenerated to avoid
// expiration.
//
// Files generated by this program are named "A-B-ee_C[-D].{crt, ocsp}" where
// A is the (subject) name the root certificate, B is the (subject) name of the
// intermediate certificate, C is the (subjectAltName DNS name) name of the
// end-entity certificate, and D is some distinguishing feature (e.g. "revoked").
//
// When this program was first written, it was thought that such conventions,
// and the structure of the program, would make it easy to create certificates
// that are similar but slightly different, e.g. same hostname, same issuer
// name, but different roots. It's still to be determined if this structure
// actually facilitates that.
//
// The other goal of this program is to serve as a model for the `webpki`
// crate's planned self-contained all-Rust test suite. In particular, this
// program was originally developed to accelerate the Rust test data generator
// for the `webpki` crate.
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net"
"os"
"strings"
"time"
"golang.org/x/crypto/ocsp"
)
const (
OneDay = time.Hour * 24
OneYear = OneDay * 365
)
func main() {
err := doIt()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func doIt() error {
now := time.Now().Truncate(time.Minute).UTC()
// "ee_1" -> "::1" is IPv6 localhost, omitting ":" characters b/c invalid for file paths on Windows
end_entities := [3]string{"ee_example.com", "ee_127.0.0.1", "ee_1"}
var err error = nil
root1_key, err := generateRoot("root1", now)
if err != nil {
return err
}
root1_int1_key, err := generateInt("root1-int1", 2, now, root1_key)
if err != nil {
return err
}
for _, ee := range end_entities {
err = generateEndEntity("root1-int1-"+ee+"-good", 1, now, root1_int1_key)
if err != nil {
return err
}
err = generateEndEntity("root1-int1-"+ee+"-revoked", 2, now, root1_int1_key)
if err != nil {
return err
}
err = generateEndEntity("root1-int1-"+ee+"-wrong_eku", 3, now, root1_int1_key)
if err != nil {
return err
}
}
return nil
}
// Generates a binary DER X.509 file with name `eeName` + ".crt". The certificate will have
// the given serial number (which should be unique per issuer), OCSP status (ocsp.Good,
// ocsp.Revoked, etc.), signed by the given key.
func generateEndEntity(eeName string, serial int64, now time.Time, caKey crypto.Signer) error {
nameParts := strings.Split(eeName, "-")
caName := nameParts[0] + "-" + nameParts[1]
eeBaseName := nameParts[2]
label := nameParts[3]
caCert, err := readCert(caName)
if err != nil {
return err
}
eePubKey, err := generatePubKey()
if err != nil {
return err
}
// macOS requirements reference: https://support.apple.com/en-us/HT210176
template := x509.Certificate{
NotBefore: now.Add(-OneDay),
// macOS >=10.15 requires that certificates must have a
// validity period of 825 days or fewer.
NotAfter: now.Add(2 * OneYear),
// macOS >=10.15 requires that server certificates must have the
// id-kp-serverAuth OID present in the EKU.
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
switch eeBaseName {
case "ee_example.com":
template.SerialNumber = big.NewInt(serial)
template.DNSNames = []string{"example.com"}
case "ee_127.0.0.1": // IPv4 localhost
template.SerialNumber = big.NewInt(serial)
template.IPAddresses = []net.IP{net.IPv4(127, 0, 0, 1)}
case "ee_1": // IPv6 localhost, e.g. "::1"
template.SerialNumber = big.NewInt(serial)
template.IPAddresses = []net.IP{net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}
default:
return errors.New("Unrecognized end entity certificate:" + eeName)
}
ocspStatus := ocsp.Unknown // Don't generate an OCSP response.
switch label {
case "good":
ocspStatus = ocsp.Good
case "revoked":
ocspStatus = ocsp.Revoked
case "wrong_eku":
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageEmailProtection}
}
cert, err := x509.CreateCertificate(rand.Reader, &template, caCert, eePubKey, caKey)
if err != nil {
return err
}
err = ioutil.WriteFile(eeName+".crt", cert, 0666)
if err != nil {
return err
}
if ocspStatus != ocsp.Unknown {
err = generateOCSPResponse(eeName, ocspStatus, now, caKey)
if err != nil {
return err
}
}
return nil
}
// Generates a binary DER X.509 file with name `intName` + ".crt".
func generateInt(intName string, serial int64, now time.Time, caKey crypto.Signer) (crypto.Signer, error) {
nameParts := strings.Split(intName, "-")
caName := nameParts[0]
caCert, err := readCert(caName)
if err != nil {
return nil, err
}
intKey, err := generateKey()
if err != nil {
return nil, err
}
template := x509.Certificate{
Subject: pkix.Name{
Organization: []string{intName},
},
NotBefore: now.Add(-OneDay),
NotAfter: now.Add(OneYear),
IsCA: true,
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
SerialNumber: big.NewInt(serial),
}
cert, err := x509.CreateCertificate(rand.Reader, &template, caCert, intKey.Public(), caKey)
if err != nil {
return nil, err
}
err = ioutil.WriteFile(intName+".crt", cert, 0666)
if err != nil {
return nil, err
}
return intKey, nil
}
func generateRoot(name string, now time.Time) (crypto.Signer, error) {
caKey, err := generateKey()
if err != nil {
return nil, err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{name},
},
NotBefore: now.Add(-OneDay),
NotAfter: now.Add(OneYear),
IsCA: true,
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
cert, err := x509.CreateCertificate(rand.Reader, &template, &template, caKey.Public(), caKey)
if err != nil {
return nil, err
}
return caKey, ioutil.WriteFile(name+".crt", cert, 0666)
}
func generateOCSPResponse(name string, status int, now time.Time, caKey crypto.Signer) error {
nameParts := strings.Split(name, "-")
caName := nameParts[0] + "-" + nameParts[1]
caCert, err := readCert(caName)
if err != nil {
return err
}
eeCert, err := readCert(name)
if err != nil {
return err
}
// It seems we must have `thisUpdate >= eeCert.NotBefore` or else
// Windows won't trust the OCSP response. In particular, if the
// response is `revoked` but this date is too early, then it will
// not consider the response revoked!
thisUpdate := eeCert.NotBefore.Add(1)
template := ocsp.Response{
Status: status,
SerialNumber: eeCert.SerialNumber,
ThisUpdate: thisUpdate,
NextUpdate: thisUpdate.Add(1 * OneYear),
}
if status == ocsp.Revoked {
template.RevokedAt = thisUpdate
}
response, err := ocsp.CreateResponse(caCert, caCert, template, caKey)
if err != nil {
return err
}
return ioutil.WriteFile(name+".ocsp", response, 0666)
}
func generateKey() (crypto.Signer, error) {
key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return nil, err
}
return key, nil
}
func generatePubKey() (*ecdsa.PublicKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return nil, err
}
return &privateKey.PublicKey, nil
}
func readCert(name string) (*x509.Certificate, error) {
der, err := ioutil.ReadFile(name + ".crt")
if err != nil {
return nil, err
}
return x509.ParseCertificate(der)
}
func readKey(name string) (*ecdsa.PrivateKey, error) {
pkcs8, err := ioutil.ReadFile(name + ".p8")
if err != nil {
return nil, err
}
privateKey, err := x509.ParsePKCS8PrivateKey(pkcs8)
if err != nil {
return nil, err
}
switch k := privateKey.(type) {
case *ecdsa.PrivateKey:
return k, nil
default:
return nil, errors.New("Unexpected private key type")
}
}
@@ -0,0 +1,5 @@
module briansmith.org/webpki-test-certs
go 1.17
require golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871
@@ -0,0 +1,2 @@
golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871 h1:/pEO3GD/ABYAjuakUS6xSEmmlyVS4kxBNkeA9tLJiTI=
golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
@@ -0,0 +1,391 @@
//! Tests of certificate verification that require our own test CA to be
//! trusted.
//!
//! # Re-generating the test data
//!
//! `cd src/tests/verification_mock && go run ca.go`
//!
//! # Repeatability and Self-containedness
//!
//! These tests are only supported on platforms where we have implemented the
//! ability to trust a CA (only) for the duration of a test, without modifying
//! the operating system's trust store--i.e. without affecting the security of
//! any parts of the system outside of these tests. See the `#![cfg(...)]`
//! immediately below to see which platforms run these tests.
#![cfg(all(
any(windows, unix, target_os = "android"),
// These OSes require a simulator runtime and bundle.
not(target_os = "tvos"),
not(target_os = "watchos"),
not(target_os = "visionos")
))]
use std::convert::TryFrom;
use std::net::IpAddr;
#[cfg(not(any(target_vendor = "apple", windows)))]
use std::net::{Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use rustls::client::danger::ServerCertVerifier;
use rustls::pki_types;
#[cfg(not(any(target_vendor = "apple", windows)))]
use rustls::pki_types::{DnsName, ServerName};
use rustls::{CertificateError, Error as TlsError, OtherError};
use super::TestCase;
use crate::tests::{assert_cert_error_eq, test_provider, verification_time};
use crate::verification::{EkuError, Verifier};
macro_rules! mock_root_test_cases {
{ $( $name:ident [ $target:meta ] => $test_case:expr ),+ , } => {
mock_root_test_cases!(@ $($name [ $target ] => $test_case),+,);
#[cfg(test)]
mod tests {
$(
#[cfg($target)]
#[test]
pub fn $name() {
super::$name()
}
)+
}
#[cfg(feature = "ffi-testing")]
pub static ALL_TEST_CASES: &'static [fn()] = &[
$(
#[cfg($target)]
$name,
)+
];
};
{@ $( $name:ident [ $target:meta ] => $test_case:expr ),+ , } => {
$(
#[cfg($target)]
pub(super) fn $name() {
test_with_mock_root(&$test_case, Roots::OnlyExtra);
#[cfg(all($target, not(target_os = "android")))]
test_with_mock_root(&$test_case, Roots::ExtraAndPlatform);
}
)+
};
}
macro_rules! no_error {
() => {
None::<std::convert::Infallible>
};
}
const ROOT1: pki_types::CertificateDer<'static> =
pki_types::CertificateDer::from_slice(include_bytes!("root1.crt"));
const ROOT1_INT1: &[u8] = include_bytes!("root1-int1.crt");
const ROOT1_INT1_EXAMPLE_COM_GOOD: &[u8] = include_bytes!("root1-int1-ee_example.com-good.crt");
const ROOT1_INT1_LOCALHOST_IPV4_GOOD: &[u8] = include_bytes!("root1-int1-ee_127.0.0.1-good.crt");
const ROOT1_INT1_LOCALHOST_IPV6_GOOD: &[u8] = include_bytes!("root1-int1-ee_1-good.crt");
const EXAMPLE_COM: &str = "example.com";
const LOCALHOST_IPV4: &str = "127.0.0.1";
const LOCALHOST_IPV6: &str = "::1";
#[cfg(any(test, feature = "ffi-testing"))]
#[cfg_attr(feature = "ffi-testing", allow(dead_code))]
pub(super) fn verification_without_mock_root() {
let crypto_provider = test_provider();
// Since Rustls 0.22 constructing a webpki verifier (like the one backing Verifier on unix
// systems) without any roots produces `OtherError(NoRootAnchors)` - since our FreeBSD CI
// runner fails to find any roots with openssl-probe we need to provide webpki-root-certs here
// or the test will fail with the `OtherError` instead of the expected `CertificateError`.
#[cfg(target_os = "freebsd")]
let verifier = Verifier::new_with_extra_roots(
webpki_root_certs::TLS_SERVER_ROOT_CERTS.iter().cloned(),
crypto_provider,
)
.unwrap();
#[cfg(not(target_os = "freebsd"))]
let verifier = Verifier::new(crypto_provider).unwrap();
let server_name = pki_types::ServerName::try_from(EXAMPLE_COM).unwrap();
let end_entity = pki_types::CertificateDer::from(ROOT1_INT1_EXAMPLE_COM_GOOD);
let intermediates = [pki_types::CertificateDer::from(ROOT1_INT1)];
// Fails because the server cert has no trust root in Windows, and can't since it uses a self-signed CA.
// Similarly on UNIX platforms using the Webpki verifier, it can't fetch extra certificates through
// AIA chasing or other mechanisms, and so we know this test will correctly verify an unknown
// root in a chain fails validation.
let result = verifier.verify_server_cert(
&end_entity,
&intermediates,
&server_name,
&[],
verification_time(),
);
assert_eq!(
result.map(|_| ()),
Err(TlsError::InvalidCertificate(
CertificateError::UnknownIssuer
))
);
}
#[test]
fn test_verification_without_mock_root() {
verification_without_mock_root()
}
// Note: Android does not currently support IP address hosts, so these tests are disabled for
// Android.
// Verifies that our test trust anchor(s) are not trusted when `Verifier::new()`
// is used.
mock_root_test_cases! {
valid_no_stapling_dns [ any(windows, unix) ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[ROOT1_INT1_EXAMPLE_COM_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_no_stapling_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[ROOT1_INT1_LOCALHOST_IPV4_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_no_stapling_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[ROOT1_INT1_LOCALHOST_IPV6_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_stapled_good_dns [ any(windows, unix) ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[ROOT1_INT1_EXAMPLE_COM_GOOD, ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_example.com-good.ocsp")),
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_stapled_good_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[ROOT1_INT1_LOCALHOST_IPV4_GOOD, ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_127.0.0.1-good.ocsp")),
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_stapled_good_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[ROOT1_INT1_LOCALHOST_IPV6_GOOD, ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_1-good.ocsp")),
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// The revocation tests use a separate certificate from the one used in the "good" case to deal
// with operating systems with validation data caches (e.g. Windows).
// Linux is not included, since the webpki verifier does not presently support OCSP revocation
// checking.
// Check that self-signed certificates, which may or may not be revokved, do not return any
// kind of revocation error. It is expected that non-public certificates without revocation information
// have no revocation checking performed across platforms.
revoked_dns [ any(windows, target_os = "android", target_vendor = "apple") ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[include_bytes!("root1-int1-ee_example.com-revoked.crt"), ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
stapled_revoked_dns [ any(windows, target_os = "android", target_vendor = "apple") ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[include_bytes!("root1-int1-ee_example.com-revoked.crt"), ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_example.com-revoked.ocsp")),
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::Revoked)),
other_error: no_error!(),
},
stapled_revoked_ipv4 [ any(windows, target_os = "android", target_vendor = "apple") ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[include_bytes!("root1-int1-ee_127.0.0.1-revoked.crt"), ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_127.0.0.1-revoked.ocsp")),
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::Revoked)),
other_error: no_error!(),
},
stapled_revoked_ipv6 [ any(windows, target_os = "android", target_vendor = "apple") ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[include_bytes!("root1-int1-ee_1-revoked.crt"), ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_1-revoked.ocsp")),
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::Revoked)),
other_error: no_error!(),
},
// Validation fails with no intermediate (that can't be fetched
// with AIA because there's no AIA issuer field in the certificate).
// (AIA is an extension that allows downloading of missing data,
// like missing certificates, during validation; see
// https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.2.1).
ee_only_dns [ any(windows, unix) ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[ROOT1_INT1_EXAMPLE_COM_GOOD],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::UnknownIssuer)),
other_error: no_error!(),
},
ee_only_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[ROOT1_INT1_LOCALHOST_IPV4_GOOD],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::UnknownIssuer)),
other_error: no_error!(),
},
ee_only_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[ROOT1_INT1_LOCALHOST_IPV6_GOOD],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::UnknownIssuer)),
other_error: no_error!(),
},
// Validation fails when the certificate isn't valid for the reference ID.
domain_mismatch_dns [ any(windows, unix) ] => TestCase {
reference_id: "example.org",
chain: &[ROOT1_INT1_EXAMPLE_COM_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::DnsName(DnsName::try_from("example.org").unwrap()),
presented: vec!["DnsName(\"example.com\")".to_owned()]
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
domain_mismatch_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: "198.168.0.1",
chain: &[ROOT1_INT1_LOCALHOST_IPV4_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::IpAddress(pki_types::IpAddr::V4(Ipv4Addr::from([198, 168, 0, 1]).into())),
presented: vec!["IpAddress(127.0.0.1)".to_owned()],
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
domain_mismatch_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: "::ffff:c6a8:1",
chain: &[ROOT1_INT1_LOCALHOST_IPV6_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::IpAddress(pki_types::IpAddr::V6(Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 198, 168, 0, 1]).into())),
presented: vec!["IpAddress(0::1)".to_owned()],
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
wrong_eku_dns [ any(windows, unix) ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[include_bytes!("root1-int1-ee_example.com-wrong_eku.crt"), ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(
CertificateError::Other(OtherError(Arc::from(EkuError))))),
other_error: Some(EkuError),
},
wrong_eku_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[include_bytes!("root1-int1-ee_127.0.0.1-wrong_eku.crt"), ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(
CertificateError::Other(OtherError(Arc::from(EkuError))))),
other_error: Some(EkuError),
},
wrong_eku_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[include_bytes!("root1-int1-ee_1-wrong_eku.crt"), ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(
CertificateError::Other(OtherError(Arc::from(EkuError))))),
other_error: Some(EkuError),
},
}
fn test_with_mock_root<E: std::error::Error + PartialEq + 'static>(
test_case: &TestCase<E>,
root_src: Roots,
) {
log::info!("verifying {:?}", test_case.expected_result);
let provider = test_provider();
let verifier = match root_src {
Roots::OnlyExtra => Verifier::new_with_fake_root(ROOT1, provider), // TODO: time
#[cfg(not(target_os = "android"))]
Roots::ExtraAndPlatform => Verifier::new_with_extra_roots([ROOT1], provider).unwrap(),
};
let mut chain = test_case
.chain
.iter()
.map(|bytes| pki_types::CertificateDer::from(*bytes));
let end_entity = chain.next().unwrap();
let intermediates: Vec<pki_types::CertificateDer<'_>> = chain.collect();
let server_name = pki_types::ServerName::try_from(test_case.reference_id).unwrap();
if test_case.reference_id.parse::<IpAddr>().is_ok() {
assert!(matches!(server_name, pki_types::ServerName::IpAddress(_)));
} else {
assert!(matches!(server_name, pki_types::ServerName::DnsName(_)));
}
let result = verifier.verify_server_cert(
&end_entity,
&intermediates,
&server_name,
test_case.stapled_ocsp.unwrap_or(&[]),
test_case.verification_time,
);
assert_cert_error_eq(
&result.map(|_| ()),
&test_case.expected_result,
test_case.other_error.as_ref(),
);
// TODO: get into specifics of errors returned when it fails.
}
enum Roots {
/// Test with only extra roots, without loading the platform trust store.
///
/// We want to keep things reproducible given the background-managed nature of trust roots on platforms.
OnlyExtra,
/// Test with loading the extra roots and the platform trust store.
///
/// Right now, not all platforms are supported.
#[cfg(not(target_os = "android"))]
ExtraAndPlatform,
}
@@ -0,0 +1,276 @@
//! Certificate verification tests that use real-world certificates and the
//! "real" (non-mock) Rustls configuration returned.
//!
//! # Repeatability and Self-containedness
//!
//! These tests are written to reduce the time-bomb nature of testing with
//! real certificates, which expire and/or can be revoked over time. For
//! example, rather than connecting to the TLS server over the network,
//! these tests operate on a locally-cached copy of the certificates
//! downloaded at a point in time. However, there are some inherent
//! limitations of what we can do when using real-world certificates. We
//! accept that the benefit of having these tests outweigh this downside.
//! If we encounter cases where these tests are flaky we'll spend additional
//! effort
//!
//! * If these certificates are ever revoked then it is possible that, even if
//! with the measures mentioned in the next paragraphs, the operating system
//! might learn of the revocation externally and cause the tests to fail.
//!
//! * Some operating systems, Windows in particular, download the set of
//! trusted roots dynamically as-needed. If there is a failure during that
//! fetching then the trust anchors for these certificates might not be
//! trusted by the operating system's root store.
//!
//! XXX: These tests should be using a stapled OCSP responses so that the
//! (operating-system-based) verifier doesn't try to fetch an OCSP
//! response or CRL certificate. However, until we can fix the validation
//! at a specific point in time, we can't do this, as the OCSP responses
//! will generally expire within a matter of days of being produced. Also,
//! we'd need to upgrade to a version of Rustls that supports passing in
//! stapled OCSP responses for each certificate in the chain. Most certificate
//! verifiers that do fetching of OCSP responses will "fail open"; that is, if
//! a networking error causes the fetch of the OCSP response to fail, then
//! they will continue roughly as though they received a "Good" response.
//! Thus we don't expect these tests to be flaky w.r.t. that, except for
//! potentially poor performance.
use rustls::client::danger::ServerCertVerifier;
use rustls::pki_types;
#[cfg(not(any(target_vendor = "apple", windows)))]
use rustls::pki_types::{DnsName, ServerName};
use rustls::{CertificateError, Error as TlsError};
use super::TestCase;
use crate::tests::{assert_cert_error_eq, test_provider, verification_time};
use crate::Verifier;
// This is the certificate chain presented by one server for
// `aws.amazon.com` when this test was updated 2025-08-13.
//
// Use this to template view the certificate using OpenSSL:
// ```sh
// openssl x509 -inform der -text -in aws_amazon_com_valid_1.crt | less
// ```
//
// You can update these cert files with `examples/update-certs.rs`
const VALID_AWS_AMAZON_COM_CHAIN: &[&[u8]] = &[
include_bytes!("aws_amazon_com_valid_1.crt"),
include_bytes!("aws_amazon_com_valid_2.crt"),
include_bytes!("aws_amazon_com_valid_3.crt"),
// XXX: This certificate is included for testing in environments that might need
// a cross-signed root certificate instead of the just the server-provided one.
include_bytes!("aws_amazon_com_valid_4.crt"),
];
/// Returns a list of names valid for [VALID_AWS_AMAZON_COM_CHAIN], in a format
/// expected by `CertificateError::NotValidForContext`.
#[cfg(not(any(target_vendor = "apple", windows)))]
fn valid_aws_chain_names() -> Vec<String> {
const VALID_AWS_NAMES: &[&str] = &[
"aws.amazon.com",
"aws-us-west-2.amazon.com",
"www.aws.amazon.com",
"1.aws-lbr.amazonaws.com",
"amazonaws-china.com",
"www.amazonaws-china.com",
"aws-us-east-1.amazon.com",
];
VALID_AWS_NAMES
.iter()
.copied()
.map(|name| format!("DnsName(\"{name}\")"))
.collect()
}
const AWS_AMAZON_COM: &str = "aws.amazon.com";
// Domain names for which `VALID_AWS_AMAZON_COM_CHAIN` isn't valid.
const VALID_UNRELATED_DOMAIN: &str = "my.1password.com";
const VALID_UNRELATED_SUBDOMAIN: &str = "www.amazon.com";
const LETSENCRYPT_ORG: &str = "letsencrypt.org";
const VALID_LETSENCRYPT_ORG_CHAIN: &[&[u8]] = &[
include_bytes!("letsencrypt_org_valid_1.crt"),
include_bytes!("letsencrypt_org_valid_2.crt"),
];
macro_rules! real_world_test_cases {
{ $( $name:ident => $test_case:expr ),+ , } => {
real_world_test_cases!(@ $($name => $test_case),+,);
#[cfg(test)]
mod tests {
$(
#[test]
pub fn $name() {
super::$name()
}
)+
}
#[cfg(feature = "ffi-testing")]
pub static ALL_TEST_CASES: &'static [fn()] = &[
$($name),+
];
};
{@ $( $name:ident => $test_case:expr ),+ , } => {
$(
pub(super) fn $name() {
real_world_test(&$test_case);
}
)+
}
}
macro_rules! no_error {
() => {
None::<std::convert::Infallible>
};
}
fn real_world_test<E: std::error::Error>(test_case: &TestCase<E>) {
log::info!(
"verifying ref ID {:?} expected {:?}",
test_case.reference_id,
test_case.expected_result
);
let crypto_provider = test_provider();
// On BSD systems openssl-probe fails to find the system CA bundle,
// so we must provide extra roots from webpki-root-cert.
#[cfg(target_os = "freebsd")]
let verifier = Verifier::new_with_extra_roots(
webpki_root_certs::TLS_SERVER_ROOT_CERTS.iter().cloned(),
crypto_provider,
)
.unwrap();
#[cfg(not(target_os = "freebsd"))]
let verifier = Verifier::new(crypto_provider).unwrap();
let mut chain = test_case
.chain
.iter()
.map(|bytes| pki_types::CertificateDer::from(*bytes));
let end_entity_cert = chain.next().unwrap();
let intermediates: Vec<pki_types::CertificateDer<'_>> = chain.collect();
let server_name = pki_types::ServerName::try_from(test_case.reference_id).unwrap();
let stapled_ocsp = test_case.stapled_ocsp.unwrap_or(&[]);
let result = verifier
.verify_server_cert(
&end_entity_cert,
&intermediates,
&server_name,
stapled_ocsp,
test_case.verification_time,
)
.map(|_| ());
assert_cert_error_eq(
&result.map(|_| ()),
&test_case.expected_result,
None::<&std::convert::Infallible>,
);
// TODO: get into specifics of errors returned when it fails.
}
// Prefer to staple the OCSP response for the end-entity certificate for
// performance and repeatability.
real_world_test_cases! {
// The certificate is valid for *.aws.amazon.com.
aws_amazon_com_valid => TestCase {
reference_id: AWS_AMAZON_COM,
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// Same as above but without stapled OCSP.
aws_amazon_com_valid_no_stapled => TestCase {
reference_id: AWS_AMAZON_COM,
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// Valid also for www.amazon.amazon.com (extra subdomain).
_aws_amazon_com_valid => TestCase {
reference_id: "www.aws.amazon.com",
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// The certificate isn't valid for an unrelated subdomain.
unrelated_domain_invalid => TestCase {
reference_id: VALID_UNRELATED_SUBDOMAIN,
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::DnsName(DnsName::try_from(VALID_UNRELATED_SUBDOMAIN).unwrap()),
presented: valid_aws_chain_names(),
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
// The certificate chain for the unrelated domain is not valid for
// my.1password.com.
unrelated_chain_not_valid_for_my_1password_com => TestCase {
reference_id: VALID_UNRELATED_DOMAIN,
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::DnsName(DnsName::try_from(VALID_UNRELATED_DOMAIN).unwrap()),
presented: valid_aws_chain_names(),
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
letsencrypt => TestCase {
reference_id: LETSENCRYPT_ORG,
chain: VALID_LETSENCRYPT_ORG_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// OCSP stapling works.
//
// XXX: This test is commented-out because it is a time-bomb due to the
// short lifetime of the OCSP responses for the certificate.
//
// TODO: If/when we can validate a certificate for a specific point in time
// during a test, re-enable this and have it test the certificate validity
// at a point in time where the OCSP response is valid.
//
// revoked_badssl_com_stapled => TestCase {
// reference_id: "revoked.badssl.com",
// chain: &[
// include_bytes!("revoked_badssl_com_1.crt"),
// include_bytes!("revoked_badssl_com_2.crt"),
// ],
// stapled_ocsp: Some(include_bytes!("revoked_badssl_com_1.ocsp")),
// // XXX: We only do OCSP stapling on Windows.
// valid: !cfg!(windows),
// },
}