From bfa72d5aab3f2c22b29cc74baf6f6ae20d6e4684 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:07:06 +0100 Subject: [PATCH 01/11] 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 02/11] 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 03/11] 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 24a920a6605cc99bf0bd3b32bccb8f29f95caae3 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 02:31:38 +0100 Subject: [PATCH 04/11] feat: optional password for public shares - public shares can have a password (bcrypt), set on create or through PUT /1/shares/links/{id}/password - visitors unlock with POST /1/public/shares/links/{id}/unlock and get a 12 hour token, sent in the OpenShockPublicShareUnlock header and as the unlockToken hub query parameter; the owner never needs it - a locked share still returns its name and author but no devices (passwordRequired) - tokens are tied to a password stamp: setting or changing the password invalidates them and closes open hub connections, removing it keeps them; deleting a share closes its connections too - incorrect passwords are rate limited per IP and capped at 20 per share per 15 minutes - hub connections to a public share are re-checked against expiry, owner and password stamp --- .../Tests/PublicSharePasswordTests.cs | 471 ++++ API/Controller/Public/GetUserProfile.cs | 3 +- .../Public/PublicShareController.cs | 40 +- API/Controller/Public/UnlockPublicShare.cs | 64 + .../Shares/Links/CreatePublicShare.cs | 3 + .../Shares/Links/DeletePublicShare.cs | 4 +- .../Shares/Links/SetPublicSharePassword.cs | 54 + API/Models/Requests/PublicShareCreate.cs | 6 + API/Models/Requests/PublicSharePasswordSet.cs | 13 + API/Models/Requests/PublicShareUnlock.cs | 11 + API/Models/Response/OwnPublicShareResponse.cs | 4 +- API/Models/Response/PublicShareResponse.cs | 10 + .../Response/PublicShareUnlockResponse.cs | 12 + .../Response/PublicUserProfileResponse.cs | 1 + API/Realtime/RedisSubscriberService.cs | 9 + Common/Constants/ApiHardLimits.cs | 2 + Common/Constants/AuthConstants.cs | 1 + Common/Errors/PublicShareError.cs | 5 + Common/Hubs/HubConnectionTracker.cs | 28 + Common/Hubs/PublicShareHub.cs | 32 +- .../Hubs/RevalidateAuthenticationHubFilter.cs | 18 +- ...203012615_PublicSharePasswords.Designer.cs | 2000 +++++++++++++++++ .../20261203012615_PublicSharePasswords.cs | 40 + .../OpenShockContextModelSnapshot.cs | 12 +- Common/OpenShockDb/Models/PublicShare.cs | 10 + Common/OpenShockDb/OpenShockContext.cs | 5 + Common/OpenShockServiceHelper.cs | 2 + .../PublicShareAccessService.cs | 78 + .../Services/RedisPubSub/IRedisPubService.cs | 6 + Common/Services/RedisPubSub/RedisChannels.cs | 6 + .../Services/RedisPubSub/RedisPubService.cs | 5 + 31 files changed, 2939 insertions(+), 16 deletions(-) create mode 100644 API.IntegrationTests/Tests/PublicSharePasswordTests.cs create mode 100644 API/Controller/Public/UnlockPublicShare.cs create mode 100644 API/Controller/Shares/Links/SetPublicSharePassword.cs create mode 100644 API/Models/Requests/PublicSharePasswordSet.cs create mode 100644 API/Models/Requests/PublicShareUnlock.cs create mode 100644 API/Models/Response/PublicShareUnlockResponse.cs create mode 100644 Common/Migrations/20261203012615_PublicSharePasswords.Designer.cs create mode 100644 Common/Migrations/20261203012615_PublicSharePasswords.cs create mode 100644 Common/Services/PublicShareAccess/PublicShareAccessService.cs diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs new file mode 100644 index 00000000..97ebe747 --- /dev/null +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -0,0 +1,471 @@ +using System.Net; +using System.Text.Json; +using Microsoft.AspNetCore.Http.Connections; +using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Constants; +using OpenShock.Common.Models.WebSocket.User; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.PublicShareAccess; +using OpenShock.Common.Services.Session; + +namespace OpenShock.API.IntegrationTests.Tests; + +public sealed class PublicSharePasswordTests +{ + private const string Password = "hunter22"; + + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + // --- Loading the share --- + + [Test] + public async Task ProtectedShare_HidesShockersUntilUnlocked() + { + var (_, shareId) = await CreateShareWithShocker("pwhide", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + var locked = await GetShare(visitor, shareId, unlockToken: null); + await Assert.That(locked.GetProperty("passwordProtected").GetBoolean()).IsTrue(); + await Assert.That(locked.GetProperty("passwordRequired").GetBoolean()).IsTrue(); + await Assert.That(locked.GetProperty("devices").GetArrayLength()).IsEqualTo(0); + await Assert.That(locked.GetProperty("name").GetString()).IsEqualTo("pw share"); + + var token = await Unlock(visitor, shareId, Password); + var unlocked = await GetShare(visitor, shareId, token); + await Assert.That(unlocked.GetProperty("passwordRequired").GetBoolean()).IsFalse(); + await Assert.That(unlocked.GetProperty("devices").GetArrayLength()).IsEqualTo(1); + } + + [Test] + public async Task ProtectedShare_BySlug_NeedsTheTokenToo() + { + var (owner, shareId) = await CreateShareWithShocker("pwslug", Password, slug: "locked"); + using var visitor = WebApplicationFactory.CreateClient(); + + var locked = await GetJson(visitor, $"/1/public/shares/links/by-slug/{owner.Username}/locked", unlockToken: null); + await Assert.That(locked.GetProperty("passwordRequired").GetBoolean()).IsTrue(); + + var token = await Unlock(visitor, shareId, Password); + var unlocked = await GetJson(visitor, $"/1/public/shares/links/by-slug/{owner.Username}/locked", token); + await Assert.That(unlocked.GetProperty("devices").GetArrayLength()).IsEqualTo(1); + } + + [Test] + public async Task ProtectedShare_OwnerSeesItWithoutPassword() + { + var (owner, shareId) = await CreateShareWithShocker("pwowner", Password); + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + + var share = await GetShare(ownerClient, shareId, unlockToken: null); + await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsFalse(); + await Assert.That(share.GetProperty("devices").GetArrayLength()).IsEqualTo(1); + } + + [Test] + public async Task ShareWithoutPassword_IsOpen() + { + var (_, shareId) = await CreateShareWithShocker("pwnone", password: null); + using var visitor = WebApplicationFactory.CreateClient(); + + var share = await GetShare(visitor, shareId, unlockToken: null); + await Assert.That(share.GetProperty("passwordProtected").GetBoolean()).IsFalse(); + await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsFalse(); + await Assert.That(share.GetProperty("devices").GetArrayLength()).IsEqualTo(1); + + var unlock = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = Password })); + await Assert.That(unlock.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + } + + [Test] + public async Task OwnList_ShowsWhetherAShareHasAPassword() + { + var (owner, shareId) = await CreateShareWithShocker("pwlist", Password); + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + + var list = await GetJson(ownerClient, "/1/shares/links", unlockToken: null); + var entry = list.EnumerateArray().Single(x => x.GetProperty("id").GetGuid() == shareId); + await Assert.That(entry.GetProperty("hasPassword").GetBoolean()).IsTrue(); + } + + // --- Unlocking --- + + [Test] + public async Task Unlock_WithWrongPassword_Returns401() + { + var (_, shareId) = await CreateShareWithShocker("pwwrong", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + var response = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = "nope-nope" })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + } + + [Test] + public async Task Unlock_AfterTooManyWrongPasswords_IsLockedOutEvenWithTheRightOne() + { + var (_, shareId) = await CreateShareWithShocker("pwlockout", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + for (var i = 0; i < PublicShareAccessService.MaxFailedAttempts; i++) + { + await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = "nope-nope" })); + } + + var response = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = Password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); + } + + [Test] + public async Task Unlock_TokenIsOnlyValidForItsShare() + { + var (_, shareId) = await CreateShareWithShocker("pwscope", Password); + var (_, otherShareId) = await CreateShareWithShocker("pwscopeo", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + var token = await Unlock(visitor, shareId, Password); + var other = await GetShare(visitor, otherShareId, token); + await Assert.That(other.GetProperty("passwordRequired").GetBoolean()).IsTrue(); + } + + // --- Changing the password --- + + [Test] + public async Task ChangingThePassword_InvalidatesEarlierTokens() + { + var (owner, shareId) = await CreateShareWithShocker("pwchange", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + + await SetPassword(owner, shareId, "another-one"); + + var share = await GetShare(visitor, shareId, token); + await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsTrue(); + + var wrongOld = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = Password })); + await Assert.That(wrongOld.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Unlock(visitor, shareId, "another-one"); + } + + [Test] + public async Task RemovingThePassword_OpensTheShare() + { + var (owner, shareId) = await CreateShareWithShocker("pwremove", Password); + + var updated = await SetPassword(owner, shareId, null); + await Assert.That(updated.GetProperty("hasPassword").GetBoolean()).IsFalse(); + + using var visitor = WebApplicationFactory.CreateClient(); + var share = await GetShare(visitor, shareId, unlockToken: null); + await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsFalse(); + } + + [Test] + public async Task SettingAPassword_ThatIsTooShort_Returns400() + { + var (owner, shareId) = await CreateShareWithShocker("pwshort", password: null); + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + + var response = await ownerClient.PutAsync($"/1/shares/links/{shareId}/password", + TestHelper.JsonContent(new { password = "abc" })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + } + + [Test] + public async Task SettingThePassword_OfSomeoneElsesShare_Returns404() + { + var (_, shareId) = await CreateShareWithShocker("pwforeign", password: null); + var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("pwforeigno"), + TestHelper.UniqueEmail("pwforeigno"), "SecurePassword123#"); + using var otherClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken); + + var response = await otherClient.PutAsync($"/1/shares/links/{shareId}/password", + TestHelper.JsonContent(new { password = Password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + } + + [Test] + public async Task Profile_DefaultShare_SaysWhetherItIsPasswordProtected() + { + var (owner, shareId) = await CreateShareWithShocker("pwprofile", Password); + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var profile = await ownerClient.PutAsync("/1/account/profile", + TestHelper.JsonContent(new + { isPublic = true, socials = Array.Empty(), defaultPublicShareId = shareId })); + await Assert.That(profile.IsSuccessStatusCode).IsTrue(); + + using var visitor = WebApplicationFactory.CreateClient(); + var json = await GetJson(visitor, $"/1/public/users/{owner.Username}", unlockToken: null, unwrapData: false); + await Assert.That(json.GetProperty("defaultPublicShare").GetProperty("passwordProtected").GetBoolean()) + .IsTrue(); + } + + // --- The hub --- + + [Test] + public async Task Hub_WithoutToken_IsRejected() + { + var (_, shareId) = await CreateShareWithShocker("pwhubnone", Password); + + await AssertCannotConnectAsync(shareId, unlockToken: null); + await AssertCannotConnectAsync(shareId, unlockToken: "not-a-real-token-not-a-real-tok"); + } + + [Test] + public async Task Hub_WithToken_ConnectsAndCanCall() + { + var (_, shareId) = await CreateShareWithShocker("pwhubok", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + + await using var connection = await ConnectAsync(shareId, token); + await connection.InvokeAsync("Control", Array.Empty()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Hub_OwnerConnectsWithoutToken() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubowner", Password); + + await using var connection = await ConnectAsync(shareId, unlockToken: null, sessionToken: owner.SessionToken); + await connection.InvokeAsync("Control", Array.Empty()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Hub_ChangingThePassword_ClosesOpenConnections() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubchange", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + await using var connection = await ConnectAsync(shareId, token); + + await SetPassword(owner, shareId, "another-one"); + + await AssertConnectionClosesAsync(connection); + await AssertCannotConnectAsync(shareId, token); + } + + [Test] + public async Task Hub_SettingAPassword_ClosesGuestsWhoGotInWithout() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubset", password: null); + await using var connection = await ConnectAsync(shareId, unlockToken: null); + + await SetPassword(owner, shareId, Password); + + await AssertConnectionClosesAsync(connection); + } + + [Test] + public async Task Hub_RemovingThePassword_KeepsConnectionsOpen() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubremove", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + await using var connection = await ConnectAsync(shareId, token); + + await SetPassword(owner, shareId, null); + + await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + await connection.InvokeAsync("Control", Array.Empty()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Hub_DeletingTheShare_ClosesOpenConnections() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubdelete", password: null); + await using var connection = await ConnectAsync(shareId, unlockToken: null); + + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var response = await ownerClient.DeleteAsync($"/1/shares/links/{shareId}"); + await Assert.That(response.IsSuccessStatusCode).IsTrue(); + + await AssertConnectionClosesAsync(connection); + } + + [Test] + public async Task Hub_PasswordChangedWithoutAnnouncement_ClosesOnTheNextCheck() + { + var (_, shareId) = await CreateShareWithShocker("pwhubfallback", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + await using var connection = await ConnectAsync(shareId, token); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = Guid.CreateVersion7(); + await db.PublicShares.Where(x => x.Id == shareId) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.PasswordStamp, stamp)); + } + + await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + Exception? failure = null; + try + { + await connection.InvokeAsync("Control", Array.Empty()); + } + catch (Exception ex) + { + failure = ex; + } + + await Assert.That(failure).IsNotNull(); + await AssertConnectionClosesAsync(connection); + } + + [Test] + public async Task Hub_LoggedInVisitor_IsClosedOnLogout() + { + var (_, shareId) = await CreateShareWithShocker("pwhublogout", password: null); + var visitor = await TestHelper.CreateAndLoginUser(WebApplicationFactory, + TestHelper.UniqueUsername("pwhublogoutv"), TestHelper.UniqueEmail("pwhublogoutv"), "SecurePassword123#"); + await using var connection = await ConnectAsync(shareId, unlockToken: null, sessionToken: visitor.SessionToken); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService() + .DeleteSessionByTokenAsync(visitor.SessionToken); + } + + await AssertConnectionClosesAsync(connection); + } + + // --- Helpers --- + + private async Task<(AuthenticatedUser Owner, Guid ShareId)> CreateShareWithShocker(string prefix, + string? password, string? slug = null) + { + var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), + TestHelper.UniqueEmail(prefix), "SecurePassword123#"); + var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id, "pw hub"); + + var shockerId = Guid.CreateVersion7(); + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Shockers.Add(new Shocker + { + Id = shockerId, Name = "pw shocker", RfId = 1234, DeviceId = deviceId, + Model = ShockerModelType.CaiXianlin + }); + await db.SaveChangesAsync(); + } + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var created = await client.PostAsync("/1/shares/links", + TestHelper.JsonContent(new { name = "pw share", password, slug })); + await Assert.That(created.StatusCode).IsEqualTo(HttpStatusCode.OK); + using var json = JsonDocument.Parse(await created.Content.ReadAsStringAsync()); + var shareId = json.RootElement.GetProperty("data").GetGuid(); + + var added = await client.PostAsync($"/1/shares/links/{shareId}/{shockerId}", null); + await Assert.That(added.StatusCode).IsEqualTo(HttpStatusCode.OK); + + return (owner, shareId); + } + + private Task GetShare(HttpClient client, Guid shareId, string? unlockToken) + => GetJson(client, $"/1/public/shares/links/{shareId}", unlockToken); + + private static async Task GetJson(HttpClient client, string path, string? unlockToken, + bool unwrapData = true) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + if (unlockToken is not null) request.Headers.Add(AuthConstants.PublicShareUnlockHeaderName, unlockToken); + + var response = await client.SendAsync(request); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var root = unwrapData ? json.RootElement.GetProperty("data") : json.RootElement; + return root.Clone(); + } + + private static async Task Unlock(HttpClient client, Guid shareId, string password) + { + var response = await client.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.GetProperty("token").GetString()!; + } + + private async Task SetPassword(AuthenticatedUser owner, Guid shareId, string? password) + { + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var response = await client.PutAsync($"/1/shares/links/{shareId}/password", + TestHelper.JsonContent(new { password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.Clone(); + } + + private async Task ConnectAsync(Guid shareId, string? unlockToken, string? sessionToken = null) + { + var server = WebApplicationFactory.Server; + var path = $"/1/hubs/share/link/{shareId}?name=Guest"; + if (unlockToken is not null) path += $"&unlockToken={Uri.EscapeDataString(unlockToken)}"; + + 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 (sessionToken is not null) + client.ConfigureRequest = request => + request.Headers.Cookie = $"{AuthConstants.UserSessionCookieName}={sessionToken}"; + return await client.ConnectAsync(context.Uri, cancellationToken); + }; + }) + .Build(); + + await connection.StartAsync(); + return connection; + } + + /// The server aborts a rejected connection right after the handshake, or the handshake fails. + private async Task AssertCannotConnectAsync(Guid shareId, string? unlockToken) + { + HubConnection? connection = null; + try + { + connection = await ConnectAsync(shareId, unlockToken); + } + catch + { + return; + } + + await using (connection) + { + await AssertConnectionClosesAsync(connection); + } + } + + 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/Controller/Public/GetUserProfile.cs b/API/Controller/Public/GetUserProfile.cs index 6acd2803..0d88b17f 100644 --- a/API/Controller/Public/GetUserProfile.cs +++ b/API/Controller/Public/GetUserProfile.cs @@ -48,7 +48,8 @@ public async Task GetUserProfile([FromRoute] string username, Can { Id = x.DefaultPublicShare.Id, Name = x.DefaultPublicShare.Name, - Slug = x.DefaultPublicShare.Slug + Slug = x.DefaultPublicShare.Slug, + PasswordProtected = x.DefaultPublicShare.PasswordHash != null } : null }) diff --git a/API/Controller/Public/PublicShareController.cs b/API/Controller/Public/PublicShareController.cs index 6a6a05fa..0b08ee6e 100644 --- a/API/Controller/Public/PublicShareController.cs +++ b/API/Controller/Public/PublicShareController.cs @@ -4,10 +4,13 @@ using OpenShock.API.Models.Response; using OpenShock.API.Utils; using OpenShock.Common.Utils; +using System.Security.Claims; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Constants; using OpenShock.Common.Errors; using OpenShock.Common.Extensions; using OpenShock.Common.Models; +using OpenShock.Common.Services.PublicShareAccess; using OpenShock.Internal.Common.Problems; namespace OpenShock.API.Controller.Public; @@ -18,6 +21,7 @@ public sealed partial class PublicController /// Gets information about a public share. /// /// + /// The token from unlocking a password-protected share. /// /// The public share information was successfully retrieved. /// The public share does not exist. @@ -26,14 +30,16 @@ public sealed partial class PublicController [ApiVersion(1)] [ProducesResponseType>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound - public Task GetPublicShare([FromRoute] Guid publicShareId, CancellationToken cancellationToken) - => GetPublicShareResponse(_db.PublicShares.Where(x => x.Id == publicShareId), cancellationToken); + public Task GetPublicShare([FromRoute] Guid publicShareId, + [FromHeader(Name = AuthConstants.PublicShareUnlockHeaderName)] string? unlockToken, CancellationToken cancellationToken) + => GetPublicShareResponse(_db.PublicShares.Where(x => x.Id == publicShareId), unlockToken, cancellationToken); /// /// Gets information about a public share by its owner's username and custom slug. /// /// /// + /// The token from unlocking a password-protected share. /// /// The public share information was successfully retrieved. /// The public share does not exist. @@ -42,13 +48,14 @@ public Task GetPublicShare([FromRoute] Guid publicShareId, Cancel [ApiVersion(1)] [ProducesResponseType>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound - public Task GetPublicShareBySlug([FromRoute] string username, [FromRoute] string slug, CancellationToken cancellationToken) + public Task GetPublicShareBySlug([FromRoute] string username, [FromRoute] string slug, + [FromHeader(Name = AuthConstants.PublicShareUnlockHeaderName)] string? unlockToken, CancellationToken cancellationToken) { slug = slug.ToLowerInvariant(); - return GetPublicShareResponse(_db.PublicShares.Where(x => x.Owner.Name == username && x.Slug == slug), cancellationToken); + return GetPublicShareResponse(_db.PublicShares.Where(x => x.Owner.Name == username && x.Slug == slug), unlockToken, cancellationToken); } - private async Task GetPublicShareResponse(IQueryable query, CancellationToken cancellationToken) + private async Task GetPublicShareResponse(IQueryable query, string? unlockToken, CancellationToken cancellationToken) { var publicShare = await query .Where(x => x.Owner.UserDeactivation == null) @@ -73,6 +80,8 @@ private async Task GetPublicShareResponse(IQueryable new { DeviceId = y.Shocker.Device.Id, @@ -99,8 +108,9 @@ private async Task GetPublicShareResponse(IQueryable GetPublicShareResponse(IQueryable x.Id != shocker.DeviceId)) @@ -125,4 +139,14 @@ private async Task GetPublicShareResponse(IQueryableThe owner always gets in; anyone else needs a token from entering the current password. + private async Task IsUnlocked(Guid publicShareId, Guid ownerId, Guid? passwordStamp, string? unlockToken) + { + var userId = User.TryGetOpenShockUserIdentity()?.GetClaimValueAsGuid(ClaimTypes.NameIdentifier); + if (userId == ownerId) return true; + + return passwordStamp is { } stamp && await HttpContext.RequestServices.GetRequiredService() + .IsTokenValidAsync(publicShareId, stamp, unlockToken); + } } diff --git a/API/Controller/Public/UnlockPublicShare.cs b/API/Controller/Public/UnlockPublicShare.cs new file mode 100644 index 00000000..667d1b54 --- /dev/null +++ b/API/Controller/Public/UnlockPublicShare.cs @@ -0,0 +1,64 @@ +using System.Net.Mime; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; +using OpenShock.API.Models.Requests; +using OpenShock.API.Models.Response; +using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Errors; +using OpenShock.Common.Services.PublicShareAccess; +using OpenShock.Common.Utils; +using OpenShock.Internal.Common.Problems; + +namespace OpenShock.API.Controller.Public; + +public sealed partial class PublicController +{ + /// + /// Unlocks a password-protected public share. + /// + /// + /// + /// + /// + /// The password was correct. + /// The public share has no password. + /// The password was incorrect. + /// The public share does not exist. + /// Too many incorrect passwords were entered for this public share. + [Tags("Public Shocker Shares")] + [HttpPost("shares/links/{publicShareId}/unlock")] + [ApiVersion(1)] + [EnableRateLimiting("auth")] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // NotPasswordProtected + [ProducesResponseType(StatusCodes.Status401Unauthorized, MediaTypeNames.Application.ProblemJson)] // PasswordIncorrect + [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound + [ProducesResponseType(StatusCodes.Status429TooManyRequests, MediaTypeNames.Application.ProblemJson)] // TooManyPasswordAttempts + public async Task UnlockPublicShare([FromRoute] Guid publicShareId, [FromBody] PublicShareUnlock body, + [FromServices] IPublicShareAccessService publicShareAccess, CancellationToken cancellationToken) + { + var share = await _db.PublicShares + .Where(x => x.Id == publicShareId && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow) && x.Owner.UserDeactivation == null) + .Select(x => new { x.PasswordHash, x.PasswordStamp }) + .FirstOrDefaultAsync(cancellationToken); + if (share is null) return Problem(PublicShareError.PublicShareNotFound); + if (share.PasswordHash is null || share.PasswordStamp is not { } stamp) return Problem(PublicShareError.NotPasswordProtected); + + if (await publicShareAccess.IsLockedOutAsync(publicShareId)) return Problem(PublicShareError.TooManyPasswordAttempts); + + if (!HashingUtils.VerifyPassword(body.Password, share.PasswordHash).Verified) + { + await publicShareAccess.RecordFailedAttemptAsync(publicShareId); + return Problem(PublicShareError.PasswordIncorrect); + } + + var token = await publicShareAccess.IssueTokenAsync(publicShareId, stamp); + return Ok(new PublicShareUnlockResponse + { + Token = token, + ExpiresOn = DateTime.UtcNow + PublicShareAccessService.TokenLifetime + }); + } +} diff --git a/API/Controller/Shares/Links/CreatePublicShare.cs b/API/Controller/Shares/Links/CreatePublicShare.cs index 96f50324..d9c42a75 100644 --- a/API/Controller/Shares/Links/CreatePublicShare.cs +++ b/API/Controller/Shares/Links/CreatePublicShare.cs @@ -8,6 +8,7 @@ using OpenShock.Common.Errors; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; using OpenShock.Internal.Common.Problems; namespace OpenShock.API.Controller.Shares.Links; @@ -49,6 +50,8 @@ public async Task CreatePublicShare([FromBody] PublicShareCreate OwnerId = CurrentUser.Id, Name = body.Name, Slug = slug, + PasswordHash = body.Password is null ? null : HashingUtils.HashPassword(body.Password), + PasswordStamp = body.Password is null ? null : Guid.CreateVersion7(), ExpiresAt = body.ExpiresOn is null ? null : DateTime.SpecifyKind(body.ExpiresOn.Value, DateTimeKind.Utc) }; _db.PublicShares.Add(entity); diff --git a/API/Controller/Shares/Links/DeletePublicShare.cs b/API/Controller/Shares/Links/DeletePublicShare.cs index 4d1f4224..5927c9c9 100644 --- a/API/Controller/Shares/Links/DeletePublicShare.cs +++ b/API/Controller/Shares/Links/DeletePublicShare.cs @@ -8,6 +8,7 @@ using OpenShock.Common.Extensions; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.RedisPubSub; using OpenShock.Internal.Common.Problems; namespace OpenShock.API.Controller.Shares.Links; @@ -27,7 +28,7 @@ public sealed partial class ShareLinksController [TokenPermission(PermissionType.Publicshares_Edit)] [ProducesResponseType(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound - public async Task DeletePublicShare([FromRoute] Guid publicShareId, [FromServices] IDeviceUpdateService deviceUpdateService, CancellationToken cancellationToken) + public async Task DeletePublicShare([FromRoute] Guid publicShareId, [FromServices] IDeviceUpdateService deviceUpdateService, [FromServices] IRedisPubService redisPubService, CancellationToken cancellationToken) { var result = await _db.PublicShares .Where(x => x.Id == publicShareId && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow)) @@ -37,6 +38,7 @@ public async Task DeletePublicShare([FromRoute] Guid publicShareI if (result <= 0) return Problem(PublicShareError.PublicShareNotFound); await deviceUpdateService.UpdatePublicShare(publicShareId); + await redisPubService.SendPublicShareAccessRevoked(publicShareId); return LegacyEmptyOk("Deleted public share"); } } diff --git a/API/Controller/Shares/Links/SetPublicSharePassword.cs b/API/Controller/Shares/Links/SetPublicSharePassword.cs new file mode 100644 index 00000000..37f72b63 --- /dev/null +++ b/API/Controller/Shares/Links/SetPublicSharePassword.cs @@ -0,0 +1,54 @@ +using System.Net.Mime; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using OpenShock.API.Models.Requests; +using OpenShock.API.Models.Response; +using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.Errors; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.RedisPubSub; +using OpenShock.Common.Utils; +using OpenShock.Internal.Common.Problems; + +namespace OpenShock.API.Controller.Shares.Links; + +public sealed partial class ShareLinksController +{ + /// + /// Set, change or remove the password of a public share + /// + /// + /// Setting or changing the password disconnects everyone currently using the share; they have to enter the + /// new one. Removing it keeps them connected. + /// + /// The updated public share + /// Public share not found or does not belong to you + [HttpPut("{publicShareId}/password")] + [ApiVersion(1)] + [TokenPermission(PermissionType.Publicshares_Edit)] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound + public async Task SetPublicSharePassword([FromRoute] Guid publicShareId, [FromBody] PublicSharePasswordSet body, + [FromServices] IRedisPubService redisPubService, CancellationToken cancellationToken) + { + var share = await _db.PublicShares.FirstOrDefaultAsync(x => x.OwnerId == CurrentUser.Id && x.Id == publicShareId && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow), cancellationToken); + if (share is null) return Problem(PublicShareError.PublicShareNotFound); + + if (body.Password is null) + { + // The stamp stays, so connections that got in with the old password are not closed. + share.PasswordHash = null; + await _db.SaveChangesAsync(cancellationToken); + return Ok(OwnPublicShareResponse.GetFromEf(share)); + } + + share.PasswordHash = HashingUtils.HashPassword(body.Password); + share.PasswordStamp = Guid.CreateVersion7(); + await _db.SaveChangesAsync(cancellationToken); + + await redisPubService.SendPublicShareAccessRevoked(publicShareId); + return Ok(OwnPublicShareResponse.GetFromEf(share)); + } +} diff --git a/API/Models/Requests/PublicShareCreate.cs b/API/Models/Requests/PublicShareCreate.cs index 21a90738..66385081 100644 --- a/API/Models/Requests/PublicShareCreate.cs +++ b/API/Models/Requests/PublicShareCreate.cs @@ -16,4 +16,10 @@ public sealed class PublicShareCreate /// [StringLength(ApiHardLimits.PublicShareSlugMaxLength, MinimumLength = ApiHardLimits.PublicShareSlugMinLength)] public string? Slug { get; init; } = null; + + /// + /// Optional password visitors must enter before they can see or control the shockers. + /// + [StringLength(ApiHardLimits.PublicSharePasswordMaxLength, MinimumLength = ApiHardLimits.PublicSharePasswordMinLength)] + public string? Password { get; init; } = null; } diff --git a/API/Models/Requests/PublicSharePasswordSet.cs b/API/Models/Requests/PublicSharePasswordSet.cs new file mode 100644 index 00000000..4bc93dd5 --- /dev/null +++ b/API/Models/Requests/PublicSharePasswordSet.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; +using OpenShock.Common.Constants; + +namespace OpenShock.API.Models.Requests; + +public sealed class PublicSharePasswordSet +{ + /// + /// The new password, or null to remove it. Setting or changing it disconnects everyone currently using the share. + /// + [StringLength(ApiHardLimits.PublicSharePasswordMaxLength, MinimumLength = ApiHardLimits.PublicSharePasswordMinLength)] + public required string? Password { get; init; } +} diff --git a/API/Models/Requests/PublicShareUnlock.cs b/API/Models/Requests/PublicShareUnlock.cs new file mode 100644 index 00000000..808b1e42 --- /dev/null +++ b/API/Models/Requests/PublicShareUnlock.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; +using OpenShock.Common.Constants; + +namespace OpenShock.API.Models.Requests; + +public sealed class PublicShareUnlock +{ + [Required(AllowEmptyStrings = false)] + [MaxLength(ApiHardLimits.PublicSharePasswordMaxLength)] + public required string Password { get; init; } +} diff --git a/API/Models/Response/OwnPublicShareResponse.cs b/API/Models/Response/OwnPublicShareResponse.cs index 17589cc3..41b9bf95 100644 --- a/API/Models/Response/OwnPublicShareResponse.cs +++ b/API/Models/Response/OwnPublicShareResponse.cs @@ -9,6 +9,7 @@ public sealed class OwnPublicShareResponse public required string? Slug { get; init; } public required DateTime CreatedOn { get; init; } public DateTime? ExpiresOn { get; init; } + public required bool HasPassword { get; init; } public static OwnPublicShareResponse GetFromEf(PublicShare x) => new() { @@ -16,6 +17,7 @@ public sealed class OwnPublicShareResponse Name = x.Name, Slug = x.Slug, CreatedOn = x.CreatedAt, - ExpiresOn = x.ExpiresAt + ExpiresOn = x.ExpiresAt, + HasPassword = x.PasswordHash != null }; } diff --git a/API/Models/Response/PublicShareResponse.cs b/API/Models/Response/PublicShareResponse.cs index 45babb1e..21ee7b7c 100644 --- a/API/Models/Response/PublicShareResponse.cs +++ b/API/Models/Response/PublicShareResponse.cs @@ -10,6 +10,16 @@ public sealed class PublicShareResponse public DateTime? ExpiresOn { get; init; } public required PublicShareAuthor Author { get; init; } + /// + /// Visitors have to enter a password before they can see or control the shockers. + /// + public required bool PasswordProtected { get; init; } + + /// + /// The share is password protected and this request did not unlock it: is empty. + /// + public required bool PasswordRequired { get; init; } + public IList Devices { get; init; } = new List(); } diff --git a/API/Models/Response/PublicShareUnlockResponse.cs b/API/Models/Response/PublicShareUnlockResponse.cs new file mode 100644 index 00000000..0eb68448 --- /dev/null +++ b/API/Models/Response/PublicShareUnlockResponse.cs @@ -0,0 +1,12 @@ +namespace OpenShock.API.Models.Response; + +public sealed class PublicShareUnlockResponse +{ + /// + /// Send it in the OpenShockPublicShareUnlock header when loading the share, and as the unlockToken query + /// parameter when connecting to its hub. Invalid once the password is changed. + /// + public required string Token { get; init; } + + public required DateTime ExpiresOn { get; init; } +} diff --git a/API/Models/Response/PublicUserProfileResponse.cs b/API/Models/Response/PublicUserProfileResponse.cs index 1753fe42..9664d54b 100644 --- a/API/Models/Response/PublicUserProfileResponse.cs +++ b/API/Models/Response/PublicUserProfileResponse.cs @@ -14,6 +14,7 @@ public sealed class PublicUserProfilePublicShare public required Guid Id { get; init; } public required string Name { get; init; } public required string? Slug { get; init; } + public required bool PasswordProtected { get; init; } } public sealed class PublicUserProfileDetails diff --git a/API/Realtime/RedisSubscriberService.cs b/API/Realtime/RedisSubscriberService.cs index 4c2c0902..4beb249f 100644 --- a/API/Realtime/RedisSubscriberService.cs +++ b/API/Realtime/RedisSubscriberService.cs @@ -59,6 +59,7 @@ public async Task StartAsync(CancellationToken cancellationToken) await _subscriber.SubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); await _subscriber.SubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); await _subscriber.SubscribeAsync(RedisChannels.ApiTokenUpdateAll, HandleApiTokenUpdate); + await _subscriber.SubscribeAsync(RedisChannels.PublicShareAccessRevoked, HandlePublicShareAccessRevoked); } private void HandleSessionRevoked(RedisChannel _, RedisValue message) @@ -78,6 +79,14 @@ private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of user [{UserId}]", closed, userId); } + private void HandlePublicShareAccessRevoked(RedisChannel _, RedisValue message) + { + if (!Guid.TryParse((string?)message, out var publicShareId)) return; + + var closed = _hubConnections.AbortPublicShare(publicShareId); + if (closed > 0) _logger.LogDebug("Closed {Count} connection(s) to public share [{PublicShareId}]", closed, publicShareId); + } + private void HandleApiTokenUpdate(RedisChannel channel, RedisValue _) { var channelName = (string?)channel; diff --git a/Common/Constants/ApiHardLimits.cs b/Common/Constants/ApiHardLimits.cs index 1717fc7a..e15e72cc 100644 --- a/Common/Constants/ApiHardLimits.cs +++ b/Common/Constants/ApiHardLimits.cs @@ -41,6 +41,8 @@ public static class ApiHardLimits public const int PublicShareSlugMinLength = 2; public const int PublicShareSlugMaxLength = 32; + public const int PublicSharePasswordMinLength = 4; + public const int PublicSharePasswordMaxLength = 128; public const int UserProfilePronounsMaxLength = 32; public const int UserProfileBioMaxLength = 1000; diff --git a/Common/Constants/AuthConstants.cs b/Common/Constants/AuthConstants.cs index 3fdb5c6a..9f3dd031 100644 --- a/Common/Constants/AuthConstants.cs +++ b/Common/Constants/AuthConstants.cs @@ -7,6 +7,7 @@ public static class AuthConstants public const string UserSessionHeaderName = "OpenShockSession"; public const string ApiTokenHeaderName = "OpenShockToken"; public const string HubTokenHeaderName = "DeviceToken"; + public const string PublicShareUnlockHeaderName = "OpenShockPublicShareUnlock"; public const string AutomationTokenHeaderName = "X-OpenShock-Automation-Token"; public const int GeneratedTokenLength = 32; diff --git a/Common/Errors/PublicShareError.cs b/Common/Errors/PublicShareError.cs index 11c1c879..2cbf07a1 100644 --- a/Common/Errors/PublicShareError.cs +++ b/Common/Errors/PublicShareError.cs @@ -18,5 +18,10 @@ public static class PublicShareError public static OpenShockProblem PublicShareExpiryDateInPast => new("ShareLink.ExpiryDateInPast", "Expiry date cannot be in the past", HttpStatusCode.BadRequest); public static OpenShockProblem SlugInvalid => new("ShareLink.SlugInvalid", "Invalid public share slug", HttpStatusCode.BadRequest, $"Slugs must be {ApiHardLimits.PublicShareSlugMinLength}-{ApiHardLimits.PublicShareSlugMaxLength} characters of lowercase letters, digits and single hyphens, and cannot start or end with a hyphen"); public static OpenShockProblem SlugTaken => new("ShareLink.SlugTaken", "You already have a public share with this slug", HttpStatusCode.Conflict); + // Password errors + public static OpenShockProblem NotPasswordProtected => new("ShareLink.NotPasswordProtected", "This public share has no password", HttpStatusCode.BadRequest); + public static OpenShockProblem PasswordIncorrect => new("ShareLink.PasswordIncorrect", "Incorrect password", HttpStatusCode.Unauthorized); + public static OpenShockProblem TooManyPasswordAttempts => new("ShareLink.TooManyPasswordAttempts", "Too many incorrect passwords", HttpStatusCode.TooManyRequests, "Too many incorrect passwords were entered for this public share. Try again later."); + public static OpenShockProblem TooManyPublicShares => new("ShareLink.TooManyShareLinks", "You have too many public shares", HttpStatusCode.Conflict, $"You have reached the maximum number of public shares ({ApiHardLimits.MaxPublicSharesPerUser})"); } diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs index d4d2a763..7d9f29f6 100644 --- a/Common/Hubs/HubConnectionTracker.cs +++ b/Common/Hubs/HubConnectionTracker.cs @@ -50,8 +50,24 @@ public sealed class HubConnectionTracker return null; } + /// + /// Starts tracking a public share connection, or marks an already tracked (logged in) one as such, so it is + /// closed when the share's access changes. + /// + /// The share's password stamp the visitor got in with, null when it had no password. + public TrackedHubConnection TrackPublicShare(HubCallerContext context, Guid publicShareId, Guid? passwordStamp) + { + var tracked = _connections.GetOrAdd(context.ConnectionId, _ => new TrackedHubConnection(context, userId: null, sessionId: null, apiTokenId: null)); + tracked.AttachPublicShare(publicShareId, passwordStamp); + return tracked; + } + public void Untrack(string connectionId) => _connections.TryRemove(connectionId, out _); + /// Closes the connections to this public share. + /// How many connections were closed. + public int AbortPublicShare(Guid publicShareId) => Abort(c => c.PublicShareId == publicShareId); + /// Closes the connections that authenticated with this session. /// The id the session is stored under, see . /// How many connections were closed. @@ -127,6 +143,18 @@ public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sess public string? SessionId { get; } public Guid? ApiTokenId { get; } + /// The public share this connection controls, null for other hubs. + public Guid? PublicShareId { get; private set; } + + /// The share's password stamp when this connection was let in, null when it had no password. + public Guid? PasswordStamp { get; private set; } + + public void AttachPublicShare(Guid publicShareId, Guid? passwordStamp) + { + PublicShareId = publicShareId; + PasswordStamp = passwordStamp; + } + public bool WasValidatedWithin(TimeSpan interval) { var last = Volatile.Read(ref _lastValidated); diff --git a/Common/Hubs/PublicShareHub.cs b/Common/Hubs/PublicShareHub.cs index 0da2b361..02266a3f 100644 --- a/Common/Hubs/PublicShareHub.cs +++ b/Common/Hubs/PublicShareHub.cs @@ -5,6 +5,7 @@ using OpenShock.Common.Models.WebSocket.User; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services; +using OpenShock.Common.Services.PublicShareAccess; using OpenShock.Common.Services.Session; using OpenShock.Common.Utils; using OpenShock.Internal.Common.Constants; @@ -17,6 +18,8 @@ public sealed class PublicShareHub : Hub private readonly IHubContext _userHub; private readonly ISessionService _sessionService; private readonly IControlSender _controlSender; + private readonly HubConnectionTracker _connectionTracker; + private readonly IPublicShareAccessService _publicShareAccess; private readonly ILogger _logger; /// /// Permissions of the API token this connection authenticated with, or null for a session @@ -26,8 +29,14 @@ public sealed class PublicShareHub : Hub ? Context.User.GetApiTokenPermissions() : null; - public PublicShareHub(OpenShockContext db, IHubContext userHub, ISessionService sessionService, IControlSender controlSender, ILogger logger) + /// Query parameter carrying the unlock token of a password-protected share. + public const string UnlockTokenQueryName = "unlockToken"; + + public PublicShareHub(OpenShockContext db, IHubContext userHub, ISessionService sessionService, IControlSender controlSender, + HubConnectionTracker connectionTracker, IPublicShareAccessService publicShareAccess, ILogger logger) { + _connectionTracker = connectionTracker; + _publicShareAccess = publicShareAccess; _db = db; _userHub = userHub; _sessionService = sessionService; @@ -58,13 +67,27 @@ public override async Task OnConnectedAsync() } } - var exists = await _db.PublicShares.AnyAsync(x => x.Id == id && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow) && x.Owner.UserDeactivation == null); - if (!exists) + var share = await _db.PublicShares + .Where(x => x.Id == id && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow) && x.Owner.UserDeactivation == null) + .Select(x => new { x.OwnerId, HasPassword = x.PasswordHash != null, x.PasswordStamp }) + .FirstOrDefaultAsync(); + if (share is null) { _logger.LogDebug("Aborting connection... public share not found"); Context.Abort(); return; } + + if (share.HasPassword && user?.Id != share.OwnerId) + { + var unlockToken = httpContext.Request.Query[UnlockTokenQueryName].FirstOrDefault(); + if (share.PasswordStamp is not { } stamp || !await _publicShareAccess.IsTokenValidAsync(id, stamp, unlockToken)) + { + _logger.LogDebug("Aborting connection... public share is password protected and was not unlocked"); + Context.Abort(); + return; + } + } // TODO: Add token auth @@ -114,6 +137,9 @@ public override async Task OnConnectedAsync() AdditionalItems = additionalItems } }; + // Closed when the share's password is set or changed, or the share is deleted. + _connectionTracker.TrackPublicShare(Context, id, share.PasswordStamp).MarkValidated(); + await Groups.AddToGroupAsync(Context.ConnectionId, GroupName(id)); await Clients.Caller.Welcome(user is null ? AuthType.Guest : AuthType.Authenticated); } diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index f8d6da28..d630b58b 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -82,7 +82,8 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) { - if (!await IsStillAuthenticated(context, invocationContext.ServiceProvider)) + if (!await IsStillAuthenticated(context, invocationContext.ServiceProvider) + || (tracked?.PublicShareId is { } publicShareId && !await IsPublicShareStillAccessible(publicShareId, tracked.PasswordStamp, context, invocationContext.ServiceProvider))) { context.Abort(); throw new HubException("Authentication is no longer valid"); @@ -94,6 +95,21 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception return await next(invocationContext); } + /// + /// A public share connection may go on while the share exists, has not expired, its owner is active and its + /// password was not set or changed since the visitor got in. Covers what the Redis message can miss. + /// + private static Task IsPublicShareStillAccessible(Guid publicShareId, Guid? passwordStamp, HubCallerContext context, IServiceProvider services) + { + var db = services.GetRequiredService(); + var now = DateTime.UtcNow; + return db.PublicShares.AnyAsync(x => + x.Id == publicShareId && + (x.ExpiresAt == null || x.ExpiresAt > now) && + x.Owner.UserDeactivation == null && + x.PasswordStamp == passwordStamp, context.ConnectionAborted); + } + private static async Task IsStillAuthenticated(HubCallerContext context, IServiceProvider services) { var user = context.User; diff --git a/Common/Migrations/20261203012615_PublicSharePasswords.Designer.cs b/Common/Migrations/20261203012615_PublicSharePasswords.Designer.cs new file mode 100644 index 00000000..4842081a --- /dev/null +++ b/Common/Migrations/20261203012615_PublicSharePasswords.Designer.cs @@ -0,0 +1,2000 @@ +// +using System; +using System.Collections.Generic; +using System.Net; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OpenShock.Common.OpenShockDb; + +#nullable disable + +namespace OpenShock.Common.Migrations; + +[DbContext(typeof(MigrationOpenShockContext))] +[Migration("20261203012615_PublicSharePasswords")] +partial class _20261203012615_PublicSharePasswords +{ + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Npgsql:CollationDefinition:public.ndcoll", "und-u-ks-level2,und-u-ks-level2,icu,False") + .HasAnnotation("ProductVersion", "11.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "audit_action", new[] { "login", "logout", "password_changed", "email_change_requested", "email_changed", "username_changed", "api_token_created", "api_token_deleted", "oauth_connected", "oauth_disconnected", "account_deactivated", "account_reactivated", "account_deleted", "automation_token_created", "automation_token_updated", "automation_token_rotated", "automation_token_deleted", "automation_token_used" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "automation_token_type", new[] { "turnstile", "rate_limit", "control_stats_read" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "configuration_value_type", new[] { "string", "bool", "int", "float", "json" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "control_limit_mode", new[] { "clamp", "lerp" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "control_type", new[] { "stop", "shock", "vibrate", "sound" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "email_status", new[] { "pending", "sending", "sent", "failed", "skipped" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "email_type", new[] { "account_activation", "password_reset", "email_verification", "email_change_notice" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "match_type_enum", new[] { "exact", "contains" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "ota_update_status", new[] { "started", "running", "finished", "error", "timeout" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "password_encryption_type", new[] { "bcrypt_enhanced", "pbkdf2" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "permission_type", new[] { "shockers.use", "shockers.edit", "shockers.pause", "devices.edit", "devices.auth", "usershares.edit", "usershares.pause", "publicshares.pause", "publicshares.edit" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "role_type", new[] { "support", "staff", "admin", "system" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "shocker_model_type", new[] { "cai_xianlin", "petrainer", "petrainer_998dr", "wellturn_t330" }); + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "timescaledb"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("FriendlyName") + .HasColumnType("text"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AdminUsersView", b => + { + b.Property("ActivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("activated_at"); + + b.Property("ApiTokenCount") + .HasColumnType("integer") + .HasColumnName("api_token_count"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("CreatedByAutomationTokenId") + .HasColumnType("uuid") + .HasColumnName("created_by_automation_token_id"); + + b.Property("DeactivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deactivated_at"); + + b.Property("DeactivatedByUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_by_user_id"); + + b.Property("DeviceCount") + .HasColumnType("integer") + .HasColumnName("device_count"); + + b.Property("Email") + .IsRequired() + .HasColumnType("character varying") + .HasColumnName("email"); + + b.Property("EmailChangeRequestCount") + .HasColumnType("integer") + .HasColumnName("email_change_request_count"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .HasColumnType("character varying") + .HasColumnName("name"); + + b.Property("NameChangeRequestCount") + .HasColumnType("integer") + .HasColumnName("name_change_request_count"); + + b.Property("PasswordHashType") + .HasColumnType("character varying") + .HasColumnName("password_hash_type"); + + b.Property("PasswordResetCount") + .HasColumnType("integer") + .HasColumnName("password_reset_count"); + + b.Property("Roles") + .IsRequired() + .HasColumnType("role_type[]") + .HasColumnName("roles"); + + b.Property("ShockerControlLogCount") + .HasColumnType("integer") + .HasColumnName("shocker_control_log_count"); + + b.Property("ShockerCount") + .HasColumnType("integer") + .HasColumnName("shocker_count"); + + b.Property("ShockerPublicShareCount") + .HasColumnType("integer") + .HasColumnName("shocker_public_share_count"); + + b.Property("ShockerUserShareCount") + .HasColumnType("integer") + .HasColumnName("shocker_user_share_count"); + + b.ToTable((string)null); + + b.ToView("admin_users_view", (string)null); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("CreatedByIp") + .IsRequired() + .HasColumnType("inet") + .HasColumnName("created_by_ip"); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_used"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property>("Permissions") + .IsRequired() + .HasColumnType("permission_type[]") + .HasColumnName("permissions"); + + b.Property("ShockerControlDurationMax") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(65535) + .HasColumnName("shocker_control_duration_max"); + + b.Property("ShockerControlDurationMin") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(300) + .HasColumnName("shocker_control_duration_min"); + + b.Property("ShockerControlDurationMode") + .ValueGeneratedOnAdd() + .HasColumnType("control_limit_mode") + .HasDefaultValue(ControlLimitMode.Clamp) + .HasColumnName("shocker_control_duration_mode"); + + b.Property("ShockerControlIntensityMax") + .ValueGeneratedOnAdd() + .HasColumnType("smallint") + .HasDefaultValue((byte)100) + .HasColumnName("shocker_control_intensity_max"); + + b.Property("ShockerControlIntensityMin") + .ValueGeneratedOnAdd() + .HasColumnType("smallint") + .HasDefaultValue((byte)0) + .HasColumnName("shocker_control_intensity_min"); + + b.Property("ShockerControlIntensityMode") + .ValueGeneratedOnAdd() + .HasColumnType("control_limit_mode") + .HasDefaultValue(ControlLimitMode.Clamp) + .HasColumnName("shocker_control_intensity_mode"); + + b.Property("ShockerControlPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("shocker_control_paused"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ValidUntil") + .HasColumnType("timestamp with time zone") + .HasColumnName("valid_until"); + + b.HasKey("Id") + .HasName("api_tokens_pkey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.HasIndex("ValidUntil"); + + b.ToTable("api_tokens", t => + { + t.HasCheckConstraint("ck_api_tokens_shocker_control_duration", "shocker_control_duration_min >= 300 AND shocker_control_duration_max <= 65535 AND shocker_control_duration_min <= shocker_control_duration_max"); + + t.HasCheckConstraint("ck_api_tokens_shocker_control_intensity", "shocker_control_intensity_min >= 0 AND shocker_control_intensity_max <= 100 AND shocker_control_intensity_min <= shocker_control_intensity_max"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiTokenReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AffectedCount") + .HasColumnType("integer") + .HasColumnName("affected_count"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IpAddress") + .IsRequired() + .HasColumnType("inet") + .HasColumnName("ip_address"); + + b.Property("IpCountry") + .HasMaxLength(4) + .HasColumnType("character varying(4)") + .HasColumnName("ip_country"); + + b.Property("SubmittedCount") + .HasColumnType("integer") + .HasColumnName("submitted_count"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("api_token_reports_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("api_token_reports"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AutomationToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AutoCleanupAfter") + .HasColumnType("interval") + .HasColumnName("auto_cleanup_after"); + + b.Property("AutoCleanupUsers") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("auto_cleanup_users"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("LastRotatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_rotated_at"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_used_at"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property>("Types") + .IsRequired() + .HasColumnType("automation_token_type[]") + .HasColumnName("types"); + + b.Property("UseCount") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("use_count"); + + b.HasKey("Id") + .HasName("automation_tokens_pkey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("automation_tokens"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ConfigurationItem", b => + { + b.Property("Name") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name") + .UseCollation("C"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("description"); + + b.Property("Type") + .HasColumnType("configuration_value_type") + .HasColumnName("type"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4096) + .HasColumnType("character varying(4096)") + .HasColumnName("value"); + + b.HasKey("Name") + .HasName("configuration_pkey"); + + b.ToTable("configuration"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ControlStat", b => + { + b.Property("Bucket") + .HasColumnType("timestamp with time zone") + .HasColumnName("bucket"); + + b.Property("ControllerUserId") + .HasColumnType("uuid") + .HasColumnName("controller_user_id"); + + b.Property("Count") + .HasColumnType("bigint") + .HasColumnName("count"); + + b.Property("DurationMs") + .HasColumnType("bigint") + .HasColumnName("duration_ms"); + + b.Property("IntensityMs") + .HasColumnType("bigint") + .HasColumnName("intensity_ms"); + + b.Property("Live") + .HasColumnType("boolean") + .HasColumnName("live"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("OwnerUserId") + .HasColumnType("uuid") + .HasColumnName("owner_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("Type") + .HasColumnType("control_type") + .HasColumnName("type"); + + b.ToTable((string)null); + + b.ToView("control_stats", (string)null); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)") + .HasColumnName("token") + .UseCollation("C"); + + b.HasKey("Id") + .HasName("devices_pkey"); + + b.HasIndex("OwnerId"); + + b.HasIndex("Token") + .IsUnique(); + + b.ToTable("devices"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DeviceOtaUpdate", b => + { + b.Property("DeviceId") + .HasColumnType("uuid") + .HasColumnName("device_id"); + + b.Property("UpdateId") + .HasColumnType("integer") + .HasColumnName("update_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Message") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("message"); + + b.Property("Status") + .HasColumnType("ota_update_status") + .HasColumnName("status"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("version"); + + b.HasKey("DeviceId", "UpdateId") + .HasName("device_ota_updates_pkey"); + + b.HasIndex(new[] { "CreatedAt" }, "device_ota_updates_created_at_idx"); + + b.ToTable("device_ota_updates"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DiscordWebhook", b => + { + b.Property("Name") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("WebhookId") + .HasColumnType("bigint") + .HasColumnName("webhook_id"); + + b.Property("WebhookToken") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("webhook_token"); + + b.HasKey("Name") + .HasName("discord_webhooks_pkey"); + + b.ToTable("discord_webhooks"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.EmailOutboxMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AttemptCount") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0) + .HasColumnName("attempt_count"); + + b.Property("CoalesceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("coalesce_key"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("FailedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("failed_at"); + + b.Property("LastError") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)") + .HasColumnName("last_error"); + + b.Property("NextAttemptAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property>("Payload") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("payload"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("recipient"); + + b.Property("RecipientName") + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("recipient_name"); + + b.Property("SentAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("sent_at"); + + b.Property("Status") + .HasColumnType("email_status") + .HasColumnName("status"); + + b.Property("Type") + .HasColumnType("email_type") + .HasColumnName("type"); + + b.HasKey("Id") + .HasName("email_outbox_pkey"); + + b.HasIndex("CoalesceKey") + .HasFilter("coalesce_key IS NOT NULL"); + + b.HasIndex("NextAttemptAt") + .HasFilter("status IN ('pending', 'sending')"); + + b.HasIndex("Recipient"); + + b.ToTable("email_outbox"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.EmailProviderBlacklist", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Domain") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("domain") + .UseCollation("ndcoll"); + + b.HasKey("Id") + .HasName("email_provider_blacklist_pkey"); + + var index = b.HasIndex("Domain") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + b.ToTable("email_provider_blacklist"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property("PasswordStamp") + .HasColumnType("uuid") + .HasColumnName("password_stamp"); + + b.Property("Slug") + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("slug") + .UseCollation("C"); + + b.HasKey("Id") + .HasName("public_shares_pkey"); + + b.HasIndex("OwnerId"); + + b.HasIndex("OwnerId", "Slug") + .IsUnique() + .HasFilter("slug IS NOT NULL"); + + b.ToTable("public_shares", t => + { + t.HasCheckConstraint("ck_public_shares_slug", "slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShareShocker", b => + { + b.Property("PublicShareId") + .HasColumnType("uuid") + .HasColumnName("public_share_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("Cooldown") + .HasColumnType("integer") + .HasColumnName("cooldown"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("PublicShareId", "ShockerId") + .HasName("public_share_shockers_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("public_share_shockers", t => + { + t.HasCheckConstraint("ck_public_share_shockers_cooldown", "cooldown >= 0"); + + t.HasCheckConstraint("ck_public_share_shockers_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_public_share_shockers_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DeviceId") + .HasColumnType("uuid") + .HasColumnName("device_id"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("Model") + .HasColumnType("shocker_model_type") + .HasColumnName("model"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("RfId") + .HasColumnType("integer") + .HasColumnName("rf_id"); + + b.HasKey("Id") + .HasName("shockers_pkey"); + + b.HasIndex("DeviceId"); + + b.ToTable("shockers", t => + { + t.HasCheckConstraint("ck_shockers_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_shockers_max_intensity", "max_intensity BETWEEN 0 AND 100"); + + t.HasCheckConstraint("ck_shockers_rf_id", "rf_id BETWEEN 0 AND 65535"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerControlLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("ControlledByUserId") + .HasColumnType("uuid") + .HasColumnName("controlled_by_user_id"); + + b.Property("CustomName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("custom_name"); + + b.Property("Duration") + .HasColumnType("bigint") + .HasColumnName("duration"); + + b.Property("InsertedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("inserted_at") + .HasDefaultValueSql("now()"); + + b.Property("Intensity") + .HasColumnType("smallint") + .HasColumnName("intensity"); + + b.Property("LiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("live_control"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("OwnerUserId") + .HasColumnType("uuid") + .HasColumnName("owner_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("Type") + .HasColumnType("control_type") + .HasColumnName("type"); + + b.HasKey("Id", "CreatedAt") + .HasName("shocker_control_logs_pkey"); + + b.HasIndex("ControlledByUserId"); + + b.HasIndex("OwnerUserId", "CreatedAt"); + + b.HasIndex("ShockerId", "CreatedAt"); + + b.ToTable("shocker_control_logs"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerShareCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.HasKey("Id") + .HasName("shocker_share_codes_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("shocker_share_codes", t => + { + t.HasCheckConstraint("ck_shocker_share_codes_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_shocker_share_codes_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ActivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("activated_at"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("CreatedByAutomationTokenId") + .HasColumnType("uuid") + .HasColumnName("created_by_automation_token_id"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email") + .UseCollation("ndcoll"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("name") + .UseCollation("ndcoll"); + + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property>("Roles") + .IsRequired() + .HasColumnType("role_type[]") + .HasColumnName("roles"); + + b.Property("SecurityStamp") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("security_stamp") + .HasDefaultValueSql("gen_random_uuid()"); + + b.HasKey("Id") + .HasName("users_pkey"); + + b.HasIndex("CreatedByAutomationTokenId"); + + var index = b.HasIndex("Email") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + var index0 = b.HasIndex("Name") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index0, new[] { "ndcoll" }); + + b.ToTable("users"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserActivationRequest", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("EmailSendAttempts") + .HasColumnType("integer") + .HasColumnName("email_send_attempts"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.HasKey("UserId") + .HasName("user_activation_requests_pkey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("user_activation_requests"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserAuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Action") + .HasColumnType("audit_action") + .HasColumnName("action"); + + b.Property("ActorId") + .HasColumnType("uuid") + .HasColumnName("actor_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IpAddress") + .HasColumnType("inet") + .HasColumnName("ip_address"); + + b.Property("Metadata") + .HasColumnType("jsonb") + .HasColumnName("metadata"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)") + .HasColumnName("reason"); + + b.Property("UserAgent") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)") + .HasColumnName("user_agent"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_audit_logs_pkey"); + + b.HasIndex("ActorId"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.ToTable("user_audit_logs"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserDeactivation", b => + { + b.Property("DeactivatedUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_user_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DeactivatedByUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_by_user_id"); + + b.Property("DeleteLater") + .HasColumnType("boolean") + .HasColumnName("delete_later"); + + b.Property("UserModerationId") + .HasColumnType("uuid") + .HasColumnName("user_moderation_id"); + + b.HasKey("DeactivatedUserId") + .HasName("user_deactivations_pkey"); + + b.HasIndex("DeactivatedByUserId"); + + b.ToTable("user_deactivations"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserEmailChange", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("NewEmail") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email_new"); + + b.Property("OldEmail") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email_old"); + + b.Property("SecurityStampAtCreate") + .HasColumnType("uuid") + .HasColumnName("security_stamp_at_create"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("used_at"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_email_changes_pkey"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UsedAt"); + + b.HasIndex("UserId"); + + b.ToTable("user_email_changes"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameBlacklist", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("MatchType") + .HasColumnType("match_type_enum") + .HasColumnName("match_type"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("value") + .UseCollation("ndcoll"); + + b.HasKey("Id") + .HasName("user_name_blacklist_pkey"); + + var index = b.HasIndex("Value") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + b.ToTable("user_name_blacklist"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameChange", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(id); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("OldName") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("old_name"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_name_changes_pkey"); + + b.HasIndex("UserId", "CreatedAt"); + + b.ToTable("user_name_changes"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserOAuthConnection", b => + { + b.Property("ProviderKey") + .HasMaxLength(16) + .HasColumnType("character varying(16)") + .HasColumnName("provider_key") + .UseCollation("C"); + + b.Property("ExternalId") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("external_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DisplayName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("display_name"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ProviderKey", "ExternalId") + .HasName("user_oauth_connections_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("user_oauth_connections"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserPasswordReset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("SecurityStampAtCreate") + .HasColumnType("uuid") + .HasColumnName("security_stamp_at_create"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("used_at"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_password_resets_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("user_password_resets"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserProfile", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("Bio") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)") + .HasColumnName("bio"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DefaultPublicShareId") + .HasColumnType("uuid") + .HasColumnName("default_public_share_id"); + + b.Property("IsPublic") + .HasColumnType("boolean") + .HasColumnName("is_public"); + + b.Property("Pronouns") + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("pronouns"); + + b.Property("Socials") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("socials"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.HasKey("UserId") + .HasName("user_profiles_pkey"); + + b.HasIndex("DefaultPublicShareId"); + + b.ToTable("user_profiles"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShare", b => + { + b.Property("SharedWithUserId") + .HasColumnType("uuid") + .HasColumnName("shared_with_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("SharedWithUserId", "ShockerId") + .HasName("user_shares_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("user_shares", t => + { + t.HasCheckConstraint("ck_user_shares_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_user_shares_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("RecipientUserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_share_invites_pkey"); + + b.HasIndex("OwnerId"); + + b.HasIndex("RecipientUserId"); + + b.ToTable("user_share_invites"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInviteShocker", b => + { + b.Property("InviteId") + .HasColumnType("uuid") + .HasColumnName("invite_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("InviteId", "ShockerId") + .HasName("user_share_invite_shockers_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("user_share_invite_shockers", t => + { + t.HasCheckConstraint("ck_user_share_invite_shockers_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_user_share_invite_shockers_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiToken", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("ApiTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_api_tokens_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiTokenReport", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "ReportedByUser") + .WithMany("ReportedApiTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_api_token_reports_reported_by_user_id"); + + b.Navigation("ReportedByUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("Devices") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_devices_owner_id"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DeviceOtaUpdate", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Device", "Device") + .WithMany("OtaUpdates") + .HasForeignKey("DeviceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_device_ota_updates_device_id"); + + b.Navigation("Device"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("OwnedPublicShares") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_shares_owner_id"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShareShocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.PublicShare", "PublicShare") + .WithMany("ShockerMappings") + .HasForeignKey("PublicShareId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_share_shockers_public_share_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("PublicShareMappings") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_share_shockers_shocker_id"); + + b.Navigation("PublicShare"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Device", "Device") + .WithMany("Shockers") + .HasForeignKey("DeviceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shockers_device_id"); + + b.Navigation("Device"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerControlLog", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shocker_control_logs_owner_user_id"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerShareCode", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("ShockerShareCodes") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shocker_share_codes_shocker_id"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.AutomationToken", "CreatedByAutomationToken") + .WithMany("CreatedUsers") + .HasForeignKey("CreatedByAutomationTokenId") + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_users_created_by_automation_token_id"); + + b.Navigation("CreatedByAutomationToken"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserActivationRequest", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithOne("UserActivationRequest") + .HasForeignKey("OpenShock.Common.OpenShockDb.UserActivationRequest", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_activation_requests_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserAuditLog", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Actor") + .WithMany("ActorAuditLogs") + .HasForeignKey("ActorId") + .OnDelete(DeleteBehavior.SetNull) + .HasConstraintName("fk_user_audit_logs_actor_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("AuditLogs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_audit_logs_user_id"); + + b.Navigation("Actor"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserDeactivation", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "DeactivatedByUser") + .WithMany() + .HasForeignKey("DeactivatedByUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_deactivations_deactivated_by_user_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "DeactivatedUser") + .WithOne("UserDeactivation") + .HasForeignKey("OpenShock.Common.OpenShockDb.UserDeactivation", "DeactivatedUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_deactivations_deactivated_user_id"); + + b.Navigation("DeactivatedByUser"); + + b.Navigation("DeactivatedUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserEmailChange", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("EmailChanges") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_email_changes_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameChange", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("NameChanges") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_name_changes_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserOAuthConnection", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("OAuthConnections") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_oauth_connections_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserPasswordReset", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("PasswordResets") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_password_resets_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserProfile", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.PublicShare", "DefaultPublicShare") + .WithMany() + .HasForeignKey("DefaultPublicShareId") + .OnDelete(DeleteBehavior.SetNull) + .HasConstraintName("fk_user_profiles_default_public_share_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithOne("Profile") + .HasForeignKey("OpenShock.Common.OpenShockDb.UserProfile", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_profiles_user_id"); + + b.Navigation("DefaultPublicShare"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShare", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "SharedWithUser") + .WithMany("IncomingUserShares") + .HasForeignKey("SharedWithUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_shares_shared_with_user_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("UserShares") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_shares_shocker_id"); + + b.Navigation("SharedWithUser"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("OutgoingUserShareInvites") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invites_owner_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "RecipientUser") + .WithMany("IncomingUserShareInvites") + .HasForeignKey("RecipientUserId") + .OnDelete(DeleteBehavior.Cascade) + .HasConstraintName("fk_user_share_invites_recipient_user_id"); + + b.Navigation("Owner"); + + b.Navigation("RecipientUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInviteShocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.UserShareInvite", "Invite") + .WithMany("ShockerMappings") + .HasForeignKey("InviteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invite_shockers_invite_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("UserShareInviteShockerMappings") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invite_shockers_shocker_id"); + + b.Navigation("Invite"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AutomationToken", b => + { + b.Navigation("CreatedUsers"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.Navigation("OtaUpdates"); + + b.Navigation("Shockers"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.Navigation("ShockerMappings"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.Navigation("PublicShareMappings"); + + b.Navigation("ShockerShareCodes"); + + b.Navigation("UserShareInviteShockerMappings"); + + b.Navigation("UserShares"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.Navigation("ActorAuditLogs"); + + b.Navigation("ApiTokens"); + + b.Navigation("AuditLogs"); + + b.Navigation("Devices"); + + b.Navigation("EmailChanges"); + + b.Navigation("IncomingUserShareInvites"); + + b.Navigation("IncomingUserShares"); + + b.Navigation("NameChanges"); + + b.Navigation("OAuthConnections"); + + b.Navigation("OutgoingUserShareInvites"); + + b.Navigation("OwnedPublicShares"); + + b.Navigation("PasswordResets"); + + b.Navigation("Profile"); + + b.Navigation("ReportedApiTokens"); + + b.Navigation("UserActivationRequest"); + + b.Navigation("UserDeactivation"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.Navigation("ShockerMappings"); + }); +#pragma warning restore 612, 618 + } +} diff --git a/Common/Migrations/20261203012615_PublicSharePasswords.cs b/Common/Migrations/20261203012615_PublicSharePasswords.cs new file mode 100644 index 00000000..3279c035 --- /dev/null +++ b/Common/Migrations/20261203012615_PublicSharePasswords.cs @@ -0,0 +1,40 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace OpenShock.Common.Migrations; + +/// +public partial class _20261203012615_PublicSharePasswords : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "password_hash", + table: "public_shares", + type: "character varying(100)", + maxLength: 100, + nullable: true, + collation: "C"); + + migrationBuilder.AddColumn( + name: "password_stamp", + table: "public_shares", + type: "uuid", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "password_hash", + table: "public_shares"); + + migrationBuilder.DropColumn( + name: "password_stamp", + table: "public_shares"); + } +} diff --git a/Common/Migrations/OpenShockContextModelSnapshot.cs b/Common/Migrations/OpenShockContextModelSnapshot.cs index 6c528ded..1e92348b 100644 --- a/Common/Migrations/OpenShockContextModelSnapshot.cs +++ b/Common/Migrations/OpenShockContextModelSnapshot.cs @@ -18,7 +18,7 @@ partial class OpenShockContextModelSnapshot : ModelSnapshot // If you encounter a merge conflict in the line below, it means you need to // discard one of the migration branches and recreate its migrations on top of // the other branch. See https://aka.ms/efcore-docs-migrations-conflicts for more info. - public override string LastMigrationId => "20261201014156_ShareLinkSlugsAndUserProfiles"; + public override string LastMigrationId => "20261203012615_PublicSharePasswords"; protected override void BuildModel(ModelBuilder modelBuilder) { @@ -704,6 +704,16 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("uuid") .HasColumnName("owner_id"); + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property("PasswordStamp") + .HasColumnType("uuid") + .HasColumnName("password_stamp"); + b.Property("Slug") .HasMaxLength(32) .HasColumnType("character varying(32)") diff --git a/Common/OpenShockDb/Models/PublicShare.cs b/Common/OpenShockDb/Models/PublicShare.cs index c8fe8701..5bde2201 100644 --- a/Common/OpenShockDb/Models/PublicShare.cs +++ b/Common/OpenShockDb/Models/PublicShare.cs @@ -15,6 +15,16 @@ public sealed class PublicShare public DateTime? ExpiresAt { get; set; } + /// + /// Optional password visitors must enter before they can see or control the shockers. + /// + public string? PasswordHash { get; set; } + + /// + /// Changes whenever the password is set or changed, invalidating every unlock issued before. + /// + public Guid? PasswordStamp { get; set; } + public DateTime CreatedAt { get; init; } // Navigations diff --git a/Common/OpenShockDb/OpenShockContext.cs b/Common/OpenShockDb/OpenShockContext.cs index a5885a60..b3ecc5dc 100644 --- a/Common/OpenShockDb/OpenShockContext.cs +++ b/Common/OpenShockDb/OpenShockContext.cs @@ -558,6 +558,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .UseCollation("C") .HasMaxLength(ApiHardLimits.PublicShareSlugMaxLength) .HasColumnName("slug"); + entity.Property(e => e.PasswordHash) + .UseCollation("C") + .HasMaxLength(ApiHardLimits.PasswordHashMaxLength) + .HasColumnName("password_hash"); + entity.Property(e => e.PasswordStamp).HasColumnName("password_stamp"); entity.Property(e => e.OwnerId).HasColumnName("owner_id"); entity.HasOne(d => d.Owner).WithMany(p => p.OwnedPublicShares) diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 43d2158a..8b59ce42 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -31,6 +31,7 @@ using OpenShock.Common.Services.Configuration; using OpenShock.Common.Services.Geo; using OpenShock.Common.Services.RedisPubSub; +using OpenShock.Common.Services.PublicShareAccess; using OpenShock.Common.Services.Session; using OpenShock.Common.Services.Webhook; using OpenShock.Common.Utils; @@ -316,6 +317,7 @@ public static IServiceCollection AddOpenShockServices(this IServiceCollection se services.AddSingleton(); services.AddScoped(); services.AddScoped(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); diff --git a/Common/Services/PublicShareAccess/PublicShareAccessService.cs b/Common/Services/PublicShareAccess/PublicShareAccessService.cs new file mode 100644 index 00000000..8c89989d --- /dev/null +++ b/Common/Services/PublicShareAccess/PublicShareAccessService.cs @@ -0,0 +1,78 @@ +using OpenShock.Common.Utils; +using OpenShock.Internal.Common.Utils; +using StackExchange.Redis; + +namespace OpenShock.Common.Services.PublicShareAccess; + +/// +/// Unlock tokens for password-protected public shares. A visitor who entered the password gets a token, +/// which they send along when they load the share and when they connect to its hub. A token is tied to the +/// share's password stamp, so setting or changing the password invalidates every token issued before. +/// +public interface IPublicShareAccessService +{ + /// Issues a token for a visitor who entered the correct password. + Task IssueTokenAsync(Guid publicShareId, Guid passwordStamp); + + /// Whether the token unlocks this share at its current password stamp. + Task IsTokenValidAsync(Guid publicShareId, Guid passwordStamp, string? token); + + /// Whether too many incorrect passwords were entered for this share recently. + Task IsLockedOutAsync(Guid publicShareId); + + /// Counts an incorrect password towards the share's lockout. + Task RecordFailedAttemptAsync(Guid publicShareId); +} + +public sealed class PublicShareAccessService : IPublicShareAccessService +{ + public static readonly TimeSpan TokenLifetime = TimeSpan.FromHours(12); + + /// + /// Incorrect passwords allowed per share within , from any visitor. + /// Per-IP limits alone would let a botnet guess indefinitely. + /// + public const int MaxFailedAttempts = 20; + public static readonly TimeSpan FailedAttemptWindow = TimeSpan.FromMinutes(15); + + private const int TokenLength = 32; + + private readonly IDatabase _redis; + + public PublicShareAccessService(IConnectionMultiplexer connectionMultiplexer) + { + _redis = connectionMultiplexer.GetDatabase(); + } + + public async Task IssueTokenAsync(Guid publicShareId, Guid passwordStamp) + { + var token = CryptoUtils.RandomString(TokenLength); + await _redis.StringSetAsync(TokenKey(token), TokenValue(publicShareId, passwordStamp), TokenLifetime); + return token; + } + + public async Task IsTokenValidAsync(Guid publicShareId, Guid passwordStamp, string? token) + { + if (string.IsNullOrEmpty(token) || token.Length != TokenLength) return false; + + var value = await _redis.StringGetAsync(TokenKey(token)); + return value.HasValue && (string?)value == TokenValue(publicShareId, passwordStamp); + } + + public async Task IsLockedOutAsync(Guid publicShareId) + { + var value = await _redis.StringGetAsync(FailedAttemptsKey(publicShareId)); + return value.TryParse(out long count) && count >= MaxFailedAttempts; + } + + public async Task RecordFailedAttemptAsync(Guid publicShareId) + { + var key = FailedAttemptsKey(publicShareId); + var count = await _redis.StringIncrementAsync(key); + if (count == 1) await _redis.KeyExpireAsync(key, FailedAttemptWindow); + } + + private static RedisKey TokenKey(string token) => $"public-share-unlock:{HashingUtils.HashToken(token)}"; + private static string TokenValue(Guid publicShareId, Guid passwordStamp) => $"{publicShareId}:{passwordStamp}"; + private static RedisKey FailedAttemptsKey(Guid publicShareId) => $"public-share-unlock-failures:{publicShareId}"; +} diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 982433e9..db98247c 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -33,6 +33,12 @@ public interface IRedisPubService /// Task SendUserAuthRevoked(Guid userId); + /// + /// Who may use a public share changed. Notifies every instance so open connections to it are closed. + /// Best-effort: a connection that misses it is caught by its next periodic check. + /// + Task SendPublicShareAccessRevoked(Guid publicShareId); + /// /// 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 53de95e7..515bab26 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -23,6 +23,12 @@ public static class RedisChannels /// public static readonly RedisChannel SessionRevoked = new("session-revoked", RedisChannel.PatternMode.Literal); + /// + /// Fired when who may use a public share changed (its password was set or changed, or it was deleted). The + /// payload is the share id. Open connections to it are closed; visitors have to get in again. + /// + public static readonly RedisChannel PublicShareAccessRevoked = new("public-share-access-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. diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 0e55f96a..9d5a442d 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -38,6 +38,11 @@ public Task SendUserAuthRevoked(Guid userId) return _subscriber.PublishAsync(RedisChannels.UserAuthRevoked, userId.ToString()); } + public Task SendPublicShareAccessRevoked(Guid publicShareId) + { + return _subscriber.PublishAsync(RedisChannels.PublicShareAccessRevoked, publicShareId.ToString()); + } + public Task SendEmailOutboxPending() { // Payload-less wake-up nudge; the consumer reads the actual rows from the database. From 6761ce3753059c7e3a28c8e3cf0eddf1b5156607 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 17:15:13 +0100 Subject: [PATCH 05/11] 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 06/11] 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 7db2b6ba08eb95b2dc93f53a1f49986584395a29 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 17:34:21 +0100 Subject: [PATCH 07/11] fix: address review on public share passwords - password attempts are reserved atomically before the check, so parallel guesses cannot pass the lockout - the lockout counter gets its expiry in the same Redis operation as its first increment - correct passwords give their attempt back and do not count towards the lockout - whitespace-only passwords can be entered, as they can be set - attaching a public share to a checked connection makes its next call check the share --- .../Tests/PublicSharePasswordTests.cs | 52 +++++++++++++++++++ API/Controller/Public/UnlockPublicShare.cs | 10 ++-- API/Models/Requests/PublicShareUnlock.cs | 5 +- Common/Hubs/HubConnectionTracker.cs | 2 + .../PublicShareAccessService.cs | 41 ++++++++++----- .../Services/RedisPubSub/IRedisPubService.cs | 3 +- 6 files changed, 91 insertions(+), 22 deletions(-) diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 97ebe747..c07cd35e 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -1,3 +1,4 @@ +using StackExchange.Redis; using System.Net; using System.Text.Json; using Microsoft.AspNetCore.Http.Connections; @@ -122,6 +123,57 @@ await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); } + [Test] + public async Task Unlock_ParallelWrongPasswords_NeverGetPastTheLimit() + { + var (_, shareId) = await CreateShareWithShocker("pwparallel", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + var responses = await Task.WhenAll(Enumerable.Range(0, PublicShareAccessService.MaxFailedAttempts + 10).Select(_ => + visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", TestHelper.JsonContent(new { password = "nope-nope" })))); + + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.Unauthorized)).IsEqualTo(PublicShareAccessService.MaxFailedAttempts); + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.TooManyRequests)).IsEqualTo(10); + } + + [Test] + public async Task Unlock_WrongPassword_StartsAnExpiringLockoutWindow() + { + var (_, shareId) = await CreateShareWithShocker("pwwindow", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", TestHelper.JsonContent(new { password = "nope-nope" })); + + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + var ttl = await redis.KeyTimeToLiveAsync($"public-share-unlock-failures:{shareId}"); + await Assert.That(ttl).IsNotNull(); + await Assert.That(ttl!.Value).IsLessThanOrEqualTo(PublicShareAccessService.FailedAttemptWindow); + } + + [Test] + public async Task Unlock_CorrectPasswords_DoNotCountTowardsTheLockout() + { + var (_, shareId) = await CreateShareWithShocker("pwnocount", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + for (var i = 0; i <= PublicShareAccessService.MaxFailedAttempts; i++) + { + var response = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", TestHelper.JsonContent(new { password = Password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + } + + [Test] + public async Task Unlock_WhitespacePassword_CanBeEntered() + { + const string spaces = " "; + var (_, shareId) = await CreateShareWithShocker("pwspaces", spaces); + using var visitor = WebApplicationFactory.CreateClient(); + + var token = await Unlock(visitor, shareId, spaces); + await Assert.That(token).IsNotEmpty(); + } + [Test] public async Task Unlock_TokenIsOnlyValidForItsShare() { diff --git a/API/Controller/Public/UnlockPublicShare.cs b/API/Controller/Public/UnlockPublicShare.cs index 667d1b54..485d637b 100644 --- a/API/Controller/Public/UnlockPublicShare.cs +++ b/API/Controller/Public/UnlockPublicShare.cs @@ -46,13 +46,11 @@ public async Task UnlockPublicShare([FromRoute] Guid publicShareI if (share is null) return Problem(PublicShareError.PublicShareNotFound); if (share.PasswordHash is null || share.PasswordStamp is not { } stamp) return Problem(PublicShareError.NotPasswordProtected); - if (await publicShareAccess.IsLockedOutAsync(publicShareId)) return Problem(PublicShareError.TooManyPasswordAttempts); + if (!await publicShareAccess.TryReserveAttemptAsync(publicShareId)) return Problem(PublicShareError.TooManyPasswordAttempts); - if (!HashingUtils.VerifyPassword(body.Password, share.PasswordHash).Verified) - { - await publicShareAccess.RecordFailedAttemptAsync(publicShareId); - return Problem(PublicShareError.PasswordIncorrect); - } + if (!HashingUtils.VerifyPassword(body.Password, share.PasswordHash).Verified) return Problem(PublicShareError.PasswordIncorrect); + + await publicShareAccess.ReleaseAttemptAsync(publicShareId); var token = await publicShareAccess.IssueTokenAsync(publicShareId, stamp); return Ok(new PublicShareUnlockResponse diff --git a/API/Models/Requests/PublicShareUnlock.cs b/API/Models/Requests/PublicShareUnlock.cs index 808b1e42..05e9c3a8 100644 --- a/API/Models/Requests/PublicShareUnlock.cs +++ b/API/Models/Requests/PublicShareUnlock.cs @@ -5,7 +5,8 @@ namespace OpenShock.API.Models.Requests; public sealed class PublicShareUnlock { - [Required(AllowEmptyStrings = false)] - [MaxLength(ApiHardLimits.PublicSharePasswordMaxLength)] + // Whitespace is allowed: share passwords may consist of spaces. + [Required(AllowEmptyStrings = true)] + [StringLength(ApiHardLimits.PublicSharePasswordMaxLength, MinimumLength = 1)] public required string Password { get; init; } } diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs index 39852871..20a8feab 100644 --- a/Common/Hubs/HubConnectionTracker.cs +++ b/Common/Hubs/HubConnectionTracker.cs @@ -59,6 +59,8 @@ public TrackedHubConnection TrackPublicShare(HubCallerContext context, Guid publ { var tracked = _connections.GetOrAdd(context.ConnectionId, _ => new TrackedHubConnection(context, userId: null, sessionId: null, apiTokenId: null)); tracked.AttachPublicShare(publicShareId, passwordStamp); + // A logged in connection was already checked, but not against the share: the next call has to. + tracked.Invalidate(); return tracked; } diff --git a/Common/Services/PublicShareAccess/PublicShareAccessService.cs b/Common/Services/PublicShareAccess/PublicShareAccessService.cs index 8c89989d..b5a13886 100644 --- a/Common/Services/PublicShareAccess/PublicShareAccessService.cs +++ b/Common/Services/PublicShareAccess/PublicShareAccessService.cs @@ -17,11 +17,15 @@ public interface IPublicShareAccessService /// Whether the token unlocks this share at its current password stamp. Task IsTokenValidAsync(Guid publicShareId, Guid passwordStamp, string? token); - /// Whether too many incorrect passwords were entered for this share recently. - Task IsLockedOutAsync(Guid publicShareId); + /// + /// Counts a password attempt towards the share's lockout, before the password is checked, so parallel + /// guesses cannot get past the limit. + /// + /// False when too many incorrect passwords were entered for this share recently. + Task TryReserveAttemptAsync(Guid publicShareId); - /// Counts an incorrect password towards the share's lockout. - Task RecordFailedAttemptAsync(Guid publicShareId); + /// Gives a reserved attempt back once the password turned out correct: only incorrect ones count. + Task ReleaseAttemptAsync(Guid publicShareId); } public sealed class PublicShareAccessService : IPublicShareAccessService @@ -59,18 +63,29 @@ public async Task IsTokenValidAsync(Guid publicShareId, Guid passwordStamp return value.HasValue && (string?)value == TokenValue(publicShareId, passwordStamp); } - public async Task IsLockedOutAsync(Guid publicShareId) + public async Task TryReserveAttemptAsync(Guid publicShareId) { - var value = await _redis.StringGetAsync(FailedAttemptsKey(publicShareId)); - return value.TryParse(out long count) && count >= MaxFailedAttempts; + var count = (long)await _redis.ScriptEvaluateAsync(ReserveAttemptScript, + [FailedAttemptsKey(publicShareId)], [(long)FailedAttemptWindow.TotalMilliseconds]); + return count <= MaxFailedAttempts; } - public async Task RecordFailedAttemptAsync(Guid publicShareId) - { - var key = FailedAttemptsKey(publicShareId); - var count = await _redis.StringIncrementAsync(key); - if (count == 1) await _redis.KeyExpireAsync(key, FailedAttemptWindow); - } + public Task ReleaseAttemptAsync(Guid publicShareId) + => _redis.ScriptEvaluateAsync(ReleaseAttemptScript, [FailedAttemptsKey(publicShareId)]); + + // The window starts with the first attempt and is not extended by later ones. Increment and expiry happen + // together, so a counter can never be left without an expiry. + private const string ReserveAttemptScript = """ + local count = redis.call('INCR', KEYS[1]) + if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end + return count + """; + + // Only decrements a counter that still exists, so one that expired in between is not recreated without an expiry. + private const string ReleaseAttemptScript = """ + if redis.call('EXISTS', KEYS[1]) == 1 then return redis.call('DECR', KEYS[1]) end + return 0 + """; private static RedisKey TokenKey(string token) => $"public-share-unlock:{HashingUtils.HashToken(token)}"; private static string TokenValue(Guid publicShareId, Guid passwordStamp) => $"{publicShareId}:{passwordStamp}"; diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index db98247c..5d682948 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -35,7 +35,8 @@ public interface IRedisPubService /// /// Who may use a public share changed. Notifies every instance so open connections to it are closed. - /// Best-effort: a connection that misses it is caught by its next periodic check. + /// Best-effort: a connection that misses it is checked on its first hub call once the revalidation interval + /// has passed since its last check. An idle connection is not checked, but cannot control anything either. /// Task SendPublicShareAccessRevoked(Guid publicShareId); From e084ba70570edfed5718a86590980e9dc2e257bf Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 17:38:48 +0100 Subject: [PATCH 08/11] fix: rejected unlock attempts are not counted and releases stay in their window --- .../Tests/PublicSharePasswordTests.cs | 35 +++++++++++++++ API/Controller/Public/UnlockPublicShare.cs | 4 +- .../PublicShareAccessService.cs | 45 ++++++++++++------- 3 files changed, 65 insertions(+), 19 deletions(-) diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index c07cd35e..056cb7dd 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -174,6 +174,41 @@ public async Task Unlock_WhitespacePassword_CanBeEntered() await Assert.That(token).IsNotEmpty(); } + [Test] + public async Task Lockout_RejectedAttempts_AreNotCounted() + { + var access = WebApplicationFactory.Services.GetRequiredService(); + var shareId = Guid.NewGuid(); + + for (var i = 0; i < PublicShareAccessService.MaxFailedAttempts - 1; i++) + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNotNull(); + + // The last attempt is a correct password still being checked when another one is rejected. + var inFlight = await access.TryReserveAttemptAsync(shareId); + await Assert.That(inFlight).IsNotNull(); + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNull(); + await access.ReleaseAttemptAsync(shareId, inFlight!); + + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNotNull(); + } + + [Test] + public async Task Lockout_ReleaseFromAnEndedWindow_DoesNotCountAgainstTheNextOne() + { + var access = WebApplicationFactory.Services.GetRequiredService(); + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + var shareId = Guid.NewGuid(); + + var stale = await access.TryReserveAttemptAsync(shareId); + await redis.KeyDeleteAsync($"public-share-unlock-failures:{shareId}"); + + for (var i = 0; i < PublicShareAccessService.MaxFailedAttempts; i++) + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNotNull(); + + await access.ReleaseAttemptAsync(shareId, stale!); + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNull(); + } + [Test] public async Task Unlock_TokenIsOnlyValidForItsShare() { diff --git a/API/Controller/Public/UnlockPublicShare.cs b/API/Controller/Public/UnlockPublicShare.cs index 485d637b..12d43fe4 100644 --- a/API/Controller/Public/UnlockPublicShare.cs +++ b/API/Controller/Public/UnlockPublicShare.cs @@ -46,11 +46,11 @@ public async Task UnlockPublicShare([FromRoute] Guid publicShareI if (share is null) return Problem(PublicShareError.PublicShareNotFound); if (share.PasswordHash is null || share.PasswordStamp is not { } stamp) return Problem(PublicShareError.NotPasswordProtected); - if (!await publicShareAccess.TryReserveAttemptAsync(publicShareId)) return Problem(PublicShareError.TooManyPasswordAttempts); + if (await publicShareAccess.TryReserveAttemptAsync(publicShareId) is not { } reservation) return Problem(PublicShareError.TooManyPasswordAttempts); if (!HashingUtils.VerifyPassword(body.Password, share.PasswordHash).Verified) return Problem(PublicShareError.PasswordIncorrect); - await publicShareAccess.ReleaseAttemptAsync(publicShareId); + await publicShareAccess.ReleaseAttemptAsync(publicShareId, reservation); var token = await publicShareAccess.IssueTokenAsync(publicShareId, stamp); return Ok(new PublicShareUnlockResponse diff --git a/Common/Services/PublicShareAccess/PublicShareAccessService.cs b/Common/Services/PublicShareAccess/PublicShareAccessService.cs index b5a13886..8a07e9d1 100644 --- a/Common/Services/PublicShareAccess/PublicShareAccessService.cs +++ b/Common/Services/PublicShareAccess/PublicShareAccessService.cs @@ -21,11 +21,17 @@ public interface IPublicShareAccessService /// Counts a password attempt towards the share's lockout, before the password is checked, so parallel /// guesses cannot get past the limit. /// - /// False when too many incorrect passwords were entered for this share recently. - Task TryReserveAttemptAsync(Guid publicShareId); + /// + /// The reservation, to hand to , or null when too many incorrect passwords were + /// entered for this share recently. A rejected attempt is not counted. + /// + Task TryReserveAttemptAsync(Guid publicShareId); - /// Gives a reserved attempt back once the password turned out correct: only incorrect ones count. - Task ReleaseAttemptAsync(Guid publicShareId); + /// + /// Gives a reserved attempt back once the password turned out correct: only incorrect ones count. Does nothing + /// when the window it was reserved in has ended. + /// + Task ReleaseAttemptAsync(Guid publicShareId, string reservation); } public sealed class PublicShareAccessService : IPublicShareAccessService @@ -63,27 +69,32 @@ public async Task IsTokenValidAsync(Guid publicShareId, Guid passwordStamp return value.HasValue && (string?)value == TokenValue(publicShareId, passwordStamp); } - public async Task TryReserveAttemptAsync(Guid publicShareId) + public async Task TryReserveAttemptAsync(Guid publicShareId) { - var count = (long)await _redis.ScriptEvaluateAsync(ReserveAttemptScript, - [FailedAttemptsKey(publicShareId)], [(long)FailedAttemptWindow.TotalMilliseconds]); - return count <= MaxFailedAttempts; + var result = await _redis.ScriptEvaluateAsync(ReserveAttemptScript, [FailedAttemptsKey(publicShareId)], + [(long)FailedAttemptWindow.TotalMilliseconds, MaxFailedAttempts, Guid.NewGuid().ToString("N")]); + return result.IsNull ? null : (string?)result; } - public Task ReleaseAttemptAsync(Guid publicShareId) - => _redis.ScriptEvaluateAsync(ReleaseAttemptScript, [FailedAttemptsKey(publicShareId)]); + public Task ReleaseAttemptAsync(Guid publicShareId, string reservation) + => _redis.ScriptEvaluateAsync(ReleaseAttemptScript, [FailedAttemptsKey(publicShareId)], [reservation]); - // The window starts with the first attempt and is not extended by later ones. Increment and expiry happen - // together, so a counter can never be left without an expiry. + // The counter is a hash of the attempt count and the id of its window. The window starts with the first attempt + // and is not extended by later ones; it gets its expiry in the same operation that creates it. The reservation + // is the window id, so a release only counts against the window it was reserved in. private const string ReserveAttemptScript = """ - local count = redis.call('INCR', KEYS[1]) - if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end - return count + local count = tonumber(redis.call('HGET', KEYS[1], 'count') or '0') + if count >= tonumber(ARGV[2]) then return false end + if redis.call('EXISTS', KEYS[1]) == 0 then + redis.call('HSET', KEYS[1], 'window', ARGV[3]) + redis.call('PEXPIRE', KEYS[1], ARGV[1]) + end + redis.call('HINCRBY', KEYS[1], 'count', 1) + return redis.call('HGET', KEYS[1], 'window') """; - // Only decrements a counter that still exists, so one that expired in between is not recreated without an expiry. private const string ReleaseAttemptScript = """ - if redis.call('EXISTS', KEYS[1]) == 1 then return redis.call('DECR', KEYS[1]) end + if redis.call('HGET', KEYS[1], 'window') == ARGV[1] then redis.call('HINCRBY', KEYS[1], 'count', -1) end return 0 """; From c06441d6b1e4e6ecd7d4dccff9456522dde7ffc0 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 17:42:25 +0100 Subject: [PATCH 09/11] fix: a correct password does not start the lockout window --- .../Tests/PublicSharePasswordTests.cs | 19 +++++++++++++++++++ .../PublicShareAccessService.cs | 4 +++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 056cb7dd..2186469b 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -209,6 +209,25 @@ public async Task Lockout_ReleaseFromAnEndedWindow_DoesNotCountAgainstTheNextOne await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNull(); } + [Test] + public async Task Lockout_CorrectPassword_DoesNotStartTheWindow() + { + var access = WebApplicationFactory.Services.GetRequiredService(); + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + var shareId = Guid.NewGuid(); + var key = $"public-share-unlock-failures:{shareId}"; + + var correct = await access.TryReserveAttemptAsync(shareId); + await access.ReleaseAttemptAsync(shareId, correct!); + await Assert.That(await redis.KeyExistsAsync(key)).IsFalse(); + + // The first incorrect password starts a full window. + await access.TryReserveAttemptAsync(shareId); + var ttl = await redis.KeyTimeToLiveAsync(key); + await Assert.That(ttl).IsNotNull(); + await Assert.That(ttl!.Value).IsGreaterThan(PublicShareAccessService.FailedAttemptWindow - TimeSpan.FromMinutes(1)); + } + [Test] public async Task Unlock_TokenIsOnlyValidForItsShare() { diff --git a/Common/Services/PublicShareAccess/PublicShareAccessService.cs b/Common/Services/PublicShareAccess/PublicShareAccessService.cs index 8a07e9d1..6dd2105b 100644 --- a/Common/Services/PublicShareAccess/PublicShareAccessService.cs +++ b/Common/Services/PublicShareAccess/PublicShareAccessService.cs @@ -93,8 +93,10 @@ public Task ReleaseAttemptAsync(Guid publicShareId, string reservation) return redis.call('HGET', KEYS[1], 'window') """; + // A window holding no incorrect password is dropped, so the window starts with the first incorrect one. private const string ReleaseAttemptScript = """ - if redis.call('HGET', KEYS[1], 'window') == ARGV[1] then redis.call('HINCRBY', KEYS[1], 'count', -1) end + if redis.call('HGET', KEYS[1], 'window') ~= ARGV[1] then return 0 end + if redis.call('HINCRBY', KEYS[1], 'count', -1) <= 0 then redis.call('DEL', KEYS[1]) end return 0 """; From e5cf584e171d7404df1fa10b2f238b27fcdb5ccb Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 23:23:25 +0100 Subject: [PATCH 10/11] fix: check queued public share calls against the share after a revocation untracks them - the lockout test asserts every wrong password gets 401 - the stamp fallback test validates once before changing the stamp - hub test connections wait for admission and are disposed when startup fails - rejection tests no longer accept any startup exception --- .../Tests/PublicSharePasswordTests.cs | 50 +++++++++++++------ Common/Hubs/HubConnectionTracker.cs | 9 ++++ .../Hubs/RevalidateAuthenticationHubFilter.cs | 3 +- 3 files changed, 47 insertions(+), 15 deletions(-) diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 2186469b..601bc915 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -114,8 +114,9 @@ public async Task Unlock_AfterTooManyWrongPasswords_IsLockedOutEvenWithTheRightO for (var i = 0; i < PublicShareAccessService.MaxFailedAttempts; i++) { - await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + var wrong = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", TestHelper.JsonContent(new { password = "nope-nope" })); + await Assert.That(wrong.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); } var response = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", @@ -322,6 +323,11 @@ public async Task Hub_WithoutToken_IsRejected() await AssertCannotConnectAsync(shareId, unlockToken: null); await AssertCannotConnectAsync(shareId, unlockToken: "not-a-real-token-not-a-real-tok"); + + // The same route admits a valid token, so the rejections above came from the password check. + using var visitor = WebApplicationFactory.CreateClient(); + await using var connection = await ConnectAsync(shareId, await Unlock(visitor, shareId, Password)); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); } [Test] @@ -406,6 +412,8 @@ public async Task Hub_PasswordChangedWithoutAnnouncement_ClosesOnTheNextCheck() using var visitor = WebApplicationFactory.CreateClient(); var token = await Unlock(visitor, shareId, Password); await using var connection = await ConnectAsync(shareId, token); + // Checked once here, so the call below has to be a re-check. + await connection.InvokeAsync("Control", Array.Empty()); await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) { @@ -519,7 +527,24 @@ private async Task SetPassword(AuthenticatedUser owner, Guid shareI return json.RootElement.Clone(); } + /// Connects and waits until the hub admitted the connection (it sends Welcome after its checks). private async Task ConnectAsync(Guid shareId, string? unlockToken, string? sessionToken = null) + { + var (connection, welcomed) = BuildConnection(shareId, unlockToken, sessionToken); + try + { + await connection.StartAsync(); + await welcomed.WaitAsync(TimeSpan.FromSeconds(30)); + return connection; + } + catch + { + await connection.DisposeAsync(); + throw; + } + } + + private (HubConnection Connection, Task Welcomed) BuildConnection(Guid shareId, string? unlockToken, string? sessionToken = null) { var server = WebApplicationFactory.Server; var path = $"/1/hubs/share/link/{shareId}?name=Guest"; @@ -541,26 +566,23 @@ private async Task ConnectAsync(Guid shareId, string? unlockToken }) .Build(); - await connection.StartAsync(); - return connection; + var welcomed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + connection.On("Welcome", _ => welcomed.TrySetResult()); + return (connection, welcomed.Task); } - /// The server aborts a rejected connection right after the handshake, or the handshake fails. + /// + /// The handshake succeeds, then the hub rejects the connection in its admission checks: it closes without + /// being welcomed. Any other failure, such as a broken route, fails the test. + /// private async Task AssertCannotConnectAsync(Guid shareId, string? unlockToken) { - HubConnection? connection = null; - try - { - connection = await ConnectAsync(shareId, unlockToken); - } - catch - { - return; - } - + var (connection, welcomed) = BuildConnection(shareId, unlockToken); await using (connection) { + await connection.StartAsync(); await AssertConnectionClosesAsync(connection); + await Assert.That(welcomed.IsCompleted).IsFalse(); } } diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs index 60050ee6..2868b0bd 100644 --- a/Common/Hubs/HubConnectionTracker.cs +++ b/Common/Hubs/HubConnectionTracker.cs @@ -61,9 +61,18 @@ public TrackedHubConnection TrackPublicShare(HubCallerContext context, Guid publ tracked.AttachPublicShare(publicShareId, passwordStamp); // A logged in connection was already checked, but not against the share: the next call has to. tracked.ResetValidation(); + // Kept on the connection too: a revocation untracks it, and its queued calls still have to be checked + // against the share while they drain. + context.Items[PublicShareConnectionKey] = tracked; return tracked; } + /// The public share connection as it was tracked, also after a revocation untracked it. + public static TrackedHubConnection? GetPublicShareConnection(HubCallerContext context) + => context.Items.TryGetValue(PublicShareConnectionKey, out var tracked) ? tracked as TrackedHubConnection : null; + + private static readonly object PublicShareConnectionKey = new(); + public void Untrack(string connectionId) => _connections.TryRemove(connectionId, out _); /// Closes the connections to this public share. diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index 001c66a0..40716158 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -100,7 +100,8 @@ private static async Task ValidateAsync(HubCallerContext context, TrackedH { if (!await IsStillAuthenticated(context, services)) return false; - if (tracked?.PublicShareId is { } publicShareId && !await IsPublicShareStillAccessible(publicShareId, tracked.PasswordStamp, context, services)) return false; + if ((tracked ?? HubConnectionTracker.GetPublicShareConnection(context)) is { PublicShareId: { } publicShareId } shareConnection + && !await IsPublicShareStillAccessible(publicShareId, shareConnection.PasswordStamp, context, services)) return false; tracked?.MarkValidated(); return true; From 50df527cfff57d1a801be8e736b1e2b7275926d2 Mon Sep 17 00:00:00 2001 From: LucHeart Date: Thu, 3 Dec 2026 23:32:08 +0100 Subject: [PATCH 11/11] refactor: reject calls on an untracked public share connection without a query --- Common/Hubs/HubConnectionTracker.cs | 6 +++--- Common/Hubs/RevalidateAuthenticationHubFilter.cs | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs index 2868b0bd..81a888d9 100644 --- a/Common/Hubs/HubConnectionTracker.cs +++ b/Common/Hubs/HubConnectionTracker.cs @@ -61,13 +61,13 @@ public TrackedHubConnection TrackPublicShare(HubCallerContext context, Guid publ tracked.AttachPublicShare(publicShareId, passwordStamp); // A logged in connection was already checked, but not against the share: the next call has to. tracked.ResetValidation(); - // Kept on the connection too: a revocation untracks it, and its queued calls still have to be checked - // against the share while they drain. + // Kept on the connection too, so a call that arrives after a revocation untracked it can be told apart + // from an anonymous connection that was never tracked. context.Items[PublicShareConnectionKey] = tracked; return tracked; } - /// The public share connection as it was tracked, also after a revocation untracked it. + /// The public share connection as it was tracked, also after it was untracked. public static TrackedHubConnection? GetPublicShareConnection(HubCallerContext context) => context.Items.TryGetValue(PublicShareConnectionKey, out var tracked) ? tracked as TrackedHubConnection : null; diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index 40716158..019e2934 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -83,6 +83,13 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception // queued calls are still draining: the check below turns those away. var tracked = _tracker.Get(context.ConnectionId); + // A public share connection only leaves the tracker when it is being closed, so there is nothing to check. + if (tracked is null && HubConnectionTracker.GetPublicShareConnection(context) is not null) + { + context.Abort(); + throw new HubException("Access to this public share is no longer valid"); + } + if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) { if (!await ValidateAsync(context, tracked, invocationContext.ServiceProvider)) @@ -100,8 +107,7 @@ private static async Task ValidateAsync(HubCallerContext context, TrackedH { if (!await IsStillAuthenticated(context, services)) return false; - if ((tracked ?? HubConnectionTracker.GetPublicShareConnection(context)) is { PublicShareId: { } publicShareId } shareConnection - && !await IsPublicShareStillAccessible(publicShareId, shareConnection.PasswordStamp, context, services)) return false; + if (tracked?.PublicShareId is { } publicShareId && !await IsPublicShareStillAccessible(publicShareId, tracked.PasswordStamp, context, services)) return false; tracked?.MarkValidated(); return true;