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