Skip to content
28 changes: 15 additions & 13 deletions Notesnook.API/Accessors/SyncItemsRepositoryAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public class SyncItemsRepositoryAccessor : ISyncItemsRepositoryAccessor
public Repository<InboxSyncItem> InboxItems { get; }
public Repository<SyncDevice> SyncDevices { get; }
public Repository<DeviceIdsChunk> DeviceIdsChunks { get; }
public UserGenerations Generations { get; }
public IReadOnlyList<SyncItemCollection> SyncItemCollections { get; }

public SyncItemsRepositoryAccessor(IDbContext dbContext,
Expand Down Expand Up @@ -95,19 +96,20 @@ public SyncItemsRepositoryAccessor(IDbContext dbContext,
InboxItems = inboxItems;
SyncDevices = syncDevices;
DeviceIdsChunks = deviceIdsChunks;
Notebooks = new SyncItemsRepository(dbContext, notebooks, logger);
Notes = new SyncItemsRepository(dbContext, notes, logger);
Contents = new SyncItemsRepository(dbContext, content, logger);
Settings = new SyncItemsRepository(dbContext, settings, logger);
LegacySettings = new SyncItemsRepository(dbContext, legacySettings, logger);
Attachments = new SyncItemsRepository(dbContext, attachments, logger);
Shortcuts = new SyncItemsRepository(dbContext, shortcuts, logger);
Reminders = new SyncItemsRepository(dbContext, reminders, logger);
Relations = new SyncItemsRepository(dbContext, relations, logger);
Colors = new SyncItemsRepository(dbContext, colors, logger);
Vaults = new SyncItemsRepository(dbContext, vaults, logger);
Tags = new SyncItemsRepository(dbContext, tags, logger);
InboxItemsHistory = new SyncItemsRepository(dbContext, inboxItemsHistory, logger);
Generations = new UserGenerations(usersSettings.Collection);
Notebooks = new SyncItemsRepository(dbContext, notebooks, Generations, logger);
Notes = new SyncItemsRepository(dbContext, notes, Generations, logger);
Contents = new SyncItemsRepository(dbContext, content, Generations, logger);
Settings = new SyncItemsRepository(dbContext, settings, Generations, logger);
LegacySettings = new SyncItemsRepository(dbContext, legacySettings, Generations, logger);
Attachments = new SyncItemsRepository(dbContext, attachments, Generations, logger);
Shortcuts = new SyncItemsRepository(dbContext, shortcuts, Generations, logger);
Reminders = new SyncItemsRepository(dbContext, reminders, Generations, logger);
Relations = new SyncItemsRepository(dbContext, relations, Generations, logger);
Colors = new SyncItemsRepository(dbContext, colors, Generations, logger);
Vaults = new SyncItemsRepository(dbContext, vaults, Generations, logger);
Tags = new SyncItemsRepository(dbContext, tags, Generations, logger);
InboxItemsHistory = new SyncItemsRepository(dbContext, inboxItemsHistory, Generations, logger);

SyncItemCollections = [
new("settingitem", Settings),
Expand Down
62 changes: 57 additions & 5 deletions Notesnook.API/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ You should have received a copy of the Affero GNU General Public License
using Notesnook.API.Services;
using Streetwriters.Common;
using Streetwriters.Common.Accessors;
using Streetwriters.Common.Exceptions;
using Streetwriters.Common.Extensions;
using Streetwriters.Common.Messages;
using Streetwriters.Common.Models;
Expand Down Expand Up @@ -185,20 +186,51 @@ private async Task EndOtherSessionsAsync(string userId)
try
{
await serviceAccessor.UserAccountService.ClearSessionsAsync(userId, clientId, all: false, jti, null);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to end other sessions of user with id: {UserId}", userId);
}
await PublishLogoutAsync(userId, jti, "Password changed.");
}

private async Task PublishLogoutAsync(string userId, string? jti, string reason)
{
try
{
await WampServers.MessengerServer.PublishMessageAsync(MessengerServerTopics.SendSSETopic, new SendSSEMessage
{
UserId = userId,
OriginTokenId = jti,
Message = new Message
{
Type = "logout",
Data = JsonSerializer.Serialize(new { reason = "Password changed." })
Data = JsonSerializer.Serialize(new { reason })
}
});
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to end other sessions of user with id: {UserId}", userId);
logger.LogError(ex, "Failed to log out the other sessions of user {UserId}", userId);
}
}

private static async Task<T> RetryAsync<T>(Func<Task<T>> action)
{
for (var attempt = 1; ; attempt++)
{
try
{
return await action();
}
catch (Exception) when (attempt < 3)
{
await Task.Delay(TimeSpan.FromMilliseconds(200 * attempt));
}
catch (Exception ex)
{
throw new ServiceUnavailableException("Your account could not be reset. Please try again.", ex);
}
}
}

Expand Down Expand Up @@ -262,10 +294,30 @@ public async Task<IActionResult> GetEncryptionVerifier()
public async Task<IActionResult> Reset([FromForm] bool removeAttachments)
{
var userId = this.User.GetUserId();
var clientId = User.FindFirstValue("client_id");
var jti = User.FindFirstValue("jti");
var accounts = serviceAccessor.UserAccountService;

if (await UserService.ResetUserAsync(userId, removeAttachments))
return Ok();
return BadRequest();
// the other devices hold the old keys, so they're kept out until the reset, attachments included, is done
var lockedOutUntil = await RetryAsync(() => accounts.LockUserAsync(userId));
try
{
await RetryAsync(async () => await accounts.ClearSessionsAsync(userId, clientId, all: false, jti, null) ? true : throw new Exception("Sessions were not cleared."));
await PublishLogoutAsync(userId, jti, "Your account is being reset.");
await UserService.ResetUserAsync(userId, removeAttachments);
}
finally
{
try
{
await accounts.UnlockUserAsync(userId, lockedOutUntil);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to unlock user {UserId} after a reset", userId);
}
}
return Ok();
}

[HttpPost("delete")]
Expand Down
6 changes: 6 additions & 0 deletions Notesnook.API/EventSources/SyncEventCounterSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public sealed class SyncEventCounterSource : EventSource
private readonly Counter<int> fetchV2Failures;
private readonly Histogram<long> fetchV2Duration;
private readonly Histogram<long> pushV2Duration;
private readonly Counter<int> purgeFailures;
private SyncEventCounterSource()
{
fetchCounter = meter.CreateCounter<int>("sync.fetches", "fetches", "Total fetches");
Expand All @@ -24,6 +25,8 @@ private SyncEventCounterSource()
fetchV2Failures = meter.CreateCounter<int>("sync.v2.fetch_failures", "fetches", "Fetches that threw, including chunks the client rejected");
fetchV2Duration = meter.CreateHistogram<long>("sync.v2.fetch_duration");
pushV2Duration = meter.CreateHistogram<long>("sync.v2.push_duration");
// no unit, which the Prometheus exporter would append to the name the alert rule uses
purgeFailures = meter.CreateCounter<int>("users.purge_failures", null, "Deleted or reset users whose data failed to purge");
}

public void Fetch() => fetchCounter.Add(1);
Expand All @@ -33,6 +36,9 @@ private SyncEventCounterSource()
public void Push() => pushCounter.Add(1);
public void RecordFetchDuration(long durationMs) => fetchV2Duration.Record(durationMs);
public void RecordPushDuration(long durationMs) => pushV2Duration.Record(durationMs);
public void PurgeFailed() => purgeFailures.Add(1);
// a counter is only exported once it has a value, and increase() can't count the failure that creates it
public void PurgeStarted() => purgeFailures.Add(0);

protected override void Dispose(bool disposing)
{
Expand Down
40 changes: 24 additions & 16 deletions Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,21 @@
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
// hub connections outlive their token, so a deleted or reset user's open connection is cut off here instead
public class SyncAuthorizationHubFilter : 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);
private const string GenerationKey = "generation";

public async ValueTask<object?> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object?>> next)
{
await EnsureNotDeletedAsync(invocationContext.Context, invocationContext.ServiceProvider);
await EnsureCurrentAsync(invocationContext.Context, invocationContext.ServiceProvider);
return await next(invocationContext);
}

Expand All @@ -32,25 +30,35 @@ public async Task OnConnectedAsync(HubLifetimeContext context, Func<HubLifetimeC
var reason = result.AuthorizationFailure?.FailureReasons.FirstOrDefault();
throw new HubException(reason?.Message ?? "Unauthorized");
}
await EnsureNotDeletedAsync(context.Context, context.ServiceProvider);
await EnsureCurrentAsync(context.Context, context.ServiceProvider);
await next(context);
}

private async Task EnsureNotDeletedAsync(HubCallerContext context, IServiceProvider services)
// uncached, since a connection must not write under its generation once a reset has ended it
private static async Task EnsureCurrentAsync(HubCallerContext context, IServiceProvider services)
{
var userId = context.User?.FindFirstValue("sub");
if (userId == null) return;

var deleted = await cache.GetOrCreateAsync($"user_deleted:{userId}", async (entry) =>
var repositories = services.GetRequiredService<ISyncItemsRepositoryAccessor>();
var settings = await repositories.UsersSettings.Collection
.Find((s) => s.UserId == userId)
.Project((s) => new { s.DeletedAt, s.Generation })
.FirstOrDefaultAsync();
if (settings == null || settings.DeletedAt != null)
{
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.");
}

context.Abort();
throw new HubException("Please login to sync.");
if (!context.Items.TryGetValue(GenerationKey, out var generation))
context.Items[GenerationKey] = generation = settings.Generation;
if ((long)generation! != settings.Generation)
{
context.Abort();
throw new HubException("Your account was reset. Please sync again.");
}
repositories.Generations.Pin(userId, settings.Generation);
}
}
}
4 changes: 3 additions & 1 deletion Notesnook.API/Hubs/SyncV2Hub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,9 @@ private async Task<SyncV2Metadata> HandleRequestFetch(string deviceId, bool incl
}
}

await SyncDeviceService.ResetAsync(userId, deviceId);
// a device that fetched across a reset re-registered after its deletion, and must still do a full sync after logging in again
if (await Repositories.Generations.IsCurrentAsync(userId))
await SyncDeviceService.ResetAsync(userId, deviceId);
Comment on lines +321 to +322

return new SyncV2Metadata
{
Expand Down
1 change: 1 addition & 0 deletions Notesnook.API/Interfaces/ISyncItemsRepositoryAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public interface ISyncItemsRepositoryAccessor
Repository<InboxSyncItem> InboxItems { get; }
Repository<SyncDevice> SyncDevices { get; }
Repository<DeviceIdsChunk> DeviceIdsChunks { get; }
UserGenerations Generations { get; }

/// <summary>
/// Every collection of a user's sync items, in the order they are synced.
Expand Down
2 changes: 1 addition & 1 deletion Notesnook.API/Interfaces/IUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public interface IUserService
Task<SignupResponse> CreateUserAsync(SignupForm form);
Task DeleteUserAsync(string userId);
Task DeleteUserAsync(string userId, string? jti, string password);
Task<bool> ResetUserAsync(string userId, bool removeAttachments);
Task ResetUserAsync(string userId, bool removeAttachments);
Task<UserResponse> GetUserAsync(string userId);
Task<EncryptedData?> GetEncryptionVerifier(string userId);
}
Expand Down
38 changes: 38 additions & 0 deletions Notesnook.API/Jobs/UserPurgeJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ public class UserPurgeJob(ISyncItemsRepositoryAccessor repositories, SyncDeviceS
{
// 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);
// requests that read the old generation before a reset can still write to it, so those land before the purge
public static readonly TimeSpan ResetGracePeriod = TimeSpan.FromMinutes(15);

public WampServer SubscriptionServer { get; init; } = WampServers.SubscriptionServer;

public async Task Execute(IJobExecutionContext context)
{
SyncEventCounterSource.Log.PurgeStarted();
var cutoff = DateTimeOffset.UtcNow.Subtract(GracePeriod).ToUnixTimeMilliseconds();
var users = await repositories.UsersSettings.Collection
.Find(Builders<UserSettings>.Filter.Lt((s) => s.DeletedAt, cutoff))
Expand All @@ -39,8 +42,43 @@ public async Task Execute(IJobExecutionContext context)
catch (Exception ex)
{
logger.LogError(ex, "Failed to purge user {UserId}", user.UserId);
SyncEventCounterSource.Log.PurgeFailed();
}
}

var resets = await repositories.UsersSettings.Collection
.Find(Builders<UserSettings>.Filter.And(
Builders<UserSettings>.Filter.Lt((s) => s.PurgePendingSince, DateTimeOffset.UtcNow.Subtract(ResetGracePeriod).ToUnixTimeMilliseconds()),
Builders<UserSettings>.Filter.Eq((s) => s.DeletedAt, null)))
.Project((s) => new { s.UserId, s.Generation })
.ToListAsync(context.CancellationToken);

foreach (var user in resets)
{
context.CancellationToken.ThrowIfCancellationRequested();
try
{
await PurgeResetAsync(user.UserId, user.Generation);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to purge the reset data of user {UserId}", user.UserId);
SyncEventCounterSource.Log.PurgeFailed();
}
}
}

private async Task PurgeResetAsync(string userId, long generation)
{
logger.LogInformation("Purging reset data of user {UserId}", userId);
foreach (var collection in repositories.SyncItemCollections)
await collection.Repository.DeleteOlderGenerationsAsync(userId, generation);

// only the generation we purged, so a reset made meanwhile stays pending
await repositories.UsersSettings.Collection.UpdateOneAsync(
(s) => s.UserId == userId && s.Generation == generation,
Builders<UserSettings>.Update.Unset((s) => s.PurgePendingSince));
logger.LogInformation("Purged reset data of user {UserId}", userId);
}

// no transaction, since one this large outlives Mongo's time limit; every step is idempotent so a failed purge is retried
Expand Down
6 changes: 6 additions & 0 deletions Notesnook.API/Models/SyncItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ public string? UserId
get; set;
}

[IgnoreDataMember]
[MessagePack.IgnoreMember]
[JsonIgnore]
[BsonIgnoreIfDefault]
public long Generation { get; set; }

[JsonPropertyName("iv")]
[DataMember(Name = "iv")]
[MessagePack.Key("iv")]
Expand Down
5 changes: 5 additions & 0 deletions Notesnook.API/Models/UserSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ public UserSettings()
public UserKeys? PendingKeys { get; set; }
public long? PendingKeysSince { get; set; }
public long? DeletedAt { get; set; }
public long Generation { get; set; }
/// <summary>
/// When the latest reset happened, kept until UserPurgeJob has deleted the data of older generations.
/// </summary>
public long? PurgePendingSince { get; set; }

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
Expand Down
Loading
Loading