From bfa72d5aab3f2c22b29cc74baf6f6ae20d6e4684 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:07:06 +0100 Subject: [PATCH 1/7] feat: close hub connections when their session or API token is revoked SignalR authenticates a connection once, when it opens, so a logged out session or a revoked, expired or deactivated API token could keep using a connection that was already open. Revocations are now announced on Redis and the instance holding an affected UserHub connection closes it right away: deleted and expired sessions, deactivated or deleted accounts, and deleted API tokens. An edited token makes its connections read it again on their next call, so the hub uses its current permissions, pause state and control limits instead of the ones from connect time. As a fallback for a lost message or a token that reaches its expiry, a hub filter re-checks a connection against the database when it opens and at most once per minute while it is making calls. --- .../Tests/SignalRUserHubTests.cs | 271 ++++++++++++++++++ API.IntegrationTests/WebApplicationFactory.cs | 8 + API/Realtime/RedisSubscriberService.cs | 64 +++++ API/Services/Account/AccountService.cs | 21 ++ Common/Hubs/HubConnectionTracker.cs | 139 +++++++++ .../Hubs/RevalidateAuthenticationHubFilter.cs | 160 +++++++++++ Common/Hubs/UserHub.cs | 11 +- Common/OpenShockServiceHelper.cs | 6 +- .../Services/RedisPubSub/IRedisPubService.cs | 13 + Common/Services/RedisPubSub/RedisChannels.cs | 17 ++ .../Services/RedisPubSub/RedisPubService.cs | 10 + Common/Services/Session/SessionService.cs | 34 ++- 12 files changed, 748 insertions(+), 6 deletions(-) create mode 100644 Common/Hubs/HubConnectionTracker.cs create mode 100644 Common/Hubs/RevalidateAuthenticationHubFilter.cs diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index f1ecc415..c5c85f66 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -1,8 +1,15 @@ using System.Net; using System.Text.Json; +using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.API.Services.Account; using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.Session; namespace OpenShock.API.IntegrationTests.Tests; @@ -99,4 +106,268 @@ public async Task PublicShareHub_Negotiate_WithoutAuth_ReturnsOk() // Should return OK (negotiate doesn't check auth or share existence) await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } + + // --- A revocation closes the open connections it concerns right away, without them calling anything --- + + [Test] + public async Task Logout_ClosesTheSessionsOpenConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkicklogout"), TestHelper.UniqueEmail("hubkicklogout"), "SecurePassword123#"); + var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickother"), TestHelper.UniqueEmail("hubkickother"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await using var otherConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={other.SessionToken}"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService().DeleteSessionByTokenAsync(user.SessionToken); + } + + await AssertConnectionClosesAsync(connection); + + // Nobody else is affected. + await otherConnection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await Assert.That(otherConnection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task DeletingAnApiToken_ClosesItsOpenConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkicktoken"), TestHelper.UniqueEmail("hubkicktoken"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deleted"); + var (_, otherRawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-kept"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await using var otherConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, otherRawToken); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.DeleteAsync($"/1/tokens/{tokenId}"); + await Assert.That(response.IsSuccessStatusCode).IsTrue(); + + await AssertConnectionClosesAsync(connection); + + await otherConnection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await Assert.That(otherConnection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task DeactivatingAnAccount_ClosesItsSessionAndApiTokenConnections() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickdeact"), TestHelper.UniqueEmail("hubkickdeact"), "SecurePassword123#"); + var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deactivated"); + await using var sessionConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await using var tokenConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var accountService = scope.ServiceProvider.GetRequiredService(); + await accountService.DeactivateAccountAsync(user.Id, user.Id, deleteLater: false); + } + + await AssertConnectionClosesAsync(sessionConnection); + await AssertConnectionClosesAsync(tokenConnection); + } + + // --- The fallback: a connection whose revocation was never announced stops at its next periodic check --- + + [Test] + public async Task Invoke_ManyCallsInARow_ChecksTheApiTokenOncePerInterval() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalcache"), TestHelper.UniqueEmail("hubrevalcache"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-cached"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); + } + + // Straight after the check above, the deleted token is not looked up again: the call goes through. + // (It would be rejected, and the connection closed, if every call queried the database.) + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + [Test] + public async Task Invoke_WithValidSession_KeepsWorking() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalok"), TestHelper.UniqueEmail("hubrevalok"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Invoke_AfterSessionDeleted_FailsAndClosesConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalsess"), TestHelper.UniqueEmail("hubrevalsess"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService().DeleteSessionsByUserIdAsync(user.Id); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + [Test] + public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsAndClosesConnection() + { + // Deactivation removes sessions after its database commit; if that step fails the session survives. + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaldeact"), TestHelper.UniqueEmail("hubrevaldeact"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.UserDeactivations.Add(new UserDeactivation + { + DeactivatedUserId = user.Id, + DeactivatedByUserId = user.Id, + DeleteLater = false + }); + await db.SaveChangesAsync(); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + [Test] + public async Task Invoke_WithValidApiToken_KeepsWorking() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokok"), TestHelper.UniqueEmail("hubrevaltokok"), "SecurePassword123#"); + var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-ok"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Invoke_AfterApiTokenDeleted_FailsAndClosesConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokdel"), TestHelper.UniqueEmail("hubrevaltokdel"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-deleted"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + [Test] + public async Task Invoke_AfterApiTokenExpired_FailsAndClosesConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokexp"), TestHelper.UniqueEmail("hubrevaltokexp"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-expired"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var expired = DateTime.UtcNow.AddMinutes(-1); + await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteUpdateAsync(s => s.SetProperty(t => t.ValidUntil, expired)); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + [Test] + public async Task Invoke_AfterApiTokenOwnerDeactivated_FailsAndClosesConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokdeact"), TestHelper.UniqueEmail("hubrevaltokdeact"), "SecurePassword123#"); + var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-deactivated"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.UserDeactivations.Add(new UserDeactivation + { + DeactivatedUserId = user.Id, + DeactivatedByUserId = user.Id, + DeleteLater = false + }); + await db.SaveChangesAsync(); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + /// + /// Opens a real hub connection against the in-process test server. The hub only allows WebSockets, which + /// the test server offers through its own client rather than through an HttpMessageHandler. + /// + private async Task ConnectAsync(string headerName, string headerValue) + { + var server = WebApplicationFactory.Server; + + var connection = new HubConnectionBuilder() + .WithUrl(new Uri(server.BaseAddress, "/1/hubs/user"), options => + { + options.Transports = HttpTransportType.WebSockets; + options.SkipNegotiation = true; + options.WebSocketFactory = async (context, cancellationToken) => + { + var client = server.CreateWebSocketClient(); + client.ConfigureRequest = request => request.Headers[headerName] = headerValue; + return await client.ConnectAsync(context.Uri, cancellationToken); + }; + }) + .Build(); + + await connection.StartAsync(); + return connection; + } + + private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnection connection) + { + // The connection was checked moments ago and that result is kept for the interval, so the + // revocation only reaches it on the first call after that. + await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + + // The server answers with an error and aborts; which of the two the client sees first is a race. + Exception? failure = null; + try + { + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + } + catch (Exception ex) + { + failure = ex; + } + + await Assert.That(failure).IsNotNull(); + + await AssertConnectionClosesAsync(connection); + } + + /// Waits for the server to close the connection, without calling anything on it. + private static async Task AssertConnectionClosesAsync(HubConnection connection) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (connection.State != HubConnectionState.Disconnected && DateTime.UtcNow < deadline) + { + await Task.Delay(50); + } + + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Disconnected); + } } diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index 7d335f68..8e3687e6 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.Options; using OpenShock.API.IntegrationTests.Docker; using OpenShock.API.IntegrationTests.HttpMessageHandlers; +using OpenShock.Common.Hubs; using Serilog; using Serilog.Events; @@ -26,6 +27,9 @@ public class WebApplicationFactory : WebApplicationFactory [ClassDataSource(Shared = SharedType.PerTestSession)] public required InMemoryRedis Redis { get; init; } + /// How long an open hub connection can go on after its session or API token was revoked, in tests. + public static readonly TimeSpan HubRevalidationInterval = TimeSpan.FromSeconds(1); + protected override void ConfigureClient(HttpClient client) { base.ConfigureClient(client); @@ -98,6 +102,10 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { services.AddTransient(); + // Hub connections re-check their session or API token at most once per interval. Kept short so + // the tests that revoke one do not have to wait out the production interval. + services.Configure(options => options.Interval = HubRevalidationInterval); + // Disable rate limiting for integration tests so auth-endpoint tests // don't interfere with each other (10 req/min is too restrictive for test suites). // Rate limiter behavior is covered by dedicated unit tests. diff --git a/API/Realtime/RedisSubscriberService.cs b/API/Realtime/RedisSubscriberService.cs index 6351d50d..4c2c0902 100644 --- a/API/Realtime/RedisSubscriberService.cs +++ b/API/Realtime/RedisSubscriberService.cs @@ -21,6 +21,7 @@ public sealed class RedisSubscriberService : IHostedService, IAsyncDisposable private readonly IHubContext _hubContext; private readonly IDbContextFactory _dbContextFactory; private readonly IRedisConnectionProvider _redisConnectionProvider; + private readonly HubConnectionTracker _hubConnections; private readonly ISubscriber _subscriber; private readonly ILogger _logger; @@ -31,18 +32,21 @@ public sealed class RedisSubscriberService : IHostedService, IAsyncDisposable /// /// /// + /// The hub connections open on this instance, closed here when what they authenticated with is revoked. /// public RedisSubscriberService( IConnectionMultiplexer connectionMultiplexer, IHubContext hubContext, IDbContextFactory dbContextFactory, IRedisConnectionProvider redisConnectionProvider, + HubConnectionTracker hubConnections, ILogger logger ) { _hubContext = hubContext; _dbContextFactory = dbContextFactory; _redisConnectionProvider = redisConnectionProvider; + _hubConnections = hubConnections; _subscriber = connectionMultiplexer.GetSubscriber(); _logger = logger; } @@ -52,6 +56,61 @@ public async Task StartAsync(CancellationToken cancellationToken) { await _subscriber.SubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); await _subscriber.SubscribeAsync(RedisChannels.DeviceStatus, HandleDeviceStatus); + await _subscriber.SubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); + await _subscriber.SubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); + await _subscriber.SubscribeAsync(RedisChannels.ApiTokenUpdateAll, HandleApiTokenUpdate); + } + + private void HandleSessionRevoked(RedisChannel _, RedisValue message) + { + var sessionId = (string?)message; + if (string.IsNullOrEmpty(sessionId)) return; + + var closed = _hubConnections.AbortSession(sessionId); + if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of a deleted session", closed); + } + + private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) + { + if (!Guid.TryParse((string?)message, out var userId)) return; + + var closed = _hubConnections.AbortUser(userId); + if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of user [{UserId}]", closed, userId); + } + + private void HandleApiTokenUpdate(RedisChannel channel, RedisValue _) + { + var channelName = (string?)channel; + if (channelName is null || !channelName.StartsWith(RedisChannels.ApiTokenUpdatePrefix, StringComparison.Ordinal)) return; + if (!Guid.TryParse(channelName.AsSpan(RedisChannels.ApiTokenUpdatePrefix.Length), out var tokenId)) return; + + // Most token changes concern no connection on this instance: no database round trip for those. + if (!_hubConnections.HasApiTokenConnections(tokenId)) return; + + OsTask.Run(() => ApplyApiTokenUpdate(tokenId)); + } + + /// + /// The same channel announces an edit and a deletion, so look: a token that is gone closes its + /// connections, one that changed makes them read it again on their next call. + /// + private async Task ApplyApiTokenUpdate(Guid tokenId) + { + await using var db = await _dbContextFactory.CreateDbContextAsync(); + + var stillValid = await db.ApiTokens.AnyAsync(x => + x.Id == tokenId && + (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && + x.User.UserDeactivation == null); + + if (stillValid) + { + _hubConnections.InvalidateApiToken(tokenId); + return; + } + + var closed = _hubConnections.AbortApiToken(tokenId); + _logger.LogDebug("Closed {Count} hub connection(s) of revoked API token [{TokenId}]", closed, tokenId); } private void HandleKeyExpired(RedisChannel _, RedisValue message) @@ -94,6 +153,11 @@ private void HandleKeyExpired(RedisChannel _, RedisValue message) OsTask.Run(() => LogicDeviceOnlineStatus(id)); } + else if (typeNameSpan.SequenceEqual(typeof(LoginSession).FullName)) + { + // A session that reached its lifetime: same as a deleted one for the connections using it. + _hubConnections.AbortSession(guidSpan.ToString()); + } } private void HandleDeviceStatus(RedisChannel _, RedisValue value) diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 6ecdee49..c9cb1f5b 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -76,6 +76,23 @@ private async Task NotifyEmailOutboxAsync() } } + /// + /// Tells every instance the account may no longer be used, so its open connections are closed, the ones + /// that authenticated with an API token included. Deliberately swallows failures: the change is already + /// committed, and a connection that misses the message is caught by its next periodic check. + /// + private async Task NotifyUserAuthRevokedAsync(Guid userId) + { + try + { + await _redisPubService.SendUserAuthRevoked(userId); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to announce revoked access for user ID: [{Id}]; open connections close on their next check", userId); + } + } + private Task IsUserNameBlacklisted(string username, CancellationToken cancellationToken) => _db.UserNameBlacklists.Matching(username).AnyAsync(cancellationToken); @@ -380,6 +397,8 @@ await _auditService.LogAsync( await transaction.CommitAsync(); } + await NotifyUserAuthRevokedAsync(userId); + // Remove all login sessions await _sessionService.DeleteSessionsByUserIdAsync(userId); @@ -470,6 +489,8 @@ await _auditService.LogAsync( await transaction.CommitAsync(); + await NotifyUserAuthRevokedAsync(userId); + return new Success(); } diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs new file mode 100644 index 00000000..d4d2a763 --- /dev/null +++ b/Common/Hubs/HubConnectionTracker.cs @@ -0,0 +1,139 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using Microsoft.AspNetCore.SignalR; +using OpenShock.Common.Authentication; +using OpenShock.Common.Constants; +using OpenShock.Common.Extensions; +using OpenShock.Common.Utils; + +namespace OpenShock.Common.Hubs; + +/// +/// The authenticated hub connections open on this instance, by what they authenticated with. Lets a +/// revocation that arrives over Redis close the affected connections right away, instead of each connection +/// finding out the next time it asks the database (see ). +/// +/// +/// Local to the process: every instance tracks its own connections and reacts to the same Redis message. +/// Lookups scan all connections, which is fine for how rarely sessions and tokens are revoked. +/// +public sealed class HubConnectionTracker +{ + private readonly ConcurrentDictionary _connections = new(); + + public TrackedHubConnection? Get(string connectionId) + => _connections.GetValueOrDefault(connectionId); + + /// Starts tracking a connection. Anonymous connections hold nothing that can be revoked and are skipped. + /// The tracked connection, or null when it was skipped. + public TrackedHubConnection? Track(HubCallerContext context) + { + var user = context.User; + if (user is null) return null; + + Guid? userId = Guid.TryParse(context.UserIdentifier, out var parsedUserId) ? parsedUserId : null; + + if (user.HasOpenShockApiTokenIdentity()) + { + if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return null; + + return _connections[context.ConnectionId] = new TrackedHubConnection(context, userId, sessionId: null, tokenId); + } + + if (user.TryGetOpenShockUserIdentity() is not null + && context.GetHttpContext() is { } httpContext + && httpContext.TryGetUserSessionToken(out var sessionToken)) + { + return _connections[context.ConnectionId] = new TrackedHubConnection(context, userId, GetSessionId(sessionToken), apiTokenId: null); + } + + return null; + } + + public void Untrack(string connectionId) => _connections.TryRemove(connectionId, out _); + + /// Closes the connections that authenticated with this session. + /// The id the session is stored under, see . + /// How many connections were closed. + public int AbortSession(string sessionId) => Abort(c => c.SessionId == sessionId); + + /// Closes every connection of this user, whatever it authenticated with. + /// How many connections were closed. + public int AbortUser(Guid userId) => Abort(c => c.UserId == userId); + + /// Closes the connections that authenticated with this API token. + /// How many connections were closed. + public int AbortApiToken(Guid tokenId) => Abort(c => c.ApiTokenId == tokenId); + + public bool HasApiTokenConnections(Guid tokenId) + { + foreach (var connection in _connections.Values) + { + if (connection.ApiTokenId == tokenId) return true; + } + + return false; + } + + /// + /// Makes the connections using this API token read it from the database again on their next call, so a + /// change to its permissions, pause state or limits applies from then on. + /// + public void InvalidateApiToken(Guid tokenId) + { + foreach (var connection in _connections.Values) + { + if (connection.ApiTokenId == tokenId) connection.Invalidate(); + } + } + + /// The id a session is stored under in Redis: the hash of its token (old tokens are stored as they are). + public static string GetSessionId(string sessionToken) + => sessionToken.Length == AuthConstants.GeneratedTokenLength ? HashingUtils.HashToken(sessionToken) : sessionToken; + + private int Abort(Func predicate) + { + var aborted = 0; + foreach (var (connectionId, connection) in _connections) + { + if (!predicate(connection)) continue; + + // Dropped here as well as on disconnect, so a message that arrives twice finds nothing. + _connections.TryRemove(connectionId, out _); + connection.Context.Abort(); + aborted++; + } + + return aborted; + } +} + +public sealed class TrackedHubConnection +{ + // 0 means "not validated": Stopwatch timestamps are never 0 in practice, and a false "not validated" + // only costs one extra check. + private long _lastValidated; + + public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sessionId, Guid? apiTokenId) + { + Context = context; + UserId = userId; + SessionId = sessionId; + ApiTokenId = apiTokenId; + } + + public HubCallerContext Context { get; } + public Guid? UserId { get; } + public string? SessionId { get; } + public Guid? ApiTokenId { get; } + + public bool WasValidatedWithin(TimeSpan interval) + { + var last = Volatile.Read(ref _lastValidated); + return last != 0 && Stopwatch.GetElapsedTime(last) < interval; + } + + public void MarkValidated() => Volatile.Write(ref _lastValidated, Stopwatch.GetTimestamp()); + + public void Invalidate() => Volatile.Write(ref _lastValidated, 0); +} diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs new file mode 100644 index 00000000..f8d6da28 --- /dev/null +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -0,0 +1,160 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.SignalR; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using OpenShock.Common.Authentication; +using OpenShock.Common.Extensions; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.Session; + +namespace OpenShock.Common.Hubs; + +/// +/// Keeps an open hub connection from outliving the session or API token it authenticated with. +/// +/// +/// SignalR authenticates a connection once, when it opens, and then keeps it for as long as the client likes. +/// Without this, logging a session out or revoking, expiring or deactivating an API token would only stop new +/// connections: an open one could keep calling, and whatever calls it already had queued would still run. +/// Aborting also discards those queued calls. +/// +/// Two things end a connection. The fast one is a Redis message: revocations are published, and the instance +/// holding the connection closes it right away (the filter registers every connection with +/// for that). The slow one is the check in this filter, which asks the +/// database before a hub method call. It exists for what the messages cannot cover, a message that was lost +/// or a token that simply reached its expiry, so it only runs once per +/// per connection, and never for an idle one. +/// +/// +/// For an API token the row read here is handed to the hub method through +/// . A change to the token invalidates the +/// connection's last check, so its permissions, pause state and control limits are read again on the next call. +/// +/// +public sealed class RevalidateAuthenticationHubFilter : IHubFilter +{ + private readonly HubConnectionTracker _tracker; + private readonly IOptions _options; + + public RevalidateAuthenticationHubFilter(HubConnectionTracker tracker, IOptions options) + { + _tracker = tracker; + _options = options; + } + + /// + public async Task OnConnectedAsync(HubLifetimeContext context, Func next) + { + var tracked = _tracker.Track(context.Context); + + // The connection was authenticated before it was tracked. A revocation announced in between found + // nothing to close, so look once now that announcements can reach it. + if (tracked is not null) + { + if (!await IsStillAuthenticated(context.Context, context.ServiceProvider)) + { + _tracker.Untrack(context.Context.ConnectionId); + context.Context.Abort(); + return; + } + + tracked.MarkValidated(); + } + + await next(context); + } + + /// + public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception, Func next) + { + _tracker.Untrack(context.Context.ConnectionId); + return next(context, exception); + } + + /// + public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) + { + var context = invocationContext.Context; + + // Untracked means anonymous (nothing to check), or a connection a revocation already closed whose + // queued calls are still draining: the check below turns those away. + var tracked = _tracker.Get(context.ConnectionId); + + if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) + { + if (!await IsStillAuthenticated(context, invocationContext.ServiceProvider)) + { + context.Abort(); + throw new HubException("Authentication is no longer valid"); + } + + tracked?.MarkValidated(); + } + + return await next(invocationContext); + } + + private static async Task IsStillAuthenticated(HubCallerContext context, IServiceProvider services) + { + var user = context.User; + + // Anonymous connection (a public share guest): nothing was granted that could have been revoked. + if (user is null) return true; + + if (user.HasOpenShockApiTokenIdentity()) + { + if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return false; + + var db = services.GetRequiredService(); + var token = await db.ApiTokens + .AsNoTracking() + .FirstOrDefaultAsync(x => + x.Id == tokenId && + (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && + x.User.UserDeactivation == null, context.ConnectionAborted); + if (token is null) return false; + + context.Items[HubCallerContextExtensions.CurrentApiTokenKey] = token; + return true; + } + + if (user.TryGetOpenShockUserIdentity() is { } identity) + { + if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return false; + + // Sessions are deleted on logout, on deactivation and on a password reset. + var sessionService = services.GetRequiredService(); + var session = await sessionService.GetSessionByTokenAsync(sessionToken); + if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return false; + + // That deletion happens in Redis after the database commit and can fail, leaving the session + // behind. The account itself is the authority, as it is when a session authenticates a request. + var db = services.GetRequiredService(); + return await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); + } + + return true; + } +} + +public sealed class HubRevalidationOptions +{ + /// + /// How long a connection's last successful database check stays good. Revocations normally close a + /// connection at once through Redis; this bounds how long one can go on when that message was lost, or + /// when an API token expired on its own. + /// + public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); +} + +public static class HubCallerContextExtensions +{ + internal static readonly object CurrentApiTokenKey = new(); + + /// + /// The API token this connection authenticated with, as it was in the database when the connection was + /// last checked. Null for a session or anonymous connection. + /// + public static ApiToken? GetCurrentApiToken(this HubCallerContext context) + => context.Items.TryGetValue(CurrentApiTokenKey, out var token) ? token as ApiToken : null; +} diff --git a/Common/Hubs/UserHub.cs b/Common/Hubs/UserHub.cs index c3d3eea3..b996fbb9 100644 --- a/Common/Hubs/UserHub.cs +++ b/Common/Hubs/UserHub.cs @@ -28,9 +28,11 @@ public sealed class UserHub : Hub /// connection. Derived per access: SignalR creates a hub instance per invocation, so a field /// set in would be null everywhere else. /// - private IReadOnlyList? TokenPermissions => Context.User?.HasOpenShockApiTokenIdentity() == true - ? Context.User.GetApiTokenPermissions() - : null; + private IReadOnlyList? TokenPermissions => Context.GetCurrentApiToken() is { } apiToken + ? apiToken.Permissions + : Context.User?.HasOpenShockApiTokenIdentity() == true + ? Context.User.GetApiTokenPermissions() + : null; public UserHub(ILogger logger, OpenShockContext db, IRedisConnectionProvider provider, IRedisPubService redisPubService, IControlSender controlSender) @@ -96,7 +98,8 @@ public async Task ControlV2(IReadOnlyList shocks, string? customName) }).FirstAsync(Context.ConnectionAborted); ApiTokenControlLimits? tokenLimits = null; - if (Context.GetHttpContext()?.GetItemByType() is { } apiToken) + // The token as it is now, not as it was when the connection opened (see RevalidateAuthenticationHubFilter). + if (Context.GetCurrentApiToken() is { } apiToken) { // A paused token may not control shockers. if (apiToken.ShockerControlPaused) return; diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 896a5059..43d2158a 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -477,7 +477,11 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga public static IServiceCollection AddOpenShockSignalR(this IServiceCollection services, ConfigurationOptions redisConfig) { - services.AddSignalR() + services.AddOptions(); + services.AddSingleton(); + services.AddSingleton(); + + services.AddSignalR(options => Microsoft.AspNetCore.SignalR.HubOptionsExtensions.AddFilter(options)) .AddOpenShockStackExchangeRedis(options => { options.Configuration = redisConfig; }) .AddJsonProtocol(options => { diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 8e308f39..982433e9 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -20,6 +20,19 @@ public interface IRedisPubService /// Task SendApiTokenUpdate(Guid tokenId); + /// + /// A login session was deleted. Notifies every instance so open connections that authenticated with it + /// are closed. Best-effort: a connection that misses it is caught by its next periodic check. + /// + /// The id the session was stored under. + Task SendSessionRevoked(string sessionId); + + /// + /// The account was deactivated or deleted. Notifies every instance so all open connections of the user + /// are closed, including ones that authenticated with an API token. + /// + Task SendUserAuthRevoked(Guid userId); + /// /// Notifies the email outbox consumer that one or more messages were just enqueued, so it drains /// them without waiting for its next safety-net poll. Best-effort: a lost notification only delays diff --git a/Common/Services/RedisPubSub/RedisChannels.cs b/Common/Services/RedisPubSub/RedisChannels.cs index d0df75bd..53de95e7 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -12,6 +12,23 @@ public static class RedisChannels public static RedisChannel ApiTokenUpdate(Guid tokenId) => new($"api-token-update:{tokenId}", RedisChannel.PatternMode.Literal); + /// Every channel, for a subscriber that cares about all tokens. + public static readonly RedisChannel ApiTokenUpdateAll = new("api-token-update:*", RedisChannel.PatternMode.Pattern); + + public const string ApiTokenUpdatePrefix = "api-token-update:"; + + /// + /// Fired when a login session is deleted (logout, password reset, deactivation). The payload is the id + /// the session was stored under. Open connections that authenticated with it are closed. + /// + public static readonly RedisChannel SessionRevoked = new("session-revoked", RedisChannel.PatternMode.Literal); + + /// + /// Fired when an account may no longer be used at all (deactivated or deleted). The payload is the user + /// id. Every open connection of that user is closed, whatever it authenticated with. + /// + public static readonly RedisChannel UserAuthRevoked = new("user-auth-revoked", RedisChannel.PatternMode.Literal); + /// /// Fired when a row is added to the email outbox, so the email consumer drains it immediately /// instead of waiting for its next poll. Payload-less: it is purely a "wake up and check" nudge. diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 9f334e91..0e55f96a 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -28,6 +28,16 @@ public Task SendApiTokenUpdate(Guid tokenId) return _subscriber.PublishAsync(RedisChannels.ApiTokenUpdate(tokenId), RedisValue.EmptyString); } + public Task SendSessionRevoked(string sessionId) + { + return _subscriber.PublishAsync(RedisChannels.SessionRevoked, sessionId); + } + + public Task SendUserAuthRevoked(Guid userId) + { + return _subscriber.PublishAsync(RedisChannels.UserAuthRevoked, userId.ToString()); + } + public Task SendEmailOutboxPending() { // Payload-less wake-up nudge; the consumer reads the actual rows from the database. diff --git a/Common/Services/Session/SessionService.cs b/Common/Services/Session/SessionService.cs index 0d5b307b..4eedbe5d 100644 --- a/Common/Services/Session/SessionService.cs +++ b/Common/Services/Session/SessionService.cs @@ -5,6 +5,7 @@ using OpenShock.Common.Redis; using OpenShock.Common.Services.Audit; using OpenShock.Common.Services.Geo; +using OpenShock.Common.Services.RedisPubSub; using OpenShock.Common.Utils; using OpenShock.Internal.Common.Utils; using Redis.OM; @@ -20,16 +21,38 @@ public sealed class SessionService : ISessionService { private readonly IRedisCollection _loginSessions; private readonly IAuditService _auditService; + private readonly IRedisPubService _redisPubService; + private readonly ILogger _logger; /// /// DI constructor /// /// /// - public SessionService(IRedisConnectionProvider redisConnectionProvider, IAuditService auditService) + /// Announces deleted sessions so open connections using them are closed. + /// + public SessionService(IRedisConnectionProvider redisConnectionProvider, IAuditService auditService, IRedisPubService redisPubService, ILogger logger) { _loginSessions = redisConnectionProvider.RedisCollection(false); _auditService = auditService; + _redisPubService = redisPubService; + _logger = logger; + } + + /// + /// Tells every instance the session is gone. Deliberately swallows failures: the session is already + /// deleted, and a connection that misses the message is caught by its next periodic check. + /// + private async Task NotifyRevokedAsync(LoginSession session) + { + try + { + await _redisPubService.SendSessionRevoked(session.Id); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to announce a deleted session; open connections using it close on their next check"); + } } public async Task CreateSessionAsync(Guid userId, string userAgent, IPAddress ipAddress, Guid? actorId, IpEnrichmentData? enrichment = null) @@ -100,6 +123,7 @@ public async Task DeleteSessionByTokenAsync(string sessionToken) if (session is null) return false; await _loginSessions.DeleteAsync(session); + await NotifyRevokedAsync(session); return true; } @@ -109,6 +133,7 @@ public async Task DeleteSessionByIdAsync(Guid sessionId) if (session is null) return false; await _loginSessions.DeleteAsync(session); + await NotifyRevokedAsync(session); return true; } @@ -118,12 +143,18 @@ public async Task DeleteSessionsByUserIdAsync(Guid userId) await _loginSessions.DeleteAsync(sessions); + foreach (var session in sessions) + { + await NotifyRevokedAsync(session); + } + return sessions.Count; } public async Task DeleteSessionAsync(LoginSession loginSession) { await _loginSessions.DeleteAsync(loginSession); + await NotifyRevokedAsync(loginSession); } public async Task LogoutSessionAsync(LoginSession loginSession) @@ -138,5 +169,6 @@ await _auditService.LogAsync( ); await _loginSessions.DeleteAsync(loginSession); + await NotifyRevokedAsync(loginSession); } } From e36716ccb2ab4eedea76234142db1d26ceb3956b Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 02:24:06 +0100 Subject: [PATCH 2/7] fix: admin deactivate, reactivate and delete user failed on every call The privilege check queried the role_type[] column in a way EF cannot translate, so all three threw. Deleting also wrote an audit row for the user it had just removed, which violated the foreign key; the user's audit log goes with the account, so the deletion is logged instead. --- .../Tests/AdminUserLifecycleTests.cs | 80 +++++++++++++++++++ API/Services/Account/AccountService.cs | 41 +++------- 2 files changed, 93 insertions(+), 28 deletions(-) create mode 100644 API.IntegrationTests/Tests/AdminUserLifecycleTests.cs diff --git a/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs b/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs new file mode 100644 index 00000000..d071b8b6 --- /dev/null +++ b/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs @@ -0,0 +1,80 @@ +using System.Net; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.API.IntegrationTests.Tests; + +public sealed class AdminUserLifecycleTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + [Test] + public async Task Admin_CanDeactivateAndReactivateAUser() + { + using var admin = await CreateAdminClient("adminlcdeact"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("adminlcdeactu"), + TestHelper.UniqueEmail("adminlcdeactu"), "SecurePassword123#"); + + var deactivate = + await admin.PutAsync($"/1/admin/users/{userId}/deactivate?deleteLater=false&reason=test", null); + await Assert.That(deactivate.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsDeactivated(userId)).IsTrue(); + + var reactivate = await admin.PutAsync($"/1/admin/users/{userId}/reactivate?reason=test", null); + await Assert.That(reactivate.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsDeactivated(userId)).IsFalse(); + } + + [Test] + public async Task Admin_CanDeleteAUser() + { + using var admin = await CreateAdminClient("adminlcdelete"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("adminlcdeleteu"), + TestHelper.UniqueEmail("adminlcdeleteu"), "SecurePassword123#"); + + var response = await admin.DeleteAsync($"/1/admin/users/{userId}?reason=test"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AnyAsync(u => u.Id == userId)).IsFalse(); + } + + [Test] + public async Task Admin_CannotDeleteAnotherAdmin() + { + using var admin = await CreateAdminClient("adminlcpriv"); + var otherAdmin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, + TestHelper.UniqueUsername("adminlcprivo"), TestHelper.UniqueEmail("adminlcprivo"), "SecurePassword123#"); + await SetRoles(otherAdmin.Id, [RoleType.Admin]); + + var response = await admin.DeleteAsync($"/1/admin/users/{otherAdmin.Id}"); + await Assert.That(response.IsSuccessStatusCode).IsFalse(); + } + + private async Task CreateAdminClient(string prefix) + { + var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), + TestHelper.UniqueEmail(prefix), "SecurePassword123#"); + await SetRoles(admin.Id, [RoleType.Admin]); + return TestHelper.CreateAuthenticatedClient(WebApplicationFactory, admin.SessionToken); + } + + private async Task SetRoles(Guid userId, List roles) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(s => s.SetProperty(u => u.Roles, roles)); + } + + private async Task IsDeactivated(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.UserDeactivations.AnyAsync(d => d.DeactivatedUserId == userId); + } +} diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 16b368bc..a57758ff 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -93,6 +93,13 @@ private async Task NotifyUserAuthRevokedAsync(Guid userId) } } + private async Task IsPrivilegedAsync(Guid userId, CancellationToken cancellationToken) + { + // Queries over the role_type[] column cannot be translated, so the roles are checked here. + var roles = await _db.Users.Where(u => u.Id == userId).Select(u => u.Roles).FirstOrDefaultAsync(cancellationToken); + return roles is not null && roles.Any(r => r is RoleType.Staff or RoleType.Admin or RoleType.System); + } + private Task IsUserNameBlacklisted(string username, CancellationToken cancellationToken) => _db.UserNameBlacklists.Matching(username).AnyAsync(cancellationToken); @@ -349,13 +356,7 @@ public async Task u.Id == executingUserId) - .SelectMany(u => u.Roles) - .AnyAsync(r => - r == RoleType.Staff || - r == RoleType.Admin || - r == RoleType.System, cancellationToken); + var isPrivileged = await IsPrivilegedAsync(executingUserId, cancellationToken); if (!isPrivileged) { return new Unauthorized(); @@ -420,13 +421,7 @@ public async Task> ReactivateAccountAsyn if (!isSelfReactivation) { - var isPrivileged = await _db.Users - .Where(u => u.Id == executingUserId) - .SelectMany(u => u.Roles) - .AnyAsync(r => - r == RoleType.Staff || - r == RoleType.Admin || - r == RoleType.System, cancellationToken); + var isPrivileged = await IsPrivilegedAsync(executingUserId, cancellationToken); if (!isPrivileged) { return new Unauthorized(); @@ -462,13 +457,7 @@ private async Task RefreshOwnedDevicesAsync(Guid userId, CancellationToken cance /// public async Task> DeleteAccountAsync(Guid executingUserId, Guid userId, string? reason = null, CancellationToken cancellationToken = default) { - var isPrivileged = await _db.Users - .Where(u => u.Id == executingUserId) - .SelectMany(u => u.Roles) - .AnyAsync(r => - r == RoleType.Staff || - r == RoleType.Admin || - r == RoleType.System, cancellationToken); + var isPrivileged = await IsPrivilegedAsync(executingUserId, cancellationToken); if (!isPrivileged) { return new Unauthorized(); @@ -490,15 +479,11 @@ public async Task Date: Thu, 3 Dec 2026 02:24:06 +0100 Subject: [PATCH 3/7] test: cover session expiry, account deletion, token edits and public share guests on hub connections --- .../Tests/SignalRUserHubTests.cs | 87 ++++++++++++++++++- 1 file changed, 84 insertions(+), 3 deletions(-) diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index c5c85f66..5385d597 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -8,8 +8,13 @@ using OpenShock.API.IntegrationTests.Helpers; using OpenShock.API.Services.Account; using OpenShock.Common.Constants; +using OpenShock.Common.Hubs; +using OpenShock.Common.Models; +using OpenShock.Common.Models.WebSocket.User; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Redis; using OpenShock.Common.Services.Session; +using StackExchange.Redis; namespace OpenShock.API.IntegrationTests.Tests; @@ -166,6 +171,82 @@ public async Task DeactivatingAnAccount_ClosesItsSessionAndApiTokenConnections() await AssertConnectionClosesAsync(tokenConnection); } + [Test] + public async Task SessionExpiring_ClosesItsOpenConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickexpire"), TestHelper.UniqueEmail("hubkickexpire"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + + // Let the session reach the end of its lifetime in Redis, as an unused one does. + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + var key = $"{typeof(LoginSession).FullName}:{HubConnectionTracker.GetSessionId(user.SessionToken)}"; + await Assert.That(await redis.KeyExpireAsync(key, TimeSpan.FromMilliseconds(100))).IsTrue(); + + await AssertConnectionClosesAsync(connection); + } + + [Test] + public async Task DeletingAnAccount_ClosesItsSessionAndApiTokenConnections() + { + var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickadmin"), TestHelper.UniqueEmail("hubkickadmin"), "SecurePassword123#"); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickdelete"), TestHelper.UniqueEmail("hubkickdelete"), "SecurePassword123#"); + var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deleted-account"); + await using var sessionConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await using var tokenConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var adminUser = await db.Users.FirstAsync(u => u.Id == admin.Id); + adminUser.Roles = [RoleType.Admin]; + await db.SaveChangesAsync(); + + await scope.ServiceProvider.GetRequiredService().DeleteAccountAsync(admin.Id, user.Id); + await Assert.That(await db.Users.AnyAsync(u => u.Id == user.Id)).IsFalse(); + } + + await AssertConnectionClosesAsync(sessionConnection); + await AssertConnectionClosesAsync(tokenConnection); + } + + [Test] + public async Task EditingOrPausingAnApiToken_KeepsItsConnectionOpen() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubtokenedit"), TestHelper.UniqueEmail("hubtokenedit"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-token-edited"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var paused = await client.PatchAsync($"/2/tokens/{tokenId}/paused", TestHelper.JsonContent(new { paused = true })); + await Assert.That(paused.IsSuccessStatusCode).IsTrue(); + + // The update is announced on the same channel as a deletion; a token that still exists is kept. + await Task.Delay(TimeSpan.FromSeconds(1)); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + // --- Public share guests hold nothing that can be revoked and are not affected by the checks --- + + [Test] + public async Task PublicShareHub_Guest_CanConnectAndKeepCalling() + { + var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubguestowner"), TestHelper.UniqueEmail("hubguestowner"), "SecurePassword123#"); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var created = await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new { name = "guest hub" })); + await Assert.That(created.IsSuccessStatusCode).IsTrue(); + using var json = JsonDocument.Parse(await created.Content.ReadAsStringAsync()); + var shareId = json.RootElement.GetProperty("data").GetGuid(); + + await using var connection = await ConnectAsync(null, null, $"/1/hubs/share/link/{shareId}?name=Guest"); + + await connection.InvokeAsync("Control", Array.Empty()); + await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + await connection.InvokeAsync("Control", Array.Empty()); + + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + // --- The fallback: a connection whose revocation was never announced stops at its next periodic check --- [Test] @@ -315,19 +396,19 @@ public async Task Invoke_AfterApiTokenOwnerDeactivated_FailsAndClosesConnection( /// Opens a real hub connection against the in-process test server. The hub only allows WebSockets, which /// the test server offers through its own client rather than through an HttpMessageHandler. /// - private async Task ConnectAsync(string headerName, string headerValue) + private async Task ConnectAsync(string? headerName, string? headerValue, string path = "/1/hubs/user") { var server = WebApplicationFactory.Server; var connection = new HubConnectionBuilder() - .WithUrl(new Uri(server.BaseAddress, "/1/hubs/user"), options => + .WithUrl(new Uri(server.BaseAddress, path), options => { options.Transports = HttpTransportType.WebSockets; options.SkipNegotiation = true; options.WebSocketFactory = async (context, cancellationToken) => { var client = server.CreateWebSocketClient(); - client.ConfigureRequest = request => request.Headers[headerName] = headerValue; + if (headerName is not null) client.ConfigureRequest = request => request.Headers[headerName] = headerValue; return await client.ConnectAsync(context.Uri, cancellationToken); }; }) From 6761ce3753059c7e3a28c8e3cf0eddf1b5156607 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 17:15:13 +0100 Subject: [PATCH 4/7] fix: address review on hub revalidation - a check that read the database before an API token edit can no longer be recorded after it - a connection whose setup throws is no longer left in the tracker - the per-interval caching test runs on its own host with a long interval, so a slow run cannot fail it - the account deletion log no longer includes the admin-provided reason --- ...lowHubRevalidationWebApplicationFactory.cs | 21 ++++++ .../Tests/HubRevalidationIntervalTests.cs | 35 ++++++++++ .../Tests/SignalRUserHubTests.cs | 29 ++------ API/Services/Account/AccountService.cs | 2 +- .../Hubs/TrackedHubConnectionTests.cs | 32 +++++++++ Common/Hubs/HubConnectionTracker.cs | 40 +++++++++-- .../Hubs/RevalidateAuthenticationHubFilter.cs | 67 +++++++++++++------ 7 files changed, 176 insertions(+), 50 deletions(-) create mode 100644 API.IntegrationTests/SlowHubRevalidationWebApplicationFactory.cs create mode 100644 API.IntegrationTests/Tests/HubRevalidationIntervalTests.cs create mode 100644 Common.Tests/Hubs/TrackedHubConnectionTests.cs diff --git a/API.IntegrationTests/SlowHubRevalidationWebApplicationFactory.cs b/API.IntegrationTests/SlowHubRevalidationWebApplicationFactory.cs new file mode 100644 index 00000000..6937f190 --- /dev/null +++ b/API.IntegrationTests/SlowHubRevalidationWebApplicationFactory.cs @@ -0,0 +1,21 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.Common.Hubs; + +namespace OpenShock.API.IntegrationTests; + +/// +/// Variant of whose hub connections keep a check for long enough that a test +/// can rely on the next call not checking again. +/// +public sealed class SlowHubRevalidationWebApplicationFactory : WebApplicationFactory +{ + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + + builder.ConfigureTestServices(services => + services.Configure(options => options.Interval = TimeSpan.FromMinutes(5))); + } +} diff --git a/API.IntegrationTests/Tests/HubRevalidationIntervalTests.cs b/API.IntegrationTests/Tests/HubRevalidationIntervalTests.cs new file mode 100644 index 00000000..e6402491 --- /dev/null +++ b/API.IntegrationTests/Tests/HubRevalidationIntervalTests.cs @@ -0,0 +1,35 @@ +using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.API.IntegrationTests.Tests; + +public sealed class HubRevalidationIntervalTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required SlowHubRevalidationWebApplicationFactory WebApplicationFactory { get; init; } + + [Test] + public async Task Invoke_ManyCallsInARow_ChecksTheApiTokenOncePerInterval() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalcache"), TestHelper.UniqueEmail("hubrevalcache"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-cached"); + await using var connection = await SignalRUserHubTests.ConnectAsync(WebApplicationFactory, AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); + } + + // Within the interval the deleted token is not looked up again, so the call goes through. It would be + // rejected, and the connection closed, if every call queried the database. Rejection once the interval + // is over is covered by the fallback tests in SignalRUserHubTests. + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } +} diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index 5385d597..b1776003 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -249,28 +249,6 @@ public async Task PublicShareHub_Guest_CanConnectAndKeepCalling() // --- The fallback: a connection whose revocation was never announced stops at its next periodic check --- - [Test] - public async Task Invoke_ManyCallsInARow_ChecksTheApiTokenOncePerInterval() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalcache"), TestHelper.UniqueEmail("hubrevalcache"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-cached"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); - } - - // Straight after the check above, the deleted token is not looked up again: the call goes through. - // (It would be rejected, and the connection closed, if every call queried the database.) - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } - [Test] public async Task Invoke_WithValidSession_KeepsWorking() { @@ -396,9 +374,12 @@ public async Task Invoke_AfterApiTokenOwnerDeactivated_FailsAndClosesConnection( /// Opens a real hub connection against the in-process test server. The hub only allows WebSockets, which /// the test server offers through its own client rather than through an HttpMessageHandler. /// - private async Task ConnectAsync(string? headerName, string? headerValue, string path = "/1/hubs/user") + private Task ConnectAsync(string? headerName, string? headerValue, string path = "/1/hubs/user") + => ConnectAsync(WebApplicationFactory, headerName, headerValue, path); + + internal static async Task ConnectAsync(WebApplicationFactory factory, string? headerName, string? headerValue, string path = "/1/hubs/user") { - var server = WebApplicationFactory.Server; + var server = factory.Server; var connection = new HubConnectionBuilder() .WithUrl(new Uri(server.BaseAddress, path), options => diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index a57758ff..c5ad4226 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -482,7 +482,7 @@ public async Task new(null!, Guid.NewGuid(), sessionId: null, apiTokenId: Guid.NewGuid()); + + [Test] + public async Task TryMarkValidated_RecordsTheCheck() + { + var connection = Create(); + + await Assert.That(connection.TryMarkValidated(connection.Generation)).IsTrue(); + await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsTrue(); + } + + [Test] + public async Task TryMarkValidated_AfterAnInvalidation_DiscardsTheStaleCheck() + { + var connection = Create(); + connection.TryMarkValidated(connection.Generation); + + var generation = connection.Generation; + connection.Invalidate(); + + await Assert.That(connection.TryMarkValidated(generation)).IsFalse(); + await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); + + await Assert.That(connection.TryMarkValidated(connection.Generation)).IsTrue(); + } +} diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs index d4d2a763..0cf16423 100644 --- a/Common/Hubs/HubConnectionTracker.cs +++ b/Common/Hubs/HubConnectionTracker.cs @@ -110,10 +110,15 @@ private int Abort(Func predicate) public sealed class TrackedHubConnection { + private readonly Lock _lock = new(); + // 0 means "not validated": Stopwatch timestamps are never 0 in practice, and a false "not validated" // only costs one extra check. private long _lastValidated; + // Bumped by every invalidation, so a check that read the database before one cannot be recorded after it. + private long _generation; + public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sessionId, Guid? apiTokenId) { Context = context; @@ -127,13 +132,40 @@ public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sess public string? SessionId { get; } public Guid? ApiTokenId { get; } + /// Taken before a check reads the database, and handed to after. + public long Generation + { + get { lock (_lock) return _generation; } + } + public bool WasValidatedWithin(TimeSpan interval) { - var last = Volatile.Read(ref _lastValidated); - return last != 0 && Stopwatch.GetElapsedTime(last) < interval; + lock (_lock) + { + return _lastValidated != 0 && Stopwatch.GetElapsedTime(_lastValidated) < interval; + } } - public void MarkValidated() => Volatile.Write(ref _lastValidated, Stopwatch.GetTimestamp()); + /// Records a successful check, unless the connection was invalidated since it started. + /// The from before the check read the database. + /// False when the check is stale and what it read must not be used. + public bool TryMarkValidated(long generation) + { + lock (_lock) + { + if (generation != _generation) return false; + + _lastValidated = Stopwatch.GetTimestamp(); + return true; + } + } - public void Invalidate() => Volatile.Write(ref _lastValidated, 0); + public void Invalidate() + { + lock (_lock) + { + _generation++; + _lastValidated = 0; + } + } } diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index f8d6da28..bb1492e1 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -47,21 +47,25 @@ public async Task OnConnectedAsync(HubLifetimeContext context, Func @@ -82,28 +86,51 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) { - if (!await IsStillAuthenticated(context, invocationContext.ServiceProvider)) + if (!await ValidateAsync(context, tracked, invocationContext.ServiceProvider)) { context.Abort(); throw new HubException("Authentication is no longer valid"); } - - tracked?.MarkValidated(); } return await next(invocationContext); } - private static async Task IsStillAuthenticated(HubCallerContext context, IServiceProvider services) + /// + /// Checks the connection against the database and records the result. A check that raced an invalidation + /// (an API token edit) read the old row, so it is thrown away and done again. + /// + private static async Task ValidateAsync(HubCallerContext context, TrackedHubConnection? tracked, IServiceProvider services) + { + const int maxAttempts = 3; + + for (var attempt = 1; ; attempt++) + { + var generation = tracked?.Generation ?? 0; + + var (valid, apiToken) = await IsStillAuthenticated(context, services); + if (!valid) return false; + + if (tracked is null || tracked.TryMarkValidated(generation)) + { + if (apiToken is not null) context.Items[HubCallerContextExtensions.CurrentApiTokenKey] = apiToken; + return true; + } + + if (attempt == maxAttempts) throw new HubException("Authentication changed while it was checked, try again"); + } + } + + private static async Task<(bool Valid, ApiToken? ApiToken)> IsStillAuthenticated(HubCallerContext context, IServiceProvider services) { var user = context.User; // Anonymous connection (a public share guest): nothing was granted that could have been revoked. - if (user is null) return true; + if (user is null) return (true, null); if (user.HasOpenShockApiTokenIdentity()) { - if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return false; + if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return (false, null); var db = services.GetRequiredService(); var token = await db.ApiTokens @@ -112,28 +139,26 @@ private static async Task IsStillAuthenticated(HubCallerContext context, I x.Id == tokenId && (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && x.User.UserDeactivation == null, context.ConnectionAborted); - if (token is null) return false; - - context.Items[HubCallerContextExtensions.CurrentApiTokenKey] = token; - return true; + return (token is not null, token); } if (user.TryGetOpenShockUserIdentity() is { } identity) { - if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return false; + if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return (false, null); // Sessions are deleted on logout, on deactivation and on a password reset. var sessionService = services.GetRequiredService(); var session = await sessionService.GetSessionByTokenAsync(sessionToken); - if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return false; + if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return (false, null); // That deletion happens in Redis after the database commit and can fail, leaving the session // behind. The account itself is the authority, as it is when a session authenticates a request. var db = services.GetRequiredService(); - return await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); + var active = await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); + return (active, null); } - return true; + return (true, null); } } From 3c680b01f4ac7f13ac58e9003179806638ca1965 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 17:23:49 +0100 Subject: [PATCH 5/7] test: assert the specific rejection when deleting another admin --- API.IntegrationTests/Tests/AdminUserLifecycleTests.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs b/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs index d071b8b6..57cf05e5 100644 --- a/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs +++ b/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs @@ -53,7 +53,12 @@ public async Task Admin_CannotDeleteAnotherAdmin() await SetRoles(otherAdmin.Id, [RoleType.Admin]); var response = await admin.DeleteAsync($"/1/admin/users/{otherAdmin.Id}"); - await Assert.That(response.IsSuccessStatusCode).IsFalse(); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Deactivate.DeniedPrivileged"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AnyAsync(u => u.Id == otherAdmin.Id)).IsTrue(); } private async Task CreateAdminClient(string prefix) From 4d2dab1ff713302ea9b9f7b5fb6da4ff57dc5a05 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 22:42:39 +0100 Subject: [PATCH 6/7] refactor: drop the generation guard from hub revalidation --- .../Hubs/TrackedHubConnectionTests.cs | 21 +++++---- Common/Hubs/HubConnectionTracker.cs | 43 +++---------------- .../Hubs/RevalidateAuthenticationHubFilter.cs | 26 +++-------- 3 files changed, 23 insertions(+), 67 deletions(-) diff --git a/Common.Tests/Hubs/TrackedHubConnectionTests.cs b/Common.Tests/Hubs/TrackedHubConnectionTests.cs index 9f14bd5b..392ce89b 100644 --- a/Common.Tests/Hubs/TrackedHubConnectionTests.cs +++ b/Common.Tests/Hubs/TrackedHubConnectionTests.cs @@ -7,26 +7,29 @@ public sealed class TrackedHubConnectionTests private static TrackedHubConnection Create() => new(null!, Guid.NewGuid(), sessionId: null, apiTokenId: Guid.NewGuid()); [Test] - public async Task TryMarkValidated_RecordsTheCheck() + public async Task NewConnection_IsNotValidated() { var connection = Create(); - await Assert.That(connection.TryMarkValidated(connection.Generation)).IsTrue(); - await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsTrue(); + await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); } [Test] - public async Task TryMarkValidated_AfterAnInvalidation_DiscardsTheStaleCheck() + public async Task MarkValidated_RecordsTheCheck() { var connection = Create(); - connection.TryMarkValidated(connection.Generation); + connection.MarkValidated(); + + await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsTrue(); + } - var generation = connection.Generation; + [Test] + public async Task Invalidate_ClearsTheCheck() + { + var connection = Create(); + connection.MarkValidated(); connection.Invalidate(); - await Assert.That(connection.TryMarkValidated(generation)).IsFalse(); await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); - - await Assert.That(connection.TryMarkValidated(connection.Generation)).IsTrue(); } } diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs index 0cf16423..4cc6efb4 100644 --- a/Common/Hubs/HubConnectionTracker.cs +++ b/Common/Hubs/HubConnectionTracker.cs @@ -110,15 +110,9 @@ private int Abort(Func predicate) public sealed class TrackedHubConnection { - private readonly Lock _lock = new(); - - // 0 means "not validated": Stopwatch timestamps are never 0 in practice, and a false "not validated" - // only costs one extra check. + // 0 means "not validated": Stopwatch timestamps are never 0 in practice. private long _lastValidated; - // Bumped by every invalidation, so a check that read the database before one cannot be recorded after it. - private long _generation; - public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sessionId, Guid? apiTokenId) { Context = context; @@ -132,40 +126,13 @@ public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sess public string? SessionId { get; } public Guid? ApiTokenId { get; } - /// Taken before a check reads the database, and handed to after. - public long Generation - { - get { lock (_lock) return _generation; } - } - public bool WasValidatedWithin(TimeSpan interval) { - lock (_lock) - { - return _lastValidated != 0 && Stopwatch.GetElapsedTime(_lastValidated) < interval; - } + var lastValidated = Interlocked.Read(ref _lastValidated); + return lastValidated != 0 && Stopwatch.GetElapsedTime(lastValidated) < interval; } - /// Records a successful check, unless the connection was invalidated since it started. - /// The from before the check read the database. - /// False when the check is stale and what it read must not be used. - public bool TryMarkValidated(long generation) - { - lock (_lock) - { - if (generation != _generation) return false; - - _lastValidated = Stopwatch.GetTimestamp(); - return true; - } - } + public void MarkValidated() => Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); - public void Invalidate() - { - lock (_lock) - { - _generation++; - _lastValidated = 0; - } - } + public void Invalidate() => Interlocked.Exchange(ref _lastValidated, 0); } diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index bb1492e1..e362dbf2 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -96,29 +96,15 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception return await next(invocationContext); } - /// - /// Checks the connection against the database and records the result. A check that raced an invalidation - /// (an API token edit) read the old row, so it is thrown away and done again. - /// + /// Checks the connection against the database and records the result. private static async Task ValidateAsync(HubCallerContext context, TrackedHubConnection? tracked, IServiceProvider services) { - const int maxAttempts = 3; - - for (var attempt = 1; ; attempt++) - { - var generation = tracked?.Generation ?? 0; - - var (valid, apiToken) = await IsStillAuthenticated(context, services); - if (!valid) return false; + var (valid, apiToken) = await IsStillAuthenticated(context, services); + if (!valid) return false; - if (tracked is null || tracked.TryMarkValidated(generation)) - { - if (apiToken is not null) context.Items[HubCallerContextExtensions.CurrentApiTokenKey] = apiToken; - return true; - } - - if (attempt == maxAttempts) throw new HubException("Authentication changed while it was checked, try again"); - } + tracked?.MarkValidated(); + if (apiToken is not null) context.Items[HubCallerContextExtensions.CurrentApiTokenKey] = apiToken; + return true; } private static async Task<(bool Valid, ApiToken? ApiToken)> IsStillAuthenticated(HubCallerContext context, IServiceProvider services) From 09a5a1702a00051348dc452d680c0547ed67bad0 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 22:47:45 +0100 Subject: [PATCH 7/7] refactor: close API token connections on any token change --- ...lowHubRevalidationWebApplicationFactory.cs | 21 --------- .../Tests/HubRevalidationIntervalTests.cs | 35 -------------- .../Tests/SignalRUserHubTests.cs | 7 +-- API/Realtime/RedisSubscriberService.cs | 28 +---------- API/Services/Account/AccountService.cs | 21 +-------- .../Hubs/TrackedHubConnectionTests.cs | 9 ---- Common/Hubs/HubConnectionTracker.cs | 24 ---------- .../Hubs/RevalidateAuthenticationHubFilter.cs | 46 ++++++------------- Common/Hubs/UserHub.cs | 11 ++--- .../Services/RedisPubSub/IRedisPubService.cs | 2 +- Common/Services/Session/SessionService.cs | 31 +++---------- 11 files changed, 31 insertions(+), 204 deletions(-) delete mode 100644 API.IntegrationTests/SlowHubRevalidationWebApplicationFactory.cs delete mode 100644 API.IntegrationTests/Tests/HubRevalidationIntervalTests.cs diff --git a/API.IntegrationTests/SlowHubRevalidationWebApplicationFactory.cs b/API.IntegrationTests/SlowHubRevalidationWebApplicationFactory.cs deleted file mode 100644 index 6937f190..00000000 --- a/API.IntegrationTests/SlowHubRevalidationWebApplicationFactory.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using OpenShock.Common.Hubs; - -namespace OpenShock.API.IntegrationTests; - -/// -/// Variant of whose hub connections keep a check for long enough that a test -/// can rely on the next call not checking again. -/// -public sealed class SlowHubRevalidationWebApplicationFactory : WebApplicationFactory -{ - protected override void ConfigureWebHost(IWebHostBuilder builder) - { - base.ConfigureWebHost(builder); - - builder.ConfigureTestServices(services => - services.Configure(options => options.Interval = TimeSpan.FromMinutes(5))); - } -} diff --git a/API.IntegrationTests/Tests/HubRevalidationIntervalTests.cs b/API.IntegrationTests/Tests/HubRevalidationIntervalTests.cs deleted file mode 100644 index e6402491..00000000 --- a/API.IntegrationTests/Tests/HubRevalidationIntervalTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Microsoft.AspNetCore.SignalR.Client; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using OpenShock.API.IntegrationTests.Helpers; -using OpenShock.Common.Constants; -using OpenShock.Common.OpenShockDb; - -namespace OpenShock.API.IntegrationTests.Tests; - -public sealed class HubRevalidationIntervalTests -{ - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required SlowHubRevalidationWebApplicationFactory WebApplicationFactory { get; init; } - - [Test] - public async Task Invoke_ManyCallsInARow_ChecksTheApiTokenOncePerInterval() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalcache"), TestHelper.UniqueEmail("hubrevalcache"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-cached"); - await using var connection = await SignalRUserHubTests.ConnectAsync(WebApplicationFactory, AuthConstants.ApiTokenHeaderName, rawToken); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); - } - - // Within the interval the deleted token is not looked up again, so the call goes through. It would be - // rejected, and the connection closed, if every call queried the database. Rejection once the interval - // is over is covered by the fallback tests in SignalRUserHubTests. - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); - } -} diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index b1776003..9544aad6 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -210,7 +210,7 @@ public async Task DeletingAnAccount_ClosesItsSessionAndApiTokenConnections() } [Test] - public async Task EditingOrPausingAnApiToken_KeepsItsConnectionOpen() + public async Task PausingAnApiToken_ClosesItsConnection() { var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubtokenedit"), TestHelper.UniqueEmail("hubtokenedit"), "SecurePassword123#"); var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-token-edited"); @@ -220,10 +220,7 @@ public async Task EditingOrPausingAnApiToken_KeepsItsConnectionOpen() var paused = await client.PatchAsync($"/2/tokens/{tokenId}/paused", TestHelper.JsonContent(new { paused = true })); await Assert.That(paused.IsSuccessStatusCode).IsTrue(); - // The update is announced on the same channel as a deletion; a token that still exists is kept. - await Task.Delay(TimeSpan.FromSeconds(1)); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + await AssertConnectionClosesAsync(connection); } // --- Public share guests hold nothing that can be revoked and are not affected by the checks --- diff --git a/API/Realtime/RedisSubscriberService.cs b/API/Realtime/RedisSubscriberService.cs index 4c2c0902..7ff90748 100644 --- a/API/Realtime/RedisSubscriberService.cs +++ b/API/Realtime/RedisSubscriberService.cs @@ -84,33 +84,9 @@ private void HandleApiTokenUpdate(RedisChannel channel, RedisValue _) if (channelName is null || !channelName.StartsWith(RedisChannels.ApiTokenUpdatePrefix, StringComparison.Ordinal)) return; if (!Guid.TryParse(channelName.AsSpan(RedisChannels.ApiTokenUpdatePrefix.Length), out var tokenId)) return; - // Most token changes concern no connection on this instance: no database round trip for those. - if (!_hubConnections.HasApiTokenConnections(tokenId)) return; - - OsTask.Run(() => ApplyApiTokenUpdate(tokenId)); - } - - /// - /// The same channel announces an edit and a deletion, so look: a token that is gone closes its - /// connections, one that changed makes them read it again on their next call. - /// - private async Task ApplyApiTokenUpdate(Guid tokenId) - { - await using var db = await _dbContextFactory.CreateDbContextAsync(); - - var stillValid = await db.ApiTokens.AnyAsync(x => - x.Id == tokenId && - (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && - x.User.UserDeactivation == null); - - if (stillValid) - { - _hubConnections.InvalidateApiToken(tokenId); - return; - } - + // An edit or pause closes the connections too: the client reconnects with the token as it is now. var closed = _hubConnections.AbortApiToken(tokenId); - _logger.LogDebug("Closed {Count} hub connection(s) of revoked API token [{TokenId}]", closed, tokenId); + if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of changed API token [{TokenId}]", closed, tokenId); } private void HandleKeyExpired(RedisChannel _, RedisValue message) diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index c5ad4226..a89261ab 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -76,23 +76,6 @@ private async Task NotifyEmailOutboxAsync() } } - /// - /// Tells every instance the account may no longer be used, so its open connections are closed, the ones - /// that authenticated with an API token included. Deliberately swallows failures: the change is already - /// committed, and a connection that misses the message is caught by its next periodic check. - /// - private async Task NotifyUserAuthRevokedAsync(Guid userId) - { - try - { - await _redisPubService.SendUserAuthRevoked(userId); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to announce revoked access for user ID: [{Id}]; open connections close on their next check", userId); - } - } - private async Task IsPrivilegedAsync(Guid userId, CancellationToken cancellationToken) { // Queries over the role_type[] column cannot be translated, so the roles are checked here. @@ -398,7 +381,7 @@ await _auditService.LogAsync( await transaction.CommitAsync(); } - await NotifyUserAuthRevokedAsync(userId); + await _redisPubService.SendUserAuthRevoked(userId); // Remove all login sessions await _sessionService.DeleteSessionsByUserIdAsync(userId); @@ -484,7 +467,7 @@ public async TaskHow many connections were closed. public int AbortApiToken(Guid tokenId) => Abort(c => c.ApiTokenId == tokenId); - public bool HasApiTokenConnections(Guid tokenId) - { - foreach (var connection in _connections.Values) - { - if (connection.ApiTokenId == tokenId) return true; - } - - return false; - } - - /// - /// Makes the connections using this API token read it from the database again on their next call, so a - /// change to its permissions, pause state or limits applies from then on. - /// - public void InvalidateApiToken(Guid tokenId) - { - foreach (var connection in _connections.Values) - { - if (connection.ApiTokenId == tokenId) connection.Invalidate(); - } - } - /// The id a session is stored under in Redis: the hash of its token (old tokens are stored as they are). public static string GetSessionId(string sessionToken) => sessionToken.Length == AuthConstants.GeneratedTokenLength ? HashingUtils.HashToken(sessionToken) : sessionToken; @@ -133,6 +111,4 @@ public bool WasValidatedWithin(TimeSpan interval) } public void MarkValidated() => Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); - - public void Invalidate() => Interlocked.Exchange(ref _lastValidated, 0); } diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index e362dbf2..17d93d74 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -26,9 +26,8 @@ namespace OpenShock.Common.Hubs; /// per connection, and never for an idle one. /// /// -/// For an API token the row read here is handed to the hub method through -/// . A change to the token invalidates the -/// connection's last check, so its permissions, pause state and control limits are read again on the next call. +/// Any change to an API token closes its connections, so a client picks up new permissions, pause state and +/// control limits when it reconnects. /// /// public sealed class RevalidateAuthenticationHubFilter : IHubFilter @@ -99,52 +98,47 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception /// Checks the connection against the database and records the result. private static async Task ValidateAsync(HubCallerContext context, TrackedHubConnection? tracked, IServiceProvider services) { - var (valid, apiToken) = await IsStillAuthenticated(context, services); - if (!valid) return false; + if (!await IsStillAuthenticated(context, services)) return false; tracked?.MarkValidated(); - if (apiToken is not null) context.Items[HubCallerContextExtensions.CurrentApiTokenKey] = apiToken; return true; } - private static async Task<(bool Valid, ApiToken? ApiToken)> IsStillAuthenticated(HubCallerContext context, IServiceProvider services) + private static async Task IsStillAuthenticated(HubCallerContext context, IServiceProvider services) { var user = context.User; // Anonymous connection (a public share guest): nothing was granted that could have been revoked. - if (user is null) return (true, null); + if (user is null) return true; if (user.HasOpenShockApiTokenIdentity()) { - if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return (false, null); + if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return false; var db = services.GetRequiredService(); - var token = await db.ApiTokens - .AsNoTracking() - .FirstOrDefaultAsync(x => - x.Id == tokenId && - (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && - x.User.UserDeactivation == null, context.ConnectionAborted); - return (token is not null, token); + return await db.ApiTokens.AnyAsync(x => + x.Id == tokenId && + (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && + x.User.UserDeactivation == null, context.ConnectionAborted); } if (user.TryGetOpenShockUserIdentity() is { } identity) { - if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return (false, null); + if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return false; // Sessions are deleted on logout, on deactivation and on a password reset. var sessionService = services.GetRequiredService(); var session = await sessionService.GetSessionByTokenAsync(sessionToken); - if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return (false, null); + if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return false; // That deletion happens in Redis after the database commit and can fail, leaving the session // behind. The account itself is the authority, as it is when a session authenticates a request. var db = services.GetRequiredService(); var active = await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); - return (active, null); + return active; } - return (true, null); + return true; } } @@ -157,15 +151,3 @@ public sealed class HubRevalidationOptions /// public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); } - -public static class HubCallerContextExtensions -{ - internal static readonly object CurrentApiTokenKey = new(); - - /// - /// The API token this connection authenticated with, as it was in the database when the connection was - /// last checked. Null for a session or anonymous connection. - /// - public static ApiToken? GetCurrentApiToken(this HubCallerContext context) - => context.Items.TryGetValue(CurrentApiTokenKey, out var token) ? token as ApiToken : null; -} diff --git a/Common/Hubs/UserHub.cs b/Common/Hubs/UserHub.cs index b996fbb9..c3d3eea3 100644 --- a/Common/Hubs/UserHub.cs +++ b/Common/Hubs/UserHub.cs @@ -28,11 +28,9 @@ public sealed class UserHub : Hub /// connection. Derived per access: SignalR creates a hub instance per invocation, so a field /// set in would be null everywhere else. /// - private IReadOnlyList? TokenPermissions => Context.GetCurrentApiToken() is { } apiToken - ? apiToken.Permissions - : Context.User?.HasOpenShockApiTokenIdentity() == true - ? Context.User.GetApiTokenPermissions() - : null; + private IReadOnlyList? TokenPermissions => Context.User?.HasOpenShockApiTokenIdentity() == true + ? Context.User.GetApiTokenPermissions() + : null; public UserHub(ILogger logger, OpenShockContext db, IRedisConnectionProvider provider, IRedisPubService redisPubService, IControlSender controlSender) @@ -98,8 +96,7 @@ public async Task ControlV2(IReadOnlyList shocks, string? customName) }).FirstAsync(Context.ConnectionAborted); ApiTokenControlLimits? tokenLimits = null; - // The token as it is now, not as it was when the connection opened (see RevalidateAuthenticationHubFilter). - if (Context.GetCurrentApiToken() is { } apiToken) + if (Context.GetHttpContext()?.GetItemByType() is { } apiToken) { // A paused token may not control shockers. if (apiToken.ShockerControlPaused) return; diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 982433e9..3a9dcb92 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -22,7 +22,7 @@ public interface IRedisPubService /// /// A login session was deleted. Notifies every instance so open connections that authenticated with it - /// are closed. Best-effort: a connection that misses it is caught by its next periodic check. + /// are closed. /// /// The id the session was stored under. Task SendSessionRevoked(string sessionId); diff --git a/Common/Services/Session/SessionService.cs b/Common/Services/Session/SessionService.cs index 4eedbe5d..ce614cf8 100644 --- a/Common/Services/Session/SessionService.cs +++ b/Common/Services/Session/SessionService.cs @@ -22,7 +22,6 @@ public sealed class SessionService : ISessionService private readonly IRedisCollection _loginSessions; private readonly IAuditService _auditService; private readonly IRedisPubService _redisPubService; - private readonly ILogger _logger; /// /// DI constructor @@ -30,29 +29,11 @@ public sealed class SessionService : ISessionService /// /// /// Announces deleted sessions so open connections using them are closed. - /// - public SessionService(IRedisConnectionProvider redisConnectionProvider, IAuditService auditService, IRedisPubService redisPubService, ILogger logger) + public SessionService(IRedisConnectionProvider redisConnectionProvider, IAuditService auditService, IRedisPubService redisPubService) { _loginSessions = redisConnectionProvider.RedisCollection(false); _auditService = auditService; _redisPubService = redisPubService; - _logger = logger; - } - - /// - /// Tells every instance the session is gone. Deliberately swallows failures: the session is already - /// deleted, and a connection that misses the message is caught by its next periodic check. - /// - private async Task NotifyRevokedAsync(LoginSession session) - { - try - { - await _redisPubService.SendSessionRevoked(session.Id); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to announce a deleted session; open connections using it close on their next check"); - } } public async Task CreateSessionAsync(Guid userId, string userAgent, IPAddress ipAddress, Guid? actorId, IpEnrichmentData? enrichment = null) @@ -123,7 +104,7 @@ public async Task DeleteSessionByTokenAsync(string sessionToken) if (session is null) return false; await _loginSessions.DeleteAsync(session); - await NotifyRevokedAsync(session); + await _redisPubService.SendSessionRevoked(session.Id); return true; } @@ -133,7 +114,7 @@ public async Task DeleteSessionByIdAsync(Guid sessionId) if (session is null) return false; await _loginSessions.DeleteAsync(session); - await NotifyRevokedAsync(session); + await _redisPubService.SendSessionRevoked(session.Id); return true; } @@ -145,7 +126,7 @@ public async Task DeleteSessionsByUserIdAsync(Guid userId) foreach (var session in sessions) { - await NotifyRevokedAsync(session); + await _redisPubService.SendSessionRevoked(session.Id); } return sessions.Count; @@ -154,7 +135,7 @@ public async Task DeleteSessionsByUserIdAsync(Guid userId) public async Task DeleteSessionAsync(LoginSession loginSession) { await _loginSessions.DeleteAsync(loginSession); - await NotifyRevokedAsync(loginSession); + await _redisPubService.SendSessionRevoked(loginSession.Id); } public async Task LogoutSessionAsync(LoginSession loginSession) @@ -169,6 +150,6 @@ await _auditService.LogAsync( ); await _loginSessions.DeleteAsync(loginSession); - await NotifyRevokedAsync(loginSession); + await _redisPubService.SendSessionRevoked(loginSession.Id); } }