From 060f4a091aa8f77c2ef81b824a8060d61d0aaa7d Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 5 Dec 2026 11:36:20 +0100 Subject: [PATCH 01/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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;