Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ pub(crate) fn client_builder() -> reqwest::ClientBuilder {
{
// A provider is already installed, which is all the client needs.
}
with_bundled_roots(reqwest::Client::builder())
crate::tls::apply(with_bundled_roots(reqwest::Client::builder()))
}

#[cfg(all(unix, not(target_vendor = "apple")))]
Expand Down
9 changes: 9 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod sarif;
mod scan;
mod severity;
pub mod text;
mod tls;
pub mod update;

use std::io::Write as _;
Expand Down Expand Up @@ -72,6 +73,11 @@ pub struct Cli {
#[arg(long, global = true, env = "PROOFLINE_ORGANIZATION_ID")]
org: Option<Uuid>,

/// PEM file of extra root certificates to trust beside the existing
/// roots, such as the root of a TLS-inspecting corporate proxy.
#[arg(long, global = true, env = "PROOFLINE_CA_CERT", value_name = "FILE")]
ca_cert: Option<PathBuf>,

#[command(subcommand)]
command: Command,
}
Expand Down Expand Up @@ -366,6 +372,9 @@ pub enum Verdict {

/// Runs one command. `token` is `PROOFLINE_TOKEN`, read by the caller.
pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdict> {
if let Some(path) = &cli.ca_cert {
tls::trust(path)?;
}
if let Command::Review(args) = &cli.command
&& args.schema
{
Expand Down
90 changes: 90 additions & 0 deletions src/tls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//! Extra root certificates the CLI trusts beside its bundled public roots.
//!
//! A TLS-inspecting proxy re-signs every connection with a private root that
//! the system roots do not contain. `--ca-cert` (or `PROOFLINE_CA_CERT`) names
//! a PEM file whose certificates are added to, never substituted for, the
//! existing roots; certificate and hostname verification stay on.

use std::path::Path;
use std::sync::OnceLock;

use reqwest::{Certificate, ClientBuilder};

static EXTRA_ROOTS: OnceLock<Vec<Certificate>> = OnceLock::new();

#[derive(Debug, thiserror::Error)]
pub enum CaCertError {
#[error("could not read the CA certificate file {path}: {reason}")]
Unreadable { path: String, reason: String },
#[error("the CA certificate file {path} is not PEM: {reason}")]
Invalid { path: String, reason: String },
#[error("the CA certificate file {path} contains no PEM certificate")]
Empty { path: String },
}

/// Reads every certificate in the PEM file at `path`.
pub fn read(path: &Path) -> Result<Vec<Certificate>, CaCertError> {
let shown = path.display().to_string();
let pem = std::fs::read(path).map_err(|error| CaCertError::Unreadable {
path: shown.clone(),
reason: error.to_string(),
})?;
let roots = Certificate::from_pem_bundle(&pem).map_err(|error| CaCertError::Invalid {
path: shown.clone(),
reason: error.to_string(),
})?;
if roots.is_empty() {
return Err(CaCertError::Empty { path: shown });
}
Ok(roots)
}

/// Trusts the certificates in the PEM file at `path` for every client this
/// process builds afterwards. Called once, before the first request.
pub fn trust(path: &Path) -> Result<(), CaCertError> {
let roots = read(path)?;
if EXTRA_ROOTS.set(roots).is_err() {
// Set once at start-up; a second call keeps the first file.
}
Ok(())
}

/// Adds the trusted extra roots, if any, to `builder`.
pub fn apply(builder: ClientBuilder) -> ClientBuilder {
builder.tls_certs_merge(EXTRA_ROOTS.get().into_iter().flatten().cloned())
}

#[cfg(test)]
mod tests {
use super::{CaCertError, read};

const FIXTURE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/ca-cert.pem");

#[test]
fn reads_a_pem_root() {
assert_eq!(read(FIXTURE.as_ref()).unwrap().len(), 1);
}

#[test]
fn a_built_client_accepts_the_root() {
let builder = crate::api::client_builder().tls_certs_merge(read(FIXTURE.as_ref()).unwrap());
assert!(builder.build().is_ok());
}

#[test]
fn refuses_a_missing_file() {
let directory = tempfile::tempdir().unwrap();
let error = read(&directory.path().join("absent.pem")).unwrap_err();
assert!(matches!(error, CaCertError::Unreadable { .. }), "{error}");
assert!(error.to_string().contains("absent.pem"), "{error}");
}

#[test]
fn refuses_a_file_without_certificates() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("empty.pem");
std::fs::write(&path, "not a certificate\n").unwrap();
let error = read(&path).unwrap_err();
assert!(matches!(error, CaCertError::Empty { .. }), "{error}");
}
}
11 changes: 11 additions & 0 deletions tests/fixtures/ca-cert.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-----BEGIN CERTIFICATE-----
MIIBqzCCAVGgAwIBAgIUIMXhm15jk6X6kV0BjTYmX3J0TgYwCgYIKoZIzj0EAwIw
IjEgMB4GA1UEAwwXUHJvb2ZsaW5lIENMSSB0ZXN0IHJvb3QwIBcNMjYxMTEwMTgx
NzM3WhgPMjEyNjEwMTcxODE3MzdaMCIxIDAeBgNVBAMMF1Byb29mbGluZSBDTEkg
dGVzdCByb290MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/hUZsfJruBqE3orB
C86X6/RdhhHNzozDTscOdagFeI876NNUtwHuv3fcvRX4xnerJqADKrk/besjUXn2
zbK48KNjMGEwHQYDVR0OBBYEFDYflJ174gjZ6AHf8hzvgA+LpV/KMB8GA1UdIwQY
MBaAFDYflJ174gjZ6AHf8hzvgA+LpV/KMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0P
AQH/BAQDAgIEMAoGCCqGSM49BAMCA0gAMEUCIGbCHhXX1MK4TJa96/NpdK65y6+S
NBtxvFi2dKNC9Kw1AiEAhlusueRMnvcbdWGp+f7X3qiqjAMw3GOw/80oXVWIN6A=
-----END CERTIFICATE-----