From 3a4f60f9f2b7ea27d9e6ff7c338ba459d8204ee4 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 02:57:49 -0800 Subject: [PATCH 1/2] chore(quest): claim quest/a1/rind/noq.md Quest-Claim: 0c1f0d889661366b From ab42f74fd13b15b3866415135f457200128e2812 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 03:07:59 -0800 Subject: [PATCH 2/2] feat(noq)!: checkpoint rind migration pending path-aware crypto Use rind TLS, initial protection and endpoint keys with fallible CPU checks. Preserve the quest and draft until rind-rustls publishes path-aware packet methods required by Noq. Co-Authored-By: GPT-6.1 Sol --- quest/a1/rind/noq.md | 4 + rs/web-transport-noq/Cargo.toml | 12 +- rs/web-transport-noq/README.md | 74 +++-- .../examples/echo-client-advanced.rs | 14 +- .../examples/echo-server-advanced.rs | 16 +- rs/web-transport-noq/src/client.rs | 53 ++-- rs/web-transport-noq/src/crypto.rs | 208 +++++++++++--- rs/web-transport-noq/src/crypto/keys.rs | 65 +++++ rs/web-transport-noq/src/error.rs | 22 +- rs/web-transport-noq/src/lib.rs | 22 ++ rs/web-transport-noq/src/server.rs | 22 +- rs/web-transport-noq/src/session.rs | 60 +++-- rs/web-transport-noq/tests/accept_wakers.rs | 11 - rs/web-transport-noq/tests/crypto.rs | 253 ++++++++++++++++++ 14 files changed, 691 insertions(+), 145 deletions(-) create mode 100644 rs/web-transport-noq/src/crypto/keys.rs create mode 100644 rs/web-transport-noq/tests/crypto.rs diff --git a/quest/a1/rind/noq.md b/quest/a1/rind/noq.md index 045f9d07..1352add3 100644 --- a/quest/a1/rind/noq.md +++ b/quest/a1/rind/noq.md @@ -9,3 +9,7 @@ web-transport-noq compiles no ring or aws-lc-rs: its builders run TLS on rind-ru Per rind's MIGRATING.md, noq 1.4's `rustls` feature works without `ring`. The client and server use `QuicClientConfig::with_initial` and `QuicServerConfig::with_initial`, which are public, with rind-rustls's TLS13_AES_128_GCM_SHA256 QUIC suite as the initial. `EndpointConfig::new` takes a reset `HmacKey` on rind's HMAC, and `ServerConfig::new` a `HandshakeTokenKey` on rind's HKDF and AES-256-GCM. noq-proto's Retry tag already uses pure-Rust aes-gcm. Replace `crypto::default_provider()` with the installed process provider, else rind. A CPU rind refuses returns an `UnsupportedCpu` error from the finishing methods, as [the Quinn child](/quest/a1/rind/quinn.md) does: `rind::cpu::check()` runs before the HMAC and token keys are built, even with an installed provider, and `Client::default()` documents its panic. Keep test-only ring in dev-dependencies only if a test needs it. Test a handshake and Retry against a ring-backed noq peer. + +## Waiting + +- moq-dev/rind: publish a stable `rind-rustls` version implementing rustls `PacketKey::encrypt_in_place_for_path` and `decrypt_in_place_for_path`, including path 0. Noq 1.4 calls these for every packet; `rind-rustls` 0.23.0 and rind main `6dbdebd578aa2c36b7109261009084148a183aad` inherit rustls's error-returning defaults, so the migration compiles but Noq panics before handshake completion. Update the dependency to that stable release and verify `rind_packet_keys_support_noq_path_api` and `ring_peer_handshake_and_retry` pass, then run the full local checks and cross-vendor review. Keep the migration draft until this clears; do not duplicate packet cryptography locally. diff --git a/rs/web-transport-noq/Cargo.toml b/rs/web-transport-noq/Cargo.toml index 5bf7234a..f8a47287 100644 --- a/rs/web-transport-noq/Cargo.toml +++ b/rs/web-transport-noq/Cargo.toml @@ -15,9 +15,6 @@ categories = ["network-programming", "web-programming"] all-features = true [features] -default = ["aws-lc-rs"] -aws-lc-rs = ["noq/aws-lc-rs", "rustls/aws-lc-rs"] -ring = ["noq/ring", "rustls/ring"] # Unlocks `noq::TransportConfig::qlog_*`, which this crate re-exports but cannot # enable on a caller's behalf. qlog = ["noq/qlog"] @@ -27,18 +24,20 @@ bytes = "1" futures = "0.3" http = "1" kio = "0.6.2" -noq = { version = "1", default-features = false, features = [ +noq = { version = "1.4", default-features = false, features = [ "tracing-log", - "platform-verifier", "runtime-tokio", "rustls", "bloom", ] } +rind = "0.2.1" +rind-rustls = "0.23" rustls = { version = "0.23", default-features = false, features = [ "logging", "std", ] } rustls-native-certs = "0.8" +socket2 = "0.6" thiserror = "2" tokio = { version = "1", default-features = false, features = [ "io-util", @@ -53,7 +52,10 @@ web-transport-trait = { workspace = true } [dev-dependencies] anyhow = "1" clap = { version = "4", features = ["derive"] } +noq = { version = "1.4", default-features = false, features = ["ring"] } rcgen = "0.14" +ring = "0.17" +rustls = { version = "0.23", default-features = false, features = ["ring"] } rustls-pemfile = "2" tokio = { version = "1", features = ["full", "test-util"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/rs/web-transport-noq/README.md b/rs/web-transport-noq/README.md index a6d7dc15..07bc9ca9 100644 --- a/rs/web-transport-noq/README.md +++ b/rs/web-transport-noq/README.md @@ -28,29 +28,73 @@ Both endpoints can send datagrams below the MTU size (~1.2kb minimum) and they m They are basically UDP packets, except they are encrypted and congestion controlled. # Usage -To use web-transport-noq, first you need to create a [noq::Endpoint](https://docs.rs/noq/latest/noq/struct.Endpoint.html); see the documentation and examples for more information. -The only requirement is that the ALPN is set to `web_transport_noq::ALPN` (aka `h3`). +Use `ClientBuilder` and `ServerBuilder` for WebTransport endpoints. Set the server's +certificate with `ServerBuilder::with_certificate`, and choose system roots or +certificate fingerprints when finishing the client builder. -Afterwards, you use [web_transport_noq::accept](https://docs.rs/web-transport-noq/latest/web_transport_noq/fn.accept.html) (as a server) or [web_transport_noq::connect](https://docs.rs/web-transport-noq/latest/web_transport_noq/fn.connect.html) (as a client) to establish a WebTransport session. -This will take over the QUIC connection and perform the boring HTTP/3 handshake for you. +```rust +# async fn example() -> Result<(), Box> { +let client = web_transport_noq::ClientBuilder::new().with_system_roots()?; +let session = client.connect(url::Url::parse("https://localhost:4433/")?).await?; +let (mut send, mut recv) = session.open_bi().await?; +send.write_all(b"hello").await?; +# Ok(()) +# } +``` -See the [examples](examples) or [moq-native](https://github.com/moq-dev/moq-rs/blob/main/moq-native/src/quic.rs) for a full setup. +See the [examples](examples) for full client and server setup. -```rust - // Create a QUIC client. - let mut endpoint = noq::Endpoint::client("[::]:0".parse()?)?; - endpoint.set_default_client_config(/* ... */); +## Crypto and CPU support - // Connect to the given URL. - let session = web_transport_noq::connect(&client, Url::parse("https://localhost")?).await?; +TLS uses `rind-rustls` unless the process has already installed a rustls +`CryptoProvider`, which takes precedence. QUIC initial packets and endpoint reset +and handshake-token keys always use rind. The `aws-lc-rs` and `ring` features are +removed; `qlog` remains available. Normal and build dependencies need no C crypto. - // Create a bidirectional stream. - let (mut send, mut recv) = session.open_bi().await?; +Rind supports the release architectures x86_64, aarch64 and armv7. It requires a +minimum CPU instruction set described in [rind's platforms](https://github.com/moq-dev/rind/blob/main/PLATFORMS.md). +Builders remain infallible to create and return `ClientError::UnsupportedCpu` or +`ServerError::UnsupportedCpu` from their finishing methods when that CPU check +fails, including with an installed provider. `Client::default()` unwraps setup and +can panic; use `ClientBuilder` to handle errors. - // Send a message. - send.write(b"hello").await?; +Advanced callers still use Noq's `crypto::rustls` types and `HandshakeData`. +Pass `crypto::initial_suite()?` to `QuicClientConfig::with_initial` or +`QuicServerConfig::with_initial`, rather than `try_from`, which depends on Noq's +built-in providers. Set ALPN to `web_transport_noq::ALPN` (`h3`) for WebTransport. +Use `crypto::endpoint_config()` for fresh reset keys and `crypto::server_config()` +for fresh Retry/validation-token keys. These helpers are fallible, as are +`crypto::default_provider()` and `crypto::sha256()`. + +```rust +# fn example(tls: rustls::ClientConfig) -> Result> { +use std::sync::Arc; +use web_transport_noq::{crypto, noq}; + +let tls = noq::crypto::rustls::QuicClientConfig::with_initial( + Arc::new(tls), crypto::initial_suite()?, +)?; +let client_config = noq::ClientConfig::new(Arc::new(tls)); +let endpoint = noq::Endpoint::new( + crypto::endpoint_config()?, + None, + std::net::UdpSocket::bind("0.0.0.0:0")?, + Arc::new(noq::TokioRuntime), +)?; +endpoint.set_default_client_config(client_config); +# Ok(endpoint) +# } ``` +For servers, wrap `QuicServerConfig::with_initial` in `crypto::server_config`, +then pass `Some(server_config)` to `Endpoint::new`. Bind sockets to match the +address families your application supports. Noq's `Endpoint::client`, +`Endpoint::server`, `EndpointConfig::default` and `ServerConfig::with_crypto` +require Noq's ring/aws-lc-rs features and are unavailable in this crate's normal +provider configuration. For persistent reset or token secrets, supply +`crypto::ResetKey` to `EndpointConfig::new` and `crypto::TokenKey` to +`ServerConfig::new`; each secret needs at least 32 bytes of entropy. + ## API The `web-transport-noq` API is almost identical to the Noq API, except that [Connection](https://docs.rs/noq/latest/noq/struct.Connection.html) is called [Session](https://docs.rs/web-transport-noq/latest/web_transport_noq/struct.Session.html). diff --git a/rs/web-transport-noq/examples/echo-client-advanced.rs b/rs/web-transport-noq/examples/echo-client-advanced.rs index d26c4971..2f08cae1 100644 --- a/rs/web-transport-noq/examples/echo-client-advanced.rs +++ b/rs/web-transport-noq/examples/echo-client-advanced.rs @@ -44,16 +44,24 @@ async fn main() -> anyhow::Result<()> { // Standard noq setup, accepting only the given certificate. // You should use system roots in production. let mut config = - rustls::ClientConfig::builder_with_provider(web_transport_noq::crypto::default_provider()) + rustls::ClientConfig::builder_with_provider(web_transport_noq::crypto::default_provider()?) .with_protocol_versions(&[&rustls::version::TLS13])? .with_root_certificates(roots) .with_no_client_auth(); config.alpn_protocols = vec![web_transport_noq::ALPN.as_bytes().to_vec()]; // this one is important - let config: noq::crypto::rustls::QuicClientConfig = config.try_into()?; + let config = noq::crypto::rustls::QuicClientConfig::with_initial( + Arc::new(config), + web_transport_noq::crypto::initial_suite()?, + )?; let config = noq::ClientConfig::new(Arc::new(config)); - let client = noq::Endpoint::client("[::]:0".parse()?)?; + let client = noq::Endpoint::new( + web_transport_noq::crypto::endpoint_config()?, + None, + std::net::UdpSocket::bind("[::]:0")?, + Arc::new(noq::TokioRuntime), + )?; let client = web_transport_noq::Client::new(client, config); // Connect to the given URL. diff --git a/rs/web-transport-noq/examples/echo-server-advanced.rs b/rs/web-transport-noq/examples/echo-server-advanced.rs index 84731290..6a8fb67d 100644 --- a/rs/web-transport-noq/examples/echo-server-advanced.rs +++ b/rs/web-transport-noq/examples/echo-server-advanced.rs @@ -63,7 +63,7 @@ async fn main() -> anyhow::Result<()> { // Standard Noq setup let mut config = - rustls::ServerConfig::builder_with_provider(web_transport_noq::crypto::default_provider()) + rustls::ServerConfig::builder_with_provider(web_transport_noq::crypto::default_provider()?) .with_protocol_versions(&[&rustls::version::TLS13])? .with_no_client_auth() .with_single_cert(chain, key)?; @@ -71,12 +71,20 @@ async fn main() -> anyhow::Result<()> { config.max_early_data_size = u32::MAX; config.alpn_protocols = vec![web_transport_noq::ALPN.as_bytes().to_vec()]; // this one is important - let config: noq::crypto::rustls::QuicServerConfig = config.try_into()?; - let config = noq::ServerConfig::with_crypto(Arc::new(config)); + let config = noq::crypto::rustls::QuicServerConfig::with_initial( + Arc::new(config), + web_transport_noq::crypto::initial_suite()?, + )?; + let config = web_transport_noq::crypto::server_config(Arc::new(config))?; tracing::info!(addr = %args.addr, "listening"); - let server = noq::Endpoint::server(config, args.addr)?; + let server = noq::Endpoint::new( + web_transport_noq::crypto::endpoint_config()?, + Some(config), + std::net::UdpSocket::bind(args.addr)?, + Arc::new(noq::TokioRuntime), + )?; // Accept new connections. while let Some(conn) = server.accept().await { diff --git a/rs/web-transport-noq/src/client.rs b/rs/web-transport-noq/src/client.rs index c3dcee47..837ad053 100644 --- a/rs/web-transport-noq/src/client.rs +++ b/rs/web-transport-noq/src/client.rs @@ -2,14 +2,12 @@ use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use crate::proto::ConnectRequest; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use noq::crypto::rustls::QuicClientConfig; use rustls::{client::danger::ServerCertVerifier, pki_types::CertificateDer}; use tokio::net::lookup_host; use url::Host; use crate::crypto; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use crate::ALPN; use crate::{ClientError, Session}; @@ -25,18 +23,16 @@ pub enum CongestionControl { LowLatency, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] /// Construct a WebTransport [Client] using sane defaults. /// /// This is optional; advanced users may use [Client::new] directly. #[derive(Clone)] pub struct ClientBuilder { - provider: crypto::Provider, + provider: Result, congestion_controller: Option>, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl ClientBuilder { /// Create a Client builder, which can be used to establish multiple [Session]s. pub fn new() -> Self { @@ -79,7 +75,7 @@ impl ClientBuilder { } let crypto = self - .builder() + .builder()? .with_root_certificates(roots) .with_no_client_auth(); @@ -91,12 +87,12 @@ impl ClientBuilder { self, certs: Vec, ) -> Result { - let hashes = certs.iter().map({ - let provider = self.provider.clone(); - move |cert| crypto::sha256(&provider, cert).as_ref().to_vec() - }); + let provider = self.provider.clone()?; + let hashes = certs + .iter() + .map(|cert| crypto::sha256(&provider, cert).map(|hash| hash.as_ref().to_vec())); - self.with_server_certificate_hashes(hashes.collect()) + self.with_server_certificate_hashes(hashes.collect::>()?) } /// Supply sha256 hashes for accepted certificates instead of using root CAs. @@ -106,13 +102,13 @@ impl ClientBuilder { ) -> Result { // Use a custom fingerprint verifier. let fingerprints = Arc::new(ServerFingerprints { - provider: self.provider.clone(), + provider: self.provider.clone()?, fingerprints: hashes, }); // Configure the crypto client. let crypto = self - .builder() + .builder()? .dangerous() .with_custom_certificate_verifier(fingerprints.clone()) .with_no_client_auth(); @@ -129,16 +125,22 @@ impl ClientBuilder { DangerousClientBuilder { inner: self } } - fn builder(&self) -> rustls::ConfigBuilder { - rustls::ClientConfig::builder_with_provider(self.provider.clone()) - .with_protocol_versions(&[&rustls::version::TLS13]) - .unwrap() + fn builder( + &self, + ) -> Result, ClientError> + { + Ok( + rustls::ClientConfig::builder_with_provider(self.provider.clone()?) + .with_protocol_versions(&[&rustls::version::TLS13])?, + ) } fn build(self, mut crypto: rustls::ClientConfig) -> Result { crypto.alpn_protocols = vec![ALPN.as_bytes().to_vec()]; - let client_config = QuicClientConfig::try_from(crypto).unwrap(); + let client_config = + QuicClientConfig::with_initial(Arc::new(crypto), crypto::initial_suite()?) + .expect("rind initial suite is AES-128-GCM-SHA256"); let mut client_config = noq::ClientConfig::new(Arc::new(client_config)); let mut transport = noq::TransportConfig::default(); @@ -148,7 +150,8 @@ impl ClientBuilder { client_config.transport_config(transport.into()); - let client = noq::Endpoint::client("[::]:0".parse().unwrap()).unwrap(); + let client = crate::endpoint(crypto::endpoint_config()?, None, "[::]:0".parse().unwrap()) + .map_err(|e| ClientError::IoError(Arc::new(e)))?; Ok(Client { endpoint: client, config: client_config, @@ -156,14 +159,12 @@ impl ClientBuilder { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl Default for ClientBuilder { fn default() -> Self { Self::new() } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] /// Builder for dangerous TLS configuration options. /// /// This builder provides access to potentially insecure TLS configurations. @@ -173,7 +174,6 @@ pub struct DangerousClientBuilder { inner: ClientBuilder, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl DangerousClientBuilder { /// Disable certificate verification entirely. /// @@ -183,11 +183,11 @@ impl DangerousClientBuilder { /// This method is safe in the Rust sense (no memory unsafety), but dangerous in the /// security sense, hence the explicit `dangerous()` builder requirement. pub fn with_no_certificate_verification(self) -> Result { - let noop = NoCertificateVerification(self.inner.provider.clone()); + let noop = NoCertificateVerification(self.inner.provider.clone()?); let crypto = self .inner - .builder() + .builder()? .dangerous() .with_custom_certificate_verifier(Arc::new(noop)) .with_no_client_auth(); @@ -257,14 +257,13 @@ impl Client { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +/// Panics if endpoint setup fails, including on a CPU rind does not support. impl Default for Client { fn default() -> Self { ClientBuilder::new().with_system_roots().unwrap() } } -#[cfg_attr(not(any(feature = "aws-lc-rs", feature = "ring")), allow(dead_code))] #[derive(Debug)] struct ServerFingerprints { provider: crypto::Provider, @@ -280,7 +279,7 @@ impl ServerCertVerifier for ServerFingerprints { _ocsp_response: &[u8], _now: rustls::pki_types::UnixTime, ) -> Result { - let cert_hash = crypto::sha256(&self.provider, end_entity); + let cert_hash = crypto::sha256(&self.provider, end_entity)?; if self .fingerprints .iter() diff --git a/rs/web-transport-noq/src/crypto.rs b/rs/web-transport-noq/src/crypto.rs index 224abc43..0d4c910b 100644 --- a/rs/web-transport-noq/src/crypto.rs +++ b/rs/web-transport-noq/src/crypto.rs @@ -1,65 +1,187 @@ -//! Simple crypto provider utilities for rustls. +//! Rind TLS and endpoint keys for Noq, with installed rustls provider precedence. //! -//! This module provides helper functions for working with rustls crypto providers, -//! supporting both ring and aws-lc-rs backends. +//! Pass [`initial_suite`] to Noq's `QuicClientConfig::with_initial` and +//! `QuicServerConfig::with_initial`, [`endpoint_config`] to `noq::Endpoint::new`, +//! and use [`server_config`] instead of `noq::ServerConfig::with_crypto`. use std::sync::Arc; use rustls::crypto::hash::{self, HashAlgorithm}; use rustls::crypto::CryptoProvider; use rustls::pki_types::CertificateDer; +use thiserror::Error; + +mod keys; +pub use keys::{ResetKey, TokenKey}; /// A shared reference to a crypto provider. pub type Provider = Arc; -/// Returns the default crypto provider. -/// -/// This function checks for a process-wide default provider first, -/// then falls back to feature-enabled providers (aws-lc-rs or ring). -/// -/// # Panics -/// -/// Panics if no provider is available. Either call `CryptoProvider::set_default()` -/// or enable exactly one of the `ring` or `aws-lc-rs` features. -pub fn default_provider() -> Provider { - // See - if let Some(provider) = CryptoProvider::get_default().cloned() { - return provider; - } +/// A CPU feature required by rind is unavailable. +#[derive(Clone, Debug, Error)] +#[error("unsupported CPU: {0}")] +pub struct UnsupportedCpu(pub(crate) String); - #[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] - { - return Arc::new(rustls::crypto::aws_lc_rs::default_provider()); - } - #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] - { - return Arc::new(rustls::crypto::ring::default_provider()); +/// An error constructing QUIC cryptography. +#[derive(Clone, Debug, Error)] +#[non_exhaustive] +pub enum ConfigError { + /// A CPU feature required by rind is unavailable. + #[error(transparent)] + UnsupportedCpu(#[from] UnsupportedCpu), + /// The system random source failed. + #[error("system random source failed")] + Random, +} + +/// Checks CPU support before using rind, including with an installed TLS provider. +fn check_cpu() -> Result<(), UnsupportedCpu> { + #[cfg(test)] + if REFUSE_CPU.get() { + return Err(UnsupportedCpu("simulated missing CPU feature".into())); } - #[allow(unreachable_code)] - { - panic!( - "CryptoProvider::set_default() must be called; or only enable one ring/aws-lc-rs feature." - ); + rind::cpu::check().map_err(|e| UnsupportedCpu(e.to_string())) +} + +/// Returns the installed process provider, otherwise rind, after checking CPU support. +pub fn default_provider() -> Result { + check_cpu()?; + if let Some(provider) = CryptoProvider::get_default().cloned() { + return Ok(provider); } + rind_rustls::default_provider() + .map(Arc::new) + .map_err(|e| UnsupportedCpu(e.to_string())) +} + +/// Returns rind's QUIC AES-128-GCM-SHA256 initial suite after checking CPU support. +pub fn initial_suite() -> Result { + check_cpu()?; + Ok(rind_rustls::cipher_suite::TLS13_AES_128_GCM_SHA256 + .tls13() + .expect("TLS 1.3 suite") + .quic_suite() + .expect("QUIC suite")) +} + +/// Creates endpoint configuration with a fresh rind stateless-reset key. +pub fn endpoint_config() -> Result { + check_cpu()?; + let mut secret = [0; 64]; + rind::rand::fill(&mut secret).map_err(|_| ConfigError::Random)?; + Ok(noq::EndpointConfig::new(Arc::new(ResetKey::new(&secret)?))) +} + +/// Creates server configuration with a fresh rind handshake-token key. +pub fn server_config( + crypto: Arc, +) -> Result { + check_cpu()?; + let mut secret = [0; 64]; + rind::rand::fill(&mut secret).map_err(|_| ConfigError::Random)?; + Ok(noq::ServerConfig::new( + crypto, + Arc::new(TokenKey::new(&secret)?), + )) } /// Computes the SHA-256 hash of a certificate using the provided crypto provider. -/// -/// # Panics -/// -/// Panics if the provider doesn't expose a SHA-256 hash algorithm. -pub fn sha256(provider: &Provider, cert: &CertificateDer<'_>) -> hash::Output { +pub fn sha256( + provider: &Provider, + cert: &CertificateDer<'_>, +) -> Result { let hash_provider = provider.cipher_suites.iter().find_map(|suite| { let hash_provider = suite.tls13()?.common.hash_provider; - if hash_provider.algorithm() == HashAlgorithm::SHA256 { - Some(hash_provider) - } else { - None - } + (hash_provider.algorithm() == HashAlgorithm::SHA256).then_some(hash_provider) }); - if let Some(hash_provider) = hash_provider { - return hash_provider.hash(cert); - } + Ok(hash_provider + .ok_or_else(|| rustls::Error::General("provider has no SHA-256 hash".into()))? + .hash(cert)) +} - panic!("No SHA-256 backend available. Ensure your provider exposes SHA-256 or enable the 'ring'/'aws-lc-rs' feature."); +#[cfg(test)] +thread_local! { + static REFUSE_CPU: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn installed_provider_and_cpu_refusal() { + // Isolate the process-wide provider from every other test in this binary. + const CHILD: &str = "WEB_TRANSPORT_NOQ_PROVIDER_TEST_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "crypto::tests::installed_provider_and_cpu_refusal", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + return; + } + rustls::crypto::ring::default_provider() + .install_default() + .expect("only this test installs a provider"); + let provider = CryptoProvider::get_default().unwrap().clone(); + assert!(Arc::ptr_eq(&default_provider().unwrap(), &provider)); + let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()); + let server_tls = rustls::ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![cert.cert.der().clone()], key.clone_key().into()) + .unwrap(); + let server = Arc::new( + noq::crypto::rustls::QuicServerConfig::with_initial( + Arc::new(server_tls), + initial_suite().unwrap(), + ) + .unwrap(), + ); + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + REFUSE_CPU.set(false); + } + } + let _reset = Reset; + REFUSE_CPU.set(true); + assert!( + default_provider().is_err(), + "installed provider must not bypass rind's CPU check" + ); + assert!(endpoint_config().is_err()); + assert!(server_config(server).is_err()); + assert!(ResetKey::new(&[0; 64]).is_err()); + assert!(TokenKey::new(&[0; 64]).is_err()); + assert!(initial_suite().is_err()); + assert!(matches!( + crate::ClientBuilder::new().with_system_roots(), + Err(crate::ClientError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ClientBuilder::new().with_server_certificates(vec![]), + Err(crate::ClientError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ClientBuilder::new().with_server_certificate_hashes(vec![]), + Err(crate::ClientError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ClientBuilder::new() + .dangerous() + .with_no_certificate_verification(), + Err(crate::ClientError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ServerBuilder::new().with_certificate(vec![], key.into()), + Err(crate::ServerError::UnsupportedCpu(_)) + )); + } } diff --git a/rs/web-transport-noq/src/crypto/keys.rs b/rs/web-transport-noq/src/crypto/keys.rs new file mode 100644 index 00000000..f11f9752 --- /dev/null +++ b/rs/web-transport-noq/src/crypto/keys.rs @@ -0,0 +1,65 @@ +use noq::crypto::{CryptoError, HandshakeTokenKey, HmacKey}; +use rind::{aead, hkdf, hmac}; + +use super::{check_cpu, UnsupportedCpu}; + +/// A rind HMAC-SHA256 key for Noq stateless resets. +pub struct ResetKey(hmac::Key); + +impl ResetKey { + /// Uses a persistent secret to reproduce reset tokens across endpoint restarts. + pub fn new(secret: &[u8]) -> Result { + check_cpu()?; + Ok(Self(hmac::Key::new(&hmac::HMAC_SHA256, secret))) + } +} + +impl HmacKey for ResetKey { + fn sign(&self, data: &[u8], out: &mut [u8]) { + out.copy_from_slice(hmac::sign(&self.0, data).as_ref()); + } + + fn signature_len(&self) -> usize { + 32 + } + + fn verify(&self, data: &[u8], signature: &[u8]) -> Result<(), CryptoError> { + hmac::verify(&self.0, data, signature).map_err(|_| CryptoError) + } +} + +/// A rind HKDF-SHA256 key for Noq Retry and validation tokens. +pub struct TokenKey(hkdf::Prk); + +impl TokenKey { + /// Derives a token key from a secret with at least 32 bytes of entropy. + pub fn new(secret: &[u8]) -> Result { + check_cpu()?; + Ok(Self( + hkdf::Salt::new(&hkdf::HKDF_SHA256, &[]).extract(secret), + )) + } + + fn aead(&self, token_nonce: u128) -> aead::Key { + aead::Key::from( + self.0 + .expand(&[&token_nonce.to_le_bytes()], &aead::AES_256_GCM), + ) + } +} + +impl HandshakeTokenKey for TokenKey { + fn seal(&self, token_nonce: u128, data: &mut Vec) -> Result<(), CryptoError> { + // Noq supplies a fresh 128-bit random nonce per token, deriving a single-use key. + self.aead(token_nonce) + .seal_in_place_append_tag(aead::Nonce::assume_unique_for_key([0; 12]), &[], data) + .map_err(|_| CryptoError) + } + + fn open<'a>(&self, token_nonce: u128, data: &'a mut [u8]) -> Result<&'a [u8], CryptoError> { + self.aead(token_nonce) + .open_in_place(aead::Nonce::assume_unique_for_key([0; 12]), &[], data) + .map(|plaintext| &*plaintext) + .map_err(|_| CryptoError) + } +} diff --git a/rs/web-transport-noq/src/error.rs b/rs/web-transport-noq/src/error.rs index 804b88cc..eb2d2054 100644 --- a/rs/web-transport-noq/src/error.rs +++ b/rs/web-transport-noq/src/error.rs @@ -7,6 +7,18 @@ use crate::{ConnectError, SettingsError}; /// An error returned when connecting to a WebTransport endpoint. #[derive(Error, Debug, Clone)] pub enum ClientError { + /// Creating or binding the endpoint failed. + #[error("I/O error: {0}")] + IoError(Arc), + + /// A CPU feature required by rind is unavailable. + #[error(transparent)] + UnsupportedCpu(#[from] crate::crypto::UnsupportedCpu), + + /// Constructing QUIC cryptography failed. + #[error(transparent)] + Crypto(#[from] crate::crypto::ConfigError), + #[error("unexpected end of stream")] UnexpectedEnd, @@ -31,7 +43,6 @@ pub enum ClientError { #[error("invalid DNS name: {0}")] InvalidDnsName(String), - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] #[error("rustls error: {0}")] Rustls(#[from] rustls::Error), } @@ -199,6 +210,14 @@ impl From for ClosedStream { /// An error returned when receiving a new WebTransport session. #[derive(Error, Debug, Clone)] pub enum ServerError { + /// A CPU feature required by rind is unavailable. + #[error(transparent)] + UnsupportedCpu(#[from] crate::crypto::UnsupportedCpu), + + /// Constructing QUIC cryptography failed. + #[error(transparent)] + Crypto(#[from] crate::crypto::ConfigError), + #[error("unexpected end of stream")] UnexpectedEnd, @@ -220,7 +239,6 @@ pub enum ServerError { #[error("io error: {0}")] IoError(Arc), - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] #[error("rustls error: {0}")] Rustls(#[from] rustls::Error), } diff --git a/rs/web-transport-noq/src/lib.rs b/rs/web-transport-noq/src/lib.rs index 2183a1f7..94f3c4ae 100644 --- a/rs/web-transport-noq/src/lib.rs +++ b/rs/web-transport-noq/src/lib.rs @@ -69,3 +69,25 @@ pub use web_transport_trait as generic; /// Re-export the WebTransport protocol implementation. pub use web_transport_proto as proto; + +// Match Noq's socket setup while supplying provider-independent endpoint keys. +fn endpoint( + config: noq::EndpointConfig, + server: Option, + addr: std::net::SocketAddr, +) -> std::io::Result { + let socket = socket2::Socket::new( + socket2::Domain::for_address(addr), + socket2::Type::DGRAM, + Some(socket2::Protocol::UDP), + )?; + if addr.is_ipv6() { + if let Err(error) = socket.set_only_v6(false) { + tracing::debug!(%error, "unable to make socket dual-stack"); + } + } + socket.bind(&addr.into())?; + let runtime = + noq::default_runtime().ok_or_else(|| std::io::Error::other("no async runtime found"))?; + noq::Endpoint::new(config, server, socket.into(), runtime) +} diff --git a/rs/web-transport-noq/src/server.rs b/rs/web-transport-noq/src/server.rs index ead0dac9..0c3fa8df 100644 --- a/rs/web-transport-noq/src/server.rs +++ b/rs/web-transport-noq/src/server.rs @@ -1,36 +1,30 @@ -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use std::sync::Arc; use futures::{future::BoxFuture, stream::FuturesUnordered, StreamExt}; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use rustls::pki_types::{CertificateDer, PrivateKeyDer}; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use crate::{crypto, CongestionControl}; use crate::{ proto::{ConnectRequest, ConnectResponse}, Connecting, ServerError, Session, Settings, }; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] /// Construct a WebTransport [Server] using sane defaults. /// /// This is optional; advanced users may use [Server::new] directly. pub struct ServerBuilder { - provider: crypto::Provider, + provider: Result, addr: std::net::SocketAddr, congestion_controller: Option>, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl Default for ServerBuilder { fn default() -> Self { Self::new() } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl ServerBuilder { /// Create a server builder with sane defaults. pub fn new() -> Self { @@ -68,18 +62,22 @@ impl ServerBuilder { key: PrivateKeyDer<'static>, ) -> Result { // Standard Noq setup - let mut config = rustls::ServerConfig::builder_with_provider(self.provider.clone()) + let mut config = rustls::ServerConfig::builder_with_provider(self.provider.clone()?) .with_protocol_versions(&[&rustls::version::TLS13])? .with_no_client_auth() .with_single_cert(chain, key)?; config.alpn_protocols = vec![crate::ALPN.as_bytes().to_vec()]; // this one is important - let config: noq::crypto::rustls::QuicServerConfig = config.try_into().unwrap(); - let config = noq::ServerConfig::with_crypto(Arc::new(config)); + let config = noq::crypto::rustls::QuicServerConfig::with_initial( + Arc::new(config), + crypto::initial_suite()?, + ) + .expect("rind initial suite is AES-128-GCM-SHA256"); + let config = crypto::server_config(Arc::new(config))?; - let server = - noq::Endpoint::server(config, self.addr).map_err(|e| ServerError::IoError(e.into()))?; + let server = crate::endpoint(crypto::endpoint_config()?, Some(config), self.addr) + .map_err(|e| ServerError::IoError(e.into()))?; Ok(Server::new(server)) } diff --git a/rs/web-transport-noq/src/session.rs b/rs/web-transport-noq/src/session.rs index cfe6fb73..9ee2c45a 100644 --- a/rs/web-transport-noq/src/session.rs +++ b/rs/web-transport-noq/src/session.rs @@ -23,7 +23,6 @@ use crate::{ /// /// Noq only exposes the ALPN via a downcast of the boxed handshake data, so the result /// is owned rather than borrowed from the connection. -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] fn negotiated_alpn(conn: &noq::Connection) -> Option { let data = conn.handshake_data()?; let data = data.downcast::().ok()?; @@ -31,19 +30,6 @@ fn negotiated_alpn(conn: &noq::Connection) -> Option { String::from_utf8(data.protocol?).ok() } -/// `noq::crypto::rustls` only exists once a TLS backend is enabled, so there is no -/// handshake data type to name here. -/// -/// This crate's own builders are gated the same way, so normally there is no connection -/// to read an ALPN from either. A caller that enables a provider on `noq` directly and -/// brings its own endpoint can still establish one, and [`Session::protocol`] reports -/// `None` for those raw sessions. Enable this crate's `aws-lc-rs` or `ring` feature to -/// get the ALPN. -#[cfg(not(any(feature = "aws-lc-rs", feature = "ring")))] -fn negotiated_alpn(_conn: &noq::Connection) -> Option { - None -} - /// An established WebTransport session, acting like a full QUIC connection. See [`noq::Connection`]. /// /// It is important to remember that WebTransport is layered on top of QUIC: @@ -1151,7 +1137,7 @@ impl web_transport_trait::Session for Session { } } -#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(test)] mod tests { use std::{ net::Ipv4Addr, @@ -1194,25 +1180,53 @@ mod tests { transport: noq::TransportConfig, peer_transport: noq::TransportConfig, ) -> [noq::Endpoint; 2] { - #[cfg(all(feature = "aws-lc-rs", feature = "ring"))] - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - let CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(KeyPair::serialize_der( &signing_key, ))); - let mut server_config = - noq::ServerConfig::with_single_cert(vec![cert.der().clone()], key).unwrap(); + let provider = crate::crypto::default_provider().unwrap(); + let tls = rustls::ServerConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![cert.der().clone()], key) + .unwrap(); + let crypto = noq::crypto::rustls::QuicServerConfig::with_initial( + Arc::new(tls), + crate::crypto::initial_suite().unwrap(), + ) + .unwrap(); + let mut server_config = crate::crypto::server_config(Arc::new(crypto)).unwrap(); server_config.transport_config(Arc::new(peer_transport)); - let server = noq::Endpoint::server(server_config, (Ipv4Addr::LOCALHOST, 0).into()).unwrap(); + let server = crate::endpoint( + crate::crypto::endpoint_config().unwrap(), + Some(server_config), + (Ipv4Addr::LOCALHOST, 0).into(), + ) + .unwrap(); let mut roots = rustls::RootCertStore::empty(); roots.add(cert.der().clone()).unwrap(); - let mut client_config = noq::ClientConfig::with_root_certificates(Arc::new(roots)).unwrap(); + let tls = rustls::ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + let crypto = noq::crypto::rustls::QuicClientConfig::with_initial( + Arc::new(tls), + crate::crypto::initial_suite().unwrap(), + ) + .unwrap(); + let mut client_config = noq::ClientConfig::new(Arc::new(crypto)); client_config.transport_config(Arc::new(transport)); - let client = noq::Endpoint::client((Ipv4Addr::LOCALHOST, 0).into()).unwrap(); + let client = crate::endpoint( + crate::crypto::endpoint_config().unwrap(), + None, + (Ipv4Addr::LOCALHOST, 0).into(), + ) + .unwrap(); client.set_default_client_config(client_config); [client, server] } diff --git a/rs/web-transport-noq/tests/accept_wakers.rs b/rs/web-transport-noq/tests/accept_wakers.rs index a30fb08d..08dd56d7 100644 --- a/rs/web-transport-noq/tests/accept_wakers.rs +++ b/rs/web-transport-noq/tests/accept_wakers.rs @@ -57,19 +57,8 @@ impl Wake for FlagWaker { } } -/// With both crypto features enabled — as `--all-features` does — the crate cannot -/// pick a provider for us, so the test installs one. -fn install_crypto_provider() { - #[cfg(all(feature = "aws-lc-rs", feature = "ring"))] - { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - } -} - /// A client and server session, already connected. async fn pair() -> Result<(web_transport_noq::Session, web_transport_noq::Session)> { - install_crypto_provider(); - let CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed(vec!["localhost".into(), "127.0.0.1".into()])?; let chain = vec![cert.der().clone()]; diff --git a/rs/web-transport-noq/tests/crypto.rs b/rs/web-transport-noq/tests/crypto.rs new file mode 100644 index 00000000..5ad4a343 --- /dev/null +++ b/rs/web-transport-noq/tests/crypto.rs @@ -0,0 +1,253 @@ +//! Rind endpoint keys and TLS interoperate with an independently configured ring peer. + +use std::{net::Ipv4Addr, sync::Arc, time::Duration}; + +use noq::crypto::{HandshakeTokenKey, HmacKey}; +use rustls::{pki_types::PrivatePkcs8KeyDer, CipherSuite}; +use web_transport_noq::{crypto, noq}; + +fn endpoint(server: Option, ours: bool) -> noq::Endpoint { + noq::Endpoint::new( + if ours { + crypto::endpoint_config().unwrap() + } else { + noq::EndpointConfig::default() + }, + server, + std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(), + Arc::new(noq::TokioRuntime), + ) + .unwrap() +} + +async fn handshake(ours_server: bool, suite: CipherSuite, retry: bool) { + let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let mut ours = rind_rustls::default_provider().unwrap(); + let mut ring = rustls::crypto::ring::default_provider(); + // Excluding AES-128 from traffic also exercises the separate initial suite. + for provider in [&mut ours, &mut ring] { + provider.cipher_suites.retain(|s| s.suite() == suite); + } + let (client_provider, server_provider) = if ours_server { + (ring, ours) + } else { + (ours, ring) + }; + let mut tls = rustls::ServerConfig::builder_with_provider(Arc::new(server_provider)) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![cert.cert.der().clone()], + PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()).into(), + ) + .unwrap(); + tls.alpn_protocols = vec![b"h3".to_vec()]; + let server_crypto = if ours_server { + noq::crypto::rustls::QuicServerConfig::with_initial( + Arc::new(tls), + crypto::initial_suite().unwrap(), + ) + .unwrap() + } else { + noq::crypto::rustls::QuicServerConfig::with_initial( + Arc::new(tls), + rustls::crypto::ring::cipher_suite::TLS13_AES_128_GCM_SHA256 + .tls13() + .unwrap() + .quic_suite() + .unwrap(), + ) + .unwrap() + }; + let server_config = if ours_server { + crypto::server_config(Arc::new(server_crypto)).unwrap() + } else { + noq::ServerConfig::with_crypto(Arc::new(server_crypto)) + }; + let server = endpoint(Some(server_config), ours_server); + let mut roots = rustls::RootCertStore::empty(); + roots.add(cert.cert.der().clone()).unwrap(); + let mut tls = rustls::ClientConfig::builder_with_provider(Arc::new(client_provider)) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + tls.alpn_protocols = vec![b"h3".to_vec()]; + let initial = if ours_server { + rustls::crypto::ring::cipher_suite::TLS13_AES_128_GCM_SHA256 + .tls13() + .unwrap() + .quic_suite() + .unwrap() + } else { + crypto::initial_suite().unwrap() + }; + let client_config = noq::ClientConfig::new(Arc::new( + noq::crypto::rustls::QuicClientConfig::with_initial(Arc::new(tls), initial).unwrap(), + )); + let client = endpoint(None, !ours_server); + let connect = client + .connect_with(client_config, server.local_addr().unwrap(), "localhost") + .unwrap(); + let accept = async { + let mut incoming = server.accept().await.unwrap(); + if retry { + assert!(!incoming.remote_address_validated()); + incoming.retry().unwrap(); + incoming = server.accept().await.unwrap(); + assert!(incoming.remote_address_validated()); + } + incoming.await.unwrap() + }; + let (client_conn, server_conn) = tokio::join!(async { connect.await.unwrap() }, accept); + let mut exported = [[0; 32]; 2]; + for (conn, output) in [&client_conn, &server_conn].into_iter().zip(&mut exported) { + conn.export_keying_material(output, b"test", b"context") + .unwrap(); + let data = conn + .handshake_data() + .unwrap() + .downcast::() + .unwrap(); + assert_eq!(data.protocol.as_deref(), Some(b"h3".as_slice())); + } + assert_eq!(exported[0], exported[1]); + for (sender, receiver) in [(&client_conn, &server_conn), (&server_conn, &client_conn)] { + let mut send = sender.open_uni().await.unwrap(); + send.write_all(b"rind and ring").await.unwrap(); + send.finish().unwrap(); + assert_eq!( + receiver + .accept_uni() + .await + .unwrap() + .read_to_end(64) + .await + .unwrap(), + b"rind and ring" + ); + } + client.close(0u32.into(), b"done"); + server.close(0u32.into(), b"done"); + tokio::join!(client.wait_idle(), server.wait_idle()); +} + +#[tokio::test] +async fn ring_peer_handshake_and_retry() { + for suite in [ + CipherSuite::TLS13_AES_128_GCM_SHA256, + CipherSuite::TLS13_AES_256_GCM_SHA384, + CipherSuite::TLS13_CHACHA20_POLY1305_SHA256, + ] { + for ours_server in [false, true] { + for retry in [false, true] { + tokio::time::timeout( + Duration::from_secs(10), + handshake(ours_server, suite, retry), + ) + .await + .expect("loopback handshake and transfer"); + } + } + } +} + +#[test] +fn reset_hmac_matches_ring_and_rejects_invalid_signatures() { + let secret = [42; 64]; + let key = crypto::ResetKey::new(&secret).unwrap(); + let ring_key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, &secret); + let mut signature = vec![0; key.signature_len()]; + key.sign(b"connection ID", &mut signature); + assert_eq!( + signature, + ring::hmac::sign(&ring_key, b"connection ID").as_ref() + ); + key.verify(b"connection ID", &signature).unwrap(); + assert!(key.verify(b"other ID", &signature).is_err()); + assert!(key.verify(b"connection ID", &signature[..16]).is_err()); + signature[0] ^= 1; + assert!(key.verify(b"connection ID", &signature).is_err()); +} + +#[test] +fn token_encryption_matches_noq_ring_construction_and_authenticates() { + let secret = [42; 64]; + let key = crypto::TokenKey::new(&secret).unwrap(); + let nonce = 0x102030405060708090a0b0c0d0e0f000u128; + // Match noq-proto 1.4's HKDF-SHA256 and little-endian 128-bit nonce. + let master = ring::hkdf::Salt::new(ring::hkdf::HKDF_SHA256, &[]).extract(&secret); + let nonce_bytes = nonce.to_le_bytes(); + let info = [&nonce_bytes[..]]; + let mut derived = [0; 32]; + master + .expand(&info, ring::hkdf::HKDF_SHA256) + .unwrap() + .fill(&mut derived) + .unwrap(); + let ring_key = ring::aead::LessSafeKey::new( + ring::aead::UnboundKey::new(&ring::aead::AES_256_GCM, &derived).unwrap(), + ); + let mut expected = b"address and connection ID".to_vec(); + ring_key + .seal_in_place_append_tag( + ring::aead::Nonce::assume_unique_for_key([0; 12]), + ring::aead::Aad::empty(), + &mut expected, + ) + .unwrap(); + let mut sealed = b"address and connection ID".to_vec(); + key.seal(nonce, &mut sealed).unwrap(); + assert_eq!(sealed, expected); + assert_eq!( + key.open(nonce, &mut sealed.clone()).unwrap(), + b"address and connection ID" + ); + assert!(key.open(nonce ^ 1, &mut sealed.clone()).is_err()); + assert!(crypto::TokenKey::new(&[43; 64]) + .unwrap() + .open(nonce, &mut sealed.clone()) + .is_err()); + for index in [0, sealed.len() - 1] { + let mut modified = sealed.clone(); + modified[index] ^= 1; + assert!(key.open(nonce, &mut modified).is_err()); + } + for length in [0, 15, sealed.len() - 1] { + assert!(key.open(nonce, &mut sealed[..length].to_vec()).is_err()); + } +} + +#[test] +fn rind_packet_keys_support_noq_path_api() { + for suite in [ + rind_rustls::cipher_suite::TLS13_AES_128_GCM_SHA256, + rind_rustls::cipher_suite::TLS13_AES_256_GCM_SHA384, + rind_rustls::cipher_suite::TLS13_CHACHA20_POLY1305_SHA256, + ] { + let suite = suite.tls13().unwrap().quic_suite().unwrap(); + let keys = suite.keys( + b"connection ID", + rustls::Side::Client, + rustls::quic::Version::V1, + ); + // Noq uses these methods even for the initial path, whose ID is zero. + for path in [0, 1, u32::MAX] { + let mut payload = b"packet payload".to_vec(); + let tag = keys + .local + .packet + .encrypt_in_place_for_path(path, 7, b"header", &mut payload) + .expect("Noq requires path-aware packet encryption"); + payload.extend_from_slice(tag.as_ref()); + assert_eq!( + keys.local + .packet + .decrypt_in_place_for_path(path, 7, b"header", &mut payload) + .expect("Noq requires path-aware packet decryption"), + b"packet payload" + ); + } + } +}