diff --git a/Cargo.lock b/Cargo.lock index 884ded34ab1..41d75cbfa4f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4945,7 +4945,6 @@ name = "moq-auth" version = "0.2.1" dependencies = [ "anyhow", - "aws-lc-rs", "axum", "base64 0.23.1", "bench-harness", @@ -4956,13 +4955,15 @@ dependencies = [ "moq-auth 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "moq-pattern 0.1.2", "moq-token", - "p256", - "p384", "pkcs1", "pkcs8 0.11.0", "rand 0.10.3", "reqwest", + "rind", + "rind-jsonwebtoken", + "rind-rustls", "rustls", + "rustls-platform-verifier", "serde", "serde_json", "serde_with", @@ -8552,6 +8553,17 @@ dependencies = [ "libcrux-traits", ] +[[package]] +name = "rind-jsonwebtoken" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3dbbb3e3d229205e18f9a5b3ee418071a29eacdb61aec66a5f34eeffef8e55f" +dependencies = [ + "jsonwebtoken", + "pkcs1", + "rind", +] + [[package]] name = "rind-object-store" version = "0.1.2" @@ -12412,6 +12424,7 @@ dependencies = [ "hyper-util", "indexmap 2.14.2", "itertools 0.13.0", + "jsonwebtoken", "lazy_static", "libc", "libspa", diff --git a/Cargo.toml b/Cargo.toml index fd42fd2a7ff..9ae72233a8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -205,6 +205,7 @@ rcgen = { version = "0.14", default-features = false } # features; nothing here wants the default native-tls stack. reqwest = { version = "0.13", default-features = false } rind = "0.1.2" +rind-jsonwebtoken = "0.1.2" rind-object-store = "0.1.2" rind-rustls = "0.1.2" rustc-hash = "2.1.3" diff --git a/quest/m2/rind/README.md b/quest/m2/rind/README.md index 73a3ce51d1d..2eea425712d 100644 --- a/quest/m2/rind/README.md +++ b/quest/m2/rind/README.md @@ -67,6 +67,5 @@ The epic's own work, once every child has merged: - [rind-instant-acme is on crates.io](/quest/m2/rind/instant-acme.md) - waiting on the adapter relay ACME needs - [Drop iroh](/quest/m2/rind/drop-iroh.md) - moq-tokio, moq-relay, and moq-cli lose the `iroh` feature and web-transport-iroh - [Transport on rind](/quest/m2/rind/transport.md) - moq-quic, moq-tokio, moq-uring, moq-rtmp, and qmux take rind, and the `aws-lc-rs`/`ring` features go -- [moq-auth on rind](/quest/m2/rind/auth.md) - JWT signing, key generation, and JWK loading run on rind - [moq-rtc on rind](/quest/m2/rind/rtc.md) - str0m and dimpl run DTLS, SRTP, and STUN on rind - [Relay ACME on instant-acme](/quest/m2/rind/acme.md) - moq-relay replaces rustls-acme with instant-acme on rind and owns renewal diff --git a/quest/m2/rind/auth.md b/quest/m2/rind/auth.md deleted file mode 100644 index 6f277dcbb17..00000000000 --- a/quest/m2/rind/auth.md +++ /dev/null @@ -1,26 +0,0 @@ -# [M] moq-auth on rind - -## Goal - -moq-auth signs and verifies every JWT algorithm it accepts today through -`rind-jsonwebtoken`, and generates keys, converts JWKs, and draws random IDs -through rind. Its graph holds no aws-lc-rs, `p256`, or `p384`, and token and -key formats are unchanged. - -## Plan - -Decided with the maintainer on 2026-10-26; see the -[epic](/quest/m2/rind/README.md). - -- Install `rind-jsonwebtoken` only when no jsonwebtoken provider is installed, - never through jsonwebtoken's `rust_crypto` backend (it signs RS* and PS* with - the `rsa` crate). -- Key generation (HMAC, RSA-2048, P-256, P-384, Ed25519) and PKCS#8/PKCS#1 - conversion move from aws-lc-rs and `p256`/`p384` to rind, keeping the DER - encoding through `pkcs1`/`pkcs8` that - [moq-dev/moq#6898](https://github.com/moq-dev/moq/pull/6898) added. Never hand-roll the encoding. -- reqwest switches to its no-provider feature. -- The released-token compatibility tests keep passing unchanged. - -Public API: moq-auth's error conversions from aws-lc-rs types change -(breaking). Wire and key formats: unchanged. diff --git a/rs/justfile b/rs/justfile index 5c6740d5aeb..4b242e0963a 100644 --- a/rs/justfile +++ b/rs/justfile @@ -502,6 +502,10 @@ codspeed: --bench priority --bench retirement --bench schedule --bench stats --bench synced --bench tail \ --bench tracks --bench varint --bench viewers --bench matching \ --bench endpoint --bench receive --bench sent_packets --bench streams --bench chunk_interleaving + # moq-auth's published release is its own dev-dependency, so `-p moq-auth` is ambiguous and + # cargo-codspeed takes no `--manifest-path`: build it from its own directory. Each build + # replaces only its own packages' benches, so `cargo codspeed run` runs both. + cd rs/moq-auth && VALGRIND_BUG_494162=1 cargo codspeed build --locked -m simulation --bench jwt # Held feed FETCH readiness across independent request and track counts. [positional-arguments] diff --git a/rs/moq-auth/Cargo.toml b/rs/moq-auth/Cargo.toml index 41bc8ba6fe9..afd7ff63b80 100644 --- a/rs/moq-auth/Cargo.toml +++ b/rs/moq-auth/Cargo.toml @@ -12,26 +12,27 @@ rust-version.workspace = true [features] default = ["client"] # The HTTP client that drives a lease against an auth server. -client = ["dep:reqwest", "dep:rustls", "dep:tokio", "kio/runtime", "dep:tracing", "dep:rand"] +client = ["dep:reqwest", "dep:rind-rustls", "dep:rustls", "dep:rustls-platform-verifier", "dep:tokio", "kio/runtime", "dep:tracing", "dep:rand"] # The reference auth server behind `moq auth serve`: the policy a relay held, on axum. serve = ["dep:axum", "dep:tokio", "dep:tracing", "tokio/net"] [dependencies] -aws-lc-rs = { workspace = true } axum = { workspace = true, optional = true } base64 = { workspace = true } data-encoding = { workspace = true } -jsonwebtoken = { workspace = true, features = ["aws_lc_rs"] } +jsonwebtoken = { workspace = true } # `async` for `Shared::wait`, until moq-auth grows an `async` feature of its own. kio = { workspace = true, features = ["async", "serde"] } moq-pattern = { workspace = true, features = ["serde"] } -p256 = "0.14.0" -p384 = "0.14.0" -pkcs1 = { workspace = true } +pkcs1 = { workspace = true, features = ["std"] } pkcs8 = { workspace = true } rand = { workspace = true, optional = true } -reqwest = { workspace = true, features = ["rustls", "json"], optional = true } +reqwest = { workspace = true, features = ["rustls-no-provider", "json"], optional = true } +rind = { workspace = true } +rind-jsonwebtoken = { workspace = true } +rind-rustls = { workspace = true, optional = true } rustls = { version = "0.23", default-features = false, optional = true } +rustls-platform-verifier = { version = "0.7", optional = true } serde = { workspace = true } serde_json = { workspace = true } serde_with = { workspace = true, features = ["base64"] } @@ -57,5 +58,9 @@ workspace-hack = { path = "../workspace-hack" } name = "verify" harness = false +[[bench]] +name = "jwt" +harness = false + [lints] workspace = true diff --git a/rs/moq-auth/MIGRATE.md b/rs/moq-auth/MIGRATE.md index bbe34b364c6..a8589d838c0 100644 --- a/rs/moq-auth/MIGRATE.md +++ b/rs/moq-auth/MIGRATE.md @@ -4,7 +4,19 @@ How to update your code for each breaking change, newest first. ## Unreleased -### RSA uses aws-lc-rs (#6898) +### Crypto runs on rind (#7570) + +Signing, verifying, key generation, and the HTTP clients' TLS run on [rind](https://github.com/moq-dev/rind), a pure-Rust library, instead of aws-lc-rs, `p256`, and `p384`. +Token, JWK, and key formats are unchanged. + +- `Error` no longer implements `From` for `aws_lc_rs::error::{Unspecified, KeyRejected}` or `p256::elliptic_curve::{Error, pkcs8::Error}`: convert those errors in your own code, since moq-auth no longer produces them. +- `KeyError::MissingEcX` and `KeyError::MissingEcY` are removed, since nothing returned them. Drop any match arms on them. +- Building a `Key`, or a `Client` given no TLS config, on a CPU that rind refuses fails with the new `Error::UnsupportedCpu`, which names the missing feature. +- A private EC JWK whose `d` does not match its `x` and `y` now fails `Key::sign`, instead of signing tokens its own public key can't verify. +- moq-auth installs rind's jsonwebtoken provider unless the process installed one first, so to use another provider, install it before building a `Key`. +- `Client::new(url, None)` uses rind's TLS with the platform's roots. Pass a `rustls::ClientConfig` to use a different provider. + +### Private RSA JWKs are complete (#6898) Private RSA JWKs must supply `d`, `p`, `q`, `dp`, `dq`, and `qi`; partial private keys and multi-prime `oth` are refused, including on verify-only imports. Export a complete two-prime JWK from your key provider or generate one with `moq auth generate --algorithm RS256`. diff --git a/rs/moq-auth/benches/jwt.rs b/rs/moq-auth/benches/jwt.rs new file mode 100644 index 00000000000..1d218378cb3 --- /dev/null +++ b/rs/moq-auth/benches/jwt.rs @@ -0,0 +1,30 @@ +//! Signing and verifying one token with each key family, through the public API. +//! +//! Run with `cargo bench -p moq-auth --bench jwt`. + +use std::hint::black_box; + +use criterion::{Criterion, criterion_group, criterion_main}; +use moq_auth::{Algorithm, Claims, Key}; + +fn bench_jwt(c: &mut Criterion) { + let claims = Claims::default() + .with_root("room") + .with_publish(["alice/**".parse::().unwrap()]); + + let mut group = c.benchmark_group("jwt"); + for algorithm in [Algorithm::HS256, Algorithm::ES256, Algorithm::EdDSA, Algorithm::RS256] { + let key = Key::generate(algorithm, None).unwrap(); + let token = key.sign(&claims).unwrap(); + group.bench_function(format!("sign_{algorithm}"), |b| { + b.iter(|| key.sign(black_box(&claims)).unwrap()) + }); + group.bench_function(format!("verify_{algorithm}"), |b| { + b.iter(|| key.verify(black_box(&token)).unwrap()) + }); + } + group.finish(); +} + +criterion_group!(benches, bench_jwt); +criterion_main!(benches); diff --git a/rs/moq-auth/src/client.rs b/rs/moq-auth/src/client.rs index 8941b0ef962..72cf6fe93cb 100644 --- a/rs/moq-auth/src/client.rs +++ b/rs/moq-auth/src/client.rs @@ -34,8 +34,9 @@ impl Client { /// A client for the server at `url`. /// /// `http://` is accepted for a loopback host only; `https://` presents `tls`, the - /// caller's client identity and roots; `unix://` speaks HTTP over the socket at - /// the URL's path. Anything else is refused here rather than at the first session. + /// caller's client identity and roots, or without it rind's TLS and the platform's + /// roots; `unix://` speaks HTTP over the socket at the URL's path. Anything else is + /// refused here rather than at the first session. pub fn new(url: Url, tls: Option) -> crate::Result { // No client-wide timeout: `connect` runs under its caller's deadline, and the // requests that run after the handshake are bounded one by one. Every request carries @@ -56,10 +57,7 @@ impl Client { } (builder, url) } - "https" => match tls { - Some(tls) => (builder.use_preconfigured_tls(tls), url), - None => (builder, url), - }, + "https" => (builder, url), #[cfg(unix)] "unix" => { let path = url.to_file_path().map_err(|()| Error::InvalidUrl(redact(&url)))?; @@ -70,9 +68,14 @@ impl Client { _ => return Err(Error::InvalidUrl(redact(&url))), }; + let tls = match tls { + Some(tls) => tls, + None => crate::crypto::tls()?, + }; + Ok(Self { identity: Arc::new(()), - http: builder.build()?, + http: builder.use_preconfigured_tls(tls).build()?, url, }) } diff --git a/rs/moq-auth/src/crypto.rs b/rs/moq-auth/src/crypto.rs new file mode 100644 index 00000000000..447279b1c91 --- /dev/null +++ b/rs/moq-auth/src/crypto.rs @@ -0,0 +1,40 @@ +/// Refuse a CPU that rind can't run on, naming the missing feature, and make rind +/// jsonwebtoken's provider unless the process installed its own first. +/// +/// rind panics on such a CPU instead, so every key runs this before its first operation. +pub(crate) fn init() -> crate::Result<()> { + rind::cpu::check().map_err(crate::Error::unsupported_cpu)?; + // An error means the process already picked a provider, which it is entitled to. + let _ = rind_jsonwebtoken::DEFAULT_PROVIDER.install_default(); + Ok(()) +} + +/// TLS on rind with the platform's roots, for an HTTP client given no config of its own. +/// +/// reqwest has no crypto provider of its own and builds a TLS config for every scheme, so +/// each client hands it one. +#[cfg(feature = "client")] +pub(crate) fn tls() -> crate::Result { + use rustls_platform_verifier::BuilderVerifierExt; + let provider = rind_rustls::default_provider().map_err(crate::Error::unsupported_cpu)?; + Ok( + rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(provider)) + .with_safe_default_protocol_versions() + .map_err(crate::Error::crypto)? + .with_platform_verifier() + .map_err(crate::Error::crypto)? + .with_no_client_auth(), + ) +} + +#[cfg(test)] +mod tests { + /// The dev-dependencies turn on jsonwebtoken's aws-lc backend, so signing alone can't show + /// that rind is the provider. + #[test] + fn installs_rind_when_none_is_installed() { + super::init().unwrap(); + let installed = rind_jsonwebtoken::DEFAULT_PROVIDER.install_default().unwrap_err(); + assert!(std::ptr::eq(installed, &rind_jsonwebtoken::DEFAULT_PROVIDER)); + } +} diff --git a/rs/moq-auth/src/error.rs b/rs/moq-auth/src/error.rs index bf07fe2b25b..0d05edd3844 100644 --- a/rs/moq-auth/src/error.rs +++ b/rs/moq-auth/src/error.rs @@ -66,14 +66,6 @@ pub enum KeyError { /// The JWT header has no `kid` to select a key with. #[error("missing kid in JWT header")] MissingKid, - - /// An EC key has no x coordinate. - #[error("missing x() point in EC key")] - MissingEcX, - - /// An EC key has no y coordinate. - #[error("missing y() point in EC key")] - MissingEcY, } /// Top-level error type for moq-auth. @@ -219,6 +211,10 @@ pub enum Error { /// The mesh coordinator's state file could not be read, parsed, or written. #[error("mesh state: {0}")] MeshState(String), + + /// This CPU lacks a feature the crate's cryptography requires, named in rind's message. + #[error("unsupported CPU: {0}")] + UnsupportedCpu(String), } // Dependency errors are flattened to their message so their crates stay out of this crate's @@ -240,10 +236,18 @@ from_message! { serde_json::Error => Json, base64::DecodeError => Base64, jsonwebtoken::errors::Error => Jwt, - p256::elliptic_curve::pkcs8::Error => Crypto, - p256::elliptic_curve::Error => Crypto, - aws_lc_rs::error::Unspecified => Crypto, - aws_lc_rs::error::KeyRejected => Crypto, +} + +impl Error { + /// A crypto backend's error, converted by hand so its crate stays out of this crate's API. + pub(crate) fn crypto(err: impl std::error::Error) -> Self { + Self::Crypto(message(err)) + } + + /// Carries rind's message rather than its type, so rind stays out of this crate's API. + pub(crate) fn unsupported_cpu(err: rind::cpu::MissingFeature) -> Self { + Self::UnsupportedCpu(err.to_string()) + } } #[cfg(feature = "client")] diff --git a/rs/moq-auth/src/generate.rs b/rs/moq-auth/src/generate.rs index 7cc55da6f10..72f9eb2007f 100644 --- a/rs/moq-auth/src/generate.rs +++ b/rs/moq-auth/src/generate.rs @@ -1,15 +1,12 @@ -use crate::error::KeyError; -use crate::{Algorithm, EllipticCurve, Jwk, Key, KeyMaterial, RsaPublicKey}; -use aws_lc_rs::encoding::{AsBigEndian, AsDer, Pkcs8V1Der}; -use aws_lc_rs::signature::KeyPair; -use p256::elliptic_curve::array::typenum::Unsigned; -use p256::elliptic_curve::point::PointCompression; -use p256::elliptic_curve::sec1::{FromSec1Point, ModulusSize, ToSec1Point}; -use p256::elliptic_curve::{Curve, CurveArithmetic, SecretKey}; -use pkcs1::der::Decode; +use crate::{Algorithm, EllipticCurve, Error, Jwk, Key, KeyMaterial, RsaPublicKey}; +use pkcs1::der::Decode as _; +use pkcs8::der::Decode as _; +use rind::signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, Ed25519KeyPair, RsaKeyPair, RsaKeySize, sign}; /// Generate a key pair for the given algorithm, returning the private and public keys. pub fn generate(algorithm: Algorithm, id: Option) -> crate::Result { + crate::crypto::init()?; + let key = match algorithm { Algorithm::HS256 => generate_hmac_key::<32>(), Algorithm::HS384 => generate_hmac_key::<48>(), @@ -20,8 +17,8 @@ pub fn generate(algorithm: Algorithm, id: Option) -> crate::Result | Algorithm::PS256 | Algorithm::PS384 | Algorithm::PS512 => generate_rsa_key(), - Algorithm::ES256 => generate_ec_key::(EllipticCurve::P256), - Algorithm::ES384 => generate_ec_key::(EllipticCurve::P384), + Algorithm::ES256 => generate_ec_key(&sign::ECDSA_P256_SHA256_FIXED, EllipticCurve::P256), + Algorithm::ES384 => generate_ec_key(&sign::ECDSA_P384_SHA384_FIXED, EllipticCurve::P384), Algorithm::EdDSA => generate_ed25519_key(), }; @@ -32,17 +29,17 @@ pub fn generate(algorithm: Algorithm, id: Option) -> crate::Result fn generate_hmac_key() -> crate::Result { let mut key = [0u8; SIZE]; - aws_lc_rs::rand::fill(&mut key)?; + rind::rand::fill(&mut key).map_err(Error::crypto)?; Ok(KeyMaterial::OCT { secret: key.to_vec() }) } +// rind exports an RSA private key only as PKCS#8, so each JWK field is read back out of it. fn generate_rsa_key() -> crate::Result { - let key = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)?; - let document: Pkcs8V1Der<'_> = key.as_der()?; - let info = - pkcs8::PrivateKeyInfoRef::try_from(document.as_ref()).map_err(|e| crate::Error::Crypto(e.to_string()))?; - let key = - pkcs1::RsaPrivateKey::from_der(info.private_key.as_bytes()).map_err(|e| crate::Error::Crypto(e.to_string()))?; + let pkcs8 = RsaKeyPair::generate(RsaKeySize::Rsa2048) + .map_err(Error::crypto)? + .to_pkcs8(); + let info = pkcs8::PrivateKeyInfoRef::from_der(pkcs8.as_ref()).map_err(Error::crypto)?; + let key = pkcs1::RsaPrivateKey::from_der(info.private_key.as_bytes()).map_err(Error::crypto)?; Ok(KeyMaterial::RSA { public: RsaPublicKey { @@ -61,44 +58,28 @@ fn generate_rsa_key() -> crate::Result { }) } -fn generate_ec_key(curve: EllipticCurve) -> crate::Result -where - C: Curve + CurveArithmetic + PointCompression, - C::AffinePoint: ToSec1Point + FromSec1Point, - C::FieldBytesSize: ModulusSize, -{ - let mut bytes = vec![0u8; C::FieldBytesSize::to_usize()]; - let secret = loop { - aws_lc_rs::rand::fill(&mut bytes)?; - - if let Ok(secret) = SecretKey::::from_slice(&bytes) { - break secret; - } - }; +fn generate_ec_key(algorithm: &'static EcdsaSigningAlgorithm, curve: EllipticCurve) -> crate::Result { + let pair = EcdsaKeyPair::generate(algorithm).map_err(Error::crypto)?; - let point = secret.public_key().to_sec1_point(false); - - let x = point.x().ok_or(KeyError::MissingEcX)?.to_vec(); - let y = point.y().ok_or(KeyError::MissingEcY)?.to_vec(); - let d = secret.to_bytes().to_vec(); + // An X9.62 uncompressed point: a 0x04 tag, then x and y at equal width. + let public = pair.public_key(); + let point = &public.as_ref()[1..]; + let (x, y) = point.split_at(point.len() / 2); Ok(KeyMaterial::EC { curve, - x, - y, - d: Some(d), + x: x.to_vec(), + y: y.to_vec(), + d: Some(pair.to_scalar().as_ref().to_vec()), }) } fn generate_ed25519_key() -> crate::Result { - let key_pair = aws_lc_rs::signature::Ed25519KeyPair::generate()?; - - let public_key = key_pair.public_key().as_ref().to_vec(); - let seed = key_pair.seed()?.as_be_bytes()?.as_ref().to_vec(); + let pair = Ed25519KeyPair::generate().map_err(Error::crypto)?; Ok(KeyMaterial::OKP { curve: EllipticCurve::Ed25519, - x: public_key, - d: Some(seed), + x: pair.public_key().as_ref().to_vec(), + d: Some(pair.to_seed().as_ref().to_vec()), }) } diff --git a/rs/moq-auth/src/key.rs b/rs/moq-auth/src/key.rs index 0fbdb8f583e..cc6521c8d7f 100644 --- a/rs/moq-auth/src/key.rs +++ b/rs/moq-auth/src/key.rs @@ -3,9 +3,8 @@ use crate::generate::generate; use crate::{Algorithm, Claims}; use base64::Engine; use jsonwebtoken::{DecodingKey, EncodingKey, Header}; -use p256::elliptic_curve::SecretKey; -use p256::elliptic_curve::pkcs8::EncodePrivateKey; use pkcs1::der::Encode; +use rind::signature::{EcdsaKeyPair, Ed25519KeyPair, sign}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; use std::sync::OnceLock; @@ -271,6 +270,8 @@ impl Jwk { /// is discoverable from here, and `import`/`export` rather than `validate` because the /// `validate` methods elsewhere in this crate check without converting. pub fn import(self) -> crate::Result { + crate::crypto::init()?; + if let Some(scope) = &self.scope { scope.validate()?; } @@ -553,22 +554,24 @@ impl Key { Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => EncodingKey::from_secret(secret), _ => return Err(KeyError::InvalidAlgorithm.into()), }, - KeyMaterial::EC { ref curve, ref d, .. } => { + KeyMaterial::EC { + ref curve, + ref x, + ref y, + ref d, + } => { let d = d.as_ref().ok_or(KeyError::MissingPrivateKey)?; - - match curve { - EllipticCurve::P256 => { - let secret_key = SecretKey::::from_slice(d)?; - let doc = secret_key.to_pkcs8_der()?; - EncodingKey::from_ec_der(doc.as_bytes()) - } - EllipticCurve::P384 => { - let secret_key = SecretKey::::from_slice(d)?; - let doc = secret_key.to_pkcs8_der()?; - EncodingKey::from_ec_der(doc.as_bytes()) - } + let algorithm = match curve { + EllipticCurve::P256 => &sign::ECDSA_P256_SHA256_FIXED, + EllipticCurve::P384 => &sign::ECDSA_P384_SHA384_FIXED, _ => return Err(KeyError::InvalidCurve("EC").into()), - } + }; + + // rind refuses a `d` whose public key is not this `x` and `y`. + let point = [&[0x04][..], x.as_slice(), y.as_slice()].concat(); + let pair = EcdsaKeyPair::from_private_key_and_public_key(algorithm, d, &point) + .map_err(crate::Error::crypto)?; + EncodingKey::from_ec_der(pair.to_pkcs8().as_ref()) } KeyMaterial::OKP { ref curve, @@ -576,14 +579,12 @@ impl Key { ref x, } => { let d = d.as_ref().ok_or(KeyError::MissingPrivateKey)?; - - let key_pair = - aws_lc_rs::signature::Ed25519KeyPair::from_seed_and_public_key(d.as_slice(), x.as_slice())?; - - match curve { - EllipticCurve::Ed25519 => EncodingKey::from_ed_der(key_pair.to_pkcs8()?.as_ref()), - _ => return Err(KeyError::InvalidCurve("OKP").into()), + if *curve != EllipticCurve::Ed25519 { + return Err(KeyError::InvalidCurve("OKP").into()); } + + let pair = Ed25519KeyPair::from_seed_and_public_key(d, x).map_err(crate::Error::crypto)?; + EncodingKey::from_ed_der(pair.to_pkcs8().as_ref()) } KeyMaterial::RSA { ref public, @@ -1607,6 +1608,22 @@ mod tests { } } + #[test] + fn ec_private_key_must_match_its_public_point() { + let other = Key::generate(Algorithm::ES256, None).unwrap(); + let KeyMaterial::EC { d: other_d, .. } = &other.material else { + unreachable!("ES256 keys are EC"); + }; + let mut jwk = Key::generate(Algorithm::ES256, None).unwrap().export(); + let KeyMaterial::EC { d, .. } = &mut jwk.material else { + unreachable!("ES256 keys are EC"); + }; + d.clone_from(other_d); + + // Its tokens would verify under neither key's published half. + assert!(jwk.import().unwrap().sign(&create_test_claims()).is_err()); + } + #[test] fn test_ed_asymmetric_algorithms() { let key_eddsa = Key::generate(Algorithm::EdDSA, Some(crate::KeyId::decode("test-id").unwrap())); diff --git a/rs/moq-auth/src/key_id.rs b/rs/moq-auth/src/key_id.rs index e91647e6411..5f99d4f4f58 100644 --- a/rs/moq-auth/src/key_id.rs +++ b/rs/moq-auth/src/key_id.rs @@ -35,7 +35,7 @@ impl KeyId { /// Generate a random key ID using cryptographically secure randomness. pub fn random() -> Self { let mut bytes = [0u8; 8]; - aws_lc_rs::rand::fill(&mut bytes).expect("failed to generate random bytes"); + rind::rand::fill(&mut bytes).expect("failed to generate random bytes"); let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect(); Self(hex) } diff --git a/rs/moq-auth/src/lib.rs b/rs/moq-auth/src/lib.rs index 80b53998eca..a348829f9fa 100644 --- a/rs/moq-auth/src/lib.rs +++ b/rs/moq-auth/src/lib.rs @@ -23,6 +23,7 @@ mod algorithm; mod claims; +mod crypto; mod error; mod fs; mod generate; diff --git a/rs/moq-auth/src/mesh/client.rs b/rs/moq-auth/src/mesh/client.rs index 861a298e873..10cdaf8c869 100644 --- a/rs/moq-auth/src/mesh/client.rs +++ b/rs/moq-auth/src/mesh/client.rs @@ -48,6 +48,7 @@ impl Client { let http = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .timeout(TIMEOUT) + .use_preconfigured_tls(crate::crypto::tls()?) .build()?; Ok(Self { http, base, signer }) } diff --git a/rs/moq-auth/src/mesh/contract_tests.rs b/rs/moq-auth/src/mesh/contract_tests.rs index d8c3c13a521..9bf6636f2a5 100644 --- a/rs/moq-auth/src/mesh/contract_tests.rs +++ b/rs/moq-auth/src/mesh/contract_tests.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use std::time::Duration; -use aws_lc_rs::signature::Ed25519KeyPair; +use rind::signature::Ed25519KeyPair; use super::*; use crate::{Algorithm, Error, Key, KeyId}; @@ -292,7 +292,10 @@ fn a_failed_save_spends_nothing() { async fn a_malformed_body_is_an_oauth_error() { let mesh = Mesh::new().await; let url = format!("{}/enroll", mesh.base); - let response = reqwest::Client::new() + let response = reqwest::Client::builder() + .use_preconfigured_tls(crate::crypto::tls().unwrap()) + .build() + .unwrap() .post(url) .header("content-type", "application/json") .body("{}") diff --git a/rs/moq-auth/src/mesh/coordinator.rs b/rs/moq-auth/src/mesh/coordinator.rs index 3c07a78146e..69eb7d2c4b9 100644 --- a/rs/moq-auth/src/mesh/coordinator.rs +++ b/rs/moq-auth/src/mesh/coordinator.rs @@ -184,7 +184,7 @@ struct Inner { pub struct Coordinator { config: Arc, /// Seals challenges, so an outstanding one needs no state. - secret: Arc, + secret: Arc, /// The next challenge's sequence number. It restarts with the secret, which voids /// every earlier challenge. sequence: Arc, @@ -211,7 +211,7 @@ impl Coordinator { .sign(&claims(EndpointId::from_bytes([0; 32]), kio::clock::wall(), None))?; Ok(Self { config: Arc::new(config), - secret: Arc::new(aws_lc_rs::hmac::Key::new(aws_lc_rs::hmac::HMAC_SHA256, &random(32))), + secret: Arc::new(rind::hmac::Key::new(&rind::hmac::HMAC_SHA256, &random(32))), sequence: Default::default(), inner: Arc::new(Mutex::new(Inner { store, @@ -432,7 +432,7 @@ impl Coordinator { /// The truncated HMAC sealing a challenge's expiry and nonce. fn tag(&self, body: &[u8]) -> Vec { - aws_lc_rs::hmac::sign(&self.secret, body).as_ref()[..TAG_LEN].to_vec() + rind::hmac::sign(&self.secret, body).as_ref()[..TAG_LEN].to_vec() } /// Apply `change` to a copy of the store and save it, adopting the copy only once it @@ -589,18 +589,16 @@ fn encode(bytes: &[u8]) -> String { fn random(len: usize) -> Vec { let mut bytes = vec![0u8; len]; - aws_lc_rs::rand::fill(&mut bytes).expect("system randomness"); + rind::rand::fill(&mut bytes).expect("system randomness"); bytes } fn sha256(bytes: &[u8]) -> Vec { - aws_lc_rs::digest::digest(&aws_lc_rs::digest::SHA256, bytes) - .as_ref() - .to_vec() + rind::digest::digest(&rind::digest::SHA256, bytes).as_ref().to_vec() } fn constant_eq(a: &[u8], b: &[u8]) -> bool { - aws_lc_rs::constant_time::verify_slices_are_equal(a, b).is_ok() + rind::constant_time::verify(a, b).is_ok() } fn hex(bytes: &[u8]) -> String { @@ -733,9 +731,9 @@ mod tests { .unwrap() .key .unwrap(); - let a = aws_lc_rs::signature::Ed25519KeyPair::generate().unwrap(); - let b = aws_lc_rs::signature::Ed25519KeyPair::generate().unwrap(); - let enroll = |signer: &aws_lc_rs::signature::Ed25519KeyPair, challenge: &Challenge| EnrollRequest { + let a = rind::signature::Ed25519KeyPair::generate().unwrap(); + let b = rind::signature::Ed25519KeyPair::generate().unwrap(); + let enroll = |signer: &rind::signature::Ed25519KeyPair, challenge: &Challenge| EnrollRequest { proof: Proof::sign(signer, &base, challenge.challenge.clone()), key: secret.clone(), name: None, diff --git a/rs/moq-auth/src/mesh/mod.rs b/rs/moq-auth/src/mesh/mod.rs index 137cb25b006..93c05f36813 100644 --- a/rs/moq-auth/src/mesh/mod.rs +++ b/rs/moq-auth/src/mesh/mod.rs @@ -77,10 +77,8 @@ impl EndpointId { /// Whether `signature` is this key's Ed25519 signature over `message`. pub fn verify(&self, message: &[u8], signature: &[u8]) -> bool { - use aws_lc_rs::signature::{ED25519, UnparsedPublicKey}; - UnparsedPublicKey::new(&ED25519, &self.0) - .verify(message, signature) - .is_ok() + use rind::signature::{PublicKey, verify}; + PublicKey::new(&verify::ED25519, &self.0).is_ok_and(|key| key.verify(message, signature).is_ok()) } /// The broadcasts this endpoint may publish: `mesh//**`. @@ -207,7 +205,7 @@ impl Proof { /// An endpoint's secret key, held by whatever stores it. /// -/// Implemented for [`aws_lc_rs::signature::Ed25519KeyPair`]; a daemon implements it for +/// Implemented for [`rind::signature::Ed25519KeyPair`]; a daemon implements it for /// its own key type. pub trait Signer: Send + Sync { /// The endpoint ID: this key's public half. @@ -216,9 +214,8 @@ pub trait Signer: Send + Sync { fn sign(&self, message: &[u8]) -> [u8; SIGNATURE_LEN]; } -impl Signer for aws_lc_rs::signature::Ed25519KeyPair { +impl Signer for rind::signature::Ed25519KeyPair { fn endpoint(&self) -> EndpointId { - use aws_lc_rs::signature::KeyPair; EndpointId( self.public_key() .as_ref() @@ -228,7 +225,7 @@ impl Signer for aws_lc_rs::signature::Ed25519KeyPair { } fn sign(&self, message: &[u8]) -> [u8; SIGNATURE_LEN] { - aws_lc_rs::signature::Ed25519KeyPair::sign(self, message) + rind::signature::Ed25519KeyPair::sign(self, message) .as_ref() .try_into() .expect("a 64-byte Ed25519 signature") @@ -335,8 +332,8 @@ impl fmt::Display for ErrorCode { mod tests { use super::*; - fn signer() -> aws_lc_rs::signature::Ed25519KeyPair { - aws_lc_rs::signature::Ed25519KeyPair::generate().unwrap() + fn signer() -> rind::signature::Ed25519KeyPair { + rind::signature::Ed25519KeyPair::generate().unwrap() } #[test] diff --git a/rs/moq-auth/src/request.rs b/rs/moq-auth/src/request.rs index 1e2ed252437..56dae7d38d0 100644 --- a/rs/moq-auth/src/request.rs +++ b/rs/moq-auth/src/request.rs @@ -98,7 +98,7 @@ impl Request { /// `#[non_exhaustive]`, so this stays the way to build one as fields are added. pub fn new(node: impl Into, transport: Transport, path: impl Into) -> Self { let mut bytes = [0u8; 16]; - aws_lc_rs::rand::fill(&mut bytes).expect("failed to generate a session id"); + rind::rand::fill(&mut bytes).expect("failed to generate a session id"); let id: String = bytes.iter().map(|b| format!("{b:02x}")).collect(); Self { id, diff --git a/rs/workspace-hack/Cargo.toml b/rs/workspace-hack/Cargo.toml index cd051ed6dd6..196115aa9ee 100644 --- a/rs/workspace-hack/Cargo.toml +++ b/rs/workspace-hack/Cargo.toml @@ -69,6 +69,7 @@ hybrid-array = { version = "0.4", default-features = false, features = ["alloc", hyper = { version = "1", features = ["full"] } hyper-util = { version = "0.1", features = ["server-auto", "service", "tokio"] } indexmap = { version = "2", features = ["serde"] } +jsonwebtoken = { version = "11", features = ["aws_lc_rs"] } lazy_static = { version = "1", default-features = false, features = ["spin_no_std"] } log = { version = "0.4", default-features = false, features = ["std"] } md-5-93f6ce9d446188ac = { package = "md-5", version = "0.10" } @@ -190,6 +191,7 @@ hybrid-array = { version = "0.4", default-features = false, features = ["alloc", hyper = { version = "1", features = ["full"] } hyper-util = { version = "0.1", features = ["server-auto", "service", "tokio"] } indexmap = { version = "2", features = ["serde"] } +jsonwebtoken = { version = "11", features = ["aws_lc_rs"] } lazy_static = { version = "1", default-features = false, features = ["spin_no_std"] } log = { version = "0.4", default-features = false, features = ["std"] } md-5-93f6ce9d446188ac = { package = "md-5", version = "0.10" } diff --git a/sh/gh/nightly.sh b/sh/gh/nightly.sh index 30fa14f8392..1e676a51fb2 100755 --- a/sh/gh/nightly.sh +++ b/sh/gh/nightly.sh @@ -131,7 +131,7 @@ case "$1" in --bench bus --bench parameter_sets --bench sent_packets --bench demux --bench receive_bursts --bench ladder # moq-auth's published release is its own dev-dependency, so `-p moq-auth` is ambiguous. # The concurrent cases' latency percentiles stay in the run's stdout. - criterion auth --manifest-path rs/moq-auth/Cargo.toml --bench verify + criterion auth --manifest-path rs/moq-auth/Cargo.toml --bench verify --bench jwt ;; rust-uring) # One run per target makes an unsupported/skipped ring fail report