diff --git a/ReadMe.md b/ReadMe.md index 87156ae..e9810f4 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -233,6 +233,47 @@ Revoking refresh tokens does not immediately invalidate access JWTs already issu Applications that do not use the EF integration can implement `IRefreshTokenStore` and register it before startup. Store implementations must make `TryRotateAsync` atomic: consuming the old token and persisting its replacement must succeed or fail as one operation. A non-atomic implementation is not safe for production use. +## EF Core integration + +### Identity stores + +`AddEfStores()` registers the ASP.NET Core Identity EF stores. `TDbContext` can be any `DbContext`: it does not have to derive from `IdentityDbContext`, but its model must contain the default Identity entities for your user, role and key types (`TUser`, `TRole`, `IdentityUserClaim`, `IdentityUserRole`, `IdentityUserLogin`, `IdentityUserToken`, `IdentityRoleClaim`). The application fails at startup with a message listing any missing entity. Custom claim, login, token or user-role entity types (the eight-argument `IdentityDbContext`) are not supported by the built-in stores; implement your own stores for that case (see the Custom Store sample). + +### Model configuration + +Add the entities of the features you use in `OnModelCreating`. Each method is independent; call only the ones you need: + +```cs +protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddRefreshTokenEntity(); + modelBuilder.AddVerificationRequestEntity(); +} +``` + +Table names or schemas can be changed with ordinary EF Core calls afterwards, for example `modelBuilder.Entity>().ToTable("RefreshTokens", "auth")`. + +### Supported providers and limitations + +- Refresh-token and verification stores require a **relational** provider. Rotation, resend and send limits use transactions and conditional updates; EF InMemory is not supported and throws `NotSupportedException`. +- The repository's tests run against SQLite. SQL Server and PostgreSQL are expected to work but are not covered by automated tests in this repository. +- Transactions run inside the DbContext execution strategy, so `EnableRetryOnFailure` (and equivalent provider settings) is supported. +- Verification create and resend use `Serializable` transactions. Under heavy concurrency, providers can abort a transaction (deadlock or serialization failure). Configure a retrying execution strategy if this matters for your workload. +- `VerificationRequest.CodeVerifier` uses an empty string as an "initial" marker. Providers that treat empty strings as `NULL` (for example Oracle) are not supported. +- Dates are stored with `DateTimeOffsetToBinaryConverter` (a `bigint`, millisecond precision) so that expiry comparisons work on every relational provider, including SQLite. +- `UserId` columns do not have a foreign key to your users table. Rows for deleted users remain until they expire, and the refresh endpoint rejects (and revokes) a refreshed session whose user no longer exists. To add a foreign key, configure it in your own `OnModelCreating` (for example `modelBuilder.Entity>().HasOne>().WithMany().HasForeignKey(token => token.UserId).OnDelete(DeleteBehavior.Cascade)`) and remove orphaned rows before applying the migration. Purging expired rows is the application's responsibility for now. + +### Migration impact + +Adding entities requires a migration for the tables you enable. When upgrading an existing database that already contains the verification tables, add two nullable columns to `AuthenticationVerificationSends`: + +| Column | Type | +| --- | --- | +| `CustomPurpose` | `nvarchar(128)` / provider equivalent, nullable | +| `CustomChannel` | `nvarchar(128)` / provider equivalent, nullable | + +`dotnet ef migrations add ` generates this change. Existing rows keep `NULL` values, which match requests without a custom purpose or channel. Send limits and "supersede pending request" behavior are now scoped per custom purpose and custom channel, so two different custom purposes for the same destination no longer affect each other. No other column, index or table name changes were made. + ## Registration with email verification Public registration uses a verification workflow instead of issuing an access token immediately. This is a major-version API change: `IUserAccountService.RegisterAsync` has been replaced by `IRegistrationService`. diff --git a/RuntimeApps.Authentication.EF/DependencyInjection/RuntimeAppsAuthenticationBuilderExtension.cs b/RuntimeApps.Authentication.EF/DependencyInjection/RuntimeAppsAuthenticationBuilderExtension.cs index 488dae4..71ab090 100644 --- a/RuntimeApps.Authentication.EF/DependencyInjection/RuntimeAppsAuthenticationBuilderExtension.cs +++ b/RuntimeApps.Authentication.EF/DependencyInjection/RuntimeAppsAuthenticationBuilderExtension.cs @@ -1,16 +1,30 @@ using RuntimeApps.Authentication.DependencyInjection; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using RuntimeApps.Authentication.EF.Identity; namespace RuntimeApps.Authentication.EF.DependencyInjection { public static class RuntimeAppsAuthenticationBuilderExtension { + /// + /// Registers the ASP.NET Core Identity EF stores. The DbContext does not have to derive from + /// , but its model must contain the default + /// Identity entities for , and + /// . This is verified at application start. + /// public static RuntimeAppsAuthenticationBuilder AddEfStores(this RuntimeAppsAuthenticationBuilder builder) - where TDbContext : IdentityDbContext + where TDbContext : DbContext where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { - builder.AddStores, + ArgumentNullException.ThrowIfNull(builder); + builder.AddStores, RoleStore>(); + builder.Services.TryAddEnumerable( + ServiceDescriptor.Singleton>()); return builder; } } diff --git a/RuntimeApps.Authentication.EF/Features/RefreshTokens/Stores/EfRefreshTokenStore.cs b/RuntimeApps.Authentication.EF/Features/RefreshTokens/Stores/EfRefreshTokenStore.cs index 833f46c..362c5a0 100644 --- a/RuntimeApps.Authentication.EF/Features/RefreshTokens/Stores/EfRefreshTokenStore.cs +++ b/RuntimeApps.Authentication.EF/Features/RefreshTokens/Stores/EfRefreshTokenStore.cs @@ -62,28 +62,54 @@ public async Task TryRotateAsync( if(!_dbContext.Database.IsRelational()) throw new NotSupportedException("Atomic refresh-token rotation requires a relational EF Core provider."); - await using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken); + // Generated keys (Guid/string) are assigned once so every retry attempt reuses the same value. + // Database-generated integer keys stay at their default and are reset before each attempt. PrepareGeneratedId(replacement); - await _dbContext.Set>().AddAsync(replacement, cancellationToken); - await _dbContext.SaveChangesAsync(cancellationToken); + var originalId = replacement.Id; - var affected = await _dbContext.Set>() - .Where(token => token.Id.Equals(tokenId) && - token.TokenHash == expectedTokenHash && - token.RevokedAt == null && - token.ExpiresAt > now) - .ExecuteUpdateAsync(setters => setters - .SetProperty(token => token.RevokedAt, now) - .SetProperty(token => token.ReplacedByTokenId, replacement.Id) - .SetProperty(token => token.HasReplacement, true), cancellationToken); - - if(affected != 1) { - await transaction.RollbackAsync(cancellationToken); - return false; - } + // User-initiated transactions must run inside the execution strategy so providers configured + // with retry-on-failure (for example EnableRetryOnFailure) retry the whole unit. + var strategy = _dbContext.Database.CreateExecutionStrategy(); + return await strategy.ExecuteAsync(async () => { + ResetReplacement(replacement, originalId); + var committed = false; + try { + await using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken); + await _dbContext.Set>().AddAsync(replacement, cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + + var affected = await _dbContext.Set>() + .Where(token => token.Id.Equals(tokenId) && + token.TokenHash == expectedTokenHash && + token.RevokedAt == null && + token.ExpiresAt > now) + .ExecuteUpdateAsync(setters => setters + .SetProperty(token => token.RevokedAt, now) + .SetProperty(token => token.ReplacedByTokenId, replacement.Id) + .SetProperty(token => token.HasReplacement, true), cancellationToken); + + if(affected != 1) { + await transaction.RollbackAsync(cancellationToken); + return false; + } + + await transaction.CommitAsync(cancellationToken); + committed = true; + return true; + } finally { + // A rolled-back or failed insert must not stay tracked as a persisted row in the + // shared scoped context (it is shared with the Identity stores). + if(!committed) + ResetReplacement(replacement, originalId); + } + }); + } - await transaction.CommitAsync(cancellationToken); - return true; + private void ResetReplacement(RefreshToken replacement, TKey originalId) { + var entry = _dbContext.Entry(replacement); + if(entry.State != EntityState.Detached) + entry.State = EntityState.Detached; + replacement.Id = originalId; } public async Task RevokeFamilyAsync(Guid familyId, DateTimeOffset revokedAt, CancellationToken cancellationToken = default) { diff --git a/RuntimeApps.Authentication.EF/Features/Verification/Configurations/VerificationSendConfiguration.cs b/RuntimeApps.Authentication.EF/Features/Verification/Configurations/VerificationSendConfiguration.cs index abf31fa..4516a5f 100644 --- a/RuntimeApps.Authentication.EF/Features/Verification/Configurations/VerificationSendConfiguration.cs +++ b/RuntimeApps.Authentication.EF/Features/Verification/Configurations/VerificationSendConfiguration.cs @@ -11,6 +11,10 @@ public void Configure(EntityTypeBuilder builder) { builder.Property(send => send.NormalizedDestination).HasMaxLength(512).IsRequired(); builder.Property(send => send.Purpose).HasConversion().HasMaxLength(32).IsRequired(); builder.Property(send => send.Channel).HasConversion().HasMaxLength(32).IsRequired(); + // Nullable and intentionally not part of the index: the index prefix still narrows the + // lookup, and wider keys would exceed index size limits on some providers. + builder.Property(send => send.CustomPurpose).HasMaxLength(128); + builder.Property(send => send.CustomChannel).HasMaxLength(128); builder.Property(send => send.SentAt).HasConversion(new DateTimeOffsetToBinaryConverter()); builder.HasIndex(send => send.SentAt); builder.HasIndex(send => new { diff --git a/RuntimeApps.Authentication.EF/Features/Verification/Stores/EfVerificationRequestStore.cs b/RuntimeApps.Authentication.EF/Features/Verification/Stores/EfVerificationRequestStore.cs index 41b2091..61b401b 100644 --- a/RuntimeApps.Authentication.EF/Features/Verification/Stores/EfVerificationRequestStore.cs +++ b/RuntimeApps.Authentication.EF/Features/Verification/Stores/EfVerificationRequestStore.cs @@ -6,6 +6,8 @@ namespace RuntimeApps.Authentication.EF.Features.Verification.Stores { /// /// Relational EF Core implementation. Conditional updates and serializable transactions protect /// request state transitions and destination-level send limits against concurrent requests. + /// Transactions run inside the DbContext execution strategy, so providers configured with + /// retry-on-failure are supported. /// public sealed class EfVerificationRequestStore: IVerificationRequestStore where TDbContext : DbContext @@ -41,48 +43,85 @@ private static void PrepareGeneratedId(VerificationRequest request) { private IQueryable> Requests => _dbContext.Set>(); private IQueryable Sends => _dbContext.Set(); + private void Detach(object entity) { + var entry = _dbContext.Entry(entity); + if(entry.State != EntityState.Detached) + entry.State = EntityState.Detached; + } + + private void ResetRequest(VerificationRequest request, TKey originalId) { + Detach(request); + request.Id = originalId; + } + public async Task TryCreateAsync( VerificationRequest request, DateTimeOffset sendsSince, int maximumSendsPerHour, CancellationToken cancellationToken = default) { EnsureRelational(); - await using var transaction = await _dbContext.Database.BeginTransactionAsync( - IsolationLevel.Serializable, cancellationToken); + // Generated keys (Guid/string) are assigned once; database-generated integer keys are reset per attempt. + PrepareGeneratedId(request); + var originalId = request.Id; - await Sends.Where(item => item.SentAt < sendsSince).ExecuteDeleteAsync(cancellationToken); + var strategy = _dbContext.Database.CreateExecutionStrategy(); + return await strategy.ExecuteAsync(async () => { + ResetRequest(request, originalId); + VerificationSend send = null; + var committed = false; + try { + await using var transaction = await _dbContext.Database.BeginTransactionAsync( + IsolationLevel.Serializable, cancellationToken); - var sendCount = await Sends.CountAsync(item => - item.NormalizedDestination == request.NormalizedDestination && - item.Purpose == request.Purpose && - item.Channel == request.Channel && - item.SentAt >= sendsSince, cancellationToken); + await Sends.Where(item => item.SentAt < sendsSince).ExecuteDeleteAsync(cancellationToken); - if(sendCount >= maximumSendsPerHour) { - await transaction.RollbackAsync(cancellationToken); - return false; - } + var sendCount = await Sends.CountAsync(item => + item.NormalizedDestination == request.NormalizedDestination && + item.Purpose == request.Purpose && + item.Channel == request.Channel && + item.CustomPurpose == request.CustomPurpose && + item.CustomChannel == request.CustomChannel && + item.SentAt >= sendsSince, cancellationToken); - await Requests.Where(item => - object.Equals(item.UserId, request.UserId) && - item.Purpose == request.Purpose && - item.Channel == request.Channel && - item.NormalizedDestination == request.NormalizedDestination && - item.Status == VerificationRequestStatus.Pending) - .ExecuteUpdateAsync(setters => setters.SetProperty( - item => item.Status, VerificationRequestStatus.Superseded), cancellationToken); + if(sendCount >= maximumSendsPerHour) { + await transaction.RollbackAsync(cancellationToken); + return false; + } - PrepareGeneratedId(request); - await _dbContext.Set>().AddAsync(request, cancellationToken); - await _dbContext.Set().AddAsync(new VerificationSend { - NormalizedDestination = request.NormalizedDestination, - Purpose = request.Purpose, - Channel = request.Channel, - SentAt = request.CreatedAt - }, cancellationToken); - await _dbContext.SaveChangesAsync(cancellationToken); - await transaction.CommitAsync(cancellationToken); - return true; + await Requests.Where(item => + object.Equals(item.UserId, request.UserId) && + item.Purpose == request.Purpose && + item.Channel == request.Channel && + item.CustomPurpose == request.CustomPurpose && + item.CustomChannel == request.CustomChannel && + item.NormalizedDestination == request.NormalizedDestination && + item.Status == VerificationRequestStatus.Pending) + .ExecuteUpdateAsync(setters => setters.SetProperty( + item => item.Status, VerificationRequestStatus.Superseded), cancellationToken); + + await _dbContext.Set>().AddAsync(request, cancellationToken); + send = new VerificationSend { + NormalizedDestination = request.NormalizedDestination, + Purpose = request.Purpose, + Channel = request.Channel, + CustomPurpose = request.CustomPurpose, + CustomChannel = request.CustomChannel, + SentAt = request.CreatedAt + }; + await _dbContext.Set().AddAsync(send, cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + committed = true; + return true; + } finally { + // Keep the shared scoped context free of rows that were rolled back or failed. + if(!committed) { + ResetRequest(request, originalId); + if(send != null) + Detach(send); + } + } + }); } public async Task TrySetInitialVerifierAsync( @@ -122,54 +161,75 @@ public async Task TryResendAsync( int maximumSendsPerHour, CancellationToken cancellationToken = default) { EnsureRelational(); - await using var transaction = await _dbContext.Database.BeginTransactionAsync( - IsolationLevel.Serializable, cancellationToken); - - var request = await Requests.SingleOrDefaultAsync(item => item.Id.Equals(requestId), cancellationToken); - if(request == null || request.Status != VerificationRequestStatus.Pending || - request.LastSentAt > now - resendCooldown) { - await transaction.RollbackAsync(cancellationToken); - return false; - } - await Sends.Where(item => item.SentAt < sendsSince).ExecuteDeleteAsync(cancellationToken); + var strategy = _dbContext.Database.CreateExecutionStrategy(); + return await strategy.ExecuteAsync(async () => { + VerificationSend send = null; + var committed = false; + try { + await using var transaction = await _dbContext.Database.BeginTransactionAsync( + IsolationLevel.Serializable, cancellationToken); - var sendCount = await Sends.CountAsync(item => - item.NormalizedDestination == request.NormalizedDestination && - item.Purpose == request.Purpose && - item.Channel == request.Channel && - item.SentAt >= sendsSince, cancellationToken); - if(sendCount >= maximumSendsPerHour) { - await transaction.RollbackAsync(cancellationToken); - return false; - } + // No-tracking read: the row is changed with ExecuteUpdate below, so a tracked copy would go stale. + var request = await Requests.AsNoTracking() + .SingleOrDefaultAsync(item => item.Id.Equals(requestId), cancellationToken); + if(request == null || request.Status != VerificationRequestStatus.Pending || + request.LastSentAt > now - resendCooldown) { + await transaction.RollbackAsync(cancellationToken); + return false; + } - var affected = await Requests.Where(item => - item.Id.Equals(requestId) && - item.Status == VerificationRequestStatus.Pending && - item.CodeVersion == expectedCodeVersion && - item.LastSentAt <= now - resendCooldown) - .ExecuteUpdateAsync(setters => setters - .SetProperty(item => item.CodeVerifier, newCodeVerifier) - .SetProperty(item => item.CodeVersion, item => item.CodeVersion + 1) - .SetProperty(item => item.SendCount, item => item.SendCount + 1) - .SetProperty(item => item.LastSentAt, now) - .SetProperty(item => item.ExpiresAt, expiresAt), cancellationToken); + await Sends.Where(item => item.SentAt < sendsSince).ExecuteDeleteAsync(cancellationToken); - if(affected != 1) { - await transaction.RollbackAsync(cancellationToken); - return false; - } + var customPurpose = request.CustomPurpose; + var customChannel = request.CustomChannel; + var sendCount = await Sends.CountAsync(item => + item.NormalizedDestination == request.NormalizedDestination && + item.Purpose == request.Purpose && + item.Channel == request.Channel && + item.CustomPurpose == customPurpose && + item.CustomChannel == customChannel && + item.SentAt >= sendsSince, cancellationToken); + if(sendCount >= maximumSendsPerHour) { + await transaction.RollbackAsync(cancellationToken); + return false; + } + + var affected = await Requests.Where(item => + item.Id.Equals(requestId) && + item.Status == VerificationRequestStatus.Pending && + item.CodeVersion == expectedCodeVersion && + item.LastSentAt <= now - resendCooldown) + .ExecuteUpdateAsync(setters => setters + .SetProperty(item => item.CodeVerifier, newCodeVerifier) + .SetProperty(item => item.CodeVersion, item => item.CodeVersion + 1) + .SetProperty(item => item.SendCount, item => item.SendCount + 1) + .SetProperty(item => item.LastSentAt, now) + .SetProperty(item => item.ExpiresAt, expiresAt), cancellationToken); + + if(affected != 1) { + await transaction.RollbackAsync(cancellationToken); + return false; + } - await _dbContext.Set().AddAsync(new VerificationSend { - NormalizedDestination = request.NormalizedDestination, - Purpose = request.Purpose, - Channel = request.Channel, - SentAt = now - }, cancellationToken); - await _dbContext.SaveChangesAsync(cancellationToken); - await transaction.CommitAsync(cancellationToken); - return true; + send = new VerificationSend { + NormalizedDestination = request.NormalizedDestination, + Purpose = request.Purpose, + Channel = request.Channel, + CustomPurpose = customPurpose, + CustomChannel = customChannel, + SentAt = now + }; + await _dbContext.Set().AddAsync(send, cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + committed = true; + return true; + } finally { + if(!committed && send != null) + Detach(send); + } + }); } public async Task TryIncrementFailedAttemptsAsync( diff --git a/RuntimeApps.Authentication.EF/Identity/EfIdentityModelStartupValidator.cs b/RuntimeApps.Authentication.EF/Identity/EfIdentityModelStartupValidator.cs new file mode 100644 index 0000000..95ecc4b --- /dev/null +++ b/RuntimeApps.Authentication.EF/Identity/EfIdentityModelStartupValidator.cs @@ -0,0 +1,44 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +namespace RuntimeApps.Authentication.EF.Identity { + /// + /// Fails fast when the DbContext used with AddEfStores does not map the default Identity entities. + /// + internal sealed class EfIdentityModelStartupValidator: IHostedService + where TDbContext : DbContext + where TUser : IdentityUser + where TRole : IdentityRole + where TKey : IEquatable { + private readonly IServiceScopeFactory _scopeFactory; + + public EfIdentityModelStartupValidator(IServiceScopeFactory scopeFactory) { + _scopeFactory = scopeFactory; + } + + public Task StartAsync(CancellationToken cancellationToken) { + using var scope = _scopeFactory.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + var missing = GetMissingEntityTypes(dbContext.Model).ToList(); + if(missing.Count > 0) + throw new InvalidOperationException( + $"{typeof(TDbContext).Name} does not map the Identity entities required by AddEfStores: " + + $"{string.Join(", ", missing)}. Derive from IdentityDbContext<{typeof(TUser).Name}, {typeof(TRole).Name}, {typeof(TKey).Name}> " + + "or map these entities in OnModelCreating. Custom claim, login, token or user-role entity types are not supported by the built-in stores."); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + internal static IEnumerable GetMissingEntityTypes(Microsoft.EntityFrameworkCore.Metadata.IModel model) { + foreach(var type in new[] { + typeof(TUser), typeof(TRole), typeof(IdentityUserClaim), typeof(IdentityUserRole), + typeof(IdentityUserLogin), typeof(IdentityUserToken), typeof(IdentityRoleClaim) + }) { + if(model.FindEntityType(type) == null) + yield return type.Name; + } + } + } +} diff --git a/RuntimeApps.Authentication/Features/Verification/Models/VerificationSend.cs b/RuntimeApps.Authentication/Features/Verification/Models/VerificationSend.cs index 4957f62..f8f82a8 100644 --- a/RuntimeApps.Authentication/Features/Verification/Models/VerificationSend.cs +++ b/RuntimeApps.Authentication/Features/Verification/Models/VerificationSend.cs @@ -5,6 +5,10 @@ public sealed class VerificationSend { public string NormalizedDestination { get; set; } public VerificationPurpose Purpose { get; set; } public VerificationChannel Channel { get; set; } + /// Distinguishes custom purposes so each has its own send limit. Null for built-in purposes. + public string CustomPurpose { get; set; } + /// Distinguishes custom channels so each has its own send limit. Null for built-in channels. + public string CustomChannel { get; set; } public DateTimeOffset SentAt { get; set; } } } diff --git a/Tests/RuntimeApps.Authentication.Test/EfExecutionStrategyTest.cs b/Tests/RuntimeApps.Authentication.Test/EfExecutionStrategyTest.cs new file mode 100644 index 0000000..a7afe82 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/EfExecutionStrategyTest.cs @@ -0,0 +1,91 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using RuntimeApps.Authentication.EF.Features.RefreshTokens.Configurations; +using RuntimeApps.Authentication.EF.Features.Verification.Configurations; +using RuntimeApps.Authentication.EF.Features.RefreshTokens.Stores; +using RuntimeApps.Authentication.EF.Features.Verification.Stores; +using RuntimeApps.Authentication.Features.RefreshTokens.Models; +using RuntimeApps.Authentication.Features.Verification.Models; +namespace RuntimeApps.Authentication.Test { + /// + /// Regression tests for providers configured with a retrying execution strategy (for example + /// EnableRetryOnFailure), which reject transactions started outside the strategy. + /// + public class EfExecutionStrategyTest { + private static readonly DateTimeOffset Now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task EfRefreshTokenStore_RotatesTokensWithRetryingExecutionStrategy() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfRefreshTokenStore(db); + var original = new RefreshToken { + UserId = 10, FamilyId = Guid.NewGuid(), TokenHash = "A".PadRight(64, '0'), + CreatedAt = Now, ExpiresAt = Now.AddDays(30) + }; + await store.CreateAsync(original, cancellationToken); + var replacement = new RefreshToken { + UserId = 10, FamilyId = original.FamilyId, TokenHash = "B".PadRight(64, '0'), + CreatedAt = Now, ExpiresAt = Now.AddDays(30) + }; + + Assert.True(await store.TryRotateAsync(original.Id, original.TokenHash, replacement, Now, cancellationToken)); + Assert.NotNull(await store.FindByHashAsync(replacement.TokenHash, cancellationToken)); + } + + [Fact] + public async Task EfVerificationRequestStore_CreatesAndResendsWithRetryingExecutionStrategy() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfVerificationRequestStore(db); + var request = new VerificationRequest { + UserId = 10, Purpose = VerificationPurpose.Registration, Channel = VerificationChannel.Email, + Destination = "person@example.com", NormalizedDestination = "PERSON@EXAMPLE.COM", + PublicHandleHash = "handle", CodeVerifier = string.Empty, SendCount = 1, + CreatedAt = Now, LastSentAt = Now, ExpiresAt = Now.AddMinutes(10), + Status = VerificationRequestStatus.Pending + }; + + Assert.True(await store.TryCreateAsync(request, Now.AddHours(-1), 5, cancellationToken)); + Assert.True(await store.TrySetInitialVerifierAsync(request.Id, "v1", Now, Now.AddMinutes(10), cancellationToken)); + var resentAt = Now.AddMinutes(2); + Assert.True(await store.TryResendAsync( + request.Id, 1, "v2", resentAt, resentAt.AddMinutes(10), TimeSpan.FromSeconds(60), Now.AddHours(-1), 5, cancellationToken)); + } + + private static RetryingDbContext CreateContext(SqliteConnection connection) => + new(new DbContextOptionsBuilder() + .UseSqlite(connection) + .ReplaceService() + .Options); + + private sealed class RetryingExecutionStrategy(ExecutionStrategyDependencies dependencies) + : ExecutionStrategy(dependencies, 3, TimeSpan.FromMilliseconds(10)) { + protected override bool ShouldRetryOn(Exception exception) => false; + } + + private sealed class RetryingExecutionStrategyFactory(ExecutionStrategyDependencies dependencies) + : RelationalExecutionStrategyFactory(dependencies) { + protected override IExecutionStrategy CreateDefaultStrategy(ExecutionStrategyDependencies dependencies) => + new RetryingExecutionStrategy(dependencies); + } + + private sealed class RetryingDbContext(DbContextOptions options) + : IdentityDbContext, IdentityRole, int>(options) { + protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddRefreshTokenEntity(); + modelBuilder.AddVerificationRequestEntity(); + } + } + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/EfIdentityIntegrationTest.cs b/Tests/RuntimeApps.Authentication.Test/EfIdentityIntegrationTest.cs new file mode 100644 index 0000000..5eb1ae5 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/EfIdentityIntegrationTest.cs @@ -0,0 +1,118 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using RuntimeApps.Authentication.DependencyInjection; +using RuntimeApps.Authentication.EF.DependencyInjection; +using RuntimeApps.Authentication.Identity.Contracts; +namespace RuntimeApps.Authentication.Test { + public class EfIdentityIntegrationTest { + private const string Password = "P@ssw0rd!Test1"; + + [Fact] + public Task AddEfStores_WorksWithDefaultStringKeys() => + AssertRoundTripAsync( + new IdentityUser { UserName = "string-user" }, new IdentityRole("string-role")); + + [Fact] + public Task AddEfStores_WorksWithIntKeys() => + AssertRoundTripAsync, IdentityRole, int>( + new IdentityUser { UserName = "int-user" }, new IdentityRole { Name = "int-role" }); + + [Fact] + public Task AddEfStores_WorksWithCustomUserAndRoleAndGuidKeys() => + AssertRoundTripAsync( + new AppUser { UserName = "guid-user", DisplayName = "Guid User" }, new AppRole { Name = "guid-role" }); + + [Fact] + public Task AddEfStores_WorksWithPlainDbContextThatMapsIdentityEntities() => + AssertRoundTripAsync, IdentityRole, int>( + new IdentityUser { UserName = "plain-user" }, new IdentityRole { Name = "plain-role" }); + + [Fact] + public async Task StartupValidation_RejectsDbContextWithoutIdentityEntities() { + await using var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(TestContext.Current.CancellationToken); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(options => options.UseSqlite(connection)); + services.AddAuthentication() + .AddRuntimeAppsAuthentication, IdentityRole, int>() + .AddEfStores, IdentityRole, int>(); + + await using var provider = services.BuildServiceProvider(); + var validator = Assert.Single( + provider.GetServices(), + service => service.GetType().Name.StartsWith("EfIdentityModelStartupValidator", StringComparison.Ordinal)); + var exception = await Assert.ThrowsAsync( + () => validator.StartAsync(TestContext.Current.CancellationToken)); + Assert.Contains("IdentityUserClaim", exception.Message); + } + + private static async Task AssertRoundTripAsync(TUser user, TRole role) + where TDbContext : DbContext + where TUser : IdentityUser, new() + where TRole : IdentityRole + where TKey : IEquatable { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(cancellationToken); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(options => options.UseSqlite(connection)); + services.AddAuthentication() + .AddRuntimeAppsAuthentication() + .AddEfStores(); + + await using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + foreach(var hosted in provider.GetServices()) + await hosted.StartAsync(cancellationToken); + + using var scope = provider.CreateScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(cancellationToken); + var users = scope.ServiceProvider.GetRequiredService>(); + var roles = scope.ServiceProvider.GetRequiredService>(); + + Assert.True((await roles.CreateAsync(role)).Succeeded); + Assert.True((await users.CreateAsync(user, Password)).Succeeded); + Assert.True((await users.AddToRoleAsync(user, role.Name)).Succeeded); + + var found = await users.FindByNameAsync(user.UserName); + Assert.NotNull(found); + Assert.Contains(role.Name, await users.GetRolesAsync(found)); + Assert.True(await users.CheckPasswordAsync(found, Password)); + } + + public sealed class AppUser: IdentityUser { + public string DisplayName { get; set; } + } + + public sealed class AppRole: IdentityRole { } + + public sealed class StringKeyDbContext(DbContextOptions options) + : IdentityDbContext(options); + + public sealed class IntKeyDbContext(DbContextOptions options) + : IdentityDbContext, IdentityRole, int>(options); + + public sealed class GuidKeyDbContext(DbContextOptions options) + : IdentityDbContext(options); + + public sealed class EmptyDbContext(DbContextOptions options): DbContext(options); + + /// A DbContext that does not derive from IdentityDbContext but maps the default Identity entities. + public sealed class PlainDbContext(DbContextOptions options): DbContext(options) { + protected override void OnModelCreating(ModelBuilder modelBuilder) { + modelBuilder.Entity>(); + modelBuilder.Entity>(); + modelBuilder.Entity>(); + modelBuilder.Entity>(); + modelBuilder.Entity>().HasKey(item => new { item.UserId, item.RoleId }); + modelBuilder.Entity>().HasKey(item => new { item.LoginProvider, item.ProviderKey }); + modelBuilder.Entity>().HasKey(item => new { item.UserId, item.LoginProvider, item.Name }); + } + } + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/EfModelConfigurationTest.cs b/Tests/RuntimeApps.Authentication.Test/EfModelConfigurationTest.cs new file mode 100644 index 0000000..1bfba63 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/EfModelConfigurationTest.cs @@ -0,0 +1,99 @@ +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using RuntimeApps.Authentication.EF.Features.RefreshTokens.Configurations; +using RuntimeApps.Authentication.EF.Features.Verification.Configurations; +using RuntimeApps.Authentication.Features.RefreshTokens.Models; +using RuntimeApps.Authentication.Features.Verification.Models; +using Microsoft.AspNetCore.Identity; +namespace RuntimeApps.Authentication.Test { + public class EfModelConfigurationTest { + [Fact] + public void RefreshTokenModel_DefinesExpectedConstraintsAndMappings() { + using var context = new GranularDbContext(); + var entity = context.Model.FindEntityType(typeof(RefreshToken)); + + Assert.Equal("AuthenticationRefreshTokens", entity.GetTableName()); + var hashIndex = entity.GetIndexes().Single(i => i.Properties.Select(p => p.Name).SequenceEqual(new[] { "TokenHash" })); + Assert.True(hashIndex.IsUnique); + Assert.Equal(64, entity.FindProperty(nameof(RefreshToken.TokenHash)).GetMaxLength()); + Assert.False(entity.FindProperty(nameof(RefreshToken.TokenHash)).IsNullable); + Assert.Equal(100, entity.FindProperty(nameof(RefreshToken.SessionName)).GetMaxLength()); + Assert.True(entity.FindProperty(nameof(RefreshToken.SessionName)).IsNullable); + Assert.True(entity.FindProperty(nameof(RefreshToken.RevokedAt)).IsNullable); + Assert.IsType(entity.FindProperty(nameof(RefreshToken.ExpiresAt)).GetValueConverter()); + Assert.Contains(entity.GetIndexes(), i => i.Properties.Select(p => p.Name).SequenceEqual(new[] { "FamilyId", "RevokedAt" })); + Assert.Contains(entity.GetIndexes(), i => i.Properties.Select(p => p.Name).SequenceEqual(new[] { "UserId", "RevokedAt" })); + Assert.Empty(entity.GetForeignKeys()); + } + + [Fact] + public void RefreshTokenModel_StringKeysHaveBoundedLength() { + using var context = new StringKeyDbContext(); + var entity = context.Model.FindEntityType(typeof(RefreshToken)); + Assert.Equal(450, entity.FindProperty(nameof(RefreshToken.UserId)).GetMaxLength()); + Assert.True(entity.FindProperty(nameof(RefreshToken.ReplacedByTokenId)).IsNullable); + } + + [Fact] + public void VerificationModel_DefinesExpectedConstraintsAndMappings() { + using var context = new GranularDbContext(); + var request = context.Model.FindEntityType(typeof(VerificationRequest)); + var send = context.Model.FindEntityType(typeof(VerificationSend)); + + Assert.Equal("AuthenticationVerificationRequests", request.GetTableName()); + Assert.Equal("AuthenticationVerificationSends", send.GetTableName()); + Assert.True(request.GetIndexes().Single(i => i.Properties.Select(p => p.Name).SequenceEqual(new[] { "PublicHandleHash" })).IsUnique); + Assert.Equal(64, request.FindProperty(nameof(VerificationRequest.PublicHandleHash)).GetMaxLength()); + Assert.Equal(512, request.FindProperty(nameof(VerificationRequest.NormalizedDestination)).GetMaxLength()); + Assert.Equal(32, request.FindProperty(nameof(VerificationRequest.Status)).GetMaxLength()); + Assert.Equal(typeof(string), request.FindProperty(nameof(VerificationRequest.Status)).GetProviderClrType()); + Assert.True(request.FindProperty(nameof(VerificationRequest.CustomPurpose)).IsNullable); + Assert.True(send.FindProperty(nameof(VerificationSend.CustomPurpose)).IsNullable); + Assert.Equal(128, send.FindProperty(nameof(VerificationSend.CustomChannel)).GetMaxLength()); + Assert.Contains(send.GetIndexes(), i => i.Properties.Select(p => p.Name).SequenceEqual( + new[] { "NormalizedDestination", "Purpose", "Channel", "SentAt" })); + Assert.Empty(request.GetForeignKeys()); + } + + [Fact] + public void GranularMethods_CanBeUsedIndependently() { + using var context = new RefreshOnlyDbContext(); + Assert.NotNull(context.Model.FindEntityType(typeof(RefreshToken))); + Assert.Null(context.Model.FindEntityType(typeof(VerificationRequest))); + Assert.Null(context.Model.FindEntityType(typeof(VerificationSend))); + } + + [Fact] + public void GranularMethods_StillWorkTogetherWithIdentityModel() { + using var context = new GranularDbContext(); + Assert.NotNull(context.Model.FindEntityType(typeof(IdentityUser))); + Assert.NotNull(context.Model.FindEntityType(typeof(RefreshToken))); + } + + private static DbContextOptions Options() where T : DbContext => + new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options; + + private sealed class RefreshOnlyDbContext(): IdentityDbContext, IdentityRole, int>(Options()) { + protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddRefreshTokenEntity(); + } + } + + private sealed class GranularDbContext(): IdentityDbContext, IdentityRole, int>(Options()) { + protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddRefreshTokenEntity(); + modelBuilder.AddVerificationRequestEntity(); + } + } + + private sealed class StringKeyDbContext(): IdentityDbContext(Options()) { + protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddRefreshTokenEntity(); + } + } + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/EfStoreRelationalBehaviorTest.cs b/Tests/RuntimeApps.Authentication.Test/EfStoreRelationalBehaviorTest.cs new file mode 100644 index 0000000..e9034c3 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/EfStoreRelationalBehaviorTest.cs @@ -0,0 +1,223 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using RuntimeApps.Authentication.EF.Features.RefreshTokens.Configurations; +using RuntimeApps.Authentication.EF.Features.Verification.Configurations; +using RuntimeApps.Authentication.EF.Features.RefreshTokens.Stores; +using RuntimeApps.Authentication.EF.Features.Verification.Stores; +using RuntimeApps.Authentication.Features.RefreshTokens.Models; +using RuntimeApps.Authentication.Features.Verification.Models; +namespace RuntimeApps.Authentication.Test { + /// Relational (SQLite) tests for transactions and conditional updates. EF InMemory is not used. + public class EfStoreRelationalBehaviorTest { + private static readonly DateTimeOffset Now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task TryRotateAsync_ConcurrentAttemptsOnSameToken_OnlyOneSucceeds() { + var cancellationToken = TestContext.Current.CancellationToken; + var path = Path.Combine(Path.GetTempPath(), $"runtimeapps-{Guid.NewGuid():N}.db"); + try { + await using(var setup = CreateFileContext(path)) { + await setup.Database.EnsureCreatedAsync(cancellationToken); + await new EfRefreshTokenStore(setup) + .CreateAsync(NewToken(10, Guid.NewGuid(), "A"), cancellationToken); + } + + Task Rotate(string replacementPrefix) => Task.Run(async () => { + await using var db = CreateFileContext(path); + var store = new EfRefreshTokenStore(db); + var current = await store.FindByHashAsync("A".PadRight(64, '0'), cancellationToken); + return await store.TryRotateAsync( + current.Id, current.TokenHash, NewToken(10, current.FamilyId, replacementPrefix), Now, cancellationToken); + }, cancellationToken); + + var results = await Task.WhenAll(Rotate("B"), Rotate("C")); + + Assert.Single(results, succeeded => succeeded); + await using var verify = CreateFileContext(path); + var rows = await verify.Set>().AsNoTracking().ToListAsync(cancellationToken); + Assert.Equal(2, rows.Count); + Assert.Single(rows, token => token.RevokedAt != null); + } finally { + SqliteConnection.ClearAllPools(); + if(File.Exists(path)) + File.Delete(path); + } + } + + [Fact] + public async Task TryRotateAsync_ExpiredToken_RollsBackReplacementAndDetachesIt() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await OpenConnectionAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfRefreshTokenStore(db); + var original = NewToken(10, Guid.NewGuid(), "A"); + await store.CreateAsync(original, cancellationToken); + var replacement = NewToken(10, original.FamilyId, "B"); + + var rotated = await store.TryRotateAsync(original.Id, original.TokenHash, replacement, Now.AddDays(31), cancellationToken); + + Assert.False(rotated); + Assert.Equal(EntityState.Detached, db.Entry(replacement).State); + Assert.Equal(0, replacement.Id); + Assert.Equal(1, await db.Set>().AsNoTracking().CountAsync(cancellationToken)); + Assert.Null(await store.FindByHashAsync(replacement.TokenHash, cancellationToken)); + } + + [Fact] + public async Task TryRotateAsync_ConsumedToken_CannotBeRotatedAgain() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await OpenConnectionAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfRefreshTokenStore(db); + var original = NewToken(10, Guid.NewGuid(), "A"); + await store.CreateAsync(original, cancellationToken); + + Assert.True(await store.TryRotateAsync(original.Id, original.TokenHash, NewToken(10, original.FamilyId, "B"), Now, cancellationToken)); + Assert.False(await store.TryRotateAsync(original.Id, original.TokenHash, NewToken(10, original.FamilyId, "C"), Now, cancellationToken)); + + Assert.Equal(2, await db.Set>().AsNoTracking().CountAsync(cancellationToken)); + } + + [Fact] + public async Task TryRotateAsync_WrongExpectedHash_IsRejected() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await OpenConnectionAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfRefreshTokenStore(db); + var original = NewToken(10, Guid.NewGuid(), "A"); + await store.CreateAsync(original, cancellationToken); + + Assert.False(await store.TryRotateAsync( + original.Id, "Z".PadRight(64, '0'), NewToken(10, original.FamilyId, "B"), Now, cancellationToken)); + Assert.Null((await store.FindByHashAsync(original.TokenHash, cancellationToken)).RevokedAt); + } + + [Fact] + public async Task TryIncrementFailedAttemptsAsync_LocksRequestAtMaximumAttempts() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await OpenConnectionAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfVerificationRequestStore(db); + var request = NewRequest(10, "handle", Now); + Assert.True(await store.TryCreateAsync(request, Now.AddHours(-1), 5, cancellationToken)); + Assert.True(await store.TrySetInitialVerifierAsync(request.Id, "v1", Now, Now.AddMinutes(10), cancellationToken)); + + Assert.True(await store.TryIncrementFailedAttemptsAsync(request.Id, 1, 2, Now, cancellationToken)); + Assert.Equal(VerificationRequestStatus.Pending, (await store.FindByHandleHashAsync("handle", cancellationToken)).Status); + + Assert.True(await store.TryIncrementFailedAttemptsAsync(request.Id, 1, 2, Now, cancellationToken)); + var locked = await store.FindByHandleHashAsync("handle", cancellationToken); + Assert.Equal(VerificationRequestStatus.Locked, locked.Status); + Assert.Equal(2, locked.FailedAttempts); + + Assert.False(await store.TryIncrementFailedAttemptsAsync(request.Id, 1, 2, Now, cancellationToken)); + Assert.False(await store.TryConsumeAsync(request.Id, 1, Now, cancellationToken)); + } + + [Fact] + public async Task TryResendAsync_WithinCooldown_IsRejectedAndNotCounted() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await OpenConnectionAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfVerificationRequestStore(db); + var request = NewRequest(10, "handle", Now); + Assert.True(await store.TryCreateAsync(request, Now.AddHours(-1), 5, cancellationToken)); + Assert.True(await store.TrySetInitialVerifierAsync(request.Id, "v1", Now, Now.AddMinutes(10), cancellationToken)); + + var tooSoon = Now.AddSeconds(5); + Assert.False(await store.TryResendAsync( + request.Id, 1, "v2", tooSoon, tooSoon.AddMinutes(10), TimeSpan.FromSeconds(60), Now.AddHours(-1), 5, cancellationToken)); + + var persisted = await store.FindByHandleHashAsync("handle", cancellationToken); + Assert.Equal(1, persisted.CodeVersion); + Assert.Equal(1, await db.Set().CountAsync(cancellationToken)); + } + + [Fact] + public async Task CustomPurposes_HaveSeparateSendLimitsAndDoNotSupersedeEachOther() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await OpenConnectionAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfVerificationRequestStore(db); + + var first = NewRequest(10, "first", Now, customPurpose: "alpha"); + var second = NewRequest(10, "second", Now, customPurpose: "beta"); + var third = NewRequest(10, "third", Now.AddSeconds(1), customPurpose: "alpha"); + + Assert.True(await store.TryCreateAsync(first, Now.AddHours(-1), 1, cancellationToken)); + Assert.True(await store.TryCreateAsync(second, Now.AddHours(-1), 1, cancellationToken)); + Assert.Equal(VerificationRequestStatus.Pending, (await store.FindByHandleHashAsync("first", cancellationToken)).Status); + + Assert.False(await store.TryCreateAsync(third, Now.AddHours(-1), 1, cancellationToken)); + Assert.Equal(EntityState.Detached, db.Entry(third).State); + } + + [Fact] + public async Task TryCreateAsync_SupersedesPreviousPendingRequestWithSameCustomPurpose() { + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await OpenConnectionAsync(cancellationToken); + await using var db = CreateContext(connection); + await db.Database.EnsureCreatedAsync(cancellationToken); + var store = new EfVerificationRequestStore(db); + + Assert.True(await store.TryCreateAsync(NewRequest(10, "first", Now, customPurpose: "alpha"), Now.AddHours(-1), 5, cancellationToken)); + Assert.True(await store.TryCreateAsync(NewRequest(10, "second", Now.AddSeconds(1), customPurpose: "alpha"), Now.AddHours(-1), 5, cancellationToken)); + + Assert.Equal(VerificationRequestStatus.Superseded, (await store.FindByHandleHashAsync("first", cancellationToken)).Status); + Assert.Equal(VerificationRequestStatus.Pending, (await store.FindByHandleHashAsync("second", cancellationToken)).Status); + } + + private static RefreshToken NewToken(int userId, Guid familyId, string hashPrefix) => new() { + UserId = userId, + FamilyId = familyId, + TokenHash = hashPrefix.PadRight(64, '0'), + CreatedAt = Now, + ExpiresAt = Now.AddDays(30) + }; + + private static VerificationRequest NewRequest(int userId, string handleHash, DateTimeOffset now, string customPurpose = null) => new() { + UserId = userId, + Purpose = customPurpose == null ? VerificationPurpose.Registration : VerificationPurpose.Custom, + Channel = VerificationChannel.Email, + CustomPurpose = customPurpose, + Destination = "person@example.com", + NormalizedDestination = "PERSON@EXAMPLE.COM", + PublicHandleHash = handleHash, + CodeVerifier = string.Empty, + SendCount = 1, + CreatedAt = now, + LastSentAt = now, + ExpiresAt = now.AddMinutes(10), + Status = VerificationRequestStatus.Pending + }; + + private static async Task OpenConnectionAsync(CancellationToken cancellationToken) { + var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(cancellationToken); + return connection; + } + + private static TestDbContext CreateContext(SqliteConnection connection) => + new(new DbContextOptionsBuilder().UseSqlite(connection).Options); + + private static TestDbContext CreateFileContext(string path) => + new(new DbContextOptionsBuilder().UseSqlite($"Data Source={path};Pooling=False").Options); + + private sealed class TestDbContext(DbContextOptions options) + : IdentityDbContext, IdentityRole, int>(options) { + protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddRefreshTokenEntity(); + modelBuilder.AddVerificationRequestEntity(); + } + } + } +}