feat: prepare 3.1.0 with connection details and improved authentication

Add tunnel statistics and an optional CLI dashboard, native sign-in controls and recovery, and broader client certificate support. Include platform integration fixes and the approved release notes.
This commit is contained in:
Kevin Yue committed 2026-10-19 23:47:11 +08:00
1 parent 18ed6bac1a
commit 4faa2ecb0d
158 files changed
+13752 -1038

No files matched your search

+90 -295
View File
@@ -1,10 +1,11 @@
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
use anyhow::{Context, ensure};
use openssl::{pkey::PKey, x509::X509};
use reqwest::Identity;
use zeroize::Zeroizing;
use super::{identity_encoding, pkcs12_identity};
#[derive(Debug, thiserror::Error)]
pub enum RequestIdentityError {
#[error("Failed to find the private key")]
@@ -13,6 +14,24 @@ pub enum RequestIdentityError {
NoPassphrase(&'static str),
#[error("Failed to decrypt private key")]
DecryptError(&'static str),
#[error(
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
)]
UnsupportedEncryption,
#[error(
"Could not convert the legacy private key with OpenSSL: {0}. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
)]
LegacyKeyConversion(&'static str),
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")]
UnsupportedKeyFormat,
#[error("Invalid private key")]
InvalidKey,
#[error("Invalid certificate or certificate chain")]
InvalidCertificate,
#[error("The PKCS#12 file must contain both a client certificate and its private key")]
IncompletePkcs12,
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")]
InvalidPkcs12(#[source] reqwest::Error),
}
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
@@ -41,37 +60,17 @@ impl fmt::Debug for ClientIdentity {
impl ClientIdentity {
pub fn load(certificate: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Self> {
let certificate_bytes = read_identity_file(certificate)?;
if certificate.ends_with(".p12") || certificate.ends_with(".pfx") {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
return Self::from_data(certificate_bytes, None, Some(passphrase));
let extension = Path::new(certificate).extension().and_then(|value| value.to_str());
if extension.is_some_and(|value| value.eq_ignore_ascii_case("p12") || value.eq_ignore_ascii_case("pfx")) {
return Self::from_data(certificate_bytes, None, passphrase);
}
let key_bytes = match key {
Some(path) => read_identity_file(path)?,
None => certificate_bytes.clone(),
};
// Keep the previous first-private-key rule: unrelated later blocks must not
// change which key is selected or whether the caller is prompted.
let key = pem::parse_many(&*key_bytes)?
.into_iter()
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
.ok_or(RequestIdentityError::NoKey)?;
let key_pem = Zeroizing::new(pem::encode(&key));
let key = if key.tag().ends_with("ENCRYPTED PRIVATE KEY") {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
let key = PKey::private_key_from_pem_passphrase(key_pem.as_bytes(), passphrase.as_bytes())
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
Zeroizing::new(key.private_key_to_pem_pkcs8()?)
} else {
Zeroizing::new(key_pem.as_bytes().to_vec())
};
// Strip private-key blocks before importing the certificate chain: macOS
// otherwise imports the same key twice for combined PEM files.
let mut certificate = Zeroizing::new(Vec::new());
for cert in X509::stack_from_pem(&certificate_bytes)? {
certificate.extend(cert.to_pem()?);
}
let identity = Identity::from_pkcs8_pem(&certificate, &key)?;
let key = Zeroizing::new(PKey::private_key_from_pem(&key)?.private_key_to_pem_pkcs8()?);
let key = identity_encoding::private_key(&key_bytes, passphrase)?;
let certificate = identity_encoding::certificate_chain(&certificate_bytes)?;
let identity = pem_request_identity(&certificate, &key)?;
Ok(Self {
material: Arc::new(IdentityMaterial {
certificate,
@@ -90,12 +89,21 @@ impl ClientIdentity {
passphrase: Option<&str>,
) -> anyhow::Result<Self> {
let (identity, passphrase) = match &key {
Some(key) => (Identity::from_pkcs8_pem(&certificate, key)?, None),
Some(key) => (pem_request_identity(&certificate, key)?, None),
None => {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
pkcs12_identity::ensure_complete(&certificate, passphrase.unwrap_or_default())?;
// A blank settings field is stored as None. Try the empty password so
// passwordless archives work, but keep prompting for protected ones.
let identity = Identity::from_pkcs12_der(&certificate, passphrase.unwrap_or_default()).map_err(|error| {
if passphrase.is_none() {
RequestIdentityError::NoPassphrase("PKCS#12")
} else {
RequestIdentityError::InvalidPkcs12(error)
}
})?;
(
Identity::from_pkcs12_der(&certificate, passphrase)?,
Some(Zeroizing::new(passphrase.to_owned())),
identity,
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
)
}
};
@@ -152,6 +160,20 @@ impl ClientIdentityFiles {
}
}
fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
let error_context =
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
let identity = Identity::from_pkcs8_pem(certificate, key).context(error_context)?;
// Native TLS may defer the certificate/key match check until connector creation.
// Build the same client used for requests without making a network connection.
reqwest::Client::builder()
.no_proxy()
.identity(identity.clone())
.build()
.context(error_context)?;
Ok(identity)
}
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
Ok(Zeroizing::new(
fs::read(path).context("Failed to read client identity")?,
@@ -189,50 +211,15 @@ pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>)
#[cfg(test)]
mod tests {
use super::*;
use openssl::pkcs12::Pkcs12;
fn generated_identity() -> (Vec<u8>, Vec<u8>) {
use openssl::{asn1::Asn1Time, hash::MessageDigest, rsa::Rsa, x509::X509NameBuilder};
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
name.append_entry_by_text("CN", "identity-fixture").unwrap();
let name = name.build();
let mut certificate = X509::builder().unwrap();
certificate.set_version(2).unwrap();
certificate.set_subject_name(&name).unwrap();
certificate.set_issuer_name(&name).unwrap();
certificate.set_pubkey(&key).unwrap();
certificate
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
.unwrap();
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
certificate.sign(&key, MessageDigest::sha256()).unwrap();
(
certificate.build().to_pem().unwrap(),
key.private_key_to_pem_pkcs8().unwrap(),
)
}
#[test]
fn pem_uses_first_private_key_without_prompting_for_later_encrypted_keys() {
let (certificate, key) = generated_identity();
let encrypted = PKey::private_key_from_pem(&key)
.unwrap()
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"unused")
.unwrap();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(&key).unwrap();
source.write_all(&encrypted).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
assert_eq!(identity.key_data().unwrap(), key);
}
const CERTIFICATE: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-cert.pem");
const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem");
const ENCRYPTED_KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pbes2-sha256.pem");
#[test]
fn pem_without_key_reports_missing_key_even_with_passphrase() {
let (certificate, _) = generated_identity();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(CERTIFICATE).unwrap();
for passphrase in [None, Some("unused")] {
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, passphrase).unwrap_err();
assert!(matches!(
@@ -244,249 +231,57 @@ mod tests {
#[test]
fn local_identity_loading_is_not_limited_by_service_message_size() {
let (certificate, key) = generated_identity();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(&key).unwrap();
source.write_all(CERTIFICATE).unwrap();
source.write_all(KEY).unwrap();
source.write_all(&vec![b'\n'; 33 * 1024]).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
assert_eq!(identity.certificate_data(), certificate);
assert_eq!(identity.key_data().unwrap(), key);
assert_eq!(identity.certificate_data(), CERTIFICATE);
assert_eq!(identity.key_data().unwrap(), KEY);
}
#[test]
fn pem_passphrases_preserve_prompt_errors_and_accept_separate_keys() {
let (certificate, key) = generated_identity();
let mut cert_file = tempfile::NamedTempFile::new().unwrap();
cert_file.write_all(&certificate).unwrap();
let mut key_file = tempfile::NamedTempFile::new().unwrap();
let encrypted = PKey::private_key_from_pem(&key)
.unwrap()
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"correct")
.unwrap();
key_file.write_all(&encrypted).unwrap();
let cert = cert_file.path().to_str().unwrap();
let key_path = Some(key_file.path().to_str().unwrap());
for (passphrase, missing) in [(None, true), (Some("wrong"), false)] {
let error = ClientIdentity::load(cert, key_path, passphrase).unwrap_err();
match error.downcast_ref::<RequestIdentityError>().unwrap() {
RequestIdentityError::NoPassphrase("PEM") => assert!(missing),
RequestIdentityError::DecryptError("PEM") => assert!(!missing),
other => panic!("Unexpected identity error: {other}"),
fn create_identity_preserves_password_errors_and_builds_a_native_request_client() {
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(CERTIFICATE).unwrap();
source.write_all(ENCRYPTED_KEY).unwrap();
for (password, missing) in [(None, true), (Some("wrong"), false)] {
let error = create_identity(source.path().to_str().unwrap(), None, password).unwrap_err();
match error.downcast_ref::<RequestIdentityError>() {
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
other => panic!("Unexpected identity error: {other:?}"),
}
}
let loaded = ClientIdentity::load(cert, key_path, Some("correct")).unwrap();
assert_eq!(loaded.key_data().unwrap(), key);
fs::write(key_file.path(), &key).unwrap();
for passphrase in [None, Some("ignored for unencrypted key")] {
assert_eq!(
ClientIdentity::load(cert, key_path, passphrase)
.unwrap()
.key_data()
.unwrap(),
key
);
}
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
drop(source);
reqwest::Client::builder().identity(identity).build().unwrap();
}
#[test]
fn loaded_identity_survives_original_file_replacement_and_owns_private_files() {
fn unencrypted_key_ignores_unused_password_and_archive_owned_file_is_private() {
use std::os::unix::fs::PermissionsExt;
let (certificate, key) = generated_identity();
let directory = tempfile::tempdir().unwrap();
let source = directory.path().join("combined.pem");
let mut combined = certificate.clone();
combined.extend(&key);
fs::write(&source, &combined).unwrap();
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
fs::write(&source, "changed after authentication").unwrap();
assert_eq!(identity.certificate_data(), certificate);
assert_eq!(identity.key_data().unwrap(), key);
assert!(!format!("{identity:?}").contains("PRIVATE KEY"));
let files = identity.write_files(Some(directory.path())).unwrap();
let certificate_path = files.certificate().to_owned();
let key_path = files.key().unwrap().to_owned();
assert_eq!(fs::read(&certificate_path).unwrap(), certificate);
assert_eq!(fs::read(&key_path).unwrap(), key);
assert_eq!(fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
let identity = ClientIdentity::from_data(
Zeroizing::new(CERTIFICATE.to_vec()),
Some(Zeroizing::new(KEY.to_vec())),
Some("unused password"),
)
.unwrap();
assert!(identity.key_password().is_none());
let archive = include_bytes!("../../tests/files/client-identity/modern.p12").to_vec();
let identity = ClientIdentity::from_data(Zeroizing::new(archive), None, Some("fixture-password")).unwrap();
let files = identity.write_files(None).unwrap();
let path = files.certificate().to_owned();
assert!(path.ends_with(".p12"));
assert!(files.key().is_none());
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
drop(files);
assert!(!Path::new(&certificate_path).exists());
assert!(!Path::new(&key_path).exists());
// The request identity remains valid after its original files disappear.
fs::remove_file(&source).unwrap();
assert!(!Path::new(&path).exists());
reqwest::Client::builder()
.identity(identity.request_identity())
.build()
.unwrap();
}
#[test]
fn pkcs12_preserves_original_data_password_and_owned_native_files() {
let (certificate, key) = generated_identity();
let certificate = X509::from_pem(&certificate).unwrap();
let key = PKey::private_key_from_pem(&key).unwrap();
let mut builder = Pkcs12::builder();
builder.name("identity-fixture").pkey(&key).cert(&certificate);
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
for suffix in [".p12", ".pfx"] {
let mut source = tempfile::Builder::new().suffix(suffix).tempfile().unwrap();
source.write_all(&encoded).unwrap();
let path = source.path().to_str().unwrap();
assert!(ClientIdentity::load(path, None, None).is_err());
assert!(ClientIdentity::load(path, None, Some("wrong")).is_err());
// PKCS#12 has always ignored a separately configured key path.
let identity = ClientIdentity::load(path, Some("missing-key-file"), Some("fixture-password")).unwrap();
fs::write(source.path(), b"replaced after login").unwrap();
assert_eq!(identity.certificate_data(), encoded);
assert!(identity.key_data().is_none());
assert_eq!(identity.key_password(), Some("fixture-password"));
assert!(!format!("{identity:?}").contains("fixture-password"));
let files = identity.write_files(None).unwrap();
assert!(files.certificate().ends_with(".p12"));
assert!(files.key().is_none());
ClientIdentity::load(files.certificate(), files.key(), identity.key_password()).unwrap();
let owned_path = files.certificate().to_owned();
drop(files);
assert!(!Path::new(&owned_path).exists());
}
let empty_password = builder.build2("").unwrap().to_der().unwrap();
// Empty-password support varies by native backend and PKCS#12 algorithms.
// Match the previous native import instead of introducing another parser.
let previously_accepted = Identity::from_pkcs12_der(&empty_password, "").is_ok();
assert_eq!(
ClientIdentity::from_data(Zeroizing::new(empty_password), None, Some("")).is_ok(),
previously_accepted
);
}
#[test]
fn pkcs12_retains_chain_without_reordering_or_reencoding() {
use openssl::{
asn1::Asn1Time,
hash::MessageDigest,
rsa::Rsa,
stack::Stack,
x509::{X509NameBuilder, extension::BasicConstraints},
};
fn certificate(
name: &str,
parent: Option<(&X509, &PKey<openssl::pkey::Private>)>,
ca: bool,
) -> (X509, PKey<openssl::pkey::Private>) {
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut subject = X509NameBuilder::new().unwrap();
subject.append_entry_by_text("CN", name).unwrap();
let subject = subject.build();
let mut cert = X509::builder().unwrap();
cert.set_version(2).unwrap();
let serial = openssl::bn::BigNum::from_u32(name.len() as u32)
.unwrap()
.to_asn1_integer()
.unwrap();
cert.set_serial_number(&serial).unwrap();
cert.set_subject_name(&subject).unwrap();
cert
.set_issuer_name(parent.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject))
.unwrap();
cert.set_pubkey(&key).unwrap();
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
if ca {
cert
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
.unwrap();
}
cert
.sign(parent.map(|(_, key)| key).unwrap_or(&key), MessageDigest::sha256())
.unwrap();
(cert.build(), key)
}
let (root, root_key) = certificate("root", None, true);
let (intermediate, intermediate_key) = certificate("intermediate", Some((&root, &root_key)), true);
let (leaf, key) = certificate("client", Some((&intermediate, &intermediate_key)), false);
// This is the reverse CA stack consumed by the previous native-tls path.
let mut ca = Stack::new().unwrap();
ca.push(root.clone()).unwrap();
ca.push(intermediate.clone()).unwrap();
let mut builder = Pkcs12::builder();
builder.name("chain-fixture").pkey(&key).cert(&leaf).ca(ca);
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
let mut source = tempfile::Builder::new().suffix(".p12").tempfile().unwrap();
source.write_all(&encoded).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
assert_eq!(identity.certificate_data(), encoded);
assert!(identity.key_data().is_none());
ClientIdentity::from_data(
Zeroizing::new(identity.certificate_data().to_vec()),
None,
identity.key_password(),
)
.unwrap();
}
#[test]
fn create_identity_from_pem_requires_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let identity = create_identity(cert, None, None);
assert!(identity.is_err());
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
}
#[test]
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_with_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let passphrase = "badssl.com";
let identity = create_identity(cert, None, Some(passphrase));
assert!(identity.is_ok());
}
#[test]
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_unencrypted_key() {
let cert = "tests/files/badssl.com-client-unencrypted.pem";
let identity = create_identity(cert, None, None);
println!("{:?}", identity);
assert!(identity.is_ok());
}
#[test]
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_cert_and_encrypted_key() {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client.pem";
let passphrase = "badssl.com";
let identity = create_identity(cert, Some(key), Some(passphrase));
assert!(identity.is_ok());
}
#[test]
fn create_identity_from_pem_cert_and_encrypted_key_no_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client.pem";
let identity = create_identity(cert, Some(key), None);
assert!(identity.is_err());
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
}
#[test]
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_cert_and_unencrypted_key() {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client-unencrypted.pem";
let identity = create_identity(cert, Some(key), None);
assert!(identity.is_ok());
}
}
#[derive(Debug, thiserror::Error)]