From bfa72d5aab3f2c22b29cc74baf6f6ae20d6e4684 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:07:06 +0100 Subject: [PATCH] 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 f1ecc415b..c5c85f664 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 7d335f688..8e3687e64 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 6351d50d7..4c2c09021 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 6ecdee491..c9cb1f5bb 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 000000000..d4d2a7634 --- /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 000000000..f8d6da285 --- /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 c3d3eea35..b996fbb9e 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 896a50594..43d2158ae 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 8e308f395..982433e9c 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 d0df75bd5..53de95e72 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 9f334e91c..0e55f96a5 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 0d5b307bb..4eedbe5db 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); } }