diff --git a/Notesnook.API/Controllers/UsersController.cs b/Notesnook.API/Controllers/UsersController.cs index 9c84172..72e3587 100644 --- a/Notesnook.API/Controllers/UsersController.cs +++ b/Notesnook.API/Controllers/UsersController.cs @@ -25,7 +25,6 @@ You should have received a copy of the Affero GNU General Public License using IdentityModel; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Timeouts; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Logging; @@ -270,7 +269,6 @@ public async Task Reset([FromForm] bool removeAttachments) } [HttpPost("delete")] - [RequestTimeout(5 * 60 * 1000)] public async Task Delete([FromForm] DeleteAccountForm form) { var userId = this.User.GetUserId(); diff --git a/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs b/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs new file mode 100644 index 0000000..44c0b1a --- /dev/null +++ b/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs @@ -0,0 +1,56 @@ +using System; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.DependencyInjection; +using MongoDB.Driver; +using Notesnook.API.Authorization; +using Notesnook.API.Interfaces; + +namespace Notesnook.API.Hubs +{ + // hub connections outlive their token, so a deleted user's open connection is cut off here instead + public class SyncAuthorizationHubFilter(IMemoryCache cache) : IHubFilter + { + // a stale answer only lets through writes that land well before UserPurgeJob's grace period ends + private static readonly TimeSpan CacheDuration = TimeSpan.FromMinutes(1); + + public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) + { + await EnsureNotDeletedAsync(invocationContext.Context, invocationContext.ServiceProvider); + return await next(invocationContext); + } + + public async Task OnConnectedAsync(HubLifetimeContext context, Func next) + { + var result = new SyncRequirement().IsAuthorized(context.Context.User, new PathString("/hubs/sync/v2")); + if (!result.Succeeded) + { + var reason = result.AuthorizationFailure?.FailureReasons.FirstOrDefault(); + throw new HubException(reason?.Message ?? "Unauthorized"); + } + await EnsureNotDeletedAsync(context.Context, context.ServiceProvider); + await next(context); + } + + private async Task EnsureNotDeletedAsync(HubCallerContext context, IServiceProvider services) + { + var userId = context.User?.FindFirstValue("sub"); + if (userId == null) return; + + var deleted = await cache.GetOrCreateAsync($"user_deleted:{userId}", async (entry) => + { + entry.AbsoluteExpirationRelativeToNow = CacheDuration; + return !await services.GetRequiredService().UsersSettings.Collection + .Find((s) => s.UserId == userId && s.DeletedAt == null).AnyAsync(); + }); + if (!deleted) return; + + context.Abort(); + throw new HubException("Please login to sync."); + } + } +} diff --git a/Notesnook.API/Hubs/SyncV2Hub.cs b/Notesnook.API/Hubs/SyncV2Hub.cs index 41ff702..349507c 100644 --- a/Notesnook.API/Hubs/SyncV2Hub.cs +++ b/Notesnook.API/Hubs/SyncV2Hub.cs @@ -27,13 +27,10 @@ You should have received a copy of the Affero GNU General Public License using System.Text.Json.Serialization; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Driver; -using Notesnook.API.Authorization; -using Notesnook.API.Extensions; using Notesnook.API.Helpers; using Notesnook.API.Interfaces; using Notesnook.API.Models; @@ -78,12 +75,6 @@ public SyncV2Hub(ISyncItemsRepositoryAccessor syncItemsRepositoryAccessor, IUnit public override async Task OnConnectedAsync() { - var result = new SyncRequirement().IsAuthorized(Context.User, new PathString("/hubs/sync/v2")); - if (!result.Succeeded) - { - var reason = result.AuthorizationFailure?.FailureReasons.FirstOrDefault(); - throw new HubException(reason?.Message ?? "Unauthorized"); - } var id = Context.User?.FindFirstValue("sub") ?? throw new HubException("User not found."); await Groups.AddToGroupAsync(Context.ConnectionId, id); await base.OnConnectedAsync(); diff --git a/Notesnook.API/Jobs/UserPurgeJob.cs b/Notesnook.API/Jobs/UserPurgeJob.cs new file mode 100644 index 0000000..33bab18 --- /dev/null +++ b/Notesnook.API/Jobs/UserPurgeJob.cs @@ -0,0 +1,83 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using MongoDB.Driver; +using Notesnook.API.Interfaces; +using Notesnook.API.Models; +using Notesnook.API.Services; +using Quartz; +using Streetwriters.Common; +using Streetwriters.Common.Accessors; +using Streetwriters.Common.Enums; +using Streetwriters.Common.Messages; + +namespace Notesnook.API.Jobs +{ + [DisallowConcurrentExecution] + public class UserPurgeJob(ISyncItemsRepositoryAccessor repositories, SyncDeviceService syncDeviceService, IS3Service s3Service, WampServiceAccessor serviceAccessor, ILogger logger) : IJob + { + // a token cached at deletion (30m) can still start a 5 GiB upload (90m) or get a presigned upload URL (1h), so those land before the purge + public static readonly TimeSpan GracePeriod = TimeSpan.FromMinutes(150); + + public WampServer SubscriptionServer { get; init; } = WampServers.SubscriptionServer; + + public async Task Execute(IJobExecutionContext context) + { + var cutoff = DateTimeOffset.UtcNow.Subtract(GracePeriod).ToUnixTimeMilliseconds(); + var users = await repositories.UsersSettings.Collection + .Find(Builders.Filter.Lt((s) => s.DeletedAt, cutoff)) + .Project((s) => new { s.UserId, s.DeletedAt }) + .ToListAsync(context.CancellationToken); + + foreach (var user in users) + { + context.CancellationToken.ThrowIfCancellationRequested(); + try + { + await PurgeAsync(user.UserId, user.DeletedAt!.Value); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to purge user {UserId}", user.UserId); + } + } + } + + // no transaction, since one this large outlives Mongo's time limit; every step is idempotent so a failed purge is retried + private async Task PurgeAsync(string userId, long deletedAt) + { + if (await serviceAccessor.UserAccountService.UserExistsAsync(userId)) + { + logger.LogWarning("User {UserId} was marked for deletion but still exists", userId); + // only the mark we saw, so a delete retried meanwhile keeps its own + await repositories.UsersSettings.Collection.UpdateOneAsync( + (s) => s.UserId == userId && s.DeletedAt == deletedAt, + Builders.Update.Unset((s) => s.DeletedAt)); + return; + } + + logger.LogInformation("Purging data of user {UserId}", userId); + + // first, so no new inbox items arrive while purging + await repositories.InboxApiKey.Collection.DeleteManyAsync((k) => k.UserId == userId); + foreach (var collection in repositories.SyncItemCollections) + await collection.Repository.Collection.DeleteManyAsync((i) => i.UserId == userId); + await repositories.InboxItems.Collection.DeleteManyAsync((i) => i.UserId == userId); + await repositories.Monographs.Collection.DeleteManyAsync((m) => m.UserId == userId); + await syncDeviceService.ResetDevicesAsync(userId); + await s3Service.DeleteDirectoryAsync(userId); + if (!Constants.IS_SELF_HOSTED) + { + await SubscriptionServer.PublishMessageAsync(SubscriptionServerTopics.DeleteSubscriptionTopic, new DeleteSubscriptionMessage + { + AppId = ApplicationType.NOTESNOOK, + UserId = userId + }); + } + + // last, as it marks the purge as unfinished + await repositories.UsersSettings.Collection.DeleteOneAsync((s) => s.UserId == userId); + logger.LogInformation("Purged data of user {UserId}", userId); + } + } +} diff --git a/Notesnook.API/Models/UserSettings.cs b/Notesnook.API/Models/UserSettings.cs index 508fbb5..37b3a0e 100644 --- a/Notesnook.API/Models/UserSettings.cs +++ b/Notesnook.API/Models/UserSettings.cs @@ -60,6 +60,7 @@ public UserSettings() /// public UserKeys? PendingKeys { get; set; } public long? PendingKeysSince { get; set; } + public long? DeletedAt { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)] diff --git a/Notesnook.API/Services/MongoIndexesHostedService.cs b/Notesnook.API/Services/MongoIndexesHostedService.cs index a597fd3..48362c4 100644 --- a/Notesnook.API/Services/MongoIndexesHostedService.cs +++ b/Notesnook.API/Services/MongoIndexesHostedService.cs @@ -55,7 +55,7 @@ public class MongoIndexesHostedService(IMongoClient client, ILogger u.UserId == userId); - Repositories.Monographs.DeleteMany((m) => m.UserId == userId); - Repositories.InboxApiKey.DeleteMany((t) => t.UserId == userId); - - var result = await unit.Commit(); - logger.LogInformation("User data deleted for user {UserId}: {Result}", userId, result); - if (!result) throw new Exception("Could not delete user data."); - - await syncDeviceService.ResetDevicesAsync(userId); - - if (!Constants.IS_SELF_HOSTED) + // marked first so a user gone from Identity is never left unpurged; upserted so a user without settings is still purged + try { - await WampServers.SubscriptionServer.PublishMessageAsync(SubscriptionServerTopics.DeleteSubscriptionTopic, new DeleteSubscriptionMessage - { - AppId = ApplicationType.NOTESNOOK, - UserId = userId - }); + await Repositories.UsersSettings.Collection.UpdateOneAsync( + Builders.Filter.Eq((s) => s.UserId, userId), + Builders.Update.Set((s) => s.DeletedAt, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()), + new UpdateOptions { IsUpsert = true }); } + // a concurrent delete upserted the settings first, so the user is already marked + catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey) { } - await DeleteAttachmentsAsync(userId); + await serviceAccessor.UserAccountService.UnregisterUserAsync(Clients.Notesnook.Id, userId); } public async Task DeleteUserAsync(string userId, string? jti, string password) { - logger.LogInformation("Deleting user account: {UserId}", userId); - // Identity's own "Wrong password." error only reaches us as a WAMP runtime error if (!await serviceAccessor.UserAccountService.VerifyPasswordAsync(userId, password)) throw new ClientException("Wrong password."); - await serviceAccessor.UserAccountService.DeleteUserAsync(Clients.Notesnook.Id, userId, password); await DeleteUserAsync(userId); diff --git a/Notesnook.API/Startup.cs b/Notesnook.API/Startup.cs index 57222ae..0eadb5a 100644 --- a/Notesnook.API/Startup.cs +++ b/Notesnook.API/Startup.cs @@ -38,6 +38,7 @@ You should have received a copy of the Affero GNU General Public License using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.ResponseCompression; +using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; @@ -253,7 +254,10 @@ public void ConfigureServices(IServiceCollection services) hub.ClientTimeoutInterval = TimeSpan.FromMinutes(10); // detailed errors expose internal (e.g. Mongo) exception messages to clients hub.EnableDetailedErrors = Environment.IsDevelopment(); - }).AddMessagePackProtocol().AddJsonProtocol(); + }).AddMessagePackProtocol().AddJsonProtocol() + .AddHubOptions((hub) => hub.AddFilter()); + services.AddMemoryCache(); + services.AddSingleton(); if (!string.IsNullOrEmpty(Constants.SIGNALR_REDIS_CONNECTION_STRING)) { @@ -312,6 +316,13 @@ public void ConfigureServices(IServiceCollection services) .WithIdentity("DeviceCleanup-trigger") // every day at midnight .WithCronSchedule("0 0 0 * * ? *")); + + var userPurgeJobKey = new JobKey("UserPurgeJob"); + q.AddJob(opts => opts.WithIdentity(userPurgeJobKey)); + q.AddTrigger(opts => opts + .ForJob(userPurgeJobKey) + .WithIdentity("UserPurge-trigger") + .WithSimpleSchedule((s) => s.WithIntervalInMinutes(5).RepeatForever())); }); } diff --git a/Streetwriters.Common/Interfaces/IUserAccountService.cs b/Streetwriters.Common/Interfaces/IUserAccountService.cs index 49ba98a..6d8061d 100644 --- a/Streetwriters.Common/Interfaces/IUserAccountService.cs +++ b/Streetwriters.Common/Interfaces/IUserAccountService.cs @@ -8,8 +8,11 @@ public interface IUserAccountService { [WampProcedure("co.streetwriters.identity.users.get_user")] Task GetUserAsync(string clientId, string userId); + // still called by API instances that predate background deletion; remove once they're all upgraded [WampProcedure("co.streetwriters.identity.users.delete_user")] Task DeleteUserAsync(string clientId, string userId, string password); + [WampProcedure("co.streetwriters.identity.users.user_exists")] + Task UserExistsAsync(string userId); [WampProcedure("co.streetwriters.identity.users.unregister_user")] Task UnregisterUserAsync(string clientId, string userId); [WampProcedure("co.streetwriters.identity.users.change_password")] diff --git a/Streetwriters.Identity/Interfaces/ISessionStore.cs b/Streetwriters.Identity/Interfaces/ISessionStore.cs index a96af5a..5b61c6e 100644 --- a/Streetwriters.Identity/Interfaces/ISessionStore.cs +++ b/Streetwriters.Identity/Interfaces/ISessionStore.cs @@ -34,6 +34,7 @@ public interface ISessionStore /// The keys under which introspection results of the ended sessions' tokens are cached. Task> EndSessionsAsync(string clientId, string subjectId, string? exceptJti, string? exceptRefreshToken); - Task EndAllSessionsAsync(string subjectId); + /// The keys under which introspection results of the ended sessions' tokens are cached. + Task> EndAllSessionsAsync(string subjectId); } } diff --git a/Streetwriters.Identity/Legacy/LegacyGrants.cs b/Streetwriters.Identity/Legacy/LegacyGrants.cs index a1b768e..1c2d1a8 100644 --- a/Streetwriters.Identity/Legacy/LegacyGrants.cs +++ b/Streetwriters.Identity/Legacy/LegacyGrants.cs @@ -124,7 +124,14 @@ public async Task> RemoveSessionsAsync(string subjectId, string cli public Task RemoveAccessTokensAsync(string subjectId, string clientId) => Grants.DeleteManyAsync(Builders.Filter.And(SubjectAndClient(subjectId, clientId), Builders.Filter.Eq("Type", ReferenceTokenType))); - public Task RemoveAllAsync(string subjectId) => Grants.DeleteManyAsync(new BsonDocument("SubjectId", subjectId)); + public async Task> RemoveAllAsync(string subjectId) + { + var filter = new BsonDocument("SubjectId", subjectId); + var removed = (await Grants.Find(filter).Project(Builders.Projection.Include("Key")).ToListAsync()) + .Select((d) => d["Key"].AsString).ToList(); + await Grants.DeleteManyAsync(filter); + return removed; + } public async Task RemoveExpiredAsync() => (await Grants.DeleteManyAsync(Builders.Filter.Lt("Expiration", timeProvider.GetUtcNow().UtcDateTime))).DeletedCount; diff --git a/Streetwriters.Identity/OpenIddictEngine/OpenIddictSessionStore.cs b/Streetwriters.Identity/OpenIddictEngine/OpenIddictSessionStore.cs index e7ba9de..daadbd8 100644 --- a/Streetwriters.Identity/OpenIddictEngine/OpenIddictSessionStore.cs +++ b/Streetwriters.Identity/OpenIddictEngine/OpenIddictSessionStore.cs @@ -77,15 +77,14 @@ public async Task> EndSessionsAsync(string clientId, string subject return [.. await EndAsync(ended), .. await legacyGrants.RemoveSessionsAsync(subjectId, clientId, exceptJti, exceptRefreshToken)]; } - public async Task EndAllSessionsAsync(string subjectId) + public async Task> EndAllSessionsAsync(string subjectId) { var ended = new List(); await foreach (var authorization in authorizations.FindBySubjectAsync(subjectId)) { if (await authorizations.GetIdAsync(authorization) is string id) ended.Add(id); } - await EndAsync(ended); - await legacyGrants.RemoveAllAsync(subjectId); + return [.. await EndAsync(ended), .. await legacyGrants.RemoveAllAsync(subjectId)]; } /// The keys under which introspection results of the sessions' access tokens are cached. diff --git a/Streetwriters.Identity/Services/PersistedGrantSessionStore.cs b/Streetwriters.Identity/Services/PersistedGrantSessionStore.cs index 0f416cd..c24b862 100644 --- a/Streetwriters.Identity/Services/PersistedGrantSessionStore.cs +++ b/Streetwriters.Identity/Services/PersistedGrantSessionStore.cs @@ -65,9 +65,12 @@ public async Task> EndSessionsAsync(string clientId, string subject return removedKeys; } - public Task EndAllSessionsAsync(string subjectId) + public async Task> EndAllSessionsAsync(string subjectId) { - return persistedGrantStore.RemoveAllAsync(new PersistedGrantFilter { SubjectId = subjectId }); + var filter = new PersistedGrantFilter { SubjectId = subjectId }; + var keys = (await persistedGrantStore.GetAllAsync(filter)).Select((grant) => grant.Key).ToList(); + await persistedGrantStore.RemoveAllAsync(filter); + return keys; } } } diff --git a/Streetwriters.Identity/Services/ScopedUserAccountService.cs b/Streetwriters.Identity/Services/ScopedUserAccountService.cs index fa8972a..a0a2098 100644 --- a/Streetwriters.Identity/Services/ScopedUserAccountService.cs +++ b/Streetwriters.Identity/Services/ScopedUserAccountService.cs @@ -36,6 +36,7 @@ private async Task WithServiceAsync(Func> act public Task GetUserAsync(string clientId, string userId) => WithServiceAsync((s) => s.GetUserAsync(clientId, userId)); public Task DeleteUserAsync(string clientId, string userId, string password) => WithServiceAsync(async (s) => { await s.DeleteUserAsync(clientId, userId, password); return true; }); + public Task UserExistsAsync(string userId) => WithServiceAsync((s) => s.UserExistsAsync(userId)); public Task UnregisterUserAsync(string clientId, string userId) => WithServiceAsync(async (s) => { await s.UnregisterUserAsync(clientId, userId); return true; }); public Task ChangePasswordAsync(string userId, string oldPassword, string newPassword) => WithServiceAsync((s) => s.ChangePasswordAsync(userId, oldPassword, newPassword)); public Task ResetPasswordAsync(string userId, string newPassword) => WithServiceAsync((s) => s.ResetPasswordAsync(userId, newPassword)); diff --git a/Streetwriters.Identity/Services/UserAccountService.cs b/Streetwriters.Identity/Services/UserAccountService.cs index b238711..acd6edc 100644 --- a/Streetwriters.Identity/Services/UserAccountService.cs +++ b/Streetwriters.Identity/Services/UserAccountService.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; +using MongoDB.Bson; using MongoDB.Driver; using Streetwriters.Common; using Streetwriters.Common.Enums; @@ -62,13 +63,29 @@ public async Task DeleteUserAsync(string clientId, string userId, string passwor await sessionStore.EndAllSessionsAsync(userId); } + // a malformed id makes FindByIdAsync throw, and can never belong to a user + public async Task UserExistsAsync(string userId) => ObjectId.TryParse(userId, out _) && await userManager.FindByIdAsync(userId) != null; + public async Task UnregisterUserAsync(string clientId, string userId) { var user = await userManager.FindByIdAsync(userId); - if (user == null || !await UserService.IsUserValidAsync(userManager, user, clientId)) return; + if (user == null) return; + if (!await UserService.IsUserValidAsync(userManager, user, clientId)) throw new Exception($"Unable to find user with ID '{user.Id}'."); - await userManager.DeleteAsync(user); - await sessionStore.EndAllSessionsAsync(userId); + // sessions end first, so a failure leaves a signed-out user who can retry rather than a deleted one still signed in + var removedKeys = await sessionStore.EndAllSessionsAsync(userId); + var result = await userManager.DeleteAsync(user); + if (!result.Succeeded) throw new Exception($"Failed to delete user {userId}: {string.Join(", ", result.Errors.Select((e) => e.Description))}"); + + // the user is already deleted, and cached tokens expire before UserPurgeJob runs + try + { + await PublishClearCacheAsync(removedKeys); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to clear the token cache of unregistered user {UserId}", userId); + } } public async Task ChangePasswordAsync(string userId, string oldPassword, string newPassword) @@ -120,14 +137,19 @@ public async Task ClearSessionsAsync(string userId, string clientId, bool ? await sessionStore.EndSessionsAsync(client.Id, user.Id.ToString(), null, null) : await sessionStore.EndSessionsAsync(client.Id, user.Id.ToString(), jti, refreshToken); - await WampServers.NotesnookServer.PublishMessageAsync(IdentityServerTopics.ClearCacheTopic, new ClearCacheMessage(removedKeys)); - await WampServers.MessengerServer.PublishMessageAsync(IdentityServerTopics.ClearCacheTopic, new ClearCacheMessage(removedKeys)); + await PublishClearCacheAsync(removedKeys); + // await SendLogoutMessageAsync(user.Id.ToString(), "Session revoked."); + return true; + } + + private static async Task PublishClearCacheAsync(List keys) + { + await WampServers.NotesnookServer.PublishMessageAsync(IdentityServerTopics.ClearCacheTopic, new ClearCacheMessage(keys)); + await WampServers.MessengerServer.PublishMessageAsync(IdentityServerTopics.ClearCacheTopic, new ClearCacheMessage(keys)); if (!Constants.IS_SELF_HOSTED) { - await WampServers.SubscriptionServer.PublishMessageAsync(IdentityServerTopics.ClearCacheTopic, new ClearCacheMessage(removedKeys)); + await WampServers.SubscriptionServer.PublishMessageAsync(IdentityServerTopics.ClearCacheTopic, new ClearCacheMessage(keys)); } - // await SendLogoutMessageAsync(user.Id.ToString(), "Session revoked."); - return true; } public async Task CreateUserAsync(string clientId, string email, string password, string? userAgent = null) diff --git a/tests/Notesnook.API.Tests/ApiErrorResponseTests.cs b/tests/Notesnook.API.Tests/ApiErrorResponseTests.cs index 2032a76..5be34ec 100644 --- a/tests/Notesnook.API.Tests/ApiErrorResponseTests.cs +++ b/tests/Notesnook.API.Tests/ApiErrorResponseTests.cs @@ -118,7 +118,7 @@ public async Task Deleting_with_a_wrong_password_is_a_400() var deleted = false; var identity = Stub.Create( ("VerifyPasswordAsync", (_) => Task.FromResult(false)), - ("DeleteUserAsync", (_) => { deleted = true; return Task.CompletedTask; })); + ("UnregisterUserAsync", (_) => { deleted = true; return Task.CompletedTask; })); await using var api = new Api(db, identity); var response = await api.Client.PostAsync("/users/delete", new FormUrlEncodedContent(new Dictionary { ["password"] = "wrong" })); diff --git a/tests/Notesnook.API.Tests/SyncV2HubTests.cs b/tests/Notesnook.API.Tests/SyncV2HubTests.cs index b6511a6..efaa9b3 100644 --- a/tests/Notesnook.API.Tests/SyncV2HubTests.cs +++ b/tests/Notesnook.API.Tests/SyncV2HubTests.cs @@ -1,9 +1,12 @@ using System.Security.Claims; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using MongoDB.Driver; using Notesnook.API.Hubs; +using Notesnook.API.Interfaces; using Notesnook.API.Models; using Notesnook.API.Services; @@ -11,17 +14,21 @@ namespace Notesnook.API.Tests; public class SyncV2HubTests(TestDatabase db) : IClassFixture { - private sealed class Caller(string userId) : HubCallerContext + private sealed class Caller(string userId, params Claim[] claims) : HubCallerContext { public override string ConnectionId => "connection"; public override string? UserIdentifier => userId; - public override ClaimsPrincipal? User { get; } = new(new ClaimsIdentity([new Claim("sub", userId)], "Test")); + public override ClaimsPrincipal? User { get; } = new(new ClaimsIdentity([new Claim("sub", userId), .. claims], "Test")); public override IDictionary Items { get; } = new Dictionary(); public override IFeatureCollection Features { get; } = new FeatureCollection(); public override CancellationToken ConnectionAborted => CancellationToken.None; - public override void Abort() { } + public bool Aborted { get; private set; } + public override void Abort() => Aborted = true; } + private static readonly Claim[] SyncClaims = [new("scope", "notesnook.sync"), new("aud", "notesnook"), new("role", "notesnook"), new("verified", "true")]; + private static Caller SyncCaller(string userId) => new(userId, SyncClaims); + private SyncV2Hub Hub(string userId) { var scope = db.CreateScope(); @@ -43,6 +50,71 @@ public async Task A_missing_device_id_is_rejected(string? deviceId) Assert.Equal(0, await db.CreateScope().Repositories.SyncDevices.Collection.CountDocumentsAsync((d) => d.UserId == userId)); } + [Fact] + public async Task Connecting_requires_sync_access() + { + var userId = Guid.NewGuid().ToString("N"); + var filter = new SyncAuthorizationHubFilter(new MemoryCache(new MemoryCacheOptions())); + var services = new ServiceCollection().BuildServiceProvider(); + + var error = await Assert.ThrowsAsync(() => filter.OnConnectedAsync( + new HubLifetimeContext(new Caller(userId, SyncClaims[..^1]), services, Hub(userId)), + (_) => throw new Exception("connected"))); + + Assert.Equal("Please confirm your email to sync your notes.", error.Message); + } + + [Fact] + public async Task A_deleted_user_is_cut_off_but_a_live_user_is_not() + { + var (deleted, live) = (Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N")); + var scope = db.CreateScope(); + await scope.Repositories.UsersSettings.Collection.InsertManyAsync([ + new UserSettings { UserId = deleted, Salt = "salt", DeletedAt = 1 }, + new UserSettings { UserId = live, Salt = "salt" }]); + var services = new ServiceCollection().AddSingleton(scope.Repositories).BuildServiceProvider(); + var filter = new SyncAuthorizationHubFilter(new MemoryCache(new MemoryCacheOptions())); + var connected = new List(); + Task Connect(string userId) => filter.OnConnectedAsync(new HubLifetimeContext(SyncCaller(userId), services, Hub(userId)), (_) => { connected.Add(userId); return Task.CompletedTask; }); + + var error = await Assert.ThrowsAsync(() => Connect(deleted)); + await Connect(live); + + Assert.Equal("Please login to sync.", error.Message); + Assert.Equal([live], connected); + } + + private sealed class Clock : Microsoft.Extensions.Internal.ISystemClock + { + public DateTimeOffset UtcNow { get; set; } = DateTimeOffset.UtcNow; + } + + [Fact] + public async Task An_open_connection_is_cut_off_once_its_user_is_deleted() + { + var userId = Guid.NewGuid().ToString("N"); + var scope = db.CreateScope(); + await scope.Repositories.UsersSettings.Collection.InsertOneAsync(new UserSettings { UserId = userId, Salt = "salt" }); + var services = new ServiceCollection().AddSingleton(scope.Repositories).BuildServiceProvider(); + var clock = new Clock(); + var filter = new SyncAuthorizationHubFilter(new MemoryCache(new MemoryCacheOptions { Clock = clock })); + var caller = SyncCaller(userId); + var invoked = 0; + ValueTask Invoke() => filter.InvokeMethodAsync( + new HubInvocationContext(caller, services, Hub(userId), typeof(SyncV2Hub).GetMethod(nameof(SyncV2Hub.PushCompleted))!, []), + (_) => { invoked++; return ValueTask.FromResult(null); }); + + await Invoke(); + await scope.Repositories.UsersSettings.Collection.UpdateOneAsync((s) => s.UserId == userId, Builders.Update.Set((s) => s.DeletedAt, 1)); + clock.UtcNow += TimeSpan.FromMinutes(2); + + var error = await Assert.ThrowsAsync(async () => await Invoke()); + + Assert.Equal("Please login to sync.", error.Message); + Assert.Equal(1, invoked); + Assert.True(caller.Aborted); + } + [Fact] public async Task A_monograph_without_an_item_id_is_sent_by_its_object_id() { diff --git a/tests/Notesnook.API.Tests/UserPurgeJobTests.cs b/tests/Notesnook.API.Tests/UserPurgeJobTests.cs new file mode 100644 index 0000000..c701f55 --- /dev/null +++ b/tests/Notesnook.API.Tests/UserPurgeJobTests.cs @@ -0,0 +1,181 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Sockets; +using Microsoft.Extensions.Logging.Abstractions; +using MongoDB.Driver; +using Notesnook.API.Interfaces; +using Notesnook.API.Jobs; +using Notesnook.API.Models; +using Notesnook.API.Services; +using Quartz; +using Streetwriters.Common; +using Streetwriters.Common.Accessors; +using Streetwriters.Common.Interfaces; +using Streetwriters.Common.Messages; +using WampSharp.V2; + +namespace Notesnook.API.Tests; + +public class UserPurgeJobTests : IClassFixture, IDisposable +{ + private readonly TestDatabase db; + private readonly DefaultWampHost subscriptionServer; + private readonly WampServer subscriptionClient; + private readonly ConcurrentQueue deletedSubscriptions = new(); + + public UserPurgeJobTests(TestDatabase db) + { + this.db = db; + // the client derives its auth token from this; the test router doesn't check it + Environment.SetEnvironmentVariable("NOTESNOOK_API_SECRET", "test-secret"); + + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + + subscriptionServer = new DefaultWampHost($"ws://127.0.0.1:{port}/wamp"); + subscriptionServer.RealmContainer.GetRealmByName("messages").Services + .GetSubject(SubscriptionServerTopics.DeleteSubscriptionTopic) + .Subscribe((m) => deletedSubscriptions.Enqueue(m.UserId), (_) => { }); + subscriptionServer.Open(); + subscriptionClient = new WampServer { Endpoint = "/wamp", Port = port, Address = $"ws://127.0.0.1:{port}/wamp", Realm = "messages" }; + } + + public void Dispose() => subscriptionServer.Dispose(); + + private static string NewUserId() => Guid.NewGuid().ToString("N"); + private static readonly long LongAgo = DateTimeOffset.UtcNow.AddHours(-3).ToUnixTimeMilliseconds(); + + private static IJobExecutionContext Context => Stub.Create(("get_CancellationToken", (_) => CancellationToken.None)); + + private static IUserAccountService Identity(Func exists) => + Stub.Create(("UserExistsAsync", (args) => Task.FromResult(exists((string)args[0]!)))); + + private static IS3Service S3(Func? deleteDirectory = null) => + Stub.Create(("DeleteDirectoryAsync", (args) => deleteDirectory?.Invoke((string)args[0]!) ?? Task.CompletedTask)); + + private Task RunAsync(IUserAccountService identity, IS3Service s3) + { + var scope = db.CreateScope(); + var accessor = new WampServiceAccessor(Servers.NotesnookAPI) { UserAccountService = identity }; + return new UserPurgeJob(scope.Repositories, scope.Devices, s3, accessor, NullLogger.Instance) { SubscriptionServer = subscriptionClient }.Execute(Context); + } + + private async Task CreateUserAsync(string userId, long? deletedAt) + { + var scope = db.CreateScope(); + await scope.Repositories.UsersSettings.Collection.InsertOneAsync(new UserSettings { UserId = userId, Salt = "salt", DeletedAt = deletedAt }); + await scope.Repositories.Notes.Collection.InsertOneAsync(new SyncItem { UserId = userId, ItemId = "note" }); + await scope.Devices.RegisterDeviceAsync(userId, "device"); + } + + private static async Task WaitUntilAsync(Func condition) + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + while (!condition()) + await Task.Delay(100, cts.Token); + } + + private Task SettingsAsync(string userId) => + db.CreateScope().Repositories.UsersSettings.Collection.Find((s) => s.UserId == userId).FirstOrDefaultAsync()!; + + private Task CountNotesAsync(string userId) => + db.CreateScope().Repositories.Notes.Collection.CountDocumentsAsync((i) => i.UserId == userId); + + private Task CountDevicesAsync(string userId) => + db.CreateScope().Repositories.SyncDevices.Collection.CountDocumentsAsync((d) => d.UserId == userId); + + [Fact] + public async Task Purges_a_deleted_user_but_not_another_user() + { + var (deleted, other) = (NewUserId(), NewUserId()); + await CreateUserAsync(deleted, LongAgo); + await CreateUserAsync(other, null); + var purgedDirectories = new ConcurrentQueue(); + + await RunAsync(Identity((id) => id == other), S3((id) => { purgedDirectories.Enqueue(id); return Task.CompletedTask; })); + + Assert.Null(await SettingsAsync(deleted)); + Assert.Equal(0, await CountNotesAsync(deleted)); + Assert.Equal(0, await CountDevicesAsync(deleted)); + Assert.Contains(deleted, purgedDirectories); + Assert.DoesNotContain(other, purgedDirectories); + await WaitUntilAsync(() => deletedSubscriptions.Contains(deleted)); + Assert.DoesNotContain(other, deletedSubscriptions); + Assert.NotNull(await SettingsAsync(other)); + Assert.Equal(1, await CountNotesAsync(other)); + Assert.Equal(1, await CountDevicesAsync(other)); + } + + [Fact] + public async Task A_user_that_still_exists_keeps_its_data_and_loses_the_mark() + { + var userId = NewUserId(); + await CreateUserAsync(userId, LongAgo); + + await RunAsync(Identity((_) => true), S3()); + + Assert.Null((await SettingsAsync(userId))!.DeletedAt); + Assert.Equal(1, await CountNotesAsync(userId)); + } + + [Fact] + public async Task A_delete_retried_during_the_existence_check_keeps_its_mark() + { + var userId = NewUserId(); + await CreateUserAsync(userId, LongAgo); + var retriedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + async Task RetryThenExist() + { + await db.CreateScope().Repositories.UsersSettings.Collection.UpdateOneAsync((s) => s.UserId == userId, Builders.Update.Set((s) => s.DeletedAt, retriedAt)); + return true; + } + + await RunAsync(Stub.Create(("UserExistsAsync", (_) => RetryThenExist())), S3()); + + Assert.Equal(retriedAt, (await SettingsAsync(userId))!.DeletedAt); + } + + [Fact] + public async Task A_user_deleted_within_the_grace_period_is_left_alone() + { + var userId = NewUserId(); + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + await CreateUserAsync(userId, now); + + await RunAsync(Identity((_) => false), S3()); + + Assert.Equal(now, (await SettingsAsync(userId))!.DeletedAt); + Assert.Equal(1, await CountNotesAsync(userId)); + } + + [Fact] + public async Task A_failed_purge_keeps_the_mark_and_the_next_run_finishes_it() + { + var userId = NewUserId(); + await CreateUserAsync(userId, LongAgo); + + await RunAsync(Identity((_) => false), S3((_) => throw new Exception("S3 is down"))); + + Assert.Equal(LongAgo, (await SettingsAsync(userId))!.DeletedAt); + + await RunAsync(Identity((_) => false), S3()); + + Assert.Null(await SettingsAsync(userId)); + Assert.Equal(0, await CountNotesAsync(userId)); + } + + [Fact] + public async Task An_unreachable_identity_leaves_the_user_untouched() + { + var userId = NewUserId(); + await CreateUserAsync(userId, LongAgo); + + await RunAsync(Stub.Create(("UserExistsAsync", (_) => Task.FromException(new TimeoutException()))), S3()); + + Assert.Equal(LongAgo, (await SettingsAsync(userId))!.DeletedAt); + Assert.Equal(1, await CountNotesAsync(userId)); + } +} diff --git a/tests/Streetwriters.Identity.Tests/TokenContractTests.cs b/tests/Streetwriters.Identity.Tests/TokenContractTests.cs index 94f355b..e45ea34 100644 --- a/tests/Streetwriters.Identity.Tests/TokenContractTests.cs +++ b/tests/Streetwriters.Identity.Tests/TokenContractTests.cs @@ -444,8 +444,8 @@ public async Task Users_are_unregistered_without_their_password() await host.WithServicesAsync(async (services) => { var accounts = services.GetRequiredService(); - // another client's user, and one that doesn't exist, are left alone - await accounts.UnregisterUserAsync("another-client", signup.UserId); + // another client's user is refused, and one that doesn't exist is left alone + await Assert.ThrowsAnyAsync(() => accounts.UnregisterUserAsync("another-client", signup.UserId)); Assert.NotNull(await services.GetRequiredService>().FindByIdAsync(signup.UserId)); await accounts.UnregisterUserAsync(ClientId, MongoDB.Bson.ObjectId.GenerateNewId().ToString());