diff --git a/doc/bin/obs.md b/doc/bin/obs.md index 72fbabe86da..fae67f2d757 100644 --- a/doc/bin/obs.md +++ b/doc/bin/obs.md @@ -24,10 +24,8 @@ The source plays Opus, AAC-LC (mono or stereo), and PCM audio. A channel count n Enter a relay URL explicitly. On the shared anonymous relay, use a unique path such as `https://cdn.moq.dev/anon/your-stream`. A URL with `?jwt=` fills the token field. Editing the token while live presents the new one without -reconnecting, on a session that carries in-band authorization: a -`moq-transport` draft-18 or later version pinned under Advanced settings, with -a relay that negotiates the MoQ Auth extension. The default protocol does not -yet, so there the dock reports the new token as refused and it applies on the +reconnecting, on a session that carries in-band authorization, which only +`moq-lite-07-wip` does. The default protocol does not yet, so there the dock reports the new token as refused and it applies on the next reconnect or Go Live. By default the dock tunes the encoder for low latency on this stream only: diff --git a/doc/bin/relay/auth.md b/doc/bin/relay/auth.md index 74c4c1370f6..e5e365bbc16 100644 --- a/doc/bin/relay/auth.md +++ b/doc/bin/relay/auth.md @@ -168,9 +168,9 @@ key can itself be **scoped** at generation (`--root`, `--publish`, ### In-band renewal -On moq-lite-07-wip or moq-transport draft-18 and later with MoQ Auth negotiated, -a client can present another JWT without reconnecting. Present its replacement -before the current grant expires and keep the returned token handle alive. +On moq-lite-07-wip a client can present another JWT without reconnecting. +Present its replacement before the current grant expires and keep the returned +token handle alive. The auth handle a reconnecting connection owns (native `Connection::auth()`, JavaScript `connection.auth`) presents its tokens again on every reconnect. A native client can instead replace its configured tokens through its diff --git a/doc/bin/relay/config.md b/doc/bin/relay/config.md index 2df66a6ea03..4cef5b6ce84 100644 --- a/doc/bin/relay/config.md +++ b/doc/bin/relay/config.md @@ -48,7 +48,6 @@ allow.uid = [1001] [listen.extensions] # moq-transport SETUP extensions to offer, each on by default. # The relay always offers ietf, for moq-lite-07 relay links. -auth = false # Decline MoQ Auth. solicit = false # Decline MoQ Solicit, so peers may announce unasked. ``` @@ -332,8 +331,7 @@ tls.cert = "relay.pem" # Present a client certificate (mTLS to pee tls.key = "relay.key" goaway.redirect = "same-host" # How far to trust a draining peer's redirect URI. goaway.handover = "10s" # Cap on how long the drained upstream keeps serving. -extensions.auth = false # Decline MoQ Auth on outbound moq-transport sessions. -extensions.solicit = false # Decline MoQ Solicit. All default to on, as in [listen.extensions]. +extensions.solicit = false # Decline MoQ Solicit on outbound moq-transport sessions, as in [listen.extensions]. ``` A draining upstream may name a replacement URI. `same-host` follows it only diff --git a/doc/concept/moq-lite.md b/doc/concept/moq-lite.md index d0d096eadee..9151120b0e5 100644 --- a/doc/concept/moq-lite.md +++ b/doc/concept/moq-lite.md @@ -244,11 +244,10 @@ A subscription or fetch that loses access resets with the `UNAUTHORIZED` stream code and the session stays up. A client that publishes outside its grant closes the session with `UNAUTHORIZED`, naming the path. A session whose last credential expires closes with `EXPIRED_AUTH_TOKEN` instead: refresh the token -and reconnect, rather than treating the credential as invalid. moq-transport carries the same -exchange through the [MoQ Auth extension](/draft/moq-auth), with -the same patterns. Older versions have no grant; the URL token keeps working -everywhere. On moq-transport an added token is kept even without the extension, -so an announcement can name it: it rides that `PUBLISH_NAMESPACE` as its +and reconnect, rather than treating the credential as invalid. Older versions +and moq-transport have no grant; the URL token keeps working everywhere. On +moq-transport an added token is kept for the requests that name it, so an +announcement can name it: it rides that `PUBLISH_NAMESPACE` as its authorization token. Naming a fresh token renews the announcement in place with `REQUEST_UPDATE`, so it can outlive the token it started with. A token added to a reconnecting connection's auth handle is presented on every session it makes, so the diff --git a/doc/concept/standard.md b/doc/concept/standard.md index 6add841448c..aea524e38e1 100644 --- a/doc/concept/standard.md +++ b/doc/concept/standard.md @@ -33,7 +33,7 @@ subset drops. What a peer actually observes against this implementation: - **Compression.** Rust peers exchange compressed tracks when both offer the [Flate extension](/draft/moq-flate). Other peers receive one shared inflated copy. A publisher that seals the compression declaration makes that fallback unavailable: an incompatible peer is refused, preserving the sealed metadata. JavaScript does not offer the IETF extension. - **Timing.** A track whose `SUBSCRIBE_OK` or `PUBLISH` declares no `TIMESCALE` is untimed. A `SUBSCRIBE` or `FETCH` with `INCLUDE_PROPERTIES=0` gets no `TIMESCALE` in its `SUBSCRIBE_OK` or `FETCH_OK`, so its objects go out unstamped. A Rust reader that never subscribed takes the units from `TRACK_STATUS`, and still asks for the properties whenever it subscribes to or fetches a timed track. - **Strict SETUP and parameters.** Repeated unknown `SETUP` options, GREASE included, are accepted if well-formed; a repeated known option is rejected. A `GROUP_ORDER` other than Ascending (1) or Descending (2) closes the session. An unknown message parameter, or one defined only for another message, closes the session. Other malformed control input closes the session with the draft's code too, such as a server `SETUP` carrying `PATH` or `AUTHORITY`, a namespace field ending in `/` (it would map to a path with an empty segment), a request cut short by FIN, or a second `GOAWAY` on one stream; a first `GOAWAY` on a request stream is legal. -- **One `SETUP` credential**, forwarded to the [auth server](/bin/relay/auth#the-contract) unverified. A second `SETUP` token closes the session. We advertise no token cache, so an alias reference in `SETUP` closes it with `PROTOCOL_VIOLATION`, one on a request with `UNKNOWN_AUTH_TOKEN_ALIAS`, and a registration on a request with `AUTH_TOKEN_CACHE_OVERFLOW`. Where the Rust side authorizes the peer or verifies tokens, each distinct request token is verified once while any open request on that session names it, and its grant authorizes only requests naming it, even where that authorization already covers it; it never widens the session. It is refused with `NOT_SUPPORTED` when nothing verifies it, when it is empty, or when its Token Type is anything but 0 (out of band). A side that does neither, JavaScript included, ignores the token. Rust refuses a request carrying more than one distinct token with `NOT_SUPPORTED`, since it verifies one; JavaScript, which verifies none, ignores them all. A token-authorized `SUBSCRIBE` still stays within the grant the peer gave us. A token-authorized `PUBLISH_NAMESPACE` needs a grant covering everything beneath the namespace, and the tracks we subscribe under it rely on that announce instead of our limit, ending with it. An update on a token-authorized request moves it to the token it carries; the old token ends with its last naming request. A request is admitted by the session or by a token for good, so an update naming a token on one the session admitted is refused with `NOT_SUPPORTED`. A token-less `PUBLISH_NAMESPACE` our limit does not cover is refused `UNAUTHORIZED`, and one the limit stops covering ends; the publisher re-announces once it widens. Expiry or revocation ends every request naming that token. The relay reports the lease end to its auth server, and a later request naming the token verifies it again. A refused renewal ends only that request. Rust and JavaScript send the token a route names (`Route::auth`) on its `PUBLISH_NAMESPACE`, and swapping it renews the request with `REQUEST_UPDATE`; the inline `NAMESPACE` that answers a solicited `SUBSCRIBE_NAMESPACE` carries no token. A token added to a reconnecting connection's auth handle rides every session it makes, so the announcement keeps it across a reconnect; one added to a single session's handle ends with that session. Rust honors a token on any supported request; discovery reveals only paths it grants, and a joining `FETCH` keeps following its subscription. A request repeating a token is refused with `MALFORMED_AUTH_TOKEN`. The negotiated [MoQ Auth extension](/concept/moq-lite#authorization) accepts additional session tokens in band. +- **One `SETUP` credential**, forwarded to the [auth server](/bin/relay/auth#the-contract) unverified. A second `SETUP` token closes the session. We advertise no token cache, so an alias reference in `SETUP` closes it with `PROTOCOL_VIOLATION`, one on a request with `UNKNOWN_AUTH_TOKEN_ALIAS`, and a registration on a request with `AUTH_TOKEN_CACHE_OVERFLOW`. Where the Rust side authorizes the peer or verifies tokens, each distinct request token is verified once while any open request on that session names it, and its grant authorizes only requests naming it, even where that authorization already covers it; it never widens the session. It is refused with `NOT_SUPPORTED` when nothing verifies it, when it is empty, or when its Token Type is anything but 0 (out of band). A side that does neither, JavaScript included, ignores the token. Rust refuses a request carrying more than one distinct token with `NOT_SUPPORTED`, since it verifies one; JavaScript, which verifies none, ignores them all. A token-authorized `SUBSCRIBE` still stays within the grant the peer gave us. A token-authorized `PUBLISH_NAMESPACE` needs a grant covering everything beneath the namespace, and the tracks we subscribe under it rely on that announce instead of our limit, ending with it. An update on a token-authorized request moves it to the token it carries; the old token ends with its last naming request. A request is admitted by the session or by a token for good, so an update naming a token on one the session admitted is refused with `NOT_SUPPORTED`. A token-less `PUBLISH_NAMESPACE` our limit does not cover is refused `UNAUTHORIZED`, and one the limit stops covering ends; the publisher re-announces once it widens. Expiry or revocation ends every request naming that token. The relay reports the lease end to its auth server, and a later request naming the token verifies it again. A refused renewal ends only that request. Rust and JavaScript send the token a route names (`Route::auth`) on its `PUBLISH_NAMESPACE`, and swapping it renews the request with `REQUEST_UPDATE`; the inline `NAMESPACE` that answers a solicited `SUBSCRIBE_NAMESPACE` carries no token. A token added to a reconnecting connection's auth handle rides every session it makes, so the announcement keeps it across a reconnect; one added to a single session's handle ends with that session. Rust honors a token on any supported request; discovery reveals only paths it grants, and a joining `FETCH` keeps following its subscription. A request repeating a token is refused with `MALFORMED_AUTH_TOKEN`. Additional session tokens in band need [moq-lite-07](/concept/moq-lite#authorization); moq-transport has no AUTH exchange. - **Pause delivery.** `FORWARD=0` on a `SUBSCRIBE` or its update drops the subscription, closing its data streams and holding nothing upstream, while the request and its slot stay. `FORWARD=1` subscribes again as a new `SUBSCRIBE` with the same filter would, so nothing carries across the pause: its `REQUEST_OK` names the live edge it joined at. A paused update may change only priority and max age. - **Refused, not fatal.** A legal request this stack does not serve is rejected on its own and the session stays up: `SUBSCRIBE_TRACKS`, multi-group `FETCH`, and joining requests reaching before the joined group get `NOT_SUPPORTED`. Range Filters get `INVALID_FILTER` from draft 20 because the advertised filter limit is zero. From draft 20, namespaces whose first tuple field is exactly `.` or `.session` get `DOES_NOT_EXIST` before application lookup; other dot prefixes still reach the application. Subscription updates accept priority, negotiated subscriber max age, and delivery timeouts. Rust also carries range changes, keeps bounded subscriptions updatable, renews request tokens, and judges `NEW_GROUP_REQUEST` as a join (see dynamic groups below). From draft 20, a wider or historical fill fails on its separate fetch stream while its subscription stays open; a largest-group fill hands its head to the live subgroup tail. Other supported-but-unimplemented preferences end that subscription; a `TRACK_PROPERTY_FILTER` there closes the session with `PROTOCOL_VIOLATION`, since it belongs only to `SUBSCRIBE_TRACKS`. A namespace update may change its prefix; suffixes after the acknowledgement are relative to that new prefix. - **Objects and datagrams.** Only subgroup 0 is accepted: a stream for any other subgroup, whether its header gives the ID or takes it from the first Object ID, is stopped and the session stays up. Rust relays preserve Object IDs, gaps, object properties, FIRST\_OBJECT, and END\_OF\_GROUP status objects between moq-transport peers for subgroup 0, including across a moq-lite-07 hop between two relays that negotiate the [ietf](/draft/moq-ietf) extension. Plain Rust readers and moq-lite peers without the extension see consecutive frames. moq-transport maps a [datagram track](/concept/moq-lite#datagrams) to `SUBSCRIBE` and `OBJECT_DATAGRAM`, with its sequence as the group ID and object ID 0. One upstream subscription serves both kinds of a name. Stream consumers receive only stream objects, and datagram consumers receive only object 0 datagrams, including through relays. An undefined Object Status or malformed datagram framing closes the session. Unreadable object properties drop only that datagram. A relayed Timestamp leaves in the units the downstream response declares, and is dropped where it declares none, as for a plain frame; an immutable one that would change or vanish is refused. On a timed track the frame holds each object's time, so a mutable Timestamp that only repeats the immutable one is not restated; a status object has no frame, so it keeps its Timestamp among its properties. Only property 0x10 is read as a Timestamp. Property 0x06 stays opaque and keeps its value regardless of timestamp units; it is dropped between draft 18 and later drafts, or refused when immutable, because draft 20 assigns it to SUBGROUP\_DELIVERY\_TIMEOUT. A status object carrying properties is refused. A `FETCH` has no status objects, so its response ends at the last frame. A group cannot resume across route changes by frame ordinal once Object IDs skip ahead of the ordinals on either route; recovery refuses it instead of splicing different objects. @@ -45,7 +45,6 @@ Several project drafts extend the IETF wire without breaking it, since `SETUP` ignores unknown parameters: [cluster](/draft/moq-cluster) routing hop lists, [solicit](/draft/moq-solicit) to make announcements opt-in, [hidden](/draft/moq-hidden) to keep `.`-named namespaces out of discovery, -[auth](/draft/moq-auth) to tell each peer what it may publish and subscribe to, [active-count](/draft/moq-active-count) to count the `NAMESPACE` messages before a `SUBSCRIBE_NAMESPACE` is synced, and [probe](/draft/moq-probe) for bandwidth estimation. Rust sessions request PROBE @@ -54,9 +53,8 @@ The consumer reads the estimate, and a viewer reads its share of it; session statistics do not request PROBE. The viewers' ceilings, summed, are the PROBE target, sent only to a peer advertising `Increase`, which a native session over moq-quic with BBR3 does and a browser session does not yet. -Both libraries offer solicit and auth unless a side's -`extensions` setting declines one, which connects it as a peer that does not -speak that extension. The pooled JavaScript `Connection` has no such setting yet. +Both libraries offer solicit unless a side's `extensions` setting declines it, +which connects it as a peer that does not speak that extension. The pooled JavaScript `Connection` has no such setting yet. moq-transport carries no [publisher instance](/concept/moq-lite#publisher-instances), so the receiving session mints one per announcement; the [epoch draft](/draft/moq-epoch) remains an unimplemented proposal. diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index fef1c6f21c1..cc447f7e2c7 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -249,7 +249,7 @@ A producer publishes everything you write, subscribed or not, so a late subscrib ## Authorization -On `moq-lite-07-wip` (opt in with `ClientConfig::versions`) and on moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth), `session->grants()` returns a `GrantConsumer`: `grant()` is the `Grant` the relay sent back, empty until it answers and while a client session reconnects, and `changed()` waits for the next one until `cancel()`. +On `moq-lite-07-wip` (opt in with `ClientConfig::versions`), `session->grants()` returns a `GrantConsumer`: `grant()` is the `Grant` the relay sent back, empty until it answers and while a client session reconnects, and `changed()` waits for the next one until `cancel()`. Set `ClientConfig::tokens` instead of putting the credential in the URL. The first is the connection credential, sent in SETUP and, while an offered version can't carry it there (lite before 07), as the URL's `?jwt=`; each other token widens the grant over AUTH. `session->tokens()->set(...)` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the session redials only if they changed. `answered()` resolves once the relay accepts them, or to an `Error` carrying its refusal code. A server-accepted session's `tokens()` is null. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index f65491913f1..31b58bd7022 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -158,7 +158,7 @@ shows which module holds each. - **Ending cleanly.** When the input ends, finish every track, then call `finish()` on its `CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` or disposing its `MoqRoute` takes it offline. How long to keep it up is yours to decide. A track still open at the close, or released without a finish, ends with `Unroutable` (`Internal` over moq-transport, which has no such code). Readers follow a publisher's runs by announcement, not by that error: see [identity and recovery](/concept/identity). - **Stats.** `session.stats()` reports `rtt`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`), and `datagramsUnrouted`, the datagrams received for a subscription with no datagram track, reported only on moq-lite 05 and later, which carry datagrams. A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Viewers.** `client.viewers()` divides the connection's receive estimate among the broadcasts you watch, max-min fair by each one's ceiling. `watch(maxBps: ...)` returns a `Viewer` claiming up to what the largest rendition the player would switch to needs; `rate()` reads its slice in bits per second, `null` while there is no estimate, so hold the current selection. `update(maxBps: ...)` changes the ceiling, such as when the catalog enables or disables a rendition. Holding a viewer requests PROBE, and the session sends the viewers' summed ceilings as the PROBE target; `dispose()` it once the broadcast stops being watched. `setTarget(targetBps: ...)` sends another target, `0` sends none, and `null` follows the viewers again. Ceilings or a target past 2^53 - 1 bps, the most a PROBE target carries, throw `OutOfRangeMoqException`. Client viewers survive reconnects and read `null` while disconnected. -- **Authorization.** On `moq-lite-07-wip` (opt in with `ConnectOptions(versions: ...)`) and on moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth), listen to `moq.grants().updates()` for the `Grant` the relay sent back and each change, `null` until it answers and while a client session reconnects. +- **Authorization.** On `moq-lite-07-wip` (opt in with `ConnectOptions(versions: ...)`), listen to `moq.grants().updates()` for the `Grant` the relay sent back and each change, `null` until it answers and while a client session reconnects. - **Tokens.** Pass `ConnectOptions(tokens: [...])` instead of putting the credential in the URL. The first is the connection credential, sent in SETUP and, while an offered version can't carry it there (lite before 07), as the URL's `?jwt=`; each other token widens the grant over AUTH. `moq.tokens().set_(tokens: [...])` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the session redials only if they changed. `await tokens().answered()` returns once the relay accepts them and throws its refusal with the relay's code. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. Audio and video subscribe setup returns `UnsupportedConfigMoqException` when the decoder refuses the codec, layout, or description; a player can then try its next ranked rendition. Decoder faults and later peer or decode failures do not report that setup refusal. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index 8f3a4e95c1c..2865952ed30 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -135,7 +135,7 @@ shows which module holds each. - **Ending cleanly.** When the input ends, finish every track, then call `Finish()` on its `media.CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.Close()` takes it offline. How long to keep it up is yours to decide. A track still open at the close, or released without a finish, ends with `Unroutable` (`Internal` over moq-transport, which has no such code). Readers follow a publisher's runs by announcement, not by that error: see [identity and recovery](/concept/identity). - **Stats.** `Session().Stats()` reports `RTT`, `EstimatedSendRateBps`, and the byte and packet counters (`BytesSent`, `BytesReceived`, `BytesLost`, `PacketsSent`, `PacketsReceived`, `PacketsLost`), and `DatagramsUnrouted`, the datagrams received for a subscription with no datagram track, reported only on moq-lite 05 and later, which carry datagrams. A field is nil when the transport does not report it, which is not the same as zero. `Version` names the negotiated protocol. `Dial` returns a connecting session; read `Session().State()` and wait with `StateChanged(ctx, state.Revision)` to observe first-dial failures and reconnects. Hold the owned `BandwidthConsumer` returned by `Session().RecvBandwidth()` to receive bandwidth estimates. `Rate()` reads the current estimate in bits per second and `RateChanged(ctx)` waits for a new one. Calling `Cancel()` on the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Viewers.** `Session().Viewers()` divides the connection's receive estimate among the broadcasts you watch, max-min fair by each one's ceiling. `Watch(maxBps)` returns a `Viewer` claiming up to what the largest rendition the player would switch to needs; `Rate()` reads its slice in bits per second, nil while there is no estimate, so hold the current selection. `Update(maxBps)` changes the ceiling, such as when the catalog enables or disables a rendition. Holding a viewer requests PROBE, and the session sends the viewers' summed ceilings as the PROBE target; `Close()` it once the broadcast stops being watched, from the goroutine that last used it. `SetTarget(&bps)` sends another target, zero sends none, and nil follows the viewers again. `Watch`, `Update`, and `SetTarget` return `moq.ErrOutOfRange` when the ceilings or the target would pass 2^53 - 1 bps, the most a PROBE target carries. Client viewers survive reconnects and read nil while disconnected. -- **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig.Versions`) and on moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth), `Session().Grants()` returns a `GrantConsumer`: `Grant()` is the `Grant` the relay sent back, nil until it answers and while a client session reconnects, and `Changed(ctx)` waits for the next one. `Cancel()` it when done. +- **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig.Versions`), `Session().Grants()` returns a `GrantConsumer`: `Grant()` is the `Grant` the relay sent back, nil until it answers and while a client session reconnects, and `Changed(ctx)` waits for the next one. `Cancel()` it when done. - **Tokens.** Set `ClientConfig.Tokens` instead of putting the credential in the URL. The first is the connection credential, sent in SETUP and, while an offered version can't carry it there (lite before 07), as the URL's `?jwt=`; each other token widens the grant over AUTH. `Session().Tokens().Set(...)` replaces a client session's tokens before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the session redials only if they changed. `Answered(ctx)` returns nil once the relay accepts them, or its refusal with the relay's code. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. - **Errors.** Read diagnostic payloads from `Reason` and structured protocol failures from `Details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `Preference`; `0` is the default and `-1` marks a compatibility transcode. Audio and video subscribe setup returns `moq.ErrUnsupportedConfig` when the decoder refuses the codec, layout, or description; a player can then try its next ranked rendition. Decoder faults and later peer or decode failures do not report that setup refusal. diff --git a/doc/lib/index.md b/doc/lib/index.md index eb8b791553b..f5061541e1e 100644 --- a/doc/lib/index.md +++ b/doc/lib/index.md @@ -75,7 +75,7 @@ how it looks in that language: - **Catalog extensions**: write your own section next to `video` and `audio`, and read others' back. - **Routes**: see which relays a broadcast came through, and advertise a cost as a standby publisher. - **Connection stats** and **errors** that tell an auth rejection (don't retry) from a shutdown or a transport failure. -- **Authorization in band**: read the grant the relay sent back (the patterns this side may publish and subscribe to, and when it lapses), and present a fresh token before the current one expires, without reconnecting. It needs `moq-lite-07-wip`, which is opt-in, or moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth). +- **Authorization in band**: read the grant the relay sent back (the patterns this side may publish and subscribe to, and when it lapses), and present a fresh token before the current one expires, without reconnecting. It needs `moq-lite-07-wip`, which is opt-in. C cannot fetch a single group by sequence. diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index cffb5956f93..dadddf1f5ef 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -59,7 +59,7 @@ route.announce(); - **Subscription defaults.** `Track.Subscription.default()` returns the default subscription, whose zero `delay.max` skips a superseded group at once; calling `subscribe()` with no options means the same. An omitted `delay` field means the same zero; `max: null` sets no subscriber limit. - **A subscription asks for `ranges`.** Each [range](/concept/moq-lite#subscriptions) starts and ends at an `absolute` group, one `relative` to the latest, or the group containing a `time` (a `Timestamp`), and a reader reads only its own ranges. A read whose ranges all end finishes once every group in them is handed out, dropped, or skipped, as in Rust. A time anchor needs a timed track and `moq-lite-07-wip` over a session. Passing the old `groups` key throws a `TypeError` naming `ranges`; `withRange` only narrows reads locally. - **Hidden paths** stay out of discovery unless the announce request opts in. See [hidden broadcasts](/concept/moq-lite#hidden-broadcasts). -- **Authorization is in band.** On moq-lite 07 (opt in with `versions: ["moq-lite-07-wip", "moq-lite-06"]`, listing every fallback you still want) and on moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth), `auth.grant` watches what the relay lets this side publish and subscribe to, and `auth.add(token)` presents another token without reconnecting. Publishing outside the grant closes the connection with `SessionCode.Unauthorized`, naming the path. On moq-lite, a subscription or track listing the grant stops covering resets with `StreamCode.Unauthorized` and the session stays up. On moq-transport, `auth.add(token)` keeps the token even without the extension, and a route created with the `Auth.Credential` it returns (`origin.route(path, { auth })`) carries it on that announcement's `PUBLISH_NAMESPACE`; `route.setAuth(other)` renews the request. A `Connection`'s `auth` handle (a getter on a pooled connection, following its URL) outlives its sessions: a token added there is presented on every reconnect and keeps riding the announcements that name it, with no re-add or re-announce. A one-shot session's `auth` ends with it, unless `Connection.connect` was given a `new Auth.Handle()` as `auth`. +- **Authorization is in band.** On moq-lite 07 (opt in with `versions: ["moq-lite-07-wip", "moq-lite-06"]`, listing every fallback you still want), `auth.grant` watches what the relay lets this side publish and subscribe to, and `auth.add(token)` presents another token without reconnecting. Publishing outside the grant closes the connection with `SessionCode.Unauthorized`, naming the path. On moq-lite, a subscription or track listing the grant stops covering resets with `StreamCode.Unauthorized` and the session stays up. On moq-transport, `auth.add(token)` only keeps the token for the requests that name it: a route created with the `Auth.Credential` it returns (`origin.route(path, { auth })`) carries it on that announcement's `PUBLISH_NAMESPACE`; `route.setAuth(other)` renews the request. A `Connection`'s `auth` handle (a getter on a pooled connection, following its URL) outlives its sessions: a token added there is presented on every reconnect and keeps riding the announcements that name it, with no re-add or re-announce. A one-shot session's `auth` ends with it, unless `Connection.connect` was given a `new Auth.Handle()` as `auth`. - **A graceful close waits.** `await connection.close()` withdraws announcements and drains for up to one second. `moq-lite-05` and newer wait for the subscriber to receive finished tails; older Lite versions wait only for transport ACKs. IETF media streams are not drained. `abort()` ends immediately. Examples: diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index 369105923ba..bec369752a5 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -112,7 +112,7 @@ shows which module holds each. - **Ending cleanly.** When the input ends, finish every track, then call `finish()` on its `CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.end()` takes it offline. How long to keep it up is yours to decide. A track still open at the end, or released without a finish, ends with `Unroutable` (`Internal` over moq-transport, which has no such code). Readers follow a publisher's runs by announcement, not by that error: see [identity and recovery](/concept/identity). - **Stats.** `session.stats()` reports `rtt`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`), and `datagramsUnrouted`, the datagrams received for a subscription with no datagram track, reported only on moq-lite 05 and later, which carry datagrams. A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Viewers.** `moq.viewers()` divides the connection's receive estimate among the broadcasts you watch, max-min fair by each one's ceiling. `watch(maxBps)` returns a `Viewer` claiming up to what the largest rendition the player would switch to needs; `rate()` reads its slice in bits per second, `null` while there is no estimate, so hold the current selection. `update(maxBps)` changes the ceiling, such as when the catalog enables or disables a rendition. Holding a viewer requests PROBE, and the session sends the viewers' summed ceilings as the PROBE target; `close()` it, or leave `use { }`, once the broadcast stops being watched. `setTarget(bps)` sends another target, `0` sends none, and `null` follows the viewers again. Ceilings or a target past 2^53 - 1 bps, the most a PROBE target carries, throw `MoqException.OutOfRange`. Client viewers survive reconnects and read `null` while disconnected. -- **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig(versions = ...)`) and on moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth), collect `moq.grants().updates()` for the `Grant` the relay sent back and each change, `null` until it answers and while a client session reconnects. Ending the collection cancels the consumer. +- **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig(versions = ...)`), collect `moq.grants().updates()` for the `Grant` the relay sent back and each change, `null` until it answers and while a client session reconnects. Ending the collection cancels the consumer. - **Tokens.** Pass `ClientConfig(tokens = listOf(...))` instead of putting the credential in the URL. The first is the connection credential, sent in SETUP and, while an offered version can't carry it there (lite before 07), as the URL's `?jwt=`; each other token widens the grant over AUTH. `moq.tokens().set(listOf(...))` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the session redials only if they changed. Suspending `tokens().answered()` returns once the relay accepts them and throws its refusal with the relay's code. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. Audio and video subscribe setup returns `MoqException.UnsupportedConfig` when the decoder refuses the codec, layout, or description; a player can then try its next ranked rendition. Decoder faults and later peer or decode failures do not report that setup refusal. diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 51ca45f9b3c..4cecd17f34b 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -127,7 +127,7 @@ shows which module holds each. - **Ending cleanly.** When the input ends, finish every track, then call `finish()` on its `moq.media.CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. A track still open at the close, or released without a finish, ends with `Unroutable` (`Internal` over moq-transport, which has no such code). Readers follow a publisher's runs by announcement, not by that error: see [identity and recovery](/concept/identity). - **Stats.** `session.stats()` reports `rtt`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`), and `datagrams_unrouted`, the datagrams received for a subscription with no datagram track, reported only on moq-lite 05 and later, which carry datagrams. A field is `None` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recv_bandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rate_changed()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Viewers.** `session.viewers()` divides the receive estimate among the broadcasts you watch. `watch(max_bps)` returns a `Viewer` claiming up to a ceiling, the bitrate of the largest rendition you would switch to; its `rate()` reads that viewer's fair share in bits per second, `None` while there is no estimate (keep the current rendition), and `update(max_bps)` changes the ceiling. Holding a viewer requests the estimate like `recv_bandwidth()`, and dropping it releases the claim. The session sends the summed ceilings as its PROBE target; `set_target(bps)` overrides that, `0` sends none, and `None` follows the viewers again. Ceilings or a target past 2^53 - 1 bps, the most a PROBE target carries, raise `moq.Error.OutOfRange`. -- **Authorization.** On `moq-lite-07-wip` (opt in with `versions=`) and on moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth), `async for grant in session.grants()` yields the `Grant` the relay sent back and each change, `None` until it answers and while a client session reconnects. `grants().grant()` reads it once; cancelling or leaving an `async with` releases the wait. +- **Authorization.** On `moq-lite-07-wip` (opt in with `versions=`), `async for grant in session.grants()` yields the `Grant` the relay sent back and each change, `None` until it answers and while a client session reconnects. `grants().grant()` reads it once; cancelling or leaving an `async with` releases the wait. - **Tokens.** Pass `tokens=[...]` instead of putting the credential in the URL. The first is the connection credential, sent in SETUP and, while an offered version can't carry it there (lite before 07), as the URL's `?jwt=`; each other token widens the grant over AUTH. `session.tokens().set([...])` replaces a client session's tokens before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the session redials only if they changed. `await tokens.answered()` returns once the relay accepts them and raises its refusal with the relay's code. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. Audio and video subscribe setup returns `moq.Error.UnsupportedConfig` when the decoder refuses the codec, layout, or description; a player can then try its next ranked rendition. Decoder faults and later peer or decode failures do not report that setup refusal. diff --git a/doc/lib/rs/moq-net.md b/doc/lib/rs/moq-net.md index 2925131f324..bc3c195c952 100644 --- a/doc/lib/rs/moq-net.md +++ b/doc/lib/rs/moq-net.md @@ -31,7 +31,7 @@ What you use it for, beyond what the concept page already describes: - **You drive the session, or `moq-tokio` does.** `connect` and `accept` return a session plus a driver that never reads the clock itself. `moq_net::time::run` polls it on tokio. `moq-tokio` hides that. A custom transport implements `moq_net::transport::poll`, and `moq_net::transport::memory::pair` links two sessions in one process with no sockets, for tests or in-process links. `Server` bounds each accept with one deadline (10 s by default, `with_timeout`) across SETUP, your admission decision (`Handshake::expired`), and moq-lite 01/02's SETUP reply, and opens a receive window the transport held back once you admit (`with_receive_window`). - **Reconnect policy comes with it.** With the `async` feature, `moq_net::Reconnect` decides which of a peer's addresses to dial, how long each dial and handshake may take, when to back off and give up, and how to follow a GOAWAY, without doing I/O: you dial each `Attempt` it asks for and report back. `moq-tokio`'s `Connection` runs it, so a client on another runtime gets the same policy rather than a copy. - **A session bounds what its peer can hold.** Each request holds a stream, so the transport's stream credit bounds subscriptions and FETCHes. Once that credit runs out, a waiting open resets the lowest-priority group stream below it, which the subscriber sees dropped, so the credit it frees goes to the higher-priority group. `session::Limits` (via `Client::with_limits` and `Server::with_limits`) bounds the announcements per session. The default suits a relay mesh, so lower it for untrusted peers. Past it, the session closes with `TOO_MANY_REQUESTS`. Peer-declared lengths are capped before they are buffered. -- **Authorization is in band.** On moq-lite 07 (`moq-lite-07-wip`, opt-in) and on moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth()` presents tokens without reconnecting and watches the grant the peer sent back. `add(token)` resolves with the token once the peer takes it: on its AUTH stream, or on moq-transport without AUTH, where only a request that names it carries it. A handle passed to `Client::with_auth` outlives each session, so its tokens, and the routes naming them, carry across your own reconnects. A server verifies tokens itself by taking `handshake.requests()` before `ok()`. `authorize(&grant)` narrows or widens a live session on any version: what falls outside resets with `Unauthorized` and the session stays up. A client that publishes outside its grant closes the session, naming the path. +- **Authorization is in band.** On moq-lite 07 (`moq-lite-07-wip`, opt-in), `session.auth()` presents tokens without reconnecting and watches the grant the peer sent back. `add(token)` resolves with the token once the peer takes it: on its AUTH stream, or on moq-transport without AUTH, where only a request that names it carries it. A handle passed to `Client::with_auth` outlives each session, so its tokens, and the routes naming them, carry across your own reconnects. A server verifies tokens itself by taking `handshake.requests()` before `ok()`. `authorize(&grant)` narrows or widens a live session on any version: what falls outside resets with `Unauthorized` and the session stays up. A client that publishes outside its grant closes the session, naming the path. - **A graceful close waits.** `session.close().await` withdraws announcements and drains for up to one second. `moq-lite-05` and newer wait for the subscriber to receive finished tails; older Lite versions and IETF wait only for transport ACKs. `abort` ends immediately. ```bash diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index b35e5fe4976..1879f3c92bb 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -109,7 +109,7 @@ shows which module holds each. - **Ending cleanly.** When the input ends, finish every track, then call `try finish()` on its `Media.CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()`, or releasing its route, takes it offline. How long to keep it up is yours to decide. A track still open at the close, or released without a finish, ends with `Unroutable` (`Internal` over moq-transport, which has no such code). Readers follow a publisher's runs by announcement, not by that error: see [identity and recovery](/concept/identity). - **Stats.** `session.stats()` reports `rtt`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`), and `datagramsUnrouted`, the datagrams received for a subscription with no datagram track, reported only on moq-lite 05 and later, which carry datagrams. A field is `nil` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Viewers.** `session.viewers()` divides the receive estimate among the broadcasts you watch. `watch(maxBps:)` returns a `Viewer` claiming up to a ceiling, the bitrate of the largest rendition you would switch to; its `rate()` reads that viewer's fair share in bits per second, `nil` while there is no estimate (keep the current rendition), and `update(maxBps:)` changes the ceiling. Holding a viewer requests the estimate like `recvBandwidth()`, and releasing it releases the claim. The session sends the summed ceilings as its PROBE target; `setTarget(targetBps:)` overrides that, `0` sends none, and `nil` follows the viewers again. `watch`, `update`, and `setTarget` throw `MoqError.OutOfRange` when the ceilings or the target would pass 2^53 - 1 bps, the most a PROBE target carries. -- **Authorization.** On `moq-lite-07-wip` (opt in with `Client(versions:)`) and on moq-transport draft-18+ with the [MoQ Auth extension](/draft/moq-auth), `for try await grant in session.grants()` yields the `Grant` the relay sent back and each change, `nil` until it answers and while a client session reconnects. Cancelling the iterating task cancels the native wait. +- **Authorization.** On `moq-lite-07-wip` (opt in with `Client(versions:)`), `for try await grant in session.grants()` yields the `Grant` the relay sent back and each change, `nil` until it answers and while a client session reconnects. Cancelling the iterating task cancels the native wait. - **Tokens.** Pass `Client(tokens: [...])` instead of putting the credential in the URL. The first is the connection credential, sent in SETUP and, while an offered version can't carry it there (lite before 07), as the URL's `?jwt=`; each other token widens the grant over AUTH. `try session.tokens()?.set([...])` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the session redials only if they changed. `try await tokens.answered()` returns once the relay accepts them and throws its refusal with the relay's code. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. - **Errors.** Diagnostic cases use the `reason:` argument label; match their associated value to inspect it. Protocol errors carry `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. Audio and video subscribe setup returns `MoqError.UnsupportedConfig` when the decoder refuses the codec, layout, or description; a player can then try its next ranked rendition. Decoder faults and later peer or decode failures do not report that setup refusal. diff --git a/drafts/draft-lcurley-moq-auth.md b/drafts/draft-lcurley-moq-auth.md deleted file mode 100644 index 2bb3dfbcbd8..00000000000 --- a/drafts/draft-lcurley-moq-auth.md +++ /dev/null @@ -1,264 +0,0 @@ ---- -title: "MoQ Auth Extension" -abbrev: "moq-auth" -category: info - -docname: draft-lcurley-moq-auth-latest -submissiontype: IETF # also: "independent", "editorial", "IAB", or "IRTF" -number: -date: -v: 3 -area: wit -workgroup: moq - -author: - - - fullname: Luke Curley - email: kixelated@gmail.com - -normative: - moqt: I-D.ietf-moq-transport - moq-lite: I-D.lcurley-moq-lite - -informative: - ---- abstract - -This document defines an extension for MoQ Transport {{moqt}} that tells an endpoint what its peer will let it publish and subscribe to. -Either endpoint presents a token on a request stream of its own, and the peer answers with the namespace patterns the token grants and when that grant lapses. -Tokens can be added and withdrawn for the life of the session, so a session can outlive the credential it started with. -An endpoint that knows its grant can fail loudly on a publication that will never be accepted, instead of waiting for a subscription that never comes. - ---- note_Note_to_Readers - -This document was generated by an AI model from the implementation at [github.com/moq-dev/moq](https://github.com/moq-dev/moq) and is maintained alongside it. -Submit an [issue](https://github.com/moq-dev/moq/issues) or [PR](https://github.com/moq-dev/moq/pulls) if this spec sucks and you want to fix anything. - ---- middle - -# Conventions and Definitions -{::boilerplate bcp14-tagged} - -The **presenter** of a token is the endpoint that sends it in AUTH, and the **acceptor** is the endpoint that answers. -A **grant** is what the acceptor allows for one token: the namespaces the presenter may publish to it, the namespaces the presenter may subscribe to from it, and an optional expiry. - - -# Introduction -{{moqt}} authorizes each request on its own. -A publisher learns that a namespace is refused only by sending PUBLISH_NAMESPACE and reading the REQUEST_ERROR, and learns nothing at all from a relay that forwards only what it is asked for. -Nothing on the wire says which role an endpoint will ever be allowed to play ([moq-transport issue 1854](https://github.com/moq-wg/moq-transport/issues/1854)), so a client authorized to publish only `alice` that publishes `bob` waits forever, and neither side logs anything. - -This extension answers that question once per credential. -Right after setup each endpoint presents the credential its connection already carried, and learns the grant it earned. -Further tokens are presented on their own request streams, and the endpoint's scope is the union of every grant it holds. - -The exchange is the Auth Stream of {{moq-lite}}, carried as {{moqt}} request streams and negotiated with a Setup Option. - - -# Setup Negotiation - -An endpoint that implements this extension sends the following Setup Option ({{moqt}} Section 9.4.1): - -~~~ -AUTH Setup Option { - Option Key (vi64) = 0x40B70 - Option Value (vi64) = 1 -} -~~~ - -The extension is negotiated when both endpoints sent the option with a value of 1. -An endpoint MUST NOT send AUTH on a session that did not negotiate it, and an endpoint that receives AUTH anyway MUST close the session with PROTOCOL_VIOLATION, as it would for any unknown message type. - -This extension is defined for the versions of {{moqt}} with the unified SETUP message, draft-18 and later. - - -# Auth Requests {#requests} - -A presenter opens a bidirectional request stream for each token and sends a single AUTH message on it. -The stream lives as long as the token, the way a subscription's request stream outlives its SUBSCRIBE_OK. - -Each endpoint SHOULD open one Auth request with an empty token as soon as the extension is negotiated. -An empty token presents the credential the connection already carried: the request URI, a client certificate, an AUTHORIZATION TOKEN Setup Option ({{moqt}} Section 9.4.1), or nothing. -Its grant tells the presenter which role the acceptor will let it play. - -The acceptor answers with AUTH_OK carrying the grant, or AUTH_ERROR refusing the token. -It MAY send further AUTH_OK messages to replace the grant, such as with a lowered expiry, and the latest AUTH_OK is the token's grant. -It MAY send AUTH_ERROR after an AUTH_OK to revoke the grant. -After an AUTH_ERROR the acceptor closes its side of the stream. - -The presenter withdraws a token by closing or resetting its side of the stream, and the acceptor then closes its own. -An acceptor that closes its side without an AUTH_ERROR ends the grant without a reason. - -A receiver MUST close the session with PROTOCOL_VIOLATION if an AUTH message fails to decode, has trailing body bytes, or has an unexpected type for its direction. -A presenter sends exactly one AUTH on its request stream; any additional message is a PROTOCOL_VIOLATION. - -## Scope {#scope} - -An endpoint's scope is the union of the grants of its open Auth requests. -A request that ends, by withdrawal, revocation, or a stream error, removes its grant from the union. -An empty union grants nothing, and the session stays open for another token. - -A grant tells the presenter what the acceptor will allow; it does not replace the acceptor's own enforcement, which MUST still refuse what the grant does not cover. - -When the union shrinks, the presenter SHOULD withdraw its advertisements and cancel its subscriptions that the union no longer covers, keeping the session and everything still covered. - -A presenter that would advertise a namespace outside the union, once the tokens it presented at setup are answered, SHOULD close the session with UNAUTHORIZED instead of sending PUBLISH_NAMESPACE, since a subscription for it will never come. -A publication that loses coverage because the union shrank is withdrawn, which is no reason to close the session. - -## Request Tokens - -An acceptor that verifies {{moqt}} AUTHORIZATION TOKEN request parameters treats each distinct token on a session as one implicit Auth request while any open request names it. -Its grant MUST NOT join the session scope: a naming request uses that grant alone, and a request without the token gains nothing from it. -The acceptor verifies the token when its first naming request opens and ends its grant when the last naming request ends; a later request verifies it again. -Expiry or revocation ends every naming request. -A request is admitted either by the session or by a token, and that never changes. -A REQUEST_UPDATE carrying a token replaces the token authority of a request a token admitted, including when the update pauses forwarding; the acceptor MUST verify the token before acknowledging the update. -On a request the session admitted, the acceptor MUST refuse an update carrying a token. -A joining FETCH retains its subscription's authority. - -## Patterns {#patterns} - -A grant names Path Patterns of {{moq-lite}}, with the same grammar, canonical form, and encoding as its AUTH_OK. -A pattern matches a Track Namespace as the path of the namespace's fields joined by `/`, where a `/` or `\` inside a field is preceded by a `\`. -Patterns are relative to the session, as its Track Namespaces are, and a count of zero grants none. -A pattern that breaks the grammar or is not canonical is a PROTOCOL_VIOLATION. - -An acceptor MUST NOT widen or trim a grant to fit one AUTH_OK. -For a grant too large to encode, it writes nothing of the AUTH_OK and sends AUTH_ERROR with NOT_SUPPORTED instead: as the first reply this refuses the token, and after an AUTH_OK it revokes the earlier grant. -Other tokens on the session are unaffected. - - -# Messages - -Each message is a {{moqt}} Control Message, framed by its Message Type and a 16-bit Message Length. - -## AUTH {#auth} - -AUTH is the first message on an Auth request stream, sent by the presenter. - -~~~ -AUTH Message { - Type (vi64) = 0x40B61, - Length (16), - Request ID (vi64), - Token Length (vi64), - Token (..), -} -~~~ - -**Request ID**: -The request's identifier, allocated from the same space as every other request ({{moqt}}). -A duplicate or wrong-parity Request ID closes the session with INVALID_REQUEST_ID, including an ID from an AUTH that has ended. - -**Token**: -The credential to verify, opaque to this extension. -An empty token presents the credential the connection already carried ({{requests}}). - -## AUTH_OK {#auth-ok} - -AUTH_OK grants the token, replacing any earlier grant on the same stream. - -~~~ -AUTH_OK Message { - Type (vi64) = 0x40B62, - Length (16), - Publish Count (vi64), - Publish Pattern (Pattern) ..., - Subscribe Count (vi64), - Subscribe Pattern (Pattern) ..., - Expires (vi64), -} - -Pattern { - Pattern Length (vi64), - Pattern (..), -} -~~~ - -**Publish Pattern**: -A pattern matching the namespaces the presenter may advertise and serve ({{patterns}}). - -**Subscribe Pattern**: -A pattern matching the namespaces the presenter may subscribe to and discover. - -**Expires**: -The number of milliseconds until the grant lapses, or 0 for never. -Expires MUST NOT exceed 2^53 - 1 milliseconds; a larger value is a PROTOCOL_VIOLATION. -The acceptor revokes a lapsed grant with AUTH_ERROR, and the presenter uses Expires to present a replacement token in time. - -## AUTH_ERROR {#auth-error} - -AUTH_ERROR refuses the token, or revokes it after an AUTH_OK. - -~~~ -AUTH_ERROR Message { - Type (vi64) = 0x40B63, - Length (16), - Error Code (vi64), - Reason Phrase Length (vi64), - Reason Phrase (..), -} -~~~ - -**Error Code**: -A code MUST fit in 32 bits; a larger value is a PROTOCOL_VIOLATION. -A code from the REQUEST_ERROR registry ({{moqt}}): UNAUTHORIZED, MALFORMED_AUTH_TOKEN, EXPIRED_AUTH_TOKEN, NOT_SUPPORTED ({{patterns}}), or GOING_AWAY. -GOING_AWAY answers an AUTH the acceptor no longer admits after its GOAWAY ({{moqt}}); it refuses the request, not the token, so the token stays valid for another session. - -**Reason Phrase**: -A human-readable reason, at most 8,192 bytes. - - -# Security Considerations - -A token presented in AUTH is as sensitive as one in the request URI or an AUTHORIZATION TOKEN, and relies on the same transport confidentiality. - -A grant is advice to the presenter, never authority for the acceptor: the acceptor MUST enforce its own authorization on every request whatever it granted. -A presenter that trusts a grant too far only fails on the acceptor's REQUEST_ERROR, as it would without this extension. - -Auth requests count against the peer's request and stream limits like any other request. - - -# IANA Considerations - -This document requests the following registrations. -High, distinctive values are requested to avoid the low ranges reserved by {{moqt}} and to minimize collisions with provisional registrations by other extensions. - -## MOQT Setup Options - -This document requests one registration in the "MOQT Setup Options" registry ({{moqt}}), whose policy is Specification Required. - -| Value | Name | Reference | -|:--------|:-----|:--------------| -| 0x40B70 | AUTH | This Document | - -AUTH is even, so its value is a bare varint. - -## MOQT Message Types - -This document requests three registrations in the "MOQT Message Types" registry ({{moqt}}). - -| Value | Name | Reference | -|:--------|:-----------|:--------------| -| 0x40B61 | AUTH | This Document | -| 0x40B62 | AUTH_OK | This Document | -| 0x40B63 | AUTH_ERROR | This Document | - - ---- back - -# Changelog - -## Since draft-lcurley-moq-auth-00 (in progress) - -- Request tokens share verification and lifetime per distinct token, isolated from session scope; updates replace a token-admitted request's token, even while pausing or resuming, and a token on a session-admitted request's update is refused. - -- AUTH_ERROR can carry GOING_AWAY, refusing an AUTH past the acceptor's GOAWAY without refusing the token. -- AUTH_OK carries moq-lite Path Patterns instead of Track Namespace prefixes, and a grant is refused only when too large for one AUTH_OK. -- The AUTH Setup Option moves from 0x40B60 to 0x40B70. -- Defined for {{moqt}} draft-18 and later, instead of draft-17 and later. - -# Acknowledgments -{:numbered="false"} - -This document was drafted with the assistance of Claude, an AI assistant by Anthropic. diff --git a/go/wrapper/session.go b/go/wrapper/session.go index 7bd00a89a1b..ce4dbc1ed94 100644 --- a/go/wrapper/session.go +++ b/go/wrapper/session.go @@ -138,8 +138,7 @@ func (s *Session) Grants() *GrantConsumer { // GrantConsumer follows the grant a session's peer gave it: the union of every // token the session presented. // -// AUTH is only on moq-lite-07-wip and on moq-transport sessions that negotiate -// the MoQ Auth extension; elsewhere the grant stays nil. +// AUTH is only on moq-lite-07-wip; elsewhere the grant stays nil. type GrantConsumer struct { inner *ffi.MoqGrantConsumer } diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index d4c58737369..3c5d969fcab 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -3,9 +3,7 @@ import { Duration, Manual, yieldNow } from "@moq/clock"; import { Duplicate, type Grant, Handle, type Issued, type Request, type Requests, Unsupported } from "./auth.ts"; import { accept as acceptSession, connect as connectSession, type Session } from "./connection/index.ts"; import { SessionCode, SessionError, StreamCode, StreamError, toStreamCode } from "./error.ts"; -import { AuthMessage as IetfAuthMessage, IetfAuthWire } from "./ietf/auth.ts"; import * as Ietf from "./ietf/index.ts"; -import * as IetfMessage from "./ietf/message.ts"; import { AuthMessage as LiteAuthMessage, LiteAuthWire } from "./lite/auth.ts"; import * as Lite from "./lite/index.ts"; import * as LiteMessage from "./lite/message.ts"; @@ -83,8 +81,8 @@ function answer(requests: Requests, answer: (token: string) => Grant): Issued[] return issued; } -// Every case runs on moq-lite-07-wip and on moq-transport with the MoQ Auth extension. -describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { +// Every case runs on each version with AUTH streams: moq-lite-07-wip. +describe.each([Lite.ALPN_07_WIP])("%s", (protocol) => { test("a shared handle presents its token on every session", async () => { const handle = new Handle(); // Added before any session: it waits for the first. @@ -112,10 +110,8 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { await waitFor(token.grant, (g) => g?.publish.equals(patterns("second")) === true); await waitFor(handle.grant, (g) => g?.publish.equals(patterns("second")) === true); expect(ended).toBe(false); - // A route naming the token carries it on the new session's requests, on moq-transport. - const carried = wireOf(second.client).auth.carried(token); - if (protocol === Lite.ALPN_07_WIP) expect(carried).toBeUndefined(); - else expect(carried).toEqual(new TextEncoder().encode("token")); + // Only moq-transport requests carry a token. + expect(wireOf(second.client).auth.carried(token)).toBeUndefined(); token.close(); expect(await token.closed).toBeNull(); @@ -129,7 +125,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { const installed = clock.install(); const warned = spyOn(console, "warn").mockImplementation(() => {}); // The server's side of each AUTH stream carrying our token, in arrival order. - const Wire = protocol === Lite.ALPN_07_WIP ? LiteAuthWire : IetfAuthWire; + const Wire = LiteAuthWire; const original = Wire.prototype.accept; const streams: Stream[] = []; const accepted = spyOn(Wire.prototype, "accept").mockImplementation(async function ( @@ -173,7 +169,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { const clock = new Manual(); const installed = clock.install(); const warned = spyOn(console, "warn").mockImplementation(() => {}); - const Wire = protocol === Lite.ALPN_07_WIP ? LiteAuthWire : IetfAuthWire; + const Wire = LiteAuthWire; const original = Wire.prototype.accept; const streams: Stream[] = []; const accepted = spyOn(Wire.prototype, "accept").mockImplementation(async function ( @@ -1167,46 +1163,44 @@ test.each(Array.from({ length: 17 }, (_, gap) => gap))( }, ); -test.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])( - "%s carries literal and wildcard grants exactly", - async (protocol) => { - const { client, server } = await connect({ publish: new OriginProducer(), protocol }); - const requests = server.auth.requests(); - const unions: Record = { - "": [["a/**"], []], - exact: [["room/alice"], []], - wildcard: [["room/*/cam"], ["**/demo.hang"]], - mixed: [["room/**", "lobby", "cam-*.hang"], []], - root: [[""], ["**"]], - }; - const parse = (texts: string[]) => new Path.Patterns(texts.map((text) => Path.Pattern.parse(text))); - const issued: Issued[] = []; - void (async () => { - for (;;) { - const request = await requests.next(); - if (!request) break; - const [publish, subscribe] = unions[new TextDecoder().decode(request.token)] ?? [[], []]; - issued.push(request.accept({ publish: parse(publish), subscribe: parse(subscribe) })); - } - })(); - - await waitFor(client.auth.grant, (g) => g !== undefined); - for (const token of ["exact", "wildcard", "mixed", "root"]) { - const [publish, subscribe] = unions[token]; - const added = await client.auth.add(token); - const got = added.grant.peek(); - expect(got?.publish.equals(parse(publish))).toBe(true); - expect(got?.subscribe.equals(parse(subscribe))).toBe(true); +test.each([Lite.ALPN_07_WIP])("%s carries literal and wildcard grants exactly", async (protocol) => { + const { client, server } = await connect({ publish: new OriginProducer(), protocol }); + const requests = server.auth.requests(); + const unions: Record = { + "": [["a/**"], []], + exact: [["room/alice"], []], + wildcard: [["room/*/cam"], ["**/demo.hang"]], + mixed: [["room/**", "lobby", "cam-*.hang"], []], + root: [[""], ["**"]], + }; + const parse = (texts: string[]) => new Path.Patterns(texts.map((text) => Path.Pattern.parse(text))); + const issued: Issued[] = []; + void (async () => { + for (;;) { + const request = await requests.next(); + if (!request) break; + const [publish, subscribe] = unions[new TextDecoder().decode(request.token)] ?? [[], []]; + issued.push(request.accept({ publish: parse(publish), subscribe: parse(subscribe) })); } - client.abort(); - server.abort(); - }, -); + })(); + + await waitFor(client.auth.grant, (g) => g !== undefined); + for (const token of ["exact", "wildcard", "mixed", "root"]) { + const [publish, subscribe] = unions[token]; + const added = await client.auth.add(token); + const got = added.grant.peek(); + expect(got?.publish.equals(parse(publish))).toBe(true); + expect(got?.subscribe.equals(parse(subscribe))).toBe(true); + } + client.abort(); + server.abort(); +}); // moq-transport keeps the token for the requests that name it, with no grant of its own. test.each([ [Lite.ALPN_05, false], [Lite.ALPN_06, false], + [Ietf.ALPN.DRAFT_22, true], ])("%s has no grant, keeping a token for requests: %p", async (protocol, kept) => { const { client, server } = await connect({ publish: new OriginProducer(), protocol }); expect(client.auth.grant.peek()).toBeUndefined(); @@ -1229,56 +1223,6 @@ test.each([ server.abort(); }); -// With MoQ Auth negotiated, a reset AUTH stream fails the token rather than keeping it for -// requests: only a peer whose SETUP omitted the extension leaves tokens to requests. -test("a reset AUTH stream fails the token on moq-transport", async () => { - const { client, server } = await connect({ publish: new OriginProducer(), protocol: Ietf.ALPN.DRAFT_22 }); - await waitFor(client.auth.grant, (g) => g !== undefined); - const read = spyOn(IetfAuthWire.prototype, "read").mockRejectedValue( - new StreamError(StreamCode.Cancel, { message: "reset" }), - ); - try { - await expect(client.auth.add("token")).rejects.toBeInstanceOf(Unsupported); - } finally { - read.mockRestore(); - client.abort(); - server.abort(); - } -}); - -test("a GOING_AWAY refusal leaves a shared token for the next session on moq-transport", async () => { - const protocol = Ietf.ALPN.DRAFT_22; - const handle = new Handle(); - const first = await connect({ publish: new OriginProducer(), protocol, auth: handle }); - await waitFor(handle.grant, (g) => g !== undefined); - const read = spyOn(IetfAuthWire.prototype, "read").mockResolvedValue({ - refused: new StreamError(StreamCode.GoingAway), - }); - const warned = spyOn(console, "warn").mockImplementation(() => {}); - let rejected: unknown; - const adding = handle.add("token"); - adding.catch((err) => { - rejected = err; - }); - try { - await settles(() => warned.mock.calls.some(([line]) => line === "auth token refused")); - for (let i = 0; i < 10; i++) await yieldNow(); - expect(rejected).toBeUndefined(); - } finally { - read.mockRestore(); - warned.mockRestore(); - first.client.abort(); - first.server.abort(); - } - - const second = await connect({ publish: new OriginProducer(), protocol, auth: handle }); - answer(second.server.auth.requests(), (token) => (token ? grant(["second"], []) : grant([], []))); - const token = await adding; - await waitFor(token.grant, (g) => g?.publish.equals(patterns("second")) === true); - second.client.abort(); - second.server.abort(); -}); - // lite-07 presents the connection's credential on an Auth Stream right away; lite-06 never // opens one. test.each([ @@ -1433,15 +1377,12 @@ test("grants issued while a reply is blocked replace the one still queued", asyn // Capture the acceptor's actual AUTH writer after a valid setup grant. The following // bytes travel through the same connection dispatcher and presenter as a real peer. -describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (protocol) => { +describe.each([Lite.ALPN_07_WIP])("AUTH violations %s", (protocol) => { test("a second presenter message closes the session", async () => { const streams: Stream[] = []; - const prototype = protocol === Lite.ALPN_07_WIP ? LiteAuthWire.prototype : IetfAuthWire.prototype; + const prototype = LiteAuthWire.prototype; const original = prototype.present; - const spy = spyOn(prototype, "present").mockImplementation(async function ( - this: LiteAuthWire & IetfAuthWire, - token, - ) { + const spy = spyOn(prototype, "present").mockImplementation(async function (this: LiteAuthWire, token) { const stream = await original.call(this, token); streams.push(stream); return stream; @@ -1466,15 +1407,10 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (pro const pair = await connect({ protocol }); await waitFor(pair.client.auth.grant, (g) => g !== undefined); await waitFor(pair.server.auth.grant, (g) => g !== undefined); - const lite = protocol === Lite.ALPN_07_WIP; - const prototype = lite ? LiteAuthMessage.prototype : IetfAuthMessage.prototype; - const spy = spyOn(prototype, "encode").mockImplementation(async (writer: Writer) => { - const body = async (w: Writer) => { - if (!lite) await w.u62(2n); + const spy = spyOn(LiteAuthMessage.prototype, "encode").mockImplementation(async (writer: Writer) => { + await LiteMessage.encode(writer, async (w: Writer) => { await w.u53(2); - }; - if (lite) await LiteMessage.encode(writer, body); - else await IetfMessage.encode(writer, body, IetfAuthMessage.id); + }); }); const added = pair.client.auth.add("bad").catch(() => undefined); try { @@ -1499,11 +1435,10 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (pro ] as const) { test(`${fault} closes the session`, async () => { const streams: Stream[] = []; - const lite = protocol === Lite.ALPN_07_WIP; - const prototype = lite ? LiteAuthWire.prototype : IetfAuthWire.prototype; + const prototype = LiteAuthWire.prototype; const original = prototype.grant; const spy = spyOn(prototype, "grant").mockImplementation(async function ( - this: LiteAuthWire & IetfAuthWire, + this: LiteAuthWire, stream, value, ) { @@ -1531,9 +1466,8 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (pro if (fault === "extra body") await writer.u53(0); } }; - const id = fault === "oversized expiry" ? (lite ? 0 : 0x40b62) : lite ? 1 : 0x40b63; - if (lite) await LiteMessage.encode(stream.writer, body, { id }); - else await IetfMessage.encode(stream.writer, body, id); + const id = fault === "oversized expiry" ? 0 : 1; + await LiteMessage.encode(stream.writer, body, { id }); } expect( (await withTimeout(pair.transport.closed, Duration.millis(100), "malformed AUTH did not close")) @@ -1547,68 +1481,3 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (pro }); } }); - -// AUTH takes the peer's request ID parity. -describe.each([Ietf.ALPN.DRAFT_22])("AUTH request IDs %s", (protocol) => { - for (const client of [true, false]) { - test(`${client ? "client" : "server"} wrong parity closes the session`, async () => { - const pair = await connect({ protocol }); - await waitFor(pair.client.auth.grant, (g) => g !== undefined); - await waitFor(pair.server.auth.grant, (g) => g !== undefined); - const original = IetfAuthMessage.prototype.encode; - const spy = spyOn(IetfAuthMessage.prototype, "encode").mockImplementation(async function ( - this: IetfAuthMessage, - writer, - version, - ) { - this.requestId = client ? 1n : 0n; - await original.call(this, writer, version); - }); - const added = (client ? pair.client : pair.server).auth.add("bad ID").catch(() => undefined); - try { - expect( - ( - await withTimeout( - pair.transport.closed, - Duration.millis(100), - "invalid AUTH ID left session open", - ) - ).closeCode, - ).toBe(SessionCode.InvalidRequestId); - } finally { - spy.mockRestore(); - pair.client.abort(); - pair.server.abort(); - await added; - } - }); - } -}); - -for (const protocol of [Ietf.ALPN.DRAFT_22]) { - test(`AUTH accepts reordered IDs on ${protocol}`, async () => { - const pair = await connect({ protocol }); - await waitFor(pair.client.auth.grant, (g) => g !== undefined); - await waitFor(pair.server.auth.grant, (g) => g !== undefined); - const original = IetfAuthMessage.prototype.encode; - const spy = spyOn(IetfAuthMessage.prototype, "encode").mockImplementation(async function ( - this: IetfAuthMessage, - writer, - version, - ) { - // Swap the next two independently opened request IDs, preserving endpoint parity. - this.requestId = this.requestId < 4n ? this.requestId + 2n : this.requestId - 2n; - await original.call(this, writer, version); - }); - try { - for (const endpoint of [pair.client, pair.server]) { - await expect(endpoint.auth.add("first")).rejects.toBeInstanceOf(Unsupported); - await expect(endpoint.auth.add("second")).rejects.toBeInstanceOf(Unsupported); - } - } finally { - spy.mockRestore(); - pair.client.abort(); - pair.server.abort(); - } - }); -} diff --git a/js/net/src/auth.ts b/js/net/src/auth.ts index 27c352e4392..613cdb95709 100644 --- a/js/net/src/auth.ts +++ b/js/net/src/auth.ts @@ -1,11 +1,9 @@ /** * In-band authorization: present tokens to the peer and learn what they grant. * - * Each side of a moq-lite-07 session, and of a moq-transport draft-18+ session when both - * sides negotiate MoQ Auth, presents the credential its connection already carried (the - * URL, or nothing) right after setup, and learns the {@link Grant} it earned. Older - * versions, and peers that do not negotiate it, carry no AUTH exchange: the grant stays - * undefined. There {@link Handle.add} rejects with {@link Unsupported} on moq-lite, and on + * Each side of a moq-lite-07 session presents the credential its connection already carried + * (the URL, or nothing) right after setup, and learns the {@link Grant} it earned. Older + * versions and moq-transport carry no AUTH exchange: the grant stays undefined. There {@link Handle.add} rejects with {@link Unsupported} on moq-lite, and on * moq-transport keeps the token, with no grant, for the announcements whose route names it. * {@link Handle.grant} is the union of every token this side presented, and {@link Handle.add} * presents another without reconnecting, returning its {@link Credential}. diff --git a/js/net/src/connection/extensions.test.ts b/js/net/src/connection/extensions.test.ts index 8679a511e16..74314d9f9a3 100644 --- a/js/net/src/connection/extensions.test.ts +++ b/js/net/src/connection/extensions.test.ts @@ -1,6 +1,4 @@ import { expect, spyOn, test } from "bun:test"; -import { SessionCode } from "../error.ts"; -import { AuthMessage, AuthOk } from "../ietf/auth.ts"; import { PublishNamespace } from "../ietf/publish_namespace.ts"; import { RequestOk } from "../ietf/request.ts"; import { ALPN, Version } from "../ietf/version.ts"; @@ -35,41 +33,15 @@ async function acceptWith(extensions: Extensions) { } test("a declined extension stays out of SETUP", async () => { - // Control: both sides offer both. + // Control: both sides offer it. const all = await handshake({}, {}); expect(all.accepted.solicit).toBe(true); - expect(all.accepted.auth).toBe(true); - expect(all.dialed.auth).toBe(true); - const none = await handshake({ auth: false, solicit: false }, {}); + const none = await handshake({ solicit: false }, {}); expect(none.accepted.solicit).toBeUndefined(); - expect(none.accepted.auth).toBe(false); - // Negotiated only when both offer it, so the declining side does not speak it either. - expect(none.dialed.auth).toBe(false); expect(none.dialed.solicit).toBe(true); }); -test("an AUTH to a side that declined it closes the session", async () => { - // Control: offered by both, the connection credential is granted. - const offering = await acceptWith({}); - const granted = await Stream.open(offering.pair.client, { version: VERSION }); - await new AuthMessage(0n, new Uint8Array()).encode(granted.writer, VERSION); - expect(await granted.reader.u53()).toBe(AuthOk.id); - offering.connection.close(); - - const logged = spyOn(console, "error").mockImplementation(() => void 0); - try { - const declined = await acceptWith({ auth: false }); - const refused = await Stream.open(declined.pair.client, { version: VERSION }); - // The session closes on the message type alone, so the rest of the write may fail. - await new AuthMessage(0n, new Uint8Array()).encode(refused.writer, VERSION).catch(() => undefined); - const info = await declined.pair.client.closed; - expect(info.closeCode).toBe(SessionCode.ProtocolViolation); - } finally { - logged.mockRestore(); - } -}); - test("a side that declined solicit takes an unsolicited announce", async () => { const announce = async (session: Awaited>) => { const stream = await Stream.open(session.pair.client, { version: VERSION }); diff --git a/js/net/src/connection/extensions.ts b/js/net/src/connection/extensions.ts index f144ac09b47..f157fc34990 100644 --- a/js/net/src/connection/extensions.ts +++ b/js/net/src/connection/extensions.ts @@ -6,8 +6,6 @@ import * as Ietf from "../ietf/index.ts"; * core, so this only changes moq-transport sessions. */ export interface Extensions { - /** The MoQ Auth extension: tokens presented and granted on their own stream (draft-18+). */ - auth?: boolean; /** The MoQ Solicit extension: the peer answers our SUBSCRIBE_NAMESPACE rather than announcing unasked. */ solicit?: boolean; } @@ -18,7 +16,6 @@ export type Offered = Required; /** Resolve each unset extension to offered. */ export function offered(extensions?: Extensions): Offered { return { - auth: extensions?.auth ?? true, solicit: extensions?.solicit ?? true, }; } @@ -26,5 +23,4 @@ export function offered(extensions?: Extensions): Offered { /** Write the options for the offered extensions into a SETUP. */ export function intoSetup(params: Ietf.SetupOptions, extensions: Offered) { if (extensions.solicit) Ietf.solicitIntoSetup(params); - if (extensions.auth) Ietf.Auth.intoSetup(params); } diff --git a/js/net/src/connection/handshake.ts b/js/net/src/connection/handshake.ts index c6ef948f1bc..18406fbee0b 100644 --- a/js/net/src/connection/handshake.ts +++ b/js/net/src/connection/handshake.ts @@ -19,9 +19,9 @@ export const DEFAULT_TIMEOUT = Duration.millis(30_000); * Returns the control stream, the uni streams that arrived before it (see * {@link receiveSetup}), plus what the peer's SETUP declared: whether it requires * solicitation, which decides whether we announce namespaces unprompted (see the MoQ Solicit - * extension), its Hop ID (see the MoQ Cluster extension), and whether MoQ Auth - * is negotiated, plus the implementation it advertised. We declare our Hop ID on every - * session, and Solicit and Auth unless `extensions` declines them: we send SUBSCRIBE_NAMESPACE for each prefix we want, so an unsolicited advertisement + * extension) and its Hop ID (see the MoQ Cluster extension), plus the implementation it + * advertised. We declare our Hop ID on every session, and Solicit unless `extensions` + * declines it: we send SUBSCRIBE_NAMESPACE for each prefix we want, so an unsolicited advertisement * can tell us nothing we won't have asked for, and a peer that knows our Hop ID can withhold * the advertisements that already flowed through us. */ @@ -38,7 +38,6 @@ export async function exchangeSetup( maxAge: boolean; activeCount: boolean; cluster: Ietf.Cluster.Hops; - auth: boolean; peerImplementation: string | undefined; }> { const params = new Ietf.SetupOptions(); @@ -79,8 +78,6 @@ export async function exchangeSetup( maxAge: received.maxAge, activeCount: received.activeCount, cluster: { self, peer: received.cluster }, - // Negotiated only when both sides offer it. - auth: received.auth && extensions.auth, peerImplementation: received.implementation, }; } @@ -111,7 +108,6 @@ async function receiveSetup( maxAge: boolean; activeCount: boolean; cluster: Hop | undefined; - auth: boolean; implementation: string | undefined; }> { const uniReader = transport.incomingUnidirectionalStreams.getReader() as ReadableStreamDefaultReader< @@ -171,7 +167,6 @@ async function receiveSetup( maxAge: Ietf.maxAgeFromSetup(setup.parameters), activeCount: Ietf.activeCountFromSetup(setup.parameters), cluster: Ietf.Cluster.fromSetup(setup.parameters), - auth: Ietf.Auth.fromSetup(setup.parameters) === true, implementation: Ietf.implementationFromSetup(setup.parameters), }; } diff --git a/js/net/src/connection/session.ts b/js/net/src/connection/session.ts index 2e7e31fb7b7..3169da3b6ce 100644 --- a/js/net/src/connection/session.ts +++ b/js/net/src/connection/session.ts @@ -32,9 +32,8 @@ export interface Session { /** * The tokens this side presented and the grant they earned, plus the tokens the peer - * presents. On moq-lite-07-wip, and on moq-transport draft-18+ when both sides negotiate - * MoQ Auth, each side presents its connection's credential right after setup. - * Otherwise the grant stays undefined. + * presents. On moq-lite-07-wip each side presents its connection's credential right after + * setup. Otherwise the grant stays undefined. * * The handle passed to `connect` as `auth`, or else one the session created for itself, * which ends with it. diff --git a/js/net/src/ietf/auth.test.ts b/js/net/src/ietf/auth.test.ts deleted file mode 100644 index 048272567ca..00000000000 --- a/js/net/src/ietf/auth.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { expect, test } from "bun:test"; -import { Unsupported } from "../auth.ts"; -import { SessionCode, type SessionError, StreamCode, type StreamError } from "../error.ts"; -import * as Path from "../path.ts"; -import { Reader, Writer } from "../stream.ts"; -import { AuthError, AuthMessage, AuthOk } from "./auth.ts"; -import { Version } from "./version.ts"; - -function patterns(...texts: string[]): Path.Patterns { - return new Path.Patterns(texts.map((text) => Path.Pattern.parse(text))); -} - -/** The bytes a write produces. */ -async function bytes(write: (w: Writer) => Promise): Promise { - const chunks: Uint8Array[] = []; - const writer = new Writer( - new WritableStream({ - write(chunk) { - chunks.push(new Uint8Array(chunk)); - }, - }), - Version.DRAFT_18, - ); - await write(writer); - writer.close(); - await writer.closed; - const out = new Uint8Array(chunks.reduce((n, c) => n + c.byteLength, 0)); - let offset = 0; - for (const chunk of chunks) { - out.set(chunk, offset); - offset += chunk.byteLength; - } - return out; -} - -/** A reader past the message type, the way the dispatcher leaves one. */ -async function afterType(write: (w: Writer) => Promise): Promise { - const reader = new Reader(undefined, await bytes(write), Version.DRAFT_18); - await reader.u53(); - return reader; -} - -test("AUTH round-trips its request id and token", async () => { - const r = await afterType((w) => new AuthMessage(4n, new TextEncoder().encode("jwt")).encode(w, Version.DRAFT_18)); - const msg = await AuthMessage.decode(r, Version.DRAFT_18); - expect(msg.requestId).toBe(4n); - expect(new TextDecoder().decode(msg.token)).toBe("jwt"); -}); - -test("AUTH_OK carries each pattern as its canonical text", async () => { - // The exact bytes `rs/moq-net/src/ietf/auth.rs` checks, so both encoders agree. - const ok = new AuthOk(patterns("room/*/cam", "ch1"), patterns(""), undefined); - const wire = await bytes((w) => ok.encode(w, Version.DRAFT_18)); - // Type, 16-bit length, then: two publish patterns in canonical order, the empty - // subscribe pattern, never expires. - expect([...wire.slice(-19)]).toEqual([ - 0x02, - 0x03, - ...new TextEncoder().encode("ch1"), - 0x0a, - ...new TextEncoder().encode("room/*/cam"), - 0x01, - 0x00, - 0x00, - ]); - - // Literals and wildcards travel exactly, never widened to a prefix. - const grant = new AuthOk(patterns("**"), patterns("live/*", "lobby/cam-*.hang", "ch1"), 60_000); - const r = await afterType((w) => grant.encode(w, Version.DRAFT_18)); - const got = await AuthOk.decode(r, Version.DRAFT_18); - expect(got.publish.equals(grant.publish)).toBe(true); - expect(got.subscribe.equals(grant.subscribe)).toBe(true); - expect(got.expires).toBe(60_000); -}); - -test("a grant too large for one message is refused before anything is written", async () => { - const huge = new AuthOk( - patterns(...Array.from({ length: 20 }, (_, i) => `${i}${"x".repeat(4000)}/**`)), - patterns(), - ); - let written = 0; - const writer = new Writer( - new WritableStream({ - write(chunk) { - written += chunk.byteLength; - }, - }), - Version.DRAFT_18, - ); - await expect(huge.encode(writer, Version.DRAFT_18)).rejects.toThrow("Message too large"); - writer.close(); - await writer.closed; - expect(written).toBe(0); -}); - -test("AUTH_ERROR preserves actionable refusal kinds", async () => { - const r = await afterType((w) => new AuthError(0x3, "too large").encode(w, Version.DRAFT_18)); - expect((await AuthError.decode(r, Version.DRAFT_18)).toError()).toBeInstanceOf(Unsupported); - const expired = new AuthError(0x5, "expired").toError() as SessionError; - expect(expired.code).toBe(SessionCode.Expired); - const malformed = new AuthError(0x4, "not a JWT").toError() as SessionError; - expect(malformed.code).toBe(SessionCode.MalformedAuthToken); - const unauthorized = new AuthError(0x1, "bad").toError() as SessionError; - expect(unauthorized.code).toBe(SessionCode.Unauthorized); - // Past the acceptor's GOAWAY: the request is refused, not the token. - const goingAway = new AuthError(0x6, "going away").toError() as StreamError; - expect(goingAway.code).toBe(StreamCode.GoingAway); -}); diff --git a/js/net/src/ietf/auth.ts b/js/net/src/ietf/auth.ts deleted file mode 100644 index 773bc836949..00000000000 --- a/js/net/src/ietf/auth.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { Unsupported } from "../auth.ts"; -import { type AuthWire, decodePatterns, encodePatterns, type WireGrant, type WireReply } from "../auth_session.ts"; -import { ProtocolViolation, SessionCode, SessionError, StreamCode, StreamError } from "../error.ts"; -import type * as Path from "../path.ts"; -import type { Reader, Stream, Writer } from "../stream.ts"; -import * as Message from "./message.ts"; -import { nextMessage } from "./request_stream.ts"; -import type { Session } from "./session.ts"; -import type { IetfVersion } from "./version.ts"; - -/** - * The MoQ Auth extension (draft-lcurley-moq-auth-01): the moq-lite Auth Stream as - * moq-transport request streams, negotiated in `auth_setup.ts`. AUTH_OK carries the - * same patterns, encoded the same way, as moq-lite's. - * - * @module - * @internal - */ - -/** The REQUEST_ERROR codes AUTH_ERROR carries. */ -const UNAUTHORIZED = 0x1; -const NOT_SUPPORTED = 0x3; -const MALFORMED_AUTH_TOKEN = 0x4; -const EXPIRED_AUTH_TOKEN = 0x5; -const GOING_AWAY = 0x6; - -/** Longest AUTH_ERROR reason, in bytes, matching the Rust decoder. */ -const MAX_REASON = 8192; - -/** - * AUTH: the first message on an Auth request stream, presenting a token. Each message - * here encodes its own type, which the dispatcher consumes before decoding. - * - * @internal - */ -export class AuthMessage { - static id = 0x40b61; - - requestId: bigint; - token: Uint8Array; - - constructor(requestId: bigint, token: Uint8Array) { - this.requestId = requestId; - this.token = token; - } - - async encode(w: Writer, _version: IetfVersion): Promise { - return Message.encode( - w, - async (wr) => { - await wr.u62(this.requestId); - await wr.u53(this.token.byteLength); - if (this.token.byteLength > 0) await wr.write(this.token); - }, - AuthMessage.id, - ); - } - - static async decode(r: Reader, _version: IetfVersion): Promise { - return Message.decode(r, async (rd) => { - const requestId = await rd.u62(); - const size = await rd.u53(); - return new AuthMessage(requestId, await rd.read(size)); - }); - } -} - -/** AUTH_OK: the grant a token earns, replacing any earlier one on the stream. @internal */ -export class AuthOk { - static id = 0x40b62; - - publish: Path.Patterns; - subscribe: Path.Patterns; - /** Milliseconds until the grant lapses, or undefined for never. */ - expires?: number; - - constructor(publish: Path.Patterns, subscribe: Path.Patterns, expires?: number) { - this.publish = publish; - this.subscribe = subscribe; - this.expires = expires; - } - - async encode(w: Writer, _version: IetfVersion): Promise { - return Message.encode( - w, - async (wr) => { - await encodePatterns(wr, this.publish); - await encodePatterns(wr, this.subscribe); - // 0 means never, so a lapsed grant rounds up to the smallest real expiry. - const expires = - this.expires === undefined - ? 0 - : Math.min(Math.max(Math.ceil(this.expires), 1), Number.MAX_SAFE_INTEGER); - await wr.u53(expires); - }, - AuthOk.id, - ); - } - - static async decode(r: Reader, _version: IetfVersion): Promise { - return Message.decode(r, async (rd) => { - const publish = await decodePatterns(rd); - const subscribe = await decodePatterns(rd); - const expires = await rd.u53(); - return new AuthOk(publish, subscribe, expires === 0 ? undefined : expires); - }); - } -} - -/** AUTH_ERROR: the acceptor refusing a token, or revoking it after an AUTH_OK. @internal */ -export class AuthError { - static id = 0x40b63; - - /** A code from the REQUEST_ERROR registry. */ - code: number; - reason: string; - - constructor(code: number, reason: string) { - this.code = code; - this.reason = reason; - } - - async encode(w: Writer, _version: IetfVersion): Promise { - if (new TextEncoder().encode(this.reason).byteLength > MAX_REASON) { - throw new Error("AUTH_ERROR reason exceeds 8,192 bytes"); - } - return Message.encode( - w, - async (wr) => { - await wr.u53(this.code); - await wr.string(this.reason); - }, - AuthError.id, - ); - } - - static async decode(r: Reader, _version: IetfVersion): Promise { - return Message.decode(r, async (rd) => { - const code = await rd.u53(); - if (code > 0xffffffff) throw new Error("AUTH_ERROR code exceeds 32 bits"); - const reason = await rd.string(); - if (new TextEncoder().encode(reason).byteLength > MAX_REASON) { - throw new Error("AUTH_ERROR reason exceeds 8,192 bytes"); - } - return new AuthError(code, reason); - }); - } - - /** What the refusal means to the presenter, preserving an actionable expiry. */ - toError(): Error { - if (this.code === NOT_SUPPORTED) return new Unsupported(this.reason); - if (this.code === MALFORMED_AUTH_TOKEN) { - return new SessionError(SessionCode.MalformedAuthToken, { reason: this.reason }); - } - if (this.code === EXPIRED_AUTH_TOKEN) return new SessionError(SessionCode.Expired, { reason: this.reason }); - if (this.code === GOING_AWAY) return new StreamError(StreamCode.GoingAway, { reason: this.reason }); - return new SessionError(SessionCode.Unauthorized, { reason: this.reason }); - } -} - -/** The moq-transport binding of the token lifecycle. @internal */ -export class IetfAuthWire implements AuthWire { - #session: Session; - #version: IetfVersion; - - constructor(session: Session) { - this.#session = session; - this.#version = session.version; - } - - async present(token: Uint8Array): Promise { - const requestId = await this.#session.nextRequestId(); - if (requestId === undefined) throw new Error("no request id available"); - const stream = await this.#session.openBi(); - await new AuthMessage(requestId, token).encode(stream.writer, this.#version); - return stream; - } - - async read(stream: Stream): Promise { - const id = await nextMessage(stream.reader, this.#version, this.#session.client); - if (id === undefined) return undefined; - switch (id) { - case AuthOk.id: { - const ok = await AuthOk.decode(stream.reader, this.#version); - return { grant: { publish: ok.publish, subscribe: ok.subscribe, expires: ok.expires } }; - } - case AuthError.id: { - const err = await AuthError.decode(stream.reader, this.#version); - return { refused: err.toError() }; - } - default: - throw new Error(`unexpected message on an auth request: 0x${id.toString(16)}`); - } - } - - /** The type id is already consumed by the dispatcher. */ - async accept(stream: Stream): Promise { - const msg = await AuthMessage.decode(stream.reader, this.#version); - this.#session.checkRequestId(msg.requestId); - return msg.token; - } - - async withdrawn(stream: Stream): Promise { - if ((await nextMessage(stream.reader, this.#version, this.#session.client)) !== undefined) - throw new ProtocolViolation("additional message on an AUTH stream"); - } - - async grant(stream: Stream, grant: WireGrant): Promise { - await new AuthOk(grant.publish, grant.subscribe, grant.expires).encode(stream.writer, this.#version); - } - - async refuse(stream: Stream, code: SessionCode, reason: string): Promise { - // The public API speaks session codes; translate the actionable request-error kinds. - const wire = - code === SessionCode.Version || code === SessionCode.Unsupported - ? NOT_SUPPORTED - : code === SessionCode.MalformedAuthToken - ? MALFORMED_AUTH_TOKEN - : code === SessionCode.Expired - ? EXPIRED_AUTH_TOKEN - : UNAUTHORIZED; - await new AuthError(wire, reason).encode(stream.writer, this.#version); - } - - async unsupported(stream: Stream, reason: string): Promise { - await new AuthError(NOT_SUPPORTED, reason).encode(stream.writer, this.#version); - await stream.writer.close(); - } -} diff --git a/js/net/src/ietf/auth_setup.ts b/js/net/src/ietf/auth_setup.ts deleted file mode 100644 index 500b3cc8631..00000000000 --- a/js/net/src/ietf/auth_setup.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { SetupOption, type SetupOptions } from "./setup_options.ts"; - -/** - * Negotiation of the MoQ Auth extension (draft-lcurley-moq-auth-01) with the AUTH Setup Option. - * Kept apart from its request streams in `auth.ts`, which only an established session loads. - * - * @module - * @internal - */ - -/** - * What the peer declared: undefined for no option, otherwise whether it offered the - * extension. Only an explicit 1 negotiates it. - * - * @internal - */ -export function fromSetup(params: SetupOptions): boolean | undefined { - const value = params.getVarint(SetupOption.Auth); - return value === undefined ? undefined : value === 1n; -} - -/** Offer the extension. @internal */ -export function intoSetup(params: SetupOptions) { - params.setVarint(SetupOption.Auth, 1n); -} diff --git a/js/net/src/ietf/connection.ts b/js/net/src/ietf/connection.ts index f75a5da0bf0..17ac1c5a54c 100644 --- a/js/net/src/ietf/connection.ts +++ b/js/net/src/ietf/connection.ts @@ -13,7 +13,6 @@ import * as Path from "../path.ts"; import { type Reader, Readers, type Stream } from "../stream.ts"; import { withTimeout } from "../util/timeout.ts"; import { registerWire } from "../wire.ts"; -import { AuthMessage, IetfAuthWire } from "./auth.ts"; import * as Cluster from "./cluster.ts"; import type { RequestKind } from "./error.ts"; import { Fetch, FetchHeader } from "./fetch.ts"; @@ -64,12 +63,12 @@ export class Connection implements Session { /** moq-transport has no PROBE, so this stays empty; see {@link Session.probe}. */ readonly probe: Getter = new Signal({}); - /** Our tokens and grants, when the peer negotiated MoQ Auth; see {@link Session.auth}. */ + /** Our tokens, which requests carry; see {@link Session.auth}. */ get auth(): Auth.Handle { return this.#auth.handle; } - // Our tokens and grants, and the answers to the peer's (MoQ Auth). + // Our tokens, for the requests that carry them. #auth: AuthSession; // The established WebTransport session. @@ -126,7 +125,6 @@ export class Connection implements Session { maxAge = false, activeCount = false, cluster, - auth = false, handle, early = [], extensions, @@ -156,8 +154,6 @@ export class Connection implements Session { * cannot negotiate the extension, as is a `peer` the peer never declared. */ cluster?: Cluster.Hops; - /** Whether MoQ Auth is negotiated: offered by both SETUPs. */ - auth?: boolean; /** The auth handle to build the session on, or undefined for one of its own. */ handle?: Auth.Handle; /** Uni streams that arrived before the peer's SETUP, type unread. */ @@ -181,9 +177,7 @@ export class Connection implements Session { // What the peer's connection credential earns by default: publishing anything to us, // since we consume on demand, and subscribing to whatever we publish. - const session = this.#session; this.#auth = new AuthSession({ - wire: auth ? new IetfAuthWire(session) : undefined, requests: true, peerGrant: { publish: new Path.Patterns([Path.Pattern.all()]), @@ -212,7 +206,6 @@ export class Connection implements Session { cluster, grant: this.#auth.scope, auth: this.#auth, - ready: this.#auth.setupAnswered(), }); this.#solicit = solicit; this.#declaredSolicit = extensions?.solicit ?? true; @@ -419,12 +412,6 @@ export class Connection implements Session { await handed(this.#subscriber.runPublishNamespace(msg, stream)); break; } - case BigInt(AuthMessage.id): { - // Only a peer that negotiated MoQ Auth may send one. - if (!this.#auth.negotiated) throw new ProtocolViolation("AUTH without MoQ Auth"); - await this.#auth.serve(stream); - break; - } case BigInt(Publish.id): { const decoded = Publish.decode(stream.reader, this.#session.version); const msg = await this.#request(stream, "publish", decoded); diff --git a/js/net/src/ietf/goaway.test.ts b/js/net/src/ietf/goaway.test.ts index 47f37b94a56..ce54f9b1301 100644 --- a/js/net/src/ietf/goaway.test.ts +++ b/js/net/src/ietf/goaway.test.ts @@ -5,12 +5,10 @@ import { createMockTransportPair, manual, settlesWithin } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { Stream } from "../stream.ts"; -import { AuthMessage, AuthOk, IetfAuthWire } from "./auth.ts"; import { Connection } from "./connection.ts"; import { GoAway } from "./goaway.ts"; import { PublishNamespace } from "./publish_namespace.ts"; import { RequestOk } from "./request.ts"; -import { NativeSession } from "./session.ts"; import { SubscribeNamespace, SubscribeNamespaceEntry } from "./subscribe_namespace.ts"; import { ALPN, Version } from "./version.ts"; @@ -138,52 +136,6 @@ for (const [version, alpn] of [ }); } -for (const [version, alpn] of [ - [Version.DRAFT_18, ALPN.DRAFT_18], - [Version.DRAFT_22, ALPN.DRAFT_22], -] as const) { - test(`${alpn} AUTH replies handle GOAWAY across grants`, async () => { - const pair = createMockTransportPair(alpn); - const wire = new IetfAuthWire(new NativeSession(pair.client, version, true)); - const stream = await wire.present(new Uint8Array()); - const peer = await Stream.accept(pair.server, version); - if (!peer) throw new Error("no AUTH stream"); - try { - await peer.writer.u53(GoAway.id); - await new GoAway({ newSessionUri: "" }).encode(peer.writer, version); - await new AuthOk(new Path.Patterns(), new Path.Patterns()).encode(peer.writer, version); - expect(await wire.read(stream)).toEqual({ - grant: { publish: new Path.Patterns(), subscribe: new Path.Patterns(), expires: undefined }, - }); - await peer.writer.u53(GoAway.id); - await new GoAway({ newSessionUri: "" }).encode(peer.writer, version); - await expect(wire.read(stream)).rejects.toThrow("second GOAWAY"); - } finally { - pair.client.close(); - } - }); - - test(`${alpn} an AUTH presenter can send GOAWAY before withdrawing`, async () => { - const pair = createMockTransportPair(alpn); - const wire = new IetfAuthWire(new NativeSession(pair.client, version, true)); - const stream = await Stream.open(pair.client, { version }); - const peer = await Stream.accept(pair.server, version); - if (!peer) throw new Error("no AUTH stream"); - try { - await new AuthMessage(1n, new Uint8Array()).encode(peer.writer, version); - expect(await stream.reader.u53()).toBe(AuthMessage.id); - await wire.accept(stream); - const withdrawn = wire.withdrawn(stream); - await peer.writer.u53(GoAway.id); - await new GoAway({ newSessionUri: "" }).encode(peer.writer, version); - peer.writer.close(); - await withdrawn; - } finally { - pair.client.close(); - } - }); -} - for (const [version, alpn] of [ [Version.DRAFT_18, ALPN.DRAFT_18], [Version.DRAFT_22, ALPN.DRAFT_22], diff --git a/js/net/src/ietf/index.ts b/js/net/src/ietf/index.ts index 975d8ccf413..8ae3101b9bb 100644 --- a/js/net/src/ietf/index.ts +++ b/js/net/src/ietf/index.ts @@ -1,7 +1,6 @@ // The SETUP surface only. The session code is imported from `connection.ts` on demand, so a bundle // that negotiates lite never loads it; re-exporting it here would pull it into the static graph. export * from "./active_count.ts"; -export * as Auth from "./auth_setup.ts"; export * as Cluster from "./cluster.ts"; export * from "./hidden.ts"; export * from "./max_age.ts"; diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index cf6fdd18afc..7d97fc3365e 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -397,17 +397,13 @@ export class Publisher { // back came from us. `undefined` when nothing negotiated it. #advert?: Cluster.Advert; - // Our grant (MoQ Auth): only what it lets us publish is advertised and served, and a + // Our grant: only what it lets us publish is advertised and served, and a // shrink withdraws what it no longer covers. Undefined until the peer answers, which // allows everything. #grant: Getter; // Holds every incoming request to that grant from dispatch to its end. #gate: Gate; - // Resolves once the tokens this session presented at setup are answered, so nothing is - // advertised before the grant it would be checked against. - #ready: Promise; - // The bytes a request carries for a route's token, for only the tokens this session issued. #auth?: Carrier; @@ -426,7 +422,6 @@ export class Publisher { cluster, grant = new Signal(undefined), auth, - ready = Promise.resolve(), }: { /** The WebTransport session, for uni streams. */ quic: WebTransport; @@ -442,19 +437,16 @@ export class Publisher { activeCount?: boolean; /** The Hop IDs the SETUP exchange settled (MoQ Cluster). */ cluster?: Cluster.Hops; - /** The union of our tokens' grants (MoQ Auth), which bounds what we publish. */ + /** The union of our tokens' grants, which bounds what we publish. */ grant?: Getter; /** This session's tokens, which a route names for its request to carry. */ auth?: Carrier; - /** Resolves once the setup tokens are answered (MoQ Auth). */ - ready?: Promise; }) { this.#quic = quic; this.#datagramWriter = DatagramStream.datagramWriter(quic); this.#grant = grant; this.#gate = new Gate(grant); this.#auth = auth; - this.#ready = ready; this.#session = session; const origin = publish && wireOf(publish); this.#advertised = origin?.advertised ?? new Signal(new Map()); @@ -1688,9 +1680,6 @@ export class Publisher { const visible = (covered: Path.Valid) => !this.#hidden || msg.hidden || !hiddenBelow(prefix, covered); const carries = (covered: Path.Valid) => visible(covered) && this.#gate.allows(covered); - // Nothing is advertised before the grant it would be checked against. - await this.#ready; - // Inline entries always land, and the receiver treats a repeated NAMESPACE as a // replacement, so repricing one is just sending it again, a new original // publisher included, as Rust does. @@ -1839,9 +1828,6 @@ export class Publisher { let dispose: Dispose | undefined; try { - // Nothing is advertised before the grant it would be checked against. - if ((await Promise.race([this.#ready.then(() => "ready" as const), closed])) !== "ready") return; - // Keyed by path. const ns: Namespaces = { active: new Map(), refused: new Map(), offered: new Map() }; // How long to stay away the next time the peer ends each advertisement while idle, @@ -1881,7 +1867,7 @@ export class Publisher { const updated = new Map(); for (const [covered, candidates] of advertised) { // Only peers that declared MoQ Hidden filter unsolicited discovery, and - // nothing our grant does not cover reaches the peer at all (MoQ Auth). + // nothing our grant does not cover reaches the peer at all. if ((this.#hidden && hiddenBelow(Path.empty(), covered)) || !this.#gate.allows(covered)) continue; const best = firstEligible(candidates); if (best) updated.set(covered, best); diff --git a/js/net/src/ietf/setup_options.test.ts b/js/net/src/ietf/setup_options.test.ts index 5d6fb233a01..5e301c4f34b 100644 --- a/js/net/src/ietf/setup_options.test.ts +++ b/js/net/src/ietf/setup_options.test.ts @@ -16,7 +16,6 @@ test("setup option keys match the registries", () => { Solicit: 0x40b5an, Hidden: 0x40b5cn, MaxAge: 0x915c4n, - Auth: 0x40b70n, ActiveCount: 0x40b64n, }); }); diff --git a/js/net/src/ietf/setup_options.ts b/js/net/src/ietf/setup_options.ts index 4fe1a61f2f4..b5e43f8930d 100644 --- a/js/net/src/ietf/setup_options.ts +++ b/js/net/src/ietf/setup_options.ts @@ -20,8 +20,6 @@ export const SetupOption = { Hidden: 0x40b5cn, /** Subscriber max age, from the MoQ Timestamp extension. */ MaxAge: 0x915c4n, - /** AUTH, from the MoQ Auth extension. See `auth.ts`. */ - Auth: 0x40b70n, /** ACTIVE_COUNT, from the MoQ Active Count extension. See `active_count.ts`. */ ActiveCount: 0x40b64n, } as const; diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index 5fb2518a254..541832b4107 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -218,7 +218,7 @@ export class Subscriber { // Settles when the peer sends GOAWAY, ranking this session's routes last. #goaway?: GetPromise; - // Our grant (MoQ Auth): a subscription it stops covering is cancelled. Undefined until + // Our grant: a subscription it stops covering is cancelled. Undefined until // the peer answers, which allows everything. #grant?: Getter; #auth?: AuthSession; @@ -254,7 +254,7 @@ export class Subscriber { activeCount?: boolean; /** Settles when the peer sends GOAWAY. */ goaway?: GetPromise; - /** The union of our tokens' grants (MoQ Auth), which bounds what we subscribe to. */ + /** The union of our tokens' grants, which bounds what we subscribe to. */ grant?: Getter; auth?: AuthSession; /** How many live requests the peer may hold. */ diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index 218369e4015..e131345ea8a 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -163,7 +163,7 @@ client = moq.Client( - `.state()` and `await .state_changed(after)`. Read one lifecycle snapshot and wait with its revision; first-dial failures and reconnects share the same session. - `.allocator() → Allocator`. Divide the send estimate between encoders and app-owned tracks. - `.viewers() → Viewers`. Divide the receive estimate between watched broadcasts: `.watch(max_bps) → Viewer` claims up to a ceiling, `Viewer.rate()` reads its slice (`None` while there is no estimate), and dropping the viewer releases it. The summed ceilings are the PROBE target; `.set_target(bps)` overrides it (`0` sends none, `None` follows the viewers again). - - `.grants() → GrantConsumer`. On `moq-lite-07-wip` and on moq-transport draft-18+ with the MoQ Auth extension, `.grant()` reads the peer's `Grant` and `async for grant in session.grants()` follows it. + - `.grants() → GrantConsumer`. On `moq-lite-07-wip`, `.grant()` reads the peer's `Grant` and `async for grant in session.grants()` follows it. - `.tokens() → Tokens | None`. A client session's credentials: `.set([...])` replaces them without reconnecting and `await .answered()` raises the relay's refusal. ### Publishing diff --git a/py/moq-rs/moq/session.py b/py/moq-rs/moq/session.py index 67f1b7ee2ab..2357e0263aa 100644 --- a/py/moq-rs/moq/session.py +++ b/py/moq-rs/moq/session.py @@ -148,9 +148,8 @@ def viewers(self) -> Viewers: class GrantConsumer: """Follows the grant a session's peer gave it, returned by :meth:`Session.grants`. - AUTH is only on ``moq-lite-07-wip`` and on moq-transport sessions that negotiate - the MoQ Auth extension; elsewhere the grant stays ``None``. Iterate it for the - current grant and then each change, until the session ends:: + AUTH is only on ``moq-lite-07-wip``; elsewhere the grant stays ``None``. Iterate + it for the current grant and then each change, until the session ends:: async for grant in session.grants(): print(grant) diff --git a/quest/m0/test-flakes-2/README.md b/quest/m0/test-flakes-2/README.md index ba440e0fce6..f919a5fd290 100644 --- a/quest/m0/test-flakes-2/README.md +++ b/quest/m0/test-flakes-2/README.md @@ -266,4 +266,10 @@ unopened while the reader went on. The test now reads a datagram through that queue before counting queues, fixed by [moq-dev/moq#8396](https://github.com/moq-dev/moq/pull/8396). +Added 2026-11-10 (maintainer's standing rule that flakes join this epic): +interop's `python -> go` media cell, whose Go subscriber closed its lite-07 +session as publishing outside its grant once in +[moq-dev/moq#8444](https://github.com/moq-dev/moq/pull/8444)'s local run and +passed on rerun. It is quarantined until its child fixes it. + Public API: none. Wire: none. diff --git a/quest/m0/test-flakes-2/interop-python-go.md b/quest/m0/test-flakes-2/interop-python-go.md new file mode 100644 index 00000000000..02bf2b98219 --- /dev/null +++ b/quest/m0/test-flakes-2/interop-python-go.md @@ -0,0 +1,25 @@ +# [S] Interop's python -> go media cell holds up + +## Goal + +The `python -> go` media cell of `just test interop --all` passes reliably, +and its quarantine in `test/interop/interop.sh`'s `run_round` is removed. + +## Plan + +Found 2026-11-10 while iterating +[moq-dev/moq#8444](https://github.com/moq-dev/moq/pull/8444), under the +flaky-test rule. One local `just test interop --all` failed only this cell +and the rerun passed it. On moq-lite-07-wip the Go subscriber (through +moq-ffi) logged `auth granted publish=[] subscribe=["**/"]`. +About 6 s later it logged `publishing outside our grant; closing the session` +from `moq_net::lite::publisher`, and then `audio gap after 0 samples`. + +The subscriber holds a publish grant of nothing, so whatever its session +judged to be published, such as a broadcast echoed back through its origin or +a reconnect's re-announce, should never have reached the grant check. Reproduce +it with the interop logs kept, find what the Go client's origin advertises, +fix the cause, then remove the quarantine. A real bug in moq-net's grant +enforcement or in moq-ffi's origin wiring is in scope. + +Public API: none expected. Wire: none. diff --git a/quest/m2/ietf-scope/README.md b/quest/m2/ietf-scope/README.md index aee996eddc7..7a68470b753 100644 --- a/quest/m2/ietf-scope/README.md +++ b/quest/m2/ietf-scope/README.md @@ -6,8 +6,9 @@ Our moq-transport support covers what a third-party implementation needs to exchange live media with ours, and stops there: SETUP, the standard AUTHORIZATION TOKEN, live PUBLISH_NAMESPACE / SUBSCRIBE / PUBLISH, joining FETCH, and relay forwarding between moq-transport and moq-lite sessions, -including across our relays. Our own extensions and the IETF-only features -nobody third-party uses are deleted from Rust, JS, and the drafts. +including across our relays, plus the extensions a third party speaks. The +IETF-only features nobody third-party uses are deleted from Rust, JS, and the +drafts. ## Plan @@ -33,6 +34,17 @@ Settled with this epic: and moq-lite 01 to 04. - Not here: `ietf/flate.rs`; compression removal has its own work. +Our moq-transport extensions, decided 2026-11-10 (maintainer, on +[moq-dev/moq#8444](https://github.com/moq-dev/moq/pull/8444)): +✅ keep MoQ Cluster (HOP_ID, RELAY_COST, HOP_PATH, ROUTE_COST), Solicit, +Hidden, and Active Count, and delete only the in-band AUTH exchange (rejected: +delete all five). OpenMOQ's moqx relay implements draft-lcurley-moq-cluster-01 +over moq-transport draft 18 and turns it on by default, so a third party does +speak cluster, and the other three cost about 780 dedicated lines between +them. AUTH cost about 2k dedicated lines plus wiring and no third party uses +it; a third party authenticates with the standard AUTHORIZATION TOKEN, which +stays. In-band grants and token renewal are moq-lite-07 only. + This epic's own work, after its children: the docs that describe moq-transport support (`doc/concept/`, `drafts/draft-lcurley-moq-ietf.md` if it lists the extensions, and the interop matrix in diff --git a/quest/m2/ietf-scope/extensions.md b/quest/m2/ietf-scope/extensions.md deleted file mode 100644 index a35decf28f0..00000000000 --- a/quest/m2/ietf-scope/extensions.md +++ /dev/null @@ -1,36 +0,0 @@ -# [L] Our extensions stop riding moq-transport - -## Goal - -moq-transport sessions no longer negotiate or carry our own extensions: -cluster, hidden, solicit, active count, and the moq-auth extension. Rust -(`rs/moq-net/src/ietf/{cluster,hidden,solicit,active_count,auth}.rs`), JS -(`js/net/src/ietf/{cluster,hidden,solicit,active_count,auth,auth_setup}.ts`), -their handshake wiring, tests, and the moq-transport sections of the -matching `drafts/draft-lcurley-moq-*` documents are deleted. They stay on -moq-lite, where our own peers use them. - -## Plan - -Part of the [IETF scope freeze](/quest/m2/ietf-scope/README.md), decided -2026-11-09. None of the third-party implementations our interop runs -(Cloudflare, moxygen, imquic, MOQtail, aiomoqt) speaks these extensions, and -our own peers connect over moq-lite. - -- Keep the standard AUTHORIZATION TOKEN (`ietf/token.rs`, `token.ts`): it is - how a third party authenticates. -- Wire: an extension removed here is one a peer must have negotiated, so a - published client or relay that offers it gets a session without it rather - than a failure. Verify that against the published `@moq/net` and the - release relay before deleting each one; if one would break a published - peer's session, stop and report it. -- A relay forwarding a hidden or soliciting lite broadcast to a - moq-transport subscriber now treats it as moq-transport does (hidden - broadcasts are never forwarded there). Test that boundary in both - languages. -- JS exports such as `Ietf.Cluster` go; the PR's Impact section carries the - migration note. - -Public API: breaking (JS `Ietf` extension types; Rust items under `ietf` -that are public). Wire: moq-transport sessions stop negotiating our -extensions; moq-lite is unchanged. diff --git a/quest/m5/rate-grant.md b/quest/m5/rate-grant.md index ab9d37fec62..6b87df62616 100644 --- a/quest/m5/rate-grant.md +++ b/quest/m5/rate-grant.md @@ -27,10 +27,8 @@ enforces. Update the AUTH grant in `drafts/draft-lcurley-moq-lite.md` and run `just drafts check`. Rates target the next unpublished lite version after finalized lite-07, -not lite-07 or its old wip identifier. Leave the -negotiated IETF AUTH extension and `drafts/draft-lcurley-moq-auth.md` -unchanged: extending cap reporting to IETF is outside this quest. Keeping -that boundary avoids expanding the agreed lite-only wire change. +not lite-07 or its old wip identifier. moq-transport carries no AUTH grant, so +the rates are lite-only. A sending session also clamps the peer's PROBE target to the cap it enforces on that peer, as viewer targets decided rather than adding a constant: a target diff --git a/rs/moq-c/src/auth.rs b/rs/moq-c/src/auth.rs index c5af637d21e..89f15c17534 100644 --- a/rs/moq-c/src/auth.rs +++ b/rs/moq-c/src/auth.rs @@ -200,8 +200,7 @@ pub unsafe extern "C" fn moq_session_tokens_answered( /// change it: `0` when the session closed or [moq_session_grants_cancel] stopped the watch, or /// a negative error when the session failed. Release `user_data` there. Read each handle with [moq_grant_info] and release it with /// [moq_grant_free]. A dialed session's grant survives reconnects, reading not present while -/// offline. AUTH is only on `moq-lite-07-wip` and on moq-transport sessions that negotiate the -/// MoQ Auth extension; elsewhere the grant stays not present. +/// offline. AUTH is only on `moq-lite-07-wip`; elsewhere the grant stays not present. /// /// Returns a positive watcher handle, or a negative code: `MOQ_ERROR_OFFLINE` for an accepted /// session still in SETUP. diff --git a/rs/moq-ffi/src/auth.rs b/rs/moq-ffi/src/auth.rs index ee494d7c206..bbe95ec646b 100644 --- a/rs/moq-ffi/src/auth.rs +++ b/rs/moq-ffi/src/auth.rs @@ -33,8 +33,7 @@ impl From for MoqGrant { /// presented. /// /// Returned by [`MoqSession::grants`](crate::session::MoqSession::grants). AUTH is only on -/// `moq-lite-07-wip` and on moq-transport sessions that negotiate the MoQ Auth extension; -/// elsewhere the grant stays `None`. +/// `moq-lite-07-wip`; elsewhere the grant stays `None`. #[derive(uniffi::Object)] pub struct MoqGrantConsumer { /// The watch behind [`grant`](Self::grant), which reads without the lock. diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 98bde166dc4..7c763378cdc 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -8713,18 +8713,13 @@ async fn answered(session: &MoqSession) -> Result<(), MoqError> { .expect("the tokens were never answered") } -/// Both sides of a session read the grant their peer gave them, on lite-07 and on moq-transport -/// with the Auth extension, and a peer that verifies no tokens of its own refuses another one as -/// unsupported. +/// Both sides of a lite-07 session read the grant their peer gave them, and a peer that verifies +/// no tokens of its own refuses another one as unsupported. #[tokio::test] async fn auth_reads_the_peer_grant() { - for version in ["moq-lite-07-wip", "moq-transport-18"] { - auth_reads_the_peer_grant_on(version).await; - } -} - -async fn auth_reads_the_peer_grant_on(version: &str) { - let (server, client, accepted) = kio::clock::timeout(TIMEOUT, session_pair(version)).await.expect("pair"); + let (server, client, accepted) = kio::clock::timeout(TIMEOUT, session_pair("moq-lite-07-wip")) + .await + .expect("pair"); // Each side's origins span the root, so its peer grants it everything. await_grant(&client, grant(&["**"], &["**"])).await; diff --git a/rs/moq-net/benches/auth.rs b/rs/moq-net/benches/auth.rs index 36502948713..3b19ff6e40e 100644 --- a/rs/moq-net/benches/auth.rs +++ b/rs/moq-net/benches/auth.rs @@ -122,8 +122,6 @@ async fn publisher(origin: &origin::Producer) -> (Session, Session, auth::Reques mock.protocol = Some(version.alpn().to_string()); let (client, server) = create_mock_session_pair(mock); // Tokens ride requests alone, and the client announces with PUBLISH_NAMESPACE. - let mut client_extensions = moq_net::setup::Extensions::default(); - client_extensions.auth = false; let mut server_extensions = moq_net::setup::Extensions::default(); server_extensions.solicit = false; let (subscribe, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); @@ -131,7 +129,6 @@ async fn publisher(origin: &origin::Producer) -> (Session, Session, auth::Reques let client = async { let (session, driver) = moq_net::Client::new() .with_versions(version.into()) - .with_extensions(client_extensions) .with_publisher(origin.consume()) .connect(harness::now(), client) .await diff --git a/rs/moq-net/src/auth.rs b/rs/moq-net/src/auth.rs index 215e7a76885..e5d83388af6 100644 --- a/rs/moq-net/src/auth.rs +++ b/rs/moq-net/src/auth.rs @@ -28,13 +28,11 @@ //! that carried a token is held to that token's grant alone and ends with it; any other //! request is held to the session's scope, which a token carried by a request never joins. //! -//! moq-transport carries the same exchange when both sides negotiate the MoQ Auth -//! extension. Older moq-lite versions, and peers that do not negotiate it, carry no -//! AUTH exchange: there the grant stays `None`. On moq-transport `add` still succeeds, -//! with a grant that stays unknown, since a request that names the auth carries its -//! token; on moq-lite without AUTH it fails with [`Error::Unsupported`]. Both wires carry -//! a grant's patterns as they are, and refuse one too large for a single AUTH_OK rather -//! than trim it. +//! Older moq-lite versions and moq-transport carry no AUTH exchange: there the grant stays +//! `None`. On moq-transport `add` still succeeds, with a grant that stays unknown, since a +//! request that names the auth carries its token; on moq-lite without AUTH it fails with +//! [`Error::Unsupported`]. moq-lite carries a grant's patterns as they are, and refuses one +//! too large for a single AUTH_OK rather than trim it. use std::{ collections::{BTreeMap, VecDeque}, @@ -872,10 +870,10 @@ impl Link { Self::bound(supported, false) } - /// A moq-transport session: like [`new`](Self::new), but a request can carry a token - /// itself, so a token needs no AUTH to be presented. - pub(crate) fn ietf(supported: bool) -> Self { - Self::bound(supported, true) + /// A moq-transport session: it speaks no AUTH, but a request can carry a token itself, + /// so a token needs no AUTH to be presented. + pub(crate) fn ietf() -> Self { + Self::bound(false, true) } fn bound(supported: bool, requests: bool) -> Self { @@ -970,12 +968,6 @@ impl Link { self.read(|link, _| link.active()) } - /// Whether this side speaks AUTH: false on a version without it, on a side that does - /// not offer it, and once the peer turns out not to. - pub(crate) fn supported(&self) -> bool { - self.read(|link, _| link.supported) - } - /// Present a token: the session's own credential at setup, presented on this session /// alone, or else one of the handle's, presented on every session. pub(crate) fn present(&self, token: Bytes, setup: bool) -> Result { @@ -1431,43 +1423,6 @@ impl Link { }) } - /// The peer turned out not to negotiate AUTH, leaving the union unknown. On - /// moq-transport every token we presented stays, with an unknown grant, for the - /// requests that name it; elsewhere each fails as unsupported, which ends the handle's - /// tokens for good. The peer's tokens can still ride its requests, so their queue - /// stays open. - pub(crate) fn unsupported(&self) { - self.with_state(|state, link| { - let link = attached(&mut state.links, link); - link.supported = false; - link.opening.clear(); - let requests = link.requests; - // Nothing will read a withdrawn slot again. - link.slots - .retain(|_, slot| !matches!(slot.phase, Phase::Withdrawn { .. })); - let mut answers = Vec::new(); - for (id, slot) in &mut link.slots { - let answer = match requests { - true => Ok(()), - false => Err(Error::Unsupported), - }; - // Called before any stream opens, so every slot not over is still queued. - if !matches!(slot.phase, Phase::Ended(_)) { - slot.phase = match requests { - true => Phase::Requests, - false => Phase::Ended(Error::Unsupported), - }; - } - if !slot.setup { - answers.push((*id, answer)); - } - } - for (id, answer) in answers { - state.answer(id, answer.map(|()| Answer::Requests)); - } - }); - } - /// Why the session ended, once it has. fn closed(&self) -> Option { self.read(|link, _| link.closed.clone()) @@ -3212,7 +3167,7 @@ mod tests { /// could carry it. #[test] fn a_request_carries_an_auth_without_the_auth_stream() { - let ietf = Link::ietf(false); + let ietf = Link::ietf(); let auth = ietf.present(Bytes::from_static(b"jwt"), false).unwrap(); assert!(matches!( auth.poll_answered(&kio::Waiter::noop()), @@ -3233,28 +3188,13 @@ mod tests { )); } - /// A peer that turns out not to speak AUTH leaves a moq-transport auth for its - /// requests rather than failing it. - #[test] - fn an_unsupported_peer_keeps_a_request_auth() { - let handle = Link::ietf(true); - let auth = handle.present(Bytes::from_static(b"jwt"), false).unwrap(); - assert!(auth.poll_answered(&kio::Waiter::noop()).is_pending()); - handle.unsupported(); - assert!(matches!( - auth.poll_answered(&kio::Waiter::noop()), - Poll::Ready(Ok(Answer::Requests)) - )); - assert_eq!(handle.token(&auth).as_deref(), Some(b"jwt".as_slice())); - } - /// Only the handle that issued an auth carries it: a route naming another session's /// auth goes out under this session's scope. #[test] fn another_handle_does_not_carry_an_auth() { - let issuer = Link::ietf(false); + let issuer = Link::ietf(); let auth = issuer.present(Bytes::from_static(b"jwt"), false).unwrap(); - assert_eq!(Link::ietf(false).token(&auth), None); + assert_eq!(Link::ietf().token(&auth), None); } /// Every clone names one credential, which stays presented until the last drops. @@ -3850,21 +3790,18 @@ mod request_token_tests { ); } - /// A request-borne token is verified even without the MoQ Auth extension: it rides the - /// request message, not the AUTH stream, so `requests()` stays live on a session whose - /// `supported` is false, even once the peer turns out not to speak AUTH. This is the shape - /// a standard moq-transport peer presents when it does not negotiate the AUTH extension. + /// A request-borne token is verified without AUTH: it rides the request message, so + /// `requests()` stays live on a session that speaks no AUTH, as on moq-transport. #[kio::test] - async fn a_request_token_is_verified_without_the_auth_extension() { + async fn a_request_token_is_verified_without_the_auth_stream() { let handle = Link::new(false); let mut requests = handle.handle().requests(); - handle.unsupported(); let verdict = handle.verify_request(token(b"jwt", 0), None); let request = requests.next().await.expect("a request reaches the acceptor"); let _issued = request.accept(Grant::all()); assert!( verdict.grant().await.expect("granted").publish.matches("room/alice"), - "admitted without the AUTH extension" + "admitted without AUTH" ); } diff --git a/rs/moq-net/src/client.rs b/rs/moq-net/src/client.rs index c0a14c0e104..6090926e2ba 100644 --- a/rs/moq-net/src/client.rs +++ b/rs/moq-net/src/client.rs @@ -272,7 +272,7 @@ impl Client { fn link(&self, supported: bool, requests: bool) -> Result { match &self.auth { Some(handle) => crate::auth::Link::attach(handle, supported, requests), - None if requests => Ok(crate::auth::Link::ietf(supported)), + None if requests => Ok(crate::auth::Link::ietf()), None => Ok(crate::auth::Link::new(supported)), } } @@ -421,11 +421,10 @@ impl Client { // SETUP is exchanged by the connection driver. // We advertise the request path in our SETUP for URL-less transports. - // The peer's SETUP decides whether AUTH is negotiated. A handle that does not - // offer it keeps the option out of our SETUP and presents no credential. - let auth = self.link(self.extensions.auth, true)?; + // moq-transport carries no AUTH: a token rides the requests that name it. + let auth = self.link(false, true)?; let peer_implementation = setup::PeerImplementation::default(); - let (protocol, goaway, credential) = ietf::start(ietf::Config { + let (protocol, goaway) = ietf::start(ietf::Config { runtime: runtime.clone(), stats: self.stats.clone(), limits: self.limits, @@ -459,7 +458,7 @@ impl Client { stats: self.stats.clone(), goaway, auth, - credential, + credential: None, estimate: None, peer_target: None, bandwidth: self.allocator(), diff --git a/rs/moq-net/src/ietf/auth.rs b/rs/moq-net/src/ietf/auth.rs deleted file mode 100644 index b6d50929d12..00000000000 --- a/rs/moq-net/src/ietf/auth.rs +++ /dev/null @@ -1,973 +0,0 @@ -//! The MoQ Auth extension (draft-lcurley-moq-auth-01). -//! -//! The moq-transport binding of the lite Auth Stream (see [`crate::auth`]): each -//! token rides a request stream of its own, answered with the patterns it grants, -//! encoded as lite's AUTH_OK encodes them. Negotiated with the AUTH Setup Option. - -#[cfg(feature = "async")] -use crate::driver::Transport; -use std::task::Poll; -use std::time::Duration; - -use bytes::Bytes; - -use crate::auth::{Grant, Link, Reply, Request, Serving}; -use crate::coding::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder}; -use crate::{Error, Patterns, SessionError}; - -#[cfg(feature = "async")] -use super::Control; -use super::{Message, RequestId, Version, peer}; -#[cfg(feature = "async")] -use crate::coding::Stream; - -/// AUTH Setup Option: the sender speaks this extension. Even, so the value is a bare -/// varint. Draft-01's code point, so a draft-00 peer, which read prefixes, never -/// negotiates it. -pub const AUTH: u64 = 0x40B70; - -/// What the peer declared: `None` for no option, otherwise whether it offered the -/// extension. Only an explicit 1 negotiates it. -pub fn from_setup(params: &super::Parameters) -> Option { - params.get_varint(super::ParameterVarInt::Auth).map(|value| value == 1) -} - -/// Offer the extension. -pub fn into_setup(params: &mut super::Parameters) { - params.set_varint(super::ParameterVarInt::Auth, 1); -} - -/// AUTH: the first message on an Auth request stream, presenting a token. -#[derive(Clone, PartialEq, Eq)] -pub struct Auth { - pub request_id: RequestId, - /// Empty presents the credential the connection already carried. - pub token: Bytes, -} - -impl std::fmt::Debug for Auth { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Auth") - .field("request_id", &self.request_id) - .field("token_len", &self.token.len()) - .finish() - } -} - -impl<'a> Message<'a> for Auth { - const ID: u64 = 0x40B61; - - fn encode_msg(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> { - self.request_id.encode(w, version)?; - w.bytes(&self.token) - } - - fn decode_msg(r: &mut Decoder<'a>, version: Version) -> Result { - Ok(Self { - request_id: RequestId::decode(r, version)?, - token: Bytes::copy_from_slice(r.bytes()?), - }) - } -} - -/// AUTH_OK: the grant a token earns, replacing any earlier one on the stream. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct AuthOk { - /// What the presenter may publish to the acceptor. - pub publish: Patterns, - /// What the presenter may subscribe to from the acceptor. - pub subscribe: Patterns, - /// How long until the grant lapses, or `None` for never. - pub expires: Option, -} - -/// Largest millisecond count every implementation carries losslessly. -const MAX_EXPIRES_MS: u64 = (1 << 53) - 1; - -impl<'a> Message<'a> for AuthOk { - const ID: u64 = 0x40B62; - - fn encode_msg(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> { - self.publish.encode(w, version)?; - self.subscribe.encode(w, version)?; - // 0 means never, so a grant that has already lapsed rounds up to the smallest - // value that still reads as an expiry. - let expires = match self.expires { - None => 0, - Some(expires) => (expires.as_nanos().div_ceil(1_000_000).min(MAX_EXPIRES_MS as u128) as u64).max(1), - }; - w.varint(expires) - } - - fn decode_msg(r: &mut Decoder<'a>, version: Version) -> Result { - let publish = Patterns::decode(r, version)?; - let subscribe = Patterns::decode(r, version)?; - let expires = match r.varint()? { - 0 => None, - ms if ms <= MAX_EXPIRES_MS => Some(Duration::from_millis(ms)), - _ => return Err(DecodeError::InvalidValue), - }; - Ok(Self { - publish, - subscribe, - expires, - }) - } -} - -/// AUTH_ERROR: the acceptor refusing a token, or revoking it after an AUTH_OK. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct AuthError { - /// A code from the REQUEST_ERROR registry. - pub code: u64, - pub reason: String, -} - -/// Longest AUTH_ERROR reason, in bytes, matching the lite wire and rejected from the -/// length prefix alone. -const MAX_REASON: usize = 8192; - -impl<'a> Message<'a> for AuthError { - const ID: u64 = 0x40B63; - - fn encode_msg(&self, w: &mut Encoder<'_>, _: Version) -> Result<(), EncodeError> { - if self.reason.len() > MAX_REASON { - return Err(EncodeError::TooLarge); - } - w.varint(self.code)?; - w.string(&self.reason) - } - - fn decode_msg(r: &mut Decoder<'a>, _: Version) -> Result { - let code = r.varint()?; - if code > u32::MAX as u64 { - return Err(DecodeError::InvalidValue); - } - let len = r.varint()?; - if len > MAX_REASON as u64 { - return Err(DecodeError::InvalidValue); - } - let reason = String::from_utf8(r.slice(len as usize)?.to_vec())?; - Ok(Self { code, reason }) - } -} - -/// The REQUEST_ERROR codes AUTH_ERROR carries. -const UNAUTHORIZED: u64 = 0x1; -const NOT_SUPPORTED: u64 = 0x3; -const MALFORMED_AUTH_TOKEN: u64 = 0x4; -const EXPIRED_AUTH_TOKEN: u64 = 0x5; -const GOING_AWAY: u64 = 0x6; - -/// The AUTH_ERROR code for a refusal. The public API speaks session codes, and the -/// actionable distinctions this registry carries are unsupported, malformed, expired, and -/// unauthorized. -fn to_code(code: SessionError) -> u64 { - match code { - SessionError::Version | SessionError::Unsupported => NOT_SUPPORTED, - SessionError::MalformedAuthToken => MALFORMED_AUTH_TOKEN, - SessionError::Expired => EXPIRED_AUTH_TOKEN, - _ => UNAUTHORIZED, - } -} - -/// Read an AUTH_ERROR code, preserving expiration so the presenter can refresh. -fn from_code(code: u64) -> Error { - match code { - NOT_SUPPORTED => Error::Unsupported, - MALFORMED_AUTH_TOKEN => Error::Session(SessionError::MalformedAuthToken), - EXPIRED_AUTH_TOKEN => Error::Expired, - GOING_AWAY => Error::GoingAway, - _ => Error::Session(SessionError::Unauthorized), - } -} - -/// Refuse an AUTH past our GOAWAY cutoff with AUTH_ERROR, the only answer its presenter reads. -#[cfg(feature = "async")] -pub(super) fn going_away(mut stream: Stream) -> super::request_stream::Reject { - let reply = AuthError { - code: GOING_AWAY, - reason: "going away".to_string(), - }; - let buffered = stream.writer.buffer_message(AuthError::ID, &reply); - super::request_stream::Reject::buffered(stream, buffered) -} - -/// What the peer's connection credential earns by default: publishing what our -/// subscribe half accepts, and subscribing to what our publish half serves. -pub(super) fn peer_grant( - publish: Option<&crate::origin::Consumer>, - subscribe: Option<&crate::origin::Producer>, -) -> Grant { - Grant { - publish: subscribe.map(|origin| origin.allowed()).unwrap_or_default(), - subscribe: publish.map(|origin| origin.allowed()).unwrap_or_default(), - expires: None, - } -} - -/// What every one of our Auth requests is sent with. -#[cfg(feature = "async")] -#[derive(Clone)] -struct Presenter { - stats: crate::stats::Session, - runtime: crate::time::Deadlines, - session: Transport, - control: Control, - handle: Link, - version: Version, -} - -/// Present every token this side adds, one AUTH request each as a child task, once the -/// peer's SETUP says it negotiated the extension. Never finishes: a session without it -/// just fails the tokens as unsupported. -#[cfg(feature = "async")] -pub(super) struct Presenting { - presenter: Presenter, - peer_setup: peer::PeerSetup, - /// Whether the peer's SETUP negotiated the extension, once read. - negotiated: Option, - tasks: crate::util::TaskSet, - /// A protocol violation on any token's stream, which ends the session. - violation: kio::Shared>, - /// The session ended, so no token opens another stream. - ended: bool, -} - -#[cfg(feature = "async")] -impl Presenting { - pub(super) fn new( - runtime: crate::time::Deadlines, - session: Transport, - control: Control, - handle: Link, - peer_setup: peer::PeerSetup, - version: Version, - stats: crate::stats::Session, - ) -> Self { - Self { - presenter: Presenter { - stats, - runtime, - session, - control, - handle, - version, - }, - peer_setup, - negotiated: None, - tasks: crate::util::TaskSet::owned(), - violation: Default::default(), - ended: false, - } - } - - /// Ready only with the protocol violation a token's stream hit. - pub(super) fn poll(&mut self, waiter: &kio::Waiter) -> Poll> { - let negotiated = match self.negotiated { - Some(negotiated) => negotiated, - None => { - let negotiated = std::task::ready!(self.peer_setup.poll_get(waiter)).auth; - if !negotiated { - self.presenter.handle.unsupported(); - } - *self.negotiated.insert(negotiated) - } - }; - if !negotiated || self.ended { - return Poll::Pending; - } - - loop { - if let Poll::Ready(mut err) = self.violation.poll(waiter, |err| match err.is_some() { - true => Poll::Ready(()), - false => Poll::Pending, - }) { - return Poll::Ready(Err(err.take().unwrap())); - } - match self.presenter.handle.poll_opening(waiter) { - Poll::Ready(Some((id, token))) => { - let mut present = Present { - presenter: self.presenter.clone(), - violation: self.violation.clone(), - id, - answered: false, - state: PresentState::Start(Ok(token)), - }; - self.tasks.push(move |waiter: &kio::Waiter| present.poll(waiter)); - } - // The children are left where they wait, no longer polled. - Poll::Ready(None) => { - self.ended = true; - return Poll::Pending; - } - Poll::Pending => { - // The children never end the session; `Ready` just means they're drained - // until the next token. - let _ = self.tasks.poll(waiter); - return Poll::Pending; - } - } - } - } -} - -/// One token's Auth requests: presented, tracked until either side ends it, and -/// presented again while [`Link::retry`] asks. -#[cfg(feature = "async")] -struct Present { - presenter: Presenter, - violation: kio::Shared>, - id: u64, - /// The peer replied to the token, on this request or an earlier one, so a request it - /// closes or resets before replying is lost rather than unsupported. - answered: bool, - state: PresentState, -} - -#[cfg(feature = "async")] -enum PresentState { - /// The token to present next, or why it cannot be. - Start(Result), - /// Waiting for a stream to send it on. - Opening { - open: crate::transport::open::Open, - token: Bytes, - }, - /// Flushing the AUTH. - Sending(Stream), - /// Reading the peer's replies. - Reading { - stream: Stream, - messages: super::request_stream::Messages, - budget: kio::coop::Budget, - }, - /// Waiting out a retry's delay. - Reopening(crate::time::Deadline), - Done, -} - -#[cfg(feature = "async")] -impl Present { - fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> { - loop { - let err = match &mut self.state { - PresentState::Start(token) => match std::mem::replace(token, Err(Error::Cancel)) { - // After a GOAWAY, sent or received, the peer must not see new requests. - Ok(token) if self.presenter.handle.active() => { - self.state = PresentState::Opening { - open: Default::default(), - token, - }; - continue; - } - Ok(_) => Error::GoingAway, - Err(err) => err, - }, - PresentState::Reopening(deadline) => { - let token = match self.presenter.handle.poll_withdrawn(self.id, waiter) { - Poll::Ready(()) => Err(Error::Cancel), - Poll::Pending => { - std::task::ready!(deadline.poll(waiter)); - self.presenter.handle.reopen(self.id) - } - }; - self.state = PresentState::Start(token); - continue; - } - PresentState::Done => return Poll::Ready(()), - PresentState::Opening { .. } | PresentState::Sending(_) | PresentState::Reading { .. } => { - let err = std::task::ready!(self.poll_request(waiter)); - // Drops the stream, whose reset is what tells the peer. - self.state = PresentState::Done; - err - } - }; - - let err = match err { - // The peer negotiated the extension, but a reset before any reply still tells - // us nothing about the token: it earns nothing here, as on moq-lite. - Error::Stream(_) if !self.answered => Error::Unsupported, - err => crate::auth::protocol_error(err), - }; - let handle = &self.presenter.handle; - // AUTH_ERROR carries no code that may pass, so unlike moq-lite only a lost - // request is presented again. - if let Some(delay) = handle.retry(self.id, &err) { - tracing::debug!(%err, ?delay, "auth token presenting again"); - self.state = PresentState::Reopening(crate::time::Deadline::after(&self.presenter.runtime, delay)); - continue; - } - if matches!(err, Error::ProtocolViolation) { - self.violation.lock().get_or_insert(err.clone()); - } - - match &err { - Error::Cancel | Error::Unsupported | Error::Transport(_) | Error::IdleTimeout | Error::Session(_) => { - tracing::debug!(%err, "auth token ended") - } - err => tracing::warn!(%err, "auth token ended"), - } - handle.ended(self.id, err); - return Poll::Ready(()); - } - } - - /// Send the token, then track its grant until either side ends it, ready with why. - fn poll_request(&mut self, waiter: &kio::Waiter) -> Poll { - let presenter = &self.presenter; - loop { - match &mut self.state { - PresentState::Opening { open, token } => { - let stream = - match std::task::ready!(Stream::poll_open(&presenter.session, open, presenter.version, waiter)) - { - Ok(stream) => stream, - Err(err) => return Poll::Ready(err), - }; - let mut stream = stream.with_stats(&presenter.stats); - let auth = Auth { - request_id: presenter.control.next_request_id(), - token: std::mem::take(token), - }; - if let Err(err) = stream.writer.buffer_message(Auth::ID, &auth) { - return Poll::Ready(err); - } - self.state = PresentState::Sending(stream); - } - PresentState::Sending(stream) => { - if let Err(err) = std::task::ready!(stream.writer.poll_flush(waiter)) { - return Poll::Ready(err); - } - let PresentState::Sending(stream) = std::mem::replace(&mut self.state, PresentState::Done) else { - unreachable!() - }; - self.state = PresentState::Reading { - stream, - messages: super::request_stream::Messages::new( - presenter.session.clone(), - presenter.control.client(), - ), - // Each grant recomputes the session's permits, so a peer streaming them - // must not hold the session's other tasks. - budget: kio::coop::Budget::new(32), - }; - } - PresentState::Reading { - stream, - messages, - budget, - } => loop { - std::task::ready!(budget.poll_yield(waiter)); - if presenter.handle.poll_withdrawn(self.id, waiter).is_ready() { - // Resetting our side is what tells the peer. - return Poll::Ready(Error::Cancel); - } - let (id, body) = match std::task::ready!(messages.poll_next(&mut stream.reader, waiter)) { - Ok(Some(super::request_stream::Framed(id, body))) => (id, body), - // The peer ended the grant without revoking it. - Ok(None) if self.answered => return Poll::Ready(Error::Cancel), - // A peer that closes before answering could not tell us anything. - Ok(None) => return Poll::Ready(Error::Unsupported), - Err(err) => return Poll::Ready(err), - }; - - match id { - AuthOk::ID => { - let ok: AuthOk = match decode_reply(&body, presenter.version) { - Ok(ok) => ok, - Err(err) => return Poll::Ready(err), - }; - let now = presenter.runtime.now(); - // The expiry is the peer's number: one past the local clock's range is - // malformed, not a reason to panic. - let expires = match ok.expires.map(|expires| now.checked_add(expires)) { - Some(None) => return Poll::Ready(Error::ProtocolViolation), - expires => expires.flatten(), - }; - self.answered = true; - presenter.handle.granted( - self.id, - Grant { - publish: ok.publish, - subscribe: ok.subscribe, - expires, - }, - ); - } - AuthError::ID => { - let refused: AuthError = match decode_reply(&body, presenter.version) { - Ok(refused) => refused, - Err(err) => return Poll::Ready(err), - }; - let err = from_code(refused.code); - tracing::warn!(%err, code = refused.code, reason = %refused.reason, "auth token refused"); - // A grant the acceptor could not tell, or never judged, is unknown, not - // empty, so only a real refusal settles the union. - if !matches!(err, Error::Unsupported | Error::GoingAway) { - presenter.handle.refused(self.id); - } - self.answered = true; - return Poll::Ready(err); - } - _ => return Poll::Ready(Error::UnexpectedMessage), - } - }, - PresentState::Start(_) | PresentState::Reopening(_) | PresentState::Done => { - unreachable!("not a request") - } - } - } - } -} - -/// Decode a reply that must fill its whole body, as every framed message does. -fn decode_reply<'m, T: Message<'m>>(body: &'m super::Body, version: Version) -> Result { - let mut data = body.decoder(version); - let msg = T::decode_msg(&mut data, version)?; - if !data.is_empty() { - return Err(Error::WrongSize); - } - Ok(msg) -} - -/// Answers the peer's Auth requests: the app's verdict when it took the requests, -/// otherwise the default grant for the connection's own credential. -#[derive(Clone)] -pub(super) struct Serve { - pub runtime: crate::time::Deadlines, - pub handle: Link, - /// What the peer's connection credential earns by default. - pub peer_grant: Grant, -} - -impl Serve { - /// Start answering one Auth request. The stream lives as long as the token. - #[cfg(feature = "async")] - pub(super) fn answer(self, mut stream: Stream, msg: Auth, version: Version) -> Answering { - let goaways = super::request_stream::GoAways::new(msg.request_id.0 % 2 == 1); - let serving = Serving::new(self.handle.clone()); - let mut default = None; - let state = match self.handle.acceptor() { - Some(requests) => { - requests.push(Request::new(msg.token, serving.issue.clone())); - AnsweringState::Serving - } - // Only the connection's own credential has a default answer; a token needs - // someone to verify it. - None if !msg.token.is_empty() => { - let reply = AuthError { - code: NOT_SUPPORTED, - reason: "tokens are not verified in band".to_string(), - }; - match stream.writer.buffer_message(AuthError::ID, &reply) { - Ok(()) => AnsweringState::Unverified, - Err(_) => AnsweringState::Done, - } - } - // Re-sent whenever a new limit changes it. - None => { - default = Some(crate::auth::DefaultGrant::new(self.handle.clone(), self.peer_grant)); - AnsweringState::Serving - } - }; - Answering { - runtime: self.runtime, - serving, - default, - stream: Some(stream), - version, - goaways, - state, - } - } -} - -/// One Auth request being answered: [`Serve::answer`]. -#[cfg(feature = "async")] -pub(super) struct Answering { - runtime: crate::time::Deadlines, - serving: Serving, - /// Feeds the default acceptor's grant into the outbox as it changes. - default: Option, - /// Taken only to close it after refusing an unverified token. - stream: Option>, - version: Version, - goaways: super::request_stream::GoAways, - state: AnsweringState, -} - -#[cfg(feature = "async")] -enum AnsweringState { - /// Flushing the refusal of a token nobody verifies, then closing. - Unverified, - /// Waiting for the refusal's acknowledgement. - UnverifiedClosing { - closing: crate::coding::Closing, - _reader: crate::coding::Reader, - }, - /// Writing the acceptor's replies until either side ends the token. - Serving, - /// Flushing a reply; `last` ends the replies once it is out. - Flushing { - last: bool, - }, - /// Waiting for the acknowledgement of our FIN. - Closing, - Done, -} - -#[cfg(feature = "async")] -impl Answering { - /// Ready once the token's stream ends, failing only on a protocol violation. - pub(super) fn poll(&mut self, waiter: &kio::Waiter) -> Poll> { - loop { - match &mut self.state { - AnsweringState::Unverified => { - let stream = self.stream.as_mut().expect("unverified holds the stream"); - let flushed = std::task::ready!(stream.writer.poll_flush(waiter)); - self.state = AnsweringState::Done; - if flushed.is_ok() { - let Stream { writer, reader } = self.stream.take().expect("unverified holds the stream"); - if let Ok(closing) = writer.closing() { - self.state = AnsweringState::UnverifiedClosing { - closing, - _reader: reader, - }; - } - } - } - AnsweringState::UnverifiedClosing { closing, .. } => { - let _ = std::task::ready!(closing.poll(waiter)); - self.state = AnsweringState::Done; - } - AnsweringState::Done => return Poll::Ready(Ok(())), - AnsweringState::Serving | AnsweringState::Flushing { .. } | AnsweringState::Closing => { - let err = match std::task::ready!(self.poll_issue(waiter)) { - Ok(()) => Error::Cancel, - Err(err) => { - match &err { - Error::Cancel - | Error::Unsupported - | Error::Stream(_) - | Error::Session(_) - | Error::Transport(_) - | Error::IdleTimeout => { - tracing::debug!(%err, "auth request ended") - } - err => tracing::warn!(%err, "auth request error"), - } - err - } - }; - self.state = AnsweringState::Done; - let err = crate::auth::protocol_error(err); - self.serving.end(err.clone()); - if matches!(err, Error::ProtocolViolation) { - return Poll::Ready(Err(err)); - } - return Poll::Ready(Ok(())); - } - } - } - } - - /// Write the acceptor's replies until either side ends the token. - fn poll_issue(&mut self, waiter: &kio::Waiter) -> Poll> { - let issue = &self.serving.issue; - let stream = self.stream.as_mut().expect("serving holds the stream"); - loop { - let reply = match &mut self.state { - AnsweringState::Flushing { last } => { - std::task::ready!(stream.writer.poll_flush(waiter))?; - match *last { - true => { - stream.writer.finish()?; - self.state = AnsweringState::Closing; - } - false => self.state = AnsweringState::Serving, - } - continue; - } - AnsweringState::Closing => return stream.writer.poll_closed(waiter), - AnsweringState::Serving => { - if let Poll::Ready(res) = self - .goaways - .poll_next::(&mut stream.reader, waiter) - .map(|res| res.map(|_| ())) - { - match res { - // The presenter withdrew the token, by FIN or by a cancelling reset. - // That is why it ended, whether or not our own FIN reaches a - // presenter that left. - Ok(()) | Err(Error::Stream(crate::StreamError::Cancel)) => { - issue.lock().peer.get_or_insert(Error::Cancel); - stream.writer.finish()?; - self.state = AnsweringState::Closing; - continue; - } - Err(err) => return Poll::Ready(Err(err)), - } - } - if let Some(default) = self.default.as_mut() - && let Poll::Ready(grant) = default.poll(waiter) - { - issue.lock().queue(Reply::Grant(grant)); - } - let mut issue = std::task::ready!(issue.poll(waiter, |issue| match issue.idle() { - true => Poll::Pending, - false => Poll::Ready(()), - })); - issue.next() - } - AnsweringState::Unverified | AnsweringState::UnverifiedClosing { .. } | AnsweringState::Done => { - unreachable!("not serving") - } - }; - - match reply { - Some(Reply::Grant(grant)) => { - let now = self.runtime.now(); - let ok = AuthOk { - publish: grant.publish, - subscribe: grant.subscribe, - expires: grant.expires.map(|at| at.saturating_duration_since(now)), - }; - // Sized as the full message before anything is written, so a grant over the u16 - // message size never leaves half a message on the wire. Never trim it: refuse, - // which revokes whatever this stream granted before. - if let Err(err) = ok.encode(&mut Encoder::new(&mut Vec::new(), self.version.into()), self.version) { - tracing::debug!(%err, "auth grant cannot be encoded as one AUTH_OK; refusing the token"); - issue.lock().refused(); - let refused = AuthError { - code: NOT_SUPPORTED, - reason: "grant cannot be encoded as one AUTH_OK".to_string(), - }; - stream.writer.buffer_message(AuthError::ID, &refused)?; - self.state = AnsweringState::Flushing { last: true }; - continue; - } - stream.writer.buffer_message(AuthOk::ID, &ok)?; - self.state = AnsweringState::Flushing { last: false }; - } - Some(Reply::Refuse { code, reason }) => { - let refused = AuthError { - code: to_code(code), - reason, - }; - stream.writer.buffer_message(AuthError::ID, &refused)?; - self.state = AnsweringState::Flushing { last: false }; - } - // The app is done with the grant, or refused the token: close our side. - None => { - stream.writer.finish()?; - self.state = AnsweringState::Closing; - } - } - } - } -} - -/// Anything but a GOAWAY after the presenter's Auth: refused once its type is read, -/// rather than waiting on a body that cannot make it legal. -#[cfg(feature = "async")] -#[derive(Debug)] -struct Unexpected; - -#[cfg(feature = "async")] -impl<'a> crate::coding::Decode<'a, Version> for Unexpected { - fn decode(r: &mut crate::coding::Decoder<'_>, _: Version) -> Result { - Err(crate::coding::DecodeError::InvalidMessage(r.varint()?)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Pattern; - - #[cfg(feature = "async")] - #[kio::test] - async fn auth_waiting_for_credit_spends_no_request_id() { - for version in [Version::Draft18] { - for client in [false, true] { - let first = if client { 0 } else { 1 }; - let control = Control::new(client); - let mut present = Present { - presenter: Presenter { - runtime: crate::time::sim(), - stats: Default::default(), - session: crate::driver::Transport::new( - crate::lite::test_transport::ScriptedSession::new(Vec::new()).without_credit(), - ), - control: control.clone(), - handle: Link::new(false), - version, - }, - violation: Default::default(), - id: 0, - answered: false, - state: PresentState::Opening { - open: Default::default(), - token: Bytes::new(), - }, - }; - let polled = kio::wait(|waiter| Poll::Ready(present.poll_request(waiter).is_pending())).await; - assert!(polled, "the request waits for credit"); - assert_eq!(control.next_request_id(), RequestId(first)); - } - } - } - - const VERSION: Version = Version::Draft18; - - fn patterns(texts: &[&str]) -> Patterns { - texts.iter().map(|text| Pattern::try_from(*text).unwrap()).collect() - } - - fn encode_msg<'m, T: Message<'m>>(msg: &T, version: Version) -> Result, EncodeError> { - let mut buf = Vec::new(); - msg.encode_msg(&mut Encoder::new(&mut buf, version.into()), version)?; - Ok(buf) - } - - fn round_trip Message<'m> + PartialEq>(msg: &T) -> T { - let buf = encode_msg(msg, VERSION).unwrap(); - let mut r = Decoder::new(&buf, VERSION.into()); - let got = T::decode_msg(&mut r, VERSION).unwrap(); - assert!(r.is_empty(), "trailing bytes after decode"); - got - } - - /// Every draft that negotiates the extension round-trips the option. - #[test] - fn setup_option_round_trips_on_supported_drafts() { - for version in [Version::Draft18, Version::Draft20, Version::Draft22] { - let mut params = super::super::Parameters::default(); - assert_eq!(from_setup(¶ms), None); - into_setup(&mut params); - assert_eq!(from_setup(¶ms), Some(true), "{version:?}"); - } - } - - /// An explicit value other than 1 is an implementation that declined, which is - /// not the same statement as saying nothing. - #[test] - fn only_one_negotiates() { - let mut params = super::super::Parameters::default(); - params.set_varint(super::super::ParameterVarInt::Auth, 0); - assert_eq!(from_setup(¶ms), Some(false)); - } - - #[test] - fn auth_round_trips() { - for token in [Bytes::new(), Bytes::from_static(b"eyJhbGciOi.jwt")] { - let msg = Auth { - request_id: RequestId(4), - token, - }; - assert_eq!(round_trip(&msg), msg); - } - } - - /// `**` grants everything, the empty pattern only the root, and the empty list - /// nothing; literals and wildcards travel exactly, never widened to a prefix. - #[test] - fn auth_ok_round_trips() { - for (publish, subscribe, expires) in [ - (patterns(&["**"]), patterns(&[]), None), - (patterns(&[""]), patterns(&["room/**"]), None), - ( - patterns(&["ch1", "room/*/cam", "**/demo.hang"]), - patterns(&["live/*", "lobby/cam-*.hang"]), - Some(Duration::from_secs(60)), - ), - ] { - let msg = AuthOk { - publish, - subscribe, - expires, - }; - assert_eq!(round_trip(&msg), msg); - } - } - - /// Each pattern is its canonical text, in canonical order, as lite's AUTH_OK spells it. - /// The exact bytes, shared with `js/net/src/ietf/auth.test.ts` so both encoders agree. - #[test] - fn auth_ok_golden() { - let msg = AuthOk { - publish: patterns(&["room/*/cam", "ch1"]), - subscribe: patterns(&[""]), - expires: None, - }; - let buf = encode_msg(&msg, VERSION).unwrap(); - assert_eq!(&buf[..], b"\x02\x03ch1\x0aroom/*/cam\x01\x00\x00"); - } - - #[test] - fn auth_error_round_trips() { - let msg = AuthError { - code: UNAUTHORIZED, - reason: "expired".to_string(), - }; - assert_eq!(round_trip(&msg), msg); - } - - /// An oversized reason is refused from its length prefix, before any of it arrives. - #[test] - fn auth_error_reason_is_capped_by_its_prefix() { - let mut buf = Vec::new(); - let mut w = Encoder::new(&mut buf, VERSION.into()); - w.varint(UNAUTHORIZED).unwrap(); - w.varint(MAX_REASON as u64 + 1).unwrap(); - let err = AuthError::decode_msg(&mut Decoder::new(&buf, VERSION.into()), VERSION).unwrap_err(); - assert!(matches!(err, DecodeError::InvalidValue), "{err:?}"); - } - - /// A reply with bytes past its message is refused, like any other framed message. - #[test] - fn replies_with_trailing_bytes_are_refused() { - let ok = AuthOk { - publish: patterns(&["room"]), - subscribe: Patterns::new(), - expires: None, - }; - let refused = AuthError { - code: UNAUTHORIZED, - reason: "expired".to_string(), - }; - let body = |msg: Vec, extra: &[u8]| super::super::Body(Bytes::from([&msg[..], extra].concat())); - - let exact = encode_msg(&ok, VERSION).unwrap(); - assert_eq!(decode_reply::(&body(exact.clone(), &[]), VERSION).unwrap(), ok); - let err = decode_reply::(&body(exact, &[0]), VERSION).unwrap_err(); - assert!(matches!(err, Error::WrongSize), "{err:?}"); - - let exact = encode_msg(&refused, VERSION).unwrap(); - assert_eq!( - decode_reply::(&body(exact.clone(), &[]), VERSION).unwrap(), - refused - ); - let err = decode_reply::(&body(exact, &[0]), VERSION).unwrap_err(); - assert!(matches!(err, Error::WrongSize), "{err:?}"); - } - - /// NOT_SUPPORTED is the acceptor unable to tell a grant, never a refusal. - #[test] - fn not_supported_is_unsupported() { - assert!(matches!(from_code(NOT_SUPPORTED), Error::Unsupported)); - assert!(matches!( - from_code(UNAUTHORIZED), - Error::Session(SessionError::Unauthorized) - )); - assert_eq!(to_code(SessionError::Unauthorized), UNAUTHORIZED); - assert!(matches!(from_code(EXPIRED_AUTH_TOKEN), Error::Expired)); - assert_eq!(to_code(SessionError::Expired), EXPIRED_AUTH_TOKEN); - assert!(matches!( - from_code(MALFORMED_AUTH_TOKEN), - Error::Session(SessionError::MalformedAuthToken) - )); - assert_eq!(to_code(SessionError::MalformedAuthToken), MALFORMED_AUTH_TOKEN); - } -} diff --git a/rs/moq-net/src/ietf/message.rs b/rs/moq-net/src/ietf/message.rs index f0e16ec4f3a..9fba2507028 100644 --- a/rs/moq-net/src/ietf/message.rs +++ b/rs/moq-net/src/ietf/message.rs @@ -10,7 +10,6 @@ pub(super) fn control(id: u64) -> crate::stats::Message { TrackStatus::ID | SubscribeTracks::ID | PublishSkipped::ID => Class::TrackInfo, Subscribe::ID | SubscribeOk::ID | Publish::ID | PublishOk::ID | PublishDone::ID => Class::Subscribe, Fetch::ID | FetchOk::ID => Class::Fetch, - auth::Auth::ID | auth::AuthOk::ID | auth::AuthError::ID => Class::Auth, GoAway::ID => Class::Goaway, _ => Class::Other, } diff --git a/rs/moq-net/src/ietf/mod.rs b/rs/moq-net/src/ietf/mod.rs index bfc349d728a..fbd5afca477 100644 --- a/rs/moq-net/src/ietf/mod.rs +++ b/rs/moq-net/src/ietf/mod.rs @@ -16,7 +16,6 @@ #[macro_use] mod parameters; pub mod active_count; -pub(crate) mod auth; pub mod cluster; #[cfg(feature = "async")] mod control; @@ -101,7 +100,6 @@ mod tests { ("RELAY_COST", cluster::RELAY_COST, 0x40B56), ("SOLICIT", solicit::SOLICIT, 0x40B5A), ("HIDDEN", hidden::HIDDEN, 0x40B5C), - ("AUTH", auth::AUTH, 0x40B70), ("ACTIVE_COUNT", active_count::ACTIVE_COUNT, 0x40B64), ] { assert_eq!(key, spec, "{name}"); diff --git a/rs/moq-net/src/ietf/parameters.rs b/rs/moq-net/src/ietf/parameters.rs index 38a1e7d3970..8806eab9eff 100644 --- a/rs/moq-net/src/ietf/parameters.rs +++ b/rs/moq-net/src/ietf/parameters.rs @@ -25,8 +25,6 @@ pub enum ParameterVarInt { Solicit = super::solicit::SOLICIT, /// HIDDEN, from the MoQ Hidden extension. Hidden = super::hidden::HIDDEN, - /// AUTH, from the MoQ Auth extension. - Auth = super::auth::AUTH, /// ACTIVE_COUNT, from the MoQ Active Count extension. ActiveCount = super::active_count::ACTIVE_COUNT, /// Subscriber max age, from the MoQ Timestamp extension. diff --git a/rs/moq-net/src/ietf/peer.rs b/rs/moq-net/src/ietf/peer.rs index 011ea9ec76c..53e37eb3f30 100644 --- a/rs/moq-net/src/ietf/peer.rs +++ b/rs/moq-net/src/ietf/peer.rs @@ -23,9 +23,6 @@ pub(crate) struct Peer { /// Whether the peer understands subscriber max age (MoQ Timestamp). pub max_age: bool, - /// MoQ Auth: whether both sides negotiated the Auth request streams. - pub auth: bool, - /// MoQ Active Count: whether the REQUEST_OK answering SUBSCRIBE_NAMESPACE counts the /// NAMESPACE messages before the subscription is synced, in both directions. pub active_count: bool, @@ -127,7 +124,6 @@ mod tests { solicit: None, hidden: false, max_age: false, - auth: false, active_count: false, flate: false, }; @@ -142,7 +138,6 @@ mod tests { solicit: Some(true), hidden: true, max_age: false, - auth: true, active_count: true, flate: true, }); diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index d48dd5b09f7..102606eb3a3 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -718,7 +718,7 @@ struct Namespaces { /// Requests whose stream woke the loop, so a wake polls those rather than every /// update in flight. woken: Arc, - /// What we may advertise: our grant (MoQ Auth) and the ceiling on the peer. + /// What we may advertise: our grant and the ceiling on the peer. permit: crate::auth::Permit, /// The dispatcher-owned gate for a solicited namespace request. gate: Option, @@ -871,7 +871,7 @@ enum NamespaceEvent { Update(Option<(crate::announce::Announce, bool, bool)>), /// The retry sleep fired: re-offer whatever the peer should be holding and isn't. Retry, - /// Our grant (MoQ Auth) or the ceiling changed: re-check every namespace against it. + /// Our grant or the ceiling changed: re-check every namespace against it. Regrant(crate::auth::Permit), /// The queued update at the front got this request ID. Renew(RequestId), @@ -948,7 +948,7 @@ pub(super) struct Publisher { // Shared across request handlers; None marks a dispatched subscription still resolving. joins: kio::Shared>>>>, version: Version, - // Our grant (MoQ Auth): only what it lets us publish is advertised and served, and a + // Our grant: only what it lets us publish is advertised and served, and a // shrink withdraws what it no longer covers. auth: crate::auth::Link, // Dispatched finite serves, including those not yet polled. @@ -1299,7 +1299,7 @@ impl SubscribeRequest { // refused by the lookup, on this request alone. tracing::debug!(id = %msg.request_id, broadcast = %self.broadcast(), track = %msg.track_name, "subscribe started"); - // Serve only what our grant lets us publish (MoQ Auth), and stop once it no + // Serve only what our grant lets us publish, and stop once it no // longer does. Checked before resolving, so a denied request never reaches the // origin. Our own authorization of the peer (the limit) admits a request without a // token; an AUTHORIZATION TOKEN on the request goes to the application to verify for @@ -2851,7 +2851,7 @@ impl Publisher { } } - /// Bound what we publish by the grant this session's tokens earn (MoQ Auth). + /// Bound what we publish by the grant this session's tokens earn. pub fn with_auth(mut self, auth: crate::auth::Link) -> Self { self.auth = auth; self @@ -5874,9 +5874,7 @@ struct ForwardNamespaces { enum ForwardState { Start, - /// Waiting on the peer's SETUP, and with MoQ Auth on the answer to the credential we - /// presented at setup, so the first advertisement, the initial set included, is already - /// checked against our grant. + /// Waiting on the peer's SETUP, which says which extensions an advertisement carries. Setup, /// Streaming updates (origin route (un)announces), until the peer closes its side. Run, @@ -5928,9 +5926,7 @@ impl ForwardNamespaces { self.state = ForwardState::Setup; } ForwardState::Setup => { - if ready!(publisher.peer_setup.poll_get(waiter)).auth { - ready!(publisher.auth.poll_setup_answered(waiter)); - } + ready!(publisher.peer_setup.poll_get(waiter)); (ns.permit, ns.epoch) = publisher.permit_now(ns.gate.as_ref()); self.work = std::mem::take(&mut self.initial) .into_iter() @@ -6425,17 +6421,12 @@ enum NamespaceServeState { /// peer's SETUP says whether it speaks it. The same SETUP says whether the OK counts what /// it sends first (MoQ Active Count). Setup, - /// With MoQ Auth, the count waits for our grant and leaves out what it does not cover. - Count { - peer: cluster::Peer, - hidden: bool, - announced: crate::origin::Routes, - }, /// The acknowledgement, sent only while the token is live, even behind stream credit. Ok { peer: cluster::Peer, hidden: bool, - announced: crate::origin::Routes, + // Boxed: the routes cursor dwarfs every other state. + announced: Box, initial: Vec, /// Taken once buffered. ok: Option, @@ -6517,7 +6508,7 @@ impl NamespaceOpen { self.state = NamespaceServeState::Ok { peer, hidden, - announced, + announced: Box::new(announced), initial, ok: Some(ietf::RequestOk { largest: None, @@ -6600,19 +6591,12 @@ impl NamespaceOpen { let announced = origin.routes(); match declared.active_count { - true if declared.auth => { - self.state = NamespaceServeState::Count { - peer, - hidden, - announced, - } - } true => self.count(peer, hidden, announced), false => { self.state = NamespaceServeState::Ok { peer, hidden, - announced, + announced: Box::new(announced), initial: Vec::new(), ok: Some(ietf::RequestOk { largest: None, @@ -6622,18 +6606,6 @@ impl NamespaceOpen { } } } - NamespaceServeState::Count { .. } => { - ready!(gate.poll_setup_answered(waiter)); - let NamespaceServeState::Count { - peer, - hidden, - announced, - } = std::mem::replace(&mut self.state, NamespaceServeState::Done) - else { - unreachable!("counting"); - }; - self.count(peer, hidden, announced); - } NamespaceServeState::Ok { ok, .. } => { if let Poll::Ready(refusal) = gate.poll_token_ended(waiter) { return Poll::Ready(Err(refusal.error)); @@ -6655,7 +6627,7 @@ impl NamespaceOpen { return Poll::Ready(Ok(Some(Acknowledged { peer, hidden, - announced, + announced: *announced, initial, }))); } @@ -19623,7 +19595,6 @@ mod tests { solicit, hidden: false, max_age: false, - auth: false, active_count: false, flate: false, }); @@ -19960,7 +19931,7 @@ mod tests { async fn swaps_a_route_auth(version: Version) { let origin = unheld_origin(); - let auth = crate::auth::Link::ietf(false); + let auth = crate::auth::Link::ietf(); let first = auth.present(bytes::Bytes::from_static(b"first-secret"), false).unwrap(); let second = auth .present(bytes::Bytes::from_static(b"second-secret"), false) @@ -20026,7 +19997,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = unheld_origin(); - let other = crate::auth::Link::ietf(false); + let other = crate::auth::Link::ietf(); let foreign = other .present(bytes::Bytes::from_static(b"foreign-secret"), false) .unwrap(); @@ -20036,7 +20007,7 @@ mod tests { settle().await; let ok = publish_namespace_ok(VERSION).await; - let (publisher, log) = auth_publisher(&origin, &crate::auth::Link::ietf(false), vec![ok], VERSION); + let (publisher, log) = auth_publisher(&origin, &crate::auth::Link::ietf(), vec![ok], VERSION); let mut run = std::pin::pin!(publisher.run_publish_namespaces()); poll_until(&mut run, &log, b"cam", 1).await; @@ -20055,7 +20026,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = unheld_origin(); - let auth = crate::auth::Link::ietf(false); + let auth = crate::auth::Link::ietf(); let token = auth.present(bytes::Bytes::from_static(b"late-secret"), false).unwrap(); let cam = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; @@ -20081,7 +20052,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = unheld_origin(); - let auth = crate::auth::Link::ietf(false); + let auth = crate::auth::Link::ietf(); let present = |token: &'static [u8]| auth.present(bytes::Bytes::from_static(token), false).unwrap(); let a = origin .announce("cam-a", crate::origin::RouteInfo::new().with_auth(present(b"a-first"))) @@ -20280,7 +20251,7 @@ mod tests { // A token too big for the header's u16 length, so the header fails after its stream // opened and its request ID was spent. A message goes out whole, so this is the one // failure a fresh in-memory stream can be made to show. - let auth = crate::auth::Link::ietf(false); + let auth = crate::auth::Link::ietf(); let token = auth.present(bytes::Bytes::from(vec![0; 70_000]), false).unwrap(); let _cam = origin .announce("cam", crate::origin::RouteInfo::new().with_auth(token)) @@ -20327,7 +20298,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = unheld_origin(); - let auth = crate::auth::Link::ietf(false); + let auth = crate::auth::Link::ietf(); let present = |token: &'static [u8]| auth.present(bytes::Bytes::from_static(token), false).unwrap(); let cam = origin .announce("cam", crate::origin::RouteInfo::new().with_auth(present(b"first"))) @@ -20380,7 +20351,7 @@ mod tests { async fn advertises_again_unanswered(version: Version) { let origin = unheld_origin(); - let auth = crate::auth::Link::ietf(false); + let auth = crate::auth::Link::ietf(); let present = |token: &'static [u8]| auth.present(bytes::Bytes::from_static(token), false).unwrap(); let cam = origin .announce("cam", crate::origin::RouteInfo::new().with_auth(present(b"first"))) @@ -20613,7 +20584,7 @@ mod tests { } for end in [End::Local, End::Fin, End::Reset, End::Refused] { let origin = unheld_origin(); - let auth = crate::auth::Link::ietf(false); + let auth = crate::auth::Link::ietf(); let first = auth.present(bytes::Bytes::from_static(b"first"), false).unwrap(); let mut first_grant = first.grant(); let cam = origin diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 1ca7020ef8a..a464f4893e7 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -12,8 +12,7 @@ use std::task::{Poll, ready}; use super::{ Control, Message, Namespaces, PublishNamespaces, Publisher, RecvFill, RecvGroup, Subscriber, Version, active_count, - auth, cluster, hidden, max_age, peer, request_stream::Reject, request_update, solicit, - subscriber::is_protocol_violation, + cluster, hidden, max_age, peer, request_stream::Reject, request_update, solicit, subscriber::is_protocol_violation, }; type RecvStream = crate::transport::boxed::RecvStream; @@ -78,17 +77,15 @@ pub struct Config { pub peer_declared: Option, /// The session's auth handle, created before [`start`] so a server can take the - /// peer's token requests during its handshake. Supports AUTH exactly when the - /// version can negotiate it and this side offers it; the peer's SETUP decides whether - /// it does. + /// peer's token requests during its handshake. moq-transport carries no AUTH, so it + /// only verifies the tokens requests carry. pub auth: crate::auth::Link, /// Uni streams that arrived before that pre-read SETUP (see [`PeerSetup::early`]), /// classified by the session before it accepts any more. pub early_unis: Vec>, - /// The extensions our SETUP offers. MoQ Auth is offered only while [`Self::auth`] - /// supports it too. + /// The extensions our SETUP offers. pub extensions: crate::setup::Extensions, /// The Implementation our SETUP advertises, or `None` to omit it. @@ -133,7 +130,7 @@ impl std::future::Future for Driver { /// Where the session is in its life. enum Machine { /// Not polled yet. The session is built on the first poll, since until then the app - /// may still take the peer's Auth requests. + /// may still take the peer's token requests. Start(Box), Running(Box), Done, @@ -159,7 +156,7 @@ impl Machine { } } -pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle, Option), Error> { +pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle), Error> { let Config { runtime, stats, @@ -189,19 +186,6 @@ pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle, Option auth.present(bytes::Bytes::new(), true).ok(), - false => None, - }; - // Which prefixes to SUBSCRIBE_NAMESPACE, as for moq-lite: a client asks about what // its origin's readers watch, a server or relay link about its whole scope. Decided // now, so the origin's announce consumers never read as synced before a request goes @@ -226,9 +210,7 @@ pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle, Option {} } - let credential = setup_token.clone(); let launch = Launch { - setup_token, auth, runtime, stats, @@ -250,7 +232,6 @@ pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle, Option Result<(Driver, crate::goaway::Handle, Option, auth: crate::auth::Link, runtime: crate::time::Deadlines, stats: crate::stats::Session, @@ -289,7 +268,6 @@ struct Launch { peer_setup_stream: Option>, early_unis: Vec>, goaway: crate::goaway::Protocol, - peer_grant: crate::auth::Grant, discovery: Option, withdrawal: crate::session::Withdrawal, owed: std::sync::Arc, @@ -300,7 +278,6 @@ struct Launch { impl Launch { fn run(self) -> Running { let Self { - setup_token, auth, runtime, stats, @@ -316,7 +293,6 @@ impl Launch { peer_setup_stream, early_unis, goaway, - peer_grant, discovery, withdrawal, owed, @@ -348,18 +324,13 @@ impl Launch { crate::session::Slots::new(limits.announces).with_stats(subscribe.stats(), crate::stats::Cap::Announces); let control = Control::new(client); + let solicit = setup.extensions.solicit; // Send SETUP and retain its writer for the session's lifetime. Only a failure // ends the session; the other halves report how it closed. let send_setup = SendSetup::new( session.clone(), version, - SetupParams { - extensions: crate::setup::Extensions { - auth: setup.extensions.auth && auth.supported(), - ..setup.extensions - }, - ..setup - }, + setup, self_origin, cost, goaway.clone(), @@ -401,25 +372,8 @@ impl Launch { goaway.going_away.clone(), ) .with_auth(auth.clone()) - .with_solicit(setup.extensions.solicit); + .with_solicit(solicit); - // Our tokens, one Auth request each, once the peer's SETUP negotiates it. - let present = auth::Presenting::new( - runtime.clone(), - session.clone(), - control.clone(), - auth.clone(), - peer_setup.clone(), - version, - stats.clone(), - ); - // Only a side that offered MoQ Auth answers the peer's Auth requests: one that - // arrives otherwise falls through to the protocol violation in `Dispatch`. - let serve = auth.supported().then(|| auth::Serve { - runtime: runtime.clone(), - handle: auth.clone(), - peer_grant, - }); subscriber.announces = announces; // When the peer's SETUP was pre-read (a gated server accept), monitor GOAWAY on @@ -446,14 +400,7 @@ impl Launch { }, ); let publish_namespaces = PublishNamespaces::new(publisher.clone()); - let dispatch = Dispatch::new( - session.clone(), - publisher, - subscriber.clone(), - peer_setup, - serve, - version, - ); + let dispatch = Dispatch::new(session.clone(), publisher, subscriber.clone(), version); // A transport without datagrams never delivers one. let datagrams = (session.max_datagram_size() != 0).then(|| Datagrams { session: session.clone(), @@ -471,7 +418,6 @@ impl Launch { publish_namespaces: Some(publish_namespaces), setup: Some(send_setup), enforce, - present: Some(present), goaway: goaway_recv, datagrams, dispatch: Some(dispatch), @@ -483,7 +429,6 @@ impl Launch { ended: None, auth, auth_close, - setup_token, } } } @@ -495,8 +440,6 @@ struct Running { ended: Option>, auth: crate::auth::Link, auth_close: AuthClose, - /// Held for the life of the session. - setup_token: Option, } impl Running { @@ -506,8 +449,6 @@ impl Running { None => { let res = ready!(self.race.poll(waiter)); close(&mut self.race.session, &res); - // Before the Auth serve tasks drop, so each settles with the session's error - // rather than a bare cancel. self.auth.close(match &res { Ok(()) => Error::Cancel, Err(err) => err.clone(), @@ -538,14 +479,10 @@ impl Running { Poll::Ready(res) } - /// Drop the halves, then release the auth handle and our connection credential. + /// Drop the halves, then release the auth handle. fn finish(self: Box, res: &Result<(), Error>) { let Self { - race, - auth, - auth_close, - setup_token, - .. + race, auth, auth_close, .. } = *self; drop(race); auth.close(match res { @@ -553,7 +490,6 @@ impl Running { Err(err) => err.clone(), }); drop(auth_close); - drop(setup_token); } } @@ -570,7 +506,6 @@ struct Race { setup: Option, /// `None` on a server, which publishes whatever the peer may read. enforce: Option, - present: Option, /// GOAWAY on a pre-read SETUP stream; `None` when `unis` reads the SETUP. goaway: Option>, datagrams: Option, @@ -597,10 +532,6 @@ impl Race { }) { return Poll::Ready(Err(err)); } - // Malformed replies are session-fatal, unlike token refusals. - if let Poll::Ready(err) = poll_failed(&mut self.present, |present| present.poll(waiter)) { - return Poll::Ready(Err(err)); - } if let Poll::Ready(err) = poll_failed(&mut self.enforce, |enforce| enforce.poll(waiter)) { return Poll::Ready(Err(err)); } @@ -842,7 +773,6 @@ pub(crate) fn decode_peer_setup(parameters: &[u8], version: Version, client: boo solicit: solicit::from_setup(¶ms, version)?, hidden: hidden::from_setup(¶ms, version), max_age: max_age::from_setup(¶ms, version), - auth: auth::from_setup(¶ms) == Some(true), active_count: active_count::from_setup(¶ms), flate: super::flate::from_setup(¶ms)?, }, @@ -946,9 +876,6 @@ impl SendSetup { } hidden::into_setup(&mut parameters, version); max_age::into_setup(&mut parameters, version); - if params.extensions.auth { - auth::into_setup(&mut parameters); - } active_count::into_setup(&mut parameters); request_update::into_setup(&mut parameters, version); super::flate::into_setup(&mut parameters); @@ -1443,7 +1370,6 @@ pub(super) fn stop_on_error( struct Dispatch { session: Transport, version: Version, - peer_setup: peer::PeerSetup, state: DispatchState, tasks: TaskSet, fatal: kio::Shared>, @@ -1460,32 +1386,17 @@ enum DispatchState { Setup { publisher: Publisher, subscriber: Subscriber, - /// Answers the peer's Auth requests, on the versions that can negotiate them. - serve: Option, }, /// Accepting requests, each served with what the peer's SETUP negotiated. Accepting(Bidi), } impl Dispatch { - fn new( - session: Transport, - publisher: Publisher, - subscriber: Subscriber, - peer_setup: peer::PeerSetup, - // Answers the peer's Auth requests, on the versions that can negotiate them. - serve: Option, - version: Version, - ) -> Self { + fn new(session: Transport, publisher: Publisher, subscriber: Subscriber, version: Version) -> Self { Self { session, version, - peer_setup, - state: DispatchState::Setup { - publisher, - subscriber, - serve, - }, + state: DispatchState::Setup { publisher, subscriber }, tasks: TaskSet::owned(), fatal: Default::default(), budget: kio::coop::Budget::new(32), @@ -1497,19 +1408,11 @@ impl Dispatch { fn poll(&mut self, waiter: &kio::Waiter) -> Poll { loop { match &self.state { - DispatchState::Setup { - publisher, - subscriber, - serve, - } => { + DispatchState::Setup { publisher, subscriber } => { // PUBLISH_NAMESPACE decodes differently once the MoQ Cluster extension is // negotiated, so dispatch waits for SETUP, which `Unis` reads independently. let peer = ready!(subscriber.poll_peer(waiter)); - // An AUTH without MoQ Auth negotiated, offered by both sides, is an unknown - // request, which falls through to the protocol violation in `BidiServe`. - let negotiated = ready!(self.peer_setup.poll_get(waiter)).auth; - // From the same slot, so this costs nothing extra: it decides whether an // unsolicited advertisement is the peer ignoring our own SETUP (MoQ Solicit). let declared = ready!(subscriber.poll_solicit(waiter)); @@ -1519,7 +1422,6 @@ impl Dispatch { subscriber: subscriber.clone(), peer, declared, - serve: serve.clone().filter(|_| negotiated), version: self.version, }; self.state = DispatchState::Accepting(bidi); @@ -1548,16 +1450,7 @@ impl Dispatch { self.tasks .push(BidiServe::new(bidi.clone(), stream, self.fatal.clone())); } - Poll::Ready(Err(err)) => { - // Each AUTH serve task settles `Issued::closed` from the handle as it - // drops, and the first reason wins: closing it while `tasks` still holds - // them keeps every grant from reporting a bare cancel. The driver closes - // it again with the same error, which then does nothing. - if let Some(serve) = &bidi.serve { - serve.handle.close(err.clone()); - } - return Poll::Ready(err); - } + Poll::Ready(Err(err)) => return Poll::Ready(err), Poll::Pending => { // The children never end the loop; a `Ready` here just means they're // drained until the next stream. @@ -1578,7 +1471,6 @@ struct Bidi { subscriber: Subscriber, peer: cluster::Peer, declared: Option, - serve: Option, version: Version, } @@ -1601,8 +1493,6 @@ enum BidiStep { Refuse(Reject), /// The publisher or subscriber serving it. Serve(crate::util::BoxTask), - /// Answering an Auth request. - Auth(Box), /// Between steps. Done, } @@ -1642,7 +1532,6 @@ impl BidiServe { ready!(task(waiter)); return Poll::Ready(Ok(())); } - BidiStep::Auth(answering) => return answering.poll(waiter), BidiStep::Done => unreachable!("polled after it finished"), } } @@ -1660,7 +1549,6 @@ impl BidiServe { subscriber, peer, declared, - serve, version, } = &mut self.bidi; let version = *version; @@ -1677,11 +1565,10 @@ impl BidiServe { | ietf::TrackStatus::ID | ietf::Publish::ID | ietf::PublishNamespace::ID - | auth::Auth::ID ) { let request_id = RequestId::decode(&mut data.decoder(version), version)?; match publisher.control.accept(request_id) { - Err(Error::GoingAway) => return Ok(BidiStep::Refuse(refuse_going_away(stream, id, version))), + Err(Error::GoingAway) => return Ok(BidiStep::Refuse(refuse_going_away(stream, version))), result => { result?; } @@ -1698,14 +1585,6 @@ impl BidiServe { ietf::Publish::ID | ietf::PublishNamespace::ID => { BidiStep::Serve(subscriber.handle_stream(id, data, stream, *peer, *declared)?) } - auth::Auth::ID if let Some(serve) = serve.take() => { - let mut data = data.decoder(version); - let msg = auth::Auth::decode_msg(&mut data, version)?; - if !data.is_empty() { - return Err(Error::WrongSize); - } - BidiStep::Auth(Box::new(serve.answer(stream, msg, version))) - } _ => { tracing::warn!(id, "unexpected bidi stream type"); return Err(Error::UnexpectedStream); @@ -1743,12 +1622,8 @@ fn poll_header( Poll::Ready(Ok((id, body))) } -/// Refuse a request past our GOAWAY cutoff with the answer its kind reads: an AUTH -/// presenter reads only AUTH_OK and AUTH_ERROR. -fn refuse_going_away(stream: Stream, id: u64, version: Version) -> Reject { - if id == auth::Auth::ID { - return auth::going_away(stream); - } +/// Refuse a request past our GOAWAY cutoff. +fn refuse_going_away(stream: Stream, version: Version) -> Reject { let kind = super::error::request::Kind::Subscribe; Reject::new( stream, @@ -1936,7 +1811,7 @@ mod tests { let scripted = crate::lite::test_transport::ScriptedSession::new(Vec::new()).without_credit(); let log = scripted.log.clone(); let session = crate::driver::Transport::new(scripted.clone()); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session, @@ -1978,294 +1853,6 @@ mod tests { } } - #[kio::test] - async fn auth_ids_need_the_peers_parity() { - for version in [Version::Draft18, Version::Draft20, Version::Draft22] { - for client in [false, true] { - let first = u64::from(client); - for requests in [vec![(true, first ^ 1)], vec![(false, first), (true, (first + 2) ^ 1)]] { - let incoming = requests - .into_iter() - .map(|(is_auth, id)| { - let mut body = Vec::new(); - let mut encoder = crate::coding::Encoder::new(&mut body, version.into()); - let kind = if is_auth { - auth::Auth { - request_id: RequestId(id), - token: Default::default(), - } - .encode_msg(&mut encoder, version) - .unwrap(); - auth::Auth::ID - } else { - ietf::TrackStatus { - authorization_token: None, - request_id: RequestId(id), - track_namespace: crate::Path::from_static("test"), - track_name: "video".into(), - properties_wanted: true, - } - .encode_msg(&mut encoder, version) - .unwrap(); - ietf::TrackStatus::ID - }; - let mut script = Vec::new(); - let mut encoder = crate::coding::Encoder::new(&mut script, version.into()); - encoder.varint(kind).unwrap(); - encoder.u16(body.len() as u16); - script.extend(body); - script - }) - .collect(); - let session = - crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(incoming); - let log = session.log.clone(); - let (driver, _, _) = start(Config { - runtime: crate::time::sim(), - stats: Default::default(), - session: crate::driver::Transport::new(session.clone()), - limits: Default::default(), - client, - publish: None, - subscribe: None, - peer_hop: None, - cost: None, - version, - path: None, - authority: None, - token: None, - peer_setup_stream: None, - peer_declared: Some(peer::Peer { - auth: true, - ..Default::default() - }), - auth: crate::auth::Link::new(true), - early_unis: Vec::new(), - implementation: None, - peer_implementation: Default::default(), - extensions: Default::default(), - }) - .unwrap(); - let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) - .await - .expect("invalid AUTH ID left the session open") - .expect_err("invalid request ID must be fatal"); - assert!( - matches!(err, Error::Session(SessionError::InvalidRequestId)), - "{version:?} client={client}: {err:?}" - ); - assert_eq!(log.closes()[0].0, SessionError::InvalidRequestId.to_code()); - } - } - } - } - - #[kio::test] - async fn malformed_auth_replies_close_the_session() { - for version in [Version::Draft22] { - for (id, body) in [ - (99, vec![]), - (auth::AuthError::ID, vec![0xc0, 0, 0, 1, 0, 0, 0, 0, 0]), - (auth::AuthError::ID, vec![1]), - (auth::AuthError::ID, vec![1, 0, 0]), - (auth::AuthOk::ID, vec![0, 0, 0xc0, 0x20, 0, 0, 0, 0, 0, 0]), - ] { - let mut script = Vec::new(); - let mut encoder = crate::coding::Encoder::new(&mut script, version.into()); - encoder.varint(id).unwrap(); - encoder.u16(body.len() as u16); - script.extend(body); - let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![script]); - let log = session.log.clone(); - let (driver, _, _) = start(Config { - runtime: crate::time::sim(), - stats: Default::default(), - session: crate::driver::Transport::new(session.clone()), - limits: Default::default(), - client: true, - publish: None, - subscribe: None, - peer_hop: None, - cost: None, - version, - path: None, - authority: None, - token: None, - peer_setup_stream: None, - peer_declared: Some(peer::Peer { - auth: true, - ..Default::default() - }), - auth: crate::auth::Link::new(true), - early_unis: Vec::new(), - implementation: None, - peer_implementation: Default::default(), - extensions: Default::default(), - }) - .unwrap(); - let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) - .await - .expect("the session outlived a malformed AUTH reply") - .expect_err("malformed AUTH is fatal"); - assert!(is_protocol_violation(&err), "{err:?}"); - assert_eq!(log.closes()[0].0, SessionError::ProtocolViolation.to_code()); - } - } - } - - /// A granted token whose Auth request the peer resets is presented again on the same - /// session, backing off while each attempt is lost before a reply: at 0s, 1s, and 3s. - #[kio::test] - async fn a_lost_auth_request_is_presented_again() { - let version = Version::Draft18; - let mut grant = Vec::new(); - let mut encoder = crate::coding::Encoder::new(&mut grant, version.into()); - encoder.varint(auth::AuthOk::ID).unwrap(); - encoder.u16(3); - grant.extend([0, 0, 0]); - let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![grant.clone(), grant]); - session.close(crate::lite::test_transport::Close::ResetStream( - crate::ietf::error::to_stream_code(&crate::StreamError::Internal), - )); - let log = session.log.clone(); - let handle = crate::auth::Handle::new(); - let (driver, _, _) = start(Config { - runtime: crate::time::sim(), - stats: Default::default(), - session: crate::driver::Transport::new(session.clone()), - limits: Default::default(), - client: true, - publish: None, - subscribe: None, - peer_hop: None, - cost: None, - version, - path: None, - authority: None, - token: None, - peer_setup_stream: None, - peer_declared: Some(peer::Peer { - auth: true, - ..Default::default() - }), - auth: crate::auth::Link::attach(&handle, true, true).unwrap(), - early_unis: Vec::new(), - implementation: None, - peer_implementation: Default::default(), - extensions: Default::default(), - }) - .unwrap(); - let token = handle.present(bytes::Bytes::from_static(b"token")).unwrap(); - - let res = kio::clock::timeout(std::time::Duration::from_secs(5), driver).await; - assert!(res.is_err(), "the session ended: {res:?}"); - assert_eq!(occurrences(&log, b"token"), 3); - assert!( - futures::FutureExt::now_or_never(token.closed()).is_none(), - "a lost request ended the token" - ); - } - - /// A peer that negotiated MoQ Auth but resets a token's request before any reply gave it - /// nothing: the token fails as unsupported rather than being presented again. - #[kio::test] - async fn an_auth_request_reset_before_its_reply_is_unsupported() { - let version = Version::Draft18; - let mut grant = Vec::new(); - let mut encoder = crate::coding::Encoder::new(&mut grant, version.into()); - encoder.varint(auth::AuthOk::ID).unwrap(); - encoder.u16(3); - grant.extend([0, 0, 0]); - // The setup token is granted; ours is reset before any reply. - let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![grant, Vec::new()]); - session.close(crate::lite::test_transport::Close::ResetStream( - crate::ietf::error::to_stream_code(&crate::StreamError::Internal), - )); - let log = session.log.clone(); - let handle = crate::auth::Handle::new(); - let (driver, _, _) = start(Config { - runtime: crate::time::sim(), - stats: Default::default(), - session: crate::driver::Transport::new(session.clone()), - limits: Default::default(), - client: true, - publish: None, - subscribe: None, - peer_hop: None, - cost: None, - version, - path: None, - authority: None, - token: None, - peer_setup_stream: None, - peer_declared: Some(peer::Peer { - auth: true, - ..Default::default() - }), - auth: crate::auth::Link::attach(&handle, true, true).unwrap(), - early_unis: Vec::new(), - implementation: None, - peer_implementation: Default::default(), - extensions: Default::default(), - }) - .unwrap(); - let token = handle.present(bytes::Bytes::from_static(b"token")).unwrap(); - - let res = kio::clock::timeout(std::time::Duration::from_secs(5), driver).await; - assert!(res.is_err(), "the session ended: {res:?}"); - assert_eq!(occurrences(&log, b"token"), 1, "presented again"); - let err = futures::FutureExt::now_or_never(token.closed()).expect("the token is still open"); - assert!(matches!(err, Error::Unsupported), "{err:?}"); - } - - #[kio::test] - async fn malformed_presenter_auth_closes_the_session() { - for version in [Version::Draft22] { - for body in [vec![0, 2], vec![0, 0, 0]] { - let mut script = Vec::new(); - let mut encoder = crate::coding::Encoder::new(&mut script, version.into()); - encoder.varint(auth::Auth::ID).unwrap(); - encoder.u16(2); - script.extend(body); - let session = - crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(vec![script]); - let log = session.log.clone(); - let (driver, _, _) = start(Config { - runtime: crate::time::sim(), - stats: Default::default(), - session: crate::driver::Transport::new(session.clone()), - limits: Default::default(), - client: false, - publish: None, - subscribe: None, - peer_hop: None, - cost: None, - version, - path: None, - authority: None, - token: None, - peer_setup_stream: None, - peer_declared: Some(peer::Peer { - auth: true, - ..Default::default() - }), - auth: crate::auth::Link::new(true), - early_unis: Vec::new(), - implementation: None, - peer_implementation: Default::default(), - extensions: Default::default(), - }) - .unwrap(); - let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) - .await - .expect("malformed presenter AUTH was ignored") - .expect_err("malformed AUTH is fatal"); - assert!(is_protocol_violation(&err), "{err:?}"); - assert_eq!(log.closes()[0].0, SessionError::ProtocolViolation.to_code()); - } - } - } - #[test] fn object_overflow_is_session_fatal_but_a_stream_error_is_not() { let mut reader = Reader::new( @@ -2334,7 +1921,7 @@ mod tests { let session = crate::lite::test_transport::ScriptedSession::new(namespace_without_hop_path(VERSION).await); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -2400,7 +1987,7 @@ mod tests { let session = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -2494,7 +2081,7 @@ mod tests { let log = session.log.clone(); let session = crate::driver::Transport::new(session); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session, @@ -2653,7 +2240,7 @@ mod tests { let session = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -2728,17 +2315,7 @@ mod tests { ); } - /// The AUTH message type as it leads an Auth request on the draft-18 wire. - fn auth_type() -> Vec { - let mut buf = Vec::new(); - crate::coding::Encoder::new(&mut buf, Version::Draft18.into()) - .varint(auth::Auth::ID) - .unwrap(); - buf - } - - /// A publishing draft-18 session with AUTH available locally, against a peer that - /// declared `auth`. Everything the session needs to keep running is held here. + /// A publishing draft-18 session. Everything it needs to keep running is held here. struct AuthSession { handle: crate::auth::Link, log: crate::lite::test_transport::Log, @@ -2749,7 +2326,7 @@ mod tests { _driver: kio::clock::sim::JoinHandle>, } - fn auth_session(auth: bool) -> AuthSession { + fn auth_session() -> AuthSession { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let cam = origin.announce("solo-cam", crate::origin::RouteInfo::new()).unwrap(); @@ -2757,8 +2334,8 @@ mod tests { let session = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); let log = session.log.clone(); - let handle = crate::auth::Link::ietf(true); - let (driver, goaway, _) = start(Config { + let handle = crate::auth::Link::ietf(); + let (driver, goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -2773,10 +2350,7 @@ mod tests { authority: None, token: None, peer_setup_stream: None, - peer_declared: Some(peer::Peer { - auth, - ..Default::default() - }), + peer_declared: Some(peer::Peer::default()), auth: handle.clone(), early_unis: Vec::new(), implementation: None, @@ -2795,20 +2369,20 @@ mod tests { } } - /// A peer that never offered MoQ Auth sees no Auth request and the session keeps - /// working. A token resolves promptly rather than hanging, kept with an unknown grant - /// for the requests that name it. + /// moq-transport has no AUTH stream, so a token resolves promptly rather than hanging, + /// kept with an unknown grant for the requests that name it, and the session keeps + /// working. #[kio::test] - async fn a_peer_without_auth_sees_no_auth_request() { - let session = auth_session(false); + async fn a_token_is_kept_for_requests() { + let session = auth_session(); let (handle, log) = (&session.handle, &session.log); let auth = kio::clock::timeout(std::time::Duration::from_secs(1), handle.handle().add("token")) .await .expect("resolved promptly") .expect("kept for requests"); - assert_eq!(auth.grant().peek(), None, "no grant without the extension"); - assert_eq!(handle.handle().grant().peek(), None, "no grant without the extension"); + assert_eq!(auth.grant().peek(), None, "no grant without AUTH"); + assert_eq!(handle.handle().grant().peek(), None, "no grant without AUTH"); for _ in 0..ANNOUNCE_TURNS { if occurrences(log, b"solo-cam") > 0 { @@ -2817,39 +2391,20 @@ mod tests { kio::clock::sleep(std::time::Duration::from_millis(1)).await; } assert_eq!(occurrences(log, b"solo-cam"), 1, "the session stopped advertising"); - assert_eq!( - occurrences(log, &auth_type()), - 0, - "sent AUTH to a peer that never offered it" - ); - } - - /// A peer that offered it gets the connection's own credential right away. - #[kio::test] - async fn a_negotiating_peer_gets_the_setup_token() { - let session = auth_session(true); - let log = &session.log; - for _ in 0..ANNOUNCE_TURNS { - if occurrences(log, &auth_type()) > 0 { - break; - } - kio::clock::sleep(std::time::Duration::from_millis(1)).await; - } - assert_eq!(occurrences(log, &auth_type()), 1, "one AUTH for the setup token"); } - /// What the draft-18 SETUP that `start` writes says about MoQ Auth and MoQ Solicit. - async fn our_setup(client: bool, auth: crate::auth::Link, extensions: crate::setup::Extensions) -> (bool, bool) { + /// Whether the draft-18 SETUP that `start` writes offers MoQ Solicit. + async fn our_setup(extensions: crate::setup::Extensions) -> bool { const VERSION: Version = Version::Draft18; let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), limits: Default::default(), - client, + client: true, publish: None, subscribe: None, peer_hop: None, @@ -2860,7 +2415,7 @@ mod tests { token: None, peer_setup_stream: None, peer_declared: Some(peer::Peer::default()), - auth, + auth: crate::auth::Link::ietf(), early_unis: Vec::new(), implementation: None, peer_implementation: Default::default(), @@ -2876,123 +2431,17 @@ mod tests { let writes = log.writes.lock().unwrap().clone(); let (setup, _) = setup::Setup::decode_slice(&writes, crate::Version::Ietf(VERSION)).expect("our SETUP"); let (params, _) = ietf::Parameters::decode_slice(&setup.parameters, VERSION).expect("its options"); - ( - auth::from_setup(¶ms) == Some(true), - solicit::from_setup(¶ms, VERSION).unwrap() == Some(true), - ) + solicit::from_setup(¶ms, VERSION).unwrap() == Some(true) } - /// Each extension reaches our SETUP only while this side offers it. + /// MoQ Solicit reaches our SETUP only while this side offers it. #[kio::test] async fn a_declined_extension_stays_out_of_setup() { let all = crate::setup::Extensions::default(); - let mut no_auth = all; - no_auth.auth = false; let mut no_solicit = all; no_solicit.solicit = false; - - // A client's handle supports AUTH exactly when it offers it. - assert_eq!(our_setup(true, crate::auth::Link::new(true), all).await, (true, true)); - assert_eq!( - our_setup(true, crate::auth::Link::new(false), no_auth).await, - (false, true) - ); - assert_eq!( - our_setup(true, crate::auth::Link::new(true), no_solicit).await, - (true, false) - ); - } - - /// A server's handle supports AUTH only when the client offered it too, so a server - /// answering a client that did not offer it leaves the option out, whatever it offers. - #[kio::test] - async fn a_server_offers_auth_only_to_a_client_that_did() { - let all = crate::setup::Extensions::default(); - assert_eq!(our_setup(false, crate::auth::Link::new(true), all).await, (true, true)); - assert_eq!( - our_setup(false, crate::auth::Link::new(false), all).await, - (false, true) - ); - } - - /// The bytes of a peer's Auth request presenting its connection credential. - async fn auth_request(version: Version) -> Vec { - let log = crate::lite::test_transport::Log::default(); - let mut writer = crate::coding::Writer::new( - crate::transport::boxed::SendStream::new(crate::lite::test_transport::SinkSend::new(log.clone())), - version, - ); - writer - .encode_message(&auth::Auth { - request_id: RequestId(0), - token: bytes::Bytes::new(), - }) - .await - .unwrap(); - let writes = log.writes.lock().unwrap(); - writes.clone() - } - - /// Run a draft-18 server whose client offered MoQ Auth and then sent an Auth request. - /// `offered` is whether the server offered it too. Returns how the session ended, if it - /// did, and what closed it. - async fn serve_auth_request(offered: bool) -> (Option>, Vec<(u32, String)>) { - const VERSION: Version = Version::Draft18; - - let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()) - .with_incoming_bidis(vec![auth_request(VERSION).await]); - let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { - runtime: crate::time::sim(), - stats: Default::default(), - session: crate::driver::Transport::new(session.clone()), - limits: Default::default(), - client: false, - publish: None, - subscribe: None, - peer_hop: None, - cost: None, - version: VERSION, - path: None, - authority: None, - token: None, - peer_setup_stream: None, - peer_declared: Some(peer::Peer { - auth: true, - ..Default::default() - }), - // As `Server` builds it: offered by the client, so supported iff we offer it. - auth: crate::auth::Link::new(offered), - early_unis: Vec::new(), - implementation: None, - peer_implementation: Default::default(), - extensions: crate::setup::Extensions::default(), - }) - .expect("start the session"); - - let res = kio::clock::timeout(std::time::Duration::from_secs(10), driver) - .await - .ok(); - (res, log.closes()) - } - - /// The Auth draft negotiates the extension only when both sides offer it, so an Auth - /// request reaching a side that declined it is a protocol violation, not a token to grant. - #[kio::test] - async fn an_auth_request_to_a_side_that_declined_it_is_refused() { - let (res, closes) = serve_auth_request(true).await; - assert!(res.is_none(), "both offered: the request is served, {res:?}"); - assert_eq!(closes, vec![]); - - let (res, closes) = serve_auth_request(false).await; - let Some(Err(err)) = res else { - panic!("declined: the Auth request did not end the session: {res:?}"); - }; - assert_eq!(SessionError::from(&err), SessionError::ProtocolViolation); - assert_eq!( - closes, - vec![(SessionError::ProtocolViolation.to_code(), err.to_string())] - ); + assert!(our_setup(all).await); + assert!(!our_setup(no_solicit).await); } /// The declared Hop ID must be the caller's own origin, whichever half carries it. @@ -3033,7 +2482,7 @@ mod tests { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -3080,7 +2529,7 @@ mod tests { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -3329,7 +2778,7 @@ mod tests { tasks, Default::default(), ); - let mut dispatch = Dispatch::new(transport, publisher, subscriber, peer_setup, None, VERSION); + let mut dispatch = Dispatch::new(transport, publisher, subscriber, VERSION); // Held open and empty, so each accepted stream waits on its header. let mut opened = Vec::new(); for _ in 0..1024 { @@ -3579,7 +3028,7 @@ mod tests { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(vec![payload]); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -3649,7 +3098,7 @@ mod tests { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(vec![payload]); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -3735,7 +3184,7 @@ mod tests { let log = session.log.clone(); let session = crate::driver::Transport::new(session.clone()); let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session, @@ -3976,7 +3425,7 @@ mod tests { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()) .with_incoming_unis(vec![setup_stream(VERSION, params, &[])]); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -4085,7 +3534,7 @@ mod tests { // The peer FINs each stream after its script, so a message it cuts short is malformed. session.close(crate::lite::test_transport::Close::Fin); let log = session.log.clone(); - let (driver, _goaway, _) = start(Config { + let (driver, _goaway) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -4119,35 +3568,23 @@ mod tests { closes.first().map(|(code, _)| SessionError::from_code(*code)) } - /// A request past our GOAWAY cutoff is refused in the answer its kind reads: an AUTH - /// with AUTH_ERROR carrying GOING_AWAY, since its presenter takes anything else as a - /// violation, and the rest with REQUEST_ERROR, inviting a retry on the next session. + /// A request past our GOAWAY cutoff is refused with REQUEST_ERROR carrying GOING_AWAY, + /// inviting a retry on the next session. #[kio::test] - async fn a_request_past_our_goaway_is_refused_in_its_own_answer() { + async fn a_request_past_our_goaway_is_refused() { const VERSION: Version = Version::Draft18; let reason = b"going away"; - let body = [&[0x6, reason.len() as u8][..], reason].concat(); - for (id, answer) in [ - (auth::Auth::ID, frame(VERSION, auth::AuthError::ID, &body)), - ( - ietf::Subscribe::ID, - // A Retry Interval of 1000ms, as a draft-18 varint. - frame( - VERSION, - ietf::RequestError::ID, - &[&[0x6, 0x83, 0xe8][..], &body[1..]].concat(), - ), - ), - ] { - let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()); - let log = session.log.clone(); - let stream = Stream::open(&crate::driver::Transport::new(session.clone()), VERSION) - .await - .unwrap(); - let mut refusal = refuse_going_away(stream, id, VERSION); - kio::wait(|waiter| refusal.poll(waiter)).await.unwrap(); - assert_eq!(*log.writes.lock().unwrap(), answer, "{id:#x}"); - } + // A Retry Interval of 1000ms, as a draft-18 varint. + let body = [&[0x6, 0x83, 0xe8, reason.len() as u8][..], reason].concat(); + let answer = frame(VERSION, ietf::RequestError::ID, &body); + let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()); + let log = session.log.clone(); + let stream = Stream::open(&crate::driver::Transport::new(session.clone()), VERSION) + .await + .unwrap(); + let mut refusal = refuse_going_away(stream, VERSION); + kio::wait(|waiter| refusal.poll(waiter)).await.unwrap(); + assert_eq!(*log.writes.lock().unwrap(), answer); } /// A malformed request closes the session with the draft's code: a Request ID of the diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index 4f8429c80ff..14b72b907ae 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -1103,7 +1103,7 @@ pub(super) struct Subscriber { // deliberately past draft-22 section 9.2's SHOULD NOT: refusing them would // fail requests that land before the replacement is up. going_away: crate::goaway::GoingAway, - // Our grant (MoQ Auth): a subscription it stops covering is cancelled. + // Our grant: a subscription it stops covering is cancelled. auth: crate::auth::Link, // Namespaces the peer may have announced at once (`session::Limits::announces`), and // tracks it lists to us. @@ -1220,7 +1220,7 @@ impl Subscriber { } } - /// Bound what we subscribe to by the grant this session's tokens earn (MoQ Auth), + /// Bound what we subscribe to by the grant this session's tokens earn, /// and what the peer may publish to us by the session's limit, as either changes. pub fn with_auth(mut self, auth: crate::auth::Link) -> Self { self.auth = auth; @@ -3443,7 +3443,7 @@ struct RunSubscribe { /// Holds the session busy while the request waits on authorization or TRACK_STATUS. /// Past that, only a subscription or a fill counts. setup: Option, - /// Subscribe only to what our grant covers (MoQ Auth), and cancel once it no longer + /// Subscribe only to what our grant covers, and cancel once it no longer /// does, leaving the rest of the session alone. gate: crate::auth::Gate, /// Group FETCHes for cache misses: standalone, so they outlive each subscription. diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 5a92caf7f47..3987dd0ff1f 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -9897,7 +9897,7 @@ mod tests { #[kio::test] #[cfg(feature = "async")] async fn an_auth_swap_is_an_update() { - let handle = crate::auth::Link::ietf(false); + let handle = crate::auth::Link::ietf(); let first = handle.present(bytes::Bytes::from_static(b"first"), false).unwrap(); let second = handle.present(bytes::Bytes::from_static(b"second"), false).unwrap(); let producer = origin(1).produce(); diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index e42d20588cf..aa817efae8f 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -456,9 +456,8 @@ impl Server { peer_implementation: options.implementation.clone(), assigned_hop: crate::Hop::random(), timer: Timer::new(None), - // The client's SETUP already settled whether it offered MoQ Auth, so it is - // negotiated exactly when we offer it too. - auth: crate::auth::Link::ietf(options.declared.auth && self.extensions.auth), + // moq-transport carries no AUTH: a token rides the requests that name it. + auth: crate::auth::Link::ietf(), inner: Some(RequestInner { server: self.clone(), runtime, @@ -899,7 +898,7 @@ impl PausedIetf { // The client's SETUP was read at the pause; hand the stream back // for GOAWAY. A server never advertises a path, hence `None`. - let (protocol, goaway, credential) = ietf::start(ietf::Config { + let (protocol, goaway) = ietf::start(ietf::Config { runtime: runtime.clone(), stats: server.stats.clone(), limits: server.limits, @@ -934,7 +933,7 @@ impl PausedIetf { stats: server.stats.clone(), goaway, auth, - credential, + credential: None, estimate: None, peer_target: None, bandwidth: crate::bandwidth::Allocator::default(), @@ -2296,7 +2295,7 @@ mod tests { token: None, peer_implementation: None, assigned_hop: Hop::random(), - auth: crate::auth::Link::ietf(false), + auth: crate::auth::Link::ietf(), timer: Timer::new(None), inner: Some(RequestInner { server: Server::new().with_publisher(&origin), diff --git a/rs/moq-net/src/session.rs b/rs/moq-net/src/session.rs index 94935f63329..a856f4b6394 100644 --- a/rs/moq-net/src/session.rs +++ b/rs/moq-net/src/session.rs @@ -438,9 +438,8 @@ impl Session { /// The handle passed to [`Client::with_auth`](crate::Client::with_auth), or else one /// this session created for itself, which ends with it. /// - /// On moq-lite-07-wip, and on moq-transport when both sides negotiate the MoQ Auth - /// extension, each side presents its connection's credential right after setup. - /// Older versions, and peers that do not negotiate it, leave the grant `None`. + /// On moq-lite-07-wip each side presents its connection's credential right after setup. + /// Older versions and moq-transport leave the grant `None`. pub fn auth(&self) -> auth::Handle { self.auth.clone() } diff --git a/rs/moq-net/src/setup.rs b/rs/moq-net/src/setup.rs index 2e8294880b6..3e8ad40346a 100644 --- a/rs/moq-net/src/setup.rs +++ b/rs/moq-net/src/setup.rs @@ -74,13 +74,11 @@ pub(crate) fn implementation(value: &str) -> Option { /// The SETUP extensions this side offers. /// /// Turning one off connects as a peer that does not speak that extension. moq-lite carries -/// auth and solicit in its core, so those only change moq-transport sessions. +/// solicit in its core, so that one only changes moq-transport sessions. #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(default, deny_unknown_fields)] #[non_exhaustive] pub struct Extensions { - /// The MoQ Auth extension: tokens presented and granted on their own stream. - pub auth: bool, /// The MoQ Solicit extension: the peer answers our SUBSCRIBE_NAMESPACE rather than /// announcing unasked (moq-transport only). pub solicit: bool, @@ -92,7 +90,6 @@ pub struct Extensions { impl Default for Extensions { fn default() -> Self { Self { - auth: true, solicit: true, ietf: false, } @@ -343,12 +340,6 @@ mod tests { assert_eq!(lite::Auth::decode_slice(&wire, lite::Version::Lite07).unwrap().0, auth); let version = crate::ietf::Version::Draft22; - let auth = crate::ietf::auth::Auth { - request_id: crate::ietf::RequestId(0), - token: Bytes::copy_from_slice(secret.as_bytes()), - }; - let wire = auth.encode_bytes(version).unwrap(); - assert_eq!(crate::ietf::auth::Auth::decode_slice(&wire, version).unwrap().0, auth); let mut params = crate::ietf::Parameters::default(); crate::ietf::token::into_setup(&mut params, &token, version).unwrap(); params.set_bytes( diff --git a/rs/moq-net/tests/integration/auth.rs b/rs/moq-net/tests/integration/auth.rs index 3e12f3569d8..6ea8556d464 100644 --- a/rs/moq-net/tests/integration/auth.rs +++ b/rs/moq-net/tests/integration/auth.rs @@ -1,8 +1,8 @@ #![cfg(feature = "async")] //! In-band AUTH over the in-memory mock transport: both sides learn their grant, -//! tokens union, and a publication outside the grant fails loud. Every case runs on -//! moq-lite-07-wip and on moq-transport with the MoQ Auth extension. +//! tokens union, and a publication outside the grant fails loud, on moq-lite-07-wip. +//! moq-transport carries tokens only on the requests that name them. use crate::support; @@ -31,22 +31,16 @@ const LITE_07: &str = "moq-lite-07-wip"; const LITE_06: &str = "moq-lite-06"; /// The lite Auth Stream's type byte. const AUTH_STREAM: u8 = 0x7; -/// The oldest draft we speak, which negotiates MoQ Auth, and the newest. +/// The oldest draft we speak, and the newest. const MOQT_18: &str = "moq-transport-18"; const MOQT_22: &str = "moq-transport-22"; -/// Run each case on every version that exchanges AUTH. +/// Run each case on the version that exchanges AUTH. macro_rules! cases { ($($case:ident),* $(,)?) => { mod lite_07 { $(#[kio::test] async fn $case() { super::$case(super::LITE_07).await })* } - mod moqt_18 { - $(#[kio::test] async fn $case() { super::$case(super::MOQT_18).await })* - } - mod moqt_22 { - $(#[kio::test] async fn $case() { super::$case(super::MOQT_22).await })* - } }; } @@ -80,26 +74,24 @@ cases!( a_wildcard_grant_is_enforced, ); -/// moq-transport's AUTH_ERROR carries no code that may pass, so only lite retries. #[kio::test] async fn lite_07_presents_a_transiently_refused_token_again() { a_transient_refusal_is_presented_again(LITE_07).await } -/// moq-transport's u16 message size is the one a test can overflow quickly. #[kio::test] -async fn moqt_18_a_grant_too_large_for_one_message_is_unsupported() { - a_grant_too_large_for_one_message_is_unsupported(MOQT_18).await +async fn lite_06_has_no_grant() { + older_versions_have_no_grant(LITE_06).await } #[kio::test] -async fn moqt_22_a_grant_too_large_for_one_message_is_unsupported() { - a_grant_too_large_for_one_message_is_unsupported(MOQT_22).await +async fn moqt_18_has_no_grant() { + older_versions_have_no_grant(MOQT_18).await } #[kio::test] -async fn lite_06_has_no_grant() { - older_versions_have_no_grant(LITE_06).await +async fn moqt_22_has_no_grant() { + older_versions_have_no_grant(MOQT_22).await } /// The control for the lite versions without AUTH: on the same barrier, lite-07 has @@ -246,50 +238,9 @@ async fn moqt_22_dropping_the_old_grant_with_its_renewal_keeps_the_announce() { .expect("timed out"); } -/// A route auth the peer revokes on its AUTH stream is no longer carried, so its request is -/// made again without it, even while another token keeps the session's grant unchanged. -#[kio::test] -async fn moqt_22_a_revoked_route_auth_remakes_its_announce() { - within(async { - let client_origin = produce_origin(2); - let server_origin = produce_origin(1); - let mut extensions = moq_net::setup::Extensions::default(); - extensions.solicit = false; - let mut pair = connect(Options { - version: Some(MOQT_22), - client_publish: Some(client_origin.clone()), - server_subscribe: Some(server_origin.clone()), - server_requests: true, - server_extensions: Some(extensions), - ..Default::default() - }) - .await; - let mut tokens = serve(pair.requests.take().unwrap(), |_| Some(Grant::all())); - let (token, _setup) = tokens.next().await.expect("the setup token"); - assert!(token.is_empty()); - - let first = pair.client.auth().add("first").await.expect("granted"); - let (token, presented) = tokens.next().await.expect("the AUTH stream's token"); - assert_eq!(token, b"first"); - let _route = client_origin - .route("room/x", origin::RouteOptions::default().with_auth(first)) - .unwrap(); - let (token, carried) = tokens.next().await.expect("the announce's token"); - assert_eq!(token, b"first"); - wait_announced(&server_origin.consume(), "room/x", true).await; - - presented.revoke(SessionError::Unauthorized, "revoked"); - carried.closed().await; - wait_announced(&server_origin.consume(), "room/x", true).await; - assert_eq!(pair.client_transport.close_reason(), None); - }) - .await - .expect("timed out"); -} - -/// A pair where the client declines MoQ Auth, so every token the server sees rode a -/// request, and the server declines MoQ Solicit, so the client announces with -/// PUBLISH_NAMESPACE rather than answering a SUBSCRIBE_NAMESPACE. +/// A moq-transport pair: every token the server sees rode a request, and the server +/// declines MoQ Solicit, so the client announces with PUBLISH_NAMESPACE rather than +/// answering a SUBSCRIBE_NAMESPACE. async fn connect_route_auth(version: &'static str) -> (Pair, origin::Producer, origin::Producer) { let client_origin = produce_origin(2); let server_origin = produce_origin(1); @@ -304,18 +255,16 @@ async fn connect_route_auth_on( server_origin: &origin::Producer, client_auth: Option, ) -> Pair { - let declined = |f: fn(&mut moq_net::setup::Extensions)| { - let mut extensions = moq_net::setup::Extensions::default(); - f(&mut extensions); - Some(extensions) - }; connect(Options { version: Some(version), client_publish: Some(client_origin.clone()), server_subscribe: Some(server_origin.clone()), server_requests: true, - client_extensions: declined(|e| e.auth = false), - server_extensions: declined(|e| e.solicit = false), + server_extensions: Some({ + let mut extensions = moq_net::setup::Extensions::default(); + extensions.solicit = false; + extensions + }), client_auth, ..Default::default() }) @@ -459,8 +408,7 @@ struct Options { server_subscribe: Option, /// Take the server's AUTH requests before its driver runs. server_requests: bool, - /// Each side's extensions, when not the defaults. - client_extensions: Option, + /// The server's extensions, when not the defaults. server_extensions: Option, version: Option<&'static str>, /// The connection credential the client's SETUP presents. @@ -496,9 +444,6 @@ async fn connect(opts: Options) -> Pair { value: token.to_vec(), }); } - if let Some(extensions) = opts.client_extensions { - client = client.with_extensions(extensions); - } if let Some(publish) = &opts.client_publish { client = client.with_publisher(publish); } @@ -1192,9 +1137,8 @@ async fn an_issued_grant_ends_with_its_session(version: &'static str) { .expect("timed out"); } -/// A peer that takes no tokens in band says so (lite resets the stream, moq-transport -/// answers NOT_SUPPORTED), which reads as unsupported rather than a refusal: the same as -/// a peer that predates AUTH. +/// A peer that takes no tokens in band says so by resetting the stream, which reads as +/// unsupported rather than a refusal: the same as a peer that predates AUTH. async fn a_reset_auth_stream_reports_unsupported(version: &'static str) { within(async { let pair = connect(Options { @@ -1458,22 +1402,17 @@ async fn a_revoked_grant_cancels_its_subscriptions(version: &'static str) { } }; // The relay's own reader learns the peer's code across the origin's splice, not a - // generic drop. moq-transport reports it in PUBLISH_DONE instead. - if version == LITE_07 { - assert!(matches!(err, Error::Stream(StreamError::Unauthorized)), "{err:?}"); - } + // generic drop. + assert!(matches!(err, Error::Stream(StreamError::Unauthorized)), "{err:?}"); assert_eq!(pair.client_transport.close_reason(), None); - // Neither stream claims the session closed. moq-lite resets both with UNAUTHORIZED; - // moq-transport has no such stream code and reports it on the request instead. + // Neither stream claims the session closed: both reset with UNAUTHORIZED. let resets = pair.client_transport.resets(); let closed = StreamError::Session(SessionError::Unauthorized).to_code(); assert!(!resets.contains(&closed), "{resets:x?}"); - if version == LITE_07 { - let unauthorized = StreamError::Unauthorized.to_code(); - let count = resets.iter().filter(|&&code| code == unauthorized).count(); - assert_eq!(count, 2, "both subscriptions reset with UNAUTHORIZED: {resets:x?}"); - } + let unauthorized = StreamError::Unauthorized.to_code(); + let count = resets.iter().filter(|&&code| code == unauthorized).count(); + assert_eq!(count, 2, "both subscriptions reset with UNAUTHORIZED: {resets:x?}"); }) .await .expect("timed out"); @@ -1555,40 +1494,6 @@ async fn lite_07_a_revoked_grant_cancels_its_datagram_subscriptions() { /// A grant that fits no single AUTH_OK is withheld, never trimmed: the presenter is told /// it is unsupported, nothing of the message reaches the wire, and the session and the /// token that did fit are untouched. -async fn a_grant_too_large_for_one_message_is_unsupported(version: &'static str) { - // Past the u16 message size. The moq-lite ceiling is 64 MiB, too slow to build here; - // `lite::auth` tests it on the encoder. - let (count, len) = (20, 4_000); - within(async { - let mut pair = connect(Options { - version: Some(version), - client_publish: Some(produce_origin(2)), - server_subscribe: Some(produce_origin(1)), - server_requests: true, - ..Default::default() - }) - .await; - let huge: Patterns = (0..count) - .map(|i| Pattern::subtree(&format!("{i}{}", "x".repeat(len))).unwrap()) - .collect(); - let mut issued = serve(pair.requests.take().unwrap(), move |token| match token { - b"" => Some(grant(&["a"], &[])), - b"huge" => Some(grant_of(huge.clone(), Patterns::new())), - _ => None, - }); - let (_, _setup) = issued.next().await.unwrap(); - assert_eq!(granted(&pair.client).await, grant(&["a"], &[])); - - let err = pair.client.auth().add("huge").await.expect_err("too large"); - assert!(matches!(err, Error::Unsupported), "{err:?}"); - // No AUTH_OK for it reached the wire: the union is still just the setup grant. - assert_eq!(pair.client.auth().grant().peek(), Some(grant(&["a"], &[]))); - assert_eq!(pair.client_transport.close_reason(), None); - }) - .await - .expect("timed out"); -} - async fn a_grant_update_too_large_for_one_message_is_unsupported(version: &'static str) { within(async { let mut pair = connect(Options { @@ -1828,7 +1733,7 @@ async fn lite_07_narrowing_resets_a_fetch_in_flight() { /// Whether `version` exchanges AUTH, so the peer also hears of a narrowing. fn speaks_auth(version: &str) -> bool { - matches!(version, LITE_07 | MOQT_18 | MOQT_22) + version == LITE_07 } /// A revocation as the reader sees it: the local gate's own error, or the peer's diff --git a/rs/moq-net/tests/integration/extensions.rs b/rs/moq-net/tests/integration/extensions.rs index b14b1e010da..9ebedcae41a 100644 --- a/rs/moq-net/tests/integration/extensions.rs +++ b/rs/moq-net/tests/integration/extensions.rs @@ -18,9 +18,6 @@ const SETTLE: Duration = Duration::from_secs(1); /// Every moq-transport draft, each of which carries the SOLICIT option. const MOQT: [&str; 2] = ["moq-transport-18", "moq-transport-22"]; -/// The oldest draft we speak, which negotiates MoQ Auth, and the newest. -const AUTH: [&str; 2] = ["moq-transport-18", "moq-transport-22"]; - fn produce_origin(hop: u64) -> origin::Producer { let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); @@ -103,49 +100,3 @@ async fn a_side_that_declines_solicit_takes_unsolicited_announces() { } } } - -/// A side that declines MoQ Auth leaves it un-negotiated whichever side declines: -/// neither side holds a grant, and a token is kept for the requests that name it -/// rather than presented on an AUTH stream. -#[kio::test] -async fn a_declined_auth_extension_is_not_negotiated() { - for name in AUTH { - let version: Version = name.parse().unwrap(); - - // Control: offered by both, the client's connection credential earns a grant. - let pair = connect_mock(MockConnectOptions::new(version)).await; - let mut grant = pair.client.auth().grant(); - kio::clock::timeout(SETTLE, async { - while grant.peek().is_none() { - grant.changed().await.expect("grant watch ended"); - } - }) - .await - .unwrap_or_else(|_| panic!("{name}: no grant with both offering")); - - for server_declines in [true, false] { - let context = format!("{name}, server declines: {server_declines}"); - let no_auth = declined(|e| e.auth = false); - let mut options = MockConnectOptions::new(version); - match server_declines { - true => options.server_extensions = no_auth, - false => options.client_extensions = no_auth, - } - let pair = connect_mock(options).await; - kio::clock::sleep(SETTLE).await; - - for session in [&pair.client, &pair.server] { - assert_eq!(session.auth().grant().peek(), None, "{context}"); - // Only a request that names it can carry the token, so it resolves at once with - // a grant that stays unknown. - let added = kio::clock::timeout(SETTLE, session.auth().add("token")) - .await - .unwrap_or_else(|_| panic!("{context}: add never resolved")) - .unwrap_or_else(|err| panic!("{context}: {err:?}")); - assert_eq!(added.grant().peek(), None, "{context}"); - assert_eq!(session.auth().grant().peek(), None, "{context}"); - } - assert_open(&pair, &context); - } - } -} diff --git a/rs/moq-net/tests/integration/stream_credit.rs b/rs/moq-net/tests/integration/stream_credit.rs index e6ca9433073..88990310d6e 100644 --- a/rs/moq-net/tests/integration/stream_credit.rs +++ b/rs/moq-net/tests/integration/stream_credit.rs @@ -149,8 +149,9 @@ async fn a_newer_group_resets_an_unfinished_older_one() { #[kio::test] async fn a_subscription_past_the_credit_is_served_once_credit_returns() { // lite-07 needs 4: session-long AUTH and ANNOUNCE plus TRACK held until SUBSCRIBE answers. - // Three is below the setup minimum; the second subscription waits for the first's credit. - for (version, credit) in [("moq-lite-07-wip", 4), ("moq-transport-22", 3)] { + // moq-transport needs 2: SUBSCRIBE_NAMESPACE and the first SUBSCRIBE. The second + // subscription waits for the first's credit. + for (version, credit) in [("moq-lite-07-wip", 4), ("moq-transport-22", 2)] { let version: Version = version.parse().unwrap(); let publisher = origin(1); let viewer = origin(2); diff --git a/rs/moq-relay/src/config.rs b/rs/moq-relay/src/config.rs index 0f409a88586..126f886183f 100644 --- a/rs/moq-relay/src/config.rs +++ b/rs/moq-relay/src/config.rs @@ -493,14 +493,14 @@ mod tests { let path = dir.path().join("relay.toml"); std::fs::write( &path, - "[listen.extensions]\nauth = false\n\n[connect.extensions]\nsolicit = false\n", + "[listen.extensions]\nietf = true\n\n[connect.extensions]\nsolicit = false\n", ) .unwrap(); let config = Config::parse_and_merge([std::ffi::OsString::from("moq-relay"), path.into()]).unwrap(); - assert!(!config.listen.extensions.auth); + assert!(config.listen.extensions.ietf); assert!(config.listen.extensions.solicit); assert!(!config.connect.extensions.solicit); - assert!(config.connect.extensions.auth); + assert!(!config.connect.extensions.ietf); } #[cfg(feature = "stun")] diff --git a/rs/moq-relay/tests/integration/auth_lifetime.rs b/rs/moq-relay/tests/integration/auth_lifetime.rs index a02653d5758..979d7f6201a 100644 --- a/rs/moq-relay/tests/integration/auth_lifetime.rs +++ b/rs/moq-relay/tests/integration/auth_lifetime.rs @@ -261,7 +261,15 @@ async fn spawn_ws_relay_with( let mut web_config = web::Config::default(); web_config.ws = true; web_config.http.listen = Some("127.0.0.1:0".parse().expect("parse listen")); + // Opt in to lite-07 beside the defaults, as `spawn_relay_config` does. + let mut listen = moq_tokio::listen::Config::default(); + listen.version = moq_net::Versions::all() + .iter() + .copied() + .chain(["moq-lite-07-wip".parse().unwrap()]) + .collect(); let web = web::Web::new(auth, cluster, crate::certificates(), web_config) + .with_listen(&listen) .bind() .expect("bind web listener"); let port = web.addrs().http.expect("HTTP listener is configured").port(); @@ -1889,7 +1897,8 @@ async fn quic_and_webtransport_report_distinct_auth_transports() { } /// A token can reach a prefix outside the initial credential, and withdrawing it -/// revokes only the streams that depended on it on both native and upgraded WS. +/// revokes only the streams that depended on it on both native and upgraded WS. Only +/// lite-07 carries a token in band. #[cfg(feature = "websocket")] #[tokio::test] async fn in_band_tokens_widen_and_withdraw_live_prefixes() { @@ -1905,7 +1914,7 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { }; let client = || { let mut config = moq_tokio::connect::Config::default(); - config.version = vec!["moq-transport-22".parse().unwrap()]; + config.version = vec!["moq-lite-07-wip".parse().unwrap()]; #[cfg(feature = "websocket")] { config.websocket.delay = Some((Duration::ZERO).into()); @@ -2013,7 +2022,6 @@ async fn request_token_lease_ends_before_the_connection_and_reopens_later() { let (port, relay) = spawn_relay_config(build_auth(script.spawn().await), cluster, server).await; let mut config = moq_tokio::connect::Config::default(); config.version = vec!["moq-transport-22".parse().unwrap()]; - config.extensions.auth = false; config.extensions.solicit = false; let client = config.init(Default::default()).unwrap().with_reconnect(false); let origin = moq_tokio::origin::spawn(); diff --git a/rs/moq-relay/tests/integration/runtime_uring.rs b/rs/moq-relay/tests/integration/runtime_uring.rs index d908ed64694..90ce1571cb3 100644 --- a/rs/moq-relay/tests/integration/runtime_uring.rs +++ b/rs/moq-relay/tests/integration/runtime_uring.rs @@ -1080,71 +1080,6 @@ async fn uring_auth_reports_distinct_quic_and_webtransport() { let _ = running.await; } -/// `listen.extensions` reaches the workers' SETUP, as it does the tokio listener's. -/// A moq-transport client's connection token reaches the decider while the relay -/// offers MoQ Auth, and is refused as unsupported once it is turned off, since no -/// request would carry it. -#[tokio::test] -async fn uring_workers_offer_the_configured_extensions() { - let _ = rind_rustls::default_provider().unwrap().install_default(); - if !supported() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let (cert, key) = certificate(dir.path()); - let all: moq_auth::Patterns = [moq_auth::Pattern::all()].into_iter().collect(); - let grant = || moq_auth::lease::Consumer::fixed(moq_auth::Grant::new(all.clone(), all.clone())); - for offered in [true, false] { - let mut config = uring_config(&cert, &key); - config.auth.public.clear(); - config.listen.extensions.auth = offered; - let mut relay = Relay::load(config).await.unwrap().with_signals(false); - let port = relay.addr().unwrap().port(); - let mut admissions = relay.admissions().expect("embedded auth"); - let ready = relay.ready(); - let running = tokio::spawn(relay.run()); - ready.wait().await.expect("relay ready"); - - let mut dial = moq_tokio::connect::Config::default(); - dial.tls.insecure = Some(true); - dial.bind = Some("127.0.0.1:0".parse().unwrap()); - dial.version = vec!["moq-transport-22".parse().unwrap()]; - let client = dial.init(Default::default()).unwrap(); - let url = format!("moql://127.0.0.1:{port}/extensions").parse().unwrap(); - let (connection, ()) = tokio::join!(connect(client, url), async { - let admission = kio::clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); - assert!(!admission.attached(), "offered {offered}: the session arrived attached"); - admission.grant(grant()); - }); - - let auth = connection.auth(); - let presented = kio::clock::timeout(TIMEOUT, auth.add("token")); - match offered { - true => { - let (token, ()) = tokio::join!(presented, async { - let admission = kio::clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); - assert!(admission.attached(), "an AUTH token arrived as a new session"); - admission.grant(grant()); - }); - let _ = token - .expect("the token was never answered") - .expect("the token was refused"); - } - false => { - // Without MoQ Auth no AUTH stream carries it: only a request naming it does. - let _ = presented - .await - .expect("the token was never answered") - .expect("a moq-transport request can carry the token"); - } - } - - drop(connection); - running.abort(); - let _ = running.await; - } -} - /// `listen.timeout` bounds every handshake phase from the first packet: TLS, /// HTTP/3 before CONNECT, and MoQ SETUP over raw QUIC and WebTransport. Each /// phase closes in its own error space. diff --git a/rs/moq-tokio/src/connect.rs b/rs/moq-tokio/src/connect.rs index fac49466f21..f073118efd2 100644 --- a/rs/moq-tokio/src/connect.rs +++ b/rs/moq-tokio/src/connect.rs @@ -377,7 +377,7 @@ mod tests { fn extensions_default_on_and_parse_off() { let config: Config = toml::from_str("[extensions]\nsolicit = false\n").expect("parse"); assert!(!config.extensions.solicit); - assert!(config.extensions.auth); + assert!(!config.extensions.ietf); assert!(toml::to_string(&config).expect("serialize").contains("solicit = false")); assert!( !toml::to_string(&Config::default()) diff --git a/rs/moq-tokio/src/listen.rs b/rs/moq-tokio/src/listen.rs index e958c3c7201..d5caa4de969 100644 --- a/rs/moq-tokio/src/listen.rs +++ b/rs/moq-tokio/src/listen.rs @@ -610,10 +610,10 @@ mod tests { /// default out when serialized. #[test] fn extensions_default_on_and_parse_off() { - let config: Config = toml::from_str("[extensions]\nauth = false\n").expect("parse"); - assert!(!config.extensions.auth); - assert!(config.extensions.solicit); - assert!(toml::to_string(&config).expect("serialize").contains("auth = false")); + let config: Config = toml::from_str("[extensions]\nsolicit = false\n").expect("parse"); + assert!(!config.extensions.solicit); + assert!(!config.extensions.ietf); + assert!(toml::to_string(&config).expect("serialize").contains("solicit = false")); assert!( !toml::to_string(&Config::default()) .expect("serialize") diff --git a/rs/moq-tokio/tests/integration/tokens.rs b/rs/moq-tokio/tests/integration/tokens.rs index 81f0654e092..7807d310653 100644 --- a/rs/moq-tokio/tests/integration/tokens.rs +++ b/rs/moq-tokio/tests/integration/tokens.rs @@ -159,9 +159,7 @@ async fn an_unchanged_refused_credential_is_terminal() { #[tokio::test] async fn an_unchanged_refused_credential_without_auth_is_terminal() { refused_credential_is_terminal(config("moq-lite-05", &["old"])).await; - let mut config = config("moq-transport-22", &["old"]); - config.extensions.auth = false; - refused_credential_is_terminal(config).await; + refused_credential_is_terminal(config("moq-transport-22", &["old"])).await; } async fn refused_credential_is_terminal(config: moq_tokio::connect::Config) { diff --git a/swift/Sources/Moq/Auth.swift b/swift/Sources/Moq/Auth.swift index ceacf548fe6..40ace56ddfa 100644 --- a/swift/Sources/Moq/Auth.swift +++ b/swift/Sources/Moq/Auth.swift @@ -10,9 +10,8 @@ public typealias Grant = MoqFFI.MoqGrant /// `for try await grant in session.grants() { ... }` yields the current grant, /// then each change, `nil` while there is none. /// -/// Returned by `Session.grants()`. AUTH is only on `moq-lite-07-wip` and on -/// moq-transport sessions that negotiate the MoQ Auth extension; elsewhere the -/// grant stays `nil`. The sequence ends when the session does; cancelling the +/// Returned by `Session.grants()`. AUTH is only on `moq-lite-07-wip`; elsewhere +/// the grant stays `nil`. The sequence ends when the session does; cancelling the /// consuming task cancels the consumer. public final class GrantConsumer: AsyncSequence, Sendable { /// The grant emitted by this sequence, `nil` while there is none. diff --git a/test/interop/README.md b/test/interop/README.md index c002e6f015c..61e3b33d704 100644 --- a/test/interop/README.md +++ b/test/interop/README.md @@ -292,10 +292,8 @@ Some cases change shape on moq-transport: so a tail reader started before the publisher's groups may begin past group 0. The tails take any contiguous run of groups through group 3, each verified byte for byte, and still require the clean end at 4. -- The AUTH extension carries prefixes alone, and a relay refuses a - grant narrower than a subtree, closing the session as Unauthorized. Pinned - passes mint `name/**` for both roles instead of the exact and `**/name` - patterns above. +- Requests name prefixes alone, so pinned passes mint `name/**` for both roles + instead of the exact and `**/name` patterns above. The browser pins through the `versions` attribute on `` and ``, and GStreamer through the `versions` property on `moqsrc`. diff --git a/test/interop/clients/js-native/control.ts b/test/interop/clients/js-native/control.ts index 96338699e96..d4e31ce7578 100644 --- a/test/interop/clients/js-native/control.ts +++ b/test/interop/clients/js-native/control.ts @@ -20,7 +20,7 @@ const quic = new Qmux(new URL(address), { requireProtocol: true, }); await quic.ready; -const extensions = offered({ auth: false, solicit: false }); +const extensions = offered({ solicit: false }); await exchangeSetup(quic, version, "interop-control", { client: true, extensions }); const session = new NativeSession(quic, version, true); diff --git a/test/interop/clients/js-native/ranges.ts b/test/interop/clients/js-native/ranges.ts index 8b7363f3572..ef354880fde 100644 --- a/test/interop/clients/js-native/ranges.ts +++ b/test/interop/clients/js-native/ranges.ts @@ -26,7 +26,7 @@ async function connect() { await transport.ready; // Moxygen's pinned HTTP/3 server predates subprotocol negotiation. This fixture's // server offers draft 18 alone, so exchange that SETUP directly on its WebTransport. - const extensions = offered({ auth: false, solicit: false }); + const extensions = offered({ solicit: false }); const setup = await exchangeSetup(transport, Version.DRAFT_18, "interop-ranges", { client: true, extensions }); return new Connection({ url, quic: transport, version: Version.DRAFT_18, client: true, extensions, ...setup }); } diff --git a/test/interop/interop.sh b/test/interop/interop.sh index 4882b09e785..1d961072fa9 100755 --- a/test/interop/interop.sh +++ b/test/interop/interop.sh @@ -1046,9 +1046,9 @@ rust_connect() { } # The pattern a cell's token grants its publisher, or its subscribers, on . The `auto` -# pass mints patterns no prefix could carry, so AUTH must deliver them as minted. moq-transport's -# AUTH extension carries prefixes alone and refuses a narrower grant, closing the -# session, so a pinned pass grants the broadcast's subtree. +# pass mints patterns no prefix could carry, so AUTH must deliver them as minted. A pinned +# pass may be moq-transport, whose requests name prefixes alone, so it grants the +# broadcast's subtree. publish_grant() { if [[ "$VERSION" == auto ]]; then printf '%s' "$1"; else printf '%s/**' "$1"; fi } @@ -1604,6 +1604,11 @@ run_round() { sub_url=$(token_url --subscribe "$(subscribe_grant "$broadcast")") sub_grant=$(grant_line "" "**/$broadcast") for sub in "${SUB_LIST[@]}"; do + if [[ "$case" == media && "$publisher" == python && "$sub" == go ]]; then + echo " SKIP $pub -> $sub (quarantined)" + record skip case="$case" publisher="$publisher" subscriber="$sub" detail="quarantined: quest/m0/test-flakes-2/interop-python-go.md" + continue + fi if is_broken "$sub"; then echo " FAIL $pub -> $sub (subscriber client unavailable)" record fail case="$case" publisher="$publisher" subscriber="$sub" detail="subscriber client unavailable" @@ -1813,7 +1818,7 @@ run_finishes() { for pub in "${PUB_LIST[@]}"; do name="finish-$pub" # The fixture and its .health sibling share a parent, so one prefix grant covers both: - # moq-transport's AUTH extension carries prefixes alone. + # moq-transport requests name prefixes alone. broadcast="$name-$$-$RANDOM/fixture.hang" grant="${broadcast%/*}/**" ack="$LOGS/$name-ack" @@ -2537,7 +2542,7 @@ run_catalog_fanout() { exec 9<>"$fifo" from=$(relay_next_line) before=$(relay_inflated) || why="relay metrics unavailable" - # Subtree grants, which moq-transport's AUTH extension can carry too. + # Subtree grants, which a moq-transport request can name too. harness_spawn "$name-pub" "$LOGS/$name-pub.log" run_catalog_publisher "$fifo" "$(token_url --publish "$broadcast/**")" "$broadcast" pid="$HARNESS_PID" for version in "${CATALOG_VERSIONS[@]}"; do