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.IntegrationTests/Tests/GrantResolverTests.cs b/API.IntegrationTests/Tests/GrantResolverTests.cs new file mode 100644 index 00000000..3371b415 --- /dev/null +++ b/API.IntegrationTests/Tests/GrantResolverTests.cs @@ -0,0 +1,374 @@ +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, + 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/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs index 29f836b8..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 { @@ -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/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index 5290f7a2..ae066f3a 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; @@ -169,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); @@ -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 @@ -314,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 54f64e3a..ed23dd13 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; @@ -26,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) { @@ -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 = ConnectionCheckInterval); }); } } diff --git a/API/Controller/Devices/DevicesController.cs b/API/Controller/Devices/DevicesController.cs index ed609d9d..46e088b8 100644 --- a/API/Controller/Devices/DevicesController.cs +++ b/API/Controller/Devices/DevicesController.cs @@ -7,12 +7,14 @@ 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; 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 +106,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 +116,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 +126,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.SendAuthorityChanged(AuthorityChange.Device(device.Id)); + return Ok(device.Token); } 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/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/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 66a93356..34abf56b 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; @@ -54,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 NotifyUserAuthRevokedAsync(Guid userId) - { - try - { - await _redisPubService.SendUserAuthRevoked(userId); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to announce revoked access for user ID: [{Id}]; open connections close on their next check", userId); - } - } - private async Task IsPrivilegedAsync(Guid userId, CancellationToken cancellationToken) { // Queries over the role_type[] column cannot be translated, so the roles are checked here. @@ -129,13 +113,11 @@ await _auditService.LogAsync( await transaction.CommitAsync(); } - await NotifyUserAuthRevokedAsync(userId); + await _redisPubService.SendAuthorityChanged(AuthorityChange.User(userId)); // Remove all login sessions await _sessionService.DeleteSessionsByUserIdAsync(userId); - await RefreshOwnedDevicesAsync(userId, cancellationToken); - return new Success(); } @@ -174,8 +156,6 @@ await _auditService.LogAsync( await transaction.CommitAsync(); - await RefreshOwnedDevicesAsync(userId, cancellationToken); - return new Success(); } @@ -183,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) { @@ -219,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/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 new file mode 100644 index 00000000..8ba3b1af --- /dev/null +++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs @@ -0,0 +1,337 @@ +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 Signal_Session_ReachesTheConnectionsOfThatSession() + { + var (registry, resolver) = Create(); + var connection = new FakeConnection(); + var subject = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = Guid.NewGuid(), SessionToken = "session-a" }; + var (handle, _) = await registry.RegisterAsync(subject, connection); + + resolver.Resolve = _ => Task.FromResult(null); + registry.Signal(AuthorityChange.Session("session-b")); + await Settle(handle); + await Assert.That(handle.IsRevoked).IsFalse(); + + registry.Signal(AuthorityChange.Session("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); + } + + /// 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() + { + 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..5190fb39 --- /dev/null +++ b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs @@ -0,0 +1,100 @@ +using MessagePack; +using OpenShock.Common.ConnectionAuthority; +using OpenShock.Common.Constants; +using OpenShock.Common.Redis.PubSub; + +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 SessionChange_AffectsOnlyConnectionsOfThatSession() + { + var session = new ConnectionSubject { Kind = ConnectionKind.SignalR, UserId = User, SessionToken = new string('t', AuthConstants.GeneratedTokenLength) }; + var storedId = SessionIds.FromToken(session.SessionToken!); + + // A session is stored under the hash of its token, and that is what a change names. + await Assert.That(storedId).IsNotEqualTo(session.SessionToken); + await Assert.That(session.SessionId).IsEqualTo(storedId); + await Assert.That(session.IsAffectedBy(AuthorityChange.Session(storedId))).IsTrue(); + await Assert.That(session.IsAffectedBy(AuthorityChange.Session("another-id"))).IsFalse(); + + // A token connection has no session, and a session change carries no id that could match anything else. + await Assert.That(Subject.IsAffectedBy(AuthorityChange.Session(storedId))).IsFalse(); + await Assert.That(new ConnectionSubject { Kind = ConnectionKind.SignalR }.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.Session, Guid.Empty))).IsFalse(); + } + + [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() + { + var guest = new ConnectionSubject { Kind = ConnectionKind.SignalR }; + + await Assert.That(guest.IsAffectedBy(new AuthorityChange(AuthorityChangeKind.User, Guid.Empty))).IsFalse(); + } +} 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/ConnectionAuthority/AuthorityChangeSubscriber.cs b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs new file mode 100644 index 00000000..af6b0a3a --- /dev/null +++ b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs @@ -0,0 +1,87 @@ +using MessagePack; +using OpenShock.Common.Redis; +using OpenShock.Common.Redis.PubSub; +using OpenShock.Common.Services.RedisPubSub; +using StackExchange.Redis; + +namespace OpenShock.Common.ConnectionAuthority; + +/// +/// Turns what Redis says about changes in someone's authority into signals for the +/// . The same in every service that holds long-lived connections. +/// +/// +/// 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. +/// +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; + } + + 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); + } + + private void HandleAuthorityChanged(RedisChannel _, RedisValue message) + { + if (!message.HasValue) 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(change.ToChange()); + } + + 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.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(); + } +} diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs new file mode 100644 index 00000000..16848376 --- /dev/null +++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs @@ -0,0 +1,178 @@ +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 , or the chance that one was missed, 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. +/// A change is matched against every connection, which is fine for how rarely authority changes. +/// +public sealed class ConnectionAuthorityRegistry +{ + private readonly ConcurrentDictionary _handles = new(); + /// + /// How many connections may be looked at at once. Connections that opened together come due together, and a + /// 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) + { + foreach (var handle in _handles.Keys) + { + if (handle.Subject.IsAffectedBy(change)) handle.RequestRefresh(); + } + } + + /// + /// Changes may have been announced while this instance could not hear them (its Redis connection was down), so + /// no connection's last look can be trusted. Connections that are checked periodically look again now; hub + /// connections look again on their next call, as they would once their interval had passed. + /// + public void SignalAll() + { + foreach (var handle in _handles.Keys) + { + handle.Invalidate(); + if (handle.Subject.Kind != ConnectionKind.SignalR) handle.RequestRefreshIfIdle(); + } + } + + /// + /// 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..062d3ee5 --- /dev/null +++ b/Common/ConnectionAuthority/ConnectionHandle.cs @@ -0,0 +1,172 @@ +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); + } + + /// 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); + 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..1cb2f6da --- /dev/null +++ b/Common/ConnectionAuthority/ConnectionSubject.cs @@ -0,0 +1,108 @@ +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 + { + 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; } + + /// 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.Session => SessionId is not null && SessionId == change.SessionId, + AuthorityChangeKind.User => UserId == change.Id || DeviceOwnerId == change.Id || PublicShareOwnerId == change.Id, + AuthorityChangeKind.ApiToken => ApiTokenId == change.Id, + AuthorityChangeKind.Device => DeviceId == change.Id, + AuthorityChangeKind.PublicShare => PublicShareId == change.Id, + _ => false + }; +} + +/// The values travel over Redis between services, see . +public enum AuthorityChangeKind : byte +{ + /// An account was deactivated, deleted or otherwise may no longer be used. + User = 0, + + /// A login session was deleted or expired. Identified by . + Session = 1, + + /// An API token was edited, paused or deleted. + ApiToken = 2, + + /// A hub was deleted or got a new token, or its shockers or the shares on them changed. + Device = 3, + + /// Who may use a public share changed. + PublicShare = 4 +} + +/// +/// Something a connection's authority can depend on has changed. Carries no detail on purpose: the affected +/// connections look up what they may do now, so a change cannot be applied out of order or half-described. +/// +public readonly record struct AuthorityChange(AuthorityChangeKind Kind, Guid Id, string? SessionId = null) +{ + public static AuthorityChange User(Guid userId) => new(AuthorityChangeKind.User, userId); + public static AuthorityChange ApiToken(Guid tokenId) => new(AuthorityChangeKind.ApiToken, tokenId); + public static AuthorityChange Device(Guid deviceId) => new(AuthorityChangeKind.Device, deviceId); + public static AuthorityChange PublicShare(Guid publicShareId) => new(AuthorityChangeKind.PublicShare, publicShareId); + + /// The id the session is stored under, see . + public static AuthorityChange Session(string sessionId) => new(AuthorityChangeKind.Session, Guid.Empty, sessionId); +} diff --git a/Common/ConnectionAuthority/Grant.cs b/Common/ConnectionAuthority/Grant.cs 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..c026eeae --- /dev/null +++ b/Common/ConnectionAuthority/GrantResolver.cs @@ -0,0 +1,118 @@ +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.PasswordStamp == passwordStamp) + .OpenToVisitors(now) + .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..0675bb02 --- /dev/null +++ b/Common/ConnectionAuthority/IAuthorizedConnection.cs @@ -0,0 +1,24 @@ +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 . + /// + /// + /// 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) => true; + + /// + /// 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/Hubs/ConnectionAuthorityHubFilter.cs b/Common/Hubs/ConnectionAuthorityHubFilter.cs new file mode 100644 index 00000000..e277c020 --- /dev/null +++ b/Common/Hubs/ConnectionAuthorityHubFilter.cs @@ -0,0 +1,107 @@ +using Microsoft.AspNetCore.SignalR; +using OpenShock.Common.ConnectionAuthority; + +namespace OpenShock.Common.Hubs; + +/// +/// 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. +/// +/// 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 ConnectionAuthorityHubFilter : IHubFilter +{ + private readonly HubConnectionAuthority _authority; + + public ConnectionAuthorityHubFilter(HubConnectionAuthority authority) + { + _authority = authority; + } + + /// + public async Task OnConnectedAsync(HubLifetimeContext context, Func next) + { + // 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 + { + if (handle is not null) + { + // 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); + } + catch + { + // SignalR does not call OnDisconnectedAsync when connecting throws. + HubConnectionAuthority.Untrack(context.Context); + throw; + } + } + + /// + public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception, Func next) + { + HubConnectionAuthority.Untrack(context.Context); + return next(context, exception); + } + + /// + public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) + { + var context = invocationContext.Context; + var handle = HubConnectionAuthority.Get(context); + + 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); + + 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(handle.Subject.PublicShareId is not null + ? "Access to this public share is no longer valid" + : "Authentication is no longer valid"); + } + + switch (await handle.EnsureFreshAsync(_authority.Interval)) + { + 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); + } +} diff --git a/Common/Hubs/HubConnectionAuthority.cs b/Common/Hubs/HubConnectionAuthority.cs new file mode 100644 index 00000000..a12f7811 --- /dev/null +++ b/Common/Hubs/HubConnectionAuthority.cs @@ -0,0 +1,151 @@ +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 + }; + } + 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..5d380220 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; @@ -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) @@ -139,7 +140,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 deleted file mode 100644 index 019e2934..00000000 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ /dev/null @@ -1,194 +0,0 @@ -using System.Security.Claims; -using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using OpenShock.Common.Authentication; -using OpenShock.Common.Extensions; -using OpenShock.Common.OpenShockDb; -using OpenShock.Common.Services.Session; - -namespace OpenShock.Common.Hubs; - -/// -/// Keeps an open hub connection from outliving the session or API token it authenticated with. -/// -/// -/// SignalR authenticates a connection once, when it opens, and then keeps it for as long as the client likes. -/// Without this, logging a session out or revoking, expiring or deactivating an API token would only stop new -/// connections: an open one could keep calling, and whatever calls it already had queued would still run. -/// Aborting also discards those queued calls. -/// -/// Two things end a connection. The fast one is a Redis message: revocations are published, and the instance -/// holding the connection closes it right away (the filter registers every connection with -/// for that). The slow one is the check in this filter, which asks the -/// database before a hub method call. It exists for what the messages cannot cover, a message that was lost -/// or a token that simply reached its expiry, so it only runs once per -/// per connection, and never for an idle one. -/// -/// -/// Any change to an API token closes its connections, so a client picks up new permissions, pause state and -/// control limits when it reconnects. -/// -/// -public sealed class RevalidateAuthenticationHubFilter : IHubFilter -{ - private readonly HubConnectionTracker _tracker; - private readonly IOptions _options; - - public RevalidateAuthenticationHubFilter(HubConnectionTracker tracker, IOptions options) - { - _tracker = tracker; - _options = options; - } - - /// - public async Task OnConnectedAsync(HubLifetimeContext context, Func next) - { - var tracked = _tracker.Track(context.Context); - - try - { - // The connection was authenticated before it was tracked. A revocation announced in between found - // nothing to close, so look once now that announcements can reach it. - if (tracked is not null && !await ValidateAsync(context.Context, tracked, context.ServiceProvider)) - { - _tracker.Untrack(context.Context.ConnectionId); - context.Context.Abort(); - return; - } - - await next(context); - } - catch - { - // SignalR does not call OnDisconnectedAsync when connecting throws. - _tracker.Untrack(context.Context.ConnectionId); - throw; - } - } - - /// - public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception, Func next) - { - _tracker.Untrack(context.Context.ConnectionId); - return next(context, exception); - } - - /// - public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) - { - var context = invocationContext.Context; - - // Untracked means anonymous (nothing to check), or a connection a revocation already closed whose - // queued calls are still draining: the check below turns those away. - var tracked = _tracker.Get(context.ConnectionId); - - // A public share connection only leaves the tracker when it is being closed, so there is nothing to check. - if (tracked is null && HubConnectionTracker.GetPublicShareConnection(context) is not null) - { - context.Abort(); - throw new HubException("Access to this public share is no longer valid"); - } - - if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) - { - if (!await ValidateAsync(context, tracked, invocationContext.ServiceProvider)) - { - context.Abort(); - throw new HubException("Authentication is no longer valid"); - } - } - - return await next(invocationContext); - } - - /// Checks the connection against the database and records the result. - private static async Task ValidateAsync(HubCallerContext context, TrackedHubConnection? tracked, IServiceProvider services) - { - if (!await IsStillAuthenticated(context, services)) return false; - - 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/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 0c864130..cbc9638a 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -419,14 +419,29 @@ 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.AddOptions(); - services.AddSingleton(); - services.AddSingleton(); + services.AddOpenShockConnectionAuthority(); + 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/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/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); diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 69fc76e2..ef334b07 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; @@ -6,39 +7,24 @@ 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 . /// /// /// 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, 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. /// - /// - /// - 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); + /// + /// 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); /// /// 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..609ed434 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -10,30 +10,18 @@ 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, 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. /// - public static readonly RedisChannel UserAuthRevoked = new("user-auth-revoked", RedisChannel.PatternMode.Literal); + /// + /// 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); /// /// 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..d71b9784 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; @@ -8,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))); @@ -22,25 +25,18 @@ public Task SendDeviceUpdate(Guid deviceId) return PublishMessage(deviceId, DeviceMessage.Create(DeviceTriggerType.DeviceInfoUpdated)); } - public Task SendApiTokenUpdate(Guid tokenId) + public async 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()); + 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/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/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 f0acb95b..a9e8c0dd 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,8 +79,20 @@ 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; + + Task IAuthorizedConnection.CloseAsync() => CloseRevoked("Hub authentication is no longer valid"); + /// /// Authentication context /// @@ -150,8 +163,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 +313,7 @@ protected override ValueTask DisposeControllerAsync() { Logger.LogTrace("Disposing controller timer"); _keepAliveTimeoutTimer.Dispose(); + _authority?.Dispose(); return base.DisposeControllerAsync(); } diff --git a/LiveControlGateway/Controllers/LiveControlController.cs b/LiveControlGateway/Controllers/LiveControlController.cs index 65ebcdb7..93aa5ae1 100644 --- a/LiveControlGateway/Controllers/LiveControlController.cs +++ b/LiveControlGateway/Controllers/LiveControlController.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Net.WebSockets; using System.Text.Json; using Microsoft.AspNetCore.Authorization; @@ -8,6 +8,7 @@ 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.Models; @@ -17,11 +18,10 @@ 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; @@ -37,11 +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 ConnectionAuthorityRegistry _authorityRegistry; private readonly ILogger _logger; private readonly GatewayMetrics _metrics; @@ -56,23 +56,25 @@ public sealed class LiveControlController : WebsocketBaseController - /// Shocker control scoping carried by the API token used to authenticate, if any. - /// Null when authenticated via a user session (no token limits apply). + /// The session token used to authenticate, if any. Null when authenticated via an API token. /// - private ApiTokenControlLimits? _tokenLimits; + private string? _sessionToken; /// - /// When true, the authenticating API token is paused (or was revoked) and may not send any control frames. + /// 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 bool _tokenPaused; + private ConnectionHandle? _authority; + + 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; - private Dictionary _sharedShockers = new(); private byte _tps = 10; private long _pingTimestamp = Stopwatch.GetTimestamp(); private ushort _latencyMs; @@ -84,7 +86,7 @@ public sealed class LiveControlController : WebsocketBaseController /// 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); @@ -93,14 +95,14 @@ 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, ConnectionAuthorityRegistry authorityRegistry, GatewayMetrics metrics, ILogger logger) : base(logger) { _hubLifetimeManager = hubLifetimeManager; _dbContextFactory = dbContextFactory; - _tokenUpdateSubscriber = tokenUpdateSubscriber; + _authorityRegistry = authorityRegistry; _metrics = metrics; _logger = logger; @@ -124,57 +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); - - 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 => - 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; - } - - _sharedShockers = 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 /// @@ -188,20 +139,40 @@ public async Task UpdatePermissions(OpenShockContext db) 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)))); - - if (!hubExistsAndYouHaveAccess) - { - return WebsocketError.WebsocketLiveControlHubNotFound; - } + 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(); + } - _device = await db.Devices.FirstOrDefaultAsync(x => x.Id == HubId); + if (ownerId is null) + { + return WebsocketError.WebsocketLiveControlHubNotFound; + } - await UpdatePermissions(db); + // From here on a change to the session, token, account or shares reaches this connection. Registering also + // reads what it may do for the first time, which covers a change made since it authenticated. + var (authority, authorityResult) = await _authorityRegistry.RegisterAsync(new ConnectionSubject + { + Kind = ConnectionKind.LiveControl, + UserId = _currentUser.Id, + ApiTokenId = _tokenId, + SessionToken = _sessionToken, + DeviceId = id, + DeviceOwnerId = ownerId + }, this); + _authority = authority; + + switch (authorityResult) + { + case RefreshResult.Revoked: + return WebsocketError.WebsocketLiveControlHubNotFound; + case RefreshResult.Failed: + return ExceptionError.Exception; } if (HttpContext.Request.Query.TryGetValue("tps", out var requestedTps)) @@ -265,24 +236,20 @@ public void OnActionExecuting(ActionExecutingContext context) if (GetOptionalItem() is { } apiToken) { _tokenId = apiToken.Id; - _tokenPaused = apiToken.ShockerControlPaused; - _tokenLimits = ApiTokenControlLimits.FromToken(apiToken); + } + else if (HttpContext.TryGetUserSessionToken(out var sessionToken)) + { + _sessionToken = sessionToken; } } - /// - /// 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, 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. /// - /// - /// - [NonAction] - public void ApplyTokenLimits(bool paused, ApiTokenControlLimits? limits) - { - _tokenPaused = paused; - _tokenLimits = limits; - } + Task IAuthorizedConnection.CloseAsync() => CloseRevoked(AuthorityRevokedDescription); + + private const string AuthorityRevokedDescription = "Authentication is no longer valid"; /// /// Post action context @@ -302,10 +269,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); + // Revoked after the precondition but before the socket was accepted, when there was nothing to close. + if (Authority.IsRevoked) + { + await CloseRevoked(AuthorityRevokedDescription); + return; + } await QueueMessage(new LiveControlResponse { @@ -484,8 +453,23 @@ await QueueMessage(new LiveControlResponse private async Task ProcessFrameInternal(ClientLiveFrame frame) { + // The socket is being closed because what it depends on was revoked. + var authority = Authority; + if (authority.IsRevoked) return; + + // 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. Looking again closes the socket. + if (grant.IsExpired(DateTime.UtcNow)) + { + authority.RequestRefresh(); + return; + } + // A paused API token may not send any control, mirroring the /shockers/control endpoint. - if (_tokenPaused) + if (grant.Token is { Paused: true }) { _metrics.Frame(GatewayMetrics.FrameOutcome.TokenPaused, frame.Type); await QueueMessage(new LiveControlResponse @@ -496,12 +480,11 @@ 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), + 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) }); @@ -516,10 +499,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); @@ -551,9 +534,9 @@ await QueueMessage(new LiveControlResponse } } - private Results.Union5 CheckFramePermissions(Guid shocker, ControlType controlType) + private Results.Union4 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(); @@ -569,6 +552,8 @@ private async Task SendPing() { if (WebSocket is not { State: WebSocketState.Open }) 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, Id); @@ -620,27 +605,12 @@ protected override async ValueTask DisposeControllerAsync() Logger.LogTrace("Disposing controller timer"); _pingTimer.Dispose(); - 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(); } } -/// -/// Union case -/// -public sealed class LiveNotEnabled; - /// /// Union case /// diff --git a/LiveControlGateway/LifetimeManager/HubLifetime.cs b/LiveControlGateway/LifetimeManager/HubLifetime.cs index 59ad00fb..8da7baee 100644 --- a/LiveControlGateway/LifetimeManager/HubLifetime.cs +++ b/LiveControlGateway/LifetimeManager/HubLifetime.cs @@ -454,9 +454,6 @@ 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); } /// 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"; 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 7642cf16..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,7 +59,6 @@ }); #pragma warning restore EXTEXP0008 builder.Services.AddSingleton(); -builder.Services.AddSingleton(); var app = builder.Build(); diff --git a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs b/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs deleted file mode 100644 index afbba5f9..00000000 --- a/LiveControlGateway/PubSub/ApiTokenUpdateSubscriber.cs +++ /dev/null @@ -1,128 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using OpenShock.Common.Models; -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, the limits are fetched from the database once and -/// pushed to all those connections, instead of each connection querying the database on its own. -/// -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; - - bool paused; - ApiTokenControlLimits? limits; - try - { - await using var db = await _dbContextFactory.CreateDbContextAsync(); - - var 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); - } - } - catch (Exception e) - { - _logger.LogError(e, "Error fetching api token [{TokenId}] limits for live control connections", tokenId); - return; - } - - foreach (var client in clients) - client.ApplyTokenLimits(paused, limits); - } -}