diff --git a/cpp/obs/src/moq-dock.cpp b/cpp/obs/src/moq-dock.cpp index b3b7e428565..1fa0c448d2c 100644 --- a/cpp/obs/src/moq-dock.cpp +++ b/cpp/obs/src/moq-dock.cpp @@ -728,30 +728,6 @@ void MoQDock::PeelJwtFromRelayUrl() urlEdit->setText(url.toString()); } -QString MoQDock::ConnectUrl() const -{ - QString text = urlEdit->text().trimmed(); - const QString token = tokenEdit->text().trimmed(); - if (token.isEmpty()) - return text; - - QUrl url(text); - if (!url.isValid() || url.scheme().isEmpty()) { - // Cannot confirm the transport is encrypted, so do not attach the token. - return text; - } - - // Never put a JWT on cleartext network dial URLs. - if (MoQDial::IsCleartext(url.scheme().toStdString())) - return text; - - QUrlQuery query(url); - query.removeAllQueryItems("jwt"); - query.addQueryItem("jwt", token); - url.setQuery(query); - return url.toString(); -} - void MoQDock::OnEncodingChanged(int mode) { const bool enabled = mode == 1; @@ -1098,7 +1074,7 @@ void MoQDock::StartStream() } } - const std::string url = ConnectUrl().toStdString(); + const std::string url = relayText.toStdString(); const std::string path = pathEdit->text().toStdString(); tokenEdited = false; tokenNotice.clear(); @@ -1113,6 +1089,7 @@ void MoQDock::StartStream() obs_data_apply(serviceSettings, advanced); obs_data_set_string(serviceSettings, "server", url.c_str()); obs_data_set_string(serviceSettings, "key", path.c_str()); + obs_data_set_string(serviceSettings, "bearer_token", token.toStdString().c_str()); service = OBSServiceAutoRelease(obs_service_create("moq_service", "moq_dock_service", serviceSettings, nullptr)); if (!service) { diff --git a/cpp/obs/src/moq-dock.h b/cpp/obs/src/moq-dock.h index 3beb13300fa..72f48bd5a4d 100644 --- a/cpp/obs/src/moq-dock.h +++ b/cpp/obs/src/moq-dock.h @@ -46,7 +46,6 @@ private slots: bool CreateConfiguredEncoders(); bool CreateCustomEncoders(); void CreateVideoEncoder(const char *id, obs_data_t *settings); - QString ConnectUrl() const; void PeelJwtFromRelayUrl(); void ClearLiveStats(); diff --git a/cpp/obs/src/moq-output.cpp b/cpp/obs/src/moq-output.cpp index e3b06aca6a9..f39c990d3ac 100644 --- a/cpp/obs/src/moq-output.cpp +++ b/cpp/obs/src/moq-output.cpp @@ -188,6 +188,11 @@ bool MoQOutput::Start() moq::ClientConfig config; config.publish = next_origin; config.implementation = MoQImplementation(); + // Not on the URL: a URL's ?jwt= overrides the client's tokens, so every reconnect + // would dial it instead of the one PresentToken() set last. + if (const char *token = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_BEARER_TOKEN); + token && *token) + config.tokens = {token}; OBSDataAutoRelease service_settings = obs_service_get_settings(service); std::string invalid = MoQSettings::Configure(service_settings, config); std::shared_ptr client; @@ -528,31 +533,36 @@ bool MoQOutput::PresentToken(const std::string &token) std::lock_guard signal_lock(signal_mutex); if (!attempt || !attempt->session) return false; + // Only a server-accepted session has no tokens. + std::shared_ptr tokens = attempt->session->tokens(); + if (!tokens) + return false; + + auto refused = [this](const std::string &reason) { + LOG_WARNING("MoQ relay refused the new publish token: %s", reason.c_str()); + std::lock_guard lock(mutex); + token_refusal = reason; + }; { std::lock_guard lock(mutex); token_refusal.clear(); } - - // Replacing `presenting` cancels a presentation still in flight, which the - // newer token supersedes. - attempt->presenting = attempt->session->auth()->add(token).then( - worker.Executor(), Current>>( - attempt, [this](const std::shared_ptr ¤t, auto result) { - if (!result) { - const std::string reason = result.error().to_string(); - LOG_WARNING("MoQ relay refused the new publish token: %s", - reason.c_str()); - std::lock_guard lock(mutex); - token_refusal = reason; - return; - } - // The old token's grant leaves the union only after the new one joined. - if (current->token) - current->token->cancel(); - current->token = *result; - LOG_INFO("MoQ relay accepted the new publish token: %s", - MoQRedactUrl(current->url).c_str()); - })); + if (auto set = tokens->set({token}); !set) { + attempt->presenting.reset(); + refused(set.error().to_string()); + return true; + } + + // Replacing `presenting` drops the wait on a token this one replaced. + attempt->presenting = tokens->answered().then( + worker.Executor(), + Current>(attempt, [refused](const std::shared_ptr ¤t, auto result) { + if (!result) { + refused(result.error().to_string()); + return; + } + LOG_INFO("MoQ relay accepted the new publish token: %s", MoQRedactUrl(current->url).c_str()); + })); return true; } diff --git a/cpp/obs/src/moq-output.h b/cpp/obs/src/moq-output.h index 036a7d580bb..a54c6559ae3 100644 --- a/cpp/obs/src/moq-output.h +++ b/cpp/obs/src/moq-output.h @@ -76,10 +76,10 @@ class MoQOutput { }; bool TryGetVideoRate(VideoRate *out); - // Present a fresh publish token on the connected session without reconnecting, - // replacing the one presented here before once the relay accepts it. False when - // there is no session yet. The outcome is logged, and a refusal is kept for - // TokenRefusal(); a session without in-band AUTH refuses it. + // Replace the session's tokens with a fresh publish token, presented without + // reconnecting and on every reconnect; the one it replaces is withdrawn once the + // relay answers. False when there is no session yet. The answer is logged, and a + // refusal is kept for TokenRefusal(); a session without in-band AUTH refuses it. bool PresentToken(const std::string &token); // Why the relay refused the token PresentToken() last presented, or empty. std::string TokenRefusal(); @@ -104,10 +104,7 @@ class MoQOutput { bool connected = false; // False while the session is between reconnects. bool live = false; - // The latest token PresentToken() got accepted, presented on every reconnect - // until it is replaced or the attempt is dropped, and the call presenting the - // next one. - std::shared_ptr token; + // The wait for the relay's answer to the token PresentToken() set last. std::optional presenting; }; diff --git a/cpp/obs/src/moq-service.cpp b/cpp/obs/src/moq-service.cpp index 0d7942b0132..1998d804b21 100644 --- a/cpp/obs/src/moq-service.cpp +++ b/cpp/obs/src/moq-service.cpp @@ -6,7 +6,7 @@ const char *audio_codecs[] = {"aac", "opus", nullptr}; const char *video_codecs[] = {"h264", "hevc", "av1", nullptr}; -MoQService::MoQService(obs_data_t *settings, obs_service_t *) : server(), path() +MoQService::MoQService(obs_data_t *settings, obs_service_t *) : server(), path(), token() { Update(settings); } @@ -15,6 +15,7 @@ void MoQService::Update(obs_data_t *settings) { server = obs_data_get_string(settings, "server"); path = obs_data_get_string(settings, "key"); + token = obs_data_get_string(settings, "bearer_token"); } obs_properties_t *MoQService::Properties() @@ -58,6 +59,8 @@ const char *MoQService::GetConnectInfo(enum obs_service_connect_info type) return server.c_str(); case OBS_SERVICE_CONNECT_INFO_STREAM_KEY: return path.c_str(); + case OBS_SERVICE_CONNECT_INFO_BEARER_TOKEN: + return token.empty() ? nullptr : token.c_str(); default: return nullptr; } diff --git a/cpp/obs/src/moq-service.h b/cpp/obs/src/moq-service.h index 7d6138b9ccc..57e0c3362ee 100644 --- a/cpp/obs/src/moq-service.h +++ b/cpp/obs/src/moq-service.h @@ -7,6 +7,8 @@ struct MoQService { // TODO: Define needed params to connect to a relay std::string server; std::string path; + // The dock's publish token, which the output presents through the client's tokens. + std::string token; MoQService(obs_data_t *settings, obs_service_t *service); diff --git a/cpp/obs/test/moq-output-test.cpp b/cpp/obs/test/moq-output-test.cpp index 5e6800632d0..7ffc9819f28 100644 --- a/cpp/obs/test/moq-output-test.cpp +++ b/cpp/obs/test/moq-output-test.cpp @@ -873,8 +873,8 @@ int main() } printf("OBS-driven restart: ok\n"); - // A token edited mid-stream goes to the live session only, and presenting a - // newer one or stopping cancels whatever is still in flight. + // A token edited mid-stream replaces the session's tokens, and presenting a + // newer one or stopping drops the wait on the relay's answer still in flight. { TestRelay relay; reset(relay.Url()); diff --git a/dart/moq/MIGRATE.md b/dart/moq/MIGRATE.md index 19e56003949..30b8f73849f 100644 --- a/dart/moq/MIGRATE.md +++ b/dart/moq/MIGRATE.md @@ -38,7 +38,7 @@ the matching generated bindings and native library. ### Cancelling a stream cancels its pending read `await subscription.cancel()` on announcements, authorization grants, and server requests now waits for the pending native operation to release, even when no event arrives. -Announcement subscriptions still own and release their cursor; cancelling a grant or request subscription keeps its shared `Auth` or `Server` usable. +Announcement and grant subscriptions own and release their consumer; cancelling a request subscription keeps its shared `Server` usable. The generated async methods now return `UniffiRustFuture`, a `Future` with `cancel()`; existing `await` and `Future` assignments work unchanged. Custom implementations of generated interfaces must return `UniffiRustFuture` instead of a plain `Future`. diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index f3db7414ac9..a1dfc8787d9 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -153,11 +153,8 @@ typedef Reservation = MoqReservation; /// A snapshot of transport connection statistics. typedef ConnectionStats = MoqConnectionStats; -/// A session's authorization: the grant its peer gave it, and more tokens to present. -typedef Auth = MoqAuth; - -/// One token presented with [Auth.add]; cancel it to withdraw the token. -typedef AuthToken = MoqAuthToken; +/// Follows the grant a session's peer gave it; cancel it to release a pending wait. +typedef GrantConsumer = MoqGrantConsumer; /// What the peer lets this side do: publish and subscribe patterns, and an expiry. typedef Grant = MoqGrant; diff --git a/dart/moq/lib/src/client.dart b/dart/moq/lib/src/client.dart index b876abf0ee7..e5bb1f15e3f 100644 --- a/dart/moq/lib/src/client.dart +++ b/dart/moq/lib/src/client.dart @@ -244,12 +244,11 @@ final class Moq { /// the room back. Bandwidth bandwidth() => session.bandwidth(); - /// The session's authorization: the grant its peer gave it, and more tokens to present. + /// Follow the grant the peer gave this session. /// - /// Listen to [AuthGrants.grants] to follow the grant, and [Auth.add] a fresh - /// token before the current one expires; each added token is presented again - /// on every reconnect. - Auth auth() => session.auth(); + /// Listen to [GrantConsumerUpdates.updates] for the current grant and each + /// change. Every call returns an independent consumer. + GrantConsumer grants() => session.grants(); /// The credentials every dial presents ([ConnectOptions.tokens]), to /// replace while running. @@ -258,9 +257,9 @@ final class Moq { /// next dial presents them, and a live session with in-band AUTH presents /// them at once, withdrawing each replaced token once its replacements are /// answered, even when one is refused. After an authorization refusal the - /// client redials only if they changed. An empty token throws - /// `ConfigMoqException`. - Tokens tokens() => _client.tokens(); + /// session redials only if they changed. An empty token throws + /// `ConfigMoqException`. Await [Tokens.answered] for the relay's verdict. + Tokens tokens() => session.tokens()!; /// Drain within one second, then stop the client. /// @@ -278,13 +277,13 @@ final class Moq { } /// A [Stream] view over a session's grant. -extension AuthGrants on Auth { +extension GrantConsumerUpdates on GrantConsumer { /// The current grant, then each change, null while there is none. /// - /// Listens on one [Auth] share its place in the changes, so a second watcher - /// takes its own from [Moq.auth]. Cancelling releases only its pending read. - /// Ends when the session shuts down, and errors with its close reason otherwise. - Stream grants() => _Grants(this); + /// Listen once: the consumer is cancelled and released when the subscription + /// ends. Ends when the session shuts down, and errors with its close reason + /// otherwise. + Stream updates() => _Grants(this); } /// A [Stream] view over an announcement cursor. @@ -297,18 +296,27 @@ extension AnnounceConsumerUpdates on AnnounceConsumer { } final class _Grants extends NativeStream { - final Auth auth; - _Grants(this.auth); + final GrantConsumer grants; + _Grants(this.grants); @override - Iterable initial() => [auth.grant()]; + Iterable initial() => [grants.grant()]; @override - UniffiRustFuture read() => auth.grantChanged(); + UniffiRustFuture read() => grants.changed(); @override bool ended(Object error) => error is CancelledMoqException || error is ClosedMoqException; + + @override + void release() { + try { + grants.cancel(); + } finally { + grants.dispose(); + } + } } final class _Updates extends NativeStream { diff --git a/dart/moq/test/cancellation_test.dart b/dart/moq/test/cancellation_test.dart index 2ca0aff9cc4..05a418c90f1 100644 --- a/dart/moq/test/cancellation_test.dart +++ b/dart/moq/test/cancellation_test.dart @@ -89,19 +89,22 @@ final class _Announcements implements AnnounceConsumer { dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } -final class _Auth implements Auth { +final class _Grants implements GrantConsumer { final started = Completer<_Read>(); + var cancels = 0; var disposals = 0; @override Grant? grant() => null; @override - UniffiRustFuture grantChanged() { + UniffiRustFuture changed() { final read = _Read(); started.complete(read); return read; } + @override + void cancel() => cancels++; @override void dispose() => disposals++; @override @@ -125,17 +128,17 @@ void main() { }, ); - test('idle grant cancellation leaves the shared auth usable', () async { - final auth = _Auth(); + test('idle grant cancellation releases its read and consumer', () async { + final source = _Grants(); final grants = []; - final subscription = auth.grants().listen(grants.add); - final read = await auth.started.future; + final subscription = source.updates().listen(grants.add); + final read = await source.started.future; await subscription.cancel(); expect(grants, [null]); expect(read.cancels, 1); expect(read.cleaned.isCompleted, isTrue); - expect(auth.disposals, 0); - expect(auth.grant(), isNull); + expect(source.cancels, 1); + expect(source.disposals, 1); }); test('cancellation before the first read still releases ownership', () async { diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index cddf1ef3635..cd3f2e7c228 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -183,25 +183,27 @@ void main() { expectEverything( await client - .auth() .grants() + .updates() .firstWhere((g) => g != null) .timeout(timeout), ); expectEverything( await serverSession - .auth() .grants() + .updates() .firstWhere((g) => g != null) .timeout(timeout), ); + expect(serverSession.tokens(), isNull); // A peer that verifies no tokens of its own refuses another one. + client.tokens().set_(tokens: ['extra']); await expectLater( - client.auth().add(token: 'extra').timeout(timeout), + client.tokens().answered().timeout(timeout), throwsA(isA()), ); - expectEverything(client.auth().grant()); + expectEverything(client.grants().grant()); // The client drains first: cancelling the server session would fail its shutdown. await client.close(); diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index c888a06cafe..6ec655cd31d 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -8935,130 +8935,31 @@ class FfiConverterMoqAudioProducer { } } -abstract class MoqAuthInterface { - UniffiRustFuture add({required String token}); - MoqGrant? grant(); - UniffiRustFuture grantChanged(); -} - -final _MoqAuthFinalizer = Finalizer>((ptr) { - rustCall((status) => uniffi_moq_ffi_fn_free_moqauth(ptr, status)); -}); - -class MoqAuth implements MoqAuthInterface { - late final Pointer _ptr; - bool _isDisposed = false; - MoqAuth._(this._ptr) { - _MoqAuthFinalizer.attach(this, _ptr, detach: this); - } - factory MoqAuth.lift(Pointer ptr) { - return MoqAuth._(ptr); - } - Pointer uniffiClonePointer() { - if (_isDisposed) { - throw StateError("Object has already been disposed"); - } - return rustCall((status) => uniffi_moq_ffi_fn_clone_moqauth(_ptr, status)); - } - - void dispose() { - if (_isDisposed) { - return; - } - _isDisposed = true; - _MoqAuthFinalizer.detach(this); - rustCall((status) => uniffi_moq_ffi_fn_free_moqauth(_ptr, status)); - } - - UniffiRustFuture add({required String token}) { - return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqauth_add( - uniffiClonePointer(), - FfiConverterString.lower(token), - ), - ffi_moq_ffi_rust_future_poll_u64, - ffi_moq_ffi_rust_future_complete_u64, - ffi_moq_ffi_rust_future_cancel_u64, - ffi_moq_ffi_rust_future_free_u64, - (ptr) => FfiConverterMoqAuthToken.lift(Pointer.fromAddress(ptr)), - moqExceptionErrorHandler, - ); - } - - MoqGrant? grant() { - return rustCallWithLifter( - (status) => - uniffi_moq_ffi_fn_method_moqauth_grant(uniffiClonePointer(), status), - FfiConverterOptionalMoqGrant.lift, - null, - ); - } - - UniffiRustFuture grantChanged() { - return uniffiRustCallAsync( - () => - uniffi_moq_ffi_fn_method_moqauth_grant_changed(uniffiClonePointer()), - ffi_moq_ffi_rust_future_poll_rust_buffer, - ffi_moq_ffi_rust_future_complete_rust_buffer, - ffi_moq_ffi_rust_future_cancel_rust_buffer, - ffi_moq_ffi_rust_future_free_rust_buffer, - FfiConverterOptionalMoqGrant.lift, - moqExceptionErrorHandler, - ); - } -} - -class FfiConverterMoqAuth { - static MoqAuth lift(Pointer ptr) { - return MoqAuth.lift(ptr); - } - - static Pointer lower(MoqAuth value) { - return value.uniffiClonePointer(); - } - - static int allocationSize(MoqAuth value) { - return 8; - } - - static LiftRetVal read(Uint8List buf) { - final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); - final pointer = Pointer.fromAddress(handle); - return LiftRetVal(MoqAuth.lift(pointer), 8); - } - - static int write(MoqAuth value, Uint8List buf) { - final handle = lower(value); - buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); - return 8; - } -} - -abstract class MoqAuthTokenInterface { +abstract class MoqGrantConsumerInterface { void cancel(); - UniffiRustFuture closed(); + UniffiRustFuture changed(); MoqGrant? grant(); } -final _MoqAuthTokenFinalizer = Finalizer>((ptr) { - rustCall((status) => uniffi_moq_ffi_fn_free_moqauthtoken(ptr, status)); +final _MoqGrantConsumerFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqgrantconsumer(ptr, status)); }); -class MoqAuthToken implements MoqAuthTokenInterface { +class MoqGrantConsumer implements MoqGrantConsumerInterface { late final Pointer _ptr; bool _isDisposed = false; - MoqAuthToken._(this._ptr) { - _MoqAuthTokenFinalizer.attach(this, _ptr, detach: this); + MoqGrantConsumer._(this._ptr) { + _MoqGrantConsumerFinalizer.attach(this, _ptr, detach: this); } - factory MoqAuthToken.lift(Pointer ptr) { - return MoqAuthToken._(ptr); + factory MoqGrantConsumer.lift(Pointer ptr) { + return MoqGrantConsumer._(ptr); } Pointer uniffiClonePointer() { if (_isDisposed) { throw StateError("Object has already been disposed"); } return rustCall( - (status) => uniffi_moq_ffi_fn_clone_moqauthtoken(_ptr, status), + (status) => uniffi_moq_ffi_fn_clone_moqgrantconsumer(_ptr, status), ); } @@ -9067,34 +8968,36 @@ class MoqAuthToken implements MoqAuthTokenInterface { return; } _isDisposed = true; - _MoqAuthTokenFinalizer.detach(this); - rustCall((status) => uniffi_moq_ffi_fn_free_moqauthtoken(_ptr, status)); + _MoqGrantConsumerFinalizer.detach(this); + rustCall((status) => uniffi_moq_ffi_fn_free_moqgrantconsumer(_ptr, status)); } void cancel() { return rustCall((status) { - uniffi_moq_ffi_fn_method_moqauthtoken_cancel( + uniffi_moq_ffi_fn_method_moqgrantconsumer_cancel( uniffiClonePointer(), status, ); }, null); } - UniffiRustFuture closed() { + UniffiRustFuture changed() { return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqauthtoken_closed(uniffiClonePointer()), - ffi_moq_ffi_rust_future_poll_void, - ffi_moq_ffi_rust_future_complete_void, - ffi_moq_ffi_rust_future_cancel_void, - ffi_moq_ffi_rust_future_free_void, - (_) {}, + () => uniffi_moq_ffi_fn_method_moqgrantconsumer_changed( + uniffiClonePointer(), + ), + ffi_moq_ffi_rust_future_poll_rust_buffer, + ffi_moq_ffi_rust_future_complete_rust_buffer, + ffi_moq_ffi_rust_future_cancel_rust_buffer, + ffi_moq_ffi_rust_future_free_rust_buffer, + FfiConverterOptionalMoqGrant.lift, moqExceptionErrorHandler, ); } MoqGrant? grant() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqauthtoken_grant( + (status) => uniffi_moq_ffi_fn_method_moqgrantconsumer_grant( uniffiClonePointer(), status, ), @@ -9104,26 +9007,26 @@ class MoqAuthToken implements MoqAuthTokenInterface { } } -class FfiConverterMoqAuthToken { - static MoqAuthToken lift(Pointer ptr) { - return MoqAuthToken.lift(ptr); +class FfiConverterMoqGrantConsumer { + static MoqGrantConsumer lift(Pointer ptr) { + return MoqGrantConsumer.lift(ptr); } - static Pointer lower(MoqAuthToken value) { + static Pointer lower(MoqGrantConsumer value) { return value.uniffiClonePointer(); } - static int allocationSize(MoqAuthToken value) { + static int allocationSize(MoqGrantConsumer value) { return 8; } - static LiftRetVal read(Uint8List buf) { + static LiftRetVal read(Uint8List buf) { final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); final pointer = Pointer.fromAddress(handle); - return LiftRetVal(MoqAuthToken.lift(pointer), 8); + return LiftRetVal(MoqGrantConsumer.lift(pointer), 8); } - static int write(MoqAuthToken value, Uint8List buf) { + static int write(MoqGrantConsumer value, Uint8List buf) { final handle = lower(value); buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); return 8; @@ -13641,7 +13544,6 @@ class FfiConverterMoqServer { abstract class MoqClientInterface { void cancel(); UniffiRustFuture connect({required String url}); - MoqTokens tokens(); } final _MoqClientFinalizer = Finalizer>((ptr) { @@ -13705,17 +13607,6 @@ class MoqClient implements MoqClientInterface { moqExceptionErrorHandler, ); } - - MoqTokens tokens() { - return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqclient_tokens( - uniffiClonePointer(), - status, - ), - FfiConverterMoqTokens.lift, - null, - ); - } } class FfiConverterMoqClient { @@ -13745,17 +13636,18 @@ class FfiConverterMoqClient { } abstract class MoqSessionInterface { - MoqAuth auth(); MoqBandwidth bandwidth(); void cancel({required int code}); UniffiRustFuture closed(); MoqOriginConsumer consume(); + MoqGrantConsumer grants(); MoqOriginProducer publish(); MoqBandwidthConsumer? recvBandwidth(); void shutdown(); MoqConnectionState state(); UniffiRustFuture stateChanged({required int after}); MoqConnectionStats stats(); + MoqTokens? tokens(); } final _MoqSessionFinalizer = Finalizer>((ptr) { @@ -13789,17 +13681,6 @@ class MoqSession implements MoqSessionInterface { rustCall((status) => uniffi_moq_ffi_fn_free_moqsession(_ptr, status)); } - MoqAuth auth() { - return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqsession_auth( - uniffiClonePointer(), - status, - ), - FfiConverterMoqAuth.lift, - null, - ); - } - MoqBandwidth bandwidth() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqsession_bandwidth( @@ -13844,6 +13725,17 @@ class MoqSession implements MoqSessionInterface { ); } + MoqGrantConsumer grants() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqsession_grants( + uniffiClonePointer(), + status, + ), + FfiConverterMoqGrantConsumer.lift, + null, + ); + } + MoqOriginProducer publish() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqsession_publish( @@ -13911,6 +13803,17 @@ class MoqSession implements MoqSessionInterface { null, ); } + + MoqTokens? tokens() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqsession_tokens( + uniffiClonePointer(), + status, + ), + FfiConverterOptionalMoqTokens.lift, + null, + ); + } } class FfiConverterMoqSession { @@ -13940,6 +13843,7 @@ class FfiConverterMoqSession { } abstract class MoqTokensInterface { + UniffiRustFuture answered(); void set_({required List tokens}); } @@ -13974,6 +13878,18 @@ class MoqTokens implements MoqTokensInterface { rustCall((status) => uniffi_moq_ffi_fn_free_moqtokens(_ptr, status)); } + UniffiRustFuture answered() { + return uniffiRustCallAsync( + () => uniffi_moq_ffi_fn_method_moqtokens_answered(uniffiClonePointer()), + ffi_moq_ffi_rust_future_poll_void, + ffi_moq_ffi_rust_future_complete_void, + ffi_moq_ffi_rust_future_cancel_void, + ffi_moq_ffi_rust_future_free_void, + (_) {}, + moqExceptionErrorHandler, + ); + } + void set_({required List tokens}) { return rustCall((status) { uniffi_moq_ffi_fn_method_moqtokens_set( @@ -16042,6 +15958,51 @@ class FfiConverterOptionalMoqSubscription { } } +class FfiConverterOptionalMoqTokens { + static MoqTokens? lift(RustBuffer buf) { + return FfiConverterOptionalMoqTokens.read(buf.asUint8List()).value; + } + + static LiftRetVal read(Uint8List buf) { + if (ByteData.view(buf.buffer, buf.offsetInBytes).getInt8(0) == 0) { + return LiftRetVal(null, 1); + } + final result = FfiConverterMoqTokens.read( + Uint8List.view(buf.buffer, buf.offsetInBytes + 1), + ); + return LiftRetVal(result.value, result.bytesRead + 1); + } + + static int allocationSize([MoqTokens? value]) { + if (value == null) { + return 1; + } + return FfiConverterMoqTokens.allocationSize(value) + 1; + } + + static RustBuffer lower(MoqTokens? value) { + if (value == null) { + return toRustBuffer(Uint8List.fromList([0])); + } + final buf = Uint8List(FfiConverterOptionalMoqTokens.allocationSize(value)); + FfiConverterOptionalMoqTokens.write(value, buf); + return toRustBuffer(buf); + } + + static int write(MoqTokens? value, Uint8List buf) { + if (value == null) { + buf[0] = 0; + return 1; + } + buf[0] = 1; + return FfiConverterMoqTokens.write( + value, + Uint8List.view(buf.buffer, buf.offsetInBytes + 1), + ) + + 1; + } +} + class FfiConverterOptionalMoqTrackInfo { static MoqTrackInfo? lift(RustBuffer buf) { return FfiConverterOptionalMoqTrackInfo.read(buf.asUint8List()).value; @@ -17168,7 +17129,7 @@ external void uniffi_moq_ffi_fn_method_moqaudioproducer_write( @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqauth( +external Pointer uniffi_moq_ffi_fn_clone_moqgrantconsumer( Pointer handle, Pointer uniffiStatus, ); @@ -17176,36 +17137,7 @@ external Pointer uniffi_moq_ffi_fn_clone_moqauth( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqauth( - Pointer handle, - Pointer uniffiStatus, -); - -@Native Function(Pointer, RustBuffer)>( - assetId: _uniffiAssetId, -) -external Pointer uniffi_moq_ffi_fn_method_moqauth_add( - Pointer ptr, - RustBuffer token, -); - -@Native, Pointer)>( - assetId: _uniffiAssetId, -) -external RustBuffer uniffi_moq_ffi_fn_method_moqauth_grant( - Pointer ptr, - Pointer uniffiStatus, -); - -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqauth_grant_changed( - Pointer ptr, -); - -@Native Function(Pointer, Pointer)>( - assetId: _uniffiAssetId, -) -external Pointer uniffi_moq_ffi_fn_clone_moqauthtoken( +external void uniffi_moq_ffi_fn_free_moqgrantconsumer( Pointer handle, Pointer uniffiStatus, ); @@ -17213,28 +17145,20 @@ external Pointer uniffi_moq_ffi_fn_clone_moqauthtoken( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqauthtoken( - Pointer handle, - Pointer uniffiStatus, -); - -@Native, Pointer)>( - assetId: _uniffiAssetId, -) -external void uniffi_moq_ffi_fn_method_moqauthtoken_cancel( +external void uniffi_moq_ffi_fn_method_moqgrantconsumer_cancel( Pointer ptr, Pointer uniffiStatus, ); @Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqauthtoken_closed( +external Pointer uniffi_moq_ffi_fn_method_moqgrantconsumer_changed( Pointer ptr, ); @Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqauthtoken_grant( +external RustBuffer uniffi_moq_ffi_fn_method_moqgrantconsumer_grant( Pointer ptr, Pointer uniffiStatus, ); @@ -19260,14 +19184,6 @@ external Pointer uniffi_moq_ffi_fn_method_moqclient_connect( RustBuffer url, ); -@Native Function(Pointer, Pointer)>( - assetId: _uniffiAssetId, -) -external Pointer uniffi_moq_ffi_fn_method_moqclient_tokens( - Pointer ptr, - Pointer uniffiStatus, -); - @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -19284,14 +19200,6 @@ external void uniffi_moq_ffi_fn_free_moqsession( Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( - assetId: _uniffiAssetId, -) -external Pointer uniffi_moq_ffi_fn_method_moqsession_auth( - Pointer ptr, - Pointer uniffiStatus, -); - @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -19322,6 +19230,14 @@ external Pointer uniffi_moq_ffi_fn_method_moqsession_consume( Pointer uniffiStatus, ); +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_method_moqsession_grants( + Pointer ptr, + Pointer uniffiStatus, +); + @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -19368,6 +19284,14 @@ external RustBuffer uniffi_moq_ffi_fn_method_moqsession_stats( Pointer uniffiStatus, ); +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqsession_tokens( + Pointer ptr, + Pointer uniffiStatus, +); + @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -19384,6 +19308,11 @@ external void uniffi_moq_ffi_fn_free_moqtokens( Pointer uniffiStatus, ); +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqtokens_answered( + Pointer ptr, +); + @Native, RustBuffer, Pointer)>( assetId: _uniffiAssetId, ) @@ -20046,22 +19975,13 @@ external int uniffi_moq_ffi_checksum_method_moqaudioproducer_reservation(); external int uniffi_moq_ffi_checksum_method_moqaudioproducer_write(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqauth_add(); +external int uniffi_moq_ffi_checksum_method_moqgrantconsumer_cancel(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqauth_grant(); +external int uniffi_moq_ffi_checksum_method_moqgrantconsumer_changed(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqauth_grant_changed(); - -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqauthtoken_cancel(); - -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqauthtoken_closed(); - -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqauthtoken_grant(); +external int uniffi_moq_ffi_checksum_method_moqgrantconsumer_grant(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbandwidth_reserve(); @@ -20505,12 +20425,6 @@ external int uniffi_moq_ffi_checksum_method_moqclient_cancel(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqclient_connect(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqclient_tokens(); - -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqsession_auth(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_bandwidth(); @@ -20523,6 +20437,9 @@ external int uniffi_moq_ffi_checksum_method_moqsession_closed(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_consume(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqsession_grants(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_publish(); @@ -20541,6 +20458,12 @@ external int uniffi_moq_ffi_checksum_method_moqsession_state_changed(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_stats(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqsession_tokens(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqtokens_answered(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtokens_set(); @@ -20760,22 +20683,13 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqaudioproducer_write() != 48796) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqauth_add() != 1074) { + if (uniffi_moq_ffi_checksum_method_moqgrantconsumer_cancel() != 22691) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqauth_grant() != 14588) { + if (uniffi_moq_ffi_checksum_method_moqgrantconsumer_changed() != 37570) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqauth_grant_changed() != 38858) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqauthtoken_cancel() != 59324) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqauthtoken_closed() != 40912) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqauthtoken_grant() != 31654) { + if (uniffi_moq_ffi_checksum_method_moqgrantconsumer_grant() != 36088) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqbandwidth_reserve() != 27807) { @@ -21243,12 +21157,6 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqclient_connect() != 5016) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqclient_tokens() != 18102) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqsession_auth() != 1680) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } if (uniffi_moq_ffi_checksum_method_moqsession_bandwidth() != 8006) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -21261,6 +21169,9 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqsession_consume() != 57909) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_method_moqsession_grants() != 48347) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqsession_publish() != 15240) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -21279,7 +21190,13 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqsession_stats() != 36396) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqtokens_set() != 58423) { + if (uniffi_moq_ffi_checksum_method_moqsession_tokens() != 2396) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqtokens_answered() != 11571) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqtokens_set() != 20110) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqvideoconsumer_cancel() != 21122) { diff --git a/doc/bin/obs.md b/doc/bin/obs.md index 335788987f8..3e344487924 100644 --- a/doc/bin/obs.md +++ b/doc/bin/obs.md @@ -28,7 +28,7 @@ reconnecting, on a session that carries in-band authorization: a `moq-transport` draft-17 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 -next Go Live. +next reconnect or Go Live. By default the dock tunes the encoder for low latency on this stream only: no B-frames or lookahead on the encoders that support turning them off. This diff --git a/doc/bin/relay/auth.md b/doc/bin/relay/auth.md index c55c7bcad9f..588f4659dbb 100644 --- a/doc/bin/relay/auth.md +++ b/doc/bin/relay/auth.md @@ -157,10 +157,12 @@ 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 -`Client::tokens()`: the next dial presents them, a live session presents them in -band and withdraws each old one once its replacement is answered, and a refusal -redials only once the tokens have changed. Older versions refuse in-band tokens. +A native client can instead replace its configured tokens through its +connection's tokens (`Connection::tokens()`, `session.tokens()` in the +bindings): the next dial presents them, a live session presents them in band and +withdraws each old one once its replacement is answered, `answered()` reports +the relay's verdict, and a refusal redials only once the tokens have changed. +Older versions refuse in-band tokens. Each accepted token adds its publish and subscribe patterns to the session's union, within its admitted root and SETUP role. A publish-only connection cannot diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index bfca0b4a6c5..ebf65addf53 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -211,9 +211,9 @@ Obtain a dynamic track request’s `demand()` before accepting it to watch subsc ## Authorization -On `moq-lite-07-wip` (opt in with `ClientConfig::versions`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session->auth()->grant()` is the `Grant` the relay sent back, empty until it answers and while a client session reconnects; `grant_changed()` waits for the next one. `add(token)` presents a fresh token without reconnecting and resolves to an `AuthToken` whose grant joins the union until `cancel()`; it is presented again on every reconnect. A refusal resolves to an `Error` carrying the relay's code. +On `moq-lite-07-wip` (opt in with `ClientConfig::versions`) and on moq-transport draft-17+ 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()`. -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. `client->tokens()->set(...)` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the client redials only if they changed. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. +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. ## Stats diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 94354f927d1..443f3737a51 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -145,11 +145,11 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoder reads.** `audio.Consumer` and `video.Consumer` return a `Read` in order: a `ReadFrame`, a `ReadGap` where media was lost, or a `ReadEnd` where the publisher stopped its encoder. What follows a gap or an end does not continue what came before. - **Decoded frames hold decoder buffers.** `dispose()` each frame from a `video.Consumer` promptly rather than waiting for the garbage collector, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. -- **Closing.** `await moq.close()` drains for up to one second and reports its result. `session.shutdown()` requests the drain synchronously; `await session.closed()` waits for its result. `session.cancel(code: 0)` closes at once. Finish or abort live tracks first. Awaiting cancellation of an announcement, grant, or request subscription releases its pending native read. Announcements also release their cursor; authorization and server listeners leave their shared owner usable. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. +- **Closing.** `await moq.close()` drains for up to one second and reports its result. `session.shutdown()` requests the drain synchronously; `await session.closed()` waits for its result. `session.cancel(code: 0)` closes at once. Finish or abort live tracks first. Awaiting cancellation of an announcement, grant, or request subscription releases its pending native read. Announcements and grants also release their consumer; server listeners leave their shared server usable. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **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()` 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`, which readers take as the publisher leaving. - **Stats.** `session.stats()` reports `rtt`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). 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. -- **Authorization.** On `moq-lite-07-wip` (opt in with `ConnectOptions(versions: ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), listen to `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. `await auth().add(token: ...)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. -- **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 client redials only if they changed. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. +- **Authorization.** On `moq-lite-07-wip` (opt in with `ConnectOptions(versions: ...)`) and on moq-transport draft-17+ 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. +- **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. - **Track demand.** Obtain a dynamic track request’s `demand()` before accepting it to watch subscribers through the handoff to its producer. The watch does not keep the track alive and ends when the track closes or the request is rejected. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index 4b1163f1744..2070f09fe6c 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -135,8 +135,8 @@ shows which module holds each. - **Closing.** `client.Close()` drains for up to one second and returns an error on failure. `session.Shutdown()` requests that drain immediately; `session.Closed(ctx)` waits for its result, and `session.Cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **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`, which readers take as the publisher leaving. - **Stats.** `Session().Stats()` reports `RTT`, `EstimatedSendRateBps`, and the byte and packet counters (`BytesSent`, `BytesReceived`, `BytesLost`, `PacketsSent`, `PacketsReceived`, `PacketsLost`). 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 `Close()` 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. -- **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig.Versions`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `Session().Auth().Grant()` is the `Grant` the relay sent back, nil until it answers and while a client session reconnects; `GrantChanged(ctx)` waits for the next one. `Add(ctx, token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `Close()`, and is presented again on every reconnect. A refusal returns the relay's code. -- **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. `client.Tokens().Set(...)` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the client redials only if they changed. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. +- **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig.Versions`) and on moq-transport draft-17+ 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. `Close()` 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. - **Track demand.** Obtain a dynamic track request’s `Demand()` before accepting it to watch subscribers through the handoff to its producer. The watch does not keep the track alive and ends when the track closes or the request is rejected. diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index 957330dd689..e8da068a6d9 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -105,8 +105,8 @@ shows which module holds each. - **Closing.** `moq.shutdown()` requests a drain immediately; suspending `moq.session.closed()` waits up to one second and reports its result. `Moq.close()`, and so `use { }`, cancels at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **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`, which readers take as the publisher leaving. - **Stats.** `session.stats()` reports `rtt`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). 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. -- **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig(versions = ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), collect `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. Suspending `auth().add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. -- **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 client redials only if they changed. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. +- **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig(versions = ...)`) and on moq-transport draft-17+ 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. +- **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. - **Track demand.** Obtain a dynamic track request’s `demand()` before accepting it to watch subscribers through the handoff to its producer. The watch does not keep the track alive and ends when the track closes or the request is rejected. diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index dd040e4b347..285f66737d6 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -119,8 +119,8 @@ shows which module holds each. - **Closing.** `session.shutdown()` requests a drain immediately; `await session.closed()` waits up to one second and reports its result. `cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **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`, which readers take as the publisher leaving. - **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`). 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 `Bandwidth.Consumer` 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. -- **Authorization.** On `moq-lite-07-wip` (opt in with `versions=`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `None` until it answers and while a client session reconnects; `await auth.grant_changed()` waits for the next one. `await auth.add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal raises with the relay's code. -- **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. `client.tokens().set([...])` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the client redials only if they changed. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. +- **Authorization.** On `moq-lite-07-wip` (opt in with `versions=`) and on moq-transport draft-17+ 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. +- **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. - **Track demand.** Obtain a dynamic track request’s `demand()` before accepting it to watch subscribers through the handoff to its producer. The watch does not keep the track alive and ends when the track closes or the request is rejected. diff --git a/doc/lib/rs/index.md b/doc/lib/rs/index.md index eb924d763c1..57804d0618f 100644 --- a/doc/lib/rs/index.md +++ b/doc/lib/rs/index.md @@ -95,7 +95,8 @@ URLs may be `https://` (QUIC or WebTransport, with a WebSocket fallback), `moql://`/`moqt://` (raw QUIC), or `iroh://`. Put credentials in `connect::Config::tokens` rather than the URL: the first rides SETUP (and `?jwt=` while an offered version needs it), each other widens the grant in band, -and `Client::tokens().set(...)` replaces them before they expire. A `?jwt=` +and `Connection::tokens().set(...)` replaces them before they expire, with +`answered().await` reporting the relay's verdict. A `?jwt=` already in the URL stays the connection credential, which reaches an older relay. `http://` is for a relay on localhost only: it fetches the certificate fingerprint unauthenticated, so never send a token over it. QUIC tuning shares diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index acc00300fbf..41513e8893d 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -105,8 +105,8 @@ shows which module holds each. - **Closing.** `session.shutdown()` requests a drain immediately; `try await session.closed()` waits up to one second and reports its result. `session.cancel(code:)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **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()` 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`, which readers take as the publisher leaving. - **Stats.** `session.stats()` reports `rtt`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). 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 `Bandwidth.Consumer` 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. -- **Authorization.** On `moq-lite-07-wip` (opt in with `Client(versions:)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `nil` until it answers and while a client session reconnects; `try await auth.grantChanged()` waits for the next one. `try await auth.add(token:)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. -- **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 client.tokens().set([...])` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the client redials only if they changed. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. +- **Authorization.** On `moq-lite-07-wip` (opt in with `Client(versions:)`) and on moq-transport draft-17+ 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. +- **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. - **Track demand.** Obtain a dynamic track request’s `demand()` before accepting it to watch subscribers through the handoff to its producer. The watch does not keep the track alive and ends when the track closes or the request is rejected. diff --git a/go/wrapper/auth_test.go b/go/wrapper/auth_test.go index 39cf9f56023..08adc9f7933 100644 --- a/go/wrapper/auth_test.go +++ b/go/wrapper/auth_test.go @@ -11,16 +11,16 @@ import ( "moq.dev/moq" ) -// awaitGrant follows auth's changes until it reports want. -func awaitGrant(t *testing.T, ctx context.Context, auth *moq.Auth, want moq.Grant) { +// awaitGrant follows session's grant until it reports want. +func awaitGrant(t *testing.T, ctx context.Context, session *moq.Session, want moq.Grant) { t.Helper() - for { - got := auth.Grant() - if got != nil && reflect.DeepEqual(*got, want) { - return - } - if _, err := auth.GrantChanged(ctx); err != nil { + grants := session.Grants() + defer grants.Close() + got := grants.Grant() + for got == nil || !reflect.DeepEqual(*got, want) { + var err error + if got, err = grants.Changed(ctx); err != nil { t.Fatalf("grant = %+v, want %+v: %v", got, want, err) } } @@ -75,8 +75,7 @@ func TestSessionAuthReadsTheGrant(t *testing.T) { } everything := moq.Grant{Publish: []string{"**"}, Subscribe: []string{"**"}} - auth := client.Session().Auth() - awaitGrant(t, ctx, auth, everything) + awaitGrant(t, ctx, client.Session(), everything) var session *moq.Session select { @@ -85,12 +84,21 @@ func TestSessionAuthReadsTheGrant(t *testing.T) { t.Fatal("no session accepted") } defer session.Cancel(0) - awaitGrant(t, ctx, session.Auth(), everything) + awaitGrant(t, ctx, session, everything) + if session.Tokens() != nil { + t.Fatal("an accepted session presents no tokens") + } - if _, err := auth.Add(ctx, "extra"); !errors.Is(err, moq.ErrUnsupported) { - t.Fatalf("add = %v, want ErrUnsupported", err) + tokens := client.Session().Tokens() + if err := tokens.Set("extra"); err != nil { + t.Fatal(err) + } + if err := tokens.Answered(ctx); !errors.Is(err, moq.ErrUnsupported) { + t.Fatalf("answered = %v, want ErrUnsupported", err) } - if got := auth.Grant(); got == nil || !reflect.DeepEqual(*got, everything) { + grants := client.Session().Grants() + defer grants.Close() + if got := grants.Grant(); got == nil || !reflect.DeepEqual(*got, everything) { t.Fatalf("grant after a refusal = %+v", got) } } diff --git a/go/wrapper/client.go b/go/wrapper/client.go index c60bc8dc4a2..0086607e60d 100644 --- a/go/wrapper/client.go +++ b/go/wrapper/client.go @@ -39,7 +39,7 @@ type ClientConfig struct { Versions []string // Tokens are the credentials every dial presents. The first is the // connection credential, unless the URL carries its own ?jwt=; each other - // one widens the session's grant. Replace them with Client.Tokens. + // one widens the session's grant. Replace them with Session.Tokens. Tokens []string // Timeout bounds one connect, dial and handshake together. Zero waits forever. Timeout *time.Duration @@ -326,25 +326,6 @@ func (c *Client) RequestBroadcast(ctx context.Context, path string) (*BroadcastC return c.consumer.RequestBroadcast(ctx, path) } -// Tokens returns the credentials the client presents, to replace while it runs. -func (c *Client) Tokens() *Tokens { - return &Tokens{inner: c.inner.Tokens()} -} - -// Tokens are the credentials a Client presents, replaceable while it runs. -type Tokens struct { - inner *ffi.MoqTokens -} - -// Set replaces the credentials every dial presents, such as before the current -// ones expire. The next dial presents them, and a live session with in-band -// AUTH presents them at once, withdrawing each replaced token once its -// replacements are answered, even when one is refused. After an authorization -// refusal the client redials only if they changed. An empty token is refused. -func (t *Tokens) Set(tokens ...string) error { - return t.inner.Set(append([]string(nil), tokens...)) -} - // Session returns the underlying session. Hold the client (or session) to keep // the connection alive. func (c *Client) Session() *Session { diff --git a/go/wrapper/session.go b/go/wrapper/session.go index b631459a981..97a62987dc7 100644 --- a/go/wrapper/session.go +++ b/go/wrapper/session.go @@ -70,71 +70,76 @@ func (s *Session) Bandwidth() *Bandwidth { return &Bandwidth{inner: s.inner.Bandwidth()} } -// Auth is the session's authorization: the grant its peer gave it, and more -// tokens to present. Each call returns an independent watcher of the grant. A -// client session's handle survives reconnects, presenting each added token again -// on every new connection. -func (s *Session) Auth() *Auth { - return &Auth{inner: s.inner.Auth()} +// Grants follows the grant the peer gave this session. Each call returns an +// independent consumer; close it when done. A client session's grant follows +// each reconnect, reading nil while offline. +func (s *Session) Grants() *GrantConsumer { + return &GrantConsumer{inner: s.inner.Grants()} } -// Auth reads a session's grant and presents more tokens. +// 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. -type Auth struct { - inner *ffi.MoqAuth +type GrantConsumer struct { + inner *ffi.MoqGrantConsumer } -// Grant returns the union of every token's grant, or nil until the peer first -// answers one. A client session reads nil while it reconnects. -func (a *Auth) Grant() *Grant { - return grantFromFFI(a.inner.Grant()) +// Grant returns the grant now, or nil until the peer first answers a token. A +// client session reads nil while it reconnects. +func (g *GrantConsumer) Grant() *Grant { + return grantFromFFI(g.inner.Grant()) } -// GrantChanged blocks until the grant differs from the one this handle last -// reported, or held when it was made, and returns it. It errors once a client's -// connection or a server's session ends; a reconnect is not an end. -func (a *Auth) GrantChanged(ctx context.Context) (*Grant, error) { - grant, err := bridge.Call(ctx, nil, a.inner.GrantChanged) +// Changed blocks until the grant differs from the one this last returned, or +// held when it was made, and returns it. It errors once a client's connection +// or a server's session ends, or after Close; a reconnect is not an end. +func (g *GrantConsumer) Changed(ctx context.Context) (*Grant, error) { + grant, err := bridge.Call(ctx, nil, g.inner.Changed) return grantFromFFI(grant), err } -// Add presents another token, returning once the peer accepts it. Its grant -// joins the union until the token is closed. The peer's refusal is a -// ProtocolError carrying its code; a session that cannot carry another token -// returns an error for which errors.Is(err, ErrUnsupported) holds. Cancelling ctx -// withdraws the token. -func (a *Auth) Add(ctx context.Context, token string) (*AuthToken, error) { - inner, err := bridge.CallHandle(ctx, nil, func(ctx context.Context) (*ffi.MoqAuthToken, error) { - return a.inner.Add(ctx, token) - }) - if err != nil { - return nil, err +// Close ends every current and future Changed call. +func (g *GrantConsumer) Close() { g.inner.Cancel() } + +// Tokens returns the credentials a native client session presents, to replace +// while it runs, or nil for a server-accepted session, which presents none. +func (s *Session) Tokens() *Tokens { + inner := s.inner.Tokens() + if inner == nil { + return nil } - return &AuthToken{inner: inner}, nil + return &Tokens{inner: *inner} } -// AuthToken is one token presented with Auth.Add. -type AuthToken struct { - inner *ffi.MoqAuthToken +// Tokens are the credentials a client session presents, replaceable while it runs. +type Tokens struct { + inner *ffi.MoqTokens } -// Grant returns this token's own grant, or nil after it ended. -func (t *AuthToken) Grant() *Grant { - return grantFromFFI(t.inner.Grant()) +// Set replaces the credentials every dial presents, such as before the current +// ones expire. The first is the connection credential, unless the URL carries +// its own ?jwt=; each other one widens the grant over in-band AUTH. The next +// dial presents them, and a live session with in-band AUTH presents them at +// once, withdrawing each replaced token once its replacements are answered, +// even when one is refused. After an authorization refusal the session redials +// only if they changed. An empty token is refused. +func (t *Tokens) Set(tokens ...string) error { + return t.inner.Set(append([]string(nil), tokens...)) } -// Closed blocks until the token ends, returning the peer's revocation or the end -// of a client's connection or a server's session, or nil when the peer closed it -// without an error. A reconnect does not end it. -func (t *AuthToken) Closed(ctx context.Context) error { - return bridge.CallErr(ctx, nil, t.inner.Closed) +// Answered blocks until the peer's first verdict on the tokens the last Set +// newly presented: nil once each is granted, in band or as a later dial's +// connection credential. A token the set kept counts only once refused, and +// nothing is re-checked after the answer. It returns the peer's refusal as a +// ProtocolError carrying its code, an error for which +// errors.Is(err, ErrUnsupported) holds when the session cannot carry an +// in-band token, or the connection's close reason. +func (t *Tokens) Answered(ctx context.Context) error { + return bridge.CallErr(ctx, nil, t.inner.Answered) } -// Close withdraws the token, removing its grant from the union. -func (t *AuthToken) Close() { t.inner.Cancel() } - // Bandwidth divides one connection's send estimate among the tracks sharing it. type Bandwidth struct { inner *ffi.MoqBandwidth diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index 18ab27e8460..acfe9167017 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -157,10 +157,8 @@ typealias BandwidthConsumer = uniffi.moq.MoqBandwidthConsumer typealias Reservation = uniffi.moq.MoqReservation /** A snapshot of transport connection statistics. */ typealias ConnectionStats = uniffi.moq.MoqConnectionStats -/** A session's authorization: the grant its peer gave it, and more tokens to present. */ -typealias Auth = uniffi.moq.MoqAuth -/** One token presented with [Auth.add]; cancel it to withdraw the token. */ -typealias AuthToken = uniffi.moq.MoqAuthToken +/** Follows the grant a session's peer gave it; cancel it to release a pending wait. */ +typealias GrantConsumer = uniffi.moq.MoqGrantConsumer /** What the peer lets this side do: publish and subscribe patterns, and an expiry. */ typealias Grant = uniffi.moq.MoqGrant /** A connection lifecycle transition reported by [Session.state]. */ diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt index 366009c8ebd..dec8f893fc6 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt @@ -59,24 +59,25 @@ fun GroupConsumer.frames(): Flow = pull({ cancel() }) { readFrame() } fun AnnounceConsumer.updates(): Flow = pull { next() }.onCompletion { cancel() } /** - * The session's grant: the current one, then each change, null while there is none. + * The session's grant, as `grants().updates()`: the current one, then each change, null + * while there is none. * - * Collections of one [Auth] share its place in the changes, so a second watcher takes - * its own from [Moq.auth]. Completes when the session shuts down, and throws its close reason otherwise. + * Collect it once: the consumer is cancelled when collection ends, however it ends. + * Completes when the session shuts down, and throws its close reason otherwise. */ -fun Auth.grants(): Flow = flow { +fun GrantConsumer.updates(): Flow = flow { emit(grant()) while (true) { currentCoroutineContext().ensureActive() val grant = try { - grantChanged() + changed() } catch (e: MoqException) { if (e.isShutdown) break throw e } emit(grant) } -} +}.onCompletion { cancel() } /** Emits [next] until it returns null, checking for cancellation before each pull. */ private fun pull(next: suspend () -> T?): Flow = flow { diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt index c8e6878a575..f2e4fe1c8e6 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt @@ -61,12 +61,12 @@ class Moq internal constructor( fun bandwidth(): Bandwidth = session.bandwidth() /** - * The session's authorization: the grant its peer gave it, and more tokens to present. + * Follow the grant the peer gave this session. * - * Collect [Auth.grants] to follow the grant, and [Auth.add] a fresh token before the - * current one expires; each added token is presented again on every reconnect. + * Collect `grants().updates()` for the current grant and each change. Every call returns + * an independent consumer. */ - fun auth(): Auth = session.auth() + fun grants(): GrantConsumer = session.grants() /** * The credentials every dial presents ([ClientConfig.tokens]), to replace while running. @@ -74,10 +74,10 @@ class Moq internal constructor( * [Tokens.set] replaces them, such as before the current ones expire: the next dial presents * them, and a live session with in-band AUTH presents them at once, withdrawing each * replaced token once its replacements are answered, even when one is refused. After an - * authorization refusal the client redials only if they changed. An empty token throws - * `MoqException.Config`. + * authorization refusal the session redials only if they changed. An empty token throws + * `MoqException.Config`. Suspend on [Tokens.answered] for the relay's verdict. */ - fun tokens(): Tokens = client.tokens() + fun tokens(): Tokens = checkNotNull(session.tokens()) { "a client session presents tokens" } /** * Request a draining close now; await `session.closed()` for its result, then [close] diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index 716df28d00a..a8523b23e15 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -693,13 +693,15 @@ class SmokeTest { ) moq.use { val everything = Grant(publish = listOf("**"), subscribe = listOf("**"), expires = null) - assertEquals(everything, moq.auth().grants().first { it != null }) + assertEquals(everything, moq.grants().updates().first { it != null }) val session = accepted.await() - assertEquals(everything, session.auth().grants().first { it != null }) + assertEquals(everything, session.grants().updates().first { it != null }) assertNull(everything.expires) + assertNull(session.tokens(), "an accepted session presents no tokens") - assertFailsWith { moq.auth().add("extra") } - assertEquals(everything, moq.auth().grant()) + moq.tokens().set(listOf("extra")) + assertFailsWith { moq.tokens().answered() } + assertEquals(everything, moq.grants().grant()) session.cancel(0u) } } diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index b64c16d640e..cfc6ee312c2 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -159,7 +159,8 @@ client = moq.Client( - `.stats() → ConnectionStats`. Snapshot RTT, bandwidth estimates, and byte/packet counters. - `.state()` and `await .state_changed(after)`. Read one lifecycle snapshot and wait with its revision; first-dial failures and reconnects share the same session. - `.bandwidth() → Bandwidth`. Divide the send estimate between encoders and app-owned tracks. - - `.auth() → Auth`. On `moq-lite-07-wip` and on moq-transport draft-17+ with the MoQ Auth extension, `.grant()` reads the peer's `Grant` and `await .add(token) → AuthToken` presents a fresh token without reconnecting. + - `.grants() → GrantConsumer`. On `moq-lite-07-wip` and on moq-transport draft-17+ with the MoQ Auth extension, `.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/docs/index.md b/py/moq-rs/docs/index.md index 4b1f49a51b3..df19611b688 100644 --- a/py/moq-rs/docs/index.md +++ b/py/moq-rs/docs/index.md @@ -44,8 +44,8 @@ asyncio.run(main()) Session Request Transport - Auth - AuthToken + GrantConsumer + Tokens Grant ``` diff --git a/py/moq-rs/moq/__init__.py b/py/moq-rs/moq/__init__.py index 0413194853f..d44c9beb711 100644 --- a/py/moq-rs/moq/__init__.py +++ b/py/moq-rs/moq/__init__.py @@ -11,7 +11,7 @@ from . import flate as flate from . import json as json from . import video as video -from .client import Client, CongestionControl, Tokens, connect, qlog_supported, versions +from .client import Client, CongestionControl, connect, qlog_supported, versions from .epoch import mint_epoch from .errors import is_auth, is_shutdown, protocol_error from .log import log_level @@ -41,7 +41,7 @@ TrackRequest, ) from .server import Request, Server, Transport -from .session import Auth, AuthToken, Bandwidth, Reservation, Session +from .session import Bandwidth, GrantConsumer, Reservation, Session, Tokens from .subscribe import ( BroadcastConsumer, GroupConsumer, @@ -94,8 +94,6 @@ "AudioCodec", "AudioEncoderInput", "AudioSampleFormat", - "Auth", - "AuthToken", "Backoff", "Bandwidth", "BroadcastConsumer", @@ -119,6 +117,7 @@ "FetchGroupOptions", "Fill", "Grant", + "GrantConsumer", "GroupConsumer", "GroupProducer", "OriginConsumer", diff --git a/py/moq-rs/moq/client.py b/py/moq-rs/moq/client.py index f79a3c35b21..b0b65bbc123 100644 --- a/py/moq-rs/moq/client.py +++ b/py/moq-rs/moq/client.py @@ -32,25 +32,6 @@ def qlog_supported() -> bool: return moq_qlog_supported() -class Tokens: - """The credentials a :class:`Client` presents, replaceable while it runs.""" - - def __init__(self, client: Client) -> None: - self._client = client - - def set(self, tokens: Sequence[str]) -> None: - """Replace the credentials every dial presents, such as before the current ones expire. - - The next dial presents them, and a live session with in-band AUTH presents them at - once, withdrawing each replaced token once its replacements are answered, even when - one is refused. After an authorization refusal the client redials only if they changed. - """ - tokens = _strs(tokens, "tokens") - if self._client._inner is not None: - self._client._inner.tokens().set(tokens) - self._client._config.tokens = tokens - - class Client: """High-level MoQ client with automatic origin wiring. @@ -175,10 +156,6 @@ async def __aexit__(self, *exc) -> None: self._inner.cancel() self._inner = None - def tokens(self) -> Tokens: - """The credentials every dial presents, to replace while running.""" - return Tokens(self) - def create_broadcast(self, path: str) -> BroadcastProducer: """Create an unannounced broadcast at ``path``, invisible until announced. Announce it after populating tracks. diff --git a/py/moq-rs/moq/session.py b/py/moq-rs/moq/session.py index a0fe61bfd61..66373059025 100644 --- a/py/moq-rs/moq/session.py +++ b/py/moq-rs/moq/session.py @@ -2,8 +2,19 @@ from __future__ import annotations -from moq_ffi import MoqAuth, MoqAuthToken, MoqBandwidth, MoqBandwidthConsumer, MoqReservation, MoqSession - +from collections.abc import Sequence + +from moq_ffi import ( + MoqBandwidth, + MoqBandwidthConsumer, + MoqGrantConsumer, + MoqReservation, + MoqSession, + MoqTokens, +) + +from ._records import _strs +from .errors import is_shutdown from .origin import OriginConsumer, OriginProducer from .publish import TrackDemand from .types import ConnectionState, ConnectionStats, Grant @@ -91,13 +102,19 @@ def stats(self) -> ConnectionStats: Individual fields are ``None`` when the transport backend doesn't report them.""" return ConnectionStats._from_ffi(self._inner.stats()) - def auth(self) -> Auth: - """The session's authorization: the grant its peer gave it, and more tokens to present. + def grants(self) -> GrantConsumer: + """Follow the grant the peer gave this session. + + Each call returns an independent consumer. A client session's grant follows + each reconnect, reading ``None`` while offline.""" + return GrantConsumer(self._inner.grants()) + + def tokens(self) -> Tokens | None: + """The credentials a native client session presents, to replace while it runs. - Each call returns an independent watcher of the grant. A client session's - handle survives reconnects, presenting each added token again on every new - connection.""" - return Auth(self._inner.auth()) + ``None`` for a server-accepted session, which presents none.""" + inner = self._inner.tokens() + return None if inner is None else Tokens(inner) def recv_bandwidth(self) -> Bandwidth.Consumer | None: """Hold an owned receive-estimate consumer; releasing the last one stops PROBE.""" @@ -115,61 +132,85 @@ def bandwidth(self) -> Bandwidth: return Bandwidth(self._inner.bandwidth()) -class Auth: - """A session's authorization, returned by :meth:`Session.auth`. +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``:: + the MoQ Auth extension; elsewhere the grant stays ``None``. Iterate it for the + current grant and then each change, until the session ends:: - auth = session.auth() - print(auth.grant()) - token = await auth.add(fresh_jwt) + async for grant in session.grants(): + print(grant) """ - def __init__(self, inner: MoqAuth) -> None: + def __init__(self, inner: MoqGrantConsumer) -> None: self._inner = inner + self._started = False + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc) -> None: + self.cancel() + + def __aiter__(self): + return self + + async def __anext__(self) -> Grant | None: + if not self._started: + self._started = True + return self.grant() + try: + return await self.changed() + except Exception as err: + if is_shutdown(err): + raise StopAsyncIteration from None + raise def grant(self) -> Grant | None: - """The union of every token's grant, or ``None`` until the peer first answers one. + """The grant now, or ``None`` until the peer first answers a token. A client session reads ``None`` while it reconnects.""" return Grant._from_ffi(self._inner.grant()) - async def grant_changed(self) -> Grant | None: - """Wait for the grant to differ from the one last reported, or held when this - handle was made, returning it. + async def changed(self) -> Grant | None: + """Wait for the grant to differ from the one this last returned, or held when + it was made, returning it. Raises once nothing will change it again: a client's connection or a server's - session ended. A reconnect is not an end.""" - return Grant._from_ffi(await self._inner.grant_changed()) - - async def add(self, token: str) -> AuthToken: - """Present another token, returning once the peer accepts it. + session ended, or :meth:`cancel`. A reconnect is not an end.""" + return Grant._from_ffi(await self._inner.changed()) - Its grant joins the union until :meth:`AuthToken.cancel`. The peer's refusal - raises ``moq.Error`` carrying its code; a session that cannot carry another - token raises ``moq.Error.Unsupported``.""" - return AuthToken(await self._inner.add(token)) + def cancel(self) -> None: + """Cancel all current and future :meth:`changed` calls.""" + self._inner.cancel() -class AuthToken: - """One token presented with :meth:`Auth.add`, withdrawn by :meth:`cancel`.""" +class Tokens: + """The credentials a native client session presents, returned by :meth:`Session.tokens`.""" - def __init__(self, inner: MoqAuthToken) -> None: + def __init__(self, inner: MoqTokens) -> None: self._inner = inner - def grant(self) -> Grant | None: - """This token's own grant, or ``None`` after it ended.""" - return Grant._from_ffi(self._inner.grant()) + def set(self, tokens: Sequence[str]) -> None: + """Replace the credentials every dial presents, such as before the current ones expire. - async def closed(self) -> None: - """Wait for the token to end, raising the peer's revocation or the end of a client's - connection or a server's session. A reconnect does not end it.""" - await self._inner.closed() + The first is the connection credential, unless the URL carries its own ``?jwt=``; + each other one widens the grant over in-band AUTH. The next dial presents them, + and a live session with in-band AUTH presents them at once, withdrawing each + replaced token once its replacements are answered, even when one is refused. + After an authorization refusal the session redials only if they changed. + """ + self._inner.set(_strs(tokens, "tokens")) - def cancel(self) -> None: - """Withdraw the token, removing its grant from the union.""" - self._inner.cancel() + async def answered(self) -> None: + """Wait for the peer's first verdict on the tokens the last ``set`` newly presented. + + Returns once each is granted, in band or as a later dial's connection credential. + A token the set kept counts only once refused, and nothing is re-checked after the + answer. Raises the peer's refusal carrying its code, ``moq.Error.Unsupported`` when + the session cannot carry an in-band token, or the connection's close reason.""" + await self._inner.answered() class Bandwidth: diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index bfe350c6758..68dba7ca505 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -902,12 +902,10 @@ def test_public_api_exports(): assert client._config.tls.fingerprints == ["abc123"] -def test_client_tokens_before_connecting(): - """Tokens reach the config, and setting them before connecting replaces them there.""" +def test_client_tokens_reach_the_config(): + """Tokens reach the config every session starts from.""" client = moq.connect("https://example.com", tokens=["first", "second"]) assert client._config.tokens == ["first", "second"] - client.tokens().set(["fresh"]) - assert client._config.tokens == ["fresh"] async def test_container_consumer_default_latency_and_context_manager(): diff --git a/py/moq-rs/tests/test_server.py b/py/moq-rs/tests/test_server.py index 007b86a783a..f48bcfff695 100644 --- a/py/moq-rs/tests/test_server.py +++ b/py/moq-rs/tests/test_server.py @@ -556,10 +556,12 @@ async def drain(reader: moq.TrackConsumer) -> None: broadcast.close() -async def _await_grant(auth: moq.Auth, want: moq.Grant) -> None: +async def _await_grant(session: moq.Session, want: moq.Grant) -> None: async def follow() -> None: - while auth.grant() != want: - await auth.grant_changed() + async with session.grants() as grants: + async for grant in grants: + if grant == want: + return await asyncio.wait_for(follow(), timeout=5.0) @@ -584,13 +586,17 @@ async def accept_loop() -> None: session = client.session assert session is not None everything = moq.Grant(publish=("**",), subscribe=("**",)) - await _await_grant(session.auth(), everything) + await _await_grant(session, everything) await asyncio.wait_for(accepted.wait(), timeout=5.0) - await _await_grant(sessions[0].auth(), everything) + await _await_grant(sessions[0], everything) + assert sessions[0].tokens() is None + tokens = session.tokens() + assert tokens is not None + tokens.set(["extra"]) with pytest.raises(moq.Error.Unsupported): - await asyncio.wait_for(session.auth().add("extra"), timeout=5.0) - assert session.auth().grant() == everything + await asyncio.wait_for(tokens.answered(), timeout=5.0) + assert session.grants().grant() == everything finally: accept_task.cancel() try: diff --git a/quest/m1/README.md b/quest/m1/README.md index f1d8e19a613..ba17e5fe626 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -119,7 +119,6 @@ surface and zero-copy texture import, land before the cut. - [Pre-cut audit findings](/quest/m1/cut-audit/README.md) - fix the crashes, hostile-input costs, and correctness bugs the 2026-10-24 audit of main found - [Cancelled moq-transport requests stop](/quest/m1/ietf-request-cancel.md) - a cancelled request releases its state even when the peer withholds credit - [Empty segments refused](/quest/m1/empty-segments.md) - `room//cam` fails loud instead of naming `room/cam` -- [In-band auth](/quest/m1/auth/README.md) - a session tells its peer what it may publish and subscribe to, unions tokens presented in band, and fails loud on an out-of-scope publish - [Cluster routing](/quest/m1/cluster-routing/README.md) - prove shared routing contracts, implement per-origin routes, and connect outbound local clusters - [Routing guide](/quest/m1/routing-guide.md) - concepts and practical outbound federation setup - [moq-c at parity](/quest/m1/c/README.md) - the hand-written `moq-c` ships at the cut with every m1 binding feature moq-ffi gains diff --git a/quest/m1/api-audit/net-names.md b/quest/m1/api-audit/net-names.md index c50b5328a95..51603569645 100644 --- a/quest/m1/api-audit/net-names.md +++ b/quest/m1/api-audit/net-names.md @@ -26,8 +26,7 @@ Decided 2026-10-23 (API audit follow-up, maintainer): `session::Stats` reads them from it. `StatsUnavailable` goes; the trait method gets a default. - **Credential.** `auth::Auth` (JS `Auth.Auth`) is one presented credential: - `auth::Credential` in Rust, JS, and the FFI. Update the - [auth epic](/quest/m1/auth/README.md), which uses the old name. + `auth::Credential` in Rust, JS, and the FFI. - **Info.** `track::Consumer::query() -> Pending` becomes `info() -> Pending`, mirroring JS `Track.Consumer.info()`. `Pending` stays generic over the task so poll callers and `track()` keep diff --git a/quest/m1/auth/README.md b/quest/m1/auth/README.md deleted file mode 100644 index 4e1bfadb816..00000000000 --- a/quest/m1/auth/README.md +++ /dev/null @@ -1,169 +0,0 @@ -# In-band auth - -## Goal - -A session tells its peer what that peer may publish and subscribe to, and a -peer can present credentials without reconnecting. Today a publisher whose -token allows `baz` but who publishes `foo/bar` waits forever: the relay only -solicits announcements for the granted prefixes, nothing is written or logged -on either side, and moq-lite has no announce refusal at all. Tokens ride the -URL, so a session can never outlive its credential and a client holding two -tokens needs two connections. On-demand publishing needs the missing half of -this: a publisher must know it is authorized before demand arrives, so silence -means "nobody wants it yet" instead of "nobody ever will". - -This questline adds an AUTH exchange to both wires: one stream per token, a -grant per token, the union of every accepted token as the session's scope, -and a loud failure when a publish can never be honored. It ends with extra -credentials able to travel in band, while the first rides SETUP, or the URL -for peers that predate the SETUP token. Key-bound peer grants for direct sessions belong to -[P2P](/quest/m2/p2p/peer-grant.md), their only consumer. - -## Plan - -Decisions settled while planning, recorded so review does not relitigate them: - -- ✅ Decided 2026-10-15 (maintainer, #5148): **one kind of auth.** A token - is presented, verified by the acceptor through `requests()`, and earns a - grant with a lifetime. An AUTH stream's token lives for the session and - its grant joins the session scope. A moq-transport `AUTHORIZATION TOKEN` - on a request is the same kind of auth, scoped to that request: it admits - only that request, never joins the scope, and ends with it. A - SUBSCRIBE_UPDATE or REQUEST_UPDATE carrying a new token replaces it. - Per-request tokens are moq-transport's naive form and are not surfaced as - a separate API. -- ✅ Decided 2026-10-19 (maintainer, closing - [#5927](https://github.com/moq-dev/moq/pull/5927)): **no per-request auth - on moq-lite.** Lite AUTH carries no ID and lite requests no `Auth` field, - so no request spends a byte on auth. moq-transport's per-request token - stays an acceptor-side mapping onto lite's model and never becomes a lite - wire feature. -- ✅ Decided 2026-10-15 (maintainer, #5148), narrowed 2026-10-19 (#5927): a - request without its own token is admitted by the union of session-lifetime - auths only, which on moq-lite is every request. A moq-transport request - carrying a token is held to that token's grant, inside the scope or not, - and ends when the token does. -- ✅ Decided 2026-10-15 (maintainer, #5148), revised 2026-10-19 (#5927): the - work lands in steps. Step 1 (#5148) is incoming only: request tokens - arrive on `requests()`, a moq-transport request is held to its token's - grant, an update's token replaces it, and no lite wire changes. Step 2, - lite requests naming an AUTH stream, is dropped; what it would have closed, - a request racing the token it relies on, landed as a presenter-side wait in - [#5992](https://github.com/moq-dev/moq/pull/5992). Step 3 - sends outgoing request tokens on moq-transport through `Route::auth` as - `USE_VALUE` ([#5695](https://github.com/moq-dev/moq/pull/5695)); - lite has nothing to send, since the token already sits in the union. -- ✅ Decided 2026-10-15 (maintainer, #5148): `auth::Handle::authorize` - keeps its name and now means the connection credential's grant; the - session adds every grant it issued to an AUTH token itself. -- ✅ Decided 2026-10-15 (maintainer, #5148): a typed (CAT etc.) or empty - request token is refused `NOT_SUPPORTED`. An AUTH token has no type, and - an empty one means the connection's own credential. -- ✅ Decided 2026-10-15 (maintainer, #5148): moq-relay verifies request - tokens in band like any token; ending a request token's lease with its - request at the auth server stays in - [Request leases](/quest/m3/auth-request-lease.md). -- ✅ Decided 2026-10-15 (maintainer, #5148): no cap on pending tokens. The - peer's credit bounds them: each AUTH token holds its stream open, and each - request token its request's slot, until answered or withdrawn. -- **One AUTH stream per token, opened by whoever presents it.** Either side of - a session may open one; the acceptor answers with the grant that token - earns. A moq-net session opens one on both sides right after SETUP with an - empty token, meaning the credential the connection already presented (the - SETUP token, URL `?jwt=`, mTLS, or nothing), so a publish-only client learns it may subscribe - to nothing and a relay learns which role its peer will ever play. This is - also the answer to - [moq-wg #1854](https://github.com/moq-wg/moq-transport/issues/1854): the - grant names the peer's role in transport. -- **Tokens union.** A client with two tokens opens two streams and the - session's scope is the union of both grants. Refresh adds a new token; - closing a stream withdraws it. Expiry, revocation, or withdrawal recomputes - the union and cancels publications and subscriptions that lose authorization. - Other authorized work continues on the same session. An empty union leaves - the session connected with no access, so it can accept a fresh token. - `auth::Handle::authorize` is the common resize operation; relay token handling - uses it rather than shipping a temporary close-on-shrink policy. -- **A public grant contains publish patterns, subscribe patterns, and an - expiry**, in the presenter's own root; the presenter never sees the relay-side - root, and every token in a union shares the connection's root. Unscoped - permission is `**`; an empty union grants nothing. Lite AUTH_OK carries - those patterns, wildcards and literals alike, from the first release, with - no covering-prefix workaround. IETF AUTH_OK carries the same patterns with - the same encoding (draft-lcurley-moq-auth-01, revised 2026-10-23 from Track - Namespace prefixes, #6566). Announce stays a prefix: - ANNOUNCE_REQUEST and SUBSCRIBE_NAMESPACE do not gain patterns. The public - grant type stays pattern-valued. -- **Fail loud by aborting the session.** A publisher whose origin announces a - broadcast outside the union aborts the session with `Unauthorized`, naming - the path. The check runs against the grants in hand once every token the - session presented is answered, setup, replayed, or app-added alike - ([#5992](https://github.com/moq-dev/moq/pull/5992)). The origin is - untouched, so a broadcast shared across sessions (P2P hops, a cluster) is - refused only where it is refused. Grant shrinkage cancels previously - authorized work on this session without aborting it or deleting the shared - origin; this is distinct from attempting a new unauthorized publication. - Apps that want to decide themselves read the grant instead. -- **The first token rides SETUP.** ✅ Decided 2026-10-19 (maintainer, - #5972): the connection credential goes in the client's SETUP (a - lite-07-wip SETUP parameter, moq-transport's AUTHORIZATION TOKEN option), - which the acceptor already reads before serving the session, so it costs - no round trip and a session's first requests wait on no AUTH. The URL is - fixed before the version is negotiated, so it carries the token as a - fallback while any offered version lacks the SETUP token. Extra tokens go - in band and are simply absent on an old peer. Nothing is refused and - nothing is silent. This replaces the earlier "always in the CONNECT - request" decision and its auth-header plan. -- **Cluster peers keep mTLS.** A relay opens AUTH toward its peer with an empty - token like any client; AUTH reports the grant actually admitted in each - direction. The next mTLS scope quest can restrict or refuse it. A v1 endpoint - must explicitly grant `**` for unrestricted access; AUTH does not widen a - scoped grant because the caller is another relay. Mesh dials use the default - version set, which leaves out `moq-lite-07-wip`, so this applies once lite-07 - is cut or a cluster opts in. -- **Client API.** Tokens live on `moq_tokio::connect::Config`, the - dial-side config. `Connection::auth()` is a handle the connection owns: it - keeps every added token, presents them on each session as it reconnects, - and reports the live session's grant. -- **Spec home.** The AUTH stream is core in the wip lite version - (`moq-lite-07-wip` today) in `drafts/draft-lcurley-moq-lite.md`, the way - routing is. moq-transport gets - `drafts/draft-lcurley-moq-auth.md`, a setup-option-negotiated extension with - AUTH, AUTH_OK, and AUTH_ERROR control messages, mirroring how moq-cluster is - the IETF binding of lite's routing. -- **Naming.** Messages are AUTH / AUTH_OK / AUTH_ERROR like SUBSCRIBE / - SUBSCRIBE_OK. Rust is `moq_net::auth` with `auth::Grant`, `auth::Handle`, - `auth::Token`, and `auth::Request`; JS mirrors as `connection.auth`. - -`Session::auth()` is additive. The relay derives the grant -from the origin handles it already scopes. Decided 2026-10-05: wire -work targets the wip lite version until the maintainer cuts it, never a -published version in place, so AUTH lands in `moq-lite-07-wip` (or whichever -version is wip then), not lite-06. The UNAUTHORIZED stream code stays on lite-06 -(#5004), since a relay can narrow a session with no Auth Stream; it is 0x3B, -because `main` assigned 0x3A to NOT_FETCHABLE first. - -## Required - -- [Binding auth polish](/quest/m1/auth/bindings-polish.md) - OBS reconnects with the presented token, Swift grant sequences - -## Related - -- [Request leases](/quest/m3/auth-request-lease.md) - deferred auth-server - accounting that ends a request token's lease with its request -- [Request tokens beyond Rust](/quest/m3/request-token-surfaces.md) - JS, moq-ffi, - and moq-cli request-token APIs, when a consumer needs one -- [Token on FETCH](/quest/m3/auth-token-fetch.md) - TRACK_STATUS and FETCH carry - and honor a request token, deferred until a consumer asks -- [#5107](https://github.com/moq-dev/moq/pull/5107) - landed request-token - decoding, including session-fatal REQUEST_UPDATE decode failures -- [#5106](https://github.com/moq-dev/moq/pull/5106) - landed setup extension - configuration -- [Malformed grant](https://github.com/moq-dev/moq/pull/5256) - a malformed or - non-canonical grant pattern, or an out-of-range `Expires`, closes the - session with PROTOCOL_VIOLATION in Rust and JS -- [JS fetch grant watch](https://github.com/moq-dev/moq/pull/5260) - a JS `fetchGroup` ends `Unauthorized` when its path leaves the grant - -- [Peer grants](/quest/m2/p2p/peer-grant.md) - P2P's key-bound credential, - built on this line's relay tokens - -- [#5269](https://github.com/moq-dev/moq/pull/5269) - explicit Lite AUTH NOT_SUPPORTED, including grant updates diff --git a/quest/m1/auth/bindings-polish.md b/quest/m1/auth/bindings-polish.md deleted file mode 100644 index 4101abd70bd..00000000000 --- a/quest/m1/auth/bindings-polish.md +++ /dev/null @@ -1,20 +0,0 @@ -# [S] Binding auth polish - -## Goal - -Two gaps left by [moq-dev/moq#6137](https://github.com/moq-dev/moq/pull/6137) -close: OBS reconnects with the token the user last presented, and Swift -exposes grants as an `AsyncSequence`. - -## Plan - -Decided 2026-10-21 with the maintainer: one m1 quest. - -- **OBS reconnect.** A reconnect dials the URL's original token, not the one - presented mid-stream through `MoQOutput::PresentToken`. Once tokens can - ride SETUP, the presented token replaces it on reconnect. -- **Swift.** Grants arrive as an `AsyncSequence`, once the generated types - are `Sendable`. If they still are not, say why in the PR rather than - forcing it. - -Public API: Swift additive. Wire: none. diff --git a/quest/m1/cut-audit/lite-wire-nits.md b/quest/m1/cut-audit/lite-wire-nits.md index d386e940003..ee0af259279 100644 --- a/quest/m1/cut-audit/lite-wire-nits.md +++ b/quest/m1/cut-audit/lite-wire-nits.md @@ -12,7 +12,7 @@ decoding is gone. Found by the 2026-10-24 pre-cut audit at 151a529670, all source-inferred. - **UNAUTHORIZED (0x3B)** is sent on lite-05/06 (`rs/moq-net/src/lite/error.rs:281`, - no version gate), as [In-band auth](/quest/m1/auth/README.md) decided + no version gate), as the in-band auth plan decided ([moq-dev/moq#5004](https://github.com/moq-dev/moq/pull/5004)), but the draft's changelog lists it under lite-07 only. Fix the draft. - **Implementation (0x6) SETUP parameter** is parsed on lite-05/06 diff --git a/quest/m2/p2p/peer-grant.md b/quest/m2/p2p/peer-grant.md index d06a9c88eec..072c0b8b1b0 100644 --- a/quest/m2/p2p/peer-grant.md +++ b/quest/m2/p2p/peer-grant.md @@ -77,7 +77,3 @@ valid proof onto another session is refused; a refreshed grant replaces the old one without dropping the session. Additive. - -## Required - -- [In-band auth](/quest/m1/auth/README.md) - relay tokens reach `main` with this line, so the relay owns AUTH and knows the session's paths diff --git a/quest/m2/rate-grant.md b/quest/m2/rate-grant.md index f89611d4031..1295b89c771 100644 --- a/quest/m2/rate-grant.md +++ b/quest/m2/rate-grant.md @@ -42,5 +42,4 @@ rates, on the next unpublished lite version after lite-07 only. ## Required -- [In-band auth](/quest/m1/auth/README.md) - the AUTH grant this extends - [QUIC caps](/quest/m2/rate-quic.md) - reintroduces the moq-auth cap type the grant carries diff --git a/quest/m3/request-token-surfaces.md b/quest/m3/request-token-surfaces.md index 2d6f60dace7..8694761da79 100644 --- a/quest/m3/request-token-surfaces.md +++ b/quest/m3/request-token-surfaces.md @@ -18,7 +18,7 @@ or acceptor to mirror. So each surface here exposes that unified shape once Rust has it, and only for the surface a named consumer uses. Start by asking that consumer which surface it needs. Do not build all three. Through moq-ffi, follow the session -AUTH shape of `MoqAuth` in `rs/moq-ffi/src/auth.rs`. Update every +AUTH shape: `MoqSession.tokens()` and `MoqSession.grants()`. Update every wrapper, as the cross-package table requires. Public API: whatever the chosen surface needs to present and accept auths diff --git a/rs/moq-c/src/client.rs b/rs/moq-c/src/client.rs index 0480c81f8bf..27b37c03c1f 100644 --- a/rs/moq-c/src/client.rs +++ b/rs/moq-c/src/client.rs @@ -69,7 +69,7 @@ pub unsafe fn parse_client(config: Option<&moq_client_config>) -> Result>()?; diff --git a/rs/moq-ffi/src/auth.rs b/rs/moq-ffi/src/auth.rs index 2ebcfadf6b2..cb14a9d88ef 100644 --- a/rs/moq-ffi/src/auth.rs +++ b/rs/moq-ffi/src/auth.rs @@ -1,6 +1,4 @@ -//! In-band authorization: what the peer lets a session do, and more tokens to present. - -use std::sync::Arc; +//! What the peer lets a session do. use crate::error::MoqError; use crate::ffi::Task; @@ -31,138 +29,52 @@ impl From for MoqGrant { } } -/// Present `token` on every session of `handle`, resolving once a peer accepts it. -async fn add(handle: moq_net::auth::Handle, token: String) -> Result { - // Without AUTH, moq-transport accepts a token only for the requests that name it, but - // nothing here can name one, so it would never be sent. The answer says how the peer - // accepted it, which a grant missing after its session drops cannot. - match handle.add(token).await? { - (auth, moq_net::auth::Answer::Granted) => Ok(auth), - (_, moq_net::auth::Answer::Requests) => Err(MoqError::Unsupported), - } -} - -/// Poll `future` once without waiting. -fn poll_now(future: F) -> std::task::Poll { - let future = std::pin::pin!(future); - std::future::Future::poll(future, &mut std::task::Context::from_waker(std::task::Waker::noop())) -} - -/// A session's authorization: the grant its peer gave it, and more tokens to present. +/// Follows the grant a session's peer gave it: the union of every token the session +/// presented. /// -/// Returned by [`MoqSession::auth`](crate::session::MoqSession::auth). AUTH is only on +/// 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`. #[derive(uniffi::Object)] -pub struct MoqAuth { - handle: moq_net::auth::Handle, +pub struct MoqGrantConsumer { /// The watch behind [`grant`](Self::grant), which reads without the lock. peek: moq_net::auth::Watch, - /// The watch behind [`grant_changed`](Self::grant_changed), which tracks what this - /// handle last reported. Concurrent callers share it, so each watcher takes its own handle. + /// The watch behind [`changed`](Self::changed), which tracks what it last returned. changed: Task, } -impl MoqAuth { - pub(crate) fn new(handle: moq_net::auth::Handle) -> Self { - // Start from the grant as it is now, so a watcher reads that with `grant` and waits - // in `grant_changed` only for what follows, never for the same grant twice. - let mut changed = handle.grant(); - let _ = poll_now(changed.changed()); +impl MoqGrantConsumer { + pub(crate) fn new(handle: &moq_net::auth::Handle) -> Self { Self { peek: handle.grant(), - changed: Task::new(changed), - handle, + changed: Task::new(handle.grant()), } } } #[uniffi::export] -impl MoqAuth { - /// The union of every token's grant, or `None` until the peer first answers one. - /// - /// A client session reads `None` while it reconnects. +impl MoqGrantConsumer { + /// The grant now, or `None` until the peer first answers a token. A client session reads + /// `None` while it reconnects. pub fn grant(&self) -> Option { let _guard = crate::ffi::enter(); self.peek.peek().map(Into::into) } - /// Wait for the grant to differ from the one this handle last reported, or held when it was + /// Wait for the grant to differ from the one this last returned, or held when it was /// made, returning it. /// - /// Calls on one handle share what it last reported; an independent watcher takes its own - /// handle from [`MoqSession::auth`](crate::session::MoqSession::auth). - /// - /// Errors once nothing will change it again: a client's connection or a server's session - /// ended. A reconnect is not an end. - pub async fn grant_changed(&self) -> Result, MoqError> { + /// Errors once nothing will change it again: a client's connection or a server's + /// session ended, or [`cancel`](Self::cancel). A reconnect is not an end. + pub async fn changed(&self) -> Result, MoqError> { self.changed .run(|mut watch| async move { Ok(watch.changed().await?.map(Into::into)) }) .await } - /// Present another token, resolving once the peer accepts it. - /// - /// Its grant joins the union until [`MoqAuthToken::cancel`]. A client session presents it - /// again on every reconnect. The peer's refusal is a [`MoqError::Protocol`] carrying its code. - /// - /// # Errors - /// - /// [`MoqError::Unsupported`] when the session cannot carry another token: a version - /// without AUTH, or moq-transport without the MoQ Auth extension. - pub async fn add(&self, token: String) -> Result, MoqError> { - let handle = self.handle.clone(); - let token = crate::ffi::detached(add(handle, token)).await?; - Ok(Arc::new(MoqAuthToken::new(token))) - } -} - -/// One token presented with [`MoqAuth::add`]. -/// -/// It stays presented until [`cancel`](Self::cancel), or until the handle is released. -#[derive(uniffi::Object)] -pub struct MoqAuthToken { - /// The watch behind [`grant`](Self::grant), which does not keep the token presented. - peek: moq_net::auth::Watch, - token: Task, -} - -impl MoqAuthToken { - fn new(token: moq_net::auth::Auth) -> Self { - Self { - peek: token.grant(), - token: Task::new(token), - } - } -} - -#[uniffi::export] -impl MoqAuthToken { - /// This token's own grant, or `None` while the peer has not answered it or after it ended. - pub fn grant(&self) -> Option { - let _guard = crate::ffi::enter(); - self.peek.peek().map(Into::into) - } - - /// Wait for the token to end: `Ok` when the peer closed it without an error, the peer's - /// revocation as [`MoqError::Protocol`], or the end of a client's connection or a server's - /// session as an error. A reconnect does not end it. - pub async fn closed(&self) -> Result<(), MoqError> { - self.token - .run(|token| async move { - match token.closed().await { - moq_net::Error::Cancel => Ok(()), - err => Err(err.into()), - } - }) - .await - } - - /// Withdraw the token, removing its grant from the union. - /// - /// Terminal: the token is withdrawn here, not when the handle is. + /// Cancel all current and future [`changed`](Self::changed) calls. pub fn cancel(&self) { - self.token.cancel(); + self.changed.cancel(); } } @@ -170,86 +82,22 @@ impl MoqAuthToken { mod tests { use std::time::Duration; - use crate::session::{MoqClient, MoqClientConfig}; - - const TIMEOUT: Duration = Duration::from_secs(10); - - /// Wait until `auth` reports `want`, following its changes. - async fn await_grant(auth: &super::MoqAuth, want: Option>) { - let publish = || auth.grant().map(|grant| grant.publish); - tokio::time::timeout(TIMEOUT, async { - while publish() != want { - auth.grant_changed().await.expect("grant watch ended"); - } - }) - .await - .unwrap_or_else(|_| panic!("timed out waiting for {want:?}, last {:?}", publish())); - } - - /// A token the peer granted is not refused as request-only when its session drops before - /// `add` reads the answer, though its grant then reads `None`. + /// Cancelling releases a wait no grant change will end. #[tokio::test] - async fn a_grant_survives_its_session_dropping_before_add_returns() { - let version: moq_net::Version = "moq-lite-07-wip".parse().unwrap(); - let mut config = moq_tokio::listen::Config::default(); - config.tcp.bind = Some("127.0.0.1:0".parse().unwrap()); - config.version = vec![version]; - let mut listener = config.init(Default::default()).unwrap().listen().await.unwrap(); - let addr = listener.tcp_local_addr().unwrap(); - - let (drop_tx, drop_rx) = tokio::sync::oneshot::channel::<()>(); - let serving = tokio::spawn(async move { - let mut request = listener.accept().await.expect("accept"); - // Nothing redials: the client stays disconnected once the session drops. - drop(listener); - let mut requests = request.requests(); - let session = request.ok().await.unwrap(); - let mut issued = Vec::new(); - for _ in 0..2 { - let request = requests.next().await.expect("token"); - let pattern = match request.token().as_ref() { - b"" => "setup/**", - _ => "extra/**", - }; - issued.push(request.accept(moq_net::auth::Grant { - publish: pattern.parse::().unwrap().into(), - ..Default::default() - })); - } - let _ = drop_rx.await; - drop((session, issued, requests)); + async fn cancel_ends_a_pending_wait() { + let handle = moq_net::auth::Handle::new(); + let grants = std::sync::Arc::new(super::MoqGrantConsumer::new(&handle)); + let waiting = tokio::spawn({ + let grants = grants.clone(); + async move { grants.changed().await } }); - - let client = MoqClient::new(MoqClientConfig { - versions: vec!["moq-lite-07-wip".into()], - bind: Some("127.0.0.1:0".into()), - ..Default::default() - }) - .unwrap(); - let session = tokio::time::timeout(TIMEOUT, client.connect(format!("tcp://{addr}"))) - .await - .expect("connect timed out") - .unwrap(); - let auth = session.auth(); - await_grant(&auth, Some(vec!["setup/**".into()])).await; - - // Presented and granted, but not read until the session is gone. - let mut adding = Box::pin(super::add(auth.handle.clone(), "extra".into())); - assert!(super::poll_now(adding.as_mut()).is_pending()); - await_grant(&auth, Some(vec!["extra/**".into(), "setup/**".into()])).await; - drop_tx.send(()).unwrap(); - await_grant(&auth, None).await; - - let std::task::Poll::Ready(added) = super::poll_now(adding.as_mut()) else { - panic!("add did not resolve"); - }; - let token = added.expect("a granted token refused after its session dropped"); - assert_eq!(token.grant().peek(), None, "no session is live"); - - session.cancel(0); - tokio::time::timeout(TIMEOUT, serving) + // Let the wait park before cancelling it. + tokio::task::yield_now().await; + grants.cancel(); + let result = tokio::time::timeout(Duration::from_secs(5), waiting) .await - .expect("server ended") + .expect("the wait outlived its cancel") .unwrap(); + assert!(matches!(result, Err(crate::error::MoqError::Cancelled)), "{result:?}"); } } diff --git a/rs/moq-ffi/src/server.rs b/rs/moq-ffi/src/server.rs index 9922b97d3bc..1869f70bdee 100644 --- a/rs/moq-ffi/src/server.rs +++ b/rs/moq-ffi/src/server.rs @@ -597,9 +597,10 @@ mod lifecycle_tests { subscribe: vec!["**".into()], expires: None, }; - for auth in [peer.auth(), session.auth()] { - while auth.grant().as_ref() != Some(&everything) { - pollster::block_on(auth.grant_changed()).unwrap(); + for grants in [peer.grants(), session.grants()] { + let mut grant = grants.grant(); + while grant.as_ref() != Some(&everything) { + grant = pollster::block_on(grants.changed()).unwrap(); } } peer.cancel(0); diff --git a/rs/moq-ffi/src/session.rs b/rs/moq-ffi/src/session.rs index 1469ac10307..37532de90de 100644 --- a/rs/moq-ffi/src/session.rs +++ b/rs/moq-ffi/src/session.rs @@ -5,7 +5,7 @@ use std::time::Duration; use url::Url; -use crate::auth::MoqAuth; +use crate::auth::MoqGrantConsumer; use crate::bandwidth::MoqBandwidth; use crate::error::MoqError; use crate::ffi::Task; @@ -31,9 +31,9 @@ pub struct MoqClientConfig { /// Empty offers every supported version; [`moq_versions`] lists them. #[uniffi(default = [])] pub versions: Vec, - /// Credentials every dial presents. The first is the connection credential, unless the URL - /// carries its own `?jwt=`; each other one widens the session's grant. Replace them through - /// [`MoqClient::tokens`]. + /// Credentials each session's dials present. The first is the connection credential, unless + /// the URL carries its own `?jwt=`; each other one widens the session's grant. Replace a + /// session's through [`MoqSession::tokens`]. #[uniffi(default = [])] pub tokens: Vec, /// How long one connect may take, dial and handshake together. 0 waits forever. @@ -316,13 +316,13 @@ pub(crate) fn parse_versions(versions: &[String]) -> Result) -> Result, MoqError> { +fn parse_tokens(tokens: Vec) -> Result, MoqError> { tokens .into_iter() .map(|token| { token .try_into() - .map_err(|err: moq_tokio::connect::EmptyToken| MoqError::Config { + .map_err(|err: moq_net::auth::EmptyToken| MoqError::Config { reason: err.to_string(), }) }) @@ -612,11 +612,14 @@ mod tests { } } - #[test] - fn setting_tokens_refuses_an_empty_token() { - let tokens = MoqClient::new(MoqClientConfig::default()).unwrap().tokens(); + #[tokio::test] + async fn setting_tokens_refuses_an_empty_token() { + let client = MoqClient::new(MoqClientConfig::default()).unwrap(); + let session = client.connect("moqt://localhost:1/".into()).await.unwrap(); + let tokens = session.tokens().expect("a client session has tokens"); tokens.set(vec!["a".into(), "b".into()]).unwrap(); assert!(matches!(tokens.set(vec![String::new()]), Err(MoqError::Config { .. }))); + session.cancel(0); } #[test] @@ -782,10 +785,6 @@ fn decode_hex(hex: &str) -> Result, MoqError> { #[derive(uniffi::Object)] pub struct MoqClient { task: Task, - /// Held outside the task, which a connect holds for as long as it dials, so a refresh - /// can land mid-dial. - #[cfg(not(target_arch = "wasm32"))] - tokens: moq_tokio::connect::Tokens, } #[uniffi::export] @@ -795,20 +794,10 @@ impl MoqClient { pub fn new(config: MoqClientConfig) -> Result, MoqError> { let client = Client::new(config)?; Ok(Arc::new(Self { - #[cfg(not(target_arch = "wasm32"))] - tokens: client.client.tokens(), task: Task::new(client), })) } - /// The credentials every dial presents, to replace while running. - pub fn tokens(&self) -> Arc { - Arc::new(MoqTokens { - #[cfg(not(target_arch = "wasm32"))] - inner: self.tokens.clone(), - }) - } - /// Start a connection without waiting for its first dial to succeed. /// /// A native session automatically reconnects with backoff when the transport drops @@ -835,21 +824,24 @@ impl MoqClient { } } -/// The credentials a [`MoqClient`] presents, replaceable while it runs. +/// The credentials a native client session presents, replaceable while it runs. +/// +/// Returned by [`MoqSession::tokens`], seeded from [`MoqClientConfig::tokens`]. #[derive(uniffi::Object)] pub struct MoqTokens { #[cfg(not(target_arch = "wasm32"))] - inner: moq_tokio::connect::Tokens, + inner: moq_net::auth::Tokens, } #[uniffi::export] impl MoqTokens { /// Replace the credentials every dial presents, such as before the current ones expire. /// - /// The next dial presents them, and a live session that supports in-band AUTH presents - /// them at once, withdrawing each replaced token once its replacements are answered, - /// even when one is refused. After an authorization refusal the client redials only if - /// they changed. A browser client has no tokens to replace, so this fails `Unsupported`. + /// The first is the connection credential, unless the URL carries its own `?jwt=`; each + /// other one widens the grant over in-band AUTH. The next dial presents them, and a live + /// session that supports in-band AUTH presents them at once, withdrawing each replaced + /// token once its replacements are answered, even when one is refused. After an + /// authorization refusal the session redials only if they changed. pub fn set(&self, tokens: Vec) -> Result<(), MoqError> { #[cfg(not(target_arch = "wasm32"))] { @@ -862,6 +854,25 @@ impl MoqTokens { Err(MoqError::Unsupported) } } + + /// Wait for the peer's first verdict on the tokens the last [`set`](Self::set) newly + /// presented: `Ok` once each is granted, in band or as a later dial's connection credential. + /// + /// A token the set kept counts only once refused, and nothing is re-checked after the + /// answer. The peer's refusal is a [`MoqError::Protocol`] carrying its code, + /// [`MoqError::Unsupported`] when the session cannot carry an in-band token, and the + /// connection's end, such as a refused dial, is its close reason. + pub async fn answered(&self) -> Result<(), MoqError> { + #[cfg(not(target_arch = "wasm32"))] + { + let tokens = self.inner.clone(); + crate::ffi::detached(async move { tokens.answered().await.map_err(MoqError::from) }).await + } + #[cfg(target_arch = "wasm32")] + { + Err(MoqError::Unsupported) + } + } } /// A snapshot of connection statistics for a [`MoqSession`]. @@ -1300,14 +1311,12 @@ impl MoqSession { self.bandwidth.clone() } - /// The session's authorization: the grant its peer gave it, and more tokens to present. + /// Follow the grant the peer gave this session. /// - /// Every call returns a new handle sharing the session's tokens, which tracks its own - /// [`grant_changed`](MoqAuth::grant_changed), so concurrent watchers each take one. A client - /// session's handle survives reconnects, presenting each added token again on every new - /// connection. - pub fn auth(&self) -> Arc { - Arc::new(MoqAuth::new(match &self.inner { + /// Every call returns an independent consumer. A client session's grant follows each + /// reconnect, reading `None` while offline. + pub fn grants(&self) -> Arc { + Arc::new(MoqGrantConsumer::new(&match &self.inner { #[cfg(not(target_arch = "wasm32"))] Inner::Connection(connection) => connection.auth(), #[cfg(not(target_arch = "wasm32"))] @@ -1317,6 +1326,23 @@ impl MoqSession { })) } + /// The credentials a native client session presents, to replace while it runs. + /// + /// `None` for a server-accepted session, which presents none, and in the browser, where + /// the URL carries the credential. + pub fn tokens(&self) -> Option> { + match &self.inner { + #[cfg(not(target_arch = "wasm32"))] + Inner::Connection(connection) => Some(Arc::new(MoqTokens { + inner: connection.tokens(), + })), + #[cfg(not(target_arch = "wasm32"))] + Inner::Session(_) => None, + #[cfg(target_arch = "wasm32")] + Inner::Dial(_) => None, + } + } + /// Hold receive-estimate demand until the returned consumer is released. pub fn recv_bandwidth(&self) -> Option> { let consumer = match &self.inner { diff --git a/rs/moq-ffi/src/session/dial.rs b/rs/moq-ffi/src/session/dial.rs index d2a721041a7..29de99511dd 100644 --- a/rs/moq-ffi/src/session/dial.rs +++ b/rs/moq-ffi/src/session/dial.rs @@ -50,8 +50,8 @@ pub(crate) struct Dial { bandwidth: moq_net::bandwidth::Allocator, /// The session's receive estimate, forwarded while a consumer holds it. recv: moq_net::bandwidth::Weak, - /// Persistent from before the handshake, so a token added while dialing waits for the - /// session; ended with the dial. + /// Persistent from before the handshake, so a grant consumer taken while dialing follows + /// the session; ended with the dial. auth: moq_net::auth::Handle, } diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 64c0be82ddd..0ad83d2ce38 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -7955,14 +7955,12 @@ async fn ascending_subscription_reads_a_cached_backlog_oldest_first() { /// Wait until `session` grants `want`, following its changes. async fn await_grant(session: &MoqSession, want: crate::auth::MoqGrant) { - // `grant_changed` waits for a grant other than the one its handle last returned, which a - // read through `grant` does not move. A fresh handle starts from the grant as it is now, - // so it is taken before the read, and the loop follows what `grant_changed` returns. - let auth = session.auth(); - let mut current = auth.grant(); + // A fresh consumer starts from the grant as it is now, so `changed` follows from there. + let grants = session.grants(); + let mut current = grants.grant(); tokio::time::timeout(TIMEOUT, async { while current.as_ref() != Some(&want) { - current = auth.grant_changed().await.expect("grant watch ended"); + current = grants.changed().await.expect("grant watch ended"); } }) .await @@ -7978,6 +7976,14 @@ fn grant(publish: &[&str], subscribe: &[&str]) -> crate::auth::MoqGrant { } } +/// The peer's answer to the tokens set last. +async fn answered(session: &MoqSession) -> Result<(), MoqError> { + let tokens = session.tokens().expect("a client session has tokens"); + tokio::time::timeout(TIMEOUT, tokens.answered()) + .await + .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. @@ -7996,15 +8002,17 @@ async fn auth_reads_the_peer_grant_on(version: &str) { // Each side's origins span the root, so its peer grants it everything. await_grant(&client, grant(&["**"], &["**"])).await; await_grant(&accepted, grant(&["**"], &["**"])).await; + assert!(accepted.tokens().is_none(), "an accepted session presents no tokens"); - let err = tokio::time::timeout(TIMEOUT, client.auth().add("extra".into())) + // The live session was dialed without a credential, so this one rides AUTH. + let tokens = client.tokens().unwrap(); + tokens.set(vec!["extra".into()]).unwrap(); + let err = answered(&client) .await - .expect("add timed out") - .err() - .expect("the default acceptor refuses a token"); + .expect_err("the default acceptor refuses a token"); assert!(matches!(err, MoqError::Unsupported), "refusal: {err:?}"); assert_eq!( - client.auth().grant(), + client.grants().grant(), Some(grant(&["**"], &["**"])), "a refusal leaves the union" ); @@ -8015,20 +8023,17 @@ async fn auth_reads_the_peer_grant_on(version: &str) { } /// moq-transport without the Auth extension carries a token only on a request that names it, -/// which no binding can, so both sides refuse one rather than report a token nothing sends. +/// which no binding can, so the answer is that the session cannot carry it. #[tokio::test] async fn auth_refuses_a_token_nothing_carries() { let (server, client, accepted) = tokio::time::timeout(TIMEOUT, session_pair("moq-transport-14")) .await .expect("pair"); + client.tokens().unwrap().set(vec!["extra".into()]).unwrap(); + let err = answered(&client).await.expect_err("a token nothing carries is refused"); + assert!(matches!(err, MoqError::Unsupported), "refusal: {err:?}"); for session in [&client, &accepted] { - let err = tokio::time::timeout(TIMEOUT, session.auth().add("extra".into())) - .await - .expect("add timed out") - .err() - .expect("a token nothing carries is refused"); - assert!(matches!(err, MoqError::Unsupported), "refusal: {err:?}"); - assert_eq!(session.auth().grant(), None, "no AUTH, no grant"); + assert_eq!(session.grants().grant(), None, "no AUTH, no grant"); } client.cancel(0); @@ -8036,8 +8041,8 @@ async fn auth_refuses_a_token_nothing_carries() { server.cancel(); } -/// A token added through a client session joins the union with its own grant, leaves it on -/// cancel, and a refusal or revocation carries the peer's code. +/// A replacement token joins the union once answered, leaves it when replaced, and a +/// refusal carries the peer's code. Each grant consumer follows the changes on its own. #[tokio::test] async fn auth_tokens_join_and_leave_the_union() { let version: moq_net::Version = "moq-lite-07-wip".parse().unwrap(); @@ -8060,11 +8065,6 @@ async fn auth_tokens_join_and_leave_the_union() { match request.token().as_ref() { b"" => issued.push(request.accept(publish("setup/**"))), b"extra" => issued.push(request.accept(publish("extra/**"))), - b"revoked" => request - .accept(publish("revoked/**")) - .revoke(moq_net::SessionError::Expired, "revoked"), - // Dropping the issued grant closes the token without an error. - b"closed" => drop(request.accept(publish("closed/**"))), _ => request.reject(moq_net::SessionError::Unauthorized, "unknown token"), } } @@ -8082,60 +8082,32 @@ async fn auth_tokens_join_and_leave_the_union() { .await .expect("connect timed out") .unwrap(); - let auth = session.auth(); await_grant(&session, grant(&["setup/**"], &[])).await; - // A second handle watches on its own and starts from the grant it was made with. - let watcher = session.auth(); - - let extra = tokio::time::timeout(TIMEOUT, auth.add("extra".into())) - .await - .expect("add timed out") - .unwrap(); - assert_eq!(extra.grant(), Some(grant(&["extra/**"], &[]))); + // A second consumer watches on its own and starts from the grant it was made with. + let watcher = session.grants(); + // The session was dialed without a credential, so the empty set is already answered. + answered(&session).await.expect("no tokens to refuse"); + + let tokens = session.tokens().unwrap(); + tokens.set(vec!["extra".into()]).unwrap(); + answered(&session).await.expect("the extra token was refused"); // Patterns are kept sorted. await_grant(&session, grant(&["extra/**", "setup/**"], &[])).await; - let seen = tokio::time::timeout(TIMEOUT, watcher.grant_changed()) + let seen = tokio::time::timeout(TIMEOUT, watcher.changed()) .await - .expect("the second handle sees the change the first took") + .expect("the second consumer sees the change") .unwrap(); assert_eq!(seen, Some(grant(&["extra/**", "setup/**"], &[]))); - extra.cancel(); - await_grant(&session, grant(&["setup/**"], &[])).await; - assert!(matches!(extra.closed().await, Err(MoqError::Cancelled))); - - let refused = tokio::time::timeout(TIMEOUT, auth.add("bogus".into())) - .await - .expect("add timed out") - .err() - .expect("refused"); + // A refused replacement still withdraws the token it replaces. + tokens.set(vec!["bogus".into()]).unwrap(); + let refused = answered(&session).await.expect_err("refused"); assert_protocol( &refused, crate::error::MoqErrorScope::Session, MoqProtocolKind::Unauthorized, ); - - let revoked = tokio::time::timeout(TIMEOUT, auth.add("revoked".into())) - .await - .expect("add timed out") - .unwrap(); - let closed = tokio::time::timeout(TIMEOUT, revoked.closed()) - .await - .expect("closed timed out") - .unwrap_err(); - assert_protocol(&closed, crate::error::MoqErrorScope::Session, MoqProtocolKind::Expired); - assert_eq!(revoked.grant(), None, "an ended token grants nothing"); - assert_eq!(auth.grant(), Some(grant(&["setup/**"], &[]))); - - let closed = tokio::time::timeout(TIMEOUT, auth.add("closed".into())) - .await - .expect("add timed out") - .unwrap(); - tokio::time::timeout(TIMEOUT, closed.closed()) - .await - .expect("closed timed out") - .expect("a clean close is not an error"); - assert_eq!(auth.grant(), Some(grant(&["setup/**"], &[]))); + await_grant(&session, grant(&["setup/**"], &[])).await; session.cancel(0); tokio::time::timeout(TIMEOUT, serving) diff --git a/rs/moq-net/src/auth.rs b/rs/moq-net/src/auth.rs index b6ad83f0fe8..820062916dc 100644 --- a/rs/moq-net/src/auth.rs +++ b/rs/moq-net/src/auth.rs @@ -45,6 +45,10 @@ use bytes::Bytes; use crate::{Error, Patterns, Result, SessionError, time::Instant}; +mod tokens; + +pub use tokens::{Dial, EmptyToken, Token, Tokens}; + /// Classify malformed AUTH messages separately from transport and local failures. pub(crate) fn protocol_error(err: Error) -> Error { match err { @@ -178,7 +182,7 @@ pub(crate) struct State { closed: Option, next_id: u64, /// Every token the application added that it has not withdrawn. - tokens: BTreeMap, + tokens: BTreeMap, next_link: u64, /// Every session built on this handle that has not dropped, oldest first. links: BTreeMap, @@ -188,10 +192,12 @@ pub(crate) struct State { limit: Option, next_issue: u64, acceptor: Acceptor, + /// The tokens a [`Tokens`] presents on this handle's sessions, when it was built by one. + configured: Option, } /// A token the application added, presented on every session of its handle. -struct Token { +struct Entry { value: Bytes, /// The first verdict any session's peer gave: how it accepted the token, or why it ended. answered: Option>, @@ -227,6 +233,9 @@ struct Attached { /// Bumped whenever the union or the scope changes, so the session's per-stream /// gates can skip re-matching paths on every wakeup. epoch: u64, + /// Whether the peer has accepted the connection, credential included: at once, unless + /// the session [awaits the peer's SETUP](Link::await_setup). + accepted: bool, } /// One token as one session presents it. @@ -296,6 +305,7 @@ impl Attached { issued: BTreeMap::new(), scope: None, epoch: 0, + accepted: true, }; attached.rescope(limit); attached @@ -425,6 +435,10 @@ impl State { if let Some(token) = self.tokens.get_mut(&id) { token.answered.get_or_insert(Ok(answer)); } + if answer == Answer::Requests { + self.unsupported(id); + } + self.settle(); } Err(err) => self.end_token(id, err), } @@ -443,6 +457,44 @@ impl State { for link in self.links.values_mut() { link.end(id, &err); } + if self.closed.is_none() && self.configured(id) { + match err { + Error::Unsupported => self.unsupported(id), + err => tracing::warn!(%err, "a configured token was refused"), + } + } + self.settle(); + } + + /// Register a token and offer it to every open session. + fn present(&mut self, token: Bytes) -> u64 { + let id = self.next_id; + self.next_id += 1; + self.tokens.insert( + id, + Entry { + value: token.clone(), + answered: None, + ended: None, + }, + ); + let answers: Vec<_> = self + .links + .values_mut() + .filter_map(|link| link.offer(id, &token)) + .collect(); + for answer in answers { + self.answer(id, answer.map(|()| Answer::Requests)); + } + id + } + + /// Stop presenting token `id` on every session. + fn withdraw(&mut self, id: u64) { + self.tokens.remove(&id); + for link in self.links.values_mut() { + link.withdraw(id); + } } /// End the handle, returning the application's queue for the caller to close once the @@ -451,6 +503,7 @@ impl State { if self.closed.is_some() { return None; } + self.record(); self.closed = Some(err.clone()); let ids: Vec = self.tokens.keys().copied().collect(); for id in ids { @@ -562,24 +615,7 @@ impl Handle { if state.bound && !state.links.values().any(Attached::active) { return Err(Error::GoingAway); } - let id = state.next_id; - state.next_id += 1; - state.tokens.insert( - id, - Token { - value: token.clone(), - answered: None, - ended: None, - }, - ); - let answers: Vec<_> = state - .links - .values_mut() - .filter_map(|link| link.offer(id, &token)) - .collect(); - for answer in answers { - state.answer(id, answer.map(|()| Answer::Requests)); - } + let id = state.present(token); Ok(Auth { presented: std::sync::Arc::new(Presented { state: self.state.clone(), @@ -717,6 +753,8 @@ impl Drop for Detach { fn drop(&mut self) { let queue = { let mut state = self.state.lock(); + // The link's credential may hold the answer a token set still waits on. + state.record(); state.links.remove(&self.id); // Dropped without closing, such as a driver dropped mid-session. match state.bound { @@ -965,6 +1003,8 @@ impl Link { link.replied = true; link.recompute(); state.answer(id, Ok(Answer::Granted)); + // Latch a set this grant completed, before a later revocation can replace its answer. + state.record(); }); } @@ -1046,6 +1086,8 @@ impl Link { /// leaves it for the next session to present, except on a handle of the session's own. pub(crate) fn ended(&self, id: u64, err: Error) { self.with_state(|state, link_id| { + // Latch a set already complete, so this end never replaces its answer. + state.record(); // A draining session's verdict is stale while an active session still presents the // token: that session's own answer decides, even mid-retry with no grant right now. let superseded = !attached(&mut state.links, link_id).active() @@ -1248,14 +1290,31 @@ impl Link { self.read(|link, _| link.closed.clone()) } + /// The peer accepts the connection credential only with its SETUP, which this client + /// reads after the session is live, while the server can still refuse it. + pub(crate) fn await_setup(&self) { + self.with(|link| link.accepted = false); + } + + /// The peer's SETUP arrived, so it accepted the connection credential. + pub(crate) fn accepted(&self) { + self.with_state(|state, link| { + attached(&mut state.links, link).accepted = true; + // Latch a set this acceptance completed, before a later end can replace its answer. + state.record(); + }); + } + /// End the session: fail every pending token here, leaving the handle's tokens for the /// next session. A handle the session created for itself ends with it. pub(crate) fn close(&self, err: Error) { let queue = self.with_state(|state, link| { - let link = attached(&mut state.links, link); - if link.closed.is_some() { + if state.links[&link].closed.is_some() { return None; } + // The session's credential may hold the answer a token set still waits on. + state.record(); + let link = attached(&mut state.links, link); link.closed = Some(err.clone()); link.opening.clear(); for slot in link.slots.values_mut() { @@ -1385,12 +1444,7 @@ impl Drop for Presented { link.withdraw(self.id); } } - None => { - state.tokens.remove(&self.id); - for link in state.links.values_mut() { - link.withdraw(self.id); - } - } + None => state.withdraw(self.id), } } } diff --git a/rs/moq-net/src/auth/tokens.rs b/rs/moq-net/src/auth/tokens.rs new file mode 100644 index 00000000000..e4dcd789100 --- /dev/null +++ b/rs/moq-net/src/auth/tokens.rs @@ -0,0 +1,957 @@ +//! The tokens a reconnecting connection presents on each session, and the peer's answer. + +use std::task::Poll; + +use bytes::Bytes; +use url::Url; + +use super::{Answer, Handle, State}; +use crate::{Error, Result}; + +/// A credential to present when dialing, such as a JWT. +/// +/// Its `Debug` shows only the length, so a dumped config never leaks it. +#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct Token(String); + +impl Token { + /// The credential itself. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Debug for Token { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Token(<{} bytes>)", self.0.len()) + } +} + +impl std::str::FromStr for Token { + type Err = EmptyToken; + + fn from_str(token: &str) -> std::result::Result { + Self::try_from(token.to_string()) + } +} + +impl TryFrom for Token { + type Error = EmptyToken; + + fn try_from(token: String) -> std::result::Result { + match token.is_empty() { + true => Err(EmptyToken), + false => Ok(Self(token)), + } + } +} + +impl From for String { + fn from(token: Token) -> Self { + token.0 + } +} + +/// An empty token, which presents no credential. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("a token cannot be empty")] +#[non_exhaustive] +pub struct EmptyToken; + +/// The tokens a connection presents on every session it dials, and the peer's answer to them. +/// +/// The first is the connection credential, which each dial carries in SETUP or its URL, +/// unless the URL already has a `?jwt=`. Every other token rides its own AUTH stream on the +/// sessions of [`handle`](Self::handle), widening the grant. Replacing them presents the new +/// ones on the live session at once, withdrawing the ones they replace only after every new +/// one has its answer, so the grant never narrows in between. +/// +/// A reconnect loop builds each session on [`handle`](Self::handle), calls +/// [`dial`](Self::dial) before each dial and [`connected`](Self::connected) once it +/// succeeds, and aborts the handle when it gives up. +/// +/// Cheap to clone; every clone shares one set. +#[derive(Clone)] +pub struct Tokens { + handle: Handle, +} + +/// What one dial presents, from [`Tokens::dial`]. +pub struct Dial { + /// The URL to dial, carrying the connection credential in its query when an offered + /// version has no SETUP token. + pub url: Url, + /// The connection credential for [`Client::with_token`](crate::Client::with_token), unless + /// the URL brought its own. + pub token: Option, + generation: u64, +} + +impl Tokens { + /// Present `tokens` on the sessions of a new [`handle`](Self::handle). + pub fn new(tokens: Vec) -> Self { + let handle = Handle::new(); + handle.state.lock().configured = Some(Configured { + fresh: dedup(&tokens), + tokens, + ..Default::default() + }); + Self { handle } + } + + /// The handle to build each session on, with [`Client::with_auth`](crate::Client::with_auth). + pub fn handle(&self) -> Handle { + self.handle.clone() + } + + /// Replace every token, reaching the live session at once and every later dial. + pub fn set(&self, tokens: Vec) { + let mut state = self.handle.state.lock(); + let configured = state.configured.as_ref().expect("built by Tokens::new"); + if configured.tokens == tokens { + return; + } + // A token still waiting on its verdict stays fresh when the new set keeps it. + let fresh = dedup(&tokens) + .into_iter() + .filter(|token| { + !configured.tokens.contains(token) + || (configured.fresh.contains(token) && configured.verdict(&state, token).is_none()) + }) + .collect(); + let configured = state.configured.as_mut().expect("built by Tokens::new"); + configured.fresh = fresh; + configured.tokens = tokens; + configured.generation += 1; + configured.answer = None; + state.hold(); + } + + /// Poll for the peer's answer to the tokens set last; see [`answered`](Self::answered). + pub fn poll_answered(&self, waiter: &kio::Waiter) -> Poll> { + let answer = |state: &State| { + state + .configured + .as_ref() + .and_then(|configured| configured.answer(state)) + }; + let mut state = match self.handle.state.poll(waiter, |state| match answer(state) { + Some(_) => Poll::Ready(()), + None => Poll::Pending, + }) { + Poll::Ready(state) => state, + Poll::Pending => return Poll::Pending, + }; + state.record(); + Poll::Ready(answer(&state).expect("checked answered")) + } + + /// Wait for the peer's first verdict on the tokens the last [`set`](Self::set) newly + /// presented, or on the initial tokens before any set: `Ok` once each is granted, in band + /// or as the connection credential a later dial carried. + /// + /// A token the set kept, the connection credential included, counts only once the peer + /// refuses it. Nothing is re-checked after the answer: a later revocation, or a new + /// session that refuses a token an earlier one granted, does not change it. + /// + /// # Errors + /// + /// The peer's refusal of a token as [`Error::Session`], [`Error::Unsupported`] when the + /// session cannot carry an in-band token, or the connection's end, such as a refused dial. + #[cfg(feature = "async")] + pub async fn answered(&self) -> Result<()> { + kio::wait(|waiter| self.poll_answered(waiter)).await + } + + /// Decide what a dial to `url` offering `versions` presents, and hold every other token in + /// band on the session it builds. Call it before each dial. + pub fn dial(&self, url: &Url, versions: &crate::Versions) -> Dial { + let mut state = self.handle.state.lock(); + state.record(); + let configured = state.configured.as_mut().expect("built by Tokens::new"); + let (url, setup, connection) = credential(url, versions, &configured.tokens); + let token = setup.map(|token| crate::setup::Token { + kind: crate::setup::Token::OUT_OF_BAND, + value: token.into_bytes(), + }); + configured.dialed = Some(connection); + configured.session = None; + configured.unsupported = false; + let generation = configured.generation; + state.hold(); + Dial { url, token, generation } + } + + /// The session the latest [`dial`](Self::dial) built on [`handle`](Self::handle), once it + /// connected, whose own answer to the connection credential then counts. A session built + /// on another handle answers nothing here. + #[cfg(feature = "async")] + pub fn connected(&self, session: &crate::Session) { + if session.auth().state.same_channel(&self.handle.state) { + self.connect(session.credential()); + } + } + + fn connect(&self, credential: Option<&super::Auth>) { + let mut state = self.handle.state.lock(); + state.record(); + let connected = match credential { + Some(auth) => Some(Connected::Slot { + link: auth.presented.link.expect("a session's own credential"), + id: auth.presented.id, + }), + // The handle backs one open session at a time: the one just built, unless it ended. + None => state + .links + .iter() + .rev() + .find(|(_, link)| link.closed.is_none()) + .map(|(link, _)| Connected::Accepted { link: *link }), + }; + state.configured.as_mut().expect("built by Tokens::new").session = connected; + } + + /// Whether the tokens changed since `dial` read them, so a refusal of its credential earns + /// another dial. + pub fn changed(&self, dial: &Dial) -> bool { + let state = self.handle.state.read(); + state.configured.as_ref().expect("built by Tokens::new").generation != dial.generation + } +} + +/// The configured tokens a [`Tokens`] presents, kept on its handle's state so each verdict +/// a session records reaches them under the same lock. +#[derive(Default)] +pub(super) struct Configured { + tokens: Vec, + generation: u64, + /// The latest dial's connection credential, never also held in band. `None` before the + /// first dial. + dialed: Option>, + /// The tokens held on their own AUTH streams, by their id among the handle's tokens. + held: Vec<(Token, u64)>, + /// Tokens a change replaced, kept presented until every held token has its answer. + retiring: Vec, + /// The latest dial's session, once it connected. + session: Option, + /// The tokens the latest sets newly presented whose verdict is not yet known. + fresh: Vec, + /// The first verdict on the latest set. + answer: Option>, + /// Whether the latest dial already logged that its session takes no tokens in band. + unsupported: bool, +} + +/// How the latest dial's session answers its connection credential. +enum Connected { + /// The version has no AUTH, so the peer accepted it with its handshake, or with its + /// SETUP when the session [awaits it](super::Link::await_setup). + Accepted { link: u64 }, + /// Its own AUTH stream on that session. + Slot { link: u64, id: u64 }, +} + +impl Configured { + /// The latest dial's connection credential, when the tokens still name it. + fn named(&self) -> Option<&str> { + let connection = self.dialed.as_ref()?.as_deref()?; + self.tokens + .iter() + .any(|token| token.as_str() == connection) + .then_some(connection) + } + + /// The peer's verdict on the connection credential, `None` while it has none or no + /// session is live. + fn credential(&self, state: &State) -> Option> { + let (link, id) = match self.session.as_ref()? { + Connected::Slot { link, id } => (link, id), + Connected::Accepted { link } => { + let link = state.links.get(link).filter(|link| link.closed.is_none())?; + return link.accepted.then_some(Ok(())); + } + }; + let link = state.links.get(link).filter(|link| link.closed.is_none())?; + let slot = link.slots.get(id)?; + match (&slot.ended, &slot.answered) { + // The moq-transport SETUP that carried it accepted it before the peer declined AUTH. + (Some(Error::Unsupported), _) => Some(Ok(())), + (Some(err), _) => Some(Err(err.clone())), + (None, Some(Ok(()))) => Some(Ok(())), + // Unanswered, or waiting out a refusal that may pass. + (None, _) => None, + } + } + + /// The peer's verdict on a token the set newly presented, `None` while it has none. + fn verdict(&self, state: &State, token: &Token) -> Option> { + if let Some((_, id)) = self.held.iter().find(|(held, _)| held == token) { + return match state.tokens.get(id)?.answered.clone()? { + Ok(Answer::Granted) => Some(Ok(())), + // Taken only for the requests that name it, and a configured token rides none. + Ok(Answer::Requests) => Some(Err(Error::Unsupported)), + Err(err) => Some(Err(err)), + }; + } + match self.named() == Some(token.as_str()) { + true => self.credential(state), + // Not presented until the first dial. + false => None, + } + } + + /// The answer to the latest set: the first refusal of any token it names, or `Ok` once + /// every fresh token is granted. `None` while one still waits. + fn answer(&self, state: &State) -> Option> { + if let Some(answer) = &self.answer { + return Some(answer.clone()); + } + if let Some(err) = &state.closed { + return Some(Err(err.clone())); + } + let held = self + .held + .iter() + .filter_map(|(_, id)| state.tokens.get(id)?.ended.clone()); + let credential = self.named().and_then(|_| self.credential(state)?.err()); + if let Some(err) = held.chain(credential).next() { + return Some(Err(err)); + } + let mut waiting = false; + for token in &self.fresh { + match self.verdict(state, token) { + Some(Ok(())) => {} + Some(Err(err)) => return Some(Err(err)), + None => waiting = true, + } + } + (!waiting).then_some(Ok(())) + } +} + +impl State { + /// Whether token `id` is one a [`Tokens`] holds in band. + pub(super) fn configured(&self, id: u64) -> bool { + self.configured + .as_ref() + .is_some_and(|configured| configured.held.iter().any(|(_, held)| *held == id)) + } + + /// Configured token `id` rides nothing on this session, which the latest dial logs once. + pub(super) fn unsupported(&mut self, id: u64) { + if !self.configured(id) { + return; + } + let configured = self.configured.as_mut().expect("checked configured"); + if !std::mem::replace(&mut configured.unsupported, true) { + tracing::debug!("the peer takes no tokens in band; presenting only the connection credential"); + } + } + + /// Keep each verdict the latest set has so far, before a dial, a new session, or a + /// dropped one takes away where it came from. + pub(super) fn record(&mut self) { + let Some(configured) = &self.configured else { return }; + if configured.answer.is_some() { + return; + } + let answer = configured.answer(self); + let granted: Vec = configured + .fresh + .iter() + .filter(|token| matches!(configured.verdict(self, token), Some(Ok(())))) + .cloned() + .collect(); + let configured = self.configured.as_mut().expect("checked configured"); + match answer { + Some(answer) => { + if answer.is_ok() { + configured.fresh.clear(); + } + configured.answer = Some(answer); + } + None => configured.fresh.retain(|token| !granted.contains(token)), + } + } + + /// Hold every configured token but the latest dial's connection credential in band, + /// presenting the new ones and retiring the ones no longer configured. + pub(super) fn hold(&mut self) { + let Some(configured) = &self.configured else { return }; + let Some(connection) = configured.dialed.clone() else { + return; + }; + let tokens: Vec = dedup(&configured.tokens) + .into_iter() + .filter(|token| Some(token.as_str()) != connection.as_deref()) + .collect(); + let mut held = Vec::with_capacity(tokens.len()); + let mut presented = Vec::new(); + for token in tokens { + let configured = self.configured.as_ref().expect("checked configured"); + let id = match configured.held.iter().find(|(kept, _)| *kept == token) { + Some((_, id)) => *id, + None => { + let id = self.present(Bytes::from(token.as_str().to_string())); + presented.push(id); + id + } + }; + held.push((token, id)); + } + let configured = self.configured.as_mut().expect("checked configured"); + let old = std::mem::replace(&mut configured.held, held); + for (_, id) in old { + if self.configured(id) { + continue; + } + // A refused token has nothing left to keep the grant wide. + match self.tokens.get(&id).is_some_and(|entry| entry.ended.is_none()) { + true => self.configured.as_mut().expect("checked configured").retiring.push(id), + false => self.withdraw(id), + } + } + // A session without AUTH answers a new token at once, before it was held. + for id in presented { + let answered = self.tokens.get(&id).and_then(|entry| entry.answered.as_ref()); + if let Some(Ok(Answer::Requests) | Err(Error::Unsupported)) = answered { + self.unsupported(id); + } + } + self.settle(); + } + + /// Withdraw the replaced tokens once every held token has its answer. + pub(super) fn settle(&mut self) { + let Some(configured) = &self.configured else { return }; + if configured.retiring.is_empty() + || configured + .held + .iter() + .any(|(_, id)| self.tokens.get(id).is_some_and(|entry| entry.answered.is_none())) + { + return; + } + let retiring = std::mem::take(&mut self.configured.as_mut().expect("checked configured").retiring); + for id in retiring { + self.withdraw(id); + } + } +} + +/// Each of `tokens` once, in order. +fn dedup(tokens: &[Token]) -> Vec { + let mut unique: Vec = Vec::with_capacity(tokens.len()); + for token in tokens { + if !unique.contains(token) { + unique.push(token.clone()); + } + } + unique +} + +/// What a dial to `url` presents: the URL to dial, the token SETUP carries, and the +/// connection credential, which is never also held in band. +fn credential(url: &Url, versions: &crate::Versions, tokens: &[Token]) -> (Url, Option, Option) { + if let Some(jwt) = jwt(url) { + // The URL's own credential (a cluster's per-peer `?jwt=`) wins, so the tokens all + // ride AUTH and no second credential reaches SETUP or the query. + return (url.clone(), None, Some(jwt)); + } + let Some(first) = tokens.first() else { + return (url.clone(), None, None); + }; + // The URL is fixed before the version is negotiated, so it carries the credential + // whenever a version that may be picked could not carry it in SETUP. + let url = match versions.iter().all(|version| version.has_setup_token()) { + true => url.clone(), + false => with_jwt(url, first.as_str()), + }; + (url, Some(first.as_str().to_string()), Some(first.as_str().to_string())) +} + +/// The request target's query: the URL's own, or for `unix:` the one inside `?path=`. +fn target_query(url: &Url) -> Option { + match url.scheme() { + "unix" => url + .query_pairs() + .find(|(k, _)| k == "path") + .and_then(|(_, path)| path.split_once('?').map(|(_, query)| query.to_string())), + _ => url.query().map(str::to_string), + } +} + +/// The non-empty `jwt` the URL's request target already carries. +fn jwt(url: &Url) -> Option { + let query = target_query(url)?; + url::form_urlencoded::parse(query.as_bytes()) + .find(|(k, v)| k == "jwt" && !v.is_empty()) + .map(|(_, v)| v.into_owned()) +} + +/// `url` with `jwt` appended to its request target's query. +fn with_jwt(url: &Url, jwt: &str) -> Url { + let mut url = url.clone(); + if url.scheme() != "unix" { + url.query_pairs_mut().append_pair("jwt", jwt); + return url; + } + // A unix socket's request target is one form-encoded `?path=` value, so the + // credential joins the query inside it. + let pairs: Vec<(String, String)> = url.query_pairs().into_owned().collect(); + let mut serializer = url::form_urlencoded::Serializer::new(String::new()); + let mut found = false; + for (k, v) in &pairs { + match k == "path" { + true => { + found = true; + let mut target = url::form_urlencoded::Serializer::new(String::new()); + target.append_pair("jwt", jwt); + let separator = if v.contains('?') { '&' } else { '?' }; + serializer.append_pair(k, &format!("{v}{separator}{}", target.finish())); + } + false => { + serializer.append_pair(k, v); + } + } + } + if !found { + let mut target = url::form_urlencoded::Serializer::new(String::new()); + target.append_pair("jwt", jwt); + serializer.append_pair("path", &format!("?{}", target.finish())); + } + url.set_query(Some(&serializer.finish())); + url +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + SessionError, + auth::{Auth, Grant, Link}, + }; + + fn tokens(names: &[&str]) -> Vec { + names.iter().map(|name| name.parse().unwrap()).collect() + } + + fn versions(names: &[&str]) -> crate::Versions { + names + .iter() + .map(|name| name.parse::().unwrap()) + .collect::>() + .into() + } + + /// One session a dial built on the handle, with AUTH when `supported`, and moq-transport + /// requests when `requests`. + struct Session { + link: Link, + credential: Option, + } + + fn dial(set: &Tokens, supported: bool, requests: bool) -> Session { + set.dial( + &"moqt://relay.example.com/".parse().unwrap(), + &versions(&["moq-lite-07-wip"]), + ); + let link = Link::attach(&set.handle, supported, requests).unwrap(); + let credential = supported.then(|| link.present(Bytes::new(), true).unwrap()); + set.connect(credential.as_ref()); + Session { link, credential } + } + + impl Session { + fn credential(&self) -> u64 { + self.credential.as_ref().unwrap().id() + } + + fn grant_credential(&self) { + self.link.granted(self.credential(), Grant::all()); + } + + /// The peer refuses or revokes the token presented as `id`, as the driver reports it. + fn refuse(&self, id: u64, code: SessionError) { + let err = Error::Session(code); + self.link.refused(id); + if self.link.retry(id, &err).is_none() { + self.link.ended(id, err); + } + } + + fn lost(self) { + self.link.close(Error::Transport("lost".into())); + } + } + + /// The id a configured token is held under. + fn id(set: &Tokens, name: &str) -> u64 { + let state = set.handle.state.read(); + let held = &state.configured.as_ref().unwrap().held; + held.iter() + .find(|(token, _)| token.as_str() == name) + .expect("not held") + .1 + } + + fn held(set: &Tokens) -> Vec { + let state = set.handle.state.read(); + let held = &state.configured.as_ref().unwrap().held; + held.iter().map(|(token, _)| token.as_str().to_string()).collect() + } + + fn presented(set: &Tokens, id: u64) -> bool { + set.handle.state.read().tokens.contains_key(&id) + } + + fn answered(set: &Tokens) -> Poll> { + set.poll_answered(&kio::Waiter::noop()) + } + + fn ok(set: &Tokens) { + let answer = answered(set); + assert!(matches!(answer, Poll::Ready(Ok(()))), "{answer:?}"); + } + + fn refused(set: &Tokens, code: SessionError) { + let answer = answered(set); + assert!( + matches!(&answer, Poll::Ready(Err(Error::Session(refused))) if *refused == code), + "{answer:?}" + ); + } + + /// Every token but the connection credential is held in band, each once. + #[test] + fn only_the_extra_tokens_ride_auth() { + let set = Tokens::new(tokens(&["connection", "a", "b", "a"])); + let _session = dial(&set, true, false); + assert_eq!(held(&set), ["a", "b"]); + } + + /// A replaced token is withdrawn only once its replacement has an answer, so the grant + /// never narrows in between, and that answer is the set's. + #[test] + fn a_replacement_retires_what_it_replaced_once_answered() { + let set = Tokens::new(tokens(&["connection", "old"])); + let session = dial(&set, true, false); + session.grant_credential(); + let old = id(&set, "old"); + session.link.granted(old, Grant::all()); + ok(&set); + + set.set(tokens(&["connection", "new"])); + assert!(answered(&set).is_pending(), "answered before the replacement was"); + assert!(presented(&set, old), "withdrawn before its replacement was answered"); + + session.link.granted(id(&set, "new"), Grant::all()); + ok(&set); + assert!(!presented(&set, old), "the replaced token was never withdrawn"); + } + + /// A replacement is authoritative: its refusal is the answer, and still withdraws what it + /// replaced. + #[test] + fn a_refused_replacement_still_retires_what_it_replaced() { + let set = Tokens::new(tokens(&["connection", "old"])); + let session = dial(&set, true, false); + session.grant_credential(); + let old = id(&set, "old"); + session.link.granted(old, Grant::all()); + + set.set(tokens(&["connection", "new"])); + session.refuse(id(&set, "new"), SessionError::Unauthorized); + refused(&set, SessionError::Unauthorized); + assert!( + !presented(&set, old), + "the replaced token outlived its refused replacement" + ); + } + + /// An extra token granted first is no answer to a fresh connection credential, whose own + /// refusal is the answer even while its session stays open. + #[test] + fn the_connection_credential_answers_for_itself() { + let set = Tokens::new(tokens(&["connection", "a"])); + let session = dial(&set, true, false); + session.link.granted(id(&set, "a"), Grant::all()); + assert!(answered(&set).is_pending(), "answered before the credential was"); + + session.refuse(session.credential(), SessionError::Unauthorized); + refused(&set, SessionError::Unauthorized); + } + + /// A refusal that may pass presents the credential again, which answers nothing until + /// the retry is answered. + #[test] + fn a_transient_refusal_of_the_credential_waits_for_its_retry() { + let set = Tokens::new(tokens(&["connection"])); + let session = dial(&set, true, false); + session.refuse(session.credential(), SessionError::Internal); + assert!(answered(&set).is_pending(), "answered before the retry was"); + + session.link.reopen(session.credential()).unwrap(); + session.grant_credential(); + ok(&set); + } + + /// The first verdict is the answer even when nothing polled it before a revocation or + /// the connection's end. + #[test] + fn a_granted_set_keeps_its_answer_when_revoked_before_it_is_read() { + let set = Tokens::new(tokens(&["connection", "a"])); + let session = dial(&set, true, false); + session.grant_credential(); + session.link.granted(id(&set, "a"), Grant::all()); + session.refuse(id(&set, "a"), SessionError::Unauthorized); + ok(&set); + + set.set(tokens(&["connection", "b"])); + session.link.granted(id(&set, "b"), Grant::all()); + set.handle().abort(Error::Session(SessionError::Unauthorized)); + ok(&set); + } + + /// A session without AUTH that awaits the server's SETUP, as a moq-lite-05/06 client does. + fn dial_awaiting_setup(set: &Tokens) -> Link { + set.dial( + &"moqt://relay.example.com/".parse().unwrap(), + &versions(&["moq-lite-06"]), + ); + let link = Link::attach(&set.handle, false, false).unwrap(); + link.await_setup(); + set.connect(None); + link + } + + /// Without AUTH, the server's SETUP is what accepts the connection credential. + #[test] + fn a_credential_without_auth_is_accepted_by_the_server_setup() { + let set = Tokens::new(tokens(&["connection"])); + let link = dial_awaiting_setup(&set); + assert!(answered(&set).is_pending(), "accepted before the server's SETUP"); + link.accepted(); + ok(&set); + } + + /// A server that refuses the credential before its SETUP grants nothing, even though + /// the session was live. + #[test] + fn a_credential_refused_before_the_server_setup_is_no_grant() { + let set = Tokens::new(tokens(&["connection"])); + let link = dial_awaiting_setup(&set); + link.close(Error::Session(SessionError::Unauthorized)); + assert!(answered(&set).is_pending(), "a refused session accepted the credential"); + set.handle().abort(Error::Session(SessionError::Unauthorized)); + refused(&set, SessionError::Unauthorized); + } + + /// The connection credential revoked after its grant refuses a later set that keeps it. + #[test] + fn a_kept_credential_revoked_after_its_grant_refuses_the_next_set() { + let set = Tokens::new(tokens(&["connection", "a", "b"])); + let session = dial(&set, true, false); + session.grant_credential(); + session.link.granted(id(&set, "a"), Grant::all()); + session.link.granted(id(&set, "b"), Grant::all()); + ok(&set); + + session.refuse(session.credential(), SessionError::Unauthorized); + set.set(tokens(&["connection", "a"])); + refused(&set, SessionError::Unauthorized); + } + + /// A kept token revoked after its grant refuses a later set that keeps it. + #[test] + fn a_kept_token_revoked_after_its_grant_refuses_the_next_set() { + let set = Tokens::new(tokens(&["connection", "a", "b"])); + let session = dial(&set, true, false); + session.grant_credential(); + session.link.granted(id(&set, "a"), Grant::all()); + session.link.granted(id(&set, "b"), Grant::all()); + ok(&set); + + session.refuse(id(&set, "a"), SessionError::Unauthorized); + set.set(tokens(&["connection", "a"])); + refused(&set, SessionError::Unauthorized); + } + + /// A set that only keeps tokens answers at once after reconnecting to a moq-transport + /// peer without AUTH, which grants nothing in band. + #[test] + fn a_kept_set_answers_at_once_on_a_session_without_auth() { + let set = Tokens::new(tokens(&["connection", "a", "b"])); + let first = dial(&set, true, false); + first.grant_credential(); + first.link.granted(id(&set, "a"), Grant::all()); + first.link.granted(id(&set, "b"), Grant::all()); + first.lost(); + + let _second = dial(&set, false, true); + set.set(tokens(&["connection", "a"])); + ok(&set); + } + + /// A kept token counts only by refusal: one a moq-transport session without AUTH took + /// only for requests is no refusal once a later session grants it. + #[test] + fn a_kept_token_is_judged_only_by_refusal() { + let set = Tokens::new(tokens(&["connection", "a", "b"])); + let first = dial(&set, false, true); + let answer = answered(&set); + assert!( + matches!(answer, Poll::Ready(Err(Error::Unsupported))), + "a session without AUTH carried a token in band: {answer:?}" + ); + first.lost(); + + let second = dial(&set, true, false); + second.grant_credential(); + second.link.granted(id(&set, "a"), Grant::all()); + set.set(tokens(&["connection", "a"])); + ok(&set); + } + + /// A token set while offline becomes the next dial's connection credential, never also + /// held in band, and that session's answer to it is the set's. + #[test] + fn a_set_while_offline_is_answered_by_the_next_credential() { + let set = Tokens::new(tokens(&["old"])); + let first = dial(&set, true, false); + first.grant_credential(); + first.lost(); + + set.set(tokens(&["new"])); + assert!(answered(&set).is_pending(), "answered while offline"); + let second = dial(&set, true, false); + assert!(held(&set).is_empty(), "the credential is also held in band"); + assert!(answered(&set).is_pending(), "answered before the credential was"); + second.grant_credential(); + ok(&set); + } + + /// A token granted in band keeps its verdict when a later dial moves it to SETUP. + #[test] + fn a_granted_token_keeps_its_verdict_as_the_next_credential() { + let set = Tokens::new(tokens(&["old"])); + let first = dial(&set, true, false); + first.grant_credential(); + set.set(tokens(&["new", "pending"])); + first.link.granted(id(&set, "new"), Grant::all()); + first.lost(); + + let second = dial(&set, true, false); + assert_eq!(held(&set), ["pending"]); + second.link.granted(id(&set, "pending"), Grant::all()); + ok(&set); + } + + /// A session that takes no token in band answers a new one as unsupported. + #[test] + fn a_session_without_auth_is_unsupported() { + for requests in [false, true] { + let set = Tokens::new(tokens(&["connection"])); + let _session = dial(&set, false, requests); + ok(&set); + set.set(tokens(&["connection", "a"])); + let answer = answered(&set); + assert!( + matches!(answer, Poll::Ready(Err(Error::Unsupported))), + "requests {requests}: {answer:?}" + ); + } + } + + /// The connection's end answers a set no session will. + #[test] + fn the_connection_end_answers_a_waiting_set() { + let set = Tokens::new(tokens(&["connection"])); + assert!(answered(&set).is_pending()); + set.handle().abort(Error::Session(SessionError::Unauthorized)); + refused(&set, SessionError::Unauthorized); + } + + #[test] + fn only_a_change_outdates_a_dial() { + let set = Tokens::new(tokens(&["a"])); + let dial = set.dial( + &"moqt://relay.example.com/".parse().unwrap(), + &versions(&["moq-lite-07-wip"]), + ); + set.set(tokens(&["a"])); + assert!(!set.changed(&dial)); + set.set(tokens(&["b"])); + assert!(set.changed(&dial)); + } + + /// Only lite-07 and moq-transport carry the credential in SETUP, so the URL stays clean. + #[test] + fn setup_versions_keep_the_credential_out_of_the_url() { + let url: Url = "https://relay.example.com/room".parse().unwrap(); + let (dialed, setup, connection) = credential( + &url, + &versions(&["moq-lite-07-wip", "moq-transport-17"]), + &tokens(&["a", "b"]), + ); + assert_eq!(dialed, url); + assert_eq!(setup.as_deref(), Some("a")); + assert_eq!(connection.as_deref(), Some("a")); + } + + /// An offered version without a SETUP token needs the credential in the query, and the + /// same value rides SETUP too. + #[test] + fn an_older_version_puts_the_credential_in_the_url() { + let url: Url = "https://relay.example.com/room?x=1".parse().unwrap(); + let (dialed, setup, _) = credential(&url, &crate::Versions::all(), &tokens(&["a b"])); + assert_eq!(dialed.as_str(), "https://relay.example.com/room?x=1&jwt=a+b"); + assert_eq!(setup.as_deref(), Some("a b")); + } + + /// A URL credential stays the connection credential, so every token rides AUTH, except + /// one equal to it, which would be granted twice. + #[test] + fn a_url_credential_sends_every_token_on_auth() { + let url: Url = "moqt://relay.example.com/room?jwt=peer".parse().unwrap(); + let set = Tokens::new(tokens(&["a", "peer", "a"])); + let dial = set.dial(&url, &crate::Versions::all()); + assert_eq!(dial.url, url); + assert_eq!(dial.token, None); + assert_eq!(held(&set), ["a"]); + } + + #[test] + fn no_tokens_present_nothing() { + let url: Url = "https://relay.example.com/room".parse().unwrap(); + assert_eq!(credential(&url, &crate::Versions::all(), &[]), (url, None, None)); + } + + /// A unix socket's request target lives in `?path=`, so the credential goes inside it. + #[test] + fn a_unix_credential_joins_the_path_target() { + for (url, expected) in [ + ("unix:///tmp/moq.sock?path=%2Froom", "/room?jwt=a"), + ("unix:///tmp/moq.sock?path=%2Froom%3Fx%3D1", "/room?x=1&jwt=a"), + ("unix:///tmp/moq.sock", "?jwt=a"), + ] { + let url: Url = url.parse().unwrap(); + let (dialed, _, _) = credential(&url, &crate::Versions::all(), &tokens(&["a"])); + let path = dialed + .query_pairs() + .find(|(k, _)| k == "path") + .map(|(_, v)| v.into_owned()); + assert_eq!(path.as_deref(), Some(expected), "{url}"); + // The rewritten target is read back as already carrying the credential. + assert_eq!(jwt(&dialed).as_deref(), Some("a")); + } + } + + #[test] + fn a_token_never_logs_its_value() { + let token: Token = "secret".parse().unwrap(); + assert_eq!(format!("{token:?}"), "Token(<6 bytes>)"); + assert!("".parse::().is_err()); + } +} diff --git a/rs/moq-net/src/client.rs b/rs/moq-net/src/client.rs index 23591ece48e..d8b3b71773d 100644 --- a/rs/moq-net/src/client.rs +++ b/rs/moq-net/src/client.rs @@ -342,6 +342,7 @@ impl Client { stats: self.stats.clone(), goaway: start.goaway, auth: start.auth, + credential: start.credential, estimate: Some(start.estimate), bandwidth: self.bandwidth(), peer_implementation: start.peer_implementation, @@ -384,7 +385,7 @@ impl Client { // offer it keeps the option out of our SETUP and presents no credential. let auth = self.link(self.extensions.auth, true)?; let peer_implementation = setup::PeerImplementation::default(); - let (protocol, goaway) = ietf::start(ietf::Config { + let (protocol, goaway, credential) = ietf::start(ietf::Config { runtime: runtime.clone(), stats: self.stats.clone(), limits: self.limits, @@ -420,6 +421,7 @@ impl Client { stats: self.stats.clone(), goaway, auth, + credential, estimate: None, bandwidth: self.bandwidth(), peer_implementation, @@ -533,7 +535,7 @@ impl Client { return self.start_lite(runtime, session, v, peer_hop); } - let (recv_bw, protocol, goaway, auth, estimate, peer_implementation) = match version { + let (recv_bw, protocol, goaway, auth, credential, estimate, peer_implementation) = match version { Version::Lite(v) => { let stream = stream.with_version(v); let start = lite::start(lite::Config { @@ -559,6 +561,7 @@ impl Client { crate::driver::Protocol::Lite(Box::new(start.driver)), start.goaway, start.auth, + start.credential, Some(start.estimate), start.peer_implementation, ) @@ -586,7 +589,7 @@ impl Client { // Draft 14-16 carry no AUTH, but the session is still limited through this handle. let auth = self.link(false, true)?; // Draft 14-16: the path rode in the bidi SETUP above, not the uni one. - let (protocol, goaway) = ietf::start(ietf::Config { + let (protocol, goaway, credential) = ietf::start(ietf::Config { runtime: runtime.clone(), stats: self.stats.clone(), limits: self.limits, @@ -616,6 +619,7 @@ impl Client { crate::driver::Protocol::Ietf(protocol), goaway, auth, + credential, None, peer_implementation, ) @@ -632,6 +636,7 @@ impl Client { stats: self.stats.clone(), goaway, auth, + credential, estimate, bandwidth: self.bandwidth(), peer_implementation, diff --git a/rs/moq-net/src/ietf/peer.rs b/rs/moq-net/src/ietf/peer.rs index bcc918aa7e9..5b87d835e64 100644 --- a/rs/moq-net/src/ietf/peer.rs +++ b/rs/moq-net/src/ietf/peer.rs @@ -51,6 +51,8 @@ pub(crate) struct PeerSetup { declined_epoch: bool, /// Where the peer's advertised implementation is published for the session handle. implementation: crate::setup::PeerImplementation, + /// The session's auth link to tell once the peer's SETUP accepts the connection. + accept: Option, } impl PeerSetup { @@ -68,9 +70,17 @@ impl PeerSetup { slot: Default::default(), declined_epoch: !offered.epoch, implementation: Default::default(), + accept: None, } } + /// Tell `link` once the peer's SETUP arrives that it accepted the connection credential. + pub fn accepting(mut self, link: crate::auth::Link) -> Self { + link.await_setup(); + self.accept = Some(link); + self + } + /// Publish the peer's advertised implementation to `slot` once its SETUP is read. pub fn with_implementation(mut self, slot: crate::setup::PeerImplementation) -> Self { self.implementation = slot; @@ -92,8 +102,13 @@ impl PeerSetup { pub fn set(&self, mut peer: Peer) { peer.epoch &= !self.declined_epoch; let mut slot = self.slot.lock(); - if slot.is_none() { - *slot = Some(peer); + if slot.is_some() { + return; + } + *slot = Some(peer); + drop(slot); + if let Some(link) = &self.accept { + link.accepted(); } } diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index b44ebb72582..b9b618217f5 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -140,7 +140,7 @@ impl std::future::Future for Driver { } } -pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle), Error> { +pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle, Option), Error> { let Config { runtime, stats, @@ -202,7 +202,7 @@ pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle), Error> { // What the peer declared in its SETUP. Seeded now when that stream was already // read (the legacy handshake, or a gated server accept), and filled by the uni // loop otherwise. - let peer_setup = peer::PeerSetup::new(extensions).with_implementation(peer_implementation); + let mut peer_setup = peer::PeerSetup::new(extensions).with_implementation(peer_implementation); let setup_read = peer_declared.is_some(); match peer_declared { Some(declared) => peer_setup.set(declared), @@ -210,9 +210,13 @@ pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle), Error> { // settle the slot rather than leave the announce loops waiting on a value // that is never coming. None if !cluster::supported(version) => peer_setup.set(peer::Peer::default()), + // A client is live before the server's SETUP, which follows its check of the + // credential. + None if client => peer_setup = peer_setup.accepting(auth.clone()), None => {} } + let credential = setup_token.clone(); let driver = async move { // Held for the life of the session. let _setup_token = setup_token; @@ -629,6 +633,7 @@ pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle), Error> { future: driver, }, goaway_handle, + credential, )) } @@ -1597,7 +1602,7 @@ mod tests { }; // SETUP already owns its stream; subsequent requests have no credit. let _ = scripted.without_credit(); - let (driver, _goaway) = start(Config { + let (driver, _goaway, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session, @@ -1694,7 +1699,7 @@ mod tests { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(incoming); let log = session.log.clone(); - let (driver, _) = start(Config { + let (driver, _, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -1753,7 +1758,7 @@ mod tests { script.extend(body); let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![script]); let log = session.log.clone(); - let (driver, _) = start(Config { + let (driver, _, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -1807,7 +1812,7 @@ mod tests { )); let log = session.log.clone(); let handle = crate::auth::Handle::new(); - let (driver, _) = start(Config { + let (driver, _, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -1863,7 +1868,7 @@ mod tests { )); let log = session.log.clone(); let handle = crate::auth::Handle::new(); - let (driver, _) = start(Config { + let (driver, _, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -1912,7 +1917,7 @@ mod tests { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(vec![script]); let log = session.log.clone(); - let (driver, _) = start(Config { + let (driver, _, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -2019,7 +2024,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()), @@ -2087,7 +2092,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()), @@ -2204,7 +2209,7 @@ mod tests { _ => None, }; - let (driver, _goaway) = start(Config { + let (driver, _goaway, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session, @@ -2466,7 +2471,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()), @@ -2573,7 +2578,7 @@ mod tests { let log = session.log.clone(); let handle = crate::auth::Link::ietf(true); - let (driver, goaway) = start(Config { + let (driver, goaway, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -2662,7 +2667,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()), @@ -2762,7 +2767,7 @@ mod tests { 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 { + let (driver, _goaway, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session: crate::driver::Transport::new(session.clone()), @@ -2855,7 +2860,7 @@ mod tests { let origin = crate::origin::Config::new(crate::Hop::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()), @@ -2904,7 +2909,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()), @@ -3320,7 +3325,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()), @@ -3392,7 +3397,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()), @@ -3502,7 +3507,7 @@ mod tests { .await .expect("open the control stream"); - let (driver, _goaway) = start(Config { + let (driver, _goaway, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session, @@ -3633,7 +3638,7 @@ mod tests { _ => None, }; let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); - let (driver, _goaway) = start(Config { + let (driver, _goaway, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), session, @@ -3878,7 +3883,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()), @@ -3986,7 +3991,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()), diff --git a/rs/moq-net/src/lite/session.rs b/rs/moq-net/src/lite/session.rs index 0ff1fe8ce21..9ed4075379b 100644 --- a/rs/moq-net/src/lite/session.rs +++ b/rs/moq-net/src/lite/session.rs @@ -23,6 +23,8 @@ pub(crate) struct SessionStart { pub goaway: crate::goaway::Handle, /// The session's AUTH tokens and grants, stored on the public [`crate::Session`]. pub auth: crate::auth::Link, + /// The connection credential presented on `auth`, stored on the public [`crate::Session`]. + pub credential: Option, /// The implementation the peer's SETUP advertised, stored on the public [`crate::Session`]. pub peer_implementation: crate::setup::PeerImplementation, } @@ -278,9 +280,14 @@ pub fn start(config: Config) -> Result { // When the caller already read it (a gated server accept), seed the slot so the // Setup stream isn't expected on the wire again. let peer_implementation = crate::setup::PeerImplementation::default(); - let peer_setup_slot = PeerSetup::new(client, session.address()) + let mut peer_setup_slot = PeerSetup::new(client, session.address()) .offer_ietf(our_setup.ietf) .with_implementation(peer_implementation.clone()); + // Without AUTH, the server checks a client's credential before its SETUP, which the + // client reads only after going live. + if client && version.has_setup_stream() && !version.has_auth() { + peer_setup_slot = peer_setup_slot.accepting(auth.clone()); + } // A version without a Setup Stream advertises nothing, so there is nothing to wait for. if !version.has_setup_stream() { peer_implementation.set(None); @@ -360,7 +367,7 @@ pub fn start(config: Config) -> Result { tokens: kio::Tasks::new(), violation: Default::default(), started: false, - _setup: setup_token, + _setup: setup_token.clone(), }, setup: version .has_setup_stream() @@ -379,6 +386,7 @@ pub fn start(config: Config) -> Result { driver, goaway: goaway_handle, auth, + credential: setup_token, peer_implementation, }) } diff --git a/rs/moq-net/src/lite/setup.rs b/rs/moq-net/src/lite/setup.rs index 1f7fc68063d..f5c9508ee7f 100644 --- a/rs/moq-net/src/lite/setup.rs +++ b/rs/moq-net/src/lite/setup.rs @@ -351,6 +351,8 @@ struct PeerSetupState { setup: Option, /// Where the peer's advertised implementation is published for the session handle. implementation: crate::setup::PeerImplementation, + /// The session's auth link to tell once the peer's SETUP accepts the connection. + accept: Option, } impl PeerSetup { @@ -362,9 +364,17 @@ impl PeerSetup { seen: false, setup: None, implementation: Default::default(), + accept: None, })) } + /// Tell `link` once the peer's SETUP arrives that it accepted the connection credential. + pub fn accepting(self, link: crate::auth::Link) -> Self { + link.await_setup(); + self.0.lock().accept = Some(link); + self + } + /// Publish the peer's advertised implementation to `slot` once its SETUP arrives. pub fn with_implementation(self, slot: crate::setup::PeerImplementation) -> Self { self.0.lock().implementation = slot; @@ -381,6 +391,11 @@ impl PeerSetup { state.seen = true; state.implementation.set(received.setup.implementation.clone()); state.setup = Some(received.setup); + let accept = state.accept.take(); + drop(state); + if let Some(link) = accept { + link.accepted(); + } Ok(()) } diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index d8ed7ff24b6..99c6e74bfad 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -210,6 +210,7 @@ impl Server { stats: self.stats.clone(), goaway: start.goaway, auth: start.auth, + credential: start.credential, estimate: Some(start.estimate), bandwidth: crate::bandwidth::Allocator::default(), peer_implementation: start.peer_implementation, @@ -575,7 +576,7 @@ impl PausedIetfModern { // 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) = ietf::start(ietf::Config { + let (protocol, goaway, credential) = ietf::start(ietf::Config { runtime: runtime.clone(), stats: server.stats.clone(), limits: server.limits, @@ -611,6 +612,7 @@ impl PausedIetfModern { stats: server.stats.clone(), goaway, auth, + credential, estimate: None, bandwidth: crate::bandwidth::Allocator::default(), peer_implementation, @@ -687,7 +689,7 @@ impl PausedLegacy { }; stream.writer.encode(&server_setup).await?; - let (recv_bw, protocol, goaway, auth, estimate, peer_implementation) = match version { + let (recv_bw, protocol, goaway, auth, credential, estimate, peer_implementation) = match version { Version::Lite(v) => { let stream = stream.with_version(v); // Pre-lite-05: no Setup Stream, so nothing to advertise or seed. @@ -711,6 +713,7 @@ impl PausedLegacy { crate::driver::Protocol::Lite(Box::new(start.driver)), start.goaway, start.auth, + start.credential, Some(start.estimate), start.peer_implementation, ) @@ -719,7 +722,7 @@ impl PausedLegacy { let stream = stream.with_version(v); let peer_implementation = setup::PeerImplementation::known(peer_implementation); // Draft 14-16: path came in the bidi SETUP, no uni SETUP to hand back. - let (protocol, goaway) = ietf::start(ietf::Config { + let (protocol, goaway, credential) = ietf::start(ietf::Config { runtime: runtime.clone(), stats: server.stats.clone(), limits: server.limits, @@ -749,6 +752,7 @@ impl PausedLegacy { crate::driver::Protocol::Ietf(protocol), goaway, auth, + credential, None, peer_implementation, ) @@ -765,6 +769,7 @@ impl PausedLegacy { stats: server.stats.clone(), goaway, auth, + credential, estimate, bandwidth: crate::bandwidth::Allocator::default(), peer_implementation, diff --git a/rs/moq-net/src/session.rs b/rs/moq-net/src/session.rs index 47f5fee479b..fd6c7a2e7f5 100644 --- a/rs/moq-net/src/session.rs +++ b/rs/moq-net/src/session.rs @@ -171,6 +171,7 @@ pub struct Session { bandwidth: bandwidth::Allocator, goaway: Arc, auth: auth::Handle, + credential: Option, } impl Session { @@ -372,6 +373,11 @@ impl Session { pub fn auth(&self) -> auth::Handle { self.auth.clone() } + + /// The connection credential this side presents on AUTH, or `None` when this session offers no AUTH. + pub(crate) fn credential(&self) -> Option<&auth::Auth> { + self.credential.as_ref() + } } /// The handles a protocol driver shares with its [`Session`]. @@ -379,6 +385,8 @@ pub(super) struct Handles { pub stats: crate::stats::Session, pub goaway: goaway::Handle, pub auth: auth::Link, + /// The connection credential the driver presented on `auth`, when its version has AUTH. + pub credential: Option, /// Where the driver publishes [`Estimate`] changes, for a protocol that reports /// them to the peer (moq-lite PROBE). Sampled only while a consumer exists. pub estimate: Option>, @@ -400,6 +408,7 @@ impl Session { let Handles { goaway, auth, + credential, estimate, stats: context, bandwidth, @@ -468,6 +477,7 @@ impl Session { bandwidth, goaway, auth: auth.handle().clone(), + credential, }; let driver = crate::Driver::new( runtime.clone(), diff --git a/rs/moq-tokio/src/client.rs b/rs/moq-tokio/src/client.rs index f5e5370bcdc..a0da27e7ec4 100644 --- a/rs/moq-tokio/src/client.rs +++ b/rs/moq-tokio/src/client.rs @@ -46,11 +46,11 @@ pub struct Client { /// every transport (passed into the QUIC backend's `connect` and used directly for /// raw TCP/UDS qmux and WebSocket). Resolved once in [`Client::new`] so the ALPN list /// can't diverge between transports. - versions: moq_net::Versions, + pub(crate) versions: moq_net::Versions, /// The URL from [`connect.url`](crate::connect::Config::url), dialed by [`Client::publish`] / [`Client::consume`]. connect: Option, - /// The credentials every dial presents, shared with each clone. - tokens: crate::connect::Tokens, + /// The credentials each new connection starts presenting. + pub(crate) tokens: Vec, /// Deadline for one [`Client::connect`], from [`crate::connect::Config::timeout`]. Zero waits forever. #[cfg(feature = "_transport")] timeout: std::time::Duration, @@ -157,7 +157,7 @@ impl Client { moq, versions, connect: config.url, - tokens: crate::connect::Tokens::new(config.tokens), + tokens: config.tokens, timeout, reconnect: true, backoff: config.backoff, @@ -257,13 +257,6 @@ impl Client { self } - /// The credentials every dial presents, seeded from - /// [`connect.tokens`](crate::connect::Config::tokens). Set new ones before the old - /// ones expire. - pub fn tokens(&self) -> crate::connect::Tokens { - self.tokens.clone() - } - /// Override whether this client redials after a session drop. /// /// Defaults to true. Each clone can choose its own reconnect policy. @@ -370,10 +363,6 @@ impl Client { } /// What a dial to `url` presents of `tokens`, given the versions this client offers. - pub(crate) fn credential(&self, url: &Url, tokens: &crate::connect::Set) -> crate::connect::Credential { - crate::connect::Credential::new(url, &self.versions, tokens) - } - /// Dial the given URL and complete the MoQ handshake. /// /// Errors if no transport feature is compiled in. @@ -387,14 +376,14 @@ impl Client { pub(crate) async fn dial( &self, _addr: crate::connect::Addr, - _credential: &crate::connect::Credential, + _presented: &moq_net::auth::Dial, ) -> crate::Result { Err(Error::NoBackend( "no backend compiled; enable quic, iroh, websocket, tcp, or uds feature", )) } - /// Dial the given URL and complete the MoQ handshake, presenting `credential`. + /// Dial the given URL and complete the MoQ handshake, presenting what `presented` decided. /// /// The scheme picks the transport, and `https://` races QUIC against the /// WebSocket fallback so a blocked UDP path still connects. The session's @@ -410,20 +399,17 @@ impl Client { pub(crate) async fn dial( &self, addr: crate::connect::Addr, - credential: &crate::connect::Credential, + presented: &moq_net::auth::Dial, ) -> crate::Result { - let addr = addr.with_url(credential.url.clone()); + let addr = addr.with_url(presented.url.clone()); #[cfg(test)] if let Some(dialer) = &self.dialer { return dialer(addr).await; } - let client = match &credential.setup { + let client = match &presented.token { Some(token) => { let mut client = self.clone(); - client.moq = client.moq.with_token(moq_net::setup::Token { - kind: moq_net::setup::Token::OUT_OF_BAND, - value: token.as_str().as_bytes().to_vec(), - }); + client.moq = client.moq.with_token(token.clone()); std::borrow::Cow::Owned(client) } None => std::borrow::Cow::Borrowed(self), @@ -930,7 +916,7 @@ mod tests { #[test] fn test_connect_tokens() { let config = Cli::config_from(["test", "--connect-token", "first", "--connect-token", "second"]); - let tokens: Vec<&str> = config.tokens.iter().map(crate::connect::Token::as_str).collect(); + let tokens: Vec<&str> = config.tokens.iter().map(moq_net::auth::Token::as_str).collect(); assert_eq!(tokens, ["first", "second"]); let config: crate::connect::Config = toml::from_str(r#"tokens = ["first"]"#).unwrap(); @@ -1417,8 +1403,8 @@ mod tests { // `dial` rather than `connect`: this is about one attempt's deadline, and // `connect` now hands back a reconnect loop that would redial past it. - let credential = client.credential(&url, &Default::default()); - let mut attempt = Box::pin(client.dial(url.into(), &credential)); + let presented = moq_net::auth::Tokens::new(Vec::new()).dial(&url, &client.versions); + let mut attempt = Box::pin(client.dial(url.into(), &presented)); let _silent = tokio::select! { res = &mut attempt => match res { Err(err) => panic!("connect failed before the silent peer accepted it: {err}"), diff --git a/rs/moq-tokio/src/connect.rs b/rs/moq-tokio/src/connect.rs index 64bc47d26fe..b05c53ec3f0 100644 --- a/rs/moq-tokio/src/connect.rs +++ b/rs/moq-tokio/src/connect.rs @@ -8,10 +8,6 @@ use crate::connection::Goaway; use std::net; use url::Url; -mod token; -pub(crate) use token::{Credential, Set}; -pub use token::{EmptyToken, Token, Tokens}; - /// Maximum time for one dial, unless overridden by `--connect-timeout`. pub(crate) const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); @@ -517,7 +513,7 @@ pub struct Config { /// while an offered version can't carry it in SETUP (lite before 07). Each other /// token rides its own AUTH stream, widening the session's grant. A URL that /// already has a `?jwt=` keeps it as the connection credential, and then every - /// token rides AUTH. Replace them while running through `Client::tokens`. + /// token rides AUTH. Replace a connection's through `Connection::tokens`. #[serde(default, skip_serializing_if = "Vec::is_empty")] #[usage( name = "connect-token", @@ -525,7 +521,7 @@ pub struct Config { env = "MOQ_CONNECT_TOKEN", setting = "connect.tokens" )] - pub tokens: Vec, + pub tokens: Vec, /// The released `connect` key, kept so [`deprecated`](Self::deprecated) can name [`url`](Self::url). #[serde(default, skip_serializing)] diff --git a/rs/moq-tokio/src/connect/token.rs b/rs/moq-tokio/src/connect/token.rs deleted file mode 100644 index 247f99ece0a..00000000000 --- a/rs/moq-tokio/src/connect/token.rs +++ /dev/null @@ -1,318 +0,0 @@ -//! The credentials a client presents, kept out of logs and replaceable while it runs. - -use moq_net::kio; -use url::Url; - -/// A credential to present when dialing, such as a JWT. -/// -/// Its `Debug` shows only the length, so a dumped config never leaks it. -#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(try_from = "String", into = "String")] -pub struct Token(String); - -impl Token { - /// The credential itself. - pub fn as_str(&self) -> &str { - &self.0 - } -} - -impl std::fmt::Debug for Token { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "Token(<{} bytes>)", self.0.len()) - } -} - -impl std::str::FromStr for Token { - type Err = EmptyToken; - - fn from_str(token: &str) -> Result { - Self::try_from(token.to_string()) - } -} - -impl TryFrom for Token { - type Error = EmptyToken; - - fn try_from(token: String) -> Result { - match token.is_empty() { - true => Err(EmptyToken), - false => Ok(Self(token)), - } - } -} - -impl From for String { - fn from(token: Token) -> Self { - token.0 - } -} - -/// An empty token, which presents no credential. -#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] -#[error("a token cannot be empty")] -#[non_exhaustive] -pub struct EmptyToken; - -/// The tokens a client presents, which every dial reads afresh. -/// -/// Clones share one set, as do the [`crate::Client`] clones it came from. Replacing it -/// reaches the next dial and, on a live session with AUTH, presents the new tokens at -/// once, withdrawing the ones they replace only after every new one has its answer. -#[derive(Clone)] -pub struct Tokens(kio::Producer); - -/// One version of the tokens, numbered so a dial can tell whether they changed since. -#[derive(Clone, Default)] -pub(crate) struct Set { - pub tokens: Vec, - pub generation: u64, -} - -impl Tokens { - #[cfg(any(feature = "_transport", test))] - pub(crate) fn new(tokens: Vec) -> Self { - Self(kio::Producer::new(Set { tokens, generation: 0 })) - } - - /// Replace every token. The first is the connection credential, unless the dial URL - /// carries its own `?jwt=`. - pub fn set(&self, tokens: Vec) { - // Never closed: this handle is a producer. - let Ok(mut set) = self.0.write() else { return }; - if set.tokens != tokens { - set.tokens = tokens; - set.generation += 1; - } - } - - pub(crate) fn snapshot(&self) -> Set { - self.0.read().clone() - } - - pub(crate) fn consume(&self) -> kio::Consumer { - self.0.consume() - } -} - -/// What one dial presents, decided from its URL, the offered versions, and the tokens. -#[derive(Clone)] -pub(crate) struct Credential { - /// The URL to dial, carrying the connection credential in its query when an offered - /// version has no SETUP token. - #[cfg_attr( - not(any(feature = "_transport", test)), - allow(dead_code, reason = "only a compiled transport dials the URL") - )] - pub url: Url, - /// The token SETUP carries, unless the URL brought its own credential. - #[cfg_attr( - not(any(feature = "_transport", test)), - allow(dead_code, reason = "only a compiled transport sends SETUP") - )] - pub setup: Option, - /// The credential the connection presents, from the URL or SETUP. Never also - /// presented on an AUTH stream. - connection: Option, -} - -impl Credential { - pub fn new(url: &Url, versions: &moq_net::Versions, set: &Set) -> Self { - if let Some(jwt) = jwt(url) { - // The URL's own credential (a cluster's per-peer `?jwt=`) wins, so the tokens - // all ride AUTH and no second credential reaches SETUP or the query. - return Self { - url: url.clone(), - setup: None, - connection: Some(jwt), - }; - } - let Some(first) = set.tokens.first() else { - return Self { - url: url.clone(), - setup: None, - connection: None, - }; - }; - // The URL is fixed before the version is negotiated, so it carries the credential - // whenever a version that may be picked could not carry it in SETUP. - let url = match versions.iter().all(|version| version.has_setup_token()) { - true => url.clone(), - false => with_jwt(url, first.as_str()), - }; - Self { - url, - setup: Some(first.clone()), - connection: Some(first.as_str().to_string()), - } - } - - /// The tokens to hold on their own AUTH streams, each once. - pub fn extra(&self, tokens: &[Token]) -> Vec { - let mut extra: Vec = Vec::new(); - for token in tokens { - if self.connection.as_deref() != Some(token.as_str()) && !extra.contains(token) { - extra.push(token.clone()); - } - } - extra - } -} - -/// The request target's query: the URL's own, or for `unix:` the one inside `?path=`. -fn target_query(url: &Url) -> Option { - match url.scheme() { - "unix" => url - .query_pairs() - .find(|(k, _)| k == "path") - .and_then(|(_, path)| path.split_once('?').map(|(_, query)| query.to_string())), - _ => url.query().map(str::to_string), - } -} - -/// The non-empty `jwt` the URL's request target already carries. -fn jwt(url: &Url) -> Option { - let query = target_query(url)?; - url::form_urlencoded::parse(query.as_bytes()) - .find(|(k, v)| k == "jwt" && !v.is_empty()) - .map(|(_, v)| v.into_owned()) -} - -/// `url` with `jwt` appended to its request target's query. -fn with_jwt(url: &Url, jwt: &str) -> Url { - let mut url = url.clone(); - if url.scheme() != "unix" { - url.query_pairs_mut().append_pair("jwt", jwt); - return url; - } - // A unix socket's request target is one form-encoded `?path=` value, so the - // credential joins the query inside it. - let pairs: Vec<(String, String)> = url.query_pairs().into_owned().collect(); - let mut serializer = url::form_urlencoded::Serializer::new(String::new()); - let mut found = false; - for (k, v) in &pairs { - match k == "path" { - true => { - found = true; - let mut target = url::form_urlencoded::Serializer::new(String::new()); - target.append_pair("jwt", jwt); - let separator = if v.contains('?') { '&' } else { '?' }; - serializer.append_pair(k, &format!("{v}{separator}{}", target.finish())); - } - false => { - serializer.append_pair(k, v); - } - } - } - if !found { - let mut target = url::form_urlencoded::Serializer::new(String::new()); - target.append_pair("jwt", jwt); - serializer.append_pair("path", &format!("?{}", target.finish())); - } - url.set_query(Some(&serializer.finish())); - url -} - -#[cfg(test)] -mod tests { - use super::*; - - fn tokens(tokens: &[&str]) -> Set { - Set { - tokens: tokens.iter().map(|token| token.parse().unwrap()).collect(), - generation: 3, - } - } - - fn versions(names: &[&str]) -> moq_net::Versions { - names - .iter() - .map(|name| name.parse::().unwrap()) - .collect::>() - .into() - } - - /// Only lite-07 and moq-transport carry the credential in SETUP, so the URL stays clean. - #[test] - fn setup_versions_keep_the_credential_out_of_the_url() { - let url: Url = "https://relay.example.com/room".parse().unwrap(); - let credential = Credential::new( - &url, - &versions(&["moq-lite-07-wip", "moq-transport-17"]), - &tokens(&["a", "b"]), - ); - assert_eq!(credential.url, url); - assert_eq!(credential.setup.as_ref().map(Token::as_str), Some("a")); - assert_eq!(credential.extra(&tokens(&["a", "b"]).tokens), tokens(&["b"]).tokens); - } - - /// An offered version without a SETUP token needs the credential in the query, and the - /// same value rides SETUP too. - #[test] - fn an_older_version_puts_the_credential_in_the_url() { - let url: Url = "https://relay.example.com/room?x=1".parse().unwrap(); - let credential = Credential::new(&url, &moq_net::Versions::all(), &tokens(&["a b"])); - assert_eq!(credential.url.as_str(), "https://relay.example.com/room?x=1&jwt=a+b"); - assert_eq!(credential.setup.as_ref().map(Token::as_str), Some("a b")); - assert!(credential.extra(&tokens(&["a b"]).tokens).is_empty()); - } - - /// A URL credential stays the connection credential, so every token rides AUTH, - /// except one equal to it, which would be granted twice. - #[test] - fn a_url_credential_sends_every_token_on_auth() { - let url: Url = "moqt://relay.example.com/room?jwt=peer".parse().unwrap(); - let credential = Credential::new(&url, &moq_net::Versions::all(), &tokens(&["a", "peer", "a"])); - assert_eq!(credential.url, url); - assert_eq!(credential.setup, None); - assert_eq!( - credential.extra(&tokens(&["a", "peer", "a"]).tokens), - tokens(&["a"]).tokens - ); - } - - #[test] - fn no_tokens_present_nothing() { - let url: Url = "https://relay.example.com/room".parse().unwrap(); - let credential = Credential::new(&url, &moq_net::Versions::all(), &Set::default()); - assert_eq!(credential.url, url); - assert_eq!(credential.setup, None); - } - - /// A unix socket's request target lives in `?path=`, so the credential goes inside it. - #[test] - fn a_unix_credential_joins_the_path_target() { - for (url, expected) in [ - ("unix:///tmp/moq.sock?path=%2Froom", "/room?jwt=a"), - ("unix:///tmp/moq.sock?path=%2Froom%3Fx%3D1", "/room?x=1&jwt=a"), - ("unix:///tmp/moq.sock", "?jwt=a"), - ] { - let url: Url = url.parse().unwrap(); - let credential = Credential::new(&url, &moq_net::Versions::all(), &tokens(&["a"])); - let path = credential - .url - .query_pairs() - .find(|(k, _)| k == "path") - .map(|(_, v)| v.into_owned()); - assert_eq!(path.as_deref(), Some(expected), "{url}"); - // The rewritten target is read back as already carrying the credential. - assert_eq!(jwt(&credential.url).as_deref(), Some("a")); - } - } - - #[test] - fn a_token_never_logs_its_value() { - let token: Token = "secret".parse().unwrap(); - assert_eq!(format!("{token:?}"), "Token(<6 bytes>)"); - assert!("".parse::().is_err()); - } - - #[test] - fn set_bumps_the_generation_only_on_change() { - let tokens = Tokens::new(vec!["a".parse().unwrap()]); - tokens.set(vec!["a".parse().unwrap()]); - assert_eq!(tokens.snapshot().generation, 0); - tokens.set(vec!["b".parse().unwrap()]); - assert_eq!(tokens.snapshot().generation, 1); - } -} diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index 30a660aac23..549cf4e9355 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -1,7 +1,5 @@ //! The reconnect loop around a session, and the [`Monitor`] that observes it. -mod tokens; - use std::task::{Poll, ready}; use std::time::Duration; @@ -38,10 +36,10 @@ fn attempt_timeout(index: usize, total: usize) -> Option { /// Whether `err` refused the credential a dial presented while the client has since been /// given new tokens, which earns another dial instead of ending the loop. It never /// retries a rejected credential: a refusal of unchanged tokens stays terminal. -fn refreshed(err: &Error, client: &Client, generation: u64) -> bool { +fn refreshed(err: &Error, tokens: &moq_net::auth::Tokens, presented: Option<&moq_net::auth::Dial>) -> bool { let refused = err.is_auth() || matches!(err, Error::MoqNet(err) if moq_net::SessionError::from(err) == moq_net::SessionError::Unauthorized); - refused && client.tokens().snapshot().generation != generation + refused && presented.is_some_and(|presented| tokens.changed(presented)) } /// Whether a failed candidate is the peer's answer for every candidate, ending the walk. @@ -625,6 +623,8 @@ struct Shared { closed: CloseGuard, /// The auth handle every session is built on, ended after the loop and any close drain. auth: moq_net::auth::Handle, + /// The tokens every dial presents, on `auth`'s sessions. + tokens: moq_net::auth::Tokens, } impl Shared { @@ -928,6 +928,8 @@ pub struct Connection { state: kio::Consumer, /// The auth handle every session of the loop is built on. auth: moq_net::auth::Handle, + /// The tokens every dial of the loop presents. + tokens: moq_net::auth::Tokens, /// Persistent send-bitrate estimate, fed by the loop from each live session. send_bandwidth: BandwidthConsumer, /// Divides `send_bandwidth`, and every session the loop dials probes for its reservations. @@ -951,7 +953,6 @@ struct Task { /// Resources owned by the loop, retained by a graceful close until its sessions drain. struct Running { shared: Shared, - tokens: tokens::Holder, } /// Serializes [`Connection::abort`] and [`Connection::close`] against the loop publishing a fresh session. @@ -968,7 +969,8 @@ impl Connection { pub(crate) fn new(mut client: Client, addrs: Addrs) -> Self { let producer = kio::Producer::::default(); let state = producer.consume(); - let auth = moq_net::auth::Handle::new(); + let tokens = moq_net::auth::Tokens::new(client.tokens.clone()); + let auth = tokens.handle(); client.moq = client.moq.with_auth(auth.clone()); // The loop feeds these across every reconnect, so a consumer's handle survives session churn @@ -990,19 +992,17 @@ impl Connection { recv_bw, closed: task_closed, auth: auth.clone(), + tokens: tokens.clone(), }; - let running = std::sync::Arc::new(Running { - shared, - tokens: tokens::Holder::new(auth.clone(), client.tokens().consume()), - }); + let running = std::sync::Arc::new(Running { shared }); let task_running = std::sync::Arc::downgrade(&running); let task = tokio::spawn(async move { let shared = &running.shared; let reconnect = client.reconnect; // Isolated inside `shared`, so a panic still records a terminal error // instead of closing the channels as if the caller had stopped it. - let res = crate::panic::isolate(Self::run(shared, client, addrs, &running.tokens)) + let res = crate::panic::isolate(Self::run(shared, client, addrs)) .await .unwrap_or(Err(Error::Panic)); if let Err(err) = res { @@ -1024,6 +1024,7 @@ impl Connection { }), state, auth, + tokens, send_bandwidth, recv_bandwidth, bandwidth, @@ -1103,7 +1104,7 @@ impl Connection { Ok(session.and(predecessor)?) } - async fn run(shared: &Shared, client: Client, addrs: Addrs, held: &tokens::Holder) -> crate::Result<()> { + async fn run(shared: &Shared, client: Client, addrs: Addrs) -> crate::Result<()> { let backoff = client.backoff.clone(); let goaway = client.goaway.resolve(); let pacing = Pacing::new(&backoff); @@ -1128,13 +1129,14 @@ impl Connection { return Err(err.into()); } - // Read once per dial, so a refusal is judged against what this dial presented. - let tokens = client.tokens().snapshot(); - match Self::dial_any(shared, &client, &addrs, &mut draining, &tokens, held).await { + // What the last dial presented, so a refusal is judged against it. + let mut presented = None; + match Self::dial_any(shared, &client, &addrs, &mut draining, &mut presented).await { Ok((addr, dialed)) => { let url = addr.url().clone(); tracing::info!(peer = %Endpoint(&url), transport = %dialed.transport, "connected"); shared.connected(&dialed.session, dialed.transport); + shared.tokens.connected(&dialed.session); let session = dialed.session; let connected = moq_clock::now(); @@ -1144,7 +1146,7 @@ impl Connection { let ended = run_session(shared, &session, &mut draining, client.restart).await; // A refusal is terminal unless the tokens changed since this dial read them. let refreshed = match &ended { - Ended::Closed(Err(err)) => refreshed(err, &client, tokens.generation), + Ended::Closed(Err(err)) => refreshed(err, &shared.tokens, presented.as_ref()), _ => false, }; @@ -1333,7 +1335,8 @@ impl Connection { } } Err(err) => { - if (err.is_terminal() && !refreshed(&err, &client, tokens.generation)) || !client.reconnect { + if (err.is_terminal() && !refreshed(&err, &shared.tokens, presented.as_ref())) || !client.reconnect + { return Err(err); } shared.retrying(&err); @@ -1373,8 +1376,7 @@ impl Connection { client: &Client, addrs: &Addrs, draining: &mut Option, - tokens: &crate::connect::Set, - held: &tokens::Holder, + presented: &mut Option, ) -> crate::Result<(crate::connect::Addr, crate::client::Dialed)> { let candidates = addrs.as_slice(); let mut last = None; @@ -1387,9 +1389,8 @@ impl Connection { // Held before the dial starts its session's driver, so a request the session // sends early waits on their answers rather than being refused outside the // connection credential's grant. - let credential = client.credential(url, tokens); - held.dialed(&credential); - let mut dial = std::pin::pin!(client.dial(addr.clone(), &credential)); + let presenting = presented.insert(shared.tokens.dial(url, &client.versions)); + let mut dial = std::pin::pin!(client.dial(addr.clone(), presenting)); let dialed = kio::wait(|waiter| { if poll_draining(draining, waiter) { shared.disconnected(); @@ -1590,6 +1591,13 @@ impl Connection { self.auth.clone() } + /// The tokens every dial of this connection presents, seeded from + /// [`connect.tokens`](crate::connect::Config::tokens). Set new ones before the old + /// ones expire, and read the peer's answer from them. + pub fn tokens(&self) -> moq_net::auth::Tokens { + self.tokens.clone() + } + /// Observe the connection's statistics and presence across reconnects. /// /// The handle keeps working across reconnects without keeping the connection loop alive. @@ -2686,19 +2694,17 @@ mod tests { } fn shared() -> Shared { + let tokens = moq_net::auth::Tokens::new(Vec::new()); Shared { state: kio::Producer::default(), send_bw: BandwidthProducer::new(), recv_bw: BandwidthProducer::new(), closed: CloseGuard::default(), - auth: moq_net::auth::Handle::new(), + auth: tokens.handle(), + tokens, } } - fn held(shared: &Shared, client: &Client) -> super::tokens::Holder { - super::tokens::Holder::new(shared.auth.clone(), client.tokens().consume()) - } - /// The first address that answers wins, however many dead ones precede it. /// This is what keeps a peer reachable when discovery advertises an interface /// that doesn't route from here ahead of the one that does. @@ -2717,14 +2723,7 @@ mod tests { let (connected, _session) = tokio::time::timeout( WALK_TIMEOUT, - Connection::dial_any( - &shared, - &client, - &addrs, - &mut draining, - &Default::default(), - &held(&shared, &client), - ), + Connection::dial_any(&shared, &client, &addrs, &mut draining, &mut None), ) .await .expect("the walk must not hang") @@ -2746,14 +2745,7 @@ mod tests { let result = tokio::time::timeout( WALK_TIMEOUT, - Connection::dial_any( - &shared, - &client, - &addrs, - &mut draining, - &Default::default(), - &held(&shared, &client), - ), + Connection::dial_any(&shared, &client, &addrs, &mut draining, &mut None), ) .await .expect("the walk must not hang"); @@ -2781,16 +2773,7 @@ mod tests { let shared = shared(); let mut draining = None; // `Session` isn't `Debug`, so unwrap the failure by hand. - let Err(err) = Connection::dial_any( - &shared, - &client, - &addrs, - &mut draining, - &Default::default(), - &held(&shared, &client), - ) - .await - else { + let Err(err) = Connection::dial_any(&shared, &client, &addrs, &mut draining, &mut None).await else { panic!("a dead address must fail"); }; @@ -3672,9 +3655,8 @@ mod tests { })); let addrs = Addrs::new("moqt://relay.example.com/".parse::().unwrap()); - let held = held(&shared, &client); - let tokens = client.tokens().snapshot(); - let (_, dialed) = Connection::dial_any(&shared, &client, &addrs, &mut None, &tokens, &held) + shared.tokens.set(client.tokens.clone()); + let (_, dialed) = Connection::dial_any(&shared, &client, &addrs, &mut None, &mut None) .await .expect("the dial failed"); diff --git a/rs/moq-tokio/src/connection/tokens.rs b/rs/moq-tokio/src/connection/tokens.rs deleted file mode 100644 index b264d8cb626..00000000000 --- a/rs/moq-tokio/src/connection/tokens.rs +++ /dev/null @@ -1,382 +0,0 @@ -//! The configured tokens a connection holds on its auth handle, beside each dial's -//! connection credential. - -use std::sync::{Arc, Mutex}; -use std::task::Poll; - -use bytes::Bytes; -use futures::FutureExt; -use moq_net::{auth, kio}; - -use crate::abort::AbortOnDrop; -use crate::connect::{Credential, Set, Token}; - -type Opening = futures::future::BoxFuture<'static, moq_net::Result<(auth::Auth, auth::Answer)>>; - -/// Holds every configured token except the latest dial's connection credential on the -/// connection's auth handle, which presents them on each session it builds, and keeps -/// them in step with the client's [`crate::connect::Tokens`]. -pub(super) struct Holder { - shared: Arc, - _task: AbortOnDrop, -} - -struct Shared { - state: Mutex, - dialed: tokio::sync::Notify, -} - -struct Holding { - auth: auth::Handle, - tokens: Vec, - /// `None` until the first dial, so a token that becomes the connection credential is - /// never also presented in band. - credential: Option, - held: Held, -} - -impl Holder { - pub fn new(auth: auth::Handle, tokens: kio::Consumer) -> Self { - let set = (*tokens.read()).clone(); - let shared = Arc::new(Shared { - state: Mutex::new(Holding { - auth, - tokens: set.tokens, - credential: None, - held: Held::default(), - }), - dialed: tokio::sync::Notify::new(), - }); - let task = tokio::spawn(run(shared.clone(), tokens, set.generation)); - Self { - shared, - _task: AbortOnDrop::new(task), - } - } - - /// Hold the tokens `credential` leaves over. Call it before the dial that presents - /// `credential` starts: the new tokens register before this returns, so the session - /// presents them from its start. - pub fn dialed(&self, credential: &Credential) { - let mut state = self.shared.state.lock().unwrap(); - state.credential = Some(credential.clone()); - state.held.unsupported = false; - state.update(); - drop(state); - self.shared.dialed.notify_one(); - } -} - -impl Holding { - fn update(&mut self) { - let Some(credential) = &self.credential else { return }; - let extra = credential.extra(&self.tokens); - self.held.update(&self.auth, extra); - } -} - -async fn run(shared: Arc, tokens: kio::Consumer, mut generation: u64) { - loop { - let changed = async { - let wait = tokens.wait(|set| match set.generation != generation { - true => Poll::Ready((set.tokens.clone(), set.generation)), - false => Poll::Pending, - }); - // Every client handle dropped, so the tokens can no longer change. - match wait.await { - Ok(changed) => changed, - Err(_) => std::future::pending().await, - } - }; - let answered = std::future::poll_fn(|cx| shared.state.lock().unwrap().held.poll_answers(cx)); - tokio::select! { - biased; - (latest, next) = changed => { - generation = next; - let mut state = shared.state.lock().unwrap(); - state.tokens = latest; - state.update(); - } - // A dial added tokens to wait on. - _ = shared.dialed.notified() => {} - _ = answered => {} - } - } -} - -/// The configured tokens held on their own AUTH streams. -#[derive(Default)] -struct Held { - tokens: Vec<(Token, Presented)>, - /// Tokens a change replaced, answered or not, kept presented until every - /// replacement has its answer so the grant never narrows in between. - retiring: Vec, - /// Whether the latest dial already logged that its session carries no extra tokens. - unsupported: bool, -} - -enum Presented { - Waiting(Opening), - Granted(#[allow(dead_code, reason = "held to keep the token presented")] auth::Auth), - /// Refused or unsupported. Not presented again unless a change removes and re-adds it. - Refused, -} - -impl Held { - fn update(&mut self, handle: &auth::Handle, tokens: Vec) { - let mut old = std::mem::take(&mut self.tokens); - for token in tokens { - let answer = match old.iter().position(|(held, _)| *held == token) { - Some(index) => old.swap_remove(index).1, - None => { - let handle = handle.clone(); - let bytes = Bytes::from(token.as_str().to_string()); - let mut opening = async move { handle.add(bytes).await }.boxed(); - // The first poll registers the token synchronously. - if let Some(result) = opening.as_mut().now_or_never() { - opening = futures::future::ready(result).boxed(); - } - Presented::Waiting(opening) - } - }; - self.tokens.push((token, answer)); - } - // A waiting registration may already hold its grant, unread, so it retires too. - self.retiring.extend( - old.into_iter() - .map(|(_, answer)| answer) - .filter(|answer| !matches!(answer, Presented::Refused)), - ); - self.settle(); - } - - /// Resolve when another token has its answer. - fn poll_answers(&mut self, cx: &mut std::task::Context<'_>) -> Poll<()> { - let mut answered = false; - let mut unsupported = false; - for (_, answer) in &mut self.tokens { - let Presented::Waiting(opening) = answer else { continue }; - let Poll::Ready(result) = opening.as_mut().poll(cx) else { - continue; - }; - answered = true; - *answer = match result { - Ok((auth, answer)) => { - // Without AUTH, moq-transport takes a token only for the requests that name - // it, but a configured token rides no request, so this session sends it - // nowhere. The handle still presents it on a later session that has AUTH. - if answer == auth::Answer::Requests { - unsupported = true; - } - Presented::Granted(auth) - } - Err(moq_net::Error::Unsupported) => { - unsupported = true; - Presented::Refused - } - Err(err) => { - tracing::warn!(%err, "a configured token was refused"); - Presented::Refused - } - }; - } - if unsupported && !std::mem::replace(&mut self.unsupported, true) { - tracing::debug!("the peer takes no tokens in band; presenting only the connection credential"); - } - self.settle(); - match answered { - true => Poll::Ready(()), - false => Poll::Pending, - } - } - - /// Withdraw the replaced tokens once nothing is waiting on an answer. - fn settle(&mut self) { - if !self - .tokens - .iter() - .any(|(_, answer)| matches!(answer, Presented::Waiting(_))) - { - self.retiring.clear(); - } - } -} - -#[cfg(all(test, feature = "tcp"))] -mod tests { - use super::*; - - struct Pair { - _client: moq_net::Session, - auth: auth::Handle, - requests: tokio::sync::mpsc::UnboundedReceiver, - _tasks: Vec>, - _acceptor: AbortOnDrop, - } - - async fn pair_on(version: &str) -> Pair { - let versions = moq_net::Versions::from(version.parse::().unwrap()); - let config = || { - let mut config = qmux::Config::new(qmux::Version::QMux01); - config.protocol = qmux::Protocol::Negotiate(versions.alpns().iter().map(|alpn| alpn.to_string()).collect()); - config - }; - let stream = |io| qmux::transport::Stream::new(io); - let (client, server) = tokio::io::duplex(64 * 1024); - let (client, server) = tokio::try_join!( - qmux::Session::connect(stream(client), config()), - qmux::Session::accept(stream(server), config()) - ) - .unwrap(); - let now = moq_net::time::Instant::now(); - let handle = auth::Handle::new(); - let client = async { - let (session, driver) = moq_net::Client::new() - .with_versions(versions.clone()) - .with_auth(handle.clone()) - .connect(now, client) - .await - .unwrap(); - (session, AbortOnDrop::new(tokio::spawn(moq_net::time::run(driver)))) - }; - let server = async { - let mut request = moq_net::Server::new() - .with_versions(versions.clone()) - .accept_request(now, server) - .await - .unwrap(); - let mut requests = request.requests(); - let (session, driver) = request.ok().await.unwrap(); - let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); - let acceptor = tokio::spawn(async move { - let _session = session; - let mut initial = Vec::new(); - while let Some(request) = requests.next().await { - if request.token().is_empty() { - initial.push(request.accept(auth::Grant::default())); - } else if sender.send(request).is_err() { - break; - } - } - }); - ( - receiver, - AbortOnDrop::new(tokio::spawn(moq_net::time::run(driver))), - AbortOnDrop::new(acceptor), - ) - }; - let ((client, client_task), (requests, server_task, acceptor)) = tokio::join!(client, server); - Pair { - _client: client, - auth: handle, - requests, - _tasks: vec![client_task, server_task], - _acceptor: acceptor, - } - } - - /// A holder for `tokens` on a pair's client, dialed with the credential a lite-07 dial - /// to `url` would present. - fn holder(pair: &Pair, url: &str, tokens: &[&str]) -> (crate::connect::Tokens, Holder) { - let tokens = crate::connect::Tokens::new(tokens.iter().map(|token| token.parse().unwrap()).collect()); - let versions = moq_net::Versions::from("moq-lite-07-wip".parse::().unwrap()); - let credential = Credential::new(&url.parse().unwrap(), &versions, &tokens.snapshot()); - let holder = Holder::new(pair.auth.clone(), tokens.consume()); - holder.dialed(&credential); - (tokens, holder) - } - - async fn next_token(pair: &mut Pair) -> auth::Request { - moq_clock::timeout(std::time::Duration::from_secs(5), pair.requests.recv()) - .await - .expect("no token presented") - .unwrap() - } - - /// Every configured token but the connection credential rides its own AUTH stream. - #[tokio::test(start_paused = true)] - async fn configured_tokens_ride_auth_beside_the_connection_credential() { - let mut pair = pair_on("moq-lite-07-wip").await; - let (_tokens, _holder) = holder(&pair, "moqt://relay.example.com/", &["connection", "a", "b"]); - let mut presented = Vec::new(); - let mut issued = Vec::new(); - for _ in 0..2 { - let request = next_token(&mut pair).await; - presented.push(request.token().to_vec()); - issued.push(request.accept(auth::Grant::all())); - } - presented.sort(); - assert_eq!(presented, [b"a".to_vec(), b"b".to_vec()]); - let again = moq_clock::timeout(std::time::Duration::from_secs(1), pair.requests.recv()).await; - assert!(again.is_err(), "the connection credential was presented twice"); - } - - /// A URL that carries its own credential sends every configured token in band. - #[tokio::test(start_paused = true)] - async fn a_url_credential_sends_every_configured_token_in_band() { - let mut pair = pair_on("moq-lite-07-wip").await; - let (_tokens, _holder) = holder(&pair, "moqt://relay.example.com/?jwt=peer", &["a"]); - let request = next_token(&mut pair).await; - assert_eq!(request.token().as_ref(), b"a"); - } - - /// A replaced token is withdrawn only once its replacement has an answer, so the grant - /// never narrows in between. - #[tokio::test(start_paused = true)] - async fn a_replaced_token_is_withdrawn_after_its_replacement_is_answered() { - let mut pair = pair_on("moq-lite-07-wip").await; - let (tokens, _holder) = holder(&pair, "moqt://relay.example.com/", &["connection", "old"]); - let old = next_token(&mut pair).await.accept(auth::Grant::all()); - - tokens.set(vec!["connection".parse().unwrap(), "new".parse().unwrap()]); - let request = next_token(&mut pair).await; - assert_eq!(request.token().as_ref(), b"new"); - let early = moq_clock::timeout(std::time::Duration::from_secs(1), old.closed()).await; - assert!(early.is_err(), "withdrawn before its replacement was answered"); - - let new = request.accept(auth::Grant::all()); - moq_clock::timeout(std::time::Duration::from_secs(5), old.closed()) - .await - .expect("the replaced token was never withdrawn"); - let kept = moq_clock::timeout(std::time::Duration::from_secs(1), new.closed()).await; - assert!(kept.is_err(), "the replacement was withdrawn"); - } - - /// A replacement is authoritative: the replaced token is withdrawn once the peer - /// answers its replacement, even with a refusal. - #[tokio::test(start_paused = true)] - async fn a_refused_replacement_still_withdraws_the_replaced_token() { - let mut pair = pair_on("moq-lite-07-wip").await; - let (tokens, _holder) = holder(&pair, "moqt://relay.example.com/", &["connection", "old"]); - let old = next_token(&mut pair).await.accept(auth::Grant::all()); - - tokens.set(vec!["connection".parse().unwrap(), "new".parse().unwrap()]); - let request = next_token(&mut pair).await; - assert_eq!(request.token().as_ref(), b"new"); - request.reject(moq_net::SessionError::Unauthorized, "expired"); - moq_clock::timeout(std::time::Duration::from_secs(5), old.closed()) - .await - .expect("the replaced token outlived its refused replacement"); - } - - /// Without AUTH a configured token rides nothing on this session, which logs that once, - /// but the handle keeps it for a later session that has AUTH. - #[tokio::test(start_paused = true)] - async fn a_configured_token_without_auth_is_kept_for_a_later_session() { - let pair = pair_on("moq-transport-14").await; - let mut held = Held::default(); - held.update(&pair.auth, vec!["a".parse().unwrap(), "b".parse().unwrap()]); - moq_clock::timeout( - std::time::Duration::from_secs(5), - std::future::poll_fn(|cx| held.poll_answers(cx)), - ) - .await - .expect("no answer"); - assert!( - held.tokens - .iter() - .all(|(_, answer)| matches!(answer, Presented::Granted(_))) - ); - assert!(held.unsupported); - } -} diff --git a/rs/moq-tokio/tests/integration/tokens.rs b/rs/moq-tokio/tests/integration/tokens.rs index c8b095123b1..f0aeb3244d4 100644 --- a/rs/moq-tokio/tests/integration/tokens.rs +++ b/rs/moq-tokio/tests/integration/tokens.rs @@ -74,11 +74,17 @@ async fn serve(version: &str, refused: &'static str) -> Server { } fn client(version: &str, tokens: &[&str]) -> moq_tokio::Client { + config(version, tokens) + .init(Default::default()) + .expect("failed to init client") +} + +fn config(version: &str, tokens: &[&str]) -> moq_tokio::connect::Config { let mut config = moq_tokio::connect::Config::default(); config.tls.insecure = Some(true); config.version = vec![version.parse().unwrap()]; config.tokens = tokens.iter().map(|token| token.parse().unwrap()).collect(); - config.init(Default::default()).expect("failed to init client") + config } async fn next(server: &mut Server) -> Seen { @@ -104,13 +110,14 @@ async fn lite_07_presents_the_token_in_setup() { ); } -/// lite-05 has no SETUP token, so the credential rides the request target's query. +/// lite-05 has no SETUP token, so the credential rides the request target's query, and the +/// server's SETUP accepts it. #[tokio::test] async fn lite_05_presents_the_token_in_the_url() { let mut server = serve("moq-lite-05", "refused").await; let client = client("moq-lite-05", &["credential"]); let url: url::Url = format!("moqt://localhost:{}/room", server.port).parse().unwrap(); - let _connection = client.connect(url); + let connection = client.connect(url); assert_eq!( next(&mut server).await, Seen { @@ -118,6 +125,10 @@ async fn lite_05_presents_the_token_in_the_url() { token: None, } ); + tokio::time::timeout(Duration::from_secs(10), connection.tokens().answered()) + .await + .expect("the credential was never answered") + .expect("the credential was refused"); } /// A refused credential the client has since replaced is dialed again with the new one. @@ -129,23 +140,44 @@ async fn a_refused_credential_redials_with_its_replacement() { let connection = client.connect(url); assert_eq!(next(&mut server).await.token.as_deref(), Some("old")); - client.tokens().set(vec!["new".parse().unwrap()]); + let tokens = connection.tokens(); + tokens.set(vec!["new".parse().unwrap()]); server.release.notify_one(); assert_eq!(next(&mut server).await.token.as_deref(), Some("new")); - let _connection = tokio::time::timeout(Duration::from_secs(10), connection.established()) + tokio::time::timeout(Duration::from_secs(10), tokens.answered()) .await - .expect("the replacement never connected") + .expect("the replacement was never answered") .expect("the replacement was refused"); + assert!(connection.connected()); } /// Without a new credential, a refusal ends the connection rather than retrying it. #[tokio::test] async fn an_unchanged_refused_credential_is_terminal() { - let mut server = serve("moq-lite-07-wip", "old").await; - let client = client("moq-lite-07-wip", &["old"]); + refused_credential_is_terminal(config("moq-lite-07-wip", &["old"])).await; +} + +/// Without AUTH, a refusal after the session went live is still the answer, never a grant. +#[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; +} + +async fn refused_credential_is_terminal(config: moq_tokio::connect::Config) { + let version = config.version[0].to_string(); + let mut server = serve(&version, "old").await; + let client = config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("moqt://localhost:{}/", server.port).parse().unwrap(); let connection = client.connect(url); - assert_eq!(next(&mut server).await.token.as_deref(), Some("old")); + let tokens = connection.tokens(); + let seen = next(&mut server).await; + assert!( + seen.token.as_deref() == Some("old") || seen.query.as_deref() == Some("jwt=old"), + "{seen:?}" + ); server.release.notify_one(); // A lite client is live before the server's answer, so the refusal may close it after. let err = tokio::time::timeout(Duration::from_secs(10), async { @@ -156,11 +188,16 @@ async fn an_unchanged_refused_credential_is_terminal() { }) .await .expect("the refusal never ended the connection"); + let unauthorized = + |err: &moq_net::Error| matches!(err, moq_net::Error::Session(moq_net::SessionError::Unauthorized)); assert!( - matches!( - err, - moq_tokio::Error::MoqNet(moq_net::Error::Session(moq_net::SessionError::Unauthorized)) - ), + matches!(&err, moq_tokio::Error::MoqNet(err) if unauthorized(err)), "{err:?}" ); + // The refusal is the answer to the tokens that dial presented. + let answer = tokens + .answered() + .await + .expect_err("the refused credential was answered"); + assert!(unauthorized(&answer), "{answer:?}"); } diff --git a/swift/Sources/Moq/Auth.swift b/swift/Sources/Moq/Auth.swift index 5c7adb5c395..ceacf548fe6 100644 --- a/swift/Sources/Moq/Auth.swift +++ b/swift/Sources/Moq/Auth.swift @@ -1,3 +1,4 @@ +import Foundation import MoqFFI /// What the peer lets this side do, in this side's own paths: the broadcast @@ -5,50 +6,93 @@ import MoqFFI /// An empty pattern list grants nothing in that direction; `**` grants everything. public typealias Grant = MoqFFI.MoqGrant -/// A session's authorization: the grant its peer gave it, and more tokens to present. +/// Follows the grant a session's peer gave it. Iterate directly: +/// `for try await grant in session.grants() { ... }` yields the current grant, +/// then each change, `nil` while there is none. /// -/// Returned by `Session.auth()`. AUTH is only on `moq-lite-07-wip` and on +/// 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`. -public final class Auth: Sendable { - let ffi: MoqAuth +/// 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. + public typealias Element = Grant? - init(_ ffi: MoqAuth) { self.ffi = ffi } + let ffi: MoqGrantConsumer - /// The union of every token's grant, or `nil` until the peer first answers one. + init(_ ffi: MoqGrantConsumer) { self.ffi = ffi } + + /// The grant now, or `nil` until the peer first answers a token. /// A client session reads `nil` while it reconnects. public func grant() -> Grant? { ffi.grant() } - /// Suspend until the grant differs from the one last reported, or held when this - /// handle was made, returning it. + /// Suspend until the grant differs from the one this last returned, or held when + /// it was made, returning it. /// Throws once nothing will change it again: a client's connection or a server's - /// session ended. A reconnect is not an end. - public func grantChanged() async throws -> Grant? { try await ffi.grantChanged() } + /// session ended, or `cancel()`. A reconnect is not an end. + public func changed() async throws -> Grant? { try await ffi.changed() } - /// Present another token, returning once the peer accepts it. - /// - /// Its grant joins the union until `AuthToken.cancel()`; a client session presents - /// it again on every reconnect. The peer's refusal throws `MoqError.Protocol` - /// carrying its code, and a session that cannot carry another token throws - /// `MoqError.Unsupported`. - public func add(token: String) async throws -> AuthToken { - AuthToken(try await ffi.add(token: token)) + /// Cancel all current and future `changed()` calls. + public func cancel() { ffi.cancel() } + + /// Create an iterator that cancels the native wait when iteration ends. + public func makeAsyncIterator() -> AsyncThrowingStream.Iterator { + let first = First() + return moqStream(cancel: { [ffi] in ffi.cancel() }) { [ffi] () async throws -> Grant?? in + if first.take() { return .some(ffi.grant()) } + do { + return .some(try await ffi.changed()) + } catch let error as MoqError where error.isShutdown { + return nil + } + }.makeAsyncIterator() } } -/// One token presented with `Auth.add(token:)`, withdrawn by `cancel()`. -public final class AuthToken: Sendable { - let ffi: MoqAuthToken +/// Whether the current grant is still to be delivered, taken once. +private final class First: @unchecked Sendable { + private let lock = NSLock() + private var pending = true - init(_ ffi: MoqAuthToken) { self.ffi = ffi } + func take() -> Bool { + lock.lock() + defer { lock.unlock() } + defer { pending = false } + return pending + } +} - /// This token's own grant, or `nil` after it ended. - public func grant() -> Grant? { ffi.grant() } +/// The credentials a native client session presents, replaceable while it runs. +/// +/// Returned by `Session.tokens()`, seeded from `Client(tokens:)`. +public final class Tokens: Sendable { + let ffi: MoqTokens - /// Suspend until the token ends, throwing the peer's revocation or the end of a client's - /// connection or a server's session. A reconnect does not end it. - public func closed() async throws { try await ffi.closed() } + init(_ ffi: MoqTokens) { + self.ffi = ffi + } - /// Withdraw the token, removing its grant from the union. - public func cancel() { ffi.cancel() } + /// Replace the credentials every dial presents, such as before the current ones expire. + /// + /// The first is the connection credential, unless the URL carries its own `?jwt=`; + /// each other one widens the grant over in-band AUTH. The next dial presents them, + /// and a live session with in-band AUTH presents them at once, withdrawing each + /// replaced token once its replacements are answered, even when one is refused. + /// After an authorization refusal the session redials only if they changed. + /// - Throws: `MoqError.Config` for an empty token. + public func set(_ tokens: [String]) throws { + try ffi.set(tokens: tokens) + } + + /// Suspend until the peer's first verdict on the tokens the last `set` newly presented: + /// return once each is granted, in band or as a later dial's connection credential. + /// + /// A token the set kept counts only once refused, and nothing is re-checked after the + /// answer. Throws the peer's refusal as `MoqError.Protocol` carrying its code, + /// `MoqError.Unsupported` when the session cannot carry an in-band token, or the + /// connection's close reason. The native wait ends with that answer, not with the + /// calling task. + public func answered() async throws { + try await ffi.answered() + } } diff --git a/swift/Sources/Moq/Client.swift b/swift/Sources/Moq/Client.swift index c28e636fbd6..7a2eababdd9 100644 --- a/swift/Sources/Moq/Client.swift +++ b/swift/Sources/Moq/Client.swift @@ -14,8 +14,8 @@ public final class Client: Sendable { /// - tokens: Credentials every dial presents. The first is the connection credential, /// sent in SETUP and, while an offered version can't carry it there, the URL's `?jwt=`; /// each other one widens the session's grant over in-band AUTH. A URL that already - /// carries `?jwt=` keeps it, and then every token rides AUTH. Replace them through - /// `tokens()`. + /// carries `?jwt=` keeps it, and then every token rides AUTH. Replace a session's + /// through `Session.tokens()`. /// - timeout: How long one connect may take, dial and handshake together; 0 waits forever. /// - race: Happy Eyeballs: how long before the next resolved address is also dialed. /// - resolutionDelay: Happy Eyeballs: how long IPv4 waits for the full DNS answer. @@ -68,11 +68,6 @@ public final class Client: Sendable { Session(try await ffi.connect(url: url)) } - /// The credentials every dial presents, to replace while running. - public func tokens() -> Tokens { - Tokens(ffi.tokens()) - } - /// Cancel all current and future `connect()` calls. public func cancel() { ffi.cancel() @@ -81,25 +76,6 @@ public final class Client: Sendable { } -/// The credentials a `Client` presents, replaceable while it runs. -public final class Tokens: Sendable { - let ffi: MoqTokens - - init(_ ffi: MoqTokens) { - self.ffi = ffi - } - - /// Replace the credentials every dial presents, such as before the current ones expire. - /// - /// The next dial presents them, and a live session with in-band AUTH presents them at - /// once, withdrawing each replaced token once its replacements are answered, even when - /// one is refused. After an authorization refusal the client redials only if they changed. - /// - Throws: `MoqError.Config` for an empty token. - public func set(_ tokens: [String]) throws { - try ffi.set(tokens: tokens) - } -} - /// The protocol versions offered by default, most preferred first, spelled the way /// `Client(versions:)` takes them. public func versions() -> [String] { @@ -170,13 +146,18 @@ public final class Session: Sendable { ffi.stats() } - /// The session's authorization: the grant its peer gave it, and more tokens to present. + /// Follow the grant the peer gave this session. /// - /// Each call returns an independent watcher of the grant. A client session's - /// handle survives reconnects, presenting each added token again on every new - /// connection. - public func auth() -> Auth { - Auth(ffi.auth()) + /// Each call returns an independent consumer. A client session's grant follows + /// each reconnect, reading `nil` while offline. + public func grants() -> GrantConsumer { + GrantConsumer(ffi.grants()) + } + + /// The credentials a native client session presents, to replace while it runs; + /// `nil` for a server-accepted session, which presents none. + public func tokens() -> Tokens? { + ffi.tokens().map(Tokens.init) } /// Hold receive-estimate demand until the returned consumer is released. diff --git a/swift/Tests/MoqTests/SmokeTests.swift b/swift/Tests/MoqTests/SmokeTests.swift index 6628c9369f7..94d6969a52d 100644 --- a/swift/Tests/MoqTests/SmokeTests.swift +++ b/swift/Tests/MoqTests/SmokeTests.swift @@ -128,18 +128,20 @@ final class SmokeTests: XCTestCase { defer { watchdog.cancel() } let everything = Grant(publish: ["**"], subscribe: ["**"], expires: nil) - for auth in [session.auth(), peer.auth()] { - var grant = auth.grant() - while grant != everything { - grant = try await auth.grantChanged() + for side in [session, peer] { + for try await grant in side.grants() where grant == everything { + break } } + XCTAssertNil(peer.tokens(), "an accepted session presents no tokens") + guard let tokens = session.tokens() else { return XCTFail("a client session has tokens") } + try tokens.set(["extra"]) do { - _ = try await session.auth().add(token: "extra") + try await tokens.answered() XCTFail("the default acceptor refuses a token") } catch MoqError.Unsupported {} - XCTAssertEqual(session.auth().grant(), everything) + XCTAssertEqual(session.grants().grant(), everything) peer.cancel(code: 0) session.cancel(code: 0) diff --git a/test/interop/clients/cpp/main.cpp b/test/interop/clients/cpp/main.cpp index 65338dfbba7..4d46fc7c70f 100644 --- a/test/interop/clients/cpp/main.cpp +++ b/test/interop/clients/cpp/main.cpp @@ -138,10 +138,10 @@ std::shared_ptr connect(const std::string &url, const Dial &dial, auto client = ok(moq::Client::init(config), "client init"); open_session = until(client->connect(url), deadline, "connect"); if (dial.grant) { - auto auth = open_session->auth(); - auto grant = auth->grant(); + auto grants = open_session->grants(); + auto grant = grants->grant(); while (!grant) { - grant = until(auth->grant_changed(), deadline, "grant"); + grant = until(grants->changed(), deadline, "grant"); } std::fprintf( stderr, "auth granted publish=%s subscribe=%s\n", patterns(grant->publish).c_str(), diff --git a/test/interop/clients/go/main.go b/test/interop/clients/go/main.go index c1c5771b190..591a9e3618c 100644 --- a/test/interop/clients/go/main.go +++ b/test/interop/clients/go/main.go @@ -115,10 +115,11 @@ func dial(ctx context.Context, url string, opts dialOptions, timeout time.Durati ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() - auth := client.Session().Auth() - grant := auth.Grant() + grants := client.Session().Grants() + defer grants.Close() + grant := grants.Grant() for grant == nil { - if grant, err = auth.GrantChanged(ctx); err != nil { + if grant, err = grants.Changed(ctx); err != nil { client.Close() return nil, fmt.Errorf("grant: %w", err) } diff --git a/test/interop/clients/python/interop.py b/test/interop/clients/python/interop.py index e1f201ae7d4..fa6b7cca61c 100644 --- a/test/interop/clients/python/interop.py +++ b/test/interop/clients/python/interop.py @@ -78,12 +78,12 @@ async def _print_grant(client: moq.Client, timeout: float) -> None: """Wait for the relay's grant and print it, in the Rust client's `auth granted` shape.""" session = client.session assert session is not None - auth = session.auth() - async def first() -> moq.Grant: - while (grant := auth.grant()) is None: - await auth.grant_changed() - return grant + async with session.grants() as grants: + async for grant in grants: + if grant is not None: + return grant + raise RuntimeError("the session ended before a grant") grant = await asyncio.wait_for(first(), timeout) print( diff --git a/test/wasm/uniffi/cases.ts b/test/wasm/uniffi/cases.ts index 118808fb967..fb08d31051b 100644 --- a/test/wasm/uniffi/cases.ts +++ b/test/wasm/uniffi/cases.ts @@ -321,23 +321,6 @@ const remote: Record Promise> = { return closed; }, - "a token added while dialing ends with a refused dial": async (relay) => { - const session = await dial(relay, "00".repeat(32)); - // Taken before the dial settles, so the token waits for a session that never comes. - const adding = session.auth().add("token"); - const state = await settled(session); - if (state.phase !== MoqConnectionPhase.Closed) throw new Error(`settled ${state.phase}`); - const added = await settle( - adding, - 5000, - "add", - () => "resolved", - (err: unknown) => (err as Error).message, - ); - if (added === "resolved") throw new Error("add resolved after a refused dial"); - return added; - }, - "cancelling a dial closes it": async (relay) => { const session = await dial(relay); session.cancel(0);