diff --git a/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs b/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs new file mode 100644 index 00000000..57cf05e5 --- /dev/null +++ b/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs @@ -0,0 +1,85 @@ +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.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) + { + 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.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index f1ecc415..9544aad6 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -1,8 +1,20 @@ 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.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; @@ -99,4 +111,322 @@ 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); + } + + [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 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"); + 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(); + + await AssertConnectionClosesAsync(connection); + } + + // --- 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] + 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 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 = factory.Server; + + var connection = new HubConnectionBuilder() + .WithUrl(new Uri(server.BaseAddress, path), options => + { + options.Transports = HttpTransportType.WebSockets; + options.SkipNegotiation = true; + options.WebSocketFactory = async (context, cancellationToken) => + { + var client = server.CreateWebSocketClient(); + if (headerName is not null) 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..7ff90748 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,37 @@ 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; + + // An edit or pause closes the connections too: the client reconnects with the token as it is now. + var closed = _hubConnections.AbortApiToken(tokenId); + if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of changed API token [{TokenId}]", closed, tokenId); } private void HandleKeyExpired(RedisChannel _, RedisValue message) @@ -94,6 +129,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 c975c832..a89261ab 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -76,6 +76,13 @@ private async Task NotifyEmailOutboxAsync() } } + 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); @@ -332,13 +339,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(); @@ -380,6 +381,8 @@ await _auditService.LogAsync( await transaction.CommitAsync(); } + await _redisPubService.SendUserAuthRevoked(userId); + // Remove all login sessions await _sessionService.DeleteSessionsByUserIdAsync(userId); @@ -401,13 +404,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(); @@ -443,13 +440,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(); @@ -471,15 +462,13 @@ public async Task new(null!, Guid.NewGuid(), sessionId: null, apiTokenId: Guid.NewGuid()); + + [Test] + public async Task NewConnection_IsNotValidated() + { + var connection = Create(); + + await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); + } + + [Test] + public async Task MarkValidated_RecordsTheCheck() + { + var connection = Create(); + connection.MarkValidated(); + + await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsTrue(); + } + +} diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs new file mode 100644 index 00000000..40b4bd45 --- /dev/null +++ b/Common/Hubs/HubConnectionTracker.cs @@ -0,0 +1,114 @@ +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); + + /// 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. + 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 lastValidated = Interlocked.Read(ref _lastValidated); + return lastValidated != 0 && Stopwatch.GetElapsedTime(lastValidated) < interval; + } + + public void MarkValidated() => Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); +} diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs new file mode 100644 index 00000000..17d93d74 --- /dev/null +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -0,0 +1,153 @@ +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. +/// +/// +/// 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 +{ + 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); + + try + { + // 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 && !await ValidateAsync(context.Context, tracked, context.ServiceProvider)) + { + _tracker.Untrack(context.Context.ConnectionId); + context.Context.Abort(); + return; + } + + await next(context); + } + catch + { + // SignalR does not call OnDisconnectedAsync when connecting throws. + _tracker.Untrack(context.Context.ConnectionId); + throw; + } + } + + /// + 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 ValidateAsync(context, tracked, invocationContext.ServiceProvider)) + { + context.Abort(); + throw new HubException("Authentication is no longer valid"); + } + } + + return await next(invocationContext); + } + + /// Checks the connection against the database and records the result. + private static async Task ValidateAsync(HubCallerContext context, TrackedHubConnection? tracked, IServiceProvider services) + { + if (!await IsStillAuthenticated(context, services)) return false; + + tracked?.MarkValidated(); + return true; + } + + 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(); + 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; + + // 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(); + var active = await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); + return active; + } + + 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); +} 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..3a9dcb92 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. + /// + /// 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..ce614cf8 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,19 @@ public sealed class SessionService : ISessionService { private readonly IRedisCollection _loginSessions; private readonly IAuditService _auditService; + private readonly IRedisPubService _redisPubService; /// /// 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) { _loginSessions = redisConnectionProvider.RedisCollection(false); _auditService = auditService; + _redisPubService = redisPubService; } public async Task CreateSessionAsync(Guid userId, string userAgent, IPAddress ipAddress, Guid? actorId, IpEnrichmentData? enrichment = null) @@ -100,6 +104,7 @@ public async Task DeleteSessionByTokenAsync(string sessionToken) if (session is null) return false; await _loginSessions.DeleteAsync(session); + await _redisPubService.SendSessionRevoked(session.Id); return true; } @@ -109,6 +114,7 @@ public async Task DeleteSessionByIdAsync(Guid sessionId) if (session is null) return false; await _loginSessions.DeleteAsync(session); + await _redisPubService.SendSessionRevoked(session.Id); return true; } @@ -118,12 +124,18 @@ public async Task DeleteSessionsByUserIdAsync(Guid userId) await _loginSessions.DeleteAsync(sessions); + foreach (var session in sessions) + { + await _redisPubService.SendSessionRevoked(session.Id); + } + return sessions.Count; } public async Task DeleteSessionAsync(LoginSession loginSession) { await _loginSessions.DeleteAsync(loginSession); + await _redisPubService.SendSessionRevoked(loginSession.Id); } public async Task LogoutSessionAsync(LoginSession loginSession) @@ -138,5 +150,6 @@ await _auditService.LogAsync( ); await _loginSessions.DeleteAsync(loginSession); + await _redisPubService.SendSessionRevoked(loginSession.Id); } }