Skip to content
Open
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
71 changes: 63 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ regex = "^1.7.0"
reqwest = { version = "0.12.5", default-features = false, features = ["rustls-tls", "stream", "gzip", "brotli", "socks", "json", "http2"] } # pinned because of https://github.com/seanmonstar/reqwest/pull/1955
reqwest_v011 = { package = "reqwest", version = "0.11", features = ["stream", "json", "multipart"] }
ring = "^0.17.14"
rustls = { version = "0.23.31", default-features = false, features = ["logging", "std", "tls12", "ring"] }
rustls = { version = "0.23.31", default-features = false, features = ["logging", "std", "tls12", "ring", "aws_lc_rs", "prefer-post-quantum"] }
rustls-pemfile = "2"
rustls-tokio-stream = "=0.3.0"
rustls-webpki = "0.103.16"
Expand Down
24 changes: 24 additions & 0 deletions cli/src/env.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use anyhow::bail;
use anyhow::Context;
use base::runtime;
use base::utils::tls::CryptoProviderKind;
use clap::builder::BoolishValueParser;
use clap::builder::TypedValueParser;
use clap::value_parser;
Expand Down Expand Up @@ -68,3 +71,24 @@ pub(super) fn resolve_deno_runtime_env() {
&runtime::EVENT_WORKER_MAX_HEAP_SIZE_MIB,
);
}

const TLS_CRYPTO_PROVIDER_ENV: &str = "EDGE_RUNTIME_TLS_CRYPTO_PROVIDER";

/// rustls has both ring and aws-lc-rs compiled in, so the process-wide
/// provider must be chosen before anything builds a TLS config. Unset or empty
/// means ring.
pub(super) fn install_tls_crypto_provider() -> anyhow::Result<CryptoProviderKind>
{
let kind = match std::env::var_os(TLS_CRYPTO_PROVIDER_ENV) {
None => CryptoProviderKind::default(),
Some(value) => match value.to_str() {
Some("") => CryptoProviderKind::default(),
Some(value) => value
.parse()
.with_context(|| format!("can't parse {TLS_CRYPTO_PROVIDER_ENV}"))?,
None => bail!("{TLS_CRYPTO_PROVIDER_ENV} is not valid UTF-8"),
},
};
let _ = kind.install_default();
Ok(kind)
}
4 changes: 4 additions & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use deno_facade::extract_from_file;
use deno_facade::generate_binary_eszip;
use deno_facade::EmitterFactory;
use deno_facade::Metadata;
use env::install_tls_crypto_provider;
use env::resolve_deno_runtime_env;
use flags::get_cli;
use flags::EszipV2ChecksumKind;
Expand Down Expand Up @@ -83,6 +84,9 @@ fn main() -> Result<ExitCode, anyhow::Error> {
}
}

let tls_crypto_provider = install_tls_crypto_provider()?;
log::debug!("TLS crypto provider: {tls_crypto_provider}");

#[allow(clippy::single_match)]
#[allow(clippy::arc_with_non_send_sync)]
let exit_code = match matches.subcommand() {
Expand Down
5 changes: 5 additions & 0 deletions crates/base/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ use tracing::Span;
use crate::inspector_server::Inspector;
use crate::snapshot;
use crate::utils::json;
use crate::utils::tls::ensure_default_crypto_provider;
use crate::utils::units::bytes_to_display;
use crate::utils::units::mib_to_bytes;
use crate::utils::units::percentage_value;
Expand Down Expand Up @@ -441,6 +442,10 @@ where
#[allow(clippy::unnecessary_literal_unwrap)]
#[allow(clippy::arc_with_non_send_sync)]
pub(crate) async fn new(mut worker: Worker) -> Result<Self, Error> {
// Everything that builds a rustls config (fetch, `Deno.connectTls`,
// `Deno.listenTls`, module downloads) runs inside a runtime.
ensure_default_crypto_provider();

let init_opts = worker.init_opts.take();
let flags = worker.flags.clone();
let event_metadata = worker.event_metadata.clone();
Expand Down
1 change: 1 addition & 0 deletions crates/base/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod dirs;
pub mod json;
pub mod test_utils;
pub mod tls;
pub mod units;
130 changes: 130 additions & 0 deletions crates/base/src/utils/tls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
use std::fmt;
use std::str::FromStr;
use std::sync::Arc;

use deno::deno_tls::rustls;
use rustls::crypto::CryptoProvider;

/// The rustls crypto provider: the backend for key exchange, cipher suites
/// and certificate signature verification on every TLS connection configured
/// through rustls 0.23 in this process.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CryptoProviderKind {
/// Classical key exchange only (X25519, P-256, P-384). This is what every
/// build before aws-lc-rs was added used.
#[default]
Ring,
/// Offers hybrid post-quantum X25519MLKEM768 first, then the classical
/// groups.
AwsLcRs,
}

#[derive(Debug, thiserror::Error)]
#[error(
"invalid TLS crypto provider {0:?}: expected \"ring\" or \"aws-lc-rs\""
)]
pub struct InvalidCryptoProvider(String);

impl CryptoProviderKind {
pub fn provider(self) -> CryptoProvider {
match self {
Self::Ring => rustls::crypto::ring::default_provider(),
Self::AwsLcRs => rustls::crypto::aws_lc_rs::default_provider(),
}
}

/// Installs this provider as the process-wide default. Fails, returning the
/// installed one, if a default was already installed.
pub fn install_default(self) -> Result<(), Arc<CryptoProvider>> {
self.provider().install_default()
}
}

impl FromStr for CryptoProviderKind {
type Err = InvalidCryptoProvider;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"ring" => Ok(Self::Ring),
"aws-lc-rs" | "aws_lc_rs" => Ok(Self::AwsLcRs),
_ => Err(InvalidCryptoProvider(s.into())),
}
}
}

impl fmt::Display for CryptoProviderKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Ring => "ring",
Self::AwsLcRs => "aws-lc-rs",
})
}
}

/// rustls is built with both ring (which rustls-tokio-stream and reqwest
/// require) and aws-lc-rs, so it can't choose a default provider on its own,
/// and `ClientConfig::builder()` / `ServerConfig::builder()` panic until one
/// is installed. The CLI installs the one its configuration names at startup;
/// this is the fallback for embedders that don't install one themselves.
pub fn ensure_default_crypto_provider() {
if CryptoProvider::get_default().is_none() {
// Losing a race to another installer is fine.
let _ = CryptoProviderKind::default().install_default();
}
}

#[cfg(test)]
mod tests {
use rustls::NamedGroup;

use super::*;

fn kx_group_names(kind: CryptoProviderKind) -> Vec<NamedGroup> {
kind.provider().kx_groups.iter().map(|g| g.name()).collect()
}

#[test]
fn parses_provider_names() {
assert_eq!(
"ring".parse::<CryptoProviderKind>().unwrap(),
CryptoProviderKind::Ring
);
assert_eq!(
"aws-lc-rs".parse::<CryptoProviderKind>().unwrap(),
CryptoProviderKind::AwsLcRs
);
assert_eq!(
"AWS_LC_RS".parse::<CryptoProviderKind>().unwrap(),
CryptoProviderKind::AwsLcRs
);
assert!("openssl".parse::<CryptoProviderKind>().is_err());
}

#[test]
fn ring_offers_only_classical_groups() {
assert_eq!(
kx_group_names(CryptoProviderKind::Ring),
[
NamedGroup::X25519,
NamedGroup::secp256r1,
NamedGroup::secp384r1
]
);
}

#[test]
fn aws_lc_rs_prefers_hybrid_post_quantum() {
// The client only sends a key share for the first group (plus X25519 when
// that group is a hybrid), so X25519MLKEM768 has to come first or servers
// will settle on classical X25519.
assert_eq!(
kx_group_names(CryptoProviderKind::AwsLcRs),
[
NamedGroup::X25519MLKEM768,
NamedGroup::X25519,
NamedGroup::secp256r1,
NamedGroup::secp384r1,
]
);
}
}
17 changes: 17 additions & 0 deletions crates/base/test_cases/tls-key-exchange/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Fetches https://localhost:<x-port>, trusting the CA certificate sent as the
// request body, and relays the response text (or the error with a 500).
export default {
async fetch(req: Request) {
const port = req.headers.get("x-port");
const client = Deno.createHttpClient({ caCerts: [await req.text()] });

try {
const resp = await fetch(`https://localhost:${port}`, { client });
return new Response(await resp.text(), { status: resp.status });
} catch (err) {
return new Response(String(err), { status: 500 });
} finally {
client.close();
}
},
};
Loading
Loading