From 060f4a091aa8f77c2ef81b824a8060d61d0aaa7d Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 11:36:20 +0100 Subject: [PATCH 01/24] fix: close live control sockets whose authentication is revoked A live control socket was authenticated once, when it opened. When its API token changed, the gateway refreshed the pause state and limits but never checked that the token could still control, so a token that lost shockers.use kept working. Expiry was only noticed if some token change happened to be announced, and a logged out session or a deactivated account kept its open socket too. The gateway now closes a live control socket when its token is deleted, expires, loses shockers.use or its user is deactivated, and when its session is deleted or its account deactivated, including sockets controlling a deactivated owner's hub through a share. Token expiry is enforced on every frame and on the ping. As a fallback for a lost message, each socket re-checks its token or session, the account and its share permissions at most once per revalidation interval, and once right after connecting. Also adds regression tests for share control while the device owner is deactivated. --- .../Tests/PublicSharePasswordTests.cs | 14 ++ .../Tests/ShockerPermissionsTests.cs | 40 ++++ .../Extensions/ApiTokenExtensionsTests.cs | 49 +++++ Common/Extensions/ApiTokenExtensions.cs | 19 ++ .../Controllers/LiveControlController.cs | 203 ++++++++++++++++-- LiveControlGateway/Program.cs | 2 + .../PubSub/ApiTokenUpdateSubscriber.cs | 42 ++-- .../PubSub/LiveControlRevocationSubscriber.cs | 85 ++++++++ 8 files changed, 413 insertions(+), 41 deletions(-) create mode 100644 Common.Tests/Extensions/ApiTokenExtensionsTests.cs create mode 100644 Common/Extensions/ApiTokenExtensions.cs create mode 100644 LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 29f836b8..1484c732 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -409,6 +409,20 @@ await scope.ServiceProvider.GetRequiredService() await AssertConnectionClosesAsync(visitorConnection); } + [Test] + public async Task Hub_OwnerDeactivated_NewGuestCannotConnect() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubownerdeactnew", password: null); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService() + .DeactivateAccountAsync(owner.Id, owner.Id, deleteLater: false); + } + + await AssertCannotConnectAsync(shareId, unlockToken: null); + } + // --- Helpers --- private async Task<(AuthenticatedUser Owner, Guid ShareId)> CreateShareWithShocker(string prefix, diff --git a/API.IntegrationTests/Tests/ShockerPermissionsTests.cs b/API.IntegrationTests/Tests/ShockerPermissionsTests.cs index edcd72f3..c55079f8 100644 --- a/API.IntegrationTests/Tests/ShockerPermissionsTests.cs +++ b/API.IntegrationTests/Tests/ShockerPermissionsTests.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.API.Services.Account; using OpenShock.Common.OpenShockDb; using OpenShock.IntegrationTests.Shared; using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper; @@ -178,6 +179,45 @@ public async Task SharedShocker_ShowsPermissionsAllowedByBoth() await Assert.That(await LogCount(shockerId)).IsEqualTo(0); } + [Test] + public async Task SharedControl_OwnerDeactivated_IsNotSent() + { + var owner = await CreateUser("deactshowner"); + var recipient = await CreateUser("deactshrecip"); + var shockerId = await CreateShocker(WebApplicationFactory, owner.Id, "Shared"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.UserShares.Add(new UserShare + { + SharedWithUserId = recipient.Id, + ShockerId = shockerId, + AllowShock = true, + AllowVibrate = true, + AllowSound = true, + AllowLiveControl = true, + IsPaused = false + }); + await db.SaveChangesAsync(); + } + + using var recipientClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, recipient.SessionToken); + var before = await Control(recipientClient, shockerId, 10, 1000); + await Assert.That(before.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await LogCount(shockerId)).IsEqualTo(1); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService() + .DeactivateAccountAsync(owner.Id, owner.Id, deleteLater: false); + } + + var after = await Control(recipientClient, shockerId, 10, 1000); + await Assert.That(after.StatusCode).IsNotEqualTo(HttpStatusCode.OK); + await Assert.That(await LogCount(shockerId)).IsEqualTo(1); + } + private Task CreateUser(string prefix) => TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password); diff --git a/Common.Tests/Extensions/ApiTokenExtensionsTests.cs b/Common.Tests/Extensions/ApiTokenExtensionsTests.cs new file mode 100644 index 00000000..3c266234 --- /dev/null +++ b/Common.Tests/Extensions/ApiTokenExtensionsTests.cs @@ -0,0 +1,49 @@ +using System.Net; +using OpenShock.Common.Extensions; +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.Common.Tests.Extensions; + +public sealed class ApiTokenExtensionsTests +{ + private static readonly DateTime Now = new(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + private static ApiToken Token(DateTime? validUntil, params PermissionType[] permissions) => new() + { + UserId = Guid.NewGuid(), + Name = "test", + TokenHash = "hash", + CreatedByIp = IPAddress.Loopback, + Permissions = [.. permissions], + ValidUntil = validUntil + }; + + [Test] + public async Task CanControlShockers_ValidTokenWithShockersUse_True() + { + await Assert.That(Token(null, PermissionType.Shockers_Use).CanControlShockers(Now)).IsTrue(); + await Assert.That(Token(Now.AddMinutes(1), PermissionType.Shockers_Use).CanControlShockers(Now)).IsTrue(); + } + + [Test] + public async Task CanControlShockers_Expired_False() + { + await Assert.That(Token(Now.AddSeconds(-1), PermissionType.Shockers_Use).CanControlShockers(Now)).IsFalse(); + } + + [Test] + public async Task CanControlShockers_WithoutShockersUse_False() + { + await Assert.That(Token(null).CanControlShockers(Now)).IsFalse(); + await Assert.That(Token(null, PermissionType.Shockers_Edit).CanControlShockers(Now)).IsFalse(); + } + + [Test] + public async Task CanControlShockers_PausedTokenKeepsAuthority_True() + { + var token = Token(null, PermissionType.Shockers_Use); + token.ShockerControlPaused = true; + await Assert.That(token.CanControlShockers(Now)).IsTrue(); + } +} diff --git a/Common/Extensions/ApiTokenExtensions.cs b/Common/Extensions/ApiTokenExtensions.cs new file mode 100644 index 00000000..5398401e --- /dev/null +++ b/Common/Extensions/ApiTokenExtensions.cs @@ -0,0 +1,19 @@ +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.Common.Extensions; + +public static class ApiTokenExtensions +{ + /// + /// Whether this token may still control shockers at : it has not expired and still + /// carries . A paused token keeps this authority, it just sends nothing. + /// + /// + /// Checked again on connections that outlive their authentication, such as live control, so a token that + /// expired or lost the permission cannot keep using a connection it opened while it was valid. + /// + public static bool CanControlShockers(this ApiToken token, DateTime now) => + (token.ValidUntil is null || token.ValidUntil >= now) && + token.Permissions.IsAllowed(PermissionType.Shockers_Use); +} diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index 65ebcdb7..e2aa910e 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -5,15 +5,18 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication; using OpenShock.Common.Authentication.Attributes; using OpenShock.Common.Errors; using OpenShock.Common.Extensions; +using OpenShock.Common.Hubs; using OpenShock.Common.Models; using OpenShock.Common.Models.WebSocket; using OpenShock.Common.Models.WebSocket.LCG; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.Session; using OpenShock.Common.Utils; using OpenShock.Common.Websocket; using OpenShock.Internal.Common.Constants; @@ -42,6 +45,9 @@ public sealed class LiveControlController : WebsocketBaseController _dbContextFactory; private readonly ApiTokenUpdateSubscriber _tokenUpdateSubscriber; + private readonly LiveControlRevocationSubscriber _revocationSubscriber; + private readonly IServiceScopeFactory _scopeFactory; + private readonly TimeSpan _revalidationInterval; private readonly ILogger _logger; private readonly GatewayMetrics _metrics; @@ -56,15 +62,49 @@ public sealed class LiveControlController : WebsocketBaseController - /// Shocker control scoping carried by the API token used to authenticate, if any. + /// What the API token used to authenticate currently grants, replaced as a whole when it changes. /// Null when authenticated via a user session (no token limits apply). /// - private ApiTokenControlLimits? _tokenLimits; + private volatile TokenState? _tokenState; + + private sealed record TokenState(bool Paused, ApiTokenControlLimits Limits, DateTime? ValidUntil) + { + public static TokenState From(ApiToken token) => + new(token.ShockerControlPaused, ApiTokenControlLimits.FromToken(token), token.ValidUntil); + + public bool IsExpired(DateTime now) => ValidUntil is { } validUntil && validUntil < now; + } /// - /// When true, the authenticating API token is paused (or was revoked) and may not send any control frames. + /// The session token used to authenticate, if any. Null when authenticated via an API token. /// - private bool _tokenPaused; + private string? _sessionToken; + + /// + /// Set once the session or token this connection authenticated with may no longer control. + /// Every frame after that is dropped while the socket is being closed. + /// + private int _revokedFlag; + + private bool Revoked => Volatile.Read(ref _revokedFlag) != 0; + + private int _revalidating; + private long _lastValidated; + + /// + /// The id the authenticating session is stored under, null when authenticated via an API token. + /// + public string? SessionId { get; private set; } + + /// + /// The user controlling through this connection. + /// + public Guid UserId => _currentUser.Id; + + /// + /// The owner of the hub this connection controls, once known. + /// + public Guid? DeviceOwnerId => _device?.OwnerId; /// /// ID of the connected hub @@ -94,13 +134,19 @@ public sealed class LiveControlController : WebsocketBaseController /// /// + /// + /// + /// /// /// - public LiveControlController(HubLifetimeManager hubLifetimeManager, IDbContextFactory dbContextFactory, ApiTokenUpdateSubscriber tokenUpdateSubscriber, GatewayMetrics metrics, ILogger logger) : base(logger) + public LiveControlController(HubLifetimeManager hubLifetimeManager, IDbContextFactory dbContextFactory, ApiTokenUpdateSubscriber tokenUpdateSubscriber, LiveControlRevocationSubscriber revocationSubscriber, IServiceScopeFactory scopeFactory, IOptions revalidationOptions, GatewayMetrics metrics, ILogger logger) : base(logger) { _hubLifetimeManager = hubLifetimeManager; _dbContextFactory = dbContextFactory; _tokenUpdateSubscriber = tokenUpdateSubscriber; + _revocationSubscriber = revocationSubscriber; + _scopeFactory = scopeFactory; + _revalidationInterval = revalidationOptions.Value.Interval; _metrics = metrics; _logger = logger; @@ -265,23 +311,114 @@ public void OnActionExecuting(ActionExecutingContext context) if (GetOptionalItem() is { } apiToken) { _tokenId = apiToken.Id; - _tokenPaused = apiToken.ShockerControlPaused; - _tokenLimits = ApiTokenControlLimits.FromToken(apiToken); + _tokenState = TokenState.From(apiToken); + } + else if (HttpContext.TryGetUserSessionToken(out var sessionToken)) + { + _sessionToken = sessionToken; + SessionId = HubConnectionTracker.GetSessionId(sessionToken); } } + /// + /// Apply the current state of the authenticating API token to this connection, pushed by the + /// when the token changed. The caller has checked it may still control. + /// + /// + [NonAction] + public void ApplyToken(ApiToken token) + { + _tokenState = TokenState.From(token); + } /// - /// Apply refreshed API token limits to this connection, pushed by the - /// when the token changed or was revoked. A revoked/expired token arrives as paused with no limits. + /// The session or token this connection authenticated with may no longer control: stop accepting frames and + /// close the socket. Safe to call more than once and from any thread. /// - /// - /// [NonAction] - public void ApplyTokenLimits(bool paused, ApiTokenControlLimits? limits) + public async Task Revoke() { - _tokenPaused = paused; - _tokenLimits = limits; + if (Interlocked.Exchange(ref _revokedFlag, 1) != 0) return; + + Logger.LogInformation("Closing live control connection of user [{UserId}] for hub [{HubId}], its authentication is no longer valid", + _currentUser.Id, HubId); + + try + { + await ForceClose(WebSocketCloseStatus.PolicyViolation, "Authentication is no longer valid"); + } + catch (Exception e) + { + // The socket may already be closing on its own; the flag above stops all control either way. + Logger.LogDebug(e, "Error while closing revoked live control connection"); + } + } + + /// + /// Re-check this connection against the database and the session store, for what the Redis messages cannot + /// cover: a message that was lost, or a token that reached its expiry. Also refreshes the token's pause state + /// and limits and the shared shocker permissions. + /// + private async Task Revalidate() + { + if (Revoked || Interlocked.Exchange(ref _revalidating, 1) == 1) return; + + try + { + await using var scope = _scopeFactory.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + if (!await IsStillAuthenticated(scope.ServiceProvider, db)) + { + await Revoke(); + return; + } + + await UpdatePermissions(db); + Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); + } + catch (OperationCanceledException) when (LinkedToken.IsCancellationRequested) + { + // Connection is closing anyway. + } + catch (Exception e) + { + // A transient failure must not drop a legitimate connection; the next ping retries. + Logger.LogWarning(e, "Error while revalidating live control connection for hub [{HubId}]", HubId); + } + finally + { + Interlocked.Exchange(ref _revalidating, 0); + } + } + + private async Task IsStillAuthenticated(IServiceProvider services, OpenShockContext db) + { + if (_tokenId is { } tokenId) + { + var token = await db.ApiTokens + .AsNoTracking() + .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null, LinkedToken); + if (token is null || !token.CanControlShockers(DateTime.UtcNow)) return false; + + ApplyToken(token); + return true; + } + + if (_sessionToken is null) return false; + + // Sessions are deleted on logout, on deactivation and on a password reset. + var session = await services.GetRequiredService().GetSessionByTokenAsync(_sessionToken); + if (session is null || session.UserId != _currentUser.Id) return false; + + // That deletion happens after the database commit and can fail, so the account is the authority. + return await db.Users.AnyAsync(u => u.Id == _currentUser.Id && u.ActivatedAt != null && u.UserDeactivation == null, LinkedToken); + } + + private bool RevalidationDue() + { + var last = Interlocked.Read(ref _lastValidated); + return last == 0 || Stopwatch.GetElapsedTime(last) >= _revalidationInterval; } /// @@ -306,6 +443,12 @@ protected override async Task SendInitialData() // so changes take effect on this connection without reconnecting. if (_tokenId is { } tokenId) await _tokenUpdateSubscriber.Register(this, tokenId); + _revocationSubscriber.Register(this); + + // Authentication happened before the registrations above, so a revocation announced in between found + // nothing to close. Look once now that announcements can reach this connection. + await Revalidate(); + if (Revoked) return; await QueueMessage(new LiveControlResponse { @@ -484,8 +627,20 @@ await QueueMessage(new LiveControlResponse private async Task ProcessFrameInternal(ClientLiveFrame frame) { + // The socket is being closed because its authentication was revoked. + if (Revoked) return; + + var tokenState = _tokenState; + + // An expired token may not control, even though nothing announces the expiry. + if (tokenState is not null && tokenState.IsExpired(DateTime.UtcNow)) + { + await Revoke(); + return; + } + // A paused API token may not send any control, mirroring the /shockers/control endpoint. - if (_tokenPaused) + if (tokenState is { Paused: true }) { _metrics.Frame(GatewayMetrics.FrameOutcome.TokenPaused, frame.Type); await QueueMessage(new LiveControlResponse @@ -499,7 +654,7 @@ await QueueMessage(new LiveControlResponse var permCheck = CheckFramePermissions(frame.Shocker, frame.Type); await (permCheck switch { - SharePermsAndLimits perms => ForwardFrame(frame, perms), + SharePermsAndLimits perms => ForwardFrame(frame, perms, tokenState?.Limits), Results.NotFound => RejectFrame(frame, GatewayMetrics.FrameOutcome.ShockerNotFound, LiveResponseType.ShockerNotFound), LiveNotEnabled => RejectFrame(frame, GatewayMetrics.FrameOutcome.LiveNotEnabled, LiveResponseType.ShockerMissingLivePermission), NoPermission => RejectFrame(frame, GatewayMetrics.FrameOutcome.NoPermission, LiveResponseType.ShockerMissingPermission), @@ -516,10 +671,10 @@ await QueueMessage(new LiveControlResponse }); } - private async Task ForwardFrame(ClientLiveFrame frame, SharePermsAndLimits perms) + private async Task ForwardFrame(ClientLiveFrame frame, SharePermsAndLimits perms, ApiTokenControlLimits? tokenLimits) { // Apply the token's intensity scoping first (if any), then clamp to the shocker and share limits. - var scopedIntensity = _tokenLimits?.ApplyIntensity(frame.Intensity) ?? frame.Intensity; + var scopedIntensity = tokenLimits?.ApplyIntensity(frame.Intensity) ?? frame.Intensity; var intensity = ControlLimitUtils.ClampIntensity(scopedIntensity, perms.Intensity); var result = HubLifetime.ReceiveFrame(frame.Shocker, _logSender, frame.Type, intensity, _tps); @@ -569,6 +724,16 @@ private async Task SendPing() { if (WebSocket is not { State: WebSocketState.Open }) return; + // Close an idle connection whose token expired, rather than waiting for its next frame. + if (_tokenState is { } tokenState && tokenState.IsExpired(DateTime.UtcNow)) + { + await Revoke(); + return; + } + + if (RevalidationDue()) await Revalidate(); + if (Revoked) return; + if (Logger.IsEnabled(LogLevel.Debug)) Logger.LogDebug("Sending ping to live control user [{UserId}] for hub [{HubId}]", _currentUser.Id, Id); @@ -620,6 +785,8 @@ protected override async ValueTask DisposeControllerAsync() Logger.LogTrace("Disposing controller timer"); _pingTimer.Dispose(); + _revocationSubscriber.Unregister(this); + if (_tokenId is { } tokenId) { try diff --git a/LiveControlGateway/Program.cs b/LiveControlGateway/Program.cs index 7642cf16..5317262f 100644 --- a/LiveControlGateway/Program.cs +++ b/LiveControlGateway/Program.cs @@ -61,6 +61,8 @@ #pragma warning restore EXTEXP0008 builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); var app = builder.Build(); diff --git a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs b/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs index afbba5f9..f71409e5 100644 --- a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs +++ b/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs @@ -1,5 +1,5 @@ using Microsoft.EntityFrameworkCore; -using OpenShock.Common.Models; +using OpenShock.Common.Extensions; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.RedisPubSub; using OpenShock.Internal.Common.Extensions; @@ -12,8 +12,10 @@ namespace OpenShock.LiveControlGateway.PubSub; /// /// Per-gateway coordinator for API token update notifications. /// Holds a single ref-counted redis subscription per token, shared by every live control connection on this -/// gateway that authenticated with it. When a token changes, the limits are fetched from the database once and -/// pushed to all those connections, instead of each connection querying the database on its own. +/// gateway that authenticated with it. When a token changes, it is fetched from the database once and its pause +/// state and limits are pushed to all those connections, instead of each connection querying the database on its +/// own. A token that may no longer control (deleted, expired, its user deactivated, or without shockers.use) +/// closes those connections instead. /// public sealed class ApiTokenUpdateSubscriber { @@ -92,37 +94,31 @@ private async Task OnTokenUpdate(Guid tokenId) if (clients.Length == 0) return; - bool paused; - ApiTokenControlLimits? limits; + ApiToken? token; try { await using var db = await _dbContextFactory.CreateDbContextAsync(); - var token = await db.ApiTokens + token = await db.ApiTokens .AsNoTracking() - .FirstOrDefaultAsync(x => x.Id == tokenId && (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow)); - - if (token is null) - { - // Token revoked/expired: deny all further control on these connections. - _logger.LogDebug("API token [{TokenId}] is gone, denying control on {Count} live connection(s)", - tokenId, clients.Length); - paused = true; - limits = null; - } - else - { - paused = token.ShockerControlPaused; - limits = ApiTokenControlLimits.FromToken(token); - } + .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null); } catch (Exception e) { - _logger.LogError(e, "Error fetching api token [{TokenId}] limits for live control connections", tokenId); + _logger.LogError(e, "Error fetching api token [{TokenId}] for live control connections", tokenId); + return; + } + + if (token is null || !token.CanControlShockers(DateTime.UtcNow)) + { + // Deleted, expired, its owner deactivated, or it lost shockers.use: the connections may not go on. + _logger.LogDebug("API token [{TokenId}] may no longer control, closing {Count} live connection(s)", + tokenId, clients.Length); + await Task.WhenAll(clients.Select(client => client.Revoke())); return; } foreach (var client in clients) - client.ApplyTokenLimits(paused, limits); + client.ApplyToken(token); } } diff --git a/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs b/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs new file mode 100644 index 00000000..a005ff7e --- /dev/null +++ b/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs @@ -0,0 +1,85 @@ +using System.Collections.Concurrent; +using OpenShock.Common.Services.RedisPubSub; +using OpenShock.Internal.Common.Utils; +using OpenShock.LiveControlGateway.Controllers; +using StackExchange.Redis; + +namespace OpenShock.LiveControlGateway.PubSub; + +/// +/// The live control connections open on this gateway, closed when the session or account they belong to is +/// revoked. A live control socket is authenticated once, when it opens, so without this a logged out session or +/// a deactivated account could keep controlling through a socket opened before. +/// +/// +/// API token changes are handled per token by . A lost message is covered +/// by each connection re-checking itself against the database at a bounded interval. +/// +public sealed class LiveControlRevocationSubscriber : IHostedService +{ + private readonly ISubscriber _subscriber; + private readonly ILogger _logger; + private readonly ConcurrentDictionary _connections = new(); + + /// + /// DI constructor + /// + /// + /// + public LiveControlRevocationSubscriber(IConnectionMultiplexer connectionMultiplexer, ILogger logger) + { + _subscriber = connectionMultiplexer.GetSubscriber(); + _logger = logger; + } + + /// Start closing this connection when its session or account is revoked. + public void Register(LiveControlController connection) => _connections.TryAdd(connection, 0); + + /// Stop tracking this connection. + public void Unregister(LiveControlController connection) => _connections.TryRemove(connection, out _); + + /// + public async Task StartAsync(CancellationToken cancellationToken) + { + await _subscriber.SubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); + await _subscriber.SubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); + } + + /// + public async Task StopAsync(CancellationToken cancellationToken) + { + await _subscriber.UnsubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); + await _subscriber.UnsubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); + } + + private void HandleSessionRevoked(RedisChannel _, RedisValue message) + { + var sessionId = (string?)message; + if (string.IsNullOrEmpty(sessionId)) return; + + Revoke(c => c.SessionId == sessionId, "session revoked"); + } + + private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) + { + if (!Guid.TryParse((string?)message, out var userId)) return; + + // The user's own connections, and everyone controlling a hub they own through a share. + Revoke(c => c.UserId == userId || c.DeviceOwnerId == userId, "account revoked"); + } + + private void Revoke(Func predicate, string reason) + { + var closed = 0; + foreach (var connection in _connections.Keys) + { + if (!predicate(connection)) continue; + + _connections.TryRemove(connection, out _); + OsTask.Run(connection.Revoke); + closed++; + } + + if (closed > 0) _logger.LogDebug("Closing {Count} live control connection(s): {Reason}", closed, reason); + } +} From 0fe0933f394b41ff9095614b767807669ef25345 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 17:00:24 +0100 Subject: [PATCH 02/24] ci: pre-pull integration test images to avoid a concurrent-pull race The API and Cron integration test processes pull the same images in parallel; one can be told the pull succeeded and then fail container creation with 'No such image'. --- .github/workflows/ci-build.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index c796cdb2..34e76c3f 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -39,6 +39,20 @@ jobs: with: dotnet-version: '${{ env.DOTNET_VERSION }}' + # The API and Cron integration test assemblies run as parallel processes against one Docker daemon. If both + # pull the same image at once, one of them can be told the pull succeeded and then get "No such image" when it + # creates the container. Pulling up front means neither has to. Keep in step with IntegrationTests.Shared/ContainerImages.cs. + - name: Pre-pull test container images + run: | + set -euo pipefail + for image in \ + ghcr.io/openshock/postgres-timescaledb:2.32.1-18.7-trixie \ + ghcr.io/dragonflydb/dragonfly:latest \ + axllent/mailpit:latest; do + docker pull --quiet "$image" & + done + wait + - name: Run tests run: | set -euo pipefail From c5faf85c6edd9d6e2d820c18649d8c3d7d5eadde Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 18:35:34 +0100 Subject: [PATCH 03/24] fix(lcg): stop stale refreshes from restoring revoked live control state Token state and shocker permissions are refreshed by several writers (the token subscriber, hub updates and periodic revalidation) that each read the database and then install the result. A read that started earlier but finished later could overwrite a newer pause or share removal until the next revalidation. Each read now takes a generation before it starts, and a result is installed only if no later read has already installed its own. Permissions are kept as a FrozenDictionary that is swapped whole, so frames read it without a lock. Revalidation also checks that the owner of a shared hub is not deactivated, so a lost owner revocation message still closes recipients' sockets. CI: wait on each image pull separately so a failed pull fails the step. --- .github/workflows/ci-build.yml | 7 +- .../Controllers/LiveControlController.cs | 74 ++++++++++++++++--- .../PubSub/ApiTokenUpdateSubscriber.cs | 5 +- 3 files changed, 75 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 34e76c3f..f2a1f341 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -45,13 +45,18 @@ jobs: - name: Pre-pull test container images run: | set -euo pipefail + pids=() for image in \ ghcr.io/openshock/postgres-timescaledb:2.32.1-18.7-trixie \ ghcr.io/dragonflydb/dragonfly:latest \ axllent/mailpit:latest; do docker pull --quiet "$image" & + pids+=("$!") + done + # A bare `wait` returns 0 even when a pull failed; waiting on each pid propagates its exit code. + for pid in "${pids[@]}"; do + wait "$pid" done - wait - name: Run tests run: | diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index e2aa910e..76a300b9 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -1,4 +1,5 @@ -using System.Diagnostics; +using System.Collections.Frozen; +using System.Diagnostics; using System.Net.WebSockets; using System.Text.Json; using Microsoft.AspNetCore.Authorization; @@ -65,7 +66,7 @@ public sealed class LiveControlController : WebsocketBaseController - private volatile TokenState? _tokenState; + private TokenState? _tokenState; private sealed record TokenState(bool Paused, ApiTokenControlLimits Limits, DateTime? ValidUntil) { @@ -91,6 +92,19 @@ public static TokenState From(ApiToken token) => private int _revalidating; private long _lastValidated; + /// + /// The token state and the shocker permissions each have more than one writer that reads the database and then + /// installs what it read (the token subscriber, and revalidation). Each + /// read takes a generation before it starts, and a result is installed only if no read that started later has + /// already installed its own. Without that, a slow read of the old state could overwrite a newer pause or share + /// removal until the next revalidation. + /// + private readonly Lock _stateLock = new(); + private static ulong _tokenReadGeneration; + private ulong _tokenAppliedGeneration; + private ulong _permissionsReadGeneration; + private ulong _permissionsAppliedGeneration; + /// /// The id the authenticating session is stored under, null when authenticated via an API token. /// @@ -112,7 +126,10 @@ public static TokenState From(ApiToken token) => public Guid? HubId { get; private set; } private Device? _device; - private Dictionary _sharedShockers = new(); + /// + /// Replaced as a whole, never changed in place, so frames read it without a lock. See . + /// + private FrozenDictionary _sharedShockers = FrozenDictionary.Empty; private byte _tps = 10; private long _pingTimestamp = Stopwatch.GetTimestamp(); private ushort _latencyMs; @@ -180,10 +197,24 @@ public async Task UpdatePermissions(OpenShockContext db) Logger.LogDebug("Updating shared permissions for hub [{HubId}] for user [{User}]", Id, _currentUser.Id); + var generation = Interlocked.Increment(ref _permissionsReadGeneration); + var permissions = (await QueryPermissions(db)).ToFrozenDictionary(); + + lock (_stateLock) + { + // A refresh that started after this one has already installed what it read. + if (generation <= _permissionsAppliedGeneration) return; + _permissionsAppliedGeneration = generation; + _sharedShockers = permissions; + } + } + + private async Task> QueryPermissions(OpenShockContext db) + { if (_device!.OwnerId == _currentUser.Id) { Logger.LogTrace("User is owner of hub"); - _sharedShockers = await db.Shockers.Where(x => x.DeviceId == Id && x.Device.Owner.UserDeactivation == null).ToDictionaryAsync(x => x.Id, x => + return await db.Shockers.Where(x => x.DeviceId == Id && x.Device.Owner.UserDeactivation == null).ToDictionaryAsync(x => x.Id, x => new LiveShockerPermission { Paused = x.IsPaused, @@ -197,10 +228,9 @@ public async Task UpdatePermissions(OpenShockContext db) Live = x.AllowLiveControl } }); - return; } - _sharedShockers = await db.UserShares + return await db.UserShares .Where(x => x.Shocker.DeviceId == Id && x.SharedWithUserId == _currentUser.Id && x.Shocker.Device.Owner.UserDeactivation == null) .Select(x => new { @@ -320,15 +350,29 @@ public void OnActionExecuting(ActionExecutingContext context) } } + /// + /// Take a generation for a read of an API token. Call before the database read whose result is passed to + /// . Shared by all connections: a connection only compares generations with the last + /// one it applied, so one increasing sequence serves them all, and one read can be applied to many connections. + /// + public static ulong BeginTokenRead() => Interlocked.Increment(ref _tokenReadGeneration); + /// /// Apply the current state of the authenticating API token to this connection, pushed by the /// when the token changed. The caller has checked it may still control. + /// Ignored if a read that started later, per , has already been applied. /// /// + /// From , taken before was read. [NonAction] - public void ApplyToken(ApiToken token) + public void ApplyToken(ApiToken token, ulong generation) { - _tokenState = TokenState.From(token); + lock (_stateLock) + { + if (generation <= _tokenAppliedGeneration) return; + _tokenAppliedGeneration = generation; + _tokenState = TokenState.From(token); + } } /// @@ -393,15 +437,27 @@ private async Task Revalidate() } private async Task IsStillAuthenticated(IServiceProvider services, OpenShockContext db) + { + if (!await IsCallerStillAuthenticated(services, db)) return false; + + // Someone controlling a shared hub loses it when the owner is deactivated. The owner's revocation message + // closes those connections; this covers that message being lost. + var ownerId = _device!.OwnerId; + return ownerId == _currentUser.Id || + await db.Users.AnyAsync(u => u.Id == ownerId && u.UserDeactivation == null, LinkedToken); + } + + private async Task IsCallerStillAuthenticated(IServiceProvider services, OpenShockContext db) { if (_tokenId is { } tokenId) { + var generation = BeginTokenRead(); var token = await db.ApiTokens .AsNoTracking() .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null, LinkedToken); if (token is null || !token.CanControlShockers(DateTime.UtcNow)) return false; - ApplyToken(token); + ApplyToken(token, generation); return true; } diff --git a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs b/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs index f71409e5..aaaab4b4 100644 --- a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs +++ b/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs @@ -94,6 +94,9 @@ private async Task OnTokenUpdate(Guid tokenId) if (clients.Length == 0) return; + // Taken before the read, so a revalidation that read the token earlier cannot overwrite this result. + var generation = LiveControlController.BeginTokenRead(); + ApiToken? token; try { @@ -119,6 +122,6 @@ private async Task OnTokenUpdate(Guid tokenId) } foreach (var client in clients) - client.ApplyToken(token); + client.ApplyToken(token, generation); } } From ab86504cfe3fce8c3c61237b505f6e0bad237dac Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 18:37:59 +0100 Subject: [PATCH 04/24] ci: drop the integration test image pre-pull from this branch Restores ci-build.yml to its state at the branch point; the change does not belong in the live control revocation fix. --- .github/workflows/ci-build.yml | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index f2a1f341..c796cdb2 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -39,25 +39,6 @@ jobs: with: dotnet-version: '${{ env.DOTNET_VERSION }}' - # The API and Cron integration test assemblies run as parallel processes against one Docker daemon. If both - # pull the same image at once, one of them can be told the pull succeeded and then get "No such image" when it - # creates the container. Pulling up front means neither has to. Keep in step with IntegrationTests.Shared/ContainerImages.cs. - - name: Pre-pull test container images - run: | - set -euo pipefail - pids=() - for image in \ - ghcr.io/openshock/postgres-timescaledb:2.32.1-18.7-trixie \ - ghcr.io/dragonflydb/dragonfly:latest \ - axllent/mailpit:latest; do - docker pull --quiet "$image" & - pids+=("$!") - done - # A bare `wait` returns 0 even when a pull failed; waiting on each pid propagates its exit code. - for pid in "${pids[@]}"; do - wait "$pid" - done - - name: Run tests run: | set -euo pipefail From d70d3d20fa5276176340443c218a8763438dfb1f Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 19:22:15 +0100 Subject: [PATCH 05/24] feat: add a shared connection authority for long-lived connections A long-lived connection is authenticated once and then holds its own copy of what it may do. Each kind of connection kept that copy current in its own way, with its own Redis handlers, its own periodic check and its own copy of the rules. This adds one component for all of them. A registry tracks the connections open on an instance by what they depend on, and a single resolver decides whether a connection may go on and what it may do. A connection looks again when it registers, when a change that can affect it is announced, and when time has passed. Only one look runs per connection at a time and a request during one makes it run once more, so an older read cannot replace a newer one. Nothing uses it yet. One-off control and the resolver share one query for who may control which shocker. --- .../Tests/GrantResolverTests.cs | 375 ++++++++++++++++++ .../ConnectionAuthorityRegistryTests.cs | 312 +++++++++++++++ .../ConnectionSubjectTests.cs | 54 +++ .../AuthorityChangeSubscriber.cs | 81 ++++ .../ConnectionAuthorityRegistry.cs | 168 ++++++++ .../ConnectionAuthoritySweeper.cs | 46 +++ .../ConnectionAuthority/ConnectionHandle.cs | 169 ++++++++ .../ConnectionAuthority/ConnectionSubject.cs | 86 ++++ Common/ConnectionAuthority/Grant.cs | 52 +++ Common/ConnectionAuthority/GrantResolver.cs | 121 ++++++ .../IAuthorizedConnection.cs | 20 + Common/ConnectionAuthority/IGrantResolver.cs | 11 + Common/ConnectionAuthority/SessionIds.cs | 11 + Common/DeviceControl/ShockerAccessQueries.cs | 55 +++ Common/OpenShockServiceHelper.cs | 16 + Common/Services/ControlSender.cs | 37 +- 16 files changed, 1578 insertions(+), 36 deletions(-) create mode 100644 API.IntegrationTests/Tests/GrantResolverTests.cs create mode 100644 Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs create mode 100644 Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs create mode 100644 Common/ConnectionAuthority/AuthorityChangeSubscriber.cs create mode 100644 Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs create mode 100644 Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs create mode 100644 Common/ConnectionAuthority/ConnectionHandle.cs create mode 100644 Common/ConnectionAuthority/ConnectionSubject.cs create mode 100644 Common/ConnectionAuthority/Grant.cs create mode 100644 Common/ConnectionAuthority/GrantResolver.cs create mode 100644 Common/ConnectionAuthority/IAuthorizedConnection.cs create mode 100644 Common/ConnectionAuthority/IGrantResolver.cs create mode 100644 Common/ConnectionAuthority/SessionIds.cs create mode 100644 Common/DeviceControl/ShockerAccessQueries.cs diff --git a/API.IntegrationTests/Tests/GrantResolverTests.cs b/API.IntegrationTests/Tests/GrantResolverTests.cs new file mode 100644 index 00000000..c8dec739 --- /dev/null +++ b/API.IntegrationTests/Tests/GrantResolverTests.cs @@ -0,0 +1,375 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.ConnectionAuthority; +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.Session; +using OpenShock.IntegrationTests.Shared; +using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// What an open connection may do, for the connections the gateway holds (live control and hub sockets), which no +/// test reaches end to end. Hub connections are covered through real connections in . +/// +public sealed class GrantResolverTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + // --- Live control: what may be controlled --- + + [Test] + public async Task LiveControl_Owner_GetsTheirShockersWithTheShockersOwnSettings() + { + var owner = await CreateUser("grantowner"); + var (deviceId, shockerId) = await CreateShockerOnDevice(owner.Id); + await Db(db => db.Shockers.Where(s => s.Id == shockerId) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.MaxIntensity, (byte?)40).SetProperty(x => x.AllowSound, false))); + + var grant = await Resolve(LiveControlBySession(owner, deviceId, owner.Id)); + + await Assert.That(grant).IsNotNull(); + await Assert.That(grant!.Token).IsNull(); + var shocker = grant.Shockers![shockerId]; + await Assert.That(shocker.Paused).IsFalse(); + await Assert.That(shocker.PermsAndLimits.Intensity).IsEqualTo((byte?)40); + await Assert.That(shocker.PermsAndLimits.Sound).IsFalse(); + await Assert.That(shocker.PermsAndLimits.Shock).IsTrue(); + } + + [Test] + public async Task LiveControl_Recipient_GetsTheTighterOfShockerAndShare() + { + var owner = await CreateUser("grantshowner"); + var recipient = await CreateUser("grantshrecip"); + var (deviceId, shockerId) = await CreateShockerOnDevice(owner.Id); + var (_, notSharedShockerId) = await CreateShockerOnDevice(owner.Id, deviceId); + await Db(db => db.Shockers.Where(s => s.Id == shockerId) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.MaxIntensity, (byte?)40).SetProperty(x => x.MaxDuration, (ushort?)null))); + await Share(shockerId, recipient.Id, share => + { + share.AllowShock = false; + share.MaxIntensity = 60; + share.MaxDuration = 2000; + }); + + var grant = await Resolve(LiveControlBySession(recipient, deviceId, owner.Id)); + + await Assert.That(grant!.Shockers!.ContainsKey(notSharedShockerId)).IsFalse(); + var shocker = grant.Shockers[shockerId]; + await Assert.That(shocker.PermsAndLimits.Shock).IsFalse(); + await Assert.That(shocker.PermsAndLimits.Vibrate).IsTrue(); + await Assert.That(shocker.PermsAndLimits.Intensity).IsEqualTo((byte?)40); + await Assert.That(shocker.PermsAndLimits.Duration).IsEqualTo((ushort?)2000); + } + + [Test] + public async Task LiveControl_Recipient_PausedByEitherSide() + { + var owner = await CreateUser("grantpowner"); + var recipient = await CreateUser("grantprecip"); + var (deviceId, sharePaused) = await CreateShockerOnDevice(owner.Id); + var (_, shockerPaused) = await CreateShockerOnDevice(owner.Id, deviceId); + await Share(sharePaused, recipient.Id, share => share.IsPaused = true); + await Share(shockerPaused, recipient.Id); + await Db(db => db.Shockers.Where(s => s.Id == shockerPaused).ExecuteUpdateAsync(s => s.SetProperty(x => x.IsPaused, true))); + + var grant = await Resolve(LiveControlBySession(recipient, deviceId, owner.Id)); + + await Assert.That(grant!.Shockers![sharePaused].Paused).IsTrue(); + await Assert.That(grant.Shockers[shockerPaused].Paused).IsTrue(); + } + + [Test] + public async Task LiveControl_RecipientWhoLostEveryShare_StaysConnectedWithNothingToControl() + { + var owner = await CreateUser("grantlostowner"); + var recipient = await CreateUser("grantlostrecip"); + var (deviceId, shockerId) = await CreateShockerOnDevice(owner.Id); + await Share(shockerId, recipient.Id); + await Db(db => db.UserShares.Where(s => s.ShockerId == shockerId).ExecuteDeleteAsync()); + + var grant = await Resolve(LiveControlBySession(recipient, deviceId, owner.Id)); + + await Assert.That(grant).IsNotNull(); + await Assert.That(grant!.Shockers!.Count).IsEqualTo(0); + } + + // --- Live control: whether the connection may go on at all --- + + [Test] + public async Task LiveControl_Recipient_OwnerDeactivated_MayNotGoOn() + { + var owner = await CreateUser("grantdeactowner"); + var recipient = await CreateUser("grantdeactrecip"); + var (deviceId, shockerId) = await CreateShockerOnDevice(owner.Id); + await Share(shockerId, recipient.Id); + await Deactivate(owner.Id); + + await Assert.That(await Resolve(LiveControlBySession(recipient, deviceId, owner.Id))).IsNull(); + } + + [Test] + public async Task LiveControl_Session_Removed_MayNotGoOn() + { + var owner = await CreateUser("grantsessgone"); + var (deviceId, _) = await CreateShockerOnDevice(owner.Id); + var subject = LiveControlBySession(owner, deviceId, owner.Id); + await Assert.That(await Resolve(subject)).IsNotNull(); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService().DeleteSessionsByUserIdAsync(owner.Id); + } + + await Assert.That(await Resolve(subject)).IsNull(); + } + + [Test] + public async Task LiveControl_Session_AccountDeactivatedWithTheSessionLeftBehind_MayNotGoOn() + { + var owner = await CreateUser("grantsessdeact"); + var (deviceId, _) = await CreateShockerOnDevice(owner.Id); + await Deactivate(owner.Id); + + await Assert.That(await Resolve(LiveControlBySession(owner, deviceId, owner.Id))).IsNull(); + } + + [Test] + public async Task LiveControl_Session_OfAnotherUser_MayNotGoOn() + { + var owner = await CreateUser("grantsessmix"); + var other = await CreateUser("grantsessmixother"); + var (deviceId, _) = await CreateShockerOnDevice(owner.Id); + + var subject = LiveControlBySession(owner, deviceId, owner.Id) with { SessionToken = other.SessionToken }; + + await Assert.That(await Resolve(subject)).IsNull(); + } + + [Test] + public async Task LiveControl_Token_CarriesItsPauseStateAndLimits() + { + var owner = await CreateUser("granttok"); + var (deviceId, _) = await CreateShockerOnDevice(owner.Id); + var (tokenId, _) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "grant-live"); + var validUntil = DateTime.UtcNow.AddHours(1); + await Db(db => db.ApiTokens.Where(t => t.Id == tokenId).ExecuteUpdateAsync(s => s + .SetProperty(t => t.ShockerControlPaused, true) + .SetProperty(t => t.ShockerControlIntensityMax, (byte)30) + .SetProperty(t => t.ValidUntil, validUntil))); + + var grant = await Resolve(LiveControlByToken(owner.Id, tokenId, deviceId, owner.Id)); + + await Assert.That(grant!.Token!.Paused).IsTrue(); + await Assert.That(grant.Token.Limits.IntensityMax).IsEqualTo((byte)30); + await Assert.That(grant.ExpiresAt).IsNotNull(); + await Assert.That(grant.IsExpired(validUntil.AddMinutes(1))).IsTrue(); + await Assert.That(grant.IsExpired(validUntil.AddMinutes(-1))).IsFalse(); + } + + public enum TokenChange + { + Deleted, + Expired, + LostShockersUse, + OwnerDeactivated + } + + [Test] + [Arguments(TokenChange.Deleted)] + [Arguments(TokenChange.Expired)] + [Arguments(TokenChange.LostShockersUse)] + [Arguments(TokenChange.OwnerDeactivated)] + public async Task LiveControl_Token_ThatMayNoLongerControl_MayNotGoOn(TokenChange change) + { + var owner = await CreateUser("granttokgone"); + var (deviceId, _) = await CreateShockerOnDevice(owner.Id); + var (tokenId, _) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "grant-live-gone"); + var subject = LiveControlByToken(owner.Id, tokenId, deviceId, owner.Id); + await Assert.That(await Resolve(subject)).IsNotNull(); + + switch (change) + { + case TokenChange.Deleted: + await Db(db => db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync()); + break; + case TokenChange.Expired: + var expired = DateTime.UtcNow.AddMinutes(-1); + await Db(db => db.ApiTokens.Where(t => t.Id == tokenId).ExecuteUpdateAsync(s => s.SetProperty(t => t.ValidUntil, expired))); + break; + case TokenChange.LostShockersUse: + await Db(async db => + { + var token = await db.ApiTokens.FirstAsync(t => t.Id == tokenId); + token.Permissions = [PermissionType.Shockers_Edit]; + return await db.SaveChangesAsync(); + }); + break; + case TokenChange.OwnerDeactivated: + await Deactivate(owner.Id); + break; + default: + throw new ArgumentOutOfRangeException(nameof(change), change, null); + } + + await Assert.That(await Resolve(subject)).IsNull(); + } + + [Test] + public async Task HubConnection_TokenWithoutShockersUse_MayGoOn() + { + // Unlike live control, a hub connection serves more than control and checks the permission per call. + var owner = await CreateUser("grantsignalr"); + var (tokenId, _) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "grant-hub", [PermissionType.Shockers_Edit]); + + var grant = await Resolve(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = owner.Id, ApiTokenId = tokenId }); + + await Assert.That(grant).IsNotNull(); + await Assert.That(grant!.Shockers).IsNull(); + } + + [Test] + public async Task LiveControl_WithoutSessionOrToken_MayNotGoOn() + { + var owner = await CreateUser("grantanon"); + var (deviceId, _) = await CreateShockerOnDevice(owner.Id); + + var subject = new ConnectionSubject { Kind = ConnectionKind.LiveControl, UserId = owner.Id, DeviceId = deviceId, DeviceOwnerId = owner.Id }; + + await Assert.That(await Resolve(subject)).IsNull(); + } + + // --- The hub's own socket --- + + public enum HubChange + { + TokenRegenerated, + Deleted, + OwnerDeactivated + } + + [Test] + [Arguments(HubChange.TokenRegenerated)] + [Arguments(HubChange.Deleted)] + [Arguments(HubChange.OwnerDeactivated)] + public async Task HubSocket_MayGoOnOnlyWhileTheHubCouldStillConnect(HubChange change) + { + var owner = await CreateUser("granthub"); + var (deviceId, hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id); + var subject = new ConnectionSubject { Kind = ConnectionKind.HubSocket, DeviceId = deviceId, DeviceOwnerId = owner.Id, HubToken = hubToken }; + await Assert.That(await Resolve(subject)).IsNotNull(); + + switch (change) + { + case HubChange.TokenRegenerated: + await Db(db => db.Devices.Where(d => d.Id == deviceId).ExecuteUpdateAsync(s => s.SetProperty(d => d.Token, new string('x', 256)))); + break; + case HubChange.Deleted: + await Db(db => db.Devices.Where(d => d.Id == deviceId).ExecuteDeleteAsync()); + break; + case HubChange.OwnerDeactivated: + await Deactivate(owner.Id); + break; + default: + throw new ArgumentOutOfRangeException(nameof(change), change, null); + } + + await Assert.That(await Resolve(subject)).IsNull(); + } + + // --- Helpers --- + + private Task CreateUser(string prefix) => + TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), "SecurePassword123#"); + + private static ConnectionSubject LiveControlBySession(AuthenticatedUser user, Guid deviceId, Guid ownerId) => new() + { + Kind = ConnectionKind.LiveControl, + UserId = user.Id, + SessionToken = user.SessionToken, + SessionId = SessionIds.FromToken(user.SessionToken), + DeviceId = deviceId, + DeviceOwnerId = ownerId + }; + + private static ConnectionSubject LiveControlByToken(Guid userId, Guid tokenId, Guid deviceId, Guid ownerId) => new() + { + Kind = ConnectionKind.LiveControl, + UserId = userId, + ApiTokenId = tokenId, + DeviceId = deviceId, + DeviceOwnerId = ownerId + }; + + private async Task Resolve(ConnectionSubject subject) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + return await scope.ServiceProvider.GetRequiredService().ResolveAsync(subject, CancellationToken.None); + } + + private async Task Db(Func> action) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + await action(scope.ServiceProvider.GetRequiredService()); + } + + /// A shocker on a new hub of , or on when given. + private async Task<(Guid DeviceId, Guid ShockerId)> CreateShockerOnDevice(Guid ownerId, Guid? onDeviceId = null) + { + if (onDeviceId is null) + { + var created = await CreateShocker(WebApplicationFactory, ownerId, "Granted"); + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return (await db.Shockers.Where(s => s.Id == created).Select(s => s.DeviceId).FirstAsync(), created); + } + + var shockerId = Guid.CreateVersion7(); + await Db(db => + { + db.Shockers.Add(new Shocker + { + Id = shockerId, + Name = "Granted too", + Model = ShockerModelType.CaiXianlin, + RfId = 4321, + DeviceId = onDeviceId.Value + }); + return db.SaveChangesAsync(); + }); + return (onDeviceId.Value, shockerId); + } + + private Task Share(Guid shockerId, Guid recipientId, Action? configure = null) => Db(db => + { + var share = new UserShare + { + SharedWithUserId = recipientId, + ShockerId = shockerId, + AllowShock = true, + AllowVibrate = true, + AllowSound = true, + AllowLiveControl = true, + IsPaused = false + }; + configure?.Invoke(share); + db.UserShares.Add(share); + return db.SaveChangesAsync(); + }); + + /// Written straight to the database: no sessions are deleted and nothing is announced. + private Task Deactivate(Guid userId) => Db(db => + { + db.UserDeactivations.Add(new UserDeactivation + { + DeactivatedUserId = userId, + DeactivatedByUserId = userId, + DeleteLater = false + }); + return db.SaveChangesAsync(); + }); +} diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs new file mode 100644 index 00000000..7d1ff9ef --- /dev/null +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -0,0 +1,312 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using OpenShock.Common.ConnectionAuthority; + +namespace OpenShock.Common.Tests.ConnectionAuthority; + +public sealed class ConnectionAuthorityRegistryTests +{ + private sealed class FakeResolver : IGrantResolver + { + /// What the next look returns. Replace to simulate a change in the database. + public Func> Resolve { get; set; } = _ => Task.FromResult(Grant.Empty); + + public int Calls; + + public Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken) + { + Interlocked.Increment(ref Calls); + return Resolve(subject); + } + } + + private sealed class FakeConnection : IAuthorizedConnection + { + public bool AcceptGrants { get; set; } = true; + public int Closed; + public Grant? LastApplied; + + public bool TryApplyGrant(Grant grant) + { + LastApplied = grant; + return AcceptGrants; + } + + public Task CloseAsync() + { + Interlocked.Increment(ref Closed); + return Task.CompletedTask; + } + } + + private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Create(TimeSpan? interval = null) + { + var resolver = new FakeResolver(); + var services = new ServiceCollection(); + services.AddScoped(_ => resolver); + var provider = services.BuildServiceProvider(); + + var options = Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions { Interval = interval ?? TimeSpan.FromMinutes(1) }); + var registry = new ConnectionAuthorityRegistry(provider.GetRequiredService(), options, NullLogger.Instance); + return (registry, resolver); + } + + private static ConnectionSubject LiveControl(Guid? userId = null, Guid? tokenId = null, Guid? deviceId = null, Guid? ownerId = null) => new() + { + Kind = ConnectionKind.LiveControl, + UserId = userId ?? Guid.NewGuid(), + ApiTokenId = tokenId, + DeviceId = deviceId ?? Guid.NewGuid(), + DeviceOwnerId = ownerId ?? Guid.NewGuid() + }; + + /// Signals only start a look; this waits for it (and any rerun) to finish. + private static Task Settle(ConnectionHandle handle) => handle.WhenIdleAsync(); + + [Test] + public async Task Register_LooksOnceAndKeepsTheGrant() + { + var (registry, resolver) = Create(); + var grant = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(1) }; + resolver.Resolve = _ => Task.FromResult(grant); + var connection = new FakeConnection(); + + var (handle, result) = await registry.RegisterAsync(LiveControl(), connection); + + await Assert.That(result).IsEqualTo(RefreshResult.Valid); + await Assert.That(handle.Grant).IsSameReferenceAs(grant); + await Assert.That(handle.IsRevoked).IsFalse(); + await Assert.That(connection.Closed).IsEqualTo(0); + await Assert.That(registry.Count).IsEqualTo(1); + } + + [Test] + public async Task Register_NothingGranted_ClosesAndStopsTracking() + { + var (registry, resolver) = Create(); + resolver.Resolve = _ => Task.FromResult(null); + var connection = new FakeConnection(); + + var (handle, result) = await registry.RegisterAsync(LiveControl(), connection); + + await Assert.That(result).IsEqualTo(RefreshResult.Revoked); + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(connection.Closed).IsEqualTo(1); + await Assert.That(registry.Count).IsEqualTo(0); + } + + [Test] + public async Task Refresh_ConnectionCannotGoOnUnderTheGrant_Closes() + { + var (registry, _) = Create(); + var connection = new FakeConnection { AcceptGrants = false }; + + var (handle, result) = await registry.RegisterAsync(LiveControl(), connection); + + await Assert.That(result).IsEqualTo(RefreshResult.Revoked); + await Assert.That(handle.Grant).IsNull(); + await Assert.That(connection.Closed).IsEqualTo(1); + } + + [Test] + public async Task Refresh_LookFails_KeepsTheGrantAndTheConnection() + { + var (registry, resolver) = Create(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(LiveControl(), connection); + var before = handle.Grant; + + resolver.Resolve = _ => throw new InvalidOperationException("database is down"); + var result = await handle.RefreshAsync(); + + await Assert.That(result).IsEqualTo(RefreshResult.Failed); + await Assert.That(handle.Grant).IsSameReferenceAs(before); + await Assert.That(handle.IsRevoked).IsFalse(); + await Assert.That(connection.Closed).IsEqualTo(0); + await Assert.That(registry.Count).IsEqualTo(1); + } + + [Test] + public async Task Signal_ReplacesTheGrantOfAffectedConnectionsOnly() + { + var (registry, resolver) = Create(); + var tokenId = Guid.NewGuid(); + var (affected, _) = await registry.RegisterAsync(LiveControl(tokenId: tokenId), new FakeConnection()); + var (other, _) = await registry.RegisterAsync(LiveControl(tokenId: Guid.NewGuid()), new FakeConnection()); + var otherBefore = other.Grant; + + var changed = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(1) }; + resolver.Resolve = _ => Task.FromResult(changed); + registry.Signal(new AuthorityChange(AuthorityChangeKind.ApiToken, tokenId)); + await Settle(affected); + + await Assert.That(affected.Grant).IsSameReferenceAs(changed); + await Assert.That(other.Grant).IsSameReferenceAs(otherBefore); + } + + [Test] + public async Task Signal_NothingGrantedAnymore_ClosesOnce() + { + var (registry, resolver) = Create(); + var userId = Guid.NewGuid(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(LiveControl(userId: userId), connection); + + resolver.Resolve = _ => Task.FromResult(null); + registry.Signal(new AuthorityChange(AuthorityChangeKind.User, userId)); + registry.Signal(new AuthorityChange(AuthorityChangeKind.User, userId)); + await Settle(handle); + + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(connection.Closed).IsEqualTo(1); + await Assert.That(await handle.RefreshAsync()).IsEqualTo(RefreshResult.Revoked); + await Assert.That(connection.Closed).IsEqualTo(1); + } + + [Test] + public async Task SignalSession_ReachesTheConnectionsOfThatSession() + { + var (registry, resolver) = Create(); + var connection = new FakeConnection(); + var subject = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), SessionToken = "token", SessionId = "session-a" }; + var (handle, _) = await registry.RegisterAsync(subject, connection); + + resolver.Resolve = _ => Task.FromResult(null); + registry.SignalSession("session-b"); + await Settle(handle); + await Assert.That(handle.IsRevoked).IsFalse(); + + registry.SignalSession("session-a"); + await Settle(handle); + await Assert.That(handle.IsRevoked).IsTrue(); + } + + /// + /// The case the per-connection ordering exists for: a look that read the old state is still running when the + /// change is announced. It must not have the last word. + /// + [Test] + public async Task Signal_DuringARunningLook_LooksAgainAndTheLaterReadWins() + { + var (registry, resolver) = Create(); + var deviceId = Guid.NewGuid(); + var (handle, _) = await registry.RegisterAsync(LiveControl(deviceId: deviceId), new FakeConnection()); + + var stale = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(1) }; + var current = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(2) }; + var staleReadStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseStaleRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var reads = 0; + resolver.Resolve = async _ => + { + if (Interlocked.Increment(ref reads) > 1) return current; + + staleReadStarted.SetResult(); + await releaseStaleRead.Task; + return stale; + }; + + var first = handle.RefreshAsync(); + await staleReadStarted.Task; + + // The change is committed and announced while the first look still holds what it read before. + registry.Signal(new AuthorityChange(AuthorityChangeKind.Device, deviceId)); + releaseStaleRead.SetResult(); + await first; + + await Assert.That(reads).IsEqualTo(2); + await Assert.That(handle.Grant).IsSameReferenceAs(current); + } + + [Test] + public async Task EnsureFresh_LooksAgainOnlyOnceTheLastLookIsTooOld() + { + var (registry, resolver) = Create(); + var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + var callsAfterRegister = resolver.Calls; + + await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1)); + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister); + + await handle.EnsureFreshAsync(TimeSpan.Zero); + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); + } + + [Test] + public async Task UpdateSubject_MakesTheNextUseLookAgain() + { + var (registry, resolver) = Create(); + var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + var callsAfterRegister = resolver.Calls; + + var publicShareId = Guid.NewGuid(); + handle.UpdateSubject(handle.Subject with { PublicShareId = publicShareId }); + await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1)); + + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); + await Assert.That(handle.Subject.PublicShareId).IsEqualTo(publicShareId); + } + + [Test] + public async Task Track_DoesNotLookUntilUsed() + { + var (registry, resolver) = Create(); + + var handle = registry.Track(new ConnectionSubject { Kind = ConnectionKind.SignalR, PublicShareId = Guid.NewGuid() }, new FakeConnection()); + + await Assert.That(resolver.Calls).IsEqualTo(0); + await Assert.That(handle.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); + } + + [Test] + public async Task Sweep_LooksAgainAtDuePeriodicConnections_NotAtIdleHubConnections() + { + var (registry, resolver) = Create(interval: TimeSpan.Zero); + var (liveControl, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + var (signalR, _) = await registry.RegisterAsync(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), ApiTokenId = Guid.NewGuid() }, new FakeConnection()); + var callsAfterRegister = resolver.Calls; + + registry.Sweep(DateTime.UtcNow); + await Settle(liveControl); + await Settle(signalR); + + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); + } + + [Test] + public async Task Sweep_ClosesAConnectionWhoseGrantExpired_WhateverItsKind() + { + var (registry, resolver) = Create(); + var expiresAt = DateTime.UtcNow.AddMinutes(5); + resolver.Resolve = _ => Task.FromResult(new Grant { ExpiresAt = expiresAt }); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), ApiTokenId = Guid.NewGuid() }, connection); + + // Not yet: nothing to do for a connection that was just checked. + registry.Sweep(expiresAt.AddMinutes(-1)); + await Settle(handle); + await Assert.That(handle.IsRevoked).IsFalse(); + + // The token reached its expiry, which nothing announces. + resolver.Resolve = _ => Task.FromResult(null); + registry.Sweep(expiresAt.AddSeconds(1)); + await Settle(handle); + + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(connection.Closed).IsEqualTo(1); + } + + [Test] + public async Task Dispose_StopsTrackingWithoutClosing() + { + var (registry, _) = Create(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(LiveControl(), connection); + + handle.Dispose(); + + await Assert.That(registry.Count).IsEqualTo(0); + await Assert.That(connection.Closed).IsEqualTo(0); + } +} diff --git a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs new file mode 100644 index 00000000..48b0f05d --- /dev/null +++ b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs @@ -0,0 +1,54 @@ +using OpenShock.Common.ConnectionAuthority; + +namespace OpenShock.Common.Tests.ConnectionAuthority; + +public sealed class ConnectionSubjectTests +{ + private static readonly Guid User = Guid.NewGuid(); + private static readonly Guid Owner = Guid.NewGuid(); + private static readonly Guid Token = Guid.NewGuid(); + private static readonly Guid Device = Guid.NewGuid(); + private static readonly Guid Share = Guid.NewGuid(); + private static readonly Guid ShareOwner = Guid.NewGuid(); + + private static readonly ConnectionSubject Subject = new() + { + Kind = ConnectionKind.LiveControl, + UserId = User, + ApiTokenId = Token, + DeviceId = Device, + DeviceOwnerId = Owner, + PublicShareId = Share, + PublicShareOwnerId = ShareOwner + }; + + [Test] + public async Task UserChange_AffectsTheUserTheHubOwnerAndTheShareOwner() + { + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, User))).IsTrue(); + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Owner))).IsTrue(); + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, ShareOwner))).IsTrue(); + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Guid.NewGuid()))).IsFalse(); + } + + [Test] + public async Task OtherChanges_AffectOnlyTheirOwnKindOfId() + { + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.ApiToken, Token))).IsTrue(); + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Device, Device))).IsTrue(); + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.PublicShare, Share))).IsTrue(); + + // The same id under another kind is a different thing. + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Device, Token))).IsFalse(); + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.ApiToken, Device))).IsFalse(); + await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.PublicShare, User))).IsFalse(); + } + + [Test] + public async Task AnonymousSubject_IsNotAffectedByAnEmptyId() + { + var guest = new ConnectionSubject { Kind = ConnectionKind.SignalR }; + + await Assert.That(guest.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Guid.Empty))).IsFalse(); + } +} diff --git a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs new file mode 100644 index 00000000..7af8892a --- /dev/null +++ b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs @@ -0,0 +1,81 @@ +using OpenShock.Common.Redis; +using OpenShock.Common.Services.RedisPubSub; +using StackExchange.Redis; + +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// Turns the Redis messages that announce a change in someone's authority into +/// . The same in every service that holds long-lived connections. +/// +/// +/// Hub changes are not handled here: a gateway already listens on each connected hub's own channel and signals +/// from there, and no other service holds connections that depend on a hub. +/// +public sealed class AuthorityChangeSubscriber : IHostedService +{ + private static readonly string LoginSessionKeyPrefix = typeof(LoginSession).FullName + ":"; + + private readonly ISubscriber _subscriber; + private readonly ConnectionAuthorityRegistry _registry; + + public AuthorityChangeSubscriber(IConnectionMultiplexer connectionMultiplexer, ConnectionAuthorityRegistry registry) + { + _subscriber = connectionMultiplexer.GetSubscriber(); + _registry = registry; + } + + 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); + await _subscriber.SubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); + } + + public async Task StopAsync(CancellationToken cancellationToken) + { + await _subscriber.UnsubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); + await _subscriber.UnsubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); + await _subscriber.UnsubscribeAsync(RedisChannels.ApiTokenUpdateAll, HandleApiTokenUpdate); + await _subscriber.UnsubscribeAsync(RedisChannels.PublicShareAccessRevoked, HandlePublicShareAccessRevoked); + await _subscriber.UnsubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); + } + + private void HandleSessionRevoked(RedisChannel _, RedisValue message) + { + var sessionId = (string?)message; + if (!string.IsNullOrEmpty(sessionId)) _registry.SignalSession(sessionId); + } + + private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) + { + if (Guid.TryParse((string?)message, out var userId)) + _registry.Signal(new AuthorityChange(AuthorityChangeKind.User, userId)); + } + + private void HandlePublicShareAccessRevoked(RedisChannel _, RedisValue message) + { + if (Guid.TryParse((string?)message, out var publicShareId)) + _registry.Signal(new AuthorityChange(AuthorityChangeKind.PublicShare, publicShareId)); + } + + 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; + + _registry.Signal(new AuthorityChange(AuthorityChangeKind.ApiToken, tokenId)); + } + + private void HandleKeyExpired(RedisChannel _, RedisValue message) + { + // A session that reached its lifetime: the same as a deleted one for the connections using it. + var key = (string?)message; + if (key is null || !key.StartsWith(LoginSessionKeyPrefix, StringComparison.Ordinal)) return; + + _registry.SignalSession(key[LoginSessionKeyPrefix.Length..]); + } +} diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs new file mode 100644 index 00000000..3108cfaa --- /dev/null +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -0,0 +1,168 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Options; + +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// The long-lived connections open on this instance and what each may currently do. +/// +/// +/// A connection is authenticated once, when it opens, and then lives for as long as the client likes. This is +/// what keeps it from outliving the session, token, share or account it depends on. Three things make a +/// connection look again, and they all end in the same : +/// +/// registering, which closes the gap between authenticating and being reachable by a change; +/// a change announced over Redis, see ; +/// time, for a change whose announcement was lost or a grant that simply expired, see +/// and . +/// +/// Local to the process: every instance tracks its own connections and reacts to the same Redis messages. +/// Lookups scan all connections, which is fine for how rarely authority changes. +/// +public sealed class ConnectionAuthorityRegistry +{ + private readonly ConcurrentDictionary _handles = new(); + /// + /// How many connections may be looked at at once. Connections that opened together come due together, and a + /// change to one account or hub can reach many; this keeps either from taking every database connection. + /// + private const int MaxConcurrentLooks = 32; + + private readonly SemaphoreSlim _lookGate = new(MaxConcurrentLooks, MaxConcurrentLooks); + private readonly IServiceScopeFactory _scopeFactory; + private readonly IOptions _options; + private readonly ILogger _logger; + + public ConnectionAuthorityRegistry(IServiceScopeFactory scopeFactory, IOptions options, ILogger logger) + { + _scopeFactory = scopeFactory; + _options = options; + _logger = logger; + } + + /// How long a successful look stays good before time alone is a reason to look again. + public TimeSpan Interval => _options.Value.Interval; + + public int Count => _handles.Count; + + /// + /// Start tracking a connection without looking at it yet, for one whose first use will. Changes reach it from + /// here on. + /// + public ConnectionHandle Track(ConnectionSubject subject, IAuthorizedConnection connection) + { + var handle = new ConnectionHandle(this, subject, connection); + _handles[handle] = 0; + return handle; + } + + /// + /// Start tracking a connection and look at it once. The connection was authenticated before it was tracked, + /// so a change announced in between found nothing to act on; this look sees it. + /// + /// + /// The handle, and how that first look went. On the connection was already + /// closed and is no longer tracked. + /// + public async Task<(ConnectionHandle Handle, RefreshResult Result)> RegisterAsync(ConnectionSubject subject, IAuthorizedConnection connection) + { + var handle = Track(subject, connection); + var result = await handle.RefreshAsync(); + return (handle, result); + } + + /// + /// Something changed: every connection it can affect looks again. Returns at once, so it is safe to call from + /// a Redis callback. + /// + public void Signal(AuthorityChange change) => RequestRefreshWhere(subject => subject.IsAffectedBy(change)); + + /// A session was deleted or expired. is the id it was stored under. + public void SignalSession(string sessionId) => RequestRefreshWhere(subject => subject.SessionId == sessionId); + + private void RequestRefreshWhere(Func predicate) + { + foreach (var handle in _handles.Keys) + { + if (predicate(handle.Subject)) handle.RequestRefresh(); + } + } + + /// + /// Time as a reason to look again: connections that are checked periodically and are due, and any connection + /// whose grant has reached its expiry. + /// + public void Sweep(DateTime now) + { + var interval = Interval; + foreach (var handle in _handles.Keys) + { + var expired = handle.Grant is { } grant && grant.IsExpired(now); + var due = handle.Subject.Kind != ConnectionKind.SignalR && !handle.WasValidatedWithin(interval); + + if (expired || due) handle.RequestRefreshIfIdle(); + } + } + + internal void Remove(ConnectionHandle handle) => _handles.TryRemove(handle, out _); + + internal async Task ResolveOnceAsync(ConnectionHandle handle) + { + if (handle.IsRevoked) return RefreshResult.Revoked; + + Grant? grant; + await _lookGate.WaitAsync(); + try + { + await using var scope = _scopeFactory.CreateAsyncScope(); + var resolver = scope.ServiceProvider.GetRequiredService(); + grant = await resolver.ResolveAsync(handle.Subject, CancellationToken.None); + } + catch (Exception e) + { + // A transient failure must not drop a legitimate connection. It keeps what it had and is looked at + // again on the next reason to. + _logger.LogWarning(e, "Error while checking what a {Kind} connection may do", handle.Subject.Kind); + return RefreshResult.Failed; + } + finally + { + _lookGate.Release(); + } + + if (grant is not null && handle.Accept(grant)) return RefreshResult.Valid; + + await RevokeAsync(handle); + return RefreshResult.Revoked; + } + + private async Task RevokeAsync(ConnectionHandle handle) + { + if (!handle.MarkRevoked()) return; + Remove(handle); + + var subject = handle.Subject; + _logger.LogInformation( + "Closing {Kind} connection of user [{UserId}] (hub [{DeviceId}], public share [{PublicShareId}]): it may no longer go on", + subject.Kind, subject.UserId, subject.DeviceId, subject.PublicShareId); + + try + { + await handle.CloseConnectionAsync(); + } + catch (Exception e) + { + // It may already be closing on its own. The revoked flag stops everything either way. + _logger.LogDebug(e, "Error while closing a revoked connection"); + } + } +} + +public sealed class ConnectionAuthorityOptions +{ + /// + /// How long a connection's last successful check stays good. Changes normally reach a connection at once + /// through Redis; this bounds how long one can go on when that message was lost. + /// + public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); +} diff --git a/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs b/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs new file mode 100644 index 00000000..699e5ba6 --- /dev/null +++ b/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs @@ -0,0 +1,46 @@ +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// Makes time a reason for connections to look at what they may do again, see +/// . +/// +public sealed class ConnectionAuthoritySweeper : BackgroundService +{ + private static readonly TimeSpan MaxPeriod = TimeSpan.FromSeconds(5); + private static readonly TimeSpan MinPeriod = TimeSpan.FromMilliseconds(250); + + private readonly ConnectionAuthorityRegistry _registry; + private readonly ILogger _logger; + + public ConnectionAuthoritySweeper(ConnectionAuthorityRegistry registry, ILogger logger) + { + _registry = registry; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + // Often enough that a due connection is not left waiting for long, without spinning on a short interval. + var period = TimeSpan.FromTicks(Math.Clamp(_registry.Interval.Ticks / 2, MinPeriod.Ticks, MaxPeriod.Ticks)); + using var timer = new PeriodicTimer(period); + + try + { + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + try + { + _registry.Sweep(DateTime.UtcNow); + } + catch (Exception e) + { + _logger.LogError(e, "Error while sweeping connections"); + } + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + // Shutting down. + } + } +} diff --git a/Common/ConnectionAuthority/ConnectionHandle.cs b/Common/ConnectionAuthority/ConnectionHandle.cs new file mode 100644 index 00000000..7a848e8a --- /dev/null +++ b/Common/ConnectionAuthority/ConnectionHandle.cs @@ -0,0 +1,169 @@ +using System.Diagnostics; + +namespace OpenShock.Common.ConnectionAuthority; + +public enum RefreshResult +{ + /// The connection may go on; its is current. + Valid, + + /// The connection may not go on and was closed. + Revoked, + + /// The check itself failed (database or Redis trouble). Nothing changed; it is tried again later. + Failed +} + +/// +/// One registered connection: what it depends on, what it may currently do, and the means to look again. +/// +/// +/// Looking again is the only way the grant changes, and only one look runs at a time per connection. A request +/// that arrives while one is running makes it run once more when it finishes, so the last look always started +/// after the last request. That is what keeps an older read from replacing a newer one. +/// +public sealed class ConnectionHandle : IDisposable +{ + private readonly ConnectionAuthorityRegistry _registry; + private readonly IAuthorizedConnection _connection; + + private readonly Lock _lock = new(); + private Task? _running; + private bool _rerun; + + private volatile ConnectionSubject _subject; + private volatile Grant? _grant; + private volatile bool _revoked; + + // 0 means "never validated": Stopwatch timestamps are never 0 in practice. + private long _lastValidated; + + internal ConnectionHandle(ConnectionAuthorityRegistry registry, ConnectionSubject subject, IAuthorizedConnection connection) + { + _registry = registry; + _subject = subject; + _connection = connection; + } + + public ConnectionSubject Subject => _subject; + + /// What the connection may do, as of the last successful look. Null until the first one. + public Grant? Grant => _grant; + + /// The connection may no longer go on. Set before it is closed, and never unset. + public bool IsRevoked => _revoked; + + /// + /// Replace what the connection depends on, for a connection that learns more after it was registered. The next + /// looks again whatever was checked before. + /// + public void UpdateSubject(ConnectionSubject subject) + { + _subject = subject; + Interlocked.Exchange(ref _lastValidated, 0); + } + + public bool WasValidatedWithin(TimeSpan interval) + { + var lastValidated = Interlocked.Read(ref _lastValidated); + return lastValidated != 0 && Stopwatch.GetElapsedTime(lastValidated) < interval; + } + + /// Look again unless the last successful look is younger than . + public Task EnsureFreshAsync(TimeSpan maxAge) + { + if (_revoked) return Task.FromResult(RefreshResult.Revoked); + if (WasValidatedWithin(maxAge)) return Task.FromResult(RefreshResult.Valid); + return RefreshAsync(); + } + + /// + /// Look up what the connection may do now, and close it if that is nothing. If a look is already running, this + /// waits for one that started after this call. + /// + public Task RefreshAsync() + { + lock (_lock) + { + if (_revoked) return Task.FromResult(RefreshResult.Revoked); + + if (_running is not null) + { + _rerun = true; + return _running; + } + + return _running = RunAsync(); + } + } + + /// Like , for a caller that cannot wait. Never throws. + public void RequestRefresh() => _ = RefreshAsync(); + + /// Completes once no look is running, for a caller that requested one without waiting for it. + public Task WhenIdleAsync() + { + lock (_lock) + { + return _running ?? Task.CompletedTask; + } + } + + /// Look again unless a look is already running: for a reason that one already covers. + internal void RequestRefreshIfIdle() + { + lock (_lock) + { + if (_revoked || _running is not null) return; + _running = RunAsync(); + } + } + + private async Task RunAsync() + { + // Leave the caller's lock before doing anything, so _running is assigned before this can finish. + await Task.Yield(); + + while (true) + { + var result = await _registry.ResolveOnceAsync(this); + + lock (_lock) + { + if (_rerun && !_revoked) + { + _rerun = false; + continue; + } + + _running = null; + return result; + } + } + } + + internal bool Accept(Grant grant) + { + if (!_connection.TryApplyGrant(grant)) return false; + + _grant = grant; + Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); + return true; + } + + /// True for the one caller that has to close the connection. + internal bool MarkRevoked() + { + lock (_lock) + { + if (_revoked) return false; + _revoked = true; + return true; + } + } + + internal Task CloseConnectionAsync() => _connection.CloseAsync(); + + /// Stop tracking the connection. Does not close it. + public void Dispose() => _registry.Remove(this); +} diff --git a/Common/ConnectionAuthority/ConnectionSubject.cs b/Common/ConnectionAuthority/ConnectionSubject.cs new file mode 100644 index 00000000..d627a5c2 --- /dev/null +++ b/Common/ConnectionAuthority/ConnectionSubject.cs @@ -0,0 +1,86 @@ +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// What kind of long-lived connection this is, which decides what it needs to keep going. +/// +public enum ConnectionKind +{ + /// A SignalR hub connection. Checked when it is used, never while idle. + SignalR, + + /// A live control socket on a gateway. Needs shockers.use and the shockers it may control. + LiveControl, + + /// The socket of a hub (the device itself) on a gateway. + HubSocket +} + +/// +/// Everything an open connection's authority depends on. A change to any of the things named here is a reason to +/// look at the connection again, see . +/// +public sealed record ConnectionSubject +{ + public required ConnectionKind Kind { get; init; } + + /// The user the connection acts as, null for a guest or a hub socket. + public Guid? UserId { get; init; } + + /// The session token the connection authenticated with, if it used a session. + public string? SessionToken { get; init; } + + /// The id the session is stored under, see . + public string? SessionId { get; init; } + + /// The API token the connection authenticated with, if it used one. + public Guid? ApiTokenId { get; init; } + + /// The hub a live control socket controls, or the hub a hub socket belongs to. + public Guid? DeviceId { get; init; } + + /// The owner of . + public Guid? DeviceOwnerId { get; init; } + + /// The token a hub socket authenticated with. + public string? HubToken { get; init; } + + /// The public share the connection controls. + public Guid? PublicShareId { get; init; } + + /// The owner of . + public Guid? PublicShareOwnerId { get; init; } + + /// The share's password stamp when the connection was let in, null when it had no password. + public Guid? PublicSharePasswordStamp { get; init; } + + /// Whether a change to the thing named by can affect this connection. + public bool IsAffectedBy(AuthorityChange change) => change.Kind switch + { + AuthorityChangeKind.User => UserId == change.Id || DeviceOwnerId == change.Id || PublicShareOwnerId == change.Id, + AuthorityChangeKind.ApiToken => ApiTokenId == change.Id, + AuthorityChangeKind.Device => DeviceId == change.Id, + AuthorityChangeKind.PublicShare => PublicShareId == change.Id, + _ => false + }; +} + +public enum AuthorityChangeKind +{ + /// An account was deactivated, deleted or otherwise may no longer be used. + User, + + /// An API token was edited, paused or deleted. + ApiToken, + + /// A hub, its shockers or the shares on them changed. + Device, + + /// Who may use a public share changed. + PublicShare +} + +/// +/// Something a connection's authority can depend on has changed. Carries no detail on purpose: the affected +/// connections look up what they may do now, so a change cannot be applied out of order or half-described. +/// +public readonly record struct AuthorityChange(AuthorityChangeKind Kind, Guid Id); diff --git a/Common/ConnectionAuthority/Grant.cs b/Common/ConnectionAuthority/Grant.cs new file mode 100644 index 00000000..1d599a04 --- /dev/null +++ b/Common/ConnectionAuthority/Grant.cs @@ -0,0 +1,52 @@ +using System.Collections.Frozen; +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// What a connection may do right now, as last read from the database. Immutable: a change produces a new grant +/// that replaces this one as a whole, so a reader never sees half of an update. +/// +public sealed record Grant +{ + /// A grant that allows going on and carries nothing else. + public static readonly Grant Empty = new(); + + /// What the authenticating API token grants, null when the connection did not use one. + public TokenGrant? Token { get; init; } + + /// + /// The shockers a live control connection may control and how, by shocker id. Null for other connections. + /// + public FrozenDictionary? Shockers { get; init; } + + /// When the grant ends on its own (a token or public share reaching its expiry), if it does. + public DateTime? ExpiresAt { get; init; } + + public bool IsExpired(DateTime now) => ExpiresAt is { } expiresAt && expiresAt < now; +} + +/// What an API token grants to a connection that authenticated with it. +public sealed record TokenGrant +{ + public required bool Paused { get; init; } + public required IReadOnlyList Permissions { get; init; } + public required ApiTokenControlLimits Limits { get; init; } + + public static TokenGrant From(ApiToken token) => new() + { + Paused = token.ShockerControlPaused, + Permissions = [.. token.Permissions], + Limits = ApiTokenControlLimits.FromToken(token) + }; + + /// Whether both grant exactly the same: pause state, permissions and control limits. + public bool GrantsTheSameAs(TokenGrant other) => + Paused == other.Paused && + Permissions.SequenceEqual(other.Permissions) && + Limits.Equals(other.Limits); +} + +/// What a user may do with one shocker: the shocker's own settings combined with their share, if any. +public sealed record ShockerGrant(bool Paused, SharePermsAndLimits PermsAndLimits); diff --git a/Common/ConnectionAuthority/GrantResolver.cs b/Common/ConnectionAuthority/GrantResolver.cs new file mode 100644 index 00000000..f53dc5d6 --- /dev/null +++ b/Common/ConnectionAuthority/GrantResolver.cs @@ -0,0 +1,121 @@ +using System.Collections.Frozen; +using Microsoft.EntityFrameworkCore; +using OpenShock.Common.DeviceControl; +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.Session; + +namespace OpenShock.Common.ConnectionAuthority; + +/// +public sealed class GrantResolver : IGrantResolver +{ + private readonly OpenShockContext _db; + private readonly ISessionService _sessionService; + + public GrantResolver(OpenShockContext db, ISessionService sessionService) + { + _db = db; + _sessionService = sessionService; + } + + /// + public async Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken) + { + var now = DateTime.UtcNow; + + if (subject.Kind == ConnectionKind.HubSocket) + return await IsHubStillValid(subject, cancellationToken) ? Grant.Empty : null; + + // Who the connection authenticated as. + TokenGrant? tokenGrant = null; + DateTime? expiresAt = null; + + if (subject.ApiTokenId is { } tokenId) + { + var token = await _db.ApiTokens + .AsNoTracking() + .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null, cancellationToken); + if (token is null || (token.ValidUntil is { } validUntil && validUntil < now)) return null; + + // Live control is one endpoint behind one permission, so losing it ends the connection. A hub + // connection serves several and checks the permission on each call. + if (subject.Kind == ConnectionKind.LiveControl && !token.Permissions.IsAllowed(PermissionType.Shockers_Use)) return null; + + tokenGrant = TokenGrant.From(token); + expiresAt = token.ValidUntil; + } + else if (subject.SessionToken is { } sessionToken) + { + // Sessions are deleted on logout, on deactivation and on a password reset. + var session = await _sessionService.GetSessionByTokenAsync(sessionToken); + if (session is null || session.UserId != subject.UserId) return 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 active = await _db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, cancellationToken); + if (!active) return null; + } + else if (subject.Kind == ConnectionKind.LiveControl) + { + // Live control is never anonymous. + return null; + } + + // What it is connected to. + if (subject.PublicShareId is { } publicShareId) + { + // 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. + var passwordStamp = subject.PublicSharePasswordStamp; + var share = await _db.PublicShares + .Where(x => + x.Id == publicShareId && + (x.ExpiresAt == null || x.ExpiresAt > now) && + x.Owner.UserDeactivation == null && + x.PasswordStamp == passwordStamp) + .Select(x => new { x.ExpiresAt }) + .FirstOrDefaultAsync(cancellationToken); + if (share is null) return null; + + expiresAt = Earliest(expiresAt, share.ExpiresAt); + } + + FrozenDictionary? shockers = null; + if (subject.Kind == ConnectionKind.LiveControl) + { + if (subject is not { DeviceId: { } deviceId, DeviceOwnerId: { } ownerId, UserId: { } userId }) return null; + + // Someone controlling a shared hub loses it when the owner is deactivated. + if (ownerId != userId && !await _db.Users.AnyAsync(u => u.Id == ownerId && u.UserDeactivation == null, cancellationToken)) + return null; + + // Losing every share leaves the connection open with nothing to control: a share can come back, and + // the client is told per frame that the shocker is not there. + var controllable = await _db.Shockers + .AsNoTracking() + .Where(x => x.DeviceId == deviceId) + .ControllableBy(userId) + .ToArrayAsync(cancellationToken); + + shockers = controllable.ToFrozenDictionary( + x => x.ShockerId, + x => new ShockerGrant(x.Paused, SharePermsAndLimits.Intersect(x.ShockerPermsAndLimits, x.PermsAndLimits))); + } + + return new Grant { Token = tokenGrant, Shockers = shockers, ExpiresAt = expiresAt }; + } + + /// + /// A hub may stay connected while it exists, still has the token it connected with and its owner is active, + /// the same as what lets it connect. + /// + private Task IsHubStillValid(ConnectionSubject subject, CancellationToken cancellationToken) + { + if (subject is not { DeviceId: { } deviceId, HubToken: { } hubToken }) return Task.FromResult(false); + + return _db.Devices.AnyAsync(x => x.Id == deviceId && x.Token == hubToken && x.Owner.UserDeactivation == null, cancellationToken); + } + + private static DateTime? Earliest(DateTime? a, DateTime? b) => a is null ? b : b is null ? a : a < b ? a : b; +} diff --git a/Common/ConnectionAuthority/IAuthorizedConnection.cs b/Common/ConnectionAuthority/IAuthorizedConnection.cs new file mode 100644 index 00000000..dae8e27e --- /dev/null +++ b/Common/ConnectionAuthority/IAuthorizedConnection.cs @@ -0,0 +1,20 @@ +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// A long-lived connection as the sees it. +/// +public interface IAuthorizedConnection +{ + /// + /// Called with what the connection may do now, each time that was read. The grant is also kept on the + /// connection's . + /// + /// False when the connection cannot go on under this grant and has to be closed. + bool TryApplyGrant(Grant grant); + + /// + /// Close the connection: it may no longer go on. Called at most once. Must not throw for a connection that is + /// already closing or not open yet. + /// + Task CloseAsync(); +} diff --git a/Common/ConnectionAuthority/IGrantResolver.cs b/Common/ConnectionAuthority/IGrantResolver.cs new file mode 100644 index 00000000..f4f90bd3 --- /dev/null +++ b/Common/ConnectionAuthority/IGrantResolver.cs @@ -0,0 +1,11 @@ +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// The one place that decides whether an open connection may go on and what it may do. Every long-lived +/// connection asks here, whatever it is and whichever service holds it. +/// +public interface IGrantResolver +{ + /// What the connection may do now, or null when it may not go on at all. + Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken); +} diff --git a/Common/ConnectionAuthority/SessionIds.cs b/Common/ConnectionAuthority/SessionIds.cs new file mode 100644 index 00000000..6c9dd221 --- /dev/null +++ b/Common/ConnectionAuthority/SessionIds.cs @@ -0,0 +1,11 @@ +using OpenShock.Common.Constants; +using OpenShock.Common.Utils; + +namespace OpenShock.Common.ConnectionAuthority; + +public static class SessionIds +{ + /// The id a session is stored under in Redis: the hash of its token (old tokens are stored as they are). + public static string FromToken(string sessionToken) + => sessionToken.Length == AuthConstants.GeneratedTokenLength ? HashingUtils.HashToken(sessionToken) : sessionToken; +} diff --git a/Common/DeviceControl/ShockerAccessQueries.cs b/Common/DeviceControl/ShockerAccessQueries.cs new file mode 100644 index 00000000..ae04cd89 --- /dev/null +++ b/Common/DeviceControl/ShockerAccessQueries.cs @@ -0,0 +1,55 @@ +using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.Common.DeviceControl; + +public static class ShockerAccessQueries +{ + /// + /// The shockers among that may control, as their owner + /// or through a share, with the shocker's own settings and the share's side by side. Shockers of a deactivated + /// owner are left out. + /// + /// + /// The single definition of who may control what, shared by one-off control commands and live control so the + /// two cannot drift apart. Combine the two sets of limits with . + /// + public static IQueryable ControllableBy(this IQueryable shockers, Guid userId) => + shockers + .Where(shocker => shocker.Device.Owner.UserDeactivation == null) + .Select(shocker => new + { + shocker, + shocker.Device.OwnerId, + Share = shocker.UserShares.FirstOrDefault(us => us.SharedWithUserId == userId) + }) + .Where(x => x.OwnerId == userId || x.Share != null) + .Select(x => new ControlShockerObj + { + ShockerId = x.shocker.Id, + ShockerName = x.shocker.Name, + ShockerRfId = x.shocker.RfId, + DeviceId = x.shocker.DeviceId, + ShockerModel = x.shocker.Model, + OwnerId = x.OwnerId, + Paused = x.shocker.IsPaused || (x.Share != null && x.Share.IsPaused), + ShockerPermsAndLimits = new SharePermsAndLimits + { + Sound = x.shocker.AllowSound, + Vibrate = x.shocker.AllowVibrate, + Shock = x.shocker.AllowShock, + Duration = x.shocker.MaxDuration, + Intensity = x.shocker.MaxIntensity, + Live = x.shocker.AllowLiveControl + }, + PermsAndLimits = x.Share == null ? null : new SharePermsAndLimits + { + Sound = x.Share.AllowSound, + Vibrate = x.Share.AllowVibrate, + Shock = x.Share.AllowShock, + Duration = x.Share.MaxDuration, + Intensity = x.Share.MaxIntensity, + Live = x.Share.AllowLiveControl + } + }); +} diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 0c864130..7d1c3719 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -419,9 +419,25 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga return services; } + /// + /// What keeps long-lived connections (hub connections, live control and hub sockets) from outliving the + /// session, token, share or account they depend on. + /// + public static IServiceCollection AddOpenShockConnectionAuthority(this IServiceCollection services) + { + services.AddOptions(); + services.AddSingleton(); + services.AddScoped(); + services.AddHostedService(); + services.AddHostedService(); + + return services; + } + public static IServiceCollection AddOpenShockSignalR(this IServiceCollection services, ConfigurationOptions redisConfig) { + services.AddOpenShockConnectionAuthority(); services.AddOptions(); services.AddSingleton(); services.AddSingleton(); diff --git a/Common/Services/ControlSender.cs b/Common/Services/ControlSender.cs index fa37af81..411b8ca2 100644 --- a/Common/Services/ControlSender.cs +++ b/Common/Services/ControlSender.cs @@ -32,42 +32,7 @@ public async Task ControlByUser(IReadOnlyList con { var shockers = await _db.Shockers .AsNoTracking() - .Where(shocker => shocker.Device.Owner.UserDeactivation == null) - .Select(shocker => new - { - shocker, - shocker.Device.OwnerId, - Share = shocker.UserShares.FirstOrDefault(us => us.SharedWithUserId == sender.Id) - }) - .Where(x => x.OwnerId == sender.Id || x.Share != null) - .Select(x => new ControlShockerObj - { - ShockerId = x.shocker.Id, - ShockerName = x.shocker.Name, - ShockerRfId = x.shocker.RfId, - DeviceId = x.shocker.DeviceId, - ShockerModel = x.shocker.Model, - OwnerId = x.OwnerId, - Paused = x.shocker.IsPaused || (x.Share != null && x.Share.IsPaused), - ShockerPermsAndLimits = new SharePermsAndLimits - { - Sound = x.shocker.AllowSound, - Vibrate = x.shocker.AllowVibrate, - Shock = x.shocker.AllowShock, - Duration = x.shocker.MaxDuration, - Intensity = x.shocker.MaxIntensity, - Live = x.shocker.AllowLiveControl - }, - PermsAndLimits = x.Share == null ? null : new SharePermsAndLimits - { - Sound = x.Share.AllowSound, - Vibrate = x.Share.AllowVibrate, - Shock = x.Share.AllowShock, - Duration = x.Share.MaxDuration, - Intensity = x.Share.MaxIntensity, - Live = x.Share.AllowLiveControl - } - }) + .ControllableBy(sender.Id) .ToArrayAsync(cancellationToken); return await ControlInternal(controls, sender, sender.Id, hubClients, shockers, ControlMetrics.Source.User, tokenLimits); From 9f1bd685de5501e1506f44509ab6151876c9eb41 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 19:22:15 +0100 Subject: [PATCH 06/24] refactor(lcg): move live control onto the shared connection authority Live control reads what it may do from its registry handle on every frame. The token subscriber, the revocation subscriber, the per-connection revalidation and the generation counters that ordered their writes are removed, as the registry does all of it. A hub update now signals the registry instead of refreshing each live control connection in turn, so control commands queued behind it on the hub's channel no longer wait for those database reads. Also gives a live control connection one connection id instead of a new one on every read. --- .../Extensions/ApiTokenExtensionsTests.cs | 49 --- Common/Extensions/ApiTokenExtensions.cs | 19 - .../Controllers/LiveControlController.cs | 386 ++++-------------- .../LifetimeManager/HubLifetime.cs | 10 +- .../LifetimeManager/HubLifetimeManager.cs | 6 + .../Models/LiveShockerPermission.cs | 19 - LiveControlGateway/Program.cs | 4 - .../PubSub/ApiTokenUpdateSubscriber.cs | 127 ------ .../PubSub/LiveControlRevocationSubscriber.cs | 85 ---- 9 files changed, 89 insertions(+), 616 deletions(-) delete mode 100644 Common.Tests/Extensions/ApiTokenExtensionsTests.cs delete mode 100644 Common/Extensions/ApiTokenExtensions.cs delete mode 100644 LiveControlGateway/Models/LiveShockerPermission.cs delete mode 100644 LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs delete mode 100644 LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs diff --git a/Common.Tests/Extensions/ApiTokenExtensionsTests.cs b/Common.Tests/Extensions/ApiTokenExtensionsTests.cs deleted file mode 100644 index 3c266234..00000000 --- a/Common.Tests/Extensions/ApiTokenExtensionsTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Net; -using OpenShock.Common.Extensions; -using OpenShock.Common.Models; -using OpenShock.Common.OpenShockDb; - -namespace OpenShock.Common.Tests.Extensions; - -public sealed class ApiTokenExtensionsTests -{ - private static readonly DateTime Now = new(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc); - - private static ApiToken Token(DateTime? validUntil, params PermissionType[] permissions) => new() - { - UserId = Guid.NewGuid(), - Name = "test", - TokenHash = "hash", - CreatedByIp = IPAddress.Loopback, - Permissions = [.. permissions], - ValidUntil = validUntil - }; - - [Test] - public async Task CanControlShockers_ValidTokenWithShockersUse_True() - { - await Assert.That(Token(null, PermissionType.Shockers_Use).CanControlShockers(Now)).IsTrue(); - await Assert.That(Token(Now.AddMinutes(1), PermissionType.Shockers_Use).CanControlShockers(Now)).IsTrue(); - } - - [Test] - public async Task CanControlShockers_Expired_False() - { - await Assert.That(Token(Now.AddSeconds(-1), PermissionType.Shockers_Use).CanControlShockers(Now)).IsFalse(); - } - - [Test] - public async Task CanControlShockers_WithoutShockersUse_False() - { - await Assert.That(Token(null).CanControlShockers(Now)).IsFalse(); - await Assert.That(Token(null, PermissionType.Shockers_Edit).CanControlShockers(Now)).IsFalse(); - } - - [Test] - public async Task CanControlShockers_PausedTokenKeepsAuthority_True() - { - var token = Token(null, PermissionType.Shockers_Use); - token.ShockerControlPaused = true; - await Assert.That(token.CanControlShockers(Now)).IsTrue(); - } -} diff --git a/Common/Extensions/ApiTokenExtensions.cs b/Common/Extensions/ApiTokenExtensions.cs deleted file mode 100644 index 5398401e..00000000 --- a/Common/Extensions/ApiTokenExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using OpenShock.Common.Models; -using OpenShock.Common.OpenShockDb; - -namespace OpenShock.Common.Extensions; - -public static class ApiTokenExtensions -{ - /// - /// Whether this token may still control shockers at : it has not expired and still - /// carries . A paused token keeps this authority, it just sends nothing. - /// - /// - /// Checked again on connections that outlive their authentication, such as live control, so a token that - /// expired or lost the permission cannot keep using a connection it opened while it was valid. - /// - public static bool CanControlShockers(this ApiToken token, DateTime now) => - (token.ValidUntil is null || token.ValidUntil >= now) && - token.Permissions.IsAllowed(PermissionType.Shockers_Use); -} diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index 76a300b9..3ed0a875 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -1,4 +1,3 @@ -using System.Collections.Frozen; using System.Diagnostics; using System.Net.WebSockets; using System.Text.Json; @@ -6,26 +5,23 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication; using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Errors; using OpenShock.Common.Extensions; -using OpenShock.Common.Hubs; using OpenShock.Common.Models; using OpenShock.Common.Models.WebSocket; using OpenShock.Common.Models.WebSocket.LCG; using OpenShock.Common.OpenShockDb; -using OpenShock.Common.Services.Session; using OpenShock.Common.Utils; using OpenShock.Common.Websocket; using OpenShock.Internal.Common.Constants; +using OpenShock.Internal.Common.Errors; using OpenShock.Internal.Common.Utils; using OpenShock.LiveControlGateway.LifetimeManager; using OpenShock.LiveControlGateway.Metrics; -using OpenShock.LiveControlGateway.Models; -using OpenShock.LiveControlGateway.PubSub; using JsonOptions = OpenShock.Common.JsonSerialization.JsonOptions; using Results = OpenShock.Common.Results; using Timer = System.Timers.Timer; @@ -41,14 +37,11 @@ namespace OpenShock.LiveControlGateway.Controllers; [Authorize(AuthenticationSchemes = OpenShockAuthSchemes.UserSessionApiTokenCombo)] [TokenPermission(PermissionType.Shockers_Use)] public sealed class LiveControlController : WebsocketBaseController>, - IActionFilter + IActionFilter, IAuthorizedConnection { private readonly HubLifetimeManager _hubLifetimeManager; private readonly IDbContextFactory _dbContextFactory; - private readonly ApiTokenUpdateSubscriber _tokenUpdateSubscriber; - private readonly LiveControlRevocationSubscriber _revocationSubscriber; - private readonly IServiceScopeFactory _scopeFactory; - private readonly TimeSpan _revalidationInterval; + private readonly ConnectionAuthorityRegistry _authorityRegistry; private readonly ILogger _logger; private readonly GatewayMetrics _metrics; @@ -62,74 +55,26 @@ public sealed class LiveControlController : WebsocketBaseController private Guid? _tokenId; - /// - /// What the API token used to authenticate currently grants, replaced as a whole when it changes. - /// Null when authenticated via a user session (no token limits apply). - /// - private TokenState? _tokenState; - - private sealed record TokenState(bool Paused, ApiTokenControlLimits Limits, DateTime? ValidUntil) - { - public static TokenState From(ApiToken token) => - new(token.ShockerControlPaused, ApiTokenControlLimits.FromToken(token), token.ValidUntil); - - public bool IsExpired(DateTime now) => ValidUntil is { } validUntil && validUntil < now; - } - /// /// The session token used to authenticate, if any. Null when authenticated via an API token. /// private string? _sessionToken; /// - /// Set once the session or token this connection authenticated with may no longer control. - /// Every frame after that is dropped while the socket is being closed. - /// - private int _revokedFlag; - - private bool Revoked => Volatile.Read(ref _revokedFlag) != 0; - - private int _revalidating; - private long _lastValidated; - - /// - /// The token state and the shocker permissions each have more than one writer that reads the database and then - /// installs what it read (the token subscriber, and revalidation). Each - /// read takes a generation before it starts, and a result is installed only if no read that started later has - /// already installed its own. Without that, a slow read of the old state could overwrite a newer pause or share - /// removal until the next revalidation. + /// This connection in the , which keeps what it may do current: the + /// token's pause state and limits and the shockers it may control. It also closes the connection once the + /// session, token or account it depends on may no longer control. Set before the socket is accepted. /// - private readonly Lock _stateLock = new(); - private static ulong _tokenReadGeneration; - private ulong _tokenAppliedGeneration; - private ulong _permissionsReadGeneration; - private ulong _permissionsAppliedGeneration; + private ConnectionHandle? _authority; - /// - /// The id the authenticating session is stored under, null when authenticated via an API token. - /// - public string? SessionId { get; private set; } - - /// - /// The user controlling through this connection. - /// - public Guid UserId => _currentUser.Id; - - /// - /// The owner of the hub this connection controls, once known. - /// - public Guid? DeviceOwnerId => _device?.OwnerId; + private ConnectionHandle Authority => + _authority ?? throw new InvalidOperationException("Connection authority is null but was accessed"); /// /// ID of the connected hub /// public Guid? HubId { get; private set; } - private Device? _device; - /// - /// Replaced as a whole, never changed in place, so frames read it without a lock. See . - /// - private FrozenDictionary _sharedShockers = FrozenDictionary.Empty; private byte _tps = 10; private long _pingTimestamp = Stopwatch.GetTimestamp(); private ushort _latencyMs; @@ -141,7 +86,7 @@ public static TokenState From(ApiToken token) => /// /// Connection Id for this connection, unique and random per connection /// - public Guid ConnectionId => Guid.CreateVersion7(); + public Guid ConnectionId { get; } = Guid.CreateVersion7(); private readonly Timer _pingTimer = new(PingInterval); @@ -150,20 +95,14 @@ public static TokenState From(ApiToken token) => /// /// /// - /// - /// - /// - /// + /// /// /// - public LiveControlController(HubLifetimeManager hubLifetimeManager, IDbContextFactory dbContextFactory, ApiTokenUpdateSubscriber tokenUpdateSubscriber, LiveControlRevocationSubscriber revocationSubscriber, IServiceScopeFactory scopeFactory, IOptions revalidationOptions, GatewayMetrics metrics, ILogger logger) : base(logger) + public LiveControlController(HubLifetimeManager hubLifetimeManager, IDbContextFactory dbContextFactory, ConnectionAuthorityRegistry authorityRegistry, GatewayMetrics metrics, ILogger logger) : base(logger) { _hubLifetimeManager = hubLifetimeManager; _dbContextFactory = dbContextFactory; - _tokenUpdateSubscriber = tokenUpdateSubscriber; - _revocationSubscriber = revocationSubscriber; - _scopeFactory = scopeFactory; - _revalidationInterval = revalidationOptions.Value.Interval; + _authorityRegistry = authorityRegistry; _metrics = metrics; _logger = logger; @@ -187,70 +126,6 @@ protected override async Task UnregisterConnection() } } - /// - /// Update all shockers permissions for this user on this hub - /// - /// - [NonAction] - public async Task UpdatePermissions(OpenShockContext db) - { - Logger.LogDebug("Updating shared permissions for hub [{HubId}] for user [{User}]", Id, - _currentUser.Id); - - var generation = Interlocked.Increment(ref _permissionsReadGeneration); - var permissions = (await QueryPermissions(db)).ToFrozenDictionary(); - - lock (_stateLock) - { - // A refresh that started after this one has already installed what it read. - if (generation <= _permissionsAppliedGeneration) return; - _permissionsAppliedGeneration = generation; - _sharedShockers = permissions; - } - } - - private async Task> QueryPermissions(OpenShockContext db) - { - if (_device!.OwnerId == _currentUser.Id) - { - Logger.LogTrace("User is owner of hub"); - return await db.Shockers.Where(x => x.DeviceId == Id && x.Device.Owner.UserDeactivation == null).ToDictionaryAsync(x => x.Id, x => - new LiveShockerPermission - { - Paused = x.IsPaused, - PermsAndLimits = new SharePermsAndLimits - { - Shock = x.AllowShock, - Vibrate = x.AllowVibrate, - Sound = x.AllowSound, - Duration = x.MaxDuration, - Intensity = x.MaxIntensity, - Live = x.AllowLiveControl - } - }); - } - - return await db.UserShares - .Where(x => x.Shocker.DeviceId == Id && x.SharedWithUserId == _currentUser.Id && x.Shocker.Device.Owner.UserDeactivation == null) - .Select(x => new - { - x.ShockerId, - Lsp = new LiveShockerPermission - { - Paused = x.Shocker.IsPaused || x.IsPaused, - PermsAndLimits = new SharePermsAndLimits - { - Sound = x.AllowSound && x.Shocker.AllowSound, - Vibrate = x.AllowVibrate && x.Shocker.AllowVibrate, - Shock = x.AllowShock && x.Shocker.AllowShock, - Duration = ControlLimitUtils.MinCap(x.MaxDuration, x.Shocker.MaxDuration), - Intensity = ControlLimitUtils.MinCap(x.MaxIntensity, x.Shocker.MaxIntensity), - Live = x.AllowLiveControl && x.Shocker.AllowLiveControl - } - } - }).ToDictionaryAsync(x => x.ShockerId, x => x.Lsp); - } - /// /// We get the id from the route, check if its valid, check if the user has access to the shocker / hub /// @@ -264,20 +139,41 @@ private async Task> QueryPermissions(Ope HubId = id; + Guid? ownerId; await using (var db = await _dbContextFactory.CreateDbContextAsync()) { - var hubExistsAndYouHaveAccess = await db.Devices.AnyAsync(x => - x.Id == HubId && x.Owner.UserDeactivation == null && (x.OwnerId == _currentUser.Id || x.Shockers.Any(y => - y.UserShares.Any(z => z.SharedWithUserId == _currentUser.Id && z.AllowLiveControl)))); + ownerId = await db.Devices + .Where(x => x.Id == HubId && x.Owner.UserDeactivation == null && (x.OwnerId == _currentUser.Id || x.Shockers.Any(y => + y.UserShares.Any(z => z.SharedWithUserId == _currentUser.Id && z.AllowLiveControl)))) + .Select(x => (Guid?)x.OwnerId) + .FirstOrDefaultAsync(); + } - if (!hubExistsAndYouHaveAccess) - { - return WebsocketError.WebsocketLiveControlHubNotFound; - } + if (ownerId is null) + { + return WebsocketError.WebsocketLiveControlHubNotFound; + } - _device = await db.Devices.FirstOrDefaultAsync(x => x.Id == HubId); + // From here on a change to the session, token, account or shares reaches this connection. Registering also + // reads what it may do for the first time, which covers a change made since it authenticated. + var (authority, authorityResult) = await _authorityRegistry.RegisterAsync(new ConnectionSubject + { + Kind = ConnectionKind.LiveControl, + UserId = _currentUser.Id, + ApiTokenId = _tokenId, + SessionToken = _sessionToken, + SessionId = _sessionToken is null ? null : SessionIds.FromToken(_sessionToken), + DeviceId = id, + DeviceOwnerId = ownerId + }, this); + _authority = authority; - await UpdatePermissions(db); + switch (authorityResult) + { + case RefreshResult.Revoked: + return WebsocketError.WebsocketLiveControlHubNotFound; + case RefreshResult.Failed: + return ExceptionError.Exception; } if (HttpContext.Request.Query.TryGetValue("tps", out var requestedTps)) @@ -341,140 +237,29 @@ public void OnActionExecuting(ActionExecutingContext context) if (GetOptionalItem() is { } apiToken) { _tokenId = apiToken.Id; - _tokenState = TokenState.From(apiToken); } else if (HttpContext.TryGetUserSessionToken(out var sessionToken)) { _sessionToken = sessionToken; - SessionId = HubConnectionTracker.GetSessionId(sessionToken); - } - } - - /// - /// Take a generation for a read of an API token. Call before the database read whose result is passed to - /// . Shared by all connections: a connection only compares generations with the last - /// one it applied, so one increasing sequence serves them all, and one read can be applied to many connections. - /// - public static ulong BeginTokenRead() => Interlocked.Increment(ref _tokenReadGeneration); - - /// - /// Apply the current state of the authenticating API token to this connection, pushed by the - /// when the token changed. The caller has checked it may still control. - /// Ignored if a read that started later, per , has already been applied. - /// - /// - /// From , taken before was read. - [NonAction] - public void ApplyToken(ApiToken token, ulong generation) - { - lock (_stateLock) - { - if (generation <= _tokenAppliedGeneration) return; - _tokenAppliedGeneration = generation; - _tokenState = TokenState.From(token); } } /// - /// The session or token this connection authenticated with may no longer control: stop accepting frames and - /// close the socket. Safe to call more than once and from any thread. + /// The registry replaces as a whole and frames read it from there, so + /// there is nothing to apply here and no grant this connection cannot go on under. /// - [NonAction] - public async Task Revoke() - { - if (Interlocked.Exchange(ref _revokedFlag, 1) != 0) return; - - Logger.LogInformation("Closing live control connection of user [{UserId}] for hub [{HubId}], its authentication is no longer valid", - _currentUser.Id, HubId); - - try - { - await ForceClose(WebSocketCloseStatus.PolicyViolation, "Authentication is no longer valid"); - } - catch (Exception e) - { - // The socket may already be closing on its own; the flag above stops all control either way. - Logger.LogDebug(e, "Error while closing revoked live control connection"); - } - } + bool IAuthorizedConnection.TryApplyGrant(Grant grant) => true; /// - /// Re-check this connection against the database and the session store, for what the Redis messages cannot - /// cover: a message that was lost, or a token that reached its expiry. Also refreshes the token's pause state - /// and limits and the shared shocker permissions. + /// The session, token or account this connection depends on may no longer control. The registry has already + /// marked it revoked, which drops every frame; this closes the socket. /// - private async Task Revalidate() + async Task IAuthorizedConnection.CloseAsync() { - if (Revoked || Interlocked.Exchange(ref _revalidating, 1) == 1) return; + // Not accepted yet when this happens while connecting; SendInitialData closes it then. + if (WebSocket is null) return; - try - { - await using var scope = _scopeFactory.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - - if (!await IsStillAuthenticated(scope.ServiceProvider, db)) - { - await Revoke(); - return; - } - - await UpdatePermissions(db); - Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); - } - catch (OperationCanceledException) when (LinkedToken.IsCancellationRequested) - { - // Connection is closing anyway. - } - catch (Exception e) - { - // A transient failure must not drop a legitimate connection; the next ping retries. - Logger.LogWarning(e, "Error while revalidating live control connection for hub [{HubId}]", HubId); - } - finally - { - Interlocked.Exchange(ref _revalidating, 0); - } - } - - private async Task IsStillAuthenticated(IServiceProvider services, OpenShockContext db) - { - if (!await IsCallerStillAuthenticated(services, db)) return false; - - // Someone controlling a shared hub loses it when the owner is deactivated. The owner's revocation message - // closes those connections; this covers that message being lost. - var ownerId = _device!.OwnerId; - return ownerId == _currentUser.Id || - await db.Users.AnyAsync(u => u.Id == ownerId && u.UserDeactivation == null, LinkedToken); - } - - private async Task IsCallerStillAuthenticated(IServiceProvider services, OpenShockContext db) - { - if (_tokenId is { } tokenId) - { - var generation = BeginTokenRead(); - var token = await db.ApiTokens - .AsNoTracking() - .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null, LinkedToken); - if (token is null || !token.CanControlShockers(DateTime.UtcNow)) return false; - - ApplyToken(token, generation); - return true; - } - - if (_sessionToken is null) return false; - - // Sessions are deleted on logout, on deactivation and on a password reset. - var session = await services.GetRequiredService().GetSessionByTokenAsync(_sessionToken); - if (session is null || session.UserId != _currentUser.Id) return false; - - // That deletion happens after the database commit and can fail, so the account is the authority. - return await db.Users.AnyAsync(u => u.Id == _currentUser.Id && u.ActivatedAt != null && u.UserDeactivation == null, LinkedToken); - } - - private bool RevalidationDue() - { - var last = Interlocked.Read(ref _lastValidated); - return last == 0 || Stopwatch.GetElapsedTime(last) >= _revalidationInterval; + await ForceClose(WebSocketCloseStatus.PolicyViolation, "Authentication is no longer valid"); } /// @@ -495,16 +280,12 @@ protected override async Task SendInitialData() Logger.LogDebug("Starting ping timer..."); _pingTimer.Start(); - // When authenticated via an API token, register for live updates to its limits/pause state (or revocation) - // so changes take effect on this connection without reconnecting. - if (_tokenId is { } tokenId) - await _tokenUpdateSubscriber.Register(this, tokenId); - _revocationSubscriber.Register(this); - - // Authentication happened before the registrations above, so a revocation announced in between found - // nothing to close. Look once now that announcements can reach this connection. - await Revalidate(); - if (Revoked) return; + // Revoked after the precondition but before the socket was accepted, when there was nothing to close. + if (Authority.IsRevoked) + { + await ForceClose(WebSocketCloseStatus.PolicyViolation, "Authentication is no longer valid"); + return; + } await QueueMessage(new LiveControlResponse { @@ -683,20 +464,23 @@ await QueueMessage(new LiveControlResponse private async Task ProcessFrameInternal(ClientLiveFrame frame) { - // The socket is being closed because its authentication was revoked. - if (Revoked) return; + // The socket is being closed because what it depends on was revoked. + var authority = Authority; + if (authority.IsRevoked) return; - var tokenState = _tokenState; + // Read once: everything below is decided from this one grant even if it is replaced meanwhile. + var grant = authority.Grant; + if (grant is null) return; - // An expired token may not control, even though nothing announces the expiry. - if (tokenState is not null && tokenState.IsExpired(DateTime.UtcNow)) + // An expired token may not control, even though nothing announces the expiry. Looking again closes the socket. + if (grant.IsExpired(DateTime.UtcNow)) { - await Revoke(); + authority.RequestRefresh(); return; } // A paused API token may not send any control, mirroring the /shockers/control endpoint. - if (tokenState is { Paused: true }) + if (grant.Token is { Paused: true }) { _metrics.Frame(GatewayMetrics.FrameOutcome.TokenPaused, frame.Type); await QueueMessage(new LiveControlResponse @@ -707,10 +491,10 @@ await QueueMessage(new LiveControlResponse return; } - var permCheck = CheckFramePermissions(frame.Shocker, frame.Type); + var permCheck = CheckFramePermissions(grant, frame.Shocker, frame.Type); await (permCheck switch { - SharePermsAndLimits perms => ForwardFrame(frame, perms, tokenState?.Limits), + SharePermsAndLimits perms => ForwardFrame(frame, perms, grant.Token?.Limits), Results.NotFound => RejectFrame(frame, GatewayMetrics.FrameOutcome.ShockerNotFound, LiveResponseType.ShockerNotFound), LiveNotEnabled => RejectFrame(frame, GatewayMetrics.FrameOutcome.LiveNotEnabled, LiveResponseType.ShockerMissingLivePermission), NoPermission => RejectFrame(frame, GatewayMetrics.FrameOutcome.NoPermission, LiveResponseType.ShockerMissingPermission), @@ -762,9 +546,9 @@ await QueueMessage(new LiveControlResponse } } - private Results.Union5 CheckFramePermissions(Guid shocker, ControlType controlType) + private Results.Union5 CheckFramePermissions(Grant grant, Guid shocker, ControlType controlType) { - if (!_sharedShockers.TryGetValue(shocker, out var shockerShare)) return new Results.NotFound(); + if (grant.Shockers is null || !grant.Shockers.TryGetValue(shocker, out var shockerShare)) return new Results.NotFound(); if (shockerShare.Paused) return new ShockerPaused(); if (!PermissionUtils.IsAllowed(controlType, true, shockerShare.PermsAndLimits)) return new NoPermission(); @@ -780,15 +564,7 @@ private async Task SendPing() { if (WebSocket is not { State: WebSocketState.Open }) return; - // Close an idle connection whose token expired, rather than waiting for its next frame. - if (_tokenState is { } tokenState && tokenState.IsExpired(DateTime.UtcNow)) - { - await Revoke(); - return; - } - - if (RevalidationDue()) await Revalidate(); - if (Revoked) return; + if (_authority is not { IsRevoked: false }) return; if (Logger.IsEnabled(LogLevel.Debug)) Logger.LogDebug("Sending ping to live control user [{UserId}] for hub [{HubId}]", _currentUser.Id, @@ -841,19 +617,7 @@ protected override async ValueTask DisposeControllerAsync() Logger.LogTrace("Disposing controller timer"); _pingTimer.Dispose(); - _revocationSubscriber.Unregister(this); - - if (_tokenId is { } tokenId) - { - try - { - await _tokenUpdateSubscriber.Unregister(this, tokenId); - } - catch (Exception e) - { - Logger.LogDebug(e, "Error unregistering from api token updates"); - } - } + _authority?.Dispose(); await base.DisposeControllerAsync(); } diff --git a/LiveControlGateway/LifetimeManager/HubLifetime.cs b/LiveControlGateway/LifetimeManager/HubLifetime.cs index 59ad00fb..9749f224 100644 --- a/LiveControlGateway/LifetimeManager/HubLifetime.cs +++ b/LiveControlGateway/LifetimeManager/HubLifetime.cs @@ -5,6 +5,7 @@ using MessagePack; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Constants; using OpenShock.Common.Hubs; using OpenShock.Common.Models; @@ -54,6 +55,7 @@ public sealed class HubLifetime : IAsyncDisposable private readonly IBatchUpdateService _batchUpdateService; private readonly IHubContext _userHub; private readonly GatewayMetrics _metrics; + private readonly ConnectionAuthorityRegistry _authorityRegistry; private readonly RedisChannel _deviceMsgChannel; private readonly ISubscriber _subscriber; @@ -99,6 +101,7 @@ public sealed class HubLifetime : IAsyncDisposable /// /// /// + /// /// public HubLifetime([Range(1, 10)] byte tps, IHubController hubController, IDbContextFactory dbContextFactory, @@ -108,6 +111,7 @@ public HubLifetime([Range(1, 10)] byte tps, IHubController hubController, IBatchUpdateService batchUpdateService, IHubContext userHub, GatewayMetrics metrics, + ConnectionAuthorityRegistry authorityRegistry, ILogger logger) { HubController = hubController; @@ -118,6 +122,7 @@ public HubLifetime([Range(1, 10)] byte tps, IHubController hubController, _batchUpdateService = batchUpdateService; _userHub = userHub; _metrics = metrics; + _authorityRegistry = authorityRegistry; _logger = logger; _waitBetweenTicks = TimeSpan.FromMilliseconds(1000.0 / tps); @@ -455,8 +460,9 @@ public async Task UpdateDevice() await using var db = await _dbContextFactory.CreateDbContextAsync(_cancellationSource.Token); await UpdateShockers(db, _cancellationSource.Token); - foreach (var websocketController in _liveControlClients) - await websocketController.UpdatePermissions(db); + // The live control connections on this hub, and the hub's own socket, look at what they may do again. + // Not awaited: the commands queued behind this message on the hub's channel must not wait for it. + _authorityRegistry.Signal(new AuthorityChange(AuthorityChangeKind.Device, HubController.Id)); } /// diff --git a/LiveControlGateway/LifetimeManager/HubLifetimeManager.cs b/LiveControlGateway/LifetimeManager/HubLifetimeManager.cs index 0c71f3d6..3bf80793 100644 --- a/LiveControlGateway/LifetimeManager/HubLifetimeManager.cs +++ b/LiveControlGateway/LifetimeManager/HubLifetimeManager.cs @@ -2,6 +2,7 @@ using System.Diagnostics.Metrics; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Hubs; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; @@ -31,6 +32,7 @@ public sealed class HubLifetimeManager private readonly GatewayMetrics _metrics; private readonly IBatchUpdateService _batchUpdateService; private readonly IHubContext _userHub; + private readonly ConnectionAuthorityRegistry _authorityRegistry; private readonly ILogger _logger; /// @@ -54,6 +56,7 @@ public sealed class HubLifetimeManager /// /// /// + /// /// public HubLifetimeManager( IDbContextFactory dbContextFactory, @@ -65,6 +68,7 @@ public HubLifetimeManager( GatewayMetrics metrics, IBatchUpdateService batchUpdateService, IHubContext userHub, + ConnectionAuthorityRegistry authorityRegistry, [FromKeyedServices("OpenShock.Gateway.Meter")] Meter meter ) { @@ -76,6 +80,7 @@ public HubLifetimeManager( _metrics = metrics; _batchUpdateService = batchUpdateService; _userHub = userHub; + _authorityRegistry = authorityRegistry; _logger = _loggerFactory.CreateLogger(); @@ -213,6 +218,7 @@ private HubLifetime CreateNewLifetime(byte tps, IHubController hubController) _batchUpdateService, _userHub, _metrics, + _authorityRegistry, _loggerFactory.CreateLogger()); return deviceLifetime; diff --git a/LiveControlGateway/Models/LiveShockerPermission.cs b/LiveControlGateway/Models/LiveShockerPermission.cs deleted file mode 100644 index 88755196..00000000 --- a/LiveControlGateway/Models/LiveShockerPermission.cs +++ /dev/null @@ -1,19 +0,0 @@ -using OpenShock.Common.Models; - -namespace OpenShock.LiveControlGateway.Models; - -/// -/// Permissions and limits for a live shocker -/// -public sealed class LiveShockerPermission -{ - /// - /// Is the live shocker paused - /// - public required bool Paused { get; set; } - - /// - /// Perms and limits for the live shocker - /// - public required SharePermsAndLimits PermsAndLimits { get; set; } -} diff --git a/LiveControlGateway/Program.cs b/LiveControlGateway/Program.cs index 5317262f..d43a42a1 100644 --- a/LiveControlGateway/Program.cs +++ b/LiveControlGateway/Program.cs @@ -10,7 +10,6 @@ using OpenShock.LiveControlGateway.LifetimeManager; using OpenShock.LiveControlGateway.Metrics; using OpenShock.LiveControlGateway.Options; -using OpenShock.LiveControlGateway.PubSub; var builder = OpenShockApplication.CreateDefaultBuilder(args); @@ -60,9 +59,6 @@ }); #pragma warning restore EXTEXP0008 builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddHostedService(sp => sp.GetRequiredService()); var app = builder.Build(); diff --git a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs b/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs deleted file mode 100644 index aaaab4b4..00000000 --- a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs +++ /dev/null @@ -1,127 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using OpenShock.Common.Extensions; -using OpenShock.Common.OpenShockDb; -using OpenShock.Common.Services.RedisPubSub; -using OpenShock.Internal.Common.Extensions; -using OpenShock.Internal.Common.Utils; -using OpenShock.LiveControlGateway.Controllers; -using StackExchange.Redis; - -namespace OpenShock.LiveControlGateway.PubSub; - -/// -/// Per-gateway coordinator for API token update notifications. -/// Holds a single ref-counted redis subscription per token, shared by every live control connection on this -/// gateway that authenticated with it. When a token changes, it is fetched from the database once and its pause -/// state and limits are pushed to all those connections, instead of each connection querying the database on its -/// own. A token that may no longer control (deleted, expired, its user deactivated, or without shockers.use) -/// closes those connections instead. -/// -public sealed class ApiTokenUpdateSubscriber -{ - private readonly IDbContextFactory _dbContextFactory; - private readonly ISubscriber _subscriber; - private readonly ILogger _logger; - - private readonly Dictionary _subscriptions = new(); - private readonly SemaphoreSlim _subscriptionsLock = new(1, 1); - - private sealed class Subscription - { - public required Action Handler { get; init; } - public readonly HashSet Clients = []; - } - - /// - /// DI constructor - /// - /// - /// - /// - public ApiTokenUpdateSubscriber( - IConnectionMultiplexer connectionMultiplexer, - IDbContextFactory dbContextFactory, - ILogger logger) - { - _dbContextFactory = dbContextFactory; - _subscriber = connectionMultiplexer.GetSubscriber(); - _logger = logger; - } - - /// - /// Register a live control connection as interested in updates to the given token. - /// Subscribes to the token's channel if this is the first connection using it on this gateway. - /// - public async Task Register(LiveControlController client, Guid tokenId) - { - using (await _subscriptionsLock.LockAsyncScoped()) - { - if (!_subscriptions.TryGetValue(tokenId, out var sub)) - { - Action handler = (_, _) => OsTask.Run(() => OnTokenUpdate(tokenId)); - await _subscriber.SubscribeAsync(RedisChannels.ApiTokenUpdate(tokenId), handler); - sub = new Subscription { Handler = handler }; - _subscriptions[tokenId] = sub; - } - - sub.Clients.Add(client); - } - } - - /// - /// Unregister a live control connection. Unsubscribes from the token's channel once no connection uses it anymore. - /// - public async Task Unregister(LiveControlController client, Guid tokenId) - { - using (await _subscriptionsLock.LockAsyncScoped()) - { - if (_subscriptions.TryGetValue(tokenId, out var sub) && sub.Clients.Remove(client) && sub.Clients.Count == 0) - { - await _subscriber.UnsubscribeAsync(RedisChannels.ApiTokenUpdate(tokenId), sub.Handler); - _subscriptions.Remove(tokenId); - } - } - } - - private async Task OnTokenUpdate(Guid tokenId) - { - LiveControlController[] clients; - using (await _subscriptionsLock.LockAsyncScoped()) - { - if (!_subscriptions.TryGetValue(tokenId, out var sub)) return; - clients = [.. sub.Clients]; - } - - if (clients.Length == 0) return; - - // Taken before the read, so a revalidation that read the token earlier cannot overwrite this result. - var generation = LiveControlController.BeginTokenRead(); - - ApiToken? token; - try - { - await using var db = await _dbContextFactory.CreateDbContextAsync(); - - token = await db.ApiTokens - .AsNoTracking() - .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null); - } - catch (Exception e) - { - _logger.LogError(e, "Error fetching api token [{TokenId}] for live control connections", tokenId); - return; - } - - if (token is null || !token.CanControlShockers(DateTime.UtcNow)) - { - // Deleted, expired, its owner deactivated, or it lost shockers.use: the connections may not go on. - _logger.LogDebug("API token [{TokenId}] may no longer control, closing {Count} live connection(s)", - tokenId, clients.Length); - await Task.WhenAll(clients.Select(client => client.Revoke())); - return; - } - - foreach (var client in clients) - client.ApplyToken(token, generation); - } -} diff --git a/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs b/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs deleted file mode 100644 index a005ff7e..00000000 --- a/LiveControlGateway/PubSub/LiveControlRevocationSubscriber.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Collections.Concurrent; -using OpenShock.Common.Services.RedisPubSub; -using OpenShock.Internal.Common.Utils; -using OpenShock.LiveControlGateway.Controllers; -using StackExchange.Redis; - -namespace OpenShock.LiveControlGateway.PubSub; - -/// -/// The live control connections open on this gateway, closed when the session or account they belong to is -/// revoked. A live control socket is authenticated once, when it opens, so without this a logged out session or -/// a deactivated account could keep controlling through a socket opened before. -/// -/// -/// API token changes are handled per token by . A lost message is covered -/// by each connection re-checking itself against the database at a bounded interval. -/// -public sealed class LiveControlRevocationSubscriber : IHostedService -{ - private readonly ISubscriber _subscriber; - private readonly ILogger _logger; - private readonly ConcurrentDictionary _connections = new(); - - /// - /// DI constructor - /// - /// - /// - public LiveControlRevocationSubscriber(IConnectionMultiplexer connectionMultiplexer, ILogger logger) - { - _subscriber = connectionMultiplexer.GetSubscriber(); - _logger = logger; - } - - /// Start closing this connection when its session or account is revoked. - public void Register(LiveControlController connection) => _connections.TryAdd(connection, 0); - - /// Stop tracking this connection. - public void Unregister(LiveControlController connection) => _connections.TryRemove(connection, out _); - - /// - public async Task StartAsync(CancellationToken cancellationToken) - { - await _subscriber.SubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); - await _subscriber.SubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); - } - - /// - public async Task StopAsync(CancellationToken cancellationToken) - { - await _subscriber.UnsubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); - await _subscriber.UnsubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); - } - - private void HandleSessionRevoked(RedisChannel _, RedisValue message) - { - var sessionId = (string?)message; - if (string.IsNullOrEmpty(sessionId)) return; - - Revoke(c => c.SessionId == sessionId, "session revoked"); - } - - private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) - { - if (!Guid.TryParse((string?)message, out var userId)) return; - - // The user's own connections, and everyone controlling a hub they own through a share. - Revoke(c => c.UserId == userId || c.DeviceOwnerId == userId, "account revoked"); - } - - private void Revoke(Func predicate, string reason) - { - var closed = 0; - foreach (var connection in _connections.Keys) - { - if (!predicate(connection)) continue; - - _connections.TryRemove(connection, out _); - OsTask.Run(connection.Revoke); - closed++; - } - - if (closed > 0) _logger.LogDebug("Closing {Count} live control connection(s): {Reason}", closed, reason); - } -} From 85dac023b1e72be4a5af723901bf5aee6156c51c Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 19:22:15 +0100 Subject: [PATCH 07/24] refactor: move SignalR hub connections onto the shared connection authority The hub filter registers connections with the registry and makes sure a connection was checked recently before a call. The hub connection tracker and the API's own revocation handlers are removed. A hub connection is still closed when its API token's pause state, permissions or limits change. Renaming a token no longer closes it, and an idle connection whose token expired is now closed instead of staying open until its next call. The API's Redis subscriber only unsubscribes its own channels on shutdown, as it now shares the Redis connection. --- .../Tests/SignalRUserHubTests.cs | 3 +- API.IntegrationTests/WebApplicationFactory.cs | 3 +- API/Realtime/RedisSubscriberService.cs | 60 +----- .../Hubs/TrackedHubConnectionTests.cs | 35 ---- Common/Hubs/HubConnectionAuthority.cs | 152 +++++++++++++++ Common/Hubs/HubConnectionTracker.cs | 163 ---------------- Common/Hubs/PublicShareHub.cs | 8 +- .../Hubs/RevalidateAuthenticationHubFilter.cs | 179 +++++------------- Common/OpenShockServiceHelper.cs | 3 +- 9 files changed, 216 insertions(+), 390 deletions(-) delete mode 100644 Common.Tests/Hubs/TrackedHubConnectionTests.cs create mode 100644 Common/Hubs/HubConnectionAuthority.cs delete mode 100644 Common/Hubs/HubConnectionTracker.cs diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index 5290f7a2..302e03e9 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -7,6 +7,7 @@ using OpenShock.API.IntegrationTests.Helpers; using OpenShock.API.Services.Account; using OpenShock.Common.Constants; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Hubs; using OpenShock.Common.Models; using OpenShock.Common.Models.WebSocket.User; @@ -279,7 +280,7 @@ private async Task ConnectCheckedSessionAsync(AuthenticatedUser u /// The Redis key a session is stored under. private static string SessionKey(string sessionToken) => - $"{typeof(LoginSession).FullName}:{HubConnectionTracker.GetSessionId(sessionToken)}"; + $"{typeof(LoginSession).FullName}:{SessionIds.FromToken(sessionToken)}"; /// /// Opens a real hub connection against the in-process test server. The hub only allows WebSockets, which diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index 54f64e3a..39933f01 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Http; using OpenShock.API.IntegrationTests.HttpMessageHandlers; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Hubs; using OpenShock.Common.Services.Geo; using OpenShock.IntegrationTests.Shared; @@ -112,7 +113,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) // 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); + services.Configure(options => options.Interval = HubRevalidationInterval); }); } } diff --git a/API/Realtime/RedisSubscriberService.cs b/API/Realtime/RedisSubscriberService.cs index e6b845cc..3ac4573a 100644 --- a/API/Realtime/RedisSubscriberService.cs +++ b/API/Realtime/RedisSubscriberService.cs @@ -21,7 +21,6 @@ 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; @@ -32,21 +31,18 @@ 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; } @@ -56,46 +52,6 @@ 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); - await _subscriber.SubscribeAsync(RedisChannels.PublicShareAccessRevoked, HandlePublicShareAccessRevoked); - } - - 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}] or to their public shares", 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; - if (channelName is null || !channelName.StartsWith(RedisChannels.ApiTokenUpdatePrefix, StringComparison.Ordinal)) return; - if (!Guid.TryParse(channelName.AsSpan(RedisChannels.ApiTokenUpdatePrefix.Length), out var tokenId)) return; - - // An edit or pause closes the connections too: the client reconnects with the token as it is now. - var closed = _hubConnections.AbortApiToken(tokenId); - if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of changed API token [{TokenId}]", closed, tokenId); } private void HandleKeyExpired(RedisChannel _, RedisValue message) @@ -138,11 +94,6 @@ 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) @@ -227,7 +178,14 @@ await _hubContext.Clients.Users(userIds).DeviceStatus([ /// public async Task StopAsync(CancellationToken cancellationToken) { - await _subscriber.UnsubscribeAllAsync(); + await UnsubscribeAsync(); + } + + // Only what this service subscribed: other services listen on the same Redis connection. + private async Task UnsubscribeAsync() + { + await _subscriber.UnsubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); + await _subscriber.UnsubscribeAsync(RedisChannels.DeviceStatus, HandleDeviceStatus); } /// @@ -235,7 +193,7 @@ public async ValueTask DisposeAsync() { try { - await _subscriber.UnsubscribeAllAsync(); + await UnsubscribeAsync(); } catch (Exception ex) { diff --git a/Common.Tests/Hubs/TrackedHubConnectionTests.cs b/Common.Tests/Hubs/TrackedHubConnectionTests.cs deleted file mode 100644 index a20c0b10..00000000 --- a/Common.Tests/Hubs/TrackedHubConnectionTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using OpenShock.Common.Hubs; - -namespace OpenShock.Common.Tests.Hubs; - -public sealed class TrackedHubConnectionTests -{ - private static TrackedHubConnection Create() => new(null!, Guid.NewGuid(), sessionId: null, apiTokenId: Guid.NewGuid()); - - [Test] - public async Task NewConnection_IsNotValidated() - { - var connection = Create(); - - await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); - } - - [Test] - public async Task MarkValidated_RecordsTheCheck() - { - var connection = Create(); - connection.MarkValidated(); - - await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsTrue(); - } - - [Test] - public async Task ResetValidation_ForcesTheNextCheck() - { - var connection = Create(); - connection.MarkValidated(); - connection.ResetValidation(); - - await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); - } -} diff --git a/Common/Hubs/HubConnectionAuthority.cs b/Common/Hubs/HubConnectionAuthority.cs new file mode 100644 index 00000000..b993e604 --- /dev/null +++ b/Common/Hubs/HubConnectionAuthority.cs @@ -0,0 +1,152 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.SignalR; +using OpenShock.Common.Authentication; +using OpenShock.Common.ConnectionAuthority; +using OpenShock.Common.Extensions; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.Common.Hubs; + +/// +/// Puts SignalR hub connections under the : describes what each one +/// depends on and keeps its on the connection. +/// +public sealed class HubConnectionAuthority +{ + private static readonly object HandleKey = new(); + + private readonly ConnectionAuthorityRegistry _registry; + + public HubConnectionAuthority(ConnectionAuthorityRegistry registry) + { + _registry = registry; + } + + public TimeSpan Interval => _registry.Interval; + + /// + /// The connection's handle, also after it was revoked or untracked, so a call still queued on a closed + /// connection can be told apart from one on a connection that was never tracked. + /// + public static ConnectionHandle? Get(HubCallerContext context) + => context.Items.TryGetValue(HandleKey, out var handle) ? handle as ConnectionHandle : null; + + /// Whether the connection authenticated with something that can be revoked. + public static bool IsAuthenticated(HubCallerContext context) + => context.User is { } user && (user.HasOpenShockApiTokenIdentity() || user.TryGetOpenShockUserIdentity() is not null); + + /// + /// Starts tracking a connection by what it authenticated with. Anonymous connections hold nothing that can be + /// revoked and are skipped. + /// + /// The handle, not yet checked, or null when the connection was skipped. + public ConnectionHandle? Track(HubCallerContext context) + { + var user = context.User; + if (user is null) return null; + + Guid? userId = user.TryGetClaimValueAsGuid(ClaimTypes.NameIdentifier, out var parsedUserId) ? parsedUserId : null; + var httpContext = context.GetHttpContext(); + + ConnectionSubject subject; + TokenGrant? connectedWith = null; + var usesToken = false; + + if (user.HasOpenShockApiTokenIdentity()) + { + if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return null; + + usesToken = true; + if (httpContext?.GetItemByType() is { } token) connectedWith = TokenGrant.From(token); + subject = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = userId, ApiTokenId = tokenId }; + } + else if (user.TryGetOpenShockUserIdentity() is not null + && httpContext is not null + && httpContext.TryGetUserSessionToken(out var sessionToken)) + { + subject = new ConnectionSubject + { + Kind = ConnectionKind.SignalR, + UserId = userId, + SessionToken = sessionToken, + SessionId = SessionIds.FromToken(sessionToken) + }; + } + else + { + return null; + } + + var handle = _registry.Track(subject, new SignalRConnection(context, usesToken, connectedWith)); + context.Items[HandleKey] = handle; + return handle; + } + + /// + /// Makes the connection depend on a public share as well, so it is closed when the share's access changes. + /// Tracks the connection if it was not (a guest). Its next call checks the share, covering a change made since + /// the caller read it. + /// + /// The connection. + /// The share the connection controls. + /// The share's owner, whose deactivation closes the connection too. + /// The share's password stamp the visitor got in with, null when it had no password. + public void AttachPublicShare(HubCallerContext context, Guid publicShareId, Guid publicShareOwnerId, Guid? passwordStamp) + { + var handle = Get(context); + if (handle is null) + { + var subject = new ConnectionSubject + { + Kind = ConnectionKind.SignalR, + PublicShareId = publicShareId, + PublicShareOwnerId = publicShareOwnerId, + PublicSharePasswordStamp = passwordStamp + }; + + context.Items[HandleKey] = _registry.Track(subject, new SignalRConnection(context, usesToken: false, connectedWith: null)); + return; + } + + handle.UpdateSubject(handle.Subject with + { + PublicShareId = publicShareId, + PublicShareOwnerId = publicShareOwnerId, + PublicSharePasswordStamp = passwordStamp + }); + } + + /// Stops tracking the connection. Its handle stays readable through . + public static void Untrack(HubCallerContext context) => Get(context)?.Dispose(); + + private sealed class SignalRConnection : IAuthorizedConnection + { + private readonly HubCallerContext _context; + private readonly bool _usesToken; + private readonly TokenGrant? _connectedWith; + + public SignalRConnection(HubCallerContext context, bool usesToken, TokenGrant? connectedWith) + { + _context = context; + _usesToken = usesToken; + _connectedWith = connectedWith; + } + + /// + /// A hub connection keeps the token it opened with for all its calls, so it can only go on while that + /// token still grants the same. Any change closes it, and the client reconnects with the token as it is now. + /// + public bool TryApplyGrant(Grant grant) + { + if (!_usesToken) return true; + return _connectedWith is not null && grant.Token is { } current && current.GrantsTheSameAs(_connectedWith); + } + + /// Aborting also discards the calls the connection still had queued. + public Task CloseAsync() + { + _context.Abort(); + return Task.CompletedTask; + } + } +} diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs deleted file mode 100644 index 3df64107..00000000 --- a/Common/Hubs/HubConnectionTracker.cs +++ /dev/null @@ -1,163 +0,0 @@ -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; - } - - /// - /// 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 connection. - /// The share the connection controls. - /// The share's owner, whose deactivation closes the connection too. - /// The share's password stamp the visitor got in with, null when it had no password. - public TrackedHubConnection TrackPublicShare(HubCallerContext context, Guid publicShareId, Guid publicShareOwnerId, Guid? passwordStamp) - { - var tracked = _connections.GetOrAdd(context.ConnectionId, _ => new TrackedHubConnection(context, userId: null, sessionId: null, apiTokenId: null)); - tracked.AttachPublicShare(publicShareId, publicShareOwnerId, 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, 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 it was untracked. - 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. - /// 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. - public int AbortSession(string sessionId) => Abort(c => c.SessionId == sessionId); - - /// Closes every connection of this user, whatever it authenticated with, and the connections to their public shares. - /// How many connections were closed. - public int AbortUser(Guid userId) => Abort(c => c.UserId == userId || c.PublicShareOwnerId == userId); - - /// Closes the connections that authenticated with this API token. - /// How many connections were closed. - public int AbortApiToken(Guid tokenId) => Abort(c => c.ApiTokenId == tokenId); - - /// The id a session is stored under in Redis: the hash of its token (old tokens are stored as they are). - public static string GetSessionId(string sessionToken) - => sessionToken.Length == AuthConstants.GeneratedTokenLength ? HashingUtils.HashToken(sessionToken) : sessionToken; - - private int Abort(Func predicate) - { - var aborted = 0; - foreach (var (connectionId, connection) in _connections) - { - if (!predicate(connection)) continue; - - // Dropped here as well as on disconnect, so a message that arrives twice finds nothing. - _connections.TryRemove(connectionId, out _); - connection.Context.Abort(); - aborted++; - } - - return aborted; - } -} - -public sealed class TrackedHubConnection -{ - // 0 means "not validated": Stopwatch timestamps are never 0 in practice. - private long _lastValidated; - - public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sessionId, Guid? apiTokenId) - { - Context = context; - UserId = userId; - SessionId = sessionId; - ApiTokenId = apiTokenId; - } - - public HubCallerContext Context { get; } - public Guid? UserId { get; } - public string? SessionId { get; } - public Guid? ApiTokenId { get; } - - /// The public share this connection controls, null for other hubs. - public Guid? PublicShareId { get; private set; } - - /// The owner of . - public Guid? PublicShareOwnerId { 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 publicShareOwnerId, Guid? passwordStamp) - { - PublicShareId = publicShareId; - PublicShareOwnerId = publicShareOwnerId; - PasswordStamp = passwordStamp; - } - - public bool WasValidatedWithin(TimeSpan interval) - { - var lastValidated = Interlocked.Read(ref _lastValidated); - return lastValidated != 0 && Stopwatch.GetElapsedTime(lastValidated) < interval; - } - - public void MarkValidated() => Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); - - /// Makes the next call check the connection again. - public void ResetValidation() => Interlocked.Exchange(ref _lastValidated, 0); -} diff --git a/Common/Hubs/PublicShareHub.cs b/Common/Hubs/PublicShareHub.cs index f0b324df..80d4dc79 100644 --- a/Common/Hubs/PublicShareHub.cs +++ b/Common/Hubs/PublicShareHub.cs @@ -18,7 +18,7 @@ public sealed class PublicShareHub : Hub private readonly IHubContext _userHub; private readonly ISessionService _sessionService; private readonly IControlSender _controlSender; - private readonly HubConnectionTracker _connectionTracker; + private readonly HubConnectionAuthority _connectionAuthority; private readonly IPublicShareAccessService _publicShareAccess; private readonly ILogger _logger; /// @@ -33,9 +33,9 @@ public sealed class PublicShareHub : Hub public const string UnlockTokenQueryName = "unlockToken"; public PublicShareHub(OpenShockContext db, IHubContext userHub, ISessionService sessionService, IControlSender controlSender, - HubConnectionTracker connectionTracker, IPublicShareAccessService publicShareAccess, ILogger logger) + HubConnectionAuthority connectionAuthority, IPublicShareAccessService publicShareAccess, ILogger logger) { - _connectionTracker = connectionTracker; + _connectionAuthority = connectionAuthority; _publicShareAccess = publicShareAccess; _db = db; _userHub = userHub; @@ -139,7 +139,7 @@ public override async Task OnConnectedAsync() }; // Closed when the share's password is set or changed, the share is deleted or its owner deactivated. Left unvalidated so the // first call checks the share again, covering a change made since it was read above. - _connectionTracker.TrackPublicShare(Context, id, share.OwnerId, share.PasswordStamp); + _connectionAuthority.AttachPublicShare(Context, id, share.OwnerId, share.PasswordStamp); 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 019e2934..946fbd3d 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -1,60 +1,54 @@ -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; +using OpenShock.Common.ConnectionAuthority; namespace OpenShock.Common.Hubs; /// -/// Keeps an open hub connection from outliving the session or API token it authenticated with. +/// Keeps an open hub connection from outliving the session, API token or public share it depends on. /// /// /// SignalR authenticates a connection once, when it opens, and then keeps it for as long as the client likes. /// Without this, logging a session out or revoking, expiring or deactivating an API token would only stop new /// connections: an open one could keep calling, and whatever calls it already had queued would still run. -/// Aborting also discards those queued calls. /// -/// Two things end a connection. The fast one is a Redis message: revocations are published, and the instance -/// holding the connection closes it right away (the filter registers every connection with -/// for that). The slow one is the check in this filter, which asks the -/// database before a hub method call. It exists for what the messages cannot cover, a message that was lost -/// or a token that simply reached its expiry, so it only runs once per -/// per connection, and never for an idle one. -/// -/// -/// Any change to an API token closes its connections, so a client picks up new permissions, pause state and -/// control limits when it reconnects. +/// The deciding and the closing are done by the , shared with every +/// other kind of long-lived connection. This filter only puts hub connections under it: it registers them, and +/// before a hub method call makes sure the connection was checked within +/// . That check is what covers a change whose Redis message was +/// lost; it never runs for an idle connection. /// /// public sealed class RevalidateAuthenticationHubFilter : IHubFilter { - private readonly HubConnectionTracker _tracker; - private readonly IOptions _options; + private readonly HubConnectionAuthority _authority; - public RevalidateAuthenticationHubFilter(HubConnectionTracker tracker, IOptions options) + public RevalidateAuthenticationHubFilter(HubConnectionAuthority authority) { - _tracker = tracker; - _options = options; + _authority = authority; } /// public async Task OnConnectedAsync(HubLifetimeContext context, Func next) { - var tracked = _tracker.Track(context.Context); + // Kept on the connection and disposed when it disconnects, see HubConnectionAuthority.Untrack. +#pragma warning disable IDISP001 + var handle = _authority.Track(context.Context); +#pragma warning restore IDISP001 try { - // The connection was authenticated before it was tracked. A revocation announced in between found - // nothing to close, so look once now that announcements can reach it. - if (tracked is not null && !await ValidateAsync(context.Context, tracked, context.ServiceProvider)) + if (handle is not null) { - _tracker.Untrack(context.Context.ConnectionId); - context.Context.Abort(); - return; + // The connection was authenticated before it was tracked. A change announced in between found + // nothing to close, so look once now that announcements can reach it. + switch (await handle.RefreshAsync()) + { + case RefreshResult.Revoked: + // Already aborted. + return; + case RefreshResult.Failed: + throw new HubException("Authentication could not be verified"); + } } await next(context); @@ -62,7 +56,7 @@ public async Task OnConnectedAsync(HubLifetimeContext context, Func public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception, Func next) { - _tracker.Untrack(context.Context.ConnectionId); + HubConnectionAuthority.Untrack(context.Context); return next(context, exception); } @@ -78,117 +72,36 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) { var context = invocationContext.Context; + var handle = HubConnectionAuthority.Get(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 (handle is null) + { + // Anonymous and not on a public share: nothing was granted that could have been revoked. An + // authenticated connection is always tracked, so one without a handle cannot be vouched for. + if (!HubConnectionAuthority.IsAuthenticated(context)) return await next(invocationContext); - // 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("Authentication is no longer valid"); + } + + // Already closed, and this is one of its queued calls still draining. + if (handle.IsRevoked) { context.Abort(); - throw new HubException("Access to this public share is no longer valid"); + throw new HubException(handle.Subject.PublicShareId is not null + ? "Access to this public share is no longer valid" + : "Authentication is no longer valid"); } - if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) + switch (await handle.EnsureFreshAsync(_authority.Interval)) { - if (!await ValidateAsync(context, tracked, invocationContext.ServiceProvider)) - { + case RefreshResult.Revoked: context.Abort(); throw new HubException("Authentication is no longer valid"); - } + case RefreshResult.Failed: + throw new HubException("Authentication could not be verified"); } return await next(invocationContext); } - - /// Checks the connection against the database and records the result. - private static async Task ValidateAsync(HubCallerContext context, TrackedHubConnection? tracked, IServiceProvider services) - { - if (!await IsStillAuthenticated(context, services)) return false; - - if (tracked?.PublicShareId is { } publicShareId && !await IsPublicShareStillAccessible(publicShareId, tracked.PasswordStamp, context, services)) return false; - - tracked?.MarkValidated(); - return true; - } - - /// - /// 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; - - // 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 current = await db.ApiTokens - .AsNoTracking() - .FirstOrDefaultAsync(x => - x.Id == tokenId && - (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && - x.User.UserDeactivation == null, context.ConnectionAborted); - if (current is null) return false; - - // The connection keeps the token it opened with. A change whose close message never reached it - // would otherwise leave it on the old pause state, permissions or limits. - return context.GetHttpContext()?.GetItemByType() is { } connectedWith && GrantsTheSame(connectedWith, current); - } - - if (user.TryGetOpenShockUserIdentity() is { } identity) - { - if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return false; - - // Sessions are deleted on logout, on deactivation and on a password reset. - var sessionService = services.GetRequiredService(); - var session = await sessionService.GetSessionByTokenAsync(sessionToken); - if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return false; - - // That deletion happens in Redis after the database commit and can fail, leaving the session - // behind. The account itself is the authority, as it is when a session authenticates a request. - var db = services.GetRequiredService(); - var active = await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); - return active; - } - - return true; - } - - private static bool GrantsTheSame(ApiToken a, ApiToken b) => - a.ShockerControlPaused == b.ShockerControlPaused && - a.Permissions.SequenceEqual(b.Permissions) && - a.ShockerControlIntensityMin == b.ShockerControlIntensityMin && - a.ShockerControlIntensityMax == b.ShockerControlIntensityMax && - a.ShockerControlIntensityMode == b.ShockerControlIntensityMode && - a.ShockerControlDurationMin == b.ShockerControlDurationMin && - a.ShockerControlDurationMax == b.ShockerControlDurationMax && - a.ShockerControlDurationMode == b.ShockerControlDurationMode; -} - -public sealed class HubRevalidationOptions -{ - /// - /// How long a connection's last successful database check stays good. Revocations normally close a - /// connection at once through Redis; this bounds how long one can go on when that message was lost, or - /// when an API token expired on its own. - /// - public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); } diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 7d1c3719..0936fcca 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -438,8 +438,7 @@ public static IServiceCollection AddOpenShockSignalR(this IServiceCollection ser ConfigurationOptions redisConfig) { services.AddOpenShockConnectionAuthority(); - services.AddOptions(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSignalR(options => Microsoft.AspNetCore.SignalR.HubOptionsExtensions.AddFilter(options)) From 0d7ebb20bac7756a6b0dd6482cdac0da20243aaa Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 19:22:15 +0100 Subject: [PATCH 08/24] fix(lcg): close a hub's socket when the hub may no longer connect A hub was only checked when it connected. A deleted hub, one whose token was regenerated or one whose owner was deactivated kept its open socket. The hub socket is now under the shared connection authority and is closed in those cases. Regenerating a hub token announces a hub update so the gateway holding the old connection sees it. --- API/Controller/Devices/DevicesController.cs | 7 ++- .../Controllers/HubControllerBase.cs | 48 ++++++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/API/Controller/Devices/DevicesController.cs b/API/Controller/Devices/DevicesController.cs index ed609d9d..12c36ed6 100644 --- a/API/Controller/Devices/DevicesController.cs +++ b/API/Controller/Devices/DevicesController.cs @@ -13,6 +13,7 @@ using OpenShock.Common.OpenShockDb; using OpenShock.Common.Redis; using OpenShock.Common.Results; +using OpenShock.Common.Services.RedisPubSub; using OpenShock.Internal.Common.Constants; using OpenShock.Internal.Common.Problems; using OpenShock.Internal.Common.Utils; @@ -104,6 +105,7 @@ public async Task EditDevice([FromRoute] Guid deviceId, [FromBody /// Regenerate a device token /// /// The id of the device to regenerate the token for + /// /// /// Successfully regenerated device token /// Device does not exist @@ -113,7 +115,7 @@ public async Task EditDevice([FromRoute] Guid deviceId, [FromBody [TokenPermission(PermissionType.Devices_Auth)] [ProducesResponseType(StatusCodes.Status200OK, MediaTypeNames.Text.Plain)] [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // DeviceNotFound - public async Task RegenerateDeviceToken([FromRoute] Guid deviceId, CancellationToken cancellationToken) + public async Task RegenerateDeviceToken([FromRoute] Guid deviceId, [FromServices] IRedisPubService redisPubService, CancellationToken cancellationToken) { var device = await _db.Devices.FirstOrDefaultAsync(x => x.OwnerId == CurrentUser.Id && x.Id == deviceId, cancellationToken); if (device is null) return Problem(HubError.HubNotFound); @@ -123,6 +125,9 @@ public async Task RegenerateDeviceToken([FromRoute] Guid deviceId var affected = await _db.SaveChangesAsync(cancellationToken); if (affected <= 0) throw new Exception("Failed to save regenerated token"); + // A hub still connected with the old token is closed by its gateway. + await redisPubService.SendDeviceUpdate(device.Id); + return Ok(device.Token); } diff --git a/LiveControlGateway/Controllers/HubControllerBase.cs b/LiveControlGateway/Controllers/HubControllerBase.cs index f0acb95b..1ce91b59 100644 --- a/LiveControlGateway/Controllers/HubControllerBase.cs +++ b/LiveControlGateway/Controllers/HubControllerBase.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using OpenShock.Common.Authentication; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Constants; using OpenShock.Common.Errors; using OpenShock.Common.Extensions; @@ -28,7 +29,7 @@ namespace OpenShock.LiveControlGateway.Controllers; /// /// The type we are receiving / deserializing /// The type we are sending out / serializing -public abstract class HubControllerBase : FlatbuffersWebsocketBaseController, IHubController, IActionFilter where TIn : class, IFlatBufferSerializable where TOut : class, IFlatBufferSerializable +public abstract class HubControllerBase : FlatbuffersWebsocketBaseController, IHubController, IActionFilter, IAuthorizedConnection where TIn : class, IFlatBufferSerializable where TOut : class, IFlatBufferSerializable { /// /// The current hub @@ -78,6 +79,26 @@ public void OnActionExecuting(ActionExecutingContext context) var identity = User.GetOpenShockHubIdentity(); CurrentHubId = identity.GetClaimValueAsGuid(OpenShockAuthClaims.HubId); CurrentHubOwnerId = identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier); + if (HttpContext.TryGetHubTokenFromHeader(out var hubToken)) _hubToken = hubToken; + } + + /// The token this hub authenticated with: it may stay connected only while that is still its token. + private string? _hubToken; + + /// + /// This socket in the , which closes it once the hub is deleted, its + /// token regenerated or its owner deactivated. + /// + private ConnectionHandle? _authority; + + bool IAuthorizedConnection.TryApplyGrant(Grant grant) => true; + + async Task IAuthorizedConnection.CloseAsync() + { + // Not accepted yet when this happens while connecting; the precondition refuses the connection then. + if (WebSocket is null) return; + + await ForceClose(WebSocketCloseStatus.PolicyViolation, "Hub authentication is no longer valid"); } /// @@ -150,8 +171,32 @@ protected override async Task ConnectionPrecondition() // Resolved before the lifetime is added, so the connect attempt metric already carries it. IpInfo = ServiceProvider.GetRequiredService().Enrich(HttpContext.GetRemoteIP()); + // From here on a change to the hub or its owner reaches this socket. Registering also checks it once, + // which covers a change made since it authenticated. Done before the lifetime exists, so a refused hub + // leaves nothing behind. + var (authority, authorityResult) = await ServiceProvider.GetRequiredService().RegisterAsync( + new ConnectionSubject + { + Kind = ConnectionKind.HubSocket, + DeviceId = CurrentHubId, + DeviceOwnerId = CurrentHubOwnerId, + HubToken = _hubToken + }, this); + _authority = authority; + + switch (authorityResult) + { + case RefreshResult.Revoked: + return AuthResultError.TokenInvalid; + case RefreshResult.Failed: + return ExceptionError.Exception; + } + var hubLifetimeResult = await _hubLifetimeManager.TryAddDeviceConnection(5, this, LinkedToken); + // Revoked while the lifetime was being set up, when there was no open socket to close. + if (authority.IsRevoked) return AuthResultError.TokenInvalid; + switch (hubLifetimeResult) { case HubLifetimeManager.Busy: @@ -276,6 +321,7 @@ protected override ValueTask DisposeControllerAsync() { Logger.LogTrace("Disposing controller timer"); _keepAliveTimeoutTimer.Dispose(); + _authority?.Dispose(); return base.DisposeControllerAsync(); } From 5e566bb1759bdacb769c88b1daae6dc987395707 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 19:25:13 +0100 Subject: [PATCH 09/24] refactor: announce authority changes on one Redis channel A deleted session, a deactivated account, a changed API token and a public share whose access changed were each announced on a channel of their own, with a handler of their own on every receiver. They are now one message on one channel that names what changed. A new reason for a connection to look again is one publish call and needs no new subscriber. A message that cannot be read makes every connection look again, as what changed is unknown. Hub changes stay on the hub's own channel, which the gateway holding the hub already listens on. During a rolling deploy, instances on the old version publish on the old channels and are not heard by new ones. A connection that misses a change that way finds out at its next periodic check. --- .../Shares/Links/DeletePublicShare.cs | 3 +- .../Shares/Links/SetPublicSharePassword.cs | 3 +- API/Services/Account/AccountService.cs | 5 +- API/Services/Token/ApiTokenService.cs | 9 +-- .../ConnectionAuthorityRegistryTests.cs | 31 +++++++++- .../ConnectionSubjectTests.cs | 41 +++++++++++++ .../AuthorityChangeSubscriber.cs | 59 ++++++++----------- .../ConnectionAuthorityRegistry.cs | 24 +++++--- .../ConnectionAuthority/ConnectionHandle.cs | 3 + .../ConnectionAuthority/ConnectionSubject.cs | 26 ++++++-- .../Redis/PubSub/AuthorityChangedMessage.cs | 25 ++++++++ .../Services/RedisPubSub/IRedisPubService.cs | 33 +++-------- Common/Services/RedisPubSub/RedisChannels.cs | 31 +++------- .../Services/RedisPubSub/RedisPubService.cs | 21 +------ Common/Services/Session/SessionService.cs | 11 ++-- .../LifetimeManager/HubLifetime.cs | 2 +- 16 files changed, 197 insertions(+), 130 deletions(-) create mode 100644 Common/Redis/PubSub/AuthorityChangedMessage.cs diff --git a/API/Controller/Shares/Links/DeletePublicShare.cs b/API/Controller/Shares/Links/DeletePublicShare.cs index 558466ec..875f18ba 100644 --- a/API/Controller/Shares/Links/DeletePublicShare.cs +++ b/API/Controller/Shares/Links/DeletePublicShare.cs @@ -1,4 +1,5 @@ using OpenShock.API.Services.DeviceUpdate; +using OpenShock.Common.ConnectionAuthority; using System.Net.Mime; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; @@ -39,7 +40,7 @@ public async Task DeletePublicShare([FromRoute] Guid publicShareI if (result <= 0) return Problem(PublicShareError.PublicShareNotFound); await deviceUpdateService.UpdatePublicShare(publicShareId); - await redisPubService.SendPublicShareAccessRevoked(publicShareId); + await redisPubService.SendAuthorityChanged(AuthorityChange.PublicShare(publicShareId)); return LegacyEmptyOk("Deleted public share"); } } diff --git a/API/Controller/Shares/Links/SetPublicSharePassword.cs b/API/Controller/Shares/Links/SetPublicSharePassword.cs index 37f72b63..8a0316e6 100644 --- a/API/Controller/Shares/Links/SetPublicSharePassword.cs +++ b/API/Controller/Shares/Links/SetPublicSharePassword.cs @@ -1,3 +1,4 @@ +using OpenShock.Common.ConnectionAuthority; using System.Net.Mime; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; @@ -48,7 +49,7 @@ public async Task SetPublicSharePassword([FromRoute] Guid publicS share.PasswordStamp = Guid.CreateVersion7(); await _db.SaveChangesAsync(cancellationToken); - await redisPubService.SendPublicShareAccessRevoked(publicShareId); + await redisPubService.SendAuthorityChanged(AuthorityChange.PublicShare(publicShareId)); return Ok(OwnPublicShareResponse.GetFromEf(share)); } } diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 66a93356..79289872 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -1,4 +1,5 @@ -using System.Net.Mail; +using OpenShock.Common.ConnectionAuthority; +using System.Net.Mail; using Microsoft.EntityFrameworkCore; using Npgsql; using OpenShock.API.Services.Signup; @@ -63,7 +64,7 @@ private async Task NotifyUserAuthRevokedAsync(Guid userId) { try { - await _redisPubService.SendUserAuthRevoked(userId); + await _redisPubService.SendAuthorityChanged(AuthorityChange.User(userId)); } catch (Exception ex) { diff --git a/API/Services/Token/ApiTokenService.cs b/API/Services/Token/ApiTokenService.cs index 7e6c081b..5d9e8613 100644 --- a/API/Services/Token/ApiTokenService.cs +++ b/API/Services/Token/ApiTokenService.cs @@ -1,3 +1,4 @@ +using OpenShock.Common.ConnectionAuthority; using System.Linq.Expressions; using System.Net; using Microsoft.EntityFrameworkCore; @@ -206,7 +207,7 @@ public async Task EditTokenV1(Guid tokenId, EditTokenRequest body, Guid? o token.Permissions = body.Permissions.Distinct().ToList(); await _db.SaveChangesAsync(); - await _redisPubService.SendApiTokenUpdate(tokenId); + await _redisPubService.SendAuthorityChanged(AuthorityChange.ApiToken(tokenId)); return true; } @@ -222,7 +223,7 @@ public async Task EditTokenV2(Guid tokenId, EditTokenRequestV2 body, Guid? body.ShockerControl.ApplyTo(token); await _db.SaveChangesAsync(); - await _redisPubService.SendApiTokenUpdate(tokenId); + await _redisPubService.SendAuthorityChanged(AuthorityChange.ApiToken(tokenId)); return true; } @@ -235,7 +236,7 @@ public async Task EditTokenV2(Guid tokenId, EditTokenRequestV2 body, Guid? .ExecuteUpdateAsync(setters => setters.SetProperty(x => x.ShockerControlPaused, paused)); if (nUpdated <= 0) return null; - await _redisPubService.SendApiTokenUpdate(tokenId); + await _redisPubService.SendAuthorityChanged(AuthorityChange.ApiToken(tokenId)); return paused; } @@ -267,7 +268,7 @@ await _auditService.LogAsync( } // Revoked tokens must stop controlling any open live control connection. - await _redisPubService.SendApiTokenUpdate(tokenId); + await _redisPubService.SendAuthorityChanged(AuthorityChange.ApiToken(tokenId)); return true; } diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs index 7d1ff9ef..18a9a598 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -164,7 +164,7 @@ public async Task Signal_NothingGrantedAnymore_ClosesOnce() } [Test] - public async Task SignalSession_ReachesTheConnectionsOfThatSession() + public async Task Signal_Session_ReachesTheConnectionsOfThatSession() { var (registry, resolver) = Create(); var connection = new FakeConnection(); @@ -172,11 +172,11 @@ public async Task SignalSession_ReachesTheConnectionsOfThatSession() var (handle, _) = await registry.RegisterAsync(subject, connection); resolver.Resolve = _ => Task.FromResult(null); - registry.SignalSession("session-b"); + registry.Signal(AuthorityChange.Session("session-b")); await Settle(handle); await Assert.That(handle.IsRevoked).IsFalse(); - registry.SignalSession("session-a"); + registry.Signal(AuthorityChange.Session("session-a")); await Settle(handle); await Assert.That(handle.IsRevoked).IsTrue(); } @@ -297,6 +297,31 @@ public async Task Sweep_ClosesAConnectionWhoseGrantExpired_WhateverItsKind() await Assert.That(connection.Closed).IsEqualTo(1); } + /// After a Redis outage, when any change may have gone unheard. + [Test] + public async Task SignalAll_LooksAgainAtPeriodicConnectionsNow_AndAtHubConnectionsOnTheirNextCall() + { + var (registry, resolver) = Create(); + var liveControlConnection = new FakeConnection(); + var (liveControl, _) = await registry.RegisterAsync(LiveControl(), liveControlConnection); + var (signalR, _) = await registry.RegisterAsync(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), ApiTokenId = Guid.NewGuid() }, new FakeConnection()); + var callsAfterRegister = resolver.Calls; + + // Revoked while nothing could be heard. + resolver.Resolve = _ => Task.FromResult(null); + registry.SignalAll(); + await Settle(liveControl); + await Settle(signalR); + + await Assert.That(liveControl.IsRevoked).IsTrue(); + await Assert.That(liveControlConnection.Closed).IsEqualTo(1); + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); + + // The idle hub connection costs nothing until it is used, and is then checked whatever its last check said. + await Assert.That(signalR.IsRevoked).IsFalse(); + await Assert.That(await signalR.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Revoked); + } + [Test] public async Task Dispose_StopsTrackingWithoutClosing() { diff --git a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs index 48b0f05d..b8e97fed 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs @@ -1,4 +1,6 @@ +using MessagePack; using OpenShock.Common.ConnectionAuthority; +using OpenShock.Common.Redis.PubSub; namespace OpenShock.Common.Tests.ConnectionAuthority; @@ -44,6 +46,45 @@ public async Task OtherChanges_AffectOnlyTheirOwnKindOfId() await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.PublicShare, User))).IsFalse(); } + [Test] + public async Task SessionChange_AffectsOnlyConnectionsOfThatSession() + { + var session = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = User, SessionToken = "token", SessionId = "stored-id" }; + + await Assert.That(session.IsAffectedBy(AuthorityChange.Session("stored-id"))).IsTrue(); + await Assert.That(session.IsAffectedBy(AuthorityChange.Session("another-id"))).IsFalse(); + + // A token connection has no session, and a session change carries no id that could match anything else. + await Assert.That(Subject.IsAffectedBy(AuthorityChange.Session("stored-id"))).IsFalse(); + await Assert.That(new ConnectionSubject { Kind = ConnectionKind.SignalR }.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Session, Guid.Empty))).IsFalse(); + } + + [Test] + [Arguments(AuthorityChangeKind.User)] + [Arguments(AuthorityChangeKind.ApiToken)] + [Arguments(AuthorityChangeKind.Device)] + [Arguments(AuthorityChangeKind.PublicShare)] + public async Task Change_SurvivesTheTripOverRedis(AuthorityChangeKind kind) + { + var change = new AuthorityChange(kind, Guid.NewGuid()); + + var bytes = MessagePackSerializer.Serialize(AuthorityChangedMessage.From(change)); + var received = MessagePackSerializer.Deserialize(bytes).ToChange(); + + await Assert.That(received).IsEqualTo(change); + } + + [Test] + public async Task SessionChange_SurvivesTheTripOverRedis() + { + var change = AuthorityChange.Session("stored-id"); + + var bytes = MessagePackSerializer.Serialize(AuthorityChangedMessage.From(change)); + var received = MessagePackSerializer.Deserialize(bytes).ToChange(); + + await Assert.That(received).IsEqualTo(change); + } + [Test] public async Task AnonymousSubject_IsNotAffectedByAnEmptyId() { diff --git a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs index 7af8892a..7695717a 100644 --- a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs +++ b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs @@ -1,12 +1,14 @@ +using MessagePack; using OpenShock.Common.Redis; +using OpenShock.Common.Redis.PubSub; using OpenShock.Common.Services.RedisPubSub; using StackExchange.Redis; namespace OpenShock.Common.ConnectionAuthority; /// -/// Turns the Redis messages that announce a change in someone's authority into -/// . The same in every service that holds long-lived connections. +/// Turns what Redis says about changes in someone's authority into signals for the +/// . The same in every service that holds long-lived connections. /// /// /// Hub changes are not handled here: a gateway already listens on each connected hub's own channel and signals @@ -18,56 +20,45 @@ public sealed class AuthorityChangeSubscriber : IHostedService private readonly ISubscriber _subscriber; private readonly ConnectionAuthorityRegistry _registry; + private readonly ILogger _logger; - public AuthorityChangeSubscriber(IConnectionMultiplexer connectionMultiplexer, ConnectionAuthorityRegistry registry) + public AuthorityChangeSubscriber(IConnectionMultiplexer connectionMultiplexer, ConnectionAuthorityRegistry registry, ILogger logger) { _subscriber = connectionMultiplexer.GetSubscriber(); _registry = registry; + _logger = logger; } 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); + await _subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, HandleAuthorityChanged); await _subscriber.SubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); } public async Task StopAsync(CancellationToken cancellationToken) { - await _subscriber.UnsubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); - await _subscriber.UnsubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); - await _subscriber.UnsubscribeAsync(RedisChannels.ApiTokenUpdateAll, HandleApiTokenUpdate); - await _subscriber.UnsubscribeAsync(RedisChannels.PublicShareAccessRevoked, HandlePublicShareAccessRevoked); + await _subscriber.UnsubscribeAsync(RedisChannels.AuthorityChanged, HandleAuthorityChanged); await _subscriber.UnsubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); } - private void HandleSessionRevoked(RedisChannel _, RedisValue message) + private void HandleAuthorityChanged(RedisChannel _, RedisValue message) { - var sessionId = (string?)message; - if (!string.IsNullOrEmpty(sessionId)) _registry.SignalSession(sessionId); - } - - private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) - { - if (Guid.TryParse((string?)message, out var userId)) - _registry.Signal(new AuthorityChange(AuthorityChangeKind.User, userId)); - } + if (!message.HasValue) return; - private void HandlePublicShareAccessRevoked(RedisChannel _, RedisValue message) - { - if (Guid.TryParse((string?)message, out var publicShareId)) - _registry.Signal(new AuthorityChange(AuthorityChangeKind.PublicShare, publicShareId)); - } - - 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; + AuthorityChangedMessage change; + try + { + change = MessagePackSerializer.Deserialize((ReadOnlyMemory)message); + } + catch (Exception e) + { + // What changed is unknown, so anything may have. + _logger.LogError(e, "Failed to read an authority change, checking every connection"); + _registry.SignalAll(); + return; + } - _registry.Signal(new AuthorityChange(AuthorityChangeKind.ApiToken, tokenId)); + _registry.Signal(change.ToChange()); } private void HandleKeyExpired(RedisChannel _, RedisValue message) @@ -76,6 +67,6 @@ private void HandleKeyExpired(RedisChannel _, RedisValue message) var key = (string?)message; if (key is null || !key.StartsWith(LoginSessionKeyPrefix, StringComparison.Ordinal)) return; - _registry.SignalSession(key[LoginSessionKeyPrefix.Length..]); + _registry.Signal(AuthorityChange.Session(key[LoginSessionKeyPrefix.Length..])); } } diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index 3108cfaa..4a52a924 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -12,7 +12,8 @@ namespace OpenShock.Common.ConnectionAuthority; /// connection look again, and they all end in the same : /// /// registering, which closes the gap between authenticating and being reachable by a change; -/// a change announced over Redis, see ; +/// a change announced over Redis, see , or the chance that one was missed, see +/// ; /// time, for a change whose announcement was lost or a grant that simply expired, see /// and . /// @@ -75,16 +76,25 @@ public ConnectionHandle Track(ConnectionSubject subject, IAuthorizedConnection c /// Something changed: every connection it can affect looks again. Returns at once, so it is safe to call from /// a Redis callback. /// - public void Signal(AuthorityChange change) => RequestRefreshWhere(subject => subject.IsAffectedBy(change)); - - /// A session was deleted or expired. is the id it was stored under. - public void SignalSession(string sessionId) => RequestRefreshWhere(subject => subject.SessionId == sessionId); + public void Signal(AuthorityChange change) + { + foreach (var handle in _handles.Keys) + { + if (handle.Subject.IsAffectedBy(change)) handle.RequestRefresh(); + } + } - private void RequestRefreshWhere(Func predicate) + /// + /// Changes may have been announced while this instance could not hear them (its Redis connection was down), so + /// no connection's last look can be trusted. Connections that are checked periodically look again now; hub + /// connections look again on their next call, as they would once their interval had passed. + /// + public void SignalAll() { foreach (var handle in _handles.Keys) { - if (predicate(handle.Subject)) handle.RequestRefresh(); + handle.Invalidate(); + if (handle.Subject.Kind != ConnectionKind.SignalR) handle.RequestRefreshIfIdle(); } } diff --git a/Common/ConnectionAuthority/ConnectionHandle.cs b/Common/ConnectionAuthority/ConnectionHandle.cs index 7a848e8a..062d3ee5 100644 --- a/Common/ConnectionAuthority/ConnectionHandle.cs +++ b/Common/ConnectionAuthority/ConnectionHandle.cs @@ -63,6 +63,9 @@ public void UpdateSubject(ConnectionSubject subject) Interlocked.Exchange(ref _lastValidated, 0); } + /// Forget the last look, so the next or sweep looks again. + public void Invalidate() => Interlocked.Exchange(ref _lastValidated, 0); + public bool WasValidatedWithin(TimeSpan interval) { var lastValidated = Interlocked.Read(ref _lastValidated); diff --git a/Common/ConnectionAuthority/ConnectionSubject.cs b/Common/ConnectionAuthority/ConnectionSubject.cs index d627a5c2..b09cf87b 100644 --- a/Common/ConnectionAuthority/ConnectionSubject.cs +++ b/Common/ConnectionAuthority/ConnectionSubject.cs @@ -56,6 +56,7 @@ public sealed record ConnectionSubject /// Whether a change to the thing named by can affect this connection. public bool IsAffectedBy(AuthorityChange change) => change.Kind switch { + AuthorityChangeKind.Session => SessionId is not null && SessionId == change.SessionId, AuthorityChangeKind.User => UserId == change.Id || DeviceOwnerId == change.Id || PublicShareOwnerId == change.Id, AuthorityChangeKind.ApiToken => ApiTokenId == change.Id, AuthorityChangeKind.Device => DeviceId == change.Id, @@ -64,23 +65,36 @@ public sealed record ConnectionSubject }; } -public enum AuthorityChangeKind +/// The values travel over Redis between services, see . +public enum AuthorityChangeKind : byte { /// An account was deactivated, deleted or otherwise may no longer be used. - User, + User = 0, + + /// A login session was deleted or expired. Identified by . + Session = 1, /// An API token was edited, paused or deleted. - ApiToken, + ApiToken = 2, /// A hub, its shockers or the shares on them changed. - Device, + Device = 3, /// Who may use a public share changed. - PublicShare + PublicShare = 4 } /// /// Something a connection's authority can depend on has changed. Carries no detail on purpose: the affected /// connections look up what they may do now, so a change cannot be applied out of order or half-described. /// -public readonly record struct AuthorityChange(AuthorityChangeKind Kind, Guid Id); +public readonly record struct AuthorityChange(AuthorityChangeKind Kind, Guid Id, string? SessionId = null) +{ + public static AuthorityChange User(Guid userId) => new(AuthorityChangeKind.User, userId); + public static AuthorityChange ApiToken(Guid tokenId) => new(AuthorityChangeKind.ApiToken, tokenId); + public static AuthorityChange Device(Guid deviceId) => new(AuthorityChangeKind.Device, deviceId); + public static AuthorityChange PublicShare(Guid publicShareId) => new(AuthorityChangeKind.PublicShare, publicShareId); + + /// The id the session is stored under, see . + public static AuthorityChange Session(string sessionId) => new(AuthorityChangeKind.Session, Guid.Empty, sessionId); +} diff --git a/Common/Redis/PubSub/AuthorityChangedMessage.cs b/Common/Redis/PubSub/AuthorityChangedMessage.cs new file mode 100644 index 00000000..8fb78122 --- /dev/null +++ b/Common/Redis/PubSub/AuthorityChangedMessage.cs @@ -0,0 +1,25 @@ +using MessagePack; +using OpenShock.Common.ConnectionAuthority; + +namespace OpenShock.Common.Redis.PubSub; + +/// +/// An as it travels over Redis. Names what changed and nothing more: receivers look +/// up the current state themselves. +/// +[MessagePackObject] +public sealed class AuthorityChangedMessage +{ + [Key(0)] public required AuthorityChangeKind Kind { get; init; } + [Key(1)] public required Guid Id { get; init; } + [Key(2)] public string? SessionId { get; init; } + + public static AuthorityChangedMessage From(AuthorityChange change) => new() + { + Kind = change.Kind, + Id = change.Id, + SessionId = change.SessionId + }; + + public AuthorityChange ToChange() => new(Kind, Id, SessionId); +} diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 69fc76e2..c7d8b852 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -1,4 +1,5 @@ -using OpenShock.Common.Models; +using OpenShock.Common.ConnectionAuthority; +using OpenShock.Common.Models; using OpenShock.Common.Redis.PubSub; namespace OpenShock.Common.Services.RedisPubSub; @@ -13,32 +14,12 @@ public interface IRedisPubService Task SendDeviceUpdate(Guid deviceId); /// - /// The shocker-control scoping (limits, pause state) of an API token changed, or the token was revoked. - /// Notifies live control gateways so open connections using the token refetch their limits. + /// Something an open connection's authority can depend on changed: an account was deactivated or deleted, a + /// session deleted, an API token edited, paused or deleted, or access to a public share changed. Notifies every + /// instance so the affected connections look up what they may do now, and are closed if that is nothing. + /// Best-effort: a connection that misses it finds out at its next periodic check. /// - /// - /// - Task SendApiTokenUpdate(Guid tokenId); - - /// - /// A login session was deleted. Notifies every instance so open connections that authenticated with it - /// are closed. - /// - /// The id the session was stored under. - Task SendSessionRevoked(string sessionId); - - /// - /// The account was deactivated or deleted. Notifies every instance so all open connections of the user - /// are closed, including ones that authenticated with an API token. - /// - Task SendUserAuthRevoked(Guid userId); - - /// - /// 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 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); + Task SendAuthorityChanged(AuthorityChange change); /// /// Notifies the email outbox consumer that one or more messages were just enqueued, so it drains diff --git a/Common/Services/RedisPubSub/RedisChannels.cs b/Common/Services/RedisPubSub/RedisChannels.cs index 515bab26..3bb0660d 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -10,30 +10,17 @@ public static class RedisChannels public static readonly RedisChannel DeviceStatus = new("device-status", RedisChannel.PatternMode.Literal); - 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 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. + /// Fired when something an open connection's authority can depend on changed: an account, a login session, an + /// API token or a public share. The payload is an + /// naming what changed. Every instance holding long-lived connections listens and has the affected ones look + /// up what they may do now. /// - public static readonly RedisChannel UserAuthRevoked = new("user-auth-revoked", RedisChannel.PatternMode.Literal); + /// + /// Hub changes are not sent here. They go to the hub's own channel, which the + /// gateway holding the hub already listens on. + /// + public static readonly RedisChannel AuthorityChanged = new("authority-changed", RedisChannel.PatternMode.Literal); /// /// Fired when a row is added to the email outbox, so the email consumer drains it immediately diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 9d5a442d..07bf878c 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -1,4 +1,5 @@ using MessagePack; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Models; using OpenShock.Common.Redis.PubSub; using StackExchange.Redis; @@ -22,25 +23,9 @@ public Task SendDeviceUpdate(Guid deviceId) return PublishMessage(deviceId, DeviceMessage.Create(DeviceTriggerType.DeviceInfoUpdated)); } - public Task SendApiTokenUpdate(Guid tokenId) + public Task SendAuthorityChanged(AuthorityChange change) { - // The channel is already scoped to the token, so the message itself carries no payload. - 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 SendPublicShareAccessRevoked(Guid publicShareId) - { - return _subscriber.PublishAsync(RedisChannels.PublicShareAccessRevoked, publicShareId.ToString()); + return Publish(RedisChannels.AuthorityChanged, AuthorityChangedMessage.From(change)); } public Task SendEmailOutboxPending() diff --git a/Common/Services/Session/SessionService.cs b/Common/Services/Session/SessionService.cs index fef78c2b..8b04994c 100644 --- a/Common/Services/Session/SessionService.cs +++ b/Common/Services/Session/SessionService.cs @@ -1,4 +1,5 @@ -using System.Net; +using OpenShock.Common.ConnectionAuthority; +using System.Net; using OpenShock.Common.Constants; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; @@ -98,7 +99,7 @@ public async Task DeleteSessionByIdAsync(Guid sessionId) if (session is null) return false; await _loginSessions.DeleteAsync(session); - await _redisPubService.SendSessionRevoked(session.Id); + await _redisPubService.SendAuthorityChanged(AuthorityChange.Session(session.Id)); return true; } @@ -110,7 +111,7 @@ public async Task DeleteSessionsByUserIdAsync(Guid userId) foreach (var session in sessions) { - await _redisPubService.SendSessionRevoked(session.Id); + await _redisPubService.SendAuthorityChanged(AuthorityChange.Session(session.Id)); } return sessions.Count; @@ -119,7 +120,7 @@ public async Task DeleteSessionsByUserIdAsync(Guid userId) public async Task DeleteSessionAsync(LoginSession loginSession) { await _loginSessions.DeleteAsync(loginSession); - await _redisPubService.SendSessionRevoked(loginSession.Id); + await _redisPubService.SendAuthorityChanged(AuthorityChange.Session(loginSession.Id)); } public async Task LogoutSessionAsync(LoginSession loginSession) @@ -134,6 +135,6 @@ await _auditService.LogAsync( ); await _loginSessions.DeleteAsync(loginSession); - await _redisPubService.SendSessionRevoked(loginSession.Id); + await _redisPubService.SendAuthorityChanged(AuthorityChange.Session(loginSession.Id)); } } diff --git a/LiveControlGateway/LifetimeManager/HubLifetime.cs b/LiveControlGateway/LifetimeManager/HubLifetime.cs index 9749f224..e341eda0 100644 --- a/LiveControlGateway/LifetimeManager/HubLifetime.cs +++ b/LiveControlGateway/LifetimeManager/HubLifetime.cs @@ -462,7 +462,7 @@ public async Task UpdateDevice() // The live control connections on this hub, and the hub's own socket, look at what they may do again. // Not awaited: the commands queued behind this message on the hub's channel must not wait for it. - _authorityRegistry.Signal(new AuthorityChange(AuthorityChangeKind.Device, HubController.Id)); + _authorityRegistry.Signal(AuthorityChange.Device(HubController.Id)); } /// From 6e67336cf37b1e20c28cdb330a9b19023b7fba9e Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 19:25:13 +0100 Subject: [PATCH 10/24] fix: check open connections again when the Redis connection comes back Redis pub/sub delivers a message only to who is listening at that moment. An instance whose Redis connection was down heard no changes, and its connections only found out at their next periodic check. When the subscription connection is restored, live control connections and hub sockets are now checked at once, and hub connections on their next call. --- .../AuthorityChangeSubscriber.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs index 7695717a..7eb48341 100644 --- a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs +++ b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs @@ -11,19 +11,27 @@ namespace OpenShock.Common.ConnectionAuthority; /// . The same in every service that holds long-lived connections. /// /// +/// Redis pub/sub delivers a message only to who is listening at that moment. While this instance's Redis +/// connection is down it hears nothing, so when the connection comes back every connection is treated as if a +/// change had been announced for it. That leaves the periodic check to cover only a message lost on a healthy +/// connection. +/// /// Hub changes are not handled here: a gateway already listens on each connected hub's own channel and signals /// from there, and no other service holds connections that depend on a hub. +/// /// public sealed class AuthorityChangeSubscriber : IHostedService { private static readonly string LoginSessionKeyPrefix = typeof(LoginSession).FullName + ":"; + private readonly IConnectionMultiplexer _connectionMultiplexer; private readonly ISubscriber _subscriber; private readonly ConnectionAuthorityRegistry _registry; private readonly ILogger _logger; public AuthorityChangeSubscriber(IConnectionMultiplexer connectionMultiplexer, ConnectionAuthorityRegistry registry, ILogger logger) { + _connectionMultiplexer = connectionMultiplexer; _subscriber = connectionMultiplexer.GetSubscriber(); _registry = registry; _logger = logger; @@ -33,10 +41,12 @@ public async Task StartAsync(CancellationToken cancellationToken) { await _subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, HandleAuthorityChanged); await _subscriber.SubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); + _connectionMultiplexer.ConnectionRestored += HandleConnectionRestored; } public async Task StopAsync(CancellationToken cancellationToken) { + _connectionMultiplexer.ConnectionRestored -= HandleConnectionRestored; await _subscriber.UnsubscribeAsync(RedisChannels.AuthorityChanged, HandleAuthorityChanged); await _subscriber.UnsubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); } @@ -69,4 +79,13 @@ private void HandleKeyExpired(RedisChannel _, RedisValue message) _registry.Signal(AuthorityChange.Session(key[LoginSessionKeyPrefix.Length..])); } + + private void HandleConnectionRestored(object? sender, ConnectionFailedEventArgs e) + { + // Only the connection that carries the subscriptions matters: messages published while it was down are gone. + if (e.ConnectionType != ConnectionType.Subscription) return; + + _logger.LogInformation("Redis subscription connection restored, checking {Count} open connection(s) for changes missed meanwhile", _registry.Count); + _registry.SignalAll(); + } } From b9c0479a0cbf4b7c318c4073ed11045f17c30540 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 19:36:00 +0100 Subject: [PATCH 11/24] refactor: clean up after moving connections onto the shared authority Renames what still carried the names of what it replaced: the hub filter, the account revocation notifier and the test setting for the check interval. A connection's session id is derived from its session token instead of being passed alongside it. Connections accept any grant unless they say otherwise, and both gateway controllers close a revoked socket through one helper. The user hub reads a token's pause state and limits from the connection's grant instead of the token it connected with. The public share hub and the resolver share one definition of a share a visitor can still reach. Removes a live control result that nothing returned, and its metric label. --- .../Tests/GrantResolverTests.cs | 1 - .../Tests/PublicSharePasswordTests.cs | 4 +-- .../Tests/SignalRUserHubTests.cs | 4 +-- API.IntegrationTests/WebApplicationFactory.cs | 6 ++--- API/Services/Account/AccountService.cs | 6 ++--- .../ConnectionAuthorityRegistryTests.cs | 2 +- .../ConnectionSubjectTests.cs | 11 +++++--- .../ConnectionAuthority/ConnectionSubject.cs | 16 +++++++++--- Common/ConnectionAuthority/GrantResolver.cs | 7 ++---- .../IAuthorizedConnection.cs | 6 ++++- ...ter.cs => ConnectionAuthorityHubFilter.cs} | 4 +-- Common/Hubs/HubConnectionAuthority.cs | 3 +-- Common/Hubs/PublicShareHub.cs | 3 ++- Common/Hubs/UserHub.cs | 10 +++++--- Common/OpenShockDb/PublicShareQueries.cs | 11 ++++++++ Common/OpenShockServiceHelper.cs | 4 +-- Common/Websocket/WebsockBaseController.cs | 9 +++++++ .../Controllers/HubControllerBase.cs | 10 +------- .../Controllers/LiveControlController.cs | 25 +++---------------- LiveControlGateway/Metrics/GatewayMetrics.cs | 3 --- 20 files changed, 77 insertions(+), 68 deletions(-) rename Common/Hubs/{RevalidateAuthenticationHubFilter.cs => ConnectionAuthorityHubFilter.cs} (96%) create mode 100644 Common/OpenShockDb/PublicShareQueries.cs diff --git a/API.IntegrationTests/Tests/GrantResolverTests.cs b/API.IntegrationTests/Tests/GrantResolverTests.cs index c8dec739..3371b415 100644 --- a/API.IntegrationTests/Tests/GrantResolverTests.cs +++ b/API.IntegrationTests/Tests/GrantResolverTests.cs @@ -291,7 +291,6 @@ private Task CreateUser(string prefix) => Kind = ConnectionKind.LiveControl, UserId = user.Id, SessionToken = user.SessionToken, - SessionId = SessionIds.FromToken(user.SessionToken), DeviceId = deviceId, DeviceOwnerId = ownerId }; diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 1484c732..46c7dbd9 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -324,7 +324,7 @@ public async Task Hub_RemovingThePassword_KeepsConnectionsOpen() await SetPassword(owner, shareId, null); - await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + await Task.Delay(WebApplicationFactory.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); await connection.InvokeAsync("Control", Array.Empty()); await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); } @@ -360,7 +360,7 @@ await db.PublicShares.Where(x => x.Id == shareId) .ExecuteUpdateAsync(s => s.SetProperty(x => x.PasswordStamp, stamp)); } - await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + await Task.Delay(WebApplicationFactory.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); Exception? failure = null; try { diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index 302e03e9..ae066f3a 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -170,7 +170,7 @@ public async Task PublicShareHub_Guest_CanConnectAndKeepCalling() 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 Task.Delay(WebApplicationFactory.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); await connection.InvokeAsync("Control", Array.Empty()); await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); @@ -315,7 +315,7 @@ private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnectio { // 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)); + await Task.Delay(WebApplicationFactory.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); // Still open here, so it is the periodic check below that ends it, not a revocation message. await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index 39933f01..ed23dd13 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -27,8 +27,8 @@ public class WebApplicationFactory : WebApplicationFactory [ClassDataSource(Shared = SharedType.PerTestSession)] public required RedisFixture 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); + /// How long an open connection can go on after a change to its authority that was never announced, in tests. + public static readonly TimeSpan ConnectionCheckInterval = TimeSpan.FromSeconds(1); protected override void ConfigureClient(HttpClient client) { @@ -113,7 +113,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) // 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); + services.Configure(options => options.Interval = ConnectionCheckInterval); }); } } diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 79289872..4b8a4421 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -60,7 +60,7 @@ private static string SeedTokenHash() /// failures: the change is already committed, the steps after it must still run, and a connection that /// misses the message is caught by its next periodic check. /// - private async Task NotifyUserAuthRevokedAsync(Guid userId) + private async Task NotifyAccountRevokedAsync(Guid userId) { try { @@ -130,7 +130,7 @@ await _auditService.LogAsync( await transaction.CommitAsync(); } - await NotifyUserAuthRevokedAsync(userId); + await NotifyAccountRevokedAsync(userId); // Remove all login sessions await _sessionService.DeleteSessionsByUserIdAsync(userId); @@ -220,7 +220,7 @@ public async Task Task.FromResult(null); diff --git a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs index b8e97fed..5190fb39 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs @@ -1,5 +1,6 @@ using MessagePack; using OpenShock.Common.ConnectionAuthority; +using OpenShock.Common.Constants; using OpenShock.Common.Redis.PubSub; namespace OpenShock.Common.Tests.ConnectionAuthority; @@ -49,13 +50,17 @@ public async Task OtherChanges_AffectOnlyTheirOwnKindOfId() [Test] public async Task SessionChange_AffectsOnlyConnectionsOfThatSession() { - var session = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = User, SessionToken = "token", SessionId = "stored-id" }; + var session = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = User, SessionToken = new string('t', AuthConstants.GeneratedTokenLength) }; + var storedId = SessionIds.FromToken(session.SessionToken!); - await Assert.That(session.IsAffectedBy(AuthorityChange.Session("stored-id"))).IsTrue(); + // A session is stored under the hash of its token, and that is what a change names. + await Assert.That(storedId).IsNotEqualTo(session.SessionToken); + await Assert.That(session.SessionId).IsEqualTo(storedId); + await Assert.That(session.IsAffectedBy(AuthorityChange.Session(storedId))).IsTrue(); await Assert.That(session.IsAffectedBy(AuthorityChange.Session("another-id"))).IsFalse(); // A token connection has no session, and a session change carries no id that could match anything else. - await Assert.That(Subject.IsAffectedBy(AuthorityChange.Session("stored-id"))).IsFalse(); + await Assert.That(Subject.IsAffectedBy(AuthorityChange.Session(storedId))).IsFalse(); await Assert.That(new ConnectionSubject { Kind = ConnectionKind.SignalR }.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Session, Guid.Empty))).IsFalse(); } diff --git a/Common/ConnectionAuthority/ConnectionSubject.cs b/Common/ConnectionAuthority/ConnectionSubject.cs index b09cf87b..736403b0 100644 --- a/Common/ConnectionAuthority/ConnectionSubject.cs +++ b/Common/ConnectionAuthority/ConnectionSubject.cs @@ -27,10 +27,18 @@ public sealed record ConnectionSubject public Guid? UserId { get; init; } /// The session token the connection authenticated with, if it used a session. - public string? SessionToken { get; init; } - - /// The id the session is stored under, see . - public string? SessionId { get; init; } + public string? SessionToken + { + get; + init + { + field = value; + SessionId = value is null ? null : SessionIds.FromToken(value); + } + } + + /// The id the session of is stored under, which is what a session change names. + public string? SessionId { get; private init; } /// The API token the connection authenticated with, if it used one. public Guid? ApiTokenId { get; init; } diff --git a/Common/ConnectionAuthority/GrantResolver.cs b/Common/ConnectionAuthority/GrantResolver.cs index f53dc5d6..c026eeae 100644 --- a/Common/ConnectionAuthority/GrantResolver.cs +++ b/Common/ConnectionAuthority/GrantResolver.cs @@ -69,11 +69,8 @@ public GrantResolver(OpenShockContext db, ISessionService sessionService) // its password was not set or changed since the visitor got in. var passwordStamp = subject.PublicSharePasswordStamp; var share = await _db.PublicShares - .Where(x => - x.Id == publicShareId && - (x.ExpiresAt == null || x.ExpiresAt > now) && - x.Owner.UserDeactivation == null && - x.PasswordStamp == passwordStamp) + .Where(x => x.Id == publicShareId && x.PasswordStamp == passwordStamp) + .OpenToVisitors(now) .Select(x => new { x.ExpiresAt }) .FirstOrDefaultAsync(cancellationToken); if (share is null) return null; diff --git a/Common/ConnectionAuthority/IAuthorizedConnection.cs b/Common/ConnectionAuthority/IAuthorizedConnection.cs index dae8e27e..0675bb02 100644 --- a/Common/ConnectionAuthority/IAuthorizedConnection.cs +++ b/Common/ConnectionAuthority/IAuthorizedConnection.cs @@ -9,8 +9,12 @@ public interface IAuthorizedConnection /// Called with what the connection may do now, each time that was read. The grant is also kept on the /// connection's . /// + /// + /// Most connections read the grant from their handle whenever they need it and can go on under any grant, which + /// is the default here. + /// /// False when the connection cannot go on under this grant and has to be closed. - bool TryApplyGrant(Grant grant); + bool TryApplyGrant(Grant grant) => true; /// /// Close the connection: it may no longer go on. Called at most once. Must not throw for a connection that is diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/ConnectionAuthorityHubFilter.cs similarity index 96% rename from Common/Hubs/RevalidateAuthenticationHubFilter.cs rename to Common/Hubs/ConnectionAuthorityHubFilter.cs index 946fbd3d..e277c020 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/ConnectionAuthorityHubFilter.cs @@ -18,11 +18,11 @@ namespace OpenShock.Common.Hubs; /// lost; it never runs for an idle connection. /// /// -public sealed class RevalidateAuthenticationHubFilter : IHubFilter +public sealed class ConnectionAuthorityHubFilter : IHubFilter { private readonly HubConnectionAuthority _authority; - public RevalidateAuthenticationHubFilter(HubConnectionAuthority authority) + public ConnectionAuthorityHubFilter(HubConnectionAuthority authority) { _authority = authority; } diff --git a/Common/Hubs/HubConnectionAuthority.cs b/Common/Hubs/HubConnectionAuthority.cs index b993e604..a12f7811 100644 --- a/Common/Hubs/HubConnectionAuthority.cs +++ b/Common/Hubs/HubConnectionAuthority.cs @@ -68,8 +68,7 @@ public static bool IsAuthenticated(HubCallerContext context) { Kind = ConnectionKind.SignalR, UserId = userId, - SessionToken = sessionToken, - SessionId = SessionIds.FromToken(sessionToken) + SessionToken = sessionToken }; } else diff --git a/Common/Hubs/PublicShareHub.cs b/Common/Hubs/PublicShareHub.cs index 80d4dc79..5d380220 100644 --- a/Common/Hubs/PublicShareHub.cs +++ b/Common/Hubs/PublicShareHub.cs @@ -68,7 +68,8 @@ public override async Task OnConnectedAsync() } var share = await _db.PublicShares - .Where(x => x.Id == id && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow) && x.Owner.UserDeactivation == null) + .Where(x => x.Id == id) + .OpenToVisitors(DateTime.UtcNow) .Select(x => new { x.OwnerId, HasPassword = x.PasswordHash != null, x.PasswordStamp }) .FirstOrDefaultAsync(); if (share is null) diff --git a/Common/Hubs/UserHub.cs b/Common/Hubs/UserHub.cs index c3d3eea3..de88f5e3 100644 --- a/Common/Hubs/UserHub.cs +++ b/Common/Hubs/UserHub.cs @@ -95,13 +95,17 @@ public async Task ControlV2(IReadOnlyList shocks, string? customName) CustomName = customName }).FirstAsync(Context.ConnectionAborted); + // What the token grants, as the connection authority last read it. A token connection always has it: the + // hub filter checks the connection before every call. ApiTokenControlLimits? tokenLimits = null; - if (Context.GetHttpContext()?.GetItemByType() is { } apiToken) + if (TokenPermissions is not null) { + if (HubConnectionAuthority.Get(Context)?.Grant?.Token is not { } tokenGrant) return; + // A paused token may not control shockers. - if (apiToken.ShockerControlPaused) return; + if (tokenGrant.Paused) return; - tokenLimits = ApiTokenControlLimits.FromToken(apiToken); + tokenLimits = tokenGrant.Limits; } await _controlSender.ControlByUser(shocks, sender, Clients, tokenLimits, Context.ConnectionAborted); diff --git a/Common/OpenShockDb/PublicShareQueries.cs b/Common/OpenShockDb/PublicShareQueries.cs new file mode 100644 index 00000000..307d2fb1 --- /dev/null +++ b/Common/OpenShockDb/PublicShareQueries.cs @@ -0,0 +1,11 @@ +namespace OpenShock.Common.OpenShockDb; + +public static class PublicShareQueries +{ + /// + /// The public shares a visitor can still reach at : not expired, and their owner's + /// account is active. Says nothing about a share's password. + /// + public static IQueryable OpenToVisitors(this IQueryable publicShares, DateTime now) => + publicShares.Where(x => (x.ExpiresAt == null || x.ExpiresAt > now) && x.Owner.UserDeactivation == null); +} diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 0936fcca..cbc9638a 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -439,9 +439,9 @@ public static IServiceCollection AddOpenShockSignalR(this IServiceCollection ser { services.AddOpenShockConnectionAuthority(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); - services.AddSignalR(options => Microsoft.AspNetCore.SignalR.HubOptionsExtensions.AddFilter(options)) + services.AddSignalR(options => Microsoft.AspNetCore.SignalR.HubOptionsExtensions.AddFilter(options)) .AddOpenShockStackExchangeRedis(options => { options.Configuration = redisConfig; }) .AddJsonProtocol(options => { diff --git a/Common/Websocket/WebsockBaseController.cs b/Common/Websocket/WebsockBaseController.cs index e6068fe8..8cf3a245 100644 --- a/Common/Websocket/WebsockBaseController.cs +++ b/Common/Websocket/WebsockBaseController.cs @@ -348,6 +348,15 @@ protected async Task ForceClose(WebSocketCloseStatus closeStatus, string? status } } + /// + /// Close the socket because what the connection depends on (its session, token, account or hub) may no longer + /// be used. Does nothing while the socket is not accepted yet: the connection is then refused or closed by + /// whoever is still setting it up. + /// + [NonAction] + protected Task CloseRevoked(string statusDescription) => + WebSocket is null ? Task.CompletedTask : ForceClose(WebSocketCloseStatus.PolicyViolation, statusDescription); + /// /// Send initial data to the client /// diff --git a/LiveControlGateway/Controllers/HubControllerBase.cs b/LiveControlGateway/Controllers/HubControllerBase.cs index 1ce91b59..a9e8c0dd 100644 --- a/LiveControlGateway/Controllers/HubControllerBase.cs +++ b/LiveControlGateway/Controllers/HubControllerBase.cs @@ -91,15 +91,7 @@ public void OnActionExecuting(ActionExecutingContext context) /// private ConnectionHandle? _authority; - bool IAuthorizedConnection.TryApplyGrant(Grant grant) => true; - - async Task IAuthorizedConnection.CloseAsync() - { - // Not accepted yet when this happens while connecting; the precondition refuses the connection then. - if (WebSocket is null) return; - - await ForceClose(WebSocketCloseStatus.PolicyViolation, "Hub authentication is no longer valid"); - } + Task IAuthorizedConnection.CloseAsync() => CloseRevoked("Hub authentication is no longer valid"); /// /// Authentication context diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index 3ed0a875..93aa5ae1 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -162,7 +162,6 @@ protected override async Task UnregisterConnection() UserId = _currentUser.Id, ApiTokenId = _tokenId, SessionToken = _sessionToken, - SessionId = _sessionToken is null ? null : SessionIds.FromToken(_sessionToken), DeviceId = id, DeviceOwnerId = ownerId }, this); @@ -244,23 +243,13 @@ public void OnActionExecuting(ActionExecutingContext context) } } - /// - /// The registry replaces as a whole and frames read it from there, so - /// there is nothing to apply here and no grant this connection cannot go on under. - /// - bool IAuthorizedConnection.TryApplyGrant(Grant grant) => true; - /// /// The session, token or account this connection depends on may no longer control. The registry has already /// marked it revoked, which drops every frame; this closes the socket. /// - async Task IAuthorizedConnection.CloseAsync() - { - // Not accepted yet when this happens while connecting; SendInitialData closes it then. - if (WebSocket is null) return; + Task IAuthorizedConnection.CloseAsync() => CloseRevoked(AuthorityRevokedDescription); - await ForceClose(WebSocketCloseStatus.PolicyViolation, "Authentication is no longer valid"); - } + private const string AuthorityRevokedDescription = "Authentication is no longer valid"; /// /// Post action context @@ -283,7 +272,7 @@ protected override async Task SendInitialData() // Revoked after the precondition but before the socket was accepted, when there was nothing to close. if (Authority.IsRevoked) { - await ForceClose(WebSocketCloseStatus.PolicyViolation, "Authentication is no longer valid"); + await CloseRevoked(AuthorityRevokedDescription); return; } @@ -496,7 +485,6 @@ await QueueMessage(new LiveControlResponse { SharePermsAndLimits perms => ForwardFrame(frame, perms, grant.Token?.Limits), Results.NotFound => RejectFrame(frame, GatewayMetrics.FrameOutcome.ShockerNotFound, LiveResponseType.ShockerNotFound), - LiveNotEnabled => RejectFrame(frame, GatewayMetrics.FrameOutcome.LiveNotEnabled, LiveResponseType.ShockerMissingLivePermission), NoPermission => RejectFrame(frame, GatewayMetrics.FrameOutcome.NoPermission, LiveResponseType.ShockerMissingPermission), ShockerPaused => RejectFrame(frame, GatewayMetrics.FrameOutcome.ShockerPaused, LiveResponseType.ShockerPaused) }); @@ -546,7 +534,7 @@ await QueueMessage(new LiveControlResponse } } - private Results.Union5 CheckFramePermissions(Grant grant, Guid shocker, ControlType controlType) + private Results.Union4 CheckFramePermissions(Grant grant, Guid shocker, ControlType controlType) { if (grant.Shockers is null || !grant.Shockers.TryGetValue(shocker, out var shockerShare)) return new Results.NotFound(); @@ -623,11 +611,6 @@ protected override async ValueTask DisposeControllerAsync() } } -/// -/// Union case -/// -public sealed class LiveNotEnabled; - /// /// Union case /// diff --git a/LiveControlGateway/Metrics/GatewayMetrics.cs b/LiveControlGateway/Metrics/GatewayMetrics.cs index 82376680..847f56ed 100644 --- a/LiveControlGateway/Metrics/GatewayMetrics.cs +++ b/LiveControlGateway/Metrics/GatewayMetrics.cs @@ -67,9 +67,6 @@ public static class FrameOutcome /// The frame named a shocker this session does not have. public const string ShockerNotFound = "shocker_not_found"; - /// The share does not permit live control. - public const string LiveNotEnabled = "live_not_enabled"; - /// The share does not permit this control type. public const string NoPermission = "no_permission"; From f6d9774268204522453c0a2f6493d42d84874f9d Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 19:51:46 +0100 Subject: [PATCH 12/24] refactor: announce hub authority changes on the authority channel A change to a hub was announced only on the hub's own channel, as a message telling its gateway to load the hub's shockers again. The gateway took every such message to also mean that who may use the hub had changed. Authority had a second path, and a hub socket that was still being set up was not listening on it yet. Hub changes are now announced on the authority channel like every other kind, and a hub's own channel only carries what the hub is told to do. Regenerating a hub token announces an authority change and no reload. Deactivating or reactivating an account no longer tells the gateways to reload that account's hubs. The account's own authority change already reaches every connection that depends on them. Announcing an authority change no longer throws. It happens after the change is saved, the caller can do nothing about a failure, and the affected connections find out at their next periodic check. One call site handled this itself and the others did not. --- API.IntegrationTests/Tests/DevicesTests.cs | 55 +++++++++++++++++++ API/Controller/Devices/DevicesController.cs | 3 +- API/Services/Account/AccountService.cs | 31 +---------- .../DeviceUpdate/DeviceUpdateService.cs | 15 ++++- .../AuthorityChangeSubscriber.cs | 4 -- .../ConnectionAuthorityRegistry.cs | 2 +- .../ConnectionAuthority/ConnectionSubject.cs | 2 +- .../Services/RedisPubSub/IRedisPubService.cs | 13 +++-- Common/Services/RedisPubSub/RedisChannels.cs | 7 ++- .../Services/RedisPubSub/RedisPubService.cs | 17 +++++- .../LifetimeManager/HubLifetime.cs | 9 --- .../LifetimeManager/HubLifetimeManager.cs | 6 -- 12 files changed, 100 insertions(+), 64 deletions(-) diff --git a/API.IntegrationTests/Tests/DevicesTests.cs b/API.IntegrationTests/Tests/DevicesTests.cs index d0f17c51..5b67c87d 100644 --- a/API.IntegrationTests/Tests/DevicesTests.cs +++ b/API.IntegrationTests/Tests/DevicesTests.cs @@ -1,10 +1,15 @@ using System.Net; using System.Text.Json; using Microsoft.EntityFrameworkCore; +using MessagePack; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Redis.PubSub; +using OpenShock.Common.Services.RedisPubSub; using OpenShock.IntegrationTests.Shared; +using StackExchange.Redis; namespace OpenShock.API.IntegrationTests.Tests; @@ -105,6 +110,56 @@ public async Task RegenerateDeviceToken_OldTokenStopsWorking_NewTokenWorks() await Assert.That((await newHub.GetAsync("/1/device/self")).StatusCode).IsEqualTo(HttpStatusCode.OK); } + // --- A change to a hub is announced as an authority change, so the gateways close or update what depends on it --- + + [Test] + public async Task RegenerateDeviceToken_AnnouncesAnAuthorityChangeForTheHub() + { + var user = await CreateUser("devregenann"); + var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "RegenAnnounceHub"); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var (announced, reloads) = await ListenForHubMessages(deviceId); + + await Assert.That((await client.PutAsync($"/1/devices/{deviceId}", null)).StatusCode).IsEqualTo(HttpStatusCode.OK); + + await announced.WaitAsync(TimeSpan.FromSeconds(10)); + + // Nothing the hub holds changed, so it is not told to load anything again. + await Assert.That(reloads()).IsEqualTo(0); + } + + [Test] + public async Task RemoveDevice_AnnouncesAnAuthorityChangeForTheHub() + { + var user = await CreateUser("devdelann"); + var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "DeleteAnnounceHub"); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var (announced, _) = await ListenForHubMessages(deviceId); + + await Assert.That((await client.DeleteAsync($"/1/devices/{deviceId}")).StatusCode).IsEqualTo(HttpStatusCode.OK); + + await announced.WaitAsync(TimeSpan.FromSeconds(10)); + } + + /// + /// Listens the way a gateway does: for an authority change naming the hub, and on the hub's own channel. + /// + private async Task<(Task Announced, Func Reloads)> ListenForHubMessages(Guid deviceId) + { + var subscriber = WebApplicationFactory.Services.GetRequiredService().GetSubscriber(); + var announced = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var reloads = 0; + + await subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, (_, value) => + { + var change = MessagePackSerializer.Deserialize((ReadOnlyMemory)value).ToChange(); + if (change == AuthorityChange.Device(deviceId)) announced.TrySetResult(); + }); + await subscriber.SubscribeAsync(RedisChannels.DeviceMessage(deviceId), (_, _) => Interlocked.Increment(ref reloads)); + + return (announced.Task, () => Volatile.Read(ref reloads)); + } + [Test] public async Task GetDeviceShockers_ReturnsTheHubsShockers() { diff --git a/API/Controller/Devices/DevicesController.cs b/API/Controller/Devices/DevicesController.cs index 12c36ed6..46e088b8 100644 --- a/API/Controller/Devices/DevicesController.cs +++ b/API/Controller/Devices/DevicesController.cs @@ -7,6 +7,7 @@ using OpenShock.API.Services.DeviceUpdate; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Errors; using OpenShock.Common.Extensions; using OpenShock.Common.Models; @@ -126,7 +127,7 @@ public async Task RegenerateDeviceToken([FromRoute] Guid deviceId if (affected <= 0) throw new Exception("Failed to save regenerated token"); // A hub still connected with the old token is closed by its gateway. - await redisPubService.SendDeviceUpdate(device.Id); + await redisPubService.SendAuthorityChanged(AuthorityChange.Device(device.Id)); return Ok(device.Token); } diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 4b8a4421..34abf56b 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -55,23 +55,6 @@ public AccountService(OpenShockContext db, IRedisPubService redisPubService, ISe private static string SeedTokenHash() => HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)); - /// - /// Tells every instance the account may no longer be used, so its open connections are closed. Swallows - /// failures: the change is already committed, the steps after it must still run, and a connection that - /// misses the message is caught by its next periodic check. - /// - private async Task NotifyAccountRevokedAsync(Guid userId) - { - try - { - await _redisPubService.SendAuthorityChanged(AuthorityChange.User(userId)); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to announce revoked access for user ID: [{Id}]; open connections close on their next check", userId); - } - } - private async Task IsPrivilegedAsync(Guid userId, CancellationToken cancellationToken) { // Queries over the role_type[] column cannot be translated, so the roles are checked here. @@ -130,13 +113,11 @@ await _auditService.LogAsync( await transaction.CommitAsync(); } - await NotifyAccountRevokedAsync(userId); + await _redisPubService.SendAuthorityChanged(AuthorityChange.User(userId)); // Remove all login sessions await _sessionService.DeleteSessionsByUserIdAsync(userId); - await RefreshOwnedDevicesAsync(userId, cancellationToken); - return new Success(); } @@ -175,8 +156,6 @@ await _auditService.LogAsync( await transaction.CommitAsync(); - await RefreshOwnedDevicesAsync(userId, cancellationToken); - return new Success(); } @@ -184,12 +163,6 @@ await _auditService.LogAsync( public Task IsSecurityStampCurrentAsync(Guid userId, Guid securityStamp, CancellationToken cancellationToken = default) => _db.Users.AnyAsync(u => u.Id == userId && u.SecurityStamp == securityStamp, cancellationToken); - private async Task RefreshOwnedDevicesAsync(Guid userId, CancellationToken cancellationToken) - { - var deviceIds = await _db.Devices.Where(x => x.OwnerId == userId).Select(x => x.Id).ToArrayAsync(cancellationToken); - await Task.WhenAll(deviceIds.Select(_redisPubService.SendDeviceUpdate)); - } - /// public async Task> DeleteAccountAsync(Guid executingUserId, Guid userId, string? reason = null, CancellationToken cancellationToken = default) { @@ -220,7 +193,7 @@ public async Task public async Task UpdateDevice(Guid ownerId, Guid deviceId, DeviceUpdateType type, Guid affectedUser) { - var task1 = _redisPubService.SendDeviceUpdate(deviceId); + var task1 = AnnounceAsync(deviceId); var task2 = _hubContext.Clients.Users(ownerId.ToString(), affectedUser.ToString()) .DeviceUpdate(deviceId, type); await Task.WhenAll(task1, task2); @@ -44,7 +45,7 @@ public async Task UpdateDevice(Guid ownerId, Guid deviceId, DeviceUpdateType typ /// public async Task UpdateDevice(Guid ownerId, Guid deviceId, DeviceUpdateType type) { - var task1 = _redisPubService.SendDeviceUpdate(deviceId); + var task1 = AnnounceAsync(deviceId); var task2 = _hubContext.Clients.Users(ownerId.ToString()) .DeviceUpdate(deviceId, type); await Task.WhenAll(task1, task2); @@ -53,7 +54,7 @@ public async Task UpdateDevice(Guid ownerId, Guid deviceId, DeviceUpdateType typ /// public async Task UpdateDeviceForAllShared(Guid ownerId, Guid deviceId, DeviceUpdateType type) { - var task1 = _redisPubService.SendDeviceUpdate(deviceId); + var task1 = AnnounceAsync(deviceId); var sharedWith = await _deviceService.GetSharedUserIdsAsync(deviceId); sharedWith.Add(ownerId); // Add the owner to the list of users to send to @@ -68,6 +69,14 @@ public async Task UpdateDeviceForAllShared(Guid ownerId, Guid deviceId, DeviceUp await Task.WhenAll(task1, task2, task3); } + /// + /// A change to a hub can be either or both of two things, and callers do not say which: its gateway has to + /// load its shockers again, and the connections that depend on it have to look up what they may do now. + /// + private Task AnnounceAsync(Guid deviceId) => Task.WhenAll( + _redisPubService.SendDeviceUpdate(deviceId), + _redisPubService.SendAuthorityChanged(AuthorityChange.Device(deviceId))); + /// public Task UpdatePublicShare(Guid publicShareId) => _publicShareHubContext.Clients.Group(PublicShareHub.GroupName(publicShareId)).Updated(); diff --git a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs index 7eb48341..af6b0a3a 100644 --- a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs +++ b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs @@ -15,10 +15,6 @@ namespace OpenShock.Common.ConnectionAuthority; /// connection is down it hears nothing, so when the connection comes back every connection is treated as if a /// change had been announced for it. That leaves the periodic check to cover only a message lost on a healthy /// connection. -/// -/// Hub changes are not handled here: a gateway already listens on each connected hub's own channel and signals -/// from there, and no other service holds connections that depend on a hub. -/// /// public sealed class AuthorityChangeSubscriber : IHostedService { diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index 4a52a924..16848376 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -18,7 +18,7 @@ namespace OpenShock.Common.ConnectionAuthority; /// and . /// /// Local to the process: every instance tracks its own connections and reacts to the same Redis messages. -/// Lookups scan all connections, which is fine for how rarely authority changes. +/// A change is matched against every connection, which is fine for how rarely authority changes. /// public sealed class ConnectionAuthorityRegistry { diff --git a/Common/ConnectionAuthority/ConnectionSubject.cs b/Common/ConnectionAuthority/ConnectionSubject.cs index 736403b0..1cb2f6da 100644 --- a/Common/ConnectionAuthority/ConnectionSubject.cs +++ b/Common/ConnectionAuthority/ConnectionSubject.cs @@ -85,7 +85,7 @@ public enum AuthorityChangeKind : byte /// An API token was edited, paused or deleted. ApiToken = 2, - /// A hub, its shockers or the shares on them changed. + /// A hub was deleted or got a new token, or its shockers or the shares on them changed. Device = 3, /// Who may use a public share changed. diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index c7d8b852..ef334b07 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -7,7 +7,8 @@ namespace OpenShock.Common.Services.RedisPubSub; public interface IRedisPubService { /// - /// Something about the device or its shockers updated + /// The hub's shockers changed. Tells the gateway holding the hub to load them again. Says nothing about who may + /// use the hub: that is . /// /// /// @@ -15,10 +16,14 @@ public interface IRedisPubService /// /// Something an open connection's authority can depend on changed: an account was deactivated or deleted, a - /// session deleted, an API token edited, paused or deleted, or access to a public share changed. Notifies every - /// instance so the affected connections look up what they may do now, and are closed if that is nothing. - /// Best-effort: a connection that misses it finds out at its next periodic check. + /// session deleted, an API token edited, paused or deleted, a hub, its shockers or the shares on them changed, + /// or access to a public share changed. Notifies every instance so the affected connections look up what they + /// may do now, and are closed if that is nothing. /// + /// + /// Call it after the change is saved. Best-effort, and never throws: a failure to announce is logged, and a + /// connection that misses the message finds out at its next periodic check. Callers need no handling of their own. + /// Task SendAuthorityChanged(AuthorityChange change); /// diff --git a/Common/Services/RedisPubSub/RedisChannels.cs b/Common/Services/RedisPubSub/RedisChannels.cs index 3bb0660d..609ed434 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -12,13 +12,14 @@ public static class RedisChannels /// /// Fired when something an open connection's authority can depend on changed: an account, a login session, an - /// API token or a public share. The payload is an + /// API token, a hub or a public share. The payload is an /// naming what changed. Every instance holding long-lived connections listens and has the affected ones look /// up what they may do now. /// /// - /// Hub changes are not sent here. They go to the hub's own channel, which the - /// gateway holding the hub already listens on. + /// This is the only way a change in authority is announced. A hub's own channel + /// carries what the hub itself is told to do, including to reload its shockers, and says nothing about who may + /// use it. /// public static readonly RedisChannel AuthorityChanged = new("authority-changed", RedisChannel.PatternMode.Literal); diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 07bf878c..d71b9784 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -9,10 +9,12 @@ namespace OpenShock.Common.Services.RedisPubSub; public sealed class RedisPubService : IRedisPubService { private readonly ISubscriber _subscriber; + private readonly ILogger _logger; - public RedisPubService(IConnectionMultiplexer connectionMultiplexer) + public RedisPubService(IConnectionMultiplexer connectionMultiplexer, ILogger logger) { _subscriber = connectionMultiplexer.GetSubscriber(); + _logger = logger; } private Task Publish(RedisChannel channel, T msg) => _subscriber.PublishAsync(channel, (RedisValue)new ReadOnlyMemory(MessagePackSerializer.Serialize(msg))); @@ -23,9 +25,18 @@ public Task SendDeviceUpdate(Guid deviceId) return PublishMessage(deviceId, DeviceMessage.Create(DeviceTriggerType.DeviceInfoUpdated)); } - public Task SendAuthorityChanged(AuthorityChange change) + public async Task SendAuthorityChanged(AuthorityChange change) { - return Publish(RedisChannels.AuthorityChanged, AuthorityChangedMessage.From(change)); + try + { + await Publish(RedisChannels.AuthorityChanged, AuthorityChangedMessage.From(change)); + } + catch (Exception e) + { + // The change itself is already saved and the caller can do nothing about this. The connections it + // affects find out at their next periodic check. + _logger.LogWarning(e, "Failed to announce a change in authority ({Kind} [{Id}]); open connections find out at their next check", change.Kind, change.Kind == AuthorityChangeKind.Session ? "session" : change.Id); + } } public Task SendEmailOutboxPending() diff --git a/LiveControlGateway/LifetimeManager/HubLifetime.cs b/LiveControlGateway/LifetimeManager/HubLifetime.cs index e341eda0..8da7baee 100644 --- a/LiveControlGateway/LifetimeManager/HubLifetime.cs +++ b/LiveControlGateway/LifetimeManager/HubLifetime.cs @@ -5,7 +5,6 @@ using MessagePack; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; -using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Constants; using OpenShock.Common.Hubs; using OpenShock.Common.Models; @@ -55,7 +54,6 @@ public sealed class HubLifetime : IAsyncDisposable private readonly IBatchUpdateService _batchUpdateService; private readonly IHubContext _userHub; private readonly GatewayMetrics _metrics; - private readonly ConnectionAuthorityRegistry _authorityRegistry; private readonly RedisChannel _deviceMsgChannel; private readonly ISubscriber _subscriber; @@ -101,7 +99,6 @@ public sealed class HubLifetime : IAsyncDisposable /// /// /// - /// /// public HubLifetime([Range(1, 10)] byte tps, IHubController hubController, IDbContextFactory dbContextFactory, @@ -111,7 +108,6 @@ public HubLifetime([Range(1, 10)] byte tps, IHubController hubController, IBatchUpdateService batchUpdateService, IHubContext userHub, GatewayMetrics metrics, - ConnectionAuthorityRegistry authorityRegistry, ILogger logger) { HubController = hubController; @@ -122,7 +118,6 @@ public HubLifetime([Range(1, 10)] byte tps, IHubController hubController, _batchUpdateService = batchUpdateService; _userHub = userHub; _metrics = metrics; - _authorityRegistry = authorityRegistry; _logger = logger; _waitBetweenTicks = TimeSpan.FromMilliseconds(1000.0 / tps); @@ -459,10 +454,6 @@ public async Task UpdateDevice() { await using var db = await _dbContextFactory.CreateDbContextAsync(_cancellationSource.Token); await UpdateShockers(db, _cancellationSource.Token); - - // The live control connections on this hub, and the hub's own socket, look at what they may do again. - // Not awaited: the commands queued behind this message on the hub's channel must not wait for it. - _authorityRegistry.Signal(AuthorityChange.Device(HubController.Id)); } /// diff --git a/LiveControlGateway/LifetimeManager/HubLifetimeManager.cs b/LiveControlGateway/LifetimeManager/HubLifetimeManager.cs index 3bf80793..0c71f3d6 100644 --- a/LiveControlGateway/LifetimeManager/HubLifetimeManager.cs +++ b/LiveControlGateway/LifetimeManager/HubLifetimeManager.cs @@ -2,7 +2,6 @@ using System.Diagnostics.Metrics; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; -using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Hubs; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; @@ -32,7 +31,6 @@ public sealed class HubLifetimeManager private readonly GatewayMetrics _metrics; private readonly IBatchUpdateService _batchUpdateService; private readonly IHubContext _userHub; - private readonly ConnectionAuthorityRegistry _authorityRegistry; private readonly ILogger _logger; /// @@ -56,7 +54,6 @@ public sealed class HubLifetimeManager /// /// /// - /// /// public HubLifetimeManager( IDbContextFactory dbContextFactory, @@ -68,7 +65,6 @@ public HubLifetimeManager( GatewayMetrics metrics, IBatchUpdateService batchUpdateService, IHubContext userHub, - ConnectionAuthorityRegistry authorityRegistry, [FromKeyedServices("OpenShock.Gateway.Meter")] Meter meter ) { @@ -80,7 +76,6 @@ public HubLifetimeManager( _metrics = metrics; _batchUpdateService = batchUpdateService; _userHub = userHub; - _authorityRegistry = authorityRegistry; _logger = _loggerFactory.CreateLogger(); @@ -218,7 +213,6 @@ private HubLifetime CreateNewLifetime(byte tps, IHubController hubController) _batchUpdateService, _userHub, _metrics, - _authorityRegistry, _loggerFactory.CreateLogger()); return deviceLifetime; From cee9a0316754bcee706efbf62638dcd4005014dd Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 20:17:30 +0100 Subject: [PATCH 13/24] fix: keep a change in authority from being lost to a failed or older check A reason to check a connection again is now counted on its handle, and a check only settles the changes that existed when it started. Until a later check succeeds the connection has no usable grant and is not fresh, so an announced pause or revocation takes effect even while it cannot be looked up. The sweep now covers every connection, so an idle hub connection is closed within the interval after a logout whose announcement was lost. A hub socket revoked before it was accepted is closed, a revoked live control socket no longer leaves its read pending, and a subject no longer prints its credentials. --- .../Tests/SignalRUserHubTests.cs | 42 ++--- API/Controller/Devices/DevicesController.cs | 2 +- .../Shares/Links/DeletePublicShare.cs | 2 +- .../Shares/Links/SetPublicSharePassword.cs | 2 +- API/Services/Account/AccountService.cs | 4 +- API/Services/Token/ApiTokenService.cs | 2 +- .../ConnectionAuthorityRegistryTests.cs | 158 ++++++++++++++++-- .../ConnectionSubjectTests.cs | 19 +++ Common/Common.csproj | 4 + .../ConnectionAuthorityOptions.cs | 10 ++ .../ConnectionAuthorityRegistry.cs | 77 ++++----- .../ConnectionAuthority/ConnectionHandle.cs | 116 +++++++++---- .../ConnectionAuthority/ConnectionSubject.cs | 9 +- Common/Hubs/ConnectionAuthorityHubFilter.cs | 14 +- Common/Services/Session/SessionService.cs | 4 +- .../Controllers/HubControllerBase.cs | 22 ++- .../Controllers/LiveControlController.cs | 14 +- 17 files changed, 368 insertions(+), 133 deletions(-) create mode 100644 Common/ConnectionAuthority/ConnectionAuthorityOptions.cs diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index ae066f3a..7293f02b 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -176,10 +176,10 @@ public async Task PublicShareHub_Guest_CanConnectAndKeepCalling() await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); } - // --- The fallback: a connection whose revocation was never announced stops at its next periodic check --- + // --- The fallback: a connection whose revocation was never announced is closed by the periodic check, also while idle --- [Test] - public async Task Invoke_AfterSessionRemovedWithoutAnnouncement_FailsAndClosesConnection() + public async Task Idle_AfterSessionRemovedWithoutAnnouncement_ClosesConnection() { var user = await CreateUser("hubrevalsess"); await using var connection = await ConnectCheckedSessionAsync(user); @@ -188,11 +188,11 @@ public async Task Invoke_AfterSessionRemovedWithoutAnnouncement_FailsAndClosesCo var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); await Assert.That(await redis.KeyDeleteAsync(SessionKey(user.SessionToken))).IsTrue(); - await AssertInvokeFailsAndConnectionClosesAsync(connection); + await AssertIdleConnectionClosesAsync(connection); } [Test] - public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsAndClosesConnection() + public async Task Idle_AfterAccountDeactivated_WithTheSessionLeftBehind_ClosesConnection() { // Deactivation removes sessions after its database commit; if that step fails the session survives. var user = await CreateUser("hubrevaldeact"); @@ -210,7 +210,7 @@ public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsA await db.SaveChangesAsync(); } - await AssertInvokeFailsAndConnectionClosesAsync(connection); + await AssertIdleConnectionClosesAsync(connection); } public enum UnannouncedTokenChange @@ -226,7 +226,7 @@ public enum UnannouncedTokenChange [Arguments(UnannouncedTokenChange.Paused)] [Arguments(UnannouncedTokenChange.Expired)] [Arguments(UnannouncedTokenChange.OwnerDeactivated)] - public async Task Invoke_AfterApiTokenChangedWithoutAnnouncement_FailsAndClosesConnection(UnannouncedTokenChange change) + public async Task Idle_AfterApiTokenChangedWithoutAnnouncement_ClosesConnection(UnannouncedTokenChange change) { var user = await CreateUser("hubrevaltok"); var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate"); @@ -264,7 +264,7 @@ public async Task Invoke_AfterApiTokenChangedWithoutAnnouncement_FailsAndClosesC } } - await AssertInvokeFailsAndConnectionClosesAsync(connection); + await AssertIdleConnectionClosesAsync(connection); } private Task CreateUser(string prefix) => @@ -311,29 +311,15 @@ internal static async Task ConnectAsync(WebApplicationFactory fac return connection; } - private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnection connection) + /// + /// The connection makes no call, so it is the periodic check that finds the change and closes it. A call + /// afterwards has nothing left to run on. + /// + private static async Task AssertIdleConnectionClosesAsync(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.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); - - // Still open here, so it is the periodic check below that ends it, not a revocation message. - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); - - // 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); + + await Assert.That(async () => await connection.InvokeAsync("Reboot", Guid.CreateVersion7())).ThrowsException(); } /// Waits for the server to close the connection, without calling anything on it. diff --git a/API/Controller/Devices/DevicesController.cs b/API/Controller/Devices/DevicesController.cs index 46e088b8..2511b037 100644 --- a/API/Controller/Devices/DevicesController.cs +++ b/API/Controller/Devices/DevicesController.cs @@ -106,7 +106,7 @@ public async Task EditDevice([FromRoute] Guid deviceId, [FromBody /// Regenerate a device token /// /// The id of the device to regenerate the token for - /// + /// Announces the new token, so a hub connected with the old one is closed. /// /// Successfully regenerated device token /// Device does not exist diff --git a/API/Controller/Shares/Links/DeletePublicShare.cs b/API/Controller/Shares/Links/DeletePublicShare.cs index 875f18ba..cfa61abc 100644 --- a/API/Controller/Shares/Links/DeletePublicShare.cs +++ b/API/Controller/Shares/Links/DeletePublicShare.cs @@ -1,10 +1,10 @@ using OpenShock.API.Services.DeviceUpdate; -using OpenShock.Common.ConnectionAuthority; using System.Net.Mime; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Errors; using OpenShock.Common.Extensions; using OpenShock.Common.Models; diff --git a/API/Controller/Shares/Links/SetPublicSharePassword.cs b/API/Controller/Shares/Links/SetPublicSharePassword.cs index 8a0316e6..fea9d9da 100644 --- a/API/Controller/Shares/Links/SetPublicSharePassword.cs +++ b/API/Controller/Shares/Links/SetPublicSharePassword.cs @@ -1,4 +1,3 @@ -using OpenShock.Common.ConnectionAuthority; using System.Net.Mime; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; @@ -6,6 +5,7 @@ using OpenShock.API.Models.Response; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Errors; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.RedisPubSub; diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 34abf56b..ad45e6f0 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -1,8 +1,8 @@ -using OpenShock.Common.ConnectionAuthority; -using System.Net.Mail; +using System.Net.Mail; using Microsoft.EntityFrameworkCore; using Npgsql; using OpenShock.API.Services.Signup; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Constants; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; diff --git a/API/Services/Token/ApiTokenService.cs b/API/Services/Token/ApiTokenService.cs index 5d9e8613..4c15b7dc 100644 --- a/API/Services/Token/ApiTokenService.cs +++ b/API/Services/Token/ApiTokenService.cs @@ -1,10 +1,10 @@ -using OpenShock.Common.ConnectionAuthority; using System.Linq.Expressions; using System.Net; using Microsoft.EntityFrameworkCore; using OpenShock.API.Models; using OpenShock.API.Models.Requests; using OpenShock.API.Models.Response; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Constants; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs index 8ba3b1af..69477f7f 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -256,11 +256,104 @@ public async Task Track_DoesNotLookUntilUsed() var handle = registry.Track(new ConnectionSubject { Kind = ConnectionKind.SignalR, PublicShareId = Guid.NewGuid() }, new FakeConnection()); await Assert.That(resolver.Calls).IsEqualTo(0); - await Assert.That(handle.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); + await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsFalse(); } + /// + /// A connection gets its second subject while a check of the first is still running. That check must not make + /// the new subject count as checked. + /// + [Test] + public async Task UpdateSubject_DuringARunningCheck_StaysUncheckedUntilTheNewSubjectIs() + { + var (registry, resolver) = Create(); + var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + + var checkStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseCheck = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + resolver.Resolve = async _ => + { + checkStarted.TrySetResult(); + await releaseCheck.Task; + return Grant.Empty; + }; + + var running = handle.RefreshAsync(); + await checkStarted.Task; + + var publicShareId = Guid.NewGuid(); + handle.UpdateSubject(handle.Subject with { PublicShareId = publicShareId }); + releaseCheck.SetResult(); + await running; + + await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsFalse(); + await Assert.That(handle.Grant).IsNull(); + + ConnectionSubject? checkedSubject = null; + resolver.Resolve = subject => + { + checkedSubject = subject; + return Task.FromResult(Grant.Empty); + }; + await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Valid); + await Assert.That(checkedSubject!.PublicShareId).IsEqualTo(publicShareId); + await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsTrue(); + } + + /// + /// An announced change whose check fails: the connection is not closed for it, but what it was granted before + /// the change is gone, and it is closed once the check can be made. + /// [Test] - public async Task Sweep_LooksAgainAtDuePeriodicConnections_NotAtIdleHubConnections() + public async Task Signal_CheckFails_NothingIsGrantedUntilACheckSucceeds() + { + var (registry, resolver) = Create(); + var tokenId = Guid.NewGuid(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(LiveControl(tokenId: tokenId), connection); + + resolver.Resolve = _ => throw new InvalidOperationException("database is down"); + registry.Signal(AuthorityChange.ApiToken(tokenId)); + await Settle(handle); + + await Assert.That(handle.IsRevoked).IsFalse(); + await Assert.That(connection.Closed).IsEqualTo(0); + await Assert.That(handle.Grant).IsNull(); + await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsFalse(); + await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Failed); + + // The database is back, and the token is indeed gone. Nothing announces it a second time. + resolver.Resolve = _ => Task.FromResult(null); + registry.Sweep(DateTime.UtcNow); + await Settle(handle); + + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(connection.Closed).IsEqualTo(1); + } + + [Test] + public async Task Signal_CheckFails_ThenSucceeds_GrantsAgain() + { + var (registry, resolver) = Create(); + var tokenId = Guid.NewGuid(); + var (handle, _) = await registry.RegisterAsync(LiveControl(tokenId: tokenId), new FakeConnection()); + + resolver.Resolve = _ => throw new InvalidOperationException("database is down"); + registry.Signal(AuthorityChange.ApiToken(tokenId)); + await Settle(handle); + await Assert.That(handle.Grant).IsNull(); + + var paused = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(1) }; + resolver.Resolve = _ => Task.FromResult(paused); + registry.Sweep(DateTime.UtcNow); + await Settle(handle); + + await Assert.That(handle.Grant).IsSameReferenceAs(paused); + await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsTrue(); + } + + [Test] + public async Task Sweep_ChecksEveryDueConnection_IdleHubConnectionsIncluded() { var (registry, resolver) = Create(interval: TimeSpan.Zero); var (liveControl, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); @@ -271,7 +364,20 @@ public async Task Sweep_LooksAgainAtDuePeriodicConnections_NotAtIdleHubConnectio await Settle(liveControl); await Settle(signalR); - await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 2); + } + + [Test] + public async Task Sweep_LeavesARecentlyCheckedConnectionAlone() + { + var (registry, resolver) = Create(); + var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + var callsAfterRegister = resolver.Calls; + + registry.Sweep(DateTime.UtcNow); + await Settle(handle); + + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister); } [Test] @@ -299,13 +405,13 @@ public async Task Sweep_ClosesAConnectionWhoseGrantExpired_WhateverItsKind() /// After a Redis outage, when any change may have gone unheard. [Test] - public async Task SignalAll_LooksAgainAtPeriodicConnectionsNow_AndAtHubConnectionsOnTheirNextCall() + public async Task SignalAll_ChecksEveryConnection() { var (registry, resolver) = Create(); var liveControlConnection = new FakeConnection(); + var signalRConnection = new FakeConnection(); var (liveControl, _) = await registry.RegisterAsync(LiveControl(), liveControlConnection); - var (signalR, _) = await registry.RegisterAsync(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), ApiTokenId = Guid.NewGuid() }, new FakeConnection()); - var callsAfterRegister = resolver.Calls; + var (signalR, _) = await registry.RegisterAsync(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), ApiTokenId = Guid.NewGuid() }, signalRConnection); // Revoked while nothing could be heard. resolver.Resolve = _ => Task.FromResult(null); @@ -315,11 +421,43 @@ public async Task SignalAll_LooksAgainAtPeriodicConnectionsNow_AndAtHubConnectio await Assert.That(liveControl.IsRevoked).IsTrue(); await Assert.That(liveControlConnection.Closed).IsEqualTo(1); - await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); + await Assert.That(signalR.IsRevoked).IsTrue(); + await Assert.That(signalRConnection.Closed).IsEqualTo(1); + } + + /// + /// A check that started during the outage may have read before a change nobody heard. It must not count as + /// the check the reconnect asks for. + /// + [Test] + public async Task SignalAll_DuringARunningCheck_ChecksAgain() + { + var (registry, resolver) = Create(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(LiveControl(), connection); + + var staleReadStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseStaleRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var reads = 0; + resolver.Resolve = async _ => + { + if (Interlocked.Increment(ref reads) > 1) return null; - // The idle hub connection costs nothing until it is used, and is then checked whatever its last check said. - await Assert.That(signalR.IsRevoked).IsFalse(); - await Assert.That(await signalR.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Revoked); + staleReadStarted.SetResult(); + await releaseStaleRead.Task; + return Grant.Empty; + }; + + var running = handle.RefreshAsync(); + await staleReadStarted.Task; + + registry.SignalAll(); + releaseStaleRead.SetResult(); + await running; + + await Assert.That(reads).IsEqualTo(2); + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(connection.Closed).IsEqualTo(1); } [Test] diff --git a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs index 5190fb39..af683fc8 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs @@ -97,4 +97,23 @@ public async Task AnonymousSubject_IsNotAffectedByAnEmptyId() await Assert.That(guest.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Guid.Empty))).IsFalse(); } + + [Test] + public async Task ToString_LeavesOutTheCredentials() + { + var subject = new ConnectionSubject + { + Kind = ConnectionKind.HubSocket, + DeviceId = Guid.NewGuid(), + SessionToken = "secret-session-token", + HubToken = "secret-hub-token" + }; + + var text = subject.ToString(); + + await Assert.That(text).DoesNotContain("secret-session-token"); + await Assert.That(text).DoesNotContain("secret-hub-token"); + await Assert.That(text).DoesNotContain(subject.SessionId!); + await Assert.That(text).Contains(subject.DeviceId.ToString()!); + } } diff --git a/Common/Common.csproj b/Common/Common.csproj index 40e10d9f..2ed9f7e1 100644 --- a/Common/Common.csproj +++ b/Common/Common.csproj @@ -9,6 +9,10 @@ false + + + + diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs new file mode 100644 index 00000000..975353e1 --- /dev/null +++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs @@ -0,0 +1,10 @@ +namespace OpenShock.Common.ConnectionAuthority; + +public sealed class ConnectionAuthorityOptions +{ + /// + /// How long a connection's last successful check stays good. Changes normally reach a connection at once + /// through Redis; this bounds how long one can go on, or an idle one stay open, when that message was lost. + /// + public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); +} diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index 16848376..0c3b9235 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -9,27 +9,35 @@ namespace OpenShock.Common.ConnectionAuthority; /// /// A connection is authenticated once, when it opens, and then lives for as long as the client likes. This is /// what keeps it from outliving the session, token, share or account it depends on. Three things make a -/// connection look again, and they all end in the same : +/// connection check again, and they all end in the same : /// /// registering, which closes the gap between authenticating and being reachable by a change; /// a change announced over Redis, see , or the chance that one was missed, see /// ; /// time, for a change whose announcement was lost or a grant that simply expired, see -/// and . +/// . This covers every connection, idle or not, so none stays open for much longer than +/// after what it depends on is gone. /// +/// A check that fails (database or Redis trouble) never closes a connection. What it leaves behind depends on +/// why it ran. After an announced change the connection has no usable until +/// a check succeeds, so a pause or a revocation that was announced takes effect even while it cannot be looked +/// up. After a check that ran only because time passed, the connection keeps what it had. Either way the check is +/// tried again at every sweep. +/// /// Local to the process: every instance tracks its own connections and reacts to the same Redis messages. /// A change is matched against every connection, which is fine for how rarely authority changes. +/// /// public sealed class ConnectionAuthorityRegistry { - private readonly ConcurrentDictionary _handles = new(); /// - /// How many connections may be looked at at once. Connections that opened together come due together, and a + /// How many connections may be checked at once. Connections that opened together come due together, and a /// change to one account or hub can reach many; this keeps either from taking every database connection. /// - private const int MaxConcurrentLooks = 32; + private const int MaxConcurrentChecks = 32; - private readonly SemaphoreSlim _lookGate = new(MaxConcurrentLooks, MaxConcurrentLooks); + private readonly ConcurrentDictionary _handles = new(); + private readonly SemaphoreSlim _checkGate = new(MaxConcurrentChecks, MaxConcurrentChecks); private readonly IServiceScopeFactory _scopeFactory; private readonly IOptions _options; private readonly ILogger _logger; @@ -41,13 +49,13 @@ public ConnectionAuthorityRegistry(IServiceScopeFactory scopeFactory, IOptionsHow long a successful look stays good before time alone is a reason to look again. + /// How long a successful check stays good before time alone is a reason to check again. public TimeSpan Interval => _options.Value.Interval; public int Count => _handles.Count; /// - /// Start tracking a connection without looking at it yet, for one whose first use will. Changes reach it from + /// Start tracking a connection without checking it yet, for one whose first use will. Changes reach it from /// here on. /// public ConnectionHandle Track(ConnectionSubject subject, IAuthorizedConnection connection) @@ -58,11 +66,11 @@ public ConnectionHandle Track(ConnectionSubject subject, IAuthorizedConnection c } /// - /// Start tracking a connection and look at it once. The connection was authenticated before it was tracked, - /// so a change announced in between found nothing to act on; this look sees it. + /// Start tracking a connection and check it once. The connection was authenticated before it was tracked, + /// so a change announced in between found nothing to act on; this check sees it. /// /// - /// The handle, and how that first look went. On the connection was already + /// The handle, and how that first check went. On the connection was already /// closed and is no longer tracked. /// public async Task<(ConnectionHandle Handle, RefreshResult Result)> RegisterAsync(ConnectionSubject subject, IAuthorizedConnection connection) @@ -73,34 +81,36 @@ public ConnectionHandle Track(ConnectionSubject subject, IAuthorizedConnection c } /// - /// Something changed: every connection it can affect looks again. Returns at once, so it is safe to call from - /// a Redis callback. + /// Something changed: every connection it can affect loses what it was granted and checks again. Returns at + /// once, so it is safe to call from a Redis callback. /// public void Signal(AuthorityChange change) { foreach (var handle in _handles.Keys) { - if (handle.Subject.IsAffectedBy(change)) handle.RequestRefresh(); + if (!handle.Subject.IsAffectedBy(change)) continue; + + handle.Invalidate(); + handle.RequestRefresh(); } } /// /// Changes may have been announced while this instance could not hear them (its Redis connection was down), so - /// no connection's last look can be trusted. Connections that are checked periodically look again now; hub - /// connections look again on their next call, as they would once their interval had passed. + /// every connection is treated as if one had been announced for it. /// public void SignalAll() { foreach (var handle in _handles.Keys) { handle.Invalidate(); - if (handle.Subject.Kind != ConnectionKind.SignalR) handle.RequestRefreshIfIdle(); + handle.RequestRefresh(); } } /// - /// Time as a reason to look again: connections that are checked periodically and are due, and any connection - /// whose grant has reached its expiry. + /// Time as a reason to check again: connections whose last good check is older than or + /// did not cover a change announced since, and connections whose grant has reached its expiry. /// public void Sweep(DateTime now) { @@ -108,39 +118,39 @@ public void Sweep(DateTime now) foreach (var handle in _handles.Keys) { var expired = handle.Grant is { } grant && grant.IsExpired(now); - var due = handle.Subject.Kind != ConnectionKind.SignalR && !handle.WasValidatedWithin(interval); - if (expired || due) handle.RequestRefreshIfIdle(); + if (expired || !handle.WasCheckedWithin(interval)) handle.RequestRefreshIfIdle(); } } internal void Remove(ConnectionHandle handle) => _handles.TryRemove(handle, out _); - internal async Task ResolveOnceAsync(ConnectionHandle handle) + internal async Task CheckOnceAsync(ConnectionHandle handle) { if (handle.IsRevoked) return RefreshResult.Revoked; + var (subject, changes) = handle.BeginCheck(); + Grant? grant; - await _lookGate.WaitAsync(); + await _checkGate.WaitAsync(); try { await using var scope = _scopeFactory.CreateAsyncScope(); var resolver = scope.ServiceProvider.GetRequiredService(); - grant = await resolver.ResolveAsync(handle.Subject, CancellationToken.None); + grant = await resolver.ResolveAsync(subject, CancellationToken.None); } catch (Exception e) { - // A transient failure must not drop a legitimate connection. It keeps what it had and is looked at - // again on the next reason to. - _logger.LogWarning(e, "Error while checking what a {Kind} connection may do", handle.Subject.Kind); + // A transient failure must not drop a legitimate connection. It is checked again at the next sweep. + _logger.LogWarning(e, "Error while checking what a {Kind} connection may do", subject.Kind); return RefreshResult.Failed; } finally { - _lookGate.Release(); + _checkGate.Release(); } - if (grant is not null && handle.Accept(grant)) return RefreshResult.Valid; + if (grant is not null && handle.Accept(grant, changes)) return RefreshResult.Valid; await RevokeAsync(handle); return RefreshResult.Revoked; @@ -167,12 +177,3 @@ private async Task RevokeAsync(ConnectionHandle handle) } } } - -public sealed class ConnectionAuthorityOptions -{ - /// - /// How long a connection's last successful check stays good. Changes normally reach a connection at once - /// through Redis; this bounds how long one can go on when that message was lost. - /// - public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); -} diff --git a/Common/ConnectionAuthority/ConnectionHandle.cs b/Common/ConnectionAuthority/ConnectionHandle.cs index 062d3ee5..a89112e7 100644 --- a/Common/ConnectionAuthority/ConnectionHandle.cs +++ b/Common/ConnectionAuthority/ConnectionHandle.cs @@ -10,17 +10,23 @@ public enum RefreshResult /// The connection may not go on and was closed. Revoked, - /// The check itself failed (database or Redis trouble). Nothing changed; it is tried again later. + /// The check itself failed (database or Redis trouble). The connection stays open and is checked again later. Failed } /// -/// One registered connection: what it depends on, what it may currently do, and the means to look again. +/// One registered connection: what it depends on, what it may currently do, and the means to check again. /// /// -/// Looking again is the only way the grant changes, and only one look runs at a time per connection. A request -/// that arrives while one is running makes it run once more when it finishes, so the last look always started -/// after the last request. That is what keeps an older read from replacing a newer one. +/// Checking is the only way the grant changes, and only one check runs at a time per connection. A request that +/// arrives while one is running makes it run once more when it finishes, so the last check always started after +/// the last request. +/// +/// A reason to check again (an announced change, a new subject) is counted, and a check only settles the reasons +/// that existed when it started. So a check that fails, or one that was already running, cannot make the +/// connection look checked: until a later check succeeds it has no usable and is not +/// fresh. +/// /// public sealed class ConnectionHandle : IDisposable { @@ -32,11 +38,17 @@ public sealed class ConnectionHandle : IDisposable private bool _rerun; private volatile ConnectionSubject _subject; - private volatile Grant? _grant; private volatile bool _revoked; + private Grant? _grant; - // 0 means "never validated": Stopwatch timestamps are never 0 in practice. - private long _lastValidated; + /// How many reasons to check again there have been. + private long _changes; + + /// as it was when the last successful check started. + private long _checkedChanges; + + // 0 means "never checked": Stopwatch timestamps are never 0 in practice. + private long _lastChecked; internal ConnectionHandle(ConnectionAuthorityRegistry registry, ConnectionSubject subject, IAuthorizedConnection connection) { @@ -47,41 +59,57 @@ internal ConnectionHandle(ConnectionAuthorityRegistry registry, ConnectionSubjec public ConnectionSubject Subject => _subject; - /// What the connection may do, as of the last successful look. Null until the first one. - public Grant? Grant => _grant; + /// + /// What the connection may do, as of the last successful check. Null until the first one, once the connection + /// is revoked, and while a change announced since has not been checked successfully: what was allowed before + /// that change can no longer be relied on. + /// + public Grant? Grant + { + get + { + lock (_lock) + { + return _revoked || _changes != _checkedChanges ? null : _grant; + } + } + } /// The connection may no longer go on. Set before it is closed, and never unset. public bool IsRevoked => _revoked; /// - /// Replace what the connection depends on, for a connection that learns more after it was registered. The next - /// looks again whatever was checked before. + /// Replace what the connection depends on, for a connection that learns more after it was registered. It + /// counts as unchecked until a check of the new subject succeeds. /// public void UpdateSubject(ConnectionSubject subject) { - _subject = subject; - Interlocked.Exchange(ref _lastValidated, 0); + lock (_lock) + { + _subject = subject; + _changes++; + } } - /// Forget the last look, so the next or sweep looks again. - public void Invalidate() => Interlocked.Exchange(ref _lastValidated, 0); - - public bool WasValidatedWithin(TimeSpan interval) + /// Whether a check that covers every change so far succeeded less than ago. + public bool WasCheckedWithin(TimeSpan maxAge) { - var lastValidated = Interlocked.Read(ref _lastValidated); - return lastValidated != 0 && Stopwatch.GetElapsedTime(lastValidated) < interval; + lock (_lock) + { + return _lastChecked != 0 && _changes == _checkedChanges && Stopwatch.GetElapsedTime(_lastChecked) < maxAge; + } } - /// Look again unless the last successful look is younger than . + /// Check again unless says the last check is still good. public Task EnsureFreshAsync(TimeSpan maxAge) { if (_revoked) return Task.FromResult(RefreshResult.Revoked); - if (WasValidatedWithin(maxAge)) return Task.FromResult(RefreshResult.Valid); + if (WasCheckedWithin(maxAge)) return Task.FromResult(RefreshResult.Valid); return RefreshAsync(); } /// - /// Look up what the connection may do now, and close it if that is nothing. If a look is already running, this + /// Look up what the connection may do now, and close it if that is nothing. If a check is already running, this /// waits for one that started after this call. /// public Task RefreshAsync() @@ -103,8 +131,20 @@ public Task RefreshAsync() /// Like , for a caller that cannot wait. Never throws. public void RequestRefresh() => _ = RefreshAsync(); - /// Completes once no look is running, for a caller that requested one without waiting for it. - public Task WhenIdleAsync() + /// + /// Something the connection depends on changed, or may have: what it was granted before counts for nothing + /// until a check that starts from here on succeeds. + /// + internal void Invalidate() + { + lock (_lock) + { + _changes++; + } + } + + /// Completes once no check is running, for a caller that requested one without waiting for it. + internal Task WhenIdleAsync() { lock (_lock) { @@ -112,7 +152,7 @@ public Task WhenIdleAsync() } } - /// Look again unless a look is already running: for a reason that one already covers. + /// Check again unless a check is already running: for a reason that one already covers. internal void RequestRefreshIfIdle() { lock (_lock) @@ -129,7 +169,7 @@ private async Task RunAsync() while (true) { - var result = await _registry.ResolveOnceAsync(this); + var result = await _registry.CheckOnceAsync(this); lock (_lock) { @@ -145,12 +185,28 @@ private async Task RunAsync() } } - internal bool Accept(Grant grant) + /// What a check that starts now has to look up, and which changes it will have covered. + internal (ConnectionSubject Subject, long Changes) BeginCheck() + { + lock (_lock) + { + return (_subject, _changes); + } + } + + /// What the check found. + /// The changes the check covers, from . + internal bool Accept(Grant grant, long changes) { if (!_connection.TryApplyGrant(grant)) return false; - _grant = grant; - Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); + lock (_lock) + { + _grant = grant; + _checkedChanges = changes; + _lastChecked = Stopwatch.GetTimestamp(); + } + return true; } diff --git a/Common/ConnectionAuthority/ConnectionSubject.cs b/Common/ConnectionAuthority/ConnectionSubject.cs index 1cb2f6da..2e2bccd8 100644 --- a/Common/ConnectionAuthority/ConnectionSubject.cs +++ b/Common/ConnectionAuthority/ConnectionSubject.cs @@ -5,7 +5,7 @@ namespace OpenShock.Common.ConnectionAuthority; /// public enum ConnectionKind { - /// A SignalR hub connection. Checked when it is used, never while idle. + /// A SignalR hub connection. SignalR, /// A live control socket on a gateway. Needs shockers.use and the shockers it may control. @@ -71,6 +71,13 @@ public string? SessionToken AuthorityChangeKind.PublicShare => PublicShareId == change.Id, _ => false }; + + /// + /// Written out by hand so the generated one cannot put or , which + /// are credentials, into a log. + /// + public override string ToString() => + $"{Kind} connection (user [{UserId}], API token [{ApiTokenId}], hub [{DeviceId}], public share [{PublicShareId}])"; } /// The values travel over Redis between services, see . diff --git a/Common/Hubs/ConnectionAuthorityHubFilter.cs b/Common/Hubs/ConnectionAuthorityHubFilter.cs index e277c020..adcd516a 100644 --- a/Common/Hubs/ConnectionAuthorityHubFilter.cs +++ b/Common/Hubs/ConnectionAuthorityHubFilter.cs @@ -14,8 +14,8 @@ namespace OpenShock.Common.Hubs; /// The deciding and the closing are done by the , shared with every /// other kind of long-lived connection. This filter only puts hub connections under it: it registers them, and /// before a hub method call makes sure the connection was checked within -/// . That check is what covers a change whose Redis message was -/// lost; it never runs for an idle connection. +/// and since the last change announced for it. A call is +/// refused when that cannot be established. Idle connections are checked by the registry's sweep. /// /// public sealed class ConnectionAuthorityHubFilter : IHubFilter @@ -88,20 +88,22 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception if (handle.IsRevoked) { context.Abort(); - throw new HubException(handle.Subject.PublicShareId is not null - ? "Access to this public share is no longer valid" - : "Authentication is no longer valid"); + throw Revoked(handle); } switch (await handle.EnsureFreshAsync(_authority.Interval)) { case RefreshResult.Revoked: context.Abort(); - throw new HubException("Authentication is no longer valid"); + throw Revoked(handle); case RefreshResult.Failed: throw new HubException("Authentication could not be verified"); } return await next(invocationContext); } + + private static HubException Revoked(ConnectionHandle handle) => new(handle.Subject.PublicShareId is not null + ? "Access to this public share is no longer valid" + : "Authentication is no longer valid"); } diff --git a/Common/Services/Session/SessionService.cs b/Common/Services/Session/SessionService.cs index 8b04994c..73ab6957 100644 --- a/Common/Services/Session/SessionService.cs +++ b/Common/Services/Session/SessionService.cs @@ -1,5 +1,5 @@ -using OpenShock.Common.ConnectionAuthority; -using System.Net; +using System.Net; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Constants; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; diff --git a/LiveControlGateway/Controllers/HubControllerBase.cs b/LiveControlGateway/Controllers/HubControllerBase.cs index a9e8c0dd..7d7814b8 100644 --- a/LiveControlGateway/Controllers/HubControllerBase.cs +++ b/LiveControlGateway/Controllers/HubControllerBase.cs @@ -63,6 +63,17 @@ protected HubLifetime HubLifetime private DateTimeOffset _connected = DateTimeOffset.UtcNow; private string? _userAgent; + private const string AuthorityRevokedDescription = "Hub authentication is no longer valid"; + + /// The token this hub authenticated with: it may stay connected only while that is still its token. + private string? _hubToken; + + /// + /// This socket in the , which closes it once the hub is deleted, its + /// token regenerated or its owner deactivated. + /// + private ConnectionHandle? _authority; + /// public override Guid Id => CurrentHubId; @@ -82,16 +93,13 @@ public void OnActionExecuting(ActionExecutingContext context) if (HttpContext.TryGetHubTokenFromHeader(out var hubToken)) _hubToken = hubToken; } - /// The token this hub authenticated with: it may stay connected only while that is still its token. - private string? _hubToken; + Task IAuthorizedConnection.CloseAsync() => CloseRevoked(AuthorityRevokedDescription); /// - /// This socket in the , which closes it once the hub is deleted, its - /// token regenerated or its owner deactivated. + /// Revoked after the precondition but before the socket was accepted, when there was nothing to close. /// - private ConnectionHandle? _authority; - - Task IAuthorizedConnection.CloseAsync() => CloseRevoked("Hub authentication is no longer valid"); + protected override Task SendInitialData() => + _authority is { IsRevoked: true } ? CloseRevoked(AuthorityRevokedDescription) : Task.CompletedTask; /// /// Authentication context diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index 93aa5ae1..e2291c94 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -67,6 +67,8 @@ public sealed class LiveControlController : WebsocketBaseController private ConnectionHandle? _authority; + private const string AuthorityRevokedDescription = "Authentication is no longer valid"; + private ConnectionHandle Authority => _authority ?? throw new InvalidOperationException("Connection authority is null but was accessed"); @@ -170,7 +172,9 @@ protected override async Task UnregisterConnection() switch (authorityResult) { case RefreshResult.Revoked: - return WebsocketError.WebsocketLiveControlHubNotFound; + // The hub and the caller's access to it were just read above, so what did not hold up is what + // the caller authenticated with. + return _tokenId is not null ? AuthResultError.TokenInvalid : AuthResultError.SessionInvalid; case RefreshResult.Failed: return ExceptionError.Exception; } @@ -249,8 +253,6 @@ public void OnActionExecuting(ActionExecutingContext context) /// Task IAuthorizedConnection.CloseAsync() => CloseRevoked(AuthorityRevokedDescription); - private const string AuthorityRevokedDescription = "Authentication is no longer valid"; - /// /// Post action context /// @@ -296,7 +298,7 @@ protected override async Task HandleReceive(CancellationToken cancellation { var message = await JsonWebSocketUtils.ReceiveFullMessageAsyncNonAlloc>( WebSocket!, - LinkedToken + cancellationToken ); switch (message) @@ -457,7 +459,9 @@ private async Task ProcessFrameInternal(ClientLiveFrame frame) var authority = Authority; if (authority.IsRevoked) return; - // Read once: everything below is decided from this one grant even if it is replaced meanwhile. + // Read once: everything below is decided from this one grant even if it is replaced meanwhile. There is + // none while a change announced for this connection has not been checked yet, so a pause or a lost share + // stops control even when it cannot be looked up right now. var grant = authority.Grant; if (grant is null) return; From 4c3d8a314bbb63aecd1beb69c90811dfbaa723c8 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 20:23:48 +0100 Subject: [PATCH 14/24] refactor: describe what a connection depends on by its kind ConnectionSubject was one record with a kind and ten optional fields, where only the resolver knew which of them a kind needs. It is now a closed record per kind of connection, holding a credential that is either a session or an API token, so a subject that makes no sense can no longer be built and the resolver no longer has to turn one down. --- .../Tests/GrantResolverTests.cs | 39 +---- .../ConnectionAuthorityRegistryTests.cs | 41 ++--- .../ConnectionSubjectTests.cs | 99 ++++++----- .../ConnectionAuthorityRegistry.cs | 7 +- .../ConnectionAuthority/ConnectionSubject.cs | 140 ++++++++++------ Common/ConnectionAuthority/GrantResolver.cs | 156 ++++++++++-------- Common/Hubs/ConnectionAuthorityHubFilter.cs | 2 +- Common/Hubs/HubConnectionAuthority.cs | 43 ++--- .../Controllers/HubControllerBase.cs | 10 +- .../Controllers/LiveControlController.cs | 28 +--- 10 files changed, 291 insertions(+), 274 deletions(-) diff --git a/API.IntegrationTests/Tests/GrantResolverTests.cs b/API.IntegrationTests/Tests/GrantResolverTests.cs index 3371b415..e866724e 100644 --- a/API.IntegrationTests/Tests/GrantResolverTests.cs +++ b/API.IntegrationTests/Tests/GrantResolverTests.cs @@ -145,7 +145,7 @@ public async Task LiveControl_Session_OfAnotherUser_MayNotGoOn() var other = await CreateUser("grantsessmixother"); var (deviceId, _) = await CreateShockerOnDevice(owner.Id); - var subject = LiveControlBySession(owner, deviceId, owner.Id) with { SessionToken = other.SessionToken }; + var subject = new LiveControlSubject(new SessionCredential(owner.Id, other.SessionToken), deviceId, owner.Id); await Assert.That(await Resolve(subject)).IsNull(); } @@ -226,23 +226,12 @@ public async Task HubConnection_TokenWithoutShockersUse_MayGoOn() var owner = await CreateUser("grantsignalr"); var (tokenId, _) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "grant-hub", [PermissionType.Shockers_Edit]); - var grant = await Resolve(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = owner.Id, ApiTokenId = tokenId }); + var grant = await Resolve(new SignalRSubject(new ApiTokenCredential(owner.Id, tokenId))); await Assert.That(grant).IsNotNull(); await Assert.That(grant!.Shockers).IsNull(); } - [Test] - public async Task LiveControl_WithoutSessionOrToken_MayNotGoOn() - { - var owner = await CreateUser("grantanon"); - var (deviceId, _) = await CreateShockerOnDevice(owner.Id); - - var subject = new ConnectionSubject { Kind = ConnectionKind.LiveControl, UserId = owner.Id, DeviceId = deviceId, DeviceOwnerId = owner.Id }; - - await Assert.That(await Resolve(subject)).IsNull(); - } - // --- The hub's own socket --- public enum HubChange @@ -260,7 +249,7 @@ public async Task HubSocket_MayGoOnOnlyWhileTheHubCouldStillConnect(HubChange ch { var owner = await CreateUser("granthub"); var (deviceId, hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id); - var subject = new ConnectionSubject { Kind = ConnectionKind.HubSocket, DeviceId = deviceId, DeviceOwnerId = owner.Id, HubToken = hubToken }; + var subject = new HubSocketSubject(deviceId, owner.Id, hubToken); await Assert.That(await Resolve(subject)).IsNotNull(); switch (change) @@ -286,23 +275,11 @@ public async Task HubSocket_MayGoOnOnlyWhileTheHubCouldStillConnect(HubChange ch private Task CreateUser(string prefix) => TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), "SecurePassword123#"); - private static ConnectionSubject LiveControlBySession(AuthenticatedUser user, Guid deviceId, Guid ownerId) => new() - { - Kind = ConnectionKind.LiveControl, - UserId = user.Id, - SessionToken = user.SessionToken, - DeviceId = deviceId, - DeviceOwnerId = ownerId - }; - - private static ConnectionSubject LiveControlByToken(Guid userId, Guid tokenId, Guid deviceId, Guid ownerId) => new() - { - Kind = ConnectionKind.LiveControl, - UserId = userId, - ApiTokenId = tokenId, - DeviceId = deviceId, - DeviceOwnerId = ownerId - }; + private static LiveControlSubject LiveControlBySession(AuthenticatedUser user, Guid deviceId, Guid ownerId) => + new(new SessionCredential(user.Id, user.SessionToken), deviceId, ownerId); + + private static LiveControlSubject LiveControlByToken(Guid userId, Guid tokenId, Guid deviceId, Guid ownerId) => + new(new ApiTokenCredential(userId, tokenId), deviceId, ownerId); private async Task Resolve(ConnectionSubject subject) { diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs index 69477f7f..44e4b047 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -51,14 +51,17 @@ private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Cre return (registry, resolver); } - private static ConnectionSubject LiveControl(Guid? userId = null, Guid? tokenId = null, Guid? deviceId = null, Guid? ownerId = null) => new() - { - Kind = ConnectionKind.LiveControl, - UserId = userId ?? Guid.NewGuid(), - ApiTokenId = tokenId, - DeviceId = deviceId ?? Guid.NewGuid(), - DeviceOwnerId = ownerId ?? Guid.NewGuid() - }; + private static LiveControlSubject LiveControl(Guid? userId = null, Guid? tokenId = null, Guid? deviceId = null, Guid? ownerId = null) => new( + new ApiTokenCredential(userId ?? Guid.NewGuid(), tokenId ?? Guid.NewGuid()), + deviceId ?? Guid.NewGuid(), + ownerId ?? Guid.NewGuid()); + + private static SignalRSubject SignalR() => new(new ApiTokenCredential(Guid.NewGuid(), Guid.NewGuid())); + + private static SignalRSubject OnPublicShare(ConnectionHandle handle, Guid publicShareId) => + (SignalRSubject)handle.Subject with { PublicShare = new PublicShareAccess(publicShareId, Guid.NewGuid(), PasswordStamp: null) }; + + private static Guid? PublicShareOf(ConnectionSubject? subject) => (subject as SignalRSubject)?.PublicShare?.PublicShareId; /// Signals only start a look; this waits for it (and any rerun) to finish. private static Task Settle(ConnectionHandle handle) => handle.WhenIdleAsync(); @@ -168,7 +171,7 @@ public async Task Signal_Session_ReachesTheConnectionsOfThatSession() { var (registry, resolver) = Create(); var connection = new FakeConnection(); - var subject = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), SessionToken = "session-a" }; + var subject = new SignalRSubject(new SessionCredential(Guid.NewGuid(), "session-a")); var (handle, _) = await registry.RegisterAsync(subject, connection); resolver.Resolve = _ => Task.FromResult(null); @@ -237,15 +240,15 @@ public async Task EnsureFresh_LooksAgainOnlyOnceTheLastLookIsTooOld() public async Task UpdateSubject_MakesTheNextUseLookAgain() { var (registry, resolver) = Create(); - var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + var (handle, _) = await registry.RegisterAsync(SignalR(), new FakeConnection()); var callsAfterRegister = resolver.Calls; var publicShareId = Guid.NewGuid(); - handle.UpdateSubject(handle.Subject with { PublicShareId = publicShareId }); + handle.UpdateSubject(OnPublicShare(handle, publicShareId)); await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1)); await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); - await Assert.That(handle.Subject.PublicShareId).IsEqualTo(publicShareId); + await Assert.That(PublicShareOf(handle.Subject)).IsEqualTo(publicShareId); } [Test] @@ -253,7 +256,7 @@ public async Task Track_DoesNotLookUntilUsed() { var (registry, resolver) = Create(); - var handle = registry.Track(new ConnectionSubject { Kind = ConnectionKind.SignalR, PublicShareId = Guid.NewGuid() }, new FakeConnection()); + var handle = registry.Track(new SignalRSubject(Credential: null, new PublicShareAccess(Guid.NewGuid(), Guid.NewGuid(), PasswordStamp: null)), new FakeConnection()); await Assert.That(resolver.Calls).IsEqualTo(0); await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsFalse(); @@ -267,7 +270,7 @@ public async Task Track_DoesNotLookUntilUsed() public async Task UpdateSubject_DuringARunningCheck_StaysUncheckedUntilTheNewSubjectIs() { var (registry, resolver) = Create(); - var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + var (handle, _) = await registry.RegisterAsync(SignalR(), new FakeConnection()); var checkStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var releaseCheck = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -282,7 +285,7 @@ public async Task UpdateSubject_DuringARunningCheck_StaysUncheckedUntilTheNewSub await checkStarted.Task; var publicShareId = Guid.NewGuid(); - handle.UpdateSubject(handle.Subject with { PublicShareId = publicShareId }); + handle.UpdateSubject(OnPublicShare(handle, publicShareId)); releaseCheck.SetResult(); await running; @@ -296,7 +299,7 @@ public async Task UpdateSubject_DuringARunningCheck_StaysUncheckedUntilTheNewSub return Task.FromResult(Grant.Empty); }; await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Valid); - await Assert.That(checkedSubject!.PublicShareId).IsEqualTo(publicShareId); + await Assert.That(PublicShareOf(checkedSubject)).IsEqualTo(publicShareId); await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsTrue(); } @@ -357,7 +360,7 @@ public async Task Sweep_ChecksEveryDueConnection_IdleHubConnectionsIncluded() { var (registry, resolver) = Create(interval: TimeSpan.Zero); var (liveControl, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); - var (signalR, _) = await registry.RegisterAsync(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), ApiTokenId = Guid.NewGuid() }, new FakeConnection()); + var (signalR, _) = await registry.RegisterAsync(SignalR(), new FakeConnection()); var callsAfterRegister = resolver.Calls; registry.Sweep(DateTime.UtcNow); @@ -387,7 +390,7 @@ public async Task Sweep_ClosesAConnectionWhoseGrantExpired_WhateverItsKind() var expiresAt = DateTime.UtcNow.AddMinutes(5); resolver.Resolve = _ => Task.FromResult(new Grant { ExpiresAt = expiresAt }); var connection = new FakeConnection(); - var (handle, _) = await registry.RegisterAsync(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), ApiTokenId = Guid.NewGuid() }, connection); + var (handle, _) = await registry.RegisterAsync(SignalR(), connection); // Not yet: nothing to do for a connection that was just checked. registry.Sweep(expiresAt.AddMinutes(-1)); @@ -411,7 +414,7 @@ public async Task SignalAll_ChecksEveryConnection() var liveControlConnection = new FakeConnection(); var signalRConnection = new FakeConnection(); var (liveControl, _) = await registry.RegisterAsync(LiveControl(), liveControlConnection); - var (signalR, _) = await registry.RegisterAsync(new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), ApiTokenId = Guid.NewGuid() }, signalRConnection); + var (signalR, _) = await registry.RegisterAsync(SignalR(), signalRConnection); // Revoked while nothing could be heard. resolver.Resolve = _ => Task.FromResult(null); diff --git a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs index af683fc8..e883a831 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs @@ -14,54 +14,65 @@ public sealed class ConnectionSubjectTests private static readonly Guid Share = Guid.NewGuid(); private static readonly Guid ShareOwner = Guid.NewGuid(); - private static readonly ConnectionSubject Subject = new() - { - Kind = ConnectionKind.LiveControl, - UserId = User, - ApiTokenId = Token, - DeviceId = Device, - DeviceOwnerId = Owner, - PublicShareId = Share, - PublicShareOwnerId = ShareOwner - }; + private static readonly ApiTokenCredential ByToken = new(User, Token); + + private static readonly LiveControlSubject LiveControl = new(ByToken, Device, Owner); + + private static readonly SignalRSubject OnPublicShare = new(ByToken, new PublicShareAccess(Share, ShareOwner, PasswordStamp: null)); + + private static readonly HubSocketSubject HubSocket = new(Device, Owner, "hub-token"); [Test] public async Task UserChange_AffectsTheUserTheHubOwnerAndTheShareOwner() { - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, User))).IsTrue(); - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Owner))).IsTrue(); - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, ShareOwner))).IsTrue(); - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Guid.NewGuid()))).IsFalse(); + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.User(User))).IsTrue(); + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.User(Owner))).IsTrue(); + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.User(Guid.NewGuid()))).IsFalse(); + + await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.User(User))).IsTrue(); + await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.User(ShareOwner))).IsTrue(); + await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.User(Owner))).IsFalse(); + + await Assert.That(HubSocket.IsAffectedBy(AuthorityChange.User(Owner))).IsTrue(); + await Assert.That(HubSocket.IsAffectedBy(AuthorityChange.User(User))).IsFalse(); } [Test] public async Task OtherChanges_AffectOnlyTheirOwnKindOfId() { - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.ApiToken, Token))).IsTrue(); - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Device, Device))).IsTrue(); - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.PublicShare, Share))).IsTrue(); + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.ApiToken(Token))).IsTrue(); + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.Device(Device))).IsTrue(); + await Assert.That(HubSocket.IsAffectedBy(AuthorityChange.Device(Device))).IsTrue(); + await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.ApiToken(Token))).IsTrue(); + await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.PublicShare(Share))).IsTrue(); // The same id under another kind is a different thing. - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Device, Token))).IsFalse(); - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.ApiToken, Device))).IsFalse(); - await Assert.That(Subject.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.PublicShare, User))).IsFalse(); + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.Device(Token))).IsFalse(); + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.ApiToken(Device))).IsFalse(); + await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.PublicShare(User))).IsFalse(); + + // And a kind of connection is not affected by what it does not depend on. + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.PublicShare(Share))).IsFalse(); + await Assert.That(HubSocket.IsAffectedBy(AuthorityChange.ApiToken(Token))).IsFalse(); + await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.Device(Device))).IsFalse(); } [Test] public async Task SessionChange_AffectsOnlyConnectionsOfThatSession() { - var session = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = User, SessionToken = new string('t', AuthConstants.GeneratedTokenLength) }; - var storedId = SessionIds.FromToken(session.SessionToken!); + var credential = new SessionCredential(User, new string('t', AuthConstants.GeneratedTokenLength)); + var session = new SignalRSubject(credential); + var storedId = SessionIds.FromToken(credential.SessionToken); // A session is stored under the hash of its token, and that is what a change names. - await Assert.That(storedId).IsNotEqualTo(session.SessionToken); - await Assert.That(session.SessionId).IsEqualTo(storedId); + await Assert.That(storedId).IsNotEqualTo(credential.SessionToken); + await Assert.That(credential.SessionId).IsEqualTo(storedId); await Assert.That(session.IsAffectedBy(AuthorityChange.Session(storedId))).IsTrue(); await Assert.That(session.IsAffectedBy(AuthorityChange.Session("another-id"))).IsFalse(); // A token connection has no session, and a session change carries no id that could match anything else. - await Assert.That(Subject.IsAffectedBy(AuthorityChange.Session(storedId))).IsFalse(); - await Assert.That(new ConnectionSubject { Kind = ConnectionKind.SignalR }.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Session, Guid.Empty))).IsFalse(); + await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.Session(storedId))).IsFalse(); + await Assert.That(new SignalRSubject(Credential: null).IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Session, Guid.Empty))).IsFalse(); } [Test] @@ -91,29 +102,35 @@ public async Task SessionChange_SurvivesTheTripOverRedis() } [Test] - public async Task AnonymousSubject_IsNotAffectedByAnEmptyId() + public async Task Guest_IsNotAffectedByAnEmptyId() { - var guest = new ConnectionSubject { Kind = ConnectionKind.SignalR }; + var guest = new SignalRSubject(Credential: null, new PublicShareAccess(Share, ShareOwner, PasswordStamp: null)); await Assert.That(guest.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Guid.Empty))).IsFalse(); + await Assert.That(guest.IsAffectedBy(AuthorityChange.User(ShareOwner))).IsTrue(); } [Test] public async Task ToString_LeavesOutTheCredentials() { - var subject = new ConnectionSubject + var session = new SessionCredential(User, "secret-session-token"); + ConnectionSubject[] subjects = + [ + new SignalRSubject(session), + new LiveControlSubject(session, Device, Owner), + new HubSocketSubject(Device, Owner, "secret-hub-token") + ]; + + foreach (var subject in subjects) { - Kind = ConnectionKind.HubSocket, - DeviceId = Guid.NewGuid(), - SessionToken = "secret-session-token", - HubToken = "secret-hub-token" - }; - - var text = subject.ToString(); - - await Assert.That(text).DoesNotContain("secret-session-token"); - await Assert.That(text).DoesNotContain("secret-hub-token"); - await Assert.That(text).DoesNotContain(subject.SessionId!); - await Assert.That(text).Contains(subject.DeviceId.ToString()!); + var text = subject.ToString(); + + await Assert.That(text).DoesNotContain("secret-session-token"); + await Assert.That(text).DoesNotContain("secret-hub-token"); + await Assert.That(text).DoesNotContain(session.SessionId); + } + + await Assert.That(session.ToString()).DoesNotContain("secret-session-token"); + await Assert.That(subjects[2].ToString()).Contains(Device.ToString()); } } diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index 0c3b9235..5a7af1c3 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -142,7 +142,7 @@ internal async Task CheckOnceAsync(ConnectionHandle handle) catch (Exception e) { // A transient failure must not drop a legitimate connection. It is checked again at the next sweep. - _logger.LogWarning(e, "Error while checking what a {Kind} connection may do", subject.Kind); + _logger.LogWarning(e, "Error while checking what a {Subject} may do", subject); return RefreshResult.Failed; } finally @@ -161,10 +161,7 @@ private async Task RevokeAsync(ConnectionHandle handle) if (!handle.MarkRevoked()) return; Remove(handle); - var subject = handle.Subject; - _logger.LogInformation( - "Closing {Kind} connection of user [{UserId}] (hub [{DeviceId}], public share [{PublicShareId}]): it may no longer go on", - subject.Kind, subject.UserId, subject.DeviceId, subject.PublicShareId); + _logger.LogInformation("Closing {Subject}: it may no longer go on", handle.Subject); try { diff --git a/Common/ConnectionAuthority/ConnectionSubject.cs b/Common/ConnectionAuthority/ConnectionSubject.cs index 2e2bccd8..d0d2995c 100644 --- a/Common/ConnectionAuthority/ConnectionSubject.cs +++ b/Common/ConnectionAuthority/ConnectionSubject.cs @@ -1,83 +1,119 @@ namespace OpenShock.Common.ConnectionAuthority; /// -/// What kind of long-lived connection this is, which decides what it needs to keep going. +/// Everything an open connection's authority depends on, by what kind of connection it is. A change to any of +/// the things named here is a reason to check the connection again, see . /// -public enum ConnectionKind +public closed record ConnectionSubject { - /// A SignalR hub connection. - SignalR, + /// Whether a change to the thing named by can affect this connection. + public abstract bool IsAffectedBy(AuthorityChange change); - /// A live control socket on a gateway. Needs shockers.use and the shockers it may control. - LiveControl, + /// The connection in words for a log, without the credentials it holds. + protected abstract string Describe(); - /// The socket of a hub (the device itself) on a gateway. - HubSocket + /// + /// Sealed, so no case gets a generated one that would put a session or hub token into a log. + /// + public sealed override string ToString() => Describe(); } /// -/// Everything an open connection's authority depends on. A change to any of the things named here is a reason to -/// look at the connection again, see . +/// A SignalR hub connection: someone signed in, a guest on a public share, or someone signed in on a public share. /// -public sealed record ConnectionSubject +/// What the connection authenticated with, null for a guest. +/// The public share the connection controls, if it is on one. +public sealed record SignalRSubject(ConnectionCredential? Credential, PublicShareAccess? PublicShare = null) : ConnectionSubject { - public required ConnectionKind Kind { get; init; } - - /// The user the connection acts as, null for a guest or a hub socket. - public Guid? UserId { get; init; } + public override bool IsAffectedBy(AuthorityChange change) => + Credential?.IsAffectedBy(change) == true || PublicShare?.IsAffectedBy(change) == true; - /// The session token the connection authenticated with, if it used a session. - public string? SessionToken + protected override string Describe() => (Credential, PublicShare) switch { - get; - init - { - field = value; - SessionId = value is null ? null : SessionIds.FromToken(value); - } - } + (not null, not null) => $"SignalR connection ({Credential}, {PublicShare})", + (not null, null) => $"SignalR connection ({Credential})", + (null, not null) => $"SignalR connection (guest, {PublicShare})", + (null, null) => "SignalR connection (anonymous)" + }; +} - /// The id the session of is stored under, which is what a session change names. - public string? SessionId { get; private init; } +/// A live control socket on a gateway. Needs shockers.use and the shockers it may control. +/// What the connection authenticated with. Live control is never anonymous. +/// The hub the socket controls. +/// The owner of . +public sealed record LiveControlSubject(ConnectionCredential Credential, Guid DeviceId, Guid DeviceOwnerId) : ConnectionSubject +{ + public override bool IsAffectedBy(AuthorityChange change) => change.Kind switch + { + AuthorityChangeKind.Device => change.Id == DeviceId, + AuthorityChangeKind.User => change.Id == DeviceOwnerId || Credential.IsAffectedBy(change), + _ => Credential.IsAffectedBy(change) + }; - /// The API token the connection authenticated with, if it used one. - public Guid? ApiTokenId { get; init; } + protected override string Describe() => $"live control connection ({Credential}, hub [{DeviceId}])"; +} - /// The hub a live control socket controls, or the hub a hub socket belongs to. - public Guid? DeviceId { get; init; } +/// The socket of a hub (the device itself) on a gateway. +/// The hub the socket belongs to. +/// The owner of . +/// The token the hub authenticated with. +public sealed record HubSocketSubject(Guid DeviceId, Guid DeviceOwnerId, string HubToken) : ConnectionSubject +{ + public override bool IsAffectedBy(AuthorityChange change) => change.Kind switch + { + AuthorityChangeKind.Device => change.Id == DeviceId, + AuthorityChangeKind.User => change.Id == DeviceOwnerId, + _ => false + }; - /// The owner of . - public Guid? DeviceOwnerId { get; init; } + protected override string Describe() => $"hub socket (hub [{DeviceId}])"; +} - /// The token a hub socket authenticated with. - public string? HubToken { get; init; } +/// What a connection authenticated with. +/// The user the connection acts as. +public closed record ConnectionCredential(Guid UserId) +{ + public bool IsAffectedBy(AuthorityChange change) => change.Kind switch + { + AuthorityChangeKind.User => change.Id == UserId, + AuthorityChangeKind.Session => this is SessionCredential session && session.SessionId == change.SessionId, + AuthorityChangeKind.ApiToken => this is ApiTokenCredential token && token.TokenId == change.Id, + _ => false + }; +} - /// The public share the connection controls. - public Guid? PublicShareId { get; init; } +/// The user the session belongs to. +/// The session token the connection authenticated with. +public sealed record SessionCredential(Guid UserId, string SessionToken) : ConnectionCredential(UserId) +{ + /// The id the session is stored under, which is what a session change names. + public string SessionId { get; } = SessionIds.FromToken(SessionToken); - /// The owner of . - public Guid? PublicShareOwnerId { get; init; } + /// Written out by hand to keep the session token and the id derived from it out of a log. + public override string ToString() => $"session of user [{UserId}]"; +} - /// The share's password stamp when the connection was let in, null when it had no password. - public Guid? PublicSharePasswordStamp { get; init; } +/// The user the token belongs to. +/// The API token the connection authenticated with. +public sealed record ApiTokenCredential(Guid UserId, Guid TokenId) : ConnectionCredential(UserId) +{ + public override string ToString() => $"API token [{TokenId}] of user [{UserId}]"; +} - /// Whether a change to the thing named by can affect this connection. +/// A public share as a connection got onto it. +/// The public share the connection controls. +/// The share's owner, whose deactivation ends the connection too. +/// The share's password stamp when the connection was let in, null when it had no password. +public sealed record PublicShareAccess(Guid PublicShareId, Guid OwnerId, Guid? PasswordStamp) +{ public bool IsAffectedBy(AuthorityChange change) => change.Kind switch { - AuthorityChangeKind.Session => SessionId is not null && SessionId == change.SessionId, - AuthorityChangeKind.User => UserId == change.Id || DeviceOwnerId == change.Id || PublicShareOwnerId == change.Id, - AuthorityChangeKind.ApiToken => ApiTokenId == change.Id, - AuthorityChangeKind.Device => DeviceId == change.Id, - AuthorityChangeKind.PublicShare => PublicShareId == change.Id, + AuthorityChangeKind.PublicShare => change.Id == PublicShareId, + AuthorityChangeKind.User => change.Id == OwnerId, _ => false }; - /// - /// Written out by hand so the generated one cannot put or , which - /// are credentials, into a log. - /// - public override string ToString() => - $"{Kind} connection (user [{UserId}], API token [{ApiTokenId}], hub [{DeviceId}], public share [{PublicShareId}])"; + public override string ToString() => $"public share [{PublicShareId}]"; } /// The values travel over Redis between services, see . diff --git a/Common/ConnectionAuthority/GrantResolver.cs b/Common/ConnectionAuthority/GrantResolver.cs index c026eeae..ddcc91c8 100644 --- a/Common/ConnectionAuthority/GrantResolver.cs +++ b/Common/ConnectionAuthority/GrantResolver.cs @@ -20,98 +20,110 @@ public GrantResolver(OpenShockContext db, ISessionService sessionService) } /// - public async Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken) + public Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken) => subject switch { - var now = DateTime.UtcNow; - - if (subject.Kind == ConnectionKind.HubSocket) - return await IsHubStillValid(subject, cancellationToken) ? Grant.Empty : null; + SignalRSubject signalR => ResolveSignalR(signalR, cancellationToken), + LiveControlSubject liveControl => ResolveLiveControl(liveControl, cancellationToken), + HubSocketSubject hubSocket => ResolveHubSocket(hubSocket, cancellationToken) + }; - // Who the connection authenticated as. - TokenGrant? tokenGrant = null; - DateTime? expiresAt = null; + private async Task ResolveSignalR(SignalRSubject subject, CancellationToken cancellationToken) + { + var now = DateTime.UtcNow; - if (subject.ApiTokenId is { } tokenId) + // A hub connection serves several endpoints and checks the token's permissions on each call, so none is + // asked for here. + var grant = Grant.Empty; + if (subject.Credential is { } credential) { - var token = await _db.ApiTokens - .AsNoTracking() - .FirstOrDefaultAsync(x => x.Id == tokenId && x.User.UserDeactivation == null, cancellationToken); - if (token is null || (token.ValidUntil is { } validUntil && validUntil < now)) return null; + grant = await ResolveCredential(credential, requiredPermission: null, now, cancellationToken); + if (grant is null) return null; + } - // Live control is one endpoint behind one permission, so losing it ends the connection. A hub - // connection serves several and checks the permission on each call. - if (subject.Kind == ConnectionKind.LiveControl && !token.Permissions.IsAllowed(PermissionType.Shockers_Use)) return null; + if (subject.PublicShare is not { } access) return grant; - tokenGrant = TokenGrant.From(token); - expiresAt = token.ValidUntil; - } - else if (subject.SessionToken is { } sessionToken) - { - // Sessions are deleted on logout, on deactivation and on a password reset. - var session = await _sessionService.GetSessionByTokenAsync(sessionToken); - if (session is null || session.UserId != subject.UserId) return 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 active = await _db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, cancellationToken); - if (!active) return null; - } - else if (subject.Kind == ConnectionKind.LiveControl) - { - // Live control is never anonymous. - return null; - } + // 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. + var share = await _db.PublicShares + .Where(x => x.Id == access.PublicShareId && x.PasswordStamp == access.PasswordStamp) + .OpenToVisitors(now) + .Select(x => new { x.ExpiresAt }) + .FirstOrDefaultAsync(cancellationToken); + if (share is null) return null; - // What it is connected to. - if (subject.PublicShareId is { } publicShareId) - { - // 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. - var passwordStamp = subject.PublicSharePasswordStamp; - var share = await _db.PublicShares - .Where(x => x.Id == publicShareId && x.PasswordStamp == passwordStamp) - .OpenToVisitors(now) - .Select(x => new { x.ExpiresAt }) - .FirstOrDefaultAsync(cancellationToken); - if (share is null) return null; - - expiresAt = Earliest(expiresAt, share.ExpiresAt); - } + return grant with { ExpiresAt = Earliest(grant.ExpiresAt, share.ExpiresAt) }; + } - FrozenDictionary? shockers = null; - if (subject.Kind == ConnectionKind.LiveControl) - { - if (subject is not { DeviceId: { } deviceId, DeviceOwnerId: { } ownerId, UserId: { } userId }) return null; + private async Task ResolveLiveControl(LiveControlSubject subject, CancellationToken cancellationToken) + { + // Live control is one endpoint behind one permission, so losing it ends the connection. + var grant = await ResolveCredential(subject.Credential, PermissionType.Shockers_Use, DateTime.UtcNow, cancellationToken); + if (grant is null) return null; - // Someone controlling a shared hub loses it when the owner is deactivated. - if (ownerId != userId && !await _db.Users.AnyAsync(u => u.Id == ownerId && u.UserDeactivation == null, cancellationToken)) - return null; + var userId = subject.Credential.UserId; - // Losing every share leaves the connection open with nothing to control: a share can come back, and - // the client is told per frame that the shocker is not there. - var controllable = await _db.Shockers - .AsNoTracking() - .Where(x => x.DeviceId == deviceId) - .ControllableBy(userId) - .ToArrayAsync(cancellationToken); + // Someone controlling a shared hub loses it when the owner is deactivated. + if (subject.DeviceOwnerId != userId && !await _db.Users.AnyAsync(u => u.Id == subject.DeviceOwnerId && u.UserDeactivation == null, cancellationToken)) + return null; - shockers = controllable.ToFrozenDictionary( - x => x.ShockerId, - x => new ShockerGrant(x.Paused, SharePermsAndLimits.Intersect(x.ShockerPermsAndLimits, x.PermsAndLimits))); - } + // Losing every share leaves the connection open with nothing to control: a share can come back, and + // the client is told per frame that the shocker is not there. + var controllable = await _db.Shockers + .AsNoTracking() + .Where(x => x.DeviceId == subject.DeviceId) + .ControllableBy(userId) + .ToArrayAsync(cancellationToken); - return new Grant { Token = tokenGrant, Shockers = shockers, ExpiresAt = expiresAt }; + return grant with + { + Shockers = controllable.ToFrozenDictionary( + x => x.ShockerId, + x => new ShockerGrant(x.Paused, SharePermsAndLimits.Intersect(x.ShockerPermsAndLimits, x.PermsAndLimits))) + }; } /// /// A hub may stay connected while it exists, still has the token it connected with and its owner is active, /// the same as what lets it connect. /// - private Task IsHubStillValid(ConnectionSubject subject, CancellationToken cancellationToken) + private async Task ResolveHubSocket(HubSocketSubject subject, CancellationToken cancellationToken) + { + var valid = await _db.Devices.AnyAsync(x => x.Id == subject.DeviceId && x.Token == subject.HubToken && x.Owner.UserDeactivation == null, cancellationToken); + return valid ? Grant.Empty : null; + } + + /// What the thing a connection authenticated with still grants, or null when it may no longer be used. + /// What the connection authenticated with. + /// A permission an API token must still have for the connection to go on. + /// The time to hold a token's expiry against. + /// + private Task ResolveCredential(ConnectionCredential credential, PermissionType? requiredPermission, DateTime now, CancellationToken cancellationToken) => credential switch + { + ApiTokenCredential apiToken => ResolveApiToken(apiToken, requiredPermission, now, cancellationToken), + SessionCredential session => ResolveSession(session, cancellationToken) + }; + + private async Task ResolveApiToken(ApiTokenCredential credential, PermissionType? requiredPermission, DateTime now, CancellationToken cancellationToken) { - if (subject is not { DeviceId: { } deviceId, HubToken: { } hubToken }) return Task.FromResult(false); + var token = await _db.ApiTokens + .AsNoTracking() + .FirstOrDefaultAsync(x => x.Id == credential.TokenId && x.User.UserDeactivation == null, cancellationToken); + if (token is null || (token.ValidUntil is { } validUntil && validUntil < now)) return null; + if (requiredPermission is { } permission && !token.Permissions.IsAllowed(permission)) return null; - return _db.Devices.AnyAsync(x => x.Id == deviceId && x.Token == hubToken && x.Owner.UserDeactivation == null, cancellationToken); + return new Grant { Token = TokenGrant.From(token), ExpiresAt = token.ValidUntil }; + } + + private async Task ResolveSession(SessionCredential credential, CancellationToken cancellationToken) + { + // Sessions are deleted on logout, on deactivation and on a password reset. + var session = await _sessionService.GetSessionByTokenAsync(credential.SessionToken); + if (session is null || session.UserId != credential.UserId) return 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 active = await _db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, cancellationToken); + return active ? Grant.Empty : null; } private static DateTime? Earliest(DateTime? a, DateTime? b) => a is null ? b : b is null ? a : a < b ? a : b; diff --git a/Common/Hubs/ConnectionAuthorityHubFilter.cs b/Common/Hubs/ConnectionAuthorityHubFilter.cs index adcd516a..3133ea2e 100644 --- a/Common/Hubs/ConnectionAuthorityHubFilter.cs +++ b/Common/Hubs/ConnectionAuthorityHubFilter.cs @@ -103,7 +103,7 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception return await next(invocationContext); } - private static HubException Revoked(ConnectionHandle handle) => new(handle.Subject.PublicShareId is not null + private static HubException Revoked(ConnectionHandle handle) => new(handle.Subject is SignalRSubject { PublicShare: not null } ? "Access to this public share is no longer valid" : "Authentication is no longer valid"); } diff --git a/Common/Hubs/HubConnectionAuthority.cs b/Common/Hubs/HubConnectionAuthority.cs index a12f7811..28b95b50 100644 --- a/Common/Hubs/HubConnectionAuthority.cs +++ b/Common/Hubs/HubConnectionAuthority.cs @@ -45,38 +45,35 @@ public static bool IsAuthenticated(HubCallerContext context) var user = context.User; if (user is null) return null; - Guid? userId = user.TryGetClaimValueAsGuid(ClaimTypes.NameIdentifier, out var parsedUserId) ? parsedUserId : null; + // Without a user there is nothing to describe. An authenticated connection that ends up untracked is + // refused by the hub filter on its first call. + if (!user.TryGetClaimValueAsGuid(ClaimTypes.NameIdentifier, out var userId)) return null; var httpContext = context.GetHttpContext(); - ConnectionSubject subject; + ConnectionCredential credential; TokenGrant? connectedWith = null; - var usesToken = false; if (user.HasOpenShockApiTokenIdentity()) { if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return null; - usesToken = true; if (httpContext?.GetItemByType() is { } token) connectedWith = TokenGrant.From(token); - subject = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = userId, ApiTokenId = tokenId }; + credential = new ApiTokenCredential(userId, tokenId); } else if (user.TryGetOpenShockUserIdentity() is not null && httpContext is not null && httpContext.TryGetUserSessionToken(out var sessionToken)) { - subject = new ConnectionSubject - { - Kind = ConnectionKind.SignalR, - UserId = userId, - SessionToken = sessionToken - }; + credential = new SessionCredential(userId, sessionToken); } else { return null; } - var handle = _registry.Track(subject, new SignalRConnection(context, usesToken, connectedWith)); + var handle = _registry.Track( + new SignalRSubject(credential), + new SignalRConnection(context, usesToken: credential is ApiTokenCredential, connectedWith)); context.Items[HandleKey] = handle; return handle; } @@ -92,27 +89,19 @@ public static bool IsAuthenticated(HubCallerContext context) /// The share's password stamp the visitor got in with, null when it had no password. public void AttachPublicShare(HubCallerContext context, Guid publicShareId, Guid publicShareOwnerId, Guid? passwordStamp) { + var access = new PublicShareAccess(publicShareId, publicShareOwnerId, passwordStamp); + var handle = Get(context); if (handle is null) { - var subject = new ConnectionSubject - { - Kind = ConnectionKind.SignalR, - PublicShareId = publicShareId, - PublicShareOwnerId = publicShareOwnerId, - PublicSharePasswordStamp = passwordStamp - }; - - context.Items[HandleKey] = _registry.Track(subject, new SignalRConnection(context, usesToken: false, connectedWith: null)); + context.Items[HandleKey] = _registry.Track( + new SignalRSubject(Credential: null, access), + new SignalRConnection(context, usesToken: false, connectedWith: null)); return; } - handle.UpdateSubject(handle.Subject with - { - PublicShareId = publicShareId, - PublicShareOwnerId = publicShareOwnerId, - PublicSharePasswordStamp = passwordStamp - }); + // Only this class tracks hub connections, and always as a SignalRSubject. + handle.UpdateSubject((SignalRSubject)handle.Subject with { PublicShare = access }); } /// Stops tracking the connection. Its handle stays readable through . diff --git a/LiveControlGateway/Controllers/HubControllerBase.cs b/LiveControlGateway/Controllers/HubControllerBase.cs index 7d7814b8..e5e28da9 100644 --- a/LiveControlGateway/Controllers/HubControllerBase.cs +++ b/LiveControlGateway/Controllers/HubControllerBase.cs @@ -174,14 +174,10 @@ protected override async Task ConnectionPrecondition() // From here on a change to the hub or its owner reaches this socket. Registering also checks it once, // which covers a change made since it authenticated. Done before the lifetime exists, so a refused hub // leaves nothing behind. + if (_hubToken is null) return AuthResultError.HeaderMissingOrInvalid; + var (authority, authorityResult) = await ServiceProvider.GetRequiredService().RegisterAsync( - new ConnectionSubject - { - Kind = ConnectionKind.HubSocket, - DeviceId = CurrentHubId, - DeviceOwnerId = CurrentHubOwnerId, - HubToken = _hubToken - }, this); + new HubSocketSubject(CurrentHubId, CurrentHubOwnerId, _hubToken), this); _authority = authority; switch (authorityResult) diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index e2291c94..10f39f66 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -51,14 +51,9 @@ public sealed class LiveControlController : WebsocketBaseController - /// Id of the API token used to authenticate, if any. Null when authenticated via a user session. + /// What the connection authenticated with: the API token or the session. /// - private Guid? _tokenId; - - /// - /// The session token used to authenticate, if any. Null when authenticated via an API token. - /// - private string? _sessionToken; + private ConnectionCredential? _credential; /// /// This connection in the , which keeps what it may do current: the @@ -158,15 +153,10 @@ protected override async Task UnregisterConnection() // From here on a change to the session, token, account or shares reaches this connection. Registering also // reads what it may do for the first time, which covers a change made since it authenticated. - var (authority, authorityResult) = await _authorityRegistry.RegisterAsync(new ConnectionSubject - { - Kind = ConnectionKind.LiveControl, - UserId = _currentUser.Id, - ApiTokenId = _tokenId, - SessionToken = _sessionToken, - DeviceId = id, - DeviceOwnerId = ownerId - }, this); + if (_credential is null) return AuthResultError.UnknownError; + + var (authority, authorityResult) = await _authorityRegistry.RegisterAsync( + new LiveControlSubject(_credential, id, ownerId.Value), this); _authority = authority; switch (authorityResult) @@ -174,7 +164,7 @@ protected override async Task UnregisterConnection() case RefreshResult.Revoked: // The hub and the caller's access to it were just read above, so what did not hold up is what // the caller authenticated with. - return _tokenId is not null ? AuthResultError.TokenInvalid : AuthResultError.SessionInvalid; + return _credential is ApiTokenCredential ? AuthResultError.TokenInvalid : AuthResultError.SessionInvalid; case RefreshResult.Failed: return ExceptionError.Exception; } @@ -239,11 +229,11 @@ public void OnActionExecuting(ActionExecutingContext context) // Session auth carries no such limits. if (GetOptionalItem() is { } apiToken) { - _tokenId = apiToken.Id; + _credential = new ApiTokenCredential(_currentUser.Id, apiToken.Id); } else if (HttpContext.TryGetUserSessionToken(out var sessionToken)) { - _sessionToken = sessionToken; + _credential = new SessionCredential(_currentUser.Id, sessionToken); } } From 11b7b1f2bc82aa4ed2785e80765ac826be409a50 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 20:30:05 +0100 Subject: [PATCH 15/24] refactor: name a change in authority by what changed AuthorityChange was a kind, an id and an optional session id, with an empty id standing in for a session change. It is now a closed record per kind of change and travels over Redis as it is, which removes the separate message type and the kind enum. A grant's shockers are empty rather than null for a connection that controls none. --- API.IntegrationTests/Tests/DevicesTests.cs | 3 +- .../Tests/GrantResolverTests.cs | 10 ++-- .../ConnectionAuthorityRegistryTests.cs | 8 +-- .../ConnectionSubjectTests.cs | 38 ++++++------ Common/ConnectionAuthority/AuthorityChange.cs | 55 +++++++++++++++++ .../AuthorityChangeSubscriber.cs | 7 +-- .../ConnectionAuthority/ConnectionSubject.cs | 60 ++++--------------- Common/ConnectionAuthority/Grant.cs | 4 +- .../Redis/PubSub/AuthorityChangedMessage.cs | 25 -------- Common/Services/RedisPubSub/RedisChannels.cs | 2 +- .../Services/RedisPubSub/RedisPubService.cs | 4 +- .../Controllers/LiveControlController.cs | 2 +- 12 files changed, 105 insertions(+), 113 deletions(-) create mode 100644 Common/ConnectionAuthority/AuthorityChange.cs delete mode 100644 Common/Redis/PubSub/AuthorityChangedMessage.cs diff --git a/API.IntegrationTests/Tests/DevicesTests.cs b/API.IntegrationTests/Tests/DevicesTests.cs index 5b67c87d..fb83d1a6 100644 --- a/API.IntegrationTests/Tests/DevicesTests.cs +++ b/API.IntegrationTests/Tests/DevicesTests.cs @@ -6,7 +6,6 @@ using OpenShock.API.IntegrationTests.Helpers; using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.OpenShockDb; -using OpenShock.Common.Redis.PubSub; using OpenShock.Common.Services.RedisPubSub; using OpenShock.IntegrationTests.Shared; using StackExchange.Redis; @@ -152,7 +151,7 @@ public async Task RemoveDevice_AnnouncesAnAuthorityChangeForTheHub() await subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, (_, value) => { - var change = MessagePackSerializer.Deserialize((ReadOnlyMemory)value).ToChange(); + var change = MessagePackSerializer.Deserialize((ReadOnlyMemory)value); if (change == AuthorityChange.Device(deviceId)) announced.TrySetResult(); }); await subscriber.SubscribeAsync(RedisChannels.DeviceMessage(deviceId), (_, _) => Interlocked.Increment(ref reloads)); diff --git a/API.IntegrationTests/Tests/GrantResolverTests.cs b/API.IntegrationTests/Tests/GrantResolverTests.cs index e866724e..368d3b14 100644 --- a/API.IntegrationTests/Tests/GrantResolverTests.cs +++ b/API.IntegrationTests/Tests/GrantResolverTests.cs @@ -33,7 +33,7 @@ await Db(db => db.Shockers.Where(s => s.Id == shockerId) await Assert.That(grant).IsNotNull(); await Assert.That(grant!.Token).IsNull(); - var shocker = grant.Shockers![shockerId]; + var shocker = grant.Shockers[shockerId]; await Assert.That(shocker.Paused).IsFalse(); await Assert.That(shocker.PermsAndLimits.Intensity).IsEqualTo((byte?)40); await Assert.That(shocker.PermsAndLimits.Sound).IsFalse(); @@ -58,7 +58,7 @@ await Share(shockerId, recipient.Id, share => var grant = await Resolve(LiveControlBySession(recipient, deviceId, owner.Id)); - await Assert.That(grant!.Shockers!.ContainsKey(notSharedShockerId)).IsFalse(); + await Assert.That(grant!.Shockers.ContainsKey(notSharedShockerId)).IsFalse(); var shocker = grant.Shockers[shockerId]; await Assert.That(shocker.PermsAndLimits.Shock).IsFalse(); await Assert.That(shocker.PermsAndLimits.Vibrate).IsTrue(); @@ -79,7 +79,7 @@ public async Task LiveControl_Recipient_PausedByEitherSide() var grant = await Resolve(LiveControlBySession(recipient, deviceId, owner.Id)); - await Assert.That(grant!.Shockers![sharePaused].Paused).IsTrue(); + await Assert.That(grant!.Shockers[sharePaused].Paused).IsTrue(); await Assert.That(grant.Shockers[shockerPaused].Paused).IsTrue(); } @@ -95,7 +95,7 @@ public async Task LiveControl_RecipientWhoLostEveryShare_StaysConnectedWithNothi var grant = await Resolve(LiveControlBySession(recipient, deviceId, owner.Id)); await Assert.That(grant).IsNotNull(); - await Assert.That(grant!.Shockers!.Count).IsEqualTo(0); + await Assert.That(grant!.Shockers.Count).IsEqualTo(0); } // --- Live control: whether the connection may go on at all --- @@ -229,7 +229,7 @@ public async Task HubConnection_TokenWithoutShockersUse_MayGoOn() var grant = await Resolve(new SignalRSubject(new ApiTokenCredential(owner.Id, tokenId))); await Assert.That(grant).IsNotNull(); - await Assert.That(grant!.Shockers).IsNull(); + await Assert.That(grant!.Shockers.Count).IsEqualTo(0); } // --- The hub's own socket --- diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs index 44e4b047..3eea5f6e 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -140,7 +140,7 @@ public async Task Signal_ReplacesTheGrantOfAffectedConnectionsOnly() var changed = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(1) }; resolver.Resolve = _ => Task.FromResult(changed); - registry.Signal(new AuthorityChange(AuthorityChangeKind.ApiToken, tokenId)); + registry.Signal(AuthorityChange.ApiToken(tokenId)); await Settle(affected); await Assert.That(affected.Grant).IsSameReferenceAs(changed); @@ -156,8 +156,8 @@ public async Task Signal_NothingGrantedAnymore_ClosesOnce() var (handle, _) = await registry.RegisterAsync(LiveControl(userId: userId), connection); resolver.Resolve = _ => Task.FromResult(null); - registry.Signal(new AuthorityChange(AuthorityChangeKind.User, userId)); - registry.Signal(new AuthorityChange(AuthorityChangeKind.User, userId)); + registry.Signal(AuthorityChange.User(userId)); + registry.Signal(AuthorityChange.User(userId)); await Settle(handle); await Assert.That(handle.IsRevoked).IsTrue(); @@ -214,7 +214,7 @@ public async Task Signal_DuringARunningLook_LooksAgainAndTheLaterReadWins() await staleReadStarted.Task; // The change is committed and announced while the first look still holds what it read before. - registry.Signal(new AuthorityChange(AuthorityChangeKind.Device, deviceId)); + registry.Signal(AuthorityChange.Device(deviceId)); releaseStaleRead.SetResult(); await first; diff --git a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs index e883a831..29746fc4 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs @@ -1,7 +1,6 @@ using MessagePack; using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Constants; -using OpenShock.Common.Redis.PubSub; namespace OpenShock.Common.Tests.ConnectionAuthority; @@ -70,35 +69,34 @@ public async Task SessionChange_AffectsOnlyConnectionsOfThatSession() await Assert.That(session.IsAffectedBy(AuthorityChange.Session(storedId))).IsTrue(); await Assert.That(session.IsAffectedBy(AuthorityChange.Session("another-id"))).IsFalse(); - // A token connection has no session, and a session change carries no id that could match anything else. + // A token connection has no session. await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.Session(storedId))).IsFalse(); - await Assert.That(new SignalRSubject(Credential: null).IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Session, Guid.Empty))).IsFalse(); } - [Test] - [Arguments(AuthorityChangeKind.User)] - [Arguments(AuthorityChangeKind.ApiToken)] - [Arguments(AuthorityChangeKind.Device)] - [Arguments(AuthorityChangeKind.PublicShare)] - public async Task Change_SurvivesTheTripOverRedis(AuthorityChangeKind kind) + public static IEnumerable> EveryKindOfChange() { - var change = new AuthorityChange(kind, Guid.NewGuid()); + yield return () => AuthorityChange.User(Guid.NewGuid()); + yield return () => AuthorityChange.Session("stored-id"); + yield return () => AuthorityChange.ApiToken(Guid.NewGuid()); + yield return () => AuthorityChange.Device(Guid.NewGuid()); + yield return () => AuthorityChange.PublicShare(Guid.NewGuid()); + } - var bytes = MessagePackSerializer.Serialize(AuthorityChangedMessage.From(change)); - var received = MessagePackSerializer.Deserialize(bytes).ToChange(); + [Test] + [MethodDataSource(nameof(EveryKindOfChange))] + public async Task Change_SurvivesTheTripOverRedis(AuthorityChange change) + { + var bytes = MessagePackSerializer.Serialize(change); + var received = MessagePackSerializer.Deserialize(bytes); await Assert.That(received).IsEqualTo(change); + await Assert.That(received.GetType()).IsEqualTo(change.GetType()); } [Test] - public async Task SessionChange_SurvivesTheTripOverRedis() + public async Task SessionChange_DoesNotPrintTheSessionId() { - var change = AuthorityChange.Session("stored-id"); - - var bytes = MessagePackSerializer.Serialize(AuthorityChangedMessage.From(change)); - var received = MessagePackSerializer.Deserialize(bytes).ToChange(); - - await Assert.That(received).IsEqualTo(change); + await Assert.That(AuthorityChange.Session("stored-id").ToString()).DoesNotContain("stored-id"); } [Test] @@ -106,7 +104,7 @@ public async Task Guest_IsNotAffectedByAnEmptyId() { var guest = new SignalRSubject(Credential: null, new PublicShareAccess(Share, ShareOwner, PasswordStamp: null)); - await Assert.That(guest.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Guid.Empty))).IsFalse(); + await Assert.That(guest.IsAffectedBy(AuthorityChange.User(Guid.Empty))).IsFalse(); await Assert.That(guest.IsAffectedBy(AuthorityChange.User(ShareOwner))).IsTrue(); } diff --git a/Common/ConnectionAuthority/AuthorityChange.cs b/Common/ConnectionAuthority/AuthorityChange.cs new file mode 100644 index 00000000..cebd9199 --- /dev/null +++ b/Common/ConnectionAuthority/AuthorityChange.cs @@ -0,0 +1,55 @@ +using MessagePack; + +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// Something a connection's authority can depend on has changed. Names what changed and nothing more, on +/// purpose: the affected connections look up what they may do now, so a change cannot be applied out of order or +/// half-described. +/// +/// +/// Travels over Redis between services as it is, see +/// . The union keys are the wire +/// format: add new cases with new keys and leave the existing ones alone. +/// +[Union(0, typeof(UserChanged))] +[Union(1, typeof(SessionChanged))] +[Union(2, typeof(ApiTokenChanged))] +[Union(3, typeof(DeviceChanged))] +[Union(4, typeof(PublicShareChanged))] +public closed record AuthorityChange +{ + public static AuthorityChange User(Guid userId) => new UserChanged(userId); + + /// The id the session is stored under, see . + public static AuthorityChange Session(string sessionId) => new SessionChanged(sessionId); + + public static AuthorityChange ApiToken(Guid tokenId) => new ApiTokenChanged(tokenId); + public static AuthorityChange Device(Guid deviceId) => new DeviceChanged(deviceId); + public static AuthorityChange PublicShare(Guid publicShareId) => new PublicShareChanged(publicShareId); +} + +/// An account was deactivated, deleted or otherwise may no longer be used. +[MessagePackObject] +public sealed record UserChanged([property: Key(0)] Guid UserId) : AuthorityChange; + +/// A login session was deleted or expired. +/// The id the session is stored under. +[MessagePackObject] +public sealed record SessionChanged([property: Key(0)] string SessionId) : AuthorityChange +{ + /// Written out by hand to keep the session's id out of a log. + public override string ToString() => nameof(SessionChanged); +} + +/// An API token was edited, paused or deleted. +[MessagePackObject] +public sealed record ApiTokenChanged([property: Key(0)] Guid TokenId) : AuthorityChange; + +/// A hub was deleted or got a new token, or its shockers or the shares on them changed. +[MessagePackObject] +public sealed record DeviceChanged([property: Key(0)] Guid DeviceId) : AuthorityChange; + +/// Who may use a public share changed. +[MessagePackObject] +public sealed record PublicShareChanged([property: Key(0)] Guid PublicShareId) : AuthorityChange; diff --git a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs index af6b0a3a..81ebf665 100644 --- a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs +++ b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs @@ -1,6 +1,5 @@ using MessagePack; using OpenShock.Common.Redis; -using OpenShock.Common.Redis.PubSub; using OpenShock.Common.Services.RedisPubSub; using StackExchange.Redis; @@ -51,10 +50,10 @@ private void HandleAuthorityChanged(RedisChannel _, RedisValue message) { if (!message.HasValue) return; - AuthorityChangedMessage change; + AuthorityChange change; try { - change = MessagePackSerializer.Deserialize((ReadOnlyMemory)message); + change = MessagePackSerializer.Deserialize((ReadOnlyMemory)message); } catch (Exception e) { @@ -64,7 +63,7 @@ private void HandleAuthorityChanged(RedisChannel _, RedisValue message) return; } - _registry.Signal(change.ToChange()); + _registry.Signal(change); } private void HandleKeyExpired(RedisChannel _, RedisValue message) diff --git a/Common/ConnectionAuthority/ConnectionSubject.cs b/Common/ConnectionAuthority/ConnectionSubject.cs index d0d2995c..075a4d48 100644 --- a/Common/ConnectionAuthority/ConnectionSubject.cs +++ b/Common/ConnectionAuthority/ConnectionSubject.cs @@ -43,10 +43,10 @@ public override bool IsAffectedBy(AuthorityChange change) => /// The owner of . public sealed record LiveControlSubject(ConnectionCredential Credential, Guid DeviceId, Guid DeviceOwnerId) : ConnectionSubject { - public override bool IsAffectedBy(AuthorityChange change) => change.Kind switch + public override bool IsAffectedBy(AuthorityChange change) => change switch { - AuthorityChangeKind.Device => change.Id == DeviceId, - AuthorityChangeKind.User => change.Id == DeviceOwnerId || Credential.IsAffectedBy(change), + DeviceChanged device => device.DeviceId == DeviceId, + UserChanged user => user.UserId == DeviceOwnerId || Credential.IsAffectedBy(change), _ => Credential.IsAffectedBy(change) }; @@ -59,10 +59,10 @@ public sealed record LiveControlSubject(ConnectionCredential Credential, Guid De /// The token the hub authenticated with. public sealed record HubSocketSubject(Guid DeviceId, Guid DeviceOwnerId, string HubToken) : ConnectionSubject { - public override bool IsAffectedBy(AuthorityChange change) => change.Kind switch + public override bool IsAffectedBy(AuthorityChange change) => change switch { - AuthorityChangeKind.Device => change.Id == DeviceId, - AuthorityChangeKind.User => change.Id == DeviceOwnerId, + DeviceChanged device => device.DeviceId == DeviceId, + UserChanged user => user.UserId == DeviceOwnerId, _ => false }; @@ -73,11 +73,11 @@ public sealed record HubSocketSubject(Guid DeviceId, Guid DeviceOwnerId, string /// The user the connection acts as. public closed record ConnectionCredential(Guid UserId) { - public bool IsAffectedBy(AuthorityChange change) => change.Kind switch + public bool IsAffectedBy(AuthorityChange change) => change switch { - AuthorityChangeKind.User => change.Id == UserId, - AuthorityChangeKind.Session => this is SessionCredential session && session.SessionId == change.SessionId, - AuthorityChangeKind.ApiToken => this is ApiTokenCredential token && token.TokenId == change.Id, + UserChanged user => user.UserId == UserId, + SessionChanged changed => this is SessionCredential session && session.SessionId == changed.SessionId, + ApiTokenChanged changed => this is ApiTokenCredential token && token.TokenId == changed.TokenId, _ => false }; } @@ -106,46 +106,12 @@ public sealed record ApiTokenCredential(Guid UserId, Guid TokenId) : ConnectionC /// The share's password stamp when the connection was let in, null when it had no password. public sealed record PublicShareAccess(Guid PublicShareId, Guid OwnerId, Guid? PasswordStamp) { - public bool IsAffectedBy(AuthorityChange change) => change.Kind switch + public bool IsAffectedBy(AuthorityChange change) => change switch { - AuthorityChangeKind.PublicShare => change.Id == PublicShareId, - AuthorityChangeKind.User => change.Id == OwnerId, + PublicShareChanged share => share.PublicShareId == PublicShareId, + UserChanged user => user.UserId == OwnerId, _ => false }; public override string ToString() => $"public share [{PublicShareId}]"; } - -/// The values travel over Redis between services, see . -public enum AuthorityChangeKind : byte -{ - /// An account was deactivated, deleted or otherwise may no longer be used. - User = 0, - - /// A login session was deleted or expired. Identified by . - Session = 1, - - /// An API token was edited, paused or deleted. - ApiToken = 2, - - /// A hub was deleted or got a new token, or its shockers or the shares on them changed. - Device = 3, - - /// Who may use a public share changed. - PublicShare = 4 -} - -/// -/// Something a connection's authority can depend on has changed. Carries no detail on purpose: the affected -/// connections look up what they may do now, so a change cannot be applied out of order or half-described. -/// -public readonly record struct AuthorityChange(AuthorityChangeKind Kind, Guid Id, string? SessionId = null) -{ - public static AuthorityChange User(Guid userId) => new(AuthorityChangeKind.User, userId); - public static AuthorityChange ApiToken(Guid tokenId) => new(AuthorityChangeKind.ApiToken, tokenId); - public static AuthorityChange Device(Guid deviceId) => new(AuthorityChangeKind.Device, deviceId); - public static AuthorityChange PublicShare(Guid publicShareId) => new(AuthorityChangeKind.PublicShare, publicShareId); - - /// The id the session is stored under, see . - public static AuthorityChange Session(string sessionId) => new(AuthorityChangeKind.Session, Guid.Empty, sessionId); -} diff --git a/Common/ConnectionAuthority/Grant.cs b/Common/ConnectionAuthority/Grant.cs index 1d599a04..5cb825d7 100644 --- a/Common/ConnectionAuthority/Grant.cs +++ b/Common/ConnectionAuthority/Grant.cs @@ -17,9 +17,9 @@ public sealed record Grant public TokenGrant? Token { get; init; } /// - /// The shockers a live control connection may control and how, by shocker id. Null for other connections. + /// The shockers a live control connection may control and how, by shocker id. Empty for other connections. /// - public FrozenDictionary? Shockers { get; init; } + public FrozenDictionary Shockers { get; init; } = FrozenDictionary.Empty; /// When the grant ends on its own (a token or public share reaching its expiry), if it does. public DateTime? ExpiresAt { get; init; } diff --git a/Common/Redis/PubSub/AuthorityChangedMessage.cs b/Common/Redis/PubSub/AuthorityChangedMessage.cs deleted file mode 100644 index 8fb78122..00000000 --- a/Common/Redis/PubSub/AuthorityChangedMessage.cs +++ /dev/null @@ -1,25 +0,0 @@ -using MessagePack; -using OpenShock.Common.ConnectionAuthority; - -namespace OpenShock.Common.Redis.PubSub; - -/// -/// An as it travels over Redis. Names what changed and nothing more: receivers look -/// up the current state themselves. -/// -[MessagePackObject] -public sealed class AuthorityChangedMessage -{ - [Key(0)] public required AuthorityChangeKind Kind { get; init; } - [Key(1)] public required Guid Id { get; init; } - [Key(2)] public string? SessionId { get; init; } - - public static AuthorityChangedMessage From(AuthorityChange change) => new() - { - Kind = change.Kind, - Id = change.Id, - SessionId = change.SessionId - }; - - public AuthorityChange ToChange() => new(Kind, Id, SessionId); -} diff --git a/Common/Services/RedisPubSub/RedisChannels.cs b/Common/Services/RedisPubSub/RedisChannels.cs index 609ed434..db4aafce 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -12,7 +12,7 @@ public static class RedisChannels /// /// Fired when something an open connection's authority can depend on changed: an account, a login session, an - /// API token, a hub or a public share. The payload is an + /// API token, a hub or a public share. The payload is an /// naming what changed. Every instance holding long-lived connections listens and has the affected ones look /// up what they may do now. /// diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index d71b9784..379b87b2 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -29,13 +29,13 @@ public async Task SendAuthorityChanged(AuthorityChange change) { try { - await Publish(RedisChannels.AuthorityChanged, AuthorityChangedMessage.From(change)); + await Publish(RedisChannels.AuthorityChanged, change); } catch (Exception e) { // The change itself is already saved and the caller can do nothing about this. The connections it // affects find out at their next periodic check. - _logger.LogWarning(e, "Failed to announce a change in authority ({Kind} [{Id}]); open connections find out at their next check", change.Kind, change.Kind == AuthorityChangeKind.Session ? "session" : change.Id); + _logger.LogWarning(e, "Failed to announce a change in authority ({Change}); open connections find out at their next check", change); } } diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index 10f39f66..e30a2e49 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -530,7 +530,7 @@ await QueueMessage(new LiveControlResponse private Results.Union4 CheckFramePermissions(Grant grant, Guid shocker, ControlType controlType) { - if (grant.Shockers is null || !grant.Shockers.TryGetValue(shocker, out var shockerShare)) return new Results.NotFound(); + if (!grant.Shockers.TryGetValue(shocker, out var shockerShare)) return new Results.NotFound(); if (shockerShare.Paused) return new ShockerPaused(); if (!PermissionUtils.IsAllowed(controlType, true, shockerShare.PermsAndLimits)) return new NoPermission(); From d24e5aa488d9d5a02ab6af0eae79e1a50b907cca Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 20:38:52 +0100 Subject: [PATCH 16/24] feat: keep announced changes in authority in a log that can be read later A change in authority was a Redis pub/sub message, which only reaches who is listening at that moment. It is now appended to a Redis stream, and the message only says there is something new to read. Every instance reads on from where it got to: when told, when its Redis connection comes back, and every few seconds in case the message was lost. An instance that fell further behind than the stream reaches back, or whose stream was lost with the store, cannot tell what it missed and checks all its connections, as every instance did before on each reconnect. --- .../Tests/AuthorityChangeLogTests.cs | 76 ++++++ API.IntegrationTests/Tests/DevicesTests.cs | 12 +- .../AuthorityChangeReaderTests.cs | 231 ++++++++++++++++++ .../AuthorityChangeReader.cs | 73 ++++++ .../AuthorityChangeSubscriber.cs | 93 +++++-- .../ConnectionAuthorityOptions.cs | 6 + .../ConnectionAuthorityRegistry.cs | 30 +-- .../IAuthorityChangeLog.cs | 54 ++++ .../RedisAuthorityChangeLog.cs | 83 +++++++ Common/OpenShockServiceHelper.cs | 2 + .../Services/RedisPubSub/IRedisPubService.cs | 5 +- Common/Services/RedisPubSub/RedisChannels.cs | 9 +- .../Services/RedisPubSub/RedisPubService.cs | 9 +- 13 files changed, 631 insertions(+), 52 deletions(-) create mode 100644 API.IntegrationTests/Tests/AuthorityChangeLogTests.cs create mode 100644 Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs create mode 100644 Common/ConnectionAuthority/AuthorityChangeReader.cs create mode 100644 Common/ConnectionAuthority/IAuthorityChangeLog.cs create mode 100644 Common/ConnectionAuthority/RedisAuthorityChangeLog.cs diff --git a/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs new file mode 100644 index 00000000..eec1b7e9 --- /dev/null +++ b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs @@ -0,0 +1,76 @@ +using Microsoft.Extensions.DependencyInjection; +using OpenShock.Common.ConnectionAuthority; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// The authority change log against the real store. What a reader makes of the log is covered without a store +/// in the unit tests; this is about the stream commands doing what the log promises. +/// +public sealed class AuthorityChangeLogTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + private IAuthorityChangeLog Log => WebApplicationFactory.Services.GetRequiredService(); + + [Test] + public async Task ReadAfter_ReturnsWhatWasAppendedSince_InOrder_AndNothingFromBefore() + { + var before = AuthorityChange.Device(Guid.NewGuid()); + var first = AuthorityChange.Session("stored-id-" + Guid.NewGuid()); + var second = AuthorityChange.ApiToken(Guid.NewGuid()); + + await Log.AppendAsync(before); + var mark = await Log.MarkAsync(); + await Log.AppendAsync(first); + await Log.AppendAsync(second); + + // Other tests announce changes into the same log, so look only at the ones made here. + var mine = (await Log.ReadAfterAsync(mark, 10_000)) + .Where(entry => entry.Change == before || entry.Change == first || entry.Change == second) + .ToArray(); + + await Assert.That(mine.Select(entry => entry.Change)).IsEquivalentTo(new[] { first, second }); + await Assert.That(mine[0].Position.CompareTo(mine[1].Position)).IsLessThan(0); + await Assert.That(mine[0].Position.CompareTo(mark)).IsGreaterThan(0); + } + + [Test] + public async Task ReadAfter_StopsAtTheCount_AndCarriesOnFromTheLastEntry() + { + var mark = await Log.MarkAsync(); + var changes = Enumerable.Range(0, 5).Select(_ => AuthorityChange.PublicShare(Guid.NewGuid())).ToArray(); + foreach (var change in changes) await Log.AppendAsync(change); + + var seen = new List(); + var position = mark; + while (true) + { + var batch = await Log.ReadAfterAsync(position, 2); + await Assert.That(batch.Count).IsLessThanOrEqualTo(2); + if (batch.Count == 0) break; + + seen.AddRange(batch.Where(entry => entry.Change is not null).Select(entry => entry.Change!)); + position = batch[^1].Position; + } + + await Assert.That(seen.Where(changes.Contains)).IsEquivalentTo(changes); + } + + [Test] + public async Task Mark_IsAnEntryWithoutAChange_AndTheLogReachesBackToIt() + { + var earlier = await Log.MarkAsync(); + var mark = await Log.MarkAsync(); + + var entries = await Log.ReadAfterAsync(earlier, 10_000); + var marked = entries.Single(entry => entry.Position == mark); + await Assert.That(marked.Change).IsNull(); + await Assert.That(marked.Unreadable).IsFalse(); + + var oldest = await Log.OldestAsync(); + await Assert.That(oldest).IsNotNull(); + await Assert.That(oldest!.Value.CompareTo(mark)).IsLessThanOrEqualTo(0); + } +} diff --git a/API.IntegrationTests/Tests/DevicesTests.cs b/API.IntegrationTests/Tests/DevicesTests.cs index fb83d1a6..8d985f8e 100644 --- a/API.IntegrationTests/Tests/DevicesTests.cs +++ b/API.IntegrationTests/Tests/DevicesTests.cs @@ -1,7 +1,6 @@ using System.Net; using System.Text.Json; using Microsoft.EntityFrameworkCore; -using MessagePack; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; using OpenShock.Common.ConnectionAuthority; @@ -149,11 +148,14 @@ public async Task RemoveDevice_AnnouncesAnAuthorityChangeForTheHub() var announced = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var reloads = 0; - await subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, (_, value) => + // The change is in the log; the message only says there is something new in it. + var log = WebApplicationFactory.Services.GetRequiredService(); + var from = await log.MarkAsync(); + await subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, (_, _) => _ = Task.Run(async () => { - var change = MessagePackSerializer.Deserialize((ReadOnlyMemory)value); - if (change == AuthorityChange.Device(deviceId)) announced.TrySetResult(); - }); + var entries = await log.ReadAfterAsync(from, 1000); + if (entries.Any(entry => entry.Change == AuthorityChange.Device(deviceId))) announced.TrySetResult(); + })); await subscriber.SubscribeAsync(RedisChannels.DeviceMessage(deviceId), (_, _) => Interlocked.Increment(ref reloads)); return (announced.Task, () => Volatile.Read(ref reloads)); diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs new file mode 100644 index 00000000..68a2c78d --- /dev/null +++ b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs @@ -0,0 +1,231 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using OpenShock.Common.ConnectionAuthority; + +namespace OpenShock.Common.Tests.ConnectionAuthority; + +public sealed class AuthorityChangeReaderTests +{ + /// The log as a list, with the two things that can happen to the real one: trimming and loss. + private sealed class FakeLog : IAuthorityChangeLog + { + private readonly List _entries = []; + private long _next = 1; + + public bool Unreachable { get; set; } + + public Task AppendAsync(AuthorityChange change) + { + _entries.Add(new LogEntry(new LogPosition(_next++, 0), change)); + return Task.CompletedTask; + } + + public void AppendUnreadable() => _entries.Add(new LogEntry(new LogPosition(_next++, 0), Change: null, Unreadable: true)); + + public Task MarkAsync() + { + ThrowIfUnreachable(); + var position = new LogPosition(_next++, 0); + _entries.Add(new LogEntry(position, Change: null)); + return Task.FromResult(position); + } + + public Task OldestAsync() + { + ThrowIfUnreachable(); + return Task.FromResult(_entries.Count == 0 ? null : _entries[0].Position); + } + + public Task> ReadAfterAsync(LogPosition position, int count) + { + ThrowIfUnreachable(); + return Task.FromResult>(_entries.Where(e => e.Position.CompareTo(position) > 0).Take(count).ToArray()); + } + + public void TrimTo(int keep) => _entries.RemoveRange(0, Math.Max(0, _entries.Count - keep)); + + public void Lose() => _entries.Clear(); + + private void ThrowIfUnreachable() + { + if (Unreachable) throw new InvalidOperationException("redis is down"); + } + } + + private sealed class CountingResolver : IGrantResolver + { + public int Calls; + + public Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken) + { + Interlocked.Increment(ref Calls); + return Task.FromResult(Grant.Empty); + } + } + + private sealed class FakeConnection : IAuthorizedConnection + { + public Task CloseAsync() => Task.CompletedTask; + } + + private sealed record Setup(FakeLog Log, AuthorityChangeReader Reader, ConnectionAuthorityRegistry Registry, CountingResolver Resolver) + { + /// A connection that depends on , already checked once. + public async Task Connect(Guid tokenId) + { + var (handle, _) = await Registry.RegisterAsync(new SignalRSubject(new ApiTokenCredential(Guid.NewGuid(), tokenId)), new FakeConnection()); + return handle; + } + + /// Reads the log and waits for the checks that started. + public async Task CatchUp(params ConnectionHandle[] handles) + { + var before = Resolver.Calls; + await Reader.CatchUpAsync(); + foreach (var handle in handles) await handle.WhenIdleAsync(); + return Resolver.Calls - before; + } + } + + private static async Task Create() + { + var resolver = new CountingResolver(); + var services = new ServiceCollection(); + services.AddScoped(_ => resolver); + var provider = services.BuildServiceProvider(); + + var registry = new ConnectionAuthorityRegistry( + provider.GetRequiredService(), + Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions()), + NullLogger.Instance); + + var log = new FakeLog(); + var reader = new AuthorityChangeReader(log, registry, NullLogger.Instance); + await reader.StartAsync(); + + return new Setup(log, reader, registry, resolver); + } + + [Test] + public async Task CatchUp_SignalsWhatWasAnnouncedSinceTheLastTime_Once() + { + var setup = await Create(); + var tokenId = Guid.NewGuid(); + var affected = await setup.Connect(tokenId); + var other = await setup.Connect(Guid.NewGuid()); + + await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + + await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(1); + await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(0); + } + + [Test] + public async Task Start_SkipsWhatWasAnnouncedBefore() + { + var setup = await Create(); + var tokenId = Guid.NewGuid(); + + // Announced before this reader started: a connection that registers afterwards was checked then. + await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + var reader = new AuthorityChangeReader(setup.Log, setup.Registry, NullLogger.Instance); + await reader.StartAsync(); + var handle = await setup.Connect(tokenId); + var before = setup.Resolver.Calls; + + await reader.CatchUpAsync(); + await handle.WhenIdleAsync(); + + await Assert.That(setup.Resolver.Calls).IsEqualTo(before); + } + + /// The case the log exists for: announced while this instance could not be reached. + [Test] + public async Task CatchUp_AfterTheLogWasUnreachable_ReadsWhatWasAnnouncedMeanwhile() + { + var setup = await Create(); + var tokenId = Guid.NewGuid(); + var handle = await setup.Connect(tokenId); + + setup.Log.Unreachable = true; + await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException(); + + setup.Log.Unreachable = false; + await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + + await Assert.That(await setup.CatchUp(handle)).IsEqualTo(1); + } + + [Test] + public async Task CatchUp_ReadsMoreThanOneBatch() + { + var setup = await Create(); + var tokenId = Guid.NewGuid(); + var handle = await setup.Connect(tokenId); + + for (var i = 0; i < 600; i++) await setup.Log.AppendAsync(AuthorityChange.Device(Guid.NewGuid())); + await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + + await Assert.That(await setup.CatchUp(handle)).IsEqualTo(1); + } + + [Test] + public async Task CatchUp_TrimmedPastWhereItReadTo_ChecksEveryConnectionAndCarriesOn() + { + var setup = await Create(); + var tokenId = Guid.NewGuid(); + var affected = await setup.Connect(tokenId); + var other = await setup.Connect(Guid.NewGuid()); + + // So much was announced that what this instance read last is gone, and with it maybe more. + for (var i = 0; i < 5; i++) await setup.Log.AppendAsync(AuthorityChange.Device(Guid.NewGuid())); + setup.Log.TrimTo(2); + + await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(2); + + // Reading goes on from there. + await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(1); + } + + [Test] + public async Task CatchUp_LogLost_ChecksEveryConnection() + { + var setup = await Create(); + var first = await setup.Connect(Guid.NewGuid()); + var second = await setup.Connect(Guid.NewGuid()); + + // The store restarted without its data. + setup.Log.Lose(); + + await Assert.That(await setup.CatchUp(first, second)).IsEqualTo(2); + await Assert.That(await setup.CatchUp(first, second)).IsEqualTo(0); + } + + [Test] + public async Task CatchUp_UnreadableEntry_ChecksEveryConnection() + { + var setup = await Create(); + var first = await setup.Connect(Guid.NewGuid()); + var second = await setup.Connect(Guid.NewGuid()); + + setup.Log.AppendUnreadable(); + + await Assert.That(await setup.CatchUp(first, second)).IsEqualTo(2); + await Assert.That(await setup.CatchUp(first, second)).IsEqualTo(0); + } + + [Test] + public async Task LogPosition_ParsesAndOrdersStreamIds() + { + await Assert.That(LogPosition.TryParse("1796499315377-2", out var position)).IsTrue(); + await Assert.That(position).IsEqualTo(new LogPosition(1796499315377, 2)); + await Assert.That(position.ToString()).IsEqualTo("1796499315377-2"); + + await Assert.That(new LogPosition(5, 0).CompareTo(new LogPosition(4, 9))).IsGreaterThan(0); + await Assert.That(new LogPosition(5, 1).CompareTo(new LogPosition(5, 2))).IsLessThan(0); + + await Assert.That(LogPosition.TryParse("not-an-id", out _)).IsFalse(); + await Assert.That(LogPosition.TryParse(null, out _)).IsFalse(); + } +} diff --git a/Common/ConnectionAuthority/AuthorityChangeReader.cs b/Common/ConnectionAuthority/AuthorityChangeReader.cs new file mode 100644 index 00000000..f2622fef --- /dev/null +++ b/Common/ConnectionAuthority/AuthorityChangeReader.cs @@ -0,0 +1,73 @@ +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// Reads the on from where this instance got to and signals each change to the +/// . +/// +/// +/// It starts at a mark it puts at the end of the log. Changes from before that need no reading: a connection is +/// checked when it registers. While the mark, or whatever was read last, is still in the log, nothing after it +/// was trimmed away and reading on misses nothing. Once it is not (this instance fell too far behind, or the log +/// was lost with the store), what was missed is unknown, so every connection is checked and reading starts over +/// from a new mark. +/// +public sealed class AuthorityChangeReader +{ + private const int BatchSize = 256; + + private readonly IAuthorityChangeLog _log; + private readonly ConnectionAuthorityRegistry _registry; + private readonly ILogger _logger; + + private LogPosition _position; + + public AuthorityChangeReader(IAuthorityChangeLog log, ConnectionAuthorityRegistry registry, ILogger logger) + { + _log = log; + _registry = registry; + _logger = logger; + } + + /// Decide where reading starts. Call once, before any connection is tracked. + public async Task StartAsync() => _position = await _log.MarkAsync(); + + /// + /// Signal everything announced since the last call. Not safe to call concurrently. Throws when the log cannot + /// be reached; calling again later carries on from the same place. + /// + public async Task CatchUpAsync() + { + var oldest = await _log.OldestAsync(); + if (oldest is not { } oldestPosition || oldestPosition.CompareTo(_position) > 0) + { + _logger.LogWarning("The authority change log no longer reaches back to where this instance read to, checking {Count} open connection(s)", _registry.Count); + + // The mark first: a change announced from here on is read, and one from before it is seen by the + // checks, which start after this. + _position = await _log.MarkAsync(); + _registry.SignalAll(); + return; + } + + IReadOnlyList entries; + do + { + entries = await _log.ReadAfterAsync(_position, BatchSize); + + foreach (var entry in entries) + { + if (entry.Change is { } change) + { + _registry.Signal(change); + } + else if (entry.Unreadable) + { + // What changed is unknown, so anything may have. + _registry.SignalAll(); + } + + _position = entry.Position; + } + } while (entries.Count == BatchSize); + } +} diff --git a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs index 81ebf665..3bd71804 100644 --- a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs +++ b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs @@ -1,4 +1,3 @@ -using MessagePack; using OpenShock.Common.Redis; using OpenShock.Common.Services.RedisPubSub; using StackExchange.Redis; @@ -6,66 +5,100 @@ namespace OpenShock.Common.ConnectionAuthority; /// -/// Turns what Redis says about changes in someone's authority into signals for the -/// . The same in every service that holds long-lived connections. +/// Keeps this instance's connections up with what is announced about changes in authority. The same in every +/// service that holds long-lived connections. /// /// -/// Redis pub/sub delivers a message only to who is listening at that moment. While this instance's Redis -/// connection is down it hears nothing, so when the connection comes back every connection is treated as if a -/// change had been announced for it. That leaves the periodic check to cover only a message lost on a healthy -/// connection. +/// The changes themselves are in the , where they wait for an instance that was +/// not listening. This decides when to read it: at once when says +/// there is something new, when the Redis connection comes back, and every +/// in case that message was lost. +/// +/// A session that reaches its lifetime is only ever announced by a Redis expiry event, which is lost when nobody +/// is listening. So when the connection that carries them comes back, the connections that depend on a session +/// are checked. +/// /// -public sealed class AuthorityChangeSubscriber : IHostedService +public sealed class AuthorityChangeSubscriber : BackgroundService { private static readonly string LoginSessionKeyPrefix = typeof(LoginSession).FullName + ":"; private readonly IConnectionMultiplexer _connectionMultiplexer; private readonly ISubscriber _subscriber; + private readonly AuthorityChangeReader _reader; private readonly ConnectionAuthorityRegistry _registry; private readonly ILogger _logger; - public AuthorityChangeSubscriber(IConnectionMultiplexer connectionMultiplexer, ConnectionAuthorityRegistry registry, ILogger logger) + /// Released when there may be something new to read. One pending release is enough for any number of reasons. + private readonly SemaphoreSlim _wake = new(0, 1); + + public AuthorityChangeSubscriber(IConnectionMultiplexer connectionMultiplexer, AuthorityChangeReader reader, ConnectionAuthorityRegistry registry, ILogger logger) { _connectionMultiplexer = connectionMultiplexer; _subscriber = connectionMultiplexer.GetSubscriber(); + _reader = reader; _registry = registry; _logger = logger; } - public async Task StartAsync(CancellationToken cancellationToken) + public override async Task StartAsync(CancellationToken cancellationToken) { + // Before anything else, and before the service takes connections: reading starts from here. + await _reader.StartAsync(); + await _subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, HandleAuthorityChanged); await _subscriber.SubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); _connectionMultiplexer.ConnectionRestored += HandleConnectionRestored; + + await base.StartAsync(cancellationToken); } - public async Task StopAsync(CancellationToken cancellationToken) + public override async Task StopAsync(CancellationToken cancellationToken) { _connectionMultiplexer.ConnectionRestored -= HandleConnectionRestored; await _subscriber.UnsubscribeAsync(RedisChannels.AuthorityChanged, HandleAuthorityChanged); await _subscriber.UnsubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); + + await base.StopAsync(cancellationToken); } - private void HandleAuthorityChanged(RedisChannel _, RedisValue message) + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - if (!message.HasValue) return; + var interval = _registry.CatchUpInterval; + + while (!stoppingToken.IsCancellationRequested) + { + try + { + await _wake.WaitAsync(interval, stoppingToken); + await _reader.CatchUpAsync(); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + // Shutting down. + } + catch (Exception e) + { + // Redis trouble. Reading carries on from the same place at the next reason to. + _logger.LogWarning(e, "Failed to read the authority change log"); + } + } + } - AuthorityChange change; + private void Wake() + { try { - change = MessagePackSerializer.Deserialize((ReadOnlyMemory)message); + _wake.Release(); } - catch (Exception e) + catch (SemaphoreFullException) { - // What changed is unknown, so anything may have. - _logger.LogError(e, "Failed to read an authority change, checking every connection"); - _registry.SignalAll(); - return; + // Already asked to read. } - - _registry.Signal(change); } + private void HandleAuthorityChanged(RedisChannel _, RedisValue __) => Wake(); + private void HandleKeyExpired(RedisChannel _, RedisValue message) { // A session that reached its lifetime: the same as a deleted one for the connections using it. @@ -77,10 +110,20 @@ private void HandleKeyExpired(RedisChannel _, RedisValue message) private void HandleConnectionRestored(object? sender, ConnectionFailedEventArgs e) { - // Only the connection that carries the subscriptions matters: messages published while it was down are gone. + Wake(); + if (e.ConnectionType != ConnectionType.Subscription) return; - _logger.LogInformation("Redis subscription connection restored, checking {Count} open connection(s) for changes missed meanwhile", _registry.Count); - _registry.SignalAll(); + _logger.LogInformation("Redis subscription connection restored, checking the connections that depend on a session for an expiry missed meanwhile"); + _registry.SignalWhere(DependsOnASession); + } + + private static bool DependsOnASession(ConnectionSubject subject) => + subject is SignalRSubject { Credential: SessionCredential } or LiveControlSubject { Credential: SessionCredential }; + + public override void Dispose() + { + _wake.Dispose(); + base.Dispose(); } } diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs index 975353e1..96b12f83 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs @@ -7,4 +7,10 @@ public sealed class ConnectionAuthorityOptions /// through Redis; this bounds how long one can go on, or an idle one stay open, when that message was lost. /// public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); + + /// + /// How often the log of announced changes is read when nothing said there was something new. Bounds how long + /// a change waits when the message that says so was lost. + /// + public TimeSpan CatchUpInterval { get; set; } = TimeSpan.FromSeconds(5); } diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index 5a7af1c3..21ffe5a9 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -12,8 +12,8 @@ namespace OpenShock.Common.ConnectionAuthority; /// connection check again, and they all end in the same : /// /// registering, which closes the gap between authenticating and being reachable by a change; -/// a change announced over Redis, see , or the chance that one was missed, see -/// ; +/// a change announced over Redis, see and , or the +/// chance that one was missed for good, see ; /// time, for a change whose announcement was lost or a grant that simply expired, see /// . This covers every connection, idle or not, so none stays open for much longer than /// after what it depends on is gone. @@ -52,6 +52,9 @@ public ConnectionAuthorityRegistry(IServiceScopeFactory scopeFactory, IOptionsHow long a successful check stays good before time alone is a reason to check again. public TimeSpan Interval => _options.Value.Interval; + /// How often the log of announced changes is read without being told to, see . + public TimeSpan CatchUpInterval => _options.Value.CatchUpInterval; + public int Count => _handles.Count; /// @@ -84,25 +87,24 @@ public ConnectionHandle Track(ConnectionSubject subject, IAuthorizedConnection c /// Something changed: every connection it can affect loses what it was granted and checks again. Returns at /// once, so it is safe to call from a Redis callback. /// - public void Signal(AuthorityChange change) - { - foreach (var handle in _handles.Keys) - { - if (!handle.Subject.IsAffectedBy(change)) continue; + public void Signal(AuthorityChange change) => SignalWhere(subject => subject.IsAffectedBy(change)); - handle.Invalidate(); - handle.RequestRefresh(); - } - } + /// + /// Changes may have been announced that this instance cannot learn of anymore, so every connection is treated + /// as if one had been announced for it. + /// + public void SignalAll() => SignalWhere(_ => true); /// - /// Changes may have been announced while this instance could not hear them (its Redis connection was down), so - /// every connection is treated as if one had been announced for it. + /// Like , for a change that cannot be named: every connection + /// picks is treated as if one had been announced for it. /// - public void SignalAll() + public void SignalWhere(Func affected) { foreach (var handle in _handles.Keys) { + if (!affected(handle.Subject)) continue; + handle.Invalidate(); handle.RequestRefresh(); } diff --git a/Common/ConnectionAuthority/IAuthorityChangeLog.cs b/Common/ConnectionAuthority/IAuthorityChangeLog.cs new file mode 100644 index 00000000..a0d2c8c4 --- /dev/null +++ b/Common/ConnectionAuthority/IAuthorityChangeLog.cs @@ -0,0 +1,54 @@ +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// The changes in authority that were announced, in order, kept for a while. What makes an announcement reach an +/// instance that was not listening when it was made: every instance reads on from where it got to. +/// +public interface IAuthorityChangeLog +{ + /// Announce a change. Throws when the log cannot be reached. + Task AppendAsync(AuthorityChange change); + + /// + /// Put a mark at the end of the log and return where it is, as a place to read on from. A mark is an entry + /// like any other, so it also tells a reader later whether the log still reaches back that far. + /// + Task MarkAsync(); + + /// Where the oldest entry still in the log is, null when the log is empty or gone. + Task OldestAsync(); + + /// Up to entries after , oldest first. + Task> ReadAfterAsync(LogPosition position, int count); +} + +/// A place in the log. Later entries compare greater. +public readonly record struct LogPosition(long Milliseconds, long Sequence) : IComparable +{ + public int CompareTo(LogPosition other) + { + var byTime = Milliseconds.CompareTo(other.Milliseconds); + return byTime != 0 ? byTime : Sequence.CompareTo(other.Sequence); + } + + public static bool TryParse(string? id, out LogPosition position) + { + position = default; + if (id is null) return false; + + var dash = id.IndexOf('-'); + if (dash <= 0) return false; + if (!long.TryParse(id.AsSpan(0, dash), out var milliseconds) || !long.TryParse(id.AsSpan(dash + 1), out var sequence)) return false; + + position = new LogPosition(milliseconds, sequence); + return true; + } + + public override string ToString() => $"{Milliseconds}-{Sequence}"; +} + +/// One entry of the log. +/// Where the entry is. +/// The change it announces, null for a mark and for an entry that could not be read. +/// The entry announces a change, but which one could not be read. +public readonly record struct LogEntry(LogPosition Position, AuthorityChange? Change, bool Unreadable = false); diff --git a/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs b/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs new file mode 100644 index 00000000..261d53b8 --- /dev/null +++ b/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs @@ -0,0 +1,83 @@ +using MessagePack; +using StackExchange.Redis; + +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// The log as a Redis stream. Unlike a pub/sub message, an entry stays until the stream is trimmed, so an +/// instance that was not listening reads it later. +/// +public sealed class RedisAuthorityChangeLog : IAuthorityChangeLog +{ + private static readonly RedisKey Key = "authority-changes"; + + private const string ChangeField = "c"; + private const string MarkField = "m"; + + /// + /// How many entries are kept, roughly. An instance that falls further behind than this cannot tell what it + /// missed and checks all its connections instead, see . + /// + private const int MaxLength = 10_000; + + private readonly IDatabase _db; + private readonly ILogger _logger; + + public RedisAuthorityChangeLog(IConnectionMultiplexer connectionMultiplexer, ILogger logger) + { + _db = connectionMultiplexer.GetDatabase(); + _logger = logger; + } + + /// + public Task AppendAsync(AuthorityChange change) => + AddAsync(ChangeField, (RedisValue)new ReadOnlyMemory(MessagePackSerializer.Serialize(change))); + + /// + public async Task MarkAsync() => Parse(await AddAsync(MarkField, 1)); + + /// + public async Task OldestAsync() + { + var entries = await _db.StreamRangeAsync(Key, count: 1); + return entries.Length == 0 ? null : Parse(entries[0].Id); + } + + /// + public async Task> ReadAfterAsync(LogPosition position, int count) + { + var entries = await _db.StreamReadAsync(Key, position.ToString(), count); + + var result = new LogEntry[entries.Length]; + for (var i = 0; i < entries.Length; i++) + { + result[i] = Read(entries[i]); + } + + return result; + } + + private Task AddAsync(RedisValue field, RedisValue value) => + _db.StreamAddAsync(Key, field, value, maxLength: MaxLength, useApproximateMaxLength: true); + + private LogEntry Read(StreamEntry entry) + { + var position = Parse(entry.Id); + + var payload = entry[ChangeField]; + if (payload.IsNull) return new LogEntry(position, Change: null); + + try + { + return new LogEntry(position, MessagePackSerializer.Deserialize((ReadOnlyMemory)payload)); + } + catch (Exception e) + { + _logger.LogError(e, "Failed to read the authority change at [{Position}]", position); + return new LogEntry(position, Change: null, Unreadable: true); + } + } + + private static LogPosition Parse(RedisValue id) => + LogPosition.TryParse(id, out var position) ? position : throw new FormatException($"Unexpected stream id '{id}'"); +} diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index cbc9638a..4716970a 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -77,6 +77,7 @@ public static IServiceCollection AddOpenShockMemDB(this IServiceCollection servi services.AddSingleton(ConnectionMultiplexer.Connect(options)); services.AddSingleton(serviceProvider => new RedisConnectionProvider(serviceProvider.GetRequiredService())); + services.AddSingleton(); services.AddSingleton(); // Readiness for the store we just registered. IsConnected alone flips late while the @@ -428,6 +429,7 @@ public static IServiceCollection AddOpenShockConnectionAuthority(this IServiceCo services.AddOptions(); services.AddSingleton(); services.AddScoped(); + services.AddSingleton(); services.AddHostedService(); services.AddHostedService(); diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index ef334b07..04babfd3 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -21,8 +21,9 @@ public interface IRedisPubService /// may do now, and are closed if that is nothing. /// /// - /// Call it after the change is saved. Best-effort, and never throws: a failure to announce is logged, and a - /// connection that misses the message finds out at its next periodic check. Callers need no handling of their own. + /// Call it after the change is saved. Never throws: a failure to announce is logged, and the connections it + /// affects find out at their next periodic check. Callers need no handling of their own. Once announced, the + /// change waits in the for an instance that was not listening. /// Task SendAuthorityChanged(AuthorityChange change); diff --git a/Common/Services/RedisPubSub/RedisChannels.cs b/Common/Services/RedisPubSub/RedisChannels.cs index db4aafce..7a6434e6 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -12,12 +12,13 @@ public static class RedisChannels /// /// Fired when something an open connection's authority can depend on changed: an account, a login session, an - /// API token, a hub or a public share. The payload is an - /// naming what changed. Every instance holding long-lived connections listens and has the affected ones look - /// up what they may do now. + /// API token, a hub or a public share. Carries no payload: what changed is in the + /// , and this only tells every instance + /// holding long-lived connections to read it now. An instance that misses the message reads the log a little + /// later on its own. /// /// - /// This is the only way a change in authority is announced. A hub's own channel + /// The log is the only way a change in authority is announced. A hub's own channel /// carries what the hub itself is told to do, including to reload its shockers, and says nothing about who may /// use it. /// diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 379b87b2..0acca7ff 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -9,11 +9,13 @@ namespace OpenShock.Common.Services.RedisPubSub; public sealed class RedisPubService : IRedisPubService { private readonly ISubscriber _subscriber; + private readonly IAuthorityChangeLog _authorityChangeLog; private readonly ILogger _logger; - public RedisPubService(IConnectionMultiplexer connectionMultiplexer, ILogger logger) + public RedisPubService(IConnectionMultiplexer connectionMultiplexer, IAuthorityChangeLog authorityChangeLog, ILogger logger) { _subscriber = connectionMultiplexer.GetSubscriber(); + _authorityChangeLog = authorityChangeLog; _logger = logger; } @@ -29,7 +31,10 @@ public async Task SendAuthorityChanged(AuthorityChange change) { try { - await Publish(RedisChannels.AuthorityChanged, change); + // The log is what carries the change. The message only says there is something new to read, so that + // nobody has to wait for their next look at the log. + await _authorityChangeLog.AppendAsync(change); + await _subscriber.PublishAsync(RedisChannels.AuthorityChanged, RedisValue.EmptyString); } catch (Exception e) { From 0fae5cc8d656ac226701ae232a41bfd2242a0b23 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 20:44:42 +0100 Subject: [PATCH 17/24] feat: stop looking every open connection up once a minute The periodic check was what found a change that never reached a connection, which made it run for every open connection every minute. What it stood in for is now handled where it happens, and the check is left as a backstop that runs every fifteen minutes. A change that cannot be announced is kept and announced once the log can be reached. A session's grant ends when the session does, so reaching its lifetime needs no message. Three writes that were never announced now are: reported API tokens, accounts deleted with their automation token, and a public share whose expiry is moved. --- .../Tests/GrantResolverTests.cs | 15 +++ .../Tests/PublicSharePasswordTests.cs | 26 +++++ API/Controller/Admin/AutomationTokenDelete.cs | 6 ++ .../Shares/Links/EditPublicShare.cs | 7 +- API/Controller/Tokens/ReportTokens.cs | 16 +++- .../AuthorityChangeAnnouncerTests.cs | 96 +++++++++++++++++++ .../AuthorityChangeAnnouncer.cs | 88 +++++++++++++++++ .../ConnectionAuthorityOptions.cs | 9 +- Common/ConnectionAuthority/GrantResolver.cs | 7 +- .../IAuthorityChangeLog.cs | 5 +- .../RedisAuthorityChangeLog.cs | 20 +++- Common/OpenShockServiceHelper.cs | 1 + .../Services/RedisPubSub/IRedisPubService.cs | 7 +- .../Services/RedisPubSub/RedisPubService.cs | 25 +---- 14 files changed, 295 insertions(+), 33 deletions(-) create mode 100644 Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs create mode 100644 Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs diff --git a/API.IntegrationTests/Tests/GrantResolverTests.cs b/API.IntegrationTests/Tests/GrantResolverTests.cs index 368d3b14..1021e772 100644 --- a/API.IntegrationTests/Tests/GrantResolverTests.cs +++ b/API.IntegrationTests/Tests/GrantResolverTests.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; using OpenShock.Common.ConnectionAuthority; +using OpenShock.Common.Constants; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.Session; @@ -112,6 +113,20 @@ public async Task LiveControl_Recipient_OwnerDeactivated_MayNotGoOn() await Assert.That(await Resolve(LiveControlBySession(recipient, deviceId, owner.Id))).IsNull(); } + [Test] + public async Task LiveControl_Session_GrantEndsWhenTheSessionDoes() + { + // Nothing reliably announces a session reaching its lifetime, so the grant carries when that is. + var owner = await CreateUser("grantsessexp"); + var (deviceId, _) = await CreateShockerOnDevice(owner.Id); + + var grant = await Resolve(LiveControlBySession(owner, deviceId, owner.Id)); + + var expected = DateTime.UtcNow.Add(Duration.LoginSessionLifetime); + await Assert.That(grant!.ExpiresAt).IsNotNull(); + await Assert.That((grant.ExpiresAt!.Value - expected).Duration()).IsLessThan(TimeSpan.FromMinutes(5)); + } + [Test] public async Task LiveControl_Session_Removed_MayNotGoOn() { diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 46c7dbd9..0279d704 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -1,3 +1,4 @@ +using OpenShock.Common.ConnectionAuthority; using OpenShock.IntegrationTests.Shared; using StackExchange.Redis; using System.Net; @@ -289,6 +290,31 @@ public async Task Hub_OwnerConnectsWithoutToken() await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); } + /// + /// An open connection holds the time the share ends as it was when last checked. Moving it has to be + /// announced, or the connection would only find out at the rare periodic check. + /// + [Test] + public async Task Hub_MovingTheExpiryCloser_ClosesOpenConnectionsWhenItIsReached() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubexpiry", password: null); + await using var connection = await ConnectAsync(shareId, unlockToken: null); + + var log = WebApplicationFactory.Services.GetRequiredService(); + var before = await log.MarkAsync(); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var response = await client.PutAsync($"/1/shares/links/{shareId}", + TestHelper.JsonContent(new { name = "Ends soon", expiresOn = DateTime.UtcNow.AddSeconds(3), slug = (string?)null })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + // The check interval is short in tests and would find it too, so the announcement is looked for itself. + var announced = (await log.ReadAfterAsync(before, 10_000)).Any(entry => entry.Change == AuthorityChange.PublicShare(shareId)); + await Assert.That(announced).IsTrue(); + + await AssertConnectionClosesAsync(connection); + } + [Test] public async Task Hub_ChangingThePassword_ClosesOpenConnections() { diff --git a/API/Controller/Admin/AutomationTokenDelete.cs b/API/Controller/Admin/AutomationTokenDelete.cs index e59d2447..5c45e34e 100644 --- a/API/Controller/Admin/AutomationTokenDelete.cs +++ b/API/Controller/Admin/AutomationTokenDelete.cs @@ -2,9 +2,11 @@ using Microsoft.EntityFrameworkCore; using Npgsql; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.Audit; +using OpenShock.Common.Services.RedisPubSub; namespace OpenShock.API.Controller.Admin; @@ -22,6 +24,7 @@ public sealed partial class AdminController public async Task DeleteAutomationToken( [FromRoute] Guid id, [FromServices] IAuditService auditService, + [FromServices] IRedisPubService redisPubService, CancellationToken ct) { PedanticallyEnsureAdmin(); @@ -69,6 +72,9 @@ await auditService.LogAsync( _logger.LogInformation( "Deleted account {UserId} together with automation token {AutomationTokenId}", userId, token.Id); + + // Closes what the account still had open. + await redisPubService.SendAuthorityChanged(AuthorityChange.User(userId)); } return Ok(); diff --git a/API/Controller/Shares/Links/EditPublicShare.cs b/API/Controller/Shares/Links/EditPublicShare.cs index 94454cab..5179a3a3 100644 --- a/API/Controller/Shares/Links/EditPublicShare.cs +++ b/API/Controller/Shares/Links/EditPublicShare.cs @@ -6,8 +6,10 @@ using OpenShock.API.Services.DeviceUpdate; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Errors; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.RedisPubSub; using OpenShock.Internal.Common.Problems; namespace OpenShock.API.Controller.Shares.Links; @@ -29,7 +31,7 @@ public sealed partial class ShareLinksController [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // PublicShareExpiryDateInPast, SlugInvalid [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // SlugTaken - public async Task EditPublicShare([FromRoute] Guid publicShareId, [FromBody] PublicShareEdit body, [FromServices] IDeviceUpdateService deviceUpdateService, CancellationToken cancellationToken) + public async Task EditPublicShare([FromRoute] Guid publicShareId, [FromBody] PublicShareEdit body, [FromServices] IDeviceUpdateService deviceUpdateService, [FromServices] IRedisPubService redisPubService, CancellationToken cancellationToken) { if (body.ExpiresOn <= DateTime.UtcNow) return Problem(PublicShareError.PublicShareExpiryDateInPast); @@ -53,6 +55,9 @@ public async Task EditPublicShare([FromRoute] Guid publicShareId, } await deviceUpdateService.UpdatePublicShare(publicShareId); + + // When the share ends may have moved, and open connections to it hold the old time. + await redisPubService.SendAuthorityChanged(AuthorityChange.PublicShare(publicShareId)); return Ok(OwnPublicShareResponse.GetFromEf(share)); } } diff --git a/API/Controller/Tokens/ReportTokens.cs b/API/Controller/Tokens/ReportTokens.cs index 6126cc2b..5a73f166 100644 --- a/API/Controller/Tokens/ReportTokens.cs +++ b/API/Controller/Tokens/ReportTokens.cs @@ -8,8 +8,10 @@ using OpenShock.API.Models.Requests; using OpenShock.API.Services.Turnstile; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.AutomationTokens; +using OpenShock.Common.Services.RedisPubSub; using OpenShock.Common.Services.Webhook; using OpenShock.Common.Utils; using OpenShock.Internal.Common.Problems; @@ -38,6 +40,7 @@ public async Task ReportTokens( [FromServices] ICloudflareTurnstileService turnstileService, [FromServices] IAutomationTokenService automationTokens, [FromServices] IWebhookService webhookService, + [FromServices] IRedisPubService redisPubService, CancellationToken cancellationToken) { var remoteIP = HttpContext.GetRemoteIP(); @@ -66,9 +69,20 @@ public async Task ReportTokens( hashes[i] = HashingUtils.HashToken(body.Secrets[i]); } - nAffected = await _db.ApiTokens + var tokenIds = await _db.ApiTokens .Where(x => hashes.Contains(x.TokenHash)) + .Select(x => x.Id) + .ToArrayAsync(); + + nAffected = await _db.ApiTokens + .Where(x => tokenIds.Contains(x.Id)) .ExecuteDeleteAsync(); + + // A leaked token must also stop what is already connected with it. + foreach (var tokenId in tokenIds) + { + await redisPubService.SendAuthorityChanged(AuthorityChange.ApiToken(tokenId)); + } } catch (Exception e) { diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs new file mode 100644 index 00000000..fd8c2439 --- /dev/null +++ b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs @@ -0,0 +1,96 @@ +using Microsoft.Extensions.Logging.Abstractions; +using OpenShock.Common.ConnectionAuthority; + +namespace OpenShock.Common.Tests.ConnectionAuthority; + +public sealed class AuthorityChangeAnnouncerTests +{ + private sealed class FlakyLog : IAuthorityChangeLog + { + private readonly List _appended = []; + + public volatile bool Unreachable; + + public AuthorityChange[] Appended + { + get + { + lock (_appended) return [.. _appended]; + } + } + + public Task AppendAsync(AuthorityChange change) + { + if (Unreachable) throw new InvalidOperationException("redis is down"); + lock (_appended) _appended.Add(change); + return Task.CompletedTask; + } + + public Task MarkAsync() => throw new NotSupportedException(); + public Task OldestAsync() => throw new NotSupportedException(); + public Task> ReadAfterAsync(LogPosition position, int count) => throw new NotSupportedException(); + } + + private static AuthorityChangeAnnouncer Create(FlakyLog log) => + new(log, NullLogger.Instance) { RetryDelay = TimeSpan.FromMilliseconds(20) }; + + private static async Task Until(Func condition) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(10); + } + + [Test] + public async Task Announce_LogsTheChange() + { + var log = new FlakyLog(); + var announcer = Create(log); + var change = AuthorityChange.User(Guid.NewGuid()); + + await announcer.AnnounceAsync(change); + + await Assert.That(log.Appended).IsEquivalentTo(new[] { change }); + await Assert.That(announcer.Waiting).IsEqualTo(0); + } + + [Test] + public async Task Announce_LogUnreachable_DoesNotThrow_AndLogsItOnceItCanBe() + { + var log = new FlakyLog { Unreachable = true }; + var announcer = Create(log); + var first = AuthorityChange.User(Guid.NewGuid()); + var second = AuthorityChange.ApiToken(Guid.NewGuid()); + + await announcer.AnnounceAsync(first); + await announcer.AnnounceAsync(second); + + await Assert.That(log.Appended.Length).IsEqualTo(0); + await Assert.That(announcer.Waiting).IsEqualTo(2); + + log.Unreachable = false; + await Until(() => announcer.Waiting == 0); + + await Assert.That(log.Appended).IsEquivalentTo(new[] { first, second }); + } + + [Test] + public async Task Announce_AfterItCaughtUp_StillRetriesTheNextFailure() + { + var log = new FlakyLog { Unreachable = true }; + var announcer = Create(log); + + await announcer.AnnounceAsync(AuthorityChange.Device(Guid.NewGuid())); + log.Unreachable = false; + await Until(() => announcer.Waiting == 0); + + // A second outage, after the first retry loop has ended. + log.Unreachable = true; + var later = AuthorityChange.PublicShare(Guid.NewGuid()); + await announcer.AnnounceAsync(later); + log.Unreachable = false; + await Until(() => announcer.Waiting == 0); + + await Assert.That(log.Appended).Contains(later); + await Assert.That(log.Appended.Length).IsEqualTo(2); + } +} diff --git a/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs new file mode 100644 index 00000000..84aac19c --- /dev/null +++ b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs @@ -0,0 +1,88 @@ +using System.Collections.Concurrent; + +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// Gets a change in authority into the , now or as soon as the log can be +/// reached again. +/// +/// +/// The change itself is already saved when it is announced, so the caller is never made to fail or wait for +/// this. A change that cannot be logged is kept here and tried again until it can. The order they end up in does +/// not matter: a change only names what to look at again. +/// +/// What is kept is lost if the process ends first. The connections it affects then find out at their next +/// periodic check, see . +/// +/// +public sealed class AuthorityChangeAnnouncer +{ + /// More than this waiting means Redis has been gone for long; newer ones are left to the periodic check. + private const int MaxWaiting = 10_000; + + private readonly IAuthorityChangeLog _log; + private readonly ILogger _logger; + + private readonly ConcurrentQueue _waiting = new(); + private int _retrying; + + public AuthorityChangeAnnouncer(IAuthorityChangeLog log, ILogger logger) + { + _log = log; + _logger = logger; + } + + /// How long to wait between attempts to log what is waiting. + internal TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(2); + + /// How many changes are waiting to be logged. + internal int Waiting => _waiting.Count; + + /// Never throws. + public async Task AnnounceAsync(AuthorityChange change) + { + try + { + await _log.AppendAsync(change); + } + catch (Exception e) + { + if (_waiting.Count >= MaxWaiting) + { + _logger.LogError(e, "Failed to announce a change in authority ({Change}) and too many are waiting already; open connections find out at their next periodic check", change); + return; + } + + _logger.LogWarning(e, "Failed to announce a change in authority ({Change}); trying again until it can be", change); + _waiting.Enqueue(change); + + if (Interlocked.CompareExchange(ref _retrying, 1, 0) == 0) _ = Task.Run(RetryAsync); + } + } + + private async Task RetryAsync() + { + while (true) + { + await Task.Delay(RetryDelay); + + try + { + while (_waiting.TryPeek(out var change)) + { + await _log.AppendAsync(change); + _waiting.TryDequeue(out _); + } + } + catch (Exception e) + { + _logger.LogDebug(e, "Still cannot announce {Count} change(s) in authority", _waiting.Count); + continue; + } + + // One may have been added between the last look and here; whoever added it saw this still running. + Volatile.Write(ref _retrying, 0); + if (_waiting.IsEmpty || Interlocked.CompareExchange(ref _retrying, 1, 0) != 0) return; + } + } +} diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs index 96b12f83..531f6978 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs @@ -3,10 +3,13 @@ namespace OpenShock.Common.ConnectionAuthority; public sealed class ConnectionAuthorityOptions { /// - /// How long a connection's last successful check stays good. Changes normally reach a connection at once - /// through Redis; this bounds how long one can go on, or an idle one stay open, when that message was lost. + /// How long a connection's last successful check stays good when nothing was announced for it. Every change + /// is announced and reaches a connection within seconds, and a grant that expires is checked when it does, so + /// this is not what normally ends a connection. It is the backstop for a change that was never announced: one + /// written past the application, or one still waiting to be announced when its process ended. Each open + /// connection costs one lookup per interval. /// - public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); + public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(15); /// /// How often the log of announced changes is read when nothing said there was something new. Bounds how long diff --git a/Common/ConnectionAuthority/GrantResolver.cs b/Common/ConnectionAuthority/GrantResolver.cs index ddcc91c8..c9b06595 100644 --- a/Common/ConnectionAuthority/GrantResolver.cs +++ b/Common/ConnectionAuthority/GrantResolver.cs @@ -123,7 +123,12 @@ public GrantResolver(OpenShockContext db, ISessionService sessionService) // 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 active = await _db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, cancellationToken); - return active ? Grant.Empty : null; + if (!active) return null; + + // Reaching its lifetime ends a session without anyone deleting it, so the grant ends with it. + return session.Expires?.UtcDateTime is { } expiresAt && expiresAt > DateTime.UtcNow + ? new Grant { ExpiresAt = expiresAt } + : Grant.Empty; } private static DateTime? Earliest(DateTime? a, DateTime? b) => a is null ? b : b is null ? a : a < b ? a : b; diff --git a/Common/ConnectionAuthority/IAuthorityChangeLog.cs b/Common/ConnectionAuthority/IAuthorityChangeLog.cs index a0d2c8c4..f259bbae 100644 --- a/Common/ConnectionAuthority/IAuthorityChangeLog.cs +++ b/Common/ConnectionAuthority/IAuthorityChangeLog.cs @@ -6,7 +6,10 @@ namespace OpenShock.Common.ConnectionAuthority; /// public interface IAuthorityChangeLog { - /// Announce a change. Throws when the log cannot be reached. + /// + /// Add a change and tell everyone reading that there is something new. Throws when the log cannot be reached; + /// to announce a change without having to handle that, use . + /// Task AppendAsync(AuthorityChange change); /// diff --git a/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs b/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs index 261d53b8..95d6835a 100644 --- a/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs +++ b/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs @@ -1,4 +1,5 @@ using MessagePack; +using OpenShock.Common.Services.RedisPubSub; using StackExchange.Redis; namespace OpenShock.Common.ConnectionAuthority; @@ -21,17 +22,32 @@ public sealed class RedisAuthorityChangeLog : IAuthorityChangeLog private const int MaxLength = 10_000; private readonly IDatabase _db; + private readonly ISubscriber _subscriber; private readonly ILogger _logger; public RedisAuthorityChangeLog(IConnectionMultiplexer connectionMultiplexer, ILogger logger) { _db = connectionMultiplexer.GetDatabase(); + _subscriber = connectionMultiplexer.GetSubscriber(); _logger = logger; } /// - public Task AppendAsync(AuthorityChange change) => - AddAsync(ChangeField, (RedisValue)new ReadOnlyMemory(MessagePackSerializer.Serialize(change))); + public async Task AppendAsync(AuthorityChange change) + { + await AddAsync(ChangeField, (RedisValue)new ReadOnlyMemory(MessagePackSerializer.Serialize(change))); + + try + { + // The entry is what carries the change. This only says there is something new to read, so that + // nobody has to wait for their next look at the log. + await _subscriber.PublishAsync(RedisChannels.AuthorityChanged, RedisValue.EmptyString); + } + catch (Exception e) + { + _logger.LogDebug(e, "Failed to say that there is a new authority change; it is read a little later"); + } + } /// public async Task MarkAsync() => Parse(await AddAsync(MarkField, 1)); diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 4716970a..0cc03425 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -78,6 +78,7 @@ public static IServiceCollection AddOpenShockMemDB(this IServiceCollection servi services.AddSingleton(serviceProvider => new RedisConnectionProvider(serviceProvider.GetRequiredService())); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); // Readiness for the store we just registered. IsConnected alone flips late while the diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 04babfd3..e8030e5a 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -21,9 +21,10 @@ public interface IRedisPubService /// may do now, and are closed if that is nothing. /// /// - /// Call it after the change is saved. Never throws: a failure to announce is logged, and the connections it - /// affects find out at their next periodic check. Callers need no handling of their own. Once announced, the - /// change waits in the for an instance that was not listening. + /// Call it after the change is saved, for every change: the periodic check that would otherwise find it is + /// rare. Never throws and needs no handling by the caller: a change that cannot be announced now is announced + /// as soon as it can be, see . Once announced, it waits in the + /// for an instance that was not listening. /// Task SendAuthorityChanged(AuthorityChange change); diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 0acca7ff..6629920e 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -9,14 +9,12 @@ namespace OpenShock.Common.Services.RedisPubSub; public sealed class RedisPubService : IRedisPubService { private readonly ISubscriber _subscriber; - private readonly IAuthorityChangeLog _authorityChangeLog; - private readonly ILogger _logger; + private readonly AuthorityChangeAnnouncer _authorityChanges; - public RedisPubService(IConnectionMultiplexer connectionMultiplexer, IAuthorityChangeLog authorityChangeLog, ILogger logger) + public RedisPubService(IConnectionMultiplexer connectionMultiplexer, AuthorityChangeAnnouncer authorityChanges) { _subscriber = connectionMultiplexer.GetSubscriber(); - _authorityChangeLog = authorityChangeLog; - _logger = logger; + _authorityChanges = authorityChanges; } private Task Publish(RedisChannel channel, T msg) => _subscriber.PublishAsync(channel, (RedisValue)new ReadOnlyMemory(MessagePackSerializer.Serialize(msg))); @@ -27,22 +25,7 @@ public Task SendDeviceUpdate(Guid deviceId) return PublishMessage(deviceId, DeviceMessage.Create(DeviceTriggerType.DeviceInfoUpdated)); } - public async Task SendAuthorityChanged(AuthorityChange change) - { - try - { - // The log is what carries the change. The message only says there is something new to read, so that - // nobody has to wait for their next look at the log. - await _authorityChangeLog.AppendAsync(change); - await _subscriber.PublishAsync(RedisChannels.AuthorityChanged, RedisValue.EmptyString); - } - catch (Exception e) - { - // The change itself is already saved and the caller can do nothing about this. The connections it - // affects find out at their next periodic check. - _logger.LogWarning(e, "Failed to announce a change in authority ({Change}); open connections find out at their next check", change); - } - } + public Task SendAuthorityChanged(AuthorityChange change) => _authorityChanges.AnnounceAsync(change); public Task SendEmailOutboxPending() { From 042ec5392d63ea5c0669e50f3c43d4692766d025 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 20:49:07 +0100 Subject: [PATCH 18/24] feat: make the connection check intervals configurable and tidy up around announcing The intervals are read from OpenShock:ConnectionAuthority. A change still waiting to be announced is tried once more when the service shuts down. Deleting accounts with their automation token also removes their sessions. Tests cover the announcements made for reported API tokens and for accounts deleted with an automation token. --- .../Tests/AutomationTokenTests.cs | 9 ++++++ API.IntegrationTests/Tests/TokensTests.cs | 29 +++++++++++++++++++ API/Controller/Admin/AutomationTokenDelete.cs | 12 ++++++++ API/Controller/Tokens/ReportTokens.cs | 1 + .../AuthorityChangeAnnouncerTests.cs | 26 +++++++++++++++++ .../AuthorityChangeAnnouncer.cs | 26 +++++++++++++++-- .../ConnectionAuthorityOptions.cs | 3 ++ Common/OpenShockServiceHelper.cs | 6 +++- 8 files changed, 108 insertions(+), 4 deletions(-) diff --git a/API.IntegrationTests/Tests/AutomationTokenTests.cs b/API.IntegrationTests/Tests/AutomationTokenTests.cs index 5568a9b9..870f77e8 100644 --- a/API.IntegrationTests/Tests/AutomationTokenTests.cs +++ b/API.IntegrationTests/Tests/AutomationTokenTests.cs @@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.AutomationTokens; @@ -315,6 +316,9 @@ public async Task Delete_DeletesTokenAndTheAccountsItCreated() var unrelatedId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("autodelunrelated"), UniqueNames.Email("autodelunrelated"), Password); using var client = await CreateAdminClient("autodelete"); + var log = WebApplicationFactory.Services.GetRequiredService(); + var before = await log.MarkAsync(); + var response = await client.DeleteAsync($"/1/admin/automationTokens/{tokenId}"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); @@ -324,6 +328,11 @@ public async Task Delete_DeletesTokenAndTheAccountsItCreated() await Assert.That(await db.AutomationTokens.AnyAsync(t => t.Id == tokenId)).IsFalse(); await Assert.That(await db.Users.AnyAsync(u => u.Id == createdId)).IsFalse(); await Assert.That(await db.Users.AnyAsync(u => u.Id == unrelatedId)).IsTrue(); + + // Announced, so whatever the deleted account still had open is closed. The other account is left alone. + var announced = (await log.ReadAfterAsync(before, 10_000)).Select(entry => entry.Change).ToArray(); + await Assert.That(announced).Contains(AuthorityChange.User(createdId)); + await Assert.That(announced).DoesNotContain(AuthorityChange.User(unrelatedId)); } // --- Helpers --- diff --git a/API.IntegrationTests/Tests/TokensTests.cs b/API.IntegrationTests/Tests/TokensTests.cs index c7dc2770..844c3dc9 100644 --- a/API.IntegrationTests/Tests/TokensTests.cs +++ b/API.IntegrationTests/Tests/TokensTests.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.ConnectionAuthority; using OpenShock.Common.OpenShockDb; using OpenShock.IntegrationTests.Shared; @@ -305,6 +306,34 @@ public async Task DeleteToken_ApiTokenDeletingAnotherTokenOfItsOwner_Returns403A // --- Helpers --- + [Test] + public async Task ReportTokens_DeletesTheLeakedTokenAndAnnouncesIt() + { + var owner = await CreateUser("tokreportowner"); + var reporter = await CreateUser("tokreporter"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "Leaked"); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, reporter.SessionToken); + + var log = WebApplicationFactory.Services.GetRequiredService(); + var before = await log.MarkAsync(); + + var response = await client.PostAsync("/1/tokens/report", TestHelper.JsonContent(new + { + turnstileResponse = "valid-token", + secrets = new[] { rawToken, "not-a-token-anyone-has" } + })); + + 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.ApiTokens.AnyAsync(t => t.Id == tokenId)).IsFalse(); + + // Announced, so a connection already open with the leaked token is closed too. + var announced = (await log.ReadAfterAsync(before, 10_000)).Select(entry => entry.Change).ToArray(); + await Assert.That(announced).Contains(AuthorityChange.ApiToken(tokenId)); + } + private Task CreateUser(string prefix) => TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password); diff --git a/API/Controller/Admin/AutomationTokenDelete.cs b/API/Controller/Admin/AutomationTokenDelete.cs index 5c45e34e..0db9ed89 100644 --- a/API/Controller/Admin/AutomationTokenDelete.cs +++ b/API/Controller/Admin/AutomationTokenDelete.cs @@ -7,6 +7,7 @@ using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.Audit; using OpenShock.Common.Services.RedisPubSub; +using OpenShock.Common.Services.Session; namespace OpenShock.API.Controller.Admin; @@ -25,6 +26,7 @@ public async Task DeleteAutomationToken( [FromRoute] Guid id, [FromServices] IAuditService auditService, [FromServices] IRedisPubService redisPubService, + [FromServices] ISessionService sessionService, CancellationToken ct) { PedanticallyEnsureAdmin(); @@ -75,6 +77,16 @@ await auditService.LogAsync( // Closes what the account still had open. await redisPubService.SendAuthorityChanged(AuthorityChange.User(userId)); + + try + { + await sessionService.DeleteSessionsByUserIdAsync(userId); + } + catch (Exception e) + { + // The account is gone, so its sessions can no longer be used; they only take up room until they expire. + _logger.LogWarning(e, "Failed to remove the sessions of deleted account {UserId}", userId); + } } return Ok(); diff --git a/API/Controller/Tokens/ReportTokens.cs b/API/Controller/Tokens/ReportTokens.cs index 5a73f166..f620508e 100644 --- a/API/Controller/Tokens/ReportTokens.cs +++ b/API/Controller/Tokens/ReportTokens.cs @@ -28,6 +28,7 @@ public sealed partial class TokensController /// /// /// + /// Announces each deleted token, so connections open with it are closed. /// /// The tokens were deleted if found [HttpPost("report")] diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs index fd8c2439..c2926841 100644 --- a/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs +++ b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs @@ -93,4 +93,30 @@ public async Task Announce_AfterItCaughtUp_StillRetriesTheNextFailure() await Assert.That(log.Appended).Contains(later); await Assert.That(log.Appended.Length).IsEqualTo(2); } + + [Test] + public async Task Dispose_TriesWhatIsStillWaitingOnceMore() + { + var log = new FlakyLog { Unreachable = true }; + var announcer = new AuthorityChangeAnnouncer(log, NullLogger.Instance) { RetryDelay = TimeSpan.FromHours(1) }; + var change = AuthorityChange.User(Guid.NewGuid()); + await announcer.AnnounceAsync(change); + + log.Unreachable = false; + await announcer.DisposeAsync(); + + await Assert.That(log.Appended).IsEquivalentTo(new[] { change }); + } + + [Test] + public async Task Dispose_LogStillUnreachable_DoesNotThrow() + { + var log = new FlakyLog { Unreachable = true }; + var announcer = new AuthorityChangeAnnouncer(log, NullLogger.Instance) { RetryDelay = TimeSpan.FromHours(1) }; + await announcer.AnnounceAsync(AuthorityChange.User(Guid.NewGuid())); + + await announcer.DisposeAsync(); + + await Assert.That(log.Appended.Length).IsEqualTo(0); + } } diff --git a/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs index 84aac19c..c9cef00a 100644 --- a/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs +++ b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs @@ -11,11 +11,12 @@ namespace OpenShock.Common.ConnectionAuthority; /// this. A change that cannot be logged is kept here and tried again until it can. The order they end up in does /// not matter: a change only names what to look at again. /// -/// What is kept is lost if the process ends first. The connections it affects then find out at their next -/// periodic check, see . +/// What is kept is tried once more when the service shuts down, and is lost if that fails too or the process +/// just ends. The connections it affects then find out at their next periodic check, see +/// . /// /// -public sealed class AuthorityChangeAnnouncer +public sealed class AuthorityChangeAnnouncer : IAsyncDisposable { /// More than this waiting means Redis has been gone for long; newer ones are left to the periodic check. private const int MaxWaiting = 10_000; @@ -85,4 +86,23 @@ private async Task RetryAsync() if (_waiting.IsEmpty || Interlocked.CompareExchange(ref _retrying, 1, 0) != 0) return; } } + + /// + /// A last attempt at what is still waiting, when the service shuts down. A change may be logged twice if the + /// retry is running too, which does no harm. + /// + public async ValueTask DisposeAsync() + { + try + { + while (_waiting.TryDequeue(out var change)) + { + await _log.AppendAsync(change); + } + } + catch (Exception e) + { + _logger.LogWarning(e, "Shutting down with {Count} change(s) in authority that could not be announced; open connections find out at their next periodic check", _waiting.Count + 1); + } + } } diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs index 531f6978..7fe3403f 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs @@ -1,7 +1,10 @@ namespace OpenShock.Common.ConnectionAuthority; +/// Bound to , so each value can be set per environment. public sealed class ConnectionAuthorityOptions { + public const string SectionName = "OpenShock:ConnectionAuthority"; + /// /// How long a connection's last successful check stays good when nothing was announced for it. Every change /// is announced and reaches a connection within seconds, and a grant that expires is checked when it does, so diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 0cc03425..01b7b41d 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -427,7 +427,11 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga /// public static IServiceCollection AddOpenShockConnectionAuthority(this IServiceCollection services) { - services.AddOptions(); + services.AddOptions() + .BindConfiguration(OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName) + .Validate(options => options.Interval > TimeSpan.Zero && options.CatchUpInterval > TimeSpan.Zero, + $"{OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName}: Interval and CatchUpInterval must be greater than zero.") + .ValidateOnStart(); services.AddSingleton(); services.AddScoped(); services.AddSingleton(); From 36c1dbd9e1d6fc72db2ea71d2cd789aa3ba2d782 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 20:49:21 +0100 Subject: [PATCH 19/24] test: fix a nullability warning in the authority change log tests --- API.IntegrationTests/Tests/AuthorityChangeLogTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs index eec1b7e9..f8defacf 100644 --- a/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs +++ b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs @@ -31,7 +31,7 @@ public async Task ReadAfter_ReturnsWhatWasAppendedSince_InOrder_AndNothingFromBe .Where(entry => entry.Change == before || entry.Change == first || entry.Change == second) .ToArray(); - await Assert.That(mine.Select(entry => entry.Change)).IsEquivalentTo(new[] { first, second }); + await Assert.That(mine.Select(entry => entry.Change!)).IsEquivalentTo(new[] { first, second }); await Assert.That(mine[0].Position.CompareTo(mine[1].Position)).IsLessThan(0); await Assert.That(mine[0].Position.CompareTo(mark)).IsGreaterThan(0); } From 37ffdd400251e32d98718a4c86c95117b6bcc80a Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 21:16:39 +0100 Subject: [PATCH 20/24] feat: check live control connections every minute and the rest every five Fifteen minutes was longer than the load calls for. Live control gets its own shorter interval, because going on with authority that is gone means still controlling someone's shockers, and there are few of those connections. --- API.IntegrationTests/WebApplicationFactory.cs | 6 ++++- .../ConnectionAuthorityRegistryTests.cs | 25 +++++++++++++++++-- .../ConnectionAuthorityOptions.cs | 8 +++++- .../ConnectionAuthorityRegistry.cs | 11 +++++--- .../ConnectionAuthoritySweeper.cs | 2 +- Common/OpenShockServiceHelper.cs | 4 +-- 6 files changed, 46 insertions(+), 10 deletions(-) diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index ed23dd13..a358d45d 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -113,7 +113,11 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) // 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 = ConnectionCheckInterval); + services.Configure(options => + { + options.Interval = ConnectionCheckInterval; + options.LiveControlInterval = ConnectionCheckInterval; + }); }); } } diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs index 3eea5f6e..1cbb0834 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -39,14 +39,18 @@ public Task CloseAsync() } } - private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Create(TimeSpan? interval = null) + private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Create(TimeSpan? interval = null, TimeSpan? liveControlInterval = null) { var resolver = new FakeResolver(); var services = new ServiceCollection(); services.AddScoped(_ => resolver); var provider = services.BuildServiceProvider(); - var options = Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions { Interval = interval ?? TimeSpan.FromMinutes(1) }); + var options = Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions + { + Interval = interval ?? TimeSpan.FromMinutes(1), + LiveControlInterval = liveControlInterval ?? interval ?? TimeSpan.FromMinutes(1) + }); var registry = new ConnectionAuthorityRegistry(provider.GetRequiredService(), options, NullLogger.Instance); return (registry, resolver); } @@ -370,6 +374,23 @@ public async Task Sweep_ChecksEveryDueConnection_IdleHubConnectionsIncluded() await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 2); } + [Test] + public async Task Sweep_ChecksLiveControlOnItsOwnShorterInterval() + { + var (registry, resolver) = Create(interval: TimeSpan.FromHours(1), liveControlInterval: TimeSpan.FromMilliseconds(1)); + var (liveControl, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + var (signalR, _) = await registry.RegisterAsync(SignalR(), new FakeConnection()); + var callsAfterRegister = resolver.Calls; + await Task.Delay(20); + + registry.Sweep(DateTime.UtcNow); + await Settle(liveControl); + await Settle(signalR); + + // Only the live control connection was due. + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); + } + [Test] public async Task Sweep_LeavesARecentlyCheckedConnectionAlone() { diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs index 7fe3403f..ba236584 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs @@ -12,7 +12,13 @@ public sealed class ConnectionAuthorityOptions /// written past the application, or one still waiting to be announced when its process ended. Each open /// connection costs one lookup per interval. /// - public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(15); + public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(5); + + /// + /// The same as , for live control connections. Shorter, because going on with authority + /// that is gone means still controlling someone's shockers, and there are few of these connections. + /// + public TimeSpan LiveControlInterval { get; set; } = TimeSpan.FromMinutes(1); /// /// How often the log of announced changes is read when nothing said there was something new. Bounds how long diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index 21ffe5a9..5322463a 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -52,6 +52,9 @@ public ConnectionAuthorityRegistry(IServiceScopeFactory scopeFactory, IOptionsHow long a successful check stays good before time alone is a reason to check again. public TimeSpan Interval => _options.Value.Interval; + /// for live control connections, which are checked more often. + public TimeSpan LiveControlInterval => _options.Value.LiveControlInterval; + /// How often the log of announced changes is read without being told to, see . public TimeSpan CatchUpInterval => _options.Value.CatchUpInterval; @@ -111,17 +114,19 @@ public void SignalWhere(Func affected) } /// - /// Time as a reason to check again: connections whose last good check is older than or - /// did not cover a change announced since, and connections whose grant has reached its expiry. + /// Time as a reason to check again: connections whose last good check is older than their interval or did + /// not cover a change announced since, and connections whose grant has reached its expiry. /// public void Sweep(DateTime now) { var interval = Interval; + var liveControlInterval = LiveControlInterval; foreach (var handle in _handles.Keys) { var expired = handle.Grant is { } grant && grant.IsExpired(now); + var maxAge = handle.Subject is LiveControlSubject ? liveControlInterval : interval; - if (expired || !handle.WasCheckedWithin(interval)) handle.RequestRefreshIfIdle(); + if (expired || !handle.WasCheckedWithin(maxAge)) handle.RequestRefreshIfIdle(); } } diff --git a/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs b/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs index 699e5ba6..3688e362 100644 --- a/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs +++ b/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs @@ -21,7 +21,7 @@ public ConnectionAuthoritySweeper(ConnectionAuthorityRegistry registry, ILogger< protected override async Task ExecuteAsync(CancellationToken stoppingToken) { // Often enough that a due connection is not left waiting for long, without spinning on a short interval. - var period = TimeSpan.FromTicks(Math.Clamp(_registry.Interval.Ticks / 2, MinPeriod.Ticks, MaxPeriod.Ticks)); + var period = TimeSpan.FromTicks(Math.Clamp(Math.Min(_registry.Interval.Ticks, _registry.LiveControlInterval.Ticks) / 2, MinPeriod.Ticks, MaxPeriod.Ticks)); using var timer = new PeriodicTimer(period); try diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 01b7b41d..56c96d30 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -429,8 +429,8 @@ public static IServiceCollection AddOpenShockConnectionAuthority(this IServiceCo { services.AddOptions() .BindConfiguration(OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName) - .Validate(options => options.Interval > TimeSpan.Zero && options.CatchUpInterval > TimeSpan.Zero, - $"{OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName}: Interval and CatchUpInterval must be greater than zero.") + .Validate(options => options.Interval > TimeSpan.Zero && options.LiveControlInterval > TimeSpan.Zero && options.CatchUpInterval > TimeSpan.Zero, + $"{OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName}: Interval, LiveControlInterval and CatchUpInterval must be greater than zero.") .ValidateOnStart(); services.AddSingleton(); services.AddScoped(); From 9bb7b3ee76ed6775eb435e5659d8e542002de7c9 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 21:17:51 +0100 Subject: [PATCH 21/24] feat: check connections other than live control every fifteen minutes Live control keeps its one minute. --- Common/ConnectionAuthority/ConnectionAuthorityOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs index ba236584..2dbfd74a 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs @@ -12,7 +12,7 @@ public sealed class ConnectionAuthorityOptions /// written past the application, or one still waiting to be announced when its process ended. Each open /// connection costs one lookup per interval. /// - public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(5); + public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(15); /// /// The same as , for live control connections. Shorter, because going on with authority From 59b124f2369066e47e91c542fdb362eedda66fe1 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 21:22:44 +0100 Subject: [PATCH 22/24] feat: close every connection when the authority change log stays out of reach Without the log an instance cannot learn that a connection should end. A short loss is sat out, fifteen seconds by default. Past that its connections are closed, and clients connect again once the store is back. --- .../AuthorityChangeReaderTests.cs | 54 +++++++++++++++++-- .../AuthorityChangeReader.cs | 30 +++++++++++ .../ConnectionAuthorityOptions.cs | 8 +++ .../ConnectionAuthorityRegistry.cs | 21 +++++++- Common/OpenShockServiceHelper.cs | 4 +- 5 files changed, 110 insertions(+), 7 deletions(-) diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs index 68a2c78d..4c0067eb 100644 --- a/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs +++ b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs @@ -65,7 +65,13 @@ private sealed class CountingResolver : IGrantResolver private sealed class FakeConnection : IAuthorizedConnection { - public Task CloseAsync() => Task.CompletedTask; + public int Closed; + + public Task CloseAsync() + { + Interlocked.Increment(ref Closed); + return Task.CompletedTask; + } } private sealed record Setup(FakeLog Log, AuthorityChangeReader Reader, ConnectionAuthorityRegistry Registry, CountingResolver Resolver) @@ -87,7 +93,7 @@ public async Task CatchUp(params ConnectionHandle[] handles) } } - private static async Task Create() + private static async Task Create(TimeSpan? closeAfterLogUnreachable = null) { var resolver = new CountingResolver(); var services = new ServiceCollection(); @@ -96,7 +102,7 @@ private static async Task Create() var registry = new ConnectionAuthorityRegistry( provider.GetRequiredService(), - Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions()), + Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions { CloseAfterLogUnreachable = closeAfterLogUnreachable ?? TimeSpan.FromHours(1) }), NullLogger.Instance); var log = new FakeLog(); @@ -156,6 +162,48 @@ public async Task CatchUp_AfterTheLogWasUnreachable_ReadsWhatWasAnnouncedMeanwhi await Assert.That(await setup.CatchUp(handle)).IsEqualTo(1); } + [Test] + public async Task CatchUp_LogUnreachableForTooLong_ClosesEveryConnection() + { + var setup = await Create(closeAfterLogUnreachable: TimeSpan.FromMilliseconds(50)); + var handle = await setup.Connect(Guid.NewGuid()); + setup.Log.Unreachable = true; + + // Not yet: a short loss is sat out. + await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException(); + await Assert.That(handle.IsRevoked).IsFalse(); + + await Task.Delay(100); + await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException(); + + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(setup.Registry.Count).IsEqualTo(0); + + // One that connects while the log is still gone goes the same way at the next read. + var later = await setup.Connect(Guid.NewGuid()); + await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException(); + await Assert.That(later.IsRevoked).IsTrue(); + } + + [Test] + public async Task CatchUp_LogBackInTime_ClosesNothing_AndTheWaitStartsOver() + { + var setup = await Create(closeAfterLogUnreachable: TimeSpan.FromMilliseconds(50)); + var handle = await setup.Connect(Guid.NewGuid()); + + setup.Log.Unreachable = true; + await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException(); + setup.Log.Unreachable = false; + await setup.Reader.CatchUpAsync(); + + // A new loss long after the first one is a new one, not the old one grown past the limit. + await Task.Delay(100); + setup.Log.Unreachable = true; + await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException(); + + await Assert.That(handle.IsRevoked).IsFalse(); + } + [Test] public async Task CatchUp_ReadsMoreThanOneBatch() { diff --git a/Common/ConnectionAuthority/AuthorityChangeReader.cs b/Common/ConnectionAuthority/AuthorityChangeReader.cs index f2622fef..ef236f58 100644 --- a/Common/ConnectionAuthority/AuthorityChangeReader.cs +++ b/Common/ConnectionAuthority/AuthorityChangeReader.cs @@ -1,3 +1,5 @@ +using System.Diagnostics; + namespace OpenShock.Common.ConnectionAuthority; /// @@ -10,6 +12,11 @@ namespace OpenShock.Common.ConnectionAuthority; /// was trimmed away and reading on misses nothing. Once it is not (this instance fell too far behind, or the log /// was lost with the store), what was missed is unknown, so every connection is checked and reading starts over /// from a new mark. +/// +/// While the log cannot be reached at all, nothing here can learn that a connection should end. That is put up +/// with for ; after it every connection is closed, +/// and again at each failed read for those that came since. +/// /// public sealed class AuthorityChangeReader { @@ -21,6 +28,9 @@ public sealed class AuthorityChangeReader private LogPosition _position; + /// When reading first failed, while it still does. + private long? _unreachableSince; + public AuthorityChangeReader(IAuthorityChangeLog log, ConnectionAuthorityRegistry registry, ILogger logger) { _log = log; @@ -36,6 +46,26 @@ public AuthorityChangeReader(IAuthorityChangeLog log, ConnectionAuthorityRegistr /// be reached; calling again later carries on from the same place. /// public async Task CatchUpAsync() + { + try + { + await ReadOnAsync(); + _unreachableSince = null; + } + catch + { + _unreachableSince ??= Stopwatch.GetTimestamp(); + + if (Stopwatch.GetElapsedTime(_unreachableSince.Value) >= _registry.CloseAfterLogUnreachable) + { + await _registry.CloseAllAsync(); + } + + throw; + } + } + + private async Task ReadOnAsync() { var oldest = await _log.OldestAsync(); if (oldest is not { } oldestPosition || oldestPosition.CompareTo(_position) > 0) diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs index 2dbfd74a..73d7168a 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs @@ -25,4 +25,12 @@ public sealed class ConnectionAuthorityOptions /// a change waits when the message that says so was lost. /// public TimeSpan CatchUpInterval { get; set; } = TimeSpan.FromSeconds(5); + + /// + /// How long the log of announced changes may be out of reach before every connection on this instance is + /// closed. Without the log nothing here can learn that a connection should end, so past this they are ended + /// instead; clients connect again once it is back. Long enough to sit out a restart or failover of the store. + /// Zero closes them at the first failed read. + /// + public TimeSpan CloseAfterLogUnreachable { get; set; } = TimeSpan.FromSeconds(15); } diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index 5322463a..86c93b6a 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -58,6 +58,9 @@ public ConnectionAuthorityRegistry(IServiceScopeFactory scopeFactory, IOptionsHow often the log of announced changes is read without being told to, see . public TimeSpan CatchUpInterval => _options.Value.CatchUpInterval; + /// How long the log of announced changes may be out of reach before . + public TimeSpan CloseAfterLogUnreachable => _options.Value.CloseAfterLogUnreachable; + public int Count => _handles.Count; /// @@ -163,12 +166,26 @@ internal async Task CheckOnceAsync(ConnectionHandle handle) return RefreshResult.Revoked; } - private async Task RevokeAsync(ConnectionHandle handle) + /// + /// Close every connection, whatever it may do: this instance can no longer learn of a change to it. Not a + /// verdict on any of them; a client that connects again is checked as usual. + /// + public async Task CloseAllAsync() + { + var handles = _handles.Keys.ToArray(); + if (handles.Length == 0) return; + + _logger.LogWarning("Closing all {Count} open connection(s): changes in authority can no longer be learned of", handles.Length); + + await Task.WhenAll(handles.Select(handle => RevokeAsync(handle, log: false))); + } + + private async Task RevokeAsync(ConnectionHandle handle, bool log = true) { if (!handle.MarkRevoked()) return; Remove(handle); - _logger.LogInformation("Closing {Subject}: it may no longer go on", handle.Subject); + if (log) _logger.LogInformation("Closing {Subject}: it may no longer go on", handle.Subject); try { diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 56c96d30..4294ca0c 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -429,8 +429,8 @@ public static IServiceCollection AddOpenShockConnectionAuthority(this IServiceCo { services.AddOptions() .BindConfiguration(OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName) - .Validate(options => options.Interval > TimeSpan.Zero && options.LiveControlInterval > TimeSpan.Zero && options.CatchUpInterval > TimeSpan.Zero, - $"{OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName}: Interval, LiveControlInterval and CatchUpInterval must be greater than zero.") + .Validate(options => options.Interval > TimeSpan.Zero && options.LiveControlInterval > TimeSpan.Zero && options.CatchUpInterval > TimeSpan.Zero && options.CloseAfterLogUnreachable >= TimeSpan.Zero, + $"{OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName}: Interval, LiveControlInterval and CatchUpInterval must be greater than zero, and CloseAfterLogUnreachable not negative.") .ValidateOnStart(); services.AddSingleton(); services.AddScoped(); From 77caee6b1699d85c7739f8189fda7c5f4fa6ec10 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 21:50:43 +0100 Subject: [PATCH 23/24] fix: close the gaps the second review of the connection authority found - A connection with an announced change whose check keeps failing is closed after CloseAfterChangeUnchecked (15 seconds by default). It could do nothing in that state, but was still sent what is pushed to its user or public share. - A check that finishes after a newer reason to check was counted runs again instead of answering Valid from what it read before. - A hub call is not let through on a recent check when the grant has reached its expiry since. - A session whose expiry passes while it is being resolved grants nothing, instead of a grant without an expiry. - A change of a kind this version does not know decodes to null without an error; it is now read as unreadable, not as a mark. - The reader looks at how far back the log reaches after every page it reads, so a trim in the middle of reading is noticed. - Editing or deleting a public share announces the change before the push to its connections, which can fail. - Tests: the announcer test waits for the first retry to end, and the reader test asserts which connection was checked. --- .../Tests/AuthorityChangeLogTests.cs | 22 ++ .../Shares/Links/DeletePublicShare.cs | 3 +- .../Shares/Links/EditPublicShare.cs | 7 +- .../AuthorityChangeAnnouncerTests.cs | 3 +- .../AuthorityChangeReaderTests.cs | 41 ++++ .../ConnectionAuthorityRegistryTests.cs | 194 ++++++++++++++++-- .../AuthorityChangeAnnouncer.cs | 3 + .../AuthorityChangeReader.cs | 26 +-- .../ConnectionAuthorityOptions.cs | 9 + .../ConnectionAuthorityRegistry.cs | 31 ++- .../ConnectionAuthority/ConnectionHandle.cs | 67 +++++- Common/ConnectionAuthority/GrantResolver.cs | 8 +- .../RedisAuthorityChangeLog.cs | 9 +- Common/OpenShockServiceHelper.cs | 4 +- 14 files changed, 371 insertions(+), 56 deletions(-) diff --git a/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs index f8defacf..be1df801 100644 --- a/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs +++ b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs @@ -1,5 +1,7 @@ +using MessagePack; using Microsoft.Extensions.DependencyInjection; using OpenShock.Common.ConnectionAuthority; +using StackExchange.Redis; namespace OpenShock.API.IntegrationTests.Tests; @@ -58,6 +60,26 @@ public async Task ReadAfter_StopsAtTheCount_AndCarriesOnFromTheLastEntry() await Assert.That(seen.Where(changes.Contains)).IsEquivalentTo(changes); } + /// + /// A newer version can announce a kind of change this one does not know. That decodes to nothing without an + /// error, and must not pass for a mark: the reader has to treat it as "anything may have changed". + /// + [Test] + public async Task ReadAfter_ChangeOfAnUnknownKind_IsUnreadable() + { + var mark = await Log.MarkAsync(); + + // A union as MessagePack writes it, [key, value], with a key no AuthorityChange has. + var payload = MessagePackSerializer.Serialize(new object[] { 250, new object[] { Guid.NewGuid() } }); + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + var id = await redis.StreamAddAsync("authority-changes", "c", (RedisValue)new ReadOnlyMemory(payload)); + + var entry = (await Log.ReadAfterAsync(mark, 10_000)).Single(entry => entry.Position.ToString() == id.ToString()); + + await Assert.That(entry.Change).IsNull(); + await Assert.That(entry.Unreadable).IsTrue(); + } + [Test] public async Task Mark_IsAnEntryWithoutAChange_AndTheLogReachesBackToIt() { diff --git a/API/Controller/Shares/Links/DeletePublicShare.cs b/API/Controller/Shares/Links/DeletePublicShare.cs index cfa61abc..a7862e83 100644 --- a/API/Controller/Shares/Links/DeletePublicShare.cs +++ b/API/Controller/Shares/Links/DeletePublicShare.cs @@ -39,8 +39,9 @@ public async Task DeletePublicShare([FromRoute] Guid publicShareI if (result <= 0) return Problem(PublicShareError.PublicShareNotFound); - await deviceUpdateService.UpdatePublicShare(publicShareId); + // Before the push to the connections on it, which can fail: announcing cannot. await redisPubService.SendAuthorityChanged(AuthorityChange.PublicShare(publicShareId)); + await deviceUpdateService.UpdatePublicShare(publicShareId); return LegacyEmptyOk("Deleted public share"); } } diff --git a/API/Controller/Shares/Links/EditPublicShare.cs b/API/Controller/Shares/Links/EditPublicShare.cs index 5179a3a3..fa3edb41 100644 --- a/API/Controller/Shares/Links/EditPublicShare.cs +++ b/API/Controller/Shares/Links/EditPublicShare.cs @@ -54,10 +54,11 @@ public async Task EditPublicShare([FromRoute] Guid publicShareId, return Problem(PublicShareError.SlugTaken); } - await deviceUpdateService.UpdatePublicShare(publicShareId); - - // When the share ends may have moved, and open connections to it hold the old time. + // When the share ends may have moved, and open connections to it hold the old time. Before the push to + // them, which can fail: announcing cannot. await redisPubService.SendAuthorityChanged(AuthorityChange.PublicShare(publicShareId)); + + await deviceUpdateService.UpdatePublicShare(publicShareId); return Ok(OwnPublicShareResponse.GetFromEf(share)); } } diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs index c2926841..33ddae8b 100644 --- a/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs +++ b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs @@ -81,7 +81,8 @@ public async Task Announce_AfterItCaughtUp_StillRetriesTheNextFailure() await announcer.AnnounceAsync(AuthorityChange.Device(Guid.NewGuid())); log.Unreachable = false; - await Until(() => announcer.Waiting == 0); + await Until(() => announcer.Waiting == 0 && !announcer.IsRetrying); + await Assert.That(announcer.IsRetrying).IsFalse(); // A second outage, after the first retry loop has ended. log.Unreachable = true; diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs index 4c0067eb..f51bd1ed 100644 --- a/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs +++ b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs @@ -36,9 +36,17 @@ public Task MarkAsync() return Task.FromResult(_entries.Count == 0 ? null : _entries[0].Position); } + /// Runs once, just before the next read: something that happens to the log between two looks at it. + public Action? BeforeNextRead { get; set; } + public Task> ReadAfterAsync(LogPosition position, int count) { ThrowIfUnreachable(); + + var beforeRead = BeforeNextRead; + BeforeNextRead = null; + beforeRead?.Invoke(); + return Task.FromResult>(_entries.Where(e => e.Position.CompareTo(position) > 0).Take(count).ToArray()); } @@ -54,10 +62,16 @@ private void ThrowIfUnreachable() private sealed class CountingResolver : IGrantResolver { + private readonly System.Collections.Concurrent.ConcurrentQueue _checked = new(); + public int Calls; + /// How often the connection behind was looked up. + public int CallsFor(ConnectionHandle handle) => _checked.Count(subject => subject == handle.Subject); + public Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken) { + _checked.Enqueue(subject); Interlocked.Increment(ref Calls); return Task.FromResult(Grant.Empty); } @@ -122,7 +136,11 @@ public async Task CatchUp_SignalsWhatWasAnnouncedSinceTheLastTime_Once() await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + // Each was looked up once already, when it connected. await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(1); + await Assert.That(setup.Resolver.CallsFor(affected)).IsEqualTo(2); + await Assert.That(setup.Resolver.CallsFor(other)).IsEqualTo(1); + await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(0); } @@ -236,6 +254,29 @@ public async Task CatchUp_TrimmedPastWhereItReadTo_ChecksEveryConnectionAndCarri await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(1); } + /// The log is trimmed whenever something is appended, also in the middle of being read. + [Test] + public async Task CatchUp_TrimmedWhileReading_ChecksEveryConnection() + { + var setup = await Create(); + var tokenId = Guid.NewGuid(); + var affected = await setup.Connect(tokenId); + var other = await setup.Connect(Guid.NewGuid()); + + // The change for this connection is trimmed away just before the read, which then returns only what is + // left as if nothing were missing. + await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + for (var i = 0; i < 4; i++) await setup.Log.AppendAsync(AuthorityChange.Device(Guid.NewGuid())); + setup.Log.BeforeNextRead = () => setup.Log.TrimTo(2); + + await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(2); + await Assert.That(setup.Resolver.CallsFor(affected)).IsEqualTo(2); + + // Reading goes on from there. + await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(1); + } + [Test] public async Task CatchUp_LogLost_ChecksEveryConnection() { diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs index 1cbb0834..4d0b49da 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -39,7 +39,7 @@ public Task CloseAsync() } } - private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Create(TimeSpan? interval = null, TimeSpan? liveControlInterval = null) + private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Create(TimeSpan? interval = null, TimeSpan? liveControlInterval = null, TimeSpan? closeAfterChangeUnchecked = null) { var resolver = new FakeResolver(); var services = new ServiceCollection(); @@ -49,7 +49,8 @@ private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Cre var options = Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions { Interval = interval ?? TimeSpan.FromMinutes(1), - LiveControlInterval = liveControlInterval ?? interval ?? TimeSpan.FromMinutes(1) + LiveControlInterval = liveControlInterval ?? interval ?? TimeSpan.FromMinutes(1), + CloseAfterChangeUnchecked = closeAfterChangeUnchecked ?? TimeSpan.FromHours(1) }); var registry = new ConnectionAuthorityRegistry(provider.GetRequiredService(), options, NullLogger.Instance); return (registry, resolver); @@ -60,7 +61,7 @@ private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Cre deviceId ?? Guid.NewGuid(), ownerId ?? Guid.NewGuid()); - private static SignalRSubject SignalR() => new(new ApiTokenCredential(Guid.NewGuid(), Guid.NewGuid())); + private static SignalRSubject SignalR(Guid? tokenId = null) => new(new ApiTokenCredential(Guid.NewGuid(), tokenId ?? Guid.NewGuid())); private static SignalRSubject OnPublicShare(ConnectionHandle handle, Guid publicShareId) => (SignalRSubject)handle.Subject with { PublicShare = new PublicShareAccess(publicShareId, Guid.NewGuid(), PasswordStamp: null) }; @@ -226,6 +227,62 @@ public async Task Signal_DuringARunningLook_LooksAgainAndTheLaterReadWins() await Assert.That(handle.Grant).IsSameReferenceAs(current); } + /// + /// The change is counted before its check is requested, and the running check can finish in between. Whoever + /// waits for that check must not be told the connection is good on what it read before the change. + /// + [Test] + public async Task Invalidate_DuringARunningLook_IsNotAnsweredFromThatLook() + { + var (registry, resolver) = Create(); + var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection()); + + var stale = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(1) }; + var current = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(2) }; + var staleReadStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseStaleRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var reads = 0; + resolver.Resolve = async _ => + { + if (Interlocked.Increment(ref reads) > 1) return current; + + staleReadStarted.SetResult(); + await releaseStaleRead.Task; + return stale; + }; + + var waiting = handle.RefreshAsync(); + await staleReadStarted.Task; + + handle.Invalidate(); + releaseStaleRead.SetResult(); + + await Assert.That(await waiting).IsEqualTo(RefreshResult.Valid); + await Assert.That(reads).IsEqualTo(2); + await Assert.That(handle.Grant).IsSameReferenceAs(current); + } + + [Test] + public async Task EnsureFresh_GrantExpiredSinceTheLastLook_LooksAgain() + { + var (registry, resolver) = Create(); + resolver.Resolve = _ => Task.FromResult(new Grant { ExpiresAt = DateTime.UtcNow.AddSeconds(-1) }); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(SignalR(), connection); + var callsAfterRegister = resolver.Calls; + + // Checked a moment ago, but what that granted has ended since. The lookup cannot be made right now. + resolver.Resolve = _ => throw new InvalidOperationException("database is down"); + await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Failed); + await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1); + + // And once it can, the token is found expired. + resolver.Resolve = _ => Task.FromResult(null); + await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Revoked); + await Assert.That(connection.Closed).IsEqualTo(1); + } + [Test] public async Task EnsureFresh_LooksAgainOnlyOnceTheLastLookIsTooOld() { @@ -268,18 +325,20 @@ public async Task Track_DoesNotLookUntilUsed() /// /// A connection gets its second subject while a check of the first is still running. That check must not make - /// the new subject count as checked. + /// the new subject count as checked: whoever waits for it gets the answer of a check of the new subject. /// [Test] - public async Task UpdateSubject_DuringARunningCheck_StaysUncheckedUntilTheNewSubjectIs() + public async Task UpdateSubject_DuringARunningCheck_IsNotAnsweredUntilTheNewSubjectIsChecked() { var (registry, resolver) = Create(); var (handle, _) = await registry.RegisterAsync(SignalR(), new FakeConnection()); var checkStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var releaseCheck = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - resolver.Resolve = async _ => + var checkedSubjects = new List(); + resolver.Resolve = async subject => { + lock (checkedSubjects) checkedSubjects.Add(subject); checkStarted.TrySetResult(); await releaseCheck.Task; return Grant.Empty; @@ -290,27 +349,21 @@ public async Task UpdateSubject_DuringARunningCheck_StaysUncheckedUntilTheNewSub var publicShareId = Guid.NewGuid(); handle.UpdateSubject(OnPublicShare(handle, publicShareId)); - releaseCheck.SetResult(); - await running; + // The check of the old subject is still running, and says nothing about the new one. await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsFalse(); await Assert.That(handle.Grant).IsNull(); - ConnectionSubject? checkedSubject = null; - resolver.Resolve = subject => - { - checkedSubject = subject; - return Task.FromResult(Grant.Empty); - }; - await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Valid); - await Assert.That(PublicShareOf(checkedSubject)).IsEqualTo(publicShareId); + releaseCheck.SetResult(); + + await Assert.That(await running).IsEqualTo(RefreshResult.Valid); + await Assert.That(checkedSubjects.Count).IsEqualTo(2); + await Assert.That(PublicShareOf(checkedSubjects[0])).IsNull(); + await Assert.That(PublicShareOf(checkedSubjects[1])).IsEqualTo(publicShareId); await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsTrue(); + await Assert.That(handle.Grant).IsNotNull(); } - /// - /// An announced change whose check fails: the connection is not closed for it, but what it was granted before - /// the change is gone, and it is closed once the check can be made. - /// [Test] public async Task Signal_CheckFails_NothingIsGrantedUntilACheckSucceeds() { @@ -359,6 +412,107 @@ public async Task Signal_CheckFails_ThenSucceeds_GrantsAgain() await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsTrue(); } + /// + /// Such a connection may do nothing, but is still sent what is pushed to its user or public share. That is not + /// put up with for longer than the limit. + /// + [Test] + public async Task Sweep_ChangeStillUncheckedAfterTheLimit_Closes() + { + var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromMilliseconds(50)); + var tokenId = Guid.NewGuid(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection); + var other = new FakeConnection(); + await registry.RegisterAsync(SignalR(), other); + + resolver.Resolve = _ => throw new InvalidOperationException("database is down"); + registry.Signal(AuthorityChange.ApiToken(tokenId)); + await Settle(handle); + + // Within the limit it stays, and is checked again. + var callsBefore = resolver.Calls; + registry.Sweep(DateTime.UtcNow); + await Settle(handle); + await Assert.That(resolver.Calls).IsEqualTo(callsBefore + 1); + await Assert.That(connection.Closed).IsEqualTo(0); + + await Task.Delay(100); + registry.Sweep(DateTime.UtcNow); + + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(connection.Closed).IsEqualTo(1); + await Assert.That(other.Closed).IsEqualTo(0); + await Assert.That(registry.Count).IsEqualTo(1); + } + + [Test] + public async Task Sweep_ChangeCheckedWithinTheLimit_Stays() + { + var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromMilliseconds(50)); + var tokenId = Guid.NewGuid(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection); + + resolver.Resolve = _ => throw new InvalidOperationException("database is down"); + registry.Signal(AuthorityChange.ApiToken(tokenId)); + await Settle(handle); + + resolver.Resolve = _ => Task.FromResult(Grant.Empty); + registry.Sweep(DateTime.UtcNow); + await Settle(handle); + + await Task.Delay(100); + registry.Sweep(DateTime.UtcNow); + + await Assert.That(connection.Closed).IsEqualTo(0); + await Assert.That(handle.Grant).IsNotNull(); + } + + /// An outage alone drops nobody: without a change announced for it, a connection keeps what it had. + [Test] + public async Task Sweep_CheckFailsWithNoChangeAnnounced_NeverCloses() + { + var (registry, resolver) = Create(interval: TimeSpan.Zero, closeAfterChangeUnchecked: TimeSpan.Zero); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(SignalR(), connection); + + resolver.Resolve = _ => throw new InvalidOperationException("database is down"); + for (var i = 0; i < 3; i++) + { + registry.Sweep(DateTime.UtcNow); + await Settle(handle); + } + + await Assert.That(connection.Closed).IsEqualTo(0); + await Assert.That(handle.Grant).IsNotNull(); + } + + /// A check that has not had its turn yet is not a check that failed. + [Test] + public async Task Sweep_ChangeNotCheckedYet_DoesNotClose() + { + var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.Zero); + var tokenId = Guid.NewGuid(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection); + + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + resolver.Resolve = async _ => + { + await release.Task; + return Grant.Empty; + }; + registry.Signal(AuthorityChange.ApiToken(tokenId)); + registry.Sweep(DateTime.UtcNow); + + await Assert.That(connection.Closed).IsEqualTo(0); + + release.SetResult(); + await Settle(handle); + await Assert.That(handle.Grant).IsNotNull(); + } + [Test] public async Task Sweep_ChecksEveryDueConnection_IdleHubConnectionsIncluded() { diff --git a/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs index c9cef00a..a9148da4 100644 --- a/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs +++ b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs @@ -39,6 +39,9 @@ public AuthorityChangeAnnouncer(IAuthorityChangeLog log, ILoggerHow many changes are waiting to be logged. internal int Waiting => _waiting.Count; + /// Whether something is running that tries what is waiting again. + internal bool IsRetrying => Volatile.Read(ref _retrying) != 0; + /// Never throws. public async Task AnnounceAsync(AuthorityChange change) { diff --git a/Common/ConnectionAuthority/AuthorityChangeReader.cs b/Common/ConnectionAuthority/AuthorityChangeReader.cs index ef236f58..bca2dc9c 100644 --- a/Common/ConnectionAuthority/AuthorityChangeReader.cs +++ b/Common/ConnectionAuthority/AuthorityChangeReader.cs @@ -67,23 +67,25 @@ public async Task CatchUpAsync() private async Task ReadOnAsync() { - var oldest = await _log.OldestAsync(); - if (oldest is not { } oldestPosition || oldestPosition.CompareTo(_position) > 0) - { - _logger.LogWarning("The authority change log no longer reaches back to where this instance read to, checking {Count} open connection(s)", _registry.Count); - - // The mark first: a change announced from here on is read, and one from before it is seen by the - // checks, which start after this. - _position = await _log.MarkAsync(); - _registry.SignalAll(); - return; - } - IReadOnlyList entries; do { entries = await _log.ReadAfterAsync(_position, BatchSize); + // Looked at after the read, every time, so it holds for what was just read: the log can be trimmed + // at any moment, and only while the entry read last is still in it is nothing missing in between. + var oldest = await _log.OldestAsync(); + if (oldest is not { } oldestPosition || oldestPosition.CompareTo(_position) > 0) + { + _logger.LogWarning("The authority change log no longer reaches back to where this instance read to, checking {Count} open connection(s)", _registry.Count); + + // The mark first: a change announced from here on is read, and one from before it is seen by the + // checks, which start after this. + _position = await _log.MarkAsync(); + _registry.SignalAll(); + return; + } + foreach (var entry in entries) { if (entry.Change is { } change) diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs index 73d7168a..2778b64c 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs @@ -33,4 +33,13 @@ public sealed class ConnectionAuthorityOptions /// Zero closes them at the first failed read. /// public TimeSpan CloseAfterLogUnreachable { get; set; } = TimeSpan.FromSeconds(15); + + /// + /// How long a connection may stay open after a change was announced for it while the check that change calls + /// for keeps failing. It may do nothing in that time, but is still sent what is pushed to its user or public + /// share, and whether it still should be is exactly what cannot be looked up. Past this it is closed instead; + /// the client connects again once the check can be made. Long enough to sit out a restart or failover of the + /// database. Zero closes it at the first sweep after a failed check. + /// + public TimeSpan CloseAfterChangeUnchecked { get; set; } = TimeSpan.FromSeconds(15); } diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index 86c93b6a..d3b43db8 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -18,11 +18,14 @@ namespace OpenShock.Common.ConnectionAuthority; /// . This covers every connection, idle or not, so none stays open for much longer than /// after what it depends on is gone. /// -/// A check that fails (database or Redis trouble) never closes a connection. What it leaves behind depends on -/// why it ran. After an announced change the connection has no usable until -/// a check succeeds, so a pause or a revocation that was announced takes effect even while it cannot be looked -/// up. After a check that ran only because time passed, the connection keeps what it had. Either way the check is -/// tried again at every sweep. +/// A check that fails (database or Redis trouble) does not close a connection by itself. What it leaves behind +/// depends on why it ran. After an announced change the connection has no usable +/// until a check succeeds, so a pause or a revocation that was announced +/// takes effect on everything the connection asks for even while it cannot be looked up. What is pushed to it +/// (its user's control logs and device updates, a public share's updates) does not ask the grant and still +/// arrives, so that state is only put up with for : after it the +/// connection is closed. After a check that ran only because time passed, the connection keeps what it had and +/// stays. Either way the check is tried again at every sweep. /// /// Local to the process: every instance tracks its own connections and reacts to the same Redis messages. /// A change is matched against every connection, which is fine for how rarely authority changes. @@ -61,6 +64,9 @@ public ConnectionAuthorityRegistry(IServiceScopeFactory scopeFactory, IOptionsHow long the log of announced changes may be out of reach before . public TimeSpan CloseAfterLogUnreachable => _options.Value.CloseAfterLogUnreachable; + /// How long a change announced for a connection may go unchecked, while checking fails, before the connection is closed. + public TimeSpan CloseAfterChangeUnchecked => _options.Value.CloseAfterChangeUnchecked; + public int Count => _handles.Count; /// @@ -118,14 +124,26 @@ public void SignalWhere(Func affected) /// /// Time as a reason to check again: connections whose last good check is older than their interval or did - /// not cover a change announced since, and connections whose grant has reached its expiry. + /// not cover a change announced since, and connections whose grant has reached its expiry. And time as a + /// limit: a connection whose announced change could not be checked for + /// is closed. /// public void Sweep(DateTime now) { var interval = Interval; var liveControlInterval = LiveControlInterval; + var closeAfterChangeUnchecked = CloseAfterChangeUnchecked; foreach (var handle in _handles.Keys) { + if (handle.HasBeenUncheckedFor(closeAfterChangeUnchecked)) + { + _logger.LogWarning("Closing {Subject}: a change was announced for it and what it may do now could not be looked up", handle.Subject); + + // Never throws, and closing is not worth holding the other connections up for. + _ = RevokeAsync(handle, log: false); + continue; + } + var expired = handle.Grant is { } grant && grant.IsExpired(now); var maxAge = handle.Subject is LiveControlSubject ? liveControlInterval : interval; @@ -153,6 +171,7 @@ internal async Task CheckOnceAsync(ConnectionHandle handle) { // A transient failure must not drop a legitimate connection. It is checked again at the next sweep. _logger.LogWarning(e, "Error while checking what a {Subject} may do", subject); + handle.CheckFailed(changes); return RefreshResult.Failed; } finally diff --git a/Common/ConnectionAuthority/ConnectionHandle.cs b/Common/ConnectionAuthority/ConnectionHandle.cs index a89112e7..99e8e0a1 100644 --- a/Common/ConnectionAuthority/ConnectionHandle.cs +++ b/Common/ConnectionAuthority/ConnectionHandle.cs @@ -10,7 +10,10 @@ public enum RefreshResult /// The connection may not go on and was closed. Revoked, - /// The check itself failed (database or Redis trouble). The connection stays open and is checked again later. + /// + /// The check itself failed (database or Redis trouble). The connection stays open and is checked again later, + /// for as long as allows. + /// Failed } @@ -27,6 +30,11 @@ public enum RefreshResult /// connection look checked: until a later check succeeds it has no usable and is not /// fresh. /// +/// +/// That stops what the connection asks for, not what is pushed to it, which goes to whatever is open. So how long +/// a reason has gone unchecked while checks fail is kept too, for the registry to end the connection over, see +/// . +/// /// public sealed class ConnectionHandle : IDisposable { @@ -50,6 +58,12 @@ public sealed class ConnectionHandle : IDisposable // 0 means "never checked": Stopwatch timestamps are never 0 in practice. private long _lastChecked; + /// Since when there has been a reason no successful check covers. Only means something while there is one. + private long _uncheckedSince; + + /// Whether a check that had such a reason to cover has failed. + private bool _checkFailed; + internal ConnectionHandle(ConnectionAuthorityRegistry registry, ConnectionSubject subject, IAuthorizedConnection connection) { _registry = registry; @@ -87,7 +101,7 @@ public void UpdateSubject(ConnectionSubject subject) lock (_lock) { _subject = subject; - _changes++; + CountChange(); } } @@ -100,11 +114,14 @@ public bool WasCheckedWithin(TimeSpan maxAge) } } - /// Check again unless says the last check is still good. + /// + /// Check again unless says the last check is still good and what it granted + /// has not reached its expiry since. Nothing announces an expiry, so a recent check does not cover it. + /// public Task EnsureFreshAsync(TimeSpan maxAge) { if (_revoked) return Task.FromResult(RefreshResult.Revoked); - if (WasCheckedWithin(maxAge)) return Task.FromResult(RefreshResult.Valid); + if (WasCheckedWithin(maxAge) && Grant?.IsExpired(DateTime.UtcNow) != true) return Task.FromResult(RefreshResult.Valid); return RefreshAsync(); } @@ -139,7 +156,37 @@ internal void Invalidate() { lock (_lock) { - _changes++; + CountChange(); + } + } + + /// Call under the lock. + private void CountChange() + { + if (_changes == _checkedChanges) _uncheckedSince = Stopwatch.GetTimestamp(); + _changes++; + } + + /// + /// Whether a reason to check again has gone without a successful check for at least + /// and a check for it failed. Not while one is merely waiting its turn: only a check that was tried and could + /// not be made says that what the connection may do cannot be learned right now. + /// + internal bool HasBeenUncheckedFor(TimeSpan limit) + { + lock (_lock) + { + return !_revoked && _checkFailed && _changes != _checkedChanges && Stopwatch.GetElapsedTime(_uncheckedSince) >= limit; + } + } + + /// A check could not be made. + /// The changes the check would have covered, from . + internal void CheckFailed(long changes) + { + lock (_lock) + { + if (changes != _checkedChanges) _checkFailed = true; } } @@ -173,7 +220,11 @@ private async Task RunAsync() lock (_lock) { - if (_rerun && !_revoked) + // A check that found the connection good, but started before the last reason to check it, says + // nothing about that reason: whoever waits for this must not be told the connection is good. + var outdated = result == RefreshResult.Valid && _changes != _checkedChanges; + + if ((_rerun || outdated) && !_revoked) { _rerun = false; continue; @@ -205,6 +256,10 @@ internal bool Accept(Grant grant, long changes) _grant = grant; _checkedChanges = changes; _lastChecked = Stopwatch.GetTimestamp(); + + // What is still not covered came after this check started, so it has not waited longer than this. + _uncheckedSince = _lastChecked; + _checkFailed = false; } return true; diff --git a/Common/ConnectionAuthority/GrantResolver.cs b/Common/ConnectionAuthority/GrantResolver.cs index c9b06595..6c6a7294 100644 --- a/Common/ConnectionAuthority/GrantResolver.cs +++ b/Common/ConnectionAuthority/GrantResolver.cs @@ -125,10 +125,10 @@ public GrantResolver(OpenShockContext db, ISessionService sessionService) var active = await _db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, cancellationToken); if (!active) return null; - // Reaching its lifetime ends a session without anyone deleting it, so the grant ends with it. - return session.Expires?.UtcDateTime is { } expiresAt && expiresAt > DateTime.UtcNow - ? new Grant { ExpiresAt = expiresAt } - : Grant.Empty; + // Reaching its lifetime ends a session without anyone deleting it, so the grant ends with it. That can + // happen while the account was being looked up, and then there is nothing left to grant. + if (session.Expires?.UtcDateTime is not { } expiresAt) return Grant.Empty; + return expiresAt > DateTime.UtcNow ? new Grant { ExpiresAt = expiresAt } : null; } private static DateTime? Earliest(DateTime? a, DateTime? b) => a is null ? b : b is null ? a : a < b ? a : b; diff --git a/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs b/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs index 95d6835a..7d3b05f3 100644 --- a/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs +++ b/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs @@ -83,15 +83,22 @@ private LogEntry Read(StreamEntry entry) var payload = entry[ChangeField]; if (payload.IsNull) return new LogEntry(position, Change: null); + AuthorityChange? change; try { - return new LogEntry(position, MessagePackSerializer.Deserialize((ReadOnlyMemory)payload)); + change = MessagePackSerializer.Deserialize((ReadOnlyMemory)payload); } catch (Exception e) { _logger.LogError(e, "Failed to read the authority change at [{Position}]", position); return new LogEntry(position, Change: null, Unreadable: true); } + + if (change is not null) return new LogEntry(position, change); + + // A kind of change this version does not know, written by a newer one: it reads as nothing, not as an error. + _logger.LogWarning("The authority change at [{Position}] is of a kind this version does not know", position); + return new LogEntry(position, Change: null, Unreadable: true); } private static LogPosition Parse(RedisValue id) => diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 4294ca0c..2ac4cfd7 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -429,8 +429,8 @@ public static IServiceCollection AddOpenShockConnectionAuthority(this IServiceCo { services.AddOptions() .BindConfiguration(OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName) - .Validate(options => options.Interval > TimeSpan.Zero && options.LiveControlInterval > TimeSpan.Zero && options.CatchUpInterval > TimeSpan.Zero && options.CloseAfterLogUnreachable >= TimeSpan.Zero, - $"{OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName}: Interval, LiveControlInterval and CatchUpInterval must be greater than zero, and CloseAfterLogUnreachable not negative.") + .Validate(options => options.Interval > TimeSpan.Zero && options.LiveControlInterval > TimeSpan.Zero && options.CatchUpInterval > TimeSpan.Zero && options.CloseAfterLogUnreachable >= TimeSpan.Zero && options.CloseAfterChangeUnchecked >= TimeSpan.Zero, + $"{OpenShock.Common.ConnectionAuthority.ConnectionAuthorityOptions.SectionName}: Interval, LiveControlInterval and CatchUpInterval must be greater than zero, and CloseAfterLogUnreachable and CloseAfterChangeUnchecked not negative.") .ValidateOnStart(); services.AddSingleton(); services.AddScoped(); From c550f435e3f3b54f1c4e00bc27d1b09c010e949c Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 23:13:28 +0100 Subject: [PATCH 24/24] fix: address the third review of the connection authority - Closing every connection no longer waits for the closes, so a stalled one cannot keep the reader from the authority change log. - The announcer's retry and its shutdown attempt take turns at the queue, so neither removes a change the other has not logged. - A change announced during an older check keeps its own limit when that check succeeds. - The unchecked-change limit is decided and the connection revoked in one step, and a check that finishes on a revoked connection says revoked. - Tests: a manual clock instead of 50 ms limits, an ordered assertion for the log's order, and a default host whose periodic check cannot close a connection before an announcement does. The tests of the periodic check use a host that checks every second. --- ...entConnectionCheckWebApplicationFactory.cs | 11 ++ .../Tests/AuthorityChangeLogTests.cs | 3 +- .../Tests/PublicSharePasswordTests.cs | 34 ++-- .../Tests/SignalRUserHubTests.cs | 27 ++- API.IntegrationTests/WebApplicationFactory.cs | 12 +- .../AuthorityChangeAnnouncerTests.cs | 46 ++++- .../AuthorityChangeReaderTests.cs | 31 +++- .../ConnectionAuthorityRegistryTests.cs | 164 +++++++++++++++++- .../AuthorityChangeAnnouncer.cs | 41 +++-- .../AuthorityChangeReader.cs | 3 +- .../ConnectionAuthorityRegistry.cs | 31 +++- .../ConnectionAuthority/ConnectionHandle.cs | 62 +++++-- 12 files changed, 397 insertions(+), 68 deletions(-) create mode 100644 API.IntegrationTests/FrequentConnectionCheckWebApplicationFactory.cs diff --git a/API.IntegrationTests/FrequentConnectionCheckWebApplicationFactory.cs b/API.IntegrationTests/FrequentConnectionCheckWebApplicationFactory.cs new file mode 100644 index 00000000..9b5c85de --- /dev/null +++ b/API.IntegrationTests/FrequentConnectionCheckWebApplicationFactory.cs @@ -0,0 +1,11 @@ +namespace OpenShock.API.IntegrationTests; + +/// +/// Variant of whose host checks open connections every second, for the tests +/// of a change that was never announced: those would otherwise have to wait out the interval. It shares the +/// database and Redis with the other hosts, so only the connection under test has to be opened against it. +/// +public sealed class FrequentConnectionCheckWebApplicationFactory : WebApplicationFactory +{ + public override TimeSpan ConnectionCheckInterval => TimeSpan.FromSeconds(1); +} diff --git a/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs index be1df801..9b7eb1b7 100644 --- a/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs +++ b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using OpenShock.Common.ConnectionAuthority; using StackExchange.Redis; +using TUnit.Assertions.Enums; namespace OpenShock.API.IntegrationTests.Tests; @@ -33,7 +34,7 @@ public async Task ReadAfter_ReturnsWhatWasAppendedSince_InOrder_AndNothingFromBe .Where(entry => entry.Change == before || entry.Change == first || entry.Change == second) .ToArray(); - await Assert.That(mine.Select(entry => entry.Change!)).IsEquivalentTo(new[] { first, second }); + await Assert.That(mine.Select(entry => entry.Change!)).IsEquivalentTo(new[] { first, second }, CollectionOrdering.Matching); await Assert.That(mine[0].Position.CompareTo(mine[1].Position)).IsLessThan(0); await Assert.That(mine[0].Position.CompareTo(mark)).IsGreaterThan(0); } diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 0279d704..5f613b16 100644 --- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -23,6 +23,13 @@ public sealed class PublicSharePasswordTests [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } + /// + /// A host that checks connections often, for the test of the periodic check. It opens its connection against + /// this one; everything else can go through either, the hosts share the database and Redis. + /// + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required FrequentConnectionCheckWebApplicationFactory FrequentChecks { get; init; } + // --- Loading the share --- [Test] @@ -308,7 +315,7 @@ public async Task Hub_MovingTheExpiryCloser_ClosesOpenConnectionsWhenItIsReached TestHelper.JsonContent(new { name = "Ends soon", expiresOn = DateTime.UtcNow.AddSeconds(3), slug = (string?)null })); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - // The check interval is short in tests and would find it too, so the announcement is looked for itself. + // The connection closing below already takes the announcement; it is also looked for itself. var announced = (await log.ReadAfterAsync(before, 10_000)).Any(entry => entry.Change == AuthorityChange.PublicShare(shareId)); await Assert.That(announced).IsTrue(); @@ -350,7 +357,8 @@ public async Task Hub_RemovingThePassword_KeepsConnectionsOpen() await SetPassword(owner, shareId, null); - await Task.Delay(WebApplicationFactory.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); + // Long enough for the announced change to have reached the connection. + await Task.Delay(TimeSpan.FromMilliseconds(1500)); await connection.InvokeAsync("Control", Array.Empty()); await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); } @@ -374,9 +382,7 @@ 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); - // Checked once here, so the call below has to be a re-check. - await connection.InvokeAsync("Control", Array.Empty()); + await using var connection = await ConnectAsync(shareId, token, factory: FrequentChecks); await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) { @@ -386,7 +392,7 @@ await db.PublicShares.Where(x => x.Id == shareId) .ExecuteUpdateAsync(s => s.SetProperty(x => x.PasswordStamp, stamp)); } - await Task.Delay(WebApplicationFactory.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); + await Task.Delay(FrequentChecks.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); Exception? failure = null; try { @@ -519,14 +525,20 @@ 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) + /// + /// Connects, waits until the hub admitted the connection (it sends Welcome after its checks) and makes one + /// call on it. A public share connection is first checked at its first call or, failing that, at the next + /// sweep. With the call made here, a change that closes it afterwards did so by being announced, and not by + /// that first check happening to come late. + /// + private async Task ConnectAsync(Guid shareId, string? unlockToken, string? sessionToken = null, WebApplicationFactory? factory = null) { - var (connection, welcomed) = BuildConnection(shareId, unlockToken, sessionToken); + var (connection, welcomed) = BuildConnection(shareId, unlockToken, sessionToken, factory); try { await connection.StartAsync(); await welcomed.WaitAsync(TimeSpan.FromSeconds(30)); + await connection.InvokeAsync("Control", Array.Empty()); return connection; } catch @@ -536,9 +548,9 @@ private async Task ConnectAsync(Guid shareId, string? unlockToken } } - private (HubConnection Connection, Task Welcomed) BuildConnection(Guid shareId, string? unlockToken, string? sessionToken = null) + private (HubConnection Connection, Task Welcomed) BuildConnection(Guid shareId, string? unlockToken, string? sessionToken = null, WebApplicationFactory? factory = null) { - var server = WebApplicationFactory.Server; + var server = (factory ?? WebApplicationFactory).Server; var path = $"/1/hubs/share/link/{shareId}?name=Guest"; if (unlockToken is not null) path += $"&unlockToken={Uri.EscapeDataString(unlockToken)}"; diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index 7293f02b..a5c8558c 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -23,6 +23,13 @@ public sealed class SignalRUserHubTests [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } + /// + /// A host that checks connections often, for the tests of the periodic check. They open their connection + /// against this one; everything else can go through either, the hosts share the database and Redis. + /// + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required FrequentConnectionCheckWebApplicationFactory FrequentChecks { get; init; } + // --- Negotiate: credentials the user hub does not accept --- [Test] @@ -167,10 +174,10 @@ public async Task PublicShareHub_Guest_CanConnectAndKeepCalling() 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 using var connection = await ConnectAsync(FrequentChecks, null, null, $"/1/hubs/share/link/{shareId}?name=Guest"); await connection.InvokeAsync("Control", Array.Empty()); - await Task.Delay(WebApplicationFactory.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); + await Task.Delay(FrequentChecks.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500)); await connection.InvokeAsync("Control", Array.Empty()); await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); @@ -182,7 +189,7 @@ public async Task PublicShareHub_Guest_CanConnectAndKeepCalling() public async Task Idle_AfterSessionRemovedWithoutAnnouncement_ClosesConnection() { var user = await CreateUser("hubrevalsess"); - await using var connection = await ConnectCheckedSessionAsync(user); + await using var connection = await ConnectCheckedSessionAsync(FrequentChecks, user); // Removed straight from Redis: no revocation message, and a deleted key raises no expiry event. var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); @@ -196,7 +203,7 @@ public async Task Idle_AfterAccountDeactivated_WithTheSessionLeftBehind_ClosesCo { // Deactivation removes sessions after its database commit; if that step fails the session survives. var user = await CreateUser("hubrevaldeact"); - await using var connection = await ConnectCheckedSessionAsync(user); + await using var connection = await ConnectCheckedSessionAsync(FrequentChecks, user); await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) { @@ -230,7 +237,7 @@ public async Task Idle_AfterApiTokenChangedWithoutAnnouncement_ClosesConnection( { var user = await CreateUser("hubrevaltok"); var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await using var connection = await ConnectAsync(FrequentChecks, AuthConstants.ApiTokenHeaderName, rawToken); await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); // Written straight to the database, so no revocation message is published. @@ -271,9 +278,9 @@ private Task CreateUser(string prefix) => TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), "SecurePassword123#"); /// Opens a session connection and makes one call on it, so it has been checked once. - private async Task ConnectCheckedSessionAsync(AuthenticatedUser user) + private static async Task ConnectCheckedSessionAsync(WebApplicationFactory factory, AuthenticatedUser user) { - var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + var connection = await ConnectAsync(factory, "Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); return connection; } @@ -322,7 +329,11 @@ private static async Task AssertIdleConnectionClosesAsync(HubConnection connecti await Assert.That(async () => await connection.InvokeAsync("Reboot", Guid.CreateVersion7())).ThrowsException(); } - /// Waits for the server to close the connection, without calling anything on it. + /// + /// Waits for the server to close the connection, without calling anything on it. On the default host only + /// an announced change or a session's expiry event can do that in this time, see + /// . + /// private static async Task AssertConnectionClosesAsync(HubConnection connection) { var deadline = DateTime.UtcNow.AddSeconds(30); diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index a358d45d..66a0a7d3 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -27,8 +27,13 @@ public class WebApplicationFactory : WebApplicationFactory [ClassDataSource(Shared = SharedType.PerTestSession)] public required RedisFixture Redis { get; init; } - /// How long an open connection can go on after a change to its authority that was never announced, in tests. - public static readonly TimeSpan ConnectionCheckInterval = TimeSpan.FromSeconds(1); + /// + /// How long an open connection can go on after a change to its authority that was never announced. Far longer + /// than any test waits for a connection to close, so a test that expects an announced change to close one + /// cannot pass on the periodic check instead. The tests of that check itself use + /// . + /// + public virtual TimeSpan ConnectionCheckInterval => TimeSpan.FromMinutes(15); protected override void ConfigureClient(HttpClient client) { @@ -111,8 +116,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) services.RemoveAll(); services.AddSingleton(); - // 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. + // How often a hub connection is checked without a reason to, see ConnectionCheckInterval. services.Configure(options => { options.Interval = ConnectionCheckInterval; diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs index 33ddae8b..88656e5e 100644 --- a/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs +++ b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs @@ -19,11 +19,14 @@ public AuthorityChange[] Appended } } - public Task AppendAsync(AuthorityChange change) + /// Runs after a change is in the log and before whoever appended it hears so. + public Func? AfterAppend { get; set; } + + public async Task AppendAsync(AuthorityChange change) { if (Unreachable) throw new InvalidOperationException("redis is down"); lock (_appended) _appended.Add(change); - return Task.CompletedTask; + if (AfterAppend is { } afterAppend) await afterAppend(); } public Task MarkAsync() => throw new NotSupportedException(); @@ -109,6 +112,45 @@ public async Task Dispose_TriesWhatIsStillWaitingOnceMore() await Assert.That(log.Appended).IsEquivalentTo(new[] { change }); } + /// + /// Shutdown and the retry both take from what is waiting. If they did so at the same time, one would remove + /// a change the other had not logged yet, and that change would never be. + /// + [Test] + public async Task Dispose_WhileTheRetryIsLogging_LogsEveryWaitingChangeOnce() + { + var log = new FlakyLog { Unreachable = true }; + var announcer = Create(log); + var first = AuthorityChange.User(Guid.NewGuid()); + var second = AuthorityChange.ApiToken(Guid.NewGuid()); + await announcer.AnnounceAsync(first); + await announcer.AnnounceAsync(second); + + // The retry gets the first change into the log and is held before it takes it off the queue. + var retryAppended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseRetry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var held = 0; + log.AfterAppend = async () => + { + if (Interlocked.Exchange(ref held, 1) != 0) return; + + retryAppended.SetResult(); + await releaseRetry.Task; + }; + log.Unreachable = false; + await retryAppended.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + var disposing = announcer.DisposeAsync().AsTask(); + await Task.Delay(50); + await Assert.That(disposing.IsCompleted).IsFalse(); + + releaseRetry.SetResult(); + await disposing.WaitAsync(TimeSpan.FromSeconds(10)); + await Until(() => announcer.Waiting == 0); + + await Assert.That(log.Appended).IsEquivalentTo(new[] { first, second }, TUnit.Assertions.Enums.CollectionOrdering.Matching); + } + [Test] public async Task Dispose_LogStillUnreachable_DoesNotThrow() { diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs index f51bd1ed..a006055c 100644 --- a/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs +++ b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs @@ -81,10 +81,13 @@ private sealed class FakeConnection : IAuthorizedConnection { public int Closed; + /// When closing is done. Replace for a connection whose other end takes its time. + public Task Closing { get; init; } = Task.CompletedTask; + public Task CloseAsync() { Interlocked.Increment(ref Closed); - return Task.CompletedTask; + return Closing; } } @@ -203,6 +206,32 @@ public async Task CatchUp_LogUnreachableForTooLong_ClosesEveryConnection() await Assert.That(later.IsRevoked).IsTrue(); } + /// + /// A connection whose other end stopped reading can take forever to close. Reading the log must not wait for + /// it, or the connections that came since would never hear of a change again. + /// + [Test] + public async Task CatchUp_LogUnreachableForTooLong_DoesNotWaitForAConnectionToClose() + { + var setup = await Create(closeAfterLogUnreachable: TimeSpan.Zero); + var neverClosed = new TaskCompletionSource(); + var stalled = new FakeConnection { Closing = neverClosed.Task }; + var (handle, _) = await setup.Registry.RegisterAsync(new SignalRSubject(new ApiTokenCredential(Guid.NewGuid(), Guid.NewGuid())), stalled); + setup.Log.Unreachable = true; + + await Assert.That(async () => await setup.Reader.CatchUpAsync().WaitAsync(TimeSpan.FromSeconds(10))).Throws(); + + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(stalled.Closed).IsEqualTo(1); + + // And reading carries on once the log is back. + setup.Log.Unreachable = false; + var tokenId = Guid.NewGuid(); + var later = await setup.Connect(tokenId); + await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId)); + await Assert.That(await setup.CatchUp(later)).IsEqualTo(1); + } + [Test] public async Task CatchUp_LogBackInTime_ClosesNothing_AndTheWaitStartsOver() { diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs index 4d0b49da..0f18bfef 100644 --- a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -26,6 +26,9 @@ private sealed class FakeConnection : IAuthorizedConnection public int Closed; public Grant? LastApplied; + /// When closing is done. Replace for a connection whose other end takes its time. + public Task Closing { get; set; } = Task.CompletedTask; + public bool TryApplyGrant(Grant grant) { LastApplied = grant; @@ -35,11 +38,23 @@ public bool TryApplyGrant(Grant grant) public Task CloseAsync() { Interlocked.Increment(ref Closed); - return Task.CompletedTask; + return Closing; } } - private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Create(TimeSpan? interval = null, TimeSpan? liveControlInterval = null, TimeSpan? closeAfterChangeUnchecked = null) + /// Elapsed time that only passes when a test says so. + private sealed class ManualTime : TimeProvider + { + private long _timestamp = TimeSpan.TicksPerHour; + + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + + public override long GetTimestamp() => Interlocked.Read(ref _timestamp); + + public void Advance(TimeSpan by) => Interlocked.Add(ref _timestamp, by.Ticks); + } + + private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Create(TimeSpan? interval = null, TimeSpan? liveControlInterval = null, TimeSpan? closeAfterChangeUnchecked = null, TimeProvider? time = null) { var resolver = new FakeResolver(); var services = new ServiceCollection(); @@ -52,7 +67,10 @@ private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Cre LiveControlInterval = liveControlInterval ?? interval ?? TimeSpan.FromMinutes(1), CloseAfterChangeUnchecked = closeAfterChangeUnchecked ?? TimeSpan.FromHours(1) }); - var registry = new ConnectionAuthorityRegistry(provider.GetRequiredService(), options, NullLogger.Instance); + var registry = new ConnectionAuthorityRegistry(provider.GetRequiredService(), options, NullLogger.Instance) + { + Time = time ?? TimeProvider.System + }; return (registry, resolver); } @@ -419,7 +437,8 @@ public async Task Signal_CheckFails_ThenSucceeds_GrantsAgain() [Test] public async Task Sweep_ChangeStillUncheckedAfterTheLimit_Closes() { - var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromMilliseconds(50)); + var time = new ManualTime(); + var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromSeconds(15), time: time); var tokenId = Guid.NewGuid(); var connection = new FakeConnection(); var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection); @@ -431,13 +450,14 @@ public async Task Sweep_ChangeStillUncheckedAfterTheLimit_Closes() await Settle(handle); // Within the limit it stays, and is checked again. + time.Advance(TimeSpan.FromSeconds(14)); var callsBefore = resolver.Calls; registry.Sweep(DateTime.UtcNow); await Settle(handle); await Assert.That(resolver.Calls).IsEqualTo(callsBefore + 1); await Assert.That(connection.Closed).IsEqualTo(0); - await Task.Delay(100); + time.Advance(TimeSpan.FromSeconds(1)); registry.Sweep(DateTime.UtcNow); await Assert.That(handle.IsRevoked).IsTrue(); @@ -449,7 +469,8 @@ public async Task Sweep_ChangeStillUncheckedAfterTheLimit_Closes() [Test] public async Task Sweep_ChangeCheckedWithinTheLimit_Stays() { - var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromMilliseconds(50)); + var time = new ManualTime(); + var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromSeconds(15), time: time); var tokenId = Guid.NewGuid(); var connection = new FakeConnection(); var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection); @@ -458,17 +479,98 @@ public async Task Sweep_ChangeCheckedWithinTheLimit_Stays() registry.Signal(AuthorityChange.ApiToken(tokenId)); await Settle(handle); + time.Advance(TimeSpan.FromSeconds(14)); resolver.Resolve = _ => Task.FromResult(Grant.Empty); registry.Sweep(DateTime.UtcNow); await Settle(handle); - await Task.Delay(100); + time.Advance(TimeSpan.FromMinutes(1)); registry.Sweep(DateTime.UtcNow); await Assert.That(connection.Closed).IsEqualTo(0); await Assert.That(handle.Grant).IsNotNull(); } + /// + /// The limit is acted on as things are when the connection would be closed. A check that got through after + /// the limit, but before the sweep came by, has settled the change. + /// + [Test] + public async Task Sweep_ChangeCheckedAfterTheLimitButBeforeTheSweep_Stays() + { + var time = new ManualTime(); + var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromSeconds(15), time: time); + var tokenId = Guid.NewGuid(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection); + + resolver.Resolve = _ => throw new InvalidOperationException("database is down"); + registry.Signal(AuthorityChange.ApiToken(tokenId)); + await Settle(handle); + + time.Advance(TimeSpan.FromSeconds(20)); + resolver.Resolve = _ => Task.FromResult(Grant.Empty); + await Assert.That(await handle.RefreshAsync()).IsEqualTo(RefreshResult.Valid); + + registry.Sweep(DateTime.UtcNow); + + await Assert.That(handle.IsRevoked).IsFalse(); + await Assert.That(connection.Closed).IsEqualTo(0); + await Assert.That(registry.Count).IsEqualTo(1); + } + + /// + /// A change announced while an older check runs is not covered by it. When that check succeeds, the newer + /// change has still waited since it was announced, not since the check finished. + /// + [Test] + public async Task Sweep_ChangeAnnouncedDuringACheckThatSucceeds_KeepsItsOwnLimit() + { + var time = new ManualTime(); + var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromSeconds(15), time: time); + var tokenId = Guid.NewGuid(); + var connection = new FakeConnection(); + var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection); + + // The check of the first change takes a while and then succeeds. Every check after it fails. + var firstCheckStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseFirstCheck = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var checks = 0; + resolver.Resolve = async _ => + { + if (Interlocked.Increment(ref checks) > 1) throw new InvalidOperationException("database is down"); + + firstCheckStarted.SetResult(); + await releaseFirstCheck.Task; + return Grant.Empty; + }; + + registry.Signal(AuthorityChange.ApiToken(tokenId)); + await firstCheckStarted.Task; + + // The second change, 5 seconds in. The first check finishes at 14 seconds, and the one for the second + // change that follows it fails. + time.Advance(TimeSpan.FromSeconds(5)); + registry.Signal(AuthorityChange.ApiToken(tokenId)); + time.Advance(TimeSpan.FromSeconds(9)); + releaseFirstCheck.SetResult(); + await Settle(handle); + await Assert.That(handle.Grant).IsNull(); + + // At 19 seconds the second change has gone unchecked for 14. + time.Advance(TimeSpan.FromSeconds(5)); + registry.Sweep(DateTime.UtcNow); + await Settle(handle); + await Assert.That(connection.Closed).IsEqualTo(0); + + // At 20 seconds for 15, though the first check succeeded only 6 seconds ago. + time.Advance(TimeSpan.FromSeconds(1)); + registry.Sweep(DateTime.UtcNow); + + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(connection.Closed).IsEqualTo(1); + } + /// An outage alone drops nobody: without a change announced for it, a connection keeps what it had. [Test] public async Task Sweep_CheckFailsWithNoChangeAnnounced_NeverCloses() @@ -638,6 +740,54 @@ public async Task SignalAll_DuringARunningCheck_ChecksAgain() await Assert.That(connection.Closed).IsEqualTo(1); } + [Test] + public async Task CloseAll_RevokesEveryConnection_WithoutWaitingForThemToClose() + { + var (registry, _) = Create(); + var neverClosed = new TaskCompletionSource(); + var stalled = new FakeConnection { Closing = neverClosed.Task }; + var other = new FakeConnection(); + var (stalledHandle, _) = await registry.RegisterAsync(SignalR(), stalled); + var (otherHandle, _) = await registry.RegisterAsync(LiveControl(), other); + + registry.CloseAll(); + + await Assert.That(stalledHandle.IsRevoked).IsTrue(); + await Assert.That(otherHandle.IsRevoked).IsTrue(); + await Assert.That(stalled.Closed).IsEqualTo(1); + await Assert.That(other.Closed).IsEqualTo(1); + await Assert.That(registry.Count).IsEqualTo(0); + } + + /// A check that finds the connection good does not undo a close that happened while it ran. + [Test] + public async Task Register_ClosedWhileTheFirstCheckRuns_IsRevoked() + { + var (registry, resolver) = Create(); + var checkStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseCheck = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + resolver.Resolve = async _ => + { + checkStarted.SetResult(); + await releaseCheck.Task; + return Grant.Empty; + }; + var connection = new FakeConnection(); + + var registering = registry.RegisterAsync(LiveControl(), connection); + await checkStarted.Task; + + registry.CloseAll(); + releaseCheck.SetResult(); + var (handle, result) = await registering; + + await Assert.That(result).IsEqualTo(RefreshResult.Revoked); + await Assert.That(handle.IsRevoked).IsTrue(); + await Assert.That(handle.Grant).IsNull(); + await Assert.That(connection.Closed).IsEqualTo(1); + await Assert.That(registry.Count).IsEqualTo(0); + } + [Test] public async Task Dispose_StopsTrackingWithoutClosing() { diff --git a/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs index a9148da4..4c734b5f 100644 --- a/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs +++ b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs @@ -27,6 +27,12 @@ public sealed class AuthorityChangeAnnouncer : IAsyncDisposable private readonly ConcurrentQueue _waiting = new(); private int _retrying; + /// + /// Held by whoever takes changes out of . Anyone may add to it at any time, but with + /// two taking from it at once, one would remove a change the other had not logged yet. + /// + private readonly SemaphoreSlim _logging = new(1, 1); + public AuthorityChangeAnnouncer(IAuthorityChangeLog log, ILogger logger) { _log = log; @@ -72,11 +78,7 @@ private async Task RetryAsync() try { - while (_waiting.TryPeek(out var change)) - { - await _log.AppendAsync(change); - _waiting.TryDequeue(out _); - } + await LogWaitingAsync(); } catch (Exception e) { @@ -91,21 +93,40 @@ private async Task RetryAsync() } /// - /// A last attempt at what is still waiting, when the service shuts down. A change may be logged twice if the - /// retry is running too, which does no harm. + /// Logs what is waiting, oldest first, until nothing is or one cannot be. A change leaves the queue only + /// after it was logged, so one that could not be is still there for the next attempt. /// - public async ValueTask DisposeAsync() + private async Task LogWaitingAsync() { + await _logging.WaitAsync(); try { - while (_waiting.TryDequeue(out var change)) + // Only the holder removes, and additions go to the other end, so what is removed is what was logged. + while (_waiting.TryPeek(out var change)) { await _log.AppendAsync(change); + _waiting.TryDequeue(out _); } } + finally + { + _logging.Release(); + } + } + + /// + /// A last attempt at what is still waiting, when the service shuts down. Waits for the retry if that is in + /// the middle of an attempt, and then tries whatever it left. + /// + public async ValueTask DisposeAsync() + { + try + { + await LogWaitingAsync(); + } catch (Exception e) { - _logger.LogWarning(e, "Shutting down with {Count} change(s) in authority that could not be announced; open connections find out at their next periodic check", _waiting.Count + 1); + _logger.LogWarning(e, "Shutting down with {Count} change(s) in authority that could not be announced; open connections find out at their next periodic check", _waiting.Count); } } } diff --git a/Common/ConnectionAuthority/AuthorityChangeReader.cs b/Common/ConnectionAuthority/AuthorityChangeReader.cs index bca2dc9c..cad37c13 100644 --- a/Common/ConnectionAuthority/AuthorityChangeReader.cs +++ b/Common/ConnectionAuthority/AuthorityChangeReader.cs @@ -58,7 +58,8 @@ public async Task CatchUpAsync() if (Stopwatch.GetElapsedTime(_unreachableSince.Value) >= _registry.CloseAfterLogUnreachable) { - await _registry.CloseAllAsync(); + // Does not wait for the connections to be gone: reading must go on whatever they do. + _registry.CloseAll(); } throw; diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs index d3b43db8..5e0574ad 100644 --- a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -52,6 +52,9 @@ public ConnectionAuthorityRegistry(IServiceScopeFactory scopeFactory, IOptionsWhat elapsed time is measured with. Only replaced in tests. + internal TimeProvider Time { get; init; } = TimeProvider.System; + /// How long a successful check stays good before time alone is a reason to check again. public TimeSpan Interval => _options.Value.Interval; @@ -61,7 +64,7 @@ public ConnectionAuthorityRegistry(IServiceScopeFactory scopeFactory, IOptionsHow often the log of announced changes is read without being told to, see . public TimeSpan CatchUpInterval => _options.Value.CatchUpInterval; - /// How long the log of announced changes may be out of reach before . + /// How long the log of announced changes may be out of reach before . public TimeSpan CloseAfterLogUnreachable => _options.Value.CloseAfterLogUnreachable; /// How long a change announced for a connection may go unchecked, while checking fails, before the connection is closed. @@ -135,12 +138,12 @@ public void Sweep(DateTime now) var closeAfterChangeUnchecked = CloseAfterChangeUnchecked; foreach (var handle in _handles.Keys) { - if (handle.HasBeenUncheckedFor(closeAfterChangeUnchecked)) + if (handle.MarkRevokedIfUncheckedFor(closeAfterChangeUnchecked)) { _logger.LogWarning("Closing {Subject}: a change was announced for it and what it may do now could not be looked up", handle.Subject); // Never throws, and closing is not worth holding the other connections up for. - _ = RevokeAsync(handle, log: false); + _ = CloseRevokedAsync(handle); continue; } @@ -189,23 +192,35 @@ internal async Task CheckOnceAsync(ConnectionHandle handle) /// Close every connection, whatever it may do: this instance can no longer learn of a change to it. Not a /// verdict on any of them; a client that connects again is checked as usual. /// - public async Task CloseAllAsync() + /// + /// Returns once every connection is revoked and its close has started, without waiting for the closes: one + /// can take as long as the other end likes, and the caller has a log to get back to reading. + /// + public void CloseAll() { var handles = _handles.Keys.ToArray(); if (handles.Length == 0) return; _logger.LogWarning("Closing all {Count} open connection(s): changes in authority can no longer be learned of", handles.Length); - await Task.WhenAll(handles.Select(handle => RevokeAsync(handle, log: false))); + // Never throws. + foreach (var handle in handles) _ = RevokeAsync(handle, log: false); } - private async Task RevokeAsync(ConnectionHandle handle, bool log = true) + private Task RevokeAsync(ConnectionHandle handle, bool log = true) { - if (!handle.MarkRevoked()) return; - Remove(handle); + if (!handle.MarkRevoked()) return Task.CompletedTask; if (log) _logger.LogInformation("Closing {Subject}: it may no longer go on", handle.Subject); + return CloseRevokedAsync(handle); + } + + /// For the one caller that revoked the handle. Never throws. + private async Task CloseRevokedAsync(ConnectionHandle handle) + { + Remove(handle); + try { await handle.CloseConnectionAsync(); diff --git a/Common/ConnectionAuthority/ConnectionHandle.cs b/Common/ConnectionAuthority/ConnectionHandle.cs index 99e8e0a1..257ff63c 100644 --- a/Common/ConnectionAuthority/ConnectionHandle.cs +++ b/Common/ConnectionAuthority/ConnectionHandle.cs @@ -1,5 +1,3 @@ -using System.Diagnostics; - namespace OpenShock.Common.ConnectionAuthority; public enum RefreshResult @@ -55,12 +53,23 @@ public sealed class ConnectionHandle : IDisposable /// as it was when the last successful check started. private long _checkedChanges; - // 0 means "never checked": Stopwatch timestamps are never 0 in practice. + /// as it was when the last check started, whether or not it succeeded. + private long _startedChanges; + + // 0 means "never checked": timestamps are never 0 in practice. private long _lastChecked; - /// Since when there has been a reason no successful check covers. Only means something while there is one. + /// + /// When the oldest reason no successful check covers was counted. Only means something while there is one. + /// private long _uncheckedSince; + /// + /// When the first reason since the last check started was counted: the oldest one that check cannot cover. + /// Only means something while there is one. + /// + private long _changedSinceStart; + /// Whether a check that had such a reason to cover has failed. private bool _checkFailed; @@ -73,6 +82,8 @@ internal ConnectionHandle(ConnectionAuthorityRegistry registry, ConnectionSubjec public ConnectionSubject Subject => _subject; + private TimeProvider Time => _registry.Time; + /// /// What the connection may do, as of the last successful check. Null until the first one, once the connection /// is revoked, and while a change announced since has not been checked successfully: what was allowed before @@ -110,7 +121,7 @@ public bool WasCheckedWithin(TimeSpan maxAge) { lock (_lock) { - return _lastChecked != 0 && _changes == _checkedChanges && Stopwatch.GetElapsedTime(_lastChecked) < maxAge; + return _lastChecked != 0 && _changes == _checkedChanges && Time.GetElapsedTime(_lastChecked) < maxAge; } } @@ -163,20 +174,31 @@ internal void Invalidate() /// Call under the lock. private void CountChange() { - if (_changes == _checkedChanges) _uncheckedSince = Stopwatch.GetTimestamp(); + var now = Time.GetTimestamp(); + if (_changes == _checkedChanges) _uncheckedSince = now; + if (_changes == _startedChanges) _changedSinceStart = now; _changes++; } /// - /// Whether a reason to check again has gone without a successful check for at least - /// and a check for it failed. Not while one is merely waiting its turn: only a check that was tried and could - /// not be made says that what the connection may do cannot be learned right now. + /// Revoke the connection if a reason to check again has gone without a successful check for at least + /// and a check for it failed. Not while one is merely waiting its turn: only a check + /// that was tried and could not be made says that what the connection may do cannot be learned right now. + /// + /// Decided and marked in one step, so a check that succeeds a moment later finds the connection revoked + /// instead of having it closed after it was found good. + /// /// - internal bool HasBeenUncheckedFor(TimeSpan limit) + /// True for the one caller that has to close the connection. + internal bool MarkRevokedIfUncheckedFor(TimeSpan limit) { lock (_lock) { - return !_revoked && _checkFailed && _changes != _checkedChanges && Stopwatch.GetElapsedTime(_uncheckedSince) >= limit; + if (_revoked || !_checkFailed || _changes == _checkedChanges) return false; + if (Time.GetElapsedTime(_uncheckedSince) < limit) return false; + + _revoked = true; + return true; } } @@ -220,11 +242,19 @@ private async Task RunAsync() lock (_lock) { + // Revoked while the check ran, by the registry for a reason of its own. That stands whatever the + // check found: nobody is told that a closed connection is good. + if (_revoked) + { + _running = null; + return RefreshResult.Revoked; + } + // A check that found the connection good, but started before the last reason to check it, says // nothing about that reason: whoever waits for this must not be told the connection is good. var outdated = result == RefreshResult.Valid && _changes != _checkedChanges; - if ((_rerun || outdated) && !_revoked) + if (_rerun || outdated) { _rerun = false; continue; @@ -241,6 +271,7 @@ private async Task RunAsync() { lock (_lock) { + _startedChanges = _changes; return (_subject, _changes); } } @@ -255,10 +286,11 @@ internal bool Accept(Grant grant, long changes) { _grant = grant; _checkedChanges = changes; - _lastChecked = Stopwatch.GetTimestamp(); + _lastChecked = Time.GetTimestamp(); - // What is still not covered came after this check started, so it has not waited longer than this. - _uncheckedSince = _lastChecked; + // What is still not covered was counted after this check started. It has waited since then, not since + // now, and no check has been tried for it yet. + if (_changes != changes) _uncheckedSince = _changedSinceStart; _checkFailed = false; }