From caae20fbd65ac6caf39e211063f3ed6e6f84e085 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 31 Oct 2026 16:02:20 -0700 Subject: [PATCH 1/6] feat(auth)!: sign, verify, and generate keys on rind Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 299 +++++++++++++++++++++++++++++++++++- Cargo.toml | 3 + rs/moq-auth/Cargo.toml | 14 +- rs/moq-auth/src/client.rs | 28 +++- rs/moq-auth/src/crypto.rs | 22 +++ rs/moq-auth/src/error.rs | 22 ++- rs/moq-auth/src/generate.rs | 78 ++++------ rs/moq-auth/src/key.rs | 63 +++++--- rs/moq-auth/src/key_id.rs | 2 +- rs/moq-auth/src/lib.rs | 1 + rs/moq-auth/src/request.rs | 2 +- 11 files changed, 436 insertions(+), 98 deletions(-) create mode 100644 rs/moq-auth/src/crypto.rs diff --git a/Cargo.lock b/Cargo.lock index b2b82342ed4..46af300e6e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -891,6 +891,8 @@ dependencies = [ "cexpr", "clang-sys", "itertools 0.13.0", + "log", + "prettyplease", "proc-macro2", "quote", "regex", @@ -1727,6 +1729,17 @@ dependencies = [ "libc", ] +[[package]] +name = "core-models" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee3344d349528f449816cfa85e558c439bdca5a6d8a738cfb21e69f0b2b1952f" +dependencies = [ + "hax-lib 0.3.7", + "pastey", + "rand 0.10.3", +] + [[package]] name = "core_affinity" version = "0.8.3" @@ -1826,6 +1839,18 @@ dependencies = [ "libc", ] +[[package]] +name = "crabgrind" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "035c801dc4b418e1d857a6536dc88b4d1929c7a1fd163389766e18d322d34a84" +dependencies = [ + "bindgen 0.72.1", + "cc", + "pkg-config", + "rustversion", +] + [[package]] name = "crc" version = "3.4.0" @@ -3713,6 +3738,79 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "hax-lib" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a33cb227f97ee5c419064c31d7c55a7d895f28d8019ccdadc311cc036500c4" +dependencies = [ + "hax-lib-macros 0.3.7", + "num-bigint", + "num-traits", +] + +[[package]] +name = "hax-lib" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb3bfcfc915e894c331662e4ac76706b777a5956535ea24535f4df30da04b1bf" +dependencies = [ + "hax-lib-macros 0.4.2", + "num-bigint", + "num-traits", +] + +[[package]] +name = "hax-lib-macros" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28da835a5f153e9f3d0cc1f42ee605a1cfa9093c93348193793d60a1b0908b51" +dependencies = [ + "hax-lib-macros-types 0.3.7", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "hax-lib-macros" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9010990fcba1d1494047fa433a433be0a5df23653a9784c739f7bba270272e" +dependencies = [ + "hax-lib-macros-types 0.4.2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "hax-lib-macros-types" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed327e9a28d6ee018a4a9ba842d4ee27e378c8a591d2beb6f42f32b24a02fcb" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "uuid", +] + +[[package]] +name = "hax-lib-macros-types" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e053e3a5aeb92df47b07323180c5088edc488ca49883a234f6c73255c54cc520" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "uuid", +] + [[package]] name = "heck" version = "0.5.0" @@ -4779,6 +4877,136 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libcrux-aes" +version = "0.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd415025511a0bd8731cae34ae2d5e07c1b3f0443d5c12bd199c9e9b2f1fd4d5" +dependencies = [ + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-hacl-rs" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27ce64ead37fc67c1039fdbcf1e8c97044e6a644cb3d1f79060b5c9ac8fdfe0a" +dependencies = [ + "libcrux-macros", +] + +[[package]] +name = "libcrux-intrinsics" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de82722c9c7419a311e84ee902e9643a15e39a6fcaade87f21e94f8d0f30fa70" +dependencies = [ + "core-models", + "hax-lib 0.4.2", +] + +[[package]] +name = "libcrux-macros" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2afdd4da30d6e23f76bd6f3ad61be5c773720349eef3e791f8b79cfea3fe1436" +dependencies = [ + "quote", + "syn 3.0.6", +] + +[[package]] +name = "libcrux-ml-kem" +version = "0.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ceed00367748ec0b545bc4a7b0521f8c9fd476d02484340f0a95b0f45f828cd" +dependencies = [ + "hax-lib 0.4.2", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-secrets", + "libcrux-sha3", + "libcrux-traits", +] + +[[package]] +name = "libcrux-p256" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7489aa205be22524e2f6ddbe006c0c4ff5f1dfc7c17b783e3d02f1cb2a01c605" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-secrets", + "libcrux-sha2", + "libcrux-traits", +] + +[[package]] +name = "libcrux-platform" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bf8bee8c35d34867a3762d6ee7b74e8523a882855c3cfce30484e9554342206" +dependencies = [ + "libc", +] + +[[package]] +name = "libcrux-poly1305" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d727ee28ee0d5d2661daa5f2f47965cd3489a0ac9130f3410e95632a98b12e49" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", +] + +[[package]] +name = "libcrux-secrets" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c4ba47b3596f2771213ff162c792e9b93ddc0cdd178a2e407e00bb8ae4afcd" +dependencies = [ + "crabgrind", + "hax-lib 0.4.2", +] + +[[package]] +name = "libcrux-sha2" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86aa35d8fc9576a41df34af4d95d1f11186c1f65cd6c829329748915ea556d71" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-traits", +] + +[[package]] +name = "libcrux-sha3" +version = "0.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c8117e86e1f03417d8ebe50ed298c6ee0b05557783a75697d0c59a2ef2dcfc6" +dependencies = [ + "hax-lib 0.4.2", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-traits", +] + +[[package]] +name = "libcrux-traits" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8958bb5c3780eb7c3355aeeb051629b830e47bfefd36befed93c81b53366bbc4" +dependencies = [ + "libcrux-secrets", + "rand 0.10.3", +] + [[package]] name = "libfuzzer-sys" version = "0.4.13" @@ -5176,7 +5404,6 @@ name = "moq-auth" version = "0.2.1" dependencies = [ "anyhow", - "aws-lc-rs", "axum", "base64 0.23.1", "jsonwebtoken", @@ -5186,13 +5413,16 @@ dependencies = [ "moq-clock", "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", + "sec1 0.8.1", "serde", "serde_json", "serde_with", @@ -8219,6 +8449,28 @@ dependencies = [ "toml_edit 0.25.15+spec-1.1.0", ] +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -8860,6 +9112,47 @@ dependencies = [ "hmac 0.13.0", ] +[[package]] +name = "rind" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc0a91565c59d87e36dcb47a73b2c5fd252b3cd7017920aec393875f1c4c0df" +dependencies = [ + "cfg-if", + "curve25519-dalek", + "fiat-crypto", + "getrandom 0.4.3", + "libc", + "libcrux-aes", + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-ml-kem", + "libcrux-p256", + "libcrux-poly1305", + "libcrux-traits", +] + +[[package]] +name = "rind-jsonwebtoken" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f47ddb24a42f4ff92519b8c061ee4eb64ef3fc65972d61451c6e4cd36fd97309" +dependencies = [ + "jsonwebtoken", + "pkcs1", + "rind", +] + +[[package]] +name = "rind-rustls" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146b5ba2940920d5c68f6ecc1cc9db58555ec89a8872f4dd8486c5ff64175e8b" +dependencies = [ + "rind", + "rustls", +] + [[package]] name = "ring" version = "0.17.14" diff --git a/Cargo.toml b/Cargo.toml index 64146a1b172..58c35a5e8cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -219,6 +219,9 @@ rcgen = { version = "0.14", default-features = false } # default-features off so each consumer picks its own TLS backend and body # features; nothing here wants the default native-tls stack. reqwest = { version = "0.13", default-features = false } +rind = "0.1" +rind-jsonwebtoken = "0.1" +rind-rustls = "0.1" rustc-hash = "2.1.3" sd-notify = "0.5" send_wrapper = "0.6" diff --git a/rs/moq-auth/Cargo.toml b/rs/moq-auth/Cargo.toml index 01b3188f2b3..3fbe5b1c44e 100644 --- a/rs/moq-auth/Cargo.toml +++ b/rs/moq-auth/Cargo.toml @@ -12,25 +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", "moq-clock/runtime", "dep:tracing", "dep:rand"] +client = ["dep:reqwest", "dep:rind-rustls", "dep:rustls", "dep:rustls-platform-verifier", "dep:tokio", "moq-clock/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 } -jsonwebtoken = { workspace = true, features = ["aws_lc_rs"] } +jsonwebtoken = { workspace = true } kio = { workspace = true } moq-clock = { version = "0.11.0", path = "../moq-clock", default-features = false, features = ["serde"] } moq-pattern = { workspace = true, features = ["serde"] } -p256 = "0.14.0" -p384 = "0.14.0" pkcs1 = { workspace = true } 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 } +sec1 = { version = "0.8", default-features = false, features = ["der"] } serde = { workspace = true } serde_json = { workspace = true } serde_with = { workspace = true, features = ["base64"] } diff --git a/rs/moq-auth/src/client.rs b/rs/moq-auth/src/client.rs index df347bd2406..c5009ddfe17 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,25 @@ impl Client { _ => return Err(Error::InvalidUrl(redact(&url))), }; + // reqwest has no crypto provider of its own and builds a TLS config for every + // scheme, so it is always handed one. + let tls = match tls { + Some(tls) => tls, + None => { + use rustls_platform_verifier::BuilderVerifierExt; + let provider = rind_rustls::default_provider().map_err(Error::crypto)?; + rustls::ClientConfig::builder_with_provider(Arc::new(provider)) + .with_safe_default_protocol_versions() + .map_err(Error::crypto)? + .with_platform_verifier() + .map_err(Error::crypto)? + .with_no_client_auth() + } + }; + 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..656d3f5384c --- /dev/null +++ b/rs/moq-auth/src/crypto.rs @@ -0,0 +1,22 @@ +/// 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::crypto)?; + // An error means the process already picked a provider, which it is entitled to. + let _ = rind_jsonwebtoken::DEFAULT_PROVIDER.install_default(); + Ok(()) +} + +#[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 72f2a0582f7..148580b1b05 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. @@ -204,7 +196,8 @@ pub enum Error { #[error("{0}")] Jwt(String), - /// A key couldn't be parsed, imported, or used by the crypto backend. + /// A key couldn't be parsed, imported, or used by the crypto backend, or this CPU + /// lacks a feature the backend requires. #[error("{0}")] Crypto(String), @@ -232,10 +225,13 @@ 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)) + } } #[cfg(feature = "client")] diff --git a/rs/moq-auth/src/generate.rs b/rs/moq-auth/src/generate.rs index 7cc55da6f10..c3c5178d318 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 private keys 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,37 @@ 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); + // 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); - 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(); + let pkcs8 = pair.to_pkcs8(); + let info = pkcs8::PrivateKeyInfoRef::from_der(pkcs8.as_ref()).map_err(Error::crypto)?; + let d = sec1::EcPrivateKey::from_der(info.private_key.as_bytes()).map_err(Error::crypto)?; Ok(KeyMaterial::EC { curve, - x, - y, - d: Some(d), + x: x.to_vec(), + y: y.to_vec(), + d: Some(d.private_key.to_vec()), }) } fn generate_ed25519_key() -> crate::Result { - let key_pair = aws_lc_rs::signature::Ed25519KeyPair::generate()?; + let pair = Ed25519KeyPair::generate().map_err(Error::crypto)?; - let public_key = key_pair.public_key().as_ref().to_vec(); - let seed = key_pair.seed()?.as_be_bytes()?.as_ref().to_vec(); + // RFC 8410 wraps the seed in a second OCTET STRING inside the PKCS#8 one. + let pkcs8 = pair.to_pkcs8(); + let info = pkcs8::PrivateKeyInfoRef::from_der(pkcs8.as_ref()).map_err(Error::crypto)?; + let seed = <&pkcs8::der::asn1::OctetStringRef>::from_der(info.private_key.as_bytes()).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(seed.as_bytes().to_vec()), }) } diff --git a/rs/moq-auth/src/key.rs b/rs/moq-auth/src/key.rs index ef2b3dd5ee0..0da853c7d7e 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, @@ -1599,6 +1600,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 0fb9b206d2d..7eb15b8d363 100644 --- a/rs/moq-auth/src/lib.rs +++ b/rs/moq-auth/src/lib.rs @@ -22,6 +22,7 @@ mod algorithm; mod claims; +mod crypto; mod error; mod fs; mod generate; diff --git a/rs/moq-auth/src/request.rs b/rs/moq-auth/src/request.rs index 2709f48aac8..c293647be3a 100644 --- a/rs/moq-auth/src/request.rs +++ b/rs/moq-auth/src/request.rs @@ -95,7 +95,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, From 312aee342999eda7fddb139e213c01f535a12545 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 31 Oct 2026 16:13:20 -0700 Subject: [PATCH 2/6] bench(auth): sign and verify per key family Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + rs/justfile | 4 ++-- rs/moq-auth/Cargo.toml | 7 ++++++- rs/moq-auth/benches/jwt.rs | 30 ++++++++++++++++++++++++++++++ 4 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 rs/moq-auth/benches/jwt.rs diff --git a/Cargo.lock b/Cargo.lock index 46af300e6e0..4893422d899 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5406,6 +5406,7 @@ dependencies = [ "anyhow", "axum", "base64 0.23.1", + "bench-harness", "jsonwebtoken", "kio 0.6.2", "moq-auth 0.2.1", diff --git a/rs/justfile b/rs/justfile index 150ceee0dd4..30eb829b8b7 100644 --- a/rs/justfile +++ b/rs/justfile @@ -504,14 +504,14 @@ gst-smoke *args: # `iter_custom`, so targets made only of it are left out too. Nightly still measures them all. codspeed: cargo codspeed build --locked -m simulation \ - -p kio -p moq-audio -p moq-e2ee -p moq-json -p moq-mux -p moq-net -p moq-pattern -p moq-quic -p moq-rtmp \ + -p kio -p moq-audio -p moq-auth -p moq-e2ee -p moq-json -p moq-mux -p moq-net -p moq-pattern -p moq-quic -p moq-rtmp \ --features moq-audio/bus,moq-net/fuzz,moq-quic/fuzz \ --bench tasks --bench waiter --bench bus --bench protect --bench codec --bench table \ --bench catalog --bench containers --bench decode_clock --bench export --bench jitter \ --bench parameter_sets --bench ts_programs --bench ts_schedule --bench ts_video \ --bench announce --bench auth --bench bandwidth --bench canonical --bench frame --bench interests \ --bench priority --bench retirement --bench schedule --bench stats --bench synced --bench tail \ - --bench tracks --bench varint --bench viewers --bench matching \ + --bench tracks --bench varint --bench viewers --bench matching --bench jwt \ --bench endpoint --bench receive --bench sent_packets --bench streams --bench chunk_interleaving # Held feed FETCH readiness across independent request and track counts. diff --git a/rs/moq-auth/Cargo.toml b/rs/moq-auth/Cargo.toml index 3fbe5b1c44e..74eddd5bbb8 100644 --- a/rs/moq-auth/Cargo.toml +++ b/rs/moq-auth/Cargo.toml @@ -23,7 +23,7 @@ jsonwebtoken = { workspace = true } kio = { workspace = true } moq-clock = { version = "0.11.0", path = "../moq-clock", default-features = false, features = ["serde"] } moq-pattern = { workspace = true, features = ["serde"] } -pkcs1 = { workspace = true } +pkcs1 = { workspace = true, features = ["std"] } pkcs8 = { workspace = true } rand = { workspace = true, optional = true } reqwest = { workspace = true, features = ["rustls-no-provider", "json"], optional = true } @@ -43,6 +43,7 @@ url = { workspace = true } [dev-dependencies] anyhow = { workspace = true } +criterion = { package = "bench-harness", path = "../bench-harness" } moq-auth = { path = ".", features = ["client", "serve"] } moq-auth-published = { package = "moq-auth", version = "=0.2.1", default-features = false } moq-clock = { path = "../moq-clock", features = ["sim"] } @@ -52,5 +53,9 @@ tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util" tracing-test = { workspace = true } wiremock = "0.6" +[[bench]] +name = "jwt" +harness = false + [lints] workspace = true 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); From dacd4657f387758a21b3c5c74da2f38910e0bd8c Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 1 Nov 2026 09:16:03 -0800 Subject: [PATCH 3/6] chore(quest): claim quest/m2/rind/auth.md Quest-Claim: 1b7870edc523fa53 From 5c3fb88c0be48ff3e226d4a8b424ca816900bc69 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 1 Nov 2026 09:16:40 -0800 Subject: [PATCH 4/6] chore(quest): moq-auth on rind is done Co-Authored-By: Claude Opus 5.5 --- quest/m2/rind/README.md | 1 - quest/m2/rind/auth.md | 26 -------------------------- 2 files changed, 27 deletions(-) delete mode 100644 quest/m2/rind/auth.md diff --git a/quest/m2/rind/README.md b/quest/m2/rind/README.md index 79c26a879cb..2d04b8bf037 100644 --- a/quest/m2/rind/README.md +++ b/quest/m2/rind/README.md @@ -67,7 +67,6 @@ 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 - [moq-cli and moq-hls on rind](/quest/m2/rind/cli.md) - object_store, reqwest, and axum-server take rind's provider 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. From 4d2fe26f1fceebc9b7f585ca462031f6d6db5ece Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 2 Nov 2026 22:52:44 -0800 Subject: [PATCH 5/6] fix(auth): build the jwt bench for CodSpeed, sync the workspace-hack, add MIGRATE `cargo codspeed build -p moq-auth` is ambiguous, since moq-auth's published release is its own dev-dependency, and cargo-codspeed takes no `--manifest-path`: build the jwt bench from moq-auth's own directory. moq-auth's own jsonwebtoken no longer enables aws_lc_rs, but its dev-dependencies still do, so `cargo hakari generate` lifts that feature into the workspace-hack. MIGRATE gains the rind switch's breaking changes, and #6898's heading no longer says RSA runs on aws-lc-rs. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + rs/justfile | 8 ++++++-- rs/moq-auth/MIGRATE.md | 14 +++++++++++++- rs/workspace-hack/Cargo.toml | 2 ++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 03f6749f282..acec2788108 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12422,6 +12422,7 @@ dependencies = [ "hyper-util", "indexmap 2.14.2", "itertools 0.13.0", + "jsonwebtoken", "lazy_static", "libc", "libspa", diff --git a/rs/justfile b/rs/justfile index 4052f4a27f9..4b242e0963a 100644 --- a/rs/justfile +++ b/rs/justfile @@ -493,15 +493,19 @@ gst-smoke *args: # rind is built to skip that one startup check, or it refuses the simulated CPU. codspeed: VALGRIND_BUG_494162=1 cargo codspeed build --locked -m simulation \ - -p kio -p moq-audio -p moq-auth -p moq-e2ee -p moq-json -p moq-mux -p moq-net -p moq-pattern -p moq-quic -p moq-rtmp \ + -p kio -p moq-audio -p moq-e2ee -p moq-json -p moq-mux -p moq-net -p moq-pattern -p moq-quic -p moq-rtmp \ --features moq-audio/bus,moq-net/fuzz,moq-quic/fuzz \ --bench tasks --bench waiter --bench bus --bench protect --bench codec --bench table \ --bench catalog --bench containers --bench decode_clock --bench export --bench jitter \ --bench parameter_sets --bench ts_programs --bench ts_schedule --bench ts_video \ --bench announce --bench auth --bench bandwidth --bench canonical --bench frame --bench interests \ --bench priority --bench retirement --bench schedule --bench stats --bench synced --bench tail \ - --bench tracks --bench varint --bench viewers --bench matching --bench jwt \ + --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/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/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" } From 77fd6817ef8661d7d2e9d03d449ee0d104773b1f Mon Sep 17 00:00:00 2001 From: quest fixer Date: Mon, 2 Nov 2026 23:53:02 -0800 Subject: [PATCH 6/6] fix(ci): register the auth jwt benchmark in Nightly --- sh/gh/nightly.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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