diff --git a/API.IntegrationTests/FrequentConnectionCheckWebApplicationFactory.cs b/API.IntegrationTests/FrequentConnectionCheckWebApplicationFactory.cs
new file mode 100644
index 00000000..9b5c85de
--- /dev/null
+++ b/API.IntegrationTests/FrequentConnectionCheckWebApplicationFactory.cs
@@ -0,0 +1,11 @@
+namespace OpenShock.API.IntegrationTests;
+
+///
+/// Variant of whose host checks open connections every second, for the tests
+/// of a change that was never announced: those would otherwise have to wait out the interval. It shares the
+/// database and Redis with the other hosts, so only the connection under test has to be opened against it.
+///
+public sealed class FrequentConnectionCheckWebApplicationFactory : WebApplicationFactory
+{
+ public override TimeSpan ConnectionCheckInterval => TimeSpan.FromSeconds(1);
+}
diff --git a/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs
new file mode 100644
index 00000000..9b7eb1b7
--- /dev/null
+++ b/API.IntegrationTests/Tests/AuthorityChangeLogTests.cs
@@ -0,0 +1,99 @@
+using MessagePack;
+using Microsoft.Extensions.DependencyInjection;
+using OpenShock.Common.ConnectionAuthority;
+using StackExchange.Redis;
+using TUnit.Assertions.Enums;
+
+namespace OpenShock.API.IntegrationTests.Tests;
+
+///
+/// The authority change log against the real store. What a reader makes of the log is covered without a store
+/// in the unit tests; this is about the stream commands doing what the log promises.
+///
+public sealed class AuthorityChangeLogTests
+{
+ [ClassDataSource(Shared = SharedType.PerTestSession)]
+ public required WebApplicationFactory WebApplicationFactory { get; init; }
+
+ private IAuthorityChangeLog Log => WebApplicationFactory.Services.GetRequiredService();
+
+ [Test]
+ public async Task ReadAfter_ReturnsWhatWasAppendedSince_InOrder_AndNothingFromBefore()
+ {
+ var before = AuthorityChange.Device(Guid.NewGuid());
+ var first = AuthorityChange.Session("stored-id-" + Guid.NewGuid());
+ var second = AuthorityChange.ApiToken(Guid.NewGuid());
+
+ await Log.AppendAsync(before);
+ var mark = await Log.MarkAsync();
+ await Log.AppendAsync(first);
+ await Log.AppendAsync(second);
+
+ // Other tests announce changes into the same log, so look only at the ones made here.
+ var mine = (await Log.ReadAfterAsync(mark, 10_000))
+ .Where(entry => entry.Change == before || entry.Change == first || entry.Change == second)
+ .ToArray();
+
+ await Assert.That(mine.Select(entry => entry.Change!)).IsEquivalentTo(new[] { first, second }, CollectionOrdering.Matching);
+ await Assert.That(mine[0].Position.CompareTo(mine[1].Position)).IsLessThan(0);
+ await Assert.That(mine[0].Position.CompareTo(mark)).IsGreaterThan(0);
+ }
+
+ [Test]
+ public async Task ReadAfter_StopsAtTheCount_AndCarriesOnFromTheLastEntry()
+ {
+ var mark = await Log.MarkAsync();
+ var changes = Enumerable.Range(0, 5).Select(_ => AuthorityChange.PublicShare(Guid.NewGuid())).ToArray();
+ foreach (var change in changes) await Log.AppendAsync(change);
+
+ var seen = new List();
+ var position = mark;
+ while (true)
+ {
+ var batch = await Log.ReadAfterAsync(position, 2);
+ await Assert.That(batch.Count).IsLessThanOrEqualTo(2);
+ if (batch.Count == 0) break;
+
+ seen.AddRange(batch.Where(entry => entry.Change is not null).Select(entry => entry.Change!));
+ position = batch[^1].Position;
+ }
+
+ await Assert.That(seen.Where(changes.Contains)).IsEquivalentTo(changes);
+ }
+
+ ///
+ /// A newer version can announce a kind of change this one does not know. That decodes to nothing without an
+ /// error, and must not pass for a mark: the reader has to treat it as "anything may have changed".
+ ///
+ [Test]
+ public async Task ReadAfter_ChangeOfAnUnknownKind_IsUnreadable()
+ {
+ var mark = await Log.MarkAsync();
+
+ // A union as MessagePack writes it, [key, value], with a key no AuthorityChange has.
+ var payload = MessagePackSerializer.Serialize(new object[] { 250, new object[] { Guid.NewGuid() } });
+ var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase();
+ var id = await redis.StreamAddAsync("authority-changes", "c", (RedisValue)new ReadOnlyMemory(payload));
+
+ var entry = (await Log.ReadAfterAsync(mark, 10_000)).Single(entry => entry.Position.ToString() == id.ToString());
+
+ await Assert.That(entry.Change).IsNull();
+ await Assert.That(entry.Unreadable).IsTrue();
+ }
+
+ [Test]
+ public async Task Mark_IsAnEntryWithoutAChange_AndTheLogReachesBackToIt()
+ {
+ var earlier = await Log.MarkAsync();
+ var mark = await Log.MarkAsync();
+
+ var entries = await Log.ReadAfterAsync(earlier, 10_000);
+ var marked = entries.Single(entry => entry.Position == mark);
+ await Assert.That(marked.Change).IsNull();
+ await Assert.That(marked.Unreadable).IsFalse();
+
+ var oldest = await Log.OldestAsync();
+ await Assert.That(oldest).IsNotNull();
+ await Assert.That(oldest!.Value.CompareTo(mark)).IsLessThanOrEqualTo(0);
+ }
+}
diff --git a/API.IntegrationTests/Tests/AutomationTokenTests.cs b/API.IntegrationTests/Tests/AutomationTokenTests.cs
index 5568a9b9..870f77e8 100644
--- a/API.IntegrationTests/Tests/AutomationTokenTests.cs
+++ b/API.IntegrationTests/Tests/AutomationTokenTests.cs
@@ -4,6 +4,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.AutomationTokens;
@@ -315,6 +316,9 @@ public async Task Delete_DeletesTokenAndTheAccountsItCreated()
var unrelatedId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("autodelunrelated"), UniqueNames.Email("autodelunrelated"), Password);
using var client = await CreateAdminClient("autodelete");
+ var log = WebApplicationFactory.Services.GetRequiredService();
+ var before = await log.MarkAsync();
+
var response = await client.DeleteAsync($"/1/admin/automationTokens/{tokenId}");
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
@@ -324,6 +328,11 @@ public async Task Delete_DeletesTokenAndTheAccountsItCreated()
await Assert.That(await db.AutomationTokens.AnyAsync(t => t.Id == tokenId)).IsFalse();
await Assert.That(await db.Users.AnyAsync(u => u.Id == createdId)).IsFalse();
await Assert.That(await db.Users.AnyAsync(u => u.Id == unrelatedId)).IsTrue();
+
+ // Announced, so whatever the deleted account still had open is closed. The other account is left alone.
+ var announced = (await log.ReadAfterAsync(before, 10_000)).Select(entry => entry.Change).ToArray();
+ await Assert.That(announced).Contains(AuthorityChange.User(createdId));
+ await Assert.That(announced).DoesNotContain(AuthorityChange.User(unrelatedId));
}
// --- Helpers ---
diff --git a/API.IntegrationTests/Tests/DevicesTests.cs b/API.IntegrationTests/Tests/DevicesTests.cs
index d0f17c51..8d985f8e 100644
--- a/API.IntegrationTests/Tests/DevicesTests.cs
+++ b/API.IntegrationTests/Tests/DevicesTests.cs
@@ -3,8 +3,11 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.OpenShockDb;
+using OpenShock.Common.Services.RedisPubSub;
using OpenShock.IntegrationTests.Shared;
+using StackExchange.Redis;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -105,6 +108,59 @@ 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;
+
+ // The change is in the log; the message only says there is something new in it.
+ var log = WebApplicationFactory.Services.GetRequiredService();
+ var from = await log.MarkAsync();
+ await subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, (_, _) => _ = Task.Run(async () =>
+ {
+ var entries = await log.ReadAfterAsync(from, 1000);
+ if (entries.Any(entry => entry.Change == AuthorityChange.Device(deviceId))) announced.TrySetResult();
+ }));
+ await subscriber.SubscribeAsync(RedisChannels.DeviceMessage(deviceId), (_, _) => Interlocked.Increment(ref reloads));
+
+ return (announced.Task, () => Volatile.Read(ref reloads));
+ }
+
[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..1021e772
--- /dev/null
+++ b/API.IntegrationTests/Tests/GrantResolverTests.cs
@@ -0,0 +1,366 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.Common.ConnectionAuthority;
+using OpenShock.Common.Constants;
+using OpenShock.Common.Models;
+using OpenShock.Common.OpenShockDb;
+using OpenShock.Common.Services.Session;
+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_GrantEndsWhenTheSessionDoes()
+ {
+ // Nothing reliably announces a session reaching its lifetime, so the grant carries when that is.
+ var owner = await CreateUser("grantsessexp");
+ var (deviceId, _) = await CreateShockerOnDevice(owner.Id);
+
+ var grant = await Resolve(LiveControlBySession(owner, deviceId, owner.Id));
+
+ var expected = DateTime.UtcNow.Add(Duration.LoginSessionLifetime);
+ await Assert.That(grant!.ExpiresAt).IsNotNull();
+ await Assert.That((grant.ExpiresAt!.Value - expected).Duration()).IsLessThan(TimeSpan.FromMinutes(5));
+ }
+
+ [Test]
+ public async Task LiveControl_Session_Removed_MayNotGoOn()
+ {
+ 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 = new LiveControlSubject(new SessionCredential(owner.Id, other.SessionToken), deviceId, owner.Id);
+
+ 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 SignalRSubject(new ApiTokenCredential(owner.Id, tokenId)));
+
+ await Assert.That(grant).IsNotNull();
+ await Assert.That(grant!.Shockers.Count).IsEqualTo(0);
+ }
+
+ // --- 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 HubSocketSubject(deviceId, owner.Id, 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 LiveControlSubject LiveControlBySession(AuthenticatedUser user, Guid deviceId, Guid ownerId) =>
+ new(new SessionCredential(user.Id, user.SessionToken), deviceId, ownerId);
+
+ private static LiveControlSubject LiveControlByToken(Guid userId, Guid tokenId, Guid deviceId, Guid ownerId) =>
+ new(new ApiTokenCredential(userId, tokenId), deviceId, ownerId);
+
+ private async Task Resolve(ConnectionSubject subject)
+ {
+ 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..5f613b16 100644
--- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs
+++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs
@@ -1,3 +1,4 @@
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.IntegrationTests.Shared;
using StackExchange.Redis;
using System.Net;
@@ -22,6 +23,13 @@ public sealed class PublicSharePasswordTests
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
+ ///
+ /// A host that checks connections often, for the test of the periodic check. It opens its connection against
+ /// this one; everything else can go through either, the hosts share the database and Redis.
+ ///
+ [ClassDataSource(Shared = SharedType.PerTestSession)]
+ public required FrequentConnectionCheckWebApplicationFactory FrequentChecks { get; init; }
+
// --- Loading the share ---
[Test]
@@ -289,6 +297,31 @@ public async Task Hub_OwnerConnectsWithoutToken()
await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected);
}
+ ///
+ /// An open connection holds the time the share ends as it was when last checked. Moving it has to be
+ /// announced, or the connection would only find out at the rare periodic check.
+ ///
+ [Test]
+ public async Task Hub_MovingTheExpiryCloser_ClosesOpenConnectionsWhenItIsReached()
+ {
+ var (owner, shareId) = await CreateShareWithShocker("pwhubexpiry", password: null);
+ await using var connection = await ConnectAsync(shareId, unlockToken: null);
+
+ var log = WebApplicationFactory.Services.GetRequiredService();
+ var before = await log.MarkAsync();
+
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken);
+ var response = await client.PutAsync($"/1/shares/links/{shareId}",
+ TestHelper.JsonContent(new { name = "Ends soon", expiresOn = DateTime.UtcNow.AddSeconds(3), slug = (string?)null }));
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+
+ // The connection closing below already takes the announcement; it is also looked for itself.
+ var announced = (await log.ReadAfterAsync(before, 10_000)).Any(entry => entry.Change == AuthorityChange.PublicShare(shareId));
+ await Assert.That(announced).IsTrue();
+
+ await AssertConnectionClosesAsync(connection);
+ }
+
[Test]
public async Task Hub_ChangingThePassword_ClosesOpenConnections()
{
@@ -324,7 +357,8 @@ public async Task Hub_RemovingThePassword_KeepsConnectionsOpen()
await SetPassword(owner, shareId, null);
- await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500));
+ // Long enough for the announced change to have reached the connection.
+ await Task.Delay(TimeSpan.FromMilliseconds(1500));
await connection.InvokeAsync("Control", Array.Empty());
await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected);
}
@@ -348,9 +382,7 @@ public async Task Hub_PasswordChangedWithoutAnnouncement_ClosesOnTheNextCheck()
var (_, shareId) = await CreateShareWithShocker("pwhubfallback", Password);
using var visitor = WebApplicationFactory.CreateClient();
var token = await Unlock(visitor, shareId, Password);
- await using var connection = await ConnectAsync(shareId, token);
- // Checked once here, so the call below has to be a re-check.
- await connection.InvokeAsync("Control", Array.Empty());
+ await using var connection = await ConnectAsync(shareId, token, factory: FrequentChecks);
await using (var scope = WebApplicationFactory.Services.CreateAsyncScope())
{
@@ -360,7 +392,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(FrequentChecks.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500));
Exception? failure = null;
try
{
@@ -409,6 +441,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,
@@ -479,14 +525,20 @@ private async Task SetPassword(AuthenticatedUser owner, Guid shareI
return json.RootElement.Clone();
}
- /// Connects and waits until the hub admitted the connection (it sends Welcome after its checks).
- private async Task ConnectAsync(Guid shareId, string? unlockToken, string? sessionToken = null)
+ ///
+ /// Connects, waits until the hub admitted the connection (it sends Welcome after its checks) and makes one
+ /// call on it. A public share connection is first checked at its first call or, failing that, at the next
+ /// sweep. With the call made here, a change that closes it afterwards did so by being announced, and not by
+ /// that first check happening to come late.
+ ///
+ private async Task ConnectAsync(Guid shareId, string? unlockToken, string? sessionToken = null, WebApplicationFactory? factory = null)
{
- var (connection, welcomed) = BuildConnection(shareId, unlockToken, sessionToken);
+ var (connection, welcomed) = BuildConnection(shareId, unlockToken, sessionToken, factory);
try
{
await connection.StartAsync();
await welcomed.WaitAsync(TimeSpan.FromSeconds(30));
+ await connection.InvokeAsync("Control", Array.Empty());
return connection;
}
catch
@@ -496,9 +548,9 @@ private async Task ConnectAsync(Guid shareId, string? unlockToken
}
}
- private (HubConnection Connection, Task Welcomed) BuildConnection(Guid shareId, string? unlockToken, string? sessionToken = null)
+ private (HubConnection Connection, Task Welcomed) BuildConnection(Guid shareId, string? unlockToken, string? sessionToken = null, WebApplicationFactory? factory = null)
{
- var server = WebApplicationFactory.Server;
+ var server = (factory ?? WebApplicationFactory).Server;
var path = $"/1/hubs/share/link/{shareId}?name=Guest";
if (unlockToken is not null) path += $"&unlockToken={Uri.EscapeDataString(unlockToken)}";
diff --git a/API.IntegrationTests/Tests/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..a5c8558c 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;
@@ -22,6 +23,13 @@ public sealed class SignalRUserHubTests
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
+ ///
+ /// A host that checks connections often, for the tests of the periodic check. They open their connection
+ /// against this one; everything else can go through either, the hosts share the database and Redis.
+ ///
+ [ClassDataSource(Shared = SharedType.PerTestSession)]
+ public required FrequentConnectionCheckWebApplicationFactory FrequentChecks { get; init; }
+
// --- Negotiate: credentials the user hub does not accept ---
[Test]
@@ -166,36 +174,36 @@ public async Task PublicShareHub_Guest_CanConnectAndKeepCalling()
using var json = JsonDocument.Parse(await created.Content.ReadAsStringAsync());
var shareId = json.RootElement.GetProperty("data").GetGuid();
- await using var connection = await ConnectAsync(null, null, $"/1/hubs/share/link/{shareId}?name=Guest");
+ await using var connection = await ConnectAsync(FrequentChecks, null, null, $"/1/hubs/share/link/{shareId}?name=Guest");
await connection.InvokeAsync("Control", Array.Empty());
- await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500));
+ await Task.Delay(FrequentChecks.ConnectionCheckInterval + TimeSpan.FromMilliseconds(500));
await connection.InvokeAsync("Control", Array.Empty());
await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected);
}
- // --- The fallback: a connection whose revocation was never announced stops at its next periodic check ---
+ // --- The fallback: a connection whose revocation was never announced is closed by the periodic check, also while idle ---
[Test]
- public async Task Invoke_AfterSessionRemovedWithoutAnnouncement_FailsAndClosesConnection()
+ public async Task Idle_AfterSessionRemovedWithoutAnnouncement_ClosesConnection()
{
var user = await CreateUser("hubrevalsess");
- await using var connection = await ConnectCheckedSessionAsync(user);
+ await using var connection = await ConnectCheckedSessionAsync(FrequentChecks, user);
// Removed straight from Redis: no revocation message, and a deleted key raises no expiry event.
var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase();
await Assert.That(await redis.KeyDeleteAsync(SessionKey(user.SessionToken))).IsTrue();
- await AssertInvokeFailsAndConnectionClosesAsync(connection);
+ await AssertIdleConnectionClosesAsync(connection);
}
[Test]
- public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsAndClosesConnection()
+ public async Task Idle_AfterAccountDeactivated_WithTheSessionLeftBehind_ClosesConnection()
{
// Deactivation removes sessions after its database commit; if that step fails the session survives.
var user = await CreateUser("hubrevaldeact");
- await using var connection = await ConnectCheckedSessionAsync(user);
+ await using var connection = await ConnectCheckedSessionAsync(FrequentChecks, user);
await using (var scope = WebApplicationFactory.Services.CreateAsyncScope())
{
@@ -209,7 +217,7 @@ public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsA
await db.SaveChangesAsync();
}
- await AssertInvokeFailsAndConnectionClosesAsync(connection);
+ await AssertIdleConnectionClosesAsync(connection);
}
public enum UnannouncedTokenChange
@@ -225,11 +233,11 @@ public enum UnannouncedTokenChange
[Arguments(UnannouncedTokenChange.Paused)]
[Arguments(UnannouncedTokenChange.Expired)]
[Arguments(UnannouncedTokenChange.OwnerDeactivated)]
- public async Task Invoke_AfterApiTokenChangedWithoutAnnouncement_FailsAndClosesConnection(UnannouncedTokenChange change)
+ public async Task Idle_AfterApiTokenChangedWithoutAnnouncement_ClosesConnection(UnannouncedTokenChange change)
{
var user = await CreateUser("hubrevaltok");
var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate");
- await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken);
+ await using var connection = await ConnectAsync(FrequentChecks, AuthConstants.ApiTokenHeaderName, rawToken);
await connection.InvokeAsync("Reboot", Guid.CreateVersion7());
// Written straight to the database, so no revocation message is published.
@@ -263,23 +271,23 @@ public async Task Invoke_AfterApiTokenChangedWithoutAnnouncement_FailsAndClosesC
}
}
- await AssertInvokeFailsAndConnectionClosesAsync(connection);
+ await AssertIdleConnectionClosesAsync(connection);
}
private Task CreateUser(string prefix) =>
TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), "SecurePassword123#");
/// Opens a session connection and makes one call on it, so it has been checked once.
- private async Task ConnectCheckedSessionAsync(AuthenticatedUser user)
+ private static async Task ConnectCheckedSessionAsync(WebApplicationFactory factory, AuthenticatedUser user)
{
- var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}");
+ var connection = await ConnectAsync(factory, "Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}");
await connection.InvokeAsync("Reboot", Guid.CreateVersion7());
return connection;
}
/// 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
@@ -310,32 +318,22 @@ internal static async Task ConnectAsync(WebApplicationFactory fac
return connection;
}
- private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnection connection)
+ ///
+ /// The connection makes no call, so it is the periodic check that finds the change and closes it. A call
+ /// afterwards has nothing left to run on.
+ ///
+ private static async Task AssertIdleConnectionClosesAsync(HubConnection connection)
{
- // The connection was checked moments ago and that result is kept for the interval, so the
- // revocation only reaches it on the first call after that.
- await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500));
-
- // Still open here, so it is the periodic check below that ends it, not a revocation message.
- await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected);
-
- // The server answers with an error and aborts; which of the two the client sees first is a race.
- Exception? failure = null;
- try
- {
- await connection.InvokeAsync("Reboot", Guid.CreateVersion7());
- }
- catch (Exception ex)
- {
- failure = ex;
- }
-
- await Assert.That(failure).IsNotNull();
-
await AssertConnectionClosesAsync(connection);
+
+ await Assert.That(async () => await connection.InvokeAsync("Reboot", Guid.CreateVersion7())).ThrowsException();
}
- /// Waits for the server to close the connection, without calling anything on it.
+ ///
+ /// Waits for the server to close the connection, without calling anything on it. On the default host only
+ /// an announced change or a session's expiry event can do that in this time, see
+ /// .
+ ///
private static async Task AssertConnectionClosesAsync(HubConnection connection)
{
var deadline = DateTime.UtcNow.AddSeconds(30);
diff --git a/API.IntegrationTests/Tests/TokensTests.cs b/API.IntegrationTests/Tests/TokensTests.cs
index c7dc2770..844c3dc9 100644
--- a/API.IntegrationTests/Tests/TokensTests.cs
+++ b/API.IntegrationTests/Tests/TokensTests.cs
@@ -3,6 +3,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.OpenShockDb;
using OpenShock.IntegrationTests.Shared;
@@ -305,6 +306,34 @@ public async Task DeleteToken_ApiTokenDeletingAnotherTokenOfItsOwner_Returns403A
// --- Helpers ---
+ [Test]
+ public async Task ReportTokens_DeletesTheLeakedTokenAndAnnouncesIt()
+ {
+ var owner = await CreateUser("tokreportowner");
+ var reporter = await CreateUser("tokreporter");
+ var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "Leaked");
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, reporter.SessionToken);
+
+ var log = WebApplicationFactory.Services.GetRequiredService();
+ var before = await log.MarkAsync();
+
+ var response = await client.PostAsync("/1/tokens/report", TestHelper.JsonContent(new
+ {
+ turnstileResponse = "valid-token",
+ secrets = new[] { rawToken, "not-a-token-anyone-has" }
+ }));
+
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ await Assert.That(await db.ApiTokens.AnyAsync(t => t.Id == tokenId)).IsFalse();
+
+ // Announced, so a connection already open with the leaked token is closed too.
+ var announced = (await log.ReadAfterAsync(before, 10_000)).Select(entry => entry.Change).ToArray();
+ await Assert.That(announced).Contains(AuthorityChange.ApiToken(tokenId));
+ }
+
private Task CreateUser(string prefix) =>
TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password);
diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs
index 54f64e3a..66a0a7d3 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,13 @@ 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. Far longer
+ /// than any test waits for a connection to close, so a test that expects an announced change to close one
+ /// cannot pass on the periodic check instead. The tests of that check itself use
+ /// .
+ ///
+ public virtual TimeSpan ConnectionCheckInterval => TimeSpan.FromMinutes(15);
protected override void ConfigureClient(HttpClient client)
{
@@ -110,9 +116,12 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
services.RemoveAll();
services.AddSingleton();
- // Hub connections re-check their session or API token at most once per interval. Kept short so
- // the tests that revoke one do not have to wait out the production interval.
- services.Configure(options => options.Interval = HubRevalidationInterval);
+ // How often a hub connection is checked without a reason to, see ConnectionCheckInterval.
+ services.Configure(options =>
+ {
+ options.Interval = ConnectionCheckInterval;
+ options.LiveControlInterval = ConnectionCheckInterval;
+ });
});
}
}
diff --git a/API/Controller/Admin/AutomationTokenDelete.cs b/API/Controller/Admin/AutomationTokenDelete.cs
index e59d2447..0db9ed89 100644
--- a/API/Controller/Admin/AutomationTokenDelete.cs
+++ b/API/Controller/Admin/AutomationTokenDelete.cs
@@ -2,9 +2,12 @@
using Microsoft.EntityFrameworkCore;
using Npgsql;
using OpenShock.Common.ApiVersioning;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.Audit;
+using OpenShock.Common.Services.RedisPubSub;
+using OpenShock.Common.Services.Session;
namespace OpenShock.API.Controller.Admin;
@@ -22,6 +25,8 @@ public sealed partial class AdminController
public async Task DeleteAutomationToken(
[FromRoute] Guid id,
[FromServices] IAuditService auditService,
+ [FromServices] IRedisPubService redisPubService,
+ [FromServices] ISessionService sessionService,
CancellationToken ct)
{
PedanticallyEnsureAdmin();
@@ -69,6 +74,19 @@ await auditService.LogAsync(
_logger.LogInformation(
"Deleted account {UserId} together with automation token {AutomationTokenId}",
userId, token.Id);
+
+ // Closes what the account still had open.
+ await redisPubService.SendAuthorityChanged(AuthorityChange.User(userId));
+
+ try
+ {
+ await sessionService.DeleteSessionsByUserIdAsync(userId);
+ }
+ catch (Exception e)
+ {
+ // The account is gone, so its sessions can no longer be used; they only take up room until they expire.
+ _logger.LogWarning(e, "Failed to remove the sessions of deleted account {UserId}", userId);
+ }
}
return Ok();
diff --git a/API/Controller/Devices/DevicesController.cs b/API/Controller/Devices/DevicesController.cs
index ed609d9d..2511b037 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
+ /// Announces the new token, so a hub connected with the old one is closed.
///
/// 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..a7862e83 100644
--- a/API/Controller/Shares/Links/DeletePublicShare.cs
+++ b/API/Controller/Shares/Links/DeletePublicShare.cs
@@ -4,6 +4,7 @@
using Microsoft.EntityFrameworkCore;
using OpenShock.Common.ApiVersioning;
using OpenShock.Common.Authentication.Attributes;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.Errors;
using OpenShock.Common.Extensions;
using OpenShock.Common.Models;
@@ -38,8 +39,9 @@ public async Task DeletePublicShare([FromRoute] Guid publicShareI
if (result <= 0) return Problem(PublicShareError.PublicShareNotFound);
+ // Before the push to the connections on it, which can fail: announcing cannot.
+ await redisPubService.SendAuthorityChanged(AuthorityChange.PublicShare(publicShareId));
await deviceUpdateService.UpdatePublicShare(publicShareId);
- await redisPubService.SendPublicShareAccessRevoked(publicShareId);
return LegacyEmptyOk("Deleted public share");
}
}
diff --git a/API/Controller/Shares/Links/EditPublicShare.cs b/API/Controller/Shares/Links/EditPublicShare.cs
index 94454cab..fa3edb41 100644
--- a/API/Controller/Shares/Links/EditPublicShare.cs
+++ b/API/Controller/Shares/Links/EditPublicShare.cs
@@ -6,8 +6,10 @@
using OpenShock.API.Services.DeviceUpdate;
using OpenShock.Common.ApiVersioning;
using OpenShock.Common.Authentication.Attributes;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.Errors;
using OpenShock.Common.OpenShockDb;
+using OpenShock.Common.Services.RedisPubSub;
using OpenShock.Internal.Common.Problems;
namespace OpenShock.API.Controller.Shares.Links;
@@ -29,7 +31,7 @@ public sealed partial class ShareLinksController
[ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // PublicShareExpiryDateInPast, SlugInvalid
[ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound
[ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // SlugTaken
- public async Task EditPublicShare([FromRoute] Guid publicShareId, [FromBody] PublicShareEdit body, [FromServices] IDeviceUpdateService deviceUpdateService, CancellationToken cancellationToken)
+ public async Task EditPublicShare([FromRoute] Guid publicShareId, [FromBody] PublicShareEdit body, [FromServices] IDeviceUpdateService deviceUpdateService, [FromServices] IRedisPubService redisPubService, CancellationToken cancellationToken)
{
if (body.ExpiresOn <= DateTime.UtcNow) return Problem(PublicShareError.PublicShareExpiryDateInPast);
@@ -52,6 +54,10 @@ public async Task EditPublicShare([FromRoute] Guid publicShareId,
return Problem(PublicShareError.SlugTaken);
}
+ // When the share ends may have moved, and open connections to it hold the old time. Before the push to
+ // them, which can fail: announcing cannot.
+ await redisPubService.SendAuthorityChanged(AuthorityChange.PublicShare(publicShareId));
+
await deviceUpdateService.UpdatePublicShare(publicShareId);
return Ok(OwnPublicShareResponse.GetFromEf(share));
}
diff --git a/API/Controller/Shares/Links/SetPublicSharePassword.cs b/API/Controller/Shares/Links/SetPublicSharePassword.cs
index 37f72b63..fea9d9da 100644
--- a/API/Controller/Shares/Links/SetPublicSharePassword.cs
+++ b/API/Controller/Shares/Links/SetPublicSharePassword.cs
@@ -5,6 +5,7 @@
using OpenShock.API.Models.Response;
using OpenShock.Common.ApiVersioning;
using OpenShock.Common.Authentication.Attributes;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.Errors;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.RedisPubSub;
@@ -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/Controller/Tokens/ReportTokens.cs b/API/Controller/Tokens/ReportTokens.cs
index 6126cc2b..f620508e 100644
--- a/API/Controller/Tokens/ReportTokens.cs
+++ b/API/Controller/Tokens/ReportTokens.cs
@@ -8,8 +8,10 @@
using OpenShock.API.Models.Requests;
using OpenShock.API.Services.Turnstile;
using OpenShock.Common.ApiVersioning;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.AutomationTokens;
+using OpenShock.Common.Services.RedisPubSub;
using OpenShock.Common.Services.Webhook;
using OpenShock.Common.Utils;
using OpenShock.Internal.Common.Problems;
@@ -26,6 +28,7 @@ public sealed partial class TokensController
///
///
///
+ /// Announces each deleted token, so connections open with it are closed.
///
/// The tokens were deleted if found
[HttpPost("report")]
@@ -38,6 +41,7 @@ public async Task ReportTokens(
[FromServices] ICloudflareTurnstileService turnstileService,
[FromServices] IAutomationTokenService automationTokens,
[FromServices] IWebhookService webhookService,
+ [FromServices] IRedisPubService redisPubService,
CancellationToken cancellationToken)
{
var remoteIP = HttpContext.GetRemoteIP();
@@ -66,9 +70,20 @@ public async Task ReportTokens(
hashes[i] = HashingUtils.HashToken(body.Secrets[i]);
}
- nAffected = await _db.ApiTokens
+ var tokenIds = await _db.ApiTokens
.Where(x => hashes.Contains(x.TokenHash))
+ .Select(x => x.Id)
+ .ToArrayAsync();
+
+ nAffected = await _db.ApiTokens
+ .Where(x => tokenIds.Contains(x.Id))
.ExecuteDeleteAsync();
+
+ // A leaked token must also stop what is already connected with it.
+ foreach (var tokenId in tokenIds)
+ {
+ await redisPubService.SendAuthorityChanged(AuthorityChange.ApiToken(tokenId));
+ }
}
catch (Exception e)
{
diff --git a/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..ad45e6f0 100644
--- a/API/Services/Account/AccountService.cs
+++ b/API/Services/Account/AccountService.cs
@@ -2,6 +2,7 @@
using Microsoft.EntityFrameworkCore;
using Npgsql;
using OpenShock.API.Services.Signup;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.Constants;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;
@@ -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..4c15b7dc 100644
--- a/API/Services/Token/ApiTokenService.cs
+++ b/API/Services/Token/ApiTokenService.cs
@@ -4,6 +4,7 @@
using OpenShock.API.Models;
using OpenShock.API.Models.Requests;
using OpenShock.API.Models.Response;
+using OpenShock.Common.ConnectionAuthority;
using OpenShock.Common.Constants;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;
@@ -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/AuthorityChangeAnnouncerTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs
new file mode 100644
index 00000000..88656e5e
--- /dev/null
+++ b/Common.Tests/ConnectionAuthority/AuthorityChangeAnnouncerTests.cs
@@ -0,0 +1,165 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using OpenShock.Common.ConnectionAuthority;
+
+namespace OpenShock.Common.Tests.ConnectionAuthority;
+
+public sealed class AuthorityChangeAnnouncerTests
+{
+ private sealed class FlakyLog : IAuthorityChangeLog
+ {
+ private readonly List _appended = [];
+
+ public volatile bool Unreachable;
+
+ public AuthorityChange[] Appended
+ {
+ get
+ {
+ lock (_appended) return [.. _appended];
+ }
+ }
+
+ /// Runs after a change is in the log and before whoever appended it hears so.
+ public Func? AfterAppend { get; set; }
+
+ public async Task AppendAsync(AuthorityChange change)
+ {
+ if (Unreachable) throw new InvalidOperationException("redis is down");
+ lock (_appended) _appended.Add(change);
+ if (AfterAppend is { } afterAppend) await afterAppend();
+ }
+
+ public Task MarkAsync() => throw new NotSupportedException();
+ public Task OldestAsync() => throw new NotSupportedException();
+ public Task> ReadAfterAsync(LogPosition position, int count) => throw new NotSupportedException();
+ }
+
+ private static AuthorityChangeAnnouncer Create(FlakyLog log) =>
+ new(log, NullLogger.Instance) { RetryDelay = TimeSpan.FromMilliseconds(20) };
+
+ private static async Task Until(Func condition)
+ {
+ var deadline = DateTime.UtcNow.AddSeconds(10);
+ while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(10);
+ }
+
+ [Test]
+ public async Task Announce_LogsTheChange()
+ {
+ var log = new FlakyLog();
+ var announcer = Create(log);
+ var change = AuthorityChange.User(Guid.NewGuid());
+
+ await announcer.AnnounceAsync(change);
+
+ await Assert.That(log.Appended).IsEquivalentTo(new[] { change });
+ await Assert.That(announcer.Waiting).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task Announce_LogUnreachable_DoesNotThrow_AndLogsItOnceItCanBe()
+ {
+ var log = new FlakyLog { Unreachable = true };
+ var announcer = Create(log);
+ var first = AuthorityChange.User(Guid.NewGuid());
+ var second = AuthorityChange.ApiToken(Guid.NewGuid());
+
+ await announcer.AnnounceAsync(first);
+ await announcer.AnnounceAsync(second);
+
+ await Assert.That(log.Appended.Length).IsEqualTo(0);
+ await Assert.That(announcer.Waiting).IsEqualTo(2);
+
+ log.Unreachable = false;
+ await Until(() => announcer.Waiting == 0);
+
+ await Assert.That(log.Appended).IsEquivalentTo(new[] { first, second });
+ }
+
+ [Test]
+ public async Task Announce_AfterItCaughtUp_StillRetriesTheNextFailure()
+ {
+ var log = new FlakyLog { Unreachable = true };
+ var announcer = Create(log);
+
+ await announcer.AnnounceAsync(AuthorityChange.Device(Guid.NewGuid()));
+ log.Unreachable = false;
+ await Until(() => announcer.Waiting == 0 && !announcer.IsRetrying);
+ await Assert.That(announcer.IsRetrying).IsFalse();
+
+ // A second outage, after the first retry loop has ended.
+ log.Unreachable = true;
+ var later = AuthorityChange.PublicShare(Guid.NewGuid());
+ await announcer.AnnounceAsync(later);
+ log.Unreachable = false;
+ await Until(() => announcer.Waiting == 0);
+
+ await Assert.That(log.Appended).Contains(later);
+ await Assert.That(log.Appended.Length).IsEqualTo(2);
+ }
+
+ [Test]
+ public async Task Dispose_TriesWhatIsStillWaitingOnceMore()
+ {
+ var log = new FlakyLog { Unreachable = true };
+ var announcer = new AuthorityChangeAnnouncer(log, NullLogger.Instance) { RetryDelay = TimeSpan.FromHours(1) };
+ var change = AuthorityChange.User(Guid.NewGuid());
+ await announcer.AnnounceAsync(change);
+
+ log.Unreachable = false;
+ await announcer.DisposeAsync();
+
+ await Assert.That(log.Appended).IsEquivalentTo(new[] { change });
+ }
+
+ ///
+ /// Shutdown and the retry both take from what is waiting. If they did so at the same time, one would remove
+ /// a change the other had not logged yet, and that change would never be.
+ ///
+ [Test]
+ public async Task Dispose_WhileTheRetryIsLogging_LogsEveryWaitingChangeOnce()
+ {
+ var log = new FlakyLog { Unreachable = true };
+ var announcer = Create(log);
+ var first = AuthorityChange.User(Guid.NewGuid());
+ var second = AuthorityChange.ApiToken(Guid.NewGuid());
+ await announcer.AnnounceAsync(first);
+ await announcer.AnnounceAsync(second);
+
+ // The retry gets the first change into the log and is held before it takes it off the queue.
+ var retryAppended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var releaseRetry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var held = 0;
+ log.AfterAppend = async () =>
+ {
+ if (Interlocked.Exchange(ref held, 1) != 0) return;
+
+ retryAppended.SetResult();
+ await releaseRetry.Task;
+ };
+ log.Unreachable = false;
+ await retryAppended.Task.WaitAsync(TimeSpan.FromSeconds(10));
+
+ var disposing = announcer.DisposeAsync().AsTask();
+ await Task.Delay(50);
+ await Assert.That(disposing.IsCompleted).IsFalse();
+
+ releaseRetry.SetResult();
+ await disposing.WaitAsync(TimeSpan.FromSeconds(10));
+ await Until(() => announcer.Waiting == 0);
+
+ await Assert.That(log.Appended).IsEquivalentTo(new[] { first, second }, TUnit.Assertions.Enums.CollectionOrdering.Matching);
+ }
+
+ [Test]
+ public async Task Dispose_LogStillUnreachable_DoesNotThrow()
+ {
+ var log = new FlakyLog { Unreachable = true };
+ var announcer = new AuthorityChangeAnnouncer(log, NullLogger.Instance) { RetryDelay = TimeSpan.FromHours(1) };
+ await announcer.AnnounceAsync(AuthorityChange.User(Guid.NewGuid()));
+
+ await announcer.DisposeAsync();
+
+ await Assert.That(log.Appended.Length).IsEqualTo(0);
+ }
+}
diff --git a/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs
new file mode 100644
index 00000000..a006055c
--- /dev/null
+++ b/Common.Tests/ConnectionAuthority/AuthorityChangeReaderTests.cs
@@ -0,0 +1,349 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging.Abstractions;
+using OpenShock.Common.ConnectionAuthority;
+
+namespace OpenShock.Common.Tests.ConnectionAuthority;
+
+public sealed class AuthorityChangeReaderTests
+{
+ /// The log as a list, with the two things that can happen to the real one: trimming and loss.
+ private sealed class FakeLog : IAuthorityChangeLog
+ {
+ private readonly List _entries = [];
+ private long _next = 1;
+
+ public bool Unreachable { get; set; }
+
+ public Task AppendAsync(AuthorityChange change)
+ {
+ _entries.Add(new LogEntry(new LogPosition(_next++, 0), change));
+ return Task.CompletedTask;
+ }
+
+ public void AppendUnreadable() => _entries.Add(new LogEntry(new LogPosition(_next++, 0), Change: null, Unreadable: true));
+
+ public Task MarkAsync()
+ {
+ ThrowIfUnreachable();
+ var position = new LogPosition(_next++, 0);
+ _entries.Add(new LogEntry(position, Change: null));
+ return Task.FromResult(position);
+ }
+
+ public Task OldestAsync()
+ {
+ ThrowIfUnreachable();
+ return Task.FromResult(_entries.Count == 0 ? null : _entries[0].Position);
+ }
+
+ /// Runs once, just before the next read: something that happens to the log between two looks at it.
+ public Action? BeforeNextRead { get; set; }
+
+ public Task> ReadAfterAsync(LogPosition position, int count)
+ {
+ ThrowIfUnreachable();
+
+ var beforeRead = BeforeNextRead;
+ BeforeNextRead = null;
+ beforeRead?.Invoke();
+
+ return Task.FromResult>(_entries.Where(e => e.Position.CompareTo(position) > 0).Take(count).ToArray());
+ }
+
+ public void TrimTo(int keep) => _entries.RemoveRange(0, Math.Max(0, _entries.Count - keep));
+
+ public void Lose() => _entries.Clear();
+
+ private void ThrowIfUnreachable()
+ {
+ if (Unreachable) throw new InvalidOperationException("redis is down");
+ }
+ }
+
+ private sealed class CountingResolver : IGrantResolver
+ {
+ private readonly System.Collections.Concurrent.ConcurrentQueue _checked = new();
+
+ public int Calls;
+
+ /// How often the connection behind was looked up.
+ public int CallsFor(ConnectionHandle handle) => _checked.Count(subject => subject == handle.Subject);
+
+ public Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken)
+ {
+ _checked.Enqueue(subject);
+ Interlocked.Increment(ref Calls);
+ return Task.FromResult(Grant.Empty);
+ }
+ }
+
+ private sealed class FakeConnection : IAuthorizedConnection
+ {
+ public int Closed;
+
+ /// When closing is done. Replace for a connection whose other end takes its time.
+ public Task Closing { get; init; } = Task.CompletedTask;
+
+ public Task CloseAsync()
+ {
+ Interlocked.Increment(ref Closed);
+ return Closing;
+ }
+ }
+
+ private sealed record Setup(FakeLog Log, AuthorityChangeReader Reader, ConnectionAuthorityRegistry Registry, CountingResolver Resolver)
+ {
+ /// A connection that depends on , already checked once.
+ public async Task Connect(Guid tokenId)
+ {
+ var (handle, _) = await Registry.RegisterAsync(new SignalRSubject(new ApiTokenCredential(Guid.NewGuid(), tokenId)), new FakeConnection());
+ return handle;
+ }
+
+ /// Reads the log and waits for the checks that started.
+ public async Task CatchUp(params ConnectionHandle[] handles)
+ {
+ var before = Resolver.Calls;
+ await Reader.CatchUpAsync();
+ foreach (var handle in handles) await handle.WhenIdleAsync();
+ return Resolver.Calls - before;
+ }
+ }
+
+ private static async Task Create(TimeSpan? closeAfterLogUnreachable = null)
+ {
+ var resolver = new CountingResolver();
+ var services = new ServiceCollection();
+ services.AddScoped(_ => resolver);
+ var provider = services.BuildServiceProvider();
+
+ var registry = new ConnectionAuthorityRegistry(
+ provider.GetRequiredService(),
+ Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions { CloseAfterLogUnreachable = closeAfterLogUnreachable ?? TimeSpan.FromHours(1) }),
+ NullLogger.Instance);
+
+ var log = new FakeLog();
+ var reader = new AuthorityChangeReader(log, registry, NullLogger.Instance);
+ await reader.StartAsync();
+
+ return new Setup(log, reader, registry, resolver);
+ }
+
+ [Test]
+ public async Task CatchUp_SignalsWhatWasAnnouncedSinceTheLastTime_Once()
+ {
+ var setup = await Create();
+ var tokenId = Guid.NewGuid();
+ var affected = await setup.Connect(tokenId);
+ var other = await setup.Connect(Guid.NewGuid());
+
+ await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId));
+
+ // Each was looked up once already, when it connected.
+ await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(1);
+ await Assert.That(setup.Resolver.CallsFor(affected)).IsEqualTo(2);
+ await Assert.That(setup.Resolver.CallsFor(other)).IsEqualTo(1);
+
+ await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task Start_SkipsWhatWasAnnouncedBefore()
+ {
+ var setup = await Create();
+ var tokenId = Guid.NewGuid();
+
+ // Announced before this reader started: a connection that registers afterwards was checked then.
+ await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId));
+ var reader = new AuthorityChangeReader(setup.Log, setup.Registry, NullLogger.Instance);
+ await reader.StartAsync();
+ var handle = await setup.Connect(tokenId);
+ var before = setup.Resolver.Calls;
+
+ await reader.CatchUpAsync();
+ await handle.WhenIdleAsync();
+
+ await Assert.That(setup.Resolver.Calls).IsEqualTo(before);
+ }
+
+ /// The case the log exists for: announced while this instance could not be reached.
+ [Test]
+ public async Task CatchUp_AfterTheLogWasUnreachable_ReadsWhatWasAnnouncedMeanwhile()
+ {
+ var setup = await Create();
+ var tokenId = Guid.NewGuid();
+ var handle = await setup.Connect(tokenId);
+
+ setup.Log.Unreachable = true;
+ await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException();
+
+ setup.Log.Unreachable = false;
+ await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId));
+
+ await Assert.That(await setup.CatchUp(handle)).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task CatchUp_LogUnreachableForTooLong_ClosesEveryConnection()
+ {
+ var setup = await Create(closeAfterLogUnreachable: TimeSpan.FromMilliseconds(50));
+ var handle = await setup.Connect(Guid.NewGuid());
+ setup.Log.Unreachable = true;
+
+ // Not yet: a short loss is sat out.
+ await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException();
+ await Assert.That(handle.IsRevoked).IsFalse();
+
+ await Task.Delay(100);
+ await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException();
+
+ await Assert.That(handle.IsRevoked).IsTrue();
+ await Assert.That(setup.Registry.Count).IsEqualTo(0);
+
+ // One that connects while the log is still gone goes the same way at the next read.
+ var later = await setup.Connect(Guid.NewGuid());
+ await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException();
+ await Assert.That(later.IsRevoked).IsTrue();
+ }
+
+ ///
+ /// A connection whose other end stopped reading can take forever to close. Reading the log must not wait for
+ /// it, or the connections that came since would never hear of a change again.
+ ///
+ [Test]
+ public async Task CatchUp_LogUnreachableForTooLong_DoesNotWaitForAConnectionToClose()
+ {
+ var setup = await Create(closeAfterLogUnreachable: TimeSpan.Zero);
+ var neverClosed = new TaskCompletionSource();
+ var stalled = new FakeConnection { Closing = neverClosed.Task };
+ var (handle, _) = await setup.Registry.RegisterAsync(new SignalRSubject(new ApiTokenCredential(Guid.NewGuid(), Guid.NewGuid())), stalled);
+ setup.Log.Unreachable = true;
+
+ await Assert.That(async () => await setup.Reader.CatchUpAsync().WaitAsync(TimeSpan.FromSeconds(10))).Throws();
+
+ await Assert.That(handle.IsRevoked).IsTrue();
+ await Assert.That(stalled.Closed).IsEqualTo(1);
+
+ // And reading carries on once the log is back.
+ setup.Log.Unreachable = false;
+ var tokenId = Guid.NewGuid();
+ var later = await setup.Connect(tokenId);
+ await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId));
+ await Assert.That(await setup.CatchUp(later)).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task CatchUp_LogBackInTime_ClosesNothing_AndTheWaitStartsOver()
+ {
+ var setup = await Create(closeAfterLogUnreachable: TimeSpan.FromMilliseconds(50));
+ var handle = await setup.Connect(Guid.NewGuid());
+
+ setup.Log.Unreachable = true;
+ await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException();
+ setup.Log.Unreachable = false;
+ await setup.Reader.CatchUpAsync();
+
+ // A new loss long after the first one is a new one, not the old one grown past the limit.
+ await Task.Delay(100);
+ setup.Log.Unreachable = true;
+ await Assert.That(async () => await setup.Reader.CatchUpAsync()).ThrowsException();
+
+ await Assert.That(handle.IsRevoked).IsFalse();
+ }
+
+ [Test]
+ public async Task CatchUp_ReadsMoreThanOneBatch()
+ {
+ var setup = await Create();
+ var tokenId = Guid.NewGuid();
+ var handle = await setup.Connect(tokenId);
+
+ for (var i = 0; i < 600; i++) await setup.Log.AppendAsync(AuthorityChange.Device(Guid.NewGuid()));
+ await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId));
+
+ await Assert.That(await setup.CatchUp(handle)).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task CatchUp_TrimmedPastWhereItReadTo_ChecksEveryConnectionAndCarriesOn()
+ {
+ var setup = await Create();
+ var tokenId = Guid.NewGuid();
+ var affected = await setup.Connect(tokenId);
+ var other = await setup.Connect(Guid.NewGuid());
+
+ // So much was announced that what this instance read last is gone, and with it maybe more.
+ for (var i = 0; i < 5; i++) await setup.Log.AppendAsync(AuthorityChange.Device(Guid.NewGuid()));
+ setup.Log.TrimTo(2);
+
+ await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(2);
+
+ // Reading goes on from there.
+ await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId));
+ await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(1);
+ }
+
+ /// The log is trimmed whenever something is appended, also in the middle of being read.
+ [Test]
+ public async Task CatchUp_TrimmedWhileReading_ChecksEveryConnection()
+ {
+ var setup = await Create();
+ var tokenId = Guid.NewGuid();
+ var affected = await setup.Connect(tokenId);
+ var other = await setup.Connect(Guid.NewGuid());
+
+ // The change for this connection is trimmed away just before the read, which then returns only what is
+ // left as if nothing were missing.
+ await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId));
+ for (var i = 0; i < 4; i++) await setup.Log.AppendAsync(AuthorityChange.Device(Guid.NewGuid()));
+ setup.Log.BeforeNextRead = () => setup.Log.TrimTo(2);
+
+ await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(2);
+ await Assert.That(setup.Resolver.CallsFor(affected)).IsEqualTo(2);
+
+ // Reading goes on from there.
+ await setup.Log.AppendAsync(AuthorityChange.ApiToken(tokenId));
+ await Assert.That(await setup.CatchUp(affected, other)).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task CatchUp_LogLost_ChecksEveryConnection()
+ {
+ var setup = await Create();
+ var first = await setup.Connect(Guid.NewGuid());
+ var second = await setup.Connect(Guid.NewGuid());
+
+ // The store restarted without its data.
+ setup.Log.Lose();
+
+ await Assert.That(await setup.CatchUp(first, second)).IsEqualTo(2);
+ await Assert.That(await setup.CatchUp(first, second)).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task CatchUp_UnreadableEntry_ChecksEveryConnection()
+ {
+ var setup = await Create();
+ var first = await setup.Connect(Guid.NewGuid());
+ var second = await setup.Connect(Guid.NewGuid());
+
+ setup.Log.AppendUnreadable();
+
+ await Assert.That(await setup.CatchUp(first, second)).IsEqualTo(2);
+ await Assert.That(await setup.CatchUp(first, second)).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task LogPosition_ParsesAndOrdersStreamIds()
+ {
+ await Assert.That(LogPosition.TryParse("1796499315377-2", out var position)).IsTrue();
+ await Assert.That(position).IsEqualTo(new LogPosition(1796499315377, 2));
+ await Assert.That(position.ToString()).IsEqualTo("1796499315377-2");
+
+ await Assert.That(new LogPosition(5, 0).CompareTo(new LogPosition(4, 9))).IsGreaterThan(0);
+ await Assert.That(new LogPosition(5, 1).CompareTo(new LogPosition(5, 2))).IsLessThan(0);
+
+ await Assert.That(LogPosition.TryParse("not-an-id", out _)).IsFalse();
+ await Assert.That(LogPosition.TryParse(null, out _)).IsFalse();
+ }
+}
diff --git a/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs
new file mode 100644
index 00000000..0f18bfef
--- /dev/null
+++ b/Common.Tests/ConnectionAuthority/ConnectionAuthorityRegistryTests.cs
@@ -0,0 +1,803 @@
+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;
+
+ /// When closing is done. Replace for a connection whose other end takes its time.
+ public Task Closing { get; set; } = Task.CompletedTask;
+
+ public bool TryApplyGrant(Grant grant)
+ {
+ LastApplied = grant;
+ return AcceptGrants;
+ }
+
+ public Task CloseAsync()
+ {
+ Interlocked.Increment(ref Closed);
+ return Closing;
+ }
+ }
+
+ /// Elapsed time that only passes when a test says so.
+ private sealed class ManualTime : TimeProvider
+ {
+ private long _timestamp = TimeSpan.TicksPerHour;
+
+ public override long TimestampFrequency => TimeSpan.TicksPerSecond;
+
+ public override long GetTimestamp() => Interlocked.Read(ref _timestamp);
+
+ public void Advance(TimeSpan by) => Interlocked.Add(ref _timestamp, by.Ticks);
+ }
+
+ private static (ConnectionAuthorityRegistry Registry, FakeResolver Resolver) Create(TimeSpan? interval = null, TimeSpan? liveControlInterval = null, TimeSpan? closeAfterChangeUnchecked = null, TimeProvider? time = null)
+ {
+ var resolver = new FakeResolver();
+ var services = new ServiceCollection();
+ services.AddScoped(_ => resolver);
+ var provider = services.BuildServiceProvider();
+
+ var options = Microsoft.Extensions.Options.Options.Create(new ConnectionAuthorityOptions
+ {
+ Interval = interval ?? TimeSpan.FromMinutes(1),
+ LiveControlInterval = liveControlInterval ?? interval ?? TimeSpan.FromMinutes(1),
+ CloseAfterChangeUnchecked = closeAfterChangeUnchecked ?? TimeSpan.FromHours(1)
+ });
+ var registry = new ConnectionAuthorityRegistry(provider.GetRequiredService(), options, NullLogger.Instance)
+ {
+ Time = time ?? TimeProvider.System
+ };
+ return (registry, resolver);
+ }
+
+ private static LiveControlSubject LiveControl(Guid? userId = null, Guid? tokenId = null, Guid? deviceId = null, Guid? ownerId = null) => new(
+ new ApiTokenCredential(userId ?? Guid.NewGuid(), tokenId ?? Guid.NewGuid()),
+ deviceId ?? Guid.NewGuid(),
+ ownerId ?? Guid.NewGuid());
+
+ private static SignalRSubject SignalR(Guid? tokenId = null) => new(new ApiTokenCredential(Guid.NewGuid(), tokenId ?? Guid.NewGuid()));
+
+ private static SignalRSubject OnPublicShare(ConnectionHandle handle, Guid publicShareId) =>
+ (SignalRSubject)handle.Subject with { PublicShare = new PublicShareAccess(publicShareId, Guid.NewGuid(), PasswordStamp: null) };
+
+ private static Guid? PublicShareOf(ConnectionSubject? subject) => (subject as SignalRSubject)?.PublicShare?.PublicShareId;
+
+ /// Signals only start a look; this waits for it (and any rerun) to finish.
+ private static Task Settle(ConnectionHandle handle) => handle.WhenIdleAsync();
+
+ [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(AuthorityChange.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(AuthorityChange.User(userId));
+ registry.Signal(AuthorityChange.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 SignalRSubject(new SessionCredential(Guid.NewGuid(), "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(AuthorityChange.Device(deviceId));
+ releaseStaleRead.SetResult();
+ await first;
+
+ await Assert.That(reads).IsEqualTo(2);
+ await Assert.That(handle.Grant).IsSameReferenceAs(current);
+ }
+
+ ///
+ /// The change is counted before its check is requested, and the running check can finish in between. Whoever
+ /// waits for that check must not be told the connection is good on what it read before the change.
+ ///
+ [Test]
+ public async Task Invalidate_DuringARunningLook_IsNotAnsweredFromThatLook()
+ {
+ var (registry, resolver) = Create();
+ var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection());
+
+ var stale = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(1) };
+ var current = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(2) };
+ var staleReadStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var releaseStaleRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ var reads = 0;
+ resolver.Resolve = async _ =>
+ {
+ if (Interlocked.Increment(ref reads) > 1) return current;
+
+ staleReadStarted.SetResult();
+ await releaseStaleRead.Task;
+ return stale;
+ };
+
+ var waiting = handle.RefreshAsync();
+ await staleReadStarted.Task;
+
+ handle.Invalidate();
+ releaseStaleRead.SetResult();
+
+ await Assert.That(await waiting).IsEqualTo(RefreshResult.Valid);
+ await Assert.That(reads).IsEqualTo(2);
+ await Assert.That(handle.Grant).IsSameReferenceAs(current);
+ }
+
+ [Test]
+ public async Task EnsureFresh_GrantExpiredSinceTheLastLook_LooksAgain()
+ {
+ var (registry, resolver) = Create();
+ resolver.Resolve = _ => Task.FromResult(new Grant { ExpiresAt = DateTime.UtcNow.AddSeconds(-1) });
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(SignalR(), connection);
+ var callsAfterRegister = resolver.Calls;
+
+ // Checked a moment ago, but what that granted has ended since. The lookup cannot be made right now.
+ resolver.Resolve = _ => throw new InvalidOperationException("database is down");
+ await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Failed);
+ await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1);
+
+ // And once it can, the token is found expired.
+ resolver.Resolve = _ => Task.FromResult(null);
+ await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Revoked);
+ await Assert.That(connection.Closed).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task EnsureFresh_LooksAgainOnlyOnceTheLastLookIsTooOld()
+ {
+ 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(SignalR(), new FakeConnection());
+ var callsAfterRegister = resolver.Calls;
+
+ var publicShareId = Guid.NewGuid();
+ handle.UpdateSubject(OnPublicShare(handle, publicShareId));
+ await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1));
+
+ await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1);
+ await Assert.That(PublicShareOf(handle.Subject)).IsEqualTo(publicShareId);
+ }
+
+ [Test]
+ public async Task Track_DoesNotLookUntilUsed()
+ {
+ var (registry, resolver) = Create();
+
+ var handle = registry.Track(new SignalRSubject(Credential: null, new PublicShareAccess(Guid.NewGuid(), Guid.NewGuid(), PasswordStamp: null)), new FakeConnection());
+
+ await Assert.That(resolver.Calls).IsEqualTo(0);
+ await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsFalse();
+ }
+
+ ///
+ /// A connection gets its second subject while a check of the first is still running. That check must not make
+ /// the new subject count as checked: whoever waits for it gets the answer of a check of the new subject.
+ ///
+ [Test]
+ public async Task UpdateSubject_DuringARunningCheck_IsNotAnsweredUntilTheNewSubjectIsChecked()
+ {
+ var (registry, resolver) = Create();
+ var (handle, _) = await registry.RegisterAsync(SignalR(), new FakeConnection());
+
+ var checkStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var releaseCheck = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var checkedSubjects = new List();
+ resolver.Resolve = async subject =>
+ {
+ lock (checkedSubjects) checkedSubjects.Add(subject);
+ checkStarted.TrySetResult();
+ await releaseCheck.Task;
+ return Grant.Empty;
+ };
+
+ var running = handle.RefreshAsync();
+ await checkStarted.Task;
+
+ var publicShareId = Guid.NewGuid();
+ handle.UpdateSubject(OnPublicShare(handle, publicShareId));
+
+ // The check of the old subject is still running, and says nothing about the new one.
+ await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsFalse();
+ await Assert.That(handle.Grant).IsNull();
+
+ releaseCheck.SetResult();
+
+ await Assert.That(await running).IsEqualTo(RefreshResult.Valid);
+ await Assert.That(checkedSubjects.Count).IsEqualTo(2);
+ await Assert.That(PublicShareOf(checkedSubjects[0])).IsNull();
+ await Assert.That(PublicShareOf(checkedSubjects[1])).IsEqualTo(publicShareId);
+ await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsTrue();
+ await Assert.That(handle.Grant).IsNotNull();
+ }
+
+ [Test]
+ public async Task Signal_CheckFails_NothingIsGrantedUntilACheckSucceeds()
+ {
+ var (registry, resolver) = Create();
+ var tokenId = Guid.NewGuid();
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(LiveControl(tokenId: tokenId), connection);
+
+ resolver.Resolve = _ => throw new InvalidOperationException("database is down");
+ registry.Signal(AuthorityChange.ApiToken(tokenId));
+ await Settle(handle);
+
+ await Assert.That(handle.IsRevoked).IsFalse();
+ await Assert.That(connection.Closed).IsEqualTo(0);
+ await Assert.That(handle.Grant).IsNull();
+ await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsFalse();
+ await Assert.That(await handle.EnsureFreshAsync(TimeSpan.FromMinutes(1))).IsEqualTo(RefreshResult.Failed);
+
+ // The database is back, and the token is indeed gone. Nothing announces it a second time.
+ resolver.Resolve = _ => Task.FromResult(null);
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(handle);
+
+ await Assert.That(handle.IsRevoked).IsTrue();
+ await Assert.That(connection.Closed).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task Signal_CheckFails_ThenSucceeds_GrantsAgain()
+ {
+ var (registry, resolver) = Create();
+ var tokenId = Guid.NewGuid();
+ var (handle, _) = await registry.RegisterAsync(LiveControl(tokenId: tokenId), new FakeConnection());
+
+ resolver.Resolve = _ => throw new InvalidOperationException("database is down");
+ registry.Signal(AuthorityChange.ApiToken(tokenId));
+ await Settle(handle);
+ await Assert.That(handle.Grant).IsNull();
+
+ var paused = new Grant { ExpiresAt = DateTime.UtcNow.AddHours(1) };
+ resolver.Resolve = _ => Task.FromResult(paused);
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(handle);
+
+ await Assert.That(handle.Grant).IsSameReferenceAs(paused);
+ await Assert.That(handle.WasCheckedWithin(TimeSpan.FromMinutes(1))).IsTrue();
+ }
+
+ ///
+ /// Such a connection may do nothing, but is still sent what is pushed to its user or public share. That is not
+ /// put up with for longer than the limit.
+ ///
+ [Test]
+ public async Task Sweep_ChangeStillUncheckedAfterTheLimit_Closes()
+ {
+ var time = new ManualTime();
+ var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromSeconds(15), time: time);
+ var tokenId = Guid.NewGuid();
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection);
+ var other = new FakeConnection();
+ await registry.RegisterAsync(SignalR(), other);
+
+ resolver.Resolve = _ => throw new InvalidOperationException("database is down");
+ registry.Signal(AuthorityChange.ApiToken(tokenId));
+ await Settle(handle);
+
+ // Within the limit it stays, and is checked again.
+ time.Advance(TimeSpan.FromSeconds(14));
+ var callsBefore = resolver.Calls;
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(handle);
+ await Assert.That(resolver.Calls).IsEqualTo(callsBefore + 1);
+ await Assert.That(connection.Closed).IsEqualTo(0);
+
+ time.Advance(TimeSpan.FromSeconds(1));
+ registry.Sweep(DateTime.UtcNow);
+
+ await Assert.That(handle.IsRevoked).IsTrue();
+ await Assert.That(connection.Closed).IsEqualTo(1);
+ await Assert.That(other.Closed).IsEqualTo(0);
+ await Assert.That(registry.Count).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task Sweep_ChangeCheckedWithinTheLimit_Stays()
+ {
+ var time = new ManualTime();
+ var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromSeconds(15), time: time);
+ var tokenId = Guid.NewGuid();
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection);
+
+ resolver.Resolve = _ => throw new InvalidOperationException("database is down");
+ registry.Signal(AuthorityChange.ApiToken(tokenId));
+ await Settle(handle);
+
+ time.Advance(TimeSpan.FromSeconds(14));
+ resolver.Resolve = _ => Task.FromResult(Grant.Empty);
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(handle);
+
+ time.Advance(TimeSpan.FromMinutes(1));
+ registry.Sweep(DateTime.UtcNow);
+
+ await Assert.That(connection.Closed).IsEqualTo(0);
+ await Assert.That(handle.Grant).IsNotNull();
+ }
+
+ ///
+ /// The limit is acted on as things are when the connection would be closed. A check that got through after
+ /// the limit, but before the sweep came by, has settled the change.
+ ///
+ [Test]
+ public async Task Sweep_ChangeCheckedAfterTheLimitButBeforeTheSweep_Stays()
+ {
+ var time = new ManualTime();
+ var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromSeconds(15), time: time);
+ var tokenId = Guid.NewGuid();
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection);
+
+ resolver.Resolve = _ => throw new InvalidOperationException("database is down");
+ registry.Signal(AuthorityChange.ApiToken(tokenId));
+ await Settle(handle);
+
+ time.Advance(TimeSpan.FromSeconds(20));
+ resolver.Resolve = _ => Task.FromResult(Grant.Empty);
+ await Assert.That(await handle.RefreshAsync()).IsEqualTo(RefreshResult.Valid);
+
+ registry.Sweep(DateTime.UtcNow);
+
+ await Assert.That(handle.IsRevoked).IsFalse();
+ await Assert.That(connection.Closed).IsEqualTo(0);
+ await Assert.That(registry.Count).IsEqualTo(1);
+ }
+
+ ///
+ /// A change announced while an older check runs is not covered by it. When that check succeeds, the newer
+ /// change has still waited since it was announced, not since the check finished.
+ ///
+ [Test]
+ public async Task Sweep_ChangeAnnouncedDuringACheckThatSucceeds_KeepsItsOwnLimit()
+ {
+ var time = new ManualTime();
+ var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.FromSeconds(15), time: time);
+ var tokenId = Guid.NewGuid();
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection);
+
+ // The check of the first change takes a while and then succeeds. Every check after it fails.
+ var firstCheckStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var releaseFirstCheck = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var checks = 0;
+ resolver.Resolve = async _ =>
+ {
+ if (Interlocked.Increment(ref checks) > 1) throw new InvalidOperationException("database is down");
+
+ firstCheckStarted.SetResult();
+ await releaseFirstCheck.Task;
+ return Grant.Empty;
+ };
+
+ registry.Signal(AuthorityChange.ApiToken(tokenId));
+ await firstCheckStarted.Task;
+
+ // The second change, 5 seconds in. The first check finishes at 14 seconds, and the one for the second
+ // change that follows it fails.
+ time.Advance(TimeSpan.FromSeconds(5));
+ registry.Signal(AuthorityChange.ApiToken(tokenId));
+ time.Advance(TimeSpan.FromSeconds(9));
+ releaseFirstCheck.SetResult();
+ await Settle(handle);
+ await Assert.That(handle.Grant).IsNull();
+
+ // At 19 seconds the second change has gone unchecked for 14.
+ time.Advance(TimeSpan.FromSeconds(5));
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(handle);
+ await Assert.That(connection.Closed).IsEqualTo(0);
+
+ // At 20 seconds for 15, though the first check succeeded only 6 seconds ago.
+ time.Advance(TimeSpan.FromSeconds(1));
+ registry.Sweep(DateTime.UtcNow);
+
+ await Assert.That(handle.IsRevoked).IsTrue();
+ await Assert.That(connection.Closed).IsEqualTo(1);
+ }
+
+ /// An outage alone drops nobody: without a change announced for it, a connection keeps what it had.
+ [Test]
+ public async Task Sweep_CheckFailsWithNoChangeAnnounced_NeverCloses()
+ {
+ var (registry, resolver) = Create(interval: TimeSpan.Zero, closeAfterChangeUnchecked: TimeSpan.Zero);
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(SignalR(), connection);
+
+ resolver.Resolve = _ => throw new InvalidOperationException("database is down");
+ for (var i = 0; i < 3; i++)
+ {
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(handle);
+ }
+
+ await Assert.That(connection.Closed).IsEqualTo(0);
+ await Assert.That(handle.Grant).IsNotNull();
+ }
+
+ /// A check that has not had its turn yet is not a check that failed.
+ [Test]
+ public async Task Sweep_ChangeNotCheckedYet_DoesNotClose()
+ {
+ var (registry, resolver) = Create(closeAfterChangeUnchecked: TimeSpan.Zero);
+ var tokenId = Guid.NewGuid();
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(SignalR(tokenId), connection);
+
+ var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ resolver.Resolve = async _ =>
+ {
+ await release.Task;
+ return Grant.Empty;
+ };
+ registry.Signal(AuthorityChange.ApiToken(tokenId));
+ registry.Sweep(DateTime.UtcNow);
+
+ await Assert.That(connection.Closed).IsEqualTo(0);
+
+ release.SetResult();
+ await Settle(handle);
+ await Assert.That(handle.Grant).IsNotNull();
+ }
+
+ [Test]
+ public async Task Sweep_ChecksEveryDueConnection_IdleHubConnectionsIncluded()
+ {
+ var (registry, resolver) = Create(interval: TimeSpan.Zero);
+ var (liveControl, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection());
+ var (signalR, _) = await registry.RegisterAsync(SignalR(), new FakeConnection());
+ var callsAfterRegister = resolver.Calls;
+
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(liveControl);
+ await Settle(signalR);
+
+ await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 2);
+ }
+
+ [Test]
+ public async Task Sweep_ChecksLiveControlOnItsOwnShorterInterval()
+ {
+ var (registry, resolver) = Create(interval: TimeSpan.FromHours(1), liveControlInterval: TimeSpan.FromMilliseconds(1));
+ var (liveControl, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection());
+ var (signalR, _) = await registry.RegisterAsync(SignalR(), new FakeConnection());
+ var callsAfterRegister = resolver.Calls;
+ await Task.Delay(20);
+
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(liveControl);
+ await Settle(signalR);
+
+ // Only the live control connection was due.
+ await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister + 1);
+ }
+
+ [Test]
+ public async Task Sweep_LeavesARecentlyCheckedConnectionAlone()
+ {
+ var (registry, resolver) = Create();
+ var (handle, _) = await registry.RegisterAsync(LiveControl(), new FakeConnection());
+ var callsAfterRegister = resolver.Calls;
+
+ registry.Sweep(DateTime.UtcNow);
+ await Settle(handle);
+
+ await Assert.That(resolver.Calls).IsEqualTo(callsAfterRegister);
+ }
+
+ [Test]
+ 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(SignalR(), 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_ChecksEveryConnection()
+ {
+ var (registry, resolver) = Create();
+ var liveControlConnection = new FakeConnection();
+ var signalRConnection = new FakeConnection();
+ var (liveControl, _) = await registry.RegisterAsync(LiveControl(), liveControlConnection);
+ var (signalR, _) = await registry.RegisterAsync(SignalR(), signalRConnection);
+
+ // 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(signalR.IsRevoked).IsTrue();
+ await Assert.That(signalRConnection.Closed).IsEqualTo(1);
+ }
+
+ ///
+ /// A check that started during the outage may have read before a change nobody heard. It must not count as
+ /// the check the reconnect asks for.
+ ///
+ [Test]
+ public async Task SignalAll_DuringARunningCheck_ChecksAgain()
+ {
+ var (registry, resolver) = Create();
+ var connection = new FakeConnection();
+ var (handle, _) = await registry.RegisterAsync(LiveControl(), connection);
+
+ var staleReadStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var releaseStaleRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var reads = 0;
+ resolver.Resolve = async _ =>
+ {
+ if (Interlocked.Increment(ref reads) > 1) return null;
+
+ staleReadStarted.SetResult();
+ await releaseStaleRead.Task;
+ return Grant.Empty;
+ };
+
+ var running = handle.RefreshAsync();
+ await staleReadStarted.Task;
+
+ registry.SignalAll();
+ releaseStaleRead.SetResult();
+ await running;
+
+ await Assert.That(reads).IsEqualTo(2);
+ await Assert.That(handle.IsRevoked).IsTrue();
+ await Assert.That(connection.Closed).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task CloseAll_RevokesEveryConnection_WithoutWaitingForThemToClose()
+ {
+ var (registry, _) = Create();
+ var neverClosed = new TaskCompletionSource();
+ var stalled = new FakeConnection { Closing = neverClosed.Task };
+ var other = new FakeConnection();
+ var (stalledHandle, _) = await registry.RegisterAsync(SignalR(), stalled);
+ var (otherHandle, _) = await registry.RegisterAsync(LiveControl(), other);
+
+ registry.CloseAll();
+
+ await Assert.That(stalledHandle.IsRevoked).IsTrue();
+ await Assert.That(otherHandle.IsRevoked).IsTrue();
+ await Assert.That(stalled.Closed).IsEqualTo(1);
+ await Assert.That(other.Closed).IsEqualTo(1);
+ await Assert.That(registry.Count).IsEqualTo(0);
+ }
+
+ /// A check that finds the connection good does not undo a close that happened while it ran.
+ [Test]
+ public async Task Register_ClosedWhileTheFirstCheckRuns_IsRevoked()
+ {
+ var (registry, resolver) = Create();
+ var checkStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var releaseCheck = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ resolver.Resolve = async _ =>
+ {
+ checkStarted.SetResult();
+ await releaseCheck.Task;
+ return Grant.Empty;
+ };
+ var connection = new FakeConnection();
+
+ var registering = registry.RegisterAsync(LiveControl(), connection);
+ await checkStarted.Task;
+
+ registry.CloseAll();
+ releaseCheck.SetResult();
+ var (handle, result) = await registering;
+
+ await Assert.That(result).IsEqualTo(RefreshResult.Revoked);
+ await Assert.That(handle.IsRevoked).IsTrue();
+ await Assert.That(handle.Grant).IsNull();
+ await Assert.That(connection.Closed).IsEqualTo(1);
+ await Assert.That(registry.Count).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task Dispose_StopsTrackingWithoutClosing()
+ {
+ 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..29746fc4
--- /dev/null
+++ b/Common.Tests/ConnectionAuthority/ConnectionSubjectTests.cs
@@ -0,0 +1,134 @@
+using MessagePack;
+using OpenShock.Common.ConnectionAuthority;
+using OpenShock.Common.Constants;
+
+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 ApiTokenCredential ByToken = new(User, Token);
+
+ private static readonly LiveControlSubject LiveControl = new(ByToken, Device, Owner);
+
+ private static readonly SignalRSubject OnPublicShare = new(ByToken, new PublicShareAccess(Share, ShareOwner, PasswordStamp: null));
+
+ private static readonly HubSocketSubject HubSocket = new(Device, Owner, "hub-token");
+
+ [Test]
+ public async Task UserChange_AffectsTheUserTheHubOwnerAndTheShareOwner()
+ {
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.User(User))).IsTrue();
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.User(Owner))).IsTrue();
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.User(Guid.NewGuid()))).IsFalse();
+
+ await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.User(User))).IsTrue();
+ await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.User(ShareOwner))).IsTrue();
+ await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.User(Owner))).IsFalse();
+
+ await Assert.That(HubSocket.IsAffectedBy(AuthorityChange.User(Owner))).IsTrue();
+ await Assert.That(HubSocket.IsAffectedBy(AuthorityChange.User(User))).IsFalse();
+ }
+
+ [Test]
+ public async Task OtherChanges_AffectOnlyTheirOwnKindOfId()
+ {
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.ApiToken(Token))).IsTrue();
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.Device(Device))).IsTrue();
+ await Assert.That(HubSocket.IsAffectedBy(AuthorityChange.Device(Device))).IsTrue();
+ await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.ApiToken(Token))).IsTrue();
+ await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.PublicShare(Share))).IsTrue();
+
+ // The same id under another kind is a different thing.
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.Device(Token))).IsFalse();
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.ApiToken(Device))).IsFalse();
+ await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.PublicShare(User))).IsFalse();
+
+ // And a kind of connection is not affected by what it does not depend on.
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.PublicShare(Share))).IsFalse();
+ await Assert.That(HubSocket.IsAffectedBy(AuthorityChange.ApiToken(Token))).IsFalse();
+ await Assert.That(OnPublicShare.IsAffectedBy(AuthorityChange.Device(Device))).IsFalse();
+ }
+
+ [Test]
+ public async Task SessionChange_AffectsOnlyConnectionsOfThatSession()
+ {
+ var credential = new SessionCredential(User, new string('t', AuthConstants.GeneratedTokenLength));
+ var session = new SignalRSubject(credential);
+ var storedId = SessionIds.FromToken(credential.SessionToken);
+
+ // A session is stored under the hash of its token, and that is what a change names.
+ await Assert.That(storedId).IsNotEqualTo(credential.SessionToken);
+ await Assert.That(credential.SessionId).IsEqualTo(storedId);
+ await Assert.That(session.IsAffectedBy(AuthorityChange.Session(storedId))).IsTrue();
+ await Assert.That(session.IsAffectedBy(AuthorityChange.Session("another-id"))).IsFalse();
+
+ // A token connection has no session.
+ await Assert.That(LiveControl.IsAffectedBy(AuthorityChange.Session(storedId))).IsFalse();
+ }
+
+ public static IEnumerable> EveryKindOfChange()
+ {
+ yield return () => AuthorityChange.User(Guid.NewGuid());
+ yield return () => AuthorityChange.Session("stored-id");
+ yield return () => AuthorityChange.ApiToken(Guid.NewGuid());
+ yield return () => AuthorityChange.Device(Guid.NewGuid());
+ yield return () => AuthorityChange.PublicShare(Guid.NewGuid());
+ }
+
+ [Test]
+ [MethodDataSource(nameof(EveryKindOfChange))]
+ public async Task Change_SurvivesTheTripOverRedis(AuthorityChange change)
+ {
+ var bytes = MessagePackSerializer.Serialize(change);
+ var received = MessagePackSerializer.Deserialize(bytes);
+
+ await Assert.That(received).IsEqualTo(change);
+ await Assert.That(received.GetType()).IsEqualTo(change.GetType());
+ }
+
+ [Test]
+ public async Task SessionChange_DoesNotPrintTheSessionId()
+ {
+ await Assert.That(AuthorityChange.Session("stored-id").ToString()).DoesNotContain("stored-id");
+ }
+
+ [Test]
+ public async Task Guest_IsNotAffectedByAnEmptyId()
+ {
+ var guest = new SignalRSubject(Credential: null, new PublicShareAccess(Share, ShareOwner, PasswordStamp: null));
+
+ await Assert.That(guest.IsAffectedBy(AuthorityChange.User(Guid.Empty))).IsFalse();
+ await Assert.That(guest.IsAffectedBy(AuthorityChange.User(ShareOwner))).IsTrue();
+ }
+
+ [Test]
+ public async Task ToString_LeavesOutTheCredentials()
+ {
+ var session = new SessionCredential(User, "secret-session-token");
+ ConnectionSubject[] subjects =
+ [
+ new SignalRSubject(session),
+ new LiveControlSubject(session, Device, Owner),
+ new HubSocketSubject(Device, Owner, "secret-hub-token")
+ ];
+
+ foreach (var subject in subjects)
+ {
+ var text = subject.ToString();
+
+ await Assert.That(text).DoesNotContain("secret-session-token");
+ await Assert.That(text).DoesNotContain("secret-hub-token");
+ await Assert.That(text).DoesNotContain(session.SessionId);
+ }
+
+ await Assert.That(session.ToString()).DoesNotContain("secret-session-token");
+ await Assert.That(subjects[2].ToString()).Contains(Device.ToString());
+ }
+}
diff --git a/Common.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/Common.csproj b/Common/Common.csproj
index 40e10d9f..2ed9f7e1 100644
--- a/Common/Common.csproj
+++ b/Common/Common.csproj
@@ -9,6 +9,10 @@
false
+
+
+
+
diff --git a/Common/ConnectionAuthority/AuthorityChange.cs b/Common/ConnectionAuthority/AuthorityChange.cs
new file mode 100644
index 00000000..cebd9199
--- /dev/null
+++ b/Common/ConnectionAuthority/AuthorityChange.cs
@@ -0,0 +1,55 @@
+using MessagePack;
+
+namespace OpenShock.Common.ConnectionAuthority;
+
+///
+/// Something a connection's authority can depend on has changed. Names what changed and nothing more, on
+/// purpose: the affected connections look up what they may do now, so a change cannot be applied out of order or
+/// half-described.
+///
+///
+/// Travels over Redis between services as it is, see
+/// . The union keys are the wire
+/// format: add new cases with new keys and leave the existing ones alone.
+///
+[Union(0, typeof(UserChanged))]
+[Union(1, typeof(SessionChanged))]
+[Union(2, typeof(ApiTokenChanged))]
+[Union(3, typeof(DeviceChanged))]
+[Union(4, typeof(PublicShareChanged))]
+public closed record AuthorityChange
+{
+ public static AuthorityChange User(Guid userId) => new UserChanged(userId);
+
+ /// The id the session is stored under, see .
+ public static AuthorityChange Session(string sessionId) => new SessionChanged(sessionId);
+
+ public static AuthorityChange ApiToken(Guid tokenId) => new ApiTokenChanged(tokenId);
+ public static AuthorityChange Device(Guid deviceId) => new DeviceChanged(deviceId);
+ public static AuthorityChange PublicShare(Guid publicShareId) => new PublicShareChanged(publicShareId);
+}
+
+/// An account was deactivated, deleted or otherwise may no longer be used.
+[MessagePackObject]
+public sealed record UserChanged([property: Key(0)] Guid UserId) : AuthorityChange;
+
+/// A login session was deleted or expired.
+/// The id the session is stored under.
+[MessagePackObject]
+public sealed record SessionChanged([property: Key(0)] string SessionId) : AuthorityChange
+{
+ /// Written out by hand to keep the session's id out of a log.
+ public override string ToString() => nameof(SessionChanged);
+}
+
+/// An API token was edited, paused or deleted.
+[MessagePackObject]
+public sealed record ApiTokenChanged([property: Key(0)] Guid TokenId) : AuthorityChange;
+
+/// A hub was deleted or got a new token, or its shockers or the shares on them changed.
+[MessagePackObject]
+public sealed record DeviceChanged([property: Key(0)] Guid DeviceId) : AuthorityChange;
+
+/// Who may use a public share changed.
+[MessagePackObject]
+public sealed record PublicShareChanged([property: Key(0)] Guid PublicShareId) : AuthorityChange;
diff --git a/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs
new file mode 100644
index 00000000..4c734b5f
--- /dev/null
+++ b/Common/ConnectionAuthority/AuthorityChangeAnnouncer.cs
@@ -0,0 +1,132 @@
+using System.Collections.Concurrent;
+
+namespace OpenShock.Common.ConnectionAuthority;
+
+///
+/// Gets a change in authority into the , now or as soon as the log can be
+/// reached again.
+///
+///
+/// The change itself is already saved when it is announced, so the caller is never made to fail or wait for
+/// this. A change that cannot be logged is kept here and tried again until it can. The order they end up in does
+/// not matter: a change only names what to look at again.
+///
+/// What is kept is tried once more when the service shuts down, and is lost if that fails too or the process
+/// just ends. The connections it affects then find out at their next periodic check, see
+/// .
+///
+///
+public sealed class AuthorityChangeAnnouncer : IAsyncDisposable
+{
+ /// More than this waiting means Redis has been gone for long; newer ones are left to the periodic check.
+ private const int MaxWaiting = 10_000;
+
+ private readonly IAuthorityChangeLog _log;
+ private readonly ILogger _logger;
+
+ private readonly ConcurrentQueue _waiting = new();
+ private int _retrying;
+
+ ///
+ /// Held by whoever takes changes out of . Anyone may add to it at any time, but with
+ /// two taking from it at once, one would remove a change the other had not logged yet.
+ ///
+ private readonly SemaphoreSlim _logging = new(1, 1);
+
+ public AuthorityChangeAnnouncer(IAuthorityChangeLog log, ILogger logger)
+ {
+ _log = log;
+ _logger = logger;
+ }
+
+ /// How long to wait between attempts to log what is waiting.
+ internal TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(2);
+
+ /// How many changes are waiting to be logged.
+ internal int Waiting => _waiting.Count;
+
+ /// Whether something is running that tries what is waiting again.
+ internal bool IsRetrying => Volatile.Read(ref _retrying) != 0;
+
+ /// Never throws.
+ public async Task AnnounceAsync(AuthorityChange change)
+ {
+ try
+ {
+ await _log.AppendAsync(change);
+ }
+ catch (Exception e)
+ {
+ if (_waiting.Count >= MaxWaiting)
+ {
+ _logger.LogError(e, "Failed to announce a change in authority ({Change}) and too many are waiting already; open connections find out at their next periodic check", change);
+ return;
+ }
+
+ _logger.LogWarning(e, "Failed to announce a change in authority ({Change}); trying again until it can be", change);
+ _waiting.Enqueue(change);
+
+ if (Interlocked.CompareExchange(ref _retrying, 1, 0) == 0) _ = Task.Run(RetryAsync);
+ }
+ }
+
+ private async Task RetryAsync()
+ {
+ while (true)
+ {
+ await Task.Delay(RetryDelay);
+
+ try
+ {
+ await LogWaitingAsync();
+ }
+ catch (Exception e)
+ {
+ _logger.LogDebug(e, "Still cannot announce {Count} change(s) in authority", _waiting.Count);
+ continue;
+ }
+
+ // One may have been added between the last look and here; whoever added it saw this still running.
+ Volatile.Write(ref _retrying, 0);
+ if (_waiting.IsEmpty || Interlocked.CompareExchange(ref _retrying, 1, 0) != 0) return;
+ }
+ }
+
+ ///
+ /// Logs what is waiting, oldest first, until nothing is or one cannot be. A change leaves the queue only
+ /// after it was logged, so one that could not be is still there for the next attempt.
+ ///
+ private async Task LogWaitingAsync()
+ {
+ await _logging.WaitAsync();
+ try
+ {
+ // Only the holder removes, and additions go to the other end, so what is removed is what was logged.
+ while (_waiting.TryPeek(out var change))
+ {
+ await _log.AppendAsync(change);
+ _waiting.TryDequeue(out _);
+ }
+ }
+ finally
+ {
+ _logging.Release();
+ }
+ }
+
+ ///
+ /// A last attempt at what is still waiting, when the service shuts down. Waits for the retry if that is in
+ /// the middle of an attempt, and then tries whatever it left.
+ ///
+ public async ValueTask DisposeAsync()
+ {
+ try
+ {
+ await LogWaitingAsync();
+ }
+ catch (Exception e)
+ {
+ _logger.LogWarning(e, "Shutting down with {Count} change(s) in authority that could not be announced; open connections find out at their next periodic check", _waiting.Count);
+ }
+ }
+}
diff --git a/Common/ConnectionAuthority/AuthorityChangeReader.cs b/Common/ConnectionAuthority/AuthorityChangeReader.cs
new file mode 100644
index 00000000..cad37c13
--- /dev/null
+++ b/Common/ConnectionAuthority/AuthorityChangeReader.cs
@@ -0,0 +1,106 @@
+using System.Diagnostics;
+
+namespace OpenShock.Common.ConnectionAuthority;
+
+///
+/// Reads the on from where this instance got to and signals each change to the
+/// .
+///
+///
+/// It starts at a mark it puts at the end of the log. Changes from before that need no reading: a connection is
+/// checked when it registers. While the mark, or whatever was read last, is still in the log, nothing after it
+/// was trimmed away and reading on misses nothing. Once it is not (this instance fell too far behind, or the log
+/// was lost with the store), what was missed is unknown, so every connection is checked and reading starts over
+/// from a new mark.
+///
+/// While the log cannot be reached at all, nothing here can learn that a connection should end. That is put up
+/// with for ; after it every connection is closed,
+/// and again at each failed read for those that came since.
+///
+///
+public sealed class AuthorityChangeReader
+{
+ private const int BatchSize = 256;
+
+ private readonly IAuthorityChangeLog _log;
+ private readonly ConnectionAuthorityRegistry _registry;
+ private readonly ILogger _logger;
+
+ private LogPosition _position;
+
+ /// When reading first failed, while it still does.
+ private long? _unreachableSince;
+
+ public AuthorityChangeReader(IAuthorityChangeLog log, ConnectionAuthorityRegistry registry, ILogger logger)
+ {
+ _log = log;
+ _registry = registry;
+ _logger = logger;
+ }
+
+ /// Decide where reading starts. Call once, before any connection is tracked.
+ public async Task StartAsync() => _position = await _log.MarkAsync();
+
+ ///
+ /// Signal everything announced since the last call. Not safe to call concurrently. Throws when the log cannot
+ /// be reached; calling again later carries on from the same place.
+ ///
+ public async Task CatchUpAsync()
+ {
+ try
+ {
+ await ReadOnAsync();
+ _unreachableSince = null;
+ }
+ catch
+ {
+ _unreachableSince ??= Stopwatch.GetTimestamp();
+
+ if (Stopwatch.GetElapsedTime(_unreachableSince.Value) >= _registry.CloseAfterLogUnreachable)
+ {
+ // Does not wait for the connections to be gone: reading must go on whatever they do.
+ _registry.CloseAll();
+ }
+
+ throw;
+ }
+ }
+
+ private async Task ReadOnAsync()
+ {
+ IReadOnlyList entries;
+ do
+ {
+ entries = await _log.ReadAfterAsync(_position, BatchSize);
+
+ // Looked at after the read, every time, so it holds for what was just read: the log can be trimmed
+ // at any moment, and only while the entry read last is still in it is nothing missing in between.
+ var oldest = await _log.OldestAsync();
+ if (oldest is not { } oldestPosition || oldestPosition.CompareTo(_position) > 0)
+ {
+ _logger.LogWarning("The authority change log no longer reaches back to where this instance read to, checking {Count} open connection(s)", _registry.Count);
+
+ // The mark first: a change announced from here on is read, and one from before it is seen by the
+ // checks, which start after this.
+ _position = await _log.MarkAsync();
+ _registry.SignalAll();
+ return;
+ }
+
+ foreach (var entry in entries)
+ {
+ if (entry.Change is { } change)
+ {
+ _registry.Signal(change);
+ }
+ else if (entry.Unreadable)
+ {
+ // What changed is unknown, so anything may have.
+ _registry.SignalAll();
+ }
+
+ _position = entry.Position;
+ }
+ } while (entries.Count == BatchSize);
+ }
+}
diff --git a/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs
new file mode 100644
index 00000000..3bd71804
--- /dev/null
+++ b/Common/ConnectionAuthority/AuthorityChangeSubscriber.cs
@@ -0,0 +1,129 @@
+using OpenShock.Common.Redis;
+using OpenShock.Common.Services.RedisPubSub;
+using StackExchange.Redis;
+
+namespace OpenShock.Common.ConnectionAuthority;
+
+///
+/// Keeps this instance's connections up with what is announced about changes in authority. The same in every
+/// service that holds long-lived connections.
+///
+///
+/// The changes themselves are in the , where they wait for an instance that was
+/// not listening. This decides when to read it: at once when says
+/// there is something new, when the Redis connection comes back, and every
+/// in case that message was lost.
+///
+/// A session that reaches its lifetime is only ever announced by a Redis expiry event, which is lost when nobody
+/// is listening. So when the connection that carries them comes back, the connections that depend on a session
+/// are checked.
+///
+///
+public sealed class AuthorityChangeSubscriber : BackgroundService
+{
+ private static readonly string LoginSessionKeyPrefix = typeof(LoginSession).FullName + ":";
+
+ private readonly IConnectionMultiplexer _connectionMultiplexer;
+ private readonly ISubscriber _subscriber;
+ private readonly AuthorityChangeReader _reader;
+ private readonly ConnectionAuthorityRegistry _registry;
+ private readonly ILogger _logger;
+
+ /// Released when there may be something new to read. One pending release is enough for any number of reasons.
+ private readonly SemaphoreSlim _wake = new(0, 1);
+
+ public AuthorityChangeSubscriber(IConnectionMultiplexer connectionMultiplexer, AuthorityChangeReader reader, ConnectionAuthorityRegistry registry, ILogger logger)
+ {
+ _connectionMultiplexer = connectionMultiplexer;
+ _subscriber = connectionMultiplexer.GetSubscriber();
+ _reader = reader;
+ _registry = registry;
+ _logger = logger;
+ }
+
+ public override async Task StartAsync(CancellationToken cancellationToken)
+ {
+ // Before anything else, and before the service takes connections: reading starts from here.
+ await _reader.StartAsync();
+
+ await _subscriber.SubscribeAsync(RedisChannels.AuthorityChanged, HandleAuthorityChanged);
+ await _subscriber.SubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired);
+ _connectionMultiplexer.ConnectionRestored += HandleConnectionRestored;
+
+ await base.StartAsync(cancellationToken);
+ }
+
+ public override async Task StopAsync(CancellationToken cancellationToken)
+ {
+ _connectionMultiplexer.ConnectionRestored -= HandleConnectionRestored;
+ await _subscriber.UnsubscribeAsync(RedisChannels.AuthorityChanged, HandleAuthorityChanged);
+ await _subscriber.UnsubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired);
+
+ await base.StopAsync(cancellationToken);
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ var interval = _registry.CatchUpInterval;
+
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ try
+ {
+ await _wake.WaitAsync(interval, stoppingToken);
+ await _reader.CatchUpAsync();
+ }
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ // Shutting down.
+ }
+ catch (Exception e)
+ {
+ // Redis trouble. Reading carries on from the same place at the next reason to.
+ _logger.LogWarning(e, "Failed to read the authority change log");
+ }
+ }
+ }
+
+ private void Wake()
+ {
+ try
+ {
+ _wake.Release();
+ }
+ catch (SemaphoreFullException)
+ {
+ // Already asked to read.
+ }
+ }
+
+ private void HandleAuthorityChanged(RedisChannel _, RedisValue __) => Wake();
+
+ private void HandleKeyExpired(RedisChannel _, RedisValue message)
+ {
+ // A session that reached its lifetime: the same as a deleted one for the connections using it.
+ 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)
+ {
+ Wake();
+
+ if (e.ConnectionType != ConnectionType.Subscription) return;
+
+ _logger.LogInformation("Redis subscription connection restored, checking the connections that depend on a session for an expiry missed meanwhile");
+ _registry.SignalWhere(DependsOnASession);
+ }
+
+ private static bool DependsOnASession(ConnectionSubject subject) =>
+ subject is SignalRSubject { Credential: SessionCredential } or LiveControlSubject { Credential: SessionCredential };
+
+ public override void Dispose()
+ {
+ _wake.Dispose();
+ base.Dispose();
+ }
+}
diff --git a/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs
new file mode 100644
index 00000000..2778b64c
--- /dev/null
+++ b/Common/ConnectionAuthority/ConnectionAuthorityOptions.cs
@@ -0,0 +1,45 @@
+namespace OpenShock.Common.ConnectionAuthority;
+
+/// Bound to , so each value can be set per environment.
+public sealed class ConnectionAuthorityOptions
+{
+ public const string SectionName = "OpenShock:ConnectionAuthority";
+
+ ///
+ /// How long a connection's last successful check stays good when nothing was announced for it. Every change
+ /// is announced and reaches a connection within seconds, and a grant that expires is checked when it does, so
+ /// this is not what normally ends a connection. It is the backstop for a change that was never announced: one
+ /// written past the application, or one still waiting to be announced when its process ended. Each open
+ /// connection costs one lookup per interval.
+ ///
+ public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(15);
+
+ ///
+ /// The same as , for live control connections. Shorter, because going on with authority
+ /// that is gone means still controlling someone's shockers, and there are few of these connections.
+ ///
+ public TimeSpan LiveControlInterval { get; set; } = TimeSpan.FromMinutes(1);
+
+ ///
+ /// How often the log of announced changes is read when nothing said there was something new. Bounds how long
+ /// a change waits when the message that says so was lost.
+ ///
+ public TimeSpan CatchUpInterval { get; set; } = TimeSpan.FromSeconds(5);
+
+ ///
+ /// How long the log of announced changes may be out of reach before every connection on this instance is
+ /// closed. Without the log nothing here can learn that a connection should end, so past this they are ended
+ /// instead; clients connect again once it is back. Long enough to sit out a restart or failover of the store.
+ /// Zero closes them at the first failed read.
+ ///
+ public TimeSpan CloseAfterLogUnreachable { get; set; } = TimeSpan.FromSeconds(15);
+
+ ///
+ /// How long a connection may stay open after a change was announced for it while the check that change calls
+ /// for keeps failing. It may do nothing in that time, but is still sent what is pushed to its user or public
+ /// share, and whether it still should be is exactly what cannot be looked up. Past this it is closed instead;
+ /// the client connects again once the check can be made. Long enough to sit out a restart or failover of the
+ /// database. Zero closes it at the first sweep after a failed check.
+ ///
+ public TimeSpan CloseAfterChangeUnchecked { get; set; } = TimeSpan.FromSeconds(15);
+}
diff --git a/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs
new file mode 100644
index 00000000..5e0574ad
--- /dev/null
+++ b/Common/ConnectionAuthority/ConnectionAuthorityRegistry.cs
@@ -0,0 +1,234 @@
+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 check again, and they all end in the same :
+///
+/// registering, which closes the gap between authenticating and being reachable by a change;
+/// a change announced over Redis, see and , or the
+/// chance that one was missed for good, see ;
+/// time, for a change whose announcement was lost or a grant that simply expired, see
+/// . This covers every connection, idle or not, so none stays open for much longer than
+/// after what it depends on is gone.
+///
+/// A check that fails (database or Redis trouble) does not close a connection by itself. What it leaves behind
+/// depends on why it ran. After an announced change the connection has no usable
+/// until a check succeeds, so a pause or a revocation that was announced
+/// takes effect on everything the connection asks for even while it cannot be looked up. What is pushed to it
+/// (its user's control logs and device updates, a public share's updates) does not ask the grant and still
+/// arrives, so that state is only put up with for : after it the
+/// connection is closed. After a check that ran only because time passed, the connection keeps what it had and
+/// stays. Either way the check is tried again at every sweep.
+///
+/// Local to the process: every instance tracks its own connections and reacts to the same Redis messages.
+/// A change is matched against every connection, which is fine for how rarely authority changes.
+///
+///
+public sealed class ConnectionAuthorityRegistry
+{
+ ///
+ /// How many connections may be checked at once. Connections that opened together come due together, and a
+ /// change to one account or hub can reach many; this keeps either from taking every database connection.
+ ///
+ private const int MaxConcurrentChecks = 32;
+
+ private readonly ConcurrentDictionary _handles = new();
+ private readonly SemaphoreSlim _checkGate = new(MaxConcurrentChecks, MaxConcurrentChecks);
+ 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;
+ }
+
+ /// What elapsed time is measured with. Only replaced in tests.
+ internal TimeProvider Time { get; init; } = TimeProvider.System;
+
+ /// How long a successful check stays good before time alone is a reason to check again.
+ public TimeSpan Interval => _options.Value.Interval;
+
+ /// for live control connections, which are checked more often.
+ public TimeSpan LiveControlInterval => _options.Value.LiveControlInterval;
+
+ /// How often the log of announced changes is read without being told to, see .
+ public TimeSpan CatchUpInterval => _options.Value.CatchUpInterval;
+
+ /// How long the log of announced changes may be out of reach before .
+ public TimeSpan CloseAfterLogUnreachable => _options.Value.CloseAfterLogUnreachable;
+
+ /// How long a change announced for a connection may go unchecked, while checking fails, before the connection is closed.
+ public TimeSpan CloseAfterChangeUnchecked => _options.Value.CloseAfterChangeUnchecked;
+
+ public int Count => _handles.Count;
+
+ ///
+ /// Start tracking a connection without checking it yet, for one whose first use will. Changes reach it from
+ /// here on.
+ ///
+ public ConnectionHandle Track(ConnectionSubject subject, IAuthorizedConnection connection)
+ {
+ var handle = new ConnectionHandle(this, subject, connection);
+ _handles[handle] = 0;
+ return handle;
+ }
+
+ ///
+ /// Start tracking a connection and check it once. The connection was authenticated before it was tracked,
+ /// so a change announced in between found nothing to act on; this check sees it.
+ ///
+ ///
+ /// The handle, and how that first check went. On the connection was already
+ /// closed and is no longer tracked.
+ ///
+ public async Task<(ConnectionHandle Handle, RefreshResult Result)> RegisterAsync(ConnectionSubject subject, IAuthorizedConnection connection)
+ {
+ var handle = Track(subject, connection);
+ var result = await handle.RefreshAsync();
+ return (handle, result);
+ }
+
+ ///
+ /// Something changed: every connection it can affect loses what it was granted and checks again. Returns at
+ /// once, so it is safe to call from a Redis callback.
+ ///
+ public void Signal(AuthorityChange change) => SignalWhere(subject => subject.IsAffectedBy(change));
+
+ ///
+ /// Changes may have been announced that this instance cannot learn of anymore, so every connection is treated
+ /// as if one had been announced for it.
+ ///
+ public void SignalAll() => SignalWhere(_ => true);
+
+ ///
+ /// Like , for a change that cannot be named: every connection
+ /// picks is treated as if one had been announced for it.
+ ///
+ public void SignalWhere(Func affected)
+ {
+ foreach (var handle in _handles.Keys)
+ {
+ if (!affected(handle.Subject)) continue;
+
+ handle.Invalidate();
+ handle.RequestRefresh();
+ }
+ }
+
+ ///
+ /// Time as a reason to check again: connections whose last good check is older than their interval or did
+ /// not cover a change announced since, and connections whose grant has reached its expiry. And time as a
+ /// limit: a connection whose announced change could not be checked for
+ /// is closed.
+ ///
+ public void Sweep(DateTime now)
+ {
+ var interval = Interval;
+ var liveControlInterval = LiveControlInterval;
+ var closeAfterChangeUnchecked = CloseAfterChangeUnchecked;
+ foreach (var handle in _handles.Keys)
+ {
+ if (handle.MarkRevokedIfUncheckedFor(closeAfterChangeUnchecked))
+ {
+ _logger.LogWarning("Closing {Subject}: a change was announced for it and what it may do now could not be looked up", handle.Subject);
+
+ // Never throws, and closing is not worth holding the other connections up for.
+ _ = CloseRevokedAsync(handle);
+ continue;
+ }
+
+ var expired = handle.Grant is { } grant && grant.IsExpired(now);
+ var maxAge = handle.Subject is LiveControlSubject ? liveControlInterval : interval;
+
+ if (expired || !handle.WasCheckedWithin(maxAge)) handle.RequestRefreshIfIdle();
+ }
+ }
+
+ internal void Remove(ConnectionHandle handle) => _handles.TryRemove(handle, out _);
+
+ internal async Task CheckOnceAsync(ConnectionHandle handle)
+ {
+ if (handle.IsRevoked) return RefreshResult.Revoked;
+
+ var (subject, changes) = handle.BeginCheck();
+
+ Grant? grant;
+ await _checkGate.WaitAsync();
+ try
+ {
+ await using var scope = _scopeFactory.CreateAsyncScope();
+ var resolver = scope.ServiceProvider.GetRequiredService();
+ grant = await resolver.ResolveAsync(subject, CancellationToken.None);
+ }
+ catch (Exception e)
+ {
+ // A transient failure must not drop a legitimate connection. It is checked again at the next sweep.
+ _logger.LogWarning(e, "Error while checking what a {Subject} may do", subject);
+ handle.CheckFailed(changes);
+ return RefreshResult.Failed;
+ }
+ finally
+ {
+ _checkGate.Release();
+ }
+
+ if (grant is not null && handle.Accept(grant, changes)) return RefreshResult.Valid;
+
+ await RevokeAsync(handle);
+ return RefreshResult.Revoked;
+ }
+
+ ///
+ /// Close every connection, whatever it may do: this instance can no longer learn of a change to it. Not a
+ /// verdict on any of them; a client that connects again is checked as usual.
+ ///
+ ///
+ /// Returns once every connection is revoked and its close has started, without waiting for the closes: one
+ /// can take as long as the other end likes, and the caller has a log to get back to reading.
+ ///
+ public void CloseAll()
+ {
+ var handles = _handles.Keys.ToArray();
+ if (handles.Length == 0) return;
+
+ _logger.LogWarning("Closing all {Count} open connection(s): changes in authority can no longer be learned of", handles.Length);
+
+ // Never throws.
+ foreach (var handle in handles) _ = RevokeAsync(handle, log: false);
+ }
+
+ private Task RevokeAsync(ConnectionHandle handle, bool log = true)
+ {
+ if (!handle.MarkRevoked()) return Task.CompletedTask;
+
+ if (log) _logger.LogInformation("Closing {Subject}: it may no longer go on", handle.Subject);
+
+ return CloseRevokedAsync(handle);
+ }
+
+ /// For the one caller that revoked the handle. Never throws.
+ private async Task CloseRevokedAsync(ConnectionHandle handle)
+ {
+ Remove(handle);
+
+ try
+ {
+ await handle.CloseConnectionAsync();
+ }
+ 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");
+ }
+ }
+}
diff --git a/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs b/Common/ConnectionAuthority/ConnectionAuthoritySweeper.cs
new file mode 100644
index 00000000..3688e362
--- /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(Math.Min(_registry.Interval.Ticks, _registry.LiveControlInterval.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..257ff63c
--- /dev/null
+++ b/Common/ConnectionAuthority/ConnectionHandle.cs
@@ -0,0 +1,315 @@
+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). The connection stays open and is checked again later,
+ /// for as long as allows.
+ ///
+ Failed
+}
+
+///
+/// One registered connection: what it depends on, what it may currently do, and the means to check again.
+///
+///
+/// Checking is the only way the grant changes, and only one check runs at a time per connection. A request that
+/// arrives while one is running makes it run once more when it finishes, so the last check always started after
+/// the last request.
+///
+/// A reason to check again (an announced change, a new subject) is counted, and a check only settles the reasons
+/// that existed when it started. So a check that fails, or one that was already running, cannot make the
+/// connection look checked: until a later check succeeds it has no usable and is not
+/// fresh.
+///
+///
+/// That stops what the connection asks for, not what is pushed to it, which goes to whatever is open. So how long
+/// a reason has gone unchecked while checks fail is kept too, for the registry to end the connection over, see
+/// .
+///
+///
+public sealed class ConnectionHandle : IDisposable
+{
+ 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 bool _revoked;
+ private Grant? _grant;
+
+ /// How many reasons to check again there have been.
+ private long _changes;
+
+ /// as it was when the last successful check started.
+ private long _checkedChanges;
+
+ /// as it was when the last check started, whether or not it succeeded.
+ private long _startedChanges;
+
+ // 0 means "never checked": timestamps are never 0 in practice.
+ private long _lastChecked;
+
+ ///
+ /// When the oldest reason no successful check covers was counted. Only means something while there is one.
+ ///
+ private long _uncheckedSince;
+
+ ///
+ /// When the first reason since the last check started was counted: the oldest one that check cannot cover.
+ /// Only means something while there is one.
+ ///
+ private long _changedSinceStart;
+
+ /// Whether a check that had such a reason to cover has failed.
+ private bool _checkFailed;
+
+ internal ConnectionHandle(ConnectionAuthorityRegistry registry, ConnectionSubject subject, IAuthorizedConnection connection)
+ {
+ _registry = registry;
+ _subject = subject;
+ _connection = connection;
+ }
+
+ public ConnectionSubject Subject => _subject;
+
+ private TimeProvider Time => _registry.Time;
+
+ ///
+ /// What the connection may do, as of the last successful check. Null until the first one, once the connection
+ /// is revoked, and while a change announced since has not been checked successfully: what was allowed before
+ /// that change can no longer be relied on.
+ ///
+ public Grant? Grant
+ {
+ get
+ {
+ lock (_lock)
+ {
+ return _revoked || _changes != _checkedChanges ? null : _grant;
+ }
+ }
+ }
+
+ /// The connection may no longer go on. Set before it is closed, and never unset.
+ public bool IsRevoked => _revoked;
+
+ ///
+ /// Replace what the connection depends on, for a connection that learns more after it was registered. It
+ /// counts as unchecked until a check of the new subject succeeds.
+ ///
+ public void UpdateSubject(ConnectionSubject subject)
+ {
+ lock (_lock)
+ {
+ _subject = subject;
+ CountChange();
+ }
+ }
+
+ /// Whether a check that covers every change so far succeeded less than ago.
+ public bool WasCheckedWithin(TimeSpan maxAge)
+ {
+ lock (_lock)
+ {
+ return _lastChecked != 0 && _changes == _checkedChanges && Time.GetElapsedTime(_lastChecked) < maxAge;
+ }
+ }
+
+ ///
+ /// Check again unless says the last check is still good and what it granted
+ /// has not reached its expiry since. Nothing announces an expiry, so a recent check does not cover it.
+ ///
+ public Task EnsureFreshAsync(TimeSpan maxAge)
+ {
+ if (_revoked) return Task.FromResult(RefreshResult.Revoked);
+ if (WasCheckedWithin(maxAge) && Grant?.IsExpired(DateTime.UtcNow) != true) return Task.FromResult(RefreshResult.Valid);
+ return RefreshAsync();
+ }
+
+ ///
+ /// Look up what the connection may do now, and close it if that is nothing. If a check is already running, this
+ /// waits for one that started after this call.
+ ///
+ public Task RefreshAsync()
+ {
+ 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();
+
+ ///
+ /// Something the connection depends on changed, or may have: what it was granted before counts for nothing
+ /// until a check that starts from here on succeeds.
+ ///
+ internal void Invalidate()
+ {
+ lock (_lock)
+ {
+ CountChange();
+ }
+ }
+
+ /// Call under the lock.
+ private void CountChange()
+ {
+ var now = Time.GetTimestamp();
+ if (_changes == _checkedChanges) _uncheckedSince = now;
+ if (_changes == _startedChanges) _changedSinceStart = now;
+ _changes++;
+ }
+
+ ///
+ /// Revoke the connection if a reason to check again has gone without a successful check for at least
+ /// and a check for it failed. Not while one is merely waiting its turn: only a check
+ /// that was tried and could not be made says that what the connection may do cannot be learned right now.
+ ///
+ /// Decided and marked in one step, so a check that succeeds a moment later finds the connection revoked
+ /// instead of having it closed after it was found good.
+ ///
+ ///
+ /// True for the one caller that has to close the connection.
+ internal bool MarkRevokedIfUncheckedFor(TimeSpan limit)
+ {
+ lock (_lock)
+ {
+ if (_revoked || !_checkFailed || _changes == _checkedChanges) return false;
+ if (Time.GetElapsedTime(_uncheckedSince) < limit) return false;
+
+ _revoked = true;
+ return true;
+ }
+ }
+
+ /// A check could not be made.
+ /// The changes the check would have covered, from .
+ internal void CheckFailed(long changes)
+ {
+ lock (_lock)
+ {
+ if (changes != _checkedChanges) _checkFailed = true;
+ }
+ }
+
+ /// Completes once no check is running, for a caller that requested one without waiting for it.
+ internal Task WhenIdleAsync()
+ {
+ lock (_lock)
+ {
+ return _running ?? Task.CompletedTask;
+ }
+ }
+
+ /// Check again unless a check 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.CheckOnceAsync(this);
+
+ lock (_lock)
+ {
+ // Revoked while the check ran, by the registry for a reason of its own. That stands whatever the
+ // check found: nobody is told that a closed connection is good.
+ if (_revoked)
+ {
+ _running = null;
+ return RefreshResult.Revoked;
+ }
+
+ // A check that found the connection good, but started before the last reason to check it, says
+ // nothing about that reason: whoever waits for this must not be told the connection is good.
+ var outdated = result == RefreshResult.Valid && _changes != _checkedChanges;
+
+ if (_rerun || outdated)
+ {
+ _rerun = false;
+ continue;
+ }
+
+ _running = null;
+ return result;
+ }
+ }
+ }
+
+ /// What a check that starts now has to look up, and which changes it will have covered.
+ internal (ConnectionSubject Subject, long Changes) BeginCheck()
+ {
+ lock (_lock)
+ {
+ _startedChanges = _changes;
+ return (_subject, _changes);
+ }
+ }
+
+ /// What the check found.
+ /// The changes the check covers, from .
+ internal bool Accept(Grant grant, long changes)
+ {
+ if (!_connection.TryApplyGrant(grant)) return false;
+
+ lock (_lock)
+ {
+ _grant = grant;
+ _checkedChanges = changes;
+ _lastChecked = Time.GetTimestamp();
+
+ // What is still not covered was counted after this check started. It has waited since then, not since
+ // now, and no check has been tried for it yet.
+ if (_changes != changes) _uncheckedSince = _changedSinceStart;
+ _checkFailed = false;
+ }
+
+ 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..075a4d48
--- /dev/null
+++ b/Common/ConnectionAuthority/ConnectionSubject.cs
@@ -0,0 +1,117 @@
+namespace OpenShock.Common.ConnectionAuthority;
+
+///
+/// Everything an open connection's authority depends on, by what kind of connection it is. A change to any of
+/// the things named here is a reason to check the connection again, see .
+///
+public closed record ConnectionSubject
+{
+ /// Whether a change to the thing named by can affect this connection.
+ public abstract bool IsAffectedBy(AuthorityChange change);
+
+ /// The connection in words for a log, without the credentials it holds.
+ protected abstract string Describe();
+
+ ///
+ /// Sealed, so no case gets a generated one that would put a session or hub token into a log.
+ ///
+ public sealed override string ToString() => Describe();
+}
+
+///
+/// A SignalR hub connection: someone signed in, a guest on a public share, or someone signed in on a public share.
+///
+/// What the connection authenticated with, null for a guest.
+/// The public share the connection controls, if it is on one.
+public sealed record SignalRSubject(ConnectionCredential? Credential, PublicShareAccess? PublicShare = null) : ConnectionSubject
+{
+ public override bool IsAffectedBy(AuthorityChange change) =>
+ Credential?.IsAffectedBy(change) == true || PublicShare?.IsAffectedBy(change) == true;
+
+ protected override string Describe() => (Credential, PublicShare) switch
+ {
+ (not null, not null) => $"SignalR connection ({Credential}, {PublicShare})",
+ (not null, null) => $"SignalR connection ({Credential})",
+ (null, not null) => $"SignalR connection (guest, {PublicShare})",
+ (null, null) => "SignalR connection (anonymous)"
+ };
+}
+
+/// A live control socket on a gateway. Needs shockers.use and the shockers it may control.
+/// What the connection authenticated with. Live control is never anonymous.
+/// The hub the socket controls.
+/// The owner of .
+public sealed record LiveControlSubject(ConnectionCredential Credential, Guid DeviceId, Guid DeviceOwnerId) : ConnectionSubject
+{
+ public override bool IsAffectedBy(AuthorityChange change) => change switch
+ {
+ DeviceChanged device => device.DeviceId == DeviceId,
+ UserChanged user => user.UserId == DeviceOwnerId || Credential.IsAffectedBy(change),
+ _ => Credential.IsAffectedBy(change)
+ };
+
+ protected override string Describe() => $"live control connection ({Credential}, hub [{DeviceId}])";
+}
+
+/// The socket of a hub (the device itself) on a gateway.
+/// The hub the socket belongs to.
+/// The owner of .
+/// The token the hub authenticated with.
+public sealed record HubSocketSubject(Guid DeviceId, Guid DeviceOwnerId, string HubToken) : ConnectionSubject
+{
+ public override bool IsAffectedBy(AuthorityChange change) => change switch
+ {
+ DeviceChanged device => device.DeviceId == DeviceId,
+ UserChanged user => user.UserId == DeviceOwnerId,
+ _ => false
+ };
+
+ protected override string Describe() => $"hub socket (hub [{DeviceId}])";
+}
+
+/// What a connection authenticated with.
+/// The user the connection acts as.
+public closed record ConnectionCredential(Guid UserId)
+{
+ public bool IsAffectedBy(AuthorityChange change) => change switch
+ {
+ UserChanged user => user.UserId == UserId,
+ SessionChanged changed => this is SessionCredential session && session.SessionId == changed.SessionId,
+ ApiTokenChanged changed => this is ApiTokenCredential token && token.TokenId == changed.TokenId,
+ _ => false
+ };
+}
+
+/// The user the session belongs to.
+/// The session token the connection authenticated with.
+public sealed record SessionCredential(Guid UserId, string SessionToken) : ConnectionCredential(UserId)
+{
+ /// The id the session is stored under, which is what a session change names.
+ public string SessionId { get; } = SessionIds.FromToken(SessionToken);
+
+ /// Written out by hand to keep the session token and the id derived from it out of a log.
+ public override string ToString() => $"session of user [{UserId}]";
+}
+
+/// The user the token belongs to.
+/// The API token the connection authenticated with.
+public sealed record ApiTokenCredential(Guid UserId, Guid TokenId) : ConnectionCredential(UserId)
+{
+ public override string ToString() => $"API token [{TokenId}] of user [{UserId}]";
+}
+
+/// A public share as a connection got onto it.
+/// The public share the connection controls.
+/// The share's owner, whose deactivation ends the connection too.
+/// The share's password stamp when the connection was let in, null when it had no password.
+public sealed record PublicShareAccess(Guid PublicShareId, Guid OwnerId, Guid? PasswordStamp)
+{
+ public bool IsAffectedBy(AuthorityChange change) => change switch
+ {
+ PublicShareChanged share => share.PublicShareId == PublicShareId,
+ UserChanged user => user.UserId == OwnerId,
+ _ => false
+ };
+
+ public override string ToString() => $"public share [{PublicShareId}]";
+}
diff --git a/Common/ConnectionAuthority/Grant.cs b/Common/ConnectionAuthority/Grant.cs
new file mode 100644
index 00000000..5cb825d7
--- /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. Empty for other connections.
+ ///
+ public FrozenDictionary Shockers { get; init; } = FrozenDictionary.Empty;
+
+ /// When the grant ends on its own (a token or public share reaching its expiry), if it does.
+ public DateTime? ExpiresAt { get; init; }
+
+ 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..6c6a7294
--- /dev/null
+++ b/Common/ConnectionAuthority/GrantResolver.cs
@@ -0,0 +1,135 @@
+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 Task ResolveAsync(ConnectionSubject subject, CancellationToken cancellationToken) => subject switch
+ {
+ SignalRSubject signalR => ResolveSignalR(signalR, cancellationToken),
+ LiveControlSubject liveControl => ResolveLiveControl(liveControl, cancellationToken),
+ HubSocketSubject hubSocket => ResolveHubSocket(hubSocket, cancellationToken)
+ };
+
+ private async Task ResolveSignalR(SignalRSubject subject, CancellationToken cancellationToken)
+ {
+ var now = DateTime.UtcNow;
+
+ // A hub connection serves several endpoints and checks the token's permissions on each call, so none is
+ // asked for here.
+ var grant = Grant.Empty;
+ if (subject.Credential is { } credential)
+ {
+ grant = await ResolveCredential(credential, requiredPermission: null, now, cancellationToken);
+ if (grant is null) return null;
+ }
+
+ if (subject.PublicShare is not { } access) return grant;
+
+ // A public share connection may go on while the share exists, has not expired, its owner is active and
+ // its password was not set or changed since the visitor got in.
+ var share = await _db.PublicShares
+ .Where(x => x.Id == access.PublicShareId && x.PasswordStamp == access.PasswordStamp)
+ .OpenToVisitors(now)
+ .Select(x => new { x.ExpiresAt })
+ .FirstOrDefaultAsync(cancellationToken);
+ if (share is null) return null;
+
+ return grant with { ExpiresAt = Earliest(grant.ExpiresAt, share.ExpiresAt) };
+ }
+
+ private async Task ResolveLiveControl(LiveControlSubject subject, CancellationToken cancellationToken)
+ {
+ // Live control is one endpoint behind one permission, so losing it ends the connection.
+ var grant = await ResolveCredential(subject.Credential, PermissionType.Shockers_Use, DateTime.UtcNow, cancellationToken);
+ if (grant is null) return null;
+
+ var userId = subject.Credential.UserId;
+
+ // Someone controlling a shared hub loses it when the owner is deactivated.
+ if (subject.DeviceOwnerId != userId && !await _db.Users.AnyAsync(u => u.Id == subject.DeviceOwnerId && u.UserDeactivation == null, cancellationToken))
+ return null;
+
+ // Losing every share leaves the connection open with nothing to control: a share can come back, and
+ // the client is told per frame that the shocker is not there.
+ var controllable = await _db.Shockers
+ .AsNoTracking()
+ .Where(x => x.DeviceId == subject.DeviceId)
+ .ControllableBy(userId)
+ .ToArrayAsync(cancellationToken);
+
+ return grant with
+ {
+ Shockers = controllable.ToFrozenDictionary(
+ x => x.ShockerId,
+ x => new ShockerGrant(x.Paused, SharePermsAndLimits.Intersect(x.ShockerPermsAndLimits, x.PermsAndLimits)))
+ };
+ }
+
+ ///
+ /// A hub may stay connected while it exists, still has the token it connected with and its owner is active,
+ /// the same as what lets it connect.
+ ///
+ private async Task ResolveHubSocket(HubSocketSubject subject, CancellationToken cancellationToken)
+ {
+ var valid = await _db.Devices.AnyAsync(x => x.Id == subject.DeviceId && x.Token == subject.HubToken && x.Owner.UserDeactivation == null, cancellationToken);
+ return valid ? Grant.Empty : null;
+ }
+
+ /// What the thing a connection authenticated with still grants, or null when it may no longer be used.
+ /// What the connection authenticated with.
+ /// A permission an API token must still have for the connection to go on.
+ /// The time to hold a token's expiry against.
+ ///
+ private Task ResolveCredential(ConnectionCredential credential, PermissionType? requiredPermission, DateTime now, CancellationToken cancellationToken) => credential switch
+ {
+ ApiTokenCredential apiToken => ResolveApiToken(apiToken, requiredPermission, now, cancellationToken),
+ SessionCredential session => ResolveSession(session, cancellationToken)
+ };
+
+ private async Task ResolveApiToken(ApiTokenCredential credential, PermissionType? requiredPermission, DateTime now, CancellationToken cancellationToken)
+ {
+ var token = await _db.ApiTokens
+ .AsNoTracking()
+ .FirstOrDefaultAsync(x => x.Id == credential.TokenId && x.User.UserDeactivation == null, cancellationToken);
+ if (token is null || (token.ValidUntil is { } validUntil && validUntil < now)) return null;
+ if (requiredPermission is { } permission && !token.Permissions.IsAllowed(permission)) return null;
+
+ return new Grant { Token = TokenGrant.From(token), ExpiresAt = token.ValidUntil };
+ }
+
+ private async Task ResolveSession(SessionCredential credential, CancellationToken cancellationToken)
+ {
+ // Sessions are deleted on logout, on deactivation and on a password reset.
+ var session = await _sessionService.GetSessionByTokenAsync(credential.SessionToken);
+ if (session is null || session.UserId != credential.UserId) return null;
+
+ // That deletion happens in Redis after the database commit and can fail, leaving the session behind.
+ // The account itself is the authority, as it is when a session authenticates a request.
+ var active = await _db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, cancellationToken);
+ if (!active) return null;
+
+ // Reaching its lifetime ends a session without anyone deleting it, so the grant ends with it. That can
+ // happen while the account was being looked up, and then there is nothing left to grant.
+ if (session.Expires?.UtcDateTime is not { } expiresAt) return Grant.Empty;
+ return expiresAt > DateTime.UtcNow ? new Grant { ExpiresAt = expiresAt } : null;
+ }
+
+ private static DateTime? Earliest(DateTime? a, DateTime? b) => a is null ? b : b is null ? a : a < b ? a : b;
+}
diff --git a/Common/ConnectionAuthority/IAuthorityChangeLog.cs b/Common/ConnectionAuthority/IAuthorityChangeLog.cs
new file mode 100644
index 00000000..f259bbae
--- /dev/null
+++ b/Common/ConnectionAuthority/IAuthorityChangeLog.cs
@@ -0,0 +1,57 @@
+namespace OpenShock.Common.ConnectionAuthority;
+
+///
+/// The changes in authority that were announced, in order, kept for a while. What makes an announcement reach an
+/// instance that was not listening when it was made: every instance reads on from where it got to.
+///
+public interface IAuthorityChangeLog
+{
+ ///
+ /// Add a change and tell everyone reading that there is something new. Throws when the log cannot be reached;
+ /// to announce a change without having to handle that, use .
+ ///
+ Task AppendAsync(AuthorityChange change);
+
+ ///
+ /// Put a mark at the end of the log and return where it is, as a place to read on from. A mark is an entry
+ /// like any other, so it also tells a reader later whether the log still reaches back that far.
+ ///
+ Task MarkAsync();
+
+ /// Where the oldest entry still in the log is, null when the log is empty or gone.
+ Task OldestAsync();
+
+ /// Up to entries after , oldest first.
+ Task> ReadAfterAsync(LogPosition position, int count);
+}
+
+/// A place in the log. Later entries compare greater.
+public readonly record struct LogPosition(long Milliseconds, long Sequence) : IComparable
+{
+ public int CompareTo(LogPosition other)
+ {
+ var byTime = Milliseconds.CompareTo(other.Milliseconds);
+ return byTime != 0 ? byTime : Sequence.CompareTo(other.Sequence);
+ }
+
+ public static bool TryParse(string? id, out LogPosition position)
+ {
+ position = default;
+ if (id is null) return false;
+
+ var dash = id.IndexOf('-');
+ if (dash <= 0) return false;
+ if (!long.TryParse(id.AsSpan(0, dash), out var milliseconds) || !long.TryParse(id.AsSpan(dash + 1), out var sequence)) return false;
+
+ position = new LogPosition(milliseconds, sequence);
+ return true;
+ }
+
+ public override string ToString() => $"{Milliseconds}-{Sequence}";
+}
+
+/// One entry of the log.
+/// Where the entry is.
+/// The change it announces, null for a mark and for an entry that could not be read.
+/// The entry announces a change, but which one could not be read.
+public readonly record struct LogEntry(LogPosition Position, AuthorityChange? Change, bool Unreadable = false);
diff --git a/Common/ConnectionAuthority/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/RedisAuthorityChangeLog.cs b/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs
new file mode 100644
index 00000000..7d3b05f3
--- /dev/null
+++ b/Common/ConnectionAuthority/RedisAuthorityChangeLog.cs
@@ -0,0 +1,106 @@
+using MessagePack;
+using OpenShock.Common.Services.RedisPubSub;
+using StackExchange.Redis;
+
+namespace OpenShock.Common.ConnectionAuthority;
+
+///
+/// The log as a Redis stream. Unlike a pub/sub message, an entry stays until the stream is trimmed, so an
+/// instance that was not listening reads it later.
+///
+public sealed class RedisAuthorityChangeLog : IAuthorityChangeLog
+{
+ private static readonly RedisKey Key = "authority-changes";
+
+ private const string ChangeField = "c";
+ private const string MarkField = "m";
+
+ ///
+ /// How many entries are kept, roughly. An instance that falls further behind than this cannot tell what it
+ /// missed and checks all its connections instead, see .
+ ///
+ private const int MaxLength = 10_000;
+
+ private readonly IDatabase _db;
+ private readonly ISubscriber _subscriber;
+ private readonly ILogger _logger;
+
+ public RedisAuthorityChangeLog(IConnectionMultiplexer connectionMultiplexer, ILogger logger)
+ {
+ _db = connectionMultiplexer.GetDatabase();
+ _subscriber = connectionMultiplexer.GetSubscriber();
+ _logger = logger;
+ }
+
+ ///
+ public async Task AppendAsync(AuthorityChange change)
+ {
+ await AddAsync(ChangeField, (RedisValue)new ReadOnlyMemory(MessagePackSerializer.Serialize(change)));
+
+ try
+ {
+ // The entry is what carries the change. This only says there is something new to read, so that
+ // nobody has to wait for their next look at the log.
+ await _subscriber.PublishAsync(RedisChannels.AuthorityChanged, RedisValue.EmptyString);
+ }
+ catch (Exception e)
+ {
+ _logger.LogDebug(e, "Failed to say that there is a new authority change; it is read a little later");
+ }
+ }
+
+ ///
+ public async Task MarkAsync() => Parse(await AddAsync(MarkField, 1));
+
+ ///
+ public async Task OldestAsync()
+ {
+ var entries = await _db.StreamRangeAsync(Key, count: 1);
+ return entries.Length == 0 ? null : Parse(entries[0].Id);
+ }
+
+ ///
+ public async Task> ReadAfterAsync(LogPosition position, int count)
+ {
+ var entries = await _db.StreamReadAsync(Key, position.ToString(), count);
+
+ var result = new LogEntry[entries.Length];
+ for (var i = 0; i < entries.Length; i++)
+ {
+ result[i] = Read(entries[i]);
+ }
+
+ return result;
+ }
+
+ private Task AddAsync(RedisValue field, RedisValue value) =>
+ _db.StreamAddAsync(Key, field, value, maxLength: MaxLength, useApproximateMaxLength: true);
+
+ private LogEntry Read(StreamEntry entry)
+ {
+ var position = Parse(entry.Id);
+
+ var payload = entry[ChangeField];
+ if (payload.IsNull) return new LogEntry(position, Change: null);
+
+ AuthorityChange? change;
+ try
+ {
+ change = MessagePackSerializer.Deserialize((ReadOnlyMemory)payload);
+ }
+ catch (Exception e)
+ {
+ _logger.LogError(e, "Failed to read the authority change at [{Position}]", position);
+ return new LogEntry(position, Change: null, Unreadable: true);
+ }
+
+ if (change is not null) return new LogEntry(position, change);
+
+ // A kind of change this version does not know, written by a newer one: it reads as nothing, not as an error.
+ _logger.LogWarning("The authority change at [{Position}] is of a kind this version does not know", position);
+ return new LogEntry(position, Change: null, Unreadable: true);
+ }
+
+ private static LogPosition Parse(RedisValue id) =>
+ LogPosition.TryParse(id, out var position) ? position : throw new FormatException($"Unexpected stream id '{id}'");
+}
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..3133ea2e
--- /dev/null
+++ b/Common/Hubs/ConnectionAuthorityHubFilter.cs
@@ -0,0 +1,109 @@
+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
+/// and since the last change announced for it. A call is
+/// refused when that cannot be established. Idle connections are checked by the registry's sweep.
+///
+///
+public sealed class ConnectionAuthorityHubFilter : IHubFilter
+{
+ 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