Skip to content

Commit

Permalink
Apply formatting with cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Oct 25, 2021
1 parent 52c77e2 commit 2c09a8c
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 60 deletions.
4 changes: 3 additions & 1 deletion examples/google.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ use std::net::TcpStream;
fn main() {
let mut roots = rustls::RootCertStore::empty();
for cert in rustls_native_certs::load_native_certs().expect("could not load platform certs") {
roots.add(&rustls::Certificate(cert.0)).unwrap();
roots
.add(&rustls::Certificate(cert.0))
.unwrap();
}

let config = rustls::ClientConfig::builder()
Expand Down
4 changes: 2 additions & 2 deletions examples/print-trust-anchors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use x509_parser::prelude::*;
fn main() -> Result<(), Box<dyn Error>> {
for cert in rustls_native_certs::load_native_certs()? {
match parse_x509_certificate(&cert.0) {
Ok((_, cert)) => println!("{}", cert.tbs_certificate.subject),
Err(e) => eprintln!("error parsing certificate: {}", e),
Ok((_, cert)) => println!("{}", cert.tbs_certificate.subject),
Err(e) => eprintln!("error parsing certificate: {}", e),
};
}
Ok(())
Expand Down
22 changes: 10 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ mod macos;
#[cfg(target_os = "macos")]
use macos as platform;

use std::io::{Error, ErrorKind};
use std::io::BufReader;
use std::fs::File;
use std::path::{Path,PathBuf};
use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};

/// Loads root certificates found in the platform's native certificate
/// store, executing callbacks on the provided builder.
Expand All @@ -40,8 +40,7 @@ use std::env;
/// and parsing a ~300KB disk file. It's therefore prudent to call
/// this sparingly.
pub fn load_native_certs() -> Result<Vec<Certificate>, Error> {
load_certs_from_env()
.unwrap_or_else(platform::load_native_certs)
load_certs_from_env().unwrap_or_else(platform::load_native_certs)
}

pub struct Certificate(pub Vec<u8>);
Expand All @@ -53,9 +52,7 @@ const ENV_CERT_FILE: &str = "SSL_CERT_FILE";
/// If it is defined, it is always used, so it must be a path to a real
/// file from which certificates can be loaded successfully.
fn load_certs_from_env() -> Option<Result<Vec<Certificate>, Error>> {
let cert_var_path = PathBuf::from(
env::var_os(ENV_CERT_FILE)?
);
let cert_var_path = PathBuf::from(env::var_os(ENV_CERT_FILE)?);

Some(load_pem_certs(&cert_var_path))
}
Expand All @@ -65,9 +62,10 @@ fn load_pem_certs(path: &Path) -> Result<Vec<Certificate>, Error> {
let mut f = BufReader::new(f);

match rustls_pemfile::certs(&mut f) {
Ok(contents) => {
Ok(contents.into_iter().map(Certificate).collect())
}
Ok(contents) => Ok(contents
.into_iter()
.map(Certificate)
.collect()),
Err(_) => Err(Error::new(
ErrorKind::InvalidData,
format!("Could not load PEM file {:?}", path),
Expand Down
17 changes: 7 additions & 10 deletions src/macos.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
use crate::Certificate;

use security_framework::trust_settings::{
Domain,
TrustSettings,
TrustSettingsForCertificate
};
use security_framework::trust_settings::{Domain, TrustSettings, TrustSettingsForCertificate};

use std::io::{Error, ErrorKind};
use std::collections::HashMap;
use std::io::{Error, ErrorKind};

pub fn load_native_certs() -> Result<Vec<Certificate>, Error> {
// The various domains are designed to interact like this:
Expand All @@ -25,7 +21,8 @@ pub fn load_native_certs() -> Result<Vec<Certificate>, Error> {

for domain in &[Domain::User, Domain::Admin, Domain::System] {
let ts = TrustSettings::new(*domain);
let iter = ts.iter()
let iter = ts
.iter()
.map_err(|err| Error::new(ErrorKind::Other, err))?;

for cert in iter {
Expand All @@ -37,12 +34,12 @@ pub fn load_native_certs() -> Result<Vec<Certificate>, Error> {
//
// "Note that an empty Trust Settings array means "always trust this cert,
// with a resulting kSecTrustSettingsResult of kSecTrustSettingsResultTrustRoot".
let trusted = ts.tls_trust_settings_for_certificate(&cert)
let trusted = ts
.tls_trust_settings_for_certificate(&cert)
.map_err(|err| Error::new(ErrorKind::Other, err))?
.unwrap_or(TrustSettingsForCertificate::TrustRoot);

all_certs.entry(der)
.or_insert(trusted);
all_certs.entry(der).or_insert(trusted);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/unix.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::Certificate;
use crate::load_pem_certs;
use crate::Certificate;

use std::io::Error;

Expand All @@ -8,6 +8,6 @@ pub fn load_native_certs() -> Result<Vec<Certificate>, Error> {

match likely_locations.cert_file {
Some(cert_file) => load_pem_certs(&cert_file),
None => Ok(Vec::new())
None => Ok(Vec::new()),
}
}
6 changes: 3 additions & 3 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ static PKIX_SERVER_AUTH: &str = "1.3.6.1.5.5.7.3.1";
fn usable_for_rustls(uses: schannel::cert_context::ValidUses) -> bool {
match uses {
schannel::cert_context::ValidUses::All => true,
schannel::cert_context::ValidUses::Oids(strs) => {
strs.iter().any(|x| x == PKIX_SERVER_AUTH)
}
schannel::cert_context::ValidUses::Oids(strs) => strs
.iter()
.any(|x| x == PKIX_SERVER_AUTH),
}
}

Expand Down
53 changes: 30 additions & 23 deletions tests/compare_mozilla.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,15 @@ fn stringify_x500name(subject: &[u8]) -> String {
let mut reader = untrusted::Reader::new(subject.into());

while !reader.at_end() {
let (tag, contents) = der::read_tag_and_get_value(&mut reader)
.unwrap();
let (tag, contents) = der::read_tag_and_get_value(&mut reader).unwrap();
assert!(tag == 0x31); // sequence, constructed, context=1

let mut inner = untrusted::Reader::new(contents);
let pair = der::expect_tag_and_get_value(&mut inner, der::Tag::Sequence)
.unwrap();
let pair = der::expect_tag_and_get_value(&mut inner, der::Tag::Sequence).unwrap();

let mut pair = untrusted::Reader::new(pair);
let oid = der::expect_tag_and_get_value(&mut pair, der::Tag::OID)
.unwrap();
let (valuety, value) = der::read_tag_and_get_value(&mut pair)
.unwrap();
let oid = der::expect_tag_and_get_value(&mut pair, der::Tag::OID).unwrap();
let (valuety, value) = der::read_tag_and_get_value(&mut pair).unwrap();

let name = match oid.as_slice_less_safe() {
[0x55, 0x04, 0x03] => "CN",
Expand All @@ -47,7 +43,7 @@ fn stringify_x500name(subject: &[u8]) -> String {
let str_value = match valuety {
// PrintableString, UTF8String, TeletexString or IA5String
0x0c | 0x13 | 0x14 | 0x16 => std::str::from_utf8(value.as_slice_less_safe()).unwrap(),
_ => panic!("unhandled x500 value type {:?}", valuety)
_ => panic!("unhandled x500 value type {:?}", valuety),
};

parts.push(format!("{}={}", name, str_value));
Expand All @@ -56,7 +52,9 @@ fn stringify_x500name(subject: &[u8]) -> String {
parts.join(", ")
}

fn to_map<'a>(anchors: &'a [webpki::TrustAnchor<'a>]) -> HashMap<Vec<u8>, &'a webpki::TrustAnchor<'a>> {
fn to_map<'a>(
anchors: &'a [webpki::TrustAnchor<'a>],
) -> HashMap<Vec<u8>, &'a webpki::TrustAnchor<'a>> {
let mut r = HashMap::new();

for anchor in anchors {
Expand All @@ -68,19 +66,20 @@ fn to_map<'a>(anchors: &'a [webpki::TrustAnchor<'a>]) -> HashMap<Vec<u8>, &'a we

#[test]
fn test_does_not_have_many_roots_unknown_by_mozilla() {
let native = rustls_native_certs::load_native_certs()
.unwrap();
let native = rustls_native_certs::load_native_certs().unwrap();
let mozilla = to_map(webpki_roots::TLS_SERVER_ROOTS.0);

let mut missing_in_moz_roots = 0;

for cert in &native {
let cert = TrustAnchor::try_from_cert_der(&cert.0).unwrap();
if let Some(moz) = mozilla.get(cert.spki) {
assert_eq!(cert.subject, moz.subject,
"subjects differ for public key");
assert_eq!(cert.subject, moz.subject, "subjects differ for public key");
} else {
println!("Native anchor {:?} is missing from mozilla set", stringify_x500name(cert.subject));
println!(
"Native anchor {:?} is missing from mozilla set",
stringify_x500name(cert.subject)
);
missing_in_moz_roots += 1;
}
}
Expand All @@ -95,14 +94,17 @@ fn test_does_not_have_many_roots_unknown_by_mozilla() {
let diff = (missing_in_moz_roots as f64) / (mozilla.len() as f64);
println!("mozilla: {:?}", mozilla.len());
println!("native: {:?}", native.len());
println!("{:?} anchors present in native set but not mozilla ({}%)", missing_in_moz_roots, diff * 100.);
println!(
"{:?} anchors present in native set but not mozilla ({}%)",
missing_in_moz_roots,
diff * 100.
);
assert!(diff < threshold, "too many unknown roots");
}

#[test]
fn test_contains_most_roots_known_by_mozilla() {
let native = rustls_native_certs::load_native_certs()
.unwrap();
let native = rustls_native_certs::load_native_certs().unwrap();

let mut native_map = HashMap::new();
for anchor in &native {
Expand All @@ -114,7 +116,10 @@ fn test_contains_most_roots_known_by_mozilla() {
let mozilla = webpki_roots::TLS_SERVER_ROOTS.0;
for cert in mozilla {
if native_map.get(cert.spki).is_none() {
println!("Mozilla anchor {:?} is missing from native set", stringify_x500name(cert.subject));
println!(
"Mozilla anchor {:?} is missing from native set",
stringify_x500name(cert.subject)
);
missing_in_native_roots += 1;
}
}
Expand All @@ -129,15 +134,17 @@ fn test_contains_most_roots_known_by_mozilla() {
let diff = (missing_in_native_roots as f64) / (mozilla.len() as f64);
println!("mozilla: {:?}", mozilla.len());
println!("native: {:?}", native.len());
println!("{:?} anchors present in mozilla set but not native ({}%)",
missing_in_native_roots, diff * 100.);
println!(
"{:?} anchors present in mozilla set but not native ({}%)",
missing_in_native_roots,
diff * 100.
);
assert!(diff < threshold, "too many missing roots");
}

#[test]
fn util_list_certs() {
let native = rustls_native_certs::load_native_certs()
.unwrap();
let native = rustls_native_certs::load_native_certs().unwrap();

for (i, cert) in native.iter().enumerate() {
let cert = TrustAnchor::try_from_cert_der(&cert.0).unwrap();
Expand Down
15 changes: 8 additions & 7 deletions tests/smoketests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use std::sync::Arc;

use std::panic;

use std::env;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::env;
use std::path::PathBuf;

// #[serial] is used on all these tests to run them sequentially. If they're run in parallel,
Expand All @@ -15,7 +15,9 @@ use serial_test::serial;
fn check_site(domain: &str) {
let mut roots = rustls::RootCertStore::empty();
for cert in rustls_native_certs::load_native_certs().unwrap() {
roots.add(&rustls::Certificate(cert.0)).unwrap();
roots
.add(&rustls::Certificate(cert.0))
.unwrap();
}

let config = rustls::ClientConfig::builder()
Expand Down Expand Up @@ -83,16 +85,15 @@ fn apple() {
#[test]
#[serial]
fn badssl_with_env() {
let result = panic::catch_unwind(|| {
check_site("self-signed.badssl.com")
});
let result = panic::catch_unwind(|| check_site("self-signed.badssl.com"));
// Self-signed certs should never be trusted by default:
assert!(result.is_err());

// But they should be trusted if SSL_CERT_FILE is set:
env::set_var("SSL_CERT_FILE",
env::set_var(
"SSL_CERT_FILE",
// The CA cert, downloaded directly from the site itself:
PathBuf::from("./tests/badssl-com-chain.pem")
PathBuf::from("./tests/badssl-com-chain.pem"),
);
check_site("self-signed.badssl.com");
env::remove_var("SSL_CERT_FILE");
Expand Down

0 comments on commit 2c09a8c

Please sign in to comment.