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
15 changes: 9 additions & 6 deletions doc/bin/relay/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ path patterns under a root, and the session can only see that part of the tree.
The relay POSTs one JSON body per session event (`connect`, `attach`, `revalidate`,
`end`) to `--auth-url` and reads a grant back. The request carries everything
the relay knows: a session id, its own `node` name, the transport, addresses,
SNI and ALPN, the path and query exactly as dialed, a moq-transport SETUP
token, the declared role and implementation, and the verified client
SNI and ALPN, the path and query exactly as dialed, the SETUP
`token` (or, on `attach`, the credential attached in band), the declared role and implementation, and the verified client
certificate. Nothing is parsed on the server's behalf: the `jwt` query parameter is a convention of
`moq auth serve`, not of the relay. A path with a `.` or `..` segment is refused
before the server is asked: a URL transport resolves those away, but a SETUP
Expand Down Expand Up @@ -190,10 +190,13 @@ removes that token's grant: streams that lose permission reset, and other grants
keep the connection alive. A refused new token leaves existing grants alone.
The grant reports its real expiry so the client can renew in time.

The relay verifies a presented JWT through the same admission path, replacing
`jwt` in the original query and preserving the connection's identity. The auth
server sees `attach` for the same session id, with a fresh `auth` id
that also names its revalidations and end. Attached grants revalidate and end
The relay verifies a presented JWT through the same admission path, preserving
the connection's identity. The auth server sees `attach` for the same session
id, with a fresh `auth` id that also names its revalidations and end. The
attached credential arrives in `token` (`kind` 0, any bytes) and `query` stays
exactly as dialed, still holding the connection's first credential, so read an
event with `auth` from `token` alone; `moq auth serve` does, and for now also reads the
attached credential from the query's `jwt` when a previous-release relay sends no `token`. Attached grants revalidate and end
independently. Each JWT counts against its own `--limit-token` cap while any
credential using it remains on that connection. The initial credential remains
responsible for the connection's stats tier.
Expand Down
5 changes: 4 additions & 1 deletion js/auth/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ const BaseRequestSchema = z.object({
path: z.string(),
/** The raw query string, without the leading `?`. */
query: z.optional(z.string()),
/** The credential a moq-transport client presented in its SETUP. */
/**
* The credential the client presented: the Token of its SETUP, or on an `attach` (and that
* credential's `revalidate` and `end`) the one it attached in band, with `query` left as dialed.
*/
token: z.optional(TokenSchema),
/** The direction the client declared at SETUP; absent means both. */
role: z.optional(RoleSchema),
Expand Down
5 changes: 2 additions & 3 deletions quest/m2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,8 @@ removal, a rename, or a wire, catalog, or format change that is free until
memory pairing found; [congestion names](/quest/m2/congestion-names.md);
[the 0.14 leftovers](/quest/m2/relay-014-leftovers.md); and
[transport names](/quest/m2/transport-names.md).
- **Auth and crypto.** [Grants](/quest/m2/auth-grants.md),
[claims](/quest/m2/auth-claims.md), and
[the attached token](/quest/m2/auth-attach-token.md). End-to-end encryption
- **Auth and crypto.** [Grants](/quest/m2/auth-grants.md) and
[claims](/quest/m2/auth-claims.md). End-to-end encryption
[is its own unpublished crate again](/quest/m2/e2ee-crate.md); its
[finished format](/quest/m3/e2ee-format.md) follows in m3.
- **Catalog, drafts, and formats.** [hang-04](/quest/m2/hang04/README.md)
Expand Down
35 changes: 35 additions & 0 deletions quest/m2/auth-attach-downstream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# [XS] Downstream auth servers read an attached credential from the token field

## Goal

Every auth server a deployment runs behind a relay reads a credential
attached in band, on `attach` and on that credential's `revalidate` and `end`
(the events with `auth`), from `token`, not from a `jwt` in `query`.

## Plan

The relay now sends an attached credential as `token` (`kind` 0) and leaves
`query` as dialed. `moq auth serve` already reads it so; a server that
verifies `query` at `attach` sees the connection's first credential instead.
Neither the presented token nor its expiry is then the one admitted.

Found at moq.pro `9373cdfb3`: `rs/edge/src/auth/mod.rs` reads the credential
only from `request.query` through `query_jwt` (`:393`), never from
`request.token`. See `:1312-1317` (`End` forgets the query credential),
`:1331` (`Attach` and `Revalidate` decide on the query's `jwt`), `:1061`, and
`limits.rs:179`, `:383`, `:419`. Plain `?jwt=` dials are unaffected. Kixel's
`src/mesh.ts:557` reads a `credential` query parameter, and its client has no
attach use today.

Until moq.pro reads `token`, it must not meet a relay with this change:
`moq auth serve` reads a previous-release relay's `query` shape for now (a
marked temporary migration in `rs/moq-auth/src/serve.rs`), but moq.pro has no
such reader for the new shape.

## Waiting

- Maintainer: check the moq.pro and Kixel auth handlers read `attach` from
`token`, and fix one that does not before it meets a relay with this change.
An agent cannot read those private repositories from here. Done when both
handlers' tests present an attach whose `query` holds an expired `jwt` and
whose `token` holds a valid one.
68 changes: 0 additions & 68 deletions quest/m2/auth-attach-token.md

This file was deleted.

1 change: 0 additions & 1 deletion quest/m2/auth-grants.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,3 @@ behind a temporary alias. Wire: none.
## Related

- [Tokens are written as documented](/quest/m2/auth-claims.md) - the token side of the same types
- [An attached token arrives as a token](/quest/m2/auth-attach-token.md) - the other change to the request the server reads
7 changes: 5 additions & 2 deletions rs/moq-auth/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ pub struct Request {
/// The raw query string, without the leading `?`.
pub query: Option<String>,

/// The credential a moq-transport client presented in its SETUP.
/// The credential the client presented: the Token of its SETUP, or on an
/// [`Attach`](Event::Attach) (and that credential's revalidations and end) the one it
/// attached in band, with `query` left as the connection dialed it.
pub token: Option<Token>,

/// The direction the client declared at SETUP; absent means both.
Expand Down Expand Up @@ -127,7 +129,8 @@ impl Request {
}
}

/// A credential from a moq-transport SETUP's `AUTHORIZATION TOKEN` option, unparsed.
/// A credential a client presented, unparsed: a SETUP Token (an `AUTHORIZATION TOKEN` on
/// moq-transport) or one attached in band.
#[serde_as]
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Token {
Expand Down
87 changes: 83 additions & 4 deletions rs/moq-auth/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,9 @@ pub struct Rule {
/// empty root: `anon/**` admits a session dialed at `/`, `/anon`, or `/anon/room`,
/// each scoped to `anon/`, and refuses one dialed at `/other`.
///
/// The JWT is the `jwt` query parameter or a moq-transport SETUP token of type 0
/// ([`Token::OUT_OF_BAND`]), verified alike. A session presenting both is verified
/// The JWT is the `jwt` query parameter or a SETUP token of type 0
/// ([`Token::OUT_OF_BAND`]), verified alike. A credential attached in band is only the
/// event's `token`, since its `query` is the connection's. A session presenting both is verified
/// once when they are the same JWT and refused when they differ, as is a SETUP token
/// of any other type, and one presenting a JWT alongside a
/// certificate: neither can safely win, since a certificate would override a JWT
Expand Down Expand Up @@ -536,8 +537,22 @@ fn authorize(rules: &Permissions, path: &str) -> Result<Permissions, Denial> {

/// The JWT the request presents: its SETUP token, or else its `jwt` query parameter.
/// Both at once count as one only when they are the same JWT.
///
/// An attached credential (an event with `auth`) is only its `token`: the `query` is the
/// connection's, still holding the first credential. An event with `auth` and no credential
/// is refused, never decided on the anonymous or mTLS rules.
fn jwt(request: &Request) -> Result<Option<Cow<'_, str>>, Denial> {
match (&request.token, query_jwt(request)?) {
let query = match (&request.auth, &request.token) {
// TEMPORARY migration: a relay before this change rewrote an attached credential into
// `jwt` in the query and cleared the token. Delete once no such relay runs beside us.
(Some(_), None) => match query_jwt(request)? {
Some(jwt) => Some(jwt),
None => return Err(Denial::MalformedToken("an attachment needs a token".into())),
},
(Some(_), Some(_)) => None,
(None, _) => query_jwt(request)?,
};
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
match (&request.token, query) {
// A client that offers a version without in-band auth copies its SETUP token
// into the URL too, so the same JWT arrives twice.
(Some(token), Some(jwt)) if token.kind == Token::OUT_OF_BAND && token.value == jwt.as_bytes() => Ok(Some(jwt)),
Expand Down Expand Up @@ -1401,6 +1416,69 @@ mod tests {
assert_eq!(grant.publish, patterns(&["**"]));
}

/// An attachment is its `token` alone: the dialed query's `jwt` is the connection's, so
/// it neither conflicts with the token nor stands in for a missing one.
#[tokio::test]
async fn an_attached_credential_is_read_from_its_token() {
let (dir, key) = key_dir();
let server = Server::new(Policy {
keys: Some(Keys::Dir(dir.path().into())),
..Default::default()
})
.unwrap();
// The connection dialed with a credential that has since expired.
let expired = Some(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(1));
let dialed = sign(&key, "demo", &["**"], &[], expired);
let attached = sign(&key, "demo", &[], &["**"], None);
let mut attach = with_setup_token(with_token(request("/demo"), &dialed), Token::OUT_OF_BAND, &attached);
attach.auth = Some("attachment".into());
attach.event = Event::Attach;
let grant = server.answer(&attach).await.unwrap().unwrap();
assert_eq!(grant.subscribe, patterns(&["**"]));
assert!(
grant.publish.is_empty(),
"the dialed query's grant leaked into the attachment"
);

// Its revalidation reads the same token, not the expired query.
let mut revalidate = attach.clone();
revalidate.event = Event::Revalidate;
assert!(server.answer(&revalidate).await.is_ok());

// An attachment with no credential at all is refused, never decided anonymously.
let mut bare = attach.clone();
bare.token = None;
bare.query = None;
for event in [Event::Attach, Event::Revalidate] {
bare.event = event;
assert!(matches!(
server.answer(&bare).await.unwrap_err(),
Denial::MalformedToken(_)
));
}
}

/// TEMPORARY, with the migration in `jwt`: a previous-release relay sends the attached
/// credential as the query's `jwt` with no token, on `attach` and on `revalidate`.
#[tokio::test]
async fn a_previous_relays_attachment_is_read_from_its_query() {
let (dir, key) = key_dir();
let server = Server::new(Policy {
keys: Some(Keys::Dir(dir.path().into())),
..Default::default()
})
.unwrap();
let attached = sign(&key, "demo", &[], &["**"], None);
let mut attach = with_token(request("/demo"), &attached);
attach.auth = Some("attachment".into());
for event in [Event::Attach, Event::Revalidate] {
attach.event = event;
let grant = server.answer(&attach).await.unwrap().unwrap();
assert_eq!(grant.subscribe, patterns(&["**"]));
assert!(grant.publish.is_empty());
}
}

/// Two different credentials would leave the server guessing which one the client meant.
#[tokio::test]
async fn a_setup_token_and_a_different_query_jwt_are_refused() {
Expand Down Expand Up @@ -2021,7 +2099,8 @@ mod tests {
server.answer(&second).await.unwrap();

let attach = |session: &Request| {
let mut attach = with_token(session.clone(), &b);
// The dialed query still holds the connection's own `jwt`.
let mut attach = with_setup_token(session.clone(), Token::OUT_OF_BAND, &b);
attach.auth = Some("attachment".into());
attach.event = Event::Attach;
attach
Expand Down
40 changes: 10 additions & 30 deletions rs/moq-relay/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -853,7 +853,7 @@ impl Decider {
}
// Nothing here can verify a token, so one is refused rather than ignored:
// its holder expects it to count, and the public grant is not what it says.
Self::Public(_) if presents_token(&request) => {
Self::Public(_) if request.token.is_some() => {
tracing::debug!(path = ?request.path, "a token was presented to public rules");
Ok(Box::pin(std::future::ready(Err(Error::Refused(Default::default())))))
}
Expand All @@ -874,16 +874,6 @@ impl Decider {
}
}

/// Whether `request` carries a token: a SETUP token of any type, or a non-empty
/// `jwt` query parameter, form-decoded as `moq auth serve` reads it, so an escaped
/// key such as `%6Awt` counts too.
fn presents_token(request: &Request) -> bool {
request.token.is_some()
|| request.query.as_deref().is_some_and(|query| {
url::form_urlencoded::parse(query.as_bytes()).any(|(key, jwt)| key == "jwt" && !jwt.is_empty())
})
}

/// Admits sessions through one admission decider.
#[derive(Clone)]
pub struct Auth {
Expand Down Expand Up @@ -1706,36 +1696,26 @@ mod tests {
}
}

/// Public rules verify nothing, so a token is refused rather than ignored, in
/// whichever form it arrives.
/// Public rules verify nothing, so a token is refused rather than ignored.
#[tokio::test]
async fn public_rules_refuse_a_token() {
let auth = config(None, &["**"])
.init("relay-1", &moq_tokio::tls::Connect::default(), false)
.unwrap();
let mut query = auth.request(moq_auth::Transport::WebSocket, "/");
query.query = Some("a=1&jwt=eyJ".into());
let mut setup = auth.request(moq_auth::Transport::Quic, "/");
setup.token = Some(moq_auth::Token {
kind: moq_auth::Token::CAT,
value: b"anything".to_vec(),
});
let mut http = auth.request(moq_auth::Transport::Http, "/");
http.query = Some("jwt=eyJ".into());
// `moq auth serve` form-decodes the key, so an escaped one is a token too.
let mut escaped = auth.request(moq_auth::Transport::WebSocket, "/");
escaped.query = Some("%6Awt=eyJ".into());
for request in [query, setup, http, escaped] {
let Err(err) = auth.admit(request).await else {
panic!("a token was admitted on the public grant");
};
assert!(matches!(err, Error::Refused(_)), "{err}");
}
let Err(err) = auth.admit(setup).await else {
panic!("a token was admitted on the public grant");
};
assert!(matches!(err, Error::Refused(_)), "{err}");

// An empty `jwt=` is no token.
let mut empty = auth.request(moq_auth::Transport::WebSocket, "/");
empty.query = Some("jwt=&b=2".into());
assert!(auth.admit(empty).await.is_ok());
// A query is the client's own: the relay reads no parameter in it as a token.
let mut query = auth.request(moq_auth::Transport::WebSocket, "/");
query.query = Some("jwt=eyJ".into());
assert!(auth.admit(query).await.is_ok());
}

/// A certificate is a fact the public rules ignore: it gets exactly what anyone does.
Expand Down
Loading