Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat: support custom TLS certificates

SpringCorel1b1969624db9
diff --git a/moli-fetch/src/blocking/mod.rs b/moli-fetch/src/blocking/mod.rs
index be89f76c2..a8ff8c8a5 100644
--- a/moli-fetch/src/blocking/mod.rs
+++ b/moli-fetch/src/blocking/mod.rs
@@ -656,6 +656,48 @@ pub(crate) fn configure_easy<H: Handler>(
.context("failed to configure curl TLS peer verification")?;
easy.ssl_verify_host(config.tls_verify_host())
.context("failed to configure curl TLS host verification")?;
+ if let Some(ca_cert) = config.ca_cert() {
+ easy.cainfo(ca_cert).with_context(|| {
+ format!(
+ "failed to configure curl CA certificate `{}`",
+ ca_cert.display()
+ )
+ })?;
+ }
+ if let Some(client_cert) = config.client_cert() {
+ easy.ssl_cert(client_cert).with_context(|| {
+ format!(
+ "failed to configure curl client certificate `{}`",
+ client_cert.display()
+ )
+ })?;
+ let cert_type = match client_cert
+ .extension()
+ .and_then(|extension| extension.to_str())
+ .map(str::to_ascii_lowercase)
+ .as_deref()
+ {
+ Some("p12" | "pfx") => "P12",
+ Some("cer" | "der") => "DER",
+ _ => "PEM",
+ };
+ easy.ssl_cert_type(cert_type)
+ .context("failed to configure curl client certificate type")?;
+ }
+ if let Some(client_key) = config.client_key() {
+ easy.ssl_key(client_key).with_context(|| {
+ format!(
+ "failed to configure curl client private key `{}`",
+ client_key.display()
+ )
+ })?;
+ easy.ssl_key_type("PEM")
+ .context("failed to configure curl client private key type")?;
+ }
+ if let Some(password) = config.client_cert_password() {
+ easy.key_password(password)
+ .context("failed to configure curl client certificate password")?;
+ }
easy.useragent(config.user_agent())
.context("failed to set curl user-agent")?;
easy.url(request_url.as_str())
diff --git a/moli-fetch/src/config.rs b/moli-fetch/src/config.rs
index 523568466..b34e5db72 100644
--- a/moli-fetch/src/config.rs
+++ b/moli-fetch/src/config.rs
@@ -1,4 +1,4 @@
-use std::num::NonZeroU32;
+use std::{num::NonZeroU32, path::PathBuf};
use cidr::AnyIpCidr;
use moli_browser_profile::{BrowserIdentityProfile, DEFAULT_ACCEPT_LANGUAGE};
@@ -36,6 +36,10 @@ pub struct FetchConfig {
block_private_networks: bool,
block_cidrs: Vec<AnyIpCidr>,
tls_verify_host: bool,
+ ca_cert: Option<PathBuf>,
+ client_cert: Option<PathBuf>,
+ client_key: Option<PathBuf>,
+ client_cert_password: Option<String>,
web_bot_auth: Option<WebBotAuthSigner>,
}
@@ -147,6 +151,37 @@ impl FetchConfig {
self.tls_verify_host = tls_verify_host;
}
+ /// Configure TLS trust and mutual-TLS credentials for every request made
+ /// by this fetch runtime, including navigations and subresources.
+ pub fn set_tls_credentials(
+ &mut self,
+ ca_cert: Option<PathBuf>,
+ client_cert: Option<PathBuf>,
+ client_key: Option<PathBuf>,
+ client_cert_password: Option<String>,
+ ) {
+ self.ca_cert = ca_cert;
+ self.client_cert = client_cert;
+ self.client_key = client_key;
+ self.client_cert_password = client_cert_password;
+ }
+
+ pub fn ca_cert(&self) -> Option<&std::path::Path> {
+ self.ca_cert.as_deref()
+ }
+
+ pub fn client_cert(&self) -> Option<&std::path::Path> {
+ self.client_cert.as_deref()
+ }
+
+ pub fn client_key(&self) -> Option<&std::path::Path> {
+ self.client_key.as_deref()
+ }
+
+ pub fn client_cert_password(&self) -> Option<&str> {
+ self.client_cert_password.as_deref()
+ }
+
pub fn web_bot_auth(&self) -> Option<&WebBotAuthSigner> {
self.web_bot_auth.as_ref()
}
@@ -285,6 +320,10 @@ impl Default for FetchConfig {
block_private_networks: false,
block_cidrs: Vec::new(),
tls_verify_host: true,
+ ca_cert: None,
+ client_cert: None,
+ client_key: None,
+ client_cert_password: None,
web_bot_auth: None,
}
}
diff --git a/moli/src/cli.rs b/moli/src/cli.rs
index 76843cd7e..09f20c765 100644
--- a/moli/src/cli.rs
+++ b/moli/src/cli.rs
@@ -1,4 +1,4 @@
-use std::{ffi::OsString, num::NonZeroU32, path::PathBuf};
+use std::{ffi::OsString, num::NonZeroU32, path::PathBuf, str::FromStr};
use clap::{Args, Parser, Subcommand, ValueEnum};
use regex::Regex;
@@ -16,6 +16,50 @@ const DUMP_MODES: &[&str] = &[
pub const DEFAULT_REDIRECT_WAIT_MS: u64 = 1_000;
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ClientCertificate {
+ path: PathBuf,
+ password: Option<String>,
+}
+
+impl ClientCertificate {
+ pub fn path(&self) -> &std::path::Path {
+ &self.path
+ }
+
+ pub fn password(&self) -> Option<&str> {
+ self.password.as_deref()
+ }
+}
+
+impl FromStr for ClientCertificate {
+ type Err = String;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ let mut path = String::new();
+ let mut chars = value.chars().peekable();
+ while let Some(character) = chars.next() {
+ match (character, chars.peek().copied()) {
+ ('\\', Some(':' | '"')) => {
+ path.push(chars.next().expect("peeked character should exist"));
+ }
+ (':', _) => {
+ let password = chars.collect::<String>();
+ return Ok(Self {
+ path: PathBuf::from(path),
+ password: Some(password),
+ });
+ }
+ _ => path.push(character),
+ }
+ }
+ Ok(Self {
+ path: PathBuf::from(path),
+ password: None,
+ })
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Parser)]
#[command(
name = "moli",
@@ -370,6 +414,22 @@ pub struct CommonArgs {
#[arg(long)]
pub insecure_disable_tls_host_verification: bool,
+ /// Use this PEM file as the CA certificate bundle for HTTPS server
+ /// verification.
+ #[arg(long, value_name = "PATH")]
+ pub ca_cert: Option<PathBuf>,
+
+ /// Use this PEM, DER, or PKCS#12 certificate for HTTPS client authentication.
+ /// PEM may contain both the certificate and its private key. Use
+ /// `--client-key` when the private key is stored separately. `.p12` and
+ /// `.pfx` files are treated as PKCS#12 identities.
+ #[arg(long, value_name = "CERTIFICATE[:PASSWORD]")]
+ pub client_cert: Option<ClientCertificate>,
+
+ /// Use this PEM private key for HTTPS client-certificate authentication.
+ #[arg(long, value_name = "PATH", requires = "client_cert")]
+ pub client_key: Option<PathBuf>,
+
/// Refuse a `fetch` whose URL the origin's `/robots.txt` disallows for the
/// configured user agent. An unreachable `robots.txt` (5xx or a transport
/// failure) disallows the whole origin, per RFC 9309. Subresources and
@@ -736,6 +796,70 @@ mod tests {
}
}
+ #[test]
+ fn tls_credentials_are_shared_by_fetch_and_serve() {
+ for command in ["fetch", "serve"] {
+ let mut args = vec![
+ "moli",
+ command,
+ "--ca-cert",
+ "ca.pem",
+ "--client-cert",
+ "client.pem:secret",
+ "--client-key",
+ "client-key.pem",
+ ];
+ if command == "fetch" {
+ args.push("https://example.test/");
+ }
+ let cli = Cli::parse_from(args);
+ let common = match cli.command {
+ Commands::Fetch(args) => args.common,
+ Commands::Serve(args) => args.common,
+ };
+ assert_eq!(common.ca_cert, Some(PathBuf::from("ca.pem")));
+ let certificate = common.client_cert.expect("client certificate");
+ assert_eq!(certificate.path(), std::path::Path::new("client.pem"));
+ assert_eq!(certificate.password(), Some("secret"));
+ assert_eq!(common.client_key, Some(PathBuf::from("client-key.pem")));
+ }
+ }
+
+ #[test]
+ fn client_certificate_can_contain_its_key_but_key_requires_certificate() {
+ let combined = Cli::try_parse_from([
+ "moli",
+ "fetch",
+ "--client-cert",
+ "combined.pem",
+ "https://example.test/",
+ ]);
+ assert!(combined.is_ok(), "a combined client PEM should be accepted");
+
+ let key_only = Cli::try_parse_from([
+ "moli",
+ "fetch",
+ "--client-key",
+ "client-key.pem",
+ "https://example.test/",
+ ]);
+ assert!(
+ key_only.is_err(),
+ "a private key without a certificate parsed"
+ );
+ }
+
+ #[test]
+ fn client_certificate_uses_curl_style_password_and_colon_escaping() {
+ let certificate = ClientCertificate::from_str(r"identity\:archive.p12:secret:tail")
+ .expect("client certificate should parse");
+ assert_eq!(
+ certificate.path(),
+ std::path::Path::new("identity:archive.p12")
+ );
+ assert_eq!(certificate.password(), Some("secret:tail"));
+ }
+
#[test]
fn short_flags_do_not_collide() {
// clap panics on a duplicate short within one command. `CommonArgs` is
diff --git a/moli/src/config.rs b/moli/src/config.rs
index 7e5345459..3f7b36e39 100644
--- a/moli/src/config.rs
+++ b/moli/src/config.rs
@@ -191,6 +191,18 @@ fn apply_common_args(config: &mut AppConfig, common: &CommonArgs) -> Result<()>
.browser
.fetch_mut()
.set_tls_verify_host(!common.insecure_disable_tls_host_verification);
+ config.browser.fetch_mut().set_tls_credentials(
+ common.ca_cert.clone(),
+ common
+ .client_cert
+ .as_ref()
+ .map(|certificate| certificate.path().to_path_buf()),
+ common.client_key.clone(),
+ common
+ .client_cert
+ .as_ref()
+ .and_then(|certificate| certificate.password().map(str::to_owned)),
+ );
configure_web_bot_auth(config.browser.fetch_mut(), common)?;
for source in &common.document_start_script {
@@ -327,3 +339,42 @@ pub fn response_wait_criteria_from_args(
}),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::AppConfig;
+ use crate::cli::{Cli, Commands};
+ use clap::Parser;
+ use std::path::Path;
+
+ #[test]
+ fn tls_credentials_reach_fetch_config_for_fetch_and_serve() {
+ for command in ["fetch", "serve"] {
+ let mut arguments = vec![
+ "moli",
+ command,
+ "--ca-cert",
+ "ca.pem",
+ "--client-cert",
+ "client.pem:secret",
+ "--client-key",
+ "client-key.pem",
+ ];
+ if command == "fetch" {
+ arguments.push("https://example.test/");
+ }
+
+ let cli = Cli::parse_from(arguments);
+ assert!(matches!(
+ &cli.command,
+ Commands::Fetch(_) | Commands::Serve(_)
+ ));
+ let config = AppConfig::from_cli(&cli).expect("TLS configuration should build");
+ let fetch = config.browser.fetch();
+ assert_eq!(fetch.ca_cert(), Some(Path::new("ca.pem")));
+ assert_eq!(fetch.client_cert(), Some(Path::new("client.pem")));
+ assert_eq!(fetch.client_key(), Some(Path::new("client-key.pem")));
+ assert_eq!(fetch.client_cert_password(), Some("secret"));
+ }
+ }
+}
diff --git a/moli/tests/cli.rs b/moli/tests/cli.rs
index 32a78bb10..c0203a46f 100644
--- a/moli/tests/cli.rs
+++ b/moli/tests/cli.rs
@@ -113,6 +113,9 @@ fn parses_explicit_fetch_command_with_compatibility_flags() {
timeout: 25_000,
common: CommonArgs {
insecure_disable_tls_host_verification: false,
+ ca_cert: None,
+ client_cert: None,
+ client_key: None,
obey_robots: true,
http_proxy: Some("http://proxy.internal:8080".to_owned()),
http_no_proxy: None,