Path: redb-identity/tests/redb.Identity.Tests/Stores/PepperRotationTokenStoreTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Stores/PepperRotationTokenStoreTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using redb.Core;
using redb.Identity.Core.ChangeEmail;
using redb.Identity.Core.EmailVerification;
using redb.Identity.Core.Models;
using redb.Identity.Core.PasswordReset;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Stores;
///
/// Pepper rotation on the three one-time link stores: a link issued under the old pepper still verifies while the
/// old pepper is listed as previous, and no longer once it is removed; every new row records its pepper id.
///
[Collection("Postgres")]
public class PepperRotationTokenStoreTests : IAsyncLifetime
{
private static readonly byte[] Old = Enumerable.Range(1, 32).Select(i => (byte)i).ToArray();
private static readonly byte[] New = Enumerable.Range(101, 32).Select(i => (byte)i).ToArray();
private readonly PostgresFixture _fixture;
private readonly IServiceScopeFactory _scopes;
public PepperRotationTokenStoreTests(PostgresFixture fixture)
{
_fixture = fixture;
_scopes = fixture.Services.GetRequiredService();
}
public async Task InitializeAsync()
{
await _fixture.Redb.SyncSchemeAsync();
await _fixture.Redb.SyncSchemeAsync();
await _fixture.Redb.SyncSchemeAsync();
}
public Task DisposeAsync() => Task.CompletedTask;
private static RecoveryCodePepperProvider Before() => RecoveryCodePepperProvider.ForTesting(Old);
private static RecoveryCodePepperProvider Rotated() => RecoveryCodePepperProvider.ForTesting(New, Old);
private static RecoveryCodePepperProvider Retired() => RecoveryCodePepperProvider.ForTesting(New);
private async Task PepperIdOf(Guid jti, Func jtiOf, Func pepperIdOf)
where TProps : class, new()
{
await using var scope = _scopes.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
var rows = await redb.Query().ToListAsync();
return pepperIdOf(rows.Single(r => jtiOf(r.Props) == jti.ToString("N")).Props);
}
[Fact]
public async Task Password_reset_link_survives_the_rotation_until_the_old_pepper_is_removed()
{
RedbPasswordResetTokenStore Store(RecoveryCodePepperProvider p) =>
new(_scopes, p, NullLogger.Instance);
var a = await Store(Before()).IssueAsync(11, "https://app.example.com/reset", TimeSpan.FromMinutes(30));
var b = await Store(Before()).IssueAsync(11, "https://app.example.com/reset", TimeSpan.FromMinutes(30));
(await PepperIdOf(a.Jti, p => p.Jti, p => p.PepperId)).Should().Be(RecoveryCodePepperProvider.ComputeId(Old));
(await Store(Rotated()).VerifyAndConsumeAsync(a.Jti, a.PlaintextToken)).Success.Should().BeTrue();
(await Store(Retired()).VerifyAndConsumeAsync(b.Jti, b.PlaintextToken)).Success.Should().BeFalse();
}
[Fact]
public async Task Email_verification_link_survives_the_rotation_until_the_old_pepper_is_removed()
{
RedbEmailVerificationTokenStore Store(RecoveryCodePepperProvider p) =>
new(_scopes, p, NullLogger.Instance);
var a = await Store(Before()).IssueAsync(12, "a@example.com", "https://app.example.com/verify", TimeSpan.FromHours(1));
var b = await Store(Before()).IssueAsync(12, "a@example.com", "https://app.example.com/verify", TimeSpan.FromHours(1));
(await PepperIdOf(a.Jti, p => p.Jti, p => p.PepperId)).Should().Be(RecoveryCodePepperProvider.ComputeId(Old));
(await Store(Rotated()).VerifyAndConsumeAsync(a.Jti, a.PlaintextToken)).Success.Should().BeTrue();
(await Store(Retired()).VerifyAndConsumeAsync(b.Jti, b.PlaintextToken)).Success.Should().BeFalse();
}
[Fact]
public async Task Change_email_link_survives_the_rotation_until_the_old_pepper_is_removed()
{
RedbChangeEmailTokenStore Store(RecoveryCodePepperProvider p) =>
new(_scopes, p, NullLogger.Instance);
var a = await Store(Before()).IssueAsync(13, "new-a@example.com", "old@example.com", "https://app.example.com/confirm",
TimeSpan.FromHours(1), invalidatePrevious: false);
var b = await Store(Before()).IssueAsync(13, "new-b@example.com", "old@example.com", "https://app.example.com/confirm",
TimeSpan.FromHours(1), invalidatePrevious: false);
(await PepperIdOf(a.Jti, p => p.Jti, p => p.PepperId)).Should().Be(RecoveryCodePepperProvider.ComputeId(Old));
(await Store(Rotated()).VerifyAndConsumeAsync(a.Jti, a.PlaintextToken)).Success.Should().BeTrue();
(await Store(Retired()).VerifyAndConsumeAsync(b.Jti, b.PlaintextToken)).Success.Should().BeFalse();
}
///
/// The rotation report counts, per previous pepper id, the users that still hold recovery codes under it (an
/// emptied set does not count) and those whose codes carry no id; it logs ids and counts, never a user.
///
[Fact]
public async Task Pepper_usage_report_counts_users_per_previous_pepper_id()
{
await _fixture.Redb.SyncSchemeAsync();
var previous = System.Security.Cryptography.RandomNumberGenerator.GetBytes(32);
var previousId = RecoveryCodePepperProvider.ComputeId(previous);
var provider = RecoveryCodePepperProvider.ForTesting(New, previous);
await using (var scope = _scopes.CreateAsyncScope())
{
var redb = scope.ServiceProvider.GetRequiredService();
foreach (var (pepperId, codes) in new (string?, List)[]
{
(previousId, ["pbkdf2$1$a$b"]), (previousId, ["pbkdf2$1$a$b", "pbkdf2$1$c$d"]), (previousId, []),
(null, ["pbkdf2$1$a$b"]), (provider.PepperId, ["pbkdf2$1$a$b"]),
})
await redb.SaveAsync(new redb.Core.Models.Entities.RedbObject(new MfaProps
{
UserId = Random.Shared.NextInt64(1_000_000, long.MaxValue),
Enabled = true,
RecoveryCodes = codes,
RecoveryCodesPepperId = pepperId,
}));
}
var log = new ListLogger();
await using (var scope = _scopes.CreateAsyncScope())
{
var redb = scope.ServiceProvider.GetRequiredService();
var processor = new redb.Identity.Core.Routes.Processors.PepperUsageReportProcessor(
MockRouteContext.Create(redb), null, () => provider, log);
await processor.Process(new TestExchange());
}
log.Lines.Should().Contain($"Pepper rotation: 2 user(s) hold recovery codes hashed with previous pepper {previousId}.");
log.Lines.Should().ContainSingle(l => l.Contains("issued before 4.8.0"))
.Which.Should().MatchRegex(@"^Pepper rotation: [1-9]\d* user\(s\)");
log.Lines.Should().NotContain(l => l.Contains(provider.PepperId), "the current pepper is not reported");
}
private sealed class ListLogger : Microsoft.Extensions.Logging.ILogger
{
public List Lines { get; } = [];
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId,
TState state, Exception? exception, Func formatter) => Lines.Add(formatter(state, exception));
}
}