From 9d1b0906b66b223524c3335dabc6ecc70552b9bc Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Thu, 29 Oct 2026 09:33:30 +0500 Subject: [PATCH 1/3] api: delete users in the background Deleting a large account ran every collection's delete in one Mongo transaction, which outlived Mongo's time limit and the request timeout. The delete now marks the user's settings with DeletedAt and unregisters the user from Identity, and UserPurgeJob purges the data after a grace period, one idempotent step at a time, retrying until it's done. A user that still exists in Identity is unmarked instead of purged. A deleted user's open sync connections are cut off by a hub filter, which also takes over the sync access check, and unregistering clears the user's cached token introspection. Identity drops delete_user and adds user_exists, so it must be deployed before this API. --- Notesnook.API/Controllers/UsersController.cs | 2 - .../UserSettingsRepositoryExtensions.cs | 13 ++ .../Hubs/SyncAuthorizationHubFilter.cs | 55 ++++++ Notesnook.API/Hubs/SyncV2Hub.cs | 9 - Notesnook.API/Jobs/UserPurgeJob.cs | 87 ++++++++++ Notesnook.API/Models/UserSettings.cs | 1 + .../Services/MongoIndexesHostedService.cs | 2 +- Notesnook.API/Services/UserService.cs | 29 +--- Notesnook.API/Startup.cs | 13 +- .../Interfaces/IUserAccountService.cs | 4 +- .../Interfaces/ISessionStore.cs | 3 +- Streetwriters.Identity/Legacy/LegacyGrants.cs | 9 +- .../OpenIddictSessionStore.cs | 5 +- .../Services/PersistedGrantSessionStore.cs | 7 +- .../Services/ScopedUserAccountService.cs | 2 +- .../Services/UserAccountService.cs | 47 +++-- .../ApiErrorResponseTests.cs | 2 +- tests/Notesnook.API.Tests/SyncV2HubTests.cs | 44 ++++- .../Notesnook.API.Tests/UserPurgeJobTests.cs | 163 ++++++++++++++++++ .../TokenContractTests.cs | 17 +- 20 files changed, 435 insertions(+), 79 deletions(-) create mode 100644 Notesnook.API/Extensions/UserSettingsRepositoryExtensions.cs create mode 100644 Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs create mode 100644 Notesnook.API/Jobs/UserPurgeJob.cs create mode 100644 tests/Notesnook.API.Tests/UserPurgeJobTests.cs 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/Extensions/UserSettingsRepositoryExtensions.cs b/Notesnook.API/Extensions/UserSettingsRepositoryExtensions.cs new file mode 100644 index 0000000..b030c9f --- /dev/null +++ b/Notesnook.API/Extensions/UserSettingsRepositoryExtensions.cs @@ -0,0 +1,13 @@ +using System.Threading.Tasks; +using MongoDB.Driver; +using Notesnook.API.Models; +using Streetwriters.Data.Repositories; + +namespace Notesnook.API.Extensions +{ + public static class UserSettingsRepositoryExtensions + { + public static async Task IsUserDeletedAsync(this Repository settings, string userId) + => !await settings.Collection.Find((s) => s.UserId == userId && s.DeletedAt == null).AnyAsync(); + } +} diff --git a/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs b/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs new file mode 100644 index 0000000..521ed8a --- /dev/null +++ b/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs @@ -0,0 +1,55 @@ +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 Notesnook.API.Authorization; +using Notesnook.API.Extensions; +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}", (entry) => + { + entry.AbsoluteExpirationRelativeToNow = CacheDuration; + return services.GetRequiredService().UsersSettings.IsUserDeletedAsync(userId); + }); + 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..985c6e0 --- /dev/null +++ b/Notesnook.API/Jobs/UserPurgeJob.cs @@ -0,0 +1,87 @@ +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 + { + // longer than a cached token's introspection (30m) and a presigned upload URL (1h), so writes made with either land before the purge + public static readonly TimeSpan GracePeriod = TimeSpan.FromMinutes(75); + + public WampServer SubscriptionServer { get; init; } = WampServers.SubscriptionServer; + + public async Task Execute(IJobExecutionContext context) + { + var cutoff = DateTimeOffset.UtcNow.Subtract(GracePeriod).ToUnixTimeMilliseconds(); + var userIds = await repositories.UsersSettings.Collection + .Find(Builders.Filter.Lt((s) => s.DeletedAt, cutoff)) + .Project((s) => s.UserId) + .ToListAsync(context.CancellationToken); + + foreach (var userId in userIds) + { + context.CancellationToken.ThrowIfCancellationRequested(); + try + { + await PurgeAsync(userId); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to purge user {UserId}", userId); + } + } + } + + private async Task PurgeAsync(string userId) + { + if (await serviceAccessor.UserAccountService.UserExistsAsync(userId)) + { + logger.LogWarning("User {UserId} was marked for deletion but still exists", userId); + await repositories.UsersSettings.Collection.UpdateOneAsync( + Builders.Filter.Eq((s) => s.UserId, userId), + Builders.Update.Unset((s) => s.DeletedAt)); + return; + } + + await PurgeUserAsync(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 PurgeUserAsync(string userId) + { + 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(Builders.Filter.Eq("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) @@ -214,7 +204,6 @@ public async Task DeleteUserAsync(string userId, string? jti, string password) // 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..5d725cd 100644 --- a/Streetwriters.Common/Interfaces/IUserAccountService.cs +++ b/Streetwriters.Common/Interfaces/IUserAccountService.cs @@ -8,8 +8,8 @@ public interface IUserAccountService { [WampProcedure("co.streetwriters.identity.users.get_user")] Task GetUserAsync(string clientId, string userId); - [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..e618c10 100644 --- a/Streetwriters.Identity/Services/ScopedUserAccountService.cs +++ b/Streetwriters.Identity/Services/ScopedUserAccountService.cs @@ -35,7 +35,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..6b2cd00 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; @@ -51,24 +52,29 @@ public class UserAccountService(UserManager userManager, IMFAService mfaSe }; } - public async Task DeleteUserAsync(string clientId, string userId, string password) - { - var user = await userManager.FindByIdAsync(userId); - if (user == null || !await UserService.IsUserValidAsync(userManager, user, clientId)) return; - - if (!await userManager.CheckPasswordAsync(user, password)) throw new Exception("Wrong password."); - - await userManager.DeleteAsync(user); - 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 +126,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..41725e0 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,20 @@ 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() { } } + private static Caller SyncCaller(string userId) => + new(userId, new Claim("scope", "notesnook.sync"), new Claim("aud", "notesnook"), new Claim("role", "notesnook"), new Claim("verified", "true")); + private SyncV2Hub Hub(string userId) { var scope = db.CreateScope(); @@ -43,6 +49,40 @@ 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, new Claim("scope", "notesnook.sync"), new Claim("aud", "notesnook"), new Claim("role", "notesnook")), 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); + } + [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..6ba8f69 --- /dev/null +++ b/tests/Notesnook.API.Tests/UserPurgeJobTests.cs @@ -0,0 +1,163 @@ +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(-2).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_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..4e64aeb 100644 --- a/tests/Streetwriters.Identity.Tests/TokenContractTests.cs +++ b/tests/Streetwriters.Identity.Tests/TokenContractTests.cs @@ -421,19 +421,6 @@ public async Task Refresh_rejects_unknown_token() await Golden.AssertMatchesAsync("refresh.unknown", await RefreshAsync("ABCDEF")); } - [Fact] - public async Task Deleted_users_tokens_stop_working() - { - var email = NewEmail(); - var signup = await SignupAsync(email); - var (access, refresh) = await LoginAsync(email); - - await host.WithServicesAsync(async (services) => { await services.GetRequiredService().DeleteUserAsync(ClientId, signup.UserId, Password); return 0; }); - - await Golden.AssertMatchesAsync("deleted.introspection", await IntrospectAsync(access)); - await Golden.AssertMatchesAsync("deleted.refresh", await RefreshAsync(refresh)); - } - [Fact] public async Task Users_are_unregistered_without_their_password() { @@ -444,8 +431,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()); From c7de66c1f103ab520aef718961436eb93d8ce476 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Thu, 29 Oct 2026 09:39:27 +0500 Subject: [PATCH 2/3] api: simplify the background user deletion --- .../Extensions/UserSettingsRepositoryExtensions.cs | 13 ------------- Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs | 7 ++++--- Notesnook.API/Jobs/UserPurgeJob.cs | 9 ++------- Notesnook.API/Services/UserService.cs | 2 -- tests/Notesnook.API.Tests/SyncV2HubTests.cs | 6 +++--- 5 files changed, 9 insertions(+), 28 deletions(-) delete mode 100644 Notesnook.API/Extensions/UserSettingsRepositoryExtensions.cs diff --git a/Notesnook.API/Extensions/UserSettingsRepositoryExtensions.cs b/Notesnook.API/Extensions/UserSettingsRepositoryExtensions.cs deleted file mode 100644 index b030c9f..0000000 --- a/Notesnook.API/Extensions/UserSettingsRepositoryExtensions.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Threading.Tasks; -using MongoDB.Driver; -using Notesnook.API.Models; -using Streetwriters.Data.Repositories; - -namespace Notesnook.API.Extensions -{ - public static class UserSettingsRepositoryExtensions - { - public static async Task IsUserDeletedAsync(this Repository settings, string userId) - => !await settings.Collection.Find((s) => s.UserId == userId && s.DeletedAt == null).AnyAsync(); - } -} diff --git a/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs b/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs index 521ed8a..44c0b1a 100644 --- a/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs +++ b/Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs @@ -6,8 +6,8 @@ using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; +using MongoDB.Driver; using Notesnook.API.Authorization; -using Notesnook.API.Extensions; using Notesnook.API.Interfaces; namespace Notesnook.API.Hubs @@ -41,10 +41,11 @@ private async Task EnsureNotDeletedAsync(HubCallerContext context, IServiceProvi var userId = context.User?.FindFirstValue("sub"); if (userId == null) return; - var deleted = await cache.GetOrCreateAsync($"user_deleted:{userId}", (entry) => + var deleted = await cache.GetOrCreateAsync($"user_deleted:{userId}", async (entry) => { entry.AbsoluteExpirationRelativeToNow = CacheDuration; - return services.GetRequiredService().UsersSettings.IsUserDeletedAsync(userId); + return !await services.GetRequiredService().UsersSettings.Collection + .Find((s) => s.UserId == userId && s.DeletedAt == null).AnyAsync(); }); if (!deleted) return; diff --git a/Notesnook.API/Jobs/UserPurgeJob.cs b/Notesnook.API/Jobs/UserPurgeJob.cs index 985c6e0..edf2cbf 100644 --- a/Notesnook.API/Jobs/UserPurgeJob.cs +++ b/Notesnook.API/Jobs/UserPurgeJob.cs @@ -43,6 +43,7 @@ public async Task Execute(IJobExecutionContext context) } } + // 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) { if (await serviceAccessor.UserAccountService.UserExistsAsync(userId)) @@ -54,18 +55,12 @@ await repositories.UsersSettings.Collection.UpdateOneAsync( return; } - await PurgeUserAsync(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 PurgeUserAsync(string userId) - { 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(Builders.Filter.Eq("UserId", userId)); + 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); diff --git a/Notesnook.API/Services/UserService.cs b/Notesnook.API/Services/UserService.cs index 9bee29a..3d7ddcd 100644 --- a/Notesnook.API/Services/UserService.cs +++ b/Notesnook.API/Services/UserService.cs @@ -199,8 +199,6 @@ await Repositories.UsersSettings.Collection.UpdateOneAsync( 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."); diff --git a/tests/Notesnook.API.Tests/SyncV2HubTests.cs b/tests/Notesnook.API.Tests/SyncV2HubTests.cs index 41725e0..c14eab2 100644 --- a/tests/Notesnook.API.Tests/SyncV2HubTests.cs +++ b/tests/Notesnook.API.Tests/SyncV2HubTests.cs @@ -25,8 +25,8 @@ private sealed class Caller(string userId, params Claim[] claims) : HubCallerCon public override void Abort() { } } - private static Caller SyncCaller(string userId) => - new(userId, new Claim("scope", "notesnook.sync"), new Claim("aud", "notesnook"), new Claim("role", "notesnook"), new Claim("verified", "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) { @@ -57,7 +57,7 @@ public async Task Connecting_requires_sync_access() var services = new ServiceCollection().BuildServiceProvider(); var error = await Assert.ThrowsAsync(() => filter.OnConnectedAsync( - new HubLifetimeContext(new Caller(userId, new Claim("scope", "notesnook.sync"), new Claim("aud", "notesnook"), new Claim("role", "notesnook")), services, Hub(userId)), + 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); From 9c46ea8a38cb39c8440419816ea7e047afada957 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Thu, 29 Oct 2026 09:48:01 +0500 Subject: [PATCH 3/3] api: address review of the background user deletion Covers uploads admitted by a cached token in the grace period, keeps a mark set by a retried delete, tests that open connections are cut off, and keeps delete_user for API instances that predate this change. --- Notesnook.API/Jobs/UserPurgeJob.cs | 19 ++++++----- .../Interfaces/IUserAccountService.cs | 3 ++ .../Services/ScopedUserAccountService.cs | 1 + .../Services/UserAccountService.cs | 11 ++++++ tests/Notesnook.API.Tests/SyncV2HubTests.cs | 34 ++++++++++++++++++- .../Notesnook.API.Tests/UserPurgeJobTests.cs | 20 ++++++++++- .../TokenContractTests.cs | 13 +++++++ 7 files changed, 90 insertions(+), 11 deletions(-) diff --git a/Notesnook.API/Jobs/UserPurgeJob.cs b/Notesnook.API/Jobs/UserPurgeJob.cs index edf2cbf..33bab18 100644 --- a/Notesnook.API/Jobs/UserPurgeJob.cs +++ b/Notesnook.API/Jobs/UserPurgeJob.cs @@ -16,41 +16,42 @@ namespace Notesnook.API.Jobs [DisallowConcurrentExecution] public class UserPurgeJob(ISyncItemsRepositoryAccessor repositories, SyncDeviceService syncDeviceService, IS3Service s3Service, WampServiceAccessor serviceAccessor, ILogger logger) : IJob { - // longer than a cached token's introspection (30m) and a presigned upload URL (1h), so writes made with either land before the purge - public static readonly TimeSpan GracePeriod = TimeSpan.FromMinutes(75); + // 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 userIds = await repositories.UsersSettings.Collection + var users = await repositories.UsersSettings.Collection .Find(Builders.Filter.Lt((s) => s.DeletedAt, cutoff)) - .Project((s) => s.UserId) + .Project((s) => new { s.UserId, s.DeletedAt }) .ToListAsync(context.CancellationToken); - foreach (var userId in userIds) + foreach (var user in users) { context.CancellationToken.ThrowIfCancellationRequested(); try { - await PurgeAsync(userId); + await PurgeAsync(user.UserId, user.DeletedAt!.Value); } catch (Exception ex) { - logger.LogError(ex, "Failed to purge user {UserId}", userId); + 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) + 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( - Builders.Filter.Eq((s) => s.UserId, userId), + (s) => s.UserId == userId && s.DeletedAt == deletedAt, Builders.Update.Unset((s) => s.DeletedAt)); return; } diff --git a/Streetwriters.Common/Interfaces/IUserAccountService.cs b/Streetwriters.Common/Interfaces/IUserAccountService.cs index 5d725cd..6d8061d 100644 --- a/Streetwriters.Common/Interfaces/IUserAccountService.cs +++ b/Streetwriters.Common/Interfaces/IUserAccountService.cs @@ -8,6 +8,9 @@ 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")] diff --git a/Streetwriters.Identity/Services/ScopedUserAccountService.cs b/Streetwriters.Identity/Services/ScopedUserAccountService.cs index e618c10..a0a2098 100644 --- a/Streetwriters.Identity/Services/ScopedUserAccountService.cs +++ b/Streetwriters.Identity/Services/ScopedUserAccountService.cs @@ -35,6 +35,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)); diff --git a/Streetwriters.Identity/Services/UserAccountService.cs b/Streetwriters.Identity/Services/UserAccountService.cs index 6b2cd00..acd6edc 100644 --- a/Streetwriters.Identity/Services/UserAccountService.cs +++ b/Streetwriters.Identity/Services/UserAccountService.cs @@ -52,6 +52,17 @@ public class UserAccountService(UserManager userManager, IMFAService mfaSe }; } + public async Task DeleteUserAsync(string clientId, string userId, string password) + { + var user = await userManager.FindByIdAsync(userId); + if (user == null || !await UserService.IsUserValidAsync(userManager, user, clientId)) return; + + if (!await userManager.CheckPasswordAsync(user, password)) throw new Exception("Wrong password."); + + await userManager.DeleteAsync(user); + 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; diff --git a/tests/Notesnook.API.Tests/SyncV2HubTests.cs b/tests/Notesnook.API.Tests/SyncV2HubTests.cs index c14eab2..efaa9b3 100644 --- a/tests/Notesnook.API.Tests/SyncV2HubTests.cs +++ b/tests/Notesnook.API.Tests/SyncV2HubTests.cs @@ -22,7 +22,8 @@ private sealed class Caller(string userId, params Claim[] claims) : HubCallerCon 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")]; @@ -83,6 +84,37 @@ await scope.Repositories.UsersSettings.Collection.InsertManyAsync([ 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 index 6ba8f69..c701f55 100644 --- a/tests/Notesnook.API.Tests/UserPurgeJobTests.cs +++ b/tests/Notesnook.API.Tests/UserPurgeJobTests.cs @@ -45,7 +45,7 @@ public UserPurgeJobTests(TestDatabase db) public void Dispose() => subscriptionServer.Dispose(); private static string NewUserId() => Guid.NewGuid().ToString("N"); - private static readonly long LongAgo = DateTimeOffset.UtcNow.AddHours(-2).ToUnixTimeMilliseconds(); + private static readonly long LongAgo = DateTimeOffset.UtcNow.AddHours(-3).ToUnixTimeMilliseconds(); private static IJobExecutionContext Context => Stub.Create(("get_CancellationToken", (_) => CancellationToken.None)); @@ -120,6 +120,24 @@ public async Task A_user_that_still_exists_keeps_its_data_and_loses_the_mark() 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() { diff --git a/tests/Streetwriters.Identity.Tests/TokenContractTests.cs b/tests/Streetwriters.Identity.Tests/TokenContractTests.cs index 4e64aeb..e45ea34 100644 --- a/tests/Streetwriters.Identity.Tests/TokenContractTests.cs +++ b/tests/Streetwriters.Identity.Tests/TokenContractTests.cs @@ -421,6 +421,19 @@ public async Task Refresh_rejects_unknown_token() await Golden.AssertMatchesAsync("refresh.unknown", await RefreshAsync("ABCDEF")); } + [Fact] + public async Task Deleted_users_tokens_stop_working() + { + var email = NewEmail(); + var signup = await SignupAsync(email); + var (access, refresh) = await LoginAsync(email); + + await host.WithServicesAsync(async (services) => { await services.GetRequiredService().DeleteUserAsync(ClientId, signup.UserId, Password); return 0; }); + + await Golden.AssertMatchesAsync("deleted.introspection", await IntrospectAsync(access)); + await Golden.AssertMatchesAsync("deleted.refresh", await RefreshAsync(refresh)); + } + [Fact] public async Task Users_are_unregistered_without_their_password() {