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