Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 0 additions & 1 deletion quest/m2/rind/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
26 changes: 0 additions & 26 deletions quest/m2/rind/auth.md

This file was deleted.

4 changes: 4 additions & 0 deletions rs/justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
19 changes: 12 additions & 7 deletions rs/moq-auth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand All @@ -57,5 +58,9 @@ workspace-hack = { path = "../workspace-hack" }
name = "verify"
harness = false

[[bench]]
name = "jwt"
harness = false

[lints]
workspace = true
14 changes: 13 additions & 1 deletion rs/moq-auth/MIGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
30 changes: 30 additions & 0 deletions rs/moq-auth/benches/jwt.rs
Original file line number Diff line number Diff line change
@@ -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`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This invocation fails: moq-auth's published release is its own dev-dependency, so cargo bench -p moq-auth --bench jwt errors with specification `moq-auth` is ambiguous — the exact reason rs/justfile now builds this bench from rs/moq-auth. Use the form the nightly script uses (cargo bench --manifest-path rs/moq-auth/Cargo.toml --bench jwt, see sh/gh/nightly.sh:133) or run cargo bench --bench jwt from this directory. The PR body's Measurements line quotes the same ambiguous command.

Suggested change
//! Run with `cargo bench -p moq-auth --bench jwt`.
//! Run with `cargo bench --manifest-path rs/moq-auth/Cargo.toml --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::<moq_auth::Pattern>().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);
17 changes: 10 additions & 7 deletions rs/moq-auth/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<rustls::ClientConfig>) -> crate::Result<Self> {
// 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
Expand All @@ -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)))?;
Expand All @@ -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,
})
}
Expand Down
40 changes: 40 additions & 0 deletions rs/moq-auth/src/crypto.rs
Original file line number Diff line number Diff line change
@@ -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<rustls::ClientConfig> {
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));
}
}
28 changes: 16 additions & 12 deletions rs/moq-auth/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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")]
Expand Down
Loading
Loading