diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 29f836b8..1484c732 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -409,6 +409,20 @@ await scope.ServiceProvider.GetRequiredService() await AssertConnectionClosesAsync(visitorConnection); } + [Test] + public async Task Hub_OwnerDeactivated_NewGuestCannotConnect() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubownerdeactnew", password: null); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService() + .DeactivateAccountAsync(owner.Id, owner.Id, deleteLater: false); + } + + await AssertCannotConnectAsync(shareId, unlockToken: null); + } + // --- Helpers --- private async Task<(AuthenticatedUser Owner, Guid ShareId)> CreateShareWithShocker(string prefix, diff --git a/API.IntegrationTests/Tests/ShockerPermissionsTests.cs b/API.IntegrationTests/Tests/ShockerPermissionsTests.cs index edcd72f3..c55079f8 100644 --- a/API.IntegrationTests/Tests/ShockerPermissionsTests.cs +++ b/API.IntegrationTests/Tests/ShockerPermissionsTests.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.API.Services.Account; using OpenShock.Common.OpenShockDb; using OpenShock.IntegrationTests.Shared; using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper; @@ -178,6 +179,45 @@ public async Task SharedShocker_ShowsPermissionsAllowedByBoth() await Assert.That(await LogCount(shockerId)).IsEqualTo(0); } + [Test] + public async Task SharedControl_OwnerDeactivated_IsNotSent() + { + var owner = await CreateUser("deactshowner"); + var recipient = await CreateUser("deactshrecip"); + var shockerId = await CreateShocker(WebApplicationFactory, owner.Id, "Shared"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.UserShares.Add(new UserShare + { + SharedWithUserId = recipient.Id, + ShockerId = shockerId, + AllowShock = true, + AllowVibrate = true, + AllowSound = true, + AllowLiveControl = true, + IsPaused = false + }); + await db.SaveChangesAsync(); + } + + using var recipientClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, recipient.SessionToken); + var before = await Control(recipientClient, shockerId, 10, 1000); + await Assert.That(before.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await LogCount(shockerId)).IsEqualTo(1); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService() + .DeactivateAccountAsync(owner.Id, owner.Id, deleteLater: false); + } + + var after = await Control(recipientClient, shockerId, 10, 1000); + await Assert.That(after.StatusCode).IsNotEqualTo(HttpStatusCode.OK); + await Assert.That(await LogCount(shockerId)).IsEqualTo(1); + } + private Task CreateUser(string prefix) => TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password); diff --git a/Common.Tests/Extensions/ApiTokenExtensionsTests.cs b/Common.Tests/Extensions/ApiTokenExtensionsTests.cs new file mode 100644 index 00000000..3c266234 --- /dev/null +++ b/Common.Tests/Extensions/ApiTokenExtensionsTests.cs @@ -0,0 +1,49 @@ +using System.Net; +using OpenShock.Common.Extensions; +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.Common.Tests.Extensions; + +public sealed class ApiTokenExtensionsTests +{ + private static readonly DateTime Now = new(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + private static ApiToken Token(DateTime? validUntil, params PermissionType[] permissions) => new() + { + UserId = Guid.NewGuid(), + Name = "test", + TokenHash = "hash", + CreatedByIp = IPAddress.Loopback, + Permissions = [.. permissions], + ValidUntil = validUntil + }; + + [Test] + public async Task CanControlShockers_ValidTokenWithShockersUse_True() + { + await Assert.That(Token(null, PermissionType.Shockers_Use).CanControlShockers(Now)).IsTrue(); + await Assert.That(Token(Now.AddMinutes(1), PermissionType.Shockers_Use).CanControlShockers(Now)).IsTrue(); + } + + [Test] + public async Task CanControlShockers_Expired_False() + { + await Assert.That(Token(Now.AddSeconds(-1), PermissionType.Shockers_Use).CanControlShockers(Now)).IsFalse(); + } + + [Test] + public async Task CanControlShockers_WithoutShockersUse_False() + { + await Assert.That(Token(null).CanControlShockers(Now)).IsFalse(); + await Assert.That(Token(null, PermissionType.Shockers_Edit).CanControlShockers(Now)).IsFalse(); + } + + [Test] + public async Task CanControlShockers_PausedTokenKeepsAuthority_True() + { + var token = Token(null, PermissionType.Shockers_Use); + token.ShockerControlPaused = true; + await Assert.That(token.CanControlShockers(Now)).IsTrue(); + } +} diff --git a/Common/Extensions/ApiTokenExtensions.cs b/Common/Extensions/ApiTokenExtensions.cs new file mode 100644 index 00000000..5398401e --- /dev/null +++ b/Common/Extensions/ApiTokenExtensions.cs @@ -0,0 +1,19 @@ +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.Common.Extensions; + +public static class ApiTokenExtensions +{ + /// + /// Whether this token may still control shockers at : it has not expired and still + /// carries . A paused token keeps this authority, it just sends nothing. + /// + /// + /// Checked again on connections that outlive their authentication, such as live control, so a token that + /// expired or lost the permission cannot keep using a connection it opened while it was valid. + /// + public static bool CanControlShockers(this ApiToken token, DateTime now) => + (token.ValidUntil is null || token.ValidUntil >= now) && + token.Permissions.IsAllowed(PermissionType.Shockers_Use); +} diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index 65ebcdb7..e2aa910e 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -5,15 +5,18 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication; using OpenShock.Common.Authentication.Attributes; using OpenShock.Common.Errors; using OpenShock.Common.Extensions; +using OpenShock.Common.Hubs; using OpenShock.Common.Models; using OpenShock.Common.Models.WebSocket; using OpenShock.Common.Models.WebSocket.LCG; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.Session; using OpenShock.Common.Utils; using OpenShock.Common.Websocket; using OpenShock.Internal.Common.Constants; @@ -42,6 +45,9 @@ public sealed class LiveControlController : WebsocketBaseController _dbContextFactory; private readonly ApiTokenUpdateSubscriber _tokenUpdateSubscriber; + private readonly LiveControlRevocationSubscriber _revocationSubscriber; + private readonly IServiceScopeFactory _scopeFactory; + private readonly TimeSpan _revalidationInterval; private readonly ILogger _logger; private readonly GatewayMetrics _metrics; @@ -56,15 +62,49 @@ public sealed class LiveControlController : WebsocketBaseController - /// Shocker control scoping carried by the API token used to authenticate, if any. + /// What the API token used to authenticate currently grants, replaced as a whole when it changes. /// Null when authenticated via a user session (no token limits apply). /// - private ApiTokenControlLimits? _tokenLimits; + private volatile TokenState? _tokenState; + + private sealed record TokenState(bool Paused, ApiTokenControlLimits Limits, DateTime? ValidUntil) + { + public static TokenState From(ApiToken token) => + new(token.ShockerControlPaused, ApiTokenControlLimits.FromToken(token), token.ValidUntil); + + public bool IsExpired(DateTime now) => ValidUntil is { } validUntil && validUntil < now; + } /// - /// When true, the authenticating API token is paused (or was revoked) and may not send any control frames. + /// The session token used to authenticate, if any. Null when authenticated via an API token. /// - private bool _tokenPaused; + private string? _sessionToken; + + /// + /// Set once the session or token this connection authenticated with may no longer control. + /// Every frame after that is dropped while the socket is being closed. + /// + private int _revokedFlag; + + private bool Revoked => Volatile.Read(ref _revokedFlag) != 0; + + private int _revalidating; + private long _lastValidated; + + /// + /// The id the authenticating session is stored under, null when authenticated via an API token. + /// + public string? SessionId { get; private set; } + + /// + /// The user controlling through this connection. + /// + public Guid UserId => _currentUser.Id; + + /// + /// The owner of the hub this connection controls, once known. + /// + public Guid? DeviceOwnerId => _device?.OwnerId; /// /// ID of the connected hub @@ -94,13 +134,19 @@ public sealed class LiveControlController : WebsocketBaseController /// /// + /// + /// + /// /// /// - public LiveControlController(HubLifetimeManager hubLifetimeManager, IDbContextFactory dbContextFactory, ApiTokenUpdateSubscriber tokenUpdateSubscriber, GatewayMetrics metrics, ILogger logger) : base(logger) + public LiveControlController(HubLifetimeManager hubLifetimeManager, IDbContextFactory dbContextFactory, ApiTokenUpdateSubscriber tokenUpdateSubscriber, LiveControlRevocationSubscriber revocationSubscriber, IServiceScopeFactory scopeFactory, IOptions revalidationOptions, GatewayMetrics metrics, ILogger logger) : base(logger) { _hubLifetimeManager = hubLifetimeManager; _dbContextFactory = dbContextFactory; _tokenUpdateSubscriber = tokenUpdateSubscriber; + _revocationSubscriber = revocationSubscriber; + _scopeFactory = scopeFactory; + _revalidationInterval = revalidationOptions.Value.Interval; _metrics = metrics; _logger = logger; @@ -265,23 +311,114 @@ public void OnActionExecuting(ActionExecutingContext context) if (GetOptionalItem() is { } apiToken) { _tokenId = apiToken.Id; - _tokenPaused = apiToken.ShockerControlPaused; - _tokenLimits = ApiTokenControlLimits.FromToken(apiToken); + _tokenState = TokenState.From(apiToken); + } + else if (HttpContext.TryGetUserSessionToken(out var sessionToken)) + { + _sessionToken = sessionToken; + SessionId = HubConnectionTracker.GetSessionId(sessionToken); } } + /// + /// Apply the current state of the authenticating API token to this connection, pushed by the + /// when the token changed. The caller has checked it may still control. + /// + /// + [NonAction] + public void ApplyToken(ApiToken token) + { + _tokenState = TokenState.From(token); + } /// - /// Apply refreshed API token limits to this connection, pushed by the - /// when the token changed or was revoked. A revoked/expired token arrives as paused with no limits. + /// The session or token this connection authenticated with may no longer control: stop accepting frames and + /// close the socket. Safe to call more than once and from any thread. /// - /// - /// [NonAction] - public void ApplyTokenLimits(bool paused, ApiTokenControlLimits? limits) + public async Task Revoke() { - _tokenPaused = paused; - _tokenLimits = limits; + if (Interlocked.Exchange(ref _revokedFlag, 1) != 0) return; + + Logger.LogInformation("Closing live control connection of user [{UserId}] for hub [{HubId}], its authentication is no longer valid", + _currentUser.Id, HubId); + + try + { + await ForceClose(WebSocketCloseStatus.PolicyViolation, "Authentication is no longer valid"); + } + catch (Exception e) + { + // The socket may already be closing on its own; the flag above stops all control either way. + Logger.LogDebug(e, "Error while closing revoked live control connection"); + } + } + + /// + /// Re-check this connection against the database and the session store, for what the Redis messages cannot + /// cover: a message that was lost, or a token that reached its expiry. Also refreshes the token's pause state + /// and limits and the shared shocker permissions. + /// + private async Task Revalidate() + { + if (Revoked || Interlocked.Exchange(ref _revalidating, 1) == 1) return; + + try + { + await using var scope = _scopeFactory.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + if (!await IsStillAuthenticated(scope.ServiceProvider, db)) + { + await Revoke(); + return; + } + + await UpdatePermissions(db); + Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); + } + catch (OperationCanceledException) when (LinkedToken.IsCancellationRequested) + { + // Connection is closing anyway. + } + catch (Exception e) + { + // A transient failure must not drop a legitimate connection; the next ping retries. + Logger.LogWarning(e, "Error while revalidating live control connection for hub [{HubId}]", HubId); + } + finally + { + Interlocked.Exchange(ref _revalidating, 0); + } + } + + private async Task IsStillAuthenticated(IServiceProvider services, OpenShockContext db) + { + if (_tokenId is { } tokenId) + { + var token = await db.ApiTokens + .AsNoTracking() + .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null, LinkedToken); + if (token is null || !token.CanControlShockers(DateTime.UtcNow)) return false; + + ApplyToken(token); + return true; + } + + if (_sessionToken is null) return false; + + // Sessions are deleted on logout, on deactivation and on a password reset. + var session = await services.GetRequiredService().GetSessionByTokenAsync(_sessionToken); + if (session is null || session.UserId != _currentUser.Id) return false; + + // That deletion happens after the database commit and can fail, so the account is the authority. + return await db.Users.AnyAsync(u => u.Id == _currentUser.Id && u.ActivatedAt != null && u.UserDeactivation == null, LinkedToken); + } + + private bool RevalidationDue() + { + var last = Interlocked.Read(ref _lastValidated); + return last == 0 || Stopwatch.GetElapsedTime(last) >= _revalidationInterval; } /// @@ -306,6 +443,12 @@ protected override async Task SendInitialData() // so changes take effect on this connection without reconnecting. if (_tokenId is { } tokenId) await _tokenUpdateSubscriber.Register(this, tokenId); + _revocationSubscriber.Register(this); + + // Authentication happened before the registrations above, so a revocation announced in between found + // nothing to close. Look once now that announcements can reach this connection. + await Revalidate(); + if (Revoked) return; await QueueMessage(new LiveControlResponse { @@ -484,8 +627,20 @@ await QueueMessage(new LiveControlResponse private async Task ProcessFrameInternal(ClientLiveFrame frame) { + // The socket is being closed because its authentication was revoked. + if (Revoked) return; + + var tokenState = _tokenState; + + // An expired token may not control, even though nothing announces the expiry. + if (tokenState is not null && tokenState.IsExpired(DateTime.UtcNow)) + { + await Revoke(); + return; + } + // A paused API token may not send any control, mirroring the /shockers/control endpoint. - if (_tokenPaused) + if (tokenState is { Paused: true }) { _metrics.Frame(GatewayMetrics.FrameOutcome.TokenPaused, frame.Type); await QueueMessage(new LiveControlResponse @@ -499,7 +654,7 @@ await QueueMessage(new LiveControlResponse var permCheck = CheckFramePermissions(frame.Shocker, frame.Type); await (permCheck switch { - SharePermsAndLimits perms => ForwardFrame(frame, perms), + SharePermsAndLimits perms => ForwardFrame(frame, perms, tokenState?.Limits), Results.NotFound => RejectFrame(frame, GatewayMetrics.FrameOutcome.ShockerNotFound, LiveResponseType.ShockerNotFound), LiveNotEnabled => RejectFrame(frame, GatewayMetrics.FrameOutcome.LiveNotEnabled, LiveResponseType.ShockerMissingLivePermission), NoPermission => RejectFrame(frame, GatewayMetrics.FrameOutcome.NoPermission, LiveResponseType.ShockerMissingPermission), @@ -516,10 +671,10 @@ await QueueMessage(new LiveControlResponse }); } - private async Task ForwardFrame(ClientLiveFrame frame, SharePermsAndLimits perms) + private async Task ForwardFrame(ClientLiveFrame frame, SharePermsAndLimits perms, ApiTokenControlLimits? tokenLimits) { // Apply the token's intensity scoping first (if any), then clamp to the shocker and share limits. - var scopedIntensity = _tokenLimits?.ApplyIntensity(frame.Intensity) ?? frame.Intensity; + var scopedIntensity = tokenLimits?.ApplyIntensity(frame.Intensity) ?? frame.Intensity; var intensity = ControlLimitUtils.ClampIntensity(scopedIntensity, perms.Intensity); var result = HubLifetime.ReceiveFrame(frame.Shocker, _logSender, frame.Type, intensity, _tps); @@ -569,6 +724,16 @@ private async Task SendPing() { if (WebSocket is not { State: WebSocketState.Open }) return; + // Close an idle connection whose token expired, rather than waiting for its next frame. + if (_tokenState is { } tokenState && tokenState.IsExpired(DateTime.UtcNow)) + { + await Revoke(); + return; + } + + if (RevalidationDue()) await Revalidate(); + if (Revoked) return; + if (Logger.IsEnabled(LogLevel.Debug)) Logger.LogDebug("Sending ping to live control user [{UserId}] for hub [{HubId}]", _currentUser.Id, Id); @@ -620,6 +785,8 @@ protected override async ValueTask DisposeControllerAsync() Logger.LogTrace("Disposing controller timer"); _pingTimer.Dispose(); + _revocationSubscriber.Unregister(this); + if (_tokenId is { } tokenId) { try diff --git a/LiveControlGateway/Program.cs b/LiveControlGateway/Program.cs index 7642cf16..5317262f 100644 --- a/LiveControlGateway/Program.cs +++ b/LiveControlGateway/Program.cs @@ -61,6 +61,8 @@ #pragma warning restore EXTEXP0008 builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); var app = builder.Build(); diff --git a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs b/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs index afbba5f9..f71409e5 100644 --- a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs +++ b/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs @@ -1,5 +1,5 @@ using Microsoft.EntityFrameworkCore; -using OpenShock.Common.Models; +using OpenShock.Common.Extensions; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.RedisPubSub; using OpenShock.Internal.Common.Extensions; @@ -12,8 +12,10 @@ namespace OpenShock.LiveControlGateway.PubSub; /// /// Per-gateway coordinator for API token update notifications. /// Holds a single ref-counted redis subscription per token, shared by every live control connection on this -/// gateway that authenticated with it. When a token changes, the limits are fetched from the database once and -/// pushed to all those connections, instead of each connection querying the database on its own. +/// gateway that authenticated with it. When a token changes, it is fetched from the database once and its pause +/// state and limits are pushed to all those connections, instead of each connection querying the database on its +/// own. A token that may no longer control (deleted, expired, its user deactivated, or without shockers.use) +/// closes those connections instead. /// public sealed class ApiTokenUpdateSubscriber { @@ -92,37 +94,31 @@ private async Task OnTokenUpdate(Guid tokenId) if (clients.Length == 0) return; - bool paused; - ApiTokenControlLimits? limits; + ApiToken? token; try { await using var db = await _dbContextFactory.CreateDbContextAsync(); - var token = await db.ApiTokens + token = await db.ApiTokens .AsNoTracking() - .FirstOrDefaultAsync(x => x.Id == tokenId && (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow)); - - if (token is null) - { - // Token revoked/expired: deny all further control on these connections. - _logger.LogDebug("API token [{TokenId}] is gone, denying control on {Count} live connection(s)", - tokenId, clients.Length); - paused = true; - limits = null; - } - else - { - paused = token.ShockerControlPaused; - limits = ApiTokenControlLimits.FromToken(token); - } + .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null); } catch (Exception e) { - _logger.LogError(e, "Error fetching api token [{TokenId}] limits for live control connections", tokenId); + _logger.LogError(e, "Error fetching api token [{TokenId}] for live control connections", tokenId); + return; + } + + if (token is null || !token.CanControlShockers(DateTime.UtcNow)) + { + // Deleted, expired, its owner deactivated, or it lost shockers.use: the connections may not go on. + _logger.LogDebug("API token [{TokenId}] may no longer control, closing {Count} live connection(s)", + tokenId, clients.Length); + await Task.WhenAll(clients.Select(client => client.Revoke())); return; } foreach (var client in clients) - client.ApplyTokenLimits(paused, limits); + client.ApplyToken(token); } } diff --git a/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs b/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs new file mode 100644 index 00000000..a005ff7e --- /dev/null +++ b/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs @@ -0,0 +1,85 @@ +using System.Collections.Concurrent; +using OpenShock.Common.Services.RedisPubSub; +using OpenShock.Internal.Common.Utils; +using OpenShock.LiveControlGateway.Controllers; +using StackExchange.Redis; + +namespace OpenShock.LiveControlGateway.PubSub; + +/// +/// The live control connections open on this gateway, closed when the session or account they belong to is +/// revoked. A live control socket is authenticated once, when it opens, so without this a logged out session or +/// a deactivated account could keep controlling through a socket opened before. +/// +/// +/// API token changes are handled per token by . A lost message is covered +/// by each connection re-checking itself against the database at a bounded interval. +/// +public sealed class LiveControlRevocationSubscriber : IHostedService +{ + private readonly ISubscriber _subscriber; + private readonly ILogger _logger; + private readonly ConcurrentDictionary _connections = new(); + + /// + /// DI constructor + /// + /// + /// + public LiveControlRevocationSubscriber(IConnectionMultiplexer connectionMultiplexer, ILogger logger) + { + _subscriber = connectionMultiplexer.GetSubscriber(); + _logger = logger; + } + + /// Start closing this connection when its session or account is revoked. + public void Register(LiveControlController connection) => _connections.TryAdd(connection, 0); + + /// Stop tracking this connection. + public void Unregister(LiveControlController connection) => _connections.TryRemove(connection, out _); + + /// + public async Task StartAsync(CancellationToken cancellationToken) + { + await _subscriber.SubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); + await _subscriber.SubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); + } + + /// + public async Task StopAsync(CancellationToken cancellationToken) + { + await _subscriber.UnsubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); + await _subscriber.UnsubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); + } + + private void HandleSessionRevoked(RedisChannel _, RedisValue message) + { + var sessionId = (string?)message; + if (string.IsNullOrEmpty(sessionId)) return; + + Revoke(c => c.SessionId == sessionId, "session revoked"); + } + + private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) + { + if (!Guid.TryParse((string?)message, out var userId)) return; + + // The user's own connections, and everyone controlling a hub they own through a share. + Revoke(c => c.UserId == userId || c.DeviceOwnerId == userId, "account revoked"); + } + + private void Revoke(Func predicate, string reason) + { + var closed = 0; + foreach (var connection in _connections.Keys) + { + if (!predicate(connection)) continue; + + _connections.TryRemove(connection, out _); + OsTask.Run(connection.Revoke); + closed++; + } + + if (closed > 0) _logger.LogDebug("Closing {Count} live control connection(s): {Reason}", closed, reason); + } +}