Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Notesnook.API/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -270,7 +269,6 @@ public async Task<IActionResult> Reset([FromForm] bool removeAttachments)
}

[HttpPost("delete")]
[RequestTimeout(5 * 60 * 1000)]
public async Task<IActionResult> Delete([FromForm] DeleteAccountForm form)
{
var userId = this.User.GetUserId();
Expand Down
56 changes: 56 additions & 0 deletions Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs
Original file line number Diff line number Diff line change
@@ -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<object?> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object?>> next)
{
await EnsureNotDeletedAsync(invocationContext.Context, invocationContext.ServiceProvider);
return await next(invocationContext);
Comment on lines +23 to +24
}

public async Task OnConnectedAsync(HubLifetimeContext context, Func<HubLifetimeContext, Task> 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<ISyncItemsRepositoryAccessor>().UsersSettings.Collection
.Find((s) => s.UserId == userId && s.DeletedAt == null).AnyAsync();
});
if (!deleted) return;

context.Abort();
throw new HubException("Please login to sync.");
}
}
}
9 changes: 0 additions & 9 deletions Notesnook.API/Hubs/SyncV2Hub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down
82 changes: 82 additions & 0 deletions Notesnook.API/Jobs/UserPurgeJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
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<UserPurgeJob> 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<UserSettings>.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);
}
}
}

// 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))
{
logger.LogWarning("User {UserId} was marked for deletion but still exists", userId);
await repositories.UsersSettings.Collection.UpdateOneAsync(
Builders<UserSettings>.Filter.Eq((s) => s.UserId, userId),
Builders<UserSettings>.Update.Unset((s) => s.DeletedAt));
Comment on lines +53 to +55
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);
}
}
}
1 change: 1 addition & 0 deletions Notesnook.API/Models/UserSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public UserSettings()
/// </summary>
public UserKeys? PendingKeys { get; set; }
public long? PendingKeysSince { get; set; }
public long? DeletedAt { get; set; }

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
Expand Down
2 changes: 1 addition & 1 deletion Notesnook.API/Services/MongoIndexesHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class MongoIndexesHostedService(IMongoClient client, ILogger<MongoIndexes
["notes"] = [.. SyncIndexes, I("Length_1", ("Length", 1))],
["sync_devices"] = [I("UserId_1_DeviceId_1", true, false, ("UserId", 1), ("DeviceId", 1)), I("LastAccessTime_1", ("LastAccessTime", 1)),
I("UserId_1", ("UserId", 1)), I("idx_device_user_activity", ("UserId", 1), ("LastAccessTime", -1))],
["user_settings"] = [I("UserId_1", true, false, ("UserId", 1))]
["user_settings"] = [I("UserId_1", true, false, ("UserId", 1)), I("DeletedAt_1", ("DeletedAt", 1))]
};

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
Expand Down
31 changes: 9 additions & 22 deletions Notesnook.API/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,38 +183,25 @@ public async Task DeleteUserAsync(string userId)
{
logger.LogInformation("Deleting user {UserId}", userId);

foreach (var collection in Repositories.SyncItemCollections)
collection.Repository.DeleteByUserId(userId);
Repositories.UsersSettings.Delete((u) => 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<UserSettings>.Filter.Eq((s) => s.UserId, userId),
Builders<UserSettings>.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);

Expand Down
13 changes: 12 additions & 1 deletion Notesnook.API/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<SyncV2Hub>((hub) => hub.AddFilter<SyncAuthorizationHubFilter>());
services.AddMemoryCache();
services.AddSingleton<SyncAuthorizationHubFilter>();

if (!string.IsNullOrEmpty(Constants.SIGNALR_REDIS_CONNECTION_STRING))
{
Expand Down Expand Up @@ -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<UserPurgeJob>(opts => opts.WithIdentity(userPurgeJobKey));
q.AddTrigger(opts => opts
.ForJob(userPurgeJobKey)
.WithIdentity("UserPurge-trigger")
.WithSimpleSchedule((s) => s.WithIntervalInMinutes(5).RepeatForever()));
});
}

Expand Down
4 changes: 2 additions & 2 deletions Streetwriters.Common/Interfaces/IUserAccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ public interface IUserAccountService
{
[WampProcedure("co.streetwriters.identity.users.get_user")]
Task<UserModel?> 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<bool> UserExistsAsync(string userId);
Comment on lines +14 to +15
[WampProcedure("co.streetwriters.identity.users.unregister_user")]
Task UnregisterUserAsync(string clientId, string userId);
[WampProcedure("co.streetwriters.identity.users.change_password")]
Expand Down
3 changes: 2 additions & 1 deletion Streetwriters.Identity/Interfaces/ISessionStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public interface ISessionStore
/// <returns>The keys under which introspection results of the ended sessions' tokens are cached.</returns>
Task<List<string>> EndSessionsAsync(string clientId, string subjectId, string? exceptJti, string? exceptRefreshToken);

Task EndAllSessionsAsync(string subjectId);
/// <returns>The keys under which introspection results of the ended sessions' tokens are cached.</returns>
Task<List<string>> EndAllSessionsAsync(string subjectId);
}
}
9 changes: 8 additions & 1 deletion Streetwriters.Identity/Legacy/LegacyGrants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,14 @@ public async Task<List<string>> RemoveSessionsAsync(string subjectId, string cli
public Task RemoveAccessTokensAsync(string subjectId, string clientId) =>
Grants.DeleteManyAsync(Builders<BsonDocument>.Filter.And(SubjectAndClient(subjectId, clientId), Builders<BsonDocument>.Filter.Eq("Type", ReferenceTokenType)));

public Task RemoveAllAsync(string subjectId) => Grants.DeleteManyAsync(new BsonDocument("SubjectId", subjectId));
public async Task<List<string>> RemoveAllAsync(string subjectId)
{
var filter = new BsonDocument("SubjectId", subjectId);
var removed = (await Grants.Find(filter).Project(Builders<BsonDocument>.Projection.Include("Key")).ToListAsync())
.Select((d) => d["Key"].AsString).ToList();
await Grants.DeleteManyAsync(filter);
return removed;
}

public async Task<long> RemoveExpiredAsync() =>
(await Grants.DeleteManyAsync(Builders<BsonDocument>.Filter.Lt("Expiration", timeProvider.GetUtcNow().UtcDateTime))).DeletedCount;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,14 @@ public async Task<List<string>> 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<List<string>> EndAllSessionsAsync(string subjectId)
{
var ended = new List<string>();
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)];
}

/// <returns>The keys under which introspection results of the sessions' access tokens are cached.</returns>
Expand Down
7 changes: 5 additions & 2 deletions Streetwriters.Identity/Services/PersistedGrantSessionStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,12 @@ public async Task<List<string>> EndSessionsAsync(string clientId, string subject
return removedKeys;
}

public Task EndAllSessionsAsync(string subjectId)
public async Task<List<string>> 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;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private async Task<T> WithServiceAsync<T>(Func<IUserAccountService, Task<T>> act
}

public Task<UserModel?> 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<bool> 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<bool> ChangePasswordAsync(string userId, string oldPassword, string newPassword) => WithServiceAsync((s) => s.ChangePasswordAsync(userId, oldPassword, newPassword));
public Task<bool> ResetPasswordAsync(string userId, string newPassword) => WithServiceAsync((s) => s.ResetPasswordAsync(userId, newPassword));
Expand Down
Loading
Loading