Files
Heimdall/tests/Heimdall.Infrastructure.Tests/ChallengeAtomicPostgresTests.cs
T
arnaud.dartois 2bf3dbc95b
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m8s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Failing after 6m10s
Heimdall Gitea / Build and scan server image (pull_request) Failing after 8m2s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s
fix(identity): harden user lifecycle and permissions
2026-11-04 10:26:07 +01:00

67 lines
3.4 KiB
C#

using Heimdall.Application.Auth.Commands.Verify2fa;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Security;
using Heimdall.TestCommon;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Shouldly;
namespace Heimdall.Infrastructure.Tests;
[Collection("PostgresInfra")]
public class ChallengeAtomicPostgresTests(PostgreSqlContainerFixture postgres)
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Independent_instances_cannot_redeem_recovery_or_challenge_twice(bool sameChallenge)
{
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton(new AuditInterceptor());
services.AddDbContext<AppDbContext>(o => o.UseNpgsql(postgres.ConnectionString));
services.AddIdentity<AppUser, AppRole>().AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();
await using var provider = services.BuildServiceProvider();
string first, second;
var code = Guid.NewGuid().ToString("N");
using (var scope = provider.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.ExecuteSqlRawAsync("CREATE EXTENSION IF NOT EXISTS pg_trgm");
await db.Database.EnsureCreatedAsync();
var users = scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>();
var email = $"{Guid.NewGuid():N}@example.test";
var user = new AppUser { Id = Guid.NewGuid(), Email = email, UserName = email, EmailConfirmed = true };
(await users.CreateAsync(user, "Correct-password-123!")).Succeeded.ShouldBeTrue();
await users.ResetAuthenticatorKeyAsync(user);
await users.SetTwoFactorEnabledAsync(user, true);
db.UserRecoveryCodes.Add(new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(code)));
first = await LoginChallengeService.CreateAsync(db, user, default);
second = sameChallenge ? first : await LoginChallengeService.CreateAsync(db, user, default);
}
using var gate = new Barrier(2);
var results = await Task.WhenAll(new[] { first, second }.Select(challenge => Task.Run(async () =>
{
// A new scope owns its own DbContext, UserManager and PostgreSQL connection.
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var jwt = Substitute.For<IJwtService>();
var roles = Substitute.For<IRolePermissionService>();
roles.GetPermissionsForRolesAsync(Arg.Any<IList<string>>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IList<string>>([]));
var handler = new Verify2faHandler(scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>(),
jwt, roles, db, NullLogger<Verify2faHandler>.Instance);
gate.SignalAndWait(TimeSpan.FromSeconds(30)).ShouldBeTrue();
return await handler.Handle(new(challenge, code), default);
})));
results.Count(x => x.IsSuccess).ShouldBe(1);
}
}