fix(sites): token d'inscription généré à la création + CI anti-flaky

- CreateSiteHandler retourne désormais SiteWithTokenResponse avec le token
  d'inscription généré à la création (via RegistrationTokenGenerator partagé)
  — corrige l'écran 'Token non disponible' après création de site
- GenerateSiteTokenHandler réutilise le helper commun (DRY)
- Test CreateSiteHandler vérifie le token non vide + expiration future
- PageTestBase : DefaultWaitTimeout 10s (bUnit défaut 1s trop court sur le
  runner CI → 3 tests Web flaky : Snapshots/Dashboard/Events)
This commit is contained in:
Arnaud Dartois committed 2026-08-10 15:06:20 +02:00
1 parent 79d6ec0495
commit 2f3b3dd666
6 files changed
+47 -19

No files matched your search

@@ -4,4 +4,4 @@ using MediatR;
namespace Heimdall.Application.Sites.Commands.CreateSite;
public record CreateSiteCommand(string Name, string? Address, string? Timezone) : IRequest<ServiceResult<SiteResponse>>;
public record CreateSiteCommand(string Name, string? Address, string? Timezone) : IRequest<ServiceResult<SiteWithTokenResponse>>;
@@ -1,29 +1,36 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Sites.Common;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Sites.Commands.CreateSite;
public class CreateSiteHandler : IRequestHandler<CreateSiteCommand, ServiceResult<SiteResponse>>
public class CreateSiteHandler : IRequestHandler<CreateSiteCommand, ServiceResult<SiteWithTokenResponse>>
{
private readonly IApplicationDbContext _context;
public CreateSiteHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<SiteResponse>> Handle(CreateSiteCommand request, CancellationToken cancellationToken)
public async Task<ServiceResult<SiteWithTokenResponse>> Handle(CreateSiteCommand request, CancellationToken cancellationToken)
{
var existing = await _context.Sites.AnyAsync(s => s.Name == request.Name, cancellationToken).ConfigureAwait(false);
if (existing)
return ServiceResult<SiteResponse>.Conflict("A site with this name already exists");
return ServiceResult<SiteWithTokenResponse>.Conflict("A site with this name already exists");
var site = new Site(request.Name, request.Address, request.Timezone);
// Generate a registration token at creation so the UI can show it
// immediately (POST /api/sites returns SiteWithTokenResponse).
var (plainToken, tokenHash, expiresAt) = RegistrationTokenGenerator.Generate();
site.GenerateRegistrationToken(tokenHash, expiresAt);
_context.Sites.Add(site);
await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
return ServiceResult<SiteResponse>.Success(new SiteResponse(
site.Id, site.Name, site.Address, site.Timezone, site.Enabled, site.CreatedAt));
return ServiceResult<SiteWithTokenResponse>.Success(new SiteWithTokenResponse(
site.Id, site.Name, site.Address, site.Timezone, plainToken, expiresAt, site.CreatedAt));
}
}
@@ -1,7 +1,6 @@
using System.Security.Cryptography;
using System.Text;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Sites.Common;
using MediatR;
namespace Heimdall.Application.Sites.Commands.GenerateSiteToken;
@@ -18,21 +17,11 @@ public class GenerateSiteTokenHandler : IRequestHandler<GenerateSiteTokenCommand
if (site is null)
return ServiceResult<RegistrationTokenResponse>.NotFound("Site not found");
var (plainToken, tokenHash, expiresAt) = GenerateRegistrationToken();
var (plainToken, tokenHash, expiresAt) = RegistrationTokenGenerator.Generate();
site.GenerateRegistrationToken(tokenHash, expiresAt);
await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
return ServiceResult<RegistrationTokenResponse>.Success(
new RegistrationTokenResponse(plainToken, expiresAt));
}
private static (string plainToken, string tokenHash, DateTime expiresAt) GenerateRegistrationToken()
{
var tokenBytes = new byte[32];
RandomNumberGenerator.Fill(tokenBytes);
var plainToken = Convert.ToHexString(tokenBytes).ToLowerInvariant();
var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(plainToken))).ToLowerInvariant();
var expiresAt = DateTime.UtcNow.AddDays(1);
return (plainToken, tokenHash, expiresAt);
}
}
@@ -0,0 +1,22 @@
using System.Security.Cryptography;
using System.Text;
namespace Heimdall.Application.Sites.Common;
/// <summary>
/// Shared registration-token generation used both at site creation and on
/// explicit token generation. Returns the plain token (shown once to the
/// user), its SHA-256 hash (stored) and the expiration time.
/// </summary>
public static class RegistrationTokenGenerator
{
public static (string PlainToken, string TokenHash, DateTime ExpiresAt) Generate()
{
var tokenBytes = new byte[32];
RandomNumberGenerator.Fill(tokenBytes);
var plainToken = Convert.ToHexString(tokenBytes).ToLowerInvariant();
var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(plainToken))).ToLowerInvariant();
var expiresAt = DateTime.UtcNow.AddDays(1);
return (plainToken, tokenHash, expiresAt);
}
}
@@ -22,6 +22,11 @@ public class CreateSiteHandlerTests
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Name.ShouldBe("Test Site");
// Le token d'inscription doit être généré à la création (le site est
// créé avec son RegistrationTokenHash — bug fix : "Token non disponible")
result.Data.RegistrationToken.ShouldNotBeNullOrEmpty();
result.Data.TokenExpiresAt.ShouldNotBeNull();
result.Data.TokenExpiresAt!.Value.ShouldBeGreaterThan(DateTime.UtcNow);
}
[Fact]
@@ -39,6 +39,11 @@ public abstract class PageTestBase : MudTestBase
protected PageTestBase()
{
// Longer default wait timeout: bUnit defaults to 1s, which is too
// short on the CI runner (flaky WaitForAssertion). 10s keeps local
// runs fast and CI green.
DefaultWaitTimeout = TimeSpan.FromSeconds(10);
// ILogger<T> (required by Login page) — silent by default
Services.AddLogging();